vortex_array/arrays/widen/encode/decimal.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Chooses a narrower [`DecimalArray`] child when encoding or reading stored decimals.
5//!
6//! In memory, a decimal array's precision determines its buffer width. The `vortex.decimal` wire
7//! format records those two properties separately. If a stored buffer is narrower than the logical
8//! dtype requires, the reader can give the child a lower precision and keep the original dtype on
9//! a [`WidenArray`]. [`WidenPlugin`] still writes this format for decimal leaves.
10//!
11//! The encoder and reader use the same rule to choose the child dtype. They use the range of
12//! valid values and the decimal scale to pick a precision, then derive the width from that
13//! precision. For example, an unscaled value of 127 needs precision 3, which uses an `i16` buffer
14//! even though 127 fits in `i8`.
15//!
16//! [`WidenPlugin`]: crate::arrays::widen::WidenPlugin
17
18use std::ops::RangeInclusive;
19
20use vortex_buffer::Buffer;
21use vortex_error::VortexExpect;
22use vortex_error::VortexResult;
23use vortex_error::vortex_bail;
24use vortex_error::vortex_ensure;
25use vortex_error::vortex_ensure_eq;
26use vortex_mask::Mask;
27
28use crate::ArrayRef;
29use crate::ExecutionCtx;
30use crate::IntoArray;
31use crate::arrays::DecimalArray;
32use crate::arrays::WidenArray;
33use crate::arrays::decimal::DecimalArrayExt;
34use crate::arrays::decimal::DecimalData;
35use crate::arrays::decimal::DecimalDataParts;
36use crate::arrays::decimal::copy_to_canonical_width;
37use crate::arrays::decimal::valid_range;
38use crate::buffer::BufferHandle;
39use crate::dtype::DType;
40use crate::dtype::DecimalDType;
41use crate::dtype::NativeDecimalType;
42use crate::dtype::i256;
43use crate::match_each_decimal_value_type;
44use crate::scalar::DecimalValue;
45use crate::scalar::ScalarValue;
46use crate::stats::Precision;
47use crate::stats::Stat;
48use crate::validity::Validity;
49
50impl WidenArray {
51 /// Stores a decimal array at the smallest precision that its valid values and scale allow.
52 ///
53 /// We keep the logical dtype and nullability by wrapping the narrower child in a
54 /// [`WidenArray`]. Reducing precision within the same storage width saves no space, so in that
55 /// case we return the input unchanged.
56 ///
57 /// Empty and all-null arrays have no values to constrain precision, but we still need to keep
58 /// the scale. They use precision 1 or the scale, whichever is greater. If a child is selected,
59 /// we cache any exact extrema as [`Stat::Min`] and [`Stat::Max`] for later aggregates.
60 ///
61 /// # Errors
62 ///
63 /// Returns an error if a valid value does not fit the input precision.
64 pub fn encode_decimal(array: DecimalArray, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
65 let logical_decimal_dtype = array.decimal_dtype();
66 let validity = array.validity()?;
67 let validity_mask = validity.execute_mask(array.len(), ctx)?;
68 let child = match_each_decimal_value_type!(array.values_type(), |T| {
69 let values_buffer = array.buffer::<T>();
70 let valid_value_range =
71 ValidRange::resolve(Precision::Absent, values_buffer.as_slice(), &validity_mask);
72 narrowest_decimal_child(
73 &values_buffer,
74 &validity,
75 &validity_mask,
76 valid_value_range,
77 logical_decimal_dtype,
78 )?
79 });
80
81 let Some(child) = child else {
82 return Ok(array.into_array());
83 };
84
85 Ok(WidenArray::try_new(child.into_array(), array.dtype().clone())?.into_array())
86 }
87
88 /// Converts stored decimals into a canonical leaf or a [`WidenArray`] over one.
89 ///
90 /// Legacy decimal readers can give us a buffer whose width does not match the logical
91 /// precision. We need a canonical leaf without changing the logical dtype or widening narrow
92 /// storage unnecessarily.
93 ///
94 /// If the width is already canonical, we trust the declared precision and reuse the buffer
95 /// without reading its values. This also lets device buffers stay on the device. Otherwise,
96 /// child selection follows [`Self::encode_decimal`], keeping the logical dtype and validity.
97 /// We reuse buffers at the selected width and convert other widths without rescaling.
98 /// A narrowing copy writes zeros in null slots. A reused buffer keeps its null slots.
99 ///
100 /// The scan and the conversion run on the CPU, so noncanonical values and their validity
101 /// **must** be in host memory. This function does not copy device memory to the host.
102 ///
103 /// Readers and decoders may already know the range. For noncanonical storage, `known_range`
104 /// lets us reuse it:
105 ///
106 /// - [`Precision::Absent`] scans valid values to find their extrema.
107 /// - [`Precision::Exact`] **must** give the actual minimum and maximum valid unscaled values.
108 /// - [`Precision::Inexact`] **must** contain every valid unscaled value.
109 ///
110 /// We cache the range on the child as [`Stat::Min`] and [`Stat::Max`], keeping its exactness
111 /// because enclosing bounds are not necessarily actual extrema. Scanning empty or all-null
112 /// input yields no extrema to cache. Canonical-width storage ignores `known_range`.
113 /// Supplied ranges are trusted, even when a narrowing copy checks the selected precision.
114 /// Incorrect ranges or declared precision can cause incorrect results in later operations.
115 ///
116 /// # Errors
117 ///
118 /// Rejects malformed buffer layout or validity length. For noncanonical storage, also rejects
119 /// values or validity in device memory, reversed ranges, and range bounds outside the logical
120 /// precision. A narrowing copy rejects valid values outside the selected precision.
121 pub fn from_stored_decimal(
122 parts: DecimalDataParts,
123 known_range: Precision<RangeInclusive<i256>>,
124 ctx: &mut ExecutionCtx,
125 ) -> VortexResult<ArrayRef> {
126 let DecimalDataParts {
127 decimal_dtype,
128 values,
129 values_type,
130 validity,
131 } = parts;
132
133 // Validate before typed buffer access or mask execution, which can panic on malformed data.
134 DecimalData::validate(&values, values_type)?;
135 let len = values.len() / values_type.byte_width();
136 if let Some(validity_len) = validity.maybe_len() {
137 vortex_ensure_eq!(
138 validity_len,
139 len,
140 "Decimal validity must have one entry per value"
141 );
142 }
143
144 if values_type == decimal_dtype.canonical_values_type() {
145 // A canonical wire node can reuse its buffer without reading the values.
146 let array = DecimalArray::try_new_handle_from_trusted_values(
147 values,
148 values_type,
149 decimal_dtype,
150 validity,
151 )?;
152
153 return Ok(array.into_array());
154 }
155
156 // The scan below reads host memory, so device memory would panic there.
157 vortex_ensure!(
158 values.is_on_host() && validity.as_array().is_none_or(ArrayRef::is_host),
159 "Decimal storage at a noncanonical width must be in host memory, got device memory"
160 );
161 let values = values.unwrap_host();
162 let mask = validity.execute_mask(len, ctx)?;
163 match_each_decimal_value_type!(values_type, |T| {
164 let values = Buffer::<T>::from_byte_buffer(values);
165 let range = ValidRange::resolve(known_range, values.as_slice(), &mask);
166 widen_or_canonical(values, validity, &mask, range, decimal_dtype)
167 })
168 }
169}
170
171/// Chooses child precision from a valid-value range and the parent scale.
172///
173/// We keep the parent scale so values do not need rescaling. The child precision must therefore
174/// be at least 1 and at least the scale. With empty or all-null input, these are the only
175/// constraints. Pass `None` for that case. Otherwise, null payloads **must** be excluded from the
176/// range.
177///
178/// # Errors
179///
180/// Returns an error if the minimum exceeds the maximum or an endpoint exceeds the parent precision.
181pub(crate) fn smallest_decimal_dtype(
182 range: Option<RangeInclusive<i256>>,
183 parent: DecimalDType,
184) -> VortexResult<DecimalDType> {
185 let minimum_precision = parent.scale().max(1) as u8;
186 let Some(range) = range else {
187 return Ok(DecimalDType::new(minimum_precision, parent.scale()));
188 };
189
190 let (min, max) = range.into_inner();
191 vortex_ensure!(
192 min <= max,
193 "Decimal range requires ordered extrema, got {min} to {max}"
194 );
195
196 for precision in minimum_precision..=parent.precision() {
197 let index = usize::from(precision);
198 if i256::MIN_BY_PRECISION[index] <= min && max <= i256::MAX_BY_PRECISION[index] {
199 return Ok(DecimalDType::new(precision, parent.scale()));
200 }
201 }
202
203 vortex_bail!("Decimal range must fit {parent}, got {min} to {max}")
204}
205
206/// Value bounds for choosing child precision and caching statistics.
207///
208/// Supplied bounds need not be actual extrema, so we keep their exactness when caching them.
209/// `Empty` means a scan found no valid values, rather than that statistics are unavailable.
210enum ValidRange {
211 /// No value is valid.
212 Empty,
213 /// The smallest and the largest valid value.
214 Exact(RangeInclusive<i256>),
215 /// Bounds that hold every valid value. They need not be valid values themselves.
216 Bounds(RangeInclusive<i256>),
217}
218
219impl ValidRange {
220 /// Uses known bounds when available, otherwise scans valid values.
221 ///
222 /// Readers and decoders may already have bounds from their input statistics. Reusing them
223 /// avoids scanning the buffer again.
224 fn resolve<F: NativeDecimalType>(
225 known_range: Precision<RangeInclusive<i256>>,
226 values: &[F],
227 mask: &Mask,
228 ) -> Self {
229 match known_range {
230 Precision::Exact(extrema) => return Self::Exact(extrema),
231 Precision::Inexact(bounds) => return Self::Bounds(bounds),
232 Precision::Absent => {}
233 }
234
235 let Some((min, max)) = valid_range(values, mask) else {
236 return Self::Empty;
237 };
238 let min = min.to_i256().vortex_expect("every decimal value fits i256");
239 let max = max.to_i256().vortex_expect("every decimal value fits i256");
240
241 Self::Exact(min..=max)
242 }
243
244 /// Returns the bounds that hold every valid value, or `None` when no value is valid.
245 fn bounds(&self) -> Option<RangeInclusive<i256>> {
246 match self {
247 Self::Empty => None,
248 Self::Exact(bounds) | Self::Bounds(bounds) => Some(bounds.clone()),
249 }
250 }
251
252 /// Caches bounds on the child so later aggregates can reuse them without another scan.
253 ///
254 /// The bounds **must** fit the child's selected precision.
255 fn cache_statistics(self, child: &DecimalArray) {
256 let extrema = match self {
257 Self::Empty => return,
258 Self::Exact(bounds) => Precision::Exact(bounds),
259 Self::Bounds(bounds) => Precision::Inexact(bounds),
260 };
261 let child_dtype = child.decimal_dtype();
262 let min = extrema
263 .clone()
264 .map(|bounds| decimal_stat(*bounds.start(), child_dtype));
265 let max = extrema.map(|bounds| decimal_stat(*bounds.end(), child_dtype));
266 child.statistics().set(Stat::Min, min);
267 child.statistics().set(Stat::Max, max);
268 }
269}
270
271/// Wraps a narrower canonical child, or builds a leaf at the logical width.
272///
273/// The result must keep the logical dtype. Returning a narrow child directly would change it.
274///
275/// `mask` **must** be the mask of `validity`.
276fn widen_or_canonical<F: NativeDecimalType>(
277 values: Buffer<F>,
278 validity: Validity,
279 mask: &Mask,
280 range: ValidRange,
281 decimal_dtype: DecimalDType,
282) -> VortexResult<ArrayRef> {
283 if let Some(child) = narrowest_decimal_child(&values, &validity, mask, range, decimal_dtype)? {
284 let dtype = DType::Decimal(decimal_dtype, validity.nullability());
285 return Ok(WidenArray::try_new(child.into_array(), dtype)?.into_array());
286 }
287
288 let array = build_canonical_decimal(&values, &validity, mask, decimal_dtype)?;
289
290 Ok(array.into_array())
291}
292
293/// Builds the narrowest canonical child, or returns `None` if no narrower width exists.
294///
295/// Reducing precision without changing width saves no space, so we return `None` in that case.
296///
297/// Every valid value **must** lie in `range`, and `mask` **must** be the mask of `validity`.
298fn narrowest_decimal_child<F: NativeDecimalType>(
299 values: &Buffer<F>,
300 validity: &Validity,
301 mask: &Mask,
302 range: ValidRange,
303 decimal_dtype: DecimalDType,
304) -> VortexResult<Option<DecimalArray>> {
305 let child_dtype = smallest_decimal_dtype(range.bounds(), decimal_dtype)?;
306 let child_type = child_dtype.canonical_values_type();
307 if child_type == decimal_dtype.canonical_values_type() {
308 return Ok(None);
309 }
310
311 let child = build_canonical_decimal(values, validity, mask, child_dtype)?;
312 range.cache_statistics(&child);
313
314 Ok(Some(child))
315}
316
317/// Reuses storage at the dtype's canonical width, copying only when conversion is needed.
318///
319/// Every valid value **must** fit `decimal_dtype`, and `mask` **must** describe `validity`.
320fn build_canonical_decimal<F: NativeDecimalType>(
321 values: &Buffer<F>,
322 validity: &Validity,
323 mask: &Mask,
324 decimal_dtype: DecimalDType,
325) -> VortexResult<DecimalArray> {
326 let values_type = decimal_dtype.canonical_values_type();
327 let buffer = if F::DECIMAL_TYPE == values_type {
328 // The copy helper allocates even at the same width, so retain the existing buffer here.
329 BufferHandle::new_host(values.clone().into_byte_buffer())
330 } else {
331 copy_to_canonical_width(values.as_slice(), mask, decimal_dtype)?
332 };
333
334 DecimalArray::try_new_handle_from_trusted_values(
335 buffer,
336 values_type,
337 decimal_dtype,
338 validity.clone(),
339 )
340}
341
342/// Represents a cached bound using the child dtype.
343///
344/// These statistics belong to the child, so their values need its canonical width rather than
345/// the logical parent's width. `value` **must** fit the child's precision.
346fn decimal_stat(value: i256, decimal_dtype: DecimalDType) -> ScalarValue {
347 let value = DecimalValue::try_from_i256(value, decimal_dtype)
348 .vortex_expect("the selected child precision contains its range bounds");
349
350 ScalarValue::Decimal(value)
351}