Skip to main content

stateknot_core/
accounting.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Exact, checked accounting values used by budgets and provider usage.
5
6use std::{fmt, str::FromStr};
7
8use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
9use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
10use thiserror::Error;
11
12use crate::decimal::{UnsignedDecimalError, parse_bounded_u64};
13
14const U64_DECIMAL_PATTERN: &str = "^(0|[1-9][0-9]{0,19})$";
15const CURRENCY_CODE_PATTERN: &str = "^[A-Z]{3}$";
16
17macro_rules! define_count {
18    ($name:ident, $visitor:ident, $schema_name:literal, $documentation:literal) => {
19        #[doc = $documentation]
20        ///
21        /// The JSON wire form is a canonical unsigned decimal string. Arithmetic
22        /// is available only through checked methods, so release builds cannot
23        /// silently wrap accounting values.
24        #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
25        pub struct $name(u64);
26
27        impl $name {
28            /// Zero usage.
29            pub const ZERO: Self = Self(0);
30
31            /// Largest representable usage.
32            pub const MAX: Self = Self(u64::MAX);
33
34            /// Constructs a count from its integer representation.
35            #[must_use]
36            pub const fn new(value: u64) -> Self {
37                Self(value)
38            }
39
40            /// Returns the underlying integer count.
41            #[must_use]
42            pub const fn get(self) -> u64 {
43                self.0
44            }
45
46            /// Adds two counts, returning `None` on overflow.
47            #[must_use]
48            pub const fn checked_add(self, other: Self) -> Option<Self> {
49                match self.0.checked_add(other.0) {
50                    Some(value) => Some(Self(value)),
51                    None => None,
52                }
53            }
54
55            /// Subtracts two counts, returning `None` on underflow.
56            #[must_use]
57            pub const fn checked_sub(self, other: Self) -> Option<Self> {
58                match self.0.checked_sub(other.0) {
59                    Some(value) => Some(Self(value)),
60                    None => None,
61                }
62            }
63
64            /// Multiplies a count by an integer, returning `None` on overflow.
65            #[must_use]
66            pub const fn checked_mul(self, multiplier: u64) -> Option<Self> {
67                match self.0.checked_mul(multiplier) {
68                    Some(value) => Some(Self(value)),
69                    None => None,
70                }
71            }
72        }
73
74        impl fmt::Display for $name {
75            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
76                self.0.fmt(formatter)
77            }
78        }
79
80        impl FromStr for $name {
81            type Err = CountParseError;
82
83            fn from_str(value: &str) -> Result<Self, Self::Err> {
84                parse_bounded_u64(value, u64::MAX)
85                    .map(Self)
86                    .map_err(CountParseError::from_decimal_error)
87            }
88        }
89
90        impl From<u64> for $name {
91            fn from(value: u64) -> Self {
92                Self::new(value)
93            }
94        }
95
96        impl From<$name> for u64 {
97            fn from(value: $name) -> Self {
98                value.0
99            }
100        }
101
102        impl Serialize for $name {
103            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
104            where
105                S: Serializer,
106            {
107                serializer.collect_str(self)
108            }
109        }
110
111        impl<'de> Deserialize<'de> for $name {
112            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
113            where
114                D: Deserializer<'de>,
115            {
116                deserializer.deserialize_str($visitor)
117            }
118        }
119
120        struct $visitor;
121
122        impl de::Visitor<'_> for $visitor {
123            type Value = $name;
124
125            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
126                write!(formatter, "a canonical decimal string containing a {}", $schema_name)
127            }
128
129            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
130            where
131                E: de::Error,
132            {
133                value.parse().map_err(E::custom)
134            }
135        }
136
137        impl JsonSchema for $name {
138            fn schema_name() -> std::borrow::Cow<'static, str> {
139                $schema_name.into()
140            }
141
142            fn schema_id() -> std::borrow::Cow<'static, str> {
143                concat!(module_path!(), "::", $schema_name).into()
144            }
145
146            fn json_schema(_: &mut SchemaGenerator) -> Schema {
147                json_schema!({
148                    "type": "string",
149                    "minLength": 1,
150                    "maxLength": 20,
151                    "pattern": U64_DECIMAL_PATTERN
152                })
153            }
154
155            fn inline_schema() -> bool {
156                true
157            }
158        }
159    };
160}
161
162define_count!(
163    TokenCount,
164    TokenCountVisitor,
165    "TokenCount",
166    "A count of model input, cached-input, reasoning, or output tokens."
167);
168define_count!(
169    ByteCount,
170    ByteCountVisitor,
171    "ByteCount",
172    "A count of input, output, event, checkpoint, or artifact bytes."
173);
174define_count!(
175    ExecutionCount,
176    ExecutionCountVisitor,
177    "ExecutionCount",
178    "A count of graph steps, model attempts, tool calls, branches, delegations, or retries."
179);
180
181/// Parse failure for a canonical token or byte count.
182#[derive(Clone, Debug, Eq, Error, PartialEq)]
183#[non_exhaustive]
184pub enum CountParseError {
185    /// The encoded count was empty or contained a non-decimal byte.
186    #[error("count must contain only unsigned ASCII decimal digits")]
187    InvalidFormat,
188
189    /// The encoded count exceeded the maximum canonical byte length.
190    #[error("count is {actual} bytes; maximum is {max}")]
191    TooLong {
192        /// Maximum accepted byte length.
193        max: usize,
194        /// Observed byte length.
195        actual: usize,
196    },
197
198    /// The encoded count contained a leading zero.
199    #[error("count contains a leading zero")]
200    NonCanonical,
201
202    /// The encoded count exceeded the `u64` range.
203    #[error("count exceeds the supported range")]
204    Overflow,
205}
206
207impl CountParseError {
208    fn from_decimal_error(error: UnsignedDecimalError) -> Self {
209        match error {
210            UnsignedDecimalError::Empty | UnsignedDecimalError::InvalidCharacter { .. } => {
211                Self::InvalidFormat
212            }
213            UnsignedDecimalError::TooLong { max, actual } => Self::TooLong { max, actual },
214            UnsignedDecimalError::LeadingZero => Self::NonCanonical,
215            UnsignedDecimalError::Overflow => Self::Overflow,
216        }
217    }
218}
219
220/// A structurally valid ISO 4217 alphabetic currency code.
221///
222/// This type intentionally validates the stable three-uppercase-ASCII-letter
223/// structure, not mutable current-currency membership. Provider configuration
224/// validates membership against a versioned ISO 4217 catalog; durable events
225/// must remain readable after a code becomes historical.
226#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
227pub struct CurrencyCode([u8; Self::LEN]);
228
229impl CurrencyCode {
230    /// Encoded length in bytes.
231    pub const LEN: usize = 3;
232
233    /// Validates an alphabetic currency code.
234    ///
235    /// # Errors
236    ///
237    /// Returns [`CurrencyCodeError::InvalidCharacter`] when any byte is not an
238    /// uppercase ASCII letter.
239    pub fn new(bytes: [u8; Self::LEN]) -> Result<Self, CurrencyCodeError> {
240        if let Some(index) = bytes.iter().position(|byte| !byte.is_ascii_uppercase()) {
241            return Err(CurrencyCodeError::InvalidCharacter { index });
242        }
243        Ok(Self(bytes))
244    }
245
246    /// Returns the three canonical ASCII bytes.
247    #[must_use]
248    pub const fn as_bytes(&self) -> &[u8; Self::LEN] {
249        &self.0
250    }
251}
252
253impl fmt::Debug for CurrencyCode {
254    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
255        formatter
256            .debug_tuple("CurrencyCode")
257            .field(&format_args!("{self}"))
258            .finish()
259    }
260}
261
262impl fmt::Display for CurrencyCode {
263    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
264        let value = std::str::from_utf8(&self.0).map_err(|_| fmt::Error)?;
265        formatter.write_str(value)
266    }
267}
268
269impl FromStr for CurrencyCode {
270    type Err = CurrencyCodeError;
271
272    fn from_str(value: &str) -> Result<Self, Self::Err> {
273        if value.len() != Self::LEN {
274            return Err(CurrencyCodeError::InvalidLength {
275                expected: Self::LEN,
276                actual: value.len(),
277            });
278        }
279        let bytes: [u8; Self::LEN] =
280            value
281                .as_bytes()
282                .try_into()
283                .map_err(|_| CurrencyCodeError::InvalidLength {
284                    expected: Self::LEN,
285                    actual: value.len(),
286                })?;
287        Self::new(bytes)
288    }
289}
290
291impl Serialize for CurrencyCode {
292    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
293    where
294        S: Serializer,
295    {
296        serializer.collect_str(self)
297    }
298}
299
300impl<'de> Deserialize<'de> for CurrencyCode {
301    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
302    where
303        D: Deserializer<'de>,
304    {
305        deserializer.deserialize_str(CurrencyCodeVisitor)
306    }
307}
308
309struct CurrencyCodeVisitor;
310
311impl de::Visitor<'_> for CurrencyCodeVisitor {
312    type Value = CurrencyCode;
313
314    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
315        formatter.write_str("a three-letter uppercase ISO 4217 currency code")
316    }
317
318    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
319    where
320        E: de::Error,
321    {
322        value.parse().map_err(E::custom)
323    }
324}
325
326impl JsonSchema for CurrencyCode {
327    fn schema_name() -> std::borrow::Cow<'static, str> {
328        "CurrencyCode".into()
329    }
330
331    fn schema_id() -> std::borrow::Cow<'static, str> {
332        concat!(module_path!(), "::CurrencyCode").into()
333    }
334
335    fn json_schema(_: &mut SchemaGenerator) -> Schema {
336        json_schema!({
337            "type": "string",
338            "minLength": 3,
339            "maxLength": 3,
340            "pattern": CURRENCY_CODE_PATTERN
341        })
342    }
343
344    fn inline_schema() -> bool {
345        true
346    }
347}
348
349/// Validation failure for a [`CurrencyCode`].
350#[derive(Clone, Debug, Eq, Error, PartialEq)]
351#[non_exhaustive]
352pub enum CurrencyCodeError {
353    /// The code was not exactly three bytes.
354    #[error("currency code is {actual} bytes; expected {expected}")]
355    InvalidLength {
356        /// Required encoded length in bytes.
357        expected: usize,
358        /// Observed byte length.
359        actual: usize,
360    },
361
362    /// A byte was not an uppercase ASCII letter.
363    #[error("currency code contains an invalid byte at offset {index}")]
364    InvalidCharacter {
365        /// Zero-based byte offset of the invalid value.
366        index: usize,
367    },
368}
369
370/// A non-negative known monetary cost in integer micro-units.
371///
372/// The stable JSON form is an object with exactly `currency` and
373/// `micro_units`; the latter is a canonical decimal string. Unknown cost is
374/// represented by absence in an enclosing usage value, not by zero money.
375#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
376#[serde(deny_unknown_fields)]
377pub struct Money {
378    currency: CurrencyCode,
379    #[serde(with = "crate::decimal::serde_u64")]
380    micro_units: u64,
381}
382
383impl Money {
384    /// Constructs a known monetary amount.
385    #[must_use]
386    pub const fn new(currency: CurrencyCode, micro_units: u64) -> Self {
387        Self {
388            currency,
389            micro_units,
390        }
391    }
392
393    /// Constructs zero cost in a specific currency.
394    #[must_use]
395    pub const fn zero(currency: CurrencyCode) -> Self {
396        Self::new(currency, 0)
397    }
398
399    /// Returns the currency code.
400    #[must_use]
401    pub const fn currency(self) -> CurrencyCode {
402        self.currency
403    }
404
405    /// Returns the integer count of micro-units.
406    #[must_use]
407    pub const fn micro_units(self) -> u64 {
408        self.micro_units
409    }
410
411    /// Adds amounts of the same currency without overflow.
412    ///
413    /// # Errors
414    ///
415    /// Returns [`MoneyArithmeticError::CurrencyMismatch`] for unlike
416    /// currencies or [`MoneyArithmeticError::Overflow`] when the result
417    /// exceeds `u64`.
418    pub fn checked_add(self, other: Self) -> Result<Self, MoneyArithmeticError> {
419        self.ensure_same_currency(other)?;
420        let micro_units = self
421            .micro_units
422            .checked_add(other.micro_units)
423            .ok_or(MoneyArithmeticError::Overflow)?;
424        Ok(Self::new(self.currency, micro_units))
425    }
426
427    /// Subtracts amounts of the same currency without underflow.
428    ///
429    /// # Errors
430    ///
431    /// Returns [`MoneyArithmeticError::CurrencyMismatch`] for unlike
432    /// currencies or [`MoneyArithmeticError::Underflow`] when `other` is
433    /// greater than `self`.
434    pub fn checked_sub(self, other: Self) -> Result<Self, MoneyArithmeticError> {
435        self.ensure_same_currency(other)?;
436        let micro_units = self
437            .micro_units
438            .checked_sub(other.micro_units)
439            .ok_or(MoneyArithmeticError::Underflow)?;
440        Ok(Self::new(self.currency, micro_units))
441    }
442
443    /// Multiplies this amount by an integer without overflow.
444    ///
445    /// # Errors
446    ///
447    /// Returns [`MoneyArithmeticError::Overflow`] when the result exceeds
448    /// `u64`.
449    pub fn checked_mul(self, multiplier: u64) -> Result<Self, MoneyArithmeticError> {
450        let micro_units = self
451            .micro_units
452            .checked_mul(multiplier)
453            .ok_or(MoneyArithmeticError::Overflow)?;
454        Ok(Self::new(self.currency, micro_units))
455    }
456
457    fn ensure_same_currency(self, other: Self) -> Result<(), MoneyArithmeticError> {
458        if self.currency == other.currency {
459            Ok(())
460        } else {
461            Err(MoneyArithmeticError::CurrencyMismatch {
462                left: self.currency,
463                right: other.currency,
464            })
465        }
466    }
467}
468
469impl JsonSchema for Money {
470    fn schema_name() -> std::borrow::Cow<'static, str> {
471        "Money".into()
472    }
473
474    fn schema_id() -> std::borrow::Cow<'static, str> {
475        concat!(module_path!(), "::Money").into()
476    }
477
478    fn json_schema(_: &mut SchemaGenerator) -> Schema {
479        json_schema!({
480            "type": "object",
481            "additionalProperties": false,
482            "required": ["currency", "micro_units"],
483            "properties": {
484                "currency": {
485                    "type": "string",
486                    "minLength": 3,
487                    "maxLength": 3,
488                    "pattern": CURRENCY_CODE_PATTERN
489                },
490                "micro_units": {
491                    "type": "string",
492                    "minLength": 1,
493                    "maxLength": 20,
494                    "pattern": U64_DECIMAL_PATTERN
495                }
496            }
497        })
498    }
499
500    fn inline_schema() -> bool {
501        true
502    }
503}
504
505/// Failure from checked monetary arithmetic.
506#[derive(Clone, Debug, Eq, Error, PartialEq)]
507#[non_exhaustive]
508pub enum MoneyArithmeticError {
509    /// Arithmetic was requested across different currencies.
510    #[error("cannot combine {left} and {right} without an explicit conversion")]
511    CurrencyMismatch {
512        /// Currency of the left operand.
513        left: CurrencyCode,
514        /// Currency of the right operand.
515        right: CurrencyCode,
516    },
517
518    /// The result exceeded the `u64` micro-unit range.
519    #[error("monetary arithmetic overflowed")]
520    Overflow,
521
522    /// Subtraction would have produced a negative amount.
523    #[error("monetary subtraction would produce a negative amount")]
524    Underflow,
525}
526
527#[cfg(test)]
528mod tests {
529    use super::*;
530    use proptest::prelude::*;
531    use serde_json::{Value, from_str, from_value, json, to_string, to_value};
532
533    fn usd() -> CurrencyCode {
534        "USD".parse().unwrap()
535    }
536
537    #[test]
538    fn counts_use_exact_decimal_strings_and_checked_arithmetic() {
539        for value in [0, 1, (1_u64 << 53) - 1, 1_u64 << 53, u64::MAX] {
540            let tokens = TokenCount::new(value);
541            let bytes = ByteCount::new(value);
542            let executions = ExecutionCount::new(value);
543            assert_eq!(tokens.to_string().parse::<TokenCount>().unwrap(), tokens);
544            assert_eq!(bytes.to_string().parse::<ByteCount>().unwrap(), bytes);
545            assert_eq!(
546                executions.to_string().parse::<ExecutionCount>().unwrap(),
547                executions
548            );
549            assert_eq!(to_string(&tokens).unwrap(), format!("\"{value}\""));
550            assert_eq!(to_string(&bytes).unwrap(), format!("\"{value}\""));
551            assert_eq!(to_string(&executions).unwrap(), format!("\"{value}\""));
552        }
553
554        assert_eq!(TokenCount::MAX.checked_add(TokenCount::new(1)), None);
555        assert_eq!(ByteCount::ZERO.checked_sub(ByteCount::new(1)), None);
556        assert_eq!(TokenCount::new(4).checked_mul(3), Some(TokenCount::new(12)));
557    }
558
559    #[test]
560    fn counts_reject_noncanonical_or_inexact_json() {
561        for value in ["", "00", "01", "+1", "-1", "1.0", "1e3", " 1"] {
562            assert!(value.parse::<TokenCount>().is_err(), "accepted {value:?}");
563            assert!(value.parse::<ByteCount>().is_err(), "accepted {value:?}");
564            assert!(
565                value.parse::<ExecutionCount>().is_err(),
566                "accepted {value:?}"
567            );
568        }
569        assert_eq!(
570            "18446744073709551616".parse::<TokenCount>(),
571            Err(CountParseError::Overflow)
572        );
573        assert!(from_value::<TokenCount>(json!(1)).is_err());
574        assert!(from_value::<ByteCount>(Value::Null).is_err());
575    }
576
577    #[test]
578    fn count_schemas_match_runtime_wire_bounds() {
579        for schema in [
580            to_value(schemars::schema_for!(TokenCount)).unwrap(),
581            to_value(schemars::schema_for!(ByteCount)).unwrap(),
582            to_value(schemars::schema_for!(ExecutionCount)).unwrap(),
583        ] {
584            assert_eq!(schema["type"], "string");
585            assert_eq!(schema["minLength"], 1);
586            assert_eq!(schema["maxLength"], 20);
587            assert_eq!(schema["pattern"], U64_DECIMAL_PATTERN);
588        }
589    }
590
591    #[test]
592    fn currency_codes_enforce_stable_iso_structure() {
593        for value in ["USD", "EUR", "XAU", "BGN"] {
594            let code = value.parse::<CurrencyCode>().unwrap();
595            assert_eq!(code.to_string(), value);
596            assert_eq!(to_string(&code).unwrap(), format!("\"{value}\""));
597        }
598
599        for value in ["", "US", "USDD", "usd", "UsD", "U1D", "¥EN", " USD"] {
600            assert!(value.parse::<CurrencyCode>().is_err(), "accepted {value:?}");
601        }
602        assert!(from_value::<CurrencyCode>(json!("usd")).is_err());
603        assert!(from_value::<CurrencyCode>(json!(123)).is_err());
604    }
605
606    #[test]
607    fn money_round_trips_and_rejects_ambiguous_objects() {
608        let money = Money::new(usd(), 1_234_567);
609        let encoded = to_value(money).unwrap();
610        assert_eq!(
611            encoded,
612            json!({"currency": "USD", "micro_units": "1234567"})
613        );
614        assert_eq!(from_value::<Money>(encoded).unwrap(), money);
615
616        for invalid in [
617            json!({"currency": "USD", "micro_units": 123}),
618            json!({"currency": "usd", "micro_units": "123"}),
619            json!({"currency": "USD", "micro_units": "01"}),
620            json!({"currency": "USD", "micro_units": "18446744073709551616"}),
621            json!({"currency": "USD", "micro_units": "1", "extra": true}),
622            json!({"currency": "USD"}),
623        ] {
624            assert!(
625                from_value::<Money>(invalid.clone()).is_err(),
626                "accepted {invalid}"
627            );
628        }
629    }
630
631    #[test]
632    fn money_arithmetic_requires_one_currency_and_never_wraps() {
633        let eur: CurrencyCode = "EUR".parse().unwrap();
634        let one = Money::new(usd(), 1);
635        let two = Money::new(usd(), 2);
636
637        assert_eq!(one.checked_add(two), Ok(Money::new(usd(), 3)));
638        assert_eq!(two.checked_sub(one), Ok(one));
639        assert_eq!(two.checked_mul(3), Ok(Money::new(usd(), 6)));
640        assert_eq!(
641            Money::new(usd(), u64::MAX).checked_add(one),
642            Err(MoneyArithmeticError::Overflow)
643        );
644        assert_eq!(one.checked_sub(two), Err(MoneyArithmeticError::Underflow));
645        assert_eq!(
646            one.checked_add(Money::new(eur, 1)),
647            Err(MoneyArithmeticError::CurrencyMismatch {
648                left: usd(),
649                right: eur,
650            })
651        );
652    }
653
654    #[test]
655    fn money_schema_requires_exact_fields_and_string_amount() {
656        let schema = to_value(schemars::schema_for!(Money)).unwrap();
657        assert_eq!(schema["type"], "object");
658        assert_eq!(schema["additionalProperties"], false);
659        assert_eq!(schema["required"], json!(["currency", "micro_units"]));
660        assert_eq!(
661            schema["properties"]["currency"]["pattern"],
662            CURRENCY_CODE_PATTERN
663        );
664        assert_eq!(
665            schema["properties"]["micro_units"]["pattern"],
666            U64_DECIMAL_PATTERN
667        );
668    }
669
670    proptest! {
671        #[test]
672        fn checked_count_arithmetic_matches_u64(left in any::<u64>(), right in any::<u64>()) {
673            let left_tokens = TokenCount::new(left);
674            let right_tokens = TokenCount::new(right);
675            prop_assert_eq!(
676                left_tokens.checked_add(right_tokens).map(TokenCount::get),
677                left.checked_add(right)
678            );
679            prop_assert_eq!(
680                left_tokens.checked_sub(right_tokens).map(TokenCount::get),
681                left.checked_sub(right)
682            );
683
684            let left_bytes = ByteCount::new(left);
685            let right_bytes = ByteCount::new(right);
686            prop_assert_eq!(
687                left_bytes.checked_add(right_bytes).map(ByteCount::get),
688                left.checked_add(right)
689            );
690            prop_assert_eq!(
691                left_bytes.checked_sub(right_bytes).map(ByteCount::get),
692                left.checked_sub(right)
693            );
694        }
695
696        #[test]
697        fn count_wire_round_trip_preserves_all_u64_values(value in any::<u64>()) {
698            let count = TokenCount::new(value);
699            let encoded = to_string(&count).unwrap();
700            prop_assert_eq!(from_str::<TokenCount>(&encoded).unwrap(), count);
701        }
702
703        #[test]
704        fn checked_money_arithmetic_matches_u64(left in any::<u64>(), right in any::<u64>()) {
705            let left_money = Money::new(usd(), left);
706            let right_money = Money::new(usd(), right);
707            prop_assert_eq!(
708                left_money.checked_add(right_money).ok().map(Money::micro_units),
709                left.checked_add(right)
710            );
711            prop_assert_eq!(
712                left_money.checked_sub(right_money).ok().map(Money::micro_units),
713                left.checked_sub(right)
714            );
715        }
716    }
717}