Skip to main content

fp_types/
lib.rs

1#![forbid(unsafe_code)]
2#![warn(rustdoc::broken_intra_doc_links)]
3
4//! Foundational value-type abstractions for **frankenpandas** — the
5//! enums, structs, and free functions that every other crate
6//! (fp-columnar, fp-index, fp-frame, fp-io, ...) consumes when
7//! representing scalar data, dtypes, missing values, and time deltas.
8//!
9//! The types here intentionally stay tiny and dependency-light
10//! (`serde`, `thiserror`) so they can sit at the bottom of the
11//! workspace dep graph.
12//!
13//! ## Core value types
14//!
15//! - [`DType`]: the dtype enum — `Null`, `Bool`, `Int64`, `Float64`,
16//!   `Utf8`, `Categorical`, `Timedelta64`, `Datetime64`, `Period`,
17//!   `Interval`, `Sparse`. Drives column / series storage decisions
18//!   across the workspace.
19//! - [`Scalar`]: the per-cell value enum, parameterized by `DType`.
20//!   Each variant holds the actual data (`Int64(i64)`, `Float64(f64)`,
21//!   `Utf8(String)`, ...) plus the `Null(NullKind)` variant for
22//!   missing values.
23//! - [`NullKind`]: distinguishes the three pandas missing-value
24//!   "flavors" — `Null` (Python `None` / SQL NULL), `NaN`
25//!   (floating-point not-a-number), `NaT` (timedelta / datetime
26//!   not-a-time). `Scalar::Null(...)` carries the kind so downstream
27//!   code can preserve pandas semantics.
28//! - [`SparseDType`]: descriptor for sparse-encoded dtypes (paired
29//!   value dtype + fill value).
30//!
31//! ## Time / duration types
32//!
33//! - [`Timedelta`]: nanosecond-precision duration with arithmetic
34//!   helpers ([`Timedelta::add`], [`Timedelta::sub`],
35//!   [`Timedelta::mul_scalar`], [`Timedelta::div_scalar`],
36//!   [`Timedelta::div_timedelta`]) that propagate `NaT` per pandas
37//!   semantics. [`TimedeltaComponents`] breaks a timedelta into
38//!   days/hours/minutes/seconds/nanos for display.
39//! - [`Timestamp`]: nanosecond-precision wall-clock timestamp with
40//!   optional timezone. Includes floor / ceil / round helpers and
41//!   `NaT` propagation.
42//!
43//! ## Dtype inference + casting
44//!
45//! - [`infer_dtype`]: derive a [`DType`] from a slice of scalars
46//!   (used during DataFrame construction).
47//! - [`common_dtype`]: pandas-style dtype promotion for binary ops.
48//! - [`cast_scalar`] / [`cast_scalar_owned`]: convert a scalar to a
49//!   target dtype with explicit error reporting on impossible casts.
50//!
51//! ## Missing-value helpers
52//!
53//! Free fns matching `pd.isna` / `pd.notna`, plus fill/drop helpers, plus
54//! the `nan*` aggregations ([`nansum`], [`nanmean`], [`nancount`],
55//! [`nanmin`], [`nanmax`], [`nanmedian`], [`nanvar`], [`nanstd`])
56//! that mirror pandas' missing-aware reductions.
57//!
58//! ⚠️ Only HALF that list is a module-level pandas surface. `pd.isna` and
59//! `pd.notna` are free functions; `pd.fillna` and `pd.dropna` do NOT exist
60//! (measured 2.2.3: `AttributeError` on the module) -- pandas exposes fill
61//! and drop only as METHODS, `Series.fillna` / `DataFrame.dropna`. The free
62//! fns here are an FP convenience, not a pandas mirror.
63//!
64//! ## Error reporting
65//!
66//! Errors are explicit enums via `thiserror`: [`TypeError`] for
67//! dtype-related failures (incompatible-cast, no-common-dtype) and
68//! [`TimedeltaError`] for parse failures.
69
70use serde::{Deserialize, Serialize};
71use thiserror::Error;
72
73#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
74#[serde(rename_all = "snake_case")]
75pub enum DType {
76    Null,
77    Bool,
78    /// Nullable boolean extension dtype. Matches pandas `BooleanDtype()`.
79    #[serde(rename = "boolean")]
80    BoolNullable,
81    Int64,
82    /// Nullable Int64 extension dtype. Matches pandas `Int64Dtype()` / `pd.NA`.
83    #[serde(rename = "Int64")]
84    Int64Nullable,
85    Float64,
86    /// Nullable Float64 extension dtype. Matches pandas `Float64Dtype()` / `pd.NA`.
87    ///
88    /// Distinct from [`DType::Float64`] the way `Int64Nullable` is distinct from
89    /// `Int64`: same 8-byte payload, different missing value. MEASURED, live
90    /// pandas 2.2.3 — a Float64 lane stores `pd.NA`, and it does so even when
91    /// the input was an explicit NaN:
92    ///
93    /// ```text
94    ///   pd.Series([1.5, None], dtype="Float64")[1]      -> <NA>   (is pd.NA)
95    ///   pd.Series([float("nan")], dtype="Float64")[0]   -> <NA>   COERCED
96    ///   pd.Series([1.5, None])[1]                       -> nan    (numpy)
97    /// ```
98    ///
99    /// which is why [`Scalar::missing_for_dtype`] gives this dtype
100    /// `NullKind::Null` and gives `Float64` `NullKind::NaN`.
101    ///
102    /// The serde spelling is pandas' spelling: `float64` is the numpy dtype and
103    /// `Float64` is the extension dtype, so this rename does NOT collide with
104    /// `Float64` — the enum is `rename_all = "snake_case"`, exactly as
105    /// `Int64Nullable`/`Int64` already are. (br-frankenpandas-qkqfb)
106    #[serde(rename = "Float64")]
107    Float64Nullable,
108    #[serde(alias = "string", alias = "str")]
109    Utf8,
110    Categorical,
111    Timedelta64,
112    /// Nanosecond-precision datetime since Unix epoch.
113    ///
114    /// A timezone is metadata shared by the whole column; values remain UTC
115    /// nanoseconds in the contiguous datetime buffer.
116    Datetime64 {
117        #[serde(default, skip_serializing_if = "Option::is_none")]
118        tz: Option<String>,
119    },
120    /// Period ordinal. Matches pandas `period[freq]`. Stores ordinal + frequency code.
121    Period,
122    /// Numeric interval value. Matches pandas `interval[float64]`.
123    Interval,
124    Sparse,
125}
126
127impl DType {
128    /// Returns true if the dtype is numeric (integer or floating point).
129    #[must_use]
130    pub const fn is_numeric(&self) -> bool {
131        matches!(
132            self,
133            Self::Int64 | Self::Int64Nullable | Self::Float64 | Self::Float64Nullable
134        )
135    }
136
137    /// Returns true if the dtype is an integer type.
138    #[must_use]
139    pub const fn is_integer(&self) -> bool {
140        matches!(self, Self::Int64 | Self::Int64Nullable)
141    }
142
143    /// Returns true if the dtype is a floating point type.
144    #[must_use]
145    pub const fn is_floating(&self) -> bool {
146        matches!(self, Self::Float64 | Self::Float64Nullable)
147    }
148
149    /// Returns true if the dtype is boolean.
150    #[must_use]
151    pub const fn is_bool(&self) -> bool {
152        matches!(self, Self::Bool | Self::BoolNullable)
153    }
154
155    /// Returns true if the dtype is object/string type.
156    #[must_use]
157    pub const fn is_object(&self) -> bool {
158        matches!(self, Self::Utf8)
159    }
160
161    /// Returns true if the dtype is datetime.
162    #[must_use]
163    pub const fn is_datetime(&self) -> bool {
164        matches!(self, Self::Datetime64 { .. })
165    }
166
167    /// Returns true if the dtype is timedelta.
168    #[must_use]
169    pub const fn is_timedelta(&self) -> bool {
170        matches!(self, Self::Timedelta64)
171    }
172
173    /// Returns true if the dtype is categorical.
174    #[must_use]
175    pub const fn is_categorical(&self) -> bool {
176        matches!(self, Self::Categorical)
177    }
178
179    /// Returns true if the dtype is sparse.
180    #[must_use]
181    pub const fn is_sparse(&self) -> bool {
182        matches!(self, Self::Sparse)
183    }
184
185    /// Returns true if the dtype is period.
186    #[must_use]
187    pub const fn is_period(&self) -> bool {
188        matches!(self, Self::Period)
189    }
190
191    /// Returns true if the dtype is interval.
192    #[must_use]
193    pub const fn is_interval(&self) -> bool {
194        matches!(self, Self::Interval)
195    }
196
197    /// Return the dtype name as a string.
198    ///
199    /// Matches numpy dtype.name property.
200    #[must_use]
201    pub const fn name(&self) -> &'static str {
202        match self {
203            Self::Bool => "bool",
204            Self::BoolNullable => "boolean",
205            Self::Int64 => "int64",
206            Self::Int64Nullable => "Int64",
207            Self::Float64 => "float64",
208            // MEASURED: str(pd.Float64Dtype()) == "Float64", the same
209            // capital-letter convention as Int64/boolean.
210            Self::Float64Nullable => "Float64",
211            Self::Utf8 => "object",
212            Self::Datetime64 { .. } => "datetime64[ns]",
213            Self::Timedelta64 => "timedelta64[ns]",
214            Self::Categorical => "category",
215            Self::Period => "period",
216            Self::Interval => "interval",
217            Self::Sparse => "Sparse",
218            Self::Null => "object",
219        }
220    }
221
222    /// Return the dtype kind character.
223    ///
224    /// Matches numpy dtype.kind property.
225    #[must_use]
226    pub const fn kind(&self) -> char {
227        match self {
228            Self::Bool | Self::BoolNullable => 'b',
229            Self::Int64 | Self::Int64Nullable => 'i',
230            // MEASURED: pd.Float64Dtype().kind == 'f', matching numpy float64 —
231            // the extension dtype reports its underlying kind, exactly as
232            // Int64Nullable reports 'i'.
233            Self::Float64 | Self::Float64Nullable => 'f',
234            Self::Utf8 => 'O',
235            Self::Datetime64 { .. } => 'M',
236            Self::Timedelta64 => 'm',
237            Self::Categorical => 'O',
238            Self::Period => 'O',
239            Self::Interval => 'O',
240            Self::Sparse => 'O',
241            Self::Null => 'O',
242        }
243    }
244
245    /// Return the dtype itemsize in bytes.
246    ///
247    /// Matches numpy dtype.itemsize property.
248    #[must_use]
249    pub const fn itemsize(&self) -> usize {
250        match self {
251            Self::Bool | Self::BoolNullable => 1,
252            Self::Int64
253            | Self::Int64Nullable
254            | Self::Float64
255            | Self::Float64Nullable
256            | Self::Datetime64 { .. }
257            | Self::Timedelta64
258            | Self::Period => 8,
259            Self::Utf8 | Self::Categorical | Self::Interval | Self::Sparse | Self::Null => 8,
260        }
261    }
262
263    /// Returns true if this is an extension dtype (categorical, sparse, period, interval, nullable).
264    ///
265    /// Matches `pd.api.types.is_extension_array_dtype()`.
266    #[must_use]
267    pub const fn is_extension(&self) -> bool {
268        matches!(
269            self,
270            Self::Categorical
271                | Self::Sparse
272                | Self::Period
273                | Self::Interval
274                | Self::Int64Nullable
275                | Self::Float64Nullable
276                | Self::BoolNullable
277        )
278    }
279
280    /// Returns true if this is a nullable extension dtype (Int64, boolean).
281    ///
282    /// Nullable extension dtypes preserve their dtype when nulls are introduced,
283    /// unlike numpy dtypes which promote to float64.
284    #[must_use]
285    pub const fn is_nullable(&self) -> bool {
286        matches!(
287            self,
288            Self::Int64Nullable | Self::Float64Nullable | Self::BoolNullable
289        )
290    }
291
292    /// Returns the non-nullable equivalent dtype.
293    ///
294    /// For nullable extension dtypes, returns the numpy equivalent.
295    /// For non-nullable dtypes, returns self.
296    #[must_use]
297    pub fn to_non_nullable(&self) -> Self {
298        match self {
299            Self::Int64Nullable => Self::Int64,
300            Self::Float64Nullable => Self::Float64,
301            Self::BoolNullable => Self::Bool,
302            other => other.clone(),
303        }
304    }
305
306    /// Returns the nullable equivalent dtype.
307    ///
308    /// For numpy int64/bool, returns the nullable extension dtype.
309    /// For already-nullable or other dtypes, returns self.
310    #[must_use]
311    pub fn to_nullable(&self) -> Self {
312        match self {
313            Self::Int64 => Self::Int64Nullable,
314            Self::Float64 => Self::Float64Nullable,
315            Self::Bool => Self::BoolNullable,
316            other => other.clone(),
317        }
318    }
319
320    /// Returns true if this is a signed integer type.
321    ///
322    /// Matches `pd.api.types.is_signed_integer_dtype()`.
323    #[must_use]
324    pub const fn is_signed_integer(&self) -> bool {
325        matches!(self, Self::Int64 | Self::Int64Nullable)
326    }
327
328    /// Returns true for the Utf8 dtype.
329    ///
330    /// ⚠️ NARROWER THAN `pd.api.types.is_string_dtype()`, which the old wording
331    /// ("string/object dtype") papered over. MEASURED, live pandas 2.2.3
332    /// (CrimsonPine 2026-08-19):
333    /// ```text
334    ///   Series(['a','b'])                        object    is_string_dtype TRUE
335    ///   Series([1,2], dtype=object)              object    is_string_dtype FALSE
336    ///   Series(Categorical(['a','b']))           category  is_string_dtype TRUE
337    ///   Series(['a','b'], dtype='string')        string    is_string_dtype TRUE
338    ///   Series([1,2])                            int64     is_string_dtype FALSE
339    /// ```
340    /// So pandas is NOT testing "object dtype": an object column holding ints is
341    /// FALSE, and a CATEGORICAL column is TRUE. This returns true only for `Utf8`,
342    /// which means it disagrees with pandas on a categorical-of-strings.
343    ///
344    /// Left as-is rather than widened: making this true for `Categorical`
345    /// unconditionally would be wrong for a categorical of non-strings, and this
346    /// enum carries no element type for its categories to test.
347    #[must_use]
348    pub const fn is_string_dtype(&self) -> bool {
349        matches!(self, Self::Utf8)
350    }
351
352    /// Returns true for any real numeric dtype (integer or float).
353    ///
354    /// Matches `pd.api.types.is_any_real_numeric_dtype()`.
355    #[must_use]
356    pub const fn is_any_real_numeric(&self) -> bool {
357        self.is_numeric()
358    }
359
360    /// Returns true for datetime-like dtypes (datetime, timedelta, period).
361    ///
362    /// Matches `pd.api.types.is_datetime64_any_dtype()` family.
363    #[must_use]
364    pub const fn is_datetime_like(&self) -> bool {
365        matches!(
366            self,
367            Self::Datetime64 { .. } | Self::Timedelta64 | Self::Period
368        )
369    }
370
371    /// Return the numpy dtype character code.
372    ///
373    /// Matches numpy dtype.char property.
374    #[must_use]
375    pub const fn char(&self) -> char {
376        match self {
377            Self::Bool | Self::BoolNullable => '?',
378            Self::Int64 | Self::Int64Nullable => 'l',
379            Self::Float64 | Self::Float64Nullable => 'd',
380            Self::Utf8 => 'O',
381            Self::Datetime64 { .. } => 'M',
382            Self::Timedelta64 => 'm',
383            Self::Categorical | Self::Period | Self::Interval | Self::Sparse | Self::Null => 'O',
384        }
385    }
386
387    /// Return the numpy type number.
388    ///
389    /// Matches numpy dtype.num property.
390    #[must_use]
391    pub const fn num(&self) -> i32 {
392        match self {
393            Self::Bool | Self::BoolNullable => 0,
394            Self::Int64 | Self::Int64Nullable => 7,
395            Self::Float64 | Self::Float64Nullable => 12,
396            Self::Utf8 => 17,
397            Self::Datetime64 { .. } => 21,
398            Self::Timedelta64 => 22,
399            Self::Categorical | Self::Period | Self::Interval | Self::Sparse | Self::Null => 17,
400        }
401    }
402
403    /// Return the byte order character.
404    ///
405    /// Matches numpy dtype.byteorder property. Returns '=' (native) for all types.
406    #[must_use]
407    pub const fn byteorder(&self) -> char {
408        '='
409    }
410
411    /// Return the numpy dtype string representation.
412    ///
413    /// Matches numpy dtype.str property.
414    #[must_use]
415    pub const fn str_repr(&self) -> &'static str {
416        match self {
417            Self::Bool | Self::BoolNullable => "|b1",
418            Self::Int64 | Self::Int64Nullable => "<i8",
419            Self::Float64 | Self::Float64Nullable => "<f8",
420            Self::Utf8 => "|O8",
421            Self::Datetime64 { .. } => "<M8[ns]",
422            Self::Timedelta64 => "<m8[ns]",
423            Self::Categorical | Self::Period | Self::Interval | Self::Sparse | Self::Null => "|O8",
424        }
425    }
426
427    /// Construct pandas' timezone-naive `datetime64[ns]` dtype.
428    #[must_use]
429    pub const fn datetime64_naive() -> Self {
430        Self::Datetime64 { tz: None }
431    }
432
433    /// Construct a timezone-aware `datetime64[ns, tz]` dtype.
434    #[must_use]
435    pub fn datetime64_tz(tz: impl Into<String>) -> Self {
436        Self::Datetime64 {
437            tz: Some(tz.into()),
438        }
439    }
440
441    /// Return the column-level timezone carried by a datetime dtype.
442    #[must_use]
443    pub fn timezone(&self) -> Option<&str> {
444        match self {
445            Self::Datetime64 { tz } => tz.as_deref(),
446            _ => None,
447        }
448    }
449
450    /// Render the pandas dtype spelling, including a timezone when present.
451    #[must_use]
452    pub fn display_name(&self) -> String {
453        match self {
454            Self::Datetime64 { tz: Some(tz) } => format!("datetime64[ns, {tz}]"),
455            _ => self.name().to_owned(),
456        }
457    }
458}
459
460#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
461pub struct SparseDType {
462    pub value_dtype: DType,
463    pub fill_value: Scalar,
464}
465
466impl SparseDType {
467    /// Construct a pandas-style sparse dtype descriptor.
468    ///
469    /// This records the logical dense value dtype plus the scalar value that is
470    /// elided from storage. The concrete sparse column representation lives in
471    /// fp-columnar; this descriptor is the shared public contract.
472    pub fn new(value_dtype: DType, fill_value: Scalar) -> Result<Self, TypeError> {
473        if matches!(value_dtype, DType::Null | DType::Sparse) {
474            return Err(TypeError::InvalidSparseValueDType { dtype: value_dtype });
475        }
476
477        let fill_value = if fill_value.is_missing() {
478            Scalar::missing_for_dtype(value_dtype.clone())
479        } else {
480            cast_scalar_owned(fill_value, value_dtype.clone())?
481        };
482
483        Ok(Self {
484            value_dtype,
485            fill_value,
486        })
487    }
488
489    /// Render the pandas dtype name, `Sparse[<subtype>, <fill>]`.
490    ///
491    /// br-frankenpandas-3gxc6. [`DType::name`] can only answer `"Sparse"`: it
492    /// is a `const fn` returning `&'static str` and `DType::Sparse` carries no
493    /// payload, so the subtype and fill value — which live here — are lost by
494    /// the time a caller has a bare [`DType`]. pandas never spells the bare
495    /// form; even `pd.Series([1.5, 0.0]).astype("Sparse")` resolves to
496    /// `Sparse[float64, nan]`.
497    ///
498    /// MEASURED, live pandas 2.2.3, `str(dtype)` / `dtype.name`:
499    ///
500    /// ```text
501    ///   SparseDtype("int64",   0)     -> Sparse[int64, 0]
502    ///   SparseDtype("int64",   7)     -> Sparse[int64, 7]
503    ///   SparseDtype("float64", nan)   -> Sparse[float64, nan]
504    ///   SparseDtype("float64", 0.0)   -> Sparse[float64, 0.0]
505    ///   SparseDtype("bool",    False) -> Sparse[bool, False]
506    ///   SparseDtype(object,    nan)   -> Sparse[object, nan]
507    /// ```
508    ///
509    /// The fill is rendered by `scalar_to_string_for_astype`, which already
510    /// spells every one of those cases the way pandas does in this position:
511    /// `True`/`False` capitalised, integers bare, lowercase `nan`, and the
512    /// trailing `.0` preserved on whole floats. Deliberately reusing it rather
513    /// than writing a second float formatter — a divergence between the two
514    /// would surface as a dtype name that no longer round-trips.
515    #[must_use]
516    pub fn pandas_name(&self) -> String {
517        format!(
518            "Sparse[{}, {}]",
519            self.value_dtype.name(),
520            scalar_to_string_for_astype(self.fill_value.clone())
521        )
522    }
523}
524
525#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
526#[serde(rename_all = "snake_case")]
527pub enum NullKind {
528    Null,
529    NaN,
530    NaT,
531}
532
533#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
534#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
535pub enum Scalar {
536    Null(NullKind),
537    Bool(bool),
538    Int64(i64),
539    Float64(f64),
540    #[serde(alias = "string", alias = "str")]
541    Utf8(String),
542    Timedelta64(i64),
543    /// Nanoseconds since Unix epoch. Matches pandas `datetime64[ns]`.
544    /// Uses `Timestamp::NAT` (i64::MIN) for missing values.
545    Datetime64(i64),
546    /// Period value (ordinal + frequency). A `Period` whose `ordinal` is
547    /// `i64::MIN` is NaT (missing). The frequency is carried so writers can
548    /// render the pandas calendar string (`2024Q1`, `2024-03`, ...) — the
549    /// calendar string is not recoverable from the ordinal alone, since
550    /// different frequencies share overlapping ordinal axes.
551    Period(Period),
552    /// Numeric interval value. Missing values remain `Scalar::Null`.
553    Interval(Interval),
554}
555
556impl std::fmt::Display for Scalar {
557    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
558        match self {
559            Self::Null(NullKind::NaN) => write!(f, "NaN"),
560            Self::Null(NullKind::NaT) => write!(f, "NaT"),
561            Self::Null(NullKind::Null) => write!(f, "None"),
562            Self::Bool(b) => write!(f, "{}", if *b { "True" } else { "False" }),
563            Self::Int64(v) => write!(f, "{v}"),
564            Self::Float64(v) => write!(f, "{v}"),
565            Self::Utf8(s) => write!(f, "{s}"),
566            Self::Timedelta64(nanos) => write!(f, "{}", Timedelta::format(*nanos)),
567            Self::Datetime64(nanos) => {
568                if *nanos == Timestamp::NAT {
569                    write!(f, "NaT")
570                } else {
571                    write!(f, "Timestamp[{nanos}]")
572                }
573            }
574            Self::Period(p) => {
575                if p.ordinal == i64::MIN {
576                    write!(f, "NaT")
577                } else {
578                    write!(f, "{}", p.calendar_string())
579                }
580            }
581            Self::Interval(interval) => write!(f, "{interval}"),
582        }
583    }
584}
585
586// Ergonomic From impls (br-frankenpandas-esjjy / fd90.182). Mirrors
587// IndexLabel's From<i64>/From<&str>/From<String> so users can write
588//   let v: Vec<Scalar> = vec![1i64.into(), 2.0.into(), "three".into()];
589// instead of the explicit Scalar::Int64(...)/Scalar::Float64(...) form.
590//
591// i64 maps to Int64 (more common than Timedelta64 in pandas-style code).
592// Users wanting Timedelta64 should construct it explicitly with
593// Scalar::Timedelta64(nanos) or via Timedelta::parse / to_timedelta.
594
595impl From<bool> for Scalar {
596    fn from(value: bool) -> Self {
597        Self::Bool(value)
598    }
599}
600
601impl From<i64> for Scalar {
602    fn from(value: i64) -> Self {
603        Self::Int64(value)
604    }
605}
606
607impl From<f64> for Scalar {
608    fn from(value: f64) -> Self {
609        Self::Float64(value)
610    }
611}
612
613impl From<&str> for Scalar {
614    fn from(value: &str) -> Self {
615        Self::Utf8(value.to_owned())
616    }
617}
618
619impl From<String> for Scalar {
620    fn from(value: String) -> Self {
621        Self::Utf8(value)
622    }
623}
624
625impl Scalar {
626    #[inline]
627    const fn debug_variant_name(&self) -> &'static str {
628        match self {
629            Self::Null(_) => "Null",
630            Self::Bool(_) => "Bool",
631            Self::Int64(_) => "Int64",
632            Self::Float64(_) => "Float64",
633            Self::Utf8(_) => "Utf8",
634            Self::Timedelta64(_) => "Timedelta64",
635            Self::Datetime64(_) => "Datetime64",
636            Self::Period(_) => "Period",
637            Self::Interval(_) => "Interval",
638        }
639    }
640
641    #[must_use]
642    pub fn dtype(&self) -> DType {
643        match self {
644            Self::Null(_) => DType::Null,
645            Self::Bool(_) => DType::Bool,
646            Self::Int64(_) => DType::Int64,
647            Self::Float64(_) => DType::Float64,
648            Self::Utf8(_) => DType::Utf8,
649            Self::Timedelta64(_) => DType::Timedelta64,
650            Self::Datetime64(_) => DType::datetime64_naive(),
651            Self::Period(_) => DType::Period,
652            Self::Interval(_) => DType::Interval,
653        }
654    }
655
656    #[must_use]
657    pub fn is_missing(&self) -> bool {
658        match self {
659            Self::Null(_) => true,
660            Self::Float64(v) => v.is_nan(),
661            Self::Timedelta64(v) => *v == Timedelta::NAT,
662            Self::Datetime64(v) => *v == Timestamp::NAT,
663            Self::Period(p) => p.ordinal == i64::MIN,
664            _ => false,
665        }
666    }
667
668    #[must_use]
669    pub fn is_nan(&self) -> bool {
670        matches!(self, Self::Null(NullKind::NaN)) || matches!(self, Self::Float64(v) if v.is_nan())
671    }
672
673    /// Returns true if this is a Bool scalar.
674    #[must_use]
675    pub const fn is_bool(&self) -> bool {
676        matches!(self, Self::Bool(_))
677    }
678
679    /// Returns true if this is an Int64 scalar.
680    #[must_use]
681    pub const fn is_integer(&self) -> bool {
682        matches!(self, Self::Int64(_))
683    }
684
685    /// Returns true if this is a Float64 scalar.
686    #[must_use]
687    pub const fn is_float(&self) -> bool {
688        matches!(self, Self::Float64(_))
689    }
690
691    /// Returns true if this is a numeric scalar (Int64 or Float64).
692    #[must_use]
693    pub const fn is_numeric(&self) -> bool {
694        matches!(self, Self::Int64(_) | Self::Float64(_))
695    }
696
697    /// Returns true if this is a Utf8 (string) scalar.
698    #[must_use]
699    pub const fn is_string(&self) -> bool {
700        matches!(self, Self::Utf8(_))
701    }
702
703    /// Returns true if this is a Datetime64 scalar.
704    #[must_use]
705    pub const fn is_datetime(&self) -> bool {
706        matches!(self, Self::Datetime64(_))
707    }
708
709    /// Returns true if this is a Timedelta64 scalar.
710    #[must_use]
711    pub const fn is_timedelta(&self) -> bool {
712        matches!(self, Self::Timedelta64(_))
713    }
714
715    /// Returns true if this is a Period scalar.
716    #[must_use]
717    pub const fn is_period(&self) -> bool {
718        matches!(self, Self::Period(_))
719    }
720
721    /// Returns true if this is an Interval scalar.
722    #[must_use]
723    pub const fn is_interval(&self) -> bool {
724        matches!(self, Self::Interval(_))
725    }
726
727    #[must_use]
728    pub fn missing_for_dtype(dtype: DType) -> Self {
729        match dtype {
730            DType::Float64 => Self::Null(NullKind::NaN),
731            // NOT NaN, and this is the whole reason the dtype exists. MEASURED,
732            // live pandas 2.2.3: a Float64 lane stores pd.NA, and it coerces an
733            // explicit NaN INPUT to pd.NA —
734            //     pd.Series([float("nan")], dtype="Float64")[0]  ->  <NA>
735            // whereas the numpy lane above keeps a real NaN. Giving this dtype
736            // NullKind::NaN would make the two flavours indistinguishable, which
737            // is exactly the gap br-frankenpandas-qkqfb was filed for.
738            DType::Float64Nullable => Self::Null(NullKind::Null),
739            DType::Timedelta64 => Self::Timedelta64(Timedelta::NAT),
740            DType::Datetime64 { .. } => Self::Datetime64(Timestamp::NAT),
741            DType::Period => Self::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
742            DType::Null => Self::Null(NullKind::Null),
743            DType::Bool
744            | DType::BoolNullable
745            | DType::Int64
746            | DType::Int64Nullable
747            | DType::Utf8
748            | DType::Categorical
749            | DType::Interval
750            | DType::Sparse => Self::Null(NullKind::Null),
751        }
752    }
753
754    #[must_use]
755    pub fn semantic_eq(&self, other: &Self) -> bool {
756        match (self, other) {
757            (Self::Float64(a), Self::Float64(b)) => {
758                if a.is_nan() && b.is_nan() {
759                    return true;
760                }
761                if *a == *b {
762                    return true;
763                }
764                let diff = (*a - *b).abs();
765                let max_abs = a.abs().max(b.abs());
766                if max_abs == 0.0 {
767                    diff < f64::EPSILON
768                } else {
769                    diff / max_abs < 1e-14
770                }
771            }
772            (Self::Null(_), Self::Float64(v)) | (Self::Float64(v), Self::Null(_)) => v.is_nan(),
773            // All Null kinds (Null / NaN / NaT) mark missingness; they are
774            // semantically indistinguishable for oracle-parity checks even
775            // though derived PartialEq would reject a cross-kind pair.
776            // fp-frame normalizes Float64 column missing cells to
777            // Null(NaN) at Column::new time, while fixture oracles encode
778            // the canonical missing marker as Null(Null).
779            (Self::Null(_), Self::Null(_)) => true,
780            // The DTYPE-SENTINEL missings are missing too, and this function
781            // already says so for every other flavour. `missing_for_dtype`
782            // DEFINES the canonical missing for Timedelta64 as
783            // `Timedelta64(Timedelta::NAT)`, for Datetime64 as
784            // `Datetime64(Timestamp::NAT)` and for Period as ordinal
785            // `i64::MIN`, and `is_missing()` returns true for all three — but
786            // without this arm none of them could ever equal the `Null` marker
787            // an oracle records for pandas' NaT, so a parity check compared a
788            // raw i64::MIN bit pattern against a null and called it a value
789            // mismatch.
790            //
791            // OBSERVED on fp_p2d_021_series_to_timedelta_negative_null_hardened:
792            //   FP     timedelta64:-9223372036854775808
793            //   pandas null           (the format has no `na_t` marker, so
794            //                          `null` IS NaT there)
795            //
796            // `compare_join_expected` in fp-conformance already carried this as
797            // a manual `|| (left.is_missing() && right.is_missing())`; putting
798            // it here makes that clause redundant instead of special, and
799            // covers the series and dataframe comparators that lacked it.
800            //
801            // This is a COMPARISON rule only. It deliberately does not touch
802            // `missing_for_dtype`: fp-columnar's 2026-07-14 NullKind TRAP note
803            // records that the sentinel and `Null(NaT)` representations coexist
804            // inside one column and a uniform gather cannot reproduce the mix,
805            // which is a storage-model question. (br-frankenpandas-xwxci)
806            _ if self.is_missing() && other.is_missing() => true,
807            _ => self == other,
808        }
809    }
810
811    #[must_use]
812    pub fn semantic_le(&self, other: &Self) -> bool {
813        match self.semantic_cmp(other) {
814            std::cmp::Ordering::Less | std::cmp::Ordering::Equal => true,
815            std::cmp::Ordering::Greater => false,
816        }
817    }
818
819    #[must_use]
820    pub fn semantic_ge(&self, other: &Self) -> bool {
821        match self.semantic_cmp(other) {
822            std::cmp::Ordering::Greater | std::cmp::Ordering::Equal => true,
823            std::cmp::Ordering::Less => false,
824        }
825    }
826
827    #[must_use]
828    pub fn is_null(&self) -> bool {
829        matches!(self, Self::Null(_))
830    }
831
832    #[must_use]
833    pub fn is_na(&self) -> bool {
834        self.is_missing()
835    }
836
837    #[must_use]
838    pub fn coalesce(&self, other: &Self) -> Self {
839        if self.is_missing() {
840            other.clone()
841        } else {
842            self.clone()
843        }
844    }
845
846    #[must_use]
847    pub fn semantic_cmp(&self, other: &Self) -> std::cmp::Ordering {
848        match (self, other) {
849            (Self::Int64(a), Self::Int64(b)) => a.cmp(b),
850            (Self::Float64(a), Self::Float64(b)) => {
851                a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)
852            }
853            (Self::Utf8(a), Self::Utf8(b)) => a.cmp(b),
854            (Self::Bool(a), Self::Bool(b)) => a.cmp(b),
855            (Self::Null(a), Self::Null(b)) => a.cmp(b),
856            (Self::Timedelta64(a), Self::Timedelta64(b)) => {
857                if *a == Timedelta::NAT || *b == Timedelta::NAT {
858                    std::cmp::Ordering::Equal
859                } else {
860                    a.cmp(b)
861                }
862            }
863            (Self::Datetime64(a), Self::Datetime64(b)) => {
864                if *a == Timestamp::NAT || *b == Timestamp::NAT {
865                    std::cmp::Ordering::Equal
866                } else {
867                    a.cmp(b)
868                }
869            }
870            (Self::Period(a), Self::Period(b)) => {
871                if a.ordinal == i64::MIN || b.ordinal == i64::MIN {
872                    std::cmp::Ordering::Equal
873                } else {
874                    a.ordinal.cmp(&b.ordinal)
875                }
876            }
877            (Self::Interval(a), Self::Interval(b)) => a
878                .left
879                .partial_cmp(&b.left)
880                .unwrap_or(std::cmp::Ordering::Equal)
881                .then_with(|| {
882                    a.right
883                        .partial_cmp(&b.right)
884                        .unwrap_or(std::cmp::Ordering::Equal)
885                })
886                .then_with(|| a.closed.cmp(&b.closed)),
887            // Cross-numeric comparison
888            (Self::Int64(a), Self::Float64(b)) => (*a as f64)
889                .partial_cmp(b)
890                .unwrap_or(std::cmp::Ordering::Equal),
891            (Self::Float64(a), Self::Int64(b)) => a
892                .partial_cmp(&(*b as f64))
893                .unwrap_or(std::cmp::Ordering::Equal),
894            // Derived Debug starts every variant with its static variant name.
895            // Different variants therefore order by that name before either
896            // payload is observed; compare those names without allocating.
897            (a, b) => a.debug_variant_name().cmp(b.debug_variant_name()),
898        }
899    }
900
901    pub fn to_f64(&self) -> Result<f64, TypeError> {
902        match self {
903            Self::Bool(v) => Ok(if *v { 1.0 } else { 0.0 }),
904            Self::Int64(v) => Ok(*v as f64),
905            Self::Float64(v) => Ok(*v),
906            Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
907            Self::Utf8(v) => Err(TypeError::NonNumericValue {
908                value: v.clone(),
909                dtype: DType::Utf8,
910            }),
911            Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
912                kind: NullKind::NaT,
913            }),
914            Self::Timedelta64(v) => Err(TypeError::NonNumericValue {
915                value: Timedelta::format(*v),
916                dtype: DType::Timedelta64,
917            }),
918            Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
919                kind: NullKind::NaT,
920            }),
921            Self::Datetime64(v) => Err(TypeError::NonNumericValue {
922                value: format!("Timestamp[{v}]"),
923                dtype: DType::datetime64_naive(),
924            }),
925            Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
926                kind: NullKind::NaT,
927            }),
928            Self::Period(p) => Err(TypeError::NonNumericValue {
929                value: p.calendar_string(),
930                dtype: DType::Period,
931            }),
932            Self::Interval(v) => Err(TypeError::NonNumericValue {
933                value: v.to_string(),
934                dtype: DType::Interval,
935            }),
936        }
937    }
938
939    /// Try to convert to i64. Returns error for missing or non-numeric values.
940    pub fn to_i64(&self) -> Result<i64, TypeError> {
941        match self {
942            Self::Bool(v) => Ok(if *v { 1 } else { 0 }),
943            Self::Int64(v) => Ok(*v),
944            Self::Float64(v) => Ok(*v as i64),
945            Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
946            Self::Utf8(v) => Err(TypeError::NonNumericValue {
947                value: v.clone(),
948                dtype: DType::Utf8,
949            }),
950            Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
951                kind: NullKind::NaT,
952            }),
953            Self::Timedelta64(v) => Ok(*v),
954            Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
955                kind: NullKind::NaT,
956            }),
957            Self::Datetime64(v) => Ok(*v),
958            Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
959                kind: NullKind::NaT,
960            }),
961            Self::Period(p) => Ok(p.ordinal),
962            Self::Interval(v) => Err(TypeError::NonNumericValue {
963                value: v.to_string(),
964                dtype: DType::Interval,
965            }),
966        }
967    }
968
969    /// Try to convert to bool. Returns error for missing values.
970    pub fn to_bool(&self) -> Result<bool, TypeError> {
971        match self {
972            Self::Bool(v) => Ok(*v),
973            Self::Int64(v) => Ok(*v != 0),
974            Self::Float64(v) => Ok(*v != 0.0 && !v.is_nan()),
975            Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
976            Self::Utf8(v) => Ok(!v.is_empty()),
977            Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
978                kind: NullKind::NaT,
979            }),
980            Self::Timedelta64(v) => Ok(*v != 0),
981            Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
982                kind: NullKind::NaT,
983            }),
984            Self::Datetime64(v) => Ok(*v != 0),
985            Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
986                kind: NullKind::NaT,
987            }),
988            Self::Period(p) => Ok(p.ordinal != 0),
989            Self::Interval(_) => Ok(true),
990        }
991    }
992
993    /// Try to convert to string representation.
994    pub fn to_str(&self) -> String {
995        match self {
996            Self::Bool(v) => if *v { "True" } else { "False" }.to_string(),
997            Self::Int64(v) => v.to_string(),
998            Self::Float64(v) => {
999                if v.is_nan() {
1000                    "nan".to_string()
1001                } else if v.is_infinite() {
1002                    if *v > 0.0 { "inf" } else { "-inf" }.to_string()
1003                } else {
1004                    v.to_string()
1005                }
1006            }
1007            Self::Null(_) => "NaN".to_string(),
1008            Self::Utf8(v) => v.clone(),
1009            Self::Timedelta64(v) => Timedelta::format(*v),
1010            Self::Datetime64(v) if *v == Timestamp::NAT => "NaT".to_string(),
1011            Self::Datetime64(v) => Timestamp::from_nanos(*v).isoformat(),
1012            Self::Period(p) if p.ordinal == i64::MIN => "NaT".to_string(),
1013            Self::Period(p) => p.calendar_string(),
1014            Self::Interval(v) => v.to_string(),
1015        }
1016    }
1017}
1018
1019#[derive(Debug, Error, Clone, PartialEq)]
1020pub enum TypeError {
1021    #[error("dtype coercion from {left:?} to {right:?} has no compatible common type")]
1022    IncompatibleDtypes { left: DType, right: DType },
1023    #[error("cannot cast scalar of dtype {from:?} to {to:?}")]
1024    InvalidCast { from: DType, to: DType },
1025    #[error("cannot cast float {value} to int64 without loss")]
1026    LossyFloatToInt { value: f64 },
1027    #[error("expected 0/1 for bool cast from int64 but found {value}")]
1028    InvalidBoolInt { value: i64 },
1029    #[error("expected 0.0/1.0 for bool cast from float64 but found {value}")]
1030    InvalidBoolFloat { value: f64 },
1031    #[error("value {value:?} has non-numeric dtype {dtype:?}")]
1032    NonNumericValue { value: String, dtype: DType },
1033    #[error("value is missing ({kind:?})")]
1034    ValueIsMissing { kind: NullKind },
1035    #[error("sparse value dtype cannot be {dtype:?}")]
1036    InvalidSparseValueDType { dtype: DType },
1037    #[error("interval_range step must be finite, positive, and not NaN (got {step})")]
1038    InvalidIntervalStep { step: f64 },
1039    #[error("interval_range step {step} does not evenly divide range end-start={span}")]
1040    IntervalStepDoesNotDivide { step: f64, span: f64 },
1041    #[error("cannot parse '{value}' as {target}")]
1042    ValueNotParseable { value: String, target: String },
1043}
1044
1045pub fn common_dtype(left: DType, right: DType) -> Result<DType, TypeError> {
1046    use DType::{
1047        Bool, BoolNullable, Categorical, Float64, Float64Nullable, Int64, Int64Nullable, Null,
1048        Sparse, Timedelta64,
1049    };
1050
1051    let out = match (&left, &right) {
1052        (a, b) if a == b => a.clone(),
1053        (Null, other) | (other, Null) => other.clone(),
1054        (Categorical, Categorical) => Categorical,
1055
1056        // Bool promotions (nullable absorbs non-nullable)
1057        (Bool, Int64) | (Int64, Bool) => Int64,
1058        (Bool, Int64Nullable) | (Int64Nullable, Bool) => Int64Nullable,
1059        (BoolNullable, Int64) | (Int64, BoolNullable) => Int64Nullable,
1060        (BoolNullable, Int64Nullable) | (Int64Nullable, BoolNullable) => Int64Nullable,
1061        (Bool, BoolNullable) | (BoolNullable, Bool) => BoolNullable,
1062        (Bool, Float64) | (Float64, Bool) => Float64,
1063        // MEASURED, live pandas 2.2.3:
1064        //     pd.Series([True,None],dtype="boolean") + pd.Series([1.5,2.5,3.5])
1065        //         -> Float64        (the EXTENSION dtype, not numpy float64)
1066        // Flipped together with the Int64Nullable arm below; see the
1067        // associativity note there for why they cannot move independently.
1068        (BoolNullable, Float64) | (Float64, BoolNullable) => Float64Nullable,
1069
1070        // Int64 promotions (nullable absorbs non-nullable)
1071        (Int64, Float64) | (Float64, Int64) => Float64,
1072        // MEASURED, live pandas 2.2.3, both spellings agree:
1073        //     find_common_type([Int64, float64])                        -> Float64
1074        //     pd.Series([1,None],dtype="Int64") + pd.Series([1.5,2.5])  -> Float64
1075        // i.e. the NULLABLE flavour wins, so the answer is Float64Nullable.
1076        //
1077        // ⚠ THIS ARM AND THE BoolNullable ARM ABOVE ARE ONE ATOMIC CHANGE. The
1078        // lattice is checked for associativity over ALL dtypes by
1079        // `common_dtype_lattice_axioms_be314`, and flipping only this arm breaks
1080        // it on (BoolNullable, Int64, Float64):
1081        //     (BN ∨ I64) ∨ F64 = Int64Nullable ∨ Float64 = Float64Nullable
1082        //     BN ∨ (I64 ∨ F64) = BN ∨ Float64            = Float64      ✗
1083        // Both arms flip, or neither does. (br-frankenpandas-qkqfb, unblocks
1084        // br-frankenpandas-f0aaa)
1085        (Int64Nullable, Float64) | (Float64, Int64Nullable) => Float64Nullable,
1086        (Int64, Int64Nullable) | (Int64Nullable, Int64) => Int64Nullable,
1087
1088        // Float64Nullable promotions. These are now REACHABLE: the two arms
1089        // above produce Float64Nullable, so anything that folds a dtype list
1090        // (melt's try_fold, combine_first's target_dtype) can feed it back in
1091        // here. They are what makes that fold associative.
1092        //
1093        // MEASURED, live pandas 2.2.3 ARITHMETIC (which is what this function
1094        // models -- see the Bool arms above, which follow arithmetic rather than
1095        // find_common_type, since find_common_type answers `object` for every
1096        // bool+numeric pair and FrankenPandas has no object dtype yet, that
1097        // being br-frankenpandas-hlcgl):
1098        //     Float64(ext) + float64(numpy)          -> Float64
1099        //     Int64(ext)   + Float64(ext)            -> Float64
1100        //     boolean(ext) + Float64(ext)            -> Float64
1101        // The nullable float absorbs every other numeric flavour, which also
1102        // makes it the top of the numeric lattice and keeps promotion
1103        // associative.
1104        (Float64Nullable, Float64) | (Float64, Float64Nullable) => Float64Nullable,
1105        (Float64Nullable, Int64) | (Int64, Float64Nullable) => Float64Nullable,
1106        (Float64Nullable, Int64Nullable) | (Int64Nullable, Float64Nullable) => Float64Nullable,
1107        (Float64Nullable, Bool) | (Bool, Float64Nullable) => Float64Nullable,
1108        (Float64Nullable, BoolNullable) | (BoolNullable, Float64Nullable) => Float64Nullable,
1109
1110        // Datetime/Timedelta
1111        (Timedelta64, Timedelta64) => Timedelta64,
1112        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
1113            if left_tz == right_tz =>
1114        {
1115            DType::Datetime64 {
1116                tz: left_tz.clone(),
1117            }
1118        }
1119
1120        (Sparse, _) | (_, Sparse) => {
1121            return Err(TypeError::IncompatibleDtypes {
1122                left: left.clone(),
1123                right: right.clone(),
1124            });
1125        }
1126        _ => {
1127            return Err(TypeError::IncompatibleDtypes { left, right });
1128        }
1129    };
1130
1131    Ok(out)
1132}
1133
1134pub fn infer_dtype(values: &[Scalar]) -> Result<DType, TypeError> {
1135    let mut current = DType::Null;
1136    let mut saw_utf8 = false;
1137    let mut saw_timedelta = false;
1138    let mut saw_datetime = false;
1139    let mut saw_non_utf8_non_null = false;
1140    // br-frankenpandas-rh1od: pandas constructs OBJECT columns whenever a
1141    // Python bool mixes with any numeric scalar ([True, 2] -> object,
1142    // measured live 2.2.3); numpy's bool<int common-type never fires at the
1143    // constructor. FrankenPandas coerced to Int64 here, which no pandas
1144    // constructor path produces. Strings already take the object bucket
1145    // below (DISC-005); bool+numeric joins them.
1146    let mut saw_bool = false;
1147    let mut saw_numeric = false;
1148
1149    // NOTE (br-frankenpandas-nywa8): inferring Float64 from a NaN-KIND missing
1150    // looks like the right central fix for pandas' int64 -> float64 promotion,
1151    // and it is NOT. `NullKind::NaN` is used throughout FrankenPandas as the
1152    // GENERIC missing marker, not specifically as "a float NaN" — e.g. short-row
1153    // padding and `missing_for_dtype(Float64)` both produce it. Promoting on it
1154    // broke 19 pre-existing fp-columnar tests (ffill returning Float64(1.0)
1155    // where Int64(1) was pinned, isin flipping a bool) because those columns are
1156    // legitimately Int64 with a generic missing. Measured, then reverted.
1157    //
1158    // The promotion has to be applied where a gap is INTRODUCED and the
1159    // introducer knows it is inventing one — see `concat_dataframes_*`, which
1160    // promotes locally. Do not move it back here without first giving
1161    // "pandas-introduced gap" a marker distinct from generic missingness.
1162    for value in values {
1163        match value.dtype() {
1164            DType::Null => {}
1165            DType::Utf8 => saw_utf8 = true,
1166            DType::Bool => {
1167                saw_bool = true;
1168                saw_non_utf8_non_null = true;
1169                current = common_dtype(current, DType::Bool)?;
1170            }
1171            DType::Int64 | DType::Float64 => {
1172                saw_numeric = true;
1173                saw_non_utf8_non_null = true;
1174                current = common_dtype(current, value.dtype())?;
1175            }
1176            DType::Timedelta64 => {
1177                saw_timedelta = true;
1178                if current == DType::Null {
1179                    current = DType::Timedelta64;
1180                } else if current != DType::Timedelta64 {
1181                    return Err(TypeError::IncompatibleDtypes {
1182                        left: current,
1183                        right: DType::Timedelta64,
1184                    });
1185                }
1186            }
1187            DType::Datetime64 { .. } => {
1188                saw_datetime = true;
1189                if current == DType::Null {
1190                    current = DType::datetime64_naive();
1191                } else if !current.is_datetime() {
1192                    return Err(TypeError::IncompatibleDtypes {
1193                        left: current,
1194                        right: DType::datetime64_naive(),
1195                    });
1196                }
1197            }
1198            other => {
1199                saw_non_utf8_non_null = true;
1200                current = common_dtype(current, other)?;
1201            }
1202        }
1203
1204        if saw_bool && saw_numeric {
1205            // Constructor inference follows pandas object-dtype behavior for
1206            // heterogeneous string/scalar payloads while arithmetic coercion
1207            // remains governed by the stricter common_dtype lattice.
1208            return Ok(DType::Utf8);
1209        }
1210        if saw_utf8 && saw_non_utf8_non_null {
1211            // Constructor inference follows pandas object-dtype behavior for
1212            // heterogeneous string/scalar payloads while arithmetic coercion
1213            // remains governed by the stricter common_dtype lattice.
1214            return Ok(DType::Utf8);
1215        }
1216        if saw_timedelta && saw_non_utf8_non_null {
1217            return Err(TypeError::IncompatibleDtypes {
1218                left: DType::Timedelta64,
1219                right: current,
1220            });
1221        }
1222        if saw_datetime && saw_non_utf8_non_null {
1223            return Err(TypeError::IncompatibleDtypes {
1224                left: DType::datetime64_naive(),
1225                right: current,
1226            });
1227        }
1228    }
1229
1230    if saw_utf8 {
1231        Ok(DType::Utf8)
1232    } else {
1233        Ok(current)
1234    }
1235}
1236
1237/// Cast a scalar to a target dtype, taking ownership to avoid redundant clones
1238/// when the value already has the correct type (AG-03: identity-cast skip).
1239pub fn cast_scalar_owned(value: Scalar, target: DType) -> Result<Scalar, TypeError> {
1240    let from = value.dtype();
1241    if from == target {
1242        return Ok(value);
1243    }
1244    // Int64 <-> Int64Nullable: same representation, just different dtype tracking
1245    if (from == DType::Int64 && target == DType::Int64Nullable)
1246        || (from == DType::Int64Nullable && target == DType::Int64)
1247    {
1248        return Ok(value);
1249    }
1250    // Bool <-> BoolNullable: same representation
1251    if (from == DType::Bool && target == DType::BoolNullable)
1252        || (from == DType::BoolNullable && target == DType::Bool)
1253    {
1254        return Ok(value);
1255    }
1256    // Float64 <-> Float64Nullable: same 8-byte payload, and a PRESENT value
1257    // round-trips unchanged in both directions. MEASURED, live pandas 2.2.3:
1258    //     pd.Series([1.5, None], dtype="Float64").astype("float64") -> [1.5, nan]
1259    //     pd.Series([1.5, None]).astype("Float64")                  -> [1.5, <NA>]
1260    // Only the MISSING marker differs, and a missing input never reaches here --
1261    // `value.is_missing()` below routes it to `missing_for_dtype(target)`, which
1262    // is what converts NaN <-> pd.NA. (br-frankenpandas-qkqfb)
1263    if (from == DType::Float64 && target == DType::Float64Nullable)
1264        || (from == DType::Float64Nullable && target == DType::Float64)
1265    {
1266        return Ok(value);
1267    }
1268    if target == DType::Utf8 {
1269        return Ok(Scalar::Utf8(scalar_to_string_for_astype(value)));
1270    }
1271    // Per br-frankenpandas-cyi4h: pandas astype(bool) (the numpy bool dtype)
1272    // treats a float NaN as truthy -> True (bool(nan) is True), unlike the
1273    // nullable 'boolean' dtype which keeps NA. FP's NaN=missing model would
1274    // otherwise fall through to the missing branch below and yield a null.
1275    // Verified vs live pandas 2.2.3.
1276    if target == DType::Bool
1277        && let Scalar::Float64(v) = &value
1278        && v.is_nan()
1279    {
1280        return Ok(Scalar::Bool(true));
1281    }
1282    // TEMPORAL -> NUMPY bool IS NONZERO-TRUTHY ON THE RAW NANOSECONDS, and it
1283    // sits here for exactly the reason the NaN check above does: FP's
1284    // missing-value model would otherwise swallow NaT below, and pandas does not
1285    // treat it as missing here.
1286    //
1287    // MEASURED, live pandas 2.2.3, `.astype('bool')` beside `.astype('int64')`
1288    // so the rule is visible as one rule rather than four cases:
1289    //
1290    //   value                                 nanos                  bool
1291    //   Timestamp(0)                              0                 False
1292    //   Timestamp('2024-03-15 10:30:45.123..')  1.71e18               True
1293    //   Timestamp('1969-12-31 23:59:59.999..')       -1               True
1294    //   NaT (either dtype)          -9223372036854775808              True
1295    //   Timedelta(0)                              0                 False
1296    //   Timedelta('1 days')          86400000000000                   True
1297    //   Timedelta('-1 ns')                       -1                   True
1298    //
1299    // So `nanos != 0` is the whole rule, and NaT needs no case of its own: it IS
1300    // i64::MIN, which is nonzero. Only the epoch and a zero duration are False.
1301    //
1302    // ⚠️ THE NULLABLE `boolean` REFUSES ALL OF THESE, including the ones whose
1303    // nanos are 0 or 1 — `.astype('boolean')` raises "Need to pass bool-like
1304    // values" for EVERY row above, so it is the dtype it rejects, not the value.
1305    // That is why this is guarded on `DType::Bool` alone and why the strict
1306    // `BoolNullable` arm below is left without a temporal case.
1307    if target == DType::Bool {
1308        match &value {
1309            Scalar::Datetime64(nanos) | Scalar::Timedelta64(nanos) => {
1310                return Ok(Scalar::Bool(*nanos != 0));
1311            }
1312            _ => {}
1313        }
1314    }
1315    // TEMPORAL -> NUMPY int64 IS RAW NANOSECONDS, and this sits ABOVE the
1316    // missing-value branch on purpose.
1317    //
1318    // MEASURED, live pandas 2.2.3:
1319    //     pd.Series([Timestamp('2024-03-15 10:30:45.123456789')]).astype('int64')
1320    //       -> 1710498645123456789
1321    //     pd.Series([Timedelta('1 days 02:03:04.005006007')]).astype('int64')
1322    //       -> 93784005006007
1323    //     pd.Series([pd.NaT], dtype='datetime64[ns]').astype('int64')
1324    //       -> -9223372036854775808        <- THE SENTINEL, not a missing value
1325    //
1326    // ⚠️ NaT IS WHY THE ORDER MATTERS. Below this point `value.is_missing()`
1327    // would turn NaT into `Null(Null)`, and pandas emphatically does not: it
1328    // hands back i64::MIN, which is the same bit pattern NaT already IS. Doing
1329    // the cast here makes the sentinel round-trip by construction rather than by
1330    // a second special case.
1331    //
1332    // ⚠️ NUMPY `int64` ONLY — the NULLABLE `Int64` REFUSES this, and so must we:
1333    //     .astype('Int64')   -> TypeError: datetime64[ns] cannot be converted
1334    //                          to IntegerDtype
1335    //     .astype('float64') -> TypeError: Cannot cast DatetimeArray to dtype
1336    //                          float64
1337    // which is why this is guarded on the exact target rather than folded into
1338    // the `Int64 | Int64Nullable` arm below, and why no Float64 arm is added.
1339    if target == DType::Int64 {
1340        match &value {
1341            Scalar::Datetime64(nanos) | Scalar::Timedelta64(nanos) => {
1342                return Ok(Scalar::Int64(*nanos));
1343            }
1344            _ => {}
1345        }
1346    }
1347    if value.is_missing() {
1348        return Ok(Scalar::missing_for_dtype(target));
1349    }
1350
1351    // Note: identity casts (from == target) are handled above, so same-type
1352    // arms are omitted from the match below.
1353    match target {
1354        DType::Null => Ok(Scalar::Null(NullKind::Null)),
1355        DType::Bool => match &value {
1356            // numpy bool: zero -> False, ANY nonzero -> True (it does not
1357            // restrict to 0/1). e.g. bool of -3 / 2.5 is True.
1358            Scalar::Int64(v) => Ok(Scalar::Bool(*v != 0)),
1359            // 0.0 and -0.0 -> False; every other value, INCLUDING NaN, -> True
1360            // (NaN != 0.0 is true), matching numpy/pandas truthiness.
1361            Scalar::Float64(v) => Ok(Scalar::Bool(*v != 0.0)),
1362            _ => Err(TypeError::InvalidCast { from, to: target }),
1363        },
1364        DType::BoolNullable => match &value {
1365            // pandas nullable Boolean ('boolean') is STRICT: only 0/1 (or
1366            // True/False) are accepted — any other value raises "Need to pass
1367            // bool-like values", UNLIKE numpy bool which is nonzero-truthy.
1368            // (br-frankenpandas-tjomg)
1369            Scalar::Bool(b) => Ok(Scalar::Bool(*b)),
1370            Scalar::Int64(0) => Ok(Scalar::Bool(false)),
1371            Scalar::Int64(1) => Ok(Scalar::Bool(true)),
1372            Scalar::Int64(v) => Err(TypeError::InvalidBoolInt { value: *v }),
1373            Scalar::Float64(v) if *v == 0.0 => Ok(Scalar::Bool(false)),
1374            Scalar::Float64(v) if *v == 1.0 => Ok(Scalar::Bool(true)),
1375            Scalar::Float64(v) => Err(TypeError::InvalidBoolFloat { value: *v }),
1376            _ => Err(TypeError::InvalidCast { from, to: target }),
1377        },
1378        DType::Int64 | DType::Int64Nullable => match &value {
1379            Scalar::Bool(v) => Ok(Scalar::Int64(i64::from(*v))),
1380            Scalar::Float64(v) => {
1381                // pandas astype(int64) truncates a finite float toward zero
1382                // (1.9 -> 1, -1.9 -> -1, 2.5 -> 2); only non-finite (NaN/±inf)
1383                // or out-of-i64-range values raise. Verified vs pandas 2.2.3
1384                // (br-frankenpandas-qcutc). NaN is handled as missing above, so
1385                // here non-finite means ±inf. `as i64` performs the toward-zero
1386                // truncation for in-range finite values.
1387                if !v.is_finite() {
1388                    return Err(TypeError::LossyFloatToInt { value: *v });
1389                }
1390                if *v < i64::MIN as f64 || *v >= 9223372036854775808.0 {
1391                    return Err(TypeError::LossyFloatToInt { value: *v });
1392                }
1393                Ok(Scalar::Int64(*v as i64))
1394            }
1395            Scalar::Utf8(s) => {
1396                // Try direct int parse first, then try float parse + truncate
1397                // (pandas accepts "1.0" as valid int via float intermediate)
1398                if let Ok(v) = s.parse::<i64>() {
1399                    return Ok(Scalar::Int64(v));
1400                }
1401                if let Ok(f) = s.parse::<f64>()
1402                    && f.is_finite()
1403                    && f.fract() == 0.0
1404                    && f >= i64::MIN as f64
1405                    && f < 9223372036854775808.0
1406                {
1407                    return Ok(Scalar::Int64(f as i64));
1408                }
1409                Err(TypeError::InvalidCast { from, to: target })
1410            }
1411            _ => Err(TypeError::InvalidCast { from, to: target }),
1412        },
1413        // Both float flavours accept the same source values; they differ only in
1414        // the missing marker, which is handled above. MEASURED:
1415        //     pd.Series([1,None],dtype="Int64").astype("Float64") -> [1.0, <NA>]
1416        DType::Float64 | DType::Float64Nullable => match &value {
1417            Scalar::Bool(v) => Ok(Scalar::Float64(if *v { 1.0 } else { 0.0 })),
1418            Scalar::Int64(v) => Ok(Scalar::Float64(*v as f64)),
1419            Scalar::Utf8(s) => s
1420                .parse::<f64>()
1421                .map(Scalar::Float64)
1422                .map_err(|_| TypeError::InvalidCast { from, to: target }),
1423            _ => Err(TypeError::InvalidCast { from, to: target }),
1424        },
1425        DType::Utf8 => Ok(Scalar::Utf8(scalar_to_string_for_astype(value))),
1426        DType::Categorical => Err(TypeError::InvalidCast { from, to: target }),
1427        DType::Timedelta64 => match &value {
1428            // A BOOL IS 0 OR 1 NANOSECONDS on the astype path. Measured:
1429            //     pd.Series([True]).astype('timedelta64[ns]') -> 1ns
1430            //     pd.Series([True]).astype('datetime64[ns]')  -> 1970-01-01 ...001
1431            // ⚠️ The CONSTRUCTOR refuses the same thing —
1432            //     pd.DataFrame([[True]], dtype='datetime64[ns]')
1433            //       -> TypeError: dtype bool cannot be converted to datetime64[ns]
1434            // -- the same astype/constructor split `float_to_temporal_nanos`
1435            // documents for non-finite input. This cast is shared, so it takes
1436            // astype's answer and the constructor's refusal belongs in
1437            // `DataFrame::with_constructor_dtype`.
1438            Scalar::Bool(v) => Ok(Scalar::Timedelta64(i64::from(*v))),
1439            Scalar::Int64(v) => Ok(Scalar::Timedelta64(*v)),
1440            Scalar::Float64(v) => Ok(Scalar::Timedelta64(float_to_temporal_nanos(*v))),
1441            Scalar::Utf8(s) => Timedelta::parse(s)
1442                .map(Scalar::Timedelta64)
1443                .map_err(|_| TypeError::InvalidCast { from, to: target }),
1444            _ => Err(TypeError::InvalidCast { from, to: target }),
1445        },
1446        DType::Datetime64 { .. } => match &value {
1447            // See the Timedelta64 arm above for the measurement and for why the
1448            // constructor's stricter refusal is not encoded here.
1449            Scalar::Bool(v) => Ok(Scalar::Datetime64(i64::from(*v))),
1450            Scalar::Int64(v) => Ok(Scalar::Datetime64(*v)),
1451            Scalar::Float64(v) => Ok(Scalar::Datetime64(float_to_temporal_nanos(*v))),
1452            Scalar::Utf8(s) => Timestamp::parse(s)
1453                .map(|timestamp| Scalar::Datetime64(timestamp.nanos))
1454                .map_err(|_| TypeError::InvalidCast { from, to: target }),
1455            _ => Err(TypeError::InvalidCast { from, to: target }),
1456        },
1457        DType::Period => match &value {
1458            // Int cast to a freq-less DType::Period: default to Daily (pandas
1459            // requires an explicit freq in the dtype; ours is freq-less).
1460            Scalar::Int64(v) => Ok(Scalar::Period(Period::new(*v, PeriodFreq::Daily))),
1461            Scalar::Utf8(s) => Period::parse(s)
1462                .map(Scalar::Period)
1463                .map_err(|_| TypeError::InvalidCast { from, to: target }),
1464            _ => Err(TypeError::InvalidCast { from, to: target }),
1465        },
1466        DType::Interval => match &value {
1467            Scalar::Utf8(s) => Interval::parse(s)
1468                .map(Scalar::Interval)
1469                .map_err(|_| TypeError::InvalidCast { from, to: target }),
1470            _ => Err(TypeError::InvalidCast { from, to: target }),
1471        },
1472        DType::Sparse => Err(TypeError::InvalidCast { from, to: target }),
1473    }
1474}
1475
1476/// A float reinterpreted as integer NANOSECONDS, the way pandas casts to
1477/// `datetime64[ns]` / `timedelta64[ns]`.
1478///
1479/// ⚠️ THIS IS NOT THE `int64` RULE, and the difference is the whole reason this
1480/// helper exists rather than a reuse. The explicit constructor REFUSES a lossy
1481/// float -> int64 (`TypeError::LossyFloatToInt`, mirroring pandas' "Trying to
1482/// coerce float values to integers"), but the temporal dtypes silently truncate.
1483/// MEASURED side by side, live pandas 2.2.3, on the single value `1.5`:
1484///
1485/// ```text
1486/// pd.DataFrame([[1.5]], dtype="int64")           -> ValueError
1487/// pd.DataFrame([[1.5]], dtype="datetime64[ns]")  -> 1ns
1488/// pd.DataFrame([[1.5]], dtype="timedelta64[ns]") -> 1ns
1489/// ```
1490///
1491/// TRUNCATION IS TOWARD ZERO, NOT FLOOR. Measured on both signs, where the two
1492/// disagree: 0.9 -> 0 and -0.9 -> 0; 1.5 -> 1 and -1.5 -> -1; -2.5 -> -2 (a
1493/// floor would give -1, -2 and -3). Rust's `as i64` is exactly this truncation.
1494///
1495/// ANYTHING NOT REPRESENTABLE AS `i64` BECOMES NaT, which is why this cannot be
1496/// a bare `as` — Rust's saturating cast would hand back `i64::MAX` where pandas
1497/// hands back NaT, and would map NaN to 0, i.e. the epoch. Measured, all NaT:
1498/// NaN, +inf, -inf, 1e30, -1e30, 9.3e18, and exactly 2^63 and -2^63; while
1499/// 2^63 - 1024 IS representable and converts (2262-04-11 23:47:16.854774784).
1500/// The bounds are therefore strict on both ends — `i64::MIN as f64` is exactly
1501/// -2^63, which pandas already reads as NaT because it IS the NaT sentinel.
1502///
1503/// ⚠️ ONE KNOWN DIVERGENCE, RECORDED RATHER THAN GUESSED. For `timedelta64[ns]`
1504/// pandas' two paths disagree on the non-finite input: `astype` yields NaT but
1505/// the constructor raises OverflowError. `datetime64[ns]` has no such split —
1506/// both give NaT. This cast is shared by both paths, so it takes the behaviour
1507/// they agree on for datetimes and `astype`'s for timedeltas; the constructor's
1508/// stricter refusal belongs in `DataFrame::with_constructor_dtype`, which is
1509/// already where the constructor-only `int64`-rejects-NA check lives, and for
1510/// the same reason.
1511fn float_to_temporal_nanos(value: f64) -> i64 {
1512    // Strict on both ends: `i64::MIN as f64` and `i64::MAX as f64` are -2^63 and
1513    // 2^63, and pandas reads both of those as NaT.
1514    if value.is_finite() && value > (i64::MIN as f64) && value < (i64::MAX as f64) {
1515        // Truncates toward zero, and the guard above means it cannot saturate.
1516        value as i64
1517    } else {
1518        // `Timestamp::NAT` and `Timedelta::NAT` are the same value (`i64::MIN`),
1519        // so this one sentinel is correct for both callers.
1520        Timestamp::NAT
1521    }
1522}
1523
1524fn scalar_to_string_for_astype(value: Scalar) -> String {
1525    match value {
1526        Scalar::Null(NullKind::Null) => "None".to_owned(),
1527        Scalar::Null(NullKind::NaN) => "nan".to_owned(),
1528        Scalar::Null(NullKind::NaT) => "NaT".to_owned(),
1529        Scalar::Bool(true) => "True".to_owned(),
1530        Scalar::Bool(false) => "False".to_owned(),
1531        Scalar::Int64(v) => v.to_string(),
1532        Scalar::Float64(v) => float_to_string_for_astype(v),
1533        Scalar::Utf8(s) => s,
1534        Scalar::Timedelta64(v) if v == Timedelta::NAT => "NaT".to_owned(),
1535        Scalar::Timedelta64(v) => Timedelta::format(v),
1536        Scalar::Datetime64(v) if v == Timestamp::NAT => "NaT".to_owned(),
1537        Scalar::Datetime64(v) => format!("Timestamp[{v}]"),
1538        Scalar::Period(p) if p.ordinal == i64::MIN => "NaT".to_owned(),
1539        Scalar::Period(p) => p.calendar_string(),
1540        Scalar::Interval(v) => v.to_string(),
1541    }
1542}
1543
1544pub fn float_to_string_for_astype(value: f64) -> String {
1545    use std::fmt::Write as _;
1546
1547    if value.is_nan() {
1548        return "nan".to_owned();
1549    }
1550    if value.is_infinite() {
1551        return value.to_string(); // "inf" / "-inf"
1552    }
1553    // pandas astype(str) renders floats via Python str(float): whole numbers
1554    // keep ".0", decimals use the shortest round-trip, and extreme magnitudes use
1555    // scientific notation ("1e+16", "1e-05"). Rust's Debug formatter matches this
1556    // (shortest round-trip, ".0" on whole numbers, scientific at Python's
1557    // boundaries); only the exponent spelling differs (Rust "1e16"/"1e-5" vs
1558    // Python "1e+16"/"1e-05"), so normalize that. The old `{:.1}` whole / Display
1559    // decimal path lost scientific notation (1e16 -> "10000000000000000.0").
1560    // Leave enough spare capacity for the positive sign and one exponent pad
1561    // digit, then normalize the formatter output in place. The former branch
1562    // allocated a second String and copied the mantissa solely to change
1563    // `e16`/`e-5` into pandas' `e+16`/`e-05` spelling.
1564    let mut rendered = String::with_capacity(32);
1565    let _ = write!(rendered, "{value:?}");
1566    let Some(exponent_marker) = rendered.find('e') else {
1567        return rendered;
1568    };
1569
1570    let sign_position = exponent_marker + 1;
1571    let digits_position = match rendered.as_bytes().get(sign_position) {
1572        Some(b'+' | b'-') => sign_position + 1,
1573        _ => {
1574            rendered.insert(sign_position, '+');
1575            sign_position + 1
1576        }
1577    };
1578    if rendered.len() - digits_position == 1 {
1579        rendered.insert(digits_position, '0');
1580    }
1581    rendered
1582}
1583
1584/// Cast a scalar reference to a target dtype (clones only when conversion is needed).
1585pub fn cast_scalar(value: &Scalar, target: DType) -> Result<Scalar, TypeError> {
1586    cast_scalar_owned(value.clone(), target)
1587}
1588
1589// ── Timedelta support ──────────────────────────────────────────────────
1590
1591#[derive(Debug, Error, Clone, PartialEq)]
1592pub enum TimedeltaError {
1593    #[error("invalid timedelta string: {0}")]
1594    InvalidFormat(String),
1595    #[error("overflow in timedelta computation")]
1596    Overflow,
1597}
1598
1599impl TimedeltaError {
1600    /// The pandas exception class this corresponds to, per
1601    /// br-frankenpandas-fyr1z-strict-raise-arms-t7ht2.
1602    ///
1603    /// Returns `None` for [`Self::InvalidFormat`], which is a parse failure
1604    /// rather than a member of the temporal-arithmetic taxonomy.
1605    #[must_use]
1606    pub const fn pandas_error(&self) -> Option<PandasTemporalError> {
1607        match self {
1608            // Probed: pd.Timedelta(float('inf'), 's') raises
1609            // OutOfBoundsTimedelta, NOT a bare OverflowError.
1610            Self::Overflow => Some(PandasTemporalError::OutOfBoundsTimedelta),
1611            Self::InvalidFormat(_) => None,
1612        }
1613    }
1614}
1615
1616#[derive(Debug, Clone, Copy, Default)]
1617pub struct TimedeltaComponents {
1618    pub days: i64,
1619    pub hours: i64,
1620    pub minutes: i64,
1621    pub seconds: i64,
1622    pub milliseconds: i64,
1623    pub microseconds: i64,
1624    pub nanoseconds: i64,
1625}
1626
1627/// The pandas-side exception class a failed temporal operation corresponds to.
1628///
1629/// Introduced by br-frankenpandas-fyr1z-policy-carrier-f29nz and completed by
1630/// fyr1z.3, which established that pandas uses FIVE distinct classes here — so
1631/// a STRICT arm must raise the RIGHT one per op rather than a blanket type.
1632/// Every mapping below was probed against live pandas 2.2.3, not inferred.
1633///
1634/// Named `...TemporalError` rather than `...OverflowError` because
1635/// [`Self::ZeroDivision`] is not an overflow; a type whose name promised
1636/// "overflow" while carrying divide-by-zero would be exactly the kind of stale
1637/// label this codebase keeps having to correct.
1638#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1639pub enum PandasTemporalError {
1640    /// `OverflowError`. e.g. `pd.Timedelta.max + pd.Timedelta('1ns')`, and
1641    /// `Series + Timedelta` / `Series - Series` / `.diff()` which report
1642    /// "Overflow in int64 addition".
1643    Overflow,
1644    /// `OutOfBoundsDatetime`. e.g. `pd.Timestamp.max + pd.Timedelta('1ns')`
1645    /// and `pd.Timestamp.min - pd.Timestamp.max`.
1646    OutOfBoundsDatetime,
1647    /// `OutOfBoundsTimedelta`. Raised by the `pd.Timedelta(value, unit=...)`
1648    /// constructor path (see br-frankenpandas-8v92m), not by the six
1649    /// arithmetic helpers below. Probed: `pd.Timedelta(float('inf'), 's')` ->
1650    /// "Cannot cast inf from s to 'ns' without overflow."
1651    OutOfBoundsTimedelta,
1652    /// `ValueError("overflow in timedelta operation")`. Raised by the
1653    /// REDUCTIONS `Series.sum()` and `Series.std()` over timedelta64.
1654    OverflowInTimedeltaOperation,
1655    /// `ZeroDivisionError`. Raised by SCALAR `Timedelta // 0`, `Timedelta / 0`
1656    /// and `Timedelta // 0.0` ONLY.
1657    ///
1658    /// ⚠ The VECTORIZED division family does NOT raise: probed,
1659    /// `Series([Timedelta]) // 0` and `/ 0` both return NaT. A STRICT arm must
1660    /// not widen this class to the vectorized surface — doing so would create
1661    /// divergence where FrankenPandas is already bit-for-bit correct, which is
1662    /// the central finding of br-frankenpandas-fyr1z (see DISC-018).
1663    ZeroDivision,
1664}
1665
1666/// A temporal overflow, naming the operation that overflowed and the pandas
1667/// exception it corresponds to.
1668#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1669pub struct TemporalFailure {
1670    /// The FrankenPandas operation, e.g. `"Timedelta::add"`.
1671    pub op: &'static str,
1672    /// What pandas raises for this operation.
1673    pub pandas_error: PandasTemporalError,
1674    /// The operand pair whose exact result left the representable range, when
1675    /// the failing operation had one. Carried for the HARDENED audit trail
1676    /// (br-frankenpandas-fyr1z-hardened-audit-vllv6) so a recovery entry can
1677    /// name the range violation rather than merely that one occurred.
1678    pub operands: Option<(i64, i64)>,
1679}
1680
1681impl TemporalFailure {
1682    #[must_use]
1683    pub const fn new(op: &'static str, pandas_error: PandasTemporalError) -> Self {
1684        Self {
1685            op,
1686            pandas_error,
1687            operands: None,
1688        }
1689    }
1690
1691    /// Attach the operands that produced this failure.
1692    #[must_use]
1693    pub const fn with_operands(mut self, lhs: i64, rhs: i64) -> Self {
1694        self.operands = Some((lhs, rhs));
1695        self
1696    }
1697}
1698
1699/// A bounded defensive recovery that HARDENED mode performed, recorded so a run
1700/// can be audited after the fact.
1701///
1702/// br-frankenpandas-fyr1z-hardened-audit-vllv6. AGENTS.md's security doctrine
1703/// requires "deterministic audit logs for recoveries and policy overrides", and
1704/// overflow-to-NaT is exactly a bounded defensive recovery. Until now it was
1705/// SILENT: a caller could not distinguish a NaT produced by an overflow from a
1706/// NaT that was already in the input, which is the whole substance of the
1707/// DISC-018 impact statement.
1708#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1709pub struct TemporalRecovery {
1710    /// The operation that overflowed.
1711    pub op: &'static str,
1712    /// The pandas exception this would have been under STRICT.
1713    pub pandas_error: PandasTemporalError,
1714    /// The operands whose exact result was unrepresentable, when known.
1715    pub operands: Option<(i64, i64)>,
1716    /// The value actually returned. Always the family's NaT sentinel today.
1717    pub recovered_as: i64,
1718}
1719
1720/// Deterministic, opt-in audit trail for HARDENED-mode recoveries.
1721///
1722/// Disabled by default and costs one `Option` check when off, so the default
1723/// path is unchanged. The log is THREAD-LOCAL: FrankenPandas parallelises many
1724/// kernels, and a shared log would impose a lock on hot arithmetic and make the
1725/// entry ORDER nondeterministic — which would defeat the point. Each worker
1726/// therefore accumulates its own deterministic sequence; a caller auditing a
1727/// parallel op drains per thread.
1728pub mod overflow_audit {
1729    use std::cell::RefCell;
1730
1731    use super::TemporalRecovery;
1732
1733    thread_local! {
1734        static LOG: RefCell<Option<Vec<TemporalRecovery>>> = const { RefCell::new(None) };
1735    }
1736
1737    /// Begin recording on THIS thread, discarding anything already buffered.
1738    pub fn enable() {
1739        LOG.with(|log| *log.borrow_mut() = Some(Vec::new()));
1740    }
1741
1742    /// Stop recording on this thread and discard the buffer.
1743    pub fn disable() {
1744        LOG.with(|log| *log.borrow_mut() = None);
1745    }
1746
1747    /// Whether recording is active on this thread.
1748    #[must_use]
1749    pub fn is_enabled() -> bool {
1750        LOG.with(|log| log.borrow().is_some())
1751    }
1752
1753    /// Take the recorded recoveries, leaving recording enabled and empty.
1754    #[must_use]
1755    pub fn drain() -> Vec<TemporalRecovery> {
1756        LOG.with(|log| match log.borrow_mut().as_mut() {
1757            Some(entries) => std::mem::take(entries),
1758            None => Vec::new(),
1759        })
1760    }
1761
1762    /// Record a recovery. A no-op — and allocation-free — when disabled.
1763    pub(super) fn record(entry: TemporalRecovery) {
1764        LOG.with(|log| {
1765            if let Some(entries) = log.borrow_mut().as_mut() {
1766                entries.push(entry);
1767            }
1768        });
1769    }
1770}
1771
1772/// How a temporal overflow should be surfaced.
1773///
1774/// br-frankenpandas-fyr1z-policy-carrier-f29nz adds this carrier WITHOUT
1775/// changing any default behavior: every existing call site is on
1776/// [`OverflowPolicy::SurfaceNat`], which is exactly what the codebase did
1777/// before. `Strict` exists so fyr1z.3 can wire per-op raise arms in a separate,
1778/// reviewable step, and NOTHING routes to it yet.
1779///
1780/// Note DISC-018: a blanket "STRICT raises everywhere" is NOT pandas parity —
1781/// pandas silently wraps on `Series * int` and `.cumsum()`, and returns NaT for
1782/// `.mean()`. The strict arm therefore needs a per-op table, which is why the
1783/// policy is carried per operation rather than set globally.
1784#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1785pub enum OverflowPolicy {
1786    /// Today's behavior, and the only arm currently wired up: overflow becomes
1787    /// the family's NaT sentinel.
1788    #[default]
1789    SurfaceNat,
1790    /// Reserved for fyr1z.3. Surfaces the [`TemporalFailure`] to the caller.
1791    Strict,
1792    /// HARDENED mode (br-frankenpandas-fyr1z-hardened-audit-vllv6): returns the
1793    /// SAME NaT as [`Self::SurfaceNat`], bit-for-bit, and additionally records a
1794    /// [`TemporalRecovery`] into [`overflow_audit`] when that log is enabled.
1795    ///
1796    /// This adds observability, never semantics. AGENTS.md defines hardened
1797    /// mode as "bounded defensive recovery" and requires a deterministic audit
1798    /// log for exactly that.
1799    HardenedNat,
1800}
1801
1802impl OverflowPolicy {
1803    /// Resolve a fallible temporal result under this policy.
1804    ///
1805    /// `SurfaceNat` discards the overflow and yields `nat`, reproducing the
1806    /// pre-f29nz behavior bit-for-bit. `Strict` propagates the overflow.
1807    ///
1808    /// # Errors
1809    /// Returns the [`TemporalFailure`] unchanged under [`Self::Strict`].
1810    pub fn resolve<T>(
1811        self,
1812        outcome: Result<T, TemporalFailure>,
1813        nat: T,
1814    ) -> Result<T, TemporalFailure> {
1815        self.resolve_recording(outcome, nat, i64::MIN)
1816    }
1817
1818    /// [`Self::resolve`] plus the sentinel value to record in the audit trail.
1819    ///
1820    /// Split out because the recovered value is generic (`T`) but the audit
1821    /// entry needs its i64 backing; `recovered_as` supplies that without
1822    /// constraining `T`.
1823    ///
1824    /// # Errors
1825    /// Returns the [`TemporalFailure`] unchanged under [`Self::Strict`].
1826    pub fn resolve_recording<T>(
1827        self,
1828        outcome: Result<T, TemporalFailure>,
1829        nat: T,
1830        recovered_as: i64,
1831    ) -> Result<T, TemporalFailure> {
1832        match (self, outcome) {
1833            (_, Ok(value)) => Ok(value),
1834            (Self::SurfaceNat, Err(_)) => Ok(nat),
1835            (Self::Strict, Err(failure)) => Err(failure),
1836            (Self::HardenedNat, Err(failure)) => {
1837                // Same value as SurfaceNat; the ONLY difference is the record.
1838                overflow_audit::record(TemporalRecovery {
1839                    op: failure.op,
1840                    pandas_error: failure.pandas_error,
1841                    operands: failure.operands,
1842                    recovered_as,
1843                });
1844                Ok(nat)
1845            }
1846        }
1847    }
1848}
1849
1850pub struct Timedelta;
1851
1852impl Timedelta {
1853    pub const NANOS_PER_MICRO: i64 = 1_000;
1854    pub const NANOS_PER_MILLI: i64 = 1_000_000;
1855    pub const NANOS_PER_SEC: i64 = 1_000_000_000;
1856    pub const NANOS_PER_MIN: i64 = 60 * Self::NANOS_PER_SEC;
1857    pub const NANOS_PER_HOUR: i64 = 60 * Self::NANOS_PER_MIN;
1858    pub const NANOS_PER_DAY: i64 = 24 * Self::NANOS_PER_HOUR;
1859    pub const NANOS_PER_WEEK: i64 = 7 * Self::NANOS_PER_DAY;
1860
1861    pub const NAT: i64 = i64::MIN;
1862
1863    pub fn parse(s: &str) -> Result<i64, TimedeltaError> {
1864        let s = s.trim();
1865
1866        if s.eq_ignore_ascii_case("nat") {
1867            return Ok(Self::NAT);
1868        }
1869
1870        let (negative, s) = if let Some(rest) = s.strip_prefix('-') {
1871            (true, rest.trim())
1872        } else {
1873            (false, s)
1874        };
1875
1876        if let Some(nanos) = Self::try_parse_time_format(s) {
1877            return Ok(if negative { -nanos } else { nanos });
1878        }
1879
1880        if let Some(nanos) = Self::try_parse_iso8601_duration(s) {
1881            return Ok(if negative { -nanos } else { nanos });
1882        }
1883
1884        let nanos = Self::parse_compound(s)?;
1885        Ok(if negative { -nanos } else { nanos })
1886    }
1887
1888    /// Parse an ISO-8601 duration the way pandas `Timedelta` accepts it:
1889    /// a leading uppercase `P`, an optional `T` separator that is otherwise
1890    /// ignored, and unit letters `W`/`D`/`H`/`M`/`S` in any position. `M` is
1891    /// always MINUTES (never months), and only seconds may be fractional —
1892    /// years/months and lowercase units are rejected, matching pandas.
1893    /// (pandas mis-handles fractional non-second components; those are rejected
1894    /// here rather than reproducing the buggy value.) (br-frankenpandas-c3p8b)
1895    fn try_parse_iso8601_duration(s: &str) -> Option<i64> {
1896        let mut rest = s.strip_prefix('P')?;
1897        if rest.is_empty() {
1898            return None;
1899        }
1900        let mut total: i64 = 0;
1901        let mut saw_component = false;
1902        while !rest.is_empty() {
1903            if let Some(after_t) = rest.strip_prefix('T') {
1904                rest = after_t;
1905                continue;
1906            }
1907            let num_end = rest.find(|c: char| !c.is_ascii_digit() && c != '.')?;
1908            if num_end == 0 {
1909                return None;
1910            }
1911            let num_str = &rest[..num_end];
1912            let unit = rest.as_bytes()[num_end];
1913            let is_fractional = num_str.contains('.');
1914            rest = &rest[num_end + 1..];
1915
1916            let (multiplier, frac_ok) = match unit {
1917                b'W' => (Self::NANOS_PER_WEEK, false),
1918                b'D' => (Self::NANOS_PER_DAY, false),
1919                b'H' => (Self::NANOS_PER_HOUR, false),
1920                b'M' => (Self::NANOS_PER_MIN, false),
1921                b'S' => (Self::NANOS_PER_SEC, true),
1922                _ => return None,
1923            };
1924            if is_fractional {
1925                if !frac_ok {
1926                    return None;
1927                }
1928                let value: f64 = num_str.parse().ok()?;
1929                let product = value * multiplier as f64;
1930                if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
1931                    return None;
1932                }
1933                total = total.checked_add(product.round() as i64)?;
1934            } else {
1935                let value: i64 = num_str.parse().ok()?;
1936                total = total.checked_add(value.checked_mul(multiplier)?)?;
1937            }
1938            saw_component = true;
1939        }
1940        saw_component.then_some(total)
1941    }
1942
1943    fn try_parse_time_format(s: &str) -> Option<i64> {
1944        let parts: Vec<&str> = s.split(':').collect();
1945        if parts.len() < 2 || parts.len() > 3 {
1946            return None;
1947        }
1948
1949        let hours: i64 = parts[0].parse().ok()?;
1950        let minutes: i64 = parts[1].parse().ok()?;
1951
1952        let (seconds, frac_nanos) = if parts.len() == 3 {
1953            if let Some((sec_str, frac_str)) = parts[2].split_once('.') {
1954                let sec: i64 = sec_str.parse().ok()?;
1955                if !frac_str.bytes().all(|byte| byte.is_ascii_digit()) {
1956                    return None;
1957                }
1958                let mut frac = 0_i64;
1959                let taken = frac_str.len().min(9);
1960                for byte in frac_str.bytes().take(9) {
1961                    frac = frac * 10 + i64::from(byte - b'0');
1962                }
1963                for _ in taken..9 {
1964                    frac *= 10;
1965                }
1966                (sec, frac)
1967            } else {
1968                let sec: i64 = parts[2].parse().ok()?;
1969                (sec, 0)
1970            }
1971        } else {
1972            (0, 0)
1973        };
1974
1975        hours
1976            .checked_mul(Self::NANOS_PER_HOUR)?
1977            .checked_add(minutes.checked_mul(Self::NANOS_PER_MIN)?)?
1978            .checked_add(seconds.checked_mul(Self::NANOS_PER_SEC)?)?
1979            .checked_add(frac_nanos)
1980    }
1981
1982    fn parse_compound(s: &str) -> Result<i64, TimedeltaError> {
1983        let mut total: i64 = 0;
1984        let mut remaining = s;
1985
1986        while !remaining.is_empty() {
1987            remaining = remaining.trim_start();
1988            if remaining.is_empty() {
1989                break;
1990            }
1991
1992            // Per br-frankenpandas-i9bah: check if remaining is a time format
1993            // (HH:MM:SS) which can appear after "N days " in pandas timedelta strings.
1994            if remaining.contains(':')
1995                && let Some(time_nanos) = Self::try_parse_time_format(remaining)
1996            {
1997                total = total
1998                    .checked_add(time_nanos)
1999                    .ok_or(TimedeltaError::Overflow)?;
2000                break;
2001            }
2002
2003            let num_end = remaining
2004                .find(|c: char| !c.is_ascii_digit() && c != '.' && c != '-')
2005                .unwrap_or(remaining.len());
2006
2007            if num_end == 0 {
2008                return Err(TimedeltaError::InvalidFormat(s.to_string()));
2009            }
2010
2011            let num_str = &remaining[..num_end];
2012            let num: f64 = num_str
2013                .parse()
2014                .map_err(|_| TimedeltaError::InvalidFormat(s.to_string()))?;
2015
2016            remaining = remaining[num_end..].trim_start();
2017
2018            let unit_end = remaining
2019                .find(|c: char| c.is_ascii_digit() || c.is_whitespace())
2020                .unwrap_or(remaining.len());
2021
2022            let unit = &remaining[..unit_end];
2023            remaining = &remaining[unit_end..];
2024
2025            let multiplier = Self::unit_to_nanos(unit)
2026                .ok_or_else(|| TimedeltaError::InvalidFormat(s.to_string()))?;
2027
2028            // Per br-frankenpandas-zw3mg: pandas raises OverflowError on
2029            // huge scientific-notation Timedeltas like "1e100 days". The
2030            // raw `as i64` cast silently saturated to i64::MAX, masking
2031            // overflow before checked_add could catch it.
2032            let product = num * multiplier as f64;
2033            if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
2034                return Err(TimedeltaError::Overflow);
2035            }
2036            let nanos = product.round() as i64;
2037            total = total.checked_add(nanos).ok_or(TimedeltaError::Overflow)?;
2038        }
2039
2040        // NOTE: there is deliberately no "total == 0 is suspicious" guard here.
2041        // One used to live at this spot and rejected every legitimately-zero
2042        // compound -- `to_timedelta("0 seconds")` raised while `"1 second"` and
2043        // `"10 seconds"` parsed, because the only exemption was the literal
2044        // string "0". pandas 2.2.3 accepts all of `0 seconds` / `0 days` / `0s`
2045        // / `0.0 hours` / `-0 seconds` as a zero Timedelta. The guard was also
2046        // unnecessary: the loop above returns `InvalidFormat` on an unparseable
2047        // number AND on an unknown unit, so the only way to reach here with
2048        // `total == 0` is an input whose components genuinely sum to zero.
2049        Ok(total)
2050    }
2051
2052    /// Map a pandas-style frequency-alias string to a nanosecond-count.
2053    ///
2054    /// Recognizes pandas's offset alias core set plus common word forms:
2055    /// W/week(s), D/day(s), H/hr/hour(s), m/T/min/minute(s), s/sec/second(s),
2056    /// ms/milli/millisecond(s)/L, us/µs/micro/microsecond(s)/U, ns/nano/
2057    /// nanosecond(s)/N. Empty string maps to days (matches pandas default).
2058    /// Returns `None` for unrecognized aliases — callers can choose to map
2059    /// that to NaT (consistent with the rest of fp-types) or surface as a
2060    /// typed error.
2061    ///
2062    /// Per br-frankenpandas-lbsx (9p0u Phase 2.6): public surface so
2063    /// downstream crates can consume the same alias map fp-types uses for
2064    /// `Timedelta::from_unit` / `Timestamp::*_to_unit`.
2065    #[must_use]
2066    pub fn unit_to_nanos(unit: &str) -> Option<i64> {
2067        match unit.to_lowercase().as_str() {
2068            "w" | "week" | "weeks" => Some(Self::NANOS_PER_WEEK),
2069            "d" | "day" | "days" => Some(Self::NANOS_PER_DAY),
2070            "h" | "hr" | "hour" | "hours" => Some(Self::NANOS_PER_HOUR),
2071            "m" | "min" | "minute" | "minutes" | "t" => Some(Self::NANOS_PER_MIN),
2072            "s" | "sec" | "second" | "seconds" => Some(Self::NANOS_PER_SEC),
2073            "ms" | "milli" | "millis" | "millisecond" | "milliseconds" | "l" => {
2074                Some(Self::NANOS_PER_MILLI)
2075            }
2076            "us" | "µs" | "micro" | "micros" | "microsecond" | "microseconds" | "u" => {
2077                Some(Self::NANOS_PER_MICRO)
2078            }
2079            "ns" | "nano" | "nanos" | "nanosecond" | "nanoseconds" | "n" => Some(1),
2080            "" => Some(Self::NANOS_PER_DAY),
2081            _ => None,
2082        }
2083    }
2084
2085    pub fn components(nanos: i64) -> TimedeltaComponents {
2086        if nanos == Self::NAT {
2087            return TimedeltaComponents::default();
2088        }
2089
2090        // pandas/Python normalize via FLOOR division (like format()): the days
2091        // component can be negative while the time-of-day remainder is always in
2092        // [0, 1 day). So pd.Timedelta(-1,'s').components == (-1, 23, 59, 59, 0, 0, 0),
2093        // NOT the abs-based (0, 0, 0, 1, 0, 0, 0).
2094        let days = nanos.div_euclid(Self::NANOS_PER_DAY);
2095        let rem = nanos.rem_euclid(Self::NANOS_PER_DAY);
2096
2097        let hours = rem / Self::NANOS_PER_HOUR;
2098        let rem = rem % Self::NANOS_PER_HOUR;
2099
2100        let minutes = rem / Self::NANOS_PER_MIN;
2101        let rem = rem % Self::NANOS_PER_MIN;
2102
2103        let seconds = rem / Self::NANOS_PER_SEC;
2104        let rem = rem % Self::NANOS_PER_SEC;
2105
2106        let milliseconds = rem / Self::NANOS_PER_MILLI;
2107        let rem = rem % Self::NANOS_PER_MILLI;
2108
2109        let microseconds = rem / Self::NANOS_PER_MICRO;
2110        let nanoseconds = rem % Self::NANOS_PER_MICRO;
2111
2112        TimedeltaComponents {
2113            days,
2114            hours,
2115            minutes,
2116            seconds,
2117            milliseconds,
2118            microseconds,
2119            nanoseconds,
2120        }
2121    }
2122
2123    pub fn total_seconds(nanos: i64) -> f64 {
2124        if nanos == Self::NAT {
2125            f64::NAN
2126        } else {
2127            nanos as f64 / Self::NANOS_PER_SEC as f64
2128        }
2129    }
2130
2131    /// Convert to specified time unit.
2132    ///
2133    /// Matches pd.Timedelta.as_unit(). Supported units: ns, us, ms, s, m, h, D.
2134    #[must_use]
2135    pub fn as_unit(nanos: i64, unit: &str) -> f64 {
2136        if nanos == Self::NAT {
2137            return f64::NAN;
2138        }
2139        let nanos_f = nanos as f64;
2140        match unit {
2141            "ns" | "nanoseconds" => nanos_f,
2142            "us" | "microseconds" => nanos_f / Self::NANOS_PER_MICRO as f64,
2143            "ms" | "milliseconds" => nanos_f / Self::NANOS_PER_MILLI as f64,
2144            "s" | "seconds" => nanos_f / Self::NANOS_PER_SEC as f64,
2145            "m" | "minutes" => nanos_f / Self::NANOS_PER_MIN as f64,
2146            "h" | "hours" => nanos_f / Self::NANOS_PER_HOUR as f64,
2147            "D" | "days" => nanos_f / Self::NANOS_PER_DAY as f64,
2148            _ => f64::NAN,
2149        }
2150    }
2151
2152    /// Return the days component, or `None` for `NaT`. Matches
2153    /// `pd.Timedelta.days`.
2154    ///
2155    /// ⚠️ `None`, NOT `0`, AND THE TYPE IS THE FIX
2156    /// (br-frankenpandas-timedelta-nat-days-returns-zero-406ni). All four
2157    /// component helpers used to return `0` for `NaT`, one of them behind a
2158    /// comment asserting "pandas returns 0 for NaT.days (no error)". MEASURED,
2159    /// live pandas 2.2.3: `pd.NaT.days` is **nan**, and
2160    /// `pd.to_timedelta([1, None, -1], unit='s').dt.days` is float64
2161    /// `[0.0, nan, -1.0]` — pandas promotes the whole column because NaN cannot
2162    /// live in int64.
2163    ///
2164    /// An `i64` return cannot express that, so correctness depended on every
2165    /// caller remembering to test `NAT` first. It did — `timedelta_component`
2166    /// checked in three separate arms — but that is a convention, and the bead
2167    /// filed it as a landmine for the next person to wire a `.dt` accessor: a
2168    /// function whose doc says "matches pandas" handing back a plausible integer
2169    /// where pandas has a missing value. `Option<i64>` moves the fact into the
2170    /// type, so a caller cannot forget and the duplicated `NAT` tests go away.
2171    #[must_use]
2172    pub fn days(nanos: i64) -> Option<i64> {
2173        if nanos == Self::NAT {
2174            return None;
2175        }
2176        // FLOOR division like pandas: pd.Timedelta(-1,'s').days == -1, not 0.
2177        Some(nanos.div_euclid(Self::NANOS_PER_DAY))
2178    }
2179
2180    /// Return the seconds component (0-86399), or `None` for `NaT`. Matches
2181    /// `pd.Timedelta.seconds`. See [`Self::days`] for why this is an `Option`.
2182    #[must_use]
2183    pub fn seconds(nanos: i64) -> Option<i64> {
2184        if nanos == Self::NAT {
2185            return None;
2186        }
2187        // Floor-normalized time-of-day remainder: pd.Timedelta(-1,'s').seconds == 86399.
2188        Some(nanos.rem_euclid(Self::NANOS_PER_DAY) / Self::NANOS_PER_SEC)
2189    }
2190
2191    /// Return the microseconds component (0-999999), or `None` for `NaT`.
2192    /// Matches `pd.Timedelta.microseconds`. See [`Self::days`].
2193    #[must_use]
2194    pub fn microseconds(nanos: i64) -> Option<i64> {
2195        if nanos == Self::NAT {
2196            return None;
2197        }
2198        Some(nanos.rem_euclid(Self::NANOS_PER_SEC) / Self::NANOS_PER_MICRO)
2199    }
2200
2201    /// Return the nanoseconds component (0-999), or `None` for `NaT`. Matches
2202    /// `pd.Timedelta.nanoseconds`. See [`Self::days`].
2203    #[must_use]
2204    pub fn nanoseconds(nanos: i64) -> Option<i64> {
2205        if nanos == Self::NAT {
2206            return None;
2207        }
2208        Some(nanos.rem_euclid(Self::NANOS_PER_MICRO))
2209    }
2210
2211    /// The coarsest [`TimedeltaStringResolution`] that renders `nanos`
2212    /// losslessly. Fold over a column with `max`.
2213    ///
2214    /// `NaT` reports `Days`, the identity of that fold, because pandas excludes
2215    /// it from the scan: `[1 days, NaT]` still renders `['1 days', 'NaT']`.
2216    #[must_use]
2217    pub const fn string_resolution(nanos: i64) -> TimedeltaStringResolution {
2218        if nanos == Self::NAT || nanos.rem_euclid(Self::NANOS_PER_DAY) == 0 {
2219            TimedeltaStringResolution::Days
2220        } else {
2221            TimedeltaStringResolution::Full
2222        }
2223    }
2224
2225    /// Render `nanos` the way `astype(str)` does, at a resolution chosen for the
2226    /// whole column by [`Self::string_resolution`].
2227    ///
2228    /// The `Full` arm is [`Self::format`] verbatim — the per-value sub-second
2229    /// width was already right. Only the `Days` arm is new, and it exists
2230    /// because a column of whole days drops its time part completely:
2231    /// `'1 days'`, not `'1 days 00:00:00'`.
2232    #[must_use]
2233    pub fn format_at_resolution(nanos: i64, resolution: TimedeltaStringResolution) -> String {
2234        if nanos == Self::NAT {
2235            return "NaT".to_string();
2236        }
2237        match resolution {
2238            TimedeltaStringResolution::Full => Self::format(nanos),
2239            // Euclidean division, so a negative whole-day value keeps pandas'
2240            // spelling: -2 days is "-2 days", never "-1 days -24:00:00".
2241            TimedeltaStringResolution::Days => {
2242                format!("{} days", nanos.div_euclid(Self::NANOS_PER_DAY))
2243            }
2244        }
2245    }
2246
2247    pub fn format(nanos: i64) -> String {
2248        use std::fmt::Write as _;
2249
2250        if nanos == Self::NAT {
2251            return "NaT".to_string();
2252        }
2253
2254        // pandas / Python timedelta normalize via FLOOR division: the days
2255        // component can be negative while the time-of-day remainder is always
2256        // non-negative, and a negative-days value prints a '+' before the time
2257        // (e.g. -1s -> "-1 days +23:59:59", not "-0 days 00:00:01"). Compute the
2258        // components with Euclidean div/rem so the remainder is in [0, 1 day).
2259        let days = nanos.div_euclid(Self::NANOS_PER_DAY);
2260        let rem = nanos.rem_euclid(Self::NANOS_PER_DAY);
2261        let hours = rem / Self::NANOS_PER_HOUR;
2262        let minutes = (rem % Self::NANOS_PER_HOUR) / Self::NANOS_PER_MIN;
2263        let seconds = (rem % Self::NANOS_PER_MIN) / Self::NANOS_PER_SEC;
2264        let frac = rem % Self::NANOS_PER_SEC;
2265
2266        // Build directly into the returned allocation. The former path first
2267        // allocated an `HH:MM:SS` string, then copied it into the result.
2268        let mut result = String::with_capacity(32);
2269        let _ = write!(result, "{days} days ");
2270        // '+' joins the negative day count to the positive time remainder.
2271        if days < 0 {
2272            result.push('+');
2273        }
2274        let _ = write!(result, "{hours:02}:{minutes:02}:{seconds:02}");
2275        if frac > 0 {
2276            // pandas renders the sub-second part with microsecond precision
2277            // (6 digits) unless a sub-microsecond (nanosecond) component is
2278            // present, in which case it widens to 9 digits.
2279            if frac % 1_000 == 0 {
2280                let _ = write!(result, ".{:06}", frac / 1_000);
2281            } else {
2282                let _ = write!(result, ".{frac:09}");
2283            }
2284        }
2285        result
2286    }
2287
2288    /// Build a nanosecond Timedelta from a float quantity of `unit`.
2289    ///
2290    /// Matches `pd.Timedelta(value, unit=...)`:
2291    /// - `NaN` → `NAT`. pandas returns `NaT`, and `NAT` is how NaT is spelled
2292    ///   in this i64 representation. Rust's float→int `as` maps `NaN` to
2293    ///   **0**, so the unguarded cast used to hand back a ZERO DURATION for a
2294    ///   missing value (br-frankenpandas-8v92m).
2295    /// - non-finite or out-of-range product → [`TimedeltaError::Overflow`].
2296    ///   pandas raises `OutOfBoundsTimedelta` ("Cannot cast inf from s to 'ns'
2297    ///   without overflow"); the `as` cast used to SATURATE to `i64::MAX`,
2298    ///   returning a finite, plausible ~106751-day duration instead.
2299    /// - unknown unit → [`TimedeltaError::InvalidFormat`], unchanged.
2300    ///
2301    /// The overflow guard is the same one `parse` and the component parser
2302    /// already use (added by br-frankenpandas-zw3mg, which fixed two of the
2303    /// three sites sharing this expression and missed this one).
2304    pub fn from_unit(value: f64, unit: &str) -> Result<i64, TimedeltaError> {
2305        let multiplier = Self::unit_to_nanos(unit)
2306            .ok_or_else(|| TimedeltaError::InvalidFormat(unit.to_string()))?;
2307        if value.is_nan() {
2308            return Ok(Self::NAT);
2309        }
2310        let product = value * multiplier as f64;
2311        if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
2312            return Err(TimedeltaError::Overflow);
2313        }
2314        Ok(product.round() as i64)
2315    }
2316
2317    // ── Arithmetic (br-frankenpandas-4r56 Phase 1) ──────────────────────
2318    //
2319    // NaT propagation: any arithmetic with `NAT` returns `NAT`. Matches
2320    // pandas `pd.NaT + anything == NaT`, `pd.NaT - anything == NaT`, etc.
2321    //
2322    // Overflow (br-frankenpandas-lgyy8): i64 overflow yields `NAT` in BOTH
2323    // directions. It never wraps and never fabricates a finite value.
2324    //
2325    // These previously used `saturating_*`, which was asymmetric and failed
2326    // OPEN on one side. Because `NAT == i64::MIN`, negative overflow clamped
2327    // onto the sentinel and already surfaced as missing — but POSITIVE
2328    // overflow clamped to `i64::MAX`, a perfectly valid, finite, plausible
2329    // duration (and, for `Timestamp`, a ~year-2262 instant) returned as if it
2330    // were real data. Live pandas 2.2.3 never does that, in either the scalar
2331    // or the vectorized path:
2332    //
2333    //   pd.Timedelta.min + Timedelta('-1ns')      -> NaT  (lands on the sentinel)
2334    //   pd.Series[datetime64] + Timedelta('-1ns') -> [NaT, ...]
2335    //   pd.Timedelta.max + Timedelta('1ns')       -> raises OverflowError
2336    //   pd.Timestamp.max + Timedelta('1ns')       -> raises OutOfBoundsDatetime
2337    //   pd.Series[datetime64] + Timedelta('1ns')  -> raises OverflowError
2338    //   pd.Timestamp.min - pd.Timestamp.max       -> raises OutOfBoundsDatetime
2339    //   pd.Timedelta.max * 2                      -> raises OverflowError
2340    //
2341    // We surface NaT where pandas raises, rather than making these infallible
2342    // `#[must_use]` helpers fallible: that is the SAME documented divergence
2343    // `div_scalar` already takes for divide-by-zero ("matches pandas, which
2344    // raises, but we surface as NaT to avoid panics at the type-system
2345    // boundary"). Every input whose exact result is representable is
2346    // unaffected bit-for-bit; only overflow moves.
2347
2348    /// Add two Timedelta nanosecond values, reporting overflow.
2349    ///
2350    /// br-frankenpandas-fyr1z-policy-carrier-f29nz. NaT propagation is NOT an
2351    /// overflow — a NaT operand yields `Ok(NAT)`, exactly as before. Only an
2352    /// unrepresentable result is an `Err`.
2353    ///
2354    /// # Errors
2355    /// [`PandasTemporalError::Overflow`] when the sum exceeds i64.
2356    pub fn try_add(a: i64, b: i64) -> Result<i64, TemporalFailure> {
2357        if a == Self::NAT || b == Self::NAT {
2358            return Ok(Self::NAT);
2359        }
2360        a.checked_add(b).ok_or(
2361            TemporalFailure::new("Timedelta::add", PandasTemporalError::Overflow)
2362                .with_operands(a, b),
2363        )
2364    }
2365
2366    /// Add two Timedelta nanosecond values. NaT propagates; overflow → NaT.
2367    #[must_use]
2368    pub fn add(a: i64, b: i64) -> i64 {
2369        Self::try_add(a, b).unwrap_or(Self::NAT)
2370    }
2371
2372    /// Subtract two Timedelta nanosecond values, reporting overflow.
2373    ///
2374    /// # Errors
2375    /// [`PandasTemporalError::Overflow`] when the difference exceeds i64.
2376    pub fn try_sub(a: i64, b: i64) -> Result<i64, TemporalFailure> {
2377        if a == Self::NAT || b == Self::NAT {
2378            return Ok(Self::NAT);
2379        }
2380        a.checked_sub(b).ok_or(
2381            TemporalFailure::new("Timedelta::sub", PandasTemporalError::Overflow)
2382                .with_operands(a, b),
2383        )
2384    }
2385
2386    /// Subtract two Timedelta nanosecond values. NaT propagates; overflow → NaT.
2387    #[must_use]
2388    pub fn sub(a: i64, b: i64) -> i64 {
2389        Self::try_sub(a, b).unwrap_or(Self::NAT)
2390    }
2391
2392    /// Negate a Timedelta value. NaT stays NaT.
2393    ///
2394    /// There is no overflow case to handle, and the `saturating_` call is a
2395    /// belt-and-braces no-op: the only `i64` whose negation overflows is
2396    /// `i64::MIN`, and `i64::MIN` IS the NaT sentinel, so it is consumed by
2397    /// the guard above. The representable range is `[i64::MIN + 1, i64::MAX]`,
2398    /// which is symmetric about zero.
2399    ///
2400    /// CORRECTED br-frankenpandas-fyr1z: this used to claim "pandas:
2401    /// `-pd.Timedelta.min` is NaT since min == -max - 1 cannot be negated".
2402    /// That is false in both halves. pandas' `Timedelta.min.value` is
2403    /// `-9223372036854775807` == `-Timedelta.max.value`, NOT `-max - 1`
2404    /// (`-max - 1` is `i64::MIN`, which pandas also reserves for NaT), and
2405    /// live pandas 2.2.3 returns `Timedelta('106751 days 23:47:16.854775807')`
2406    /// — i.e. `Timedelta.max` — for `-pd.Timedelta.min`, `abs(pd.Timedelta
2407    /// .min)`, and the vectorized `-Series[timedelta64]` / `.abs()` forms.
2408    /// Do not "fix" this to return NaT; that would be the parity regression.
2409    #[must_use]
2410    pub fn neg(a: i64) -> i64 {
2411        if a == Self::NAT {
2412            return Self::NAT;
2413        }
2414        a.saturating_neg()
2415    }
2416
2417    /// Absolute value of a Timedelta. NaT stays NaT.
2418    ///
2419    /// As with [`Timedelta::neg`], no overflow is reachable: `i64::MIN` is the
2420    /// NaT sentinel and is consumed by the guard, and `|i64::MIN + 1|` is
2421    /// exactly `i64::MAX`. pandas agrees — `abs(pd.Timedelta.min)` is
2422    /// `Timedelta.max`, not NaT.
2423    #[must_use]
2424    pub fn abs(a: i64) -> i64 {
2425        if a == Self::NAT {
2426            return Self::NAT;
2427        }
2428        a.saturating_abs()
2429    }
2430
2431    /// Multiply a Timedelta value by an integer factor. NaT propagates;
2432    /// overflow → NaT (see the overflow note above).
2433    ///
2434    /// Matches pandas `pd.Timedelta(...) * int`, which raises `OverflowError`
2435    /// rather than returning a saturated duration.
2436    #[must_use]
2437    pub fn mul_scalar(a: i64, factor: i64) -> i64 {
2438        Self::try_mul_scalar(a, factor).unwrap_or(Self::NAT)
2439    }
2440
2441    /// Multiply a Timedelta by an integer factor under an explicit policy.
2442    ///
2443    /// br-frankenpandas-fyr1z-wrap-signoff-s4lkx, DECIDED BY THE MAINTAINER:
2444    /// **STRICT REPRODUCES PANDAS' SILENT WRAP.** The rationale is that this is
2445    /// a PORT — STRICT means bit-for-bit observable parity with the incumbent
2446    /// *including its quirks*, so the wrap is a deliberately reproduced pandas
2447    /// behaviour, not a defect of ours.
2448    ///
2449    /// Verified against live pandas 2.2.3: `Series([Timedelta.max]) * 2` returns
2450    /// `-2` ns (displayed `-1 days +23:59:59.999999998`), which is exactly
2451    /// `i64::MAX.wrapping_mul(2)`. Rust's wrapping arithmetic reproduces numpy's
2452    /// int64 wraparound bit-for-bit, so no emulation is needed.
2453    ///
2454    /// The wrap is INTEGER-MULTIPLIER ONLY: `Series * 2.0` returns NaT in
2455    /// pandas, so a float multiplier must not route here.
2456    ///
2457    /// Every other policy keeps today's behaviour — NaT, with HARDENED also
2458    /// recording the recovery. So the fail-open shape br-frankenpandas-lgyy8
2459    /// removed is reachable ONLY when a caller explicitly asks for STRICT
2460    /// incumbent parity, never by default. See DISC-020.
2461    #[must_use]
2462    pub fn mul_scalar_with_policy(a: i64, factor: i64, policy: OverflowPolicy) -> i64 {
2463        if a == Self::NAT {
2464            return Self::NAT;
2465        }
2466        if matches!(policy, OverflowPolicy::Strict) {
2467            return a.wrapping_mul(factor);
2468        }
2469        policy
2470            .resolve_recording(Self::try_mul_scalar(a, factor), Self::NAT, Self::NAT)
2471            .unwrap_or(Self::NAT)
2472    }
2473
2474    /// Multiply a Timedelta value by an integer factor, reporting overflow.
2475    ///
2476    /// # Errors
2477    /// [`PandasTemporalError::Overflow`] when the product exceeds i64 — which
2478    /// is what the SCALAR `pd.Timedelta.max * 2` raises. Note DISC-018: the
2479    /// VECTORIZED `Series * int` wraps silently instead, so a strict arm for
2480    /// this op must decide per-surface rather than inherit this class blindly.
2481    pub fn try_mul_scalar(a: i64, factor: i64) -> Result<i64, TemporalFailure> {
2482        if a == Self::NAT {
2483            return Ok(Self::NAT);
2484        }
2485        a.checked_mul(factor).ok_or(
2486            TemporalFailure::new("Timedelta::mul_scalar", PandasTemporalError::Overflow)
2487                .with_operands(a, factor),
2488        )
2489    }
2490
2491    /// Floor-divide a Timedelta value by an integer divisor. NaT propagates.
2492    /// Returns NaT on divide-by-zero (matches pandas, which raises, but we
2493    /// surface as NaT to avoid panics at the type-system boundary).
2494    ///
2495    /// Matches pandas / Python `pd.Timedelta(...) // int`: floor division,
2496    /// not truncation toward zero. `-100 // 3 == -34`, and `100 // -3 ==
2497    /// -34`. Rust's `/` truncates toward zero and `div_euclid` keeps the
2498    /// remainder non-negative — neither matches pandas when the divisor is
2499    /// negative. This helper adjusts trunc-toward-zero into floor.
2500    #[must_use]
2501    pub fn div_scalar(a: i64, divisor: i64) -> i64 {
2502        Self::try_div_scalar(a, divisor).unwrap_or(Self::NAT)
2503    }
2504
2505    /// Floor-divide a Timedelta by an integer divisor, reporting divide-by-zero.
2506    ///
2507    /// br-frankenpandas-fyr1z-strict-raise-arms-t7ht2. NaT propagation is not a
2508    /// failure and yields `Ok(NAT)`; only a zero divisor is an `Err`.
2509    ///
2510    /// ⚠ SCALAR SEMANTICS ONLY. pandas raises `ZeroDivisionError` for the
2511    /// scalar `pd.Timedelta('1s') // 0`, but the VECTORIZED
2512    /// `Series([Timedelta]) // 0` returns NaT (both probed on 2.2.3). The
2513    /// infallible [`Self::div_scalar`] above keeps the NaT behavior that the
2514    /// vectorized callers depend on, and a STRICT arm must route only the
2515    /// scalar surface here.
2516    ///
2517    /// # Errors
2518    /// [`PandasTemporalError::ZeroDivision`] when `divisor == 0`.
2519    pub fn try_div_scalar(a: i64, divisor: i64) -> Result<i64, TemporalFailure> {
2520        if divisor == 0 {
2521            return Err(TemporalFailure::new(
2522                "Timedelta::div_scalar",
2523                PandasTemporalError::ZeroDivision,
2524            )
2525            .with_operands(a, divisor));
2526        }
2527        if a == Self::NAT {
2528            return Ok(Self::NAT);
2529        }
2530        Ok(Self::div_scalar_inner(a, divisor))
2531    }
2532
2533    fn div_scalar_inner(a: i64, divisor: i64) -> i64 {
2534        // NAT == i64::MIN so the classic `i64::MIN / -1` overflow path is
2535        // already handled by the NAT check above. `(i64::MIN + 1) / -1`
2536        // equals `i64::MAX` with no overflow, so we never need a
2537        // saturation branch here.
2538        let q = a / divisor;
2539        let r = a % divisor;
2540        // If remainder is non-zero and has opposite sign from divisor,
2541        // Rust's trunc-toward-zero `/` is one step above the floor. Adjust
2542        // down by 1 to match Python/pandas floor division.
2543        if r != 0 && (r < 0) != (divisor < 0) {
2544            q - 1
2545        } else {
2546            q
2547        }
2548    }
2549
2550    /// Divide two Timedelta values, returning the ratio as f64.
2551    /// Matches pandas `pd.Timedelta(...) / pd.Timedelta(...)` → float.
2552    /// NaT in either operand → NaN. Zero divisor → ±Inf (per IEEE 754).
2553    #[must_use]
2554    pub fn div_timedelta(a: i64, b: i64) -> f64 {
2555        if a == Self::NAT || b == Self::NAT {
2556            return f64::NAN;
2557        }
2558        (a as f64) / (b as f64)
2559    }
2560
2561    /// Returns ISO 8601 duration format string.
2562    ///
2563    /// Matches pandas `pd.Timedelta.isoformat()`. Returns format like
2564    /// "P1DT2H3M4.567890123S" for 1 day, 2 hours, 3 minutes, 4.567890123 seconds.
2565    /// NaT returns "NaT".
2566    #[must_use]
2567    pub fn isoformat(nanos: i64) -> String {
2568        use std::fmt::Write as _;
2569
2570        if nanos == Self::NAT {
2571            return "NaT".to_string();
2572        }
2573
2574        let negative = nanos < 0;
2575        let abs_nanos = nanos.saturating_abs();
2576
2577        let days = abs_nanos / Self::NANOS_PER_DAY;
2578        let remaining = abs_nanos % Self::NANOS_PER_DAY;
2579
2580        let hours = remaining / Self::NANOS_PER_HOUR;
2581        let remaining = remaining % Self::NANOS_PER_HOUR;
2582
2583        let minutes = remaining / Self::NANOS_PER_MIN;
2584        let remaining = remaining % Self::NANOS_PER_MIN;
2585
2586        let seconds = remaining / Self::NANOS_PER_SEC;
2587        let sub_sec_nanos = remaining % Self::NANOS_PER_SEC;
2588
2589        // Build directly into the returned allocation. The former sequence of
2590        // `format!` calls allocated two temporary strings for integral values
2591        // and three for fractional values before copying them into `result`.
2592        let mut result = String::with_capacity(40);
2593        if negative {
2594            result.push('-');
2595        }
2596        // `fmt::Write for String` is infallible.
2597        let _ = write!(result, "P{days}DT{hours}H{minutes}M{seconds}");
2598        if sub_sec_nanos != 0 {
2599            result.push('.');
2600            let _ = write!(result, "{sub_sec_nanos:09}");
2601            while result.ends_with('0') {
2602                result.pop();
2603            }
2604        }
2605        result.push('S');
2606        result
2607    }
2608
2609    /// Rounds down to the nearest frequency unit.
2610    ///
2611    /// Matches pandas `pd.Timedelta.floor(freq)`. NaT is preserved.
2612    #[must_use]
2613    pub fn floor(nanos: i64, freq: &str) -> i64 {
2614        if nanos == Self::NAT {
2615            return Self::NAT;
2616        }
2617        let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
2618            return Self::NAT;
2619        };
2620        if unit_nanos == 0 {
2621            return Self::NAT;
2622        }
2623        nanos
2624            .div_euclid(unit_nanos)
2625            .checked_mul(unit_nanos)
2626            .unwrap_or(Self::NAT)
2627    }
2628
2629    /// Rounds up to the nearest frequency unit.
2630    ///
2631    /// Matches pandas `pd.Timedelta.ceil(freq)`. NaT is preserved; overflow
2632    /// → NaT (`pd.Timedelta.max.ceil('D')` raises `OutOfBoundsTimedelta:
2633    /// Cannot round ... without overflow`, so a clamped `i64::MAX` would be a
2634    /// fabricated finite duration — see br-frankenpandas-kyd16).
2635    #[must_use]
2636    pub fn ceil(nanos: i64, freq: &str) -> i64 {
2637        if nanos == Self::NAT {
2638            return Self::NAT;
2639        }
2640        let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
2641            return Self::NAT;
2642        };
2643        if unit_nanos == 0 {
2644            return Self::NAT;
2645        }
2646        let remainder = nanos.rem_euclid(unit_nanos);
2647        if remainder == 0 {
2648            nanos
2649        } else {
2650            nanos
2651                .checked_add(unit_nanos - remainder)
2652                .unwrap_or(Self::NAT)
2653        }
2654    }
2655
2656    /// Rounds to the nearest frequency unit.
2657    ///
2658    /// Matches pandas `pd.Timedelta.round(freq)`. Uses banker's rounding
2659    /// (round half to even). NaT is preserved.
2660    #[must_use]
2661    pub fn round(nanos: i64, freq: &str) -> i64 {
2662        if nanos == Self::NAT {
2663            return Self::NAT;
2664        }
2665        let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
2666            return Self::NAT;
2667        };
2668        if unit_nanos == 0 {
2669            return Self::NAT;
2670        }
2671        let negative = nanos < 0;
2672        let abs_nanos = nanos.saturating_abs();
2673
2674        let quotient = abs_nanos / unit_nanos;
2675        let remainder = abs_nanos % unit_nanos;
2676        let half = unit_nanos / 2;
2677
2678        // Round-UP must be checked (br-frankenpandas-kyd16). `quotient *
2679        // unit_nanos` is always <= abs_nanos and cannot overflow, but
2680        // `(quotient + 1) * unit_nanos` can exceed i64::MAX — and this used
2681        // UNCHECKED arithmetic, so it panicked in debug and WRAPPED to a
2682        // large-negative duration in release. pandas raises
2683        // OutOfBoundsTimedelta ("Cannot round ... without overflow"); we
2684        // surface NaT, consistent with the rest of this block.
2685        let round_up = || {
2686            quotient
2687                .checked_add(1)
2688                .and_then(|q| q.checked_mul(unit_nanos))
2689        };
2690        let rounded = if remainder > half {
2691            round_up()
2692        } else if remainder < half {
2693            Some(quotient * unit_nanos)
2694        } else {
2695            // Exactly half: round to even
2696            if quotient % 2 == 0 {
2697                Some(quotient * unit_nanos)
2698            } else {
2699                round_up()
2700            }
2701        };
2702
2703        match rounded {
2704            // Negating is safe: `rounded` is non-negative and at most i64::MAX,
2705            // so `-rounded` is at worst i64::MIN + 1 — never the NaT sentinel.
2706            Some(rounded) => {
2707                if negative {
2708                    -rounded
2709                } else {
2710                    rounded
2711                }
2712            }
2713            None => Self::NAT,
2714        }
2715    }
2716}
2717
2718// ── Timestamp types (br-frankenpandas-9p0u — 4r56 Phase 2) ─────────────
2719//
2720// Nanosecond-precision i64 since Unix epoch + optional IANA tz name.
2721// TZ-dependent arithmetic (DST transitions, tz conversion) is deferred
2722// to Phase 3 which pulls chrono_tz into fp-types; Phase 2 stores the
2723// tz name as opaque metadata and performs arithmetic on the absolute
2724// nanos axis only.
2725
2726/// Number of days in a given month (1-12) of a given year.
2727fn days_in_month(year: i64, month: u32) -> Option<u32> {
2728    if !(1..=12).contains(&month) {
2729        return None;
2730    }
2731    let is_leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
2732    let days: [u32; 12] = [
2733        31,
2734        if is_leap { 29 } else { 28 },
2735        31,
2736        30,
2737        31,
2738        30,
2739        31,
2740        31,
2741        30,
2742        31,
2743        30,
2744        31,
2745    ];
2746    Some(days[(month - 1) as usize])
2747}
2748
2749/// Number of ISO-8601 weeks in a year (52 or 53).
2750///
2751/// A year has 53 ISO weeks iff its first day falls on a Thursday, or it is a
2752/// leap year whose first day is a Wednesday — captured by the dominical
2753/// closed form `p(year) == 4 || p(year - 1) == 3`, where
2754/// `p(y) = (y + ⌊y/4⌋ − ⌊y/100⌋ + ⌊y/400⌋) mod 7` is the weekday of Dec 31.
2755fn iso_weeks_in_year(year: i64) -> i64 {
2756    fn p(y: i64) -> i64 {
2757        (y + y.div_euclid(4) - y.div_euclid(100) + y.div_euclid(400)).rem_euclid(7)
2758    }
2759    if p(year) == 4 || p(year - 1) == 3 {
2760        53
2761    } else {
2762        52
2763    }
2764}
2765
2766/// A nanosecond-precision point in time, Unix-epoch anchored.
2767///
2768/// Phase 2 scope: construction, arithmetic, equality, ordering, serde.
2769/// TZ semantics (IANA tz lookup, DST-aware shift) are deferred to Phase
2770/// 3 — see br-frankenpandas-4r56.
2771#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
2772pub struct Timestamp {
2773    /// Nanoseconds since Unix epoch. `i64::MIN` is NaT.
2774    pub nanos: i64,
2775    /// Optional IANA time-zone name (e.g. `"US/Eastern"`). `None` means
2776    /// naive / UTC-anchored. Phase 2 treats this as opaque metadata;
2777    /// Phase 3 wires chrono_tz interpretation.
2778    #[serde(default, skip_serializing_if = "Option::is_none")]
2779    pub tz: Option<String>,
2780}
2781
2782/// How `astype(str)` renders a `timedelta64[ns]` COLUMN.
2783///
2784/// ⚠️ THE TIMEDELTA LADDER IS NOT THE DATETIME ONE, and copying the sibling
2785/// across is the mistake this type exists to prevent. It has exactly TWO rungs,
2786/// and — unlike [`DatetimeStringResolution`] — THE SUB-SECOND WIDTH IS PER
2787/// VALUE, not per column. MEASURED, live pandas 2.2.3:
2788///
2789/// ```text
2790/// [1 days, 2 days]              -> ['1 days', '2 days']
2791/// [1 days, 5 ms]                -> ['1 days 00:00:00', '0 days 00:00:00.005000']
2792/// [1 days 02:03:04.005, 1 ns]   -> ['1 days 02:03:04.005000',
2793///                                   '0 days 00:00:00.000000001']
2794/// ```
2795///
2796/// That last row is the whole distinction: a millisecond value keeps its SIX
2797/// digits while its neighbour prints NINE. On the datetime side the same pair
2798/// would have been widened to a common nine. So the only column-wide question
2799/// here is whether the time-of-day part can be dropped entirely, which is what
2800/// [`Timedelta::string_resolution`] answers; [`Timedelta::format`] already gets
2801/// the per-value part right and is reused unchanged.
2802#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
2803pub enum TimedeltaStringResolution {
2804    /// `1 days` / `-2 days` / `0 days` — every value is a whole day.
2805    Days,
2806    /// `1 days 02:03:04.005000` — the full rendering, sub-second width per value.
2807    Full,
2808}
2809
2810/// How wide `astype(str)` renders a `datetime64[ns]` value.
2811///
2812/// ⚠️ THIS IS A PROPERTY OF THE COLUMN, NOT OF THE VALUE, which is the whole
2813/// reason it is a separate type rather than a branch inside a per-scalar
2814/// formatter. MEASURED, live pandas 2.2.3 — the SAME midnight timestamp renders
2815/// three different ways depending only on what it shares a column with:
2816///
2817/// ```text
2818/// Series([midnight, midnight]).astype(str)   -> '2024-03-15'
2819/// Series([midnight, one_nanosecond]).astype(str)
2820///                                            -> '2024-03-15 00:00:00.000000000'
2821/// str(Timestamp(midnight))                   -> '2024-03-15 00:00:00'
2822/// ```
2823///
2824/// pandas picks the coarsest rung that is lossless for EVERY element and
2825/// imposes it on all of them. The `Ord` derive is the fold: scan the column
2826/// with `max` over [`Timestamp::string_resolution`], then format every value at
2827/// the winner. Variants are declared coarsest-first so that `max` means
2828/// "finest needed".
2829#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
2830pub enum DatetimeStringResolution {
2831    /// `2024-03-15` — every value in the column is midnight.
2832    Date,
2833    /// `2024-03-15 10:30:45` — every value is a whole second.
2834    Second,
2835    /// `2024-03-15 10:30:45.123`
2836    Milli,
2837    /// `2024-03-15 10:30:45.123456`
2838    Micro,
2839    /// `2024-03-15 10:30:45.123456789`
2840    Nano,
2841}
2842
2843impl Timestamp {
2844    /// NaT sentinel, parallel to `Timedelta::NAT`.
2845    pub const NAT: i64 = i64::MIN;
2846
2847    /// Construct a UTC-anchored (tz=None) Timestamp from nanoseconds
2848    /// since Unix epoch.
2849    #[must_use]
2850    pub const fn from_nanos(nanos: i64) -> Self {
2851        Self { nanos, tz: None }
2852    }
2853
2854    /// Construct a Timestamp tagged with an IANA tz name.
2855    ///
2856    /// Phase 2 doesn't interpret the tz — it only carries the name
2857    /// through arithmetic + serde. Phase 3 wires chrono_tz conversion.
2858    #[must_use]
2859    pub fn from_nanos_tz(nanos: i64, tz_name: impl Into<String>) -> Self {
2860        Self {
2861            nanos,
2862            tz: Some(tz_name.into()),
2863        }
2864    }
2865
2866    /// Returns the current UTC timestamp.
2867    ///
2868    /// ⚠️ THIS MATCHES `pd.Timestamp.utcnow()`, NOT `pd.Timestamp.now()`, and the
2869    /// old doc claimed both. They are different functions: pandas' `now()` returns
2870    /// LOCAL time with no timezone attached, while `utcnow()` returns UTC.
2871    /// MEASURED, live pandas 2.2.3 (CrimsonPine 2026-08-19) on a UTC-4 host:
2872    /// ```text
2873    ///   pd.Timestamp.now()    2026-08-19 07:17:07.266940        tz None
2874    ///   pd.Timestamp.utcnow() 2026-08-19 11:17:07.267100+00:00  tz UTC
2875    ///   difference: 14400 s
2876    /// ```
2877    /// A caller who trusted the old claim and ran on a non-UTC host would be off by
2878    /// their whole UTC offset — four hours here — with no error and no NaT to notice.
2879    /// This crate has no local-timezone concept, so the UTC answer is the only one it
2880    /// can give; only the false half of the claim is removed.
2881    #[must_use]
2882    pub fn now() -> Self {
2883        use std::time::{SystemTime, UNIX_EPOCH};
2884        let duration = SystemTime::now()
2885            .duration_since(UNIX_EPOCH)
2886            .unwrap_or_default();
2887        let nanos = duration.as_nanos() as i64;
2888        Self { nanos, tz: None }
2889    }
2890
2891    /// Alias for `now()`. Matches `pd.Timestamp.utcnow()`.
2892    #[must_use]
2893    pub fn utcnow() -> Self {
2894        Self::now()
2895    }
2896
2897    /// Returns today's date at midnight UTC.
2898    ///
2899    /// Matches `pd.Timestamp.today()`.
2900    #[must_use]
2901    pub fn today() -> Self {
2902        let now = Self::now();
2903        now.normalize()
2904    }
2905
2906    /// The NaT sentinel value for a Timestamp.
2907    #[must_use]
2908    pub const fn nat() -> Self {
2909        Self {
2910            nanos: Self::NAT,
2911            tz: None,
2912        }
2913    }
2914
2915    /// True iff this Timestamp is NaT.
2916    #[must_use]
2917    pub const fn is_nat(&self) -> bool {
2918        self.nanos == Self::NAT
2919    }
2920
2921    /// Nanoseconds since Unix epoch, matching `pd.Timestamp.value`.
2922    #[must_use]
2923    pub const fn value(&self) -> i64 {
2924        self.nanos
2925    }
2926
2927    /// Stored resolution unit, matching `pd.Timestamp.unit`.
2928    ///
2929    /// FrankenPandas `Timestamp` stores nanoseconds internally, so non-NaT
2930    /// values report `ns`. `NaT` has no unit.
2931    #[must_use]
2932    pub const fn unit(&self) -> Option<&'static str> {
2933        if self.is_nat() { None } else { Some("ns") }
2934    }
2935
2936    /// Return the resolution of the timestamp (always "ns" for nanoseconds).
2937    ///
2938    /// Matches `pd.Timestamp.resolution`. Returns None for NaT.
2939    #[must_use]
2940    pub const fn resolution(&self) -> Option<&'static str> {
2941        if self.is_nat() { None } else { Some("ns") }
2942    }
2943
2944    /// Numpy datetime64 scalar payload, matching `pd.Timestamp.asm8`.
2945    #[must_use]
2946    pub const fn asm8(&self) -> i64 {
2947        self.value()
2948    }
2949
2950    /// Convert to a datetime64 payload, matching `pd.Timestamp.to_datetime64()`.
2951    #[must_use]
2952    pub const fn to_datetime64(&self) -> i64 {
2953        self.value()
2954    }
2955
2956    /// Convert to a numpy scalar payload, matching `pd.Timestamp.to_numpy()`.
2957    #[must_use]
2958    pub const fn to_numpy(&self) -> i64 {
2959        self.value()
2960    }
2961
2962    /// POSIX timestamp in seconds, matching `pd.Timestamp.timestamp()`.
2963    ///
2964    /// Pandas exposes this through Python's datetime surface, so sub-microsecond
2965    /// nanoseconds are rounded to six decimal places. `NaT` raises in pandas;
2966    /// fp-types surfaces the same condition as a missing-value error.
2967    pub fn timestamp(&self) -> Result<f64, TypeError> {
2968        if self.is_nat() {
2969            return Err(TypeError::ValueIsMissing {
2970                kind: NullKind::NaT,
2971            });
2972        }
2973        let seconds = self.nanos as f64 / 1_000_000_000.0;
2974        let rounded = format!("{seconds:.6}").parse().unwrap_or(seconds);
2975        Ok(rounded)
2976    }
2977
2978    /// Add a Timedelta. NaT in either operand → NaT; overflow → NaT.
2979    /// TZ is preserved from `self`.
2980    ///
2981    /// Overflow is NaT in both directions (br-frankenpandas-lgyy8) — see the
2982    /// overflow note on [`Timedelta::add`]. A saturated `i64::MAX` would be a
2983    /// finite, plausible ~year-2262 instant returned as if it were real data;
2984    /// `pd.Timestamp.max + pd.Timedelta('1ns')` raises `OutOfBoundsDatetime`.
2985    #[must_use]
2986    pub fn add_timedelta(&self, td_nanos: i64) -> Self {
2987        self.try_add_timedelta(td_nanos)
2988            .unwrap_or_else(|_| Self::nat())
2989    }
2990
2991    /// Shift by a Timedelta, reporting overflow.
2992    ///
2993    /// br-frankenpandas-fyr1z-policy-carrier-f29nz. A NaT operand is
2994    /// propagation, not overflow, so it yields `Ok(nat())`. On overflow the
2995    /// caller gets the error INSTEAD of the tz-dropped NaT; the infallible
2996    /// `add_timedelta` above still produces that NaT, unchanged.
2997    ///
2998    /// # Errors
2999    /// [`PandasTemporalError::OutOfBoundsDatetime`], matching
3000    /// `pd.Timestamp.max + pd.Timedelta('1ns')`.
3001    pub fn try_add_timedelta(&self, td_nanos: i64) -> Result<Self, TemporalFailure> {
3002        if self.is_nat() || td_nanos == Timedelta::NAT {
3003            return Ok(Self::nat());
3004        }
3005        match self.nanos.checked_add(td_nanos) {
3006            Some(nanos) => Ok(Self {
3007                nanos,
3008                tz: self.tz.clone(),
3009            }),
3010            // Overflow drops the tz with the value: an out-of-range instant has
3011            // no zone, and `Self::nat()` is the one canonical NaT (matching the
3012            // NaT-operand arms above, which also return an untagged NaT).
3013            None => Err(TemporalFailure::new(
3014                "Timestamp::add_timedelta",
3015                PandasTemporalError::OutOfBoundsDatetime,
3016            )
3017            .with_operands(self.nanos, td_nanos)),
3018        }
3019    }
3020
3021    /// Subtract a Timedelta. NaT propagation; overflow → NaT. TZ preserved.
3022    #[must_use]
3023    pub fn sub_timedelta(&self, td_nanos: i64) -> Self {
3024        self.try_sub_timedelta(td_nanos)
3025            .unwrap_or_else(|_| Self::nat())
3026    }
3027
3028    /// Shift back by a Timedelta, reporting overflow. See
3029    /// [`Self::try_add_timedelta`].
3030    ///
3031    /// # Errors
3032    /// [`PandasTemporalError::OutOfBoundsDatetime`].
3033    pub fn try_sub_timedelta(&self, td_nanos: i64) -> Result<Self, TemporalFailure> {
3034        if self.is_nat() || td_nanos == Timedelta::NAT {
3035            return Ok(Self::nat());
3036        }
3037        match self.nanos.checked_sub(td_nanos) {
3038            Some(nanos) => Ok(Self {
3039                nanos,
3040                tz: self.tz.clone(),
3041            }),
3042            None => Err(TemporalFailure::new(
3043                "Timestamp::sub_timedelta",
3044                PandasTemporalError::OutOfBoundsDatetime,
3045            )
3046            .with_operands(self.nanos, td_nanos)),
3047        }
3048    }
3049
3050    /// Subtract another Timestamp. Returns a Timedelta (i64 nanos).
3051    /// NaT in either → `Timedelta::NAT`; overflow → `Timedelta::NAT`
3052    /// (`pd.Timestamp.min - pd.Timestamp.max` raises `OutOfBoundsDatetime`).
3053    #[must_use]
3054    pub fn sub_timestamp(&self, other: &Self) -> i64 {
3055        self.try_sub_timestamp(other).unwrap_or(Timedelta::NAT)
3056    }
3057
3058    /// Elapsed nanoseconds between two Timestamps, reporting overflow.
3059    ///
3060    /// # Errors
3061    /// [`PandasTemporalError::OutOfBoundsDatetime`], matching
3062    /// `pd.Timestamp.min - pd.Timestamp.max`.
3063    pub fn try_sub_timestamp(&self, other: &Self) -> Result<i64, TemporalFailure> {
3064        if self.is_nat() || other.is_nat() {
3065            return Ok(Timedelta::NAT);
3066        }
3067        self.nanos.checked_sub(other.nanos).ok_or(
3068            TemporalFailure::new(
3069                "Timestamp::sub_timestamp",
3070                PandasTemporalError::OutOfBoundsDatetime,
3071            )
3072            .with_operands(self.nanos, other.nanos),
3073        )
3074    }
3075
3076    /// NaT-aware semantic equality: two NaT Timestamps are equal to each
3077    /// other (matches pandas `pd.NaT == pd.NaT` under `equals()`, though
3078    /// pandas's `==` operator returns False for NaT==NaT — we follow the
3079    /// `semantic_eq` convention used elsewhere in fp-types).
3080    #[must_use]
3081    pub fn semantic_eq(&self, other: &Self) -> bool {
3082        if self.is_nat() && other.is_nat() {
3083            return true;
3084        }
3085        if self.is_nat() || other.is_nat() {
3086            return false;
3087        }
3088        self.nanos == other.nanos && self.tz == other.tz
3089    }
3090
3091    // ── Rounding to a Timedelta unit (br-frankenpandas-5h6n) ────────────
3092    //
3093    // Pure i64 arithmetic on the nanos axis. tz is preserved. Phase 3
3094    // chrono_tz integration will add a tz-aware variant that handles DST
3095    // boundaries correctly; these methods operate on the absolute time
3096    // axis, matching pandas's tz-naive `.floor` / `.ceil` / `.round`
3097    // semantics for unit values smaller than a day.
3098
3099    /// Round down to the nearest multiple of `unit_nanos`.
3100    ///
3101    /// Matches `pd.Timestamp(...).floor(unit)`. NaT in `self` or a
3102    /// non-positive `unit_nanos` returns NaT.
3103    #[must_use]
3104    pub fn floor_to(&self, unit_nanos: i64) -> Self {
3105        if self.is_nat() || unit_nanos <= 0 {
3106            return Self::nat();
3107        }
3108        let Some(nanos) = self.nanos.div_euclid(unit_nanos).checked_mul(unit_nanos) else {
3109            return Self::nat();
3110        };
3111        Self {
3112            nanos,
3113            tz: self.tz.clone(),
3114        }
3115    }
3116
3117    /// Round up to the nearest multiple of `unit_nanos`.
3118    ///
3119    /// Matches `pd.Timestamp(...).ceil(unit)`. NaT or non-positive
3120    /// `unit_nanos` returns NaT. Already-multiple inputs return self.
3121    #[must_use]
3122    pub fn ceil_to(&self, unit_nanos: i64) -> Self {
3123        if self.is_nat() || unit_nanos <= 0 {
3124            return Self::nat();
3125        }
3126        let rem = self.nanos.rem_euclid(unit_nanos);
3127        let nanos = if rem == 0 {
3128            self.nanos
3129        } else {
3130            // Checked, matching the sibling `floor_to` directly above
3131            // (br-frankenpandas-kyd16). A clamped i64::MAX would be a finite,
3132            // plausible ~year-2262 instant; `pd.Timestamp.max.ceil('D')`
3133            // raises OutOfBoundsDatetime "Cannot round ... without overflow".
3134            let Some(nanos) = self.nanos.checked_add(unit_nanos - rem) else {
3135                return Self::nat();
3136            };
3137            nanos
3138        };
3139        Self {
3140            nanos,
3141            tz: self.tz.clone(),
3142        }
3143    }
3144
3145    /// Round to the nearest multiple of `unit_nanos`, banker's rounding
3146    /// (half-to-even) on ties.
3147    ///
3148    /// Matches `pd.Timestamp(...).round(unit)`. NaT or non-positive
3149    /// `unit_nanos` returns NaT.
3150    #[must_use]
3151    pub fn round_to(&self, unit_nanos: i64) -> Self {
3152        if self.is_nat() || unit_nanos <= 0 {
3153            return Self::nat();
3154        }
3155        let floor = self.nanos.div_euclid(unit_nanos);
3156        let rem = self.nanos.rem_euclid(unit_nanos);
3157        let half = unit_nanos / 2;
3158        let chosen_floor = if rem < half {
3159            floor
3160        } else if rem > half {
3161            floor + 1
3162        } else if unit_nanos % 2 != 0 {
3163            // Odd unit can't have a true half; treat as round-up.
3164            floor + 1
3165        } else {
3166            // Tie: pick the even multiple.
3167            if floor % 2 == 0 { floor } else { floor + 1 }
3168        };
3169        // Checked, matching the sibling `floor_to` (br-frankenpandas-kyd16):
3170        // `pd.Timestamp.max.round('D')` raises OutOfBoundsDatetime rather than
3171        // returning the clamped i64::MAX instant.
3172        let Some(nanos) = chosen_floor.checked_mul(unit_nanos) else {
3173            return Self::nat();
3174        };
3175        Self {
3176            nanos,
3177            tz: self.tz.clone(),
3178        }
3179    }
3180
3181    // ── String-unit rounding (br-frankenpandas-lbsx) ────────────────────
3182    //
3183    // Pandas convenience: `.floor('H')` / `.ceil('1D')` / `.round('s')`.
3184    // These delegate to `Timedelta::unit_to_nanos` for unit lookup, then to
3185    // the nanos-based `floor_to`/`ceil_to`/`round_to`. Unknown unit strings
3186    // return NaT, matching the rest of fp-types' "missing-input → missing-
3187    // output" convention.
3188
3189    /// Round down to the nearest multiple of the named unit.
3190    ///
3191    /// Matches `pd.Timestamp(...).floor(unit)`. Unknown unit → NaT.
3192    #[must_use]
3193    pub fn floor_to_unit(&self, unit: &str) -> Self {
3194        match Timedelta::unit_to_nanos(unit) {
3195            Some(unit_nanos) => self.floor_to(unit_nanos),
3196            None => Self::nat(),
3197        }
3198    }
3199
3200    /// Round up to the nearest multiple of the named unit.
3201    ///
3202    /// Matches `pd.Timestamp(...).ceil(unit)`. Unknown unit → NaT.
3203    #[must_use]
3204    pub fn ceil_to_unit(&self, unit: &str) -> Self {
3205        match Timedelta::unit_to_nanos(unit) {
3206            Some(unit_nanos) => self.ceil_to(unit_nanos),
3207            None => Self::nat(),
3208        }
3209    }
3210
3211    /// Round to the nearest multiple of the named unit, banker's rounding.
3212    ///
3213    /// Matches `pd.Timestamp(...).round(unit)`. Unknown unit → NaT.
3214    #[must_use]
3215    pub fn round_to_unit(&self, unit: &str) -> Self {
3216        match Timedelta::unit_to_nanos(unit) {
3217            Some(unit_nanos) => self.round_to(unit_nanos),
3218            None => Self::nat(),
3219        }
3220    }
3221
3222    /// Pandas-named alias for [`floor_to_unit`](Self::floor_to_unit).
3223    #[must_use]
3224    pub fn floor(&self, freq: &str) -> Self {
3225        self.floor_to_unit(freq)
3226    }
3227
3228    /// Pandas-named alias for [`ceil_to_unit`](Self::ceil_to_unit).
3229    #[must_use]
3230    pub fn ceil(&self, freq: &str) -> Self {
3231        self.ceil_to_unit(freq)
3232    }
3233
3234    /// Pandas-named alias for [`round_to_unit`](Self::round_to_unit).
3235    #[must_use]
3236    pub fn round(&self, freq: &str) -> Self {
3237        self.round_to_unit(freq)
3238    }
3239
3240    /// Extract the year component from the timestamp.
3241    ///
3242    /// Matches `pd.Timestamp.year`. Returns None for NaT.
3243    #[must_use]
3244    pub fn year(&self) -> Option<i64> {
3245        if self.is_nat() {
3246            return None;
3247        }
3248        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
3249        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
3250        // for the post-1970 positive case.
3251        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
3252        let days = days_since_epoch + 719_468;
3253        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
3254        let doe = days - era * 146_097;
3255        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
3256        let y = yoe + era * 400;
3257        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
3258        let mp = (5 * doy + 2) / 153;
3259        let m = if mp < 10 { mp + 3 } else { mp - 9 };
3260        Some(if m <= 2 { y + 1 } else { y })
3261    }
3262
3263    /// Extract the month component (1-12) from the timestamp.
3264    ///
3265    /// Matches `pd.Timestamp.month`. Returns None for NaT.
3266    #[must_use]
3267    pub fn month(&self) -> Option<i64> {
3268        if self.is_nat() {
3269            return None;
3270        }
3271        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
3272        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
3273        // for the post-1970 positive case.
3274        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
3275        let days = days_since_epoch + 719_468;
3276        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
3277        let doe = days - era * 146_097;
3278        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
3279        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
3280        let mp = (5 * doy + 2) / 153;
3281        Some(if mp < 10 { mp + 3 } else { mp - 9 })
3282    }
3283
3284    /// Extract the day component (1-31) from the timestamp.
3285    ///
3286    /// Matches `pd.Timestamp.day`. Returns None for NaT.
3287    #[must_use]
3288    pub fn day(&self) -> Option<i64> {
3289        if self.is_nat() {
3290            return None;
3291        }
3292        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
3293        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
3294        // for the post-1970 positive case.
3295        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
3296        let days = days_since_epoch + 719_468;
3297        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
3298        let doe = days - era * 146_097;
3299        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
3300        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
3301        let mp = (5 * doy + 2) / 153;
3302        Some(doy - (153 * mp + 2) / 5 + 1)
3303    }
3304
3305    /// Extract the hour component (0-23) from the timestamp.
3306    ///
3307    /// Matches `pd.Timestamp.hour`. Returns None for NaT.
3308    #[must_use]
3309    pub fn hour(&self) -> Option<i64> {
3310        if self.is_nat() {
3311            return None;
3312        }
3313        // rem_euclid keeps the seconds-of-day in [0, 86400) even for negative
3314        // (pre-1970) nanos with a sub-second part (br-frankenpandas-wkjtw);
3315        // rem_euclid == `%` for the post-1970 positive case.
3316        let secs_of_day =
3317            self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
3318        Some(secs_of_day / 3600)
3319    }
3320
3321    /// Extract the minute component (0-59) from the timestamp.
3322    ///
3323    /// Matches `pd.Timestamp.minute`. Returns None for NaT.
3324    #[must_use]
3325    pub fn minute(&self) -> Option<i64> {
3326        if self.is_nat() {
3327            return None;
3328        }
3329        // rem_euclid keeps the seconds-of-day in [0, 86400) even for negative
3330        // (pre-1970) nanos with a sub-second part (br-frankenpandas-wkjtw);
3331        // rem_euclid == `%` for the post-1970 positive case.
3332        let secs_of_day =
3333            self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
3334        Some((secs_of_day % 3600) / 60)
3335    }
3336
3337    /// Extract the second component (0-59) from the timestamp.
3338    ///
3339    /// Matches `pd.Timestamp.second`. Returns None for NaT.
3340    #[must_use]
3341    pub fn second(&self) -> Option<i64> {
3342        if self.is_nat() {
3343            return None;
3344        }
3345        // rem_euclid keeps the seconds-of-day in [0, 86400) even for negative
3346        // (pre-1970) nanos with a sub-second part (br-frankenpandas-wkjtw);
3347        // rem_euclid == `%` for the post-1970 positive case.
3348        let secs_of_day =
3349            self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
3350        Some(secs_of_day % 60)
3351    }
3352
3353    /// Extract the microsecond component (0-999999) from the timestamp.
3354    ///
3355    /// Matches `pd.Timestamp.microsecond`. Returns None for NaT.
3356    #[must_use]
3357    pub fn microsecond(&self) -> Option<i64> {
3358        if self.is_nat() {
3359            return None;
3360        }
3361        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos
3362        // (br-frankenpandas-wkjtw); == `%` for the post-1970 positive case.
3363        let sub_nanos = self.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
3364        Some((sub_nanos / 1000) as i64)
3365    }
3366
3367    /// Extract the nanosecond component (0-999) from the timestamp.
3368    ///
3369    /// Matches `pd.Timestamp.nanosecond`. Returns None for NaT.
3370    #[must_use]
3371    pub fn nanosecond(&self) -> Option<i64> {
3372        if self.is_nat() {
3373            return None;
3374        }
3375        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos
3376        // (br-frankenpandas-wkjtw); == `%` for the post-1970 positive case.
3377        let sub_nanos = self.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
3378        Some((sub_nanos % 1000) as i64)
3379    }
3380
3381    /// Return the day of the week (Monday=0, Sunday=6).
3382    ///
3383    /// Matches `pd.Timestamp.dayofweek`. Returns None for NaT.
3384    #[must_use]
3385    pub fn dayofweek(&self) -> Option<i64> {
3386        if self.is_nat() {
3387            return None;
3388        }
3389        // Floor days for pre-1970 (br-frankenpandas-wkjtw); == `/` for positive.
3390        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
3391        let dow = ((days_since_epoch + 3) % 7 + 7) % 7;
3392        Some(dow)
3393    }
3394
3395    /// Alias for dayofweek(). Matches `pd.Timestamp.weekday`.
3396    #[must_use]
3397    pub fn weekday(&self) -> Option<i64> {
3398        self.dayofweek()
3399    }
3400
3401    /// Alias for dayofweek(). Matches `pd.Timestamp.day_of_week`.
3402    #[must_use]
3403    pub fn day_of_week(&self) -> Option<i64> {
3404        self.dayofweek()
3405    }
3406
3407    /// Return the day of the year (1-366).
3408    ///
3409    /// Matches `pd.Timestamp.dayofyear`. Returns None for NaT.
3410    #[must_use]
3411    pub fn dayofyear(&self) -> Option<i64> {
3412        if self.is_nat() {
3413            return None;
3414        }
3415        let m = self.month()?;
3416        let d = self.day()?;
3417        let y = self.year()?;
3418        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
3419        let days_before: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
3420        let base = days_before[(m - 1) as usize] + d;
3421        if is_leap && m > 2 {
3422            Some(base + 1)
3423        } else {
3424            Some(base)
3425        }
3426    }
3427
3428    /// Alias for dayofyear(). Matches `pd.Timestamp.day_of_year`.
3429    #[must_use]
3430    pub fn day_of_year(&self) -> Option<i64> {
3431        self.dayofyear()
3432    }
3433
3434    /// Return the proleptic Gregorian ordinal (number of days since Jan 1, year 1).
3435    ///
3436    /// Matches `pd.Timestamp.toordinal()`. Returns None for NaT.
3437    #[must_use]
3438    pub fn toordinal(&self) -> Option<i64> {
3439        if self.is_nat() {
3440            return None;
3441        }
3442        let y = self.year()?;
3443        let m = self.month()?;
3444        let d = self.day()?;
3445        // Algorithm: count days from year 1 to the start of the given year,
3446        // add days in the months before the given month, add the day of month.
3447        // Account for leap years.
3448        let y_minus_1 = y - 1;
3449        let mut ordinal = y_minus_1 * 365 + y_minus_1 / 4 - y_minus_1 / 100 + y_minus_1 / 400;
3450        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
3451        let days_before: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
3452        ordinal += days_before[(m - 1) as usize];
3453        if is_leap && m > 2 {
3454            ordinal += 1;
3455        }
3456        ordinal += d;
3457        Some(ordinal)
3458    }
3459
3460    /// Construct a Timestamp from a proleptic Gregorian ordinal.
3461    ///
3462    /// Matches `pd.Timestamp.fromordinal(ordinal)`. Returns NaT for invalid ordinals.
3463    #[must_use]
3464    pub fn fromordinal(ordinal: i64) -> Self {
3465        if ordinal <= 0 {
3466            return Self {
3467                nanos: Self::NAT,
3468                tz: None,
3469            };
3470        }
3471        // Convert y/m/d to days since Unix epoch, then to nanos
3472        // Unix epoch is 1970-01-01, which is ordinal 719163
3473        let days_since_epoch = ordinal - 719163;
3474        match days_since_epoch.checked_mul(Timedelta::NANOS_PER_DAY) {
3475            Some(nanos) => Self { nanos, tz: None },
3476            None => Self::nat(),
3477        }
3478    }
3479
3480    /// Return the Julian Date (astronomical day number).
3481    ///
3482    /// Matches `pd.Timestamp.to_julian_date()`. Returns NaN for NaT.
3483    /// The Julian Date is the continuous count of days since the beginning
3484    /// of the Julian Period (January 1, 4713 BC in the proleptic Julian calendar).
3485    #[must_use]
3486    pub fn to_julian_date(&self) -> f64 {
3487        if self.is_nat() {
3488            return f64::NAN;
3489        }
3490        // Gregorian ordinal 1 (Jan 1, year 1) corresponds to Julian Day 1721425.5
3491        // (at noon, since JD starts at noon)
3492        // For a timestamp at midnight, we subtract 0.5
3493        let ordinal = match self.toordinal() {
3494            Some(o) => o,
3495            None => return f64::NAN,
3496        };
3497        // Fractional day from time components
3498        let h = self.hour().unwrap_or(0) as f64;
3499        let m = self.minute().unwrap_or(0) as f64;
3500        let s = self.second().unwrap_or(0) as f64;
3501        let us = self.microsecond().unwrap_or(0) as f64;
3502        let ns = self.nanosecond().unwrap_or(0) as f64;
3503        let frac_day =
3504            (h + m / 60.0 + s / 3600.0 + us / 3_600_000_000.0 + ns / 3_600_000_000_000.0) / 24.0;
3505        // Julian day at midnight of ordinal 1 is 1721424.5
3506        1721424.5 + ordinal as f64 + frac_day
3507    }
3508
3509    /// Return the quarter (1-4) of the year.
3510    ///
3511    /// Matches `pd.Timestamp.quarter`. Returns None for NaT.
3512    #[must_use]
3513    pub fn quarter(&self) -> Option<i64> {
3514        self.month().map(|m| (m - 1) / 3 + 1)
3515    }
3516
3517    /// Return the ISO week number (1-53).
3518    ///
3519    /// Matches `pd.Timestamp.week`. Returns None for NaT.
3520    #[must_use]
3521    pub fn weekofyear(&self) -> Option<i64> {
3522        if self.is_nat() {
3523            return None;
3524        }
3525        let doy = self.dayofyear()?;
3526        let dow = self.dayofweek()?;
3527        let year = self.year()?;
3528        let iso_dow = if dow == 6 { 7 } else { dow + 1 };
3529        let week = (doy - iso_dow + 10) / 7;
3530        // ISO-8601 has 53-week years, so the clamps must consult the actual
3531        // week count, not hardcode 52/1: a week<1 belongs to the LAST week of
3532        // the previous year (52 OR 53), and a week beyond this year's count
3533        // wraps to week 1 of the next year. pandas isocalendar().week agrees:
3534        // 2021-01-01 -> 53 (2020 is a 53-week year), 2026-12-31 -> 53.
3535        if week < 1 {
3536            Some(iso_weeks_in_year(year - 1))
3537        } else if week > iso_weeks_in_year(year) {
3538            Some(1)
3539        } else {
3540            Some(week)
3541        }
3542    }
3543
3544    /// Alias for weekofyear(). Matches `pd.Timestamp.week`.
3545    #[must_use]
3546    pub fn week(&self) -> Option<i64> {
3547        self.weekofyear()
3548    }
3549
3550    /// Return the timestamp value in the specified unit.
3551    ///
3552    /// Matches `pd.Timestamp.value` when unit is nanoseconds.
3553    /// Supported units: "ns", "us", "ms", "s".
3554    #[must_use]
3555    pub fn to_unit(&self, unit: &str) -> Option<i64> {
3556        if self.is_nat() {
3557            return None;
3558        }
3559        match unit {
3560            "ns" | "nanosecond" | "nanoseconds" => Some(self.nanos),
3561            "us" | "microsecond" | "microseconds" => Some(self.nanos / 1_000),
3562            "ms" | "millisecond" | "milliseconds" => Some(self.nanos / 1_000_000),
3563            "s" | "second" | "seconds" => Some(self.nanos / 1_000_000_000),
3564            _ => None,
3565        }
3566    }
3567
3568    /// Whether the year is a leap year.
3569    ///
3570    /// Matches `pd.Timestamp.is_leap_year`. Returns None for NaT.
3571    #[must_use]
3572    pub fn is_leap_year(&self) -> Option<bool> {
3573        self.year()
3574            .map(|y| (y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
3575    }
3576
3577    /// Whether the day is the first day of the month.
3578    ///
3579    /// Matches `pd.Timestamp.is_month_start`. Returns None for NaT.
3580    #[must_use]
3581    pub fn is_month_start(&self) -> Option<bool> {
3582        self.day().map(|d| d == 1)
3583    }
3584
3585    /// Whether the day is the last day of the month.
3586    ///
3587    /// Matches `pd.Timestamp.is_month_end`. Returns None for NaT.
3588    #[must_use]
3589    pub fn is_month_end(&self) -> Option<bool> {
3590        let y = self.year()?;
3591        let m = self.month()?;
3592        let d = self.day()?;
3593        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
3594        let days_in_month: [i64; 12] = [
3595            31,
3596            if is_leap { 29 } else { 28 },
3597            31,
3598            30,
3599            31,
3600            30,
3601            31,
3602            31,
3603            30,
3604            31,
3605            30,
3606            31,
3607        ];
3608        Some(d == days_in_month[(m - 1) as usize])
3609    }
3610
3611    /// Whether the day is the first day of a quarter.
3612    ///
3613    /// Matches `pd.Timestamp.is_quarter_start`. Returns None for NaT.
3614    #[must_use]
3615    pub fn is_quarter_start(&self) -> Option<bool> {
3616        let m = self.month()?;
3617        let d = self.day()?;
3618        Some(d == 1 && (m == 1 || m == 4 || m == 7 || m == 10))
3619    }
3620
3621    /// Whether the day is the last day of a quarter.
3622    ///
3623    /// Matches `pd.Timestamp.is_quarter_end`. Returns None for NaT.
3624    #[must_use]
3625    pub fn is_quarter_end(&self) -> Option<bool> {
3626        let m = self.month()?;
3627        let d = self.day()?;
3628        Some(
3629            (m == 3 && d == 31)
3630                || (m == 6 && d == 30)
3631                || (m == 9 && d == 30)
3632                || (m == 12 && d == 31),
3633        )
3634    }
3635
3636    /// Whether the day is the first day of the year (Jan 1).
3637    ///
3638    /// Matches `pd.Timestamp.is_year_start`. Returns None for NaT.
3639    #[must_use]
3640    pub fn is_year_start(&self) -> Option<bool> {
3641        let m = self.month()?;
3642        let d = self.day()?;
3643        Some(m == 1 && d == 1)
3644    }
3645
3646    /// Whether the day is the last day of the year (Dec 31).
3647    ///
3648    /// Matches `pd.Timestamp.is_year_end`. Returns None for NaT.
3649    #[must_use]
3650    pub fn is_year_end(&self) -> Option<bool> {
3651        let m = self.month()?;
3652        let d = self.day()?;
3653        Some(m == 12 && d == 31)
3654    }
3655
3656    /// Return the number of days in the month of this timestamp.
3657    ///
3658    /// Matches `pd.Timestamp.days_in_month`. Returns None for NaT.
3659    #[must_use]
3660    pub fn days_in_month(&self) -> Option<i64> {
3661        let y = self.year()?;
3662        let m = self.month()?;
3663        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
3664        let days: [i64; 12] = [
3665            31,
3666            if is_leap { 29 } else { 28 },
3667            31,
3668            30,
3669            31,
3670            30,
3671            31,
3672            31,
3673            30,
3674            31,
3675            30,
3676            31,
3677        ];
3678        Some(days[(m - 1) as usize])
3679    }
3680
3681    /// Alias for days_in_month(). Matches `pd.Timestamp.daysinmonth`.
3682    #[must_use]
3683    pub fn daysinmonth(&self) -> Option<i64> {
3684        self.days_in_month()
3685    }
3686
3687    /// Normalize to midnight/day boundary, matching `pd.Timestamp.normalize()`.
3688    #[must_use]
3689    pub fn normalize(&self) -> Self {
3690        self.floor_to(Timedelta::NANOS_PER_DAY)
3691    }
3692
3693    /// Replace timestamp components with new values.
3694    ///
3695    /// Matches pd.Timestamp.replace(). None values keep the existing component.
3696    #[must_use]
3697    #[allow(clippy::too_many_arguments)]
3698    pub fn replace(
3699        &self,
3700        year: Option<i64>,
3701        month: Option<i64>,
3702        day: Option<i64>,
3703        hour: Option<i64>,
3704        minute: Option<i64>,
3705        second: Option<i64>,
3706        microsecond: Option<i64>,
3707        nanosecond: Option<i64>,
3708    ) -> Self {
3709        if self.is_nat() {
3710            return self.clone();
3711        }
3712        let cur_year = self.year().unwrap_or(1970);
3713        let cur_month = self.month().unwrap_or(1);
3714        let cur_day = self.day().unwrap_or(1);
3715        let cur_hour = self.hour().unwrap_or(0);
3716        let cur_minute = self.minute().unwrap_or(0);
3717        let cur_second = self.second().unwrap_or(0);
3718        let cur_micro = self.microsecond().unwrap_or(0);
3719        let cur_nano = self.nanosecond().unwrap_or(0);
3720
3721        let y = year.unwrap_or(cur_year);
3722        let mo = month.unwrap_or(cur_month);
3723        let d = day.unwrap_or(cur_day);
3724        let h = hour.unwrap_or(cur_hour);
3725        let mi = minute.unwrap_or(cur_minute);
3726        let s = second.unwrap_or(cur_second);
3727        let us = microsecond.unwrap_or(cur_micro);
3728        let ns = nanosecond.unwrap_or(cur_nano);
3729
3730        if !(1..=12).contains(&mo)
3731            || !(1..=days_in_month(y, mo as u32).unwrap_or(0) as i64).contains(&d)
3732            || !(0..=23).contains(&h)
3733            || !(0..=59).contains(&mi)
3734            || !(0..=59).contains(&s)
3735            || !(0..=999_999).contains(&us)
3736            || !(0..=999).contains(&ns)
3737        {
3738            return Self::nat();
3739        }
3740
3741        // Checked nanosecond arithmetic (br-frankenpandas-dzz6x). The component
3742        // validation above rejects an out-of-range month/day/hour/... but says
3743        // nothing about the YEAR, and i64 nanoseconds run out at
3744        // `i64::MAX / NANOS_PER_DAY` = 106_751 days from the epoch — about year
3745        // 2262, the same bound pandas documents for ns-resolution Timestamps.
3746        // Unchecked, `replace(year=3000)` wrapped in release mode and returned a
3747        // silently wrong, plausible-looking in-range instant. Overflow now folds
3748        // to NaT, matching both the validation arm above and the sibling
3749        // constructors `fromordinal` / `floor_to`, which already fail this way.
3750        // In-range results are unchanged: the checked ops return exactly the
3751        // value the plain operators produced whenever no overflow occurred.
3752        let days_from_epoch = Self::days_from_ymd(y, mo, d);
3753        let secs = h * 3600 + mi * 60 + s;
3754        let Some(total_nanos) = days_from_epoch
3755            .checked_mul(Timedelta::NANOS_PER_DAY)
3756            .and_then(|nanos| {
3757                secs.checked_mul(Timedelta::NANOS_PER_SEC)
3758                    .and_then(|s_nanos| nanos.checked_add(s_nanos))
3759            })
3760            .and_then(|nanos| {
3761                us.checked_mul(Timedelta::NANOS_PER_MICRO)
3762                    .and_then(|us_nanos| nanos.checked_add(us_nanos))
3763            })
3764            .and_then(|nanos| nanos.checked_add(ns))
3765        else {
3766            return Self::nat();
3767        };
3768
3769        Self {
3770            nanos: total_nanos,
3771            tz: self.tz.clone(),
3772        }
3773    }
3774
3775    fn days_from_ymd(year: i64, month: i64, day: i64) -> i64 {
3776        let y = if month <= 2 { year - 1 } else { year };
3777        let era = if y >= 0 { y } else { y - 399 } / 400;
3778        let yoe = y - era * 400;
3779        let doy = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1;
3780        let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
3781        era * 146097 + doe - 719468
3782    }
3783
3784    /// Return an ISO 8601 string representation of the timestamp.
3785    ///
3786    /// Matches `pd.Timestamp.isoformat()`. NaT returns "NaT".
3787    #[must_use]
3788    pub fn isoformat(&self) -> String {
3789        use std::fmt::Write as _;
3790
3791        if self.is_nat() {
3792            return "NaT".to_string();
3793        }
3794        let display_nanos = self
3795            .tz
3796            .as_deref()
3797            .and_then(Self::fixed_utc_offset_seconds)
3798            .and_then(|offset| self.nanos.checked_add(offset * Timedelta::NANOS_PER_SEC))
3799            .unwrap_or(self.nanos);
3800        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos
3801        // (br-frankenpandas-wkjtw); == `%` for the post-1970 positive case.
3802        let days_since_epoch = display_nanos.div_euclid(Timedelta::NANOS_PER_DAY);
3803        let nanos_of_day = display_nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
3804        let secs_of_day = nanos_of_day / Timedelta::NANOS_PER_SEC;
3805        let sub_nanos = nanos_of_day.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
3806
3807        let days = days_since_epoch + 719_468;
3808        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
3809        let doe = days - era * 146_097;
3810        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
3811        let y = yoe + era * 400;
3812        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
3813        let mp = (5 * doy + 2) / 153;
3814        let d = doy - (153 * mp + 2) / 5 + 1;
3815        let m = if mp < 10 { mp + 3 } else { mp - 9 };
3816        let year = if m <= 2 { y + 1 } else { y };
3817
3818        let hour = secs_of_day / 3600;
3819        let minute = (secs_of_day % 3600) / 60;
3820        let second = secs_of_day % 60;
3821
3822        // Build the timestamp and its optional timezone suffix in the returned
3823        // allocation. The former timezone-aware path first allocated `base`,
3824        // then allocated again to copy `base` into the suffixed result.
3825        let suffix_capacity = self
3826            .tz
3827            .as_ref()
3828            .map_or(0, |tz| if tz == "UTC" { 6 } else { tz.len() + 2 });
3829        let mut result = String::with_capacity(29 + suffix_capacity);
3830        if sub_nanos == 0 {
3831            let _ = write!(
3832                result,
3833                "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}"
3834            );
3835        } else if sub_nanos.is_multiple_of(1_000) {
3836            let _ = write!(
3837                result,
3838                "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{:06}",
3839                sub_nanos / 1_000
3840            );
3841        } else {
3842            let _ = write!(
3843                result,
3844                "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{sub_nanos:09}"
3845            );
3846        }
3847        match &self.tz {
3848            Some(tz) if tz == "UTC" => result.push_str("+00:00"),
3849            Some(tz) if Self::fixed_utc_offset_seconds(tz).is_some() => {
3850                result.push_str(tz.strip_prefix("UTC").unwrap_or(tz));
3851            }
3852            Some(tz) => {
3853                result.push('[');
3854                result.push_str(tz);
3855                result.push(']');
3856            }
3857            None => {}
3858        }
3859        result
3860    }
3861
3862    /// Alias for isoformat.
3863    #[must_use]
3864    pub fn to_iso8601(&self) -> String {
3865        self.isoformat()
3866    }
3867
3868    /// The coarsest [`DatetimeStringResolution`] that renders `nanos` losslessly.
3869    ///
3870    /// Fold this over a column with `max` to get the column's width — see
3871    /// [`DatetimeStringResolution`] for why the width is a property of the
3872    /// COLUMN and not of the value. `NaT` reports [`DatetimeStringResolution`]
3873    /// `::Date`, the identity for that fold, because pandas excludes it from the
3874    /// scan entirely: a column of one midnight plus one NaT still renders
3875    /// `['2024-03-15', 'NaT']`.
3876    #[must_use]
3877    pub const fn string_resolution(nanos: i64) -> DatetimeStringResolution {
3878        if nanos == Self::NAT {
3879            return DatetimeStringResolution::Date;
3880        }
3881        if nanos.rem_euclid(Timedelta::NANOS_PER_DAY) == 0 {
3882            DatetimeStringResolution::Date
3883        } else if nanos.rem_euclid(Timedelta::NANOS_PER_SEC) == 0 {
3884            DatetimeStringResolution::Second
3885        } else if nanos.rem_euclid(Timedelta::NANOS_PER_MILLI) == 0 {
3886            DatetimeStringResolution::Milli
3887        } else if nanos.rem_euclid(Timedelta::NANOS_PER_MICRO) == 0 {
3888            DatetimeStringResolution::Micro
3889        } else {
3890            DatetimeStringResolution::Nano
3891        }
3892    }
3893
3894    /// Render `nanos` the way `astype(str)` does, at a resolution chosen for the
3895    /// whole column by [`Self::string_resolution`].
3896    ///
3897    /// ⚠️ NOT [`Self::isoformat`]. That one is `pd.Timestamp.isoformat()` — a `T`
3898    /// separator, and a width chosen per VALUE. This is the array formatter:
3899    /// a SPACE separator, and a width imposed on every element alike. MEASURED,
3900    /// live pandas 2.2.3, one column per rung:
3901    ///
3902    /// ```text
3903    /// all midnight       -> '2024-03-15'
3904    /// all whole seconds  -> '2024-03-15 10:30:45'
3905    /// all whole millis   -> '2024-03-15 10:30:45.123'
3906    /// all whole micros   -> '2024-03-15 10:30:45.123456'
3907    /// anything finer     -> '2024-03-15 10:30:45.123456789'
3908    /// NaT                -> 'NaT'          (a STRING, not a missing value)
3909    /// ```
3910    ///
3911    /// There is NO minute rung: a column of whole minutes still renders its
3912    /// seconds (`'2024-01-01 00:05:00'`).
3913    #[must_use]
3914    pub fn format_at_resolution(nanos: i64, resolution: DatetimeStringResolution) -> String {
3915        use std::fmt::Write as _;
3916
3917        if nanos == Self::NAT {
3918            return "NaT".to_string();
3919        }
3920        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos,
3921        // the same correction isoformat makes (br-frankenpandas-wkjtw): a
3922        // pre-epoch value must render 1969-12-31 23:59:59.999999999, not a
3923        // negative fraction.
3924        let days_since_epoch = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
3925        let nanos_of_day = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
3926        let secs_of_day = nanos_of_day / Timedelta::NANOS_PER_SEC;
3927        let sub_nanos = nanos_of_day.rem_euclid(Timedelta::NANOS_PER_SEC);
3928        // The crate's existing Hinnant civil-from-days, NOT a second copy: two
3929        // implementations of a calendar algorithm are two chances to drift.
3930        let (year, month, day) = civil_from_days(days_since_epoch);
3931
3932        // pandas' datetime64[ns] range is 1677..=2262, so the year is always
3933        // four digits and `{:04}` never truncates.
3934        let mut result = String::with_capacity(30);
3935        // `fmt::Write for String` is infallible.
3936        let _ = write!(result, "{year:04}-{month:02}-{day:02}");
3937        if matches!(resolution, DatetimeStringResolution::Date) {
3938            return result;
3939        }
3940        let _ = write!(
3941            result,
3942            " {:02}:{:02}:{:02}",
3943            secs_of_day / 3600,
3944            (secs_of_day % 3600) / 60,
3945            secs_of_day % 60
3946        );
3947        let (fraction, width) = match resolution {
3948            DatetimeStringResolution::Date | DatetimeStringResolution::Second => return result,
3949            DatetimeStringResolution::Milli => (sub_nanos / Timedelta::NANOS_PER_MILLI, 3_usize),
3950            DatetimeStringResolution::Micro => (sub_nanos / Timedelta::NANOS_PER_MICRO, 6_usize),
3951            DatetimeStringResolution::Nano => (sub_nanos, 9_usize),
3952        };
3953        let _ = write!(result, ".{fraction:0width$}", width = width);
3954        result
3955    }
3956
3957    /// Parse a datetime string into a Timestamp.
3958    ///
3959    /// Supports ISO 8601 formats:
3960    /// - "2024-01-15" (date only, time defaults to 00:00:00)
3961    /// - "2024-01-15T10:30:00" (datetime)
3962    /// - "2024-01-15 10:30:00" (space separator)
3963    /// - "2024-01-15T10:30:00.123456" (with fractional seconds)
3964    /// - "2024-01-15T10:30:00Z" (UTC timezone)
3965    /// - "2024-01-15T10:30:00+05:30" (offset timezone)
3966    /// - "NaT" (Not a Timestamp)
3967    ///
3968    /// Matches `pd.Timestamp()` constructor behavior.
3969    pub fn parse(s: &str) -> Result<Self, TypeError> {
3970        let s = s.trim();
3971
3972        if s.eq_ignore_ascii_case("nat") {
3973            return Ok(Self::nat());
3974        }
3975
3976        let Some((datetime_part, tz)) = Self::split_timezone(s) else {
3977            return Err(TypeError::ValueNotParseable {
3978                value: s.to_string(),
3979                target: "Timestamp".to_string(),
3980            });
3981        };
3982
3983        let (date_part, time_part) = if datetime_part.contains('T') {
3984            datetime_part
3985                .split_once('T')
3986                .ok_or_else(|| TypeError::ValueNotParseable {
3987                    value: s.to_string(),
3988                    target: "Timestamp".to_string(),
3989                })?
3990        } else if datetime_part.contains(' ')
3991            && datetime_part.chars().filter(|&c| c == ' ').count() == 1
3992        {
3993            datetime_part
3994                .split_once(' ')
3995                .ok_or_else(|| TypeError::ValueNotParseable {
3996                    value: s.to_string(),
3997                    target: "Timestamp".to_string(),
3998                })?
3999        } else {
4000            (datetime_part, "00:00:00")
4001        };
4002
4003        let (year, month, day) =
4004            Self::parse_date(date_part).ok_or_else(|| TypeError::ValueNotParseable {
4005                value: s.to_string(),
4006                target: "Timestamp".to_string(),
4007            })?;
4008
4009        let (hour, minute, second, nanos) =
4010            Self::parse_time(time_part).ok_or_else(|| TypeError::ValueNotParseable {
4011                value: s.to_string(),
4012                target: "Timestamp".to_string(),
4013            })?;
4014
4015        // br-frankenpandas-94o1u: an unrepresentable instant is a parse
4016        // failure, not a wrapped value.
4017        let total_nanos = Self::ymd_hms_to_nanos(year, month, day, hour, minute, second, nanos)
4018            .ok_or_else(|| TypeError::ValueNotParseable {
4019                value: s.to_string(),
4020                target: "Timestamp".to_string(),
4021            })?;
4022
4023        Ok(if let Some(tz_name) = tz {
4024            Self::from_nanos_tz(total_nanos, tz_name)
4025        } else {
4026            Self::from_nanos(total_nanos)
4027        })
4028    }
4029
4030    fn split_timezone(s: &str) -> Option<(&str, Option<String>)> {
4031        if let Some(stripped) = s.strip_suffix('Z') {
4032            Some((stripped, Some("UTC".to_string())))
4033        } else if let Some(idx) = s.rfind('+') {
4034            if idx > 10 && Self::is_timezone_offset(&s[idx..]) {
4035                Some((&s[..idx], Some(s[idx..].to_string())))
4036            } else if idx > 10 {
4037                None
4038            } else {
4039                Some((s, None))
4040            }
4041        } else if let Some(idx) = s.rfind('-') {
4042            if idx > 10 && Self::is_timezone_offset(&s[idx..]) {
4043                Some((&s[..idx], Some(s[idx..].to_string())))
4044            } else if idx > 10 {
4045                None
4046            } else {
4047                Some((s, None))
4048            }
4049        } else {
4050            Some((s, None))
4051        }
4052    }
4053
4054    fn fixed_utc_offset_seconds(tz: &str) -> Option<i64> {
4055        if tz == "UTC" {
4056            return Some(0);
4057        }
4058        let offset = tz.strip_prefix("UTC").unwrap_or(tz);
4059        if !Self::is_timezone_offset(offset) {
4060            return None;
4061        }
4062        let sign = if offset.starts_with('+') { 1 } else { -1 };
4063        let hours = offset[1..3].parse::<i64>().ok()?;
4064        let minutes = offset[4..6].parse::<i64>().ok()?;
4065        Some(sign * (hours * 3_600 + minutes * 60))
4066    }
4067
4068    fn is_timezone_offset(s: &str) -> bool {
4069        let bytes = s.as_bytes();
4070        if bytes.len() != 6 || !matches!(bytes[0], b'+' | b'-') || bytes[3] != b':' {
4071            return false;
4072        }
4073        if !bytes[1..3].iter().all(u8::is_ascii_digit)
4074            || !bytes[4..6].iter().all(u8::is_ascii_digit)
4075        {
4076            return false;
4077        }
4078        let hour = u32::from(bytes[1] - b'0') * 10 + u32::from(bytes[2] - b'0');
4079        let minute = u32::from(bytes[4] - b'0') * 10 + u32::from(bytes[5] - b'0');
4080        hour <= 23 && minute <= 59
4081    }
4082
4083    fn parse_date(s: &str) -> Option<(i64, u32, u32)> {
4084        let parts: Vec<&str> = s.split('-').collect();
4085        if parts.len() != 3 {
4086            return None;
4087        }
4088        let year: i64 = parts[0].parse().ok()?;
4089        let month: u32 = parts[1].parse().ok()?;
4090        let day: u32 = parts[2].parse().ok()?;
4091        if !(1..=days_in_month(year, month)?).contains(&day) {
4092            return None;
4093        }
4094        Some((year, month, day))
4095    }
4096
4097    fn parse_time(s: &str) -> Option<(u32, u32, u32, u64)> {
4098        let (time_str, frac_str) = match s.split_once('.') {
4099            Some((time, frac)) => (time, Some(frac)),
4100            None => (s, None),
4101        };
4102        let parts: Vec<&str> = time_str.split(':').collect();
4103        if parts.is_empty() || parts.len() > 3 {
4104            return None;
4105        }
4106        let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
4107        let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
4108        let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
4109
4110        if hour > 23 || minute > 59 || second > 59 {
4111            return None;
4112        }
4113
4114        let nanos = match frac_str {
4115            None => 0,
4116            Some(frac) => {
4117                if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
4118                    return None;
4119                }
4120                let digits = frac.len().min(9);
4121                let mut nanos = 0_u64;
4122                for byte in frac.bytes().take(digits) {
4123                    nanos = nanos * 10 + u64::from(byte - b'0');
4124                }
4125                for _ in digits..9 {
4126                    nanos *= 10;
4127                }
4128                nanos
4129            }
4130        };
4131
4132        Some((hour, minute, second, nanos))
4133    }
4134
4135    /// Compose a civil date-time into i64 nanoseconds since the epoch, or
4136    /// `None` when the instant is not representable.
4137    ///
4138    /// Checked composition (br-frankenpandas-94o1u). `parse_date` validates the
4139    /// month and the day-of-month but parses the YEAR as an unbounded `i64`,
4140    /// and i64 nanoseconds top out around year 2262 — the bound pandas
4141    /// documents for ns-resolution Timestamps. Unchecked, the two multiplies
4142    /// below wrapped in release, so `Timestamp::parse("300000-01-01")` returned
4143    /// `Ok` holding a silently wrong, plausible-looking in-range instant.
4144    /// pandas raises `OutOfBoundsDatetime`.
4145    ///
4146    /// This is the ingestion path — CSV/JSON date columns and user strings —
4147    /// so failing OPEN with corrupt data is the failure mode the security
4148    /// doctrine specifically forbids. `None` here becomes the same
4149    /// `ValueNotParseable` the caller already returns for any other
4150    /// unparseable input, so no new error variant and no API change.
4151    ///
4152    /// The day-count arithmetic above the multiplies cannot overflow for any
4153    /// `year` that survives `str::parse::<i64>` minus the era arithmetic's own
4154    /// bounds, but it is routed through checked ops anyway so an extreme year
4155    /// is rejected rather than wrapped before it ever reaches the seconds step.
4156    fn ymd_hms_to_nanos(
4157        year: i64,
4158        month: u32,
4159        day: u32,
4160        hour: u32,
4161        minute: u32,
4162        second: u32,
4163        sub_nanos: u64,
4164    ) -> Option<i64> {
4165        let m = month as i64;
4166        let d = day as i64;
4167
4168        let y = if m <= 2 { year.checked_sub(1)? } else { year };
4169        let era = if y >= 0 { y } else { y.checked_sub(399)? } / 400;
4170        let yoe = y.checked_sub(era.checked_mul(400)?)?;
4171        let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
4172        let doe = yoe
4173            .checked_mul(365)?
4174            .checked_add(yoe / 4 - yoe / 100)?
4175            .checked_add(doy)?;
4176        let days_since_epoch = era
4177            .checked_mul(146_097)?
4178            .checked_add(doe)?
4179            .checked_sub(719_468)?;
4180
4181        let total_seconds = days_since_epoch
4182            .checked_mul(86400)?
4183            .checked_add(i64::from(hour) * 3600)?
4184            .checked_add(i64::from(minute) * 60)?
4185            .checked_add(i64::from(second))?;
4186        total_seconds
4187            .checked_mul(Timedelta::NANOS_PER_SEC)?
4188            .checked_add(sub_nanos as i64)
4189    }
4190
4191    /// Format timestamp using strftime directives.
4192    ///
4193    /// Matches `pd.Timestamp.strftime(format)`. Supports: %Y (year), %m (month),
4194    /// %d (day), %H (hour), %M (minute), %S (second), %f (microsecond).
4195    /// NaT returns "NaT".
4196    #[must_use]
4197    pub fn strftime(&self, format: &str) -> String {
4198        use std::fmt::Write as _;
4199
4200        if self.is_nat() {
4201            return "NaT".to_string();
4202        }
4203        // Floor both boundaries for pre-epoch instants. Truncating division
4204        // produces an internally inconsistent date/time pair for every negative
4205        // non-midnight timestamp (and is especially visible at -1 ns):
4206        // 1970-01-01 00:00:00.999999 instead of
4207        // 1969-12-31 23:59:59.999999.
4208        let total_secs = self.nanos.div_euclid(Timedelta::NANOS_PER_SEC);
4209        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos
4210        // (br-frankenpandas-wkjtw); == `%` for the post-1970 positive case.
4211        let sub_nanos = self.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
4212
4213        let days_since_epoch = total_secs.div_euclid(86400);
4214        let secs_of_day = total_secs.rem_euclid(86400);
4215
4216        let days = days_since_epoch + 719_468;
4217        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
4218        let doe = days - era * 146_097;
4219        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
4220        let y = yoe + era * 400;
4221        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
4222        let mp = (5 * doy + 2) / 153;
4223        let d = doy - (153 * mp + 2) / 5 + 1;
4224        let m = if mp < 10 { mp + 3 } else { mp - 9 };
4225        let year = if m <= 2 { y + 1 } else { y };
4226
4227        let hour = secs_of_day / 3600;
4228        let minute = (secs_of_day % 3600) / 60;
4229        let second = secs_of_day % 60;
4230        let micros = sub_nanos / 1000;
4231
4232        // Write recognized directives directly into the returned allocation.
4233        // The former seven-step replacement chain copied the whole format once
4234        // per directive and allocated a temporary string for every component.
4235        let mut result = String::with_capacity(format.len().saturating_add(32));
4236        let mut rest = format;
4237        while let Some(percent) = rest.find('%') {
4238            result.push_str(&rest[..percent]);
4239            let directive = &rest[percent..];
4240            rest = if let Some(next) = directive.strip_prefix("%Y") {
4241                let _ = write!(result, "{year:04}");
4242                next
4243            } else if let Some(next) = directive.strip_prefix("%m") {
4244                let _ = write!(result, "{m:02}");
4245                next
4246            } else if let Some(next) = directive.strip_prefix("%d") {
4247                let _ = write!(result, "{d:02}");
4248                next
4249            } else if let Some(next) = directive.strip_prefix("%H") {
4250                let _ = write!(result, "{hour:02}");
4251                next
4252            } else if let Some(next) = directive.strip_prefix("%M") {
4253                let _ = write!(result, "{minute:02}");
4254                next
4255            } else if let Some(next) = directive.strip_prefix("%S") {
4256                let _ = write!(result, "{second:02}");
4257                next
4258            } else if let Some(next) = directive.strip_prefix("%f") {
4259                let _ = write!(result, "{micros:06}");
4260                next
4261            } else {
4262                // Preserve the chained `replace` behavior for unknown, escaped,
4263                // and trailing percent signs; the following byte may still begin
4264                // a recognized directive (for example, `%%Y` -> `%2024`).
4265                result.push('%');
4266                &directive[1..]
4267            };
4268        }
4269        result.push_str(rest);
4270        result
4271    }
4272
4273    /// Return the day of the week as a string (e.g., "Monday").
4274    ///
4275    /// Matches `pd.Timestamp.day_name()`. NaT returns "NaT".
4276    #[must_use]
4277    pub fn day_name(&self) -> String {
4278        const NAMES: [&str; 7] = [
4279            "Thursday",
4280            "Friday",
4281            "Saturday",
4282            "Sunday",
4283            "Monday",
4284            "Tuesday",
4285            "Wednesday",
4286        ];
4287        if self.is_nat() {
4288            return "NaT".to_string();
4289        }
4290        // Floor days for pre-1970 (br-frankenpandas-wkjtw); == `/` for positive.
4291        // Truncating `/` rounds a negative, non-midnight instant TOWARD zero, so
4292        // it lands on the following day and names the wrong weekday: pandas 2.2.3
4293        // gives 1969-07-20T20:17:40 -> "Sunday", truncation gave "Monday". The
4294        // wkjtw fix was applied to `dayofweek` but never here.
4295        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
4296        let dow = ((days_since_epoch % 7) + 7) % 7;
4297        NAMES[dow as usize].to_string()
4298    }
4299
4300    /// Return the month name as a string (e.g., "January").
4301    ///
4302    /// Matches `pd.Timestamp.month_name()`. NaT returns "NaT".
4303    #[must_use]
4304    pub fn month_name(&self) -> String {
4305        const NAMES: [&str; 12] = [
4306            "January",
4307            "February",
4308            "March",
4309            "April",
4310            "May",
4311            "June",
4312            "July",
4313            "August",
4314            "September",
4315            "October",
4316            "November",
4317            "December",
4318        ];
4319        if self.is_nat() {
4320            return "NaT".to_string();
4321        }
4322        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
4323        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
4324        // for the post-1970 positive case.
4325        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
4326        let days = days_since_epoch + 719_468;
4327        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
4328        let doe = days - era * 146_097;
4329        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
4330        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
4331        let mp = (5 * doy + 2) / 153;
4332        let m = if mp < 10 { mp + 3 } else { mp - 9 };
4333        NAMES[(m - 1) as usize].to_string()
4334    }
4335
4336    /// Localize a naive timestamp to a timezone.
4337    ///
4338    /// Matches `pd.Timestamp.tz_localize(tz)`. If `tz` is None, removes the
4339    /// timezone (makes timestamp naive). NaT propagates.
4340    #[must_use]
4341    pub fn tz_localize(&self, tz: Option<&str>) -> Self {
4342        if self.is_nat() {
4343            return Self::nat();
4344        }
4345        Self {
4346            nanos: self.nanos,
4347            tz: tz.map(String::from),
4348        }
4349    }
4350
4351    /// Convert timezone-aware timestamp to another timezone.
4352    ///
4353    /// Matches `pd.Timestamp.tz_convert(tz)`. If timestamp is naive (no tz),
4354    /// the timezone is simply attached without conversion. NaT propagates.
4355    /// Note: actual UTC offset conversion requires chrono-tz (Phase 3).
4356    #[must_use]
4357    pub fn tz_convert(&self, tz: &str) -> Self {
4358        if self.is_nat() {
4359            return Self::nat();
4360        }
4361        Self {
4362            nanos: self.nanos,
4363            tz: Some(tz.to_string()),
4364        }
4365    }
4366
4367    /// Create a Timestamp from a Unix timestamp (seconds since epoch).
4368    ///
4369    /// Matches `pd.Timestamp.fromtimestamp(ts)`. The optional `tz` parameter
4370    /// specifies the timezone to localize to.
4371    #[must_use]
4372    pub fn fromtimestamp(ts: f64, tz: Option<&str>) -> Self {
4373        if ts.is_nan() || ts.is_infinite() {
4374            return Self::nat();
4375        }
4376        let nanos_f64 = ts * 1_000_000_000.0;
4377        // Check for overflow before casting - i64 range is roughly ±9.2e18
4378        const MAX_NANOS: f64 = i64::MAX as f64;
4379        const MIN_NANOS: f64 = i64::MIN as f64;
4380        if !(MIN_NANOS..=MAX_NANOS).contains(&nanos_f64) {
4381            return Self::nat();
4382        }
4383        Self {
4384            nanos: nanos_f64 as i64,
4385            tz: tz.map(String::from),
4386        }
4387    }
4388
4389    /// Create a Timestamp from milliseconds since epoch.
4390    ///
4391    /// Convenience constructor complementing fromtimestamp. An `ms` outside
4392    /// the representable nanosecond range → NaT, matching `fromtimestamp`
4393    /// directly above (br-frankenpandas-kyd16); the previous
4394    /// `saturating_mul` handed back a finite ~year-2262 instant instead.
4395    #[must_use]
4396    pub fn from_millis(ms: i64, tz: Option<&str>) -> Self {
4397        let Some(nanos) = ms.checked_mul(1_000_000) else {
4398            return Self::nat();
4399        };
4400        Self {
4401            nanos,
4402            tz: tz.map(String::from),
4403        }
4404    }
4405
4406    /// Create a Timestamp from microseconds since epoch.
4407    ///
4408    /// Convenience constructor complementing fromtimestamp.
4409    #[must_use]
4410    pub fn from_micros(us: i64, tz: Option<&str>) -> Self {
4411        let Some(nanos) = us.checked_mul(1_000) else {
4412            return Self::nat();
4413        };
4414        Self {
4415            nanos,
4416            tz: tz.map(String::from),
4417        }
4418    }
4419
4420    /// Return the timezone string, or None if naive.
4421    #[must_use]
4422    pub fn tzinfo(&self) -> Option<&str> {
4423        self.tz.as_deref()
4424    }
4425
4426    /// Return the timezone name, or None if naive.
4427    ///
4428    /// Alias for tzinfo() matching pandas Timestamp.tzname().
4429    #[must_use]
4430    pub fn tzname(&self) -> Option<&str> {
4431        self.tzinfo()
4432    }
4433}
4434
4435impl std::fmt::Display for Timestamp {
4436    /// Phase 2 debug-style format; Phase 3 replaces with pandas ISO-8601
4437    /// notation once chrono interpretation lands.
4438    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4439        if self.is_nat() {
4440            return f.write_str("NaT");
4441        }
4442        match &self.tz {
4443            Some(tz) => write!(f, "Timestamp[{}, {}]", self.nanos, tz),
4444            None => write!(f, "Timestamp[{}, UTC]", self.nanos),
4445        }
4446    }
4447}
4448
4449impl PartialOrd for Timestamp {
4450    /// Orders by nanos axis; NaT is incomparable (`None`). Tz difference
4451    /// does not affect ordering — two Timestamps at the same absolute
4452    /// nanos compare equal regardless of tz label (Phase 3 will revisit
4453    /// whether tz affects ordering semantics).
4454    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
4455        if self.is_nat() || other.is_nat() {
4456            return None;
4457        }
4458        Some(self.nanos.cmp(&other.nanos))
4459    }
4460}
4461
4462// ── Missingness utilities ──────────────────────────────────────────────
4463
4464pub fn isna(values: &[Scalar]) -> Vec<bool> {
4465    values.iter().map(Scalar::is_missing).collect()
4466}
4467
4468pub fn isnull(values: &[Scalar]) -> Vec<bool> {
4469    isna(values)
4470}
4471
4472pub fn notna(values: &[Scalar]) -> Vec<bool> {
4473    values.iter().map(|v| !v.is_missing()).collect()
4474}
4475
4476pub fn notnull(values: &[Scalar]) -> Vec<bool> {
4477    notna(values)
4478}
4479
4480pub fn count_na(values: &[Scalar]) -> usize {
4481    values.iter().filter(|v| v.is_missing()).count()
4482}
4483
4484pub fn fill_na(values: &[Scalar], fill: &Scalar) -> Vec<Scalar> {
4485    values
4486        .iter()
4487        .map(|v| {
4488            if v.is_missing() {
4489                fill.clone()
4490            } else {
4491                v.clone()
4492            }
4493        })
4494        .collect()
4495}
4496
4497pub fn dropna(values: &[Scalar]) -> Vec<Scalar> {
4498    values.iter().filter(|v| !v.is_missing()).cloned().collect()
4499}
4500
4501// ── Nanops: null-skipping numeric reductions ───────────────────────────
4502
4503fn collect_finite(values: &[Scalar]) -> Vec<f64> {
4504    values
4505        .iter()
4506        .filter(|v| !v.is_missing())
4507        .filter_map(|v| v.to_f64().ok())
4508        .collect()
4509}
4510
4511/// Per br-frankenpandas-620mj: if a column is uniformly Timedelta64
4512/// (with optional NAT/Null missing), sum/mean preserve Timedelta dtype
4513/// matching pandas — instead of silently coercing to Float64(0.0) via
4514/// the collect_finite path (which drops Timedelta64 because to_f64
4515/// errors). A NaT-only input remains a Timedelta family so sum returns
4516/// zero Timedelta and mean returns NaT. Returns Some(sum_in_ns,
4517/// observed_count) when applicable.
4518fn collect_timedelta_ns(values: &[Scalar]) -> Option<(i128, usize)> {
4519    let mut sum: i128 = 0;
4520    let mut count: usize = 0;
4521    let mut saw_timedelta = false;
4522    for v in values {
4523        match v {
4524            Scalar::Timedelta64(ns) => {
4525                saw_timedelta = true;
4526                if v.is_missing() {
4527                    continue;
4528                }
4529                sum += i128::from(*ns);
4530                count += 1;
4531            }
4532            _ if v.is_missing() => continue,
4533            // Any non-Timedelta non-missing value bails out to the
4534            // existing Float64 path, preserving cross-type behavior.
4535            _ => return None,
4536        }
4537    }
4538    if saw_timedelta {
4539        Some((sum, count))
4540    } else {
4541        None
4542    }
4543}
4544
4545/// Narrow an exact `i128` nanosecond quantity back to a `Timedelta64` scalar,
4546/// surfacing NaT when the value is not representable.
4547///
4548/// Per br-frankenpandas-opz27, this replaces the `clamp(i64::MIN, i64::MAX)`
4549/// the reduction paths used to do, which failed open twice over:
4550///
4551/// - a positive overflow became `i64::MAX`, a fabricated finite ~106751-day
4552///   Timedelta presented as real data (the br-frankenpandas-lgyy8 class);
4553/// - `Timedelta::NAT` *is* `i64::MIN`, so the clamp's lower bound landed
4554///   exactly on the missing sentinel — a negative overflow silently became
4555///   NaT by accident, and the bound was off by one against the true minimum.
4556///
4557/// The representable range is therefore `[i64::MIN + 1, i64::MAX]`, and both
4558/// overflow directions now yield NaT deliberately. Live pandas 2.2.3 raises
4559/// (`OverflowError` / `ValueError: overflow in timedelta operation`) where
4560/// these reductions overflow; FP surfaces NaT instead, matching the
4561/// infallible-helper convention established by `Timedelta::div_scalar` and
4562/// br-frankenpandas-lgyy8. Every exactly-representable result is unaffected.
4563fn timedelta_ns_to_scalar(ns: i128) -> Scalar {
4564    if ns > i128::from(i64::MAX) || ns <= i128::from(i64::MIN) {
4565        return Scalar::Timedelta64(Timedelta::NAT);
4566    }
4567    Scalar::Timedelta64(ns as i64)
4568}
4569
4570pub fn nansum(values: &[Scalar]) -> Scalar {
4571    if let Some((sum, _)) = collect_timedelta_ns(values) {
4572        return timedelta_ns_to_scalar(sum);
4573    }
4574    // Fused single-pass fold: filter missing / non-f64-coercible and accumulate
4575    // in one scan, avoiding the intermediate `collect_finite` Vec<f64> and its
4576    // second pass. Bit-identical to `collect_finite(..).iter().sum()`: same
4577    // finite values in the same order, same left-fold f64 `+` (empty -> 0.0).
4578    let mut sum = 0.0_f64;
4579    for v in values {
4580        if v.is_missing() {
4581            continue;
4582        }
4583        if let Ok(x) = v.to_f64() {
4584            sum += x;
4585        }
4586    }
4587    Scalar::Float64(sum)
4588}
4589
4590/// Sum of a STRING group: pandas concatenates, skipping missing entries.
4591///
4592/// br-frankenpandas-a7faz. `nansum` cannot serve this: it coerces through
4593/// `to_f64`, which fails for every `Utf8`, so a string column sums to
4594/// `Float64(0.0)` — a wrong value rather than a refusal. This is a separate
4595/// reducer rather than a branch inside `nansum` on purpose: the SUM SURFACES
4596/// DISAGREE in pandas and a shared change would silently move the others.
4597///
4598/// MEASURED, live pandas 2.2.3 (CrimsonPine 2026-08-18):
4599/// ```text
4600///   Series(['a','b','c']).sum()              -> 'abc'
4601///   Series(['a',None,'c']).sum()             -> TypeError: can only concatenate str
4602///   DataFrame({'v':['a',None]}).sum()        -> TypeError (same)
4603///   df.groupby(k)['v'].sum()  with a None    -> 'a'      SKIPS, does not raise
4604///   s.resample('ME').sum()    with a None    -> 'ps'     SKIPS, does not raise
4605/// ```
4606/// So the REDUCTION surfaces raise on a missing entry while the GROUPED surfaces
4607/// skip it. This function implements the grouped rule and must not be wired into
4608/// `Series::sum`/`DataFrame::sum` without implementing their raise.
4609///
4610/// ⚠️ AND AN EMPTY OR ALL-MISSING GROUP IS INTEGER `0`, NOT `""`. Measured:
4611/// ```text
4612///   Series(['p','q'], index=[Jan-01, Mar-01]).resample('ME').sum()
4613///     -> ['p', 0, 'q']        <- the empty February bucket is int 0
4614///   Series([None,None,'r','u'], ...).resample('ME').sum()
4615///     -> [0, 'ru']            <- an all-missing bucket is int 0 too
4616///   types: ['int', 'str']     <- the output column is genuinely MIXED
4617/// ```
4618/// That is pandas' `sum()` identity element leaking through unchanged, and it is
4619/// why this returns `Scalar::Int64(0)` rather than an empty string: matching the
4620/// incumbent here means reproducing a mixed-dtype column.
4621///
4622/// Concatenation is POSITIONAL, not sorted — `Series(['z','a','m']).sum()` is
4623/// `'zam'`. Callers that bucket by time therefore hand the values over in index
4624/// order, which is what produced `'psq'` for a Jan bucket holding Jan-01 'p',
4625/// Jan-05 's', Jan-15 'q'.
4626#[must_use]
4627pub fn nansum_utf8(values: &[Scalar]) -> Scalar {
4628    let mut out: Option<String> = None;
4629    for v in values {
4630        if v.is_missing() {
4631            continue;
4632        }
4633        if let Scalar::Utf8(part) = v {
4634            out.get_or_insert_with(String::new).push_str(part);
4635        }
4636    }
4637    match out {
4638        Some(joined) => Scalar::Utf8(joined),
4639        // Not `Utf8(String::new())`: pandas yields the integer identity here.
4640        None => Scalar::Int64(0),
4641    }
4642}
4643
4644pub fn nanmean(values: &[Scalar]) -> Scalar {
4645    if let Some((sum, count)) = collect_timedelta_ns(values) {
4646        if count == 0 {
4647            return Scalar::Timedelta64(Timedelta::NAT);
4648        }
4649        // |sum / count| <= max|ns| for count >= 1, so the mean of representable
4650        // inputs is always representable; the narrowing is defensive only.
4651        return timedelta_ns_to_scalar(sum / count as i128);
4652    }
4653    // br-frankenpandas-adv58: Datetime64 mean is the mean of the epoch-ns
4654    // backing, re-read as an instant. Accumulated in i128 and divided with
4655    // Rust's toward-zero integer division, which is exactly the rounding pandas
4656    // shows where it is exact ([0,1] -> 0, [0,3] -> 1, [-3,0] -> -1; floor and
4657    // ties-to-even are both refuted). Where pandas is NOT exact it snaps to its
4658    // f64 grid — even for a constant series — and FP stays exact. See DISC-019.
4659    if let Some((sum, count)) = collect_datetime_ns(values) {
4660        if count == 0 {
4661            return Scalar::Datetime64(Timestamp::NAT);
4662        }
4663        let mean = sum / count as i128;
4664        if mean > i128::from(i64::MAX) || mean <= i128::from(i64::MIN) {
4665            return Scalar::Datetime64(Timestamp::NAT);
4666        }
4667        return Scalar::Datetime64(mean as i64);
4668    }
4669    // Fused single-pass fold (see `nansum`): accumulate sum + count of finite
4670    // values in one scan. Bit-identical to the prior `collect_finite` two-pass:
4671    // count == nums.len(), sum folds the same values in the same order.
4672    let mut sum = 0.0_f64;
4673    let mut count = 0usize;
4674    for v in values {
4675        if v.is_missing() {
4676            continue;
4677        }
4678        if let Ok(x) = v.to_f64() {
4679            sum += x;
4680            count += 1;
4681        }
4682    }
4683    if count == 0 {
4684        return Scalar::Null(NullKind::NaN);
4685    }
4686    Scalar::Float64(sum / count as f64)
4687}
4688
4689pub fn nanany(values: &[Scalar]) -> Scalar {
4690    for v in values {
4691        if v.is_missing() {
4692            continue;
4693        }
4694        match v {
4695            Scalar::Bool(flag) if *flag => return Scalar::Bool(true),
4696            Scalar::Int64(val) if *val != 0 => return Scalar::Bool(true),
4697            Scalar::Float64(val) if !val.is_nan() && *val != 0.0 => return Scalar::Bool(true),
4698            Scalar::Utf8(val) if !val.is_empty() => return Scalar::Bool(true),
4699            // pandas Series([td]).any() returns True for any non-zero
4700            // Timedelta. NaT is already filtered by is_missing() above.
4701            Scalar::Timedelta64(ns) if *ns != 0 => return Scalar::Bool(true),
4702            _ => continue,
4703        }
4704    }
4705    Scalar::Bool(false)
4706}
4707
4708pub fn nanall(values: &[Scalar]) -> Scalar {
4709    for v in values {
4710        if v.is_missing() {
4711            continue;
4712        }
4713        match v {
4714            Scalar::Bool(flag) if !*flag => return Scalar::Bool(false),
4715            Scalar::Int64(val) if *val == 0 => return Scalar::Bool(false),
4716            Scalar::Float64(val) if val.is_nan() || *val == 0.0 => return Scalar::Bool(false),
4717            Scalar::Utf8(val) if val.is_empty() => return Scalar::Bool(false),
4718            // pandas Series([td(0)]).all() returns False; any non-zero
4719            // Timedelta is truthy. NaT is already filtered by is_missing.
4720            Scalar::Timedelta64(ns) if *ns == 0 => return Scalar::Bool(false),
4721            _ => continue,
4722        }
4723    }
4724    Scalar::Bool(true)
4725}
4726
4727pub fn nancount(values: &[Scalar]) -> Scalar {
4728    let n = values.iter().filter(|v| !v.is_missing()).count();
4729    Scalar::Int64(n as i64)
4730}
4731
4732pub fn nanmin(values: &[Scalar]) -> Scalar {
4733    let mut min: Option<&Scalar> = None;
4734    for v in values {
4735        if v.is_missing() {
4736            continue;
4737        }
4738        match (min, v) {
4739            (None, _) => min = Some(v),
4740            (Some(Scalar::Int64(a)), Scalar::Int64(b)) => {
4741                if b < a {
4742                    min = Some(v)
4743                }
4744            }
4745            (Some(Scalar::Float64(a)), Scalar::Float64(b)) => {
4746                if *b < *a {
4747                    min = Some(v)
4748                }
4749            }
4750            (Some(Scalar::Utf8(a)), Scalar::Utf8(b)) => {
4751                if b < a {
4752                    min = Some(v)
4753                }
4754            }
4755            (Some(Scalar::Bool(a)), Scalar::Bool(b)) => {
4756                if b < a {
4757                    min = Some(v)
4758                }
4759            }
4760            // Per br-frankenpandas-yic5m: Timedelta64.to_f64() errors, so
4761            // the catch-all below would silently return NaN. Compare ns
4762            // representations directly; NAT is already filtered by
4763            // is_missing() above.
4764            (Some(Scalar::Timedelta64(a)), Scalar::Timedelta64(b)) => {
4765                if b < a {
4766                    min = Some(v)
4767                }
4768            }
4769            // br-frankenpandas-axhhk: Datetime64 needs the same arm for the
4770            // same reason — its to_f64() errors too. Without it a 2+-element
4771            // datetime column returned Null(NaN), while a 1-element one
4772            // returned the right answer via the (None, _) seed above.
4773            (Some(Scalar::Datetime64(a)), Scalar::Datetime64(b)) => {
4774                if b < a {
4775                    min = Some(v)
4776                }
4777            }
4778            // br-frankenpandas-qoabs: Period, third dtype with the same
4779            // to_f64() failure. Ordinals are ONLY comparable within one freq —
4780            // pandas refuses mixed freq outright (IncompatibleFrequency), so a
4781            // differing freq must NOT be ordered here. Comparing the raw
4782            // ordinals across freqs would invent an ordering pandas rejects
4783            // (monthly 2020-01 is ordinal 600, daily 2020-01-05 is 18267).
4784            // br-frankenpandas-qoabs: Period, third dtype with the same
4785            // to_f64() failure. Ordinals are ONLY comparable within one freq —
4786            // pandas refuses mixed freq outright (IncompatibleFrequency), so a
4787            // differing freq must NOT be ordered here. Comparing the raw
4788            // ordinals across freqs would invent an ordering pandas rejects
4789            // (monthly 2020-01 is ordinal 600, daily 2020-01-05 is 18267).
4790            (Some(Scalar::Period(a)), Scalar::Period(b)) => {
4791                if a.freq != b.freq {
4792                    return Scalar::Null(NullKind::NaN);
4793                }
4794                if b.ordinal < a.ordinal {
4795                    min = Some(v)
4796                }
4797            }
4798            // br-frankenpandas-srqdo: Interval, fourth dtype whose to_f64()
4799            // errors. pandas orders Intervals by (left, right) — a tie on left
4800            // falls through to right. `closed` is NOT part of the comparison:
4801            // pandas does order scalar Intervals that tie on both bounds by an
4802            // internal `closed` ordering, but a real IntervalArray requires a
4803            // UNIFORM closed, so that case cannot arise from an Interval
4804            // column, and guessing an undocumented enum order would be worse
4805            // than keeping the first on an exact tie.
4806            //
4807            // A NaN bound is not orderable and has no pandas counterpart —
4808            // IntervalArray refuses to build one ("missing values must be
4809            // missing in the same location both left and right") — so bail to
4810            // missing rather than impose an arbitrary order. Note this avoids
4811            // `partial_cmp().unwrap()`, which would be a panic in library code.
4812            (Some(Scalar::Interval(a)), Scalar::Interval(b)) => {
4813                if a.left.is_nan() || a.right.is_nan() || b.left.is_nan() || b.right.is_nan() {
4814                    return Scalar::Null(NullKind::NaN);
4815                }
4816                if (b.left, b.right) < (a.left, a.right) {
4817                    min = Some(v)
4818                }
4819            }
4820            (Some(a), b) => match (a.to_f64(), b.to_f64()) {
4821                (Ok(af), Ok(bf)) if bf < af => min = Some(v),
4822                (Ok(_), Ok(_)) => {}
4823                _ => return Scalar::Null(NullKind::NaN),
4824            },
4825        }
4826    }
4827    match min {
4828        Some(v) => v.clone(),
4829        None => Scalar::Null(NullKind::NaN),
4830    }
4831}
4832
4833pub fn nanmax(values: &[Scalar]) -> Scalar {
4834    let mut max: Option<&Scalar> = None;
4835    for v in values {
4836        if v.is_missing() {
4837            continue;
4838        }
4839        match (max, v) {
4840            (None, _) => max = Some(v),
4841            (Some(Scalar::Int64(a)), Scalar::Int64(b)) => {
4842                if b > a {
4843                    max = Some(v)
4844                }
4845            }
4846            (Some(Scalar::Float64(a)), Scalar::Float64(b)) => {
4847                if *b > *a {
4848                    max = Some(v)
4849                }
4850            }
4851            (Some(Scalar::Utf8(a)), Scalar::Utf8(b)) => {
4852                if b > a {
4853                    max = Some(v)
4854                }
4855            }
4856            (Some(Scalar::Bool(a)), Scalar::Bool(b)) => {
4857                if b > a {
4858                    max = Some(v)
4859                }
4860            }
4861            // Per br-frankenpandas-yic5m: Timedelta64.to_f64() errors, so
4862            // the catch-all below would silently return NaN. Compare ns
4863            // representations directly; NAT is already filtered above.
4864            (Some(Scalar::Timedelta64(a)), Scalar::Timedelta64(b)) => {
4865                if b > a {
4866                    max = Some(v)
4867                }
4868            }
4869            // br-frankenpandas-axhhk: Datetime64 sibling of the arm above.
4870            (Some(Scalar::Datetime64(a)), Scalar::Datetime64(b)) => {
4871                if b > a {
4872                    max = Some(v)
4873                }
4874            }
4875            // br-frankenpandas-qoabs: Period, freq-guarded — see `nanmin`.
4876            (Some(Scalar::Period(a)), Scalar::Period(b)) => {
4877                if a.freq != b.freq {
4878                    return Scalar::Null(NullKind::NaN);
4879                }
4880                if b.ordinal > a.ordinal {
4881                    max = Some(v)
4882                }
4883            }
4884            // br-frankenpandas-srqdo: Interval, ordered by (left, right) with
4885            // NaN bounds refused — see `nanmin` for the full reasoning.
4886            (Some(Scalar::Interval(a)), Scalar::Interval(b)) => {
4887                if a.left.is_nan() || a.right.is_nan() || b.left.is_nan() || b.right.is_nan() {
4888                    return Scalar::Null(NullKind::NaN);
4889                }
4890                if (b.left, b.right) > (a.left, a.right) {
4891                    max = Some(v)
4892                }
4893            }
4894            (Some(a), b) => match (a.to_f64(), b.to_f64()) {
4895                (Ok(af), Ok(bf)) if bf > af => max = Some(v),
4896                (Ok(_), Ok(_)) => {}
4897                _ => return Scalar::Null(NullKind::NaN),
4898            },
4899        }
4900    }
4901    match max {
4902        Some(v) => v.clone(),
4903        None => Scalar::Null(NullKind::NaN),
4904    }
4905}
4906
4907/// Which temporal family a uniformly-temporal input belongs to, and everything
4908/// needed to rebuild a `Scalar` of it from a raw i64 backing.
4909///
4910/// br-frankenpandas-d7zjp replaced the previous `fn(i64) -> Scalar` constructor
4911/// with this enum for one reason: a plain fn pointer CANNOT CARRY A FREQ, and a
4912/// `Period` is `{ordinal, freq}`. That limitation is what blocked Period from
4913/// joining median/quantile/cummax/cummin when Datetime64 did.
4914///
4915/// The i64 payload is nanoseconds for Timedelta64/Datetime64 and an ORDINAL for
4916/// Period — different units, but every operation here is pure ordering or an
4917/// average over that backing, which is meaningful in both.
4918#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4919enum TemporalFamily {
4920    Timedelta,
4921    Datetime,
4922    /// Periods only compare within ONE freq; see [`collect_temporal_backing`].
4923    Period(PeriodFreq),
4924}
4925
4926impl TemporalFamily {
4927    /// Rebuild a scalar of this family from its raw backing.
4928    fn make(self, raw: i64) -> Scalar {
4929        match self {
4930            Self::Timedelta => Scalar::Timedelta64(raw),
4931            Self::Datetime => Scalar::Datetime64(raw),
4932            Self::Period(freq) => Scalar::Period(Period::new(raw, freq)),
4933        }
4934    }
4935
4936    /// The family's missing sentinel, dtype preserved.
4937    fn nat(self) -> Scalar {
4938        self.make(i64::MIN)
4939    }
4940}
4941
4942/// Per br-frankenpandas-j8ntk: harvest the raw backing of a uniformly-temporal
4943/// input as f64 (53 bits of mantissa, exact for ns spans up to ~104 days;
4944/// beyond that pandas itself loses precision the same way), together with the
4945/// family to rebuild results in. A NaT-only input keeps its family.
4946///
4947/// Returns `None` unless every non-missing value belongs to ONE family — which
4948/// for Period means one FREQ as well, because pandas refuses to order Periods
4949/// of differing freq at all (`IncompatibleFrequency`) and their ordinals are
4950/// not comparable across freqs.
4951///
4952/// br-frankenpandas-adv58 widened this to Datetime64 and d7zjp to Period. The
4953/// f64 hop is inherited deliberately: quantile interpolates by a fractional
4954/// weight, so the newer families keep the SAME accuracy contract the Timedelta
4955/// arm already had rather than inventing a stricter one per dtype.
4956fn collect_temporal_backing(values: &[Scalar]) -> Option<(Vec<f64>, TemporalFamily)> {
4957    let mut out = Vec::with_capacity(values.len());
4958    let mut family: Option<TemporalFamily> = None;
4959    for v in values {
4960        let (raw, this) = match v {
4961            Scalar::Timedelta64(ns) => (*ns, TemporalFamily::Timedelta),
4962            Scalar::Datetime64(ns) => (*ns, TemporalFamily::Datetime),
4963            Scalar::Period(p) => (p.ordinal, TemporalFamily::Period(p.freq)),
4964            _ if v.is_missing() => continue,
4965            _ => return None,
4966        };
4967        // Mixing families — or, for Period, mixing freqs — is not one family.
4968        match family {
4969            Some(existing) if existing != this => return None,
4970            _ => family = Some(this),
4971        }
4972        if v.is_missing() {
4973            continue;
4974        }
4975        out.push(raw as f64);
4976    }
4977    family.map(|f| (out, f))
4978}
4979
4980/// Timedelta64-ONLY view of [`collect_temporal_backing`].
4981///
4982/// var/sem keep this narrower gate on purpose: live pandas 2.2.3 RAISES
4983/// `TypeError: 'DatetimeArray' ... does not support reduction 'var'` (and the
4984/// same for 'sem', and for every one of them on Period), so widening them would
4985/// invent a value pandas refuses to produce.
4986fn collect_timedelta_ns_f64(values: &[Scalar]) -> Option<Vec<f64>> {
4987    match collect_temporal_backing(values) {
4988        Some((out, TemporalFamily::Timedelta)) => Some(out),
4989        _ => None,
4990    }
4991}
4992
4993/// Clamp an f64 result into i64 range and wrap as Scalar::Timedelta64.
4994fn float_ns_to_timedelta(value: f64) -> Scalar {
4995    float_ns_to_temporal(value, TemporalFamily::Timedelta)
4996}
4997
4998/// Family-generic form of [`float_ns_to_timedelta`], per br-frankenpandas-adv58:
4999/// NaT for a non-finite input, otherwise the value in the caller's family.
5000fn float_ns_to_temporal(value: f64, make: TemporalFamily) -> Scalar {
5001    if !value.is_finite() {
5002        return make.nat();
5003    }
5004    let clamped = value.clamp(i64::MIN as f64, i64::MAX as f64);
5005    make.make(clamped as i64)
5006}
5007
5008pub fn nanmedian(values: &[Scalar]) -> Scalar {
5009    // Preserve exact nanosecond ordering for uniformly-temporal input.
5010    // Converting to f64 loses distinct ticks beyond the 53-bit boundary.
5011    //
5012    // br-frankenpandas-adv58: Datetime64 joins Timedelta64 here, and keeps the
5013    // SAME exact i128 treatment its Timedelta sibling already had. Note that
5014    // this makes FP strictly more precise than pandas 2.2.3, which routes
5015    // datetime median through f64 and therefore snaps to a 256 ns grid at
5016    // 2020-era timestamps — returning, for an odd-count input, a Timestamp that
5017    // is not even one of the supplied values. See DISC-019.
5018    // br-frankenpandas-d7zjp: Period joins via the family enum, which — unlike
5019    // the fn-pointer constructor this replaced — can carry its freq. A
5020    // mixed-freq input is not one family, so it falls through rather than
5021    // being ordered by raw ordinal, matching pandas refusing it outright.
5022    let Some((_, make)) = collect_temporal_backing(values) else {
5023        // Not uniformly temporal: fall through to the numeric arm below.
5024        return nanmedian_numeric(values);
5025    };
5026    let mut td: Vec<i64> = values
5027        .iter()
5028        .filter(|value| !value.is_missing())
5029        .filter_map(|value| match value {
5030            Scalar::Timedelta64(ns) | Scalar::Datetime64(ns) => Some(*ns),
5031            Scalar::Period(p) => Some(p.ordinal),
5032            _ => None,
5033        })
5034        .collect();
5035    if td.is_empty() {
5036        // All-missing temporal input falls through to the numeric arm, which
5037        // yields Null(NaN). Do NOT "improve" this to a family-typed NaT: the
5038        // Null(NaN) result is pinned by the oracle test
5039        // `nanmedian_matches_numeric_and_timedelta_oracle_oabhi`, and the old
5040        // `is_timedelta_input` gate produced it by returning false for an
5041        // all-missing input. `collect_temporal_backing` marks the family on
5042        // seeing the VARIANT instead, so the fall-through has to be explicit.
5043        return nanmedian_numeric(values);
5044    }
5045    // O(n) selection instead of a full sort: order statistics depend only
5046    // on values, so the unstable partition yields the same middle values.
5047    let n = td.len();
5048    let mid = n / 2;
5049    let (left, mid_ref, _right) = td.select_nth_unstable(mid);
5050    let mid_val = *mid_ref;
5051    let median_ns = if n.is_multiple_of(2) {
5052        let lower = left.iter().copied().fold(i64::MIN, i64::max);
5053        // Toward-zero division, matching pandas where pandas is exact.
5054        (i128::from(lower) + i128::from(mid_val)) / 2
5055    } else {
5056        i128::from(mid_val)
5057    };
5058    make.make(median_ns as i64)
5059}
5060
5061/// Numeric (f64) median arm, split out of [`nanmedian`] by
5062/// br-frankenpandas-adv58 so the temporal arm can return early. Also the
5063/// fall-through for non-uniform input, e.g. mixed Datetime64 + Int64.
5064fn nanmedian_numeric(values: &[Scalar]) -> Scalar {
5065    let mut nums = collect_finite(values);
5066    if nums.is_empty() {
5067        return Scalar::Null(NullKind::NaN);
5068    }
5069    // O(n) selection instead of an O(n log n) full sort: select_nth_unstable_by
5070    // places the `mid`-th smallest at index `mid` with all smaller elements
5071    // (unordered) in the left partition. For even n the (mid-1)-th smallest is
5072    // the MAX of that left partition. Bit-identical to the sort path: order
5073    // statistics depend only on VALUES, and ties share a value, so the
5074    // unstable partition yields the same nums[mid-1]/nums[mid] the sort did.
5075    let n = nums.len();
5076    let mid = n / 2;
5077    let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
5078    let (left, mid_ref, _right) = nums.select_nth_unstable_by(mid, cmp);
5079    let mid_val = *mid_ref;
5080    if n.is_multiple_of(2) {
5081        let lower = left.iter().copied().fold(f64::NEG_INFINITY, f64::max);
5082        Scalar::Float64((lower + mid_val) / 2.0)
5083    } else {
5084        Scalar::Float64(mid_val)
5085    }
5086}
5087
5088pub fn nanvar(values: &[Scalar], ddof: usize) -> Scalar {
5089    // Per br-frankenpandas-j8ntk: Timedelta64 var preserves dtype — pandas
5090    // returns Timedelta even though variance is ns² conceptually; matching.
5091    if let Some(td) = collect_timedelta_ns_f64(values) {
5092        if td.len() <= ddof {
5093            return Scalar::Timedelta64(Timedelta::NAT);
5094        }
5095        let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
5096        let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
5097        return float_ns_to_timedelta(sum_sq / (td.len() - ddof) as f64);
5098    }
5099    let nums = collect_finite(values);
5100    if nums.len() <= ddof {
5101        return Scalar::Null(NullKind::NaN);
5102    }
5103    let mean: f64 = nums.iter().sum::<f64>() / nums.len() as f64;
5104    let sum_sq: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
5105    Scalar::Float64(sum_sq / (nums.len() - ddof) as f64)
5106}
5107
5108pub fn nanstd(values: &[Scalar], ddof: usize) -> Scalar {
5109    // Per br-frankenpandas-j8ntk: Timedelta64 std preserves dtype.
5110    //
5111    // br-frankenpandas-40ujm: Datetime64 is accepted here too, and the family
5112    // constructor is deliberately DISCARDED — the dispersion of a set of
5113    // instants is a DURATION, so datetime std returns a Timedelta, exactly as
5114    // pandas does. Verified against the oracle: pandas gives the identical
5115    // value for a Datetime64 series and a Timedelta64 series built from the
5116    // same ns (both 2592479955563784 for [0, 60d, 31d]).
5117    //
5118    // This is the ONLY reduction in the std/var/sem group that widens. pandas
5119    // RAISES for datetime64 var and sem ("does not support reduction"), so
5120    // those keep the Timedelta-only `collect_timedelta_ns_f64` gate rather than
5121    // inventing a value pandas refuses to produce.
5122    //
5123    // br-frankenpandas-d7zjp: PERIOD IS EXCLUDED HERE. pandas raises
5124    // "'PeriodArray' with dtype period[M] does not support reduction 'std'",
5125    // so widening std to Period alongside Datetime64 would invent a value —
5126    // and the family enum makes that mistake one line away, hence the guard.
5127    if let Some((td, family)) = collect_temporal_backing(values)
5128        && !matches!(family, TemporalFamily::Period(_))
5129    {
5130        if td.len() <= ddof {
5131            return Scalar::Timedelta64(Timedelta::NAT);
5132        }
5133        let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
5134        let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
5135        let var = sum_sq / (td.len() - ddof) as f64;
5136        return float_ns_to_timedelta(var.sqrt());
5137    }
5138    match nanvar(values, ddof) {
5139        Scalar::Float64(v) => Scalar::Float64(v.sqrt()),
5140        other => other,
5141    }
5142}
5143
5144/// Standard error of the mean over non-missing values.
5145///
5146/// Matches `pd.Series.sem(ddof=1)` / `scipy.stats.sem`. Computed as
5147/// `std(values, ddof) / sqrt(n)` where `n` is the non-missing count.
5148/// Returns `Null(NaN)` when `n <= ddof`.
5149pub fn nansem(values: &[Scalar], ddof: usize) -> Scalar {
5150    // Per br-frankenpandas-j8ntk: Timedelta64 sem preserves dtype.
5151    if let Some(td) = collect_timedelta_ns_f64(values) {
5152        if td.len() <= ddof {
5153            return Scalar::Timedelta64(Timedelta::NAT);
5154        }
5155        let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
5156        let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
5157        let var = sum_sq / (td.len() - ddof) as f64;
5158        let std = var.sqrt();
5159        return float_ns_to_timedelta(std / (td.len() as f64).sqrt());
5160    }
5161    let nums = collect_finite(values);
5162    if nums.len() <= ddof {
5163        return Scalar::Null(NullKind::NaN);
5164    }
5165    let n = nums.len();
5166    let mean = nums.iter().sum::<f64>() / n as f64;
5167    let sum_sq = nums.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
5168    let var = sum_sq / (n - ddof) as f64;
5169    let std = var.sqrt();
5170    Scalar::Float64(std / (n as f64).sqrt())
5171}
5172
5173/// Peak-to-peak range of non-missing values (max − min).
5174///
5175/// Matches `np.ptp` behavior on nan-safe inputs. Returns `Null(NaN)`
5176/// for empty or all-missing inputs.
5177pub fn nanptp(values: &[Scalar]) -> Scalar {
5178    // br-frankenpandas-axhhk: Datetime64 ptp is NOT a dtype-preserving sibling
5179    // of the Timedelta64 arm below — the span between two instants is a
5180    // DURATION, so pandas returns a Timedelta here (`s.max() - s.min()` on a
5181    // datetime64 Series). Subtract in i128 and narrow through the shared
5182    // opz27 helper so an unrepresentable span becomes NaT rather than a
5183    // fabricated extreme. Previously to_f64() errored on every element, `seen`
5184    // stayed false, and this returned Null(NaN).
5185    if is_datetime_input(values) {
5186        let (mut lo, mut hi) = (i64::MAX, i64::MIN);
5187        for value in values {
5188            if value.is_missing() {
5189                continue;
5190            }
5191            if let Scalar::Datetime64(ns) = value {
5192                lo = lo.min(*ns);
5193                hi = hi.max(*ns);
5194            }
5195        }
5196        return timedelta_ns_to_scalar(i128::from(hi) - i128::from(lo));
5197    }
5198    // Preserve every nanosecond in the uniformly-Timedelta64 case. Converting
5199    // to f64 before subtracting loses ranges below one f64 ULP beyond 104 days.
5200    // The Scalar fallback below retains mixed-family behavior.
5201    let (mut td_lo, mut td_hi) = (i64::MAX, i64::MIN);
5202    let mut saw_timedelta = false;
5203    let mut all_timedelta = true;
5204    for value in values {
5205        if value.is_missing() {
5206            continue;
5207        }
5208        match value {
5209            Scalar::Timedelta64(ns) => {
5210                saw_timedelta = true;
5211                td_lo = td_lo.min(*ns);
5212                td_hi = td_hi.max(*ns);
5213            }
5214            _ => {
5215                all_timedelta = false;
5216                break;
5217            }
5218        }
5219    }
5220    if all_timedelta && saw_timedelta {
5221        // Subtract in i128: the true range of two representable Timedeltas can
5222        // exceed i64 (max - min overflows), where live pandas 2.2.3 raises
5223        // OverflowError. Saturating here fabricated a finite Timedelta.max.
5224        return timedelta_ns_to_scalar(i128::from(td_hi) - i128::from(td_lo));
5225    }
5226    // Fused single-pass min/max (see `nansum`): track lo/hi while filtering, no
5227    // intermediate Vec<f64>. Bit-identical to the prior collect_finite two-pass:
5228    // `seen` is true exactly when collect_finite would be non-empty, and the
5229    // lo/hi comparisons fold the same finite values in the same order.
5230    let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
5231    let mut seen = false;
5232    for v in values {
5233        if v.is_missing() {
5234            continue;
5235        }
5236        if let Ok(x) = v.to_f64() {
5237            seen = true;
5238            if x < lo {
5239                lo = x;
5240            }
5241            if x > hi {
5242                hi = x;
5243            }
5244        }
5245    }
5246    if !seen {
5247        return Scalar::Null(NullKind::NaN);
5248    }
5249    Scalar::Float64(hi - lo)
5250}
5251
5252/// Sample skewness (bias-corrected, Fisher-Pearson) over non-missing values.
5253///
5254/// Matches `pd.Series.skew()`. Requires at least 3 non-missing values;
5255/// returns `Null(NaN)` otherwise, and when the sample standard deviation
5256/// is zero.
5257pub fn nanskew(values: &[Scalar]) -> Scalar {
5258    let nums = collect_finite(values);
5259    let n = nums.len() as f64;
5260    if n < 3.0 {
5261        return Scalar::Null(NullKind::NaN);
5262    }
5263    let mean = nums.iter().sum::<f64>() / n;
5264    // Accumulate both central moments while the collected values are hot. Each
5265    // sum still observes the same terms in the same order as the former two
5266    // iterator passes, preserving floating-point results bit-for-bit.
5267    let (mut m2, mut m3) = (0.0_f64, 0.0_f64);
5268    for x in nums {
5269        let delta = x - mean;
5270        // d2 reuse: 2 multiplies per element instead of 3. powi(3) lowers to two
5271        // multiplies of {delta, delta*delta}, and float MULTIPLY is commutative
5272        // bit-for-bit, so both sums observe the identical terms — the comment above
5273        // about preserving results bit-for-bit still holds. No ADDITION order changed.
5274        // (br-frankenpandas-8s4mb)
5275        let d2 = delta * delta;
5276        m2 += d2;
5277        m3 += d2 * delta;
5278    }
5279    let s2 = m2 / (n - 1.0);
5280    if s2 == 0.0 {
5281        return Scalar::Float64(0.0);
5282    }
5283    let s3 = s2.powf(1.5);
5284    Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
5285}
5286
5287/// Excess sample kurtosis (Fisher's definition, bias-corrected) over
5288/// non-missing values.
5289///
5290/// Matches `pd.Series.kurt()`. Requires at least 4 non-missing values;
5291/// returns `Null(NaN)` otherwise, and when the sample standard deviation
5292/// is zero.
5293pub fn nankurt(values: &[Scalar]) -> Scalar {
5294    let nums = collect_finite(values);
5295    let n = nums.len() as f64;
5296    if n < 4.0 {
5297        return Scalar::Null(NullKind::NaN);
5298    }
5299    let mean = nums.iter().sum::<f64>() / n;
5300    // Accumulate both central moments while the collected values are hot. Each
5301    // sum still observes the same terms in the same order as the former two
5302    // iterator passes, preserving floating-point results bit-for-bit.
5303    let (mut m2, mut m4) = (0.0_f64, 0.0_f64);
5304    for x in nums {
5305        let delta = x - mean;
5306        // d2 reuse; see `nanskew`. powi(4) lowers to (d*d)*(d*d), which is exactly
5307        // d2 * d2, so this is bit-identical.
5308        let d2 = delta * delta;
5309        m2 += d2;
5310        m4 += d2 * d2;
5311    }
5312    let s2 = m2 / (n - 1.0);
5313    if s2 == 0.0 {
5314        return Scalar::Float64(0.0);
5315    }
5316    let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
5317    let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
5318    Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
5319}
5320
5321/// Product of non-missing values. Returns 1.0 for empty input (matching pandas).
5322pub fn nanprod(values: &[Scalar]) -> Scalar {
5323    // Per br-frankenpandas-szq6a: pandas raises TypeError on
5324    // td_series.prod() because Timedelta² has no dimension. Returning the
5325    // misleading Float64(1.0) (empty-iterator default after collect_finite
5326    // drops every Timedelta64) is worse than surfacing missing. NaT
5327    // propagates the "type-incompatible" signal in lieu of a Result-level
5328    // error.
5329    if is_timedelta_input(values) {
5330        return Scalar::Null(NullKind::NaN);
5331    }
5332    // Fused single-pass fold (see `nansum`): filter missing / non-coercible and
5333    // multiply in one scan, no intermediate Vec<f64>. Bit-identical to
5334    // `collect_finite(..).iter().product()`: same finite values, same order,
5335    // same f64 `*` (Product for f64 == fold(1.0, *)); empty -> 1.0.
5336    let mut prod = 1.0_f64;
5337    for v in values {
5338        if v.is_missing() {
5339            continue;
5340        }
5341        if let Ok(x) = v.to_f64() {
5342            prod *= x;
5343        }
5344    }
5345    Scalar::Float64(prod)
5346}
5347
5348/// Cumulative sum respecting null propagation.
5349///
5350/// Per br-frankenpandas-x0x91: detect uniformly-Timedelta64 input
5351/// (allowing Null/NAT missing markers). Returns true when at least one
5352/// non-missing value is Timedelta64 and no other dtype appears.
5353fn is_timedelta_input(values: &[Scalar]) -> bool {
5354    let mut saw_td = false;
5355    for v in values {
5356        if v.is_missing() {
5357            continue;
5358        }
5359        match v {
5360            Scalar::Timedelta64(_) => saw_td = true,
5361            _ => return false,
5362        }
5363    }
5364    saw_td
5365}
5366
5367/// Datetime64 mirror of [`collect_timedelta_ns`], per br-frankenpandas-adv58.
5368///
5369/// Note the deliberate difference from [`is_datetime_input`]: the family is
5370/// marked on seeing the *variant*, before the missing check, so an ALL-NaT
5371/// datetime input still reports as the Datetime family with `count == 0`. That
5372/// is what lets `nanmean` return `Datetime64(NaT)` — preserving dtype the way
5373/// pandas does — instead of degrading to a numeric NaN. `collect_timedelta_ns`
5374/// has used this convention all along; matching it keeps the two families
5375/// symmetric.
5376fn collect_datetime_ns(values: &[Scalar]) -> Option<(i128, usize)> {
5377    let mut sum: i128 = 0;
5378    let mut count: usize = 0;
5379    let mut saw_datetime = false;
5380    for v in values {
5381        match v {
5382            Scalar::Datetime64(ns) => {
5383                saw_datetime = true;
5384                if v.is_missing() {
5385                    continue;
5386                }
5387                sum += i128::from(*ns);
5388                count += 1;
5389            }
5390            _ if v.is_missing() => continue,
5391            _ => return None,
5392        }
5393    }
5394    if saw_datetime {
5395        Some((sum, count))
5396    } else {
5397        None
5398    }
5399}
5400
5401/// Sibling of [`is_timedelta_input`] for Datetime64, per br-frankenpandas-axhhk.
5402///
5403/// `Datetime64::to_f64()` errors exactly like `Timedelta64::to_f64()` does, so
5404/// every reduction that routed datetimes through the f64 catch-all silently
5405/// produced `Null(NaN)`. Datetime64 orders exactly like its i64 nanosecond
5406/// backing, and NaT (`Timestamp::NAT`) is already filtered by `is_missing`.
5407fn is_datetime_input(values: &[Scalar]) -> bool {
5408    let mut saw_dt = false;
5409    for v in values {
5410        if v.is_missing() {
5411            continue;
5412        }
5413        match v {
5414            Scalar::Datetime64(_) => saw_dt = true,
5415            _ => return false,
5416        }
5417    }
5418    saw_dt
5419}
5420
5421/// Returns true for uniformly-Int64 input with optional missing markers.
5422fn is_int64_input(values: &[Scalar]) -> bool {
5423    let mut saw_int = false;
5424    for value in values {
5425        if value.is_missing() {
5426            continue;
5427        }
5428        match value {
5429            Scalar::Int64(_) => saw_int = true,
5430            _ => return false,
5431        }
5432    }
5433    saw_int
5434}
5435
5436/// First-position arg-extremum over a uniformly i64-backed scalar family.
5437/// True when every non-missing value is an Interval, per br-frankenpandas-2h9dm.
5438fn is_interval_input(values: &[Scalar]) -> bool {
5439    let mut saw_interval = false;
5440    for v in values {
5441        if v.is_missing() {
5442            continue;
5443        }
5444        match v {
5445            Scalar::Interval(_) => saw_interval = true,
5446            _ => return false,
5447        }
5448    }
5449    saw_interval
5450}
5451
5452/// Positional extreme over a uniformly-Interval input, per br-frankenpandas-2h9dm.
5453///
5454/// Intervals cannot use [`nanarg_i64`] (they are two f64s, not an i64 newtype)
5455/// and cannot use the f64 fallback in the callers (`to_f64` errors on them), so
5456/// they get this dedicated lexicographic (left, right) walk. `closed` is not
5457/// part of the comparison, for the reasons documented on `nanmin`.
5458///
5459/// Returns `None` if any bound is NaN: such an interval is not orderable and
5460/// pandas will not even construct one, so an arbitrary index would be worse
5461/// than declining. This is also why the comparison is a plain `<`/`>` on a
5462/// tuple rather than `partial_cmp().unwrap()`, which would panic.
5463fn nanarg_interval(values: &[Scalar], find_max: bool) -> Option<usize> {
5464    let mut best: Option<(usize, (f64, f64))> = None;
5465    for (index, value) in values.iter().enumerate() {
5466        if value.is_missing() {
5467            continue;
5468        }
5469        let Scalar::Interval(iv) = value else {
5470            continue;
5471        };
5472        if iv.left.is_nan() || iv.right.is_nan() {
5473            return None;
5474        }
5475        let key = (iv.left, iv.right);
5476        match best {
5477            None => best = Some((index, key)),
5478            // Strict comparison keeps the FIRST occurrence of a duplicated
5479            // extreme, which is what pandas' idxmin/idxmax return.
5480            Some((_, current)) if (find_max && key > current) || (!find_max && key < current) => {
5481                best = Some((index, key));
5482            }
5483            _ => {}
5484        }
5485    }
5486    best.map(|(index, _)| index)
5487}
5488
5489fn nanarg_i64(values: &[Scalar], find_max: bool) -> Option<usize> {
5490    let mut best: Option<(usize, i64)> = None;
5491    for (index, value) in values.iter().enumerate() {
5492        if value.is_missing() {
5493            continue;
5494        }
5495        // br-frankenpandas-axhhk: Datetime64 joins the typed i64 families here.
5496        // Its ns backing orders identically, and routing it through the f64
5497        // path instead returned None for any 2+-element datetime input.
5498        //
5499        // br-frankenpandas-d7zjp: Period cannot join this or-pattern — it is a
5500        // STRUCT, not an i64 newtype — so it contributes its ordinal here. The
5501        // caller has already established a single freq via
5502        // `collect_temporal_backing`, so these ordinals are comparable.
5503        let candidate = match value {
5504            Scalar::Int64(raw) | Scalar::Timedelta64(raw) | Scalar::Datetime64(raw) => raw,
5505            Scalar::Period(p) => &p.ordinal,
5506            _ => continue,
5507        };
5508        match best {
5509            None => best = Some((index, *candidate)),
5510            Some((_, current))
5511                if (find_max && *candidate > current) || (!find_max && *candidate < current) =>
5512            {
5513                best = Some((index, *candidate));
5514            }
5515            _ => {}
5516        }
5517    }
5518    best.map(|(index, _)| index)
5519}
5520
5521/// Per br-frankenpandas-x0x91: cumulative running aggregation over a
5522/// uniformly-Timedelta64 input. NaT/Null positions emit NaT and skip
5523/// the accumulator. Saturating i128 keeps overflow contained at i64
5524/// bounds when emitting.
5525fn timedelta_cumulative<F>(values: &[Scalar], init: i128, mut step: F) -> Vec<Scalar>
5526where
5527    F: FnMut(i128, i128) -> i128,
5528{
5529    let mut out = Vec::with_capacity(values.len());
5530    let mut running: i128 = init;
5531    for v in values {
5532        if v.is_missing() {
5533            out.push(Scalar::Null(NullKind::NaT));
5534            continue;
5535        }
5536        if let Scalar::Timedelta64(ns) = v {
5537            // `running` is exact: i128 has enough headroom that folding i64
5538            // nanoseconds cannot overflow it for any constructible input. Only
5539            // the narrowing to the output element can fail, so a running sum
5540            // that overflows i64 and later returns to range emits its true
5541            // value again instead of poisoning the tail — nothing is
5542            // fabricated at any index.
5543            running = step(running, i128::from(*ns));
5544            out.push(timedelta_ns_to_scalar(running));
5545        } else {
5546            out.push(Scalar::Null(NullKind::NaT));
5547        }
5548    }
5549    out
5550}
5551
5552/// Per br-frankenpandas-x0x91: running extrema (min/max) over a
5553/// uniformly-Timedelta64 input. `sentinel` is the identity element
5554/// (i64::MAX for min, i64::MIN for max) used until the first
5555/// non-missing value initializes the accumulator.
5556/// `make` builds the output scalar from the running ns value, so the same
5557/// walk serves Timedelta64 and — per br-frankenpandas-axhhk — Datetime64,
5558/// whose running extrema are Timestamps rather than durations.
5559fn timedelta_cumulative_extrema<F>(
5560    values: &[Scalar],
5561    sentinel: i64,
5562    make: TemporalFamily,
5563    mut step: F,
5564) -> Vec<Scalar>
5565where
5566    F: FnMut(i64, i64) -> i64,
5567{
5568    let mut out = Vec::with_capacity(values.len());
5569    let mut running: Option<i64> = None;
5570    for v in values {
5571        if v.is_missing() {
5572            out.push(Scalar::Null(NullKind::NaT));
5573            continue;
5574        }
5575        // br-frankenpandas-d7zjp: a Period contributes its ordinal.
5576        let raw = match v {
5577            Scalar::Timedelta64(ns) | Scalar::Datetime64(ns) => Some(*ns),
5578            Scalar::Period(p) => Some(p.ordinal),
5579            _ => None,
5580        };
5581        if let Some(ns) = raw.as_ref() {
5582            let new_val = match running {
5583                Some(prev) => step(prev, *ns),
5584                None => *ns,
5585            };
5586            running = Some(new_val);
5587            out.push(make.make(new_val));
5588        } else {
5589            out.push(Scalar::Null(NullKind::NaT));
5590        }
5591    }
5592    let _ = sentinel; // silence unused warning if closure ignores it
5593    out
5594}
5595
5596/// Matches `np.nancumsum` / `pd.Series.cumsum()`. Missing input positions
5597/// pass through as `Null(NaN)` in the output; the running sum ignores
5598/// those positions when accumulating.
5599/// Cumulative sum under an explicit overflow policy.
5600///
5601/// br-frankenpandas-fyr1z-wrap-signoff-s4lkx, DECIDED BY THE MAINTAINER: under
5602/// [`OverflowPolicy::Strict`] this REPRODUCES pandas' silent int64 wraparound,
5603/// because STRICT means bit-for-bit observable parity with the incumbent
5604/// including its quirks.
5605///
5606/// Verified against live pandas 2.2.3:
5607/// `Series([Timedelta.max, Timedelta.max]).cumsum()` returns
5608/// `[9223372036854775807, -2]` and the three-element case
5609/// `[max, -2, 9223372036854775805]` — exactly `wrapping_add` accumulation in
5610/// i64. Note the third element proves the accumulator KEEPS WRAPPING rather
5611/// than sticking: it is `(-2).wrapping_add(max)`.
5612///
5613/// Under every other policy this delegates to [`nancumsum`], which keeps the
5614/// exact-i128 accumulation and NaT-on-unrepresentable behaviour from
5615/// br-frankenpandas-opz27. See DISC-020.
5616#[must_use]
5617pub fn nancumsum_with_policy(values: &[Scalar], policy: OverflowPolicy) -> Vec<Scalar> {
5618    if !matches!(policy, OverflowPolicy::Strict) || !is_timedelta_input(values) {
5619        return nancumsum(values);
5620    }
5621    let mut out = Vec::with_capacity(values.len());
5622    let mut running: i64 = 0;
5623    for value in values {
5624        if value.is_missing() {
5625            out.push(Scalar::Null(NullKind::NaT));
5626            continue;
5627        }
5628        if let Scalar::Timedelta64(ns) = value {
5629            // Deliberately WRAPPING, not checked: this is the incumbent's
5630            // observable behaviour and STRICT exists to reproduce it.
5631            running = running.wrapping_add(*ns);
5632            out.push(Scalar::Timedelta64(running));
5633        } else {
5634            out.push(Scalar::Null(NullKind::NaT));
5635        }
5636    }
5637    out
5638}
5639
5640pub fn nancumsum(values: &[Scalar]) -> Vec<Scalar> {
5641    // Per br-frankenpandas-x0x91: when input is uniformly Timedelta64 (with
5642    // optional NaT/Null missing markers), preserve Timedelta dtype to match
5643    // pandas td_series.cumsum() returning Timedelta64.
5644    if is_timedelta_input(values) {
5645        return timedelta_cumulative(values, 0_i128, |acc, x| acc.saturating_add(x));
5646    }
5647    let mut out = Vec::with_capacity(values.len());
5648    let mut running = 0.0_f64;
5649    for v in values {
5650        if v.is_missing() {
5651            out.push(Scalar::Null(NullKind::NaN));
5652            continue;
5653        }
5654        match v.to_f64() {
5655            Ok(x) if !x.is_nan() => {
5656                running += x;
5657                out.push(Scalar::Float64(running));
5658            }
5659            _ => out.push(Scalar::Null(NullKind::NaN)),
5660        }
5661    }
5662    out
5663}
5664
5665/// Cumulative product respecting null propagation.
5666///
5667/// Matches `np.nancumprod` / `pd.Series.cumprod()`. Missing positions
5668/// pass through as `Null(NaN)` without advancing the running product.
5669pub fn nancumprod(values: &[Scalar]) -> Vec<Scalar> {
5670    let mut out = Vec::with_capacity(values.len());
5671    let mut running = 1.0_f64;
5672    for v in values {
5673        if v.is_missing() {
5674            out.push(Scalar::Null(NullKind::NaN));
5675            continue;
5676        }
5677        match v.to_f64() {
5678            Ok(x) if !x.is_nan() => {
5679                running *= x;
5680                out.push(Scalar::Float64(running));
5681            }
5682            _ => out.push(Scalar::Null(NullKind::NaN)),
5683        }
5684    }
5685    out
5686}
5687
5688/// Cumulative maximum respecting null propagation.
5689///
5690/// Matches `pd.Series.cummax()`. Missing positions pass through as
5691/// `Null(NaN)` without updating the running maximum. The first
5692/// non-missing value initializes the running maximum.
5693pub fn nancummax(values: &[Scalar]) -> Vec<Scalar> {
5694    // Per br-frankenpandas-x0x91 (Timedelta64), -axhhk (Datetime64) and
5695    // -d7zjp (Period): every uniformly-temporal family preserves its dtype
5696    // here. Without this the f64 path below errors on every element and
5697    // produces an all-NaN column. A mixed-freq Period input is not one family,
5698    // so it correctly does not take this path.
5699    if let Some((_, family)) = collect_temporal_backing(values) {
5700        return timedelta_cumulative_extrema(values, i64::MAX, family, |acc, x| acc.max(x));
5701    }
5702    let mut out = Vec::with_capacity(values.len());
5703    let mut running: Option<f64> = None;
5704    for v in values {
5705        if v.is_missing() {
5706            out.push(Scalar::Null(NullKind::NaN));
5707            continue;
5708        }
5709        match v.to_f64() {
5710            Ok(x) if !x.is_nan() => {
5711                let new_val = match running {
5712                    Some(prev) => prev.max(x),
5713                    None => x,
5714                };
5715                running = Some(new_val);
5716                out.push(Scalar::Float64(new_val));
5717            }
5718            _ => out.push(Scalar::Null(NullKind::NaN)),
5719        }
5720    }
5721    out
5722}
5723
5724/// Cumulative minimum respecting null propagation.
5725///
5726/// Matches `pd.Series.cummin()`. Symmetric to `nancummax`.
5727pub fn nancummin(values: &[Scalar]) -> Vec<Scalar> {
5728    // Per br-frankenpandas-x0x91: Timedelta64 preserves dtype.
5729    if is_timedelta_input(values) {
5730        return timedelta_cumulative_extrema(
5731            values,
5732            i64::MIN,
5733            TemporalFamily::Timedelta,
5734            |acc, x| acc.min(x),
5735        );
5736    }
5737    // br-frankenpandas-axhhk / -d7zjp: Datetime64 and Period siblings.
5738    if let Some((_, family)) = collect_temporal_backing(values) {
5739        return timedelta_cumulative_extrema(values, i64::MIN, family, |acc, x| acc.min(x));
5740    }
5741    let mut out = Vec::with_capacity(values.len());
5742    let mut running: Option<f64> = None;
5743    for v in values {
5744        if v.is_missing() {
5745            out.push(Scalar::Null(NullKind::NaN));
5746            continue;
5747        }
5748        match v.to_f64() {
5749            Ok(x) if !x.is_nan() => {
5750                let new_val = match running {
5751                    Some(prev) => prev.min(x),
5752                    None => x,
5753                };
5754                running = Some(new_val);
5755                out.push(Scalar::Float64(new_val));
5756            }
5757            _ => out.push(Scalar::Null(NullKind::NaN)),
5758        }
5759    }
5760    out
5761}
5762
5763/// Linear-interpolation quantile over non-missing numeric values.
5764///
5765/// Matches `np.nanquantile(values, q)` with `interpolation='linear'`.
5766/// Returns `Null(NaN)` for empty inputs or when `q` is outside
5767/// `[0.0, 1.0]`.
5768pub fn nanquantile(values: &[Scalar], q: f64) -> Scalar {
5769    if !(0.0..=1.0).contains(&q) {
5770        return Scalar::Null(NullKind::NaN);
5771    }
5772    // Per br-frankenpandas-5djk7: pandas td_series.quantile(q) returns
5773    // Timedelta64 with linear-interpolated ns. Was silently NaN before.
5774    if let Some((mut td, make)) = collect_temporal_backing(values) {
5775        if td.is_empty() {
5776            return make.nat();
5777        }
5778        let n = td.len();
5779        if n == 1 {
5780            return float_ns_to_temporal(td[0], make);
5781        }
5782        let pos = q * (n - 1) as f64;
5783        let lo = pos.floor() as usize;
5784        let hi = pos.ceil() as usize;
5785        // O(n) selection instead of a full sort (see the numeric arm below):
5786        // select the lo-th order statistic; the (lo+1)-th is the MIN of the
5787        // right partition. Bit-identical (finite ns, values-only order stats).
5788        let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
5789        let (_left, lo_ref, right) = td.select_nth_unstable_by(lo, cmp);
5790        let lo_val = *lo_ref;
5791        let ns = if lo == hi {
5792            lo_val
5793        } else {
5794            let hi_val = right.iter().copied().fold(f64::INFINITY, f64::min);
5795            let weight = pos - lo as f64;
5796            lo_val + (hi_val - lo_val) * weight
5797        };
5798        return float_ns_to_temporal(ns, make);
5799    }
5800    let mut nums = collect_finite(values);
5801    if nums.is_empty() {
5802        return Scalar::Null(NullKind::NaN);
5803    }
5804    let n = nums.len();
5805    if n == 1 {
5806        return Scalar::Float64(nums[0]);
5807    }
5808    let pos = q * (n - 1) as f64;
5809    let lo = pos.floor() as usize;
5810    let hi = pos.ceil() as usize;
5811    // O(n) selection instead of a full sort: select the `lo`-th order statistic;
5812    // when interpolation is needed (hi == lo+1) the (lo+1)-th smallest is the
5813    // MIN of the right partition. Bit-identical to the sort path (same
5814    // nums[lo]/nums[hi] values, since order statistics depend only on values).
5815    let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
5816    let (_left, lo_ref, right) = nums.select_nth_unstable_by(lo, cmp);
5817    let lo_val = *lo_ref;
5818    if lo == hi {
5819        return Scalar::Float64(lo_val);
5820    }
5821    let hi_val = right.iter().copied().fold(f64::INFINITY, f64::min);
5822    let weight = pos - lo as f64;
5823    Scalar::Float64(lo_val + (hi_val - lo_val) * weight)
5824}
5825
5826/// Position (in the original slice) of the non-missing maximum.
5827///
5828/// Matches `np.nanargmax`. Returns `None` if every value is missing.
5829/// Ties resolve to the first position seen (matching numpy).
5830pub fn nanargmax(values: &[Scalar]) -> Option<usize> {
5831    // Compare typed 64-bit families directly: f64 coercion loses ordering for
5832    // adjacent Int64 values beyond the 53-bit exactness boundary.
5833    // br-frankenpandas-axhhk: Datetime64 belongs here too — it not only loses
5834    // ordering under f64, its to_f64() errors outright, so it returned None.
5835    if is_int64_input(values) || collect_temporal_backing(values).is_some() {
5836        return nanarg_i64(values, true);
5837    }
5838    // br-frankenpandas-2h9dm: Intervals order lexicographically by
5839    // (left, right) and fit neither the i64 walk above nor the f64 fallback
5840    // below, whose to_f64() errors on them — so they returned None.
5841    if is_interval_input(values) {
5842        return nanarg_interval(values, true);
5843    }
5844    let mut best: Option<(usize, f64)> = None;
5845    for (i, v) in values.iter().enumerate() {
5846        if v.is_missing() {
5847            continue;
5848        }
5849        if let Ok(x) = v.to_f64() {
5850            if x.is_nan() {
5851                continue;
5852            }
5853            match best {
5854                None => best = Some((i, x)),
5855                Some((_, cur)) if x > cur => best = Some((i, x)),
5856                _ => {}
5857            }
5858        }
5859    }
5860    best.map(|(i, _)| i)
5861}
5862
5863/// Position (in the original slice) of the non-missing minimum.
5864///
5865/// Matches `np.nanargmin`. Returns `None` if every value is missing.
5866pub fn nanargmin(values: &[Scalar]) -> Option<usize> {
5867    // See nanargmax: preserve exact ordering for typed 64-bit families
5868    // (Datetime64 included, per br-frankenpandas-axhhk).
5869    if is_int64_input(values) || collect_temporal_backing(values).is_some() {
5870        return nanarg_i64(values, false);
5871    }
5872    // br-frankenpandas-2h9dm: Interval sibling of the branch in `nanargmax`.
5873    if is_interval_input(values) {
5874        return nanarg_interval(values, false);
5875    }
5876    let mut best: Option<(usize, f64)> = None;
5877    for (i, v) in values.iter().enumerate() {
5878        if v.is_missing() {
5879            continue;
5880        }
5881        if let Ok(x) = v.to_f64() {
5882            if x.is_nan() {
5883                continue;
5884            }
5885            match best {
5886                None => best = Some((i, x)),
5887                Some((_, cur)) if x < cur => best = Some((i, x)),
5888                _ => {}
5889            }
5890        }
5891    }
5892    best.map(|(i, _)| i)
5893}
5894
5895/// Count of unique non-missing values.
5896pub fn nannunique(values: &[Scalar]) -> Scalar {
5897    use rustc_hash::FxHashSet;
5898    #[derive(Hash, PartialEq, Eq)]
5899    enum ScalarKey<'a> {
5900        Bool(bool),
5901        Int64(i64),
5902        FloatBits(u64),
5903        Utf8(&'a str),
5904        Timedelta64(i64),
5905        Datetime64(i64),
5906        Period(i64, PeriodFreq),
5907        Interval(u64, u64, IntervalClosed),
5908    }
5909
5910    let mut seen = FxHashSet::default();
5911    for val in values {
5912        if val.is_missing() {
5913            continue;
5914        }
5915        let key = match val {
5916            Scalar::Bool(v) => ScalarKey::Bool(*v),
5917            Scalar::Int64(v) => ScalarKey::Int64(*v),
5918            Scalar::Float64(v) => {
5919                let normalized = if *v == 0.0 { 0.0 } else { *v };
5920                ScalarKey::FloatBits(normalized.to_bits())
5921            }
5922            Scalar::Utf8(v) => ScalarKey::Utf8(v.as_str()),
5923            Scalar::Timedelta64(v) => ScalarKey::Timedelta64(*v),
5924            Scalar::Datetime64(v) => ScalarKey::Datetime64(*v),
5925            Scalar::Period(p) => ScalarKey::Period(p.ordinal, p.freq),
5926            Scalar::Interval(v) => ScalarKey::Interval(
5927                normalized_float_bits(v.left),
5928                normalized_float_bits(v.right),
5929                v.closed,
5930            ),
5931            Scalar::Null(_) => continue,
5932        };
5933        seen.insert(key);
5934    }
5935    Scalar::Int64(seen.len() as i64)
5936}
5937
5938fn normalized_float_bits(value: f64) -> u64 {
5939    let normalized = if value == 0.0 { 0.0 } else { value };
5940    normalized.to_bits()
5941}
5942
5943// ── Interval types (br-frankenpandas-j8k4 Phase 1) ──────────────────────
5944//
5945// Scaffolding for pandas `pd.Interval` / `pd.IntervalIndex` / `pd.IntervalDtype`.
5946//
5947// Phase 1 ships float-valued intervals only (matches `cut`/`qcut` output on
5948// numeric bins — the dominant pandas use case). Generic-subtype intervals
5949// over Int64 / Timestamp are deferred to Phase 2 alongside the DType::Interval
5950// enum-variant wiring. See br-j8k4 for the phased roadmap.
5951//
5952// Semantics mirror pandas: closed tells which endpoints are included.
5953//   Left    → [left, right)
5954//   Right   → (left, right]       ← pandas default
5955//   Both    → [left, right]
5956//   Neither → (left, right)
5957
5958/// Endpoint-inclusion policy for an `Interval`.
5959///
5960/// Matches pandas `pd.Interval.closed` / `pd.IntervalDtype.closed` string
5961/// values ("left" / "right" / "both" / "neither").
5962#[derive(
5963    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize,
5964)]
5965#[serde(rename_all = "snake_case")]
5966#[non_exhaustive]
5967pub enum IntervalClosed {
5968    /// `[left, right)` — left-inclusive, right-exclusive.
5969    Left,
5970    /// `(left, right]` — left-exclusive, right-inclusive. Pandas default.
5971    #[default]
5972    Right,
5973    /// `[left, right]` — both endpoints included.
5974    Both,
5975    /// `(left, right)` — neither endpoint included.
5976    Neither,
5977}
5978
5979impl IntervalClosed {
5980    /// Left endpoint included?
5981    #[must_use]
5982    pub fn left_closed(self) -> bool {
5983        matches!(self, Self::Left | Self::Both)
5984    }
5985
5986    /// Right endpoint included?
5987    #[must_use]
5988    pub fn right_closed(self) -> bool {
5989        matches!(self, Self::Right | Self::Both)
5990    }
5991}
5992
5993impl std::fmt::Display for IntervalClosed {
5994    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5995        match self {
5996            Self::Left => write!(f, "left"),
5997            Self::Right => write!(f, "right"),
5998            Self::Both => write!(f, "both"),
5999            Self::Neither => write!(f, "neither"),
6000        }
6001    }
6002}
6003
6004/// A bounded numeric interval between two `f64` endpoints.
6005///
6006/// Matches `pd.Interval(left, right, closed)` on the numeric-subtype path.
6007/// Accessors match pandas: `.left`, `.right`, `.closed`, `.length`, `.mid`,
6008/// `.contains`, `.is_empty`, `.overlaps`.
6009#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
6010pub struct Interval {
6011    pub left: f64,
6012    pub right: f64,
6013    #[serde(default)]
6014    pub closed: IntervalClosed,
6015}
6016
6017impl Interval {
6018    /// Construct an interval. No validation on `left <= right` — pandas also
6019    /// accepts reversed intervals (they're non-empty only if empty-by-design).
6020    #[must_use]
6021    pub const fn new(left: f64, right: f64, closed: IntervalClosed) -> Self {
6022        Self {
6023            left,
6024            right,
6025            closed,
6026        }
6027    }
6028
6029    /// `right - left` (pandas `.length`). Negative for reversed intervals.
6030    #[must_use]
6031    pub fn length(&self) -> f64 {
6032        self.right - self.left
6033    }
6034
6035    /// Midpoint `(left + right) / 2` (pandas `.mid`).
6036    #[must_use]
6037    pub fn mid(&self) -> f64 {
6038        (self.left + self.right) / 2.0
6039    }
6040
6041    /// Empty iff endpoints coincide AND at least one side is open.
6042    /// Pandas semantics: `pd.Interval(3, 3, 'right').is_empty → True`.
6043    #[must_use]
6044    pub fn is_empty(&self) -> bool {
6045        self.left == self.right && !matches!(self.closed, IntervalClosed::Both)
6046    }
6047
6048    /// Does `value` fall inside this interval?
6049    ///
6050    /// NaN always returns false, matching pandas `pd.Interval.__contains__`
6051    /// behavior (NaN doesn't compare equal to anything).
6052    #[must_use]
6053    pub fn contains(&self, value: f64) -> bool {
6054        if value.is_nan() {
6055            return false;
6056        }
6057        let left_ok = if self.closed.left_closed() {
6058            value >= self.left
6059        } else {
6060            value > self.left
6061        };
6062        let right_ok = if self.closed.right_closed() {
6063            value <= self.right
6064        } else {
6065            value < self.right
6066        };
6067        left_ok && right_ok
6068    }
6069
6070    /// Do `self` and `other` share any point?
6071    ///
6072    /// Matches `pd.Interval.overlaps(other)`. Two intervals overlap iff the
6073    /// max of their lefts is less than the min of their rights, with
6074    /// endpoint-inclusion determining the strictness of the comparison when
6075    /// they touch exactly.
6076    #[must_use]
6077    pub fn overlaps(&self, other: &Self) -> bool {
6078        if self.left > other.right || other.left > self.right {
6079            return false;
6080        }
6081        // Touching-at-a-point: overlap iff both sides at that touchpoint are closed.
6082        if self.right == other.left {
6083            return self.closed.right_closed() && other.closed.left_closed();
6084        }
6085        if other.right == self.left {
6086            return other.closed.right_closed() && self.closed.left_closed();
6087        }
6088        true
6089    }
6090
6091    /// Parse an interval string. Supports bracket notation:
6092    /// - '[0, 1]' -> closed on both ends
6093    /// - '(0, 1)' -> open on both ends
6094    /// - '[0, 1)' -> closed left, open right (pandas default)
6095    /// - '(0, 1]' -> open left, closed right
6096    pub fn parse(s: &str) -> Result<Self, TypeError> {
6097        let s = s.trim();
6098        if s.len() < 5 {
6099            return Err(TypeError::ValueNotParseable {
6100                value: s.to_string(),
6101                target: "Interval".to_string(),
6102            });
6103        }
6104
6105        let first_char = s.chars().next().unwrap();
6106        let last_char = s.chars().last().unwrap();
6107
6108        let left_closed = match first_char {
6109            '[' => true,
6110            '(' => false,
6111            _ => {
6112                return Err(TypeError::ValueNotParseable {
6113                    value: s.to_string(),
6114                    target: "Interval".to_string(),
6115                });
6116            }
6117        };
6118
6119        let right_closed = match last_char {
6120            ']' => true,
6121            ')' => false,
6122            _ => {
6123                return Err(TypeError::ValueNotParseable {
6124                    value: s.to_string(),
6125                    target: "Interval".to_string(),
6126                });
6127            }
6128        };
6129
6130        let closed = match (left_closed, right_closed) {
6131            (true, true) => IntervalClosed::Both,
6132            (true, false) => IntervalClosed::Left,
6133            (false, true) => IntervalClosed::Right,
6134            (false, false) => IntervalClosed::Neither,
6135        };
6136
6137        let inner = &s[1..s.len() - 1];
6138        let Some((left_text, right_text)) = inner.split_once(',') else {
6139            return Err(TypeError::ValueNotParseable {
6140                value: s.to_string(),
6141                target: "Interval".to_string(),
6142            });
6143        };
6144        if right_text.contains(',') {
6145            return Err(TypeError::ValueNotParseable {
6146                value: s.to_string(),
6147                target: "Interval".to_string(),
6148            });
6149        }
6150
6151        let left: f64 = left_text
6152            .trim()
6153            .parse()
6154            .map_err(|_| TypeError::ValueNotParseable {
6155                value: s.to_string(),
6156                target: "Interval".to_string(),
6157            })?;
6158
6159        let right: f64 = right_text
6160            .trim()
6161            .parse()
6162            .map_err(|_| TypeError::ValueNotParseable {
6163                value: s.to_string(),
6164                target: "Interval".to_string(),
6165            })?;
6166
6167        Ok(Self::new(left, right, closed))
6168    }
6169}
6170
6171impl std::fmt::Display for Interval {
6172    /// Matches `str(pd.Interval(...))` for the `interval[float64]` subtype, which
6173    /// is the only subtype FrankenPandas stores (f64 endpoints): the endpoints
6174    /// render with Python `str(float)` semantics, so whole numbers KEEP ".0"
6175    /// (`str(pd.Interval(0.0, 5.0, 'right'))` is `"(0.0, 5.0]"`, not `"(0, 5]"`).
6176    /// Verified vs pandas 2.2.3 across whole/fractional/negative/scientific
6177    /// endpoints. (br-frankenpandas-5xw1b)
6178    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6179        let left_bracket = if self.closed.left_closed() { '[' } else { '(' };
6180        let right_bracket = if self.closed.right_closed() { ']' } else { ')' };
6181        write!(
6182            f,
6183            "{left_bracket}{}, {}{right_bracket}",
6184            float_to_string_for_astype(self.left),
6185            float_to_string_for_astype(self.right)
6186        )
6187    }
6188}
6189
6190// ── interval_range builders (br-frankenpandas-xaom — Phase 2 of j8k4) ────
6191
6192/// Build `periods` equal-width intervals spanning `[start, end]`.
6193///
6194/// Matches `pd.interval_range(start, end, periods=N, closed=...)` for the
6195/// numeric-subtype case. Returns exactly `periods` intervals; when
6196/// `periods == 0` or `start >= end`, returns an empty vector (matches
6197/// pandas's empty IntervalIndex).
6198///
6199/// ```
6200/// use fp_types::{interval_range_by_periods, IntervalClosed};
6201/// let bins = interval_range_by_periods(0.0, 10.0, 5, IntervalClosed::Right);
6202/// assert_eq!(bins.len(), 5);
6203/// assert_eq!(bins[0].left, 0.0);
6204/// assert_eq!(bins[0].right, 2.0);
6205/// assert_eq!(bins[4].right, 10.0);
6206/// ```
6207#[must_use]
6208pub fn interval_range_by_periods(
6209    start: f64,
6210    end: f64,
6211    periods: usize,
6212    closed: IntervalClosed,
6213) -> Vec<Interval> {
6214    if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
6215        return Vec::new();
6216    }
6217    let step = (end - start) / (periods as f64);
6218    let mut out = Vec::with_capacity(periods);
6219    for i in 0..periods {
6220        let left = start + step * (i as f64);
6221        // Use end exactly for the final right edge to avoid float drift.
6222        let right = if i + 1 == periods {
6223            end
6224        } else {
6225            start + step * ((i + 1) as f64)
6226        };
6227        out.push(Interval::new(left, right, closed));
6228    }
6229    out
6230}
6231
6232/// Build equal-`step`-width intervals spanning `[start, end]`.
6233///
6234/// Matches `pd.interval_range(start, end, freq=step, closed=...)` for the
6235/// numeric-subtype case. `step` must be finite and positive; `(end - start)`
6236/// must be an integer multiple of `step` (within float tolerance) — pandas
6237/// raises `ValueError` otherwise; this fn returns `Err(TypeError::IntervalStepDoesNotDivide)`.
6238///
6239/// Returns an empty vector when `start == end` (matches pandas' zero-bin
6240/// IntervalIndex); returns an empty vector when `start > end` (pandas also
6241/// returns empty rather than erroring in this case).
6242pub fn interval_range_by_step(
6243    start: f64,
6244    end: f64,
6245    step: f64,
6246    closed: IntervalClosed,
6247) -> Result<Vec<Interval>, TypeError> {
6248    if !step.is_finite() || !step.is_sign_positive() || step == 0.0 {
6249        return Err(TypeError::InvalidIntervalStep { step });
6250    }
6251    if !start.is_finite() || !end.is_finite() || start >= end {
6252        return Ok(Vec::new());
6253    }
6254    let span = end - start;
6255    let periods_f = span / step;
6256    let periods = periods_f.round() as i64;
6257    if periods <= 0 {
6258        return Ok(Vec::new());
6259    }
6260    let reconstructed = step * (periods as f64);
6261    // Relative tolerance: allow float-rounding noise proportional to span.
6262    if (span - reconstructed).abs() > span.abs() * 1e-9 + 1e-12 {
6263        return Err(TypeError::IntervalStepDoesNotDivide { step, span });
6264    }
6265    let periods = periods as usize;
6266    let mut out = Vec::with_capacity(periods);
6267    for i in 0..periods {
6268        let left = start + step * (i as f64);
6269        let right = if i + 1 == periods {
6270            end
6271        } else {
6272            start + step * ((i + 1) as f64)
6273        };
6274        out.push(Interval::new(left, right, closed));
6275    }
6276    Ok(out)
6277}
6278
6279// ── Period types (br-frankenpandas-epoj Phase 1) ────────────────────────
6280//
6281// Scaffolding for pandas `pd.Period` / `pd.PeriodIndex` / `pd.PeriodDtype`.
6282//
6283// A Period is a calendar *span* (Q1 2024, Jan 2024, 2024-03-15), distinct
6284// from a Timestamp (an instant). Phase 1 ships the PeriodFreq enum +
6285// Period struct with ordinal-based arithmetic (Period + n, Period - Period),
6286// Display in pandas notation, and parse from standard strings. Calendar-
6287// conversion (ordinal ↔ ymd) and DType::Period wiring land in Phase 2.
6288
6289/// Period frequency code. Matches pandas offset alias core set.
6290///
6291/// The ordinal axis is frequency-specific: for Monthly, ordinal 0 is a
6292/// fixed anchor (pandas uses months since 1970-01). Phase 1 doesn't
6293/// commit to a specific epoch yet — the ordinal scheme is opaque until
6294/// Phase 2 wires calendar arithmetic. What Phase 1 DOES nail down is:
6295/// same-freq Periods compare + subtract; Period + i64 shifts by `n`
6296/// periods of the declared frequency.
6297#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
6298#[serde(rename_all = "SCREAMING-KEBAB-CASE")]
6299#[non_exhaustive]
6300pub enum PeriodFreq {
6301    /// `Y-DEC` / `A` / `Y` — annual periods.
6302    Annual,
6303    /// `Q-DEC` / `Q` — quarterly periods.
6304    Quarterly,
6305    /// `M` — monthly periods.
6306    Monthly,
6307    /// `W-SUN` / `W` — weekly periods.
6308    Weekly,
6309    /// `D` — daily periods.
6310    Daily,
6311    /// `B` — business-day periods.
6312    Business,
6313    /// `h` / `H` — hourly periods.
6314    Hourly,
6315    /// `min` / `T` — minutely periods.
6316    Minutely,
6317    /// `s` / `S` — secondly periods.
6318    Secondly,
6319    /// `ms` — millisecond periods. NOT `MS`, which pandas reads as month start.
6320    Milliseconds,
6321    /// `us` / `US` — microsecond periods.
6322    Microseconds,
6323    /// `ns` / `NS` — nanosecond periods.
6324    Nanoseconds,
6325}
6326
6327impl PeriodFreq {
6328    /// Parse a pandas-style frequency alias. Recognizes the common subset
6329    /// (Y-DEC/A/Y, Q-DEC/Q, M, W-SUN/W, D, B, h/H, min/T, s/S) plus the
6330    /// sub-second units ms, us/US, ns/NS.
6331    ///
6332    /// Case-insensitive with ONE exception: bare `MS` is month start in pandas,
6333    /// not milliseconds, and is refused here the way pandas refuses it for
6334    /// `to_period`. See the check at the top of the body.
6335    pub fn parse(alias: &str) -> Option<Self> {
6336        // ⚠️ CASE MATTERS FOR EXACTLY ONE ALIAS, and this parser uppercases
6337        // everything. MEASURED, live pandas 2.2.3, Timestamp.to_period(f):
6338        //     'ms' -> millisecond      'Ms' -> millisecond
6339        //     'MS' -> ValueError       (it is month start, a date_range-only freq)
6340        //     'us' -> microsecond      'US' -> microsecond
6341        //     'ns' -> nanosecond       'NS' -> nanosecond
6342        // So only the fully-capitalised `MS` is excluded; every other casing of
6343        // "ms" is milliseconds, while us/ns are case-insensitive and belong in
6344        // the table below. Checked here, before the uppercase collapses it.
6345        if alias.eq_ignore_ascii_case("ms") && alias != "MS" {
6346            return Some(Self::Milliseconds);
6347        }
6348        match alias.to_ascii_uppercase().as_str() {
6349            "A" | "Y" | "A-DEC" | "Y-DEC" | "ANNUAL" | "YEARLY" => Some(Self::Annual),
6350            "Q" | "Q-DEC" | "QUARTERLY" => Some(Self::Quarterly),
6351            "M" | "MONTHLY" => Some(Self::Monthly),
6352            "W" | "W-SUN" | "WEEKLY" => Some(Self::Weekly),
6353            "D" | "DAILY" => Some(Self::Daily),
6354            "B" | "BUSINESS" => Some(Self::Business),
6355            "H" | "HOURLY" => Some(Self::Hourly),
6356            "T" | "MIN" | "MINUTELY" => Some(Self::Minutely),
6357            "S" | "SECONDLY" => Some(Self::Secondly),
6358            "US" | "MICROSECOND" | "MICROSECONDS" => Some(Self::Microseconds),
6359            "NS" | "NANOSECOND" | "NANOSECONDS" => Some(Self::Nanoseconds),
6360            // The spelled-out form only; bare "MS" is deliberately absent, and
6361            // every other casing of it was taken above.
6362            "MILLISECOND" | "MILLISECONDS" => Some(Self::Milliseconds),
6363            _ => None,
6364        }
6365    }
6366
6367    /// Canonical pandas alias string.
6368    #[must_use]
6369    pub const fn alias(self) -> &'static str {
6370        match self {
6371            Self::Annual => "Y-DEC",
6372            Self::Quarterly => "Q-DEC",
6373            Self::Monthly => "M",
6374            Self::Weekly => "W-SUN",
6375            Self::Daily => "D",
6376            Self::Business => "B",
6377            Self::Hourly => "h",
6378            Self::Minutely => "min",
6379            Self::Secondly => "s",
6380            Self::Milliseconds => "ms",
6381            Self::Microseconds => "us",
6382            Self::Nanoseconds => "ns",
6383        }
6384    }
6385
6386    /// Resolution word for `PeriodIndex.resolution`, or `None` where pandas has
6387    /// no answer.
6388    ///
6389    /// ⚠️ THIS IS NOT THE ALIAS TABLE. pandas' `.resolution` names the period's
6390    /// *component*, in the same vocabulary `DatetimeIndex::resolution` already
6391    /// uses here -- it is not the frequency string, which is what
6392    /// [`PeriodFreq::alias`] is for. MEASURED, live pandas 2.2.3, one-element
6393    /// `PeriodIndex` per freq:
6394    ///     Y   -> 'year'        Q   -> 'quarter'     M  -> 'month'
6395    ///     D   -> 'day'         h   -> 'hour'        min-> 'minute'
6396    ///     s   -> 'second'
6397    ///     W   -> raises AttributeError
6398    ///     B   -> raises AttributeError
6399    /// Every arm below previously returned the alias instead ("A-DEC", "M", "H",
6400    /// "T", "S", ...), so all nine disagreed with the incumbent; W and B answered
6401    /// where pandas refuses. The refusal is modelled as `None` rather than a
6402    /// wrong word, because the caller already returns `Option` for the empty
6403    /// index and pandas' own failure there is an absence, not a value.
6404    #[must_use]
6405    pub const fn resolution(self) -> Option<&'static str> {
6406        match self {
6407            Self::Annual => Some("year"),
6408            Self::Quarterly => Some("quarter"),
6409            Self::Monthly => Some("month"),
6410            Self::Daily => Some("day"),
6411            Self::Hourly => Some("hour"),
6412            Self::Minutely => Some("minute"),
6413            Self::Secondly => Some("second"),
6414            Self::Milliseconds => Some("millisecond"),
6415            Self::Microseconds => Some("microsecond"),
6416            Self::Nanoseconds => Some("nanosecond"),
6417            // pandas' Week and BusinessDay offsets carry no `_resolution_obj`,
6418            // so `.resolution` raises AttributeError rather than answering.
6419            Self::Weekly | Self::Business => None,
6420        }
6421    }
6422}
6423
6424impl std::fmt::Display for PeriodFreq {
6425    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6426        f.write_str(self.alias())
6427    }
6428}
6429
6430/// A single pandas-style Period value.
6431///
6432/// Stored as an integer ordinal on a frequency-specific axis plus the
6433/// frequency code. Two Periods with different `freq` are incompatible —
6434/// arithmetic and comparison require same-freq operands.
6435#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
6436pub struct Period {
6437    pub ordinal: i64,
6438    pub freq: PeriodFreq,
6439}
6440
6441impl Period {
6442    #[must_use]
6443    pub const fn new(ordinal: i64, freq: PeriodFreq) -> Self {
6444        Self { ordinal, freq }
6445    }
6446
6447    /// Integer position on this period's frequency axis, matching
6448    /// `pd.Period.ordinal`.
6449    #[must_use]
6450    pub const fn ordinal(&self) -> i64 {
6451        self.ordinal
6452    }
6453
6454    /// Frequency code for this period, matching `pd.Period.freq`.
6455    #[must_use]
6456    pub const fn freq(&self) -> PeriodFreq {
6457        self.freq
6458    }
6459
6460    /// Canonical pandas frequency alias, matching `pd.Period.freqstr`.
6461    #[must_use]
6462    pub const fn freqstr(&self) -> &'static str {
6463        self.freq.alias()
6464    }
6465
6466    /// Same-freq ordinal comparison. Returns `None` if `freq` differs —
6467    /// caller decides whether that's an error or a panic site.
6468    #[must_use]
6469    pub fn cmp_same_freq(&self, other: &Self) -> Option<std::cmp::Ordering> {
6470        if self.freq != other.freq {
6471            return None;
6472        }
6473        Some(self.ordinal.cmp(&other.ordinal))
6474    }
6475
6476    /// Shift by `n` periods of the current frequency.
6477    /// Matches `pd.Period + n` and `pd.Period - n`.
6478    #[must_use]
6479    pub fn shift(&self, n: i64) -> Self {
6480        Self {
6481            ordinal: self.ordinal.saturating_add(n),
6482            freq: self.freq,
6483        }
6484    }
6485
6486    /// Period-difference in units of the shared frequency.
6487    /// Returns `None` if `freq` differs (pandas raises IncompatibleFrequency).
6488    #[must_use]
6489    pub fn diff(&self, other: &Self) -> Option<i64> {
6490        if self.freq != other.freq {
6491            return None;
6492        }
6493        Some(self.ordinal.saturating_sub(other.ordinal))
6494    }
6495
6496    /// Parse common pandas `Period(...)` strings and infer the frequency.
6497    ///
6498    /// Supported forms mirror pandas' unambiguous scalar constructor cases:
6499    /// annual (`"2024"`), quarterly (`"2024Q1"`), monthly (`"2024-01"`),
6500    /// and daily (`"2024-01-15"`). The ordinal axes match pandas:
6501    /// 1970, 1970Q1, 1970-01, and 1970-01-01 all have ordinal 0.
6502    pub fn parse(s: &str) -> Result<Self, TypeError> {
6503        let trimmed = s.trim();
6504        if trimmed.eq_ignore_ascii_case("nat") {
6505            return Ok(Self::new(i64::MIN, PeriodFreq::Daily));
6506        }
6507
6508        if let Some((year, quarter)) = parse_quarter_period(trimmed) {
6509            let ordinal = year
6510                .checked_sub(1970)
6511                .and_then(|offset| offset.checked_mul(4))
6512                .and_then(|base| base.checked_add(i64::from(quarter) - 1))
6513                .ok_or_else(|| TypeError::ValueNotParseable {
6514                    value: s.to_owned(),
6515                    target: "Period".to_owned(),
6516                })?;
6517            return Ok(Self::new(ordinal, PeriodFreq::Quarterly));
6518        }
6519
6520        if let Some((year, month, day)) = parse_ymd_period(trimmed) {
6521            let ordinal = Timestamp::days_from_ymd(year, i64::from(month), i64::from(day));
6522            return Ok(Self::new(ordinal, PeriodFreq::Daily));
6523        }
6524
6525        if let Some((year, month)) = parse_year_month_period(trimmed) {
6526            let ordinal = year
6527                .checked_sub(1970)
6528                .and_then(|offset| offset.checked_mul(12))
6529                .and_then(|base| base.checked_add(i64::from(month) - 1))
6530                .ok_or_else(|| TypeError::ValueNotParseable {
6531                    value: s.to_owned(),
6532                    target: "Period".to_owned(),
6533                })?;
6534            return Ok(Self::new(ordinal, PeriodFreq::Monthly));
6535        }
6536
6537        if let Some(year) = parse_annual_period(trimmed) {
6538            let ordinal = year
6539                .checked_sub(1970)
6540                .ok_or_else(|| TypeError::ValueNotParseable {
6541                    value: s.to_owned(),
6542                    target: "Period".to_owned(),
6543                })?;
6544            return Ok(Self::new(ordinal, PeriodFreq::Annual));
6545        }
6546
6547        Err(TypeError::ValueNotParseable {
6548            value: s.to_owned(),
6549            target: "Period".to_owned(),
6550        })
6551    }
6552
6553    /// Pandas calendar string for this period, matching `str(pd.Period)`.
6554    ///
6555    /// Inverts the frequency-specific ordinal axes anchored at 1970:
6556    /// `1970`/`1970Q1`/`1970-01`/`1970-01-01`/`1970-01-01 00:00` all have
6557    /// ordinal 0. Returns `"NaT"` for the missing sentinel (`i64::MIN`).
6558    ///
6559    /// EVERY frequency is exact, Weekly and Business included.
6560    ///
6561    /// ⚠️ THOSE TWO ARE NOT INDEXED IN DAYS, which is what made them wrong until
6562    /// 08363d42f: a weekly ordinal counts WEEKS from the Monday 1969-12-22 and
6563    /// renders as the RANGE it spans (`2024-03-11/2024-03-17`), and a business
6564    /// ordinal counts BUSINESS DAYS at five per week. Both used to be handed to
6565    /// `civil_from_days`, which reads its argument as days since the epoch, so
6566    /// ordinal 2829 rendered `1977-09-30` instead of the week of 2024-03-15.
6567    ///
6568    /// The note that used to sit here called them "best-effort" and said neither
6569    /// was "reachable through the current parse/cast paths". The first half was
6570    /// a real limitation; the second was too narrow a survey. [`Self::parse`]
6571    /// indeed cannot produce them and neither can `cast_scalar` — but
6572    /// `DatetimeIndex::to_period("W")` builds them directly, and fp-index then
6573    /// renders those values through `Display` in `PeriodIndex::format`,
6574    /// `to_index`, `to_flat_index`, the `.str` accessor and the `get_loc` error
6575    /// message. The frequencies were unreachable only from the two paths the
6576    /// note happened to check.
6577    #[must_use]
6578    pub fn calendar_string(&self) -> String {
6579        let mut rendered = String::new();
6580        // `fmt::Write for String` is infallible.
6581        let _ = self.write_calendar(&mut rendered);
6582        rendered
6583    }
6584
6585    fn write_calendar(&self, rendered: &mut impl std::fmt::Write) -> std::fmt::Result {
6586        if self.ordinal == i64::MIN {
6587            return rendered.write_str("NaT");
6588        }
6589        let ord = self.ordinal;
6590        match self.freq {
6591            PeriodFreq::Annual => {
6592                let year = 1970 + ord;
6593                write!(rendered, "{year}")
6594            }
6595            PeriodFreq::Quarterly => {
6596                let year = 1970 + ord.div_euclid(4);
6597                let quarter = ord.rem_euclid(4) + 1;
6598                write!(rendered, "{year}Q{quarter}")
6599            }
6600            PeriodFreq::Monthly => {
6601                let year = 1970 + ord.div_euclid(12);
6602                let month = ord.rem_euclid(12) + 1;
6603                write!(rendered, "{year:04}-{month:02}")
6604            }
6605            PeriodFreq::Daily => {
6606                let (y, m, d) = civil_from_days(ord);
6607                write!(rendered, "{y:04}-{m:02}-{d:02}")
6608            }
6609            // ⚠️ NOT DAYS SINCE THE EPOCH. A business ordinal counts BUSINESS
6610            // DAYS — five per week — so handing it to `civil_from_days` (which
6611            // wants a day count) put the label decades out: ordinal 14141 is
6612            // 2024-03-15 and rendered as 2008-09-19.
6613            //
6614            // The forward map in fp-index is
6615            //     days.div_euclid(7) * 5 + {Thu:0, Fri:1, Mon:2, Tue:3, Wed:4}
6616            // measured against pandas at every sampled date, so this is its
6617            // inverse: five ordinals per seven days, with the remainder naming a
6618            // weekday offset from the Thursday the epoch falls on.
6619            PeriodFreq::Business => {
6620                const WEEKDAY_OFFSET: [i64; 5] = [0, 1, 4, 5, 6];
6621                // Euclidean, so a pre-epoch ordinal keeps a remainder in 0..5:
6622                // ordinal -1 is 1969-12-31, not a negative weekday index.
6623                let offset = WEEKDAY_OFFSET[ord.rem_euclid(5) as usize];
6624                let days = ord.div_euclid(5).saturating_mul(7).saturating_add(offset);
6625                let (y, m, d) = civil_from_days(days);
6626                write!(rendered, "{y:04}-{m:02}-{d:02}")
6627            }
6628            // ⚠️ TWO BUGS IN ONE ARM. A weekly ordinal counts WEEKS from the
6629            // Monday 1969-12-22 (ten days before the epoch), and pandas renders a
6630            // weekly period as the RANGE it spans, not as one date:
6631            //     Period('2024-03-15', 'W') -> '2024-03-11/2024-03-17'
6632            // ordinal 2829, which this arm rendered as '1977-09-30'.
6633            //
6634            // fp-frame's `format_period_label` already produced the range form
6635            // for the same freq, so the two renderers disagreed on every weekly
6636            // period; this makes them agree.
6637            PeriodFreq::Weekly => {
6638                // Days-since-epoch of the anchor Monday 1969-12-22.
6639                const WEEK_ANCHOR_DAY: i64 = -10;
6640                let start = ord.saturating_mul(7).saturating_add(WEEK_ANCHOR_DAY);
6641                let (sy, sm, sd) = civil_from_days(start);
6642                let (ey, em, ed) = civil_from_days(start.saturating_add(6));
6643                write!(rendered, "{sy:04}-{sm:02}-{sd:02}/{ey:04}-{em:02}-{ed:02}")
6644            }
6645            PeriodFreq::Hourly => {
6646                let (y, m, d) = civil_from_days(ord.div_euclid(24));
6647                let hour = ord.rem_euclid(24);
6648                write!(rendered, "{y:04}-{m:02}-{d:02} {hour:02}:00")
6649            }
6650            PeriodFreq::Minutely => {
6651                let day = ord.div_euclid(1440);
6652                let mins = ord.rem_euclid(1440);
6653                let (y, m, d) = civil_from_days(day);
6654                write!(
6655                    rendered,
6656                    "{y:04}-{m:02}-{d:02} {:02}:{:02}",
6657                    mins / 60,
6658                    mins % 60
6659                )
6660            }
6661            PeriodFreq::Secondly => {
6662                let day = ord.div_euclid(86_400);
6663                let secs = ord.rem_euclid(86_400);
6664                let (y, m, d) = civil_from_days(day);
6665                write!(
6666                    rendered,
6667                    "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}",
6668                    secs / 3600,
6669                    (secs % 3600) / 60,
6670                    secs % 60
6671                )
6672            }
6673            // The three sub-second frequencies differ only in the divisor and
6674            // the FIXED fraction width -- pandas pads to the full width and
6675            // never trims trailing zeros. MEASURED on 2024-03-15 10:30:45.123456789:
6676            //     ms -> "2024-03-15 10:30:45.123"
6677            //     us -> "2024-03-15 10:30:45.123456"
6678            //     ns -> "2024-03-15 10:30:45.123456789"
6679            PeriodFreq::Milliseconds | PeriodFreq::Microseconds | PeriodFreq::Nanoseconds => {
6680                let (per_sec, width) = match self.freq {
6681                    PeriodFreq::Milliseconds => (1_000_i64, 3_usize),
6682                    PeriodFreq::Microseconds => (1_000_000_i64, 6_usize),
6683                    _ => (1_000_000_000_i64, 9_usize),
6684                };
6685                // 86_400 * 1e9 = 8.64e13 -- the widest of these is well inside i64.
6686                let per_day = 86_400 * per_sec;
6687                let day = ord.div_euclid(per_day);
6688                let rest = ord.rem_euclid(per_day);
6689                let secs = rest / per_sec;
6690                let frac = rest % per_sec;
6691                let (y, m, d) = civil_from_days(day);
6692                write!(
6693                    rendered,
6694                    "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}.{:0width$}",
6695                    secs / 3600,
6696                    (secs % 3600) / 60,
6697                    secs % 60,
6698                    frac,
6699                    width = width
6700                )
6701            }
6702        }
6703    }
6704}
6705
6706/// Convert a day count (days since 1970-01-01) to a proleptic-Gregorian
6707/// `(year, month, day)`, using Howard Hinnant's civil-from-days algorithm
6708/// (same kernel as `Timestamp::isoformat`).
6709fn civil_from_days(days_since_epoch: i64) -> (i64, u32, u32) {
6710    let days = days_since_epoch + 719_468;
6711    let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
6712    let doe = days - era * 146_097;
6713    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
6714    let y = yoe + era * 400;
6715    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
6716    let mp = (5 * doy + 2) / 153;
6717    let d = doy - (153 * mp + 2) / 5 + 1;
6718    let m = if mp < 10 { mp + 3 } else { mp - 9 };
6719    let year = if m <= 2 { y + 1 } else { y };
6720    (year, m as u32, d as u32)
6721}
6722
6723fn parse_annual_period(value: &str) -> Option<i64> {
6724    (value.len() == 4 && value.chars().all(|ch| ch.is_ascii_digit()))
6725        .then(|| value.parse::<i64>().ok())
6726        .flatten()
6727}
6728
6729fn parse_year_month_period(value: &str) -> Option<(i64, u32)> {
6730    let (year, month) = value.split_once('-')?;
6731    if year.len() != 4 || month.len() != 2 {
6732        return None;
6733    }
6734    let year = year.parse::<i64>().ok()?;
6735    let month = month.parse::<u32>().ok()?;
6736    (1..=12).contains(&month).then_some((year, month))
6737}
6738
6739fn parse_ymd_period(value: &str) -> Option<(i64, u32, u32)> {
6740    let mut parts = value.split('-');
6741    let year = parts.next()?;
6742    let month = parts.next()?;
6743    let day = parts.next()?;
6744    if parts.next().is_some() || year.len() != 4 || month.len() != 2 || day.len() != 2 {
6745        return None;
6746    }
6747    let year = year.parse::<i64>().ok()?;
6748    let month = month.parse::<u32>().ok()?;
6749    let day = day.parse::<u32>().ok()?;
6750    (1..=days_in_month(year, month)?)
6751        .contains(&day)
6752        .then_some((year, month, day))
6753}
6754
6755fn parse_quarter_period(value: &str) -> Option<(i64, u32)> {
6756    let (year, quarter) = value.split_once('Q').or_else(|| value.split_once('q'))?;
6757    if year.len() != 4 || quarter.len() != 1 {
6758        return None;
6759    }
6760    let year = year.parse::<i64>().ok()?;
6761    let quarter = quarter.parse::<u32>().ok()?;
6762    (1..=4).contains(&quarter).then_some((year, quarter))
6763}
6764
6765impl std::fmt::Display for Period {
6766    /// Pandas `str(Period)` form: the calendar string (`2024`, `2024Q1`,
6767    /// `2024-03`, `2024-01-15`, ...). NaT (ordinal `i64::MIN`) renders `NaT`.
6768    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6769        self.write_calendar(f)
6770    }
6771}
6772
6773/// Build `periods` consecutive Periods starting at `start`.
6774///
6775/// Matches `pd.period_range(start, periods=N, freq=start.freq)` for the
6776/// count-based form. The frequency is taken from `start` — pandas requires
6777/// `freq` to match when both are passed; mismatches are an error in
6778/// pandas, but here we sidestep ambiguity by deriving from `start.freq`.
6779///
6780/// Per br-frankenpandas-2jef (epoj Phase 2). Pure ordinal arithmetic — no
6781/// calendar conversion (Phase 3 wires chrono). `periods=0` returns empty.
6782///
6783/// ```
6784/// use fp_types::{period_range, Period, PeriodFreq};
6785/// let q1 = Period::new(216, PeriodFreq::Quarterly);
6786/// let year = period_range(q1, 4);
6787/// assert_eq!(year.len(), 4);
6788/// assert_eq!(year[0].ordinal, 216);
6789/// assert_eq!(year[3].ordinal, 219);
6790/// ```
6791#[must_use]
6792pub fn period_range(start: Period, periods: usize) -> Vec<Period> {
6793    (0..periods).map(|i| start.shift(i as i64)).collect()
6794}
6795
6796#[cfg(test)]
6797mod tests {
6798    use super::{
6799        DType, Interval, IntervalClosed, NullKind, Period, PeriodFreq, Scalar, SparseDType,
6800        cast_scalar, common_dtype, infer_dtype,
6801    };
6802
6803    /// br-frankenpandas-ay8o9: Scalar::semantic_cmp underpins ALL ordering in
6804    /// the library (sort, min/max, is_monotonic, searchsorted, groupby key
6805    /// order) and is the reference the differential harnesses rely on. Property
6806    /// test of its total-order axioms over finite/non-NaT same-dtype scalars,
6807    /// plus the intentional NaN degeneracy. Deterministic seeded LCG — no rand
6808    /// crate, no mocks.
6809    /// br-frankenpandas-767ak: extends ay8o9's NaN pinning to the temporal NAT
6810    /// sentinels (i64::MIN). semantic_cmp treats NAT as degenerate (Equal to all
6811    /// same-dtype), which is why temporal ordering ops must treat NAT as missing.
6812    #[test]
6813    fn semantic_cmp_cross_numeric_int_float_cdpai() {
6814        // Property (br-frankenpandas-cdpai): semantic_cmp compares Int64 vs Float64
6815        // as f64, antisymmetric across the operand order. Seeded LCG, no mocks.
6816        use std::cmp::Ordering;
6817        let mut st: u64 = 0xc205_a1b2_c3d4_e5f6;
6818        let mut next = || {
6819            st = st
6820                .wrapping_mul(6_364_136_223_846_793_005)
6821                .wrapping_add(1_442_695_040_888_963_407);
6822            (st >> 33) as u32
6823        };
6824        for _ in 0..3000u32 {
6825            let i = (next() % 21) as i64 - 10;
6826            let f = (next() % 400) as f64 / 20.0 - 10.0; // finite
6827            let exp = (i as f64).partial_cmp(&f).unwrap();
6828            assert_eq!(Scalar::Int64(i).semantic_cmp(&Scalar::Float64(f)), exp);
6829            assert_eq!(
6830                Scalar::Float64(f).semantic_cmp(&Scalar::Int64(i)),
6831                exp.reverse()
6832            );
6833        }
6834        // Exact int/float equality compares Equal in both directions.
6835        assert_eq!(
6836            Scalar::Int64(5).semantic_cmp(&Scalar::Float64(5.0)),
6837            Ordering::Equal
6838        );
6839        assert_eq!(
6840            Scalar::Float64(5.0).semantic_cmp(&Scalar::Int64(5)),
6841            Ordering::Equal
6842        );
6843        assert_eq!(
6844            Scalar::Int64(3).semantic_cmp(&Scalar::Float64(3.5)),
6845            Ordering::Less
6846        );
6847        assert_eq!(
6848            Scalar::Int64(4).semantic_cmp(&Scalar::Float64(3.5)),
6849            Ordering::Greater
6850        );
6851    }
6852
6853    #[test]
6854    fn semantic_cmp_nat_degeneracy_temporal_767ak() {
6855        use std::cmp::Ordering;
6856        const NAT: i64 = i64::MIN;
6857
6858        // Timedelta64 NAT is degenerate (Equal to finite and to itself).
6859        let td_nat = Scalar::Timedelta64(NAT);
6860        for v in [-3i64, 0, 5, 99] {
6861            let td = Scalar::Timedelta64(v);
6862            assert_eq!(td_nat.semantic_cmp(&td), Ordering::Equal, "td NAT vs {v}");
6863            assert_eq!(td.semantic_cmp(&td_nat), Ordering::Equal, "td {v} vs NAT");
6864        }
6865        assert_eq!(td_nat.semantic_cmp(&td_nat), Ordering::Equal);
6866
6867        // Datetime64 NAT likewise.
6868        let dt_nat = Scalar::Datetime64(NAT);
6869        for v in [-3i64, 0, 5, 99] {
6870            let dt = Scalar::Datetime64(v);
6871            assert_eq!(dt_nat.semantic_cmp(&dt), Ordering::Equal, "dt NAT vs {v}");
6872            assert_eq!(dt.semantic_cmp(&dt_nat), Ordering::Equal, "dt {v} vs NAT");
6873        }
6874        assert_eq!(dt_nat.semantic_cmp(&dt_nat), Ordering::Equal);
6875
6876        // Non-NAT temporal values order normally (reflexive, antisymmetric, lt).
6877        for (a, b) in [(1i64, 2i64), (5, 5), (9, -1)] {
6878            let (ta, tb) = (Scalar::Timedelta64(a), Scalar::Timedelta64(b));
6879            assert_eq!(ta.semantic_cmp(&ta), Ordering::Equal);
6880            assert_eq!(ta.semantic_cmp(&tb), b.cmp(&a).reverse()); // a.cmp(b)
6881            assert_eq!(ta.semantic_cmp(&tb), a.cmp(&b));
6882            let (da, db) = (Scalar::Datetime64(a), Scalar::Datetime64(b));
6883            assert_eq!(da.semantic_cmp(&db), a.cmp(&b));
6884        }
6885    }
6886
6887    fn semantic_cmp_cross_variant_values_d5ikg() -> [Scalar; 9] {
6888        [
6889            Scalar::Null(NullKind::Null),
6890            Scalar::Bool(true),
6891            Scalar::Int64(-7),
6892            Scalar::Float64(3.5),
6893            Scalar::Utf8("mixed".to_owned()),
6894            Scalar::Timedelta64(11),
6895            Scalar::Datetime64(1_735_732_800_123_456_789),
6896            Scalar::Period(Period::new(649, PeriodFreq::Monthly)),
6897            Scalar::Interval(Interval::new(-1.5, 2.5, IntervalClosed::Right)),
6898        ]
6899    }
6900
6901    fn semantic_cmp_uses_debug_fallback_d5ikg(left: &Scalar, right: &Scalar) -> bool {
6902        !matches!(
6903            (left, right),
6904            (Scalar::Int64(_), Scalar::Float64(_)) | (Scalar::Float64(_), Scalar::Int64(_))
6905        )
6906    }
6907
6908    #[test]
6909    fn semantic_cmp_cross_variant_matches_debug_order_d5ikg() {
6910        let values = semantic_cmp_cross_variant_values_d5ikg();
6911        for (left_index, left) in values.iter().enumerate() {
6912            for (right_index, right) in values.iter().enumerate() {
6913                if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
6914                {
6915                    assert_eq!(
6916                        left.semantic_cmp(right),
6917                        format!("{left:?}").cmp(&format!("{right:?}")),
6918                        "cross-variant order mismatch: {left:?} vs {right:?}"
6919                    );
6920                }
6921            }
6922        }
6923    }
6924
6925    #[test]
6926    #[ignore = "foreground release attribution harness"]
6927    fn semantic_cmp_cross_variant_debug_alloc_ab_d5ikg() {
6928        use std::cmp::Ordering;
6929
6930        const BATCH: usize = 4_096;
6931        const BLOCKS: usize = 9;
6932
6933        fn former(left: &Scalar, right: &Scalar) -> Ordering {
6934            format!("{left:?}").cmp(&format!("{right:?}"))
6935        }
6936
6937        fn candidate(left: &Scalar, right: &Scalar) -> Ordering {
6938            left.semantic_cmp(right)
6939        }
6940
6941        fn elapsed(values: &[Scalar], compare: fn(&Scalar, &Scalar) -> Ordering) -> u128 {
6942            let mut less = 0usize;
6943            let started = std::time::Instant::now();
6944            for _ in 0..BATCH {
6945                for (left_index, left) in values.iter().enumerate() {
6946                    for (right_index, right) in values.iter().enumerate() {
6947                        if left_index != right_index
6948                            && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
6949                            && compare(std::hint::black_box(left), std::hint::black_box(right))
6950                                == Ordering::Less
6951                        {
6952                            less += 1;
6953                        }
6954                    }
6955                }
6956            }
6957            std::hint::black_box(less);
6958            started.elapsed().as_nanos()
6959        }
6960
6961        fn median(samples: &mut [u128]) -> u128 {
6962            samples.sort_unstable();
6963            samples[samples.len() / 2]
6964        }
6965
6966        let values = semantic_cmp_cross_variant_values_d5ikg();
6967
6968        for (left_index, left) in values.iter().enumerate() {
6969            for (right_index, right) in values.iter().enumerate() {
6970                if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
6971                {
6972                    assert_eq!(
6973                        former(left, right),
6974                        candidate(left, right),
6975                        "cross-variant order mismatch: {left:?} vs {right:?}"
6976                    );
6977                }
6978            }
6979        }
6980
6981        std::hint::black_box(elapsed(&values, former));
6982        std::hint::black_box(elapsed(&values, candidate));
6983
6984        let mut former_samples = Vec::with_capacity(BLOCKS * 2);
6985        let mut candidate_samples = Vec::with_capacity(BLOCKS * 2);
6986        for block in 0..BLOCKS {
6987            if block.is_multiple_of(2) {
6988                former_samples.push(elapsed(&values, former));
6989                candidate_samples.push(elapsed(&values, candidate));
6990                candidate_samples.push(elapsed(&values, candidate));
6991                former_samples.push(elapsed(&values, former));
6992            } else {
6993                candidate_samples.push(elapsed(&values, candidate));
6994                former_samples.push(elapsed(&values, former));
6995                former_samples.push(elapsed(&values, former));
6996                candidate_samples.push(elapsed(&values, candidate));
6997            }
6998        }
6999
7000        let former_p50 = median(&mut former_samples);
7001        let candidate_p50 = median(&mut candidate_samples);
7002        eprintln!(
7003            "semantic_cmp_cross_variant_debug_alloc former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup={:.6}",
7004            former_p50 as f64 / candidate_p50 as f64
7005        );
7006    }
7007
7008    #[test]
7009    fn semantic_cmp_total_order_axioms_ay8o9() {
7010        use std::cmp::Ordering;
7011
7012        let mut state: u64 = 0xc0ff_eeba_df00_d123;
7013        let mut next = || {
7014            state = state
7015                .wrapping_mul(6_364_136_223_846_793_005)
7016                .wrapping_add(1_442_695_040_888_963_407);
7017            (state >> 33) as u32
7018        };
7019
7020        for iter in 0..6000u32 {
7021            let dt = next() % 4;
7022            // Build a same-dtype, finite, non-NaT scalar from a random u32.
7023            let mk = |r: u32| match dt {
7024                0 => Scalar::Int64((r % 11) as i64 - 5),
7025                // finite, in -5.0..=5.0 by 0.5 — no NaN/inf.
7026                1 => Scalar::Float64(f64::from((r % 21) as i32 - 10) / 2.0),
7027                2 => Scalar::Utf8(format!("s{}", r % 5)),
7028                _ => Scalar::Bool(r.is_multiple_of(2)),
7029            };
7030            let a = mk(next());
7031            let b = mk(next());
7032            let c = mk(next());
7033            let ctx = format!("iter={iter} a={a:?} b={b:?} c={c:?}");
7034
7035            // Reflexivity.
7036            assert_eq!(a.semantic_cmp(&a), Ordering::Equal, "reflexive {ctx}");
7037            // Antisymmetry.
7038            assert_eq!(
7039                a.semantic_cmp(&b),
7040                b.semantic_cmp(&a).reverse(),
7041                "antisymmetric {ctx}"
7042            );
7043            // le / ge / eq consistency with the ordering.
7044            let ab = a.semantic_cmp(&b);
7045            assert_eq!(
7046                a.semantic_le(&b),
7047                ab != Ordering::Greater,
7048                "le-consistent {ctx}"
7049            );
7050            assert_eq!(
7051                a.semantic_ge(&b),
7052                ab != Ordering::Less,
7053                "ge-consistent {ctx}"
7054            );
7055            assert_eq!(
7056                a.semantic_le(&b) && a.semantic_ge(&b),
7057                ab == Ordering::Equal,
7058                "le&ge<=>eq {ctx}"
7059            );
7060            // Transitivity: a<=b && b<=c  =>  a<=c.
7061            if a.semantic_cmp(&b) != Ordering::Greater && b.semantic_cmp(&c) != Ordering::Greater {
7062                assert_ne!(a.semantic_cmp(&c), Ordering::Greater, "transitivity {ctx}");
7063            }
7064        }
7065
7066        // Pin the intentional NaN degeneracy: a Float64 NaN compares Equal to
7067        // every finite Float64 (and to itself) — this is why ordering ops must
7068        // treat NaN as missing rather than relying on semantic_cmp to order it.
7069        let nan = Scalar::Float64(f64::NAN);
7070        for v in [
7071            Scalar::Float64(-3.5),
7072            Scalar::Float64(0.0),
7073            Scalar::Float64(7.25),
7074        ] {
7075            assert_eq!(nan.semantic_cmp(&v), Ordering::Equal, "NaN cmp finite");
7076            assert_eq!(v.semantic_cmp(&nan), Ordering::Equal, "finite cmp NaN");
7077        }
7078        assert_eq!(nan.semantic_cmp(&nan), Ordering::Equal, "NaN cmp NaN");
7079    }
7080
7081    /// br-frankenpandas-be314: common_dtype is the dtype-promotion lattice
7082    /// underpinning every binary op, alignment, and concat (dtype coercion is a
7083    /// crown-jewel correctness area). Exhaustively (all 14x14 DType pairs) assert
7084    /// its lattice axioms — an asymmetric arm would make df1+df2 and df2+df1
7085    /// disagree on dtype.
7086    #[test]
7087    fn common_dtype_lattice_axioms_be314() {
7088        let all: [DType; 14] = [
7089            DType::Null,
7090            DType::Bool,
7091            DType::BoolNullable,
7092            DType::Int64,
7093            DType::Int64Nullable,
7094            DType::Float64,
7095            // br-frankenpandas-qkqfb: a new variant is only safe once the
7096            // commutativity and associativity sweeps below cover it.
7097            DType::Float64Nullable,
7098            DType::Utf8,
7099            DType::Categorical,
7100            DType::Timedelta64,
7101            DType::datetime64_naive(),
7102            DType::Period,
7103            DType::Interval,
7104            DType::Sparse,
7105        ];
7106
7107        for a in &all {
7108            // Idempotence: a promoted with itself is itself.
7109            assert_eq!(
7110                common_dtype(a.clone(), a.clone()),
7111                Ok(a.clone()),
7112                "idempotent {a:?}"
7113            );
7114            // Null is the identity element of the promotion lattice.
7115            assert_eq!(
7116                common_dtype(DType::Null, a.clone()),
7117                Ok(a.clone()),
7118                "null-left identity {a:?}"
7119            );
7120            assert_eq!(
7121                common_dtype(a.clone(), DType::Null),
7122                Ok(a.clone()),
7123                "null-right identity {a:?}"
7124            );
7125
7126            for b in &all {
7127                // Commutativity: same Ok value AND same ok-ness. An asymmetric
7128                // match arm would make binary-op output dtype order-dependent.
7129                assert_eq!(
7130                    common_dtype(a.clone(), b.clone()).ok(),
7131                    common_dtype(b.clone(), a.clone()).ok(),
7132                    "commutative value {a:?},{b:?}"
7133                );
7134                assert_eq!(
7135                    common_dtype(a.clone(), b.clone()).is_ok(),
7136                    common_dtype(b.clone(), a.clone()).is_ok(),
7137                    "commutative ok-ness {a:?},{b:?}"
7138                );
7139            }
7140        }
7141
7142        // Associativity over the Ok-closed subset: when both nestings succeed,
7143        // promotion order must not change the result.
7144        for a in &all {
7145            for b in &all {
7146                for c in &all {
7147                    if let (Ok(ab), Ok(bc)) = (
7148                        common_dtype(a.clone(), b.clone()),
7149                        common_dtype(b.clone(), c.clone()),
7150                    ) && let (Ok(left), Ok(right)) =
7151                        (common_dtype(ab, c.clone()), common_dtype(a.clone(), bc))
7152                    {
7153                        assert_eq!(left, right, "associative {a:?},{b:?},{c:?}");
7154                    }
7155                }
7156            }
7157        }
7158    }
7159
7160    /// br-frankenpandas-e3sfq: infer_dtype drives Column/Series construction
7161    /// dtype inference. Assert its homogeneous + mixed-coercion rules.
7162    #[test]
7163    fn infer_dtype_coercion_rules_e3sfq() {
7164        use DType::{Bool, Float64, Int64, Null, Utf8};
7165
7166        // Empty and all-null infer to Null.
7167        assert_eq!(infer_dtype(&[]), Ok(Null));
7168        assert_eq!(
7169            infer_dtype(&[Scalar::Null(NullKind::Null), Scalar::Null(NullKind::NaN)]),
7170            Ok(Null)
7171        );
7172
7173        // Homogeneous slices infer to their own dtype (random, seeded LCG).
7174        let mut s: u64 = 0x132d_a7e0_0e3f_c0de;
7175        let mut next = || {
7176            s = s
7177                .wrapping_mul(6_364_136_223_846_793_005)
7178                .wrapping_add(1_442_695_040_888_963_407);
7179            (s >> 33) as u32
7180        };
7181        for _ in 0..600u32 {
7182            let n = (next() % 6) as usize + 1;
7183            let ints: Vec<Scalar> = (0..n)
7184                .map(|_| Scalar::Int64((next() % 9) as i64 - 4))
7185                .collect();
7186            assert_eq!(infer_dtype(&ints), Ok(Int64));
7187            let floats: Vec<Scalar> = (0..n)
7188                .map(|_| Scalar::Float64(f64::from((next() % 7) as i32)))
7189                .collect();
7190            assert_eq!(infer_dtype(&floats), Ok(Float64));
7191            let bools: Vec<Scalar> = (0..n).map(|_| Scalar::Bool(next() % 2 == 0)).collect();
7192            assert_eq!(infer_dtype(&bools), Ok(Bool));
7193            let strs: Vec<Scalar> = (0..n)
7194                .map(|_| Scalar::Utf8(format!("s{}", next() % 4)))
7195                .collect();
7196            assert_eq!(infer_dtype(&strs), Ok(Utf8));
7197        }
7198
7199        // Mixed-coercion rules.
7200        assert_eq!(
7201            infer_dtype(&[
7202                Scalar::Int64(1),
7203                Scalar::Null(NullKind::Null),
7204                Scalar::Int64(2)
7205            ]),
7206            Ok(Int64),
7207            "Int64 + nulls -> Int64"
7208        );
7209        assert_eq!(
7210            infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]),
7211            Ok(Float64),
7212            "Int64 + Float64 -> Float64"
7213        );
7214        // br-frankenpandas-rh1od: MEASURED live pandas 2.2.3 — a bool mixed
7215        // with numerics constructs OBJECT; the old Int64 coercion here was
7216        // numpy common-type behavior no pandas constructor path produces.
7217        assert_eq!(
7218            infer_dtype(&[Scalar::Bool(true), Scalar::Int64(3)]),
7219            Ok(Utf8),
7220            "Bool + Int64 -> object bucket (pandas constructs object)"
7221        );
7222        assert_eq!(
7223            infer_dtype(&[Scalar::Utf8("a".into()), Scalar::Int64(3)]),
7224            Ok(Utf8),
7225            "Utf8 + Int64 -> Utf8 (object fallback)"
7226        );
7227    }
7228
7229    /// br-frankenpandas-1ews0: missing_for_dtype is the canonical per-dtype
7230    /// missing sentinel (used by null-fill / with_validity / cast). Exhaustively
7231    /// assert it is always missing, and that casting any missing to any dtype
7232    /// stays missing.
7233    #[test]
7234    fn missing_for_dtype_always_missing_1ews0() {
7235        let all: [DType; 14] = [
7236            DType::Null,
7237            DType::Bool,
7238            DType::BoolNullable,
7239            DType::Int64,
7240            DType::Int64Nullable,
7241            DType::Float64,
7242            DType::Float64Nullable,
7243            DType::Utf8,
7244            DType::Categorical,
7245            DType::Timedelta64,
7246            DType::datetime64_naive(),
7247            DType::Period,
7248            DType::Interval,
7249            DType::Sparse,
7250        ];
7251        for dt in &all {
7252            let m = Scalar::missing_for_dtype(dt.clone());
7253            assert!(m.is_missing(), "missing_for_dtype({dt:?}) must be missing");
7254            for target in &all {
7255                let cast = cast_scalar(&m, target.clone()).expect("cast of missing");
7256                if target == &DType::Utf8 {
7257                    // Casting a missing value to string follows pandas astype(str):
7258                    // it yields a string ("None"/"NaN"/"NaT"), NOT a missing value.
7259                    assert!(
7260                        matches!(cast, Scalar::Utf8(_)),
7261                        "cast(missing {dt:?} -> Utf8) yields a string, got {cast:?}"
7262                    );
7263                } else if matches!(dt, DType::Timedelta64 | DType::Datetime64 { .. })
7264                    && matches!(target, DType::Bool | DType::Int64)
7265                {
7266                    // ⚠️ TWO MORE PLACES pandas BREAKS this invariant, and both
7267                    // are the same underlying fact: NaT is not a separate
7268                    // representation, it IS i64::MIN, and the numpy casts read
7269                    // the bits. MEASURED, live pandas 2.2.3:
7270                    //
7271                    //   pd.Series([pd.NaT], dtype='datetime64[ns]').astype('int64')
7272                    //     -> -9223372036854775808      the SENTINEL, not a missing
7273                    //   pd.Series([pd.NaT], dtype='timedelta64[ns]').astype('bool')
7274                    //     -> True                      nonzero, so truthy
7275                    //
7276                    // Same shape as the Utf8 carve-out above: the invariant is
7277                    // FrankenPandas' own, and pandas does not honour it wherever
7278                    // a cast is defined to reinterpret rather than to convert.
7279                    // Narrowly scoped on purpose — every other missing, and these
7280                    // two toward every other target, still stay missing.
7281                    match target {
7282                        DType::Bool => assert_eq!(
7283                            cast,
7284                            Scalar::Bool(true),
7285                            "cast(missing {dt:?} -> Bool) is pandas' nonzero-truthy \
7286                             read of the NaT bits"
7287                        ),
7288                        _ => assert_eq!(
7289                            cast,
7290                            Scalar::Int64(i64::MIN),
7291                            "cast(missing {dt:?} -> Int64) is the NaT sentinel itself"
7292                        ),
7293                    }
7294                } else {
7295                    // Every other target preserves missingness via cast_scalar's
7296                    // value.is_missing() -> missing_for_dtype(target) branch.
7297                    assert!(
7298                        cast.is_missing(),
7299                        "cast(missing {dt:?} -> {target:?}) must stay missing, got {cast:?}"
7300                    );
7301                }
7302            }
7303        }
7304    }
7305
7306    #[test]
7307    fn cast_scalar_bool_int_roundtrip_6w07b() {
7308        use super::cast_scalar;
7309        // Property (br-frankenpandas-6w07b): Bool<->Int64 cast. Seeded LCG, no mocks.
7310        assert_eq!(
7311            cast_scalar(&Scalar::Bool(true), DType::Int64).unwrap(),
7312            Scalar::Int64(1)
7313        );
7314        assert_eq!(
7315            cast_scalar(&Scalar::Bool(false), DType::Int64).unwrap(),
7316            Scalar::Int64(0)
7317        );
7318        assert_eq!(
7319            cast_scalar(&Scalar::Int64(0), DType::Bool).unwrap(),
7320            Scalar::Bool(false)
7321        );
7322        let mut st: u64 = 0x4b07_0b1c_2d3e_4f50;
7323        let mut next = || {
7324            st = st
7325                .wrapping_mul(6_364_136_223_846_793_005)
7326                .wrapping_add(1_442_695_040_888_963_407);
7327            (st >> 33) as u32
7328        };
7329        for _ in 0..2000u32 {
7330            let v = (next() % 21) as i64 - 10;
7331            assert_eq!(
7332                cast_scalar(&Scalar::Int64(v), DType::Bool).unwrap(),
7333                Scalar::Bool(v != 0),
7334                "int->bool v={v}"
7335            );
7336        }
7337    }
7338
7339    /// br-frankenpandas-6a83t: cast_scalar is the scalar dtype-coercion path
7340    #[test]
7341    fn cast_scalar_float_to_int_truncates_toward_zero_u9lec() {
7342        use super::cast_scalar;
7343        // Property (br-frankenpandas-u9lec): Float64->Int64 truncates toward zero, not
7344        // floor (-3.7 -> -3). Seeded LCG, no mocks.
7345        let mut st: u64 = 0x4ca5_0b1c_2d3e_4f50;
7346        let mut next = || {
7347            st = st
7348                .wrapping_mul(6_364_136_223_846_793_005)
7349                .wrapping_add(1_442_695_040_888_963_407);
7350            (st >> 33) as u32
7351        };
7352        // Explicit negative-direction checks (the gotcha).
7353        for (f, exp) in [
7354            (-3.7, -3i64),
7355            (3.7, 3),
7356            (-3.2, -3),
7357            (3.2, 3),
7358            (-0.9, 0),
7359            (0.9, 0),
7360            (-5.0, -5),
7361            (5.0, 5),
7362        ] {
7363            assert_eq!(
7364                cast_scalar(&Scalar::Float64(f), DType::Int64).unwrap(),
7365                Scalar::Int64(exp),
7366                "cast {f}"
7367            );
7368        }
7369        // Property over random signed fractional values.
7370        for _ in 0..3000u32 {
7371            let v = (next() % 2_000_001) as f64 / 1000.0 - 1000.0; // [-1000, 1000]
7372            let got = cast_scalar(&Scalar::Float64(v), DType::Int64).unwrap();
7373            assert_eq!(
7374                got,
7375                Scalar::Int64(v.trunc() as i64),
7376                "trunc-toward-zero v={v}"
7377            );
7378        }
7379    }
7380
7381    /// Float -> `datetime64[ns]` / `timedelta64[ns]` reinterprets the float as
7382    /// integer NANOSECONDS. Every value here is transcribed from live pandas
7383    /// 2.2.3, measured on both the constructor and `astype` paths.
7384    ///
7385    /// ⚠️ THE CONTRAST WITH `int64` IS THE POINT: the explicit constructor
7386    /// REFUSES a lossy float -> int64, and silently truncates the same float
7387    /// into a temporal dtype. Assuming one rule covers both is how this gets
7388    /// re-broken, so both are asserted here on the same input.
7389    #[test]
7390    fn cast_scalar_float_to_temporal_truncates_to_nanoseconds() {
7391        use super::{Timedelta, Timestamp, cast_scalar};
7392
7393        // TRUNCATION TOWARD ZERO, on both signs, where a floor would disagree.
7394        // pandas: 0.9 -> 0, -0.9 -> 0, 1.5 -> 1, -1.5 -> -1, -2.5 -> -2.
7395        for (input, want) in [
7396            (1.5_f64, 1_i64),
7397            (-1.5, -1),
7398            (0.9, 0),
7399            (-0.9, 0),
7400            (2.5, 2),
7401            (-2.5, -2),
7402            (1.999_999, 1),
7403            (-1.999_999, -1),
7404            (2.0, 2),
7405            (1e18, 1_000_000_000_000_000_000),
7406        ] {
7407            assert_eq!(
7408                cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
7409                Scalar::Datetime64(want),
7410                "datetime64 cast of {input}"
7411            );
7412            assert_eq!(
7413                cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
7414                Scalar::Timedelta64(want),
7415                "timedelta64 cast of {input}"
7416            );
7417        }
7418
7419        // ANYTHING NOT REPRESENTABLE AS i64 IS NaT — not a saturated i64::MAX,
7420        // and not the epoch. A bare `as i64` would produce both of those wrong
7421        // answers (saturation for the large values, 0 for NaN).
7422        for input in [
7423            f64::NAN,
7424            f64::INFINITY,
7425            f64::NEG_INFINITY,
7426            1e30,
7427            -1e30,
7428            9.3e18,
7429            -9.3e18,
7430            9_223_372_036_854_775_808.0,  // exactly 2^63
7431            -9_223_372_036_854_775_808.0, // exactly -2^63, which IS the NaT sentinel
7432        ] {
7433            assert_eq!(
7434                cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
7435                Scalar::Datetime64(Timestamp::NAT),
7436                "datetime64 cast of {input} must be NaT"
7437            );
7438            assert_eq!(
7439                cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
7440                Scalar::Timedelta64(Timedelta::NAT),
7441                "timedelta64 cast of {input} must be NaT"
7442            );
7443        }
7444
7445        // ...but the largest float BELOW 2^63 is representable and converts.
7446        // pandas renders it 2262-04-11 23:47:16.854774784.
7447        let just_inside = 9_223_372_036_854_774_784.0_f64; // 2^63 - 1024
7448        assert_eq!(
7449            cast_scalar(&Scalar::Float64(just_inside), DType::datetime64_naive()).unwrap(),
7450            Scalar::Datetime64(9_223_372_036_854_774_784),
7451            "the largest representable float must NOT be treated as NaT"
7452        );
7453
7454        // THE CONTRAST. Same input, three dtypes, two different rules — the
7455        // temporal ones truncate where int64 refuses outright.
7456        assert_eq!(
7457            cast_scalar(&Scalar::Float64(1.5), DType::datetime64_naive()).unwrap(),
7458            Scalar::Datetime64(1)
7459        );
7460        assert_eq!(
7461            cast_scalar(&Scalar::Float64(1.5), DType::Int64).unwrap(),
7462            Scalar::Int64(1),
7463            "the SHARED cast truncates here too; it is the explicit constructor \
7464             that refuses, via Column::new's LossyFloatToInt pre-check"
7465        );
7466    }
7467
7468    /// The MIRROR direction: `datetime64[ns]` / `timedelta64[ns]` -> numpy
7469    /// `int64` is the raw nanosecond count, and a bool is 0 or 1 nanoseconds
7470    /// going the other way. Every value transcribed from live pandas 2.2.3
7471    /// `astype`.
7472    #[test]
7473    fn cast_scalar_temporal_to_int64_is_raw_nanoseconds() {
7474        use super::{Timedelta, Timestamp, cast_scalar};
7475
7476        // Timestamp('2024-03-15 10:30:45.123456789') and
7477        // Timedelta('1 days 02:03:04.005006007').
7478        for nanos in [1_710_498_645_123_456_789_i64, 93_784_005_006_007, 0, -1] {
7479            assert_eq!(
7480                cast_scalar(&Scalar::Datetime64(nanos), DType::Int64).unwrap(),
7481                Scalar::Int64(nanos),
7482                "datetime64 -> int64 must be the raw nanos ({nanos})"
7483            );
7484            assert_eq!(
7485                cast_scalar(&Scalar::Timedelta64(nanos), DType::Int64).unwrap(),
7486                Scalar::Int64(nanos)
7487            );
7488        }
7489
7490        // ⚠️ NaT BECOMES THE SENTINEL, NOT A MISSING VALUE. pandas:
7491        //     pd.Series([pd.NaT], dtype='datetime64[ns]').astype('int64')
7492        //       -> -9223372036854775808
7493        // This is the assertion that pins the cast ABOVE the is_missing()
7494        // branch; move it below and both of these become Null.
7495        assert_eq!(
7496            cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Int64).unwrap(),
7497            Scalar::Int64(i64::MIN),
7498            "NaT -> int64 is the sentinel i64::MIN, not a missing value"
7499        );
7500        assert_eq!(
7501            cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Int64).unwrap(),
7502            Scalar::Int64(i64::MIN)
7503        );
7504
7505        // ⚠️ THE NULLABLE Int64 REFUSES WHAT numpy int64 ACCEPTS:
7506        //     .astype('Int64')   -> TypeError: datetime64[ns] cannot be
7507        //                          converted to IntegerDtype
7508        //     .astype('float64') -> TypeError: Cannot cast DatetimeArray
7509        // Both must stay refused, which is what makes the guard on the exact
7510        // target load-bearing rather than cosmetic.
7511        // `DType` stopped being `Copy` when `Datetime64 { tz }` landed
7512        // (2f159e68f), so the loop variable is cloned into each call.
7513        for target in [DType::Int64Nullable, DType::Float64, DType::Float64Nullable] {
7514            assert!(
7515                cast_scalar(
7516                    &Scalar::Datetime64(1_710_498_645_123_456_789),
7517                    target.clone()
7518                )
7519                .is_err(),
7520                "datetime64 -> {target:?} must stay refused"
7521            );
7522            assert!(
7523                cast_scalar(&Scalar::Timedelta64(93_784_005_006_007), target.clone()).is_err(),
7524                "timedelta64 -> {target:?} must stay refused"
7525            );
7526        }
7527
7528        // A bool is 0 or 1 NANOSECONDS on the astype path.
7529        for (flag, want) in [(true, 1_i64), (false, 0)] {
7530            assert_eq!(
7531                cast_scalar(&Scalar::Bool(flag), DType::datetime64_naive()).unwrap(),
7532                Scalar::Datetime64(want)
7533            );
7534            assert_eq!(
7535                cast_scalar(&Scalar::Bool(flag), DType::Timedelta64).unwrap(),
7536                Scalar::Timedelta64(want)
7537            );
7538        }
7539    }
7540
7541    /// The two halves of the column-width datetime formatter, checked apart:
7542    /// which rung a value NEEDS, and how a value RENDERS at a given rung.
7543    /// Transcribed from live pandas 2.2.3 `.astype(str)`, one column per rung.
7544    #[test]
7545    fn timestamp_string_resolution_and_formatting_match_pandas() {
7546        use super::{DatetimeStringResolution as Res, Timestamp};
7547
7548        const MIDNIGHT: i64 = 1_710_460_800_000_000_000; // 2024-03-15 00:00:00
7549
7550        // Which rung each value needs, on its own.
7551        assert_eq!(Timestamp::string_resolution(MIDNIGHT), Res::Date);
7552        assert_eq!(
7553            Timestamp::string_resolution(MIDNIGHT + 37_845_000_000_000),
7554            Res::Second
7555        );
7556        assert_eq!(
7557            Timestamp::string_resolution(MIDNIGHT + 37_845_123_000_000),
7558            Res::Milli
7559        );
7560        assert_eq!(
7561            Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_000),
7562            Res::Micro
7563        );
7564        assert_eq!(
7565            Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_789),
7566            Res::Nano
7567        );
7568        // A whole MINUTE is not its own rung — it still needs Second.
7569        assert_eq!(
7570            Timestamp::string_resolution(MIDNIGHT + 300_000_000_000),
7571            Res::Second
7572        );
7573        // NaT reports the coarsest rung, the identity of the `max` fold, which
7574        // is what keeps it from dragging a column to nanoseconds.
7575        assert_eq!(Timestamp::string_resolution(Timestamp::NAT), Res::Date);
7576
7577        // Coarsest-first ordering is what makes `max` mean "finest needed".
7578        assert!(Res::Date < Res::Second);
7579        assert!(Res::Second < Res::Milli);
7580        assert!(Res::Milli < Res::Micro);
7581        assert!(Res::Micro < Res::Nano);
7582
7583        // ...and how ONE value renders at each rung it might be forced into.
7584        let value = MIDNIGHT + 37_845_123_456_789;
7585        assert_eq!(
7586            Timestamp::format_at_resolution(value, Res::Date),
7587            "2024-03-15"
7588        );
7589        assert_eq!(
7590            Timestamp::format_at_resolution(value, Res::Second),
7591            "2024-03-15 10:30:45"
7592        );
7593        assert_eq!(
7594            Timestamp::format_at_resolution(value, Res::Milli),
7595            "2024-03-15 10:30:45.123"
7596        );
7597        assert_eq!(
7598            Timestamp::format_at_resolution(value, Res::Micro),
7599            "2024-03-15 10:30:45.123456"
7600        );
7601        assert_eq!(
7602            Timestamp::format_at_resolution(value, Res::Nano),
7603            "2024-03-15 10:30:45.123456789"
7604        );
7605
7606        // A midnight forced to the nanosecond rung keeps its zero fraction --
7607        // pandas pads, it does not trim.
7608        assert_eq!(
7609            Timestamp::format_at_resolution(MIDNIGHT, Res::Nano),
7610            "2024-03-15 00:00:00.000000000"
7611        );
7612
7613        // ⚠️ NOT isoformat: a SPACE separator, not a `T`.
7614        assert_eq!(
7615            Timestamp::format_at_resolution(MIDNIGHT, Res::Second),
7616            "2024-03-15 00:00:00"
7617        );
7618
7619        // NaT is the STRING "NaT" at every rung.
7620        for resolution in [Res::Date, Res::Second, Res::Milli, Res::Micro, Res::Nano] {
7621            assert_eq!(
7622                Timestamp::format_at_resolution(Timestamp::NAT, resolution),
7623                "NaT"
7624            );
7625        }
7626
7627        // Pre-epoch: rem_euclid must keep the fraction on the right side of
7628        // midnight, or -1ns renders as 1970-01-01 with a negative fraction.
7629        assert_eq!(
7630            Timestamp::format_at_resolution(-1, Res::Nano),
7631            "1969-12-31 23:59:59.999999999"
7632        );
7633
7634        // Both ends of pandas' datetime64[ns] range.
7635        assert_eq!(
7636            Timestamp::format_at_resolution(-9_223_372_036_854_775_806, Res::Nano),
7637            "1677-09-21 00:12:43.145224194"
7638        );
7639        assert_eq!(
7640            Timestamp::format_at_resolution(9_223_372_036_854_775_807, Res::Nano),
7641            "2262-04-11 23:47:16.854775807"
7642        );
7643    }
7644
7645    /// Temporal -> numpy `bool` is nonzero-truthy on the RAW NANOSECONDS, which
7646    /// makes NaT `true`. Transcribed from live pandas 2.2.3 `.astype('bool')`,
7647    /// measured beside `.astype('int64')` so the one rule is visible as one rule.
7648    #[test]
7649    fn cast_scalar_temporal_to_bool_is_nonzero_on_the_nanos() {
7650        use super::{Timedelta, Timestamp, cast_scalar};
7651
7652        // Only the epoch and a zero duration are false.
7653        for (nanos, want) in [
7654            (0_i64, false),
7655            (1_710_498_645_123_456_789, true),
7656            (-1, true),
7657            (86_400_000_000_000, true),
7658            (1, true),
7659        ] {
7660            assert_eq!(
7661                cast_scalar(&Scalar::Datetime64(nanos), DType::Bool).unwrap(),
7662                Scalar::Bool(want),
7663                "datetime64 {nanos} -> bool"
7664            );
7665            assert_eq!(
7666                cast_scalar(&Scalar::Timedelta64(nanos), DType::Bool).unwrap(),
7667                Scalar::Bool(want),
7668                "timedelta64 {nanos} -> bool"
7669            );
7670        }
7671
7672        // ⚠️ NaT IS TRUE, not missing. It needs no case of its own — NaT IS
7673        // i64::MIN, which is nonzero — but it only reaches the rule because the
7674        // cast sits ABOVE is_missing(); below it, both of these become Null.
7675        assert_eq!(
7676            cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Bool).unwrap(),
7677            Scalar::Bool(true),
7678            "NaT -> bool is true in pandas, not a missing value"
7679        );
7680        assert_eq!(
7681            cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Bool).unwrap(),
7682            Scalar::Bool(true)
7683        );
7684
7685        // ⚠️ THE NULLABLE `boolean` REFUSES THE WHOLE DTYPE, not just the odd
7686        // value: pandas raises "Need to pass bool-like values" for every row
7687        // above, INCLUDING the ones whose nanos are 0 or 1. That exclusion is
7688        // what the `DType::Bool` guard buys, so it is asserted rather than
7689        // assumed.
7690        //
7691        // NaT is deliberately NOT in this loop, and the reason is a KNOWN
7692        // DIVERGENCE rather than an oversight: `is_missing()` catches NaT before
7693        // any BoolNullable arm can refuse it, so FP answers `Null` where pandas
7694        // raises. Asserting `is_err()` for it here would fail. Left visible.
7695        for nanos in [0_i64, 1, -1, 1_710_498_645_123_456_789] {
7696            assert!(
7697                cast_scalar(&Scalar::Datetime64(nanos), DType::BoolNullable).is_err(),
7698                "datetime64 {nanos} -> nullable boolean must stay refused"
7699            );
7700            assert!(
7701                cast_scalar(&Scalar::Timedelta64(nanos), DType::BoolNullable).is_err(),
7702                "timedelta64 {nanos} -> nullable boolean must stay refused"
7703            );
7704        }
7705    }
7706
7707    #[test]
7708    fn nancount_nunique_prod_any_all_mx60x() {
7709        use super::{nanall, nanany, nancount, nannunique, nanprod};
7710        // br-frankenpandas-mx60x: nancount/nannunique/nanprod/nanany/nanall skip NaN
7711        // and match finite-only oracles. Seeded LCG, no mocks.
7712        let mut s: u64 = 0x4e2a_0b1c_2d3e_4f50;
7713        let mut next = || {
7714            s = s
7715                .wrapping_mul(6_364_136_223_846_793_005)
7716                .wrapping_add(1_442_695_040_888_963_407);
7717            (s >> 33) as u32
7718        };
7719        let asf = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
7720        let asb = |sc: Scalar| -> bool { matches!(sc, Scalar::Bool(true)) };
7721        for iter in 0..1000u32 {
7722            let n = (next() % 10) as usize + 1;
7723            let raw: Vec<f64> = (0..n)
7724                .map(|_| {
7725                    if next() % 4 == 0 {
7726                        f64::NAN
7727                    } else {
7728                        (next() % 5) as f64
7729                    }
7730                })
7731                .collect();
7732            let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
7733            if finite.is_empty() {
7734                continue;
7735            }
7736            let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
7737            let distinct: std::collections::HashSet<u64> =
7738                finite.iter().map(|x| x.to_bits()).collect();
7739            let prod: f64 = finite.iter().product();
7740            assert!(
7741                (asf(nancount(&scalars)) - finite.len() as f64).abs() < 1e-9,
7742                "nancount iter={iter}"
7743            );
7744            assert!(
7745                (asf(nannunique(&scalars)) - distinct.len() as f64).abs() < 1e-9,
7746                "nannunique iter={iter}"
7747            );
7748            assert!(
7749                (asf(nanprod(&scalars)) - prod).abs() < 1e-7,
7750                "nanprod iter={iter}"
7751            );
7752            assert_eq!(
7753                asb(nanany(&scalars)),
7754                finite.iter().any(|&x| x != 0.0),
7755                "nanany iter={iter}"
7756            );
7757            assert_eq!(
7758                asb(nanall(&scalars)),
7759                finite.iter().all(|&x| x != 0.0),
7760                "nanall iter={iter}"
7761            );
7762        }
7763    }
7764
7765    #[test]
7766    fn nan_reduction_kernels_skip_correctness_1uagc() {
7767        use super::{nanmax, nanmedian, nanmin, nansum};
7768        // br-frankenpandas-1uagc: nansum/nanmin/nanmax/nanmedian skip NaN and match
7769        // finite-only oracles. Seeded LCG, no mocks.
7770        let mut s: u64 = 0x4e1a_0b2c_2d3e_4f50;
7771        let mut next = || {
7772            s = s
7773                .wrapping_mul(6_364_136_223_846_793_005)
7774                .wrapping_add(1_442_695_040_888_963_407);
7775            (s >> 33) as u32
7776        };
7777        let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
7778        for iter in 0..1000u32 {
7779            let n = (next() % 12) as usize + 1;
7780            let raw: Vec<f64> = (0..n)
7781                .map(|_| {
7782                    if next() % 4 == 0 {
7783                        f64::NAN
7784                    } else {
7785                        (next() % 200) as f64 - 100.0
7786                    }
7787                })
7788                .collect();
7789            let mut finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
7790            if finite.is_empty() {
7791                continue;
7792            }
7793            let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
7794            let sum: f64 = finite.iter().sum();
7795            let mn = finite.iter().copied().fold(f64::INFINITY, f64::min);
7796            let mx = finite.iter().copied().fold(f64::NEG_INFINITY, f64::max);
7797            finite.sort_by(|a, b| a.partial_cmp(b).unwrap());
7798            let m = finite.len();
7799            let med = if m % 2 == 1 {
7800                finite[m / 2]
7801            } else {
7802                (finite[m / 2 - 1] + finite[m / 2]) / 2.0
7803            };
7804            assert!(
7805                (val(nansum(&scalars)) - sum).abs() < 1e-7,
7806                "nansum iter={iter}"
7807            );
7808            assert!(
7809                (val(nanmin(&scalars)) - mn).abs() < 1e-9,
7810                "nanmin iter={iter}"
7811            );
7812            assert!(
7813                (val(nanmax(&scalars)) - mx).abs() < 1e-9,
7814                "nanmax iter={iter}"
7815            );
7816            assert!(
7817                (val(nanmedian(&scalars)) - med).abs() < 1e-9,
7818                "nanmedian iter={iter}"
7819            );
7820        }
7821    }
7822
7823    #[test]
7824    fn nanvar_ddof_nanstd_nan_skip_p00ag() {
7825        use super::{nanmean, nanstd, nanvar};
7826        // br-frankenpandas-p00ag: nanmean/nanvar/nanstd skip NaN; ddof picks the
7827        // denominator; nanstd==sqrt(nanvar). Seeded LCG, no mocks.
7828        let mut s: u64 = 0x4e0a_0b1c_2d3e_4f50;
7829        let mut next = || {
7830            s = s
7831                .wrapping_mul(6_364_136_223_846_793_005)
7832                .wrapping_add(1_442_695_040_888_963_407);
7833            (s >> 33) as u32
7834        };
7835        let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
7836        for iter in 0..1000u32 {
7837            let n = (next() % 10) as usize + 2;
7838            let raw: Vec<f64> = (0..n)
7839                .map(|_| {
7840                    if next() % 4 == 0 {
7841                        f64::NAN
7842                    } else {
7843                        (next() % 200) as f64 / 7.0
7844                    }
7845                })
7846                .collect();
7847            let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
7848            if finite.len() < 2 {
7849                continue;
7850            }
7851            let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
7852            let nf = finite.len() as f64;
7853            let mean = finite.iter().sum::<f64>() / nf;
7854            let ss = finite.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
7855            assert!(
7856                (val(nanmean(&scalars)) - mean).abs() < 1e-7,
7857                "nanmean iter={iter}"
7858            );
7859            assert!(
7860                (val(nanvar(&scalars, 0)) - ss / nf).abs() < 1e-7,
7861                "nanvar ddof0 iter={iter}"
7862            );
7863            assert!(
7864                (val(nanvar(&scalars, 1)) - ss / (nf - 1.0)).abs() < 1e-7,
7865                "nanvar ddof1 iter={iter}"
7866            );
7867            assert!(
7868                (val(nanstd(&scalars, 1)) - (ss / (nf - 1.0)).sqrt()).abs() < 1e-7,
7869                "nanstd ddof1 iter={iter}"
7870            );
7871        }
7872    }
7873
7874    #[test]
7875    fn nanskew_nankurt_min_sample_and_known_xybnq() {
7876        // br-frankenpandas-xybnq: guard nanskew/nankurt min-sample-size (NaN below
7877        // threshold) + known pandas G1/G2 values (the f4dc5540 inline-copy bug area).
7878        use super::{nankurt, nanskew};
7879        let f = |xs: &[f64]| -> Vec<Scalar> { xs.iter().map(|&x| Scalar::Float64(x)).collect() };
7880        let val = |s: Scalar| -> Option<f64> {
7881            if s.is_missing() {
7882                None
7883            } else {
7884                s.to_f64().ok()
7885            }
7886        };
7887
7888        // skew needs >= 3 observations.
7889        assert_eq!(val(nanskew(&f(&[1.0, 2.0]))), None, "skew n=2 -> NaN");
7890        let sym = val(nanskew(&f(&[1.0, 2.0, 3.0]))).expect("skew n=3");
7891        assert!(sym.abs() < 1e-9, "symmetric skew ~0, got {sym}");
7892        let right = val(nanskew(&f(&[1.0, 1.0, 1.0, 5.0]))).expect("skew n=4");
7893        assert!(right > 0.0, "right-skewed -> positive skew, got {right}");
7894
7895        // kurt needs >= 4 observations.
7896        assert_eq!(val(nankurt(&f(&[1.0, 2.0, 3.0]))), None, "kurt n=3 -> NaN");
7897        let k = val(nankurt(&f(&[1.0, 2.0, 3.0, 4.0, 5.0]))).expect("kurt n=5");
7898        assert!(
7899            (k - (-1.2)).abs() < 1e-6,
7900            "pandas kurt([1..5]) == -1.2, got {k}"
7901        );
7902    }
7903
7904    #[test]
7905    #[ignore = "foreground release attribution harness"]
7906    fn nanskew_fused_moment_scan_ab_mavln() {
7907        const ROWS: usize = 100_000;
7908        const BATCH: usize = 8;
7909
7910        fn former(values: &[Scalar]) -> Scalar {
7911            let nums = super::collect_finite(values);
7912            let n = nums.len() as f64;
7913            if n < 3.0 {
7914                return Scalar::Null(NullKind::NaN);
7915            }
7916            let mean = nums.iter().sum::<f64>() / n;
7917            let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
7918            let m3: f64 = nums.iter().map(|x| (x - mean).powi(3)).sum();
7919            let s2 = m2 / (n - 1.0);
7920            if s2 == 0.0 {
7921                return Scalar::Float64(0.0);
7922            }
7923            let s3 = s2.powf(1.5);
7924            Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
7925        }
7926
7927        fn assert_bits_eq(former: Scalar, candidate: Scalar) {
7928            match (former, candidate) {
7929                (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
7930                (a, b) => assert_eq!(a, b),
7931            }
7932        }
7933
7934        fn elapsed(values: &[Scalar], skew: fn(&[Scalar]) -> Scalar) -> u128 {
7935            std::hint::black_box(skew(std::hint::black_box(values)));
7936            let started = std::time::Instant::now();
7937            for _ in 0..BATCH {
7938                std::hint::black_box(skew(std::hint::black_box(values)));
7939            }
7940            started.elapsed().as_nanos()
7941        }
7942
7943        fn median(samples: &mut [u128]) -> u128 {
7944            samples.sort_unstable();
7945            samples[samples.len() / 2]
7946        }
7947
7948        for values in [
7949            vec![],
7950            vec![Scalar::Int64(1), Scalar::Int64(2)],
7951            vec![Scalar::Int64(7); 16],
7952            vec![
7953                Scalar::Int64(-3),
7954                Scalar::Null(NullKind::NaN),
7955                Scalar::Float64(2.5),
7956                Scalar::Utf8("skip".to_owned()),
7957                Scalar::Int64(11),
7958            ],
7959        ] {
7960            assert_bits_eq(former(&values), super::nanskew(&values));
7961        }
7962
7963        let values = (0..ROWS)
7964            .map(|i| {
7965                if i % 257 == 0 {
7966                    Scalar::Null(NullKind::NaN)
7967                } else {
7968                    Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
7969                }
7970            })
7971            .collect::<Vec<_>>();
7972        assert_bits_eq(former(&values), super::nanskew(&values));
7973
7974        for _ in 0..2 {
7975            std::hint::black_box(elapsed(&values, former));
7976            std::hint::black_box(elapsed(&values, super::nanskew));
7977        }
7978
7979        let mut former_samples = Vec::with_capacity(18);
7980        let mut candidate_samples = Vec::with_capacity(18);
7981        for block in 0_usize..9 {
7982            if block.is_multiple_of(2) {
7983                former_samples.push(elapsed(&values, former));
7984                candidate_samples.push(elapsed(&values, super::nanskew));
7985                candidate_samples.push(elapsed(&values, super::nanskew));
7986                former_samples.push(elapsed(&values, former));
7987            } else {
7988                candidate_samples.push(elapsed(&values, super::nanskew));
7989                former_samples.push(elapsed(&values, former));
7990                former_samples.push(elapsed(&values, former));
7991                candidate_samples.push(elapsed(&values, super::nanskew));
7992            }
7993        }
7994
7995        let former_p50 = median(&mut former_samples);
7996        let candidate_p50 = median(&mut candidate_samples);
7997        eprintln!(
7998            "NANSKEW_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
7999            former_p50 as f64 / candidate_p50 as f64,
8000        );
8001        eprintln!("NANSKEW_FUSED_AB former_samples_ns={former_samples:?}");
8002        eprintln!("NANSKEW_FUSED_AB candidate_samples_ns={candidate_samples:?}");
8003    }
8004
8005    #[test]
8006    #[ignore = "foreground performance probe"]
8007    fn nankurt_fused_moment_scan_ab_idka7() {
8008        const ROWS: usize = 65_536;
8009        const BATCH: usize = 4;
8010
8011        fn former(values: &[Scalar]) -> Scalar {
8012            let nums = super::collect_finite(values);
8013            let n = nums.len() as f64;
8014            if n < 4.0 {
8015                return Scalar::Null(NullKind::NaN);
8016            }
8017            let mean = nums.iter().sum::<f64>() / n;
8018            let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
8019            let m4: f64 = nums.iter().map(|x| (x - mean).powi(4)).sum();
8020            let s2 = m2 / (n - 1.0);
8021            if s2 == 0.0 {
8022                return Scalar::Float64(0.0);
8023            }
8024            let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
8025            let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
8026            Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
8027        }
8028
8029        fn assert_bits_eq(former: Scalar, candidate: Scalar) {
8030            match (former, candidate) {
8031                (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
8032                (a, b) => assert_eq!(a, b),
8033            }
8034        }
8035
8036        fn elapsed(values: &[Scalar], kurt: fn(&[Scalar]) -> Scalar) -> u128 {
8037            let started = std::time::Instant::now();
8038            for _ in 0..BATCH {
8039                std::hint::black_box(kurt(std::hint::black_box(values)));
8040            }
8041            started.elapsed().as_nanos()
8042        }
8043
8044        fn median(samples: &mut [u128]) -> u128 {
8045            samples.sort_unstable();
8046            samples[samples.len() / 2]
8047        }
8048
8049        for values in [
8050            vec![],
8051            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
8052            vec![Scalar::Int64(7); 16],
8053            vec![
8054                Scalar::Int64(-3),
8055                Scalar::Null(NullKind::NaN),
8056                Scalar::Float64(2.5),
8057                Scalar::Utf8("skip".to_owned()),
8058                Scalar::Int64(11),
8059                Scalar::Float64(-7.25),
8060            ],
8061        ] {
8062            assert_bits_eq(former(&values), super::nankurt(&values));
8063        }
8064
8065        let values = (0..ROWS)
8066            .map(|i| {
8067                if i % 257 == 0 {
8068                    Scalar::Null(NullKind::NaN)
8069                } else {
8070                    Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
8071                }
8072            })
8073            .collect::<Vec<_>>();
8074        assert_bits_eq(former(&values), super::nankurt(&values));
8075
8076        for _ in 0..2 {
8077            std::hint::black_box(elapsed(&values, former));
8078            std::hint::black_box(elapsed(&values, super::nankurt));
8079        }
8080
8081        let mut former_samples = Vec::with_capacity(10);
8082        let mut candidate_samples = Vec::with_capacity(10);
8083        for block in 0_usize..5 {
8084            if block.is_multiple_of(2) {
8085                former_samples.push(elapsed(&values, former));
8086                candidate_samples.push(elapsed(&values, super::nankurt));
8087                candidate_samples.push(elapsed(&values, super::nankurt));
8088                former_samples.push(elapsed(&values, former));
8089            } else {
8090                candidate_samples.push(elapsed(&values, super::nankurt));
8091                former_samples.push(elapsed(&values, former));
8092                former_samples.push(elapsed(&values, former));
8093                candidate_samples.push(elapsed(&values, super::nankurt));
8094            }
8095        }
8096
8097        let former_p50 = median(&mut former_samples);
8098        let candidate_p50 = median(&mut candidate_samples);
8099        eprintln!(
8100            "NANKURT_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
8101            former_p50 as f64 / candidate_p50 as f64,
8102        );
8103        eprintln!("NANKURT_FUSED_AB former_samples_ns={former_samples:?}");
8104        eprintln!("NANKURT_FUSED_AB candidate_samples_ns={candidate_samples:?}");
8105    }
8106
8107    /// behind astype/promotion. Property test of its confirmed identity +
8108    /// numeric/bool coercion rules over random scalars. Deterministic seeded LCG.
8109    #[test]
8110    fn cast_scalar_to_utf8_formatting_yes7i() {
8111        // Property (br-frankenpandas-yes7i): cast to Utf8 formats per pandas
8112        // astype(str): Int64 -> decimal, Bool -> True/False. Seeded LCG, no mocks.
8113        let mut st: u64 = 0x4e57_0b1c_2d3e_4f50;
8114        let mut next = || {
8115            st = st
8116                .wrapping_mul(6_364_136_223_846_793_005)
8117                .wrapping_add(1_442_695_040_888_963_407);
8118            (st >> 33) as u32
8119        };
8120        for _ in 0..3000u32 {
8121            let n = (next() % 4_000_001) as i64 - 2_000_000;
8122            assert_eq!(
8123                cast_scalar(&Scalar::Int64(n), DType::Utf8).unwrap(),
8124                Scalar::Utf8(n.to_string())
8125            );
8126        }
8127        assert_eq!(
8128            cast_scalar(&Scalar::Bool(true), DType::Utf8).unwrap(),
8129            Scalar::Utf8("True".to_string())
8130        );
8131        assert_eq!(
8132            cast_scalar(&Scalar::Bool(false), DType::Utf8).unwrap(),
8133            Scalar::Utf8("False".to_string())
8134        );
8135    }
8136
8137    #[test]
8138    fn cast_scalar_coercion_rules_6a83t() {
8139        let mut state: u64 = 0x5a17_c0de_1234_abcd;
8140        let mut next = || {
8141            state = state
8142                .wrapping_mul(6_364_136_223_846_793_005)
8143                .wrapping_add(1_442_695_040_888_963_407);
8144            (state >> 33) as u32
8145        };
8146
8147        for _ in 0..4000u32 {
8148            let n = (next() % 21) as i64 - 10; // -10..=10, incl 0
8149            let b = next() % 2 == 0;
8150            let f = f64::from((next() % 41) as i32 - 20) / 4.0; // finite, incl 0.0
8151
8152            let i = Scalar::Int64(n);
8153            let bo = Scalar::Bool(b);
8154            let fl = Scalar::Float64(f);
8155
8156            // Identity casts.
8157            assert_eq!(cast_scalar(&i, DType::Int64), Ok(i.clone()));
8158            assert_eq!(cast_scalar(&bo, DType::Bool), Ok(bo.clone()));
8159            assert_eq!(cast_scalar(&fl, DType::Float64), Ok(fl.clone()));
8160
8161            // Representation-preserving nullable identities.
8162            assert_eq!(cast_scalar(&i, DType::Int64Nullable), Ok(i.clone()));
8163            assert_eq!(cast_scalar(&bo, DType::BoolNullable), Ok(bo.clone()));
8164
8165            // Int64 coercions.
8166            assert_eq!(cast_scalar(&i, DType::Bool), Ok(Scalar::Bool(n != 0)));
8167            assert_eq!(
8168                cast_scalar(&i, DType::Float64),
8169                Ok(Scalar::Float64(n as f64))
8170            );
8171
8172            // Bool coercions.
8173            assert_eq!(
8174                cast_scalar(&bo, DType::Int64),
8175                Ok(Scalar::Int64(i64::from(b)))
8176            );
8177            assert_eq!(
8178                cast_scalar(&bo, DType::Float64),
8179                Ok(Scalar::Float64(if b { 1.0 } else { 0.0 }))
8180            );
8181
8182            // Finite Float64 -> Int64 truncates toward zero (x as i64).
8183            assert_eq!(cast_scalar(&fl, DType::Int64), Ok(Scalar::Int64(f as i64)));
8184        }
8185    }
8186
8187    /// br-frankenpandas-esjjy / fd90.182: ergonomic From impls for Scalar.
8188    #[test]
8189    fn scalar_from_primitive_types() {
8190        // Each primitive maps to its canonical Scalar variant.
8191        assert_eq!(Scalar::from(true), Scalar::Bool(true));
8192        assert_eq!(Scalar::from(42i64), Scalar::Int64(42));
8193        assert_eq!(Scalar::from(1.5f64), Scalar::Float64(1.5));
8194        assert_eq!(Scalar::from("hi"), Scalar::Utf8("hi".to_owned()));
8195        assert_eq!(
8196            Scalar::from(String::from("world")),
8197            Scalar::Utf8("world".to_owned())
8198        );
8199
8200        // .into() works in mixed-type Vec<Scalar> contexts (the README's
8201        // case_when example pattern, and what fd90.181 needed for apply_row
8202        // closures).
8203        let mixed: Vec<Scalar> = vec![1i64.into(), 2.0f64.into(), "three".into()];
8204        assert_eq!(mixed[0], Scalar::Int64(1));
8205        assert_eq!(mixed[1], Scalar::Float64(2.0));
8206        assert_eq!(mixed[2], Scalar::Utf8("three".to_owned()));
8207    }
8208
8209    #[test]
8210    fn dtype_inference_routes_bool_numeric_mix_to_object_bucket_rh1od() {
8211        // Was `dtype_inference_coerces_numeric_values` (Bool+Int64+Float64 ->
8212        // Float64). br-frankenpandas-rh1od, MEASURED live pandas 2.2.3:
8213        // pd.Series([True, 7, 3.5]) constructs OBJECT — no pandas constructor
8214        // path produces the numpy common-type Float64 here.
8215        let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Float64(3.5)];
8216        assert_eq!(
8217            infer_dtype(&values).expect("dtype should infer"),
8218            DType::Utf8
8219        );
8220    }
8221
8222    #[test]
8223    fn interval_scalar_has_dtype_storage_and_unique_semantics_5g5uj() {
8224        let left = Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right));
8225        let right = Scalar::Interval(Interval::new(1.0, 2.0, IntervalClosed::Right));
8226        assert_eq!(left.dtype(), DType::Interval);
8227        assert!(!left.is_missing());
8228        assert_eq!(
8229            infer_dtype(&[left.clone(), right.clone()]).expect("interval dtype"),
8230            DType::Interval
8231        );
8232        assert_eq!(
8233            common_dtype(DType::Interval, DType::Interval).expect("same interval dtype"),
8234            DType::Interval
8235        );
8236        assert_eq!(
8237            cast_scalar(&Scalar::Null(NullKind::Null), DType::Interval).expect("missing casts"),
8238            Scalar::Null(NullKind::Null)
8239        );
8240        assert_eq!(
8241            cast_scalar(&left, DType::Utf8).expect("interval string cast"),
8242            Scalar::Utf8("(0.0, 1.0]".to_owned())
8243        );
8244        assert_eq!(
8245            super::nannunique(&[left.clone(), right, left, Scalar::Null(NullKind::Null)]),
8246            Scalar::Int64(2)
8247        );
8248    }
8249
8250    #[test]
8251    fn cast_scalar_parses_temporal_extension_strings_avm08() {
8252        let expected_nanos = super::Timestamp::parse("2024-01-15T10:30:45")
8253            .expect("timestamp parse")
8254            .nanos;
8255        assert_eq!(
8256            cast_scalar(
8257                &Scalar::Utf8("2024-01-15T10:30:45".to_owned()),
8258                DType::datetime64_naive()
8259            )
8260            .expect("datetime cast"),
8261            Scalar::Datetime64(expected_nanos)
8262        );
8263        assert_eq!(
8264            cast_scalar(&Scalar::Utf8("2024Q1".to_owned()), DType::Period).expect("period cast"),
8265            Scalar::Period(Period::new(216, PeriodFreq::Quarterly))
8266        );
8267        assert_eq!(
8268            cast_scalar(&Scalar::Utf8("(0, 1]".to_owned()), DType::Interval)
8269                .expect("interval cast"),
8270            Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right))
8271        );
8272    }
8273
8274    #[test]
8275    fn missing_values_get_target_missing_marker() {
8276        let missing = Scalar::Null(NullKind::Null);
8277        let cast = cast_scalar(&missing, DType::Float64).expect("missing casts");
8278        assert_eq!(cast, Scalar::Null(NullKind::NaN));
8279    }
8280
8281    #[test]
8282    fn cast_scalar_to_utf8_uses_pandas_string_spellings() {
8283        let cases = [
8284            (Scalar::Bool(true), "True"),
8285            (Scalar::Bool(false), "False"),
8286            (Scalar::Int64(-7), "-7"),
8287            (Scalar::Float64(1.0), "1.0"),
8288            (Scalar::Float64(1.5), "1.5"),
8289            (Scalar::Float64(f64::NAN), "nan"),
8290            (Scalar::Null(NullKind::Null), "None"),
8291            (Scalar::Null(NullKind::NaN), "nan"),
8292            (Scalar::Null(NullKind::NaT), "NaT"),
8293        ];
8294
8295        for (value, expected) in cases {
8296            assert_eq!(
8297                cast_scalar(&value, DType::Utf8).expect("cast"),
8298                Scalar::Utf8(expected.to_owned())
8299            );
8300        }
8301    }
8302
8303    #[test]
8304    fn semantic_eq_treats_nan_as_equal() {
8305        let left = Scalar::Float64(f64::NAN);
8306        let right = Scalar::Null(NullKind::NaN);
8307        assert!(left.semantic_eq(&right));
8308    }
8309
8310    #[test]
8311    fn semantic_eq_treats_nan_as_missing_null() {
8312        let left = Scalar::Float64(f64::NAN);
8313        let right = Scalar::Null(NullKind::Null);
8314        assert!(left.semantic_eq(&right));
8315    }
8316
8317    /// A DTYPE-SENTINEL missing equals a `Null` marker, for every dtype that
8318    /// has one.
8319    ///
8320    /// `missing_for_dtype` DEFINES the canonical missing for Timedelta64 as
8321    /// `Timedelta64(NAT)`, for Datetime64 as `Datetime64(NAT)` and for Period as
8322    /// ordinal `i64::MIN`, and `is_missing()` agrees — but `semantic_eq` used to
8323    /// unify only the `Null`/NaN flavours, so an oracle's `null` for pandas' NaT
8324    /// could never match FP's sentinel. Observed on
8325    /// `fp_p2d_021_series_to_timedelta_negative_null_hardened`, where the
8326    /// fixture pinned the raw `-9223372036854775808` as though it were data.
8327    ///
8328    /// THE NEGATIVE CASES ARE THE POINT — "both missing" must not become "any
8329    /// sentinel matches anything":
8330    /// - a NaT sentinel must NOT equal a PRESENT timedelta;
8331    /// - two DIFFERENT present timedeltas must stay unequal;
8332    /// - Period and Datetime64 must unify too, or the fix is Timedelta-only.
8333    ///
8334    /// (br-frankenpandas-xwxci)
8335    #[test]
8336    fn semantic_eq_unifies_dtype_sentinel_missing_with_null_xwxci() {
8337        for sentinel in [
8338            Scalar::Timedelta64(Timedelta::NAT),
8339            Scalar::Datetime64(Timestamp::NAT),
8340            Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
8341        ] {
8342            assert!(sentinel.is_missing(), "{sentinel:?} must report missing");
8343            for marker in [
8344                Scalar::Null(NullKind::Null),
8345                Scalar::Null(NullKind::NaN),
8346                Scalar::Null(NullKind::NaT),
8347            ] {
8348                assert!(
8349                    sentinel.semantic_eq(&marker),
8350                    "{sentinel:?} vs {marker:?} are both missing"
8351                );
8352                assert!(marker.semantic_eq(&sentinel), "and symmetrically");
8353            }
8354        }
8355
8356        // NOT a blanket match: a sentinel differs from a PRESENT value.
8357        let present = Scalar::Timedelta64(-60);
8358        assert!(!Scalar::Timedelta64(Timedelta::NAT).semantic_eq(&present));
8359        assert!(!present.semantic_eq(&Scalar::Null(NullKind::Null)));
8360        // And two distinct present values stay distinct.
8361        assert!(!present.semantic_eq(&Scalar::Timedelta64(-61)));
8362    }
8363
8364    #[test]
8365    fn common_dtype_rejects_string_numeric_mix() {
8366        let err = common_dtype(DType::Utf8, DType::Int64).expect_err("must fail");
8367        assert_eq!(
8368            err.to_string(),
8369            "dtype coercion from Utf8 to Int64 has no compatible common type"
8370        );
8371        let err = common_dtype(DType::Float64, DType::Utf8).expect_err("must fail");
8372        assert_eq!(
8373            err.to_string(),
8374            "dtype coercion from Float64 to Utf8 has no compatible common type"
8375        );
8376    }
8377
8378    #[test]
8379    fn sparse_dtype_normalizes_fill_value_to_value_dtype() {
8380        let dtype = SparseDType::new(DType::Float64, Scalar::Int64(0)).expect("fill should cast");
8381
8382        assert_eq!(dtype.value_dtype, DType::Float64);
8383        assert_eq!(dtype.fill_value, Scalar::Float64(0.0));
8384    }
8385
8386    #[test]
8387    fn sparse_dtype_rejects_sparse_value_dtype() {
8388        let err = SparseDType::new(DType::Sparse, Scalar::Int64(0)).expect_err("must reject");
8389
8390        assert_eq!(err.to_string(), "sparse value dtype cannot be Sparse");
8391    }
8392
8393    #[test]
8394    fn common_dtype_rejects_sparse_dense_mix() {
8395        let err = common_dtype(DType::Sparse, DType::Int64).expect_err("must fail");
8396
8397        assert_eq!(
8398            err.to_string(),
8399            "dtype coercion from Sparse to Int64 has no compatible common type"
8400        );
8401    }
8402
8403    // ── Nullable Int64/Bool dtype tests (br-frankenpandas-rg8ys.6.4) ────
8404
8405    #[test]
8406    fn nullable_int64_promotion_matrix() {
8407        // Int64 + Int64Nullable -> Int64Nullable (nullable absorbs)
8408        assert_eq!(
8409            common_dtype(DType::Int64, DType::Int64Nullable).unwrap(),
8410            DType::Int64Nullable
8411        );
8412        assert_eq!(
8413            common_dtype(DType::Int64Nullable, DType::Int64).unwrap(),
8414            DType::Int64Nullable
8415        );
8416
8417        // Int64Nullable + Float64 -> Float64Nullable. The old comment here said
8418        // "float always wins"; that is half right. The float wins, but the
8419        // NULLABLE flavour of it does — MEASURED, live pandas 2.2.3:
8420        //   pd.Series([1,None],dtype="Int64") + pd.Series([1.5,2.5]) -> Float64
8421        // where that Float64 is the extension dtype (missing = pd.NA), not
8422        // numpy float64 (missing = NaN). (br-frankenpandas-qkqfb)
8423        assert_eq!(
8424            common_dtype(DType::Int64Nullable, DType::Float64).unwrap(),
8425            DType::Float64Nullable
8426        );
8427        assert_eq!(
8428            common_dtype(DType::Float64, DType::Int64Nullable).unwrap(),
8429            DType::Float64Nullable
8430        );
8431
8432        // Int64Nullable + Int64Nullable -> Int64Nullable
8433        assert_eq!(
8434            common_dtype(DType::Int64Nullable, DType::Int64Nullable).unwrap(),
8435            DType::Int64Nullable
8436        );
8437
8438        // Bool + Int64Nullable -> Int64Nullable
8439        assert_eq!(
8440            common_dtype(DType::Bool, DType::Int64Nullable).unwrap(),
8441            DType::Int64Nullable
8442        );
8443
8444        // BoolNullable + Int64 -> Int64Nullable
8445        assert_eq!(
8446            common_dtype(DType::BoolNullable, DType::Int64).unwrap(),
8447            DType::Int64Nullable
8448        );
8449    }
8450
8451    #[test]
8452    fn nullable_bool_promotion_matrix() {
8453        // Bool + BoolNullable -> BoolNullable
8454        assert_eq!(
8455            common_dtype(DType::Bool, DType::BoolNullable).unwrap(),
8456            DType::BoolNullable
8457        );
8458        assert_eq!(
8459            common_dtype(DType::BoolNullable, DType::Bool).unwrap(),
8460            DType::BoolNullable
8461        );
8462
8463        // BoolNullable + Float64 -> Float64Nullable. MEASURED, live pandas 2.2.3:
8464        //   pd.Series([True,None],dtype="boolean") + pd.Series([1.5,2.5,3.5])
8465        //     -> Float64   (extension)
8466        // This arm moves together with the Int64Nullable one in
8467        // nullable_int64_promotion_matrix; flipping either alone breaks lattice
8468        // associativity. (br-frankenpandas-qkqfb)
8469        assert_eq!(
8470            common_dtype(DType::BoolNullable, DType::Float64).unwrap(),
8471            DType::Float64Nullable
8472        );
8473
8474        // CONTROL: the all-numpy pair is untouched and stays on the numpy side.
8475        //   pd.Series([True,False],dtype="bool") + pd.Series([1.5,2.5]) -> float64
8476        assert_eq!(
8477            common_dtype(DType::Bool, DType::Float64).unwrap(),
8478            DType::Float64
8479        );
8480    }
8481
8482    #[test]
8483    fn dtype_is_nullable_helper() {
8484        assert!(DType::Int64Nullable.is_nullable());
8485        assert!(DType::BoolNullable.is_nullable());
8486        assert!(!DType::Int64.is_nullable());
8487        assert!(!DType::Bool.is_nullable());
8488        assert!(!DType::Float64.is_nullable());
8489        assert!(!DType::Utf8.is_nullable());
8490    }
8491
8492    #[test]
8493    fn dtype_to_nullable_conversions() {
8494        assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
8495        assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
8496        // ⚠ THIS LINE WAS RED ON main SINCE fa6caee91 AND NOBODY SAW IT.
8497        // It used to read `Float64.to_nullable() == Float64  // unchanged`,
8498        // which was true only while FP had no nullable float at all. fa6caee91
8499        // (br-frankenpandas-qkqfb slice 1) added DType::Float64Nullable and
8500        // pointed to_nullable at it, but that commit was gated with
8501        // `cargo check --all-targets` plus a NAME-FILTERED test run, so this
8502        // pre-existing test was never executed and the break went unnoticed.
8503        // Float64's nullable flavour IS Float64Nullable — that is the dtype's
8504        // entire reason to exist — so the assertion is what was stale.
8505        assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
8506        assert_eq!(
8507            DType::Float64Nullable.to_nullable(),
8508            DType::Float64Nullable,
8509            "idempotent: already nullable"
8510        );
8511        assert_eq!(DType::Int64Nullable.to_nullable(), DType::Int64Nullable);
8512    }
8513
8514    #[test]
8515    fn dtype_to_non_nullable_conversions() {
8516        assert_eq!(DType::Int64Nullable.to_non_nullable(), DType::Int64);
8517        assert_eq!(DType::BoolNullable.to_non_nullable(), DType::Bool);
8518        assert_eq!(DType::Int64.to_non_nullable(), DType::Int64); // unchanged
8519        assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
8520    }
8521
8522    #[test]
8523    fn nullable_dtype_name_reports_pandas_style() {
8524        assert_eq!(DType::Int64.name(), "int64");
8525        assert_eq!(DType::Int64Nullable.name(), "Int64"); // capital I
8526        assert_eq!(DType::Bool.name(), "bool");
8527        assert_eq!(DType::BoolNullable.name(), "boolean");
8528    }
8529
8530    #[test]
8531    fn cast_scalar_int64_nullable_identity() {
8532        let val = Scalar::Int64(42);
8533        // Int64 -> Int64Nullable is identity (no actual conversion)
8534        let result = cast_scalar(&val, DType::Int64Nullable).unwrap();
8535        assert_eq!(result, Scalar::Int64(42));
8536
8537        // Int64Nullable -> Int64 is also identity
8538        let result2 = cast_scalar(&val, DType::Int64).unwrap();
8539        assert_eq!(result2, Scalar::Int64(42));
8540    }
8541
8542    #[test]
8543    fn cast_float_to_utf8_uses_pandas_str_float_with_scientific() {
8544        // pandas astype(str) of floats == Python str(float): whole -> ".0",
8545        // shortest round-trip decimals, scientific (e+NN/e-NN) for large/small,
8546        // inf -> "inf", NaN -> "nan". Verified vs live pandas 2.2.3. (Previously
8547        // large/small lost scientific notation, e.g. 1e16 -> "10000000000000000.0".)
8548        let cases: &[(f64, &str)] = &[
8549            (1.0, "1.0"),
8550            (2.5, "2.5"),
8551            (100.0, "100.0"),
8552            (0.1, "0.1"),
8553            (0.0001, "0.0001"),
8554            (1e16, "1e+16"),
8555            (1e20, "1e+20"),
8556            (1e-5, "1e-05"),
8557            (1e-7, "1e-07"),
8558            (f64::INFINITY, "inf"),
8559            (f64::NEG_INFINITY, "-inf"),
8560        ];
8561        for (v, expected) in cases {
8562            assert_eq!(
8563                cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
8564                Scalar::Utf8((*expected).to_owned()),
8565                "float {v} -> str"
8566            );
8567        }
8568    }
8569
8570    fn float_to_string_for_astype_former(value: f64) -> String {
8571        if value.is_nan() {
8572            return "nan".to_owned();
8573        }
8574        if value.is_infinite() {
8575            return value.to_string();
8576        }
8577        let rendered = format!("{value:?}");
8578        match rendered.split_once('e') {
8579            None => rendered,
8580            Some((mantissa, exponent)) => {
8581                let (sign, digits) = match exponent.strip_prefix('-') {
8582                    Some(digits) => ('-', digits),
8583                    None => ('+', exponent.strip_prefix('+').unwrap_or(exponent)),
8584                };
8585                format!("{mantissa}e{sign}{digits:0>2}")
8586            }
8587        }
8588    }
8589
8590    fn scientific_astype_values(len: usize) -> Vec<f64> {
8591        const EXPONENTS: [i32; 16] = [
8592            -300, -200, -100, -50, -10, -7, -6, -5, 16, 17, 20, 50, 100, 200, 300, 307,
8593        ];
8594        (0..len)
8595            .map(|position| {
8596                let mantissa = 1.0 + (position % 997) as f64 / 997.0;
8597                let magnitude = mantissa * 10.0_f64.powi(EXPONENTS[position % EXPONENTS.len()]);
8598                if position.is_multiple_of(2) {
8599                    magnitude
8600                } else {
8601                    -magnitude
8602                }
8603            })
8604            .collect()
8605    }
8606
8607    #[test]
8608    fn float_to_string_for_astype_in_place_matches_former() {
8609        let fixed = [
8610            f64::NAN,
8611            f64::INFINITY,
8612            f64::NEG_INFINITY,
8613            0.0,
8614            -0.0,
8615            f64::MIN_POSITIVE,
8616            f64::MAX,
8617            f64::MIN,
8618            1e16,
8619            -1e16,
8620            1e-5,
8621            -1e-5,
8622            1.234_567_890_123_456_8e20,
8623            -9.876_543_210_987_654e-123,
8624        ];
8625        for value in fixed.into_iter().chain(scientific_astype_values(16_384)) {
8626            assert_eq!(
8627                super::float_to_string_for_astype(value),
8628                float_to_string_for_astype_former(value),
8629                "value={value:?}"
8630            );
8631        }
8632    }
8633
8634    #[test]
8635    #[ignore = "foreground performance probe"]
8636    fn float_to_string_for_astype_in_place_ab() {
8637        use std::time::Instant;
8638
8639        const VALUES: usize = 16_384;
8640        const SAMPLES: usize = 10;
8641        let values = scientific_astype_values(VALUES);
8642        for &value in &values {
8643            let former = float_to_string_for_astype_former(value);
8644            assert!(former.contains('e'), "benchmark value must be scientific");
8645            assert_eq!(super::float_to_string_for_astype(value), former);
8646        }
8647
8648        for _ in 0..2 {
8649            for &value in &values {
8650                std::hint::black_box(float_to_string_for_astype_former(value));
8651                std::hint::black_box(super::float_to_string_for_astype(value));
8652            }
8653        }
8654
8655        let mut former_ns = Vec::with_capacity(SAMPLES);
8656        let mut public_ns = Vec::with_capacity(SAMPLES);
8657        for sample in 0..SAMPLES {
8658            let run = |formatter: fn(f64) -> String| {
8659                let started = Instant::now();
8660                for &value in std::hint::black_box(&values) {
8661                    std::hint::black_box(formatter(std::hint::black_box(value)));
8662                }
8663                started.elapsed().as_nanos()
8664            };
8665            if sample.is_multiple_of(2) {
8666                former_ns.push(run(float_to_string_for_astype_former));
8667                public_ns.push(run(super::float_to_string_for_astype));
8668            } else {
8669                public_ns.push(run(super::float_to_string_for_astype));
8670                former_ns.push(run(float_to_string_for_astype_former));
8671            }
8672        }
8673
8674        former_ns.sort_unstable();
8675        public_ns.sort_unstable();
8676        let former_p50 = former_ns[SAMPLES / 2];
8677        let public_p50 = public_ns[SAMPLES / 2];
8678        println!(
8679            "float_to_string_for_astype_in_place_ab values={VALUES} former_p50_ns={former_p50} public_p50_ns={public_p50} speedup={:.6} former_samples={former_ns:?} public_samples={public_ns:?}",
8680            former_p50 as f64 / public_p50 as f64
8681        );
8682    }
8683
8684    #[test]
8685    fn cast_float_to_utf8_threshold_boundaries_match_python() {
8686        // Python str(float) switches to scientific notation only at |x| >= 1e16
8687        // or |x| < 1e-4. Values JUST INSIDE those bounds must stay decimal — a
8688        // formatter that switches to sci early (or late) diverges. All expected
8689        // values verified against Python 3 str()/repr (== pandas astype(str)).
8690        let cases: &[(f64, &str)] = &[
8691            (1e15, "1000000000000000.0"),
8692            (9_999_999_999_999_998.0, "9999999999999998.0"),
8693            (1_234_567_890_123_456.0, "1234567890123456.0"),
8694            (123_456_789_012_345.0, "123456789012345.0"),
8695            (12_345_678_901_234_567.0, "1.2345678901234568e+16"),
8696            (1e16, "1e+16"),
8697            (1.5e16, "1.5e+16"),
8698            (1e17, "1e+17"),
8699            (1e-4, "0.0001"),
8700            (5e-5, "5e-05"),
8701            (-1e15, "-1000000000000000.0"),
8702            (-1e16, "-1e+16"),
8703            (-1e-5, "-1e-05"),
8704        ];
8705        for (v, expected) in cases {
8706            assert_eq!(
8707                cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
8708                Scalar::Utf8((*expected).to_owned()),
8709                "float {v} -> str"
8710            );
8711        }
8712    }
8713
8714    #[test]
8715    fn cast_to_bool_uses_pandas_nonzero_truthiness() {
8716        // pandas astype(bool): zero -> False, any nonzero -> True (not just 0/1),
8717        // -0.0 -> False, and NaN -> True (numpy bool(nan), br-cyi4h). Verified vs
8718        // live pandas 2.2.3.
8719        let cases_int: &[(i64, bool)] = &[(0, false), (1, true), (-3, true), (2, true)];
8720        for (v, expected) in cases_int {
8721            assert_eq!(
8722                cast_scalar(&Scalar::Int64(*v), DType::Bool).unwrap(),
8723                Scalar::Bool(*expected),
8724                "int {v} -> bool"
8725            );
8726        }
8727        let cases_float: &[(f64, bool)] = &[
8728            (0.0, false),
8729            (-0.0, false),
8730            (0.1, true),
8731            (2.5, true),
8732            (1.0, true),
8733            // pandas astype(bool): NaN is truthy -> True (numpy bool). br-cyi4h.
8734            (f64::NAN, true),
8735        ];
8736        for (v, expected) in cases_float {
8737            assert_eq!(
8738                cast_scalar(&Scalar::Float64(*v), DType::Bool).unwrap(),
8739                Scalar::Bool(*expected),
8740                "float {v} -> bool"
8741            );
8742        }
8743    }
8744
8745    #[test]
8746    fn nullable_dtype_is_extension() {
8747        assert!(DType::Int64Nullable.is_extension());
8748        assert!(DType::BoolNullable.is_extension());
8749        assert!(!DType::Int64.is_extension());
8750        assert!(!DType::Bool.is_extension());
8751    }
8752
8753    #[test]
8754    fn infer_dtype_preserves_string_numeric_mix_as_utf8_bucket() {
8755        let values = vec![Scalar::Utf8("x".into()), Scalar::Int64(7)];
8756        assert_eq!(
8757            infer_dtype(&values).expect("dtype should infer"),
8758            DType::Utf8
8759        );
8760    }
8761
8762    #[test]
8763    fn infer_dtype_routes_bool_numeric_mix_to_utf8_object_bucket_rh1od() {
8764        // br-frankenpandas-rh1od, MEASURED live pandas 2.2.3: a bool mixed
8765        // with any numeric scalar constructs OBJECT ([True, 2] -> object,
8766        // payloads preserved); numpy's bool<int common-type never fires at
8767        // the constructor. Discriminating: before the change this inferred
8768        // Int64 and coerced True -> 1.
8769        let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Bool(false)];
8770        assert_eq!(
8771            infer_dtype(&values).expect("dtype should infer"),
8772            DType::Utf8
8773        );
8774        let with_float = vec![Scalar::Int64(1), Scalar::Float64(2.5), Scalar::Bool(true)];
8775        assert_eq!(
8776            infer_dtype(&with_float).expect("dtype should infer"),
8777            DType::Utf8
8778        );
8779        let with_null = vec![
8780            Scalar::Bool(true),
8781            Scalar::Null(NullKind::Null),
8782            Scalar::Int64(2),
8783        ];
8784        assert_eq!(
8785            infer_dtype(&with_null).expect("dtype should infer"),
8786            DType::Utf8
8787        );
8788    }
8789
8790    #[test]
8791    fn infer_dtype_keeps_nonmixed_bool_and_numeric_paths_rh1od() {
8792        // Pure bool stays bool; numeric-only mixes keep the common_dtype
8793        // lattice (int+float -> float64) — the object bucket is ONLY for the
8794        // cross-family mix.
8795        assert_eq!(
8796            infer_dtype(&[Scalar::Bool(true), Scalar::Bool(false)]).expect("dtype should infer"),
8797            DType::Bool
8798        );
8799        assert_eq!(
8800            infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]).expect("dtype should infer"),
8801            DType::Float64
8802        );
8803    }
8804
8805    // ── Scalar missingness methods ─────────────────────────────────────
8806
8807    #[test]
8808    fn is_null_detects_explicit_nulls() {
8809        assert!(Scalar::Null(NullKind::Null).is_null());
8810        assert!(Scalar::Null(NullKind::NaN).is_null());
8811        assert!(!Scalar::Int64(42).is_null());
8812        assert!(!Scalar::Float64(f64::NAN).is_null());
8813    }
8814
8815    #[test]
8816    fn is_na_matches_is_missing() {
8817        let vals = vec![
8818            Scalar::Null(NullKind::Null),
8819            Scalar::Float64(f64::NAN),
8820            Scalar::Int64(0),
8821            Scalar::Bool(false),
8822        ];
8823        for v in &vals {
8824            assert_eq!(v.is_na(), v.is_missing());
8825        }
8826    }
8827
8828    #[test]
8829    fn coalesce_picks_first_non_missing() {
8830        let null = Scalar::Null(NullKind::Null);
8831        let fill = Scalar::Int64(99);
8832        assert_eq!(null.coalesce(&fill), fill);
8833        assert_eq!(fill.coalesce(&null), fill);
8834    }
8835
8836    // ── Missingness utilities ──────────────────────────────────────────
8837
8838    #[test]
8839    fn isna_notna_complement() {
8840        let vals = vec![
8841            Scalar::Int64(1),
8842            Scalar::Null(NullKind::Null),
8843            Scalar::Float64(f64::NAN),
8844            Scalar::Float64(3.0),
8845        ];
8846        let na = super::isna(&vals);
8847        let not = super::notna(&vals);
8848        assert_eq!(na, vec![false, true, true, false]);
8849        for (a, b) in na.iter().zip(not.iter()) {
8850            assert_ne!(a, b);
8851        }
8852    }
8853
8854    #[test]
8855    fn count_na_counts_missing() {
8856        let vals = vec![
8857            Scalar::Int64(1),
8858            Scalar::Null(NullKind::Null),
8859            Scalar::Float64(f64::NAN),
8860        ];
8861        assert_eq!(super::count_na(&vals), 2);
8862    }
8863
8864    #[test]
8865    fn fill_na_replaces_missing() {
8866        let vals = vec![
8867            Scalar::Int64(1),
8868            Scalar::Null(NullKind::Null),
8869            Scalar::Float64(f64::NAN),
8870            Scalar::Int64(4),
8871        ];
8872        let filled = super::fill_na(&vals, &Scalar::Int64(0));
8873        assert_eq!(filled[0], Scalar::Int64(1));
8874        assert_eq!(filled[1], Scalar::Int64(0));
8875        assert_eq!(filled[2], Scalar::Int64(0));
8876        assert_eq!(filled[3], Scalar::Int64(4));
8877    }
8878
8879    #[test]
8880    fn dropna_removes_missing() {
8881        let vals = vec![
8882            Scalar::Int64(1),
8883            Scalar::Null(NullKind::Null),
8884            Scalar::Int64(3),
8885            Scalar::Float64(f64::NAN),
8886        ];
8887        let kept = super::dropna(&vals);
8888        assert_eq!(kept.len(), 2);
8889        assert_eq!(kept[0], Scalar::Int64(1));
8890        assert_eq!(kept[1], Scalar::Int64(3));
8891    }
8892
8893    #[test]
8894    fn null_helpers_match_scalar_oracle_imt0c() {
8895        // Differential vs independent scalar null-helper oracle
8896        // (br-frankenpandas-imt0c). Seeded LCG, no mocks.
8897        fn next(seed: &mut u64) -> u64 {
8898            *seed = seed
8899                .wrapping_mul(3202034522624059733)
8900                .wrapping_add(4354685564936845319);
8901            *seed
8902        }
8903
8904        fn assert_null_helpers(case: usize, values: &[Scalar], fill: &Scalar) {
8905            let expected_missing = values.iter().filter(|value| value.is_missing()).count();
8906            let expected_dropped = values
8907                .iter()
8908                .filter(|value| !value.is_missing())
8909                .cloned()
8910                .collect::<Vec<_>>();
8911            let expected_filled = values
8912                .iter()
8913                .map(|value| {
8914                    if value.is_missing() {
8915                        fill.clone()
8916                    } else {
8917                        value.clone()
8918                    }
8919                })
8920                .collect::<Vec<_>>();
8921
8922            assert_eq!(
8923                super::count_na(values),
8924                expected_missing,
8925                "case={case}: count_na mismatch for {values:?}"
8926            );
8927
8928            let dropped = super::dropna(values);
8929            assert_eq!(
8930                dropped.len(),
8931                expected_dropped.len(),
8932                "case={case}: dropna length mismatch for {values:?}"
8933            );
8934            for (pos, (actual, expected)) in dropped.iter().zip(expected_dropped.iter()).enumerate()
8935            {
8936                assert!(
8937                    actual.semantic_eq(expected),
8938                    "case={case} pos={pos}: dropna expected {expected:?}, got {actual:?}"
8939                );
8940            }
8941
8942            let filled = super::fill_na(values, fill);
8943            assert_eq!(
8944                filled.len(),
8945                expected_filled.len(),
8946                "case={case}: fill_na length mismatch for {values:?}"
8947            );
8948            for (pos, (actual, expected)) in filled.iter().zip(expected_filled.iter()).enumerate() {
8949                assert!(
8950                    actual.semantic_eq(expected),
8951                    "case={case} pos={pos}: fill_na expected {expected:?}, got {actual:?}"
8952                );
8953            }
8954        }
8955
8956        let all_missing = [
8957            Scalar::Null(NullKind::Null),
8958            Scalar::Null(NullKind::NaN),
8959            Scalar::Float64(f64::NAN),
8960            Scalar::Timedelta64(i64::MIN),
8961        ];
8962        assert_null_helpers(usize::MAX, &all_missing, &Scalar::Utf8("filled".into()));
8963
8964        let mut seed = 0xc011_a7ed_0b5e_1a55_u64;
8965        for case in 0..260 {
8966            let len = (next(&mut seed) % 83 + 1) as usize;
8967            let mut values = Vec::with_capacity(len);
8968            for pos in 0..len {
8969                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
8970                values.push(match next(&mut seed) % 11 {
8971                    0 => Scalar::Null(NullKind::Null),
8972                    1 => Scalar::Null(NullKind::NaN),
8973                    2 => Scalar::Float64(f64::NAN),
8974                    3 => Scalar::Timedelta64(i64::MIN),
8975                    4 => Scalar::Bool(raw & 1 == 0),
8976                    5 => Scalar::Int64(raw),
8977                    6 => Scalar::Float64(raw as f64 / 37.0),
8978                    7 => Scalar::Float64(if raw & 1 == 0 { 0.0 } else { -0.0 }),
8979                    8 => Scalar::Utf8(format!("null_helper_{case}_{pos}")),
8980                    9 => Scalar::Utf8(String::new()),
8981                    _ => Scalar::Timedelta64(raw),
8982                });
8983            }
8984
8985            let fill = match case % 5 {
8986                0 => Scalar::Bool(true),
8987                1 => Scalar::Int64(-777),
8988                2 => Scalar::Float64(12.5),
8989                3 => Scalar::Utf8("filled".into()),
8990                _ => Scalar::Timedelta64(123_456),
8991            };
8992            assert_null_helpers(case, &values, &fill);
8993        }
8994    }
8995
8996    // ── Nanops ─────────────────────────────────────────────────────────
8997
8998    #[test]
8999    fn nansum_skips_nulls() {
9000        let vals = vec![
9001            Scalar::Float64(1.0),
9002            Scalar::Null(NullKind::Null),
9003            Scalar::Float64(2.0),
9004            Scalar::Float64(f64::NAN),
9005            Scalar::Int64(7),
9006        ];
9007        assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
9008    }
9009
9010    #[test]
9011    fn nansum_empty_returns_zero() {
9012        assert_eq!(super::nansum(&[]), Scalar::Float64(0.0));
9013    }
9014
9015    #[test]
9016    fn nansum_nanmean_match_numeric_and_timedelta_oracle_1xmi7() {
9017        // Differential vs independent sum/mean oracles
9018        // (br-frankenpandas-1xmi7). Seeded LCG, no mocks.
9019        fn next(seed: &mut u64) -> u64 {
9020            *seed = seed
9021                .wrapping_mul(6364136223846793005)
9022                .wrapping_add(1442695040888963407);
9023            *seed
9024        }
9025
9026        fn expected_numeric(values: &[Scalar]) -> (Scalar, Scalar) {
9027            let mut sum = 0.0;
9028            let mut count = 0usize;
9029            for value in values {
9030                if value.is_missing() {
9031                    continue;
9032                }
9033                if let Ok(value) = value.to_f64() {
9034                    sum += value;
9035                    count += 1;
9036                }
9037            }
9038            let mean = if count == 0 {
9039                Scalar::Null(NullKind::NaN)
9040            } else {
9041                Scalar::Float64(sum / count as f64)
9042            };
9043            (Scalar::Float64(sum), mean)
9044        }
9045
9046        fn expected_timedelta(values: &[Scalar]) -> (Scalar, Scalar) {
9047            let mut sum = 0_i128;
9048            let mut count = 0_i128;
9049            for value in values {
9050                if let Scalar::Timedelta64(ns) = value
9051                    && !value.is_missing()
9052                {
9053                    sum += i128::from(*ns);
9054                    count += 1;
9055                }
9056            }
9057            if count == 0 {
9058                return (Scalar::Timedelta64(0), Scalar::Timedelta64(Timedelta::NAT));
9059            }
9060            // br-frankenpandas-opz27: this reference oracle used to clamp, which
9061            // is the exact behaviour the production path was just fixed away
9062            // from. Keeping the clamp here would leave the oracle blessing a
9063            // contradicted rule (it only ever agreed because these inputs do
9064            // not overflow). Mirror the representable-range contract instead.
9065            (
9066                super::timedelta_ns_to_scalar(sum),
9067                super::timedelta_ns_to_scalar(sum / count),
9068            )
9069        }
9070
9071        fn assert_sum_mean(
9072            case: usize,
9073            family: &str,
9074            values: &[Scalar],
9075            expected_sum: Scalar,
9076            expected_mean: Scalar,
9077        ) {
9078            let actual_sum = super::nansum(values);
9079            let actual_mean = super::nanmean(values);
9080            assert!(
9081                actual_sum.semantic_eq(&expected_sum),
9082                "case={case} family={family}: expected sum {expected_sum:?}, got {actual_sum:?} for {values:?}"
9083            );
9084            assert!(
9085                actual_mean.semantic_eq(&expected_mean),
9086                "case={case} family={family}: expected mean {expected_mean:?}, got {actual_mean:?} for {values:?}"
9087            );
9088        }
9089
9090        let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
9091        let (sum, mean) = expected_numeric(&all_missing);
9092        assert_sum_mean(usize::MAX, "numeric_all_missing", &all_missing, sum, mean);
9093
9094        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
9095        let (sum, mean) = expected_timedelta(&td_all_missing);
9096        assert_sum_mean(
9097            usize::MAX - 1,
9098            "timedelta_all_missing",
9099            &td_all_missing,
9100            sum,
9101            mean,
9102        );
9103
9104        let mut seed = 0x511d_ed5a_7a11_1a55_u64;
9105        for case in 0..260 {
9106            let len = (next(&mut seed) % 89 + 1) as usize;
9107
9108            let mut numeric = Vec::with_capacity(len);
9109            numeric.push(Scalar::Int64(case as i64 - 130));
9110            for _ in 1..len {
9111                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
9112                numeric.push(match next(&mut seed) % 8 {
9113                    0 => Scalar::Null(NullKind::Null),
9114                    1 => Scalar::Null(NullKind::NaN),
9115                    2 => Scalar::Float64(f64::NAN),
9116                    3 => Scalar::Bool(raw & 1 == 0),
9117                    4 => Scalar::Int64(raw % 257),
9118                    5 => Scalar::Float64(raw as f64 / 67.0),
9119                    6 => Scalar::Float64(0.0),
9120                    _ => Scalar::Float64(-0.0),
9121                });
9122            }
9123            let (sum, mean) = expected_numeric(&numeric);
9124            assert_sum_mean(case, "numeric", &numeric, sum, mean);
9125
9126            let mut timedeltas = Vec::with_capacity(len);
9127            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
9128            for _ in 1..len {
9129                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
9130                timedeltas.push(match next(&mut seed) % 7 {
9131                    0 => Scalar::Null(NullKind::Null),
9132                    1 => Scalar::Timedelta64(i64::MIN),
9133                    _ => Scalar::Timedelta64(raw),
9134                });
9135            }
9136            let (sum, mean) = expected_timedelta(&timedeltas);
9137            assert_sum_mean(case, "timedelta", &timedeltas, sum, mean);
9138        }
9139    }
9140
9141    #[test]
9142    fn nannunique_merges_negative_zero_and_zero() {
9143        let vals = vec![
9144            Scalar::Float64(-0.0),
9145            Scalar::Float64(0.0),
9146            Scalar::Float64(1.0),
9147        ];
9148        assert_eq!(super::nannunique(&vals), Scalar::Int64(2));
9149    }
9150
9151    #[test]
9152    fn nannunique_matches_scalar_bucket_oracle_elvbg() {
9153        // Differential vs independent scalar unique-bucket oracle
9154        // (br-frankenpandas-elvbg). Seeded LCG, no mocks.
9155        fn next(seed: &mut u64) -> u64 {
9156            *seed = seed
9157                .wrapping_mul(2862933555777941757)
9158                .wrapping_add(3037000493);
9159            *seed
9160        }
9161
9162        fn same_bucket(left: &Scalar, right: &Scalar) -> bool {
9163            match (left, right) {
9164                (Scalar::Float64(left), Scalar::Float64(right)) => {
9165                    let left = if *left == 0.0 { 0.0 } else { *left };
9166                    let right = if *right == 0.0 { 0.0 } else { *right };
9167                    left.to_bits() == right.to_bits()
9168                }
9169                _ => left == right,
9170            }
9171        }
9172
9173        fn expected_nunique(values: &[Scalar]) -> i64 {
9174            let mut seen = Vec::<Scalar>::new();
9175            for value in values {
9176                if value.is_missing() {
9177                    continue;
9178                }
9179                if !seen.iter().any(|existing| same_bucket(existing, value)) {
9180                    seen.push(value.clone());
9181                }
9182            }
9183            seen.len() as i64
9184        }
9185
9186        fn assert_nannunique(case: usize, values: &[Scalar]) {
9187            assert_eq!(
9188                super::nannunique(values),
9189                Scalar::Int64(expected_nunique(values)),
9190                "case={case}: nannunique mismatch for {values:?}"
9191            );
9192        }
9193
9194        assert_nannunique(
9195            usize::MAX,
9196            &[
9197                Scalar::Float64(-0.0),
9198                Scalar::Float64(0.0),
9199                Scalar::Float64(f64::NAN),
9200                Scalar::Null(NullKind::Null),
9201                Scalar::Timedelta64(i64::MIN),
9202            ],
9203        );
9204
9205        let mut seed = 0x0e1b_60d0_b5e7_u64;
9206        for case in 0..320 {
9207            let len = (next(&mut seed) % 97 + 1) as usize;
9208            let mut values = Vec::with_capacity(len);
9209            for pos in 0..len {
9210                let raw = (next(&mut seed) % 1_001) as i64 - 500;
9211                values.push(match next(&mut seed) % 11 {
9212                    0 => Scalar::Null(NullKind::Null),
9213                    1 => Scalar::Null(NullKind::NaN),
9214                    2 => Scalar::Float64(f64::NAN),
9215                    3 => Scalar::Bool(raw & 1 == 0),
9216                    4 => Scalar::Int64(raw % 37),
9217                    5 => Scalar::Float64(raw as f64 / 19.0),
9218                    6 => Scalar::Float64(0.0),
9219                    7 => Scalar::Float64(-0.0),
9220                    8 => Scalar::Utf8(format!("uniq_{}", pos % 13)),
9221                    9 => Scalar::Utf8(String::new()),
9222                    _ => Scalar::Timedelta64(raw % 41),
9223                });
9224            }
9225            assert_nannunique(case, &values);
9226        }
9227    }
9228
9229    #[test]
9230    fn nanmean_basic() {
9231        let vals = vec![
9232            Scalar::Float64(2.0),
9233            Scalar::Null(NullKind::Null),
9234            Scalar::Float64(4.0),
9235        ];
9236        assert_eq!(super::nanmean(&vals), Scalar::Float64(3.0));
9237    }
9238
9239    #[test]
9240    fn nanmean_all_null_returns_nan() {
9241        let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
9242        assert!(super::nanmean(&vals).is_missing());
9243    }
9244
9245    #[test]
9246    fn nansum_nanmean_timedelta64_preserves_dtype_620mj() {
9247        // Per br-frankenpandas-620mj: pandas td_series.sum()/mean() return
9248        // Timedelta64, not Float64(0.0). Was silently zero before because
9249        // collect_finite drops Timedelta64 (to_f64 errors).
9250        let one_hour = 3_600 * 1_000_000_000_i64;
9251        let vals = vec![
9252            Scalar::Timedelta64(one_hour),
9253            Scalar::Timedelta64(2 * one_hour),
9254            Scalar::Timedelta64(3 * one_hour),
9255        ];
9256        assert_eq!(super::nansum(&vals), Scalar::Timedelta64(6 * one_hour));
9257        assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
9258    }
9259
9260    #[test]
9261    fn nansum_nanmean_timedelta64_skips_nat_620mj() {
9262        let one_hour = 3_600 * 1_000_000_000_i64;
9263        let vals = vec![
9264            Scalar::Timedelta64(Timedelta::NAT),
9265            Scalar::Timedelta64(one_hour),
9266            Scalar::Timedelta64(3 * one_hour),
9267            Scalar::Timedelta64(Timedelta::NAT),
9268        ];
9269        // NAT is missing → skipped. Sum: 1h+3h=4h; mean: 2h.
9270        assert_eq!(super::nansum(&vals), Scalar::Timedelta64(4 * one_hour));
9271        assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
9272    }
9273
9274    /// br-frankenpandas-opz27: the Timedelta reduction surface used to narrow
9275    /// its exact i128 accumulator with `clamp(i64::MIN, i64::MAX)`, which
9276    /// fabricated a finite Timedelta.max on positive overflow. Live pandas
9277    /// 2.2.3 raises `ValueError: overflow in timedelta operation` here; FP
9278    /// surfaces NaT per the lgyy8 convention. A clamping implementation
9279    /// returns `Timedelta64(i64::MAX)` and fails this.
9280    #[test]
9281    fn nansum_timedelta_overflow_is_nat_not_fabricated_max_opz27() {
9282        let vals = vec![Scalar::Timedelta64(i64::MAX), Scalar::Timedelta64(i64::MAX)];
9283        let got = super::nansum(&vals);
9284        assert!(
9285            got.is_missing(),
9286            "overflowing sum must be missing, got {got:?}"
9287        );
9288        assert_eq!(got, Scalar::Timedelta64(Timedelta::NAT));
9289        assert_ne!(got, Scalar::Timedelta64(i64::MAX));
9290    }
9291
9292    /// The negative direction used to reach NaT only *by accident*, because
9293    /// `Timedelta::NAT == i64::MIN` is exactly the clamp's lower bound — and
9294    /// that bound is off by one against the true minimum (`i64::MIN + 1`).
9295    /// Pin both the sentinel and the boundary so the accident becomes a rule.
9296    #[test]
9297    fn nansum_timedelta_negative_overflow_is_nat_opz27() {
9298        let min_repr = i64::MIN + 1; // Timedelta.min; i64::MIN is the NaT sentinel
9299        let vals = vec![Scalar::Timedelta64(min_repr), Scalar::Timedelta64(min_repr)];
9300        assert_eq!(super::nansum(&vals), Scalar::Timedelta64(Timedelta::NAT));
9301
9302        // Exactly the most-negative representable total stays a real value and
9303        // must NOT collapse into the sentinel one nanosecond above it.
9304        let exact = vec![Scalar::Timedelta64(min_repr + 1), Scalar::Timedelta64(-1)];
9305        let got = super::nansum(&exact);
9306        assert_eq!(got, Scalar::Timedelta64(min_repr));
9307        assert!(!got.is_missing(), "Timedelta.min is representable, not NaT");
9308    }
9309
9310    /// pandas 2.2.3: `Series([Timedelta.min, Timedelta.max]).max() - .min()`
9311    /// raises OverflowError. FP used `saturating_sub`, fabricating
9312    /// Timedelta.max as a plausible range.
9313    #[test]
9314    fn nanptp_timedelta_overflow_is_nat_opz27() {
9315        let vals = vec![
9316            Scalar::Timedelta64(i64::MIN + 1),
9317            Scalar::Timedelta64(i64::MAX),
9318        ];
9319        let got = super::nanptp(&vals);
9320        assert!(
9321            got.is_missing(),
9322            "unrepresentable range must be NaT, got {got:?}"
9323        );
9324        assert_ne!(got, Scalar::Timedelta64(i64::MAX));
9325
9326        // A representable range is still exact to the nanosecond (the reason
9327        // this path avoids f64 at all).
9328        let hour = 3_600 * 1_000_000_000_i64;
9329        let ok = vec![Scalar::Timedelta64(hour), Scalar::Timedelta64(4 * hour)];
9330        assert_eq!(super::nanptp(&ok), Scalar::Timedelta64(3 * hour));
9331    }
9332
9333    /// The load-bearing cumsum case: accumulation stays exact in i128, so only
9334    /// the *unrepresentable* index goes NaT and a later index that returns to
9335    /// range emits its true value. A clamping implementation pins `running` at
9336    /// i64::MAX and can never produce the final value, so it fails this test.
9337    #[test]
9338    fn nancumsum_timedelta_overflow_recovers_exact_value_opz27() {
9339        let vals = vec![
9340            Scalar::Timedelta64(i64::MAX),
9341            Scalar::Timedelta64(i64::MAX), // true total 2*i64::MAX: unrepresentable
9342            Scalar::Timedelta64(i64::MIN + 1), // back in range: total == i64::MAX
9343        ];
9344        let out = super::nancumsum(&vals);
9345        assert_eq!(out.len(), 3);
9346        assert_eq!(out[0], Scalar::Timedelta64(i64::MAX));
9347        assert!(
9348            out[1].is_missing(),
9349            "overflowed index must be NaT, got {:?}",
9350            out[1]
9351        );
9352        assert_eq!(
9353            out[2],
9354            Scalar::Timedelta64(i64::MAX),
9355            "exact i128 accumulation must recover; a clamped running sum cannot"
9356        );
9357    }
9358
9359    /// Non-overflowing cumsum is unchanged bit-for-bit, and input NaT still
9360    /// passes through without advancing the running total.
9361    #[test]
9362    fn nancumsum_timedelta_exact_path_unchanged_opz27() {
9363        let sec = 1_000_000_000_i64;
9364        let vals = vec![
9365            Scalar::Timedelta64(sec),
9366            Scalar::Timedelta64(Timedelta::NAT),
9367            Scalar::Timedelta64(2 * sec),
9368        ];
9369        let out = super::nancumsum(&vals);
9370        assert_eq!(out[0], Scalar::Timedelta64(sec));
9371        assert!(out[1].is_missing());
9372        assert_eq!(out[2], Scalar::Timedelta64(3 * sec));
9373    }
9374
9375    const DAY_NS: i64 = 86_400 * 1_000_000_000;
9376    /// 2020-01-01T00:00:00Z in epoch nanoseconds.
9377    const DT_2020: i64 = 1_577_836_800_000_000_000;
9378
9379    /// br-frankenpandas-axhhk: every one of these returned `Null(NaN)` (or
9380    /// `None`) before the Datetime64 arms existed, because `Datetime64::to_f64()`
9381    /// errors and each reduction fell through to the f64 catch-all. Expectations
9382    /// are the live pandas 2.2.3 answers for
9383    /// `Series([2020-01-01, +60d, +31d])`:
9384    ///   min 2020-01-01 · max 2020-03-01 · ptp Timedelta 60 days
9385    ///   argmin 0 · argmax 1 · cummax/cummin Timestamps
9386    #[test]
9387    fn datetime64_ordering_reductions_match_pandas_axhhk() {
9388        let d = Scalar::Datetime64;
9389        let vals = vec![
9390            d(DT_2020),
9391            d(DT_2020 + 60 * DAY_NS),
9392            d(DT_2020 + 31 * DAY_NS),
9393        ];
9394
9395        assert_eq!(super::nanmin(&vals), d(DT_2020));
9396        assert_eq!(super::nanmax(&vals), d(DT_2020 + 60 * DAY_NS));
9397        assert_eq!(super::nanargmin(&vals), Some(0));
9398        assert_eq!(super::nanargmax(&vals), Some(1));
9399
9400        // ptp of two INSTANTS is a DURATION: Timedelta64, not Datetime64.
9401        let span = super::nanptp(&vals);
9402        assert_eq!(span, Scalar::Timedelta64(60 * DAY_NS));
9403        assert_eq!(span.dtype(), DType::Timedelta64);
9404
9405        assert_eq!(
9406            super::nancummax(&vals),
9407            vec![
9408                d(DT_2020),
9409                d(DT_2020 + 60 * DAY_NS),
9410                d(DT_2020 + 60 * DAY_NS)
9411            ]
9412        );
9413        assert_eq!(
9414            super::nancummin(&vals),
9415            vec![d(DT_2020), d(DT_2020), d(DT_2020)]
9416        );
9417    }
9418
9419    /// The size-dependence is the part that made this bug quiet, so pin it
9420    /// explicitly rather than only asserting the headline. A ONE-element
9421    /// datetime slice was always correct (the `(None, _)` arm seeds `min`
9422    /// before any comparison runs); TWO elements hit the catch-all and
9423    /// returned NaN. A regression that drops the Datetime64 arm would still
9424    /// pass a single-element test.
9425    #[test]
9426    fn datetime64_min_max_size_dependence_pinned_axhhk() {
9427        let d = Scalar::Datetime64;
9428        let one = vec![d(DT_2020)];
9429        assert_eq!(super::nanmin(&one), d(DT_2020));
9430        assert_eq!(super::nanmax(&one), d(DT_2020));
9431
9432        let two = vec![d(DT_2020 + DAY_NS), d(DT_2020)];
9433        let got_min = super::nanmin(&two);
9434        assert!(
9435            !got_min.is_missing(),
9436            "2-element datetime min must not be missing, got {got_min:?}"
9437        );
9438        assert_eq!(got_min, d(DT_2020));
9439        assert_eq!(super::nanmax(&two), d(DT_2020 + DAY_NS));
9440    }
9441
9442    /// NaT still skips, and a datetime span too large for i64 surfaces NaT via
9443    /// the shared opz27 narrowing rather than a fabricated extreme.
9444    #[test]
9445    fn datetime64_reductions_skip_nat_and_guard_span_overflow_axhhk() {
9446        let d = Scalar::Datetime64;
9447        let with_nat = vec![
9448            d(Timestamp::NAT),
9449            d(DT_2020 + 31 * DAY_NS),
9450            d(DT_2020),
9451            d(Timestamp::NAT),
9452        ];
9453        assert_eq!(super::nanmin(&with_nat), d(DT_2020));
9454        assert_eq!(super::nanmax(&with_nat), d(DT_2020 + 31 * DAY_NS));
9455        assert_eq!(super::nanptp(&with_nat), Scalar::Timedelta64(31 * DAY_NS));
9456        // argmin/argmax report positions in the ORIGINAL slice, NaT skipped.
9457        assert_eq!(super::nanargmin(&with_nat), Some(2));
9458        assert_eq!(super::nanargmax(&with_nat), Some(1));
9459
9460        // Span exceeding i64 ns: NaT, never a fabricated Timedelta.max.
9461        let huge = vec![d(i64::MIN + 1), d(i64::MAX)];
9462        let span = super::nanptp(&huge);
9463        assert!(span.is_missing(), "unrepresentable span must be NaT");
9464        assert_ne!(span, Scalar::Timedelta64(i64::MAX));
9465    }
9466
9467    /// br-frankenpandas-adv58: mean/median/quantile returned `Null(NaN)` for
9468    /// datetime input. Expectations are the live pandas 2.2.3 answers for
9469    /// `Series([2020-01-01, +60d, +31d])`, which at day granularity pandas
9470    /// computes exactly:
9471    ///   mean 2020-01-31T08:00 · median 2020-02-01 · q0.5 2020-02-01
9472    ///   q0.25 2020-01-16T12:00
9473    #[test]
9474    fn datetime64_averaging_reductions_match_pandas_adv58() {
9475        let d = Scalar::Datetime64;
9476        let vals = vec![
9477            d(DT_2020),
9478            d(DT_2020 + 60 * DAY_NS),
9479            d(DT_2020 + 31 * DAY_NS),
9480        ];
9481        // 1580457600e9 / 1580515200e9 / 1579176000e9, straight from the probe.
9482        assert_eq!(super::nanmean(&vals), d(1_580_457_600_000_000_000));
9483        assert_eq!(super::nanmedian(&vals), d(1_580_515_200_000_000_000));
9484        assert_eq!(super::nanquantile(&vals, 0.5), d(1_580_515_200_000_000_000));
9485        assert_eq!(
9486            super::nanquantile(&vals, 0.25),
9487            d(1_579_176_000_000_000_000)
9488        );
9489    }
9490
9491    /// The even-count rounding rule, probed at 1 ns granularity where pandas is
9492    /// exact. It is TRUNCATION TOWARD ZERO — plain Rust integer division.
9493    /// `floor` would give -1 for [-1,0]; ties-to-even would give 2 for [1,2].
9494    /// Both are refuted by these cases, so this test discriminates against the
9495    /// two rounding rules a reimplementation is most likely to pick.
9496    #[test]
9497    fn datetime64_mean_median_round_toward_zero_adv58() {
9498        let d = Scalar::Datetime64;
9499        for (a, b, want) in [
9500            (0_i64, 1_i64, 0_i64),
9501            (0, 3, 1),
9502            (1, 2, 1),
9503            (-1, 0, 0),
9504            (-3, 0, -1),
9505            (-2, -1, -1),
9506            (0, 2, 1),
9507            (-2, 0, -1),
9508        ] {
9509            let vals = vec![d(a), d(b)];
9510            assert_eq!(
9511                super::nanmean(&vals),
9512                d(want),
9513                "mean of [{a}, {b}] should be {want}"
9514            );
9515            assert_eq!(
9516                super::nanmedian(&vals),
9517                d(want),
9518                "median of [{a}, {b}] should be {want}"
9519            );
9520        }
9521    }
9522
9523    /// NaT is skipped, and an all-NaT datetime input stays in the Datetime
9524    /// family rather than degrading to a numeric NaN.
9525    #[test]
9526    fn datetime64_averaging_skips_nat_adv58() {
9527        let d = Scalar::Datetime64;
9528        let vals = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
9529        // pandas: mean == median == 2020-01-02, count 2.
9530        assert_eq!(super::nanmean(&vals), d(DT_2020 + DAY_NS));
9531        assert_eq!(super::nanmedian(&vals), d(DT_2020 + DAY_NS));
9532
9533        let all_nat = vec![d(Timestamp::NAT), d(Timestamp::NAT)];
9534        let got = super::nanmean(&all_nat);
9535        assert!(
9536            got.is_missing(),
9537            "all-NaT mean must be missing, got {got:?}"
9538        );
9539        assert_eq!(
9540            got.dtype(),
9541            DType::datetime64_naive(),
9542            "must stay Datetime64"
9543        );
9544    }
9545
9546    /// FP is EXACT here and pandas is not: pandas routes datetime
9547    /// mean/median/quantile through f64, so at 2020-era magnitudes (~1.58e18,
9548    /// f64 ULP 256 ns) it snaps to a 256 ns grid — it returns B+0 for the mean
9549    /// of the CONSTANT series [B+1, B+1], and for an odd-count median it can
9550    /// return a Timestamp that is not even one of the inputs. FP keeps the
9551    /// exact i128 treatment its Timedelta sibling already had. DISC-019.
9552    #[test]
9553    fn datetime64_averaging_is_exact_where_pandas_snaps_adv58() {
9554        let d = Scalar::Datetime64;
9555
9556        // Constant series: the answer is unambiguous; pandas still loses it.
9557        let constant = vec![d(DT_2020 + 1), d(DT_2020 + 1)];
9558        assert_eq!(super::nanmean(&constant), d(DT_2020 + 1));
9559        assert_eq!(super::nanmedian(&constant), d(DT_2020 + 1));
9560
9561        // Odd-count median is a SELECTION: the result must be an input value.
9562        let odd = vec![d(DT_2020), d(DT_2020 + 129), d(DT_2020 + 258)];
9563        let med = super::nanmedian(&odd);
9564        assert_eq!(med, d(DT_2020 + 129));
9565        assert!(
9566            odd.contains(&med),
9567            "odd-count median must be one of the inputs; pandas returns B+256, which is not"
9568        );
9569    }
9570
9571    /// br-frankenpandas-40ujm: datetime std returned `Null(NaN)`; pandas 2.2.3
9572    /// returns a Timedelta. Every value below is the probed oracle answer for
9573    /// `Series([2020-01-01, +60d, +31d])`, in raw ns:
9574    ///   ddof=1 (default) 2592479955563784   ddof=0 2116751019841492
9575    ///   ddof=2           3666320313338702   ddof=3 NaT (n - ddof <= 0)
9576    /// pandas truncates the sqrt toward zero (ddof=0 is 2116751019841492.8).
9577    #[test]
9578    fn datetime64_std_matches_pandas_ddof_variants_40ujm() {
9579        let d = Scalar::Datetime64;
9580        let vals = vec![
9581            d(DT_2020),
9582            d(DT_2020 + 60 * DAY_NS),
9583            d(DT_2020 + 31 * DAY_NS),
9584        ];
9585        // Dispersion of instants is a DURATION: Timedelta64, not Datetime64.
9586        let s1 = super::nanstd(&vals, 1);
9587        assert_eq!(s1, Scalar::Timedelta64(2_592_479_955_563_784));
9588        assert_eq!(s1.dtype(), DType::Timedelta64);
9589        assert_eq!(
9590            super::nanstd(&vals, 0),
9591            Scalar::Timedelta64(2_116_751_019_841_492)
9592        );
9593        assert_eq!(
9594            super::nanstd(&vals, 2),
9595            Scalar::Timedelta64(3_666_320_313_338_702)
9596        );
9597        // n - ddof <= 0 => NaT, matching pandas.
9598        assert!(super::nanstd(&vals, 3).is_missing());
9599    }
9600
9601    /// pandas returns the SAME std for a Datetime64 series and a Timedelta64
9602    /// series built from identical ns. That equivalence is the whole basis for
9603    /// routing both families through one computation, so pin it directly.
9604    #[test]
9605    fn datetime64_std_equals_timedelta64_std_on_same_ns_40ujm() {
9606        let offsets = [0_i64, 60 * DAY_NS, 31 * DAY_NS];
9607        let dt: Vec<Scalar> = offsets.iter().map(|o| Scalar::Datetime64(*o)).collect();
9608        let td: Vec<Scalar> = offsets.iter().map(|o| Scalar::Timedelta64(*o)).collect();
9609        assert_eq!(super::nanstd(&dt, 1), super::nanstd(&td, 1));
9610        assert_eq!(
9611            super::nanstd(&dt, 1),
9612            Scalar::Timedelta64(2_592_479_955_563_784)
9613        );
9614    }
9615
9616    /// NaT skips (a 3-element series with one NaT must equal the 2-element
9617    /// series without it), a single element gives NaT at the default ddof, and
9618    /// var/sem stay REFUSED for datetimes because pandas raises on them.
9619    #[test]
9620    fn datetime64_std_skips_nat_and_var_sem_stay_unsupported_40ujm() {
9621        let d = Scalar::Datetime64;
9622        let with_nat = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
9623        let without = vec![d(DT_2020), d(DT_2020 + 2 * DAY_NS)];
9624        // pandas: both are Timedelta 1 days 09:56:28.051789035.
9625        assert_eq!(super::nanstd(&with_nat, 1), super::nanstd(&without, 1));
9626        assert_eq!(
9627            super::nanstd(&with_nat, 1),
9628            Scalar::Timedelta64(122_188_051_789_035)
9629        );
9630
9631        // n=1 with ddof=1 -> NaT, as pandas returns.
9632        assert!(super::nanstd(&[d(DT_2020)], 1).is_missing());
9633        assert!(super::nanstd(&[d(Timestamp::NAT)], 1).is_missing());
9634
9635        // pandas RAISES TypeError for datetime64 var and sem. FP must not
9636        // invent a value: these stay on the Timedelta-only gate and report
9637        // missing. A regression that widened them would return a number here.
9638        let vals = vec![d(DT_2020), d(DT_2020 + 60 * DAY_NS)];
9639        assert!(super::nanvar(&vals, 1).is_missing());
9640        assert!(super::nansem(&vals, 1).is_missing());
9641    }
9642
9643    /// br-frankenpandas-qoabs: Period is the THIRD dtype whose `to_f64()`
9644    /// errors, so min/max fell into the f64 catch-all and returned
9645    /// `Null(NaN)`. pandas 2.2.3 on `Series([2020-01, 2020-03, 2020-02], M)`
9646    /// gives min 2020-01 and max 2020-03; ordinals are 600/601/602.
9647    #[test]
9648    fn period_min_max_match_pandas_qoabs() {
9649        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
9650        let vals = vec![p(600), p(602), p(601)];
9651        assert_eq!(super::nanmin(&vals), p(600));
9652        assert_eq!(super::nanmax(&vals), p(602));
9653
9654        // Size-dependence, exactly as in axhhk: ONE element always worked via
9655        // the `(None, _)` seed, so a test with a single value would pass even
9656        // with no Period arm at all. Assert both sizes.
9657        assert_eq!(super::nanmin(&[p(600)]), p(600));
9658        let two = vec![p(602), p(600)];
9659        assert!(!super::nanmin(&two).is_missing());
9660        assert_eq!(super::nanmin(&two), p(600));
9661        assert_eq!(super::nanmax(&two), p(602));
9662    }
9663
9664    /// A Period whose ordinal is the NaT sentinel is missing and skipped, and
9665    /// an all-missing Period input reports missing rather than a value.
9666    #[test]
9667    fn period_min_max_skip_nat_qoabs() {
9668        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
9669        let nat = Scalar::Period(Period::new(i64::MIN, PeriodFreq::Monthly));
9670        let vals = vec![nat.clone(), p(602), p(600), nat.clone()];
9671        assert_eq!(super::nanmin(&vals), p(600));
9672        assert_eq!(super::nanmax(&vals), p(602));
9673        assert!(super::nanmin(&[nat.clone(), nat]).is_missing());
9674    }
9675
9676    /// MIXED FREQ must not be ordered. pandas refuses it outright
9677    /// (`IncompatibleFrequency: Input has different freq=D from Period(freq=M)`),
9678    /// so FP reports missing rather than inventing an order. This is the test
9679    /// that discriminates: an implementation comparing raw ordinals would
9680    /// happily return a value here, because monthly 2020-01 is ordinal 600
9681    /// while daily 2020-01-05 is 18267 — it would call the daily period later.
9682    #[test]
9683    fn period_mixed_freq_is_not_ordered_qoabs() {
9684        let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
9685        let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
9686        let vals = vec![month.clone(), day.clone()];
9687        let got_min = super::nanmin(&vals);
9688        assert!(
9689            got_min.is_missing(),
9690            "mixed-freq Period min must not be ordered, got {got_min:?}"
9691        );
9692        assert_ne!(
9693            got_min, day,
9694            "must not rank the daily period by raw ordinal"
9695        );
9696        assert!(super::nanmax(&vals).is_missing());
9697    }
9698
9699    /// br-frankenpandas-d7zjp: the rest of the Period reduction family, which
9700    /// qoabs deferred because a `fn(i64) -> Scalar` constructor cannot carry a
9701    /// freq. Expectations are the probed pandas 2.2.3 answers for
9702    /// `Series([2020-01, 2020-03, 2020-02], freq=M)` (ordinals 600/601/602):
9703    ///   median 2020-02 · quantile(0.5) 2020-02 · idxmin 0 · idxmax 1
9704    ///   cummax ends 2020-03 · cummin ends 2020-01
9705    #[test]
9706    fn period_full_reduction_family_matches_pandas_d7zjp() {
9707        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
9708        let vals = vec![p(600), p(602), p(601)];
9709
9710        assert_eq!(super::nanmedian(&vals), p(601));
9711        assert_eq!(super::nanquantile(&vals, 0.5), p(601));
9712        assert_eq!(super::nanargmin(&vals), Some(0));
9713        assert_eq!(super::nanargmax(&vals), Some(1));
9714        assert_eq!(super::nancummax(&vals), vec![p(600), p(602), p(602)]);
9715        assert_eq!(super::nancummin(&vals), vec![p(600), p(600), p(600)]);
9716    }
9717
9718    /// Even-count Period median picks by TRUNCATION TOWARD ZERO on the ordinal,
9719    /// the same rule the datetime family uses. Probed: pandas gives 2020-02 for
9720    /// [2020-01, 2020-04] (ordinals 600/603, midpoint 601.5) and 2020-01 for
9721    /// [2020-01, 2020-02] (600/601, midpoint 600.5).
9722    #[test]
9723    fn period_even_count_median_truncates_toward_zero_d7zjp() {
9724        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
9725        assert_eq!(super::nanmedian(&[p(600), p(603)]), p(601));
9726        assert_eq!(super::nanmedian(&[p(600), p(601)]), p(600));
9727    }
9728
9729    /// MIXED FREQ must not be ordered by ANY of these, for the same reason as
9730    /// in qoabs: pandas raises IncompatibleFrequency, and raw ordinals are not
9731    /// comparable across freqs (monthly 2020-01 is 600, daily 2020-01-05 is
9732    /// 18267). The family enum encodes the freq, so a mixed input is simply not
9733    /// one family and never reaches a typed arm.
9734    #[test]
9735    fn period_mixed_freq_not_ordered_by_any_reduction_d7zjp() {
9736        let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
9737        let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
9738        let vals = vec![month, day];
9739
9740        assert!(super::nanmedian(&vals).is_missing());
9741        assert!(super::nanquantile(&vals, 0.5).is_missing());
9742        assert_eq!(super::nanargmin(&vals), None);
9743        assert_eq!(super::nanargmax(&vals), None);
9744        // The cumulative ops must not emit an ordered Period column either.
9745        assert!(super::nancummax(&vals).iter().all(Scalar::is_missing));
9746        assert!(super::nancummin(&vals).iter().all(Scalar::is_missing));
9747    }
9748
9749    /// pandas RAISES for Period mean/sum/std/var ("does not support reduction",
9750    /// and for mean explicitly "the meaning is ambiguous"). FP must not invent
9751    /// values. `std` is the trap here: the family enum puts Period one line
9752    /// away from the Datetime64 arm that 40ujm deliberately widened, so this
9753    /// asserts the guard holds.
9754    #[test]
9755    fn period_unsupported_reductions_stay_missing_d7zjp() {
9756        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
9757        let vals = vec![p(600), p(602), p(601)];
9758        assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
9759        assert!(super::nanvar(&vals, 1).is_missing(), "pandas raises var");
9760        assert!(super::nansem(&vals, 1).is_missing(), "pandas raises sem");
9761        assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
9762    }
9763
9764    /// br-frankenpandas-srqdo: Interval is the FOURTH dtype whose `to_f64()`
9765    /// errors, so min/max fell into the f64 catch-all and returned
9766    /// `Null(NaN)`. pandas 2.2.3 on `IntervalArray.from_tuples([(0,1),(4,5),(2,3)])`
9767    /// gives min `(0, 1]` and max `(4, 5]`.
9768    #[test]
9769    fn interval_min_max_match_pandas_srqdo() {
9770        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
9771        let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
9772        assert_eq!(super::nanmin(&vals), iv(0.0, 1.0));
9773        assert_eq!(super::nanmax(&vals), iv(4.0, 5.0));
9774
9775        // Size-dependence, per the axhhk lesson: ONE element always worked via
9776        // the `(None, _)` seed, so a single-value test passes even with no arm.
9777        assert_eq!(super::nanmin(&[iv(2.0, 3.0)]), iv(2.0, 3.0));
9778        let two = vec![iv(4.0, 5.0), iv(0.0, 1.0)];
9779        assert!(!super::nanmin(&two).is_missing());
9780        assert_eq!(super::nanmin(&two), iv(0.0, 1.0));
9781        assert_eq!(super::nanmax(&two), iv(4.0, 5.0));
9782    }
9783
9784    /// The tie-on-left case, which is what discriminates a correct (left, right)
9785    /// comparison from one that only looks at `left`. pandas: Interval(0,2) <
9786    /// Interval(0,5) is True. An implementation comparing left alone keeps
9787    /// whichever came first and returns the wrong element here.
9788    #[test]
9789    fn interval_ties_on_left_order_by_right_srqdo() {
9790        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
9791        let vals = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
9792        assert_eq!(super::nanmin(&vals), iv(0.0, 2.0));
9793        assert_eq!(super::nanmax(&vals), iv(0.0, 9.0));
9794    }
9795
9796    /// A NaN bound has no pandas counterpart — `IntervalArray` refuses to build
9797    /// one ("missing values must be missing in the same location both left and
9798    /// right") — so it must report missing rather than impose an arbitrary
9799    /// order. Critically this must NOT panic: the obvious
9800    /// `partial_cmp().unwrap()` implementation would.
9801    #[test]
9802    fn interval_nan_bound_is_not_ordered_srqdo() {
9803        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
9804        let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
9805        assert!(super::nanmin(&vals).is_missing());
9806        assert!(super::nanmax(&vals).is_missing());
9807    }
9808
9809    /// pandas RAISES or NotImplementedErrors every other reduction for
9810    /// Interval (median/mean/sum/std/quantile/cummax). FP must not invent
9811    /// values, so they stay missing.
9812    #[test]
9813    fn interval_unsupported_reductions_stay_missing_srqdo() {
9814        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
9815        let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
9816        assert!(super::nanmedian(&vals).is_missing(), "pandas raises median");
9817        assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
9818        assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
9819        assert!(
9820            super::nanquantile(&vals, 0.5).is_missing(),
9821            "pandas raises quantile"
9822        );
9823        assert!(
9824            super::nancummax(&vals).iter().all(Scalar::is_missing),
9825            "pandas NotImplementedErrors cummax"
9826        );
9827    }
9828
9829    /// br-frankenpandas-2h9dm: Interval argmin/argmax returned None, because
9830    /// `Interval::to_f64()` errors and the f64 fallback skipped every element.
9831    /// All four expectations are probed pandas 2.2.3 `idxmin`/`idxmax`.
9832    #[test]
9833    fn interval_argmin_argmax_match_pandas_2h9dm() {
9834        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
9835        // pandas: idxmin 1, idxmax 0
9836        let vals = vec![iv(4.0, 5.0), iv(0.0, 1.0), iv(2.0, 3.0)];
9837        assert_eq!(super::nanargmin(&vals), Some(1));
9838        assert_eq!(super::nanargmax(&vals), Some(0));
9839
9840        // Left-tie resolves by RIGHT. pandas: idxmin 1, idxmax 2. An
9841        // implementation comparing only `left` keeps index 0 for both.
9842        let tie = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
9843        assert_eq!(super::nanargmin(&tie), Some(1));
9844        assert_eq!(super::nanargmax(&tie), Some(2));
9845    }
9846
9847    /// Duplicated extreme returns the FIRST occurrence (pandas idxmin 0 on
9848    /// [(0,1),(0,1),(9,9)]), and missing entries are skipped while the returned
9849    /// index stays a position in the ORIGINAL slice (pandas idxmin 2 / idxmax 0
9850    /// on [(4,5), None, (0,1)]).
9851    #[test]
9852    fn interval_arg_first_occurrence_and_missing_2h9dm() {
9853        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
9854        let dup = vec![iv(0.0, 1.0), iv(0.0, 1.0), iv(9.0, 9.0)];
9855        assert_eq!(
9856            super::nanargmin(&dup),
9857            Some(0),
9858            "first occurrence, not last"
9859        );
9860        assert_eq!(super::nanargmax(&dup), Some(2));
9861
9862        let with_missing = vec![iv(4.0, 5.0), Scalar::Null(NullKind::NaN), iv(0.0, 1.0)];
9863        assert_eq!(super::nanargmin(&with_missing), Some(2));
9864        assert_eq!(super::nanargmax(&with_missing), Some(0));
9865    }
9866
9867    /// A NaN bound is not orderable, so decline rather than return an arbitrary
9868    /// index — and critically, do not panic the way `partial_cmp().unwrap()`
9869    /// would.
9870    #[test]
9871    fn interval_arg_nan_bound_declines_2h9dm() {
9872        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
9873        let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
9874        assert_eq!(super::nanargmin(&vals), None);
9875        assert_eq!(super::nanargmax(&vals), None);
9876    }
9877
9878    /// br-frankenpandas-fyr1z-policy-carrier-f29nz: the load-bearing guarantee
9879    /// of this bead is NO DEFAULT BEHAVIOR CHANGE. Prove it rather than assert
9880    /// it: over a seeded corpus that deliberately straddles the i64 boundary
9881    /// and the NaT sentinel, every infallible helper must equal its fallible
9882    /// sibling resolved under the default `SurfaceNat` policy — which is also
9883    /// exactly what the pre-f29nz bodies computed.
9884    #[test]
9885    fn overflow_policy_carrier_preserves_default_behavior_f29nz() {
9886        // Seeded LCG, no rand dependency (see [[differential-test-coverage]]).
9887        let mut state: u64 = 0x5DEE_CE66_D125_1F00;
9888        let mut next = || {
9889            state = state
9890                .wrapping_mul(6_364_136_223_846_793_005)
9891                .wrapping_add(1_442_695_040_888_963_407);
9892            state
9893        };
9894        // Edge values first, then random ones. i64::MIN is the NaT sentinel.
9895        let mut corpus: Vec<i64> = vec![
9896            0,
9897            1,
9898            -1,
9899            2,
9900            -2,
9901            i64::MAX,
9902            i64::MIN,
9903            i64::MIN + 1,
9904            i64::MAX - 1,
9905            i64::MAX / 2,
9906            -(i64::MAX / 2),
9907        ];
9908        for _ in 0..400 {
9909            let raw = next() as i64;
9910            corpus.push(raw);
9911            corpus.push(raw / 3);
9912        }
9913
9914        let policy = super::OverflowPolicy::default();
9915        assert_eq!(
9916            policy,
9917            super::OverflowPolicy::SurfaceNat,
9918            "default must not move"
9919        );
9920
9921        for &a in &corpus {
9922            for &b in &corpus {
9923                // Timedelta::add / sub / mul_scalar
9924                assert_eq!(
9925                    Timedelta::add(a, b),
9926                    policy
9927                        .resolve(Timedelta::try_add(a, b), Timedelta::NAT)
9928                        .expect("SurfaceNat never errors"),
9929                    "add({a}, {b}) diverged"
9930                );
9931                assert_eq!(
9932                    Timedelta::sub(a, b),
9933                    policy
9934                        .resolve(Timedelta::try_sub(a, b), Timedelta::NAT)
9935                        .expect("SurfaceNat never errors"),
9936                    "sub({a}, {b}) diverged"
9937                );
9938                assert_eq!(
9939                    Timedelta::mul_scalar(a, b),
9940                    policy
9941                        .resolve(Timedelta::try_mul_scalar(a, b), Timedelta::NAT)
9942                        .expect("SurfaceNat never errors"),
9943                    "mul_scalar({a}, {b}) diverged"
9944                );
9945
9946                // Timestamp::{add,sub}_timedelta / sub_timestamp — including tz,
9947                // since overflow deliberately drops it.
9948                let ts = Timestamp::from_nanos(a);
9949                assert_eq!(
9950                    ts.add_timedelta(b),
9951                    ts.try_add_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
9952                    "add_timedelta({a}, {b}) diverged"
9953                );
9954                assert_eq!(
9955                    ts.sub_timedelta(b),
9956                    ts.try_sub_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
9957                    "sub_timedelta({a}, {b}) diverged"
9958                );
9959                let other = Timestamp::from_nanos(b);
9960                assert_eq!(
9961                    ts.sub_timestamp(&other),
9962                    ts.try_sub_timestamp(&other).unwrap_or(Timedelta::NAT),
9963                    "sub_timestamp({a}, {b}) diverged"
9964                );
9965            }
9966        }
9967    }
9968
9969    /// The carrier must actually CARRY something: `Strict` propagates the
9970    /// overflow with the right op name and the pandas error class probed from
9971    /// live 2.2.3. Without this, `resolve` could ignore its policy and the
9972    /// equivalence test above would still pass.
9973    #[test]
9974    fn overflow_policy_strict_reports_op_and_pandas_class_f29nz() {
9975        use super::{OverflowPolicy, PandasTemporalError};
9976
9977        let strict = OverflowPolicy::Strict;
9978
9979        // pd.Timedelta.max + pd.Timedelta('1ns') -> OverflowError
9980        let err = strict
9981            .resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT)
9982            .expect_err("must surface under Strict");
9983        assert_eq!(err.op, "Timedelta::add");
9984        assert_eq!(err.pandas_error, PandasTemporalError::Overflow);
9985
9986        // pd.Timestamp.max + pd.Timedelta('1ns') -> OutOfBoundsDatetime
9987        let ts = Timestamp::from_nanos(i64::MAX);
9988        let err = strict
9989            .resolve(ts.try_add_timedelta(1), Timestamp::nat())
9990            .expect_err("must surface under Strict");
9991        assert_eq!(err.op, "Timestamp::add_timedelta");
9992        assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
9993
9994        // pd.Timestamp.min - pd.Timestamp.max -> OutOfBoundsDatetime
9995        let err = strict
9996            .resolve(
9997                Timestamp::from_nanos(i64::MIN + 1)
9998                    .try_sub_timestamp(&Timestamp::from_nanos(i64::MAX)),
9999                Timedelta::NAT,
10000            )
10001            .expect_err("must surface under Strict");
10002        assert_eq!(err.op, "Timestamp::sub_timestamp");
10003        assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
10004
10005        // A NaT operand is PROPAGATION, not overflow: Strict must still be Ok.
10006        assert_eq!(
10007            strict
10008                .resolve(Timedelta::try_add(Timedelta::NAT, 1), Timedelta::NAT)
10009                .expect("NaT propagation is not an overflow"),
10010            Timedelta::NAT
10011        );
10012        // And a representable result is untouched under either policy.
10013        assert_eq!(
10014            strict
10015                .resolve(Timedelta::try_add(2, 3), Timedelta::NAT)
10016                .expect("no overflow"),
10017            5
10018        );
10019    }
10020
10021    /// br-frankenpandas-fyr1z-strict-raise-arms-t7ht2: the scalar divide-by-zero
10022    /// row, and the boundary a STRICT arm must not cross. All four expectations
10023    /// probed on live pandas 2.2.3:
10024    ///   SCALAR  Timedelta('1s') // 0   -> ZeroDivisionError
10025    ///   SCALAR  Timedelta('1s') / 0    -> ZeroDivisionError
10026    ///   VECTOR  Series([Td]) // 0      -> NaT   (must NOT raise)
10027    ///   VECTOR  Series([Td]) / 0       -> NaT   (must NOT raise)
10028    #[test]
10029    fn timedelta_scalar_zero_division_taxonomy_t7ht2() {
10030        use super::{OverflowPolicy, PandasTemporalError};
10031
10032        // The fallible scalar sibling reports ZeroDivision with its op name.
10033        let err = Timedelta::try_div_scalar(1_000_000_000, 0)
10034            .expect_err("scalar divide-by-zero must be reportable");
10035        assert_eq!(err.op, "Timedelta::div_scalar");
10036        assert_eq!(err.pandas_error, PandasTemporalError::ZeroDivision);
10037
10038        // THE BOUNDARY: the infallible helper the vectorized callers use keeps
10039        // returning NaT. If this ever starts raising, FrankenPandas diverges
10040        // from pandas on a row where it is currently bit-for-bit correct.
10041        assert_eq!(Timedelta::div_scalar(1_000_000_000, 0), Timedelta::NAT);
10042        assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 0), Timedelta::NAT);
10043
10044        // Under the default policy the failure resolves back to NaT, so
10045        // nothing changes for existing callers.
10046        assert_eq!(
10047            OverflowPolicy::default()
10048                .resolve(Timedelta::try_div_scalar(1_000_000_000, 0), Timedelta::NAT)
10049                .expect("SurfaceNat never errors"),
10050            Timedelta::NAT
10051        );
10052
10053        // Non-zero divisors are untouched, including the floor-division
10054        // adjustment for mixed signs (-7 // 2 == -4, not -3).
10055        assert_eq!(Timedelta::try_div_scalar(-7, 2), Ok(-4));
10056        assert_eq!(Timedelta::div_scalar(-7, 2), -4);
10057        assert_eq!(Timedelta::try_div_scalar(7, 2), Ok(3));
10058        // NaT propagates as Ok, not as a failure.
10059        assert_eq!(
10060            Timedelta::try_div_scalar(Timedelta::NAT, 2),
10061            Ok(Timedelta::NAT)
10062        );
10063    }
10064
10065    /// The constructor row of the taxonomy. Probed:
10066    /// `pd.Timedelta(float('inf'), 's')` raises OutOfBoundsTimedelta —
10067    /// specifically NOT a bare OverflowError, which is why the mapping is
10068    /// explicit rather than assumed.
10069    #[test]
10070    fn timedelta_constructor_error_maps_to_out_of_bounds_t7ht2() {
10071        use super::{PandasTemporalError, TimedeltaError};
10072
10073        assert_eq!(
10074            TimedeltaError::Overflow.pandas_error(),
10075            Some(PandasTemporalError::OutOfBoundsTimedelta)
10076        );
10077        // A parse failure is not part of the arithmetic taxonomy.
10078        assert_eq!(
10079            TimedeltaError::InvalidFormat("nonsense".into()).pandas_error(),
10080            None
10081        );
10082        // And the live path still errors on a non-finite input (8v92m).
10083        assert!(Timedelta::from_unit(f64::INFINITY, "s").is_err());
10084        assert_eq!(
10085            Timedelta::from_unit(f64::INFINITY, "s")
10086                .unwrap_err()
10087                .pandas_error(),
10088            Some(PandasTemporalError::OutOfBoundsTimedelta)
10089        );
10090    }
10091
10092    /// br-frankenpandas-fyr1z-hardened-audit-vllv6: HARDENED mode adds
10093    /// observability, NEVER semantics. Every value it returns must be
10094    /// bit-for-bit what SurfaceNat returns — proven over the same seeded corpus
10095    /// the f29nz equivalence test uses, with the audit log ENABLED throughout so
10096    /// recording cannot perturb results.
10097    #[test]
10098    fn hardened_audit_values_are_bit_identical_to_surface_nat_vllv6() {
10099        use super::{OverflowPolicy, overflow_audit};
10100
10101        overflow_audit::enable();
10102        let mut state: u64 = 0x1234_5678_9ABC_DEF0;
10103        let mut next = || {
10104            state = state
10105                .wrapping_mul(6_364_136_223_846_793_005)
10106                .wrapping_add(1_442_695_040_888_963_407);
10107            state
10108        };
10109        let mut corpus: Vec<i64> = vec![
10110            0,
10111            1,
10112            -1,
10113            2,
10114            -2,
10115            i64::MAX,
10116            i64::MIN,
10117            i64::MIN + 1,
10118            i64::MAX - 1,
10119        ];
10120        for _ in 0..120 {
10121            corpus.push(next() as i64);
10122        }
10123
10124        for &a in &corpus {
10125            for &b in &corpus {
10126                for op in [
10127                    Timedelta::try_add as fn(i64, i64) -> Result<i64, super::TemporalFailure>,
10128                    Timedelta::try_sub,
10129                    Timedelta::try_mul_scalar,
10130                    Timedelta::try_div_scalar,
10131                ] {
10132                    let soft = OverflowPolicy::SurfaceNat
10133                        .resolve(op(a, b), Timedelta::NAT)
10134                        .expect("SurfaceNat never errors");
10135                    let hard = OverflowPolicy::HardenedNat
10136                        .resolve(op(a, b), Timedelta::NAT)
10137                        .expect("HardenedNat never errors");
10138                    assert_eq!(hard, soft, "HARDENED changed a value for ({a}, {b})");
10139                }
10140            }
10141        }
10142        overflow_audit::disable();
10143    }
10144
10145    /// The audit trail itself: HARDENED records the op, the pandas class it
10146    /// would have raised, the OPERANDS whose exact result left the
10147    /// representable range, and the value actually returned — deterministically
10148    /// and in order. SurfaceNat and Strict record nothing.
10149    #[test]
10150    fn hardened_audit_records_deterministic_recovery_entries_vllv6() {
10151        use super::{OverflowPolicy, PandasTemporalError, overflow_audit};
10152
10153        overflow_audit::enable();
10154        assert!(overflow_audit::is_enabled());
10155        assert!(overflow_audit::drain().is_empty(), "starts empty");
10156
10157        // Two overflows and one representable result, in a fixed order.
10158        let _ =
10159            OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
10160        let _ = OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(2, 3), Timedelta::NAT);
10161        let _ =
10162            OverflowPolicy::HardenedNat.resolve(Timedelta::try_div_scalar(5, 0), Timedelta::NAT);
10163
10164        let entries = overflow_audit::drain();
10165        assert_eq!(entries.len(), 2, "only the two failures are recorded");
10166
10167        assert_eq!(entries[0].op, "Timedelta::add");
10168        assert_eq!(entries[0].pandas_error, PandasTemporalError::Overflow);
10169        assert_eq!(entries[0].operands, Some((i64::MAX, 1)));
10170        assert_eq!(entries[0].recovered_as, i64::MIN);
10171
10172        assert_eq!(entries[1].op, "Timedelta::div_scalar");
10173        assert_eq!(entries[1].pandas_error, PandasTemporalError::ZeroDivision);
10174        assert_eq!(entries[1].operands, Some((5, 0)));
10175
10176        // Draining leaves recording enabled and empty.
10177        assert!(overflow_audit::drain().is_empty());
10178
10179        // The OTHER policies must stay silent — the audit is HARDENED-only.
10180        let _ = OverflowPolicy::SurfaceNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
10181        let _ = OverflowPolicy::Strict.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
10182        assert!(
10183            overflow_audit::drain().is_empty(),
10184            "SurfaceNat/Strict must not write to the audit trail"
10185        );
10186
10187        overflow_audit::disable();
10188        assert!(!overflow_audit::is_enabled());
10189        // Disabled: recording is a no-op and drain yields nothing.
10190        let _ =
10191            OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
10192        assert!(
10193            overflow_audit::drain().is_empty(),
10194            "disabled must not record"
10195        );
10196    }
10197
10198    /// br-frankenpandas-fyr1z-wrap-signoff-s4lkx.
10199    ///
10200    /// THIS TEST PINS A PANDAS QUIRK THAT WE REPRODUCE ON PURPOSE. The values
10201    /// below are NOT what a careful implementation would choose: multiplying a
10202    /// positive duration by 2 yields a NEGATIVE one. They are what live pandas
10203    /// 2.2.3 returns, because numpy int64 wraps silently, and the maintainer
10204    /// decided that STRICT means bit-for-bit observable parity with the
10205    /// incumbent INCLUDING its quirks — this being a port.
10206    ///
10207    /// So: if this test fails, do NOT "fix" the wrap. Either pandas changed, or
10208    /// someone routed a non-STRICT caller into the STRICT path. Both need
10209    /// investigating rather than correcting the arithmetic.
10210    ///
10211    /// Oracle values, probed directly:
10212    ///   Series([Timedelta.max]) * 2            -> -2 ns
10213    ///   Series([max, max]).cumsum()            -> [max, -2]
10214    ///   Series([max, max, max]).cumsum()       -> [max, -2, max - 2]
10215    #[test]
10216    fn strict_reproduces_pandas_silent_timedelta_wrap_s4lkx() {
10217        use super::{OverflowPolicy, nancumsum_with_policy};
10218
10219        // Series * int -- pandas returns -2, i.e. i64::MAX.wrapping_mul(2).
10220        assert_eq!(
10221            Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::Strict),
10222            -2,
10223            "STRICT must reproduce pandas' wrap, not repair it"
10224        );
10225
10226        // cumsum -- and the THIRD element is the important one: it proves the
10227        // accumulator keeps wrapping rather than sticking at a bound.
10228        let max = Scalar::Timedelta64(i64::MAX);
10229        let out = nancumsum_with_policy(
10230            &[max.clone(), max.clone(), max.clone()],
10231            OverflowPolicy::Strict,
10232        );
10233        assert_eq!(
10234            out,
10235            vec![
10236                Scalar::Timedelta64(i64::MAX),
10237                Scalar::Timedelta64(-2),
10238                Scalar::Timedelta64(i64::MAX - 2),
10239            ],
10240            "STRICT cumsum must reproduce pandas' int64 wraparound exactly"
10241        );
10242
10243        // NaT still propagates; the wrap is about overflow, not missingness.
10244        assert_eq!(
10245            Timedelta::mul_scalar_with_policy(Timedelta::NAT, 2, OverflowPolicy::Strict),
10246            Timedelta::NAT
10247        );
10248    }
10249
10250    /// The other half of the s4lkx decision, and the reason reproducing a
10251    /// fail-open quirk is acceptable at all: it is reachable ONLY when a caller
10252    /// explicitly asks for STRICT incumbent parity. Every other policy — and
10253    /// crucially the DEFAULT — still refuses to fabricate a plausible value,
10254    /// keeping the br-frankenpandas-lgyy8 guarantee intact.
10255    #[test]
10256    fn non_strict_policies_still_refuse_to_wrap_s4lkx() {
10257        use super::{OverflowPolicy, nancumsum_with_policy, overflow_audit};
10258
10259        for policy in [OverflowPolicy::SurfaceNat, OverflowPolicy::HardenedNat] {
10260            assert_eq!(
10261                Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
10262                Timedelta::NAT,
10263                "{policy:?} must NOT wrap"
10264            );
10265            assert_ne!(
10266                Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
10267                -2,
10268                "{policy:?} must not reproduce the pandas quirk"
10269            );
10270        }
10271        // The bare default is SurfaceNat, so an unconfigured caller is safe.
10272        assert_eq!(
10273            Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::default()),
10274            Timedelta::NAT
10275        );
10276
10277        // cumsum likewise keeps the exact-i128 / NaT behaviour off STRICT.
10278        let max = Scalar::Timedelta64(i64::MAX);
10279        let soft = nancumsum_with_policy(&[max.clone(), max.clone()], OverflowPolicy::SurfaceNat);
10280        assert!(soft[1].is_missing(), "non-STRICT cumsum must NaT, not wrap");
10281        assert_eq!(soft, super::nancumsum(&[max.clone(), max]));
10282
10283        // HARDENED wrapping would be doubly wrong: it would fabricate a value
10284        // AND leave nothing in the audit trail to explain it.
10285        overflow_audit::enable();
10286        let _ = Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::HardenedNat);
10287        assert_eq!(
10288            overflow_audit::drain().len(),
10289            1,
10290            "HARDENED must record the recovery it performed"
10291        );
10292        overflow_audit::disable();
10293    }
10294
10295    /// Mixed Datetime64 + another dtype must NOT take the typed arm — it falls
10296    /// back exactly as before, so this fix cannot change cross-type behavior.
10297    #[test]
10298    fn datetime64_mixed_input_still_falls_back_axhhk() {
10299        let vals = vec![Scalar::Datetime64(DT_2020), Scalar::Int64(5)];
10300        // `is_datetime_input` is false here, so both keep their PRE-EXISTING
10301        // cross-type behavior, which differs between the two by construction:
10302        //   nanmin  — the catch-all compares via to_f64(); the Datetime64 side
10303        //             errors, so it bails to Null(NaN).
10304        //   nanptp  — its f64 loop SKIPS values whose to_f64() errors, so the
10305        //             datetime is dropped and the range is taken over the lone
10306        //             Int64 => Float64(0.0). Same shape as the documented
10307        //             mixed-timedelta fallback in ..._620mj (which yields 5.0).
10308        // Neither is changed by this bead; pinning both stops the new typed arm
10309        // from silently widening to mixed input later.
10310        assert!(super::nanmin(&vals).is_missing());
10311        assert_eq!(super::nanptp(&vals), Scalar::Float64(0.0));
10312    }
10313
10314    #[test]
10315    fn nansum_nanmean_mixed_timedelta_other_falls_back_620mj() {
10316        // Mixed Timedelta64 + other type bails out of the Timedelta path
10317        // and uses Float64 collect_finite (which drops Timedelta).
10318        // Preserves existing cross-type behavior (effectively ignores TD).
10319        let vals = vec![Scalar::Timedelta64(3600 * 1_000_000_000), Scalar::Int64(5)];
10320        // Int64(5) makes it through to_f64 → 5.0; Timedelta is dropped.
10321        assert_eq!(super::nansum(&vals), Scalar::Float64(5.0));
10322    }
10323
10324    #[test]
10325    fn nancount_counts_non_missing() {
10326        let vals = vec![
10327            Scalar::Int64(1),
10328            Scalar::Null(NullKind::Null),
10329            Scalar::Float64(3.0),
10330        ];
10331        assert_eq!(super::nancount(&vals), Scalar::Int64(2));
10332    }
10333
10334    #[test]
10335    fn nanany_nanall_nancount_match_scalar_oracle_zr2qg() {
10336        // Differential vs scalar truthiness/count oracle
10337        // (br-frankenpandas-zr2qg). Seeded LCG, no mocks.
10338        fn next(seed: &mut u64) -> u64 {
10339            *seed = seed
10340                .wrapping_mul(6364136223846793005)
10341                .wrapping_add(1442695040888963407);
10342            *seed
10343        }
10344
10345        fn truthy(value: &Scalar) -> Option<bool> {
10346            if value.is_missing() {
10347                return None;
10348            }
10349            match value {
10350                Scalar::Bool(value) => Some(*value),
10351                Scalar::Int64(value) => Some(*value != 0),
10352                Scalar::Float64(value) => Some(*value != 0.0),
10353                Scalar::Utf8(value) => Some(!value.is_empty()),
10354                Scalar::Timedelta64(value) => Some(*value != 0),
10355                _ => None,
10356            }
10357        }
10358
10359        fn assert_nanops(case: usize, values: &[Scalar]) {
10360            let truth_values = values.iter().filter_map(truthy).collect::<Vec<_>>();
10361            let expected_any = truth_values.iter().any(|value| *value);
10362            let expected_all = !truth_values.iter().any(|value| !*value);
10363            let expected_count = values.iter().filter(|value| !value.is_missing()).count() as i64;
10364
10365            assert_eq!(
10366                super::nanany(values),
10367                Scalar::Bool(expected_any),
10368                "case={case}: nanany mismatch for {values:?}"
10369            );
10370            assert_eq!(
10371                super::nanall(values),
10372                Scalar::Bool(expected_all),
10373                "case={case}: nanall mismatch for {values:?}"
10374            );
10375            assert_eq!(
10376                super::nancount(values),
10377                Scalar::Int64(expected_count),
10378                "case={case}: nancount mismatch for {values:?}"
10379            );
10380        }
10381
10382        assert_nanops(
10383            usize::MAX,
10384            &[
10385                Scalar::Null(NullKind::Null),
10386                Scalar::Null(NullKind::NaN),
10387                Scalar::Float64(f64::NAN),
10388                Scalar::Timedelta64(i64::MIN),
10389            ],
10390        );
10391
10392        let mut seed = 0x7a20_2f7e_5ca1_ab1e_u64;
10393        for case in 0..320 {
10394            let len = (next(&mut seed) % 89 + 1) as usize;
10395            let mut values = Vec::with_capacity(len);
10396            for pos in 0..len {
10397                let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
10398                let value = match next(&mut seed) % 12 {
10399                    0 => Scalar::Null(NullKind::Null),
10400                    1 => Scalar::Null(NullKind::NaN),
10401                    2 => Scalar::Float64(f64::NAN),
10402                    3 => Scalar::Bool(raw & 1 == 0),
10403                    4 => Scalar::Bool(false),
10404                    5 => Scalar::Int64(raw % 17),
10405                    6 => Scalar::Int64(0),
10406                    7 => Scalar::Float64(raw as f64 / 23.0),
10407                    8 => Scalar::Float64(0.0),
10408                    9 => Scalar::Utf8(if raw & 1 == 0 {
10409                        String::new()
10410                    } else {
10411                        format!("nanops_{case}_{pos}")
10412                    }),
10413                    10 => Scalar::Timedelta64(raw),
10414                    _ => Scalar::Timedelta64(0),
10415                };
10416                values.push(value);
10417            }
10418            assert_nanops(case, &values);
10419        }
10420    }
10421
10422    #[test]
10423    fn nanmin_basic() {
10424        let vals = vec![
10425            Scalar::Float64(5.0),
10426            Scalar::Null(NullKind::Null),
10427            Scalar::Float64(2.0),
10428            Scalar::Float64(8.0),
10429        ];
10430        assert_eq!(super::nanmin(&vals), Scalar::Float64(2.0));
10431    }
10432
10433    #[test]
10434    fn nanmax_basic() {
10435        let vals = vec![
10436            Scalar::Float64(5.0),
10437            Scalar::Float64(f64::NAN),
10438            Scalar::Float64(8.0),
10439        ];
10440        assert_eq!(super::nanmax(&vals), Scalar::Float64(8.0));
10441    }
10442
10443    #[test]
10444    fn nanmin_nanmax_empty_returns_nan() {
10445        assert!(super::nanmin(&[]).is_missing());
10446        assert!(super::nanmax(&[]).is_missing());
10447    }
10448
10449    #[test]
10450    fn nanmin_nanmax_match_same_family_oracle_vj7ds() {
10451        // Differential vs independent same-family comparator oracle
10452        // (br-frankenpandas-vj7ds). Seeded LCG, no mocks.
10453        fn next(seed: &mut u64) -> u64 {
10454            *seed = seed
10455                .wrapping_mul(6364136223846793005)
10456                .wrapping_add(1442695040888963407);
10457            *seed
10458        }
10459
10460        fn family_cmp(left: &Scalar, right: &Scalar) -> std::cmp::Ordering {
10461            match (left, right) {
10462                (Scalar::Bool(left), Scalar::Bool(right)) => left.cmp(right),
10463                (Scalar::Int64(left), Scalar::Int64(right)) => left.cmp(right),
10464                (Scalar::Float64(left), Scalar::Float64(right)) => {
10465                    left.partial_cmp(right).expect("finite floats")
10466                }
10467                (Scalar::Utf8(left), Scalar::Utf8(right)) => left.cmp(right),
10468                (Scalar::Timedelta64(left), Scalar::Timedelta64(right)) => left.cmp(right),
10469                // `assert_minmax` verifies that every present value belongs
10470                // to one generated family before it invokes this comparator.
10471                _ => std::cmp::Ordering::Equal,
10472            }
10473        }
10474
10475        fn assert_minmax(case: usize, family: &str, values: &[Scalar]) {
10476            let present = values
10477                .iter()
10478                .filter(|value| !value.is_missing())
10479                .cloned()
10480                .collect::<Vec<_>>();
10481            let actual_min = super::nanmin(values);
10482            let actual_max = super::nanmax(values);
10483            if present.is_empty() {
10484                assert!(
10485                    actual_min.is_missing(),
10486                    "case={case} family={family}: expected missing min for {values:?}, got {actual_min:?}"
10487                );
10488                assert!(
10489                    actual_max.is_missing(),
10490                    "case={case} family={family}: expected missing max for {values:?}, got {actual_max:?}"
10491                );
10492                return;
10493            }
10494
10495            let is_expected_family = |value: &Scalar| match family {
10496                "int" => matches!(value, Scalar::Int64(_)),
10497                "float" => matches!(value, Scalar::Float64(_)),
10498                "bool" => matches!(value, Scalar::Bool(_)),
10499                "utf8" => matches!(value, Scalar::Utf8(_)),
10500                "timedelta" => matches!(value, Scalar::Timedelta64(_)),
10501                _ => false,
10502            };
10503            assert!(
10504                present.iter().all(is_expected_family),
10505                "case={case} family={family}: mixed family escaped generator: {values:?}"
10506            );
10507
10508            let expected_min = present.iter().min_by(|left, right| family_cmp(left, right));
10509            let expected_max = present.iter().max_by(|left, right| family_cmp(left, right));
10510            assert!(
10511                actual_min.semantic_eq(expected_min.expect("min")),
10512                "case={case} family={family}: expected min {:?}, got {actual_min:?} for {values:?}",
10513                expected_min.expect("min")
10514            );
10515            assert!(
10516                actual_max.semantic_eq(expected_max.expect("max")),
10517                "case={case} family={family}: expected max {:?}, got {actual_max:?} for {values:?}",
10518                expected_max.expect("max")
10519            );
10520        }
10521
10522        let all_missing = [
10523            Scalar::Null(NullKind::Null),
10524            Scalar::Null(NullKind::NaN),
10525            Scalar::Float64(f64::NAN),
10526            Scalar::Timedelta64(i64::MIN),
10527        ];
10528        assert_minmax(usize::MAX, "all_missing", &all_missing);
10529
10530        let mut seed = 0xa11c_0aba_2e7d_f00d_u64;
10531        for case in 0..240 {
10532            let len = (next(&mut seed) % 73 + 1) as usize;
10533
10534            let mut ints = Vec::with_capacity(len);
10535            ints.push(Scalar::Int64(case as i64 - 120));
10536            for _ in 1..len {
10537                let raw = (next(&mut seed) % 1_001) as i64 - 500;
10538                ints.push(match next(&mut seed) % 6 {
10539                    0 => Scalar::Null(NullKind::Null),
10540                    1 => Scalar::Null(NullKind::NaN),
10541                    _ => Scalar::Int64(raw),
10542                });
10543            }
10544            assert_minmax(case, "int", &ints);
10545
10546            let mut floats = Vec::with_capacity(len);
10547            floats.push(Scalar::Float64(case as f64 / 11.0));
10548            for _ in 1..len {
10549                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
10550                floats.push(match next(&mut seed) % 8 {
10551                    0 | 1 => Scalar::Float64(f64::NAN),
10552                    2 => Scalar::Float64(f64::INFINITY),
10553                    3 => Scalar::Float64(f64::NEG_INFINITY),
10554                    4 => Scalar::Float64(0.0),
10555                    5 => Scalar::Float64(-0.0),
10556                    _ => Scalar::Float64(raw as f64 / 41.0),
10557                });
10558            }
10559            assert_minmax(case, "float", &floats);
10560
10561            let mut bools = Vec::with_capacity(len);
10562            bools.push(Scalar::Bool(case & 1 == 0));
10563            for _ in 1..len {
10564                bools.push(match next(&mut seed) % 5 {
10565                    0 => Scalar::Null(NullKind::Null),
10566                    1 => Scalar::Null(NullKind::NaN),
10567                    raw => Scalar::Bool(raw & 1 == 0),
10568                });
10569            }
10570            assert_minmax(case, "bool", &bools);
10571
10572            let mut utf8 = Vec::with_capacity(len);
10573            utf8.push(Scalar::Utf8(format!("minmax_{}", case % 17)));
10574            for pos in 1..len {
10575                utf8.push(match next(&mut seed) % 7 {
10576                    0 => Scalar::Null(NullKind::Null),
10577                    1 => Scalar::Null(NullKind::NaN),
10578                    raw => Scalar::Utf8(format!("minmax_{}_{}", raw, pos % 11)),
10579                });
10580            }
10581            assert_minmax(case, "utf8", &utf8);
10582
10583            let mut timedeltas = Vec::with_capacity(len);
10584            timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
10585            for _ in 1..len {
10586                let raw = (next(&mut seed) % 1_003) as i64 - 501;
10587                timedeltas.push(match next(&mut seed) % 7 {
10588                    0 => Scalar::Null(NullKind::Null),
10589                    1 => Scalar::Timedelta64(i64::MIN),
10590                    _ => Scalar::Timedelta64(raw),
10591                });
10592            }
10593            assert_minmax(case, "timedelta", &timedeltas);
10594        }
10595    }
10596
10597    #[test]
10598    fn nanmin_nanmax_mixed_incompatible_types_returns_nan() {
10599        let vals = vec![Scalar::Int64(5), Scalar::Utf8("hello".into())];
10600        assert!(super::nanmin(&vals).is_missing());
10601        assert!(super::nanmax(&vals).is_missing());
10602
10603        let vals2 = vec![Scalar::Utf8("a".into()), Scalar::Float64(3.0)];
10604        assert!(super::nanmin(&vals2).is_missing());
10605        assert!(super::nanmax(&vals2).is_missing());
10606    }
10607
10608    #[test]
10609    fn nanmin_nanmax_compatible_numeric_types_ok() {
10610        let vals = vec![Scalar::Int64(5), Scalar::Float64(3.0), Scalar::Bool(true)];
10611        assert_eq!(super::nanmin(&vals), Scalar::Bool(true));
10612        assert_eq!(super::nanmax(&vals), Scalar::Int64(5));
10613    }
10614
10615    #[test]
10616    fn nanmin_nanmax_timedelta64_returns_timedelta_yic5m() {
10617        // Per br-frankenpandas-yic5m: nanmin/nanmax on Timedelta64 returns
10618        // the smallest/largest Timedelta64 — was silently NaN before
10619        // because Timedelta64.to_f64() errors and the catch-all swallowed it.
10620        let one_hour = 3_600 * 1_000_000_000_i64;
10621        let vals = vec![
10622            Scalar::Timedelta64(3 * one_hour),
10623            Scalar::Timedelta64(one_hour),
10624            Scalar::Timedelta64(2 * one_hour),
10625        ];
10626        assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
10627        assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(3 * one_hour));
10628    }
10629
10630    #[test]
10631    fn nanmin_nanmax_timedelta64_skips_nat_yic5m() {
10632        let one_hour = 3_600 * 1_000_000_000_i64;
10633        let vals = vec![
10634            Scalar::Timedelta64(Timedelta::NAT),
10635            Scalar::Timedelta64(one_hour),
10636            Scalar::Timedelta64(2 * one_hour),
10637            Scalar::Timedelta64(Timedelta::NAT),
10638        ];
10639        assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
10640        assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(2 * one_hour));
10641    }
10642
10643    #[test]
10644    fn nanmedian_odd_count() {
10645        let vals = vec![
10646            Scalar::Float64(3.0),
10647            Scalar::Null(NullKind::Null),
10648            Scalar::Float64(1.0),
10649            Scalar::Float64(2.0),
10650        ];
10651        assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.0));
10652    }
10653
10654    #[test]
10655    fn nanmedian_even_count() {
10656        let vals = vec![
10657            Scalar::Float64(1.0),
10658            Scalar::Float64(3.0),
10659            Scalar::Float64(2.0),
10660            Scalar::Float64(4.0),
10661        ];
10662        assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.5));
10663    }
10664
10665    #[test]
10666    fn nanmedian_matches_numeric_and_timedelta_oracle_oabhi() {
10667        // Differential vs independent sort-based median oracles
10668        // (br-frankenpandas-oabhi). Seeded LCG, no mocks.
10669        fn next(seed: &mut u64) -> u64 {
10670            *seed = seed
10671                .wrapping_mul(6364136223846793005)
10672                .wrapping_add(1442695040888963407);
10673            *seed
10674        }
10675
10676        fn expected_numeric(values: &[Scalar]) -> Scalar {
10677            let mut finite = values
10678                .iter()
10679                .filter(|value| !value.is_missing())
10680                .filter_map(|value| value.to_f64().ok())
10681                .filter(|value| !value.is_nan())
10682                .collect::<Vec<_>>();
10683            if finite.is_empty() {
10684                return Scalar::Null(NullKind::NaN);
10685            }
10686            finite.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
10687            let mid = finite.len() / 2;
10688            if finite.len().is_multiple_of(2) {
10689                Scalar::Float64((finite[mid - 1] + finite[mid]) / 2.0)
10690            } else {
10691                Scalar::Float64(finite[mid])
10692            }
10693        }
10694
10695        fn expected_timedelta(values: &[Scalar]) -> Scalar {
10696            let mut finite = values
10697                .iter()
10698                .filter_map(|value| match value {
10699                    Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns),
10700                    _ => None,
10701                })
10702                .collect::<Vec<_>>();
10703            if finite.is_empty() {
10704                return Scalar::Null(NullKind::NaN);
10705            }
10706            finite.sort_unstable();
10707            let mid = finite.len() / 2;
10708            let median = if finite.len().is_multiple_of(2) {
10709                (i128::from(finite[mid - 1]) + i128::from(finite[mid])) / 2
10710            } else {
10711                i128::from(finite[mid])
10712            };
10713            Scalar::Timedelta64(median as i64)
10714        }
10715
10716        fn assert_median(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
10717            let actual = super::nanmedian(values);
10718            assert!(
10719                actual.semantic_eq(&expected),
10720                "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
10721            );
10722        }
10723
10724        assert_median(
10725            usize::MAX,
10726            "numeric_all_missing",
10727            &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
10728            Scalar::Null(NullKind::NaN),
10729        );
10730        assert_median(
10731            usize::MAX - 1,
10732            "timedelta_all_missing",
10733            &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
10734            Scalar::Null(NullKind::NaN),
10735        );
10736        let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
10737        assert_median(
10738            usize::MAX - 2,
10739            "timedelta_odd_median_beyond_f64_exactness",
10740            &[
10741                Scalar::Timedelta64(beyond_f64_exact_ns),
10742                Scalar::Timedelta64(beyond_f64_exact_ns + 1),
10743                Scalar::Timedelta64(beyond_f64_exact_ns + 2),
10744                Scalar::Timedelta64(Timedelta::NAT),
10745            ],
10746            Scalar::Timedelta64(beyond_f64_exact_ns + 1),
10747        );
10748
10749        let mut seed = 0x0ab1_1eda_57a7_15e5_u64;
10750        for case in 0..220 {
10751            let len = (next(&mut seed) % 79 + 1) as usize;
10752
10753            let mut numeric = Vec::with_capacity(len);
10754            numeric.push(Scalar::Int64(case as i64 - 110));
10755            for _ in 1..len {
10756                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
10757                numeric.push(match next(&mut seed) % 8 {
10758                    0 => Scalar::Null(NullKind::Null),
10759                    1 => Scalar::Null(NullKind::NaN),
10760                    2 => Scalar::Float64(f64::NAN),
10761                    3 => Scalar::Bool(raw & 1 == 0),
10762                    4 => Scalar::Int64(raw % 251),
10763                    5 => Scalar::Float64(raw as f64 / 61.0),
10764                    6 => Scalar::Float64(0.0),
10765                    _ => Scalar::Float64(-0.0),
10766                });
10767            }
10768            assert_median(case, "numeric", &numeric, expected_numeric(&numeric));
10769
10770            let mut timedeltas = Vec::with_capacity(len);
10771            timedeltas.push(Scalar::Timedelta64(case as i64 - 110));
10772            for _ in 1..len {
10773                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
10774                timedeltas.push(match next(&mut seed) % 7 {
10775                    0 => Scalar::Null(NullKind::Null),
10776                    1 => Scalar::Timedelta64(i64::MIN),
10777                    _ => Scalar::Timedelta64(raw),
10778                });
10779            }
10780            assert_median(
10781                case,
10782                "timedelta",
10783                &timedeltas,
10784                expected_timedelta(&timedeltas),
10785            );
10786        }
10787    }
10788
10789    #[test]
10790    fn nanvar_nanstd_nansem_match_numeric_and_timedelta_oracle_k7apg() {
10791        // Differential vs independent variance/std/sem oracles
10792        // (br-frankenpandas-k7apg). Seeded LCG, no mocks.
10793        fn next(seed: &mut u64) -> u64 {
10794            *seed = seed
10795                .wrapping_mul(2862933555777941757)
10796                .wrapping_add(3037000493);
10797            *seed
10798        }
10799
10800        fn numeric_samples(values: &[Scalar]) -> Vec<f64> {
10801            values
10802                .iter()
10803                .filter(|value| !value.is_missing())
10804                .filter_map(|value| value.to_f64().ok())
10805                .collect()
10806        }
10807
10808        fn timedelta_samples(values: &[Scalar]) -> Vec<f64> {
10809            values
10810                .iter()
10811                .filter_map(|value| match value {
10812                    Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
10813                    _ => None,
10814                })
10815                .collect()
10816        }
10817
10818        fn reductions_from_samples(samples: &[f64], ddof: usize) -> Option<(f64, f64, f64)> {
10819            if samples.len() <= ddof {
10820                return None;
10821            }
10822            let mean = samples.iter().sum::<f64>() / samples.len() as f64;
10823            let sum_sq = samples
10824                .iter()
10825                .map(|value| (value - mean).powi(2))
10826                .sum::<f64>();
10827            let var = sum_sq / (samples.len() - ddof) as f64;
10828            let std = var.sqrt();
10829            let sem = std / (samples.len() as f64).sqrt();
10830            Some((var, std, sem))
10831        }
10832
10833        fn expected_numeric(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
10834            let samples = numeric_samples(values);
10835            let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
10836                let missing = Scalar::Null(NullKind::NaN);
10837                return (missing.clone(), missing.clone(), missing);
10838            };
10839            (
10840                Scalar::Float64(var),
10841                Scalar::Float64(std),
10842                Scalar::Float64(sem),
10843            )
10844        }
10845
10846        fn expected_timedelta(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
10847            let samples = timedelta_samples(values);
10848            if samples.is_empty() {
10849                let missing = Scalar::Timedelta64(Timedelta::NAT);
10850                return (missing.clone(), missing.clone(), missing);
10851            }
10852            let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
10853                let missing = Scalar::Timedelta64(i64::MIN);
10854                return (missing.clone(), missing.clone(), missing);
10855            };
10856            (
10857                Scalar::Timedelta64(var as i64),
10858                Scalar::Timedelta64(std as i64),
10859                Scalar::Timedelta64(sem as i64),
10860            )
10861        }
10862
10863        fn assert_reductions(
10864            case: usize,
10865            family: &str,
10866            values: &[Scalar],
10867            ddof: usize,
10868            expected: (Scalar, Scalar, Scalar),
10869        ) {
10870            let (expected_var, expected_std, expected_sem) = expected;
10871            let actual_var = super::nanvar(values, ddof);
10872            let actual_std = super::nanstd(values, ddof);
10873            let actual_sem = super::nansem(values, ddof);
10874            assert!(
10875                actual_var.semantic_eq(&expected_var),
10876                "case={case} family={family} ddof={ddof}: expected var {expected_var:?}, got {actual_var:?} for {values:?}"
10877            );
10878            assert!(
10879                actual_std.semantic_eq(&expected_std),
10880                "case={case} family={family} ddof={ddof}: expected std {expected_std:?}, got {actual_std:?} for {values:?}"
10881            );
10882            assert!(
10883                actual_sem.semantic_eq(&expected_sem),
10884                "case={case} family={family} ddof={ddof}: expected sem {expected_sem:?}, got {actual_sem:?} for {values:?}"
10885            );
10886        }
10887
10888        let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
10889        assert_reductions(
10890            usize::MAX,
10891            "numeric_all_missing",
10892            &numeric_all_missing,
10893            0,
10894            expected_numeric(&numeric_all_missing, 0),
10895        );
10896
10897        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
10898        assert_reductions(
10899            usize::MAX - 1,
10900            "timedelta_all_missing",
10901            &td_all_missing,
10902            0,
10903            expected_timedelta(&td_all_missing, 0),
10904        );
10905
10906        let mut seed = 0x7a11_c0de_5eed_0421_u64;
10907        for case in 0..240 {
10908            let len = (next(&mut seed) % 83 + 1) as usize;
10909            let ddof = (next(&mut seed) % 4) as usize;
10910
10911            let mut numeric = Vec::with_capacity(len);
10912            numeric.push(Scalar::Float64(case as f64 / 13.0));
10913            for _ in 1..len {
10914                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
10915                numeric.push(match next(&mut seed) % 8 {
10916                    0 => Scalar::Null(NullKind::Null),
10917                    1 => Scalar::Null(NullKind::NaN),
10918                    2 => Scalar::Float64(f64::NAN),
10919                    3 => Scalar::Bool(raw & 1 == 0),
10920                    4 => Scalar::Int64(raw % 251),
10921                    5 => Scalar::Float64(raw as f64 / 73.0),
10922                    6 => Scalar::Float64(0.0),
10923                    _ => Scalar::Float64(-0.0),
10924                });
10925            }
10926            assert_reductions(
10927                case,
10928                "numeric",
10929                &numeric,
10930                ddof,
10931                expected_numeric(&numeric, ddof),
10932            );
10933
10934            let mut timedeltas = Vec::with_capacity(len);
10935            timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
10936            for _ in 1..len {
10937                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
10938                timedeltas.push(match next(&mut seed) % 7 {
10939                    0 => Scalar::Null(NullKind::Null),
10940                    1 => Scalar::Timedelta64(i64::MIN),
10941                    _ => Scalar::Timedelta64(raw),
10942                });
10943            }
10944            assert_reductions(
10945                case,
10946                "timedelta",
10947                &timedeltas,
10948                ddof,
10949                expected_timedelta(&timedeltas, ddof),
10950            );
10951        }
10952    }
10953
10954    #[test]
10955    fn nanvar_population() {
10956        let vals = vec![
10957            Scalar::Float64(2.0),
10958            Scalar::Float64(4.0),
10959            Scalar::Float64(4.0),
10960            Scalar::Float64(4.0),
10961            Scalar::Float64(5.0),
10962            Scalar::Float64(5.0),
10963            Scalar::Float64(7.0),
10964            Scalar::Float64(9.0),
10965        ];
10966        let var = super::nanvar(&vals, 0);
10967        assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
10968        if let Scalar::Float64(v) = var {
10969            assert!((v - 4.0).abs() < 1e-10);
10970        }
10971    }
10972
10973    #[test]
10974    fn nanvar_sample_ddof1() {
10975        let vals = vec![
10976            Scalar::Float64(2.0),
10977            Scalar::Float64(4.0),
10978            Scalar::Float64(4.0),
10979            Scalar::Float64(4.0),
10980            Scalar::Float64(5.0),
10981            Scalar::Float64(5.0),
10982            Scalar::Float64(7.0),
10983            Scalar::Float64(9.0),
10984        ];
10985        let var = super::nanvar(&vals, 1);
10986        assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
10987        if let Scalar::Float64(v) = var {
10988            assert!((v - 32.0 / 7.0).abs() < 1e-10);
10989        }
10990    }
10991
10992    #[test]
10993    fn nanvar_insufficient_values_returns_nan() {
10994        let vals = vec![Scalar::Float64(5.0)];
10995        assert!(super::nanvar(&vals, 1).is_missing());
10996    }
10997
10998    #[test]
10999    fn nanstd_is_sqrt_of_var() {
11000        let vals = vec![
11001            Scalar::Float64(2.0),
11002            Scalar::Float64(4.0),
11003            Scalar::Float64(4.0),
11004            Scalar::Float64(4.0),
11005            Scalar::Float64(5.0),
11006            Scalar::Float64(5.0),
11007            Scalar::Float64(7.0),
11008            Scalar::Float64(9.0),
11009        ];
11010        let std = super::nanstd(&vals, 0);
11011        assert!(matches!(std, Scalar::Float64(_)), "expected Float64");
11012        if let Scalar::Float64(v) = std {
11013            assert!((v - 2.0).abs() < 1e-10);
11014        }
11015    }
11016
11017    #[test]
11018    fn nanmedian_timedelta64_preserves_dtype_j8ntk() {
11019        // Per br-frankenpandas-j8ntk: pandas td_series.median() returns
11020        // Timedelta64; was silently NaN before via collect_finite.
11021        let one_hour = 3_600 * 1_000_000_000_i64;
11022        let vals = vec![
11023            Scalar::Timedelta64(one_hour),
11024            Scalar::Timedelta64(2 * one_hour),
11025            Scalar::Timedelta64(3 * one_hour),
11026        ];
11027        assert_eq!(super::nanmedian(&vals), Scalar::Timedelta64(2 * one_hour));
11028    }
11029
11030    #[test]
11031    fn nanstd_timedelta64_preserves_dtype_j8ntk() {
11032        // Per br-frankenpandas-j8ntk: pandas td_series.std() returns
11033        // Timedelta64. Check Timedelta64 output and reasonable magnitude
11034        // for population std of [1h, 2h, 3h] = sqrt(2/3) * 1h.
11035        let one_hour: i64 = 3_600 * 1_000_000_000;
11036        let vals = vec![
11037            Scalar::Timedelta64(one_hour),
11038            Scalar::Timedelta64(2 * one_hour),
11039            Scalar::Timedelta64(3 * one_hour),
11040        ];
11041        let std = super::nanstd(&vals, 0);
11042        match std {
11043            Scalar::Timedelta64(ns) => {
11044                let expected = (2.0_f64 / 3.0).sqrt() * one_hour as f64;
11045                assert!(
11046                    (ns as f64 - expected).abs() < 1e6,
11047                    "expected ~{expected} ns, got {ns}"
11048                );
11049            }
11050            other => panic!("expected Timedelta64, got {other:?}"),
11051        }
11052    }
11053
11054    #[test]
11055    fn nanstd_nansem_timedelta64_insufficient_returns_nat_j8ntk() {
11056        let one_hour = 3_600 * 1_000_000_000_i64;
11057        let vals = vec![Scalar::Timedelta64(one_hour)];
11058        // ddof=1 with n=1 → underflow, returns NaT
11059        match super::nanstd(&vals, 1) {
11060            Scalar::Timedelta64(v) => assert_eq!(v, Timedelta::NAT),
11061            other => panic!("expected Timedelta64 NAT, got {other:?}"),
11062        }
11063        match super::nansem(&vals, 1) {
11064            Scalar::Timedelta64(v) => assert_eq!(v, Timedelta::NAT),
11065            other => panic!("expected Timedelta64 NAT, got {other:?}"),
11066        }
11067    }
11068
11069    #[test]
11070    fn nanops_with_mixed_types() {
11071        let vals = vec![
11072            Scalar::Bool(true),
11073            Scalar::Int64(3),
11074            Scalar::Float64(6.0),
11075            Scalar::Null(NullKind::Null),
11076        ];
11077        assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
11078        assert_eq!(super::nancount(&vals), Scalar::Int64(3));
11079    }
11080
11081    #[test]
11082    fn nanops_all_missing_returns_identity() {
11083        let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
11084        assert_eq!(super::nansum(&vals), Scalar::Float64(0.0));
11085        assert!(super::nanmean(&vals).is_missing());
11086        assert!(super::nanmedian(&vals).is_missing());
11087        assert!(super::nanvar(&vals, 0).is_missing());
11088        assert!(super::nanstd(&vals, 0).is_missing());
11089    }
11090
11091    // ── Timedelta tests ────────────────────────────────────────────────
11092
11093    #[test]
11094    fn timedelta_parse_simple_units() {
11095        use super::Timedelta;
11096        assert_eq!(Timedelta::parse("1d").unwrap(), Timedelta::NANOS_PER_DAY);
11097        assert_eq!(
11098            Timedelta::parse("2h").unwrap(),
11099            2 * Timedelta::NANOS_PER_HOUR
11100        );
11101        assert_eq!(
11102            Timedelta::parse("30m").unwrap(),
11103            30 * Timedelta::NANOS_PER_MIN
11104        );
11105        assert_eq!(
11106            Timedelta::parse("45s").unwrap(),
11107            45 * Timedelta::NANOS_PER_SEC
11108        );
11109        assert_eq!(
11110            Timedelta::parse("100ms").unwrap(),
11111            100 * Timedelta::NANOS_PER_MILLI
11112        );
11113        assert_eq!(
11114            Timedelta::parse("500us").unwrap(),
11115            500 * Timedelta::NANOS_PER_MICRO
11116        );
11117        assert_eq!(Timedelta::parse("1000ns").unwrap(), 1000);
11118    }
11119
11120    #[test]
11121    fn timedelta_parse_zero_valued_compound() {
11122        use super::Timedelta;
11123        // Each of these is a Timedelta of zero, not a parse failure. Verified
11124        // against live pandas 2.2.3: every form below yields
11125        // `Timedelta('0 days 00:00:00')`. A guard in `parse_compound` used to
11126        // reject them all except the bare "0", which made
11127        // `to_timedelta(["10 seconds", "1 second", "0 seconds"])` raise on the
11128        // third element only.
11129        for s in [
11130            "0 seconds",
11131            "0 second",
11132            "0 sec",
11133            "0s",
11134            "0 days",
11135            "0d",
11136            "0 hours",
11137            "0.0 hours",
11138            "0 minutes",
11139            "0ms",
11140            "0us",
11141            "0ns",
11142            "0",
11143            "0 days 0 seconds",
11144        ] {
11145            assert_eq!(Timedelta::parse(s).unwrap(), 0, "parse({s:?}) should be 0");
11146        }
11147        // The sign is carried by the caller, so a negative zero is still zero.
11148        assert_eq!(Timedelta::parse("-0 seconds").unwrap(), 0);
11149        // Removing the guard must NOT admit garbage: an unknown unit and a
11150        // missing number are still rejected inside the loop.
11151        assert!(Timedelta::parse("0 fortnights").is_err());
11152        assert!(Timedelta::parse("seconds").is_err());
11153    }
11154
11155    #[test]
11156    fn timedelta_parse_compound() {
11157        use super::Timedelta;
11158        let expected = Timedelta::NANOS_PER_DAY
11159            + 2 * Timedelta::NANOS_PER_HOUR
11160            + 30 * Timedelta::NANOS_PER_MIN;
11161        assert_eq!(Timedelta::parse("1d 2h 30m").unwrap(), expected);
11162        assert_eq!(Timedelta::parse("1d2h30m").unwrap(), expected);
11163    }
11164
11165    #[test]
11166    fn timedelta_parse_iso8601_matches_pandas_tdiso() {
11167        use super::Timedelta;
11168        // Verified vs pandas 2.2.3 Timedelta(...).value.
11169        assert_eq!(Timedelta::parse("P1DT2H3M4S").unwrap(), 93_784_000_000_000);
11170        assert_eq!(Timedelta::parse("PT1H").unwrap(), 3_600_000_000_000);
11171        assert_eq!(Timedelta::parse("PT1H30M").unwrap(), 5_400_000_000_000);
11172        assert_eq!(Timedelta::parse("P1D").unwrap(), 86_400_000_000_000);
11173        assert_eq!(Timedelta::parse("P2W").unwrap(), 1_209_600_000_000_000);
11174        assert_eq!(Timedelta::parse("PT0.5S").unwrap(), 500_000_000);
11175        // pandas quirks: T ignored, M is minutes everywhere, units in any order.
11176        assert_eq!(Timedelta::parse("P1M").unwrap(), 60_000_000_000);
11177        assert_eq!(Timedelta::parse("P1H").unwrap(), 3_600_000_000_000);
11178        assert_eq!(Timedelta::parse("PT1D").unwrap(), 86_400_000_000_000);
11179        assert_eq!(Timedelta::parse("P1D1H").unwrap(), 90_000_000_000_000);
11180        assert_eq!(Timedelta::parse("-P1DT2H").unwrap(), -93_600_000_000_000);
11181        // Rejected like pandas: years, lowercase, bare P/PT.
11182        assert!(Timedelta::parse("P1Y").is_err());
11183        assert!(Timedelta::parse("p1d").is_err());
11184        assert!(Timedelta::parse("P").is_err());
11185        assert!(Timedelta::parse("PT").is_err());
11186    }
11187
11188    #[test]
11189    fn timedelta_parse_time_format() {
11190        use super::Timedelta;
11191        let expected = Timedelta::NANOS_PER_HOUR
11192            + 30 * Timedelta::NANOS_PER_MIN
11193            + 45 * Timedelta::NANOS_PER_SEC;
11194        assert_eq!(Timedelta::parse("01:30:45").unwrap(), expected);
11195    }
11196
11197    #[test]
11198    fn timedelta_parse_time_fraction_rejects_unicode_without_panic() {
11199        use super::{Timedelta, TimedeltaError};
11200        let err = Timedelta::parse("00:00:00.\u{00e9}\u{00e9}\u{00e9}\u{00e9}\u{00e9}")
11201            .expect_err("non-ASCII fractional seconds must reject");
11202        assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
11203    }
11204
11205    #[test]
11206    fn timedelta_parse_time_format_rejects_overflow_without_panic() {
11207        use super::{Timedelta, TimedeltaError};
11208        let err = Timedelta::parse("9223372036854775807:00")
11209            .expect_err("oversized hour component must reject");
11210        assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
11211    }
11212
11213    #[test]
11214    fn timedelta_parse_rejects_huge_value_overflow_zw3mg() {
11215        // Per br-frankenpandas-zw3mg: the compound parser used a raw
11216        // `as i64` cast that silently saturated to i64::MAX when the
11217        // product of (decimal-digit f64) × unit multiplier overflows.
11218        // Use a large literal (no scientific notation — the lexer only
11219        // accepts digits, '.', '-'). 1e18 days × NANOS_PER_DAY (~8.64e13)
11220        // overflows i64.
11221        use super::{Timedelta, TimedeltaError};
11222        let huge = format!("{} days", "9".repeat(18));
11223        assert!(matches!(
11224            Timedelta::parse(&huge).expect_err("9...(18 9s) days must overflow"),
11225            TimedeltaError::Overflow
11226        ));
11227    }
11228
11229    #[test]
11230    fn timedelta_parse_nat() {
11231        use super::Timedelta;
11232        assert_eq!(Timedelta::parse("NaT").unwrap(), Timedelta::NAT);
11233        assert_eq!(Timedelta::parse("nat").unwrap(), Timedelta::NAT);
11234    }
11235
11236    #[test]
11237    fn timedelta_parse_negative() {
11238        use super::Timedelta;
11239        assert_eq!(Timedelta::parse("-1d").unwrap(), -Timedelta::NANOS_PER_DAY);
11240    }
11241
11242    #[test]
11243    fn timedelta_components() {
11244        use super::Timedelta;
11245        let nanos = Timedelta::NANOS_PER_DAY
11246            + Timedelta::NANOS_PER_HOUR
11247            + Timedelta::NANOS_PER_MIN
11248            + Timedelta::NANOS_PER_SEC
11249            + Timedelta::NANOS_PER_MILLI
11250            + 2 * Timedelta::NANOS_PER_MICRO
11251            + 3;
11252        let comp = Timedelta::components(nanos);
11253        assert_eq!(comp.days, 1);
11254        assert_eq!(comp.hours, 1);
11255        assert_eq!(comp.minutes, 1);
11256        assert_eq!(comp.seconds, 1);
11257        assert_eq!(comp.milliseconds, 1);
11258        assert_eq!(comp.microseconds, 2);
11259        assert_eq!(comp.nanoseconds, 3);
11260    }
11261
11262    #[test]
11263    fn timedelta_negative_components_floor_div() {
11264        use super::Timedelta;
11265        // pandas floor-normalizes negative timedeltas: pd.Timedelta(-1,'s') has
11266        // days=-1, seconds=86399, components=(-1, 23, 59, 59, 0, 0, 0).
11267        let neg_1s = -Timedelta::NANOS_PER_SEC;
11268        assert_eq!(Timedelta::days(neg_1s), Some(-1));
11269        assert_eq!(Timedelta::seconds(neg_1s), Some(86399));
11270        assert_eq!(Timedelta::microseconds(neg_1s), Some(0));
11271        assert_eq!(Timedelta::nanoseconds(neg_1s), Some(0));
11272        let comp = Timedelta::components(neg_1s);
11273        assert_eq!(
11274            (
11275                comp.days,
11276                comp.hours,
11277                comp.minutes,
11278                comp.seconds,
11279                comp.milliseconds,
11280                comp.microseconds,
11281                comp.nanoseconds
11282            ),
11283            (-1, 23, 59, 59, 0, 0, 0)
11284        );
11285
11286        // pd.Timedelta(-86401,'s'): days=-2, seconds=86399.
11287        let neg = -86_401 * Timedelta::NANOS_PER_SEC;
11288        assert_eq!(Timedelta::days(neg), Some(-2));
11289        assert_eq!(Timedelta::seconds(neg), Some(86399));
11290    }
11291
11292    /// br-frankenpandas-timedelta-nat-days-returns-zero-406ni.
11293    ///
11294    /// All four component helpers returned `0` for `NaT`, one of them behind a
11295    /// comment asserting "pandas returns 0 for NaT.days (no error)". MEASURED,
11296    /// live pandas 2.2.3: `pd.NaT.days` is **nan**, and
11297    /// `pd.to_timedelta([1, None, -1], unit='s').dt.days` is float64
11298    /// `[0.0, nan, -1.0]`.
11299    ///
11300    /// ⚠️ `0` IS THE ONE WRONG ANSWER THAT LOOKS RIGHT. It is a legal value for
11301    /// three of these four accessors — `seconds`, `microseconds` and
11302    /// `nanoseconds` all legitimately return 0 for a whole number of days — so a
11303    /// caller cannot distinguish "midnight" from "missing" by inspecting the
11304    /// result. That is the fail-open-as-plausible-data class, and it is why the
11305    /// fix is the return TYPE and not a corrected comment.
11306    #[test]
11307    fn timedelta_components_are_missing_for_nat_not_zero_406ni() {
11308        use super::Timedelta;
11309        assert_eq!(Timedelta::days(Timedelta::NAT), None);
11310        assert_eq!(Timedelta::seconds(Timedelta::NAT), None);
11311        assert_eq!(Timedelta::microseconds(Timedelta::NAT), None);
11312        assert_eq!(Timedelta::nanoseconds(Timedelta::NAT), None);
11313
11314        // NON-VACUITY: a whole number of days legitimately answers 0 for the
11315        // three sub-day components, so `Some(0)` and `None` must be reachable
11316        // from the same accessor. A test that only checked NaT could pass
11317        // against a helper that returned `None` unconditionally.
11318        let one_day = Timedelta::NANOS_PER_DAY;
11319        assert_eq!(Timedelta::days(one_day), Some(1));
11320        assert_eq!(Timedelta::seconds(one_day), Some(0));
11321        assert_eq!(Timedelta::microseconds(one_day), Some(0));
11322        assert_eq!(Timedelta::nanoseconds(one_day), Some(0));
11323    }
11324
11325    #[test]
11326    fn timedelta_total_seconds() {
11327        use super::Timedelta;
11328        let nanos = 90_000_000_000i64; // 90 seconds
11329        assert!((Timedelta::total_seconds(nanos) - 90.0).abs() < 1e-9);
11330        assert!(Timedelta::total_seconds(Timedelta::NAT).is_nan());
11331    }
11332
11333    #[test]
11334    fn timedelta_format_basic() {
11335        use super::Timedelta;
11336        assert_eq!(Timedelta::format(Timedelta::NAT), "NaT");
11337        assert_eq!(
11338            Timedelta::format(Timedelta::NANOS_PER_DAY),
11339            "1 days 00:00:00"
11340        );
11341        assert_eq!(
11342            Timedelta::format(Timedelta::NANOS_PER_DAY + 2 * Timedelta::NANOS_PER_HOUR),
11343            "1 days 02:00:00"
11344        );
11345    }
11346
11347    #[test]
11348    fn timedelta_format_subsecond_matches_pandas() {
11349        use super::Timedelta;
11350        // pandas str(Timedelta) uses 6 fractional digits (microseconds) unless a
11351        // sub-microsecond (nanosecond) component is present, then 9 digits.
11352        // Verified vs live pandas 2.2.3.
11353        assert_eq!(
11354            Timedelta::format(1_500_000_000), // 1.5s
11355            "0 days 00:00:01.500000"
11356        );
11357        assert_eq!(
11358            Timedelta::format(1_000_000), // 1ms
11359            "0 days 00:00:00.001000"
11360        );
11361        assert_eq!(
11362            Timedelta::format(123_456_000), // 123456us
11363            "0 days 00:00:00.123456"
11364        );
11365        // Nanosecond component -> 9 digits.
11366        assert_eq!(
11367            Timedelta::format(500), // 500ns
11368            "0 days 00:00:00.000000500"
11369        );
11370        assert_eq!(Timedelta::format(123_456_789), "0 days 00:00:00.123456789");
11371    }
11372
11373    #[test]
11374    fn timedelta_format_negative_uses_python_borrow_form() {
11375        use super::Timedelta;
11376        // pandas/Python normalize negatives via floor division: the days count
11377        // goes negative, the time remainder stays non-negative, and a '+' joins
11378        // them. Verified vs live pandas 2.2.3.
11379        assert_eq!(Timedelta::format(-1_000_000_000), "-1 days +23:59:59");
11380        assert_eq!(
11381            Timedelta::format(-Timedelta::NANOS_PER_DAY),
11382            "-1 days +00:00:00"
11383        );
11384        assert_eq!(
11385            Timedelta::format(-25 * Timedelta::NANOS_PER_HOUR),
11386            "-2 days +23:00:00"
11387        );
11388        assert_eq!(
11389            Timedelta::format(-1_500_000_000),
11390            "-1 days +23:59:58.500000"
11391        );
11392        assert_eq!(Timedelta::format(-500), "-1 days +23:59:59.999999500");
11393        assert_eq!(Timedelta::format(-1), "-1 days +23:59:59.999999999");
11394    }
11395
11396    #[test]
11397    #[ignore = "foreground release attribution harness"]
11398    fn timedelta_format_single_buffer_ab_5ro9h() {
11399        use std::{hint::black_box, time::Instant};
11400
11401        use super::Timedelta;
11402
11403        fn former(nanos: i64) -> String {
11404            if nanos == Timedelta::NAT {
11405                return "NaT".to_string();
11406            }
11407
11408            let days = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
11409            let rem = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
11410            let hours = rem / Timedelta::NANOS_PER_HOUR;
11411            let minutes = (rem % Timedelta::NANOS_PER_HOUR) / Timedelta::NANOS_PER_MIN;
11412            let seconds = (rem % Timedelta::NANOS_PER_MIN) / Timedelta::NANOS_PER_SEC;
11413            let frac = rem % Timedelta::NANOS_PER_SEC;
11414
11415            let time_part = format!("{hours:02}:{minutes:02}:{seconds:02}");
11416            let sep = if days < 0 { "+" } else { "" };
11417            if frac > 0 {
11418                if frac % 1_000 == 0 {
11419                    format!("{days} days {sep}{time_part}.{:06}", frac / 1_000)
11420                } else {
11421                    format!("{days} days {sep}{time_part}.{frac:09}")
11422                }
11423            } else {
11424                format!("{days} days {sep}{time_part}")
11425            }
11426        }
11427
11428        fn candidate(nanos: i64) -> String {
11429            Timedelta::format(nanos)
11430        }
11431
11432        fn elapsed(values: &[i64], format: fn(i64) -> String) -> u128 {
11433            let started = Instant::now();
11434            let mut digest = 0_usize;
11435            for &value in values {
11436                digest = digest.wrapping_add(black_box(format(black_box(value))).len());
11437            }
11438            black_box(digest);
11439            started.elapsed().as_nanos()
11440        }
11441
11442        fn median(samples: &mut [u128]) -> u128 {
11443            samples.sort_unstable();
11444            samples[samples.len() / 2]
11445        }
11446
11447        let mut seed = 0x8f42_67a1_b3d9_c50e_u64;
11448        let values: Vec<i64> = (0..16_384)
11449            .map(|i| {
11450                seed = seed
11451                    .wrapping_mul(6_364_136_223_846_793_005)
11452                    .wrapping_add(1_442_695_040_888_963_407);
11453                let magnitude = (seed & i64::MAX as u64) as i64;
11454                match i % 4 {
11455                    0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
11456                    1 => magnitude,
11457                    2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
11458                    _ => -magnitude,
11459                }
11460            })
11461            .collect();
11462
11463        for &value in &[
11464            Timedelta::NAT,
11465            0,
11466            1,
11467            -1,
11468            Timedelta::NANOS_PER_DAY,
11469            -Timedelta::NANOS_PER_DAY,
11470            i64::MAX,
11471            i64::MIN + 1,
11472        ] {
11473            assert_eq!(former(value), candidate(value));
11474        }
11475        for &value in &values {
11476            assert_eq!(former(value), candidate(value));
11477        }
11478
11479        for _ in 0..2 {
11480            black_box(elapsed(&values, former));
11481            black_box(elapsed(&values, candidate));
11482        }
11483
11484        let mut former_samples = Vec::with_capacity(18);
11485        let mut candidate_samples = Vec::with_capacity(18);
11486        for block in 0_usize..9 {
11487            if block.is_multiple_of(2) {
11488                former_samples.push(elapsed(&values, former));
11489                candidate_samples.push(elapsed(&values, candidate));
11490                candidate_samples.push(elapsed(&values, candidate));
11491                former_samples.push(elapsed(&values, former));
11492            } else {
11493                candidate_samples.push(elapsed(&values, candidate));
11494                former_samples.push(elapsed(&values, former));
11495                former_samples.push(elapsed(&values, former));
11496                candidate_samples.push(elapsed(&values, candidate));
11497            }
11498        }
11499
11500        let former_p50 = median(&mut former_samples);
11501        let candidate_p50 = median(&mut candidate_samples);
11502        eprintln!(
11503            "TIMEDELTA_FORMAT_SINGLE_BUFFER_AB rows={} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
11504            values.len(),
11505            former_p50 as f64 / candidate_p50 as f64,
11506        );
11507        eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB former_samples_ns={former_samples:?}");
11508        eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB candidate_samples_ns={candidate_samples:?}");
11509    }
11510
11511    #[test]
11512    fn timedelta_isoformat_basic() {
11513        use super::Timedelta;
11514        assert_eq!(Timedelta::isoformat(Timedelta::NAT), "NaT");
11515        assert_eq!(Timedelta::isoformat(0), "P0DT0H0M0S");
11516        assert_eq!(Timedelta::isoformat(Timedelta::NANOS_PER_DAY), "P1DT0H0M0S");
11517        assert_eq!(
11518            Timedelta::isoformat(
11519                Timedelta::NANOS_PER_DAY
11520                    + 2 * Timedelta::NANOS_PER_HOUR
11521                    + 30 * Timedelta::NANOS_PER_MIN
11522                    + 45 * Timedelta::NANOS_PER_SEC
11523            ),
11524            "P1DT2H30M45S"
11525        );
11526        assert_eq!(
11527            Timedelta::isoformat(Timedelta::NANOS_PER_SEC + 500_000_000),
11528            "P0DT0H0M1.5S"
11529        );
11530        assert_eq!(
11531            Timedelta::isoformat(-(Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR)),
11532            "-P1DT1H0M0S"
11533        );
11534    }
11535
11536    #[test]
11537    #[ignore = "foreground release attribution harness"]
11538    fn timedelta_isoformat_single_buffer_ab_7jra1() {
11539        use std::{hint::black_box, time::Instant};
11540
11541        use super::Timedelta;
11542
11543        fn former_impl(nanos: i64) -> String {
11544            if nanos == Timedelta::NAT {
11545                return "NaT".to_string();
11546            }
11547
11548            let negative = nanos < 0;
11549            let abs_nanos = nanos.saturating_abs();
11550            let days = abs_nanos / Timedelta::NANOS_PER_DAY;
11551            let remaining = abs_nanos % Timedelta::NANOS_PER_DAY;
11552            let hours = remaining / Timedelta::NANOS_PER_HOUR;
11553            let remaining = remaining % Timedelta::NANOS_PER_HOUR;
11554            let minutes = remaining / Timedelta::NANOS_PER_MIN;
11555            let remaining = remaining % Timedelta::NANOS_PER_MIN;
11556            let seconds = remaining / Timedelta::NANOS_PER_SEC;
11557            let sub_sec_nanos = remaining % Timedelta::NANOS_PER_SEC;
11558
11559            let mut result = String::new();
11560            if negative {
11561                result.push('-');
11562            }
11563
11564            result.push_str(&format!("P{days}DT{hours}H{minutes}M"));
11565
11566            if sub_sec_nanos == 0 {
11567                result.push_str(&format!("{seconds}S"));
11568            } else {
11569                let frac = format!("{sub_sec_nanos:09}");
11570                let trimmed = frac.trim_end_matches('0');
11571                result.push_str(&format!("{seconds}.{trimmed}S"));
11572            }
11573
11574            result
11575        }
11576
11577        fn elapsed(values: &[i64], format: impl Fn(i64) -> String) -> u128 {
11578            let start = Instant::now();
11579            let mut digest = 0_usize;
11580            for &value in values {
11581                digest = digest.wrapping_add(black_box(format(black_box(value))).len());
11582            }
11583            black_box(digest);
11584            start.elapsed().as_nanos()
11585        }
11586
11587        fn median(values: &mut [u128]) -> u128 {
11588            values.sort_unstable();
11589            values[values.len() / 2]
11590        }
11591
11592        let mut seed = 0x7d5a_4c31_91e2_b607_u64;
11593        let values: Vec<i64> = (0..16_384)
11594            .map(|i| {
11595                seed = seed
11596                    .wrapping_mul(6_364_136_223_846_793_005)
11597                    .wrapping_add(1_442_695_040_888_963_407);
11598                let magnitude =
11599                    (seed & i64::MAX as u64) as i64 % (3_650 * Timedelta::NANOS_PER_DAY);
11600                match i % 4 {
11601                    0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
11602                    1 => magnitude,
11603                    2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
11604                    _ => -magnitude,
11605                }
11606            })
11607            .collect();
11608
11609        for &value in &[
11610            Timedelta::NAT,
11611            0,
11612            1,
11613            -1,
11614            Timedelta::NANOS_PER_DAY,
11615            i64::MAX,
11616            i64::MIN + 1,
11617        ] {
11618            assert_eq!(former_impl(value), Timedelta::isoformat(value));
11619        }
11620        for &value in &values {
11621            assert_eq!(former_impl(value), Timedelta::isoformat(value));
11622        }
11623
11624        for _ in 0..2 {
11625            black_box(elapsed(&values, former_impl));
11626            black_box(elapsed(&values, Timedelta::isoformat));
11627        }
11628
11629        let mut former = Vec::with_capacity(18);
11630        let mut candidate = Vec::with_capacity(18);
11631        for block in 0..9 {
11632            if block % 2 == 0 {
11633                former.push(elapsed(&values, former_impl));
11634                candidate.push(elapsed(&values, Timedelta::isoformat));
11635                candidate.push(elapsed(&values, Timedelta::isoformat));
11636                former.push(elapsed(&values, former_impl));
11637            } else {
11638                candidate.push(elapsed(&values, Timedelta::isoformat));
11639                former.push(elapsed(&values, former_impl));
11640                former.push(elapsed(&values, former_impl));
11641                candidate.push(elapsed(&values, Timedelta::isoformat));
11642            }
11643        }
11644
11645        let former_p50 = median(&mut former);
11646        let candidate_p50 = median(&mut candidate);
11647        eprintln!(
11648            "ISOFORMAT_AB rows={} former_p50_ns={} candidate_p50_ns={} ratio={:.6} former_ns_per_row={:.3} candidate_ns_per_row={:.3}",
11649            values.len(),
11650            former_p50,
11651            candidate_p50,
11652            former_p50 as f64 / candidate_p50 as f64,
11653            former_p50 as f64 / values.len() as f64,
11654            candidate_p50 as f64 / values.len() as f64,
11655        );
11656        eprintln!("ISOFORMAT_AB former_samples_ns={former:?}");
11657        eprintln!("ISOFORMAT_AB candidate_samples_ns={candidate:?}");
11658    }
11659
11660    #[test]
11661    fn timedelta_floor_ceil_round() {
11662        use super::Timedelta;
11663        let nanos = Timedelta::NANOS_PER_HOUR + 30 * Timedelta::NANOS_PER_MIN;
11664
11665        // floor: rounds down
11666        assert_eq!(Timedelta::floor(nanos, "h"), Timedelta::NANOS_PER_HOUR);
11667        assert_eq!(Timedelta::floor(nanos, "d"), 0);
11668
11669        // ceil: rounds up
11670        assert_eq!(Timedelta::ceil(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
11671        assert_eq!(Timedelta::ceil(nanos, "d"), Timedelta::NANOS_PER_DAY);
11672
11673        // round: rounds to nearest (banker's rounding on tie)
11674        assert_eq!(Timedelta::round(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
11675
11676        // NaT preserved
11677        assert_eq!(Timedelta::floor(Timedelta::NAT, "h"), Timedelta::NAT);
11678        assert_eq!(Timedelta::ceil(Timedelta::NAT, "h"), Timedelta::NAT);
11679        assert_eq!(Timedelta::round(Timedelta::NAT, "h"), Timedelta::NAT);
11680
11681        // Invalid freq returns NAT
11682        assert_eq!(Timedelta::floor(nanos, "invalid"), Timedelta::NAT);
11683    }
11684
11685    #[test]
11686    fn timedelta_floor_ceil_negative_use_euclidean_rounding_t79yh() {
11687        use super::Timedelta;
11688
11689        assert_eq!(
11690            Timedelta::floor(-1, "s"),
11691            -Timedelta::NANOS_PER_SEC,
11692            "floor(-1ns, 1s)"
11693        );
11694        assert_eq!(Timedelta::ceil(-1, "s"), 0, "ceil(-1ns, 1s)");
11695        assert_eq!(
11696            Timedelta::floor(-1_500_000_000, "s"),
11697            -2 * Timedelta::NANOS_PER_SEC
11698        );
11699        assert_eq!(
11700            Timedelta::ceil(-1_500_000_000, "s"),
11701            -Timedelta::NANOS_PER_SEC
11702        );
11703        assert_eq!(
11704            Timedelta::floor(-Timedelta::NANOS_PER_SEC, "s"),
11705            -Timedelta::NANOS_PER_SEC
11706        );
11707        assert_eq!(
11708            Timedelta::ceil(-Timedelta::NANOS_PER_SEC, "s"),
11709            -Timedelta::NANOS_PER_SEC
11710        );
11711        assert_eq!(
11712            Timedelta::floor(1_500_000_000, "s"),
11713            Timedelta::NANOS_PER_SEC
11714        );
11715        assert_eq!(
11716            Timedelta::ceil(1_500_000_000, "s"),
11717            2 * Timedelta::NANOS_PER_SEC
11718        );
11719    }
11720
11721    #[test]
11722    fn timedelta_scalar_dtype() {
11723        let td = Scalar::Timedelta64(86_400_000_000_000);
11724        assert_eq!(td.dtype(), DType::Timedelta64);
11725    }
11726
11727    #[test]
11728    fn timedelta_scalar_is_missing() {
11729        use super::Timedelta;
11730        let valid = Scalar::Timedelta64(1000);
11731        let nat = Scalar::Timedelta64(Timedelta::NAT);
11732        assert!(!valid.is_missing());
11733        assert!(nat.is_missing());
11734    }
11735
11736    #[test]
11737    fn dtype_utf8_deserializes_legacy_aliases() {
11738        let dtype: DType = serde_json::from_str("\"str\"").unwrap();
11739        assert_eq!(dtype, DType::Utf8);
11740
11741        let dtype: DType = serde_json::from_str("\"string\"").unwrap();
11742        assert_eq!(dtype, DType::Utf8);
11743    }
11744
11745    #[test]
11746    fn datetime64_dtype_carries_timezone_00ze3() {
11747        let naive = DType::datetime64_naive();
11748        assert_eq!(naive.timezone(), None);
11749        assert_eq!(naive.display_name(), "datetime64[ns]");
11750
11751        let aware = DType::datetime64_tz("America/New_York");
11752        assert_eq!(aware.timezone(), Some("America/New_York"));
11753        assert_eq!(aware.display_name(), "datetime64[ns, America/New_York]");
11754        assert_ne!(aware, naive, "timezone must participate in dtype identity");
11755
11756        let json = serde_json::to_string(&aware).expect("serialize timezone dtype");
11757        assert_eq!(
11758            serde_json::from_str::<DType>(&json).expect("deserialize timezone dtype"),
11759            aware
11760        );
11761    }
11762
11763    #[test]
11764    fn scalar_utf8_deserializes_legacy_aliases() {
11765        let scalar: Scalar = serde_json::from_str(r#"{"kind":"str","value":"x"}"#).unwrap();
11766        assert_eq!(scalar, Scalar::Utf8("x".to_owned()));
11767
11768        let scalar: Scalar = serde_json::from_str(r#"{"kind":"string","value":"y"}"#).unwrap();
11769        assert_eq!(scalar, Scalar::Utf8("y".to_owned()));
11770    }
11771
11772    #[test]
11773    fn nancumsum_skips_nulls_and_accumulates() {
11774        let values = vec![
11775            Scalar::Float64(1.0),
11776            Scalar::Null(NullKind::NaN),
11777            Scalar::Float64(2.0),
11778            Scalar::Float64(3.0),
11779        ];
11780        let out = super::nancumsum(&values);
11781        assert!(matches!(out[0], Scalar::Float64(v) if (v - 1.0).abs() < 1e-9));
11782        assert!(out[1].is_missing());
11783        assert!(matches!(out[2], Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
11784        assert!(matches!(out[3], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
11785    }
11786
11787    #[test]
11788    fn nancumprod_skips_nulls_and_multiplies() {
11789        let values = vec![
11790            Scalar::Float64(2.0),
11791            Scalar::Null(NullKind::NaN),
11792            Scalar::Float64(3.0),
11793            Scalar::Float64(4.0),
11794        ];
11795        let out = super::nancumprod(&values);
11796        assert!(matches!(out[0], Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
11797        assert!(out[1].is_missing());
11798        assert!(matches!(out[2], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
11799        assert!(matches!(out[3], Scalar::Float64(v) if (v - 24.0).abs() < 1e-9));
11800    }
11801
11802    #[test]
11803    fn nancummax_tracks_running_max() {
11804        let values = vec![
11805            Scalar::Float64(1.0),
11806            Scalar::Float64(3.0),
11807            Scalar::Null(NullKind::NaN),
11808            Scalar::Float64(2.0),
11809            Scalar::Float64(5.0),
11810        ];
11811        let out = super::nancummax(&values);
11812        assert_eq!(out[0], Scalar::Float64(1.0));
11813        assert_eq!(out[1], Scalar::Float64(3.0));
11814        assert!(out[2].is_missing());
11815        assert_eq!(out[3], Scalar::Float64(3.0));
11816        assert_eq!(out[4], Scalar::Float64(5.0));
11817    }
11818
11819    #[test]
11820    fn nancummin_tracks_running_min() {
11821        let values = vec![
11822            Scalar::Float64(5.0),
11823            Scalar::Float64(3.0),
11824            Scalar::Null(NullKind::NaN),
11825            Scalar::Float64(4.0),
11826            Scalar::Float64(1.0),
11827        ];
11828        let out = super::nancummin(&values);
11829        assert_eq!(out[0], Scalar::Float64(5.0));
11830        assert_eq!(out[1], Scalar::Float64(3.0));
11831        assert!(out[2].is_missing());
11832        assert_eq!(out[3], Scalar::Float64(3.0));
11833        assert_eq!(out[4], Scalar::Float64(1.0));
11834    }
11835
11836    #[test]
11837    fn nancumsum_timedelta64_preserves_dtype_x0x91() {
11838        // Per br-frankenpandas-x0x91: pandas td_series.cumsum() returns
11839        // Timedelta64 running sums. Was silently NaN before.
11840        let one_hour = 3_600 * 1_000_000_000_i64;
11841        let values = vec![
11842            Scalar::Timedelta64(one_hour),
11843            Scalar::Timedelta64(2 * one_hour),
11844            Scalar::Timedelta64(3 * one_hour),
11845        ];
11846        let out = super::nancumsum(&values);
11847        assert_eq!(out[0], Scalar::Timedelta64(one_hour));
11848        assert_eq!(out[1], Scalar::Timedelta64(3 * one_hour));
11849        assert_eq!(out[2], Scalar::Timedelta64(6 * one_hour));
11850    }
11851
11852    #[test]
11853    fn nancummax_nancummin_timedelta64_preserves_dtype_x0x91() {
11854        let one_hour = 3_600 * 1_000_000_000_i64;
11855        let values = vec![
11856            Scalar::Timedelta64(2 * one_hour),
11857            Scalar::Timedelta64(5 * one_hour),
11858            Scalar::Timedelta64(one_hour),
11859            Scalar::Timedelta64(3 * one_hour),
11860        ];
11861        let mx = super::nancummax(&values);
11862        assert_eq!(mx[0], Scalar::Timedelta64(2 * one_hour));
11863        assert_eq!(mx[1], Scalar::Timedelta64(5 * one_hour));
11864        assert_eq!(mx[2], Scalar::Timedelta64(5 * one_hour));
11865        assert_eq!(mx[3], Scalar::Timedelta64(5 * one_hour));
11866
11867        let mn = super::nancummin(&values);
11868        assert_eq!(mn[0], Scalar::Timedelta64(2 * one_hour));
11869        assert_eq!(mn[1], Scalar::Timedelta64(2 * one_hour));
11870        assert_eq!(mn[2], Scalar::Timedelta64(one_hour));
11871        assert_eq!(mn[3], Scalar::Timedelta64(one_hour));
11872    }
11873
11874    #[test]
11875    fn nancumulative_timedelta64_skips_nat_x0x91() {
11876        let one_hour = 3_600 * 1_000_000_000_i64;
11877        let values = vec![
11878            Scalar::Timedelta64(one_hour),
11879            Scalar::Timedelta64(Timedelta::NAT),
11880            Scalar::Timedelta64(2 * one_hour),
11881        ];
11882        let cs = super::nancumsum(&values);
11883        assert_eq!(cs[0], Scalar::Timedelta64(one_hour));
11884        assert!(cs[1].is_missing());
11885        assert_eq!(cs[2], Scalar::Timedelta64(3 * one_hour));
11886    }
11887
11888    #[test]
11889    fn nancumulative_matches_numeric_and_timedelta_oracle_k63oz() {
11890        // Differential vs independent cumulative nanops oracles
11891        // (br-frankenpandas-k63oz). Seeded LCG, no mocks.
11892        fn next(seed: &mut u64) -> u64 {
11893            *seed = seed
11894                .wrapping_mul(3202034522624059733)
11895                .wrapping_add(4354685564936845319);
11896            *seed
11897        }
11898
11899        fn assert_vec(case: usize, family: &str, op: &str, actual: &[Scalar], expected: &[Scalar]) {
11900            assert_eq!(
11901                actual.len(),
11902                expected.len(),
11903                "case={case} family={family} op={op}: length mismatch"
11904            );
11905            for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
11906                assert!(
11907                    actual.semantic_eq(expected),
11908                    "case={case} family={family} op={op} pos={pos}: expected {expected:?}, got {actual:?}"
11909                );
11910            }
11911        }
11912
11913        fn expected_numeric(
11914            values: &[Scalar],
11915        ) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
11916            let mut sum = Vec::with_capacity(values.len());
11917            let mut prod = Vec::with_capacity(values.len());
11918            let mut max = Vec::with_capacity(values.len());
11919            let mut min = Vec::with_capacity(values.len());
11920            let mut running_sum = 0.0_f64;
11921            let mut running_prod = 1.0_f64;
11922            let mut running_max: Option<f64> = None;
11923            let mut running_min: Option<f64> = None;
11924
11925            for value in values {
11926                if value.is_missing() {
11927                    sum.push(Scalar::Null(NullKind::NaN));
11928                    prod.push(Scalar::Null(NullKind::NaN));
11929                    max.push(Scalar::Null(NullKind::NaN));
11930                    min.push(Scalar::Null(NullKind::NaN));
11931                    continue;
11932                }
11933                let Ok(value) = value.to_f64() else {
11934                    sum.push(Scalar::Null(NullKind::NaN));
11935                    prod.push(Scalar::Null(NullKind::NaN));
11936                    max.push(Scalar::Null(NullKind::NaN));
11937                    min.push(Scalar::Null(NullKind::NaN));
11938                    continue;
11939                };
11940                if value.is_nan() {
11941                    sum.push(Scalar::Null(NullKind::NaN));
11942                    prod.push(Scalar::Null(NullKind::NaN));
11943                    max.push(Scalar::Null(NullKind::NaN));
11944                    min.push(Scalar::Null(NullKind::NaN));
11945                    continue;
11946                }
11947                running_sum += value;
11948                running_prod *= value;
11949                running_max = Some(running_max.map_or(value, |current| current.max(value)));
11950                running_min = Some(running_min.map_or(value, |current| current.min(value)));
11951                sum.push(Scalar::Float64(running_sum));
11952                prod.push(Scalar::Float64(running_prod));
11953                max.push(Scalar::Float64(running_max.expect("initialized")));
11954                min.push(Scalar::Float64(running_min.expect("initialized")));
11955            }
11956
11957            (sum, prod, max, min)
11958        }
11959
11960        fn expected_timedelta(values: &[Scalar]) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
11961            let mut sum = Vec::with_capacity(values.len());
11962            let mut max = Vec::with_capacity(values.len());
11963            let mut min = Vec::with_capacity(values.len());
11964            let mut running_sum = 0_i128;
11965            let mut running_max: Option<i64> = None;
11966            let mut running_min: Option<i64> = None;
11967
11968            for value in values {
11969                if value.is_missing() {
11970                    sum.push(Scalar::Null(NullKind::NaT));
11971                    max.push(Scalar::Null(NullKind::NaT));
11972                    min.push(Scalar::Null(NullKind::NaT));
11973                    continue;
11974                }
11975                let Scalar::Timedelta64(ns) = value else {
11976                    sum.push(Scalar::Null(NullKind::NaT));
11977                    max.push(Scalar::Null(NullKind::NaT));
11978                    min.push(Scalar::Null(NullKind::NaT));
11979                    continue;
11980                };
11981                running_sum = running_sum.saturating_add(i128::from(*ns));
11982                running_max = Some(running_max.map_or(*ns, |current| current.max(*ns)));
11983                running_min = Some(running_min.map_or(*ns, |current| current.min(*ns)));
11984                // br-frankenpandas-opz27: mirror the production contract (NaT
11985                // outside the representable range), not the old clamp.
11986                sum.push(super::timedelta_ns_to_scalar(running_sum));
11987                max.push(Scalar::Timedelta64(running_max.expect("initialized")));
11988                min.push(Scalar::Timedelta64(running_min.expect("initialized")));
11989            }
11990
11991            (sum, max, min)
11992        }
11993
11994        let mut seed = 0xc0de_c63a_5eed_0421_u64;
11995        for case in 0..260 {
11996            let len = (next(&mut seed) % 89 + 1) as usize;
11997
11998            let mut numeric = Vec::with_capacity(len);
11999            numeric.push(Scalar::Int64(case as i64 - 130));
12000            for _ in 1..len {
12001                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
12002                numeric.push(match next(&mut seed) % 8 {
12003                    0 => Scalar::Null(NullKind::Null),
12004                    1 => Scalar::Null(NullKind::NaN),
12005                    2 => Scalar::Float64(f64::NAN),
12006                    3 => Scalar::Bool(raw & 1 == 0),
12007                    4 => Scalar::Int64(raw % 251),
12008                    5 => Scalar::Float64(raw as f64 / 79.0),
12009                    6 => Scalar::Float64(0.0),
12010                    _ => Scalar::Float64(-0.0),
12011                });
12012            }
12013            let (sum, prod, max, min) = expected_numeric(&numeric);
12014            assert_vec(case, "numeric", "cumsum", &super::nancumsum(&numeric), &sum);
12015            assert_vec(
12016                case,
12017                "numeric",
12018                "cumprod",
12019                &super::nancumprod(&numeric),
12020                &prod,
12021            );
12022            assert_vec(case, "numeric", "cummax", &super::nancummax(&numeric), &max);
12023            assert_vec(case, "numeric", "cummin", &super::nancummin(&numeric), &min);
12024
12025            let mut timedeltas = Vec::with_capacity(len);
12026            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
12027            for _ in 1..len {
12028                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
12029                timedeltas.push(match next(&mut seed) % 7 {
12030                    0 => Scalar::Null(NullKind::Null),
12031                    1 => Scalar::Timedelta64(i64::MIN),
12032                    _ => Scalar::Timedelta64(raw),
12033                });
12034            }
12035            let (td_sum, td_max, td_min) = expected_timedelta(&timedeltas);
12036            assert_vec(
12037                case,
12038                "timedelta",
12039                "cumsum",
12040                &super::nancumsum(&timedeltas),
12041                &td_sum,
12042            );
12043            assert_vec(
12044                case,
12045                "timedelta",
12046                "cummax",
12047                &super::nancummax(&timedeltas),
12048                &td_max,
12049            );
12050            assert_vec(
12051                case,
12052                "timedelta",
12053                "cummin",
12054                &super::nancummin(&timedeltas),
12055                &td_min,
12056            );
12057        }
12058    }
12059
12060    #[test]
12061    fn nanquantile_linear_interpolation_matches_numpy() {
12062        let values = vec![
12063            Scalar::Float64(1.0),
12064            Scalar::Float64(2.0),
12065            Scalar::Float64(3.0),
12066            Scalar::Float64(4.0),
12067            Scalar::Float64(5.0),
12068        ];
12069        // median
12070        let q = super::nanquantile(&values, 0.5);
12071        assert!(matches!(q, Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
12072        // 25th percentile: interpolate between 2.0 and 3.0 at pos 1.0 → 2.0
12073        let q25 = super::nanquantile(&values, 0.25);
12074        assert!(matches!(q25, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
12075    }
12076
12077    #[test]
12078    fn nanquantile_ignores_nulls() {
12079        let values = vec![
12080            Scalar::Float64(1.0),
12081            Scalar::Null(NullKind::NaN),
12082            Scalar::Float64(3.0),
12083        ];
12084        let q = super::nanquantile(&values, 0.5);
12085        assert!(matches!(q, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
12086    }
12087
12088    #[test]
12089    fn nanquantile_empty_and_out_of_range_yield_null() {
12090        assert!(super::nanquantile(&[], 0.5).is_missing());
12091        assert!(super::nanquantile(&[Scalar::Float64(1.0)], 1.5).is_missing());
12092        assert!(super::nanquantile(&[Scalar::Float64(1.0)], -0.1).is_missing());
12093    }
12094
12095    #[test]
12096    fn nanquantile_timedelta64_preserves_dtype_5djk7() {
12097        // Per br-frankenpandas-5djk7: pandas td_series.quantile(q) returns
12098        // Timedelta64 — was silently NaN before via collect_finite.
12099        let one_hour: i64 = 3_600 * 1_000_000_000;
12100        let vals = vec![
12101            Scalar::Timedelta64(one_hour),
12102            Scalar::Timedelta64(2 * one_hour),
12103            Scalar::Timedelta64(3 * one_hour),
12104            Scalar::Timedelta64(4 * one_hour),
12105            Scalar::Timedelta64(5 * one_hour),
12106        ];
12107        assert_eq!(
12108            super::nanquantile(&vals, 0.5),
12109            Scalar::Timedelta64(3 * one_hour)
12110        );
12111        assert_eq!(
12112            super::nanquantile(&vals, 0.0),
12113            Scalar::Timedelta64(one_hour)
12114        );
12115        assert_eq!(
12116            super::nanquantile(&vals, 1.0),
12117            Scalar::Timedelta64(5 * one_hour)
12118        );
12119    }
12120
12121    #[test]
12122    fn nanquantile_timedelta64_linear_interpolation_5djk7() {
12123        let one_hour: i64 = 3_600 * 1_000_000_000;
12124        let vals = vec![
12125            Scalar::Timedelta64(one_hour),
12126            Scalar::Timedelta64(3 * one_hour),
12127        ];
12128        // Linear interpolation: at q=0.5, midpoint = 2h
12129        assert_eq!(
12130            super::nanquantile(&vals, 0.5),
12131            Scalar::Timedelta64(2 * one_hour)
12132        );
12133    }
12134
12135    #[test]
12136    fn nanquantile_matches_numeric_and_timedelta_oracle_ecb7r() {
12137        // Differential vs independent sort-based quantile oracles
12138        // (br-frankenpandas-ecb7r). Seeded LCG, no mocks.
12139        fn next(seed: &mut u64) -> u64 {
12140            *seed = seed
12141                .wrapping_mul(3202034522624059733)
12142                .wrapping_add(4354685564936845319);
12143            *seed
12144        }
12145
12146        fn interpolated(sorted: &[f64], q: f64) -> f64 {
12147            if sorted.len() == 1 {
12148                return sorted[0];
12149            }
12150            let pos = q * (sorted.len() - 1) as f64;
12151            let lo = pos.floor() as usize;
12152            let hi = pos.ceil() as usize;
12153            if lo == hi {
12154                sorted[lo]
12155            } else {
12156                let weight = pos - lo as f64;
12157                sorted[lo] + (sorted[hi] - sorted[lo]) * weight
12158            }
12159        }
12160
12161        fn expected_numeric(values: &[Scalar], q: f64) -> Scalar {
12162            if !(0.0..=1.0).contains(&q) {
12163                return Scalar::Null(NullKind::NaN);
12164            }
12165            let mut samples = values
12166                .iter()
12167                .filter(|value| !value.is_missing())
12168                .filter_map(|value| value.to_f64().ok())
12169                .collect::<Vec<_>>();
12170            if samples.is_empty() {
12171                return Scalar::Null(NullKind::NaN);
12172            }
12173            samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
12174            Scalar::Float64(interpolated(&samples, q))
12175        }
12176
12177        fn expected_timedelta(values: &[Scalar], q: f64) -> Scalar {
12178            if !(0.0..=1.0).contains(&q) {
12179                return Scalar::Null(NullKind::NaN);
12180            }
12181            let mut samples = values
12182                .iter()
12183                .filter_map(|value| match value {
12184                    Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
12185                    _ => None,
12186                })
12187                .collect::<Vec<_>>();
12188            if samples.is_empty() {
12189                // Per br-frankenpandas-k7apg: a NaT-only Timedelta input stays in
12190                // the Timedelta family (pandas returns NaT, not float NaN).
12191                return Scalar::Timedelta64(Timedelta::NAT);
12192            }
12193            samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
12194            Scalar::Timedelta64(interpolated(&samples, q) as i64)
12195        }
12196
12197        fn assert_quantile(case: usize, family: &str, values: &[Scalar], q: f64, expected: Scalar) {
12198            let actual = super::nanquantile(values, q);
12199            assert!(
12200                actual.semantic_eq(&expected),
12201                "case={case} family={family} q={q}: expected {expected:?}, got {actual:?} for {values:?}"
12202            );
12203        }
12204
12205        let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
12206        assert_quantile(
12207            usize::MAX,
12208            "numeric_all_missing",
12209            &numeric_all_missing,
12210            0.5,
12211            expected_numeric(&numeric_all_missing, 0.5),
12212        );
12213        assert_quantile(
12214            usize::MAX - 1,
12215            "numeric_out_of_range",
12216            &[Scalar::Float64(1.0), Scalar::Float64(2.0)],
12217            1.25,
12218            Scalar::Null(NullKind::NaN),
12219        );
12220
12221        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
12222        assert_quantile(
12223            usize::MAX - 2,
12224            "timedelta_all_missing",
12225            &td_all_missing,
12226            0.5,
12227            expected_timedelta(&td_all_missing, 0.5),
12228        );
12229        assert_quantile(
12230            usize::MAX - 3,
12231            "timedelta_out_of_range",
12232            &[Scalar::Timedelta64(1), Scalar::Timedelta64(2)],
12233            -0.25,
12234            Scalar::Null(NullKind::NaN),
12235        );
12236
12237        let mut seed = 0x4a17_1e5e_0b5e_a11d_u64;
12238        for case in 0..260 {
12239            let len = (next(&mut seed) % 83 + 1) as usize;
12240            let q = match next(&mut seed) % 8 {
12241                0 => 0.0,
12242                1 => 0.25,
12243                2 => 0.5,
12244                3 => 0.75,
12245                4 => 1.0,
12246                _ => (next(&mut seed) % 1_001) as f64 / 1_000.0,
12247            };
12248
12249            let mut numeric = Vec::with_capacity(len);
12250            numeric.push(Scalar::Int64(case as i64 - 130));
12251            for _ in 1..len {
12252                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
12253                numeric.push(match next(&mut seed) % 8 {
12254                    0 => Scalar::Null(NullKind::Null),
12255                    1 => Scalar::Null(NullKind::NaN),
12256                    2 => Scalar::Float64(f64::NAN),
12257                    3 => Scalar::Bool(raw & 1 == 0),
12258                    4 => Scalar::Int64(raw % 251),
12259                    5 => Scalar::Float64(raw as f64 / 67.0),
12260                    6 => Scalar::Float64(0.0),
12261                    _ => Scalar::Float64(-0.0),
12262                });
12263            }
12264            assert_quantile(case, "numeric", &numeric, q, expected_numeric(&numeric, q));
12265
12266            let mut timedeltas = Vec::with_capacity(len);
12267            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
12268            for _ in 1..len {
12269                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
12270                timedeltas.push(match next(&mut seed) % 7 {
12271                    0 => Scalar::Null(NullKind::Null),
12272                    1 => Scalar::Timedelta64(i64::MIN),
12273                    _ => Scalar::Timedelta64(raw),
12274                });
12275            }
12276            assert_quantile(
12277                case,
12278                "timedelta",
12279                &timedeltas,
12280                q,
12281                expected_timedelta(&timedeltas, q),
12282            );
12283        }
12284    }
12285
12286    #[test]
12287    fn nanargmax_returns_first_position() {
12288        let values = vec![
12289            Scalar::Float64(1.0),
12290            Scalar::Null(NullKind::NaN),
12291            Scalar::Float64(4.0),
12292            Scalar::Float64(4.0),
12293            Scalar::Float64(2.0),
12294        ];
12295        assert_eq!(super::nanargmax(&values), Some(2));
12296    }
12297
12298    #[test]
12299    fn nanargmin_returns_first_position() {
12300        let values = vec![
12301            Scalar::Float64(3.0),
12302            Scalar::Null(NullKind::NaN),
12303            Scalar::Float64(1.0),
12304            Scalar::Float64(1.0),
12305        ];
12306        assert_eq!(super::nanargmin(&values), Some(2));
12307    }
12308
12309    #[test]
12310    fn nanargmax_all_missing_returns_none() {
12311        let values = vec![Scalar::Null(NullKind::NaN), Scalar::Null(NullKind::Null)];
12312        assert_eq!(super::nanargmax(&values), None);
12313        assert_eq!(super::nanargmin(&values), None);
12314    }
12315
12316    #[test]
12317    fn nanargmax_nanargmin_match_numeric_and_timedelta_oracle_unkj6() {
12318        // Differential vs independent first-tie arg oracles
12319        // (br-frankenpandas-unkj6). Seeded LCG, no mocks.
12320        fn next(seed: &mut u64) -> u64 {
12321            *seed = seed
12322                .wrapping_mul(2862933555777941757)
12323                .wrapping_add(3037000493);
12324            *seed
12325        }
12326
12327        fn expected_numeric(values: &[Scalar], find_max: bool) -> Option<usize> {
12328            let mut best: Option<(usize, f64)> = None;
12329            for (idx, value) in values.iter().enumerate() {
12330                if value.is_missing() {
12331                    continue;
12332                }
12333                let Ok(value) = value.to_f64() else {
12334                    continue;
12335                };
12336                if value.is_nan() {
12337                    continue;
12338                }
12339                match best {
12340                    None => best = Some((idx, value)),
12341                    Some((_, current))
12342                        if (find_max && value > current) || (!find_max && value < current) =>
12343                    {
12344                        best = Some((idx, value));
12345                    }
12346                    _ => {}
12347                }
12348            }
12349            best.map(|(idx, _)| idx)
12350        }
12351
12352        fn expected_timedelta(values: &[Scalar], find_max: bool) -> Option<usize> {
12353            let mut best: Option<(usize, i64)> = None;
12354            for (idx, value) in values.iter().enumerate() {
12355                if value.is_missing() {
12356                    continue;
12357                }
12358                let Scalar::Timedelta64(ns) = value else {
12359                    continue;
12360                };
12361                match best {
12362                    None => best = Some((idx, *ns)),
12363                    Some((_, current))
12364                        if (find_max && *ns > current) || (!find_max && *ns < current) =>
12365                    {
12366                        best = Some((idx, *ns));
12367                    }
12368                    _ => {}
12369                }
12370            }
12371            best.map(|(idx, _)| idx)
12372        }
12373
12374        fn assert_args(
12375            case: usize,
12376            family: &str,
12377            values: &[Scalar],
12378            expected_min: Option<usize>,
12379            expected_max: Option<usize>,
12380        ) {
12381            assert_eq!(
12382                super::nanargmin(values),
12383                expected_min,
12384                "case={case} family={family}: nanargmin mismatch for {values:?}"
12385            );
12386            assert_eq!(
12387                super::nanargmax(values),
12388                expected_max,
12389                "case={case} family={family}: nanargmax mismatch for {values:?}"
12390            );
12391        }
12392
12393        let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
12394        assert_args(usize::MAX, "numeric_all_missing", &all_missing, None, None);
12395        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
12396        assert_args(
12397            usize::MAX - 1,
12398            "timedelta_all_missing",
12399            &td_all_missing,
12400            None,
12401            None,
12402        );
12403        let positive_int64_endpoint = [
12404            Scalar::Int64(i64::MAX - 1),
12405            Scalar::Null(NullKind::Null),
12406            Scalar::Int64(i64::MAX),
12407        ];
12408        assert_args(
12409            usize::MAX - 2,
12410            "int64_positive_endpoint_exact_order",
12411            &positive_int64_endpoint,
12412            Some(0),
12413            Some(2),
12414        );
12415        let negative_int64_endpoint = [
12416            Scalar::Int64(i64::MIN + 2),
12417            Scalar::Null(NullKind::NaN),
12418            Scalar::Int64(i64::MIN + 1),
12419        ];
12420        assert_args(
12421            usize::MAX - 3,
12422            "int64_negative_endpoint_exact_order",
12423            &negative_int64_endpoint,
12424            Some(2),
12425            Some(0),
12426        );
12427
12428        let mut seed = 0xa126_5eed_ed9e_u64;
12429        for case in 0..260 {
12430            let len = (next(&mut seed) % 83 + 1) as usize;
12431
12432            let mut numeric = Vec::with_capacity(len);
12433            numeric.push(Scalar::Int64(case as i64 - 130));
12434            if len > 1 {
12435                numeric.push(Scalar::Int64(case as i64 - 130));
12436            }
12437            for _ in numeric.len()..len {
12438                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
12439                numeric.push(match next(&mut seed) % 9 {
12440                    0 => Scalar::Null(NullKind::Null),
12441                    1 => Scalar::Null(NullKind::NaN),
12442                    2 => Scalar::Float64(f64::NAN),
12443                    3 => Scalar::Bool(raw & 1 == 0),
12444                    4 => Scalar::Int64(raw % 211),
12445                    5 => Scalar::Float64(raw as f64 / 47.0),
12446                    6 => Scalar::Float64(0.0),
12447                    7 => Scalar::Float64(-0.0),
12448                    _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
12449                });
12450            }
12451            assert_args(
12452                case,
12453                "numeric",
12454                &numeric,
12455                expected_numeric(&numeric, false),
12456                expected_numeric(&numeric, true),
12457            );
12458
12459            let mut timedeltas = Vec::with_capacity(len);
12460            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
12461            if len > 1 {
12462                timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
12463            }
12464            for _ in timedeltas.len()..len {
12465                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
12466                timedeltas.push(match next(&mut seed) % 7 {
12467                    0 => Scalar::Null(NullKind::Null),
12468                    1 => Scalar::Timedelta64(i64::MIN),
12469                    _ => Scalar::Timedelta64(raw),
12470                });
12471            }
12472            assert_args(
12473                case,
12474                "timedelta",
12475                &timedeltas,
12476                expected_timedelta(&timedeltas, false),
12477                expected_timedelta(&timedeltas, true),
12478            );
12479        }
12480    }
12481
12482    #[test]
12483    fn nansem_matches_std_over_sqrt_n() {
12484        let values = vec![
12485            Scalar::Float64(2.0),
12486            Scalar::Float64(4.0),
12487            Scalar::Float64(4.0),
12488            Scalar::Float64(4.0),
12489            Scalar::Float64(5.0),
12490            Scalar::Float64(5.0),
12491            Scalar::Float64(7.0),
12492            Scalar::Float64(9.0),
12493        ];
12494        // numpy/scipy: std(ddof=1) = 2.138089935299395; sem = std/sqrt(8) = 0.7559
12495        let sem = super::nansem(&values, 1);
12496        assert!(matches!(sem, Scalar::Float64(_)));
12497        let Scalar::Float64(v) = sem else {
12498            return;
12499        };
12500        assert!((v - 0.7559289460184544).abs() < 1e-9);
12501    }
12502
12503    #[test]
12504    fn nansem_single_buffer_matches_former_numeric_bits_jgwg4() {
12505        fn former(values: &[Scalar], ddof: usize) -> Scalar {
12506            let nums = super::collect_finite(values);
12507            if nums.len() <= ddof {
12508                return Scalar::Null(NullKind::NaN);
12509            }
12510            match super::nanstd(values, ddof) {
12511                Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
12512                other => other,
12513            }
12514        }
12515
12516        fn assert_same_bits(values: &[Scalar], ddof: usize) {
12517            let expected = former(values, ddof);
12518            let actual = super::nansem(values, ddof);
12519            match (&expected, &actual) {
12520                (Scalar::Float64(expected), Scalar::Float64(actual)) => {
12521                    assert_eq!(
12522                        actual.to_bits(),
12523                        expected.to_bits(),
12524                        "values={values:?} ddof={ddof}"
12525                    );
12526                }
12527                _ => assert!(
12528                    actual.semantic_eq(&expected),
12529                    "values={values:?} ddof={ddof}: expected {expected:?}, got {actual:?}"
12530                ),
12531            }
12532        }
12533
12534        let mut generated = Vec::with_capacity(4_096);
12535        for idx in 0..4_096_i64 {
12536            generated.push(match idx % 257 {
12537                0 => Scalar::Null(NullKind::NaN),
12538                1 => Scalar::Float64(-0.0),
12539                2 => Scalar::Float64(0.0),
12540                _ if idx % 2 == 0 => Scalar::Int64(idx - 2_048),
12541                _ => Scalar::Float64((idx - 2_048) as f64 / 17.0),
12542            });
12543        }
12544
12545        let cases = [
12546            Vec::new(),
12547            vec![Scalar::Int64(1)],
12548            vec![
12549                Scalar::Null(NullKind::Null),
12550                Scalar::Float64(f64::NAN),
12551                Scalar::Int64(i64::MIN),
12552                Scalar::Int64(i64::MAX),
12553                Scalar::Float64(-0.0),
12554                Scalar::Float64(0.0),
12555            ],
12556            generated,
12557        ];
12558        for values in &cases {
12559            for ddof in [0, 1, values.len(), values.len().saturating_add(1)] {
12560                assert_same_bits(values, ddof);
12561            }
12562        }
12563    }
12564
12565    #[test]
12566    #[ignore = "foreground release A/B harness"]
12567    fn nansem_single_buffer_allocator_preconditioned_ab_jgwg4() {
12568        const ROWS: usize = 262_144;
12569        const BATCH: usize = 8;
12570        const BLOCKS: usize = 9;
12571        const PRECONDITION_CALLS: usize = 2;
12572
12573        fn former(values: &[Scalar], ddof: usize) -> Scalar {
12574            let nums = super::collect_finite(values);
12575            if nums.len() <= ddof {
12576                return Scalar::Null(NullKind::NaN);
12577            }
12578            match super::nanstd(values, ddof) {
12579                Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
12580                other => other,
12581            }
12582        }
12583
12584        fn evaluate(values: &[Scalar], candidate: bool) -> Scalar {
12585            let values = std::hint::black_box(values);
12586            if candidate {
12587                super::nansem(values, 1)
12588            } else {
12589                former(values, 1)
12590            }
12591        }
12592
12593        fn elapsed_ns(values: &[Scalar], candidate: bool) -> u128 {
12594            for _ in 0..PRECONDITION_CALLS {
12595                std::hint::black_box(evaluate(values, candidate));
12596            }
12597            let started = std::time::Instant::now();
12598            for _ in 0..BATCH {
12599                std::hint::black_box(evaluate(values, candidate));
12600            }
12601            started.elapsed().as_nanos()
12602        }
12603
12604        fn median(mut samples: Vec<u128>) -> u128 {
12605            samples.sort_unstable();
12606            samples[samples.len() / 2]
12607        }
12608
12609        fn spread(a: u128, b: u128) -> f64 {
12610            a.abs_diff(b) as f64 / ((a + b) as f64 / 2.0)
12611        }
12612
12613        let values = (0..ROWS)
12614            .map(|idx| {
12615                if idx % 257 == 0 {
12616                    Scalar::Null(NullKind::NaN)
12617                } else {
12618                    Scalar::Int64((idx % 8_191) as i64 - 4_095)
12619                }
12620            })
12621            .collect::<Vec<_>>();
12622
12623        let expected_bits = match former(&values, 1) {
12624            Scalar::Float64(value) => Some(value.to_bits()),
12625            _ => None,
12626        };
12627        let actual_bits = match super::nansem(&values, 1) {
12628            Scalar::Float64(value) => Some(value.to_bits()),
12629            _ => None,
12630        };
12631        assert!(
12632            expected_bits.is_some(),
12633            "numeric nansem must return Float64"
12634        );
12635        assert_eq!(actual_bits, expected_bits, "A/B output bits");
12636
12637        std::hint::black_box(evaluate(&values, false));
12638        std::hint::black_box(evaluate(&values, true));
12639
12640        let body_started = std::time::Instant::now();
12641        let mut former_a = Vec::with_capacity(BLOCKS);
12642        let mut former_b = Vec::with_capacity(BLOCKS);
12643        let mut candidate_a = Vec::with_capacity(BLOCKS);
12644        let mut candidate_b = Vec::with_capacity(BLOCKS);
12645        for block in 0..BLOCKS {
12646            let order = if block % 2 == 0 {
12647                [(false, 0), (true, 0), (true, 1), (false, 1)]
12648            } else {
12649                [(true, 1), (false, 1), (false, 0), (true, 0)]
12650            };
12651            for (candidate, duplicate) in order {
12652                let elapsed = elapsed_ns(&values, candidate);
12653                match (candidate, duplicate) {
12654                    (false, 0) => former_a.push(elapsed),
12655                    (false, _) => former_b.push(elapsed),
12656                    (true, 0) => candidate_a.push(elapsed),
12657                    (true, _) => candidate_b.push(elapsed),
12658                }
12659            }
12660        }
12661
12662        let former_a = median(former_a) / BATCH as u128;
12663        let former_b = median(former_b) / BATCH as u128;
12664        let candidate_a = median(candidate_a) / BATCH as u128;
12665        let candidate_b = median(candidate_b) / BATCH as u128;
12666        let former_mean = (former_a + former_b) as f64 / 2.0;
12667        let candidate_mean = (candidate_a + candidate_b) as f64 / 2.0;
12668        println!(
12669            "NANSEM_SINGLE_BUFFER_AB rows={ROWS} former_a_ns={former_a} former_b_ns={former_b} candidate_a_ns={candidate_a} candidate_b_ns={candidate_b} former_spread={:.6} candidate_spread={:.6} speedup={:.6} body_seconds={:.6}",
12670            spread(former_a, former_b),
12671            spread(candidate_a, candidate_b),
12672            former_mean / candidate_mean,
12673            body_started.elapsed().as_secs_f64()
12674        );
12675    }
12676
12677    #[test]
12678    fn nansem_empty_returns_null() {
12679        assert!(super::nansem(&[], 1).is_missing());
12680        assert!(super::nansem(&[Scalar::Float64(1.0)], 1).is_missing());
12681    }
12682
12683    #[test]
12684    fn nanptp_returns_max_minus_min() {
12685        let values = vec![
12686            Scalar::Float64(3.0),
12687            Scalar::Null(NullKind::NaN),
12688            Scalar::Float64(7.0),
12689            Scalar::Float64(1.0),
12690        ];
12691        assert_eq!(super::nanptp(&values), Scalar::Float64(6.0));
12692    }
12693
12694    #[test]
12695    fn nanptp_empty_returns_null() {
12696        assert!(super::nanptp(&[]).is_missing());
12697        assert!(super::nanptp(&[Scalar::Null(NullKind::NaN)]).is_missing());
12698    }
12699
12700    #[test]
12701    fn nanptp_timedelta64_preserves_dtype_u2g0r() {
12702        // Per br-frankenpandas-u2g0r: ptp on Timedelta64 returns Timedelta64.
12703        let one_hour: i64 = 3_600 * 1_000_000_000;
12704        let values = vec![
12705            Scalar::Timedelta64(one_hour),
12706            Scalar::Timedelta64(5 * one_hour),
12707            Scalar::Timedelta64(2 * one_hour),
12708        ];
12709        assert_eq!(super::nanptp(&values), Scalar::Timedelta64(4 * one_hour));
12710    }
12711
12712    #[test]
12713    fn nanptp_matches_numeric_and_timedelta_oracle_affjt() {
12714        // Differential vs independent max-min oracles
12715        // (br-frankenpandas-affjt). Seeded LCG, no mocks.
12716        fn next(seed: &mut u64) -> u64 {
12717            *seed = seed
12718                .wrapping_mul(3202034522624059733)
12719                .wrapping_add(4354685564936845319);
12720            *seed
12721        }
12722
12723        fn expected_numeric(values: &[Scalar]) -> Scalar {
12724            let mut lo = f64::INFINITY;
12725            let mut hi = f64::NEG_INFINITY;
12726            let mut seen = false;
12727            for value in values {
12728                if value.is_missing() {
12729                    continue;
12730                }
12731                if let Ok(value) = value.to_f64() {
12732                    seen = true;
12733                    lo = lo.min(value);
12734                    hi = hi.max(value);
12735                }
12736            }
12737            if seen {
12738                Scalar::Float64(hi - lo)
12739            } else {
12740                Scalar::Null(NullKind::NaN)
12741            }
12742        }
12743
12744        fn expected_timedelta(values: &[Scalar]) -> Scalar {
12745            let mut lo = i64::MAX;
12746            let mut hi = i64::MIN;
12747            let mut seen = false;
12748            for value in values {
12749                if let Scalar::Timedelta64(ns) = value
12750                    && !value.is_missing()
12751                {
12752                    seen = true;
12753                    lo = lo.min(*ns);
12754                    hi = hi.max(*ns);
12755                }
12756            }
12757            if seen {
12758                Scalar::Timedelta64(hi - lo)
12759            } else {
12760                Scalar::Null(NullKind::NaN)
12761            }
12762        }
12763
12764        fn assert_ptp(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
12765            let actual = super::nanptp(values);
12766            assert!(
12767                actual.semantic_eq(&expected),
12768                "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
12769            );
12770        }
12771
12772        assert_ptp(
12773            usize::MAX,
12774            "numeric_all_missing",
12775            &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
12776            Scalar::Null(NullKind::NaN),
12777        );
12778        assert_ptp(
12779            usize::MAX - 1,
12780            "timedelta_all_missing",
12781            &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
12782            Scalar::Null(NullKind::NaN),
12783        );
12784        let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
12785        assert_ptp(
12786            usize::MAX - 2,
12787            "timedelta_one_ns_range_beyond_f64_exactness",
12788            &[
12789                Scalar::Timedelta64(beyond_f64_exact_ns),
12790                Scalar::Timedelta64(beyond_f64_exact_ns - 1),
12791                Scalar::Timedelta64(Timedelta::NAT),
12792            ],
12793            Scalar::Timedelta64(1),
12794        );
12795
12796        let mut seed = 0xa22f_17ed_57a7_15e5_u64;
12797        for case in 0..260 {
12798            let len = (next(&mut seed) % 83 + 1) as usize;
12799
12800            let mut numeric = Vec::with_capacity(len);
12801            numeric.push(Scalar::Int64(case as i64 - 130));
12802            for _ in 1..len {
12803                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
12804                numeric.push(match next(&mut seed) % 9 {
12805                    0 => Scalar::Null(NullKind::Null),
12806                    1 => Scalar::Null(NullKind::NaN),
12807                    2 => Scalar::Float64(f64::NAN),
12808                    3 => Scalar::Bool(raw & 1 == 0),
12809                    4 => Scalar::Int64(raw),
12810                    5 => Scalar::Float64(raw as f64 / 53.0),
12811                    6 => Scalar::Float64(0.0),
12812                    7 => Scalar::Float64(-0.0),
12813                    _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
12814                });
12815            }
12816            assert_ptp(case, "numeric", &numeric, expected_numeric(&numeric));
12817
12818            let mut timedeltas = Vec::with_capacity(len);
12819            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
12820            for _ in 1..len {
12821                let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
12822                timedeltas.push(match next(&mut seed) % 7 {
12823                    0 => Scalar::Null(NullKind::Null),
12824                    1 => Scalar::Timedelta64(i64::MIN),
12825                    _ => Scalar::Timedelta64(raw),
12826                });
12827            }
12828            assert_ptp(
12829                case,
12830                "timedelta",
12831                &timedeltas,
12832                expected_timedelta(&timedeltas),
12833            );
12834        }
12835    }
12836
12837    #[test]
12838    fn nanargmax_nanargmin_timedelta64_compare_by_ns_ql1t5() {
12839        // Per br-frankenpandas-ql1t5: argmax/argmin on Timedelta64 compare
12840        // i64 ns directly instead of silently skipping via to_f64.
12841        let one_hour: i64 = 3_600 * 1_000_000_000;
12842        let values = vec![
12843            Scalar::Timedelta64(2 * one_hour),
12844            Scalar::Timedelta64(5 * one_hour),
12845            Scalar::Timedelta64(one_hour),
12846            Scalar::Timedelta64(3 * one_hour),
12847        ];
12848        assert_eq!(super::nanargmax(&values), Some(1));
12849        assert_eq!(super::nanargmin(&values), Some(2));
12850    }
12851
12852    #[test]
12853    fn nanprod_timedelta64_returns_null_szq6a() {
12854        // Per br-frankenpandas-szq6a: pandas raises on Timedelta prod
12855        // (dimensionally undefined). We surface Null instead of the
12856        // misleading Float64(1.0) the old empty-iterator default emitted.
12857        let one_hour: i64 = 3_600 * 1_000_000_000;
12858        let values = vec![
12859            Scalar::Timedelta64(2 * one_hour),
12860            Scalar::Timedelta64(3 * one_hour),
12861        ];
12862        assert!(super::nanprod(&values).is_missing());
12863    }
12864
12865    #[test]
12866    fn nanprod_matches_numeric_and_timedelta_oracle_9938h() {
12867        // Differential vs independent product oracles
12868        // (br-frankenpandas-9938h). Seeded LCG, no mocks.
12869        fn next(seed: &mut u64) -> u64 {
12870            *seed = seed
12871                .wrapping_mul(6364136223846793005)
12872                .wrapping_add(1442695040888963407);
12873            *seed
12874        }
12875
12876        fn expected_numeric(values: &[Scalar]) -> Scalar {
12877            let mut product = 1.0_f64;
12878            for value in values {
12879                if value.is_missing() {
12880                    continue;
12881                }
12882                if let Ok(value) = value.to_f64() {
12883                    product *= value;
12884                }
12885            }
12886            Scalar::Float64(product)
12887        }
12888
12889        fn expected_timedelta(values: &[Scalar]) -> Scalar {
12890            if values
12891                .iter()
12892                .any(|value| matches!(value, Scalar::Timedelta64(_)) && !value.is_missing())
12893            {
12894                Scalar::Null(NullKind::NaN)
12895            } else {
12896                Scalar::Float64(1.0)
12897            }
12898        }
12899
12900        fn assert_prod(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
12901            let actual = super::nanprod(values);
12902            assert!(
12903                actual.semantic_eq(&expected),
12904                "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
12905            );
12906        }
12907
12908        let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
12909        assert_prod(
12910            usize::MAX,
12911            "numeric_all_missing",
12912            &all_missing,
12913            Scalar::Float64(1.0),
12914        );
12915
12916        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
12917        assert_prod(
12918            usize::MAX - 1,
12919            "timedelta_all_missing",
12920            &td_all_missing,
12921            expected_timedelta(&td_all_missing),
12922        );
12923
12924        let mut seed = 0x6e0d_9938_a11c_0de5_u64;
12925        for case in 0..280 {
12926            let len = (next(&mut seed) % 89 + 1) as usize;
12927
12928            let mut numeric = Vec::with_capacity(len);
12929            numeric.push(Scalar::Int64((case % 17) as i64 - 8));
12930            for _ in 1..len {
12931                let raw = (next(&mut seed) % 2_001) as i64 - 1_000;
12932                numeric.push(match next(&mut seed) % 9 {
12933                    0 => Scalar::Null(NullKind::Null),
12934                    1 => Scalar::Null(NullKind::NaN),
12935                    2 => Scalar::Float64(f64::NAN),
12936                    3 => Scalar::Bool(raw & 1 == 0),
12937                    4 => Scalar::Int64(raw % 19),
12938                    5 => Scalar::Float64(raw as f64 / 97.0),
12939                    6 => Scalar::Float64(0.0),
12940                    7 => Scalar::Float64(-0.0),
12941                    _ => Scalar::Float64(1.0),
12942                });
12943            }
12944            assert_prod(case, "numeric", &numeric, expected_numeric(&numeric));
12945
12946            let mut timedeltas = Vec::with_capacity(len);
12947            timedeltas.push(Scalar::Timedelta64(case as i64 - 140));
12948            for _ in 1..len {
12949                let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
12950                timedeltas.push(match next(&mut seed) % 7 {
12951                    0 => Scalar::Null(NullKind::Null),
12952                    1 => Scalar::Timedelta64(i64::MIN),
12953                    _ => Scalar::Timedelta64(raw),
12954                });
12955            }
12956            assert_prod(
12957                case,
12958                "timedelta",
12959                &timedeltas,
12960                expected_timedelta(&timedeltas),
12961            );
12962        }
12963    }
12964
12965    #[test]
12966    fn nanskew_symmetric_distribution_near_zero() {
12967        let values = vec![
12968            Scalar::Float64(1.0),
12969            Scalar::Float64(2.0),
12970            Scalar::Float64(3.0),
12971            Scalar::Float64(4.0),
12972            Scalar::Float64(5.0),
12973        ];
12974        // Perfectly symmetric -> skew = 0
12975        let skew = super::nanskew(&values);
12976        assert!(matches!(skew, Scalar::Float64(_)));
12977        let Scalar::Float64(v) = skew else {
12978            return;
12979        };
12980        assert!(v.abs() < 1e-9);
12981    }
12982
12983    #[test]
12984    fn nanskew_too_few_values_returns_null() {
12985        assert!(super::nanskew(&[]).is_missing());
12986        assert!(super::nanskew(&[Scalar::Float64(1.0), Scalar::Float64(2.0)]).is_missing());
12987    }
12988
12989    #[test]
12990    fn nankurt_symmetric_uniform_distribution() {
12991        let values = vec![
12992            Scalar::Float64(1.0),
12993            Scalar::Float64(2.0),
12994            Scalar::Float64(3.0),
12995            Scalar::Float64(4.0),
12996            Scalar::Float64(5.0),
12997        ];
12998        // pandas kurt([1,2,3,4,5]) = -1.2
12999        let kurt = super::nankurt(&values);
13000        assert!(matches!(kurt, Scalar::Float64(_)));
13001        let Scalar::Float64(v) = kurt else {
13002            return;
13003        };
13004        assert!((v + 1.2).abs() < 1e-9);
13005    }
13006
13007    #[test]
13008    fn nankurt_too_few_values_returns_null() {
13009        let vals: Vec<Scalar> = (0..3).map(|i| Scalar::Float64(i as f64)).collect();
13010        assert!(super::nankurt(&vals).is_missing());
13011    }
13012
13013    #[test]
13014    fn nanskew_constant_series_returns_zero() {
13015        let values = vec![
13016            Scalar::Float64(5.0),
13017            Scalar::Float64(5.0),
13018            Scalar::Float64(5.0),
13019        ];
13020        assert_eq!(super::nanskew(&values), Scalar::Float64(0.0));
13021        assert_eq!(
13022            super::nankurt(&[
13023                Scalar::Float64(5.0),
13024                Scalar::Float64(5.0),
13025                Scalar::Float64(5.0),
13026                Scalar::Float64(5.0),
13027            ]),
13028            Scalar::Float64(0.0)
13029        );
13030    }
13031
13032    #[test]
13033    fn nanskew_nankurt_match_numeric_oracle_jr7zk() {
13034        // Differential vs independent bias-corrected moment oracles
13035        // (br-frankenpandas-jr7zk). Seeded LCG, no mocks.
13036        fn next(seed: &mut u64) -> u64 {
13037            *seed = seed
13038                .wrapping_mul(2862933555777941757)
13039                .wrapping_add(3037000493);
13040            *seed
13041        }
13042
13043        fn samples(values: &[Scalar]) -> Vec<f64> {
13044            values
13045                .iter()
13046                .filter(|value| !value.is_missing())
13047                .filter_map(|value| value.to_f64().ok())
13048                .collect()
13049        }
13050
13051        fn expected_skew(values: &[Scalar]) -> Scalar {
13052            let samples = samples(values);
13053            let n = samples.len() as f64;
13054            if n < 3.0 {
13055                return Scalar::Null(NullKind::NaN);
13056            }
13057            let mean = samples.iter().sum::<f64>() / n;
13058            let m2 = samples
13059                .iter()
13060                .map(|value| (value - mean).powi(2))
13061                .sum::<f64>();
13062            let m3 = samples
13063                .iter()
13064                .map(|value| (value - mean).powi(3))
13065                .sum::<f64>();
13066            let s2 = m2 / (n - 1.0);
13067            if s2 == 0.0 {
13068                return Scalar::Float64(0.0);
13069            }
13070            Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s2.powf(1.5)))
13071        }
13072
13073        fn expected_kurt(values: &[Scalar]) -> Scalar {
13074            let samples = samples(values);
13075            let n = samples.len() as f64;
13076            if n < 4.0 {
13077                return Scalar::Null(NullKind::NaN);
13078            }
13079            let mean = samples.iter().sum::<f64>() / n;
13080            let m2 = samples
13081                .iter()
13082                .map(|value| (value - mean).powi(2))
13083                .sum::<f64>();
13084            let m4 = samples
13085                .iter()
13086                .map(|value| (value - mean).powi(4))
13087                .sum::<f64>();
13088            let s2 = m2 / (n - 1.0);
13089            if s2 == 0.0 {
13090                return Scalar::Float64(0.0);
13091            }
13092            let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
13093            let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
13094            Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
13095        }
13096
13097        fn assert_moments(case: usize, values: &[Scalar]) {
13098            let expected_skew = expected_skew(values);
13099            let expected_kurt = expected_kurt(values);
13100            let actual_skew = super::nanskew(values);
13101            let actual_kurt = super::nankurt(values);
13102            assert!(
13103                actual_skew.semantic_eq(&expected_skew),
13104                "case={case}: expected skew {expected_skew:?}, got {actual_skew:?} for {values:?}"
13105            );
13106            assert!(
13107                actual_kurt.semantic_eq(&expected_kurt),
13108                "case={case}: expected kurt {expected_kurt:?}, got {actual_kurt:?} for {values:?}"
13109            );
13110        }
13111
13112        assert_moments(
13113            usize::MAX,
13114            &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
13115        );
13116        assert_moments(
13117            usize::MAX - 1,
13118            &[
13119                Scalar::Float64(7.0),
13120                Scalar::Float64(7.0),
13121                Scalar::Float64(7.0),
13122                Scalar::Float64(7.0),
13123            ],
13124        );
13125
13126        let mut seed = 0x5ce7_9a55_a11c_0de5_u64;
13127        for case in 0..260 {
13128            let len = (next(&mut seed) % 89 + 1) as usize;
13129            let mut values = Vec::with_capacity(len);
13130            if case % 11 == 0 {
13131                values.extend((0..len).map(|_| Scalar::Float64(3.0)));
13132            } else {
13133                values.push(Scalar::Float64(case as f64 / 19.0));
13134                for _ in 1..len {
13135                    let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
13136                    values.push(match next(&mut seed) % 8 {
13137                        0 => Scalar::Null(NullKind::Null),
13138                        1 => Scalar::Null(NullKind::NaN),
13139                        2 => Scalar::Float64(f64::NAN),
13140                        3 => Scalar::Bool(raw & 1 == 0),
13141                        4 => Scalar::Int64(raw % 251),
13142                        5 => Scalar::Float64(raw as f64 / 83.0),
13143                        6 => Scalar::Float64(0.0),
13144                        _ => Scalar::Float64(-0.0),
13145                    });
13146                }
13147            }
13148            assert_moments(case, &values);
13149        }
13150    }
13151
13152    // ── Interval tests (br-frankenpandas-j8k4) ──────────────────────────
13153
13154    #[test]
13155    fn interval_default_closed_is_right() {
13156        assert_eq!(IntervalClosed::default(), IntervalClosed::Right);
13157    }
13158
13159    #[test]
13160    fn interval_left_and_right_closed_helpers() {
13161        assert!(IntervalClosed::Left.left_closed());
13162        assert!(!IntervalClosed::Left.right_closed());
13163        assert!(!IntervalClosed::Right.left_closed());
13164        assert!(IntervalClosed::Right.right_closed());
13165        assert!(IntervalClosed::Both.left_closed());
13166        assert!(IntervalClosed::Both.right_closed());
13167        assert!(!IntervalClosed::Neither.left_closed());
13168        assert!(!IntervalClosed::Neither.right_closed());
13169    }
13170
13171    #[test]
13172    fn interval_display_matches_pandas_notation() {
13173        assert_eq!(
13174            Interval::new(0.0, 5.0, IntervalClosed::Right).to_string(),
13175            "(0.0, 5.0]"
13176        );
13177        assert_eq!(
13178            Interval::new(0.0, 5.0, IntervalClosed::Left).to_string(),
13179            "[0.0, 5.0)"
13180        );
13181        assert_eq!(
13182            Interval::new(0.0, 5.0, IntervalClosed::Both).to_string(),
13183            "[0.0, 5.0]"
13184        );
13185        assert_eq!(
13186            Interval::new(0.0, 5.0, IntervalClosed::Neither).to_string(),
13187            "(0.0, 5.0)"
13188        );
13189        assert_eq!(
13190            Interval::new(2.5, 3.5, IntervalClosed::Right).to_string(),
13191            "(2.5, 3.5]"
13192        );
13193        assert_eq!(
13194            Interval::new(-1.0, 0.0, IntervalClosed::Right).to_string(),
13195            "(-1.0, 0.0]"
13196        );
13197        assert_eq!(
13198            Interval::new(1e20, 2e20, IntervalClosed::Right).to_string(),
13199            "(1e+20, 2e+20]"
13200        );
13201    }
13202
13203    #[test]
13204    fn interval_length_and_mid() {
13205        let i = Interval::new(2.0, 10.0, IntervalClosed::Right);
13206        assert_eq!(i.length(), 8.0);
13207        assert_eq!(i.mid(), 6.0);
13208    }
13209
13210    #[test]
13211    fn interval_contains_matches_closed_policy() {
13212        let right = Interval::new(0.0, 5.0, IntervalClosed::Right);
13213        assert!(!right.contains(0.0));
13214        assert!(right.contains(2.5));
13215        assert!(right.contains(5.0));
13216
13217        let left = Interval::new(0.0, 5.0, IntervalClosed::Left);
13218        assert!(left.contains(0.0));
13219        assert!(left.contains(2.5));
13220        assert!(!left.contains(5.0));
13221
13222        let both = Interval::new(0.0, 5.0, IntervalClosed::Both);
13223        assert!(both.contains(0.0));
13224        assert!(both.contains(5.0));
13225
13226        let neither = Interval::new(0.0, 5.0, IntervalClosed::Neither);
13227        assert!(!neither.contains(0.0));
13228        assert!(!neither.contains(5.0));
13229        assert!(neither.contains(2.5));
13230    }
13231
13232    #[test]
13233    fn interval_contains_nan_returns_false() {
13234        let i = Interval::new(0.0, 10.0, IntervalClosed::Both);
13235        assert!(!i.contains(f64::NAN));
13236    }
13237
13238    #[test]
13239    fn interval_is_empty_matches_pandas() {
13240        // pd.Interval(3, 3, 'right').is_empty → True
13241        assert!(Interval::new(3.0, 3.0, IntervalClosed::Right).is_empty());
13242        assert!(Interval::new(3.0, 3.0, IntervalClosed::Left).is_empty());
13243        assert!(Interval::new(3.0, 3.0, IntervalClosed::Neither).is_empty());
13244        // pd.Interval(3, 3, 'both').is_empty → False (single point)
13245        assert!(!Interval::new(3.0, 3.0, IntervalClosed::Both).is_empty());
13246        // Non-degenerate intervals are never empty.
13247        assert!(!Interval::new(0.0, 5.0, IntervalClosed::Right).is_empty());
13248    }
13249
13250    #[test]
13251    fn interval_overlaps_disjoint_returns_false() {
13252        let a = Interval::new(0.0, 1.0, IntervalClosed::Right);
13253        let b = Interval::new(2.0, 3.0, IntervalClosed::Right);
13254        assert!(!a.overlaps(&b));
13255        assert!(!b.overlaps(&a));
13256    }
13257
13258    #[test]
13259    fn interval_overlaps_nested_returns_true() {
13260        let outer = Interval::new(0.0, 10.0, IntervalClosed::Right);
13261        let inner = Interval::new(3.0, 7.0, IntervalClosed::Right);
13262        assert!(outer.overlaps(&inner));
13263        assert!(inner.overlaps(&outer));
13264    }
13265
13266    #[test]
13267    fn interval_overlaps_touching_respects_closed_policy() {
13268        // (0, 1] touching (1, 2] at point 1.
13269        let right_right = (
13270            Interval::new(0.0, 1.0, IntervalClosed::Right),
13271            Interval::new(1.0, 2.0, IntervalClosed::Right),
13272        );
13273        // right_right.0 is closed at 1; right_right.1 is open at 1 → no overlap.
13274        assert!(!right_right.0.overlaps(&right_right.1));
13275
13276        // [0, 1] touching [1, 2] — both closed at 1 → overlap.
13277        let both_both = (
13278            Interval::new(0.0, 1.0, IntervalClosed::Both),
13279            Interval::new(1.0, 2.0, IntervalClosed::Both),
13280        );
13281        assert!(both_both.0.overlaps(&both_both.1));
13282    }
13283
13284    #[test]
13285    fn interval_roundtrips_through_serde_json() {
13286        let i = Interval::new(1.5, 3.25, IntervalClosed::Both);
13287        let json = serde_json::to_string(&i).expect("serialize");
13288        let back: Interval = serde_json::from_str(&json).expect("deserialize");
13289        assert_eq!(i, back);
13290    }
13291
13292    #[test]
13293    fn interval_serde_default_closed_is_right_when_missing() {
13294        // JSON payloads that omit `closed` deserialize with the pandas default.
13295        let back: Interval =
13296            serde_json::from_str(r#"{"left":0.0,"right":5.0}"#).expect("deserialize");
13297        assert_eq!(back.closed, IntervalClosed::Right);
13298    }
13299
13300    // ── Period tests (br-frankenpandas-epoj) ────────────────────────────
13301
13302    #[test]
13303    fn period_freq_parses_canonical_aliases() {
13304        assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::Annual));
13305        assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::Annual));
13306        assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::Quarterly));
13307        assert_eq!(PeriodFreq::parse("M"), Some(PeriodFreq::Monthly));
13308        assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::Weekly));
13309        assert_eq!(PeriodFreq::parse("D"), Some(PeriodFreq::Daily));
13310        assert_eq!(PeriodFreq::parse("B"), Some(PeriodFreq::Business));
13311        assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
13312        assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
13313        assert_eq!(PeriodFreq::parse("min"), Some(PeriodFreq::Minutely));
13314        assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
13315    }
13316
13317    #[test]
13318    fn period_freq_parse_is_case_insensitive() {
13319        assert_eq!(PeriodFreq::parse("quarterly"), Some(PeriodFreq::Quarterly));
13320        assert_eq!(PeriodFreq::parse("MONTHLY"), Some(PeriodFreq::Monthly));
13321    }
13322
13323    #[test]
13324    fn period_freq_rejects_unknown_aliases() {
13325        assert_eq!(PeriodFreq::parse("nanosec"), None);
13326        assert_eq!(PeriodFreq::parse(""), None);
13327        assert_eq!(PeriodFreq::parse("xyz"), None);
13328    }
13329
13330    #[test]
13331    fn period_freq_alias_roundtrip() {
13332        for freq in [
13333            PeriodFreq::Annual,
13334            PeriodFreq::Quarterly,
13335            PeriodFreq::Monthly,
13336            PeriodFreq::Weekly,
13337            PeriodFreq::Daily,
13338            PeriodFreq::Business,
13339            PeriodFreq::Hourly,
13340            PeriodFreq::Minutely,
13341            PeriodFreq::Secondly,
13342            PeriodFreq::Milliseconds,
13343            PeriodFreq::Microseconds,
13344            PeriodFreq::Nanoseconds,
13345        ] {
13346            assert_eq!(PeriodFreq::parse(freq.alias()), Some(freq));
13347        }
13348    }
13349
13350    /// The three sub-second frequencies pandas' `to_period` accepts and this
13351    /// crate used to reject. Transcribed from live pandas 2.2.3 on
13352    /// `Timestamp('2024-03-15 10:30:45.123456789')`.
13353    #[test]
13354    fn period_freq_subsecond_units_match_pandas() {
13355        // Aliases and resolution words.
13356        assert_eq!(PeriodFreq::Milliseconds.alias(), "ms");
13357        assert_eq!(PeriodFreq::Microseconds.alias(), "us");
13358        assert_eq!(PeriodFreq::Nanoseconds.alias(), "ns");
13359        assert_eq!(PeriodFreq::Milliseconds.resolution(), Some("millisecond"));
13360        assert_eq!(PeriodFreq::Microseconds.resolution(), Some("microsecond"));
13361        assert_eq!(PeriodFreq::Nanoseconds.resolution(), Some("nanosecond"));
13362
13363        // ⚠️ THE ONE CASE-SENSITIVE ALIAS. pandas reads bare "MS" as month start
13364        // and refuses it here, while every other casing of "ms" is milliseconds.
13365        assert_eq!(PeriodFreq::parse("ms"), Some(PeriodFreq::Milliseconds));
13366        assert_eq!(PeriodFreq::parse("Ms"), Some(PeriodFreq::Milliseconds));
13367        assert_eq!(PeriodFreq::parse("mS"), Some(PeriodFreq::Milliseconds));
13368        assert_eq!(PeriodFreq::parse("MS"), None);
13369        // us/ns are case-insensitive in pandas, so both casings resolve.
13370        assert_eq!(PeriodFreq::parse("us"), Some(PeriodFreq::Microseconds));
13371        assert_eq!(PeriodFreq::parse("US"), Some(PeriodFreq::Microseconds));
13372        assert_eq!(PeriodFreq::parse("ns"), Some(PeriodFreq::Nanoseconds));
13373        assert_eq!(PeriodFreq::parse("NS"), Some(PeriodFreq::Nanoseconds));
13374
13375        // Ordinals are unit counts since the epoch; labels pad the fraction to
13376        // the full width of the frequency and never trim trailing zeros.
13377        assert_eq!(
13378            Period::new(1_710_498_645_123, PeriodFreq::Milliseconds).calendar_string(),
13379            "2024-03-15 10:30:45.123"
13380        );
13381        assert_eq!(
13382            Period::new(1_710_498_645_123_456, PeriodFreq::Microseconds).calendar_string(),
13383            "2024-03-15 10:30:45.123456"
13384        );
13385        assert_eq!(
13386            Period::new(1_710_498_645_123_456_789, PeriodFreq::Nanoseconds).calendar_string(),
13387            "2024-03-15 10:30:45.123456789"
13388        );
13389
13390        // A whole-second instant still shows its zero fraction, and the
13391        // pre-epoch ordinals are the FLOOR, not a truncation toward zero:
13392        // Timestamp('1969-12-31 23:59:59.999') at 'ms' has ordinal -1.
13393        assert_eq!(
13394            Period::new(0, PeriodFreq::Milliseconds).calendar_string(),
13395            "1970-01-01 00:00:00.000"
13396        );
13397        assert_eq!(
13398            Period::new(-1, PeriodFreq::Milliseconds).calendar_string(),
13399            "1969-12-31 23:59:59.999"
13400        );
13401        assert_eq!(
13402            Period::new(-1_000, PeriodFreq::Microseconds).calendar_string(),
13403            "1969-12-31 23:59:59.999000"
13404        );
13405        assert_eq!(
13406            Period::new(-999_999, PeriodFreq::Nanoseconds).calendar_string(),
13407            "1969-12-31 23:59:59.999000001"
13408        );
13409    }
13410
13411    #[test]
13412    fn period_freq_anchored_aliases_are_pandas_canonical_h2wiv() {
13413        assert_eq!(PeriodFreq::Annual.alias(), "Y-DEC");
13414        assert_eq!(PeriodFreq::Quarterly.alias(), "Q-DEC");
13415        assert_eq!(PeriodFreq::Weekly.alias(), "W-SUN");
13416
13417        assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::Annual));
13418        assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::Annual));
13419        assert_eq!(PeriodFreq::parse("Y-DEC"), Some(PeriodFreq::Annual));
13420        assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::Quarterly));
13421        assert_eq!(PeriodFreq::parse("Q-DEC"), Some(PeriodFreq::Quarterly));
13422        assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::Weekly));
13423        assert_eq!(PeriodFreq::parse("W-SUN"), Some(PeriodFreq::Weekly));
13424    }
13425
13426    #[test]
13427    fn period_freq_intraday_aliases_are_pandas_canonical_8kfdo() {
13428        assert_eq!(PeriodFreq::Hourly.alias(), "h");
13429        assert_eq!(PeriodFreq::Minutely.alias(), "min");
13430        assert_eq!(PeriodFreq::Secondly.alias(), "s");
13431
13432        assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
13433        assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
13434        assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
13435    }
13436
13437    /// The resolution table is the COMPONENT WORD, never the frequency alias.
13438    /// Transcribed from live pandas 2.2.3: `pd.PeriodIndex([ts], freq=f).resolution`
13439    /// for each f, with W and B raising AttributeError.
13440    #[test]
13441    fn period_freq_resolution_is_the_component_word_not_the_alias() {
13442        assert_eq!(PeriodFreq::Annual.resolution(), Some("year"));
13443        assert_eq!(PeriodFreq::Quarterly.resolution(), Some("quarter"));
13444        assert_eq!(PeriodFreq::Monthly.resolution(), Some("month"));
13445        assert_eq!(PeriodFreq::Daily.resolution(), Some("day"));
13446        assert_eq!(PeriodFreq::Hourly.resolution(), Some("hour"));
13447        assert_eq!(PeriodFreq::Minutely.resolution(), Some("minute"));
13448        assert_eq!(PeriodFreq::Secondly.resolution(), Some("second"));
13449
13450        // pandas raises AttributeError for these two rather than answering.
13451        assert_eq!(PeriodFreq::Weekly.resolution(), None);
13452        assert_eq!(PeriodFreq::Business.resolution(), None);
13453
13454        // The bug this replaces was the alias table copied into the resolution
13455        // slot, so pin the two apart: no frequency may report the same string
13456        // for both. (Every pandas alias is short and lowercase-ish; every
13457        // resolution word is a full English noun -- they never coincide.)
13458        for freq in [
13459            PeriodFreq::Annual,
13460            PeriodFreq::Quarterly,
13461            PeriodFreq::Monthly,
13462            PeriodFreq::Weekly,
13463            PeriodFreq::Daily,
13464            PeriodFreq::Business,
13465            PeriodFreq::Hourly,
13466            PeriodFreq::Minutely,
13467            PeriodFreq::Secondly,
13468        ] {
13469            assert_ne!(
13470                Some(freq.alias()),
13471                freq.resolution(),
13472                "{freq:?} reports its alias as its resolution again"
13473            );
13474        }
13475    }
13476
13477    #[test]
13478    fn period_scalar_accessors_match_pandas_star8() {
13479        let period = Period::new(600, PeriodFreq::Monthly);
13480
13481        assert_eq!(period.ordinal(), 600);
13482        assert_eq!(period.freq(), PeriodFreq::Monthly);
13483        assert_eq!(period.freqstr(), "M");
13484    }
13485
13486    #[test]
13487    fn period_parse_common_pandas_ordinals_avm08() {
13488        assert_eq!(
13489            Period::parse("2024").unwrap(),
13490            Period::new(54, PeriodFreq::Annual)
13491        );
13492        assert_eq!(
13493            Period::parse("2024Q1").unwrap(),
13494            Period::new(216, PeriodFreq::Quarterly)
13495        );
13496        assert_eq!(
13497            Period::parse("2024-01").unwrap(),
13498            Period::new(648, PeriodFreq::Monthly)
13499        );
13500        assert_eq!(
13501            Period::parse("2024-01-15").unwrap(),
13502            Period::new(19_737, PeriodFreq::Daily)
13503        );
13504        assert!(Period::parse("216").is_err());
13505    }
13506
13507    #[test]
13508    fn period_shift_advances_ordinal() {
13509        let q1 = Period::new(216, PeriodFreq::Quarterly);
13510        let q2 = q1.shift(1);
13511        assert_eq!(q2.ordinal, 217);
13512        assert_eq!(q2.freq, PeriodFreq::Quarterly);
13513        let q0 = q1.shift(-1);
13514        assert_eq!(q0.ordinal, 215);
13515    }
13516
13517    #[test]
13518    fn period_shift_saturates_on_overflow() {
13519        let p = Period::new(i64::MAX - 2, PeriodFreq::Daily);
13520        assert_eq!(p.shift(100).ordinal, i64::MAX);
13521        let p = Period::new(i64::MIN + 2, PeriodFreq::Daily);
13522        assert_eq!(p.shift(-100).ordinal, i64::MIN);
13523    }
13524
13525    #[test]
13526    fn period_diff_returns_period_count() {
13527        let a = Period::new(216, PeriodFreq::Quarterly);
13528        let b = Period::new(220, PeriodFreq::Quarterly);
13529        assert_eq!(b.diff(&a), Some(4));
13530        assert_eq!(a.diff(&b), Some(-4));
13531    }
13532
13533    #[test]
13534    fn period_diff_rejects_mismatched_freq() {
13535        let monthly = Period::new(100, PeriodFreq::Monthly);
13536        let quarterly = Period::new(100, PeriodFreq::Quarterly);
13537        assert_eq!(monthly.diff(&quarterly), None);
13538        assert_eq!(quarterly.diff(&monthly), None);
13539    }
13540
13541    #[test]
13542    fn period_cmp_same_freq_respects_ordinal_order() {
13543        use std::cmp::Ordering;
13544        let a = Period::new(10, PeriodFreq::Monthly);
13545        let b = Period::new(20, PeriodFreq::Monthly);
13546        assert_eq!(a.cmp_same_freq(&b), Some(Ordering::Less));
13547        assert_eq!(b.cmp_same_freq(&a), Some(Ordering::Greater));
13548        assert_eq!(a.cmp_same_freq(&a), Some(Ordering::Equal));
13549    }
13550
13551    #[test]
13552    fn period_cmp_cross_freq_returns_none() {
13553        let m = Period::new(1, PeriodFreq::Monthly);
13554        let q = Period::new(1, PeriodFreq::Quarterly);
13555        assert_eq!(m.cmp_same_freq(&q), None);
13556    }
13557
13558    #[test]
13559    fn period_arithmetic_matches_seeded_oracles_bac28() {
13560        use std::cmp::Ordering;
13561
13562        fn next(seed: &mut u64) -> u64 {
13563            *seed = seed
13564                .wrapping_mul(2862933555777941757)
13565                .wrapping_add(3037000493);
13566            *seed
13567        }
13568
13569        fn freq_for(raw: u64) -> PeriodFreq {
13570            // All TWELVE frequencies. This stopped at nine, so no property
13571            // test here ever generated a sub-second period.
13572            match raw % 12 {
13573                0 => PeriodFreq::Annual,
13574                1 => PeriodFreq::Quarterly,
13575                2 => PeriodFreq::Monthly,
13576                3 => PeriodFreq::Weekly,
13577                4 => PeriodFreq::Daily,
13578                5 => PeriodFreq::Business,
13579                6 => PeriodFreq::Hourly,
13580                7 => PeriodFreq::Minutely,
13581                8 => PeriodFreq::Secondly,
13582                9 => PeriodFreq::Milliseconds,
13583                10 => PeriodFreq::Microseconds,
13584                _ => PeriodFreq::Nanoseconds,
13585            }
13586        }
13587
13588        fn different_freq(freq: PeriodFreq) -> PeriodFreq {
13589            match freq {
13590                PeriodFreq::Annual => PeriodFreq::Quarterly,
13591                PeriodFreq::Quarterly => PeriodFreq::Monthly,
13592                PeriodFreq::Monthly => PeriodFreq::Weekly,
13593                PeriodFreq::Weekly => PeriodFreq::Daily,
13594                PeriodFreq::Daily => PeriodFreq::Business,
13595                PeriodFreq::Business => PeriodFreq::Hourly,
13596                PeriodFreq::Hourly => PeriodFreq::Minutely,
13597                PeriodFreq::Minutely => PeriodFreq::Secondly,
13598                // The cycle closes through the sub-second units, so every
13599                // frequency still maps to a DIFFERENT one — the only property
13600                // this helper owes its callers.
13601                PeriodFreq::Secondly => PeriodFreq::Milliseconds,
13602                PeriodFreq::Milliseconds => PeriodFreq::Microseconds,
13603                PeriodFreq::Microseconds => PeriodFreq::Nanoseconds,
13604                PeriodFreq::Nanoseconds => PeriodFreq::Annual,
13605            }
13606        }
13607
13608        fn assert_period_case(
13609            case: usize,
13610            freq: PeriodFreq,
13611            ordinal: i64,
13612            shift_by: i64,
13613            other_ordinal: i64,
13614        ) {
13615            let period = Period::new(ordinal, freq);
13616            let shifted = period.shift(shift_by);
13617            assert_eq!(
13618                shifted.ordinal,
13619                ordinal.saturating_add(shift_by),
13620                "case {case}: shift ordinal"
13621            );
13622            assert_eq!(shifted.freq, freq, "case {case}: shift freq");
13623
13624            let same_freq_other = Period::new(other_ordinal, freq);
13625            assert_eq!(
13626                period.diff(&same_freq_other),
13627                Some(ordinal.saturating_sub(other_ordinal)),
13628                "case {case}: same-freq diff"
13629            );
13630            assert_eq!(
13631                period.cmp_same_freq(&same_freq_other),
13632                Some(ordinal.cmp(&other_ordinal)),
13633                "case {case}: same-freq cmp"
13634            );
13635
13636            let cross_freq_other = Period::new(other_ordinal, different_freq(freq));
13637            assert_eq!(
13638                period.diff(&cross_freq_other),
13639                None,
13640                "case {case}: cross-freq diff"
13641            );
13642            assert_eq!(
13643                period.cmp_same_freq(&cross_freq_other),
13644                None,
13645                "case {case}: cross-freq cmp"
13646            );
13647        }
13648
13649        assert_period_case(usize::MAX, PeriodFreq::Daily, i64::MAX - 2, 10, i64::MIN);
13650        assert_period_case(
13651            usize::MAX - 1,
13652            PeriodFreq::Daily,
13653            i64::MIN + 2,
13654            -10,
13655            i64::MAX,
13656        );
13657        assert_eq!(
13658            Period::new(10, PeriodFreq::Monthly)
13659                .cmp_same_freq(&Period::new(10, PeriodFreq::Monthly)),
13660            Some(Ordering::Equal)
13661        );
13662
13663        let mut seed = 0xbac2_8d1f_0d1c_5eed_u64;
13664        for case in 0..260 {
13665            let freq = freq_for(next(&mut seed));
13666            let ordinal = match case % 53 {
13667                0 => i64::MAX - (next(&mut seed) % 8) as i64,
13668                1 => i64::MIN + (next(&mut seed) % 8) as i64,
13669                _ => (next(&mut seed) % 200_001) as i64 - 100_000,
13670            };
13671            let shift_by = match case % 47 {
13672                0 => 512,
13673                1 => -512,
13674                _ => (next(&mut seed) % 4097) as i64 - 2048,
13675            };
13676            let other_ordinal = match case % 41 {
13677                0 => i64::MAX,
13678                1 => i64::MIN,
13679                _ => (next(&mut seed) % 200_001) as i64 - 100_000,
13680            };
13681            assert_period_case(case, freq, ordinal, shift_by, other_ordinal);
13682        }
13683    }
13684
13685    #[test]
13686    fn period_display_is_pandas_calendar_string() {
13687        // Ordinal 216 on the quarterly axis (1970Q1 == 0) is 1970 + 54y = 2024Q1.
13688        assert_eq!(
13689            Period::new(216, PeriodFreq::Quarterly).to_string(),
13690            "2024Q1"
13691        );
13692        // 1970 + 54 == 2024 on the annual axis.
13693        assert_eq!(Period::new(54, PeriodFreq::Annual).to_string(), "2024");
13694        // 1970-01 == 0 -> 2024-03 is 54*12 + 2 == 650 months.
13695        assert_eq!(Period::new(650, PeriodFreq::Monthly).to_string(), "2024-03");
13696        // Day 0 == 1970-01-01; 2024-01-15.
13697        assert_eq!(
13698            Period::new(fp_days("2024-01-15"), PeriodFreq::Daily).to_string(),
13699            "2024-01-15"
13700        );
13701        assert_eq!(
13702            Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)).to_string(),
13703            "NaT"
13704        );
13705    }
13706
13707    /// The two frequencies whose ordinal is NOT a day count. Both rendered
13708    /// through `civil_from_days` and came out decades wrong; the test above
13709    /// covered Y/Q/M/D and never touched either, which is how it survived.
13710    ///
13711    /// Every string is `str(pd.Period(ordinal=..., freq=...))` on live pandas
13712    /// 2.2.3, and FrankenPandas' own ordinals were confirmed to agree with
13713    /// pandas' at each sampled date before these were taken.
13714    #[test]
13715    fn weekly_and_business_periods_do_not_index_days() {
13716        // ⚠️ WEEKLY IS A RANGE, not a date: the ordinal counts WEEKS from the
13717        // Monday 1969-12-22, and pandas prints the seven days it spans.
13718        // Ordinal 2829 is the week of 2024-03-15 and used to render
13719        // "1977-09-30" — the result of reading a week count as a day count.
13720        for (ordinal, want) in [
13721            (0_i64, "1969-12-22/1969-12-28"),
13722            (1, "1969-12-29/1970-01-04"),
13723            (2829, "2024-03-11/2024-03-17"),
13724            (1540, "1999-06-28/1999-07-04"),
13725            (15237, "2261-12-30/2262-01-05"),
13726            // Pre-epoch, where Euclidean division matters.
13727            (-1, "1969-12-15/1969-12-21"),
13728            (-2829, "1915-10-04/1915-10-10"),
13729        ] {
13730            assert_eq!(
13731                Period::new(ordinal, PeriodFreq::Weekly).to_string(),
13732                want,
13733                "weekly ordinal {ordinal}"
13734            );
13735        }
13736
13737        // ⚠️ BUSINESS COUNTS BUSINESS DAYS — five per week — so consecutive
13738        // ordinals skip the weekend. Ordinal 14141 is 2024-03-15 and used to
13739        // render "2008-09-19".
13740        for (ordinal, want) in [
13741            (0_i64, "1970-01-01"), // a Thursday: the epoch anchors the cycle
13742            (1, "1970-01-02"),     // Friday
13743            (2, "1970-01-05"),     // Monday — the weekend is SKIPPED
13744            (3, "1970-01-06"),
13745            (4, "1970-01-07"),
13746            (5, "1970-01-08"),
13747            (14141, "2024-03-15"),
13748            (76179, "2262-01-01"),
13749            // A Sunday input rolls FORWARD when the ordinal is taken, so 7697
13750            // is the Monday 1999-07-05 rather than 1999-07-04.
13751            (7697, "1999-07-05"),
13752            (-1, "1969-12-31"),
13753            (-5, "1969-12-25"),
13754            (-6, "1969-12-24"),
13755        ] {
13756            assert_eq!(
13757                Period::new(ordinal, PeriodFreq::Business).to_string(),
13758                want,
13759                "business ordinal {ordinal}"
13760            );
13761        }
13762
13763        // Five business ordinals per seven calendar days, checked as a property
13764        // rather than as a table: the same arithmetic the forward map in
13765        // fp-index uses, read backwards.
13766        for ordinal in -400_i64..400 {
13767            let rendered = Period::new(ordinal, PeriodFreq::Business).to_string();
13768            let later = Period::new(ordinal + 5, PeriodFreq::Business).to_string();
13769            assert_ne!(rendered, later, "business ordinals must not repeat");
13770        }
13771
13772        assert_eq!(Period::new(i64::MIN, PeriodFreq::Weekly).to_string(), "NaT");
13773        assert_eq!(
13774            Period::new(i64::MIN, PeriodFreq::Business).to_string(),
13775            "NaT"
13776        );
13777    }
13778
13779    fn period_display_former_profile(period: &Period) -> String {
13780        let calendar = period.calendar_string();
13781        let mut rendered = String::new();
13782        rendered.push_str(&calendar);
13783        rendered
13784    }
13785
13786    fn measure_period_renderer(periods: &[Period], render: impl Fn(&Period) -> String) -> u128 {
13787        use std::{hint::black_box, time::Instant};
13788
13789        let started = Instant::now();
13790        let mut checksum = 0usize;
13791        for period in periods {
13792            let rendered = render(black_box(period));
13793            checksum = checksum.wrapping_add(rendered.len());
13794            drop(black_box(rendered));
13795        }
13796        black_box(checksum);
13797        started.elapsed().as_nanos()
13798    }
13799
13800    #[test]
13801    #[ignore = "release-only attribution probe for br-frankenpandas-6pqra"]
13802    fn profile_period_display_direct_sink_ab_6pqra() {
13803        const FREQUENCIES: [PeriodFreq; 9] = [
13804            PeriodFreq::Annual,
13805            PeriodFreq::Quarterly,
13806            PeriodFreq::Monthly,
13807            PeriodFreq::Weekly,
13808            PeriodFreq::Daily,
13809            PeriodFreq::Business,
13810            PeriodFreq::Hourly,
13811            PeriodFreq::Minutely,
13812            PeriodFreq::Secondly,
13813        ];
13814        const SAMPLES: usize = 10;
13815
13816        let periods = (0..65_536)
13817            .map(|index| {
13818                let ordinal = if index % 4093 == 0 {
13819                    i64::MIN
13820                } else {
13821                    ((index as i64 * 7_919) % 4_000_001) - 2_000_000
13822                };
13823                Period::new(ordinal, FREQUENCIES[index % FREQUENCIES.len()])
13824            })
13825            .collect::<Vec<_>>();
13826
13827        for period in &periods {
13828            assert_eq!(period_display_former_profile(period), period.to_string());
13829        }
13830
13831        for _ in 0..2 {
13832            measure_period_renderer(&periods, period_display_former_profile);
13833            measure_period_renderer(&periods, Period::to_string);
13834        }
13835
13836        let mut former_ns = Vec::with_capacity(SAMPLES);
13837        let mut public_ns = Vec::with_capacity(SAMPLES);
13838        for sample in 0..SAMPLES {
13839            if sample % 2 == 0 {
13840                former_ns.push(measure_period_renderer(
13841                    &periods,
13842                    period_display_former_profile,
13843                ));
13844                public_ns.push(measure_period_renderer(&periods, Period::to_string));
13845            } else {
13846                public_ns.push(measure_period_renderer(&periods, Period::to_string));
13847                former_ns.push(measure_period_renderer(
13848                    &periods,
13849                    period_display_former_profile,
13850                ));
13851            }
13852        }
13853        former_ns.sort_unstable();
13854        public_ns.sort_unstable();
13855        let former_p50 = former_ns[SAMPLES / 2];
13856        let public_p50 = public_ns[SAMPLES / 2];
13857        let former_p95 = former_ns[SAMPLES - 1];
13858        let public_p95 = public_ns[SAMPLES - 1];
13859        println!("PROFILE_PERIOD_DISPLAY_FORMER_NS={former_ns:?}");
13860        println!("PROFILE_PERIOD_DISPLAY_PUBLIC_NS={public_ns:?}");
13861        println!(
13862            "PROFILE_PERIOD_DISPLAY_P50_RATIO={:.6}",
13863            former_p50 as f64 / public_p50 as f64
13864        );
13865        println!(
13866            "PROFILE_PERIOD_DISPLAY_P95_RATIO={:.6}",
13867            former_p95 as f64 / public_p95 as f64
13868        );
13869    }
13870
13871    #[cfg(test)]
13872    fn fp_days(ymd: &str) -> i64 {
13873        Period::parse(ymd).expect("daily period").ordinal
13874    }
13875
13876    #[test]
13877    fn period_roundtrips_through_serde_json() {
13878        let p = Period::new(42, PeriodFreq::Weekly);
13879        let json = serde_json::to_string(&p).expect("serialize");
13880        let back: Period = serde_json::from_str(&json).expect("deserialize");
13881        assert_eq!(p, back);
13882    }
13883
13884    // ── period_range tests (br-frankenpandas-2jef — epoj Phase 2) ───────
13885
13886    use super::period_range;
13887
13888    #[test]
13889    fn period_range_zero_periods_is_empty() {
13890        let start = Period::new(216, PeriodFreq::Quarterly);
13891        assert!(period_range(start, 0).is_empty());
13892    }
13893
13894    #[test]
13895    fn period_range_single_period_returns_start_only() {
13896        let start = Period::new(216, PeriodFreq::Quarterly);
13897        let r = period_range(start, 1);
13898        assert_eq!(r.len(), 1);
13899        assert_eq!(r[0], start);
13900    }
13901
13902    #[test]
13903    fn period_range_increments_ordinal_by_one_per_step() {
13904        let start = Period::new(216, PeriodFreq::Quarterly);
13905        let r = period_range(start, 4);
13906        assert_eq!(r.len(), 4);
13907        assert_eq!(r[0].ordinal, 216);
13908        assert_eq!(r[1].ordinal, 217);
13909        assert_eq!(r[2].ordinal, 218);
13910        assert_eq!(r[3].ordinal, 219);
13911    }
13912
13913    #[test]
13914    fn period_range_preserves_frequency() {
13915        let start = Period::new(0, PeriodFreq::Monthly);
13916        let r = period_range(start, 12);
13917        assert!(r.iter().all(|p| p.freq == PeriodFreq::Monthly));
13918    }
13919
13920    #[test]
13921    fn period_range_negative_starting_ordinal_works() {
13922        // Ordinal axis is signed — pre-epoch periods are valid.
13923        let start = Period::new(-3, PeriodFreq::Annual);
13924        let r = period_range(start, 5);
13925        assert_eq!(
13926            r.iter().map(|p| p.ordinal).collect::<Vec<_>>(),
13927            vec![-3, -2, -1, 0, 1]
13928        );
13929    }
13930
13931    #[test]
13932    fn period_range_large_n_does_not_panic() {
13933        // 1024 monthly periods — large enough to catch any allocation bug.
13934        let start = Period::new(0, PeriodFreq::Monthly);
13935        let r = period_range(start, 1024);
13936        assert_eq!(r.len(), 1024);
13937        assert_eq!(r[1023].ordinal, 1023);
13938    }
13939
13940    #[test]
13941    fn period_range_matches_seeded_ordinal_oracle_z3zh2() {
13942        fn next(seed: &mut u64) -> u64 {
13943            *seed = seed
13944                .wrapping_mul(6364136223846793005)
13945                .wrapping_add(1442695040888963407);
13946            *seed
13947        }
13948
13949        fn freq_for(raw: u64) -> PeriodFreq {
13950            // All TWELVE frequencies. This stopped at nine, so no property
13951            // test here ever generated a sub-second period.
13952            match raw % 12 {
13953                0 => PeriodFreq::Annual,
13954                1 => PeriodFreq::Quarterly,
13955                2 => PeriodFreq::Monthly,
13956                3 => PeriodFreq::Weekly,
13957                4 => PeriodFreq::Daily,
13958                5 => PeriodFreq::Business,
13959                6 => PeriodFreq::Hourly,
13960                7 => PeriodFreq::Minutely,
13961                8 => PeriodFreq::Secondly,
13962                9 => PeriodFreq::Milliseconds,
13963                10 => PeriodFreq::Microseconds,
13964                _ => PeriodFreq::Nanoseconds,
13965            }
13966        }
13967
13968        fn assert_oracle_case(case: usize, start: Period, periods: usize) {
13969            let got = period_range(start, periods);
13970            assert_eq!(got.len(), periods, "case {case}: length");
13971
13972            for (position, period) in got.iter().enumerate() {
13973                let expected_ordinal = start.ordinal.saturating_add(position as i64);
13974                assert_eq!(
13975                    period.ordinal, expected_ordinal,
13976                    "case {case}: ordinal at {position}"
13977                );
13978                assert_eq!(period.freq, start.freq, "case {case}: freq at {position}");
13979            }
13980        }
13981
13982        assert_oracle_case(usize::MAX, Period::new(42, PeriodFreq::Monthly), 0);
13983        assert_oracle_case(
13984            usize::MAX - 1,
13985            Period::new(i64::MAX - 3, PeriodFreq::Daily),
13986            8,
13987        );
13988
13989        let mut seed = 0x9e21_0d1c_5eed_0421_u64;
13990        for case in 0..260 {
13991            let freq = freq_for(next(&mut seed));
13992            let periods = (next(&mut seed) % 80) as usize;
13993            let start_ordinal = if case % 37 == 0 {
13994                i64::MAX - 7
13995            } else {
13996                (next(&mut seed) % 20_001) as i64 - 10_000
13997            };
13998            assert_oracle_case(case, Period::new(start_ordinal, freq), periods);
13999        }
14000    }
14001
14002    // ── interval_range tests (br-frankenpandas-xaom) ────────────────────
14003
14004    use super::{TypeError, interval_range_by_periods, interval_range_by_step};
14005
14006    #[test]
14007    fn interval_range_by_periods_matches_pandas_default_case() {
14008        // pd.interval_range(0, 10, periods=5) → [(0,2],(2,4],(4,6],(6,8],(8,10]]
14009        let bins = interval_range_by_periods(0.0, 10.0, 5, IntervalClosed::Right);
14010        assert_eq!(bins.len(), 5);
14011        for (i, bin) in bins.iter().enumerate() {
14012            assert_eq!(bin.left, (i as f64) * 2.0);
14013            assert_eq!(bin.right, ((i + 1) as f64) * 2.0);
14014            assert_eq!(bin.closed, IntervalClosed::Right);
14015        }
14016    }
14017
14018    #[test]
14019    fn interval_range_by_periods_final_edge_is_exact_end() {
14020        // Guards against accumulated float drift on the last right edge.
14021        let bins = interval_range_by_periods(0.0, 1.0, 7, IntervalClosed::Right);
14022        assert_eq!(bins.last().unwrap().right, 1.0);
14023    }
14024
14025    #[test]
14026    fn interval_range_by_periods_zero_periods_is_empty() {
14027        assert!(interval_range_by_periods(0.0, 10.0, 0, IntervalClosed::Right).is_empty());
14028    }
14029
14030    #[test]
14031    fn interval_range_by_periods_reversed_range_is_empty() {
14032        // pandas: pd.interval_range(10, 0, periods=5) → IntervalIndex([]).
14033        assert!(interval_range_by_periods(10.0, 0.0, 5, IntervalClosed::Right).is_empty());
14034    }
14035
14036    #[test]
14037    fn interval_range_by_periods_preserves_closed_policy() {
14038        for closed in [
14039            IntervalClosed::Left,
14040            IntervalClosed::Right,
14041            IntervalClosed::Both,
14042            IntervalClosed::Neither,
14043        ] {
14044            let bins = interval_range_by_periods(0.0, 4.0, 2, closed);
14045            assert!(bins.iter().all(|b| b.closed == closed));
14046        }
14047    }
14048
14049    #[test]
14050    fn interval_range_by_step_matches_pandas_default_case() {
14051        // pd.interval_range(0, 10, freq=2) → [(0,2],(2,4],(4,6],(6,8],(8,10]]
14052        let bins = interval_range_by_step(0.0, 10.0, 2.0, IntervalClosed::Right).expect("ok");
14053        assert_eq!(bins.len(), 5);
14054        assert_eq!(bins[0].left, 0.0);
14055        assert_eq!(bins[4].right, 10.0);
14056    }
14057
14058    #[test]
14059    fn interval_range_by_step_rejects_non_positive_step() {
14060        assert!(matches!(
14061            interval_range_by_step(0.0, 10.0, 0.0, IntervalClosed::Right),
14062            Err(TypeError::InvalidIntervalStep { .. })
14063        ));
14064        assert!(matches!(
14065            interval_range_by_step(0.0, 10.0, -2.0, IntervalClosed::Right),
14066            Err(TypeError::InvalidIntervalStep { .. })
14067        ));
14068        assert!(matches!(
14069            interval_range_by_step(0.0, 10.0, f64::NAN, IntervalClosed::Right),
14070            Err(TypeError::InvalidIntervalStep { .. })
14071        ));
14072        assert!(matches!(
14073            interval_range_by_step(0.0, 10.0, f64::INFINITY, IntervalClosed::Right),
14074            Err(TypeError::InvalidIntervalStep { .. })
14075        ));
14076    }
14077
14078    #[test]
14079    fn interval_range_by_step_rejects_non_dividing_step() {
14080        // pandas: pd.interval_range(0, 10, freq=3) → ValueError
14081        // (span=10 not divisible by step=3). Reject with IntervalStepDoesNotDivide.
14082        assert!(matches!(
14083            interval_range_by_step(0.0, 10.0, 3.0, IntervalClosed::Right),
14084            Err(TypeError::IntervalStepDoesNotDivide { .. })
14085        ));
14086    }
14087
14088    #[test]
14089    fn interval_range_by_step_reversed_range_is_empty() {
14090        let bins = interval_range_by_step(10.0, 0.0, 2.0, IntervalClosed::Right).expect("ok");
14091        assert!(bins.is_empty());
14092    }
14093
14094    #[test]
14095    fn interval_range_by_step_degenerate_zero_span_is_empty() {
14096        let bins = interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right).expect("ok");
14097        assert!(bins.is_empty());
14098    }
14099
14100    #[test]
14101    fn interval_range_by_step_accepts_float_step_within_tolerance() {
14102        // step=0.1 ten times == 1.0 but float arithmetic produces 0.9999...
14103        let bins = interval_range_by_step(0.0, 1.0, 0.1, IntervalClosed::Right).expect("ok");
14104        assert_eq!(bins.len(), 10);
14105        assert_eq!(bins.last().unwrap().right, 1.0);
14106    }
14107
14108    #[test]
14109    fn interval_range_matches_seeded_arithmetic_oracle_t9ozf() {
14110        // Differential vs independent interval edge oracles
14111        // (br-frankenpandas-t9ozf). Seeded LCG, no mocks.
14112        fn next(seed: &mut u64) -> u64 {
14113            *seed = seed
14114                .wrapping_mul(2862933555777941757)
14115                .wrapping_add(3037000493);
14116            *seed
14117        }
14118
14119        fn closed_for(raw: u64) -> IntervalClosed {
14120            match raw % 4 {
14121                0 => IntervalClosed::Left,
14122                1 => IntervalClosed::Right,
14123                2 => IntervalClosed::Both,
14124                _ => IntervalClosed::Neither,
14125            }
14126        }
14127
14128        fn assert_interval(
14129            case: usize,
14130            kind: &str,
14131            pos: usize,
14132            actual: &Interval,
14133            expected: &Interval,
14134        ) {
14135            assert!(
14136                (actual.left - expected.left).abs() < 1e-12,
14137                "case={case} kind={kind} pos={pos}: expected left {}, got {}",
14138                expected.left,
14139                actual.left
14140            );
14141            assert!(
14142                (actual.right - expected.right).abs() < 1e-12,
14143                "case={case} kind={kind} pos={pos}: expected right {}, got {}",
14144                expected.right,
14145                actual.right
14146            );
14147            assert_eq!(
14148                actual.closed, expected.closed,
14149                "case={case} kind={kind} pos={pos}: closed mismatch"
14150            );
14151        }
14152
14153        fn expected_by_periods(
14154            start: f64,
14155            end: f64,
14156            periods: usize,
14157            closed: IntervalClosed,
14158        ) -> Vec<Interval> {
14159            if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
14160                return Vec::new();
14161            }
14162            let step = (end - start) / periods as f64;
14163            (0..periods)
14164                .map(|pos| {
14165                    let left = start + step * pos as f64;
14166                    let right = if pos + 1 == periods {
14167                        end
14168                    } else {
14169                        start + step * (pos + 1) as f64
14170                    };
14171                    Interval::new(left, right, closed)
14172                })
14173                .collect()
14174        }
14175
14176        fn expected_by_step(
14177            start: f64,
14178            end: f64,
14179            step: f64,
14180            closed: IntervalClosed,
14181        ) -> Vec<Interval> {
14182            if start >= end {
14183                return Vec::new();
14184            }
14185            let count = ((end - start) / step).round() as usize;
14186            (0..count)
14187                .map(|pos| {
14188                    let left = start + step * pos as f64;
14189                    let right = if pos + 1 == count {
14190                        end
14191                    } else {
14192                        start + step * (pos + 1) as f64
14193                    };
14194                    Interval::new(left, right, closed)
14195                })
14196                .collect()
14197        }
14198
14199        assert!(interval_range_by_periods(5.0, 5.0, 4, IntervalClosed::Right).is_empty());
14200        assert!(interval_range_by_periods(5.0, 4.0, 4, IntervalClosed::Right).is_empty());
14201        assert!(
14202            interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right)
14203                .expect("zero span")
14204                .is_empty()
14205        );
14206
14207        let mut seed = 0x171e_7a11_c0de_5eed_u64;
14208        for case in 0..220 {
14209            let start = (next(&mut seed) % 2_001) as f64 / 10.0 - 100.0;
14210            let periods = (next(&mut seed) % 24 + 1) as usize;
14211            let width = (next(&mut seed) % 1_000 + 1) as f64 / 4.0;
14212            let end = start + width;
14213            let closed = closed_for(next(&mut seed));
14214
14215            let actual = interval_range_by_periods(start, end, periods, closed);
14216            let expected = expected_by_periods(start, end, periods, closed);
14217            assert_eq!(
14218                actual.len(),
14219                expected.len(),
14220                "case={case} periods: length mismatch"
14221            );
14222            for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
14223                assert_interval(case, "periods", pos, actual, expected);
14224            }
14225
14226            let step_count = (next(&mut seed) % 20 + 1) as usize;
14227            let step = (next(&mut seed) % 25 + 1) as f64;
14228            let step_end = start + step * step_count as f64;
14229            let actual = interval_range_by_step(start, step_end, step, closed).expect("divides");
14230            let expected = expected_by_step(start, step_end, step, closed);
14231            assert_eq!(
14232                actual.len(),
14233                expected.len(),
14234                "case={case} step: length mismatch"
14235            );
14236            for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
14237                assert_interval(case, "step", pos, actual, expected);
14238            }
14239        }
14240    }
14241
14242    // ── Timedelta arithmetic tests (br-frankenpandas-4r56 Phase 1) ──────
14243
14244    use super::Timedelta;
14245
14246    #[test]
14247    fn timedelta_add_sums_non_nat() {
14248        let one_hour = Timedelta::NANOS_PER_HOUR;
14249        let one_day = Timedelta::NANOS_PER_DAY;
14250        assert_eq!(Timedelta::add(one_hour, one_day), one_hour + one_day);
14251    }
14252
14253    #[test]
14254    fn timedelta_add_propagates_nat() {
14255        assert_eq!(Timedelta::add(Timedelta::NAT, 100), Timedelta::NAT);
14256        assert_eq!(Timedelta::add(100, Timedelta::NAT), Timedelta::NAT);
14257        assert_eq!(
14258            Timedelta::add(Timedelta::NAT, Timedelta::NAT),
14259            Timedelta::NAT
14260        );
14261    }
14262
14263    #[test]
14264    fn timedelta_add_returns_nat_on_overflow() {
14265        // CORRECTED br-frankenpandas-lgyy8. This test previously asserted
14266        // `add(i64::MAX - 10, 100) == i64::MAX`, i.e. that positive overflow
14267        // yields a finite, plausible duration. Live pandas 2.2.3 raises
14268        // OverflowError for `pd.Timedelta.max + pd.Timedelta('1ns')` and never
14269        // returns a fabricated finite value, so the old expectation encoded a
14270        // fail-open bug. Overflow is now NaT in BOTH directions.
14271        assert_eq!(Timedelta::add(i64::MAX - 10, 100), Timedelta::NAT);
14272        // Negative side is unchanged: i64::MIN IS the NaT sentinel, so this
14273        // already surfaced as missing (pandas: Timedelta.min + -1ns -> NaT).
14274        assert_eq!(Timedelta::add(i64::MIN + 10, -100), Timedelta::NAT);
14275    }
14276
14277    #[test]
14278    fn timedelta_sub_subtracts_non_nat() {
14279        let one_hour = Timedelta::NANOS_PER_HOUR;
14280        assert_eq!(
14281            Timedelta::sub(one_hour, Timedelta::NANOS_PER_MIN),
14282            one_hour - Timedelta::NANOS_PER_MIN
14283        );
14284    }
14285
14286    #[test]
14287    fn timedelta_sub_propagates_nat() {
14288        assert_eq!(Timedelta::sub(Timedelta::NAT, 100), Timedelta::NAT);
14289        assert_eq!(Timedelta::sub(100, Timedelta::NAT), Timedelta::NAT);
14290    }
14291
14292    #[test]
14293    fn timedelta_neg_flips_sign_non_nat() {
14294        assert_eq!(Timedelta::neg(5), -5);
14295        assert_eq!(Timedelta::neg(-5), 5);
14296        assert_eq!(Timedelta::neg(0), 0);
14297    }
14298
14299    #[test]
14300    fn timedelta_neg_preserves_nat() {
14301        assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
14302    }
14303
14304    #[test]
14305    fn timedelta_abs_returns_magnitude() {
14306        assert_eq!(Timedelta::abs(-5), 5);
14307        assert_eq!(Timedelta::abs(5), 5);
14308        assert_eq!(Timedelta::abs(0), 0);
14309        assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
14310    }
14311
14312    #[test]
14313    fn neg_and_abs_at_the_representable_floor_are_not_overflow_fyr1z() {
14314        // br-frankenpandas-fyr1z. Until this test existed, `neg`/`abs` were
14315        // only exercised at ±5 and 0, and the doc comment on `neg` asserted
14316        // the OPPOSITE of pandas: "pandas: `-pd.Timedelta.min` is NaT since
14317        // min == -max - 1 cannot be negated". Both halves are false, so an
14318        // implementer trusting the comment could have replaced
14319        // `saturating_neg()` with a NaT arm and broken parity without failing
14320        // a single existing assertion. Measured against the installed oracle,
14321        // pandas 2.2.3:
14322        //   pd.Timedelta.min.value                 == -9223372036854775807
14323        //   -pd.Timedelta.min                      -> Timedelta.max (NOT NaT)
14324        //   abs(pd.Timedelta.min)                  -> Timedelta.max (NOT NaT)
14325        //   -Series([Timedelta.min])               -> [Timedelta.max]
14326        //   Series([Timedelta.min]).abs()          -> [Timedelta.max]
14327        //
14328        // The reason there is no overflow to handle: pandas' representable
14329        // range is symmetric about zero because i64::MIN is spent on the NaT
14330        // sentinel, exactly as it is here.
14331        const MAX: i64 = i64::MAX;
14332        const MIN_OK: i64 = i64::MIN + 1; // most-negative NON-NaT value
14333
14334        // The range really is symmetric — this is the premise the old comment
14335        // denied, and everything below follows from it.
14336        assert_eq!(MIN_OK, -MAX);
14337        assert_eq!(Timedelta::NAT, i64::MIN);
14338
14339        // The cases the false comment would have turned into NaT.
14340        assert_eq!(Timedelta::neg(MIN_OK), MAX);
14341        assert_eq!(Timedelta::neg(MAX), MIN_OK);
14342        assert_eq!(Timedelta::abs(MIN_OK), MAX);
14343        assert_eq!(Timedelta::abs(MAX), MAX);
14344
14345        // Round-tripping the floor must be exact, not sticky at a saturation
14346        // clamp: a `saturating_*` impl that ever clamped would land on
14347        // i64::MIN here and read as NaT.
14348        assert_eq!(Timedelta::neg(Timedelta::neg(MIN_OK)), MIN_OK);
14349        assert_ne!(Timedelta::neg(MIN_OK), Timedelta::NAT);
14350        assert_ne!(Timedelta::abs(MIN_OK), Timedelta::NAT);
14351
14352        // NaT itself is still the one input that stays NaT — the guard, not a
14353        // saturation branch, is what handles it.
14354        assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
14355        assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
14356    }
14357
14358    #[test]
14359    fn overflow_divergence_surface_is_only_where_pandas_refuses_fyr1z() {
14360        // br-frankenpandas-fyr1z, the decision bead for DISC-018. The bead was
14361        // filed on the premise "pandas raises; FP returns NaT", which would
14362        // make EVERY overflow a divergence. Probing live pandas 2.2.3 refutes
14363        // that: on the vectorized surface — the one users actually meet —
14364        // pandas returns NaT itself in several of these cases, so FP already
14365        // agrees there and a blanket "STRICT raises" mode would INTRODUCE
14366        // divergence rather than remove it.
14367        //
14368        // This test pins the agreement half. It is the negative control for
14369        // the divergence half already pinned by
14370        // `arithmetic_overflow_never_fabricates_a_finite_value_lgyy8`.
14371        const MAX: i64 = i64::MAX;
14372        const MIN_OK: i64 = i64::MIN + 1;
14373
14374        // ── AGREEMENT: pandas returns NaT here too, measured ───────────────
14375        // Series([Timedelta.max]) / 0    -> [NaT]
14376        // Series([Timedelta.max]) // 0   -> [NaT]
14377        // Series([Timedelta.max]) / 0.0  -> [NaT]
14378        assert_eq!(Timedelta::div_scalar(MAX, 0), Timedelta::NAT);
14379        assert_eq!(Timedelta::div_scalar(MIN_OK, 0), Timedelta::NAT);
14380        assert_eq!(Timedelta::div_scalar(0, 0), Timedelta::NAT);
14381
14382        // Series([Timedelta.min]) - Timedelta('1ns') -> [NaT], because the
14383        // result lands exactly on the i64::MIN sentinel. FP and pandas agree
14384        // — but only by SENTINEL COLLISION, not by policy. One further step
14385        // (`min - 2ns`) is `OverflowError: Overflow in int64 addition` in
14386        // pandas while FP still says NaT, which is the real divergence. A
14387        // test that only checked the 1ns case would therefore prove nothing;
14388        // both depths are asserted so the pair stays honest.
14389        assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT); // pandas: NaT
14390        assert_eq!(Timedelta::sub(MIN_OK, 2), Timedelta::NAT); // pandas: RAISES
14391        assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(1).is_nat());
14392        assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(2).is_nat());
14393
14394        // ── DIVERGENCE: pandas refuses, FP surfaces NaT ────────────────────
14395        // Kept adjacent to the agreement cases so the boundary between the
14396        // two halves is visible in one place; DISC-018 is the prose record.
14397        assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
14398        assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
14399        assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
14400
14401        // ── CONTROL: representable results are untouched by any of this ────
14402        assert_eq!(Timedelta::div_scalar(MAX, 1), MAX);
14403        assert_eq!(Timedelta::div_scalar(-100, 3), -34); // floor, not trunc
14404        assert_eq!(Timedelta::div_scalar(100, -3), -34);
14405        assert_eq!(Timedelta::sub(MIN_OK + 2, 1), MIN_OK + 1);
14406    }
14407
14408    #[test]
14409    fn timedelta_mul_scalar_scales() {
14410        let three_hours = Timedelta::NANOS_PER_HOUR * 3;
14411        assert_eq!(
14412            Timedelta::mul_scalar(Timedelta::NANOS_PER_HOUR, 3),
14413            three_hours
14414        );
14415        assert_eq!(Timedelta::mul_scalar(100, 0), 0);
14416        assert_eq!(Timedelta::mul_scalar(100, -2), -200);
14417    }
14418
14419    #[test]
14420    fn timedelta_mul_scalar_returns_nat_on_overflow() {
14421        // CORRECTED br-frankenpandas-lgyy8: previously asserted i64::MAX.
14422        // pandas `pd.Timedelta.max * 2` raises OverflowError.
14423        assert_eq!(Timedelta::mul_scalar(i64::MAX, 2), Timedelta::NAT);
14424        assert_eq!(Timedelta::mul_scalar(i64::MIN + 1, 2), Timedelta::NAT);
14425    }
14426
14427    #[test]
14428    fn from_unit_nan_is_nat_and_overflow_is_err_8v92m() {
14429        use super::TimedeltaError;
14430
14431        // br-frankenpandas-8v92m. Rust's float->int `as` maps NaN to 0 and
14432        // saturates infinities, so the unguarded
14433        //     Ok((value * multiplier as f64).round() as i64)
14434        // failed OPEN twice: NaN became a ZERO DURATION, and inf/1e30 became a
14435        // finite plausible ~106751-day duration. Live pandas 2.2.3:
14436        //   pd.Timedelta(nan, unit='s')   -> NaT
14437        //   pd.Timedelta(inf, unit='s')   -> OutOfBoundsTimedelta
14438        //                                    "Cannot cast inf from s to 'ns' without overflow."
14439        //   pd.Timedelta(1e30, unit='s')  -> OutOfBoundsTimedelta
14440        //   pd.Timedelta(1.5, unit='s')   -> Timedelta('0 days 00:00:01.5')  <- must NOT change
14441        // The guard is copied from the two siblings that already had it
14442        // (br-frankenpandas-zw3mg), which is why `parse` behaviour is pinned
14443        // below too: all three copies must now agree.
14444
14445        // ── NaN -> NaT, NOT zero. This is the load-bearing case: an impl that
14446        // returns Ok(0) fails, and so does one that returns Err, because
14447        // pandas gives NaT rather than raising.
14448        assert_eq!(Timedelta::from_unit(f64::NAN, "s"), Ok(Timedelta::NAT));
14449        assert_ne!(Timedelta::from_unit(f64::NAN, "s"), Ok(0));
14450        assert_eq!(Timedelta::from_unit(f64::NAN, "D"), Ok(Timedelta::NAT));
14451
14452        // ── non-finite / out-of-range -> Overflow, not a saturated duration.
14453        assert_eq!(
14454            Timedelta::from_unit(f64::INFINITY, "s"),
14455            Err(TimedeltaError::Overflow)
14456        );
14457        assert_eq!(
14458            Timedelta::from_unit(f64::NEG_INFINITY, "s"),
14459            Err(TimedeltaError::Overflow)
14460        );
14461        assert_eq!(
14462            Timedelta::from_unit(1e30, "s"),
14463            Err(TimedeltaError::Overflow)
14464        );
14465        assert_eq!(
14466            Timedelta::from_unit(1e30, "D"),
14467            Err(TimedeltaError::Overflow)
14468        );
14469
14470        // ── CONTROL: ordinary values must be untouched, bit-for-bit. An
14471        // over-eager guard that rejected anything large would fail here.
14472        assert_eq!(Timedelta::from_unit(1.5, "s"), Ok(1_500_000_000));
14473        assert_eq!(Timedelta::from_unit(0.0, "s"), Ok(0));
14474        assert_eq!(Timedelta::from_unit(-2.5, "s"), Ok(-2_500_000_000));
14475        assert_eq!(Timedelta::from_unit(1.0, "D"), Ok(Timedelta::NANOS_PER_DAY));
14476        assert_eq!(
14477            Timedelta::from_unit(3.0, "h"),
14478            Ok(3 * Timedelta::NANOS_PER_HOUR)
14479        );
14480        // Just inside the representable range still returns its exact product,
14481        // so the boundary is pinned from the accepting side as well.
14482        let big_days = 100_000.0_f64;
14483        let expected = (big_days * Timedelta::NANOS_PER_DAY as f64).round() as i64;
14484        assert_eq!(Timedelta::from_unit(big_days, "D"), Ok(expected));
14485        assert!(expected > 0, "fixture must stay in range to be a control");
14486
14487        // ── an unknown unit is still InvalidFormat, NOT Overflow — the unit
14488        // check must keep running before the range check.
14489        assert!(matches!(
14490            Timedelta::from_unit(1.0, "nonsense-unit"),
14491            Err(TimedeltaError::InvalidFormat(_))
14492        ));
14493        assert!(matches!(
14494            Timedelta::from_unit(f64::NAN, "nonsense-unit"),
14495            Err(TimedeltaError::InvalidFormat(_)),
14496        ));
14497
14498        // ── the already-guarded sibling is unchanged. NOTE the input shape:
14499        // the compound lexer accepts only digits, '.' and '-', so scientific
14500        // notation is an InvalidFormat, not an Overflow — the overflow case
14501        // needs a long decimal literal (this is zw3mg's own fixture).
14502        let huge = format!("{} days", "9".repeat(18));
14503        assert!(matches!(
14504            Timedelta::parse(&huge),
14505            Err(TimedeltaError::Overflow)
14506        ));
14507        assert!(matches!(
14508            Timedelta::parse("1e100 days"),
14509            Err(TimedeltaError::InvalidFormat(_))
14510        ));
14511    }
14512
14513    #[test]
14514    fn rounding_and_ms_us_overflow_never_fabricates_a_finite_value_kyd16() {
14515        // br-frankenpandas-kyd16, the sibling sweep of lgyy8. Three defects:
14516        //   (1) Timedelta::round used UNCHECKED `(quotient + 1) * unit_nanos`
14517        //       on the round-up branch — debug PANIC, release WRAP to a
14518        //       large-negative duration.
14519        //   (2) Timedelta::floor/ceil and Timestamp::ceil_to/round_to
14520        //       saturated to i64::MAX, a finite plausible duration / ~year-2262
14521        //       instant handed back as real data — while their own sibling
14522        //       Timestamp::floor_to was ALREADY checked.
14523        //   (3) Timestamp::from_millis/from_micros saturated likewise, while
14524        //       their neighbour `fromtimestamp` already returned NaT.
14525        // Live pandas 2.2.3 raises on every one of these and names the cause:
14526        //   Timestamp.max.ceil('D')/round('D') -> OutOfBoundsDatetime
14527        //       "Cannot round 2262-04-11 23:47:16.854775807 to freq=<Day> without overflow"
14528        //   Timestamp.min.floor('D')           -> OutOfBoundsDatetime (same)
14529        //   Timedelta.max.ceil('D')/round('D') -> OutOfBoundsTimedelta (same shape)
14530        //   Timedelta.min.floor('D')           -> OutOfBoundsTimedelta (same)
14531        // ...but Timestamp.max.floor('D') is an ordinary in-range answer and
14532        // must NOT change. Both halves are asserted below.
14533        const MAX: i64 = i64::MAX;
14534        const MIN_OK: i64 = i64::MIN + 1;
14535        const DAY: i64 = Timedelta::NANOS_PER_DAY;
14536
14537        // ── (1) round(): must not panic, must not wrap negative ────────────
14538        let rounded = Timedelta::round(MAX, "D");
14539        assert_eq!(
14540            rounded,
14541            Timedelta::NAT,
14542            "rounding i64::MAX up to a whole day overflows; the old unchecked \
14543             multiply panicked in debug and wrapped in release"
14544        );
14545        // The wrap signature specifically: a positive input must never round
14546        // to a negative duration. This fails for a wrapping impl even if the
14547        // debug panic is somehow avoided.
14548        assert!(
14549            rounded == Timedelta::NAT || rounded > 0,
14550            "a positive duration must never round to a negative one"
14551        );
14552        assert_eq!(Timedelta::round(MIN_OK, "D"), Timedelta::NAT);
14553
14554        // ── (2) floor/ceil overflow -> NaT, not a fabricated finite value ──
14555        assert_eq!(Timedelta::ceil(MAX, "D"), Timedelta::NAT);
14556        assert_eq!(Timedelta::floor(MIN_OK, "D"), Timedelta::NAT);
14557        assert!(Timestamp::from_nanos(MAX).ceil_to(DAY).is_nat());
14558        assert!(Timestamp::from_nanos(MAX).round_to(DAY).is_nat());
14559        assert!(Timestamp::from_nanos(MIN_OK).floor_to(DAY).is_nat());
14560        assert!(Timestamp::from_nanos(MIN_OK).round_to(DAY).is_nat());
14561
14562        // ── (3) ms/us constructors out of range -> NaT ─────────────────────
14563        assert!(Timestamp::from_millis(MAX, None).is_nat());
14564        assert!(Timestamp::from_millis(MIN_OK, None).is_nat());
14565        assert!(Timestamp::from_micros(MAX, None).is_nat());
14566        assert!(Timestamp::from_micros(MIN_OK, Some("US/Eastern")).is_nat());
14567
14568        // ── CONTROL: in-range rounding is untouched. An implementation that
14569        // NaT'd too eagerly — or that treated "near the limit" as overflow —
14570        // fails every assertion below.
14571        //
14572        // Timestamp.max.floor('D') is the exact case pandas ANSWERS rather
14573        // than raising, so it pins the boundary from the other side.
14574        let max_floor = Timestamp::from_nanos(MAX).floor_to(DAY);
14575        assert!(!max_floor.is_nat(), "Timestamp.max.floor(D) must succeed");
14576        assert_eq!(max_floor.nanos, (MAX / DAY) * DAY);
14577        assert_eq!(Timedelta::floor(MAX, "D"), (MAX / DAY) * DAY);
14578        assert_eq!(
14579            Timedelta::ceil(MIN_OK, "D"),
14580            (MIN_OK.div_euclid(DAY) + 1) * DAY
14581        );
14582
14583        // Ordinary values, bit-for-bit.
14584        let hour = Timedelta::NANOS_PER_HOUR;
14585        assert_eq!(Timedelta::floor(90 * 60 * 1_000_000_000, "h"), hour);
14586        assert_eq!(Timedelta::ceil(90 * 60 * 1_000_000_000, "h"), 2 * hour);
14587        assert_eq!(Timedelta::round(90 * 60 * 1_000_000_000, "h"), 2 * hour);
14588        assert_eq!(Timedelta::round(-90 * 60 * 1_000_000_000, "h"), -2 * hour);
14589        assert_eq!(Timedelta::round(29 * 60 * 1_000_000_000, "h"), 0);
14590        assert_eq!(Timestamp::from_millis(1_500, None).nanos, 1_500_000_000);
14591        assert_eq!(Timestamp::from_micros(-2_000, None).nanos, -2_000_000);
14592        assert_eq!(
14593            Timestamp::from_nanos(hour + 1).floor_to(hour).nanos,
14594            hour,
14595            "in-range floor unchanged"
14596        );
14597        assert_eq!(
14598            Timestamp::from_nanos(hour + 1).ceil_to(hour).nanos,
14599            2 * hour,
14600            "in-range ceil unchanged"
14601        );
14602
14603        // NaT / degenerate-unit inputs unchanged.
14604        assert_eq!(Timedelta::round(Timedelta::NAT, "D"), Timedelta::NAT);
14605        assert_eq!(Timedelta::floor(Timedelta::NAT, "D"), Timedelta::NAT);
14606        assert_eq!(Timedelta::ceil(1_000, "nonsense-unit"), Timedelta::NAT);
14607        assert!(Timestamp::nat().ceil_to(DAY).is_nat());
14608        assert!(Timestamp::from_nanos(0).round_to(0).is_nat());
14609        // A non-overflowing round still carries its zone.
14610        assert_eq!(
14611            Timestamp::from_nanos_tz(hour + 1, "US/Eastern")
14612                .ceil_to(hour)
14613                .tz
14614                .as_deref(),
14615            Some("US/Eastern")
14616        );
14617    }
14618
14619    #[test]
14620    fn timedelta_mul_scalar_propagates_nat() {
14621        assert_eq!(Timedelta::mul_scalar(Timedelta::NAT, 5), Timedelta::NAT);
14622    }
14623
14624    #[test]
14625    fn arithmetic_overflow_never_fabricates_a_finite_value_lgyy8() {
14626        // br-frankenpandas-lgyy8. The bug: these six helpers used
14627        // `saturating_*`, so POSITIVE overflow returned i64::MAX — a valid,
14628        // finite, plausible duration / ~year-2262 instant — as if it were real
14629        // data. (Negative overflow landed on i64::MIN, which IS the NaT
14630        // sentinel, so that direction already surfaced as missing.) Live
14631        // pandas 2.2.3 never returns a fabricated finite value on overflow in
14632        // either direction, scalar or vectorized:
14633        //   pd.Timedelta.max + Timedelta('1ns')  -> OverflowError
14634        //   pd.Timestamp.max + Timedelta('1ns')  -> OutOfBoundsDatetime
14635        //   pd.Timestamp.min - pd.Timestamp.max  -> OutOfBoundsDatetime
14636        //   pd.Timedelta.max * 2                 -> OverflowError
14637        //   pd.Timedelta.min + Timedelta('-1ns') -> NaT
14638        //
14639        // Every assertion below is a case a saturating implementation FAILS.
14640        const MAX: i64 = i64::MAX;
14641        const MIN_OK: i64 = i64::MIN + 1; // most-negative NON-NaT value
14642
14643        // ── positive overflow: the actual bug ──────────────────────────────
14644        assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
14645        assert_eq!(Timedelta::add(MAX - 10, 100), Timedelta::NAT);
14646        assert_eq!(Timedelta::sub(MAX, -1), Timedelta::NAT);
14647        assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
14648        assert_eq!(Timedelta::mul_scalar(MAX / 2 + 2, 2), Timedelta::NAT);
14649        assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
14650        assert!(Timestamp::from_nanos(MAX).sub_timedelta(-1).is_nat());
14651        // Timestamp.max - Timestamp.min: the true difference is ~2^64, far
14652        // outside i64. Saturation returned MAX (a ~292-year duration presented
14653        // as the real answer); pandas raises OutOfBoundsDatetime.
14654        assert_eq!(
14655            Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(MIN_OK)),
14656            Timedelta::NAT
14657        );
14658
14659        // ── negative overflow: unchanged, still NaT ────────────────────────
14660        assert_eq!(Timedelta::add(MIN_OK, -1), Timedelta::NAT);
14661        assert_eq!(Timedelta::add(MIN_OK, -2), Timedelta::NAT);
14662        assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
14663        assert_eq!(Timedelta::mul_scalar(MIN_OK, 2), Timedelta::NAT);
14664        assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(1).is_nat());
14665        assert!(Timestamp::from_nanos(MIN_OK).add_timedelta(-1).is_nat());
14666        assert_eq!(
14667            Timestamp::from_nanos(MIN_OK).sub_timestamp(&Timestamp::from_nanos(MAX)),
14668            Timedelta::NAT
14669        );
14670
14671        // ── the boundary: the largest REPRESENTABLE results must still be
14672        // returned exactly. This is what stops the fix from being bought with
14673        // an over-eager NaT that swallows valid arithmetic — an implementation
14674        // that NaT'd one step early fails here, as does one that NaT'd on any
14675        // operand near the limits.
14676        assert_eq!(Timedelta::add(MAX - 1, 1), MAX);
14677        assert_eq!(Timedelta::add(MAX, 0), MAX);
14678        assert_eq!(Timedelta::sub(MAX, 1), MAX - 1);
14679        assert_eq!(Timedelta::add(MIN_OK + 1, -1), MIN_OK);
14680        assert_eq!(Timedelta::mul_scalar(MAX / 2, 2), (MAX / 2) * 2);
14681        assert_eq!(Timedelta::mul_scalar(MIN_OK, 1), MIN_OK);
14682        assert_eq!(Timestamp::from_nanos(MAX - 1).add_timedelta(1).nanos, MAX);
14683        assert_eq!(
14684            Timestamp::from_nanos(MIN_OK + 1).sub_timedelta(1).nanos,
14685            MIN_OK
14686        );
14687        assert_eq!(
14688            Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(0)),
14689            MAX
14690        );
14691        // Ordinary values are untouched bit-for-bit.
14692        assert_eq!(Timedelta::add(1_000, 2_345), 3_345);
14693        assert_eq!(Timedelta::sub(1_000, 2_345), -1_345);
14694        assert_eq!(Timedelta::mul_scalar(-7, 6), -42);
14695
14696        // ── a result landing EXACTLY on i64::MIN is representable, but i64::MIN
14697        // IS the NaT sentinel, so it must read as NaT rather than as the most
14698        // negative duration. pandas agrees: Timedelta.min + -1ns -> NaT. Note
14699        // `MIN_OK - 1 == i64::MIN` does not overflow, so this case survives the
14700        // switch from saturating_* to checked_* only because the sentinel and
14701        // the clamp coincide — assert it explicitly rather than by accident.
14702        assert_eq!(MIN_OK - 1, i64::MIN);
14703        assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
14704        assert_eq!(Timedelta::add(MIN_OK, 0), MIN_OK);
14705
14706        // ── NaT operands still propagate, and tz no longer rides along with a
14707        // fabricated instant: an overflowed Timestamp is the canonical NaT.
14708        assert!(Timestamp::nat().add_timedelta(1).is_nat());
14709        assert!(
14710            Timestamp::from_nanos(0)
14711                .add_timedelta(Timedelta::NAT)
14712                .is_nat()
14713        );
14714        let tzed = Timestamp::from_nanos_tz(MAX, "US/Eastern");
14715        let overflowed = tzed.add_timedelta(1);
14716        assert!(overflowed.is_nat());
14717        assert_eq!(overflowed.tz, None, "an overflow NaT carries no zone");
14718        // ...while a NON-overflowing shift still preserves the zone.
14719        assert_eq!(
14720            Timestamp::from_nanos_tz(0, "US/Eastern")
14721                .add_timedelta(Timedelta::NANOS_PER_DAY)
14722                .tz
14723                .as_deref(),
14724            Some("US/Eastern")
14725        );
14726    }
14727
14728    #[test]
14729    fn timedelta_div_scalar_floor_divides() {
14730        // Floor division (matches Python / pandas): -100 // 3 == -34, not -33.
14731        assert_eq!(Timedelta::div_scalar(100, 3), 33);
14732        assert_eq!(Timedelta::div_scalar(-100, 3), -34);
14733        assert_eq!(Timedelta::div_scalar(100, -3), -34);
14734        assert_eq!(Timedelta::div_scalar(-100, -3), 33);
14735    }
14736
14737    #[test]
14738    fn timedelta_div_scalar_zero_divisor_returns_nat() {
14739        assert_eq!(Timedelta::div_scalar(100, 0), Timedelta::NAT);
14740    }
14741
14742    #[test]
14743    fn timedelta_div_scalar_min_neg_one_propagates_nat() {
14744        // i64::MIN aliases NaT, so `div_scalar(i64::MIN, _)` propagates NaT
14745        // — the `i64::MIN / -1` arithmetic-overflow case is subsumed.
14746        assert_eq!(Timedelta::div_scalar(i64::MIN, -1), Timedelta::NAT);
14747        // (i64::MIN + 1) is a real timedelta; `/ -1` does not overflow.
14748        assert_eq!(Timedelta::div_scalar(i64::MIN + 1, -1), i64::MAX);
14749    }
14750
14751    #[test]
14752    fn timedelta_div_scalar_propagates_nat() {
14753        assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 10), Timedelta::NAT);
14754    }
14755
14756    #[test]
14757    fn timedelta_div_timedelta_returns_float_ratio() {
14758        let two_hours = Timedelta::NANOS_PER_HOUR * 2;
14759        let one_hour = Timedelta::NANOS_PER_HOUR;
14760        assert!((Timedelta::div_timedelta(two_hours, one_hour) - 2.0).abs() < 1e-12);
14761        assert!((Timedelta::div_timedelta(one_hour, two_hours) - 0.5).abs() < 1e-12);
14762    }
14763
14764    #[test]
14765    fn timedelta_div_timedelta_nat_returns_nan() {
14766        assert!(Timedelta::div_timedelta(Timedelta::NAT, 100).is_nan());
14767        assert!(Timedelta::div_timedelta(100, Timedelta::NAT).is_nan());
14768    }
14769
14770    // ── Timestamp tests (br-frankenpandas-9p0u — 4r56 Phase 2) ──────────
14771
14772    use super::Timestamp;
14773
14774    #[test]
14775    fn timestamp_from_nanos_is_naive_utc() {
14776        let ts = Timestamp::from_nanos(1_700_000_000_000_000_000);
14777        assert_eq!(ts.nanos, 1_700_000_000_000_000_000);
14778        assert_eq!(ts.tz, None);
14779        assert!(!ts.is_nat());
14780    }
14781
14782    #[test]
14783    fn timestamp_from_nanos_tz_carries_tz_name() {
14784        let ts = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
14785        assert_eq!(ts.tz.as_deref(), Some("US/Eastern"));
14786    }
14787
14788    #[test]
14789    fn timestamp_now_returns_current_time() {
14790        let before = std::time::SystemTime::now()
14791            .duration_since(std::time::UNIX_EPOCH)
14792            .unwrap()
14793            .as_nanos() as i64;
14794        let ts = Timestamp::now();
14795        let after = std::time::SystemTime::now()
14796            .duration_since(std::time::UNIX_EPOCH)
14797            .unwrap()
14798            .as_nanos() as i64;
14799        assert!(ts.nanos >= before);
14800        assert!(ts.nanos <= after);
14801        assert!(!ts.is_nat());
14802    }
14803
14804    #[test]
14805    fn timestamp_today_returns_midnight() {
14806        let ts = Timestamp::today();
14807        assert!(!ts.is_nat());
14808        // Today should be normalized (midnight), so hour/min/sec should be 0
14809        assert_eq!(ts.hour(), Some(0));
14810        assert_eq!(ts.minute(), Some(0));
14811        assert_eq!(ts.second(), Some(0));
14812    }
14813
14814    #[test]
14815    fn timestamp_add_timedelta_shifts_nanos_and_preserves_tz() {
14816        let ts = Timestamp::from_nanos_tz(0, "US/Eastern");
14817        let one_day = Timedelta::NANOS_PER_DAY;
14818        let shifted = ts.add_timedelta(one_day);
14819        assert_eq!(shifted.nanos, one_day);
14820        assert_eq!(shifted.tz.as_deref(), Some("US/Eastern"));
14821    }
14822
14823    #[test]
14824    fn timestamp_add_timedelta_returns_nat_on_overflow() {
14825        // CORRECTED br-frankenpandas-lgyy8: previously asserted i64::MAX, i.e.
14826        // a finite ~year-2262 instant handed back as real data. pandas
14827        // `pd.Timestamp.max + pd.Timedelta('1ns')` raises OutOfBoundsDatetime.
14828        let ts = Timestamp::from_nanos(i64::MAX - 10);
14829        assert!(ts.add_timedelta(100).is_nat());
14830    }
14831
14832    #[test]
14833    fn timestamp_add_timedelta_propagates_nat() {
14834        // NaT Timestamp + anything = NaT.
14835        assert!(Timestamp::nat().add_timedelta(100).is_nat());
14836        // Timestamp + NaT Timedelta = NaT.
14837        assert!(
14838            Timestamp::from_nanos(0)
14839                .add_timedelta(Timedelta::NAT)
14840                .is_nat()
14841        );
14842    }
14843
14844    #[test]
14845    fn timestamp_sub_timedelta_shifts_backward() {
14846        let ts = Timestamp::from_nanos(1_000);
14847        let shifted = ts.sub_timedelta(Timedelta::NANOS_PER_MICRO);
14848        assert_eq!(shifted.nanos, 0);
14849    }
14850
14851    #[test]
14852    fn timestamp_sub_timestamp_returns_timedelta_nanos() {
14853        let t0 = Timestamp::from_nanos(0);
14854        let t1 = Timestamp::from_nanos(Timedelta::NANOS_PER_HOUR);
14855        assert_eq!(t1.sub_timestamp(&t0), Timedelta::NANOS_PER_HOUR);
14856        assert_eq!(t0.sub_timestamp(&t1), -Timedelta::NANOS_PER_HOUR);
14857    }
14858
14859    #[test]
14860    fn timestamp_sub_timestamp_nat_propagates() {
14861        let ts = Timestamp::from_nanos(1_000);
14862        assert_eq!(Timestamp::nat().sub_timestamp(&ts), Timedelta::NAT);
14863        assert_eq!(ts.sub_timestamp(&Timestamp::nat()), Timedelta::NAT);
14864    }
14865
14866    #[test]
14867    fn timestamp_semantic_eq_treats_two_nat_as_equal() {
14868        assert!(Timestamp::nat().semantic_eq(&Timestamp::nat()));
14869        assert!(!Timestamp::nat().semantic_eq(&Timestamp::from_nanos(0)));
14870        assert!(!Timestamp::from_nanos(0).semantic_eq(&Timestamp::nat()));
14871    }
14872
14873    #[test]
14874    fn timestamp_partial_cmp_orders_by_nanos_nat_is_incomparable() {
14875        use std::cmp::Ordering;
14876        let a = Timestamp::from_nanos(0);
14877        let b = Timestamp::from_nanos(100);
14878        assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
14879        assert_eq!(b.partial_cmp(&a), Some(Ordering::Greater));
14880        assert_eq!(a.partial_cmp(&a), Some(Ordering::Equal));
14881        assert_eq!(a.partial_cmp(&Timestamp::nat()), None);
14882        assert_eq!(Timestamp::nat().partial_cmp(&Timestamp::nat()), None);
14883    }
14884
14885    #[test]
14886    fn timestamp_display_matches_phase2_debug_format() {
14887        assert_eq!(Timestamp::from_nanos(42).to_string(), "Timestamp[42, UTC]");
14888        assert_eq!(
14889            Timestamp::from_nanos_tz(42, "US/Eastern").to_string(),
14890            "Timestamp[42, US/Eastern]"
14891        );
14892        assert_eq!(Timestamp::nat().to_string(), "NaT");
14893    }
14894
14895    #[test]
14896    fn timestamp_value_and_unit_match_pandas_l0edr() {
14897        let ts = Timestamp::from_nanos(1_000_000_123);
14898        assert_eq!(ts.value(), 1_000_000_123);
14899        assert_eq!(ts.unit(), Some("ns"));
14900
14901        let nat = Timestamp::nat();
14902        assert_eq!(nat.value(), Timestamp::NAT);
14903        assert_eq!(nat.unit(), None);
14904    }
14905
14906    #[test]
14907    fn timestamp_numpy_datetime64_materializers_match_value_twksi() {
14908        let ts = Timestamp::from_nanos(1_000_000_123);
14909        assert_eq!(ts.asm8(), ts.value());
14910        assert_eq!(ts.to_datetime64(), ts.value());
14911        assert_eq!(ts.to_numpy(), ts.value());
14912
14913        let nat = Timestamp::nat();
14914        assert_eq!(nat.asm8(), Timestamp::NAT);
14915        assert_eq!(nat.to_datetime64(), Timestamp::NAT);
14916        assert_eq!(nat.to_numpy(), Timestamp::NAT);
14917    }
14918
14919    #[test]
14920    fn timestamp_timestamp_accessor_matches_pandas_microsecond_rounding_py0h3() {
14921        assert_eq!(Timestamp::from_nanos(0).timestamp(), Ok(0.0));
14922        assert_eq!(Timestamp::from_nanos(1_500_000_000).timestamp(), Ok(1.5));
14923        assert_eq!(Timestamp::from_nanos(500).timestamp(), Ok(0.0));
14924        assert_eq!(Timestamp::from_nanos(501).timestamp(), Ok(0.000001));
14925        assert_eq!(Timestamp::from_nanos(2_500).timestamp(), Ok(0.000003));
14926
14927        assert!(matches!(
14928            Timestamp::from_nanos(-500).timestamp(),
14929            Ok(value) if value == -0.0 && value.is_sign_negative()
14930        ));
14931        assert_eq!(Timestamp::from_nanos(-2_500).timestamp(), Ok(-0.000003));
14932        assert_eq!(
14933            Timestamp::nat().timestamp(),
14934            Err(TypeError::ValueIsMissing {
14935                kind: NullKind::NaT,
14936            })
14937        );
14938    }
14939
14940    #[test]
14941    fn timestamp_roundtrips_through_serde_json() {
14942        let naive = Timestamp::from_nanos(1_700_000_000_000_000_000);
14943        let json = serde_json::to_string(&naive).expect("serialize");
14944        let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
14945        assert_eq!(naive, back);
14946
14947        let tz_aware = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
14948        let json = serde_json::to_string(&tz_aware).expect("serialize");
14949        let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
14950        assert_eq!(tz_aware, back);
14951    }
14952
14953    #[test]
14954    fn timestamp_is_send_and_sync() {
14955        fn assert_send_sync<T: Send + Sync>() {}
14956        assert_send_sync::<Timestamp>();
14957    }
14958
14959    // ── Timestamp rounding tests (br-frankenpandas-5h6n) ────────────────
14960
14961    #[test]
14962    fn timestamp_pre_epoch_accessors_floor_not_truncate() {
14963        // br-frankenpandas-wkjtw: pre-1970 instants with a sub-day part used to
14964        // truncate toward zero, landing on the wrong calendar day. -1 ns is
14965        // 1969-12-31 23:59:59.999999999 UTC.
14966        let ts = Timestamp::from_nanos(-1);
14967        assert_eq!(ts.year(), Some(1969));
14968        assert_eq!(ts.month(), Some(12));
14969        assert_eq!(ts.day(), Some(31));
14970        assert_eq!(ts.hour(), Some(23));
14971        assert_eq!(ts.minute(), Some(59));
14972        assert_eq!(ts.second(), Some(59));
14973        assert_eq!(ts.microsecond(), Some(999_999));
14974        assert_eq!(ts.nanosecond(), Some(999));
14975        // 1969-12-31 is a Wednesday (pandas Monday=0 -> 2).
14976        assert_eq!(ts.dayofweek(), Some(2));
14977
14978        // 1969-12-31 12:00:00 — the classic truncation case (-43200 s).
14979        let noon = Timestamp::from_nanos(-43200 * Timedelta::NANOS_PER_SEC);
14980        assert_eq!(noon.year(), Some(1969));
14981        assert_eq!(noon.month(), Some(12));
14982        assert_eq!(noon.day(), Some(31));
14983        assert_eq!(noon.hour(), Some(12));
14984
14985        // Exact midnight pre-epoch was already correct; keep it green.
14986        let midnight = Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY);
14987        assert_eq!(midnight.year(), Some(1969));
14988        assert_eq!(midnight.day(), Some(31));
14989        assert_eq!(midnight.hour(), Some(0));
14990    }
14991
14992    #[test]
14993    fn timestamp_floor_to_rounds_down() {
14994        // 12:34:56 → floor by 1H → 12:00:00
14995        let h = Timedelta::NANOS_PER_HOUR;
14996        let twelve_h = h * 12;
14997        let twelve_thirty_four =
14998            twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
14999        let ts = Timestamp::from_nanos(twelve_thirty_four);
15000        let floored = ts.floor_to(h);
15001        assert_eq!(floored.nanos, twelve_h);
15002    }
15003
15004    #[test]
15005    fn timestamp_floor_to_handles_already_aligned() {
15006        // 12:00:00 floored by 1H → 12:00:00 (no change).
15007        let h = Timedelta::NANOS_PER_HOUR;
15008        let twelve_h = h * 12;
15009        let ts = Timestamp::from_nanos(twelve_h);
15010        assert_eq!(ts.floor_to(h).nanos, twelve_h);
15011    }
15012
15013    #[test]
15014    fn timestamp_floor_to_handles_negative_nanos() {
15015        // -100 ns floored by 60 ns:
15016        //   div_euclid(-100, 60) = -2 (since -2*60=-120, rem=20 ≥ 0).
15017        //   result = -2 * 60 = -120.
15018        let ts = Timestamp::from_nanos(-100);
15019        assert_eq!(ts.floor_to(60).nanos, -120);
15020    }
15021
15022    #[test]
15023    fn timestamp_floor_to_returns_nat_on_axis_underflow_30hdi() {
15024        let ts = Timestamp::from_nanos(i64::MIN + 1);
15025        assert!(ts.floor_to(10).is_nat());
15026
15027        let safe = Timestamp::from_nanos(i64::MIN + 10);
15028        assert_eq!(safe.floor_to(10).nanos, i64::MIN + 8);
15029
15030        let tz = Timestamp::from_nanos_tz(-100, "UTC").floor_to(60);
15031        assert_eq!(tz.nanos, -120);
15032        assert_eq!(tz.tz.as_deref(), Some("UTC"));
15033    }
15034
15035    #[test]
15036    fn timestamp_ceil_to_rounds_up() {
15037        // 12:34:56 → ceil by 1H → 13:00:00.
15038        let h = Timedelta::NANOS_PER_HOUR;
15039        let twelve_h = h * 12;
15040        let thirteen_h = h * 13;
15041        let twelve_thirty_four =
15042            twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
15043        let ts = Timestamp::from_nanos(twelve_thirty_four);
15044        assert_eq!(ts.ceil_to(h).nanos, thirteen_h);
15045    }
15046
15047    #[test]
15048    fn timestamp_ceil_to_no_op_on_aligned() {
15049        let h = Timedelta::NANOS_PER_HOUR;
15050        let twelve_h = h * 12;
15051        let ts = Timestamp::from_nanos(twelve_h);
15052        assert_eq!(ts.ceil_to(h).nanos, twelve_h);
15053    }
15054
15055    #[test]
15056    fn timestamp_round_to_rounds_to_nearest() {
15057        // 12:30:01 (one second past the half-hour): round to 1H → 13:00:00.
15058        let h = Timedelta::NANOS_PER_HOUR;
15059        let twelve_h = h * 12;
15060        let twelve_thirty_one_sec =
15061            twelve_h + Timedelta::NANOS_PER_MIN * 30 + Timedelta::NANOS_PER_SEC;
15062        let ts = Timestamp::from_nanos(twelve_thirty_one_sec);
15063        assert_eq!(ts.round_to(h).nanos, h * 13);
15064
15065        // 12:29:59 (one second before half): round to 1H → 12:00:00.
15066        let twelve_twenty_nine_sec =
15067            twelve_h + Timedelta::NANOS_PER_MIN * 29 + Timedelta::NANOS_PER_SEC * 59;
15068        let ts = Timestamp::from_nanos(twelve_twenty_nine_sec);
15069        assert_eq!(ts.round_to(h).nanos, twelve_h);
15070    }
15071
15072    #[test]
15073    fn timestamp_round_to_bankers_tie_to_even() {
15074        // Tie cases: rem == unit/2 exactly. Pick even-multiple floor.
15075        // unit=10, so half=5. nanos=5: floor=0 (even), so → 0.
15076        // nanos=15: floor=1 (odd), so → 20.
15077        // nanos=25: floor=2 (even), so → 20.
15078        // nanos=35: floor=3 (odd), so → 40.
15079        assert_eq!(Timestamp::from_nanos(5).round_to(10).nanos, 0);
15080        assert_eq!(Timestamp::from_nanos(15).round_to(10).nanos, 20);
15081        assert_eq!(Timestamp::from_nanos(25).round_to(10).nanos, 20);
15082        assert_eq!(Timestamp::from_nanos(35).round_to(10).nanos, 40);
15083    }
15084
15085    #[test]
15086    fn timestamp_round_to_zero_unit_returns_nat() {
15087        let ts = Timestamp::from_nanos(100);
15088        assert!(ts.round_to(0).is_nat());
15089        assert!(ts.floor_to(0).is_nat());
15090        assert!(ts.ceil_to(0).is_nat());
15091    }
15092
15093    #[test]
15094    fn timestamp_round_to_negative_unit_returns_nat() {
15095        let ts = Timestamp::from_nanos(100);
15096        assert!(ts.round_to(-10).is_nat());
15097        assert!(ts.floor_to(-10).is_nat());
15098        assert!(ts.ceil_to(-10).is_nat());
15099    }
15100
15101    #[test]
15102    fn timestamp_rounding_propagates_nat() {
15103        let nat = Timestamp::nat();
15104        assert!(nat.floor_to(60).is_nat());
15105        assert!(nat.ceil_to(60).is_nat());
15106        assert!(nat.round_to(60).is_nat());
15107    }
15108
15109    #[test]
15110    fn timestamp_rounding_preserves_tz() {
15111        let ts = Timestamp::from_nanos_tz(100, "US/Eastern");
15112        assert_eq!(ts.floor_to(60).tz.as_deref(), Some("US/Eastern"));
15113        assert_eq!(ts.ceil_to(60).tz.as_deref(), Some("US/Eastern"));
15114        assert_eq!(ts.round_to(60).tz.as_deref(), Some("US/Eastern"));
15115    }
15116
15117    // ── Timestamp string-unit rounding tests (br-frankenpandas-lbsx) ────
15118
15119    #[test]
15120    fn timestamp_floor_to_unit_h_rounds_to_hour() {
15121        let h = Timedelta::NANOS_PER_HOUR;
15122        let twelve_h = h * 12;
15123        let twelve_thirty_four =
15124            twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
15125        let ts = Timestamp::from_nanos(twelve_thirty_four);
15126        assert_eq!(ts.floor_to_unit("H").nanos, twelve_h);
15127        assert_eq!(ts.floor_to_unit("h").nanos, twelve_h);
15128        assert_eq!(ts.floor_to_unit("hour").nanos, twelve_h);
15129        assert_eq!(ts.floor_to_unit("hours").nanos, twelve_h);
15130        assert_eq!(ts.floor_to_unit("hr").nanos, twelve_h);
15131    }
15132
15133    #[test]
15134    fn timestamp_ceil_to_unit_d_rounds_to_day() {
15135        // 12:34:56 → ceil to 1 day → 24:00:00 (next day).
15136        let h = Timedelta::NANOS_PER_HOUR;
15137        let d = Timedelta::NANOS_PER_DAY;
15138        let twelve_thirty_four = h * 12 + Timedelta::NANOS_PER_MIN * 34;
15139        let ts = Timestamp::from_nanos(twelve_thirty_four);
15140        assert_eq!(ts.ceil_to_unit("D").nanos, d);
15141        assert_eq!(ts.ceil_to_unit("day").nanos, d);
15142        assert_eq!(ts.ceil_to_unit("days").nanos, d);
15143    }
15144
15145    #[test]
15146    fn timestamp_round_to_unit_min_rounds_to_minute() {
15147        // 12:34:31 → round to 1 minute → 12:35:00.
15148        let m = Timedelta::NANOS_PER_MIN;
15149        let twelve_thirty_four_thirty_one =
15150            Timedelta::NANOS_PER_HOUR * 12 + m * 34 + Timedelta::NANOS_PER_SEC * 31;
15151        let ts = Timestamp::from_nanos(twelve_thirty_four_thirty_one);
15152        let expected = Timedelta::NANOS_PER_HOUR * 12 + m * 35;
15153        assert_eq!(ts.round_to_unit("min").nanos, expected);
15154        assert_eq!(ts.round_to_unit("T").nanos, expected); // pandas pre-2.2 alias
15155        assert_eq!(ts.round_to_unit("minute").nanos, expected);
15156    }
15157
15158    #[test]
15159    fn timestamp_floor_ceil_round_aliases_match_unit_methods_li897() {
15160        let ts = Timestamp::from_nanos(
15161            Timedelta::NANOS_PER_HOUR * 12
15162                + Timedelta::NANOS_PER_MIN * 34
15163                + Timedelta::NANOS_PER_SEC * 31,
15164        );
15165
15166        assert_eq!(ts.floor("H"), ts.floor_to_unit("H"));
15167        assert_eq!(ts.ceil("D"), ts.ceil_to_unit("D"));
15168        assert_eq!(ts.round("min"), ts.round_to_unit("min"));
15169    }
15170
15171    #[test]
15172    fn timestamp_normalize_floors_to_day_and_preserves_tz_455op() {
15173        let ts = Timestamp::from_nanos_tz(
15174            Timedelta::NANOS_PER_DAY * 3
15175                + Timedelta::NANOS_PER_HOUR * 12
15176                + Timedelta::NANOS_PER_MIN * 34,
15177            "US/Eastern",
15178        );
15179        let normalized = ts.normalize();
15180
15181        assert_eq!(normalized.nanos, Timedelta::NANOS_PER_DAY * 3);
15182        assert_eq!(normalized.tz.as_deref(), Some("US/Eastern"));
15183        assert!(Timestamp::nat().normalize().is_nat());
15184        for nanos in [
15185            i64::MIN + 1,
15186            -Timedelta::NANOS_PER_DAY - 1,
15187            -Timedelta::NANOS_PER_DAY,
15188            -1,
15189            0,
15190            Timedelta::NANOS_PER_DAY - 1,
15191            Timedelta::NANOS_PER_DAY,
15192            i64::MAX,
15193        ] {
15194            let timestamp = Timestamp::from_nanos(nanos);
15195            assert_eq!(timestamp.normalize(), timestamp.floor_to_unit("D"));
15196        }
15197    }
15198
15199    #[test]
15200    #[ignore = "foreground profile-first A/B"]
15201    fn timestamp_normalize_direct_day_profile_dk721() {
15202        use std::{hint::black_box, time::Instant};
15203
15204        fn former(timestamp: &Timestamp) -> Timestamp {
15205            timestamp.floor_to_unit("D")
15206        }
15207
15208        fn candidate(timestamp: &Timestamp) -> Timestamp {
15209            timestamp.normalize()
15210        }
15211
15212        fn elapsed(input: &[Timestamp], normalize: impl Fn(&Timestamp) -> Timestamp) -> u128 {
15213            let started = Instant::now();
15214            let mut checksum = 0_u64;
15215            for timestamp in input {
15216                let normalized = normalize(black_box(timestamp));
15217                checksum = checksum.rotate_left(7) ^ normalized.nanos as u64;
15218            }
15219            black_box(checksum);
15220            started.elapsed().as_nanos()
15221        }
15222
15223        fn percentile(samples: &mut [u128], percent: usize) -> u128 {
15224            samples.sort_unstable();
15225            let rank = (samples.len() * percent).div_ceil(100).saturating_sub(1);
15226            samples[rank]
15227        }
15228
15229        let parity_cases = [
15230            Timestamp::nat(),
15231            Timestamp::from_nanos(i64::MIN + 1),
15232            Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY - 1),
15233            Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY),
15234            Timestamp::from_nanos(-1),
15235            Timestamp::from_nanos(0),
15236            Timestamp::from_nanos(Timedelta::NANOS_PER_DAY - 1),
15237            Timestamp::from_nanos(Timedelta::NANOS_PER_DAY),
15238            Timestamp::from_nanos(i64::MAX),
15239            Timestamp::from_nanos_tz(-1, "US/Eastern"),
15240            Timestamp::from_nanos_tz(
15241                Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR,
15242                "Asia/Tokyo",
15243            ),
15244        ];
15245        for timestamp in &parity_cases {
15246            assert_eq!(former(timestamp), candidate(timestamp));
15247            assert_eq!(timestamp.normalize(), former(timestamp));
15248        }
15249
15250        const ROWS: usize = 16_384;
15251        const SAMPLES: usize = 20;
15252        let input = (0..ROWS)
15253            .map(|index| {
15254                let day = index as i64 % 4_096 - 2_048;
15255                let offset = ((index as u64).wrapping_mul(6_364_136_223_846_793_005_u64)
15256                    % Timedelta::NANOS_PER_DAY as u64) as i64;
15257                Timestamp::from_nanos(day * Timedelta::NANOS_PER_DAY + offset)
15258            })
15259            .collect::<Vec<_>>();
15260        for timestamp in &input {
15261            assert_eq!(former(timestamp), candidate(timestamp));
15262        }
15263
15264        for _ in 0..3 {
15265            black_box(elapsed(&input, former));
15266            black_box(elapsed(&input, candidate));
15267        }
15268
15269        let mut former_ns = Vec::with_capacity(SAMPLES);
15270        let mut candidate_ns = Vec::with_capacity(SAMPLES);
15271        for sample in 0..SAMPLES {
15272            if sample % 2 == 0 {
15273                former_ns.push(elapsed(&input, former));
15274                candidate_ns.push(elapsed(&input, candidate));
15275            } else {
15276                candidate_ns.push(elapsed(&input, candidate));
15277                former_ns.push(elapsed(&input, former));
15278            }
15279        }
15280
15281        let mut former_sorted = former_ns.clone();
15282        let mut candidate_sorted = candidate_ns.clone();
15283        let former_p50 = percentile(&mut former_sorted, 50);
15284        let former_p95 = percentile(&mut former_sorted, 95);
15285        let former_p99 = percentile(&mut former_sorted, 99);
15286        let candidate_p50 = percentile(&mut candidate_sorted, 50);
15287        let candidate_p95 = percentile(&mut candidate_sorted, 95);
15288        let candidate_p99 = percentile(&mut candidate_sorted, 99);
15289        println!(
15290            "TIMESTAMP_NORMALIZE_DIRECT_DAY rows={ROWS} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup_p50={:.6} former_p95_ns={former_p95} candidate_p95_ns={candidate_p95} speedup_p95={:.6} former_p99_ns={former_p99} candidate_p99_ns={candidate_p99} speedup_p99={:.6} former_samples={former_ns:?} candidate_samples={candidate_ns:?}",
15291            former_p50 as f64 / candidate_p50 as f64,
15292            former_p95 as f64 / candidate_p95 as f64,
15293            former_p99 as f64 / candidate_p99 as f64,
15294        );
15295    }
15296
15297    #[test]
15298    fn timestamp_unit_rounding_unknown_unit_returns_nat() {
15299        let ts = Timestamp::from_nanos(100);
15300        assert!(ts.floor_to_unit("fortnight").is_nat());
15301        assert!(ts.ceil_to_unit("century").is_nat());
15302        assert!(ts.round_to_unit("xyz").is_nat());
15303    }
15304
15305    #[test]
15306    fn timestamp_unit_rounding_propagates_nat() {
15307        let nat = Timestamp::nat();
15308        assert!(nat.floor_to_unit("H").is_nat());
15309        assert!(nat.ceil_to_unit("H").is_nat());
15310        assert!(nat.round_to_unit("H").is_nat());
15311    }
15312
15313    #[test]
15314    fn timestamp_unit_rounding_preserves_tz() {
15315        let ts = Timestamp::from_nanos_tz(Timedelta::NANOS_PER_HOUR * 12 + 100, "US/Eastern");
15316        assert_eq!(ts.floor_to_unit("H").tz.as_deref(), Some("US/Eastern"));
15317        assert_eq!(ts.ceil_to_unit("H").tz.as_deref(), Some("US/Eastern"));
15318        assert_eq!(ts.round_to_unit("H").tz.as_deref(), Some("US/Eastern"));
15319    }
15320
15321    #[test]
15322    fn timedelta_unit_to_nanos_is_now_public_and_matches_pandas_aliases() {
15323        // Public surface check: pandas alias core set.
15324        assert_eq!(
15325            Timedelta::unit_to_nanos("W"),
15326            Some(Timedelta::NANOS_PER_WEEK)
15327        );
15328        assert_eq!(
15329            Timedelta::unit_to_nanos("D"),
15330            Some(Timedelta::NANOS_PER_DAY)
15331        );
15332        assert_eq!(
15333            Timedelta::unit_to_nanos("H"),
15334            Some(Timedelta::NANOS_PER_HOUR)
15335        );
15336        assert_eq!(
15337            Timedelta::unit_to_nanos("min"),
15338            Some(Timedelta::NANOS_PER_MIN)
15339        );
15340        assert_eq!(
15341            Timedelta::unit_to_nanos("s"),
15342            Some(Timedelta::NANOS_PER_SEC)
15343        );
15344        assert_eq!(
15345            Timedelta::unit_to_nanos("ms"),
15346            Some(Timedelta::NANOS_PER_MILLI)
15347        );
15348        assert_eq!(
15349            Timedelta::unit_to_nanos("us"),
15350            Some(Timedelta::NANOS_PER_MICRO)
15351        );
15352        assert_eq!(Timedelta::unit_to_nanos("ns"), Some(1));
15353        // Empty string → days (pandas default).
15354        assert_eq!(Timedelta::unit_to_nanos(""), Some(Timedelta::NANOS_PER_DAY));
15355        // Unknown alias → None.
15356        assert_eq!(Timedelta::unit_to_nanos("century"), None);
15357    }
15358
15359    #[test]
15360    fn timestamp_isoformat_basic() {
15361        let ts = Timestamp::from_nanos(0);
15362        assert_eq!(ts.isoformat(), "1970-01-01T00:00:00");
15363
15364        let ts_utc = Timestamp::from_nanos_tz(0, "UTC");
15365        assert_eq!(ts_utc.isoformat(), "1970-01-01T00:00:00+00:00");
15366
15367        let ts_fixed_offset = Timestamp::from_nanos_tz(0, "UTC+05:30");
15368        assert_eq!(
15369            ts_fixed_offset.isoformat(),
15370            "1970-01-01T05:30:00+05:30",
15371            "a fixed-offset timestamp must render local wall time rather than a UTC instant with an annotation"
15372        );
15373
15374        let ts_tz = Timestamp::from_nanos_tz(
15375            Timedelta::NANOS_PER_DAY
15376                + Timedelta::NANOS_PER_HOUR * 14
15377                + Timedelta::NANOS_PER_MIN * 30,
15378            "America/New_York",
15379        );
15380        assert!(ts_tz.isoformat().contains("1970-01-02T14:30:00"));
15381        assert!(ts_tz.isoformat().contains("[America/New_York]"));
15382
15383        assert_eq!(Timestamp::nat().isoformat(), "NaT");
15384    }
15385
15386    #[test]
15387    fn timestamp_isoformat_pre_epoch_subsecond_uses_floor_day_263m5() {
15388        assert_eq!(
15389            Timestamp::from_nanos(-1).isoformat(),
15390            "1969-12-31T23:59:59.999999999"
15391        );
15392        assert_eq!(
15393            Timestamp::from_nanos(-Timedelta::NANOS_PER_SEC).isoformat(),
15394            "1969-12-31T23:59:59"
15395        );
15396        assert_eq!(
15397            Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY).isoformat(),
15398            "1969-12-31T00:00:00"
15399        );
15400        assert_eq!(
15401            Timestamp::from_nanos_tz(-1, "UTC").isoformat(),
15402            "1969-12-31T23:59:59.999999999+00:00"
15403        );
15404    }
15405
15406    #[test]
15407    fn timestamp_isoformat_preserves_nanosecond_fraction_4r99y() {
15408        assert_eq!(
15409            Timestamp::from_nanos(123_456_789).isoformat(),
15410            "1970-01-01T00:00:00.123456789"
15411        );
15412        assert_eq!(
15413            Timestamp::from_nanos(123_456_000).isoformat(),
15414            "1970-01-01T00:00:00.123456"
15415        );
15416        assert_eq!(
15417            Timestamp::from_nanos(123_000_000).isoformat(),
15418            "1970-01-01T00:00:00.123000"
15419        );
15420        assert_eq!(
15421            Timestamp::from_nanos_tz(1, "UTC").isoformat(),
15422            "1970-01-01T00:00:00.000000001+00:00"
15423        );
15424    }
15425
15426    fn timestamp_isoformat_former_q8g50(timestamp: &Timestamp) -> String {
15427        if timestamp.is_nat() {
15428            return "NaT".to_owned();
15429        }
15430        let base = Timestamp::from_nanos(timestamp.nanos).isoformat();
15431        match &timestamp.tz {
15432            Some(tz) if tz == "UTC" => format!("{base}+00:00"),
15433            Some(tz) => format!("{base}[{tz}]"),
15434            None => base,
15435        }
15436    }
15437
15438    #[test]
15439    fn timestamp_isoformat_one_buffer_matches_former_q8g50() {
15440        let nanos = [
15441            Timestamp::NAT,
15442            -Timedelta::NANOS_PER_DAY - 1,
15443            -Timedelta::NANOS_PER_SEC,
15444            -1,
15445            0,
15446            1,
15447            123_456_000,
15448            123_456_789,
15449            i64::MAX,
15450        ];
15451        let timezones = [
15452            None,
15453            Some("UTC"),
15454            Some("America/New_York"),
15455            Some(""),
15456            Some("Etc/Γ"),
15457        ];
15458        for value in nanos {
15459            for timezone in timezones {
15460                let timestamp = Timestamp {
15461                    nanos: value,
15462                    tz: timezone.map(str::to_owned),
15463                };
15464                assert_eq!(
15465                    timestamp.isoformat(),
15466                    timestamp_isoformat_former_q8g50(&timestamp),
15467                    "nanos={value} timezone={timezone:?}"
15468                );
15469            }
15470        }
15471    }
15472
15473    #[test]
15474    #[ignore = "foreground release A/B only"]
15475    fn timestamp_isoformat_one_buffer_ab_q8g50() {
15476        use std::{hint::black_box, time::Instant};
15477
15478        const ITEMS: usize = 8_192;
15479        const SAMPLES: usize = 10;
15480
15481        fn elapsed(values: &[Timestamp], render: fn(&Timestamp) -> String) -> u128 {
15482            let started = Instant::now();
15483            let mut checksum = 0usize;
15484            for timestamp in black_box(values) {
15485                checksum = checksum.wrapping_add(black_box(render(black_box(timestamp))).len());
15486            }
15487            black_box(checksum);
15488            started.elapsed().as_nanos()
15489        }
15490
15491        let values = (0..ITEMS)
15492            .map(|idx| {
15493                let nanos = (idx as i64 - ITEMS as i64 / 2) * 1_000_123_456_789;
15494                let timezone = if idx.is_multiple_of(2) {
15495                    "UTC"
15496                } else {
15497                    "America/New_York"
15498                };
15499                Timestamp::from_nanos_tz(nanos, timezone)
15500            })
15501            .collect::<Vec<_>>();
15502        for timestamp in &values {
15503            assert_eq!(
15504                timestamp.isoformat(),
15505                timestamp_isoformat_former_q8g50(timestamp)
15506            );
15507        }
15508
15509        black_box(elapsed(&values, timestamp_isoformat_former_q8g50));
15510        black_box(elapsed(&values, Timestamp::isoformat));
15511
15512        let mut former_ns = Vec::with_capacity(SAMPLES);
15513        let mut one_buffer_ns = Vec::with_capacity(SAMPLES);
15514        for sample in 0..SAMPLES {
15515            if sample.is_multiple_of(2) {
15516                former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
15517                one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
15518            } else {
15519                one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
15520                former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
15521            }
15522        }
15523        former_ns.sort_unstable();
15524        one_buffer_ns.sort_unstable();
15525        let former_p50 = former_ns[SAMPLES / 2];
15526        let one_buffer_p50 = one_buffer_ns[SAMPLES / 2];
15527        println!(
15528            "timestamp_isoformat_one_buffer_ab items={ITEMS} samples={SAMPLES} former_p50_ns={former_p50} one_buffer_p50_ns={one_buffer_p50} speedup={:.6}x",
15529            former_p50 as f64 / one_buffer_p50 as f64
15530        );
15531        println!("former_samples_ns={former_ns:?}");
15532        println!("one_buffer_samples_ns={one_buffer_ns:?}");
15533    }
15534
15535    #[test]
15536    fn timestamp_strftime_basic() {
15537        let ts = Timestamp::from_nanos(
15538            Timedelta::NANOS_PER_DAY * 365
15539                + Timedelta::NANOS_PER_HOUR * 9
15540                + Timedelta::NANOS_PER_MIN * 15,
15541        );
15542        assert_eq!(ts.strftime("%Y-%m-%d"), "1971-01-01");
15543        assert_eq!(ts.strftime("%H:%M:%S"), "09:15:00");
15544        assert_eq!(ts.strftime("%Y/%m/%d %H:%M"), "1971/01/01 09:15");
15545        assert_eq!(ts.strftime("%%Y|%%%m|%Q|%|λ"), "%1971|%%01|%Q|%|λ");
15546        assert_eq!(Timestamp::nat().strftime("%Y-%m-%d"), "NaT");
15547    }
15548
15549    #[test]
15550    fn timestamp_strftime_floors_pre_epoch_instants_1pmlp() {
15551        let apollo = Timestamp::parse("1969-07-20T20:17:40").unwrap();
15552        assert_eq!(
15553            apollo.strftime("%Y-%m-%d %H:%M:%S.%f"),
15554            "1969-07-20 20:17:40.000000"
15555        );
15556
15557        // The smallest negative instant catches both truncation defects:
15558        // second flooring and day flooring.
15559        let one_ns_before_epoch = Timestamp::from_nanos(-1);
15560        assert_eq!(
15561            one_ns_before_epoch.strftime("%Y-%m-%d %H:%M:%S.%f"),
15562            "1969-12-31 23:59:59.999999"
15563        );
15564    }
15565
15566    #[test]
15567    #[ignore = "foreground normal-release attribution harness"]
15568    fn timestamp_strftime_one_buffer_profile_8qzbo() {
15569        use std::{hint::black_box, time::Instant};
15570
15571        const ITEMS: usize = 8_192;
15572        const SAMPLES: usize = 10;
15573        const FORMAT: &str = "%Y-%m-%d %H:%M:%S.%f|%Y%m%d|%%Y|λ%Q";
15574
15575        fn former(timestamp: &Timestamp, format: &str) -> String {
15576            if timestamp.is_nat() {
15577                return "NaT".to_string();
15578            }
15579            let total_secs = timestamp.nanos / Timedelta::NANOS_PER_SEC;
15580            let sub_nanos = timestamp.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
15581
15582            let days_since_epoch = total_secs / 86400;
15583            let secs_of_day = (total_secs % 86400 + 86400) % 86400;
15584            let days = days_since_epoch + 719_468;
15585            let era = (if days >= 0 { days } else { days - 146_096 }) / 146_097;
15586            let doe = days - era * 146_097;
15587            let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
15588            let y = yoe + era * 400;
15589            let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
15590            let mp = (5 * doy + 2) / 153;
15591            let d = doy - (153 * mp + 2) / 5 + 1;
15592            let m = if mp < 10 { mp + 3 } else { mp - 9 };
15593            let year = if m <= 2 { y + 1 } else { y };
15594            let hour = secs_of_day / 3600;
15595            let minute = (secs_of_day % 3600) / 60;
15596            let second = secs_of_day % 60;
15597            let micros = sub_nanos / 1000;
15598
15599            format
15600                .replace("%Y", &format!("{year:04}"))
15601                .replace("%m", &format!("{m:02}"))
15602                .replace("%d", &format!("{d:02}"))
15603                .replace("%H", &format!("{hour:02}"))
15604                .replace("%M", &format!("{minute:02}"))
15605                .replace("%S", &format!("{second:02}"))
15606                .replace("%f", &format!("{micros:06}"))
15607        }
15608
15609        fn elapsed(timestamps: &[Timestamp], formatter: fn(&Timestamp, &str) -> String) -> u128 {
15610            let started = Instant::now();
15611            let mut digest = 0_usize;
15612            for timestamp in timestamps {
15613                let value = formatter(black_box(timestamp), black_box(FORMAT));
15614                digest = digest.wrapping_add(value.len());
15615                digest ^= usize::from(value.as_bytes().first().copied().unwrap_or_default());
15616                black_box(value);
15617            }
15618            black_box(digest);
15619            started.elapsed().as_nanos()
15620        }
15621
15622        fn percentile(samples: &mut [u128], pct: usize) -> u128 {
15623            samples.sort_unstable();
15624            let rank = (samples.len() * pct).div_ceil(100).saturating_sub(1);
15625            samples[rank]
15626        }
15627
15628        let edge_timestamps = [
15629            Timestamp::nat(),
15630            Timestamp::from_nanos(i64::MIN + 1),
15631            Timestamp::from_nanos(-1_234_567_890),
15632            Timestamp::from_nanos(0),
15633            Timestamp::from_nanos(1_735_732_800_123_456_789),
15634            Timestamp::from_nanos(i64::MAX),
15635        ];
15636        let edge_formats = [
15637            "",
15638            "%Y-%m-%d %H:%M:%S.%f",
15639            "%Y%Y%m%m%d%d%H%H%M%M%S%S%f%f",
15640            "%%Y|%%%m|%Q|%|λ",
15641            FORMAT,
15642        ];
15643        for timestamp in &edge_timestamps {
15644            for format in edge_formats {
15645                assert_eq!(former(timestamp, format), timestamp.strftime(format));
15646            }
15647        }
15648
15649        let timestamps = (0..ITEMS)
15650            .map(|index| {
15651                let centered = index as i64 - ITEMS as i64 / 2;
15652                Timestamp::from_nanos(centered * 987_654_321_123_456)
15653            })
15654            .collect::<Vec<_>>();
15655        for timestamp in &timestamps {
15656            assert_eq!(former(timestamp, FORMAT), timestamp.strftime(FORMAT));
15657        }
15658
15659        black_box(elapsed(&timestamps, former));
15660        black_box(elapsed(&timestamps, Timestamp::strftime));
15661
15662        let mut former_samples = Vec::with_capacity(SAMPLES);
15663        let mut public_samples = Vec::with_capacity(SAMPLES);
15664        for sample in 0..SAMPLES {
15665            if sample.is_multiple_of(2) {
15666                former_samples.push(elapsed(&timestamps, former));
15667                public_samples.push(elapsed(&timestamps, Timestamp::strftime));
15668            } else {
15669                public_samples.push(elapsed(&timestamps, Timestamp::strftime));
15670                former_samples.push(elapsed(&timestamps, former));
15671            }
15672        }
15673        let former_p50 = percentile(&mut former_samples, 50);
15674        let former_p95 = percentile(&mut former_samples, 95);
15675        let public_p50 = percentile(&mut public_samples, 50);
15676        let public_p95 = percentile(&mut public_samples, 95);
15677        println!(
15678            "TIMESTAMP_STRFTIME_AB items={ITEMS} samples={SAMPLES} former_p50_ns={former_p50} former_p95_ns={former_p95} public_p50_ns={public_p50} public_p95_ns={public_p95} p50_speedup={:.6} p95_speedup={:.6}",
15679            former_p50 as f64 / public_p50 as f64,
15680            former_p95 as f64 / public_p95 as f64,
15681        );
15682        println!("TIMESTAMP_STRFTIME_AB former_samples_ns={former_samples:?}");
15683        println!("TIMESTAMP_STRFTIME_AB public_samples_ns={public_samples:?}");
15684    }
15685
15686    #[test]
15687    fn timestamp_day_name_and_month_name() {
15688        let ts = Timestamp::from_nanos(0);
15689        assert_eq!(ts.day_name(), "Thursday");
15690        assert_eq!(ts.month_name(), "January");
15691
15692        let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
15693        assert_eq!(ts2.day_name(), "Friday");
15694        assert_eq!(ts2.month_name(), "January");
15695
15696        assert_eq!(Timestamp::nat().day_name(), "NaT");
15697        assert_eq!(Timestamp::nat().month_name(), "NaT");
15698    }
15699
15700    #[test]
15701    fn timestamp_replace_validates_components_zw0y2() {
15702        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
15703        let replaced = ts.replace(
15704            Some(2024),
15705            Some(2),
15706            Some(29),
15707            Some(23),
15708            Some(59),
15709            Some(58),
15710            Some(987_654),
15711            Some(321),
15712        );
15713        assert_eq!(replaced.year(), Some(2024));
15714        assert_eq!(replaced.month(), Some(2));
15715        assert_eq!(replaced.day(), Some(29));
15716        assert_eq!(replaced.hour(), Some(23));
15717        assert_eq!(replaced.minute(), Some(59));
15718        assert_eq!(replaced.second(), Some(58));
15719        assert_eq!(replaced.microsecond(), Some(987_654));
15720        assert_eq!(replaced.nanosecond(), Some(321));
15721
15722        let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
15723        assert_eq!(
15724            tz.replace(None, Some(2), Some(29), None, None, None, None, None)
15725                .tz
15726                .as_deref(),
15727            Some("UTC")
15728        );
15729
15730        assert!(
15731            ts.replace(None, Some(13), None, None, None, None, None, None)
15732                .is_nat()
15733        );
15734        assert!(
15735            ts.replace(Some(2023), Some(2), Some(29), None, None, None, None, None)
15736                .is_nat()
15737        );
15738        assert!(
15739            ts.replace(None, None, None, Some(24), None, None, None, None)
15740                .is_nat()
15741        );
15742        assert!(
15743            ts.replace(None, None, None, None, Some(60), None, None, None)
15744                .is_nat()
15745        );
15746        assert!(
15747            ts.replace(None, None, None, None, None, Some(60), None, None)
15748                .is_nat()
15749        );
15750        assert!(
15751            ts.replace(None, None, None, None, None, None, Some(1_000_000), None)
15752                .is_nat()
15753        );
15754        assert!(
15755            ts.replace(None, None, None, None, None, None, None, Some(1_000))
15756                .is_nat()
15757        );
15758        assert!(
15759            Timestamp::nat()
15760                .replace(Some(2024), Some(1), Some(1), None, None, None, None, None)
15761                .is_nat()
15762        );
15763    }
15764
15765    /// br-frankenpandas-dzz6x: `replace` validates every component EXCEPT the
15766    /// year, and i64 nanoseconds run out around year 2262. The old unchecked
15767    /// multiply wrapped in release mode and handed back a plausible-looking
15768    /// in-range instant for an unrepresentable year — the exact failure a naive
15769    /// implementation still produces, so each far-out year below is a real
15770    /// negative case, not a restatement of the code.
15771    #[test]
15772    fn timestamp_replace_returns_nat_on_nanosecond_overflow_dzz6x() {
15773        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
15774
15775        for year in [3000, 10_000, 300_000, i64::MAX / 400] {
15776            let out = ts.replace(Some(year), None, None, None, None, None, None, None);
15777            assert!(
15778                out.is_nat(),
15779                "replace(year={year}) is unrepresentable in i64 ns and must be \
15780                 NaT, got nanos={:?} (year {:?}) — this is the silent wrap",
15781                out.nanos,
15782                out.year()
15783            );
15784        }
15785        for year in [-3000, -100_000, i64::MIN / 400] {
15786            let out = ts.replace(Some(year), None, None, None, None, None, None, None);
15787            assert!(out.is_nat(), "replace(year={year}) must be NaT");
15788        }
15789
15790        // Boundary: i64 ns tops out at 106_751 days from the epoch, so 2262 is
15791        // representable at the start of the year and 2263 is not. This pins the
15792        // fix to the real limit — a guard that merely rejected "big" years by
15793        // some rounder cutoff would fail one side of this pair.
15794        let in_range = ts.replace(
15795            Some(2262),
15796            Some(1),
15797            Some(1),
15798            Some(0),
15799            Some(0),
15800            Some(0),
15801            Some(0),
15802            Some(0),
15803        );
15804        assert!(
15805            !in_range.is_nat(),
15806            "2262-01-01 is representable and must survive"
15807        );
15808        assert_eq!(in_range.year(), Some(2262));
15809        assert!(
15810            ts.replace(
15811                Some(2263),
15812                Some(12),
15813                Some(31),
15814                Some(23),
15815                Some(59),
15816                Some(59),
15817                Some(999_999),
15818                Some(999)
15819            )
15820            .is_nat(),
15821            "end of 2263 exceeds the i64 ns axis and must be NaT"
15822        );
15823
15824        // In-range results are untouched by the checked arithmetic, including
15825        // the timezone, so the guard cannot have been bought with a behavior
15826        // change on the normal path.
15827        let unchanged = ts.replace(
15828            Some(1999),
15829            Some(6),
15830            Some(30),
15831            Some(12),
15832            Some(1),
15833            Some(2),
15834            Some(3),
15835            Some(4),
15836        );
15837        assert_eq!(unchanged.year(), Some(1999));
15838        assert_eq!(unchanged.month(), Some(6));
15839        assert_eq!(unchanged.day(), Some(30));
15840        assert_eq!(unchanged.hour(), Some(12));
15841        assert_eq!(unchanged.minute(), Some(1));
15842        assert_eq!(unchanged.second(), Some(2));
15843        assert_eq!(unchanged.microsecond(), Some(3));
15844        assert_eq!(unchanged.nanosecond(), Some(4));
15845        let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
15846        assert_eq!(
15847            tz.replace(Some(1999), None, None, None, None, None, None, None)
15848                .tz
15849                .as_deref(),
15850            Some("UTC")
15851        );
15852    }
15853
15854    #[test]
15855    fn timestamp_component_accessors() {
15856        let ts = Timestamp::from_nanos(0);
15857        assert_eq!(ts.year(), Some(1970));
15858        assert_eq!(ts.month(), Some(1));
15859        assert_eq!(ts.day(), Some(1));
15860        assert_eq!(ts.hour(), Some(0));
15861        assert_eq!(ts.minute(), Some(0));
15862        assert_eq!(ts.second(), Some(0));
15863        assert_eq!(ts.microsecond(), Some(0));
15864        assert_eq!(ts.nanosecond(), Some(0));
15865
15866        let ts2 = Timestamp::from_nanos(
15867            Timedelta::NANOS_PER_DAY * 365
15868                + Timedelta::NANOS_PER_HOUR * 14
15869                + Timedelta::NANOS_PER_MIN * 30
15870                + Timedelta::NANOS_PER_SEC * 45
15871                + 123_456_789,
15872        );
15873        assert_eq!(ts2.year(), Some(1971));
15874        assert_eq!(ts2.month(), Some(1));
15875        assert_eq!(ts2.day(), Some(1));
15876        assert_eq!(ts2.hour(), Some(14));
15877        assert_eq!(ts2.minute(), Some(30));
15878        assert_eq!(ts2.second(), Some(45));
15879        assert_eq!(ts2.microsecond(), Some(123456));
15880        assert_eq!(ts2.nanosecond(), Some(789));
15881
15882        assert_eq!(Timestamp::nat().year(), None);
15883        assert_eq!(Timestamp::nat().month(), None);
15884        assert_eq!(Timestamp::nat().day(), None);
15885    }
15886
15887    #[test]
15888    fn timestamp_dayofweek_dayofyear_quarter() {
15889        let ts = Timestamp::from_nanos(0);
15890        assert_eq!(ts.dayofweek(), Some(3));
15891        assert_eq!(ts.weekday(), Some(3));
15892        assert_eq!(ts.dayofyear(), Some(1));
15893        assert_eq!(ts.quarter(), Some(1));
15894
15895        let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 90);
15896        assert_eq!(ts2.quarter(), Some(2));
15897
15898        let ts3 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
15899        assert_eq!(ts3.dayofyear(), Some(1));
15900        assert_eq!(ts3.dayofweek(), Some(4));
15901
15902        assert_eq!(Timestamp::nat().dayofweek(), None);
15903        assert_eq!(Timestamp::nat().dayofyear(), None);
15904        assert_eq!(Timestamp::nat().quarter(), None);
15905    }
15906
15907    #[test]
15908    fn timestamp_is_boundary_methods() {
15909        let jan1 = Timestamp::from_nanos(0);
15910        assert_eq!(jan1.is_leap_year(), Some(false));
15911        assert_eq!(jan1.is_month_start(), Some(true));
15912        assert_eq!(jan1.is_month_end(), Some(false));
15913        assert_eq!(jan1.is_quarter_start(), Some(true));
15914        assert_eq!(jan1.is_quarter_end(), Some(false));
15915        assert_eq!(jan1.is_year_start(), Some(true));
15916        assert_eq!(jan1.is_year_end(), Some(false));
15917
15918        let dec31 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 364);
15919        assert_eq!(dec31.is_month_start(), Some(false));
15920        assert_eq!(dec31.is_month_end(), Some(true));
15921        assert_eq!(dec31.is_quarter_end(), Some(true));
15922        assert_eq!(dec31.is_year_end(), Some(true));
15923
15924        assert_eq!(Timestamp::nat().is_leap_year(), None);
15925        assert_eq!(Timestamp::nat().is_month_start(), None);
15926    }
15927
15928    #[test]
15929    fn timestamp_days_in_month() {
15930        let jan = Timestamp::from_nanos(0);
15931        assert_eq!(jan.days_in_month(), Some(31));
15932        assert_eq!(jan.daysinmonth(), Some(31));
15933
15934        let feb_non_leap = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 31);
15935        assert_eq!(feb_non_leap.days_in_month(), Some(28));
15936
15937        assert_eq!(Timestamp::nat().days_in_month(), None);
15938    }
15939
15940    #[test]
15941    fn timestamp_weekofyear() {
15942        let jan1 = Timestamp::from_nanos(0);
15943        assert_eq!(jan1.weekofyear(), Some(1));
15944        assert_eq!(jan1.week(), Some(1));
15945
15946        let jan8 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 7);
15947        assert_eq!(jan8.weekofyear(), Some(2));
15948
15949        assert_eq!(Timestamp::nat().weekofyear(), None);
15950        assert_eq!(Timestamp::nat().week(), None);
15951    }
15952
15953    #[test]
15954    fn timestamp_weekofyear_iso_53_week_boundaries() {
15955        // ISO-8601 53-week-year boundaries vs pandas 2.2.3 isocalendar().week.
15956        // (br-frankenpandas-xmfmd) Date -> nanos via days since 1970-01-01.
15957        fn week_of(date_days: i64) -> Option<i64> {
15958            Timestamp::from_nanos(date_days * Timedelta::NANOS_PER_DAY).weekofyear()
15959        }
15960        // Days from 1970-01-01 for each date (UTC, no tz).
15961        // 2021-01-01 -> week 53 (2020 is a 53-week year); FP used to give 52.
15962        assert_eq!(week_of(18_628), Some(53)); // 2021-01-01
15963        // 2016-01-01 -> week 53 (2015 is a 53-week year).
15964        assert_eq!(week_of(16_801), Some(53)); // 2016-01-01
15965        // 2026-12-31 -> week 53; FP used to give 1.
15966        assert_eq!(week_of(20_818), Some(53)); // 2026-12-31
15967        // 2020-12-31 -> week 53.
15968        assert_eq!(week_of(18_627), Some(53)); // 2020-12-31
15969        // Cases that must stay correct (non-53 boundaries):
15970        assert_eq!(week_of(19_358), Some(52)); // 2023-01-01 -> week 52
15971        assert_eq!(week_of(20_087), Some(1)); // 2024-12-30 -> week 1
15972        assert_eq!(week_of(18_260), Some(1)); // 2019-12-30 -> week 1
15973    }
15974
15975    #[test]
15976    fn iso_weeks_in_year_53_week_years() {
15977        use super::iso_weeks_in_year;
15978        // Known 53-week years; everything else is 52.
15979        for y in [2004, 2009, 2015, 2020, 2026] {
15980            assert_eq!(iso_weeks_in_year(y), 53, "{y} should have 53 ISO weeks");
15981        }
15982        for y in [2018, 2019, 2021, 2022, 2023, 2024] {
15983            assert_eq!(iso_weeks_in_year(y), 52, "{y} should have 52 ISO weeks");
15984        }
15985    }
15986
15987    #[test]
15988    fn timestamp_to_unit() {
15989        let ts = Timestamp::from_nanos(1_000_000_000);
15990        assert_eq!(ts.to_unit("ns"), Some(1_000_000_000));
15991        assert_eq!(ts.to_unit("us"), Some(1_000_000));
15992        assert_eq!(ts.to_unit("ms"), Some(1_000));
15993        assert_eq!(ts.to_unit("s"), Some(1));
15994        assert_eq!(ts.to_unit("invalid"), None);
15995
15996        assert_eq!(Timestamp::nat().to_unit("ns"), None);
15997    }
15998
15999    #[test]
16000    fn timestamp_toordinal() {
16001        // 2026-01-01 is ordinal 738886 (days since Jan 1, year 1)
16002        // Days from Unix epoch: 738886 - 719163 = 19723
16003        let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
16004        let ts = Timestamp::from_nanos(nanos_2026_01_01);
16005        assert_eq!(ts.toordinal(), Some(738886));
16006
16007        // NaT returns None
16008        assert_eq!(Timestamp::nat().toordinal(), None);
16009    }
16010
16011    #[test]
16012    fn timestamp_fromordinal() {
16013        // Round-trip test: create a timestamp from ordinal derived from toordinal
16014        // First create a known timestamp
16015        let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
16016        let ts_orig = Timestamp::from_nanos(nanos_2026_01_01);
16017        let ordinal = ts_orig.toordinal().unwrap();
16018
16019        // Now convert back using fromordinal
16020        let ts = Timestamp::fromordinal(ordinal);
16021        assert_eq!(ts.year(), ts_orig.year());
16022        assert_eq!(ts.month(), ts_orig.month());
16023        assert_eq!(ts.day(), ts_orig.day());
16024
16025        // Invalid ordinal returns NaT
16026        let nat = Timestamp::fromordinal(0);
16027        assert!(nat.is_nat());
16028    }
16029
16030    #[test]
16031    fn timestamp_fromordinal_guards_nanosecond_overflow_ycvrd() {
16032        const EPOCH_ORDINAL: i64 = 719_163;
16033        let max_day_offset = i64::MAX / Timedelta::NANOS_PER_DAY;
16034        let max_valid_ordinal = EPOCH_ORDINAL + max_day_offset;
16035
16036        let max_valid = Timestamp::fromordinal(max_valid_ordinal);
16037        assert!(!max_valid.is_nat());
16038        assert_eq!(max_valid.nanos, max_day_offset * Timedelta::NANOS_PER_DAY);
16039
16040        assert!(Timestamp::fromordinal(max_valid_ordinal + 1).is_nat());
16041        assert!(Timestamp::fromordinal(i64::MAX).is_nat());
16042    }
16043
16044    #[test]
16045    fn timestamp_ordinal_matches_seeded_epoch_oracle_l2f0p() {
16046        const EPOCH_ORDINAL: i64 = 719_163;
16047        const DAY: i64 = Timedelta::NANOS_PER_DAY;
16048
16049        fn next(seed: &mut u64) -> u64 {
16050            *seed = seed
16051                .wrapping_mul(3202034522624059733)
16052                .wrapping_add(4354685564936845319);
16053            *seed
16054        }
16055
16056        fn assert_ordinal_case(case: usize, day_offset: i64, subday_nanos: i64) {
16057            let nanos = day_offset.saturating_mul(DAY).saturating_add(subday_nanos);
16058            let ts = Timestamp::from_nanos(nanos);
16059            let expected_day_offset = nanos.div_euclid(DAY);
16060            let expected_ordinal = EPOCH_ORDINAL + expected_day_offset;
16061
16062            assert_eq!(
16063                ts.toordinal(),
16064                Some(expected_ordinal),
16065                "case {case}: toordinal"
16066            );
16067
16068            let midnight = Timestamp::fromordinal(expected_ordinal);
16069            assert_eq!(
16070                midnight.nanos,
16071                expected_day_offset * DAY,
16072                "case {case}: fromordinal nanos"
16073            );
16074            assert_eq!(
16075                midnight.toordinal(),
16076                Some(expected_ordinal),
16077                "case {case}: fromordinal roundtrip"
16078            );
16079        }
16080
16081        assert_eq!(Timestamp::nat().toordinal(), None);
16082        assert!(Timestamp::fromordinal(0).is_nat());
16083        assert!(Timestamp::fromordinal(-1).is_nat());
16084
16085        assert_ordinal_case(usize::MAX, -1, DAY - 1);
16086        assert_ordinal_case(usize::MAX - 1, 0, -1);
16087        assert_ordinal_case(usize::MAX - 2, 19_723, 0);
16088
16089        let mut seed = 0x1f20_f0d1_0a11_0d1e_u64;
16090        for case in 0..260 {
16091            let day_offset = (next(&mut seed) % 40_001) as i64 - 10_000;
16092            let subday_nanos = match case % 7 {
16093                0 => 0,
16094                1 => DAY - 1,
16095                2 => -1,
16096                _ => (next(&mut seed) % (2 * DAY as u64 - 1)) as i64 - (DAY - 1),
16097            };
16098            assert_ordinal_case(case, day_offset, subday_nanos);
16099        }
16100    }
16101
16102    /// br-frankenpandas-94o1u: `parse_date` bounds the month and the day but
16103    /// parses the YEAR as an unbounded i64, and i64 nanoseconds top out around
16104    /// 2262. The old unchecked composition wrapped in release, so these inputs
16105    /// returned `Ok` holding a plausible in-range instant instead of failing —
16106    /// on the INGESTION path, where the input is untrusted. Each case below is
16107    /// a real negative case: a naive implementation still returns Ok here.
16108    #[test]
16109    fn timestamp_parse_rejects_unrepresentable_years_94o1u() {
16110        for s in [
16111            "300000-01-01",
16112            "10000000-06-15T12:30:45",
16113            "999999999-01-01",
16114            "-300000-01-01",
16115            "-99999999-12-31T23:59:59",
16116        ] {
16117            let got = Timestamp::parse(s);
16118            assert!(
16119                got.is_err(),
16120                "parse({s:?}) is unrepresentable in i64 ns and must be Err, got {:?} \
16121                 — this is the silent wrap",
16122                got.map(|ts| (ts.nanos, ts.year()))
16123            );
16124        }
16125
16126        // Boundary: the i64 ns axis reaches into 2262 but not 2263. Pins the
16127        // guard to the real limit — a cutoff at some rounder year fails a side.
16128        let ok = Timestamp::parse("2262-01-01").expect("2262-01-01 is representable");
16129        assert_eq!(ok.year(), Some(2262));
16130        assert!(
16131            Timestamp::parse("2263-12-31T23:59:59").is_err(),
16132            "end of 2263 exceeds the i64 ns axis and must be Err"
16133        );
16134
16135        // A rejected year must not poison the normal path: ordinary parses,
16136        // including every accepted shape (date-only, T- and space-separated,
16137        // fractional seconds, tz suffix), still succeed and are unchanged.
16138        assert_eq!(Timestamp::parse("2024-01-15").unwrap().year(), Some(2024));
16139        assert_eq!(
16140            Timestamp::parse("2024-01-15T10:30:45").unwrap().hour(),
16141            Some(10)
16142        );
16143        assert_eq!(
16144            Timestamp::parse("2024-01-15 10:30:45").unwrap().minute(),
16145            Some(30)
16146        );
16147        assert_eq!(
16148            Timestamp::parse("2024-01-15T10:30:45.123456789")
16149                .unwrap()
16150                .nanosecond(),
16151            Some(789)
16152        );
16153        assert_eq!(
16154            Timestamp::parse("2024-01-15T00:00:00Z").unwrap().year(),
16155            Some(2024)
16156        );
16157        // Pre-epoch (negative nanos) is representable and must keep working.
16158        assert_eq!(Timestamp::parse("1900-01-01").unwrap().year(), Some(1900));
16159    }
16160
16161    #[test]
16162    fn timestamp_parse_iso8601_date_only() {
16163        let ts = Timestamp::parse("2024-01-15").unwrap();
16164        assert_eq!(ts.year(), Some(2024));
16165        assert_eq!(ts.month(), Some(1));
16166        assert_eq!(ts.day(), Some(15));
16167        assert_eq!(ts.hour(), Some(0));
16168        assert_eq!(ts.minute(), Some(0));
16169        assert_eq!(ts.second(), Some(0));
16170    }
16171
16172    #[test]
16173    fn timestamp_parse_iso8601_datetime() {
16174        let ts = Timestamp::parse("2024-01-15T10:30:45").unwrap();
16175        assert_eq!(ts.year(), Some(2024));
16176        assert_eq!(ts.month(), Some(1));
16177        assert_eq!(ts.day(), Some(15));
16178        assert_eq!(ts.hour(), Some(10));
16179        assert_eq!(ts.minute(), Some(30));
16180        assert_eq!(ts.second(), Some(45));
16181    }
16182
16183    #[test]
16184    fn timestamp_parse_space_separator() {
16185        let ts = Timestamp::parse("2024-01-15 10:30:45").unwrap();
16186        assert_eq!(ts.year(), Some(2024));
16187        assert_eq!(ts.hour(), Some(10));
16188    }
16189
16190    #[test]
16191    fn timestamp_parse_with_fractional_seconds() {
16192        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
16193        assert_eq!(ts.second(), Some(45));
16194        assert_eq!(ts.microsecond(), Some(123456));
16195        assert_eq!(ts.nanosecond(), Some(789));
16196    }
16197
16198    #[test]
16199    fn timestamp_parse_utc_timezone() {
16200        let ts = Timestamp::parse("2024-01-15T10:30:45Z").unwrap();
16201        assert_eq!(ts.tz, Some("UTC".to_string()));
16202    }
16203
16204    #[test]
16205    fn timestamp_parse_offset_timezone() {
16206        let ts = Timestamp::parse("2024-01-15T10:30:45+05:30").unwrap();
16207        assert_eq!(ts.tz, Some("+05:30".to_string()));
16208
16209        let ts = Timestamp::parse("2024-01-15T10:30:45-05:30").unwrap();
16210        assert_eq!(ts.tz, Some("-05:30".to_string()));
16211    }
16212
16213    #[test]
16214    fn timestamp_parse_rejects_invalid_timezone_offsets_0v676() {
16215        assert!(Timestamp::parse("2024-01-15T10:30:45+bad").is_err());
16216        assert!(Timestamp::parse("2024-01-15T10:30:45+0500").is_err());
16217        assert!(Timestamp::parse("2024-01-15T10:30:45+24:00").is_err());
16218        assert!(Timestamp::parse("2024-01-15T10:30:45+05:60").is_err());
16219        assert!(Timestamp::parse("2024-01-15T10:30:45-25:00").is_err());
16220    }
16221
16222    #[test]
16223    fn timestamp_parse_nat() {
16224        let ts = Timestamp::parse("NaT").unwrap();
16225        assert!(ts.is_nat());
16226        let ts2 = Timestamp::parse("nat").unwrap();
16227        assert!(ts2.is_nat());
16228    }
16229
16230    #[test]
16231    fn timestamp_parse_invalid() {
16232        assert!(Timestamp::parse("not a date").is_err());
16233        assert!(Timestamp::parse("2024-13-01").is_err()); // invalid month
16234        assert!(Timestamp::parse("2024-01-32").is_err()); // invalid day
16235    }
16236
16237    #[test]
16238    fn timestamp_parse_rejects_invalid_fractional_seconds_87se2() {
16239        assert!(Timestamp::parse("2024-01-15T10:30:45.").is_err());
16240        assert!(Timestamp::parse("2024-01-15T10:30:45.abc").is_err());
16241        assert!(Timestamp::parse("2024-01-15T10:30:45.-1").is_err());
16242        assert!(Timestamp::parse("2024-01-15T10:30:45.123").is_err());
16243        assert!(Timestamp::parse("2024-01-15T10:30:45.123456789x").is_err());
16244
16245        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789987").unwrap();
16246        assert_eq!(ts.second(), Some(45));
16247        assert_eq!(ts.microsecond(), Some(123456));
16248        assert_eq!(ts.nanosecond(), Some(789));
16249    }
16250
16251    #[test]
16252    #[ignore = "foreground profile-first A/B"]
16253    fn timestamp_parse_fraction_digit_fold_profile_pdiku() {
16254        use std::{hint::black_box, time::Instant};
16255
16256        const CALLS: usize = 131_072;
16257        const SAMPLES: usize = 12;
16258        type ParsedTime = Option<(u32, u32, u32, u64)>;
16259        const VALID: [&str; 16] = [
16260            "00:00:00.0",
16261            "01:02:03.1",
16262            "02:03:04.01",
16263            "03:04:05.001",
16264            "04:05:06.0001",
16265            "05:06:07.00001",
16266            "06:07:08.000001",
16267            "07:08:09.0000001",
16268            "08:09:10.00000001",
16269            "09:10:11.000000001",
16270            "10:11:12.123456789",
16271            "11:12:13.999999999",
16272            "12:13:14.123456789987",
16273            "13:14:15.000000000001",
16274            "14:15:16.101010101010",
16275            "23:59:59.987654321234",
16276        ];
16277
16278        #[inline(never)]
16279        fn former(s: &str) -> ParsedTime {
16280            let (time_str, frac_str) = match s.split_once('.') {
16281                Some((time, frac)) => (time, Some(frac)),
16282                None => (s, None),
16283            };
16284            let parts: Vec<&str> = time_str.split(':').collect();
16285            if parts.is_empty() || parts.len() > 3 {
16286                return None;
16287            }
16288            let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
16289            let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
16290            let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
16291
16292            if hour > 23 || minute > 59 || second > 59 {
16293                return None;
16294            }
16295
16296            let nanos = match frac_str {
16297                None => 0,
16298                Some(frac) => {
16299                    if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
16300                        return None;
16301                    }
16302                    let truncated = &frac[..frac.len().min(9)];
16303                    let padded = format!("{truncated:0<9}");
16304                    padded.parse::<u64>().ok()?
16305                }
16306            };
16307
16308            Some((hour, minute, second, nanos))
16309        }
16310
16311        #[inline(never)]
16312        fn candidate(s: &str) -> ParsedTime {
16313            Timestamp::parse_time(s)
16314        }
16315
16316        fn elapsed(inputs: &[&str], parser: fn(&str) -> ParsedTime) -> u128 {
16317            let started = Instant::now();
16318            for input in black_box(inputs) {
16319                black_box(parser(black_box(*input)));
16320            }
16321            started.elapsed().as_nanos()
16322        }
16323
16324        fn percentile(samples: &[u128], percent: usize) -> u128 {
16325            let mut sorted = samples.to_vec();
16326            sorted.sort_unstable();
16327            let rank = (sorted.len() * percent).div_ceil(100).saturating_sub(1);
16328            sorted[rank]
16329        }
16330
16331        let invalid = [
16332            "",
16333            "24:00:00.1",
16334            "12:60:00.1",
16335            "12:00:60.1",
16336            "12:00:00.",
16337            "12:00:00.abc",
16338            "12:00:00.-1",
16339            "12:00:00.123",
16340            "12:00:00.123456789x",
16341            "12:00:00.1.2",
16342            "12:00:00:01.1",
16343        ];
16344        for input in VALID.iter().chain(invalid.iter()) {
16345            assert_eq!(candidate(input), former(input), "input={input:?}");
16346        }
16347
16348        let inputs = (0..CALLS)
16349            .map(|index| VALID[index % VALID.len()])
16350            .collect::<Vec<_>>();
16351        for _ in 0..2 {
16352            black_box(elapsed(&inputs, former));
16353            black_box(elapsed(&inputs, candidate));
16354        }
16355
16356        let mut former_ns = Vec::with_capacity(SAMPLES);
16357        let mut candidate_ns = Vec::with_capacity(SAMPLES);
16358        for sample in 0..SAMPLES {
16359            if sample.is_multiple_of(2) {
16360                former_ns.push(elapsed(&inputs, former));
16361                candidate_ns.push(elapsed(&inputs, candidate));
16362            } else {
16363                candidate_ns.push(elapsed(&inputs, candidate));
16364                former_ns.push(elapsed(&inputs, former));
16365            }
16366        }
16367
16368        let former_p50 = percentile(&former_ns, 50);
16369        let former_p95 = percentile(&former_ns, 95);
16370        let former_p99 = percentile(&former_ns, 99);
16371        let candidate_p50 = percentile(&candidate_ns, 50);
16372        let candidate_p95 = percentile(&candidate_ns, 95);
16373        let candidate_p99 = percentile(&candidate_ns, 99);
16374        println!(
16375            "TIMESTAMP_FRACTION_PARSE calls={CALLS} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup_p50={:.6} former_p95_ns={former_p95} candidate_p95_ns={candidate_p95} speedup_p95={:.6} former_p99_ns={former_p99} candidate_p99_ns={candidate_p99} speedup_p99={:.6} former_samples={former_ns:?} candidate_samples={candidate_ns:?}",
16376            former_p50 as f64 / candidate_p50 as f64,
16377            former_p95 as f64 / candidate_p95 as f64,
16378            former_p99 as f64 / candidate_p99 as f64,
16379        );
16380    }
16381
16382    #[test]
16383    fn timestamp_parse_matches_seeded_iso_component_oracle_1u7a0() {
16384        fn next(seed: &mut u64) -> u64 {
16385            *seed = seed
16386                .wrapping_mul(3935559000370003845)
16387                .wrapping_add(2691343689449507681);
16388            *seed
16389        }
16390
16391        fn leap(year: i64) -> bool {
16392            (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
16393        }
16394
16395        fn month_len(year: i64, month: u32) -> u32 {
16396            match month {
16397                1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
16398                4 | 6 | 9 | 11 => 30,
16399                2 if leap(year) => 29,
16400                2 => 28,
16401                _ => 0,
16402            }
16403        }
16404
16405        struct Components {
16406            year: i64,
16407            month: u32,
16408            day: u32,
16409            hour: u32,
16410            minute: u32,
16411            second: u32,
16412            nanos: u64,
16413        }
16414
16415        fn assert_components(case: usize, text: &str, expected: Components) {
16416            let ts = Timestamp::parse(text).expect("seeded valid timestamp");
16417            let Components {
16418                year,
16419                month,
16420                day,
16421                hour,
16422                minute,
16423                second,
16424                nanos,
16425            } = expected;
16426            assert_eq!(ts.year(), Some(year), "case {case}: year");
16427            assert_eq!(ts.month(), Some(month as i64), "case {case}: month");
16428            assert_eq!(ts.day(), Some(day as i64), "case {case}: day");
16429            assert_eq!(ts.hour(), Some(hour as i64), "case {case}: hour");
16430            assert_eq!(ts.minute(), Some(minute as i64), "case {case}: minute");
16431            assert_eq!(ts.second(), Some(second as i64), "case {case}: second");
16432            assert_eq!(
16433                ts.microsecond(),
16434                Some((nanos / 1000) as i64),
16435                "case {case}: microsecond"
16436            );
16437            assert_eq!(
16438                ts.nanosecond(),
16439                Some((nanos % 1000) as i64),
16440                "case {case}: nanosecond"
16441            );
16442        }
16443
16444        assert!(Timestamp::parse("NaT").expect("NaT parses").is_nat());
16445        assert!(
16446            Timestamp::parse("nAt")
16447                .expect("mixed-case NaT parses")
16448                .is_nat()
16449        );
16450        assert!(Timestamp::parse("1900-02-29").is_err());
16451        assert!(Timestamp::parse("2001-04-31").is_err());
16452        assert!(Timestamp::parse("2024-00-15").is_err());
16453
16454        assert_components(
16455            usize::MAX,
16456            "2000-02-29",
16457            Components {
16458                year: 2000,
16459                month: 2,
16460                day: 29,
16461                hour: 0,
16462                minute: 0,
16463                second: 0,
16464                nanos: 0,
16465            },
16466        );
16467        assert_components(
16468            usize::MAX - 1,
16469            "2024-02-29T23:59:59.000000001",
16470            Components {
16471                year: 2024,
16472                month: 2,
16473                day: 29,
16474                hour: 23,
16475                minute: 59,
16476                second: 59,
16477                nanos: 1,
16478            },
16479        );
16480
16481        let mut seed = 0x15e0_1d50_1f0a_cade_u64;
16482        for case in 0..260 {
16483            let year = 1900 + (next(&mut seed) % 201) as i64;
16484            let month = 1 + (next(&mut seed) % 12) as u32;
16485            let day = 1 + (next(&mut seed) % month_len(year, month) as u64) as u32;
16486            let hour = (next(&mut seed) % 24) as u32;
16487            let minute = (next(&mut seed) % 60) as u32;
16488            let second = (next(&mut seed) % 60) as u32;
16489            let nanos = next(&mut seed) % 1_000_000_000;
16490
16491            match case % 4 {
16492                0 => {
16493                    let text = format!("{year:04}-{month:02}-{day:02}");
16494                    assert_components(
16495                        case,
16496                        &text,
16497                        Components {
16498                            year,
16499                            month,
16500                            day,
16501                            hour: 0,
16502                            minute: 0,
16503                            second: 0,
16504                            nanos: 0,
16505                        },
16506                    );
16507                }
16508                1 => {
16509                    let text =
16510                        format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}");
16511                    assert_components(
16512                        case,
16513                        &text,
16514                        Components {
16515                            year,
16516                            month,
16517                            day,
16518                            hour,
16519                            minute,
16520                            second,
16521                            nanos: 0,
16522                        },
16523                    );
16524                }
16525                2 => {
16526                    let text =
16527                        format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}");
16528                    assert_components(
16529                        case,
16530                        &text,
16531                        Components {
16532                            year,
16533                            month,
16534                            day,
16535                            hour,
16536                            minute,
16537                            second,
16538                            nanos: 0,
16539                        },
16540                    );
16541                }
16542                _ => {
16543                    let text = format!(
16544                        "{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{nanos:09}"
16545                    );
16546                    assert_components(
16547                        case,
16548                        &text,
16549                        Components {
16550                            year,
16551                            month,
16552                            day,
16553                            hour,
16554                            minute,
16555                            second,
16556                            nanos,
16557                        },
16558                    );
16559                }
16560            }
16561        }
16562    }
16563
16564    #[test]
16565    fn period_parse_annual() {
16566        let p = Period::parse("2024").unwrap();
16567        assert_eq!(p.freq(), PeriodFreq::Annual);
16568        assert_eq!(p.ordinal(), 2024 - 1970);
16569    }
16570
16571    #[test]
16572    fn period_parse_quarterly() {
16573        let p = Period::parse("2024Q1").unwrap();
16574        assert_eq!(p.freq(), PeriodFreq::Quarterly);
16575        assert_eq!(p.ordinal(), (2024 - 1970) * 4);
16576
16577        let p2 = Period::parse("2024q3").unwrap();
16578        assert_eq!(p2.freq(), PeriodFreq::Quarterly);
16579        assert_eq!(p2.ordinal(), (2024 - 1970) * 4 + 2);
16580    }
16581
16582    #[test]
16583    fn period_parse_monthly() {
16584        let p = Period::parse("2024-01").unwrap();
16585        assert_eq!(p.freq(), PeriodFreq::Monthly);
16586        assert_eq!(p.ordinal(), (2024 - 1970) * 12);
16587
16588        let p2 = Period::parse("2024-12").unwrap();
16589        assert_eq!(p2.freq(), PeriodFreq::Monthly);
16590        assert_eq!(p2.ordinal(), (2024 - 1970) * 12 + 11);
16591    }
16592
16593    #[test]
16594    fn period_parse_nat() {
16595        let p = Period::parse("NaT").unwrap();
16596        assert_eq!(p.ordinal(), i64::MIN);
16597    }
16598
16599    #[test]
16600    fn period_parse_invalid() {
16601        assert!(Period::parse("not a period").is_err());
16602        assert!(Period::parse("2024Q5").is_err()); // invalid quarter
16603        assert!(Period::parse("2024-13").is_err()); // invalid month
16604    }
16605
16606    #[test]
16607    fn interval_parse_basic() {
16608        let i = Interval::parse("[0, 1]").unwrap();
16609        assert_eq!(i.left, 0.0);
16610        assert_eq!(i.right, 1.0);
16611        assert_eq!(i.closed, IntervalClosed::Both);
16612
16613        let i2 = Interval::parse("(0, 1)").unwrap();
16614        assert_eq!(i2.left, 0.0);
16615        assert_eq!(i2.right, 1.0);
16616        assert_eq!(i2.closed, IntervalClosed::Neither);
16617
16618        let i3 = Interval::parse("[0, 1)").unwrap();
16619        assert_eq!(i3.closed, IntervalClosed::Left);
16620
16621        let i4 = Interval::parse("(0, 1]").unwrap();
16622        assert_eq!(i4.closed, IntervalClosed::Right);
16623    }
16624
16625    #[test]
16626    fn interval_parse_floats() {
16627        let i = Interval::parse("[-1.5, 2.5)").unwrap();
16628        assert_eq!(i.left, -1.5);
16629        assert_eq!(i.right, 2.5);
16630        assert_eq!(i.closed, IntervalClosed::Left);
16631    }
16632
16633    #[test]
16634    fn interval_parse_invalid() {
16635        assert!(Interval::parse("invalid").is_err());
16636        assert!(Interval::parse("[0]").is_err());
16637        assert!(Interval::parse("0, 1").is_err()); // missing brackets
16638    }
16639
16640    fn interval_parse_error_profile(s: &str) -> super::TypeError {
16641        super::TypeError::ValueNotParseable {
16642            value: s.to_string(),
16643            target: "Interval".to_string(),
16644        }
16645    }
16646
16647    #[inline(never)]
16648    fn interval_parse_former_profile(s: &str) -> Result<Interval, super::TypeError> {
16649        let s = std::hint::black_box(s).trim();
16650        if s.len() < 5 {
16651            return Err(interval_parse_error_profile(s));
16652        }
16653
16654        let first_char = s.chars().next().unwrap();
16655        let last_char = s.chars().last().unwrap();
16656        let left_closed = match first_char {
16657            '[' => true,
16658            '(' => false,
16659            _ => return Err(interval_parse_error_profile(s)),
16660        };
16661        let right_closed = match last_char {
16662            ']' => true,
16663            ')' => false,
16664            _ => return Err(interval_parse_error_profile(s)),
16665        };
16666        let closed = match (left_closed, right_closed) {
16667            (true, true) => IntervalClosed::Both,
16668            (true, false) => IntervalClosed::Left,
16669            (false, true) => IntervalClosed::Right,
16670            (false, false) => IntervalClosed::Neither,
16671        };
16672
16673        let inner = &s[1..s.len() - 1];
16674        let parts: Vec<&str> = inner.split(',').collect();
16675        if parts.len() != 2 {
16676            return Err(interval_parse_error_profile(s));
16677        }
16678        let left = parts[0]
16679            .trim()
16680            .parse()
16681            .map_err(|_| interval_parse_error_profile(s))?;
16682        let right = parts[1]
16683            .trim()
16684            .parse()
16685            .map_err(|_| interval_parse_error_profile(s))?;
16686        Ok(Interval::new(left, right, closed))
16687    }
16688
16689    #[inline(never)]
16690    fn interval_parse_split_once_profile(s: &str) -> Result<Interval, super::TypeError> {
16691        Interval::parse(std::hint::black_box(s))
16692    }
16693
16694    fn assert_interval_parse_profile_parity(s: &str) {
16695        match (
16696            interval_parse_former_profile(s),
16697            interval_parse_split_once_profile(s),
16698        ) {
16699            (Ok(former), Ok(candidate)) => {
16700                assert_eq!(former.left.to_bits(), candidate.left.to_bits(), "left: {s}");
16701                assert_eq!(
16702                    former.right.to_bits(),
16703                    candidate.right.to_bits(),
16704                    "right: {s}"
16705                );
16706                assert_eq!(former.closed, candidate.closed, "closed: {s}");
16707            }
16708            (Err(former), Err(candidate)) => assert_eq!(former, candidate, "error: {s}"),
16709            (former, candidate) => assert_eq!(
16710                former.is_ok(),
16711                candidate.is_ok(),
16712                "parse result mismatch for {s}: {former:?} != {candidate:?}"
16713            ),
16714        }
16715    }
16716
16717    #[inline(never)]
16718    fn measure_interval_parser_profile(
16719        parser: fn(&str) -> Result<Interval, super::TypeError>,
16720        inputs: &[&str],
16721        rounds: usize,
16722    ) -> u128 {
16723        use std::{hint::black_box, time::Instant};
16724
16725        let started = Instant::now();
16726        let mut checksum = 0_u64;
16727        for _ in 0..rounds {
16728            for input in inputs {
16729                let parsed = parser(black_box(input)).expect("profile input must parse");
16730                let closed = match parsed.closed {
16731                    IntervalClosed::Left => 1_u64,
16732                    IntervalClosed::Right => 2,
16733                    IntervalClosed::Both => 3,
16734                    IntervalClosed::Neither => 4,
16735                };
16736                checksum = checksum
16737                    .wrapping_add(parsed.left.to_bits().rotate_left(7))
16738                    .wrapping_add(parsed.right.to_bits().rotate_right(11))
16739                    .wrapping_add(closed);
16740                black_box(parsed);
16741            }
16742        }
16743        black_box(checksum);
16744        started.elapsed().as_nanos()
16745    }
16746
16747    #[test]
16748    #[ignore = "release-only attribution probe for br-frankenpandas-81jjv"]
16749    fn profile_interval_parse_endpoint_split_ab_81jjv() {
16750        const VALID: [&str; 8] = [
16751            "[0, 1]",
16752            "(-0.0, 0.0]",
16753            " [ -1.5e3 , 2.75E-4 ) ",
16754            "(NaN, -0]",
16755            "[-inf, inf)",
16756            "[9.25, -7.5]",
16757            "(4.9406564584124654e-324, 1.7976931348623157e308)",
16758            "[-42, 17.125)",
16759        ];
16760        const INVALID: [&str; 12] = [
16761            "invalid",
16762            "[0]",
16763            "0, 1",
16764            "[0 1]",
16765            "[0, 1, 2]",
16766            "[0, 1,]",
16767            "[0,,1]",
16768            "[, 1]",
16769            "[0, ]",
16770            "{0, 1}",
16771            "[0, 1}",
16772            "  ⟦0, 1⟧  ",
16773        ];
16774        const ROUNDS: usize = 16_384;
16775        const SAMPLES: usize = 10;
16776
16777        for input in VALID.iter().chain(INVALID.iter()) {
16778            assert_interval_parse_profile_parity(input);
16779        }
16780        for _ in 0..2 {
16781            measure_interval_parser_profile(interval_parse_former_profile, &VALID, ROUNDS);
16782            measure_interval_parser_profile(interval_parse_split_once_profile, &VALID, ROUNDS);
16783        }
16784
16785        let mut former_ns = Vec::with_capacity(SAMPLES);
16786        let mut candidate_ns = Vec::with_capacity(SAMPLES);
16787        for sample in 0..SAMPLES {
16788            if sample % 2 == 0 {
16789                former_ns.push(measure_interval_parser_profile(
16790                    interval_parse_former_profile,
16791                    &VALID,
16792                    ROUNDS,
16793                ));
16794                candidate_ns.push(measure_interval_parser_profile(
16795                    interval_parse_split_once_profile,
16796                    &VALID,
16797                    ROUNDS,
16798                ));
16799            } else {
16800                candidate_ns.push(measure_interval_parser_profile(
16801                    interval_parse_split_once_profile,
16802                    &VALID,
16803                    ROUNDS,
16804                ));
16805                former_ns.push(measure_interval_parser_profile(
16806                    interval_parse_former_profile,
16807                    &VALID,
16808                    ROUNDS,
16809                ));
16810            }
16811        }
16812        former_ns.sort_unstable();
16813        candidate_ns.sort_unstable();
16814        let former_p50 = former_ns[SAMPLES / 2];
16815        let candidate_p50 = candidate_ns[SAMPLES / 2];
16816        let former_p95 = former_ns[SAMPLES - 1];
16817        let candidate_p95 = candidate_ns[SAMPLES - 1];
16818        println!("PROFILE_INTERVAL_PARSE_FORMER_NS={former_ns:?}");
16819        println!("PROFILE_INTERVAL_PARSE_CANDIDATE_NS={candidate_ns:?}");
16820        println!(
16821            "PROFILE_INTERVAL_PARSE_P50_RATIO={:.6}",
16822            former_p50 as f64 / candidate_p50 as f64
16823        );
16824        println!(
16825            "PROFILE_INTERVAL_PARSE_P95_RATIO={:.6}",
16826            former_p95 as f64 / candidate_p95 as f64
16827        );
16828    }
16829}
16830
16831/// `DType::Float64Nullable` — pandas' `Float64Dtype()`, the dtype a nullable
16832/// Int64 lane widens INTO (br-frankenpandas-qkqfb).
16833///
16834/// Every rule asserted here was measured against live pandas 2.2.3 before it was
16835/// written; the measurement is quoted next to the assertion it justifies.
16836#[cfg(test)]
16837mod float64_nullable_qkqfb {
16838    use super::{DType, NullKind, Scalar, cast_scalar, common_dtype};
16839
16840    /// THE POINT OF THE DTYPE. A numpy float lane's missing value is a real NaN;
16841    /// the extension lane's is pd.NA. If both mapped to the same marker the two
16842    /// flavours would be indistinguishable and the dtype would buy nothing.
16843    ///
16844    /// MEASURED, live pandas 2.2.3:
16845    /// ```text
16846    ///   pd.Series([1.5, None], dtype="Float64")[1]     -> <NA>   (is pd.NA)
16847    ///   pd.Series([1.5, None])[1]                      -> nan
16848    ///   pd.Series([float("nan")], dtype="Float64")[0]  -> <NA>   COERCED
16849    /// ```
16850    #[test]
16851    fn the_two_float_flavours_have_different_missing_markers_qkqfb() {
16852        assert_eq!(
16853            Scalar::missing_for_dtype(DType::Float64Nullable),
16854            Scalar::Null(NullKind::Null),
16855            "the extension lane stores pd.NA"
16856        );
16857        assert_eq!(
16858            Scalar::missing_for_dtype(DType::Float64),
16859            Scalar::Null(NullKind::NaN),
16860            "the numpy lane stores a real NaN"
16861        );
16862        // The negative case: collapsing these two is precisely the defect, so
16863        // assert they are NOT equal rather than only asserting each value.
16864        assert_ne!(
16865            Scalar::missing_for_dtype(DType::Float64Nullable),
16866            Scalar::missing_for_dtype(DType::Float64),
16867        );
16868    }
16869
16870    /// MEASURED: `str(pd.Float64Dtype())` is `"Float64"`, and the numpy dtype is
16871    /// `"float64"`. dtype-check fixtures assert pandas' SPELLING
16872    /// (br-frankenpandas-62d1s), so the capital F is load-bearing, not cosmetic.
16873    #[test]
16874    fn spelling_is_pandas_spelling_qkqfb() {
16875        assert_eq!(DType::Float64Nullable.name(), "Float64");
16876        assert_eq!(DType::Float64.name(), "float64");
16877        assert_ne!(DType::Float64Nullable.name(), DType::Float64.name());
16878    }
16879
16880    /// The serde spelling has to survive a round trip AND stay distinct from the
16881    /// numpy flavour. `rename_all = "snake_case"` turns `Float64` into
16882    /// `"float64"`, which is what leaves `"Float64"` free for the extension —
16883    /// the same trick `Int64Nullable` already relies on. A naive
16884    /// `#[serde(rename = "Float64")]` on the WRONG variant would collide, and
16885    /// this test is what would catch it.
16886    #[test]
16887    fn serde_round_trips_and_does_not_collide_with_numpy_float64_qkqfb() {
16888        let ext = serde_json::to_string(&DType::Float64Nullable).expect("serialize");
16889        let numpy = serde_json::to_string(&DType::Float64).expect("serialize");
16890        assert_eq!(ext, "\"Float64\"");
16891        assert_eq!(numpy, "\"float64\"");
16892        assert_ne!(ext, numpy);
16893
16894        assert_eq!(
16895            serde_json::from_str::<DType>(&ext).expect("deserialize"),
16896            DType::Float64Nullable
16897        );
16898        assert_eq!(
16899            serde_json::from_str::<DType>(&numpy).expect("deserialize"),
16900            DType::Float64
16901        );
16902    }
16903
16904    /// It is a float, it is numeric, and it is a nullable extension — all three,
16905    /// or downstream dtype dispatch silently skips it.
16906    #[test]
16907    fn predicates_place_it_in_the_right_families_qkqfb() {
16908        assert!(DType::Float64Nullable.is_floating());
16909        assert!(DType::Float64Nullable.is_numeric());
16910        assert!(DType::Float64Nullable.is_any_real_numeric());
16911        assert!(DType::Float64Nullable.is_nullable());
16912        assert!(DType::Float64Nullable.is_extension());
16913        // And NOT these: an integer predicate that accepted it would let a
16914        // float value through an int-only fast path.
16915        assert!(!DType::Float64Nullable.is_integer());
16916        assert!(!DType::Float64Nullable.is_signed_integer());
16917        assert!(!DType::Float64Nullable.is_bool());
16918        // MEASURED: pd.Float64Dtype().kind == 'f', matching numpy float64 --
16919        // the extension reports its UNDERLYING kind, as Int64Nullable does.
16920        assert_eq!(DType::Float64Nullable.kind(), 'f');
16921        assert_eq!(DType::Float64Nullable.kind(), DType::Float64.kind());
16922        assert_eq!(DType::Float64Nullable.itemsize(), 8);
16923    }
16924
16925    /// The nullable/non-nullable pairing must be a genuine involution, or a
16926    /// round trip through either accessor silently changes flavour.
16927    #[test]
16928    fn nullable_pairing_is_an_involution_qkqfb() {
16929        assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
16930        assert_eq!(DType::Float64Nullable.to_non_nullable(), DType::Float64);
16931        // Idempotent at both ends.
16932        assert_eq!(DType::Float64Nullable.to_nullable(), DType::Float64Nullable);
16933        assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
16934        // The other families are untouched by the new variant.
16935        assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
16936        assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
16937    }
16938
16939    /// MEASURED ARITHMETIC, live pandas 2.2.3 -- this function models arithmetic
16940    /// promotion, not `find_common_type` (see the Bool arms in `common_dtype`):
16941    /// ```text
16942    ///   Float64(ext) + float64(numpy)  -> Float64
16943    ///   Int64(ext)   + Float64(ext)    -> Float64
16944    ///   boolean(ext) + Float64(ext)    -> Float64
16945    ///   Float64(ext) - Float64(ext)    -> Float64
16946    /// ```
16947    /// The nullable float absorbs every other numeric flavour.
16948    #[test]
16949    fn the_nullable_float_absorbs_every_numeric_flavour_qkqfb() {
16950        for other in [
16951            DType::Float64,
16952            DType::Int64,
16953            DType::Int64Nullable,
16954            DType::Bool,
16955            DType::BoolNullable,
16956            DType::Float64Nullable,
16957        ] {
16958            assert_eq!(
16959                common_dtype(DType::Float64Nullable, other.clone()),
16960                Ok(DType::Float64Nullable),
16961                "Float64Nullable + {other:?}"
16962            );
16963            // Commutativity is asserted wholesale by
16964            // common_dtype_lattice_axioms_be314; repeated here because an
16965            // asymmetric arm makes df1+df2 disagree with df2+df1.
16966            assert_eq!(
16967                common_dtype(other.clone(), DType::Float64Nullable),
16968                Ok(DType::Float64Nullable),
16969                "{other:?} + Float64Nullable"
16970            );
16971        }
16972        // Null is the lattice identity and must not absorb it.
16973        assert_eq!(
16974            common_dtype(DType::Null, DType::Float64Nullable),
16975            Ok(DType::Float64Nullable)
16976        );
16977    }
16978
16979    /// A PRESENT value crosses between the two float flavours unchanged; only the
16980    /// MISSING marker is converted.
16981    ///
16982    /// MEASURED:
16983    /// ```text
16984    ///   pd.Series([1.5,None],dtype="Float64").astype("float64") -> [1.5, nan]
16985    ///   pd.Series([1,None],  dtype="Int64").astype("Float64")   -> [1.0, <NA>]
16986    /// ```
16987    #[test]
16988    fn casts_preserve_values_and_convert_only_the_marker_qkqfb() {
16989        let present = Scalar::Float64(1.5);
16990        assert_eq!(
16991            cast_scalar(&present, DType::Float64Nullable),
16992            Ok(Scalar::Float64(1.5))
16993        );
16994        assert_eq!(
16995            cast_scalar(&Scalar::Float64(1.5), DType::Float64),
16996            Ok(Scalar::Float64(1.5))
16997        );
16998        // Int -> nullable float widens the value, as pandas does.
16999        assert_eq!(
17000            cast_scalar(&Scalar::Int64(1), DType::Float64Nullable),
17001            Ok(Scalar::Float64(1.0))
17002        );
17003        assert_eq!(
17004            cast_scalar(&Scalar::Bool(true), DType::Float64Nullable),
17005            Ok(Scalar::Float64(1.0))
17006        );
17007
17008        // THE MARKER CONVERSION, in both directions. This is the assertion a
17009        // "just alias Float64Nullable to Float64" implementation fails.
17010        assert_eq!(
17011            cast_scalar(&Scalar::Null(NullKind::NaN), DType::Float64Nullable),
17012            Ok(Scalar::Null(NullKind::Null)),
17013            "numpy NaN entering an extension lane becomes pd.NA"
17014        );
17015        assert_eq!(
17016            cast_scalar(&Scalar::Null(NullKind::Null), DType::Float64),
17017            Ok(Scalar::Null(NullKind::NaN)),
17018            "pd.NA entering a numpy lane becomes NaN"
17019        );
17020    }
17021
17022    /// The slice boundary this test used to pin has now been crossed: a
17023    /// nullable lane widening against a numpy float answers the NULLABLE float.
17024    /// MEASURED, live pandas 2.2.3, both spellings:
17025    /// ```text
17026    ///   find_common_type([Int64, float64])                        ->  Float64
17027    ///   pd.Series([1,None],dtype="Int64") + pd.Series([1.5,2.5])  ->  Float64
17028    /// ```
17029    /// (`Float64` there is the EXTENSION dtype — `Float64Dtype()` — not numpy
17030    /// `float64`.) br-frankenpandas-qkqfb; unblocks br-frankenpandas-f0aaa.
17031    #[test]
17032    fn int64nullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
17033        assert_eq!(
17034            common_dtype(DType::Int64Nullable, DType::Float64),
17035            Ok(DType::Float64Nullable)
17036        );
17037        assert_eq!(
17038            common_dtype(DType::Float64, DType::Int64Nullable),
17039            Ok(DType::Float64Nullable)
17040        );
17041    }
17042
17043    /// The BoolNullable sibling, MEASURED on the same pandas:
17044    /// ```text
17045    ///   pd.Series([True,None],dtype="boolean") + pd.Series([1.5,2.5,3.5])
17046    ///       -> Float64   (extension)
17047    /// ```
17048    /// The numpy-bool lane is NOT affected and stays on numpy float64, which is
17049    /// the control that keeps this from being a blanket "nullable everywhere".
17050    #[test]
17051    fn boolnullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
17052        assert_eq!(
17053            common_dtype(DType::BoolNullable, DType::Float64),
17054            Ok(DType::Float64Nullable)
17055        );
17056        assert_eq!(
17057            common_dtype(DType::Bool, DType::Float64),
17058            Ok(DType::Float64),
17059            "numpy bool + numpy float stays entirely on the numpy side"
17060        );
17061    }
17062
17063    /// ⚠ WHY THOSE TWO ARMS CANNOT MOVE INDEPENDENTLY. This is the exact triple
17064    /// that fails if only the Int64Nullable arm is flipped, spelled out so the
17065    /// coupling survives someone later "simplifying" one arm back:
17066    /// ```text
17067    ///   (BoolNullable ∨ Int64) ∨ Float64 = Int64Nullable ∨ Float64 = Float64Nullable
17068    ///   BoolNullable ∨ (Int64 ∨ Float64) = BoolNullable  ∨ Float64 = ???
17069    /// ```
17070    /// `common_dtype_lattice_axioms_be314` sweeps this for all 14 dtypes; this
17071    /// test names the single witness so a failure is diagnosable without
17072    /// re-deriving it from a 14³ sweep. (br-frankenpandas-qkqfb)
17073    #[test]
17074    fn the_nullable_float_flip_is_associative_on_its_witness_triple_qkqfb() {
17075        let (bn, i64n, f64d) = (DType::BoolNullable, DType::Int64, DType::Float64);
17076
17077        let left = common_dtype(
17078            common_dtype(bn.clone(), i64n.clone()).unwrap(),
17079            f64d.clone(),
17080        )
17081        .unwrap();
17082        let right = common_dtype(bn, common_dtype(i64n, f64d).unwrap()).unwrap();
17083
17084        assert_eq!(left, right, "promotion order must not change the result");
17085        assert_eq!(left, DType::Float64Nullable);
17086    }
17087}
17088
17089/// br-frankenpandas-3gxc6: the Sparse dtype NAME is parameterized in pandas.
17090///
17091/// Every expectation below was read off live pandas 2.2.3 before the code was
17092/// written, via `str(dtype)` / `dtype.name` on a `pd.SparseDtype`.
17093#[cfg(test)]
17094mod sparse_dtype_pandas_name_3gxc6 {
17095    use super::{DType, Scalar, SparseDType};
17096
17097    fn name(value_dtype: DType, fill: Scalar) -> String {
17098        SparseDType::new(value_dtype, fill)
17099            .expect("sparse descriptor")
17100            .pandas_name()
17101    }
17102
17103    /// The row the corpus fixture `fp_p2d_017_series_dtype_sparse_strict`
17104    /// exercises. FrankenPandas used to answer the bare `"Sparse"`.
17105    #[test]
17106    fn int64_fill_zero_is_the_fixture_row() {
17107        assert_eq!(name(DType::Int64, Scalar::Int64(0)), "Sparse[int64, 0]");
17108    }
17109
17110    /// A non-default fill must appear, or the name would be a constant wearing
17111    /// a parameterized shape.
17112    #[test]
17113    fn the_fill_value_is_actually_rendered() {
17114        assert_eq!(name(DType::Int64, Scalar::Int64(7)), "Sparse[int64, 7]");
17115        assert_ne!(
17116            name(DType::Int64, Scalar::Int64(0)),
17117            name(DType::Int64, Scalar::Int64(7)),
17118            "two different fills must not collapse to one name"
17119        );
17120    }
17121
17122    /// pandas spells this `nan`, lowercase, not `NaN` and not `None`.
17123    #[test]
17124    fn float64_nan_fill_is_lowercase_nan() {
17125        assert_eq!(
17126            name(DType::Float64, Scalar::Float64(f64::NAN)),
17127            "Sparse[float64, nan]"
17128        );
17129    }
17130
17131    /// pandas keeps the trailing `.0` here. A `{}`-style float format would
17132    /// render `0` and silently make this name collide with the int64 one.
17133    #[test]
17134    fn float64_zero_fill_keeps_its_trailing_point_zero() {
17135        assert_eq!(
17136            name(DType::Float64, Scalar::Float64(0.0)),
17137            "Sparse[float64, 0.0]"
17138        );
17139        assert_ne!(
17140            name(DType::Float64, Scalar::Float64(0.0)),
17141            name(DType::Int64, Scalar::Int64(0)),
17142            "float64 and int64 zero fills are different dtypes"
17143        );
17144    }
17145
17146    /// Python capitalisation, not Rust's `false`.
17147    #[test]
17148    fn bool_fill_uses_python_capitalisation() {
17149        assert_eq!(
17150            name(DType::Bool, Scalar::Bool(false)),
17151            "Sparse[bool, False]"
17152        );
17153        assert_eq!(name(DType::Bool, Scalar::Bool(true)), "Sparse[bool, True]");
17154    }
17155
17156    /// FP spells its object dtype `object`, which is what pandas prints for a
17157    /// `SparseDtype(object, nan)`.
17158    #[test]
17159    fn utf8_subtype_renders_as_object() {
17160        let rendered = name(DType::Utf8, Scalar::Null(crate::NullKind::NaN));
17161        assert!(
17162            rendered.starts_with("Sparse[object, "),
17163            "expected an object subtype, got {rendered}"
17164        );
17165    }
17166
17167    /// The bare name is what this bead removed; guard against a regression
17168    /// that reintroduces it for any constructible descriptor.
17169    #[test]
17170    fn no_constructible_descriptor_renders_the_bare_name() {
17171        for (dtype, fill) in [
17172            (DType::Int64, Scalar::Int64(0)),
17173            (DType::Float64, Scalar::Float64(1.5)),
17174            (DType::Bool, Scalar::Bool(true)),
17175            (DType::Utf8, Scalar::Utf8("x".to_owned())),
17176        ] {
17177            let rendered = name(dtype.clone(), fill);
17178            assert_ne!(rendered, "Sparse", "bare name regressed for {dtype:?}");
17179            assert!(
17180                rendered.starts_with("Sparse[") && rendered.ends_with(']'),
17181                "malformed sparse name {rendered}"
17182            );
17183        }
17184    }
17185}