proof_of_sql/base/math/
decimal.rs

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
//! Module for parsing an `IntermediateDecimal` into a `Decimal75`.
use crate::base::{
    math::BigDecimalExt,
    scalar::{Scalar, ScalarConversionError},
};
use alloc::string::{String, ToString};
use bigdecimal::{BigDecimal, ParseBigDecimalError};
use serde::{Deserialize, Deserializer, Serialize};
use snafu::Snafu;

/// Errors related to the processing of decimal values in proof-of-sql
#[derive(Snafu, Debug, PartialEq)]
pub enum IntermediateDecimalError {
    /// Represents an error encountered during the parsing of a decimal string.
    #[snafu(display("{error}"))]
    ParseError {
        /// The underlying error
        error: ParseBigDecimalError,
    },
    /// Error occurs when this decimal cannot fit in a primitive.
    #[snafu(display("Value out of range for target type"))]
    OutOfRange,
    /// Error occurs when this decimal cannot be losslessly cast into a primitive.
    #[snafu(display("Fractional part of decimal is non-zero"))]
    LossyCast,
    /// Cannot cast this decimal to a big integer
    #[snafu(display("Conversion to integer failed"))]
    ConversionFailure,
}

impl Eq for IntermediateDecimalError {}

/// Errors related to decimal operations.
#[derive(Snafu, Debug, Eq, PartialEq)]
pub enum DecimalError {
    #[snafu(display("Invalid decimal format or value: {error}"))]
    /// Error when a decimal format or value is incorrect,
    /// the string isn't even a decimal e.g. "notastring",
    /// "-21.233.122" etc aka `InvalidDecimal`
    InvalidDecimal {
        /// The underlying error
        error: String,
    },

    #[snafu(display("Decimal precision is not valid: {error}"))]
    /// Decimal precision exceeds the allowed limit,
    /// e.g. precision above 75/76/whatever set by Scalar
    /// or non-positive aka `InvalidPrecision`
    InvalidPrecision {
        /// The underlying error
        error: String,
    },

    #[snafu(display("Decimal scale is not valid: {scale}"))]
    /// Decimal scale is not valid. Here we use i16 in order to include
    /// invalid scale values
    InvalidScale {
        /// The invalid scale value
        scale: String,
    },

    #[snafu(display("Unsupported operation: cannot round decimal: {error}"))]
    /// This error occurs when attempting to scale a
    /// decimal in such a way that a loss of precision occurs.
    RoundingError {
        /// The underlying error
        error: String,
    },

    /// Errors that may occur when parsing an intermediate decimal
    /// into a posql decimal
    #[snafu(transparent)]
    IntermediateDecimalConversionError {
        /// The underlying source error
        source: IntermediateDecimalError,
    },
}

/// Result type for decimal operations.
pub type DecimalResult<T> = Result<T, DecimalError>;

// This exists because `TryFrom<arrow::datatypes::DataType>` for `ColumnType` error is String
impl From<DecimalError> for String {
    fn from(error: DecimalError) -> Self {
        error.to_string()
    }
}

#[derive(Eq, PartialEq, Debug, Clone, Hash, Serialize, Copy)]
/// limit-enforced precision
pub struct Precision(u8);
pub(crate) const MAX_SUPPORTED_PRECISION: u8 = 75;

impl Precision {
    /// Constructor for creating a Precision instance
    pub fn new(value: u8) -> Result<Self, DecimalError> {
        if value > MAX_SUPPORTED_PRECISION || value == 0 {
            Err(DecimalError::InvalidPrecision {
                error: value.to_string(),
            })
        } else {
            Ok(Precision(value))
        }
    }

    /// Gets the precision as a u8 for this decimal
    #[must_use]
    pub fn value(&self) -> u8 {
        self.0
    }
}

impl TryFrom<u64> for Precision {
    type Error = DecimalError;
    fn try_from(value: u64) -> Result<Self, Self::Error> {
        Precision::new(
            value
                .try_into()
                .map_err(|_| DecimalError::InvalidPrecision {
                    error: value.to_string(),
                })?,
        )
    }
}

// Custom deserializer for precision since we need to limit its value to 75
impl<'de> Deserialize<'de> for Precision {
    fn deserialize<D>(deserializer: D) -> Result<Precision, D::Error>
    where
        D: Deserializer<'de>,
    {
        // Deserialize as a u8
        let value = u8::deserialize(deserializer)?;

        // Use the Precision::new method to ensure the value is within the allowed range
        Precision::new(value).map_err(serde::de::Error::custom)
    }
}

/// Fallibly attempts to convert an `IntermediateDecimal` into the
/// native proof-of-sql [Scalar] backing store. This function adjusts
/// the decimal to the specified `target_precision` and `target_scale`,
/// and validates that the adjusted decimal does not exceed the specified precision.
/// If the conversion is successful, it returns the `Scalar` representation;
/// otherwise, it returns a `DecimalError` indicating the type of failure
/// (e.g., exceeding precision limits).
///
/// ## Arguments
/// * `d` - The `IntermediateDecimal` to convert.
/// * `target_precision` - The maximum number of digits the scalar can represent.
/// * `target_scale` - The scale (number of decimal places) to use in the scalar.
///
/// ## Errors
/// Returns `DecimalError::InvalidPrecision` error if the number of digits in
/// the decimal exceeds the `target_precision` before or after adjusting for
/// `target_scale`, or if the target precision is zero.
pub(crate) fn try_convert_intermediate_decimal_to_scalar<S: Scalar>(
    d: &BigDecimal,
    target_precision: Precision,
    target_scale: i8,
) -> DecimalResult<S> {
    d.try_into_bigint_with_precision_and_scale(target_precision.value(), target_scale)?
        .try_into()
        .map_err(|e: ScalarConversionError| DecimalError::InvalidDecimal {
            error: e.to_string(),
        })
}

#[cfg(test)]
mod scale_adjust_test {

    use super::*;
    use crate::base::scalar::test_scalar::TestScalar;
    use num_bigint::BigInt;

    #[test]
    fn we_cannot_scale_past_max_precision() {
        let decimal = "12345678901234567890123456789012345678901234567890123456789012345678900.0"
            .parse()
            .unwrap();

        let target_scale = 5;

        assert!(try_convert_intermediate_decimal_to_scalar::<TestScalar>(
            &decimal,
            Precision::new(u8::try_from(decimal.precision()).unwrap_or(u8::MAX)).unwrap(),
            target_scale
        )
        .is_err());
    }

    #[test]
    fn we_can_match_exact_decimals_from_queries_to_db() {
        let decimal: BigDecimal = "123.45".parse().unwrap();
        let target_scale = 2;
        let target_precision = 20;
        let big_int =
            decimal.try_into_bigint_with_precision_and_scale(target_precision, target_scale);
        let expected_big_int: BigInt = "12345".parse().unwrap();
        assert_eq!(big_int, Ok(expected_big_int));
    }

    #[test]
    fn we_can_match_decimals_with_negative_scale() {
        let decimal = "120.00".parse().unwrap();
        let target_scale = -1;
        let expected = [12, 0, 0, 0];
        let result = try_convert_intermediate_decimal_to_scalar::<TestScalar>(
            &decimal,
            Precision::new(MAX_SUPPORTED_PRECISION).unwrap(),
            target_scale,
        )
        .unwrap();
        assert_eq!(result, TestScalar::from(expected));
    }

    #[test]
    fn we_can_match_integers_with_negative_scale() {
        let decimal = "12300".parse().unwrap();
        let target_scale = -2;
        let expected_limbs = [123, 0, 0, 0];

        let limbs = try_convert_intermediate_decimal_to_scalar::<TestScalar>(
            &decimal,
            Precision::new(u8::try_from(decimal.precision()).unwrap_or(u8::MAX)).unwrap(),
            target_scale,
        )
        .unwrap();

        assert_eq!(limbs, TestScalar::from(expected_limbs));
    }

    #[test]
    fn we_can_match_negative_decimals() {
        let decimal = "-123.45".parse().unwrap();
        let target_scale = 2;
        let expected_limbs = [12345, 0, 0, 0];
        let limbs = try_convert_intermediate_decimal_to_scalar::<TestScalar>(
            &decimal,
            Precision::new(u8::try_from(decimal.precision()).unwrap_or(u8::MAX)).unwrap(),
            target_scale,
        )
        .unwrap();
        assert_eq!(limbs, -TestScalar::from(expected_limbs));
    }

    #[allow(clippy::cast_possible_wrap)]
    #[test]
    fn we_can_match_decimals_at_extrema() {
        // a big decimal cannot scale up past the supported precision
        let decimal = "1234567890123456789012345678901234567890123456789012345678901234567890.0"
            .parse()
            .unwrap();
        let target_scale = 6; // now precision exceeds maximum
        assert!(try_convert_intermediate_decimal_to_scalar::<TestScalar>(
            &decimal,
            Precision::new(u8::try_from(decimal.precision()).unwrap_or(u8::MAX),).unwrap(),
            target_scale
        )
        .is_err());

        // maximum decimal value we can support
        let decimal =
            "99999999999999999999999999999999999999999999999999999999999999999999999999.0"
                .parse()
                .unwrap();
        let target_scale = 1;
        assert!(try_convert_intermediate_decimal_to_scalar::<TestScalar>(
            &decimal,
            Precision::new(MAX_SUPPORTED_PRECISION).unwrap(),
            target_scale
        )
        .is_ok());

        // scaling larger than max will fail
        let decimal =
            "999999999999999999999999999999999999999999999999999999999999999999999999999.0"
                .parse()
                .unwrap();
        let target_scale = 1;
        assert!(try_convert_intermediate_decimal_to_scalar::<TestScalar>(
            &decimal,
            Precision::new(MAX_SUPPORTED_PRECISION).unwrap(),
            target_scale
        )
        .is_err());

        // smallest possible decimal value we can support (either signed/unsigned)
        let decimal =
            "0.000000000000000000000000000000000000000000000000000000000000000000000000001"
                .parse()
                .unwrap();
        let target_scale = MAX_SUPPORTED_PRECISION as i8;
        assert!(try_convert_intermediate_decimal_to_scalar::<TestScalar>(
            &decimal,
            Precision::new(u8::try_from(decimal.precision()).unwrap_or(u8::MAX),).unwrap(),
            target_scale
        )
        .is_ok());

        // this is ok because it can be scaled to 75 precision
        let decimal = "0.1".parse().unwrap();
        let target_scale = MAX_SUPPORTED_PRECISION as i8;
        assert!(try_convert_intermediate_decimal_to_scalar::<TestScalar>(
            &decimal,
            Precision::new(MAX_SUPPORTED_PRECISION).unwrap(),
            target_scale
        )
        .is_ok());

        // this exceeds max precision
        let decimal = "1.0".parse().unwrap();
        let target_scale = 75;
        assert!(try_convert_intermediate_decimal_to_scalar::<TestScalar>(
            &decimal,
            Precision::new(u8::try_from(decimal.precision()).unwrap_or(u8::MAX),).unwrap(),
            target_scale
        )
        .is_err());

        // but this is ok
        let decimal = "1.0".parse().unwrap();
        let target_scale = 74;
        assert!(try_convert_intermediate_decimal_to_scalar::<TestScalar>(
            &decimal,
            Precision::new(MAX_SUPPORTED_PRECISION).unwrap(),
            target_scale
        )
        .is_ok());
    }
}