spg-engine 7.37.22

Execution engine for SPG: glues spg-sql parsing to spg-storage. Foreign keys, joins, vectors, cold tier.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
//! NUMERIC value construction, parsing, rescaling, and precision checks.
//! Split out of `lib.rs` (v7.32 engine modularisation): pure functions
//! with no Engine state — integer/float/text in, `Result<Value,
//! EngineError>` out.

use spg_storage::Value;

use crate::EngineError;

/// v7.39 (round 273) — apply a NEGATIVE declared scale: round the value
/// to the nearest multiple of `10^k` and return it at display scale 0,
/// which is how PG stores `numeric(10,-2)`.
///
/// The rounding is done in ONE step against `10^(src_scale + k)`. Going
/// via the integer first would round twice, and 1249.5 to hundreds would
/// come out 1300 instead of 1200.
fn apply_negative_scale(scaled: i128, src_scale: u16, k: u16) -> Option<i128> {
    let denom = pow10_i128_checked(src_scale.checked_add(k)?)?;
    let half = denom / 2;
    let biased = if scaled >= 0 {
        scaled.checked_add(half)?
    } else {
        scaled.checked_sub(half)?
    };
    (biased / denom).checked_mul(pow10_i128_checked(k)?)
}

/// The unsigned part of a declared scale, and whether it was negative.
const fn split_declared_scale(scale: i16) -> (bool, u16) {
    if scale < 0 {
        (true, scale.unsigned_abs())
    } else {
        #[allow(clippy::cast_sign_loss)]
        (false, scale as u16)
    }
}

/// Promote an integer to a NUMERIC value at the requested scale.
/// Rejects values that, after scaling, would overflow the column's
/// precision budget.
pub(crate) fn numeric_from_integer(
    n: i128,
    precision: u16,
    scale: i16,
    col_name: &str,
) -> Result<Value<'static>, EngineError> {
    let (neg, k) = split_declared_scale(scale);
    if neg {
        let rounded = apply_negative_scale(n, 0, k).ok_or_else(|| {
            EngineError::Unsupported(alloc::format!(
                "integer overflow scaling value for column `{col_name}` to scale {scale}"
            ))
        })?;
        check_precision(rounded, precision, scale, col_name)?;
        return Ok(Value::Numeric {
            scaled: rounded,
            scale: 0,
            kind: spg_storage::NumericKind::Finite,
        });
    }
    let scale = k;
    let factor = pow10_i128(scale);
    let scaled = n.checked_mul(factor).ok_or_else(|| {
        EngineError::Unsupported(alloc::format!(
            "integer overflow scaling value for column `{col_name}` to scale {scale}"
        ))
    })?;
    #[allow(clippy::cast_possible_wrap)]
    let signed_scale = scale as i16;
    check_precision(scaled, precision, signed_scale, col_name)?;
    Ok(Value::Numeric {
        scaled,
        scale,
        kind: spg_storage::NumericKind::Finite,
    })
}

/// Float → NUMERIC. Uses round-half-away-from-zero on `x * 10^scale`,
/// then verifies the result fits the column's precision.
#[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
pub(crate) fn numeric_from_float(
    x: f64,
    precision: u16,
    scale: i16,
    col_name: &str,
) -> Result<Value<'static>, EngineError> {
    let (neg_scale, k) = split_declared_scale(scale);
    if neg_scale {
        if !x.is_finite() {
            return Err(EngineError::Unsupported(alloc::format!(
                "cannot store non-finite float in NUMERIC column `{col_name}`"
            )));
        }
        let mut f = 1.0_f64;
        for _ in 0..k {
            f *= 10.0;
        }
        let q = (x / f).round();
        #[allow(clippy::cast_possible_truncation)]
        let rounded = (q as i128).checked_mul(pow10_i128(k)).ok_or_else(|| {
            EngineError::Unsupported(alloc::format!(
                "value overflows NUMERIC column `{col_name}`"
            ))
        })?;
        check_precision(rounded, precision, scale, col_name)?;
        return Ok(Value::Numeric {
            scaled: rounded,
            scale: 0,
            kind: spg_storage::NumericKind::Finite,
        });
    }
    let scale = k;
    if !x.is_finite() {
        return Err(EngineError::Unsupported(alloc::format!(
            "cannot store non-finite float in NUMERIC column `{col_name}`"
        )));
    }
    let mut factor = 1.0_f64;
    for _ in 0..scale {
        factor *= 10.0;
    }
    // Round half-away-from-zero by biasing then casting (`as i128`
    // truncates toward zero, so the bias + truncation gives the
    // desired rounding). `f64::floor` / `ceil` live in std; we don't
    // need them — the cast handles the truncation step.
    let shifted = x * factor;
    let biased = if shifted >= 0.0 {
        shifted + 0.5
    } else {
        shifted - 0.5
    };
    // Range-check before casting back to i128 — the cast itself is
    // saturating in Rust, which would silently truncate huge inputs.
    if !(-1e38..=1e38).contains(&biased) {
        return Err(EngineError::Unsupported(alloc::format!(
            "value {x} overflows NUMERIC range for column `{col_name}`"
        )));
    }
    let scaled = biased as i128;
    #[allow(clippy::cast_possible_wrap)]
    let signed_scale = scale as i16;
    check_precision(scaled, precision, signed_scale, col_name)?;
    Ok(Value::Numeric {
        scaled,
        scale,
        kind: spg_storage::NumericKind::Finite,
    })
}

/// v7.17.0 Phase 3.P0-67 — parse PG-canonical decimal text into
/// `(mantissa: i128, source_scale: u16)`. Accepts optional sign,
/// optional integer part, optional fractional part. Rejects
/// scientific notation, embedded spaces, locale-specific
/// thousand separators. Returns None on bad input — coerce_value
/// turns that into a TypeMismatch error.
/// v7.38 (read01, T6) — recognise PG's NUMERIC special-value spellings.
/// Case-insensitive: `NaN`; `Infinity` / `Inf` / `+Infinity` / `+Inf`;
/// `-Infinity` / `-Inf`. Returns `None` for an ordinary number.
pub(crate) fn parse_numeric_special(s: &str) -> Option<spg_storage::NumericKind> {
    use spg_storage::NumericKind;
    let t = s.trim();
    let lower = t.to_ascii_lowercase();
    match lower.as_str() {
        "nan" => Some(NumericKind::NaN),
        "infinity" | "inf" | "+infinity" | "+inf" => Some(NumericKind::PosInf),
        "-infinity" | "-inf" => Some(NumericKind::NegInf),
        _ => None,
    }
}

/// v7.39 (round 254) — PG's NUMERIC special-value table for the scalar
/// math family, probed cell by cell against live PG18.4 (2026-07-19).
///
/// The `NumericKind` infrastructure has existed since v7.38 (comparison,
/// min/max and `power` honour it), but every other math function and the
/// numeric casts rebuilt their result with `kind: Finite`, so a NaN or
/// ±Infinity argument collapsed to the canonical mantissa `0` and the
/// answer was silently wrong (`abs('-Infinity')` = 0, not Infinity).
///
/// Returns `None` when the call has no special argument or the name is
/// not in the table (the ordinary finite path then runs unchanged).
///
/// # Errors
/// The cells where PG itself raises: sqrt / ln / log of -Infinity, and
/// width_bucket with a NaN operand or bound.
pub(crate) fn special_math(
    name: &str,
    args: &[Value<'_>],
) -> Option<Result<Value<'static>, crate::eval::EvalError>> {
    use spg_storage::NumericKind as K;
    let kind_of = |v: &Value<'_>| match v {
        Value::Numeric { kind, .. } if *kind != K::Finite => Some(*kind),
        _ => None,
    };
    // Only NUMERIC specials take this path; the float8 family follows
    // IEEE semantics through Rust's own f64 arithmetic.
    if !args.iter().any(|a| kind_of(a).is_some()) {
        return None;
    }
    let special = |k: K| {
        Ok(Value::Numeric {
            scaled: 0,
            scale: 0,
            kind: k,
        })
    };
    let finite = |n: i128| {
        Ok(Value::Numeric {
            scaled: n,
            scale: 0,
            kind: K::Finite,
        })
    };
    let neg_err = |what: &str| {
        Err(crate::eval::EvalError::TypeMismatch {
            detail: alloc::format!("cannot take {what} of a negative number"),
        })
    };
    let a0 = kind_of(&args[0]);
    let a1 = args.get(1).and_then(kind_of);
    Some(match (name, a0) {
        // abs folds -Infinity onto +Infinity; NaN stays NaN.
        ("abs", Some(K::NegInf)) => special(K::PosInf),
        ("abs", Some(k)) => special(k),
        // The rounding family passes every special through unchanged —
        // including the two-argument spellings (`round(x, n)` /
        // `trunc(x, n)`), where the scale argument is simply ignored.
        ("trunc" | "truncate" | "round" | "ceil" | "ceiling" | "floor" | "trim_scale", Some(k)) => {
            special(k)
        }
        // sign reports the direction of an infinity, NaN of a NaN.
        ("sign", Some(K::PosInf)) => finite(1),
        ("sign", Some(K::NegInf)) => finite(-1),
        ("sign", Some(K::NaN)) => special(K::NaN),
        // scale / min_scale of a special is NULL (PG has no scale to report).
        ("scale" | "min_scale", Some(_)) => Ok(Value::Null),
        ("sqrt", Some(K::NegInf)) => neg_err("square root"),
        ("sqrt", Some(k)) => special(k),
        ("ln", Some(K::NegInf)) => neg_err("logarithm"),
        ("ln", Some(k)) => special(k),
        ("exp", Some(K::NegInf)) => finite(0),
        ("exp", Some(k)) => special(k),
        // log's one-argument form is base 10; the two-argument form is
        // log(base, x) — probed: log(2, Inf) = Infinity, log(Inf, 2) = 0.
        ("log", Some(K::NegInf)) if args.len() == 1 => neg_err("logarithm"),
        ("log", Some(k)) if args.len() == 1 => special(k),
        ("log", Some(K::PosInf)) => finite(0),
        ("log", _) if a1 == Some(K::PosInf) => special(K::PosInf),
        ("log", _) if a1 == Some(K::NaN) || a0 == Some(K::NaN) => special(K::NaN),
        // div truncates toward zero: an infinite dividend stays infinite,
        // an infinite divisor gives 0, NaN anywhere gives NaN.
        ("div", Some(K::NaN)) => special(K::NaN),
        ("div", Some(k)) if a1.is_none() => special(k),
        ("div", _) if a1 == Some(K::NaN) => special(K::NaN),
        ("div", _) => finite(0),
        // mod is NaN whenever either side is special (probed: even
        // mod(Infinity, 2) is NaN, not Infinity).
        ("mod", _) => special(K::NaN),
        // width_bucket refuses a NaN operand or bound outright.
        ("width_bucket", _) => Err(crate::eval::EvalError::TypeMismatch {
            detail: alloc::string::String::from(
                "operand, lower bound, and upper bound cannot be NaN",
            ),
        }),
        _ => return None,
    })
}

/// v7.38 (read01) — PG 16+ accepts `_` as a digit-group separator in numeric /
/// integer *input* (`'1_000'::numeric`), but only between two digits — not
/// leading, trailing, doubled, or adjacent to a sign / point / exponent.
/// Returns the underscore-free string, or `None` if any `_` is misplaced.
pub(crate) fn strip_digit_underscores(s: &str) -> Option<alloc::borrow::Cow<'_, str>> {
    if !s.contains('_') {
        return Some(alloc::borrow::Cow::Borrowed(s));
    }
    let b = s.as_bytes();
    for (i, &c) in b.iter().enumerate() {
        if c == b'_'
            && !(i > 0 && i + 1 < b.len() && b[i - 1].is_ascii_digit() && b[i + 1].is_ascii_digit())
        {
            return None;
        }
    }
    Some(alloc::borrow::Cow::Owned(s.replace('_', "")))
}

pub(crate) fn parse_numeric_text(s: &str) -> Option<(i128, u16)> {
    let s = s.trim();
    if s.is_empty() {
        return None;
    }
    let s: &str = &strip_digit_underscores(s)?;
    // Scientific notation (`1e3`, `1.5e2`, `3E-4`): split off the exponent
    // and fold it into the decimal scale. PG accepts this in numeric input.
    if let Some(idx) = s.find(['e', 'E']) {
        let exp: i32 = s[idx + 1..].parse().ok()?;
        let (mantissa, base_scale) = parse_plain_numeric(&s[..idx])?;
        // Effective scale = base fractional digits minus the exponent.
        let eff = i32::from(base_scale) - exp;
        return if eff >= 0 {
            Some((mantissa, u16::try_from(eff).ok()?))
        } else {
            // Negative scale → shift the mantissa up, land at scale 0.
            let shift = u16::try_from(-eff).ok()?;
            if shift > 38 {
                return None;
            }
            Some((mantissa.checked_mul(pow10_i128(shift))?, 0))
        };
    }
    parse_plain_numeric(s)
}

/// Parse a plain (no-exponent) decimal `[+-]int[.frac]` into `(mantissa, scale)`.
fn parse_plain_numeric(s: &str) -> Option<(i128, u16)> {
    if s.is_empty() {
        return None;
    }
    let (negative, rest) = match s.as_bytes()[0] {
        b'-' => (true, &s[1..]),
        b'+' => (false, &s[1..]),
        _ => (false, s),
    };
    if rest.is_empty() {
        return None;
    }
    let (int_part, frac_part) = match rest.find('.') {
        Some(idx) => (&rest[..idx], &rest[idx + 1..]),
        None => (rest, ""),
    };
    if int_part.is_empty() && frac_part.is_empty() {
        return None;
    }
    if int_part.bytes().any(|b| !b.is_ascii_digit()) {
        return None;
    }
    if frac_part.bytes().any(|b| !b.is_ascii_digit()) {
        return None;
    }
    let scale_u32 = u32::try_from(frac_part.len()).ok()?;
    // v7.39 (round 271) — was u8::MAX. The third of three places that
    // silently dropped a decimal with more than 255 places out of the
    // numeric path.
    if scale_u32 > u32::from(u16::MAX) {
        return None;
    }
    #[allow(clippy::cast_possible_truncation)]
    let scale = scale_u32 as u16;
    let mut digits = alloc::string::String::with_capacity(int_part.len() + frac_part.len() + 1);
    if negative {
        digits.push('-');
    }
    digits.push_str(int_part);
    digits.push_str(frac_part);
    // Strip a leading "+0..0" so parse doesn't choke on "00" etc.
    let digits = if digits == "-" {
        return None;
    } else if digits.is_empty() {
        "0"
    } else {
        digits.as_str()
    };
    let mantissa: i128 = digits.parse().ok()?;
    Some((mantissa, scale))
}

/// Move a Numeric value from `src_scale` to `dst_scale`. Going up
/// multiplies by 10; going down rounds half-away-from-zero.
pub(crate) fn numeric_rescale(
    scaled: i128,
    src_scale: u16,
    precision: u16,
    dst_scale: i16,
    col_name: &str,
) -> Result<Value<'static>, EngineError> {
    let (neg_scale, k) = split_declared_scale(dst_scale);
    if neg_scale {
        let rounded = apply_negative_scale(scaled, src_scale, k).ok_or_else(|| {
            EngineError::Unsupported(alloc::format!(
                "overflow rescaling NUMERIC for column `{col_name}`"
            ))
        })?;
        check_precision(rounded, precision, dst_scale, col_name)?;
        return Ok(Value::Numeric {
            scaled: rounded,
            scale: 0,
            kind: spg_storage::NumericKind::Finite,
        });
    }
    let dst_scale = k;
    // v7.39 (round 272) — a declared scale of 999 is legal in PG, and no
    // i128 mantissa can carry it. Rather than report an overflow for a
    // typmod PG accepts, hand the whole rescale to the
    // arbitrary-precision form, which the storage layer already carries.
    if dst_scale >= src_scale && pow10_i128_checked(dst_scale - src_scale).is_none() {
        let widened =
            spg_storage::bignum::BigNumeric::from_i128(scaled, src_scale).round_to(dst_scale);
        return Ok(crate::eval::binop::bignum_to_value(widened));
    }
    let new_scaled = if dst_scale >= src_scale {
        let bump = pow10_i128(dst_scale - src_scale);
        match scaled.checked_mul(bump) {
            Some(v) => v,
            None => {
                let widened = spg_storage::bignum::BigNumeric::from_i128(scaled, src_scale)
                    .round_to(dst_scale);
                return Ok(crate::eval::binop::bignum_to_value(widened));
            }
        }
    } else {
        let drop = pow10_i128(src_scale - dst_scale);
        let half = drop / 2;
        if scaled >= 0 {
            (scaled + half) / drop
        } else {
            (scaled - half) / drop
        }
    };
    #[allow(clippy::cast_possible_wrap)]
    let signed_dst = dst_scale as i16;
    check_precision(new_scaled, precision, signed_dst, col_name)?;
    Ok(Value::Numeric {
        scaled: new_scaled,
        scale: dst_scale,
        kind: spg_storage::NumericKind::Finite,
    })
}

/// Drop the fractional part of a scaled integer, returning the integer
/// portion (toward zero). Used for NUMERIC → INT casts.
pub(crate) const fn numeric_truncate_to_integer(scaled: i128, scale: u16) -> i128 {
    if scale == 0 {
        return scaled;
    }
    let factor = pow10_i128_const(scale);
    scaled / factor
}

/// Round a scaled NUMERIC to the nearest integer, half away from zero — the
/// behaviour PG uses when assigning / casting `numeric` to an integer type
/// (`1.5 → 2`, `-1.5 → -2`, `1.4 → 1`). Used by the integer-column coercion
/// arms so an INSERT rounds like the `::int` cast rather than truncating.
pub(crate) const fn numeric_round_to_integer(scaled: i128, scale: u16) -> i128 {
    if scale == 0 {
        return scaled;
    }
    let factor = pow10_i128_const(scale);
    let neg = scaled < 0;
    let abs = scaled.unsigned_abs() as i128;
    let q = abs / factor;
    let r = abs % factor;
    let mag = if 2 * r >= factor { q + 1 } else { q };
    if neg { -mag } else { mag }
}

/// Verify a scaled NUMERIC value fits the column's declared precision.
/// `precision == 0` is the "unconstrained" form (bare `NUMERIC`); we
/// skip the check there.
///
/// v7.39 (round 193) — PG's exact wording + DETAIL (live-verified):
/// `numeric field overflow` / `A field with precision P, scale S must
/// round to an absolute value less than 10^(P-S).` The wire layer
/// splits the " DETAIL: " tail into the ErrorResponse D field.
/// v7.39 (round 272) — the precision check by DIGIT COUNT, for values
/// (and precisions) the i128 comparison below cannot express. PG's rule
/// is on the integer part: it must fit `precision - scale` digits.
pub(crate) fn check_precision_text(
    v: &Value<'static>,
    precision: u16,
    scale: i16,
    _col_name: &str,
) -> Result<(), EngineError> {
    if precision == 0 {
        return Ok(());
    }
    let text = match v {
        Value::Numeric { scaled, scale, .. } => crate::eval::format_numeric(*scaled, *scale),
        Value::NumericBig(b) => b.to_decimal_str(),
        _ => return Ok(()),
    };
    let body = text.trim_start_matches('-');
    let int_part = body
        .split('.')
        .next()
        .unwrap_or(body)
        .trim_start_matches('0');
    // PG's limit is 10^(precision - scale); a NEGATIVE scale therefore
    // ALLOWS more integer digits, not fewer.
    let allowed = usize::try_from(i32::from(precision) - i32::from(scale)).unwrap_or(0);
    if int_part.len() > allowed {
        return Err(numeric_field_overflow(precision, scale));
    }
    Ok(())
}

fn numeric_field_overflow(precision: u16, scale: i16) -> EngineError {
    EngineError::Unsupported(alloc::format!(
        "numeric field overflow DETAIL: A field with precision {precision}, scale {scale} \
         must round to an absolute value less than 10^{}.",
        i32::from(precision) - i32::from(scale)
    ))
}

fn check_precision(
    scaled: i128,
    precision: u16,
    scale: i16,
    col_name: &str,
) -> Result<(), EngineError> {
    if precision == 0 {
        return Ok(());
    }
    // A precision past i128's width cannot be expressed as a limit here;
    // fall back to counting digits.
    if precision > 38 || scale < 0 {
        return check_precision_text(
            &Value::Numeric {
                scaled,
                scale: 0,
                kind: spg_storage::NumericKind::Finite,
            },
            precision,
            scale,
            col_name,
        );
    }
    #[allow(clippy::cast_sign_loss)]
    let limit = pow10_i128(precision);
    if scaled.unsigned_abs() >= limit.unsigned_abs() {
        return Err(numeric_field_overflow(precision, scale));
    }
    Ok(())
}

/// Exact NUMERIC addition, aligning the two operands on the larger of
/// their scales (scaling *up* never rounds, so the sum stays exact).
/// Used by `sum(numeric)` / `avg(numeric)` accumulators — reuses the
/// same integral-mantissa arithmetic the `+` binop does, no f64.
/// Saturates on i128 overflow rather than panicking (extreme
/// magnitudes are out of scope; representable-range sums are exact).
/// v7.39 (read01 numeric.c) — overflow-honest sibling of `numeric_add`:
/// `None` when the scale-aligned sum leaves i128, so the caller can promote
/// to the bignum accumulator instead of saturating to a wrong value.
pub(crate) fn numeric_add_checked(
    a: i128,
    a_scale: u16,
    b: i128,
    b_scale: u16,
) -> Option<(i128, u16)> {
    if a_scale == b_scale {
        a.checked_add(b).map(|s| (s, a_scale))
    } else if a_scale > b_scale {
        let f = 10i128.checked_pow(u32::from(a_scale - b_scale))?;
        a.checked_add(b.checked_mul(f)?).map(|s| (s, a_scale))
    } else {
        let f = 10i128.checked_pow(u32::from(b_scale - a_scale))?;
        a.checked_mul(f)?.checked_add(b).map(|s| (s, b_scale))
    }
}

pub(crate) fn numeric_add(a: i128, a_scale: u16, b: i128, b_scale: u16) -> (i128, u16) {
    if a_scale == b_scale {
        (a.saturating_add(b), a_scale)
    } else if a_scale > b_scale {
        let f = pow10_sat(a_scale - b_scale);
        (a.saturating_add(b.saturating_mul(f)), a_scale)
    } else {
        let f = pow10_sat(b_scale - a_scale);
        (a.saturating_mul(f).saturating_add(b), b_scale)
    }
}

/// PG-compatible `avg(numeric)` = sum / count. Picks the division result
/// scale with `division_display_scale` (which reproduces PG's observable
/// division scale — ~16 significant digits in 4-digit groups), then
/// rounds half-away-from-zero, matching PG18's exact avg output text
/// including trailing digits. `count` must be > 0 (callers gate on
/// `count == 0 → NULL`).
pub(crate) fn numeric_avg(sum_scaled: i128, sum_scale: u16, count: i128) -> (i128, u16) {
    let rscale = division_display_scale(sum_scaled, sum_scale, count, 0);
    let (num, den) = if i32::from(rscale) >= i32::from(sum_scale) {
        let k = rscale - sum_scale;
        (sum_scaled.saturating_mul(pow10_sat(k)), count)
    } else {
        let k = sum_scale - rscale;
        (sum_scaled, count.saturating_mul(pow10_sat(k)))
    };
    (div_round_half_away(num, den), rscale)
}

/// PG-compatible `numeric / numeric`: picks the display scale with
/// `division_display_scale` (which keeps ~16 significant digits — so
/// `10 / 3` yields 16 fractional digits, not 0), then rounds
/// half-away-from-zero. `a`/`b` are
/// `(scaled, scale)` pairs; `b != 0` is the caller's contract. Returns `None`
/// only on i128 overflow of the pre-scale multiply (SPG's fixed-width limit,
/// surfaced as an honest error rather than a silently-truncated result).
pub(crate) fn numeric_div(a: i128, sa: u16, b: i128, sb: u16) -> Option<(i128, u16)> {
    let rscale = division_display_scale(a, sa, b, sb);
    // True value = (a / 10^sa) / (b / 10^sb) = (a * 10^sb) / (b * 10^sa).
    // Express it at `rscale`: result_scaled = round( a * 10^(sb+rscale) /
    // (b * 10^sa) ). Fold the exponents into one power of ten with a sign.
    let e = i32::from(sb) + i32::from(rscale) - i32::from(sa);
    let (num, den) = if e >= 0 {
        (a.checked_mul(pow10_checked(e as u32)?)?, b)
    } else {
        (a, b.checked_mul(pow10_checked((-e) as u32)?)?)
    };
    Some((div_round_half_away(num, den), rscale))
}

/// `10^p` as i128, or `None` on overflow (unlike `pow10_sat`, which
/// saturates — a saturated power would corrupt the division scaling).
fn pow10_checked(p: u32) -> Option<i128> {
    let mut acc: i128 = 1;
    for _ in 0..p {
        acc = acc.checked_mul(10)?;
    }
    Some(acc)
}

/// The display scale SPG gives a NUMERIC division result. This targets
/// the scale PG's `/` operator produces — a differential-verified
/// behaviour, not a transcription of PG's code: `10/3` →
/// `3.3333333333333333` (16 fractional digits), `1/3` →
/// `0.33333333333333333333` (20), `1000000/3` → `333333.333333333333`
/// (12). The rule keeps roughly 16 significant decimal digits, shifted by
/// the quotient's magnitude and floored by the dividend's own scale.
///
/// The magnitude is counted in 4-digit groups, because PG's result scale
/// steps a whole group at a time (which is why `1/3` gains four more
/// fractional digits than `10/3`, not one) — SPG has to group the same
/// way to land on PG's exact scale. `base10000_weight_firstdigit` gives
/// each operand's leading-group index and digit. The 1000 cap is PG's
/// display-scale ceiling; SPG then clamps to its `u8` scale field.
fn division_display_scale(
    dividend: i128,
    dividend_scale: u16,
    divisor: i128,
    divisor_scale: u16,
) -> u16 {
    let dwf = base10000_weight_firstdigit(dividend, dividend_scale);
    let vwf = base10000_weight_firstdigit(divisor, divisor_scale);
    division_display_scale_from_wf(dwf, dividend_scale, vwf)
}

/// v7.38 (read01, T3.C3) — the same display scale for a division whose
/// operands exceed i128. Works off each operand's unscaled mantissa digit
/// string (from `BigNumeric::to_decimal_str`) so the base-10000 weight logic
/// is shared with the i128 path.
pub(crate) fn division_display_scale_big(
    dividend: &spg_storage::bignum::BigNumeric,
    divisor: &spg_storage::bignum::BigNumeric,
) -> u16 {
    let (dm, ds) = mantissa_and_scale_big(dividend);
    let (vm, vs) = mantissa_and_scale_big(divisor);
    let dwf = weight_firstdigit_core(&dm, ds);
    let vwf = weight_firstdigit_core(&vm, vs);
    division_display_scale_from_wf(dwf, ds, vwf)
}

/// v7.38 (read01, C4) — the display scale PG's numeric `sqrt` gives its
/// result: ~16 significant digits keyed off the argument's base-10000 weight
/// (`sweight = (weight+1)*2 - 1`, then `16 - sweight`), floored by the
/// argument's own scale, capped at PG's 1000-digit ceiling then SPG's `u8`.
/// Differential-verified: `sqrt(2)` → 15 fractional digits, `sqrt(1e38)` → 0.
pub(crate) fn sqrt_display_scale_big(arg: &spg_storage::bignum::BigNumeric) -> u16 {
    let (m, s) = mantissa_and_scale_big(arg);
    let (weight, _lead) = weight_firstdigit_core(&m, s);
    let sweight = (weight + 1) * 2 - 1;
    let scale = (16 - sweight).max(i32::from(s)).max(0).min(1000);
    // v7.39 (round 271) — PG's own ceiling is 1000; the 255 was SPG's
    // u8 scale, which clipped a legitimate display scale.
    scale as u16
}

/// Shared tail of `division_display_scale[_big]`: given each operand's
/// base-10000 `(weight, firstdigit)` and the dividend's scale, produce the
/// display scale PG's `/` yields (~16 significant digits, floored by the
/// dividend's own scale, capped at PG's 1000-digit ceiling then SPG's `u8`).
fn division_display_scale_from_wf(
    (dividend_group, dividend_lead): (i32, i32),
    dividend_scale: u16,
    (divisor_group, divisor_lead): (i32, i32),
) -> u16 {
    // Quotient magnitude ≈ dividend's leading group minus divisor's. When
    // the leading digits tie, the quotient can land a group lower, so drop
    // one group rather than risk under-scaling the result.
    let mut quotient_group = dividend_group - divisor_group;
    if dividend_lead <= divisor_lead {
        quotient_group -= 1;
    }
    // 16 significant digits at 4 per group: more fractional digits when the
    // quotient is small, fewer when it is large. Never below the dividend's
    // own scale or 0, never above PG's 1000-digit display ceiling, then
    // clamped to SPG's `u8` scale field.
    let scale = (16 - quotient_group * 4)
        .max(i32::from(dividend_scale))
        .max(0)
        .min(1000);
    // v7.39 (round 271) — PG's own ceiling is 1000; the 255 was SPG's
    // u8 scale, which clipped a legitimate display scale.
    scale as u16
}

/// The unsigned unscaled mantissa (decimal digits, no leading zeros except
/// "0") and scale of a `BigNumeric`, for the weight logic. Derived from the
/// rendered decimal so it works regardless of limb layout.
fn mantissa_and_scale_big(b: &spg_storage::bignum::BigNumeric) -> (alloc::string::String, u16) {
    use alloc::string::{String, ToString};
    let s = b.to_decimal_str();
    let s = s.strip_prefix('-').unwrap_or(&s);
    let digits: String = s.chars().filter(|c| *c != '.').collect();
    let trimmed = digits.trim_start_matches('0');
    let m = if trimmed.is_empty() {
        "0".to_string()
    } else {
        trimmed.to_string()
    };
    (m, b.scale())
}

/// Base-10000 weight + leading digit of `|scaled / 10^scale|`, matching
/// how PG normalizes a `NumericVar` (digits grouped in 4s anchored on
/// the decimal point). Returns `(weight, first_digit)` where `weight`
/// is in units of 10000 and `first_digit` is the most-significant
/// non-zero base-10000 digit. Zero → `(0, 0)`.
fn base10000_weight_firstdigit(scaled: i128, scale: u16) -> (i32, i32) {
    let a = scaled.unsigned_abs();
    if a == 0 {
        return (0, 0);
    }
    weight_firstdigit_core(&alloc::string::ToString::to_string(&a), scale)
}

/// Base-10000 weight + leading digit computed from an unscaled unsigned
/// mantissa digit string (no leading zeros except "0") and its scale. Shared
/// by the i128 and BigNumeric division-scale paths.
fn weight_firstdigit_core(s: &str, scale: u16) -> (i32, i32) {
    if s == "0" {
        return (0, 0);
    }
    let ndigits = s.len() as i32;
    let scale = i32::from(scale);
    let int_digits = ndigits - scale;
    if int_digits > 0 {
        // Integer part present: the most-significant group sits at
        // weight floor((int_digits - 1) / 4); its width is the leftover
        // 1..=4 leading decimal digits.
        let weight = (int_digits - 1) / 4;
        let top_len = (int_digits - weight * 4) as usize;
        let firstdigit: i32 = s[..top_len].parse().unwrap_or(0);
        (weight, firstdigit)
    } else {
        // |value| < 1: count leading fractional zeros, group by 4 from
        // the decimal point; the first non-zero group's index g gives
        // weight = -(g + 1).
        let lead_zeros = (-int_digits) as usize;
        let g = (lead_zeros as i32) / 4;
        let weight = -(g + 1);
        let mut frac = alloc::string::String::with_capacity(lead_zeros + s.len());
        for _ in 0..lead_zeros {
            frac.push('0');
        }
        frac.push_str(s);
        let start = (4 * g) as usize;
        let mut group: alloc::string::String = frac[start..].chars().take(4).collect();
        while group.len() < 4 {
            group.push('0');
        }
        let firstdigit: i32 = group.parse().unwrap_or(0);
        (weight, firstdigit)
    }
}

/// Divide `num / den` (den > 0) rounding half away from zero, matching
/// PG's `round_var`.
fn div_round_half_away(num: i128, den: i128) -> i128 {
    let q = num / den;
    let r = num % den;
    if r.unsigned_abs() * 2 >= den.unsigned_abs() {
        if num >= 0 { q + 1 } else { q - 1 }
    } else {
        q
    }
}

/// `10^p` as i128, saturating at `i128::MAX` instead of panicking on
/// overflow (guards the avg-scale multiply for pathological scales).
fn pow10_sat(p: u16) -> i128 {
    let mut acc: i128 = 1;
    for _ in 0..p {
        match acc.checked_mul(10) {
            Some(v) => acc = v,
            None => return i128::MAX,
        }
    }
    acc
}

/// v7.39 (round 271) — saturating, not panicking. With `scale` widened
/// to u16 a caller can now hand this a power well past the i128 range;
/// it used to overflow and abort the query. Saturating matches the
/// sibling `pow10_sat` and is a no-op for every power that fits.
const fn pow10_i128_const(p: u16) -> i128 {
    let mut acc: i128 = 1;
    let mut i = 0;
    while i < p {
        match acc.checked_mul(10) {
            Some(v) => acc = v,
            None => return i128::MAX,
        }
        i += 1;
    }
    acc
}

fn pow10_i128(p: u16) -> i128 {
    pow10_i128_const(p)
}

/// `10^p`, or None once it leaves the i128 range.
const fn pow10_i128_checked(p: u16) -> Option<i128> {
    let mut acc: i128 = 1;
    let mut i = 0;
    while i < p {
        match acc.checked_mul(10) {
            Some(v) => acc = v,
            None => return None,
        }
        i += 1;
    }
    Some(acc)
}