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
460impl std::str::FromStr for DType {
461    type Err = TypeError;
462
463    fn from_str(s: &str) -> Result<Self, Self::Err> {
464        let trimmed = s.trim();
465        match trimmed {
466            "int64" | "int" | "i8" | "integer" | "<i8" => Ok(Self::Int64),
467            "Int64" | "Int64Dtype" => Ok(Self::Int64Nullable),
468            "float64" | "float" | "f8" | "floating" | "<f8" => Ok(Self::Float64),
469            "Float64" | "Float64Dtype" => Ok(Self::Float64Nullable),
470            "bool" | "|b1" => Ok(Self::Bool),
471            "boolean" | "BooleanDtype" => Ok(Self::BoolNullable),
472            "string" | "str" | "object" | "utf8" | "Utf8" | "O" | "|O8" => Ok(Self::Utf8),
473            "category" | "categorical" | "CategoricalDtype" => Ok(Self::Categorical),
474            "timedelta64" | "timedelta64[ns]" | "timedelta" | "Timedelta" | "<m8[ns]" => {
475                Ok(Self::Timedelta64)
476            }
477            "period" | "Period" => Ok(Self::Period),
478            "interval" | "Interval" => Ok(Self::Interval),
479            "sparse" | "Sparse" => Ok(Self::Sparse),
480            "null" | "Null" => Ok(Self::Null),
481            _ if trimmed.starts_with("period[") || trimmed.starts_with("Period[") => {
482                Ok(Self::Period)
483            }
484            _ if trimmed.starts_with("interval[") || trimmed.starts_with("Interval[") => {
485                Ok(Self::Interval)
486            }
487            _ if trimmed.starts_with("sparse[") || trimmed.starts_with("Sparse[") => {
488                Ok(Self::Sparse)
489            }
490            _ if trimmed.starts_with("datetime64")
491                || trimmed.starts_with("datetime")
492                || trimmed.starts_with("<M8") =>
493            {
494                if let Some(idx) = trimmed.find(',') {
495                    let tz_part = if let Some(rest) = trimmed.get(idx + 1..) {
496                        rest.trim().trim_end_matches(']').trim().to_string()
497                    } else {
498                        String::new()
499                    };
500                    Ok(Self::Datetime64 { tz: Some(tz_part) })
501                } else {
502                    Ok(Self::Datetime64 { tz: None })
503                }
504            }
505            _ => Err(TypeError::ValueNotParseable {
506                value: s.to_string(),
507                target: "DType".to_string(),
508            }),
509        }
510    }
511}
512
513impl std::fmt::Display for DType {
514    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
515        write!(f, "{}", self.display_name())
516    }
517}
518
519/// A numpy numeric dtype narrower than the 64-bit storage a column keeps its
520/// values in: pandas' int8 / int16 / int32, uint8 / uint16 / uint32 / uint64
521/// and float32, and over a nullable column the masked Int8 ... UInt64 /
522/// Float32 (fvsao.23).
523///
524/// The values stay in the Int64 / Float64 storage (or its nullable form);
525/// the width is the dtype pandas reports and confines the values: an integer
526/// width holds only values in its range (a cast or arithmetic wraps into it,
527/// as numpy does: `astype('int8')` of 300 is 44), float32 only values exactly
528/// representable as an `f32` (every result is rounded to the nearest `f32`,
529/// which for `+ - * /` and `sqrt` is what float32 arithmetic gives: binary64
530/// carries more than 2 * 24 + 2 significand bits, so rounding twice cannot
531/// land elsewhere).
532///
533/// uint64 holds only values below 2**63 in that storage: a larger one would
534/// be its negative two's-complement pattern, which every path that does not
535/// know the width reads as the negative number, so it is refused instead.
536#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
537pub enum NumericWidth {
538    #[serde(rename = "int8")]
539    Int8,
540    #[serde(rename = "int16")]
541    Int16,
542    #[serde(rename = "int32")]
543    Int32,
544    #[serde(rename = "uint8")]
545    UInt8,
546    #[serde(rename = "uint16")]
547    UInt16,
548    #[serde(rename = "uint32")]
549    UInt32,
550    #[serde(rename = "uint64")]
551    UInt64,
552    #[serde(rename = "float32")]
553    Float32,
554}
555
556impl NumericWidth {
557    /// Every width, integers first.
558    pub const ALL: [Self; 8] = [
559        Self::Int8,
560        Self::Int16,
561        Self::Int32,
562        Self::UInt8,
563        Self::UInt16,
564        Self::UInt32,
565        Self::UInt64,
566        Self::Float32,
567    ];
568
569    /// pandas' dtype name: numpy's (`int32`) over a numpy column, the masked
570    /// extension dtype's (`Int32`, `UInt8`, `Float32`) over a nullable one.
571    #[must_use]
572    pub const fn name(self, nullable: bool) -> &'static str {
573        match (self, nullable) {
574            (Self::Int8, false) => "int8",
575            (Self::Int16, false) => "int16",
576            (Self::Int32, false) => "int32",
577            (Self::UInt8, false) => "uint8",
578            (Self::UInt16, false) => "uint16",
579            (Self::UInt32, false) => "uint32",
580            (Self::UInt64, false) => "uint64",
581            (Self::Float32, false) => "float32",
582            (Self::Int8, true) => "Int8",
583            (Self::Int16, true) => "Int16",
584            (Self::Int32, true) => "Int32",
585            (Self::UInt8, true) => "UInt8",
586            (Self::UInt16, true) => "UInt16",
587            (Self::UInt32, true) => "UInt32",
588            (Self::UInt64, true) => "UInt64",
589            (Self::Float32, true) => "Float32",
590        }
591    }
592
593    /// The width and whether it is the masked (nullable) dtype, for a pandas
594    /// or numpy dtype name: `int32` / `i4` / `<i4`, `Int32` / `Int32Dtype`,
595    /// `float32` / `f4` / `single`, ... `None` for any other name, the 64-bit
596    /// ones included (those are [`DType`]'s).
597    #[must_use]
598    pub fn parse(name: &str) -> Option<(Self, bool)> {
599        let name = name.trim();
600        let name = name
601            .strip_prefix('<')
602            .or_else(|| name.strip_prefix('|'))
603            .or_else(|| name.strip_prefix('='))
604            .unwrap_or(name);
605        let found = match name {
606            "int8" | "i1" | "byte" => (Self::Int8, false),
607            "int16" | "i2" | "short" => (Self::Int16, false),
608            "int32" | "i4" | "intc" => (Self::Int32, false),
609            "uint8" | "u1" | "ubyte" => (Self::UInt8, false),
610            "uint16" | "u2" | "ushort" => (Self::UInt16, false),
611            "uint32" | "u4" | "uintc" => (Self::UInt32, false),
612            "uint64" | "u8" | "uint" | "ulonglong" | "uintp" => (Self::UInt64, false),
613            "float32" | "f4" | "single" => (Self::Float32, false),
614            "Int8" | "Int8Dtype" => (Self::Int8, true),
615            "Int16" | "Int16Dtype" => (Self::Int16, true),
616            "Int32" | "Int32Dtype" => (Self::Int32, true),
617            "UInt8" | "UInt8Dtype" => (Self::UInt8, true),
618            "UInt16" | "UInt16Dtype" => (Self::UInt16, true),
619            "UInt32" | "UInt32Dtype" => (Self::UInt32, true),
620            "UInt64" | "UInt64Dtype" => (Self::UInt64, true),
621            "Float32" | "Float32Dtype" => (Self::Float32, true),
622            _ => return None,
623        };
624        Some(found)
625    }
626
627    /// The storage dtype a column of this width keeps its values in.
628    #[must_use]
629    pub const fn storage(self, nullable: bool) -> DType {
630        match (self.is_float(), nullable) {
631            (true, false) => DType::Float64,
632            (true, true) => DType::Float64Nullable,
633            (false, false) => DType::Int64,
634            (false, true) => DType::Int64Nullable,
635        }
636    }
637
638    /// Whether a column of `dtype` can carry this width: an integer width
639    /// over Int64 / Int64Nullable, float32 over Float64 / Float64Nullable.
640    #[must_use]
641    pub const fn fits_storage(self, dtype: &DType) -> bool {
642        if self.is_float() {
643            matches!(dtype, DType::Float64 | DType::Float64Nullable)
644        } else {
645            matches!(dtype, DType::Int64 | DType::Int64Nullable)
646        }
647    }
648
649    /// numpy's `itemsize`: bytes per element.
650    #[must_use]
651    pub const fn itemsize(self) -> usize {
652        match self {
653            Self::Int8 | Self::UInt8 => 1,
654            Self::Int16 | Self::UInt16 => 2,
655            Self::Int32 | Self::UInt32 | Self::Float32 => 4,
656            Self::UInt64 => 8,
657        }
658    }
659
660    /// numpy's `kind`: `'i'`, `'u'` or `'f'`.
661    #[must_use]
662    pub const fn kind(self) -> char {
663        match self {
664            Self::Int8 | Self::Int16 | Self::Int32 => 'i',
665            Self::UInt8 | Self::UInt16 | Self::UInt32 | Self::UInt64 => 'u',
666            Self::Float32 => 'f',
667        }
668    }
669
670    #[must_use]
671    pub const fn is_float(self) -> bool {
672        matches!(self, Self::Float32)
673    }
674
675    #[must_use]
676    pub const fn is_unsigned(self) -> bool {
677        matches!(
678            self,
679            Self::UInt8 | Self::UInt16 | Self::UInt32 | Self::UInt64
680        )
681    }
682
683    /// The smallest and largest value an integer width holds in the Int64
684    /// storage (uint64's largest is `i64::MAX`, see the type's doc); `None`
685    /// for float32.
686    #[must_use]
687    pub const fn int_bounds(self) -> Option<(i64, i64)> {
688        match self {
689            Self::Int8 => Some((i8::MIN as i64, i8::MAX as i64)),
690            Self::Int16 => Some((i16::MIN as i64, i16::MAX as i64)),
691            Self::Int32 => Some((i32::MIN as i64, i32::MAX as i64)),
692            Self::UInt8 => Some((0, u8::MAX as i64)),
693            Self::UInt16 => Some((0, u16::MAX as i64)),
694            Self::UInt32 => Some((0, u32::MAX as i64)),
695            Self::UInt64 => Some((0, i64::MAX)),
696            Self::Float32 => None,
697        }
698    }
699
700    /// Whether an integer width holds `value` unchanged.
701    #[must_use]
702    pub const fn holds_int(self, value: i64) -> bool {
703        match self.int_bounds() {
704            Some((low, high)) => low <= value && value <= high,
705            None => false,
706        }
707    }
708
709    /// `value` wrapped into an integer width as numpy's casts and integer
710    /// arithmetic wrap it (modulo 2**bits, two's complement): int8 of 300 is
711    /// 44, uint8 of -5 is 251. Any wrapping i64 result reduces to the right
712    /// one, since 2**bits divides 2**64. `None` for float32, and for a uint64
713    /// result at or above 2**63 (not held; see the type's doc).
714    #[must_use]
715    pub const fn wrap_int(self, value: i64) -> Option<i64> {
716        match self {
717            Self::Int8 => Some(value as i8 as i64),
718            Self::Int16 => Some(value as i16 as i64),
719            Self::Int32 => Some(value as i32 as i64),
720            Self::UInt8 => Some(value as u8 as i64),
721            Self::UInt16 => Some(value as u16 as i64),
722            Self::UInt32 => Some(value as u32 as i64),
723            Self::UInt64 if value >= 0 => Some(value),
724            Self::UInt64 | Self::Float32 => None,
725        }
726    }
727
728    /// `value` rounded to the nearest `f32` (ties to even), as a float32
729    /// column holds it: 0.1 is 0.10000000149011612. NaN and infinities stay;
730    /// a finite value beyond `f32::MAX` becomes an infinity, as numpy's cast.
731    #[must_use]
732    #[allow(clippy::cast_possible_truncation)]
733    pub fn round_f32(value: f64) -> f64 {
734        f64::from(value as f32)
735    }
736
737    /// The smallest signed integer width holding every value in
738    /// `low..=high`, or `None` when only int64 does (`to_numeric(...,
739    /// downcast='integer')`).
740    #[must_use]
741    pub const fn smallest_signed(low: i64, high: i64) -> Option<Self> {
742        if low >= i8::MIN as i64 && high <= i8::MAX as i64 {
743            Some(Self::Int8)
744        } else if low >= i16::MIN as i64 && high <= i16::MAX as i64 {
745            Some(Self::Int16)
746        } else if low >= i32::MIN as i64 && high <= i32::MAX as i64 {
747            Some(Self::Int32)
748        } else {
749            None
750        }
751    }
752
753    /// The smallest unsigned integer width holding every value in
754    /// `low..=high`, or `None` when a value is negative
755    /// (`downcast='unsigned'`).
756    #[must_use]
757    pub const fn smallest_unsigned(low: i64, high: i64) -> Option<Self> {
758        if low < 0 {
759            None
760        } else if high <= u8::MAX as i64 {
761            Some(Self::UInt8)
762        } else if high <= u16::MAX as i64 {
763            Some(Self::UInt16)
764        } else if high <= u32::MAX as i64 {
765            Some(Self::UInt32)
766        } else {
767            Some(Self::UInt64)
768        }
769    }
770
771    /// pandas' dtype for the codes of a categorical with `categories`
772    /// categories: the smallest signed width whose maximum exceeds the
773    /// count (codes run -1 .. count - 1; `coerce_indexer_dtype`), so 126
774    /// categories are int8 and 127 are int16. `None` means int64.
775    #[must_use]
776    pub const fn for_category_codes(categories: usize) -> Option<Self> {
777        if categories < i8::MAX as usize {
778            Some(Self::Int8)
779        } else if categories < i16::MAX as usize {
780            Some(Self::Int16)
781        } else if categories < i32::MAX as usize {
782            Some(Self::Int32)
783        } else {
784            None
785        }
786    }
787}
788
789/// numpy's `pairwise_sum`, the kernel of its float `add.reduce` over a
790/// contiguous run, every addition in `T`: below 8 values a running sum from
791/// 0; up to 128, eight running sums seeded with the first eight values and
792/// stepped over the 8-value blocks, folded as
793/// `((r0 + r1) + (r2 + r3)) + ((r4 + r5) + (r6 + r7))`, then the remainder in
794/// order; beyond that the two halves (the first a multiple of 8 long) summed
795/// apart. pandas' float32 and float64 sums are it bit for bit, where a sum
796/// rounded once or added left to right differs in the last place (fvsao.23,
797/// br-frankenpandas-9iim6).
798#[must_use]
799pub fn numpy_pairwise_sum<T>(values: &[T]) -> T
800where
801    T: Copy + Default + std::ops::Add<Output = T>,
802{
803    // The same split as `pairwise_range`, over the slice itself (no copy).
804    if values.len() <= PAIRWISE_BLOCK {
805        return pairwise_block(values);
806    }
807    let mut half = values.len() / 2;
808    half -= half % 8;
809    numpy_pairwise_sum(&values[..half]) + numpy_pairwise_sum(&values[half..])
810}
811
812/// numpy's `PW_BLOCKSIZE`: runs this long or shorter are summed directly.
813const PAIRWISE_BLOCK: usize = 128;
814
815/// [`numpy_pairwise_sum`] over `len` values that numpy reads from one array
816/// but fp holds in another shape (a cast, chunks, missing slots as 0):
817/// `fill(start, block)` writes values `start..start + block.len()` into each
818/// block, at most 128 long, the blocks asked for left to right.
819pub fn numpy_pairwise_sum_by<T, F>(len: usize, fill: &F) -> T
820where
821    T: Copy + Default + std::ops::Add<Output = T>,
822    F: Fn(usize, &mut [T]),
823{
824    pairwise_range(0, len, fill)
825}
826
827/// Values `start..start + len` of [`numpy_pairwise_sum_by`].
828fn pairwise_range<T, F>(start: usize, len: usize, fill: &F) -> T
829where
830    T: Copy + Default + std::ops::Add<Output = T>,
831    F: Fn(usize, &mut [T]),
832{
833    if len <= PAIRWISE_BLOCK {
834        let mut buffer = [T::default(); PAIRWISE_BLOCK];
835        let block = &mut buffer[..len];
836        fill(start, block);
837        return pairwise_block(block);
838    }
839    let mut half = len / 2;
840    half -= half % 8;
841    pairwise_range(start, half, fill) + pairwise_range(start + half, len - half, fill)
842}
843
844/// [`numpy_pairwise_sum`] of `term(value)` over `values`, each term made
845/// where it is added.
846fn numpy_pairwise_sum_of<T, F>(values: &[f64], term: &F) -> T
847where
848    T: Copy + Default + std::ops::Add<Output = T>,
849    F: Fn(f64) -> T,
850{
851    if values.len() > PAIRWISE_BLOCK {
852        let mut half = values.len() / 2;
853        half -= half % 8;
854        return numpy_pairwise_sum_of(&values[..half], term)
855            + numpy_pairwise_sum_of(&values[half..], term);
856    }
857    let n = values.len();
858    if n < 8 {
859        return values
860            .iter()
861            .fold(T::default(), |acc, &value| acc + term(value));
862    }
863    let mut sums: [T; 8] = std::array::from_fn(|lane| term(values[lane]));
864    let whole = n - n % 8;
865    for block in values[8..whole].as_chunks::<8>().0 {
866        for (sum, &value) in sums.iter_mut().zip(block) {
867            *sum = *sum + term(value);
868        }
869    }
870    let folded =
871        ((sums[0] + sums[1]) + (sums[2] + sums[3])) + ((sums[4] + sums[5]) + (sums[6] + sums[7]));
872    values[whole..]
873        .iter()
874        .fold(folded, |acc, &value| acc + term(value))
875}
876
877/// numpy's pairwise sum of at most 128 contiguous values.
878fn pairwise_block<T>(values: &[T]) -> T
879where
880    T: Copy + Default + std::ops::Add<Output = T>,
881{
882    let n = values.len();
883    if n < 8 {
884        return values.iter().fold(T::default(), |acc, &value| acc + value);
885    }
886    let mut sums = [T::default(); 8];
887    sums.copy_from_slice(&values[..8]);
888    let whole = n - n % 8;
889    for block in values[8..whole].as_chunks::<8>().0 {
890        for (sum, &value) in sums.iter_mut().zip(block) {
891            *sum = *sum + value;
892        }
893    }
894    let folded =
895        ((sums[0] + sums[1]) + (sums[2] + sums[3])) + ((sums[4] + sums[5]) + (sums[6] + sums[7]));
896    values[whole..]
897        .iter()
898        .fold(folded, |acc, &value| acc + value)
899}
900
901/// A numeric column's values as pandas' float reductions read them: one
902/// buffer or the chunks of one (a `concat` result), float64 or a numpy int64
903/// array (read through numpy's int64 -> float64 cast; ints that pandas holds
904/// as float64 because one is missing are `Float`).
905#[derive(Debug, Clone, Copy)]
906pub enum ReductionValues<'a> {
907    Float(&'a [f64]),
908    Int(&'a [i64]),
909    FloatChunks(&'a [&'a [f64]]),
910    IntChunks(&'a [&'a [i64]]),
911}
912
913impl ReductionValues<'_> {
914    fn len(self) -> usize {
915        match self {
916            Self::Float(values) => values.len(),
917            Self::Int(values) => values.len(),
918            Self::FloatChunks(chunks) => chunks.iter().map(|chunk| chunk.len()).sum(),
919            Self::IntChunks(chunks) => chunks.iter().map(|chunk| chunk.len()).sum(),
920        }
921    }
922}
923
924/// Reads [`ReductionValues`] block by block, left to right (a chunked
925/// column's cursor only moves forward).
926struct ValueReader<'a> {
927    values: ReductionValues<'a>,
928    /// The chunk the last block started in and that chunk's first position.
929    cursor: std::cell::Cell<(usize, usize)>,
930}
931
932impl<'a> ValueReader<'a> {
933    fn new(values: ReductionValues<'a>) -> Self {
934        Self {
935            values,
936            cursor: std::cell::Cell::new((0, 0)),
937        }
938    }
939
940    /// Values `start..start + block.len()` as float64.
941    #[allow(clippy::cast_precision_loss)] // numpy's int64 -> float64 cast
942    fn read(&self, start: usize, block: &mut [f64]) {
943        match self.values {
944            ReductionValues::Float(values) => {
945                block.copy_from_slice(&values[start..start + block.len()]);
946            }
947            ReductionValues::Int(values) => {
948                for (slot, &value) in block.iter_mut().zip(&values[start..]) {
949                    *slot = value as f64;
950                }
951            }
952            ReductionValues::FloatChunks(chunks) => {
953                self.read_chunks(chunks, start, block, |slots, values| {
954                    slots.copy_from_slice(values);
955                });
956            }
957            ReductionValues::IntChunks(chunks) => {
958                self.read_chunks(chunks, start, block, |slots, values| {
959                    for (slot, &value) in slots.iter_mut().zip(values) {
960                        *slot = value as f64;
961                    }
962                });
963            }
964        }
965    }
966
967    fn read_chunks<T>(
968        &self,
969        chunks: &[&[T]],
970        start: usize,
971        block: &mut [f64],
972        copy: impl Fn(&mut [f64], &[T]),
973    ) {
974        let (mut chunk, mut chunk_start) = self.cursor.get();
975        if start < chunk_start {
976            (chunk, chunk_start) = (0, 0);
977        }
978        while start >= chunk_start + chunks[chunk].len() {
979            chunk_start += chunks[chunk].len();
980            chunk += 1;
981        }
982        self.cursor.set((chunk, chunk_start));
983        let mut filled = 0;
984        while filled < block.len() {
985            let offset = start + filled - chunk_start;
986            let take = (chunks[chunk].len() - offset).min(block.len() - filled);
987            copy(
988                &mut block[filled..filled + take],
989                &chunks[chunk][offset..offset + take],
990            );
991            filled += take;
992            if filled < block.len() {
993                chunk_start += chunks[chunk].len();
994                chunk += 1;
995            }
996        }
997    }
998}
999
1000/// How pandas holds a column's missing values, which decides the order its
1001/// float reductions add in (br-frankenpandas-9iim6).
1002#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1003pub enum MissingLayout {
1004    /// A numpy float64 / int64 array: pandas' nanops fill the missing (NaN,
1005    /// NaT) slots with 0 in place and sum the whole array, every pairwise
1006    /// block keeping its position.
1007    Numpy,
1008    /// A masked (nullable `Float64` / `Int64`) array: numpy adds each run of
1009    /// present values onto a running total (`add.reduce(where=)`).
1010    Masked,
1011}
1012
1013/// numpy's buffer for a casting reduction: an int64 array summed as float64
1014/// is cast, and summed, 8192 values at a time.
1015const NUMPY_CAST_BUFFER: usize = 8192;
1016
1017/// pandas' float reductions of one numeric column - `sum`, `mean`, `var`,
1018/// `std`, `sem`, `skew`, `kurt` - adding in numpy's exact order, so a long
1019/// column answers pandas' bits rather than a nearby value. Measured against
1020/// live pandas 2.2.3 / numpy 2.3.5; bead br-frankenpandas-9iim6 holds the
1021/// model and the alternatives it rejected.
1022#[derive(Debug, Clone, Copy)]
1023pub struct PandasReductions<'a> {
1024    values: ReductionValues<'a>,
1025    /// Packed presence bits, bit `i % 64` of word `i / 64` for slot `i`;
1026    /// `None` when every slot is present.
1027    present: Option<&'a [u64]>,
1028    /// The float values' NaNs are the missing slots (and some value is one).
1029    nan_missing: bool,
1030    layout: MissingLayout,
1031    len: usize,
1032    count: usize,
1033    /// The float total, when the count's sweep already added it.
1034    total: Option<f64>,
1035}
1036
1037impl<'a> PandasReductions<'a> {
1038    /// A numpy float64 array, its NaNs the missing values (nanops' mask is
1039    /// `isnan`); read without a presence bitmap.
1040    #[must_use]
1041    pub fn numpy_nan_missing(values: ReductionValues<'a>) -> Self {
1042        let len = values.len();
1043        let mut reductions = Self {
1044            values,
1045            present: None,
1046            nan_missing: true,
1047            layout: MissingLayout::Numpy,
1048            len,
1049            count: len,
1050            total: None,
1051        };
1052        if let ReductionValues::Float(_) | ReductionValues::FloatChunks(_) = values {
1053            // One sweep counts the values and adds them, NaN as 0 in place.
1054            let SumPair(total, count) = reductions.add_reduce(|value| SumPair(value, 1), false);
1055            reductions.count = count;
1056            reductions.total = Some(total);
1057        }
1058        reductions.nan_missing = reductions.count < len;
1059        reductions
1060    }
1061
1062    /// `present` is the packed presence bits (`None`: all present).
1063    #[must_use]
1064    pub fn new(
1065        values: ReductionValues<'a>,
1066        present: Option<&'a [u64]>,
1067        layout: MissingLayout,
1068    ) -> Self {
1069        let len = values.len();
1070        let count = present.map_or(len, |words| {
1071            let whole: usize = words[..len / 64]
1072                .iter()
1073                .map(|word| word.count_ones() as usize)
1074                .sum();
1075            let tail = len % 64;
1076            whole
1077                + if tail == 0 {
1078                    0
1079                } else {
1080                    (words[len / 64] & ((1_u64 << tail) - 1)).count_ones() as usize
1081                }
1082        });
1083        Self {
1084            values,
1085            present: present.filter(|_| count < len),
1086            nan_missing: false,
1087            layout,
1088            len,
1089            count,
1090            total: None,
1091        }
1092    }
1093
1094    /// The present values.
1095    #[must_use]
1096    pub fn count(&self) -> usize {
1097        self.count
1098    }
1099
1100    /// The first slot in `from..end` whose presence is `present`, else `end`.
1101    fn next_slot(&self, from: usize, end: usize, present: bool) -> usize {
1102        let Some(words) = self.present else {
1103            return if present { from } else { end };
1104        };
1105        let mut i = from;
1106        while i < end {
1107            let word = if present {
1108                words[i / 64]
1109            } else {
1110                !words[i / 64]
1111            };
1112            let ahead = word >> (i % 64);
1113            if ahead != 0 {
1114                return (i + ahead.trailing_zeros() as usize).min(end);
1115            }
1116            i += 64 - i % 64;
1117        }
1118        end
1119    }
1120
1121    /// numpy's `add.reduce` of `term(value)` over the present values, in this
1122    /// layout's order; `cast_buffered` adds 8192 values at a time onto the
1123    /// total, as numpy sums an int64 array as float64. A `T` of several sums
1124    /// adds each in that same order.
1125    fn add_reduce<T>(&self, term: impl Fn(f64) -> T, cast_buffered: bool) -> T
1126    where
1127        T: Copy + Default + std::ops::Add<Output = T>,
1128    {
1129        let reader = ValueReader::new(self.values);
1130        // The values of `first..first + block.len()`, each through `term`.
1131        let read_terms = |first: usize, block: &mut [T]| {
1132            let mut values = [0.0_f64; PAIRWISE_BLOCK];
1133            let values = &mut values[..block.len()];
1134            reader.read(first, values);
1135            let terms = block.iter_mut().zip(values.iter());
1136            if self.nan_missing {
1137                // The NaN slots are 0, in place.
1138                for (slot, &value) in terms {
1139                    *slot = if value.is_nan() {
1140                        T::default()
1141                    } else {
1142                        term(value)
1143                    };
1144                }
1145            } else {
1146                for (slot, &value) in terms {
1147                    *slot = term(value);
1148                }
1149            }
1150        };
1151        let buffer = if cast_buffered {
1152            NUMPY_CAST_BUFFER
1153        } else {
1154            self.len.max(1)
1155        };
1156        let mut total = T::default();
1157        let mut chunk_start = 0;
1158        while chunk_start < self.len {
1159            let chunk_end = (chunk_start + buffer).min(self.len);
1160            match self.layout {
1161                MissingLayout::Numpy => {
1162                    if let (ReductionValues::Float(values), None) = (self.values, self.present) {
1163                        let values = &values[chunk_start..chunk_end];
1164                        let part = if self.nan_missing {
1165                            // The NaN slots are 0, in place.
1166                            let term = |value: f64| {
1167                                if value.is_nan() {
1168                                    T::default()
1169                                } else {
1170                                    term(value)
1171                                }
1172                            };
1173                            numpy_pairwise_sum_of(values, &term)
1174                        } else {
1175                            numpy_pairwise_sum_of(values, &term)
1176                        };
1177                        total = total + part;
1178                        chunk_start = chunk_end;
1179                        continue;
1180                    }
1181                    let fill = |start: usize, block: &mut [T]| {
1182                        let first = chunk_start + start;
1183                        read_terms(first, block);
1184                        // The missing slots are 0, in place.
1185                        let end = first + block.len();
1186                        let mut slot = self.next_slot(first, end, false);
1187                        while slot < end {
1188                            let run_end = self.next_slot(slot, end, true);
1189                            block[slot - first..run_end - first].fill(T::default());
1190                            slot = self.next_slot(run_end, end, false);
1191                        }
1192                    };
1193                    total = total + numpy_pairwise_sum_by(chunk_end - chunk_start, &fill);
1194                }
1195                MissingLayout::Masked => {
1196                    let mut run_start = self.next_slot(chunk_start, chunk_end, true);
1197                    while run_start < chunk_end {
1198                        let run_end = self.next_slot(run_start, chunk_end, false);
1199                        let fill = |start: usize, block: &mut [T]| {
1200                            read_terms(run_start + start, block);
1201                        };
1202                        total = total + numpy_pairwise_sum_by(run_end - run_start, &fill);
1203                        run_start = self.next_slot(run_end, chunk_end, true);
1204                    }
1205                }
1206            }
1207            chunk_start = chunk_end;
1208        }
1209        total
1210    }
1211
1212    /// The values' total as [`Self::add_reduce`] adds them, a present float
1213    /// buffer summed in place.
1214    fn total(&self, cast_buffered: bool) -> f64 {
1215        if let Some(total) = self.total {
1216            return total;
1217        }
1218        if let (ReductionValues::Float(values), None, false) =
1219            (self.values, self.present, self.nan_missing)
1220        {
1221            return 0.0 + numpy_pairwise_sum(values);
1222        }
1223        self.add_reduce(|value| value, cast_buffered)
1224    }
1225
1226    /// The total `mean` divides: an int64 array's through numpy's cast
1227    /// buffer (a datetime64's NaT slots are 0 in it).
1228    fn mean_total(&self) -> f64 {
1229        let int = matches!(
1230            self.values,
1231            ReductionValues::Int(_) | ReductionValues::IntChunks(_)
1232        );
1233        self.total(int)
1234    }
1235
1236    /// `Series.sum()` of a float column, missing values skipped.
1237    #[must_use]
1238    pub fn sum(&self) -> f64 {
1239        self.total(false)
1240    }
1241
1242    /// `Series.mean()`; NaN with no present value.
1243    #[must_use]
1244    #[allow(clippy::cast_precision_loss)] // pandas' float count
1245    pub fn mean(&self) -> f64 {
1246        if self.count == 0 {
1247            return f64::NAN;
1248        }
1249        self.mean_total() / self.count as f64
1250    }
1251
1252    /// `Series.var(ddof=ddof)`; NaN with `ddof` or fewer present values.
1253    #[must_use]
1254    #[allow(clippy::cast_precision_loss)] // pandas' float count
1255    pub fn var(&self, ddof: usize) -> f64 {
1256        if self.count <= ddof {
1257            return f64::NAN;
1258        }
1259        // nanops casts an int64 array to float64 whole before its mean; the
1260        // masked var sums int64 values through the cast buffer.
1261        let total = if self.layout == MissingLayout::Masked {
1262            self.mean_total()
1263        } else {
1264            self.total(false)
1265        };
1266        let mean = total / self.count as f64;
1267        let squares = self.add_reduce(
1268            |value| {
1269                let deviation = mean - value;
1270                deviation * deviation
1271            },
1272            false,
1273        );
1274        squares / (self.count - ddof) as f64
1275    }
1276
1277    /// `Series.std(ddof=ddof)`.
1278    #[must_use]
1279    pub fn std(&self, ddof: usize) -> f64 {
1280        self.var(ddof).sqrt()
1281    }
1282
1283    /// This column as nanops reads it: pandas' `sem`, `skew` and `kurt` read
1284    /// even a masked column with its missing slots filled with 0.
1285    fn as_numpy(&self) -> Self {
1286        Self {
1287            layout: MissingLayout::Numpy,
1288            ..*self
1289        }
1290    }
1291
1292    /// `Series.sem(ddof=ddof)`: `sqrt(var) / sqrt(count)`.
1293    #[must_use]
1294    #[allow(clippy::cast_precision_loss)] // pandas' float count
1295    pub fn sem(&self, ddof: usize) -> f64 {
1296        self.as_numpy().var(ddof).sqrt() / (self.count as f64).sqrt()
1297    }
1298
1299    /// The central sums `(m2, m3 or m4)` of nanskew / nankurt.
1300    #[allow(clippy::cast_precision_loss)] // pandas' float count
1301    fn central_moments(&self, fourth: bool) -> (f64, f64) {
1302        let numpy = self.as_numpy();
1303        let mean = numpy.total(false) / self.count as f64;
1304        // Both sums in one sweep: each adds in numpy's order on its own.
1305        let SumPair(m2, higher) = numpy.add_reduce(
1306            |value| {
1307                let deviation = value - mean;
1308                let square = deviation * deviation;
1309                let higher = if fourth {
1310                    square * square
1311                } else {
1312                    square * deviation
1313                };
1314                SumPair(square, higher)
1315            },
1316            false,
1317        );
1318        (m2, higher)
1319    }
1320
1321    /// `Series.skew()`: pandas' nanskew; NaN below 3 values, 0 for constant
1322    /// data.
1323    #[must_use]
1324    #[allow(clippy::cast_precision_loss)] // pandas' float count
1325    pub fn skew(&self) -> f64 {
1326        if self.count < 3 {
1327            return f64::NAN;
1328        }
1329        let (m2, m3) = self.central_moments(false);
1330        let (m2, m3) = (zero_out_fperr(m2), zero_out_fperr(m3));
1331        if m2 == 0.0 {
1332            return 0.0;
1333        }
1334        let count = self.count as f64;
1335        // pandas raises with libm pow (n = 2922 tells it from sqrt); a
1336        // literal 0.5 exponent would let LLVM substitute sqrt.
1337        let half = std::hint::black_box(0.5);
1338        (count * (count - 1.0).powf(half) / (count - 2.0)) * (m3 / m2.powf(1.5))
1339    }
1340
1341    /// `Series.kurt()`: pandas' nankurt; NaN below 4 values, 0 when the
1342    /// denominator vanishes (constant data).
1343    #[must_use]
1344    #[allow(clippy::cast_precision_loss)] // pandas' float count
1345    pub fn kurt(&self) -> f64 {
1346        if self.count < 4 {
1347            return f64::NAN;
1348        }
1349        let (m2, m4) = self.central_moments(true);
1350        let count = self.count as f64;
1351        let numerator = zero_out_fperr(count * (count + 1.0) * (count - 1.0) * m4);
1352        let denominator = zero_out_fperr((count - 2.0) * (count - 3.0) * (m2 * m2));
1353        if denominator == 0.0 {
1354            return 0.0;
1355        }
1356        let adjustment = 3.0 * ((count - 1.0) * (count - 1.0)) / ((count - 2.0) * (count - 3.0));
1357        numerator / denominator - adjustment
1358    }
1359}
1360
1361/// Two sums carried side by side (two float sums, or a float sum and a
1362/// count), added lane by lane.
1363#[derive(Debug, Clone, Copy, Default)]
1364struct SumPair<A, B = A>(A, B);
1365
1366impl<A: std::ops::Add<Output = A>, B: std::ops::Add<Output = B>> std::ops::Add for SumPair<A, B> {
1367    type Output = Self;
1368
1369    fn add(self, other: Self) -> Self {
1370        Self(self.0 + other.0, self.1 + other.1)
1371    }
1372}
1373
1374/// A float key's bits spread for an FxHash table: the high half folded
1375/// into the low (bijective, so equal bits stay equal and distinct stay
1376/// distinct). An integer-valued float's bits end in up to 52 zeros, which
1377/// FxHash's multiply keeps where the table takes its bucket from: 100 round
1378/// keys shared about two buckets, and drop_duplicates / duplicated / groupby
1379/// of round floats ran 4-6x slower than of fractional ones. The splitmix64
1380/// finalizer spread them too but cost fractional keys a sixth
1381/// (br-frankenpandas-mixf64, br-frankenpandas-bss5q.3).
1382#[must_use]
1383pub const fn spread_float_bits(bits: u64) -> u64 {
1384    bits ^ (bits >> 32)
1385}
1386
1387/// pandas' `_zero_out_fperr`: a moment below 1e-14 in magnitude is 0.
1388fn zero_out_fperr(value: f64) -> f64 {
1389    if value.abs() < 1e-14 { 0.0 } else { value }
1390}
1391
1392/// What pandas' default text-to-float64 conversion - `read_csv` /
1393/// `read_table` with `float_precision=None` or `'high'`, and `to_numeric` of
1394/// strings - makes of a token (br-frankenpandas-py3c0).
1395#[derive(Debug, Clone, Copy, PartialEq)]
1396pub enum PandasDecimal {
1397    /// A decimal number, converted as pandas converts it.
1398    Value(f64),
1399    /// A token that starts as a number but that pandas does not read as a
1400    /// float: trailing text, an exponent without digits or with more than 17,
1401    /// a value past float64's range.
1402    Rejected,
1403    /// No digits before an exponent: not a decimal (the `inf` / `nan`
1404    /// spellings, `.`, `-`); the caller's own rules apply.
1405    NotDecimal,
1406}
1407
1408/// Significant digits pandas' converter keeps, leading zeros included;
1409/// also the most exponent digits it reads.
1410const PANDAS_DECIMAL_DIGITS: usize = 17;
1411
1412/// The significand as pandas accumulates it, `x * 10 + d` in float64. While
1413/// the digits stay within 2^53 every step is exact, so they add as an
1414/// integer.
1415#[derive(Default)]
1416struct PandasSignificand {
1417    exact: u64,
1418    float: f64,
1419    rounding: bool,
1420    digits: usize,
1421}
1422
1423impl PandasSignificand {
1424    fn push(&mut self, digit: u8) {
1425        self.digits += 1;
1426        if !self.rounding {
1427            let next = self.exact * 10 + u64::from(digit);
1428            if next <= 1 << 53 {
1429                self.exact = next;
1430                return;
1431            }
1432            self.rounding = true;
1433            #[allow(clippy::cast_precision_loss)] // at most 2^53: exact
1434            let exact = self.exact as f64;
1435            self.float = exact;
1436        }
1437        self.float = self.float * 10.0 + f64::from(digit);
1438    }
1439
1440    #[allow(clippy::cast_precision_loss)] // at most 2^53: exact
1441    fn value(&self) -> f64 {
1442        if self.rounding {
1443            self.float
1444        } else {
1445            self.exact as f64
1446        }
1447    }
1448}
1449
1450/// pandas' scaling table: the float64 nearest each `1e0 ..= 1e308`.
1451static PANDAS_POW10: std::sync::LazyLock<[f64; 309]> = std::sync::LazyLock::new(|| {
1452    std::array::from_fn(|power| format!("1e{power}").parse().unwrap_or(f64::INFINITY))
1453});
1454
1455/// pandas' default text-to-float64 conversion of `token` (no surrounding
1456/// space). It is not correctly rounded: the first 17 digits - leading zeros
1457/// count - accumulate as `x * 10 + d` in float64 (digits past them in the
1458/// integer part raise the exponent, in the fraction they are dropped), the
1459/// exponent is a wrapping 32-bit integer of at most 17 digits, and the value
1460/// is scaled ONCE by a float64 power of ten: `x * 1e{e}` for `e` up to 308,
1461/// `x / 1e{-e}` down to -308, `x / 1e{-308-e} / 1e308` down to -616, `+0.0`
1462/// below that; past 308, or overflowing to infinity, the token is not a
1463/// float. The sign applies last. Measured against live pandas 2.2.3 over
1464/// 180k tokens (repr / `%.20e` / `%.25f` / 1-30 digit fractions / leading
1465/// zeros / exponents to +-640 / wrapping exponents), 0 mismatches;
1466/// `float()` misses about a third of them.
1467#[must_use]
1468pub fn pandas_decimal_to_f64(token: &[u8]) -> PandasDecimal {
1469    let (negative, body) = match token.first() {
1470        Some(b'-') => (true, &token[1..]),
1471        Some(b'+') => (false, &token[1..]),
1472        _ => (false, token),
1473    };
1474    let mut significand = PandasSignificand::default();
1475    let mut exponent = 0_i32;
1476    let mut pos = 0;
1477    while let Some(&byte @ b'0'..=b'9') = body.get(pos) {
1478        if significand.digits < PANDAS_DECIMAL_DIGITS {
1479            significand.push(byte - b'0');
1480        } else {
1481            exponent = exponent.wrapping_add(1);
1482        }
1483        pos += 1;
1484    }
1485    let mut seen_digit = pos > 0;
1486    if body.get(pos) == Some(&b'.') {
1487        pos += 1;
1488        while let Some(&byte @ b'0'..=b'9') = body.get(pos) {
1489            if significand.digits < PANDAS_DECIMAL_DIGITS {
1490                significand.push(byte - b'0');
1491                exponent = exponent.wrapping_sub(1);
1492            }
1493            seen_digit = true;
1494            pos += 1;
1495        }
1496    }
1497    if !seen_digit {
1498        return PandasDecimal::NotDecimal;
1499    }
1500    if let Some(b'e' | b'E') = body.get(pos) {
1501        pos += 1;
1502        let negative_exponent = match body.get(pos) {
1503            Some(b'-') => {
1504                pos += 1;
1505                true
1506            }
1507            Some(b'+') => {
1508                pos += 1;
1509                false
1510            }
1511            _ => false,
1512        };
1513        let start = pos;
1514        let mut written = 0_i32;
1515        while pos - start < PANDAS_DECIMAL_DIGITS
1516            && let Some(&byte @ b'0'..=b'9') = body.get(pos)
1517        {
1518            written = written
1519                .wrapping_mul(10)
1520                .wrapping_add(i32::from(byte - b'0'));
1521            pos += 1;
1522        }
1523        if pos == start {
1524            return PandasDecimal::Rejected;
1525        }
1526        exponent = exponent.wrapping_add(if negative_exponent {
1527            written.wrapping_neg()
1528        } else {
1529            written
1530        });
1531    }
1532    if pos != body.len() {
1533        return PandasDecimal::Rejected;
1534    }
1535    let value = significand.value();
1536    let pow10 = |power: i32| PANDAS_POW10[power.unsigned_abs() as usize];
1537    let magnitude = match exponent {
1538        309.. => return PandasDecimal::Rejected,
1539        0.. => value * pow10(exponent),
1540        -308.. => value / pow10(exponent),
1541        -616.. => value / pow10(-308 - exponent) / pow10(308),
1542        _ => return PandasDecimal::Value(0.0),
1543    };
1544    if magnitude.is_infinite() {
1545        return PandasDecimal::Rejected;
1546    }
1547    PandasDecimal::Value(if negative { -magnitude } else { magnitude })
1548}
1549
1550/// An integer cell of a column pandas reads as float64 (one of its cells is
1551/// fractional): the integer's digits through [`pandas_decimal_to_f64`],
1552/// exact up to 2^53.
1553#[must_use]
1554#[allow(clippy::cast_precision_loss)] // at most 2^53, or 19 digits: a value
1555pub fn pandas_int_to_f64(value: i64) -> f64 {
1556    if value.unsigned_abs() <= 1 << 53 {
1557        return value as f64;
1558    }
1559    match pandas_decimal_to_f64(value.to_string().as_bytes()) {
1560        PandasDecimal::Value(parsed) => parsed,
1561        // 19 digits at most: always a value.
1562        PandasDecimal::Rejected | PandasDecimal::NotDecimal => value as f64,
1563    }
1564}
1565
1566/// A numeric column's numpy dtype as numpy's promotion sees it: kind and
1567/// bits. The 64-bit ones are a column without a [`NumericWidth`].
1568#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1569pub enum NumpyNumeric {
1570    Bool,
1571    Int(u8),
1572    UInt(u8),
1573    Float(u8),
1574}
1575
1576impl NumpyNumeric {
1577    /// The numpy dtype of a column of `dtype` carrying `width`; `None` for a
1578    /// column that is not bool, integer or float (or a width its storage
1579    /// cannot carry).
1580    #[must_use]
1581    pub const fn of(dtype: &DType, width: Option<NumericWidth>) -> Option<Self> {
1582        match (dtype, width) {
1583            (DType::Bool | DType::BoolNullable, None) => Some(Self::Bool),
1584            (DType::Int64 | DType::Int64Nullable, None) => Some(Self::Int(64)),
1585            (DType::Float64 | DType::Float64Nullable, None) => Some(Self::Float(64)),
1586            (DType::Int64 | DType::Int64Nullable, Some(width)) if !width.is_float() => {
1587                Some(Self::of_width(width))
1588            }
1589            (DType::Float64 | DType::Float64Nullable, Some(NumericWidth::Float32)) => {
1590                Some(Self::Float(32))
1591            }
1592            _ => None,
1593        }
1594    }
1595
1596    #[must_use]
1597    pub const fn of_width(width: NumericWidth) -> Self {
1598        match width {
1599            NumericWidth::Int8 => Self::Int(8),
1600            NumericWidth::Int16 => Self::Int(16),
1601            NumericWidth::Int32 => Self::Int(32),
1602            NumericWidth::UInt8 => Self::UInt(8),
1603            NumericWidth::UInt16 => Self::UInt(16),
1604            NumericWidth::UInt32 => Self::UInt(32),
1605            NumericWidth::UInt64 => Self::UInt(64),
1606            NumericWidth::Float32 => Self::Float(32),
1607        }
1608    }
1609
1610    /// The width a column of this numpy dtype carries: `None` for bool,
1611    /// int64 and float64.
1612    #[must_use]
1613    pub const fn width(self) -> Option<NumericWidth> {
1614        match self {
1615            Self::Int(8) => Some(NumericWidth::Int8),
1616            Self::Int(16) => Some(NumericWidth::Int16),
1617            Self::Int(32) => Some(NumericWidth::Int32),
1618            Self::UInt(8) => Some(NumericWidth::UInt8),
1619            Self::UInt(16) => Some(NumericWidth::UInt16),
1620            Self::UInt(32) => Some(NumericWidth::UInt32),
1621            Self::UInt(64) => Some(NumericWidth::UInt64),
1622            Self::Float(32) => Some(NumericWidth::Float32),
1623            _ => None,
1624        }
1625    }
1626
1627    #[must_use]
1628    pub const fn is_float(self) -> bool {
1629        matches!(self, Self::Float(_))
1630    }
1631
1632    /// numpy's `result_type` of two arrays: the smallest dtype holding both
1633    /// (bool yields to anything; int8 + uint8 is int16, int64 + uint64
1634    /// float64; float32 holds integers of up to 16 bits, a wider integer
1635    /// makes it float64).
1636    #[must_use]
1637    pub const fn result_type(self, other: Self) -> Self {
1638        const fn wider(a: u8, b: u8) -> u8 {
1639            if a > b { a } else { b }
1640        }
1641        match (self, other) {
1642            (Self::Bool, x) | (x, Self::Bool) => x,
1643            (Self::Int(a), Self::Int(b)) => Self::Int(wider(a, b)),
1644            (Self::UInt(a), Self::UInt(b)) => Self::UInt(wider(a, b)),
1645            (Self::Int(signed), Self::UInt(unsigned))
1646            | (Self::UInt(unsigned), Self::Int(signed)) => {
1647                if signed > unsigned {
1648                    Self::Int(signed)
1649                } else if unsigned < 64 {
1650                    Self::Int(wider(signed, unsigned * 2))
1651                } else {
1652                    Self::Float(64)
1653                }
1654            }
1655            (Self::Float(a), Self::Float(b)) => Self::Float(wider(a, b)),
1656            (Self::Float(bits), Self::Int(int_bits) | Self::UInt(int_bits))
1657            | (Self::Int(int_bits) | Self::UInt(int_bits), Self::Float(bits)) => {
1658                if int_bits <= 16 {
1659                    Self::Float(bits)
1660                } else {
1661                    Self::Float(64)
1662                }
1663            }
1664        }
1665    }
1666
1667    /// The dtype of this array combined with a Python `int` (NEP 50: the
1668    /// Python scalar is weak, the array's dtype wins; bool becomes int64).
1669    /// Whether the int fits that dtype is the caller's check.
1670    #[must_use]
1671    pub const fn with_python_int(self) -> Self {
1672        match self {
1673            Self::Bool => Self::Int(64),
1674            other => other,
1675        }
1676    }
1677
1678    /// The dtype of this array combined with a Python `float`: a float
1679    /// array keeps its dtype (float32 + 0.2 is float32), anything else is
1680    /// float64.
1681    #[must_use]
1682    pub const fn with_python_float(self) -> Self {
1683        match self {
1684            Self::Float(bits) => Self::Float(bits),
1685            _ => Self::Float(64),
1686        }
1687    }
1688}
1689
1690/// Trait for types that carry or represent a [`DType`].
1691pub trait AsDType {
1692    /// Return the corresponding [`DType`].
1693    fn as_dtype(&self) -> DType;
1694}
1695
1696impl AsDType for DType {
1697    fn as_dtype(&self) -> DType {
1698        self.clone()
1699    }
1700}
1701
1702impl AsDType for &DType {
1703    fn as_dtype(&self) -> DType {
1704        (*self).clone()
1705    }
1706}
1707
1708impl AsDType for &str {
1709    fn as_dtype(&self) -> DType {
1710        self.parse::<DType>().unwrap_or(DType::Utf8)
1711    }
1712}
1713
1714impl AsDType for String {
1715    fn as_dtype(&self) -> DType {
1716        self.as_str().as_dtype()
1717    }
1718}
1719
1720pub mod api {
1721    //! Public pandas API modules (`pandas.api.*`).
1722
1723    pub mod types {
1724        //! Dtype inspection and conversion functions (`pandas.api.types`).
1725
1726        use crate::{AsDType, DType, Scalar, TypeError};
1727
1728        /// Matches `pd.api.types.is_bool_dtype`.
1729        #[must_use]
1730        pub fn is_bool_dtype(dtype: &impl AsDType) -> bool {
1731            dtype.as_dtype().is_bool()
1732        }
1733
1734        /// Matches `pd.api.types.is_numeric_dtype`.
1735        #[must_use]
1736        pub fn is_numeric_dtype(dtype: &impl AsDType) -> bool {
1737            dtype.as_dtype().is_numeric()
1738        }
1739
1740        /// Matches `pd.api.types.is_integer_dtype`.
1741        #[must_use]
1742        pub fn is_integer_dtype(dtype: &impl AsDType) -> bool {
1743            dtype.as_dtype().is_integer()
1744        }
1745
1746        /// Matches `pd.api.types.is_signed_integer_dtype`.
1747        #[must_use]
1748        pub fn is_signed_integer_dtype(dtype: &impl AsDType) -> bool {
1749            dtype.as_dtype().is_signed_integer()
1750        }
1751
1752        /// Matches `pd.api.types.is_unsigned_integer_dtype`.
1753        #[must_use]
1754        pub fn is_unsigned_integer_dtype(_dtype: &impl AsDType) -> bool {
1755            false
1756        }
1757
1758        /// Matches `pd.api.types.is_float_dtype`.
1759        #[must_use]
1760        pub fn is_float_dtype(dtype: &impl AsDType) -> bool {
1761            dtype.as_dtype().is_floating()
1762        }
1763
1764        /// Matches `pd.api.types.is_string_dtype`.
1765        #[must_use]
1766        pub fn is_string_dtype(dtype: &impl AsDType) -> bool {
1767            dtype.as_dtype().is_string_dtype()
1768        }
1769
1770        /// Matches `pd.api.types.is_datetime64_any_dtype`.
1771        #[must_use]
1772        pub fn is_datetime64_any_dtype(dtype: &impl AsDType) -> bool {
1773            dtype.as_dtype().is_datetime()
1774        }
1775
1776        /// Matches `pd.api.types.is_datetime64_dtype`.
1777        #[must_use]
1778        pub fn is_datetime64_dtype(dtype: &impl AsDType) -> bool {
1779            dtype.as_dtype().is_datetime()
1780        }
1781
1782        /// Matches `pd.api.types.is_datetime64_ns_dtype`.
1783        #[must_use]
1784        pub fn is_datetime64_ns_dtype(dtype: &impl AsDType) -> bool {
1785            dtype.as_dtype().is_datetime()
1786        }
1787
1788        /// Matches `pd.api.types.is_timedelta64_dtype`.
1789        #[must_use]
1790        pub fn is_timedelta64_dtype(dtype: &impl AsDType) -> bool {
1791            dtype.as_dtype().is_timedelta()
1792        }
1793
1794        /// Matches `pd.api.types.is_timedelta64_ns_dtype`.
1795        #[must_use]
1796        pub fn is_timedelta64_ns_dtype(dtype: &impl AsDType) -> bool {
1797            dtype.as_dtype().is_timedelta()
1798        }
1799
1800        /// Matches `pd.api.types.is_period_dtype`.
1801        #[must_use]
1802        pub fn is_period_dtype(dtype: &impl AsDType) -> bool {
1803            dtype.as_dtype().is_period()
1804        }
1805
1806        /// Matches `pd.api.types.is_categorical_dtype`.
1807        #[must_use]
1808        pub fn is_categorical_dtype(dtype: &impl AsDType) -> bool {
1809            dtype.as_dtype().is_categorical()
1810        }
1811
1812        /// Matches `pd.api.types.is_interval_dtype`.
1813        #[must_use]
1814        pub fn is_interval_dtype(dtype: &impl AsDType) -> bool {
1815            dtype.as_dtype().is_interval()
1816        }
1817
1818        /// Matches `pd.api.types.is_sparse`.
1819        #[must_use]
1820        pub fn is_sparse(dtype: &impl AsDType) -> bool {
1821            dtype.as_dtype().is_sparse()
1822        }
1823
1824        /// Matches `pd.api.types.is_extension_array_dtype`.
1825        #[must_use]
1826        pub fn is_extension_array_dtype(dtype: &impl AsDType) -> bool {
1827            dtype.as_dtype().is_extension()
1828        }
1829
1830        /// Matches `pd.api.types.is_object_dtype`.
1831        #[must_use]
1832        pub fn is_object_dtype(dtype: &impl AsDType) -> bool {
1833            dtype.as_dtype().is_object()
1834        }
1835
1836        /// Matches `pd.api.types.is_int64_dtype`.
1837        #[must_use]
1838        pub fn is_int64_dtype(dtype: &impl AsDType) -> bool {
1839            matches!(dtype.as_dtype(), DType::Int64 | DType::Int64Nullable)
1840        }
1841
1842        /// Matches `pd.api.types.is_dtype_equal`.
1843        #[must_use]
1844        pub fn is_dtype_equal(source: &impl AsDType, target: &impl AsDType) -> bool {
1845            source.as_dtype() == target.as_dtype()
1846        }
1847
1848        /// Matches `pd.api.types.is_scalar`.
1849        #[must_use]
1850        pub const fn is_scalar(_scalar: &Scalar) -> bool {
1851            true
1852        }
1853
1854        /// Convert a string specification into a pandas DType. Matches `pd.api.types.pandas_dtype`.
1855        ///
1856        /// # Errors
1857        ///
1858        /// Returns [`TypeError::ValueNotParseable`] if the string cannot be parsed as a valid dtype.
1859        pub fn pandas_dtype(name: &str) -> Result<DType, TypeError> {
1860            name.parse::<DType>()
1861        }
1862
1863        /// Infer the dtype kind of a slice of scalars. Matches `pd.api.types.infer_dtype`.
1864        #[must_use]
1865        pub fn infer_dtype(scalars: &[Scalar], skipna: bool) -> &'static str {
1866            if scalars.is_empty() {
1867                return "empty";
1868            }
1869            let mut has_int = false;
1870            let mut has_float = false;
1871            let mut has_bool = false;
1872            let mut has_str = false;
1873            let mut has_ts = false;
1874            let mut has_td = false;
1875            let mut has_period = false;
1876            let mut count = 0;
1877
1878            for s in scalars {
1879                if s.is_null() {
1880                    if !skipna {
1881                        return "mixed";
1882                    }
1883                    continue;
1884                }
1885                count += 1;
1886                match s {
1887                    Scalar::Bool(_) => has_bool = true,
1888                    Scalar::Int64(_) => has_int = true,
1889                    Scalar::Float64(_) => has_float = true,
1890                    Scalar::Utf8(_) => has_str = true,
1891                    Scalar::Datetime64(_) => has_ts = true,
1892                    Scalar::Timedelta64(_) => has_td = true,
1893                    Scalar::Period(_) => has_period = true,
1894                    _ => {}
1895                }
1896            }
1897
1898            if count == 0 {
1899                return "empty";
1900            }
1901            if has_bool && !has_int && !has_float && !has_str && !has_ts && !has_td && !has_period {
1902                return "boolean";
1903            }
1904            if has_int && !has_float && !has_bool && !has_str && !has_ts && !has_td && !has_period {
1905                return "integer";
1906            }
1907            if (has_float || (has_int && has_float))
1908                && !has_bool
1909                && !has_str
1910                && !has_ts
1911                && !has_td
1912                && !has_period
1913            {
1914                return "floating";
1915            }
1916            if has_str && !has_int && !has_float && !has_bool && !has_ts && !has_td && !has_period {
1917                return "string";
1918            }
1919            if has_ts && !has_int && !has_float && !has_bool && !has_str && !has_td && !has_period {
1920                return "datetime64";
1921            }
1922            if has_td && !has_int && !has_float && !has_bool && !has_str && !has_ts && !has_period {
1923                return "timedelta64";
1924            }
1925            if has_period && !has_int && !has_float && !has_bool && !has_str && !has_ts && !has_td {
1926                return "period";
1927            }
1928            "mixed"
1929        }
1930
1931        /// Convenience helper for 64-bit float types (`pd.api.types.is_float64_dtype` does NOT exist in pandas; see [`is_float_dtype`]).
1932        #[must_use]
1933        pub fn is_float64_dtype(dtype: &impl AsDType) -> bool {
1934            matches!(dtype.as_dtype(), DType::Float64 | DType::Float64Nullable)
1935        }
1936
1937        /// Convenience helper for 32-bit integer types (`pd.api.types.is_int32_dtype` does NOT exist in pandas; see [`is_integer_dtype`]).
1938        #[must_use]
1939        pub fn is_int32_dtype(_dtype: &impl AsDType) -> bool {
1940            false
1941        }
1942
1943        /// Matches `pd.api.types.is_number`.
1944        #[must_use]
1945        pub fn is_number(scalar: &Scalar) -> bool {
1946            scalar.is_numeric() || matches!(scalar, Scalar::Bool(_))
1947        }
1948
1949        /// Matches `pd.api.types.is_bool`.
1950        #[must_use]
1951        pub fn is_bool(scalar: &Scalar) -> bool {
1952            matches!(scalar, Scalar::Bool(_))
1953        }
1954
1955        /// Matches `pd.api.types.is_integer`.
1956        #[must_use]
1957        pub fn is_integer(scalar: &Scalar) -> bool {
1958            matches!(scalar, Scalar::Int64(_))
1959        }
1960
1961        /// Matches `pd.api.types.is_float`.
1962        #[must_use]
1963        pub fn is_float(scalar: &Scalar) -> bool {
1964            matches!(scalar, Scalar::Float64(_))
1965        }
1966    }
1967
1968    pub mod extensions {
1969        //! Extension arrays and accessor registration hooks (`pandas.api.extensions`).
1970
1971        /// Compatibility registration hook for DataFrame accessors matching `pd.api.extensions.register_dataframe_accessor`.
1972        pub fn register_dataframe_accessor(_name: &str) {}
1973
1974        /// Compatibility registration hook for Series accessors matching `pd.api.extensions.register_series_accessor`.
1975        pub fn register_series_accessor(_name: &str) {}
1976
1977        /// Compatibility registration hook for Index accessors matching `pd.api.extensions.register_index_accessor`.
1978        pub fn register_index_accessor(_name: &str) {}
1979    }
1980
1981    pub mod indexers {
1982        //! Custom window and rolling indexers (`pandas.api.indexers`).
1983
1984        /// Base specification for window indexers, matching `pd.api.indexers.BaseIndexer`.
1985        #[derive(Debug, Clone, PartialEq, Eq, Default)]
1986        pub struct BaseIndexer {
1987            pub window_size: usize,
1988            pub step: usize,
1989        }
1990
1991        impl BaseIndexer {
1992            #[must_use]
1993            pub const fn new(window_size: usize, step: usize) -> Self {
1994                Self { window_size, step }
1995            }
1996        }
1997
1998        /// Fixed forward-looking window indexer, matching `pd.api.indexers.FixedForwardWindowIndexer`.
1999        #[derive(Debug, Clone, PartialEq, Eq, Default)]
2000        pub struct FixedForwardWindowIndexer {
2001            pub window_size: usize,
2002        }
2003
2004        impl FixedForwardWindowIndexer {
2005            #[must_use]
2006            pub const fn new(window_size: usize) -> Self {
2007                Self { window_size }
2008            }
2009        }
2010
2011        /// Variable offset window indexer, matching `pd.api.indexers.VariableOffsetWindowIndexer`.
2012        #[derive(Debug, Clone, PartialEq, Eq, Default)]
2013        pub struct VariableOffsetWindowIndexer {
2014            pub index_offset: i64,
2015        }
2016
2017        impl VariableOffsetWindowIndexer {
2018            #[must_use]
2019            pub const fn new(index_offset: i64) -> Self {
2020                Self { index_offset }
2021            }
2022        }
2023    }
2024}
2025
2026pub use api::types::pandas_dtype;
2027
2028#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2029pub struct SparseDType {
2030    pub value_dtype: DType,
2031    pub fill_value: Scalar,
2032}
2033
2034impl SparseDType {
2035    /// Construct a pandas-style sparse dtype descriptor.
2036    ///
2037    /// This records the logical dense value dtype plus the scalar value that is
2038    /// elided from storage. The concrete sparse column representation lives in
2039    /// fp-columnar; this descriptor is the shared public contract.
2040    pub fn new(value_dtype: DType, fill_value: Scalar) -> Result<Self, TypeError> {
2041        if matches!(value_dtype, DType::Null | DType::Sparse) {
2042            return Err(TypeError::InvalidSparseValueDType { dtype: value_dtype });
2043        }
2044
2045        let fill_value = if fill_value.is_missing() {
2046            Scalar::missing_for_dtype(value_dtype.clone())
2047        } else {
2048            cast_scalar_owned(fill_value, value_dtype.clone())?
2049        };
2050
2051        Ok(Self {
2052            value_dtype,
2053            fill_value,
2054        })
2055    }
2056
2057    /// Render the pandas dtype name, `Sparse[<subtype>, <fill>]`.
2058    ///
2059    /// br-frankenpandas-3gxc6. [`DType::name`] can only answer `"Sparse"`: it
2060    /// is a `const fn` returning `&'static str` and `DType::Sparse` carries no
2061    /// payload, so the subtype and fill value — which live here — are lost by
2062    /// the time a caller has a bare [`DType`]. pandas never spells the bare
2063    /// form; even `pd.Series([1.5, 0.0]).astype("Sparse")` resolves to
2064    /// `Sparse[float64, nan]`.
2065    ///
2066    /// MEASURED, live pandas 2.2.3, `str(dtype)` / `dtype.name`:
2067    ///
2068    /// ```text
2069    ///   SparseDtype("int64",   0)     -> Sparse[int64, 0]
2070    ///   SparseDtype("int64",   7)     -> Sparse[int64, 7]
2071    ///   SparseDtype("float64", nan)   -> Sparse[float64, nan]
2072    ///   SparseDtype("float64", 0.0)   -> Sparse[float64, 0.0]
2073    ///   SparseDtype("bool",    False) -> Sparse[bool, False]
2074    ///   SparseDtype(object,    nan)   -> Sparse[object, nan]
2075    /// ```
2076    ///
2077    /// The fill is rendered by `scalar_to_string_for_astype`, which already
2078    /// spells every one of those cases the way pandas does in this position:
2079    /// `True`/`False` capitalised, integers bare, lowercase `nan`, and the
2080    /// trailing `.0` preserved on whole floats. Deliberately reusing it rather
2081    /// than writing a second float formatter — a divergence between the two
2082    /// would surface as a dtype name that no longer round-trips.
2083    #[must_use]
2084    pub fn pandas_name(&self) -> String {
2085        format!(
2086            "Sparse[{}, {}]",
2087            self.value_dtype.name(),
2088            scalar_to_string_for_astype(self.fill_value.clone())
2089        )
2090    }
2091}
2092
2093impl AsDType for SparseDType {
2094    fn as_dtype(&self) -> DType {
2095        DType::Sparse
2096    }
2097}
2098
2099/// Pandas-equivalent categorical dtype descriptor (`pd.CategoricalDtype`).
2100///
2101/// Encapsulates the optional category vocabulary and ordering semantics.
2102#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
2103pub struct CategoricalDtype {
2104    pub categories: Option<Vec<String>>,
2105    pub ordered: bool,
2106}
2107
2108pub type CategoricalDType = CategoricalDtype;
2109
2110impl CategoricalDtype {
2111    /// Construct a new `CategoricalDtype`.
2112    #[must_use]
2113    pub const fn new(categories: Option<Vec<String>>, ordered: bool) -> Self {
2114        Self {
2115            categories,
2116            ordered,
2117        }
2118    }
2119
2120    /// Return categories if known.
2121    #[must_use]
2122    pub fn categories(&self) -> Option<&[String]> {
2123        self.categories.as_deref()
2124    }
2125
2126    /// Return whether this categorical is ordered.
2127    #[must_use]
2128    pub const fn ordered(&self) -> bool {
2129        self.ordered
2130    }
2131
2132    /// Return the pandas dtype string name (`"category"`).
2133    #[must_use]
2134    pub const fn name(&self) -> &'static str {
2135        "category"
2136    }
2137
2138    /// Return the pandas kind character (`"O"`).
2139    #[must_use]
2140    pub const fn kind(&self) -> &'static str {
2141        "O"
2142    }
2143}
2144
2145impl AsDType for CategoricalDtype {
2146    fn as_dtype(&self) -> DType {
2147        DType::Categorical
2148    }
2149}
2150
2151impl std::fmt::Display for CategoricalDtype {
2152    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2153        let ord_str = if self.ordered { "True" } else { "False" };
2154        match &self.categories {
2155            Some(cats) => write!(
2156                f,
2157                "CategoricalDtype(categories={cats:?}, ordered={ord_str})"
2158            ),
2159            None => write!(f, "CategoricalDtype(categories=None, ordered={ord_str})"),
2160        }
2161    }
2162}
2163
2164/// Pandas-equivalent period dtype descriptor (`pd.PeriodDtype`).
2165///
2166/// Represents time period durations with a specific frequency (default `"D"`).
2167#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
2168pub struct PeriodDtype {
2169    pub freq: String,
2170}
2171
2172pub type PeriodDType = PeriodDtype;
2173
2174impl PeriodDtype {
2175    /// Construct a new `PeriodDtype` with given frequency.
2176    #[must_use]
2177    pub fn new(freq: impl Into<String>) -> Self {
2178        Self { freq: freq.into() }
2179    }
2180
2181    /// Return the period frequency string.
2182    #[must_use]
2183    pub fn freq(&self) -> &str {
2184        &self.freq
2185    }
2186
2187    /// Return the pandas dtype string name (`period[<freq>]`).
2188    #[must_use]
2189    pub fn name(&self) -> String {
2190        format!("period[{}]", self.freq)
2191    }
2192
2193    /// Return the pandas kind character (`"O"`).
2194    #[must_use]
2195    pub const fn kind(&self) -> &'static str {
2196        "O"
2197    }
2198}
2199
2200impl Default for PeriodDtype {
2201    fn default() -> Self {
2202        Self {
2203            freq: "D".to_string(),
2204        }
2205    }
2206}
2207
2208impl AsDType for PeriodDtype {
2209    fn as_dtype(&self) -> DType {
2210        DType::Period
2211    }
2212}
2213
2214impl std::fmt::Display for PeriodDtype {
2215    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2216        write!(f, "period[{}]", self.freq)
2217    }
2218}
2219
2220/// Pandas-equivalent interval dtype descriptor (`pd.IntervalDtype`).
2221///
2222/// Encapsulates the interval subtype and endpoint closure behavior.
2223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2224pub struct IntervalDtype {
2225    pub subtype: DType,
2226    pub closed: Option<IntervalClosed>,
2227}
2228
2229pub type IntervalDType = IntervalDtype;
2230
2231impl IntervalDtype {
2232    /// Construct a new `IntervalDtype`.
2233    #[must_use]
2234    pub const fn new(subtype: DType, closed: Option<IntervalClosed>) -> Self {
2235        Self { subtype, closed }
2236    }
2237
2238    /// Return the interval subtype.
2239    #[must_use]
2240    pub const fn subtype(&self) -> &DType {
2241        &self.subtype
2242    }
2243
2244    /// Return the endpoint closure convention.
2245    #[must_use]
2246    pub const fn closed(&self) -> Option<IntervalClosed> {
2247        self.closed
2248    }
2249
2250    /// Return the pandas dtype string name (`"interval"`).
2251    #[must_use]
2252    pub const fn name(&self) -> &'static str {
2253        "interval"
2254    }
2255
2256    /// Return the pandas kind character (`"O"`).
2257    #[must_use]
2258    pub const fn kind(&self) -> &'static str {
2259        "O"
2260    }
2261}
2262
2263impl Default for IntervalDtype {
2264    fn default() -> Self {
2265        Self {
2266            subtype: DType::Float64,
2267            closed: Some(IntervalClosed::Right),
2268        }
2269    }
2270}
2271
2272impl AsDType for IntervalDtype {
2273    fn as_dtype(&self) -> DType {
2274        DType::Interval
2275    }
2276}
2277
2278impl std::fmt::Display for IntervalDtype {
2279    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2280        match self.closed {
2281            Some(c) => write!(f, "interval[{}, {c}]", self.subtype.name()),
2282            None => write!(f, "interval[{}]", self.subtype.name()),
2283        }
2284    }
2285}
2286
2287#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
2288#[serde(rename_all = "snake_case")]
2289pub enum NullKind {
2290    Null,
2291    NaN,
2292    NaT,
2293}
2294
2295/// JSON spelling of a `Scalar::Float64` payload. JSON has no infinity:
2296/// serde_json writes a non-finite `f64` as `null` and cannot read that back,
2297/// so a division-by-zero answer could not travel through a fixture or the
2298/// oracle at all. ±inf is spelled `"inf"` / `"-inf"` (the pandas oracle emits
2299/// the same strings); finite values and NaN serialize exactly as before, and
2300/// the `null` serde_json writes for NaN now reads back as NaN.
2301/// (br-frankenpandas-rc0923-epic-rust-parity-bugs-4qg5w.3)
2302mod float64_json {
2303    use serde::{Deserialize, Deserializer, Serializer, de::Error as _};
2304
2305    pub fn serialize<S: Serializer>(value: &f64, serializer: S) -> Result<S::Ok, S::Error> {
2306        if value.is_infinite() {
2307            serializer.serialize_str(if value.is_sign_positive() {
2308                "inf"
2309            } else {
2310                "-inf"
2311            })
2312        } else {
2313            serializer.serialize_f64(*value)
2314        }
2315    }
2316
2317    #[derive(Deserialize)]
2318    #[serde(untagged)]
2319    enum Repr {
2320        Number(f64),
2321        Text(String),
2322        Null(()),
2323    }
2324
2325    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<f64, D::Error> {
2326        match Repr::deserialize(deserializer)? {
2327            Repr::Number(value) => Ok(value),
2328            Repr::Text(text) => match text.as_str() {
2329                "inf" => Ok(f64::INFINITY),
2330                "-inf" => Ok(f64::NEG_INFINITY),
2331                other => Err(D::Error::custom(format!(
2332                    "float64 value must be a number, \"inf\" or \"-inf\", got {other:?}"
2333                ))),
2334            },
2335            Repr::Null(()) => Ok(f64::NAN),
2336        }
2337    }
2338}
2339
2340#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2341#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
2342pub enum Scalar {
2343    Null(NullKind),
2344    Bool(bool),
2345    Int64(i64),
2346    Float64(#[serde(with = "float64_json")] f64),
2347    #[serde(alias = "string", alias = "str")]
2348    Utf8(String),
2349    Timedelta64(i64),
2350    /// Nanoseconds since Unix epoch. Matches pandas `datetime64[ns]`.
2351    /// Uses `Timestamp::NAT` (i64::MIN) for missing values.
2352    Datetime64(i64),
2353    /// Period value (ordinal + frequency). A `Period` whose `ordinal` is
2354    /// `i64::MIN` is NaT (missing). The frequency is carried so writers can
2355    /// render the pandas calendar string (`2024Q1`, `2024-03`, ...) — the
2356    /// calendar string is not recoverable from the ordinal alone, since
2357    /// different frequencies share overlapping ordinal axes.
2358    Period(Period),
2359    /// Numeric interval value. Missing values remain `Scalar::Null`.
2360    Interval(Interval),
2361    /// A pandas object cell none of the kinds above holds: a list
2362    /// (`str.split`'s cells, `Series([[1, 2], [3]])`) or a host-language
2363    /// value the core only carries (fvsao.33).
2364    Object(ObjectValue),
2365}
2366
2367/// A pandas object cell that is not one of [`Scalar`]'s value kinds: a list,
2368/// or a value of the host language (a Python `datetime.date`, dict, numpy
2369/// dtype) that the core carries without reading (fvsao.33).
2370#[derive(Clone)]
2371pub enum ObjectValue {
2372    /// A list of values, compared and printed as Python's list.
2373    List(std::sync::Arc<[Scalar]>),
2374    /// A bytes value, compared and printed as Python's bytes (`b'ab'`):
2375    /// `str.encode`'s cells. The core reads it, so a bytes column needs no
2376    /// host (4qg5w.8).
2377    Bytes(std::sync::Arc<[u8]>),
2378    /// A host-language value, opaque to the core.
2379    Host(HostValue),
2380}
2381
2382/// A host-language value an object cell carries - the Python binding's
2383/// objects: compared and printed by the host itself.
2384pub trait HostObject: Send + Sync {
2385    /// `self == other` in the host language.
2386    fn host_eq(&self, other: &dyn HostObject) -> bool;
2387    /// The host's `repr` (`datetime.date(2024, 1, 5)`).
2388    fn host_repr(&self) -> String;
2389    /// The host's `str` (`2024-01-05`), what `astype(str)` makes of it.
2390    fn host_str(&self) -> String;
2391    /// The cell as pandas displays it in a repr (`pprint_thing`), where that
2392    /// differs from its `str`: a tuple's or array's items unquoted (`(a, 1)`,
2393    /// `[1, 2]`); by default its `str`.
2394    fn host_pprint(&self) -> String {
2395        self.host_str()
2396    }
2397    /// The host's hash, None for an unhashable value (a dict).
2398    fn host_hash(&self) -> Option<u64>;
2399    /// `self` ordered against `other` in the host language (Python's `<` /
2400    /// `>` / `==`), None where the host cannot order them (a date against a
2401    /// time, two dicts).
2402    fn host_cmp(&self, other: &dyn HostObject) -> Option<std::cmp::Ordering>;
2403    /// `self == other` in the host language for a plain value (numpy's
2404    /// `dtype('float64') == 'float64'` is True); false unless the host says so.
2405    fn host_eq_scalar(&self, _other: &Scalar) -> bool {
2406        false
2407    }
2408    /// The value's type as the host's own errors name it (`datetime.date`,
2409    /// `dict`), for a refusal pandas lets the host raise.
2410    fn host_type_name(&self) -> String {
2411        "object".to_owned()
2412    }
2413    /// The value itself, for the host that made it to take back.
2414    fn as_any(&self) -> &dyn std::any::Any;
2415}
2416
2417/// How many host objects are alive (see [`host_values_block_workers`]).
2418static LIVE_HOST_VALUES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2419
2420/// Whether this process's callers may hold a host lock (see
2421/// [`declare_host_lock`]).
2422static HOST_LOCK_DECLARED: std::sync::atomic::AtomicBool =
2423    std::sync::atomic::AtomicBool::new(false);
2424
2425/// Declare that callers into the core may hold a host lock that host objects
2426/// need - the Python binding, whose every call holds the GIL, declares it
2427/// when its module loads. Without it no worker is ever blocked.
2428pub fn declare_host_lock() {
2429    HOST_LOCK_DECLARED.store(true, std::sync::atomic::Ordering::Relaxed);
2430}
2431
2432/// Whether a parallel kernel must run inline (one worker): a host value
2433/// compares, hashes and prints through its host (Python), which a worker
2434/// thread reaches only by taking the host's lock (the GIL); when the thread
2435/// that spawned the worker holds that lock while it waits for the worker,
2436/// both wait forever - `DataFrame.groupby(dates).rank()` hung that way
2437/// (4qg5w.13). So while any host object is alive in a process whose callers
2438/// may hold that lock, kernels size themselves to one worker.
2439#[must_use]
2440pub fn host_values_block_workers() -> bool {
2441    workers_blocked(
2442        HOST_LOCK_DECLARED.load(std::sync::atomic::Ordering::Relaxed),
2443        LIVE_HOST_VALUES.load(std::sync::atomic::Ordering::Relaxed),
2444    )
2445}
2446
2447/// The rule of [`host_values_block_workers`], free of process state.
2448const fn workers_blocked(host_lock_declared: bool, live_host_values: usize) -> bool {
2449    host_lock_declared && live_host_values > 0
2450}
2451
2452/// A host object, counted alive while any handle to it exists.
2453struct HostSlot(Box<dyn HostObject>);
2454
2455impl Drop for HostSlot {
2456    fn drop(&mut self) {
2457        LIVE_HOST_VALUES.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
2458    }
2459}
2460
2461/// A shared handle on a [`HostObject`].
2462#[derive(Clone)]
2463pub struct HostValue(std::sync::Arc<HostSlot>);
2464
2465impl HostValue {
2466    #[must_use]
2467    pub fn new(object: impl HostObject + 'static) -> Self {
2468        LIVE_HOST_VALUES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2469        Self(std::sync::Arc::new(HostSlot(Box::new(object))))
2470    }
2471
2472    #[must_use]
2473    pub fn object(&self) -> &dyn HostObject {
2474        &*self.0.0
2475    }
2476}
2477
2478impl PartialEq for HostValue {
2479    fn eq(&self, other: &Self) -> bool {
2480        std::sync::Arc::ptr_eq(&self.0, &other.0) || self.object().host_eq(other.object())
2481    }
2482}
2483
2484impl std::fmt::Debug for HostValue {
2485    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2486        formatter.write_str(&self.object().host_repr())
2487    }
2488}
2489
2490impl ObjectValue {
2491    /// A list cell of `items`.
2492    #[must_use]
2493    pub fn list(items: Vec<Scalar>) -> Self {
2494        Self::List(items.into())
2495    }
2496
2497    /// The items of a list cell.
2498    #[must_use]
2499    pub fn as_list(&self) -> Option<&[Scalar]> {
2500        match self {
2501            Self::List(items) => Some(items),
2502            Self::Bytes(_) | Self::Host(_) => None,
2503        }
2504    }
2505
2506    /// A bytes cell of `data`.
2507    #[must_use]
2508    pub fn bytes(data: Vec<u8>) -> Self {
2509        Self::Bytes(data.into())
2510    }
2511
2512    /// The bytes of a bytes cell.
2513    #[must_use]
2514    pub fn as_bytes(&self) -> Option<&[u8]> {
2515        match self {
2516            Self::Bytes(data) => Some(data),
2517            Self::List(_) | Self::Host(_) => None,
2518        }
2519    }
2520
2521    /// The cell as Python's `repr` spells it (`[1, 'a', None]`, `b'ab'`).
2522    #[must_use]
2523    pub fn repr(&self) -> String {
2524        match self {
2525            Self::List(items) => {
2526                let parts: Vec<String> = items.iter().map(Scalar::python_repr).collect();
2527                format!("[{}]", parts.join(", "))
2528            }
2529            Self::Bytes(data) => python_bytes_repr(data),
2530            Self::Host(value) => value.object().host_repr(),
2531        }
2532    }
2533
2534    /// The cell as pandas displays it in a repr (pandas' `pprint_thing`): a
2535    /// list's items unquoted (`[1, a]`), a host value as the host pprints it.
2536    #[must_use]
2537    pub fn pprint(&self) -> String {
2538        match self {
2539            Self::List(items) => {
2540                let parts: Vec<String> = items
2541                    .iter()
2542                    .map(|item| match item {
2543                        Scalar::Utf8(text) => text.clone(),
2544                        Scalar::Object(object) => object.pprint(),
2545                        other => other.python_repr(),
2546                    })
2547                    .collect();
2548                format!("[{}]", parts.join(", "))
2549            }
2550            Self::Bytes(data) => python_bytes_repr(data),
2551            Self::Host(value) => value.object().host_pprint(),
2552        }
2553    }
2554
2555    /// The cell's Python type as Python's errors name it (`list`, `bytes`,
2556    /// `datetime.date`).
2557    #[must_use]
2558    pub fn type_name(&self) -> String {
2559        match self {
2560            Self::List(_) => "list".to_owned(),
2561            Self::Bytes(_) => "bytes".to_owned(),
2562            Self::Host(value) => value.object().host_type_name(),
2563        }
2564    }
2565
2566    /// Python's `==` between this cell and a plain value: a host value asks
2567    /// the host (a dtype equals its name), a list or bytes never equals one
2568    /// (`b'a' == 'a'` is False).
2569    #[must_use]
2570    pub fn python_eq_scalar(&self, other: &Scalar) -> bool {
2571        match self {
2572            Self::Host(value) => value.object().host_eq_scalar(other),
2573            Self::List(_) | Self::Bytes(_) => false,
2574        }
2575    }
2576
2577    /// Python's ordering of two cells, None where Python raises: host values
2578    /// by the host, lists item by item (a shorter prefix first), bytes by
2579    /// byte, and cells of different kinds unordered.
2580    #[must_use]
2581    pub fn python_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2582        match (self, other) {
2583            (Self::Bytes(left), Self::Bytes(right)) => Some(left.cmp(right)),
2584            (Self::Host(left), Self::Host(right)) => {
2585                if left == right {
2586                    Some(std::cmp::Ordering::Equal)
2587                } else {
2588                    left.object().host_cmp(right.object())
2589                }
2590            }
2591            (Self::List(left), Self::List(right)) => {
2592                for (a, b) in left.iter().zip(right.iter()) {
2593                    if a != b {
2594                        let ordering = a.python_cmp(b)?;
2595                        if ordering.is_ne() {
2596                            return Some(ordering);
2597                        }
2598                    }
2599                }
2600                Some(left.len().cmp(&right.len()))
2601            }
2602            _ => None,
2603        }
2604    }
2605
2606    /// A total order over cells, for sorted labels and ordered maps: Python's
2607    /// ordering where it has one; otherwise a list before a host value, then
2608    /// the reprs, then identity - so two unequal cells are never Equal and
2609    /// equal cells always are.
2610    #[must_use]
2611    pub fn total_cmp(&self, other: &Self) -> std::cmp::Ordering {
2612        use std::cmp::Ordering;
2613        if self == other {
2614            return Ordering::Equal;
2615        }
2616        if let Some(ordering) = self.python_cmp(other).filter(|ordering| ordering.is_ne()) {
2617            return ordering;
2618        }
2619        let rank = |cell: &Self| match cell {
2620            Self::List(_) => 0_u8,
2621            Self::Bytes(_) => 1,
2622            Self::Host(_) => 2,
2623        };
2624        rank(self)
2625            .cmp(&rank(other))
2626            .then_with(|| self.repr().cmp(&other.repr()))
2627            .then_with(|| self.address().cmp(&other.address()))
2628    }
2629
2630    /// Where the cell's shared data lives: the last tie-break of
2631    /// [`Self::total_cmp`] between unequal cells that print alike.
2632    fn address(&self) -> usize {
2633        match self {
2634            Self::List(items) => items.as_ptr().addr(),
2635            Self::Bytes(data) => data.as_ptr().addr(),
2636            Self::Host(value) => std::sync::Arc::as_ptr(&value.0).cast::<()>().addr(),
2637        }
2638    }
2639}
2640
2641/// Python's `repr` of a bytes value: `b'...'` (double quotes when it holds a
2642/// `'` and no `"`), printable ASCII as itself, `\\`, `\t`, `\n`, `\r` and
2643/// the quote escaped, every other byte as `\xNN`.
2644#[must_use]
2645pub fn python_bytes_repr(data: &[u8]) -> String {
2646    let quote = if data.contains(&b'\'') && !data.contains(&b'"') {
2647        b'"'
2648    } else {
2649        b'\''
2650    };
2651    let mut out = String::with_capacity(data.len() + 3);
2652    out.push('b');
2653    out.push(char::from(quote));
2654    for &byte in data {
2655        match byte {
2656            b'\\' => out.push_str("\\\\"),
2657            b'\t' => out.push_str("\\t"),
2658            b'\n' => out.push_str("\\n"),
2659            b'\r' => out.push_str("\\r"),
2660            _ if byte == quote => {
2661                out.push('\\');
2662                out.push(char::from(byte));
2663            }
2664            0x20..=0x7e => out.push(char::from(byte)),
2665            _ => out.push_str(&format!("\\x{byte:02x}")),
2666        }
2667    }
2668    out.push(char::from(quote));
2669    out
2670}
2671
2672impl PartialOrd for ObjectValue {
2673    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2674        Some(self.cmp(other))
2675    }
2676}
2677
2678/// [`ObjectValue::total_cmp`], so a cell can be an ordered label.
2679impl Ord for ObjectValue {
2680    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2681        self.total_cmp(other)
2682    }
2683}
2684
2685impl PartialEq for ObjectValue {
2686    fn eq(&self, other: &Self) -> bool {
2687        match (self, other) {
2688            (Self::List(left), Self::List(right)) => left == right,
2689            (Self::Bytes(left), Self::Bytes(right)) => left == right,
2690            (Self::Host(left), Self::Host(right)) => left == right,
2691            _ => false,
2692        }
2693    }
2694}
2695
2696/// So a cell can key a hash map (groupby, unique, isin): lists by their
2697/// items' reprs, host values by the host's hash (their repr when the host
2698/// has none).
2699impl Eq for ObjectValue {}
2700
2701impl std::hash::Hash for ObjectValue {
2702    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2703        match self {
2704            Self::List(items) => {
2705                0_u8.hash(state);
2706                for item in items.iter() {
2707                    item.python_repr().hash(state);
2708                }
2709            }
2710            Self::Bytes(data) => {
2711                2_u8.hash(state);
2712                data.hash(state);
2713            }
2714            Self::Host(value) => {
2715                1_u8.hash(state);
2716                match value.object().host_hash() {
2717                    Some(hash) => hash.hash(state),
2718                    None => value.object().host_repr().hash(state),
2719                }
2720            }
2721        }
2722    }
2723}
2724
2725impl std::fmt::Debug for ObjectValue {
2726    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2727        formatter.write_str(&self.repr())
2728    }
2729}
2730
2731/// Python's `str` of the cell - what `astype(str)` and the writers produce:
2732/// a list or bytes as its repr (`['a', 1]`, `b'ab'`), a host value as its
2733/// str.
2734impl std::fmt::Display for ObjectValue {
2735    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2736        match self {
2737            Self::List(_) | Self::Bytes(_) => formatter.write_str(&self.repr()),
2738            Self::Host(value) => formatter.write_str(&value.object().host_str()),
2739        }
2740    }
2741}
2742
2743/// A list cell serializes as the sequence of its items, a bytes cell as
2744/// `{"bytes": [..]}`; a host value has no serialized form.
2745impl Serialize for ObjectValue {
2746    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2747        match self {
2748            Self::List(items) => items.as_ref().serialize(serializer),
2749            Self::Bytes(data) => SerializedObject::Bytes {
2750                bytes: data.to_vec(),
2751            }
2752            .serialize(serializer),
2753            Self::Host(_) => Err(serde::ser::Error::custom(
2754                "a host-language object cell cannot be serialized",
2755            )),
2756        }
2757    }
2758}
2759
2760/// The serialized forms of an object cell: a list's items, or a bytes
2761/// value's bytes.
2762#[derive(Serialize, Deserialize)]
2763#[serde(untagged)]
2764enum SerializedObject {
2765    List(Vec<Scalar>),
2766    Bytes { bytes: Vec<u8> },
2767}
2768
2769impl<'de> Deserialize<'de> for ObjectValue {
2770    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2771        Ok(match SerializedObject::deserialize(deserializer)? {
2772            SerializedObject::List(items) => Self::list(items),
2773            SerializedObject::Bytes { bytes } => Self::bytes(bytes),
2774        })
2775    }
2776}
2777
2778impl std::fmt::Display for Scalar {
2779    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2780        match self {
2781            Self::Null(NullKind::NaN) => write!(f, "NaN"),
2782            Self::Null(NullKind::NaT) => write!(f, "NaT"),
2783            Self::Null(NullKind::Null) => write!(f, "None"),
2784            Self::Bool(b) => write!(f, "{}", if *b { "True" } else { "False" }),
2785            Self::Int64(v) => write!(f, "{v}"),
2786            Self::Float64(v) => write!(f, "{v}"),
2787            Self::Utf8(s) => write!(f, "{s}"),
2788            Self::Timedelta64(nanos) => write!(f, "{}", Timedelta::format(*nanos)),
2789            Self::Datetime64(nanos) => {
2790                if *nanos == Timestamp::NAT {
2791                    write!(f, "NaT")
2792                } else {
2793                    write!(f, "Timestamp[{nanos}]")
2794                }
2795            }
2796            Self::Period(p) => {
2797                if p.ordinal == i64::MIN {
2798                    write!(f, "NaT")
2799                } else {
2800                    write!(f, "{}", p.calendar_string())
2801                }
2802            }
2803            Self::Interval(interval) => write!(f, "{interval}"),
2804            Self::Object(object) => write!(f, "{object}"),
2805        }
2806    }
2807}
2808
2809impl Scalar {
2810    /// Python's ordering of two values: numbers by value, text by code
2811    /// point, instants, durations and same-frequency periods by their
2812    /// payload, intervals by (left, right), object cells by
2813    /// [`ObjectValue::python_cmp`]; None where
2814    /// Python raises (a number against text, a list against a tuple, two
2815    /// dicts).
2816    #[must_use]
2817    pub fn python_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2818        let numeric =
2819            |value: &Self| matches!(value, Self::Bool(_) | Self::Int64(_) | Self::Float64(_));
2820        match (self, other) {
2821            (Self::Utf8(a), Self::Utf8(b)) => Some(a.cmp(b)),
2822            (Self::Datetime64(a), Self::Datetime64(b))
2823            | (Self::Timedelta64(a), Self::Timedelta64(b)) => Some(a.cmp(b)),
2824            (Self::Period(a), Self::Period(b)) if a.freq == b.freq => {
2825                Some(a.ordinal.cmp(&b.ordinal))
2826            }
2827            (Self::Interval(a), Self::Interval(b)) => Some(
2828                a.left
2829                    .partial_cmp(&b.left)?
2830                    .then(a.right.partial_cmp(&b.right)?),
2831            ),
2832            (Self::Object(a), Self::Object(b)) => a.python_cmp(b),
2833            _ if numeric(self) && numeric(other) => {
2834                self.to_f64().ok()?.partial_cmp(&other.to_f64().ok()?)
2835            }
2836            _ => None,
2837        }
2838    }
2839
2840    /// The two types Python's TypeError names when it cannot order `self`
2841    /// against `other` (see [`Self::python_cmp`]): two lists by the first
2842    /// unequal items they hold (`[1] < ['a']` names 'int' and 'str'), any
2843    /// other pair by their own types.
2844    #[must_use]
2845    pub fn python_cmp_type_names(&self, other: &Self) -> (String, String) {
2846        if let (Self::Object(ObjectValue::List(left)), Self::Object(ObjectValue::List(right))) =
2847            (self, other)
2848            && let Some((a, b)) = left.iter().zip(right.iter()).find(|(a, b)| a != b)
2849        {
2850            return a.python_cmp_type_names(b);
2851        }
2852        (self.python_type_name(), other.python_type_name())
2853    }
2854
2855    /// The value's Python type as Python's errors name it (`str`, `int`,
2856    /// `Timestamp`, `list`), for a TypeError pandas lets Python raise.
2857    #[must_use]
2858    pub fn python_type_name(&self) -> String {
2859        match self {
2860            Self::Null(NullKind::NaN) | Self::Float64(_) => "float",
2861            Self::Null(NullKind::NaT) => "NaTType",
2862            Self::Null(NullKind::Null) => "NoneType",
2863            Self::Bool(_) => "bool",
2864            Self::Int64(_) => "int",
2865            Self::Utf8(_) => "str",
2866            Self::Timedelta64(_) => "Timedelta",
2867            Self::Datetime64(_) => "Timestamp",
2868            Self::Period(_) => "Period",
2869            Self::Interval(_) => "Interval",
2870            Self::Object(object) => return object.type_name(),
2871        }
2872        .to_owned()
2873    }
2874
2875    /// The value as Python's `repr` spells it inside a container (`'a'`,
2876    /// `1`, `1.5`, `None`, `nan`, `[1, 2]`) - how a list cell prints its
2877    /// items.
2878    #[must_use]
2879    pub fn python_repr(&self) -> String {
2880        match self {
2881            Self::Null(NullKind::NaN) => "nan".to_owned(),
2882            Self::Null(NullKind::NaT) => "NaT".to_owned(),
2883            Self::Null(NullKind::Null) => "None".to_owned(),
2884            Self::Utf8(text) => {
2885                let quote = if text.contains('\'') && !text.contains('"') {
2886                    '"'
2887                } else {
2888                    '\''
2889                };
2890                let mut out = String::with_capacity(text.len() + 2);
2891                out.push(quote);
2892                for ch in text.chars() {
2893                    match ch {
2894                        '\\' => out.push_str("\\\\"),
2895                        '\n' => out.push_str("\\n"),
2896                        '\r' => out.push_str("\\r"),
2897                        '\t' => out.push_str("\\t"),
2898                        c if c == quote => {
2899                            out.push('\\');
2900                            out.push(c);
2901                        }
2902                        c => out.push(c),
2903                    }
2904                }
2905                out.push(quote);
2906                out
2907            }
2908            Self::Float64(value) => {
2909                if value.is_nan() {
2910                    "nan".to_owned()
2911                } else if value.is_infinite() {
2912                    if *value > 0.0 { "inf" } else { "-inf" }.to_owned()
2913                } else if value.fract() == 0.0 && value.abs() < 1e16 {
2914                    format!("{value:.1}")
2915                } else {
2916                    format!("{value}")
2917                }
2918            }
2919            Self::Object(object) => object.repr(),
2920            other => other.to_string(),
2921        }
2922    }
2923}
2924
2925/// Pandas `pd.NA` singleton representing missing data in nullable dtypes.
2926pub const NA: Scalar = Scalar::Null(NullKind::Null);
2927
2928/// Pandas `pd.NaT` singleton representing Not-a-Time in datetime/timedelta data.
2929pub const NAT: Scalar = Scalar::Null(NullKind::NaT);
2930
2931/// Alias for [`NAT`] matching pandas capitalization `pd.NaT`.
2932#[allow(non_upper_case_globals)]
2933pub const NaT: Scalar = NAT;
2934
2935// Ergonomic From impls (br-frankenpandas-esjjy / fd90.182). Mirrors
2936// IndexLabel's From<i64>/From<&str>/From<String> so users can write
2937//   let v: Vec<Scalar> = vec![1i64.into(), 2.0.into(), "three".into()];
2938// instead of the explicit Scalar::Int64(...)/Scalar::Float64(...) form.
2939//
2940// i64 maps to Int64 (more common than Timedelta64 in pandas-style code).
2941// Users wanting Timedelta64 should construct it explicitly with
2942// Scalar::Timedelta64(nanos) or via Timedelta::parse / to_timedelta.
2943
2944impl From<bool> for Scalar {
2945    fn from(value: bool) -> Self {
2946        Self::Bool(value)
2947    }
2948}
2949
2950impl From<i64> for Scalar {
2951    fn from(value: i64) -> Self {
2952        Self::Int64(value)
2953    }
2954}
2955
2956impl From<f64> for Scalar {
2957    fn from(value: f64) -> Self {
2958        Self::Float64(value)
2959    }
2960}
2961
2962impl From<&str> for Scalar {
2963    fn from(value: &str) -> Self {
2964        Self::Utf8(value.to_owned())
2965    }
2966}
2967
2968impl From<String> for Scalar {
2969    fn from(value: String) -> Self {
2970        Self::Utf8(value)
2971    }
2972}
2973
2974impl Scalar {
2975    #[inline]
2976    const fn debug_variant_name(&self) -> &'static str {
2977        match self {
2978            Self::Null(_) => "Null",
2979            Self::Bool(_) => "Bool",
2980            Self::Int64(_) => "Int64",
2981            Self::Float64(_) => "Float64",
2982            Self::Utf8(_) => "Utf8",
2983            Self::Timedelta64(_) => "Timedelta64",
2984            Self::Datetime64(_) => "Datetime64",
2985            Self::Period(_) => "Period",
2986            Self::Interval(_) => "Interval",
2987            Self::Object(_) => "Object",
2988        }
2989    }
2990
2991    #[must_use]
2992    pub fn dtype(&self) -> DType {
2993        match self {
2994            Self::Null(_) => DType::Null,
2995            Self::Bool(_) => DType::Bool,
2996            Self::Int64(_) => DType::Int64,
2997            Self::Float64(_) => DType::Float64,
2998            Self::Utf8(_) => DType::Utf8,
2999            Self::Timedelta64(_) => DType::Timedelta64,
3000            Self::Datetime64(_) => DType::datetime64_naive(),
3001            Self::Period(_) => DType::Period,
3002            Self::Interval(_) => DType::Interval,
3003            // pandas' object dtype, which this crate spells Utf8.
3004            Self::Object(_) => DType::Utf8,
3005        }
3006    }
3007
3008    #[must_use]
3009    pub fn is_missing(&self) -> bool {
3010        match self {
3011            Self::Null(_) => true,
3012            Self::Float64(v) => v.is_nan(),
3013            Self::Timedelta64(v) => *v == Timedelta::NAT,
3014            Self::Datetime64(v) => *v == Timestamp::NAT,
3015            Self::Period(p) => p.ordinal == i64::MIN,
3016            _ => false,
3017        }
3018    }
3019
3020    #[must_use]
3021    pub fn is_nan(&self) -> bool {
3022        matches!(self, Self::Null(NullKind::NaN)) || matches!(self, Self::Float64(v) if v.is_nan())
3023    }
3024
3025    /// Returns true if this is a Bool scalar.
3026    #[must_use]
3027    pub const fn is_bool(&self) -> bool {
3028        matches!(self, Self::Bool(_))
3029    }
3030
3031    /// Returns true if this is an Int64 scalar.
3032    #[must_use]
3033    pub const fn is_integer(&self) -> bool {
3034        matches!(self, Self::Int64(_))
3035    }
3036
3037    /// Returns true if this is a Float64 scalar.
3038    #[must_use]
3039    pub const fn is_float(&self) -> bool {
3040        matches!(self, Self::Float64(_))
3041    }
3042
3043    /// Returns true if this is a numeric scalar (Int64 or Float64).
3044    #[must_use]
3045    pub const fn is_numeric(&self) -> bool {
3046        matches!(self, Self::Int64(_) | Self::Float64(_))
3047    }
3048
3049    /// Returns true if this is a Utf8 (string) scalar.
3050    #[must_use]
3051    pub const fn is_string(&self) -> bool {
3052        matches!(self, Self::Utf8(_))
3053    }
3054
3055    /// Returns true if this is a Datetime64 scalar.
3056    #[must_use]
3057    pub const fn is_datetime(&self) -> bool {
3058        matches!(self, Self::Datetime64(_))
3059    }
3060
3061    /// Returns true if this is a Timedelta64 scalar.
3062    #[must_use]
3063    pub const fn is_timedelta(&self) -> bool {
3064        matches!(self, Self::Timedelta64(_))
3065    }
3066
3067    /// Returns true if this is a Period scalar.
3068    #[must_use]
3069    pub const fn is_period(&self) -> bool {
3070        matches!(self, Self::Period(_))
3071    }
3072
3073    /// Returns true if this is an Interval scalar.
3074    #[must_use]
3075    pub const fn is_interval(&self) -> bool {
3076        matches!(self, Self::Interval(_))
3077    }
3078
3079    /// Returns the wrapped i64 if this is an [`Scalar::Int64`] variant.
3080    #[must_use]
3081    pub const fn as_i64(&self) -> Option<i64> {
3082        match self {
3083            Self::Int64(v) => Some(*v),
3084            _ => None,
3085        }
3086    }
3087
3088    /// Alias for [`Scalar::as_i64`].
3089    #[must_use]
3090    pub const fn as_int(&self) -> Option<i64> {
3091        self.as_i64()
3092    }
3093
3094    /// Returns the wrapped f64 if this is a [`Scalar::Float64`] variant.
3095    #[must_use]
3096    pub const fn as_f64(&self) -> Option<f64> {
3097        match self {
3098            Self::Float64(v) => Some(*v),
3099            _ => None,
3100        }
3101    }
3102
3103    /// Alias for [`Scalar::as_f64`].
3104    #[must_use]
3105    pub const fn as_float(&self) -> Option<f64> {
3106        self.as_f64()
3107    }
3108
3109    /// Returns the wrapped bool if this is a [`Scalar::Bool`] variant.
3110    #[must_use]
3111    pub const fn as_bool(&self) -> Option<bool> {
3112        match self {
3113            Self::Bool(v) => Some(*v),
3114            _ => None,
3115        }
3116    }
3117
3118    /// Returns a string slice if this is a [`Scalar::Utf8`] variant.
3119    #[must_use]
3120    pub fn as_str(&self) -> Option<&str> {
3121        match self {
3122            Self::Utf8(s) => Some(s.as_str()),
3123            _ => None,
3124        }
3125    }
3126
3127    /// Returns the raw nanoseconds timestamp if this is a [`Scalar::Datetime64`] variant.
3128    #[must_use]
3129    pub const fn as_datetime_nanos(&self) -> Option<i64> {
3130        match self {
3131            Self::Datetime64(v) => Some(*v),
3132            _ => None,
3133        }
3134    }
3135
3136    /// Returns the raw nanoseconds duration if this is a [`Scalar::Timedelta64`] variant.
3137    #[must_use]
3138    pub const fn as_timedelta_nanos(&self) -> Option<i64> {
3139        match self {
3140            Self::Timedelta64(v) => Some(*v),
3141            _ => None,
3142        }
3143    }
3144
3145    /// Returns the period ordinal if this is a [`Scalar::Period`] variant.
3146    #[must_use]
3147    pub const fn as_period_ordinal(&self) -> Option<i64> {
3148        match self {
3149            Self::Period(p) => Some(p.ordinal),
3150            _ => None,
3151        }
3152    }
3153
3154    /// Returns the [`Interval`] if this is a [`Scalar::Interval`] variant.
3155    #[must_use]
3156    pub const fn as_interval(&self) -> Option<Interval> {
3157        match self {
3158            Self::Interval(i) => Some(*i),
3159            _ => None,
3160        }
3161    }
3162
3163    #[must_use]
3164    pub fn missing_for_dtype(dtype: DType) -> Self {
3165        match dtype {
3166            DType::Float64 => Self::Null(NullKind::NaN),
3167            // NOT NaN, and this is the whole reason the dtype exists. MEASURED,
3168            // live pandas 2.2.3: a Float64 lane stores pd.NA, and it coerces an
3169            // explicit NaN INPUT to pd.NA —
3170            //     pd.Series([float("nan")], dtype="Float64")[0]  ->  <NA>
3171            // whereas the numpy lane above keeps a real NaN. Giving this dtype
3172            // NullKind::NaN would make the two flavours indistinguishable, which
3173            // is exactly the gap br-frankenpandas-qkqfb was filed for.
3174            DType::Float64Nullable => Self::Null(NullKind::Null),
3175            DType::Timedelta64 => Self::Timedelta64(Timedelta::NAT),
3176            DType::Datetime64 { .. } => Self::Datetime64(Timestamp::NAT),
3177            DType::Period => Self::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
3178            DType::Null => Self::Null(NullKind::Null),
3179            DType::Bool
3180            | DType::BoolNullable
3181            | DType::Int64
3182            | DType::Int64Nullable
3183            | DType::Utf8
3184            | DType::Categorical
3185            | DType::Interval
3186            | DType::Sparse => Self::Null(NullKind::Null),
3187        }
3188    }
3189
3190    #[must_use]
3191    pub fn semantic_eq(&self, other: &Self) -> bool {
3192        match (self, other) {
3193            (Self::Float64(a), Self::Float64(b)) => {
3194                if a.is_nan() && b.is_nan() {
3195                    return true;
3196                }
3197                if *a == *b {
3198                    return true;
3199                }
3200                let diff = (*a - *b).abs();
3201                let max_abs = a.abs().max(b.abs());
3202                if max_abs == 0.0 {
3203                    diff < f64::EPSILON
3204                } else {
3205                    diff / max_abs < 1e-14
3206                }
3207            }
3208            (Self::Null(_), Self::Float64(v)) | (Self::Float64(v), Self::Null(_)) => v.is_nan(),
3209            // All Null kinds (Null / NaN / NaT) mark missingness; they are
3210            // semantically indistinguishable for oracle-parity checks even
3211            // though derived PartialEq would reject a cross-kind pair.
3212            // fp-frame normalizes Float64 column missing cells to
3213            // Null(NaN) at Column::new time, while fixture oracles encode
3214            // the canonical missing marker as Null(Null).
3215            (Self::Null(_), Self::Null(_)) => true,
3216            // The DTYPE-SENTINEL missings are missing too, and this function
3217            // already says so for every other flavour. `missing_for_dtype`
3218            // DEFINES the canonical missing for Timedelta64 as
3219            // `Timedelta64(Timedelta::NAT)`, for Datetime64 as
3220            // `Datetime64(Timestamp::NAT)` and for Period as ordinal
3221            // `i64::MIN`, and `is_missing()` returns true for all three — but
3222            // without this arm none of them could ever equal the `Null` marker
3223            // an oracle records for pandas' NaT, so a parity check compared a
3224            // raw i64::MIN bit pattern against a null and called it a value
3225            // mismatch.
3226            //
3227            // OBSERVED on fp_p2d_021_series_to_timedelta_negative_null_hardened:
3228            //   FP     timedelta64:-9223372036854775808
3229            //   pandas null           (the format has no `na_t` marker, so
3230            //                          `null` IS NaT there)
3231            //
3232            // `compare_join_expected` in fp-conformance already carried this as
3233            // a manual `|| (left.is_missing() && right.is_missing())`; putting
3234            // it here makes that clause redundant instead of special, and
3235            // covers the series and dataframe comparators that lacked it.
3236            //
3237            // This is a COMPARISON rule only. It deliberately does not touch
3238            // `missing_for_dtype`: fp-columnar's 2026-07-14 NullKind TRAP note
3239            // records that the sentinel and `Null(NaT)` representations coexist
3240            // inside one column and a uniform gather cannot reproduce the mix,
3241            // which is a storage-model question. (br-frankenpandas-xwxci)
3242            _ if self.is_missing() && other.is_missing() => true,
3243            // An Interval's `==` ignores its subtype (pandas' Interval(0, 3)
3244            // == Interval(0.0, 3.0)), but interval[int64] and
3245            // interval[float64] are different pandas dtypes - '(0, 3]' and
3246            // '(0.0, 3.0]' (fvsao.54).
3247            (Self::Interval(a), Self::Interval(b)) => a == b && a.subtype == b.subtype,
3248            _ => self == other,
3249        }
3250    }
3251
3252    #[must_use]
3253    pub fn semantic_le(&self, other: &Self) -> bool {
3254        match self.semantic_cmp(other) {
3255            std::cmp::Ordering::Less | std::cmp::Ordering::Equal => true,
3256            std::cmp::Ordering::Greater => false,
3257        }
3258    }
3259
3260    #[must_use]
3261    pub fn semantic_ge(&self, other: &Self) -> bool {
3262        match self.semantic_cmp(other) {
3263            std::cmp::Ordering::Greater | std::cmp::Ordering::Equal => true,
3264            std::cmp::Ordering::Less => false,
3265        }
3266    }
3267
3268    #[must_use]
3269    pub fn is_null(&self) -> bool {
3270        matches!(self, Self::Null(_))
3271    }
3272
3273    #[must_use]
3274    pub fn is_na(&self) -> bool {
3275        self.is_missing()
3276    }
3277
3278    /// Return `true` if this scalar is NA/missing (alias for [`Self::is_na`]).
3279    #[must_use]
3280    pub fn isna(&self) -> bool {
3281        self.is_missing()
3282    }
3283
3284    /// Return `true` if this scalar is null (alias for [`Self::is_null`]).
3285    #[must_use]
3286    pub fn isnull(&self) -> bool {
3287        self.is_null()
3288    }
3289
3290    /// Return `true` if this scalar is not NA/missing (matches pandas `notna`).
3291    #[must_use]
3292    pub fn notna(&self) -> bool {
3293        !self.is_missing()
3294    }
3295
3296    /// Return `true` if this scalar is not null/missing (matches pandas `notnull`).
3297    #[must_use]
3298    pub fn notnull(&self) -> bool {
3299        !self.is_missing()
3300    }
3301
3302    /// Return `true` if this scalar is not NA/missing.
3303    #[must_use]
3304    pub fn is_not_na(&self) -> bool {
3305        !self.is_missing()
3306    }
3307
3308    /// Return `true` if this scalar is not NA/missing.
3309    #[must_use]
3310    pub fn not_na(&self) -> bool {
3311        !self.is_missing()
3312    }
3313
3314    #[must_use]
3315    pub fn coalesce(&self, other: &Self) -> Self {
3316        if self.is_missing() {
3317            other.clone()
3318        } else {
3319            self.clone()
3320        }
3321    }
3322
3323    #[must_use]
3324    pub fn semantic_cmp(&self, other: &Self) -> std::cmp::Ordering {
3325        match (self, other) {
3326            (Self::Int64(a), Self::Int64(b)) => a.cmp(b),
3327            (Self::Float64(a), Self::Float64(b)) => {
3328                a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)
3329            }
3330            (Self::Utf8(a), Self::Utf8(b)) => a.cmp(b),
3331            (Self::Bool(a), Self::Bool(b)) => a.cmp(b),
3332            (Self::Null(a), Self::Null(b)) => a.cmp(b),
3333            (Self::Timedelta64(a), Self::Timedelta64(b)) => {
3334                if *a == Timedelta::NAT || *b == Timedelta::NAT {
3335                    std::cmp::Ordering::Equal
3336                } else {
3337                    a.cmp(b)
3338                }
3339            }
3340            (Self::Datetime64(a), Self::Datetime64(b)) => {
3341                if *a == Timestamp::NAT || *b == Timestamp::NAT {
3342                    std::cmp::Ordering::Equal
3343                } else {
3344                    a.cmp(b)
3345                }
3346            }
3347            (Self::Period(a), Self::Period(b)) => {
3348                if a.ordinal == i64::MIN || b.ordinal == i64::MIN {
3349                    std::cmp::Ordering::Equal
3350                } else {
3351                    a.ordinal.cmp(&b.ordinal)
3352                }
3353            }
3354            (Self::Interval(a), Self::Interval(b)) => a
3355                .left
3356                .partial_cmp(&b.left)
3357                .unwrap_or(std::cmp::Ordering::Equal)
3358                .then_with(|| {
3359                    a.right
3360                        .partial_cmp(&b.right)
3361                        .unwrap_or(std::cmp::Ordering::Equal)
3362                })
3363                .then_with(|| a.closed.cmp(&b.closed)),
3364            // Object cells (dates, lists) in Python's order (fvsao.66).
3365            (Self::Object(a), Self::Object(b)) => a.cmp(b),
3366            // Cross-numeric comparison
3367            (Self::Int64(a), Self::Float64(b)) => (*a as f64)
3368                .partial_cmp(b)
3369                .unwrap_or(std::cmp::Ordering::Equal),
3370            (Self::Float64(a), Self::Int64(b)) => a
3371                .partial_cmp(&(*b as f64))
3372                .unwrap_or(std::cmp::Ordering::Equal),
3373            // Derived Debug starts every variant with its static variant name.
3374            // Different variants therefore order by that name before either
3375            // payload is observed; compare those names without allocating.
3376            (a, b) => a.debug_variant_name().cmp(b.debug_variant_name()),
3377        }
3378    }
3379
3380    pub fn to_f64(&self) -> Result<f64, TypeError> {
3381        match self {
3382            Self::Bool(v) => Ok(if *v { 1.0 } else { 0.0 }),
3383            Self::Int64(v) => Ok(*v as f64),
3384            Self::Float64(v) => Ok(*v),
3385            Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3386            Self::Utf8(v) => Err(TypeError::NonNumericValue {
3387                value: v.clone(),
3388                dtype: DType::Utf8,
3389            }),
3390            Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3391                kind: NullKind::NaT,
3392            }),
3393            Self::Timedelta64(v) => Err(TypeError::NonNumericValue {
3394                value: Timedelta::format(*v),
3395                dtype: DType::Timedelta64,
3396            }),
3397            Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3398                kind: NullKind::NaT,
3399            }),
3400            Self::Datetime64(v) => Err(TypeError::NonNumericValue {
3401                value: format!("Timestamp[{v}]"),
3402                dtype: DType::datetime64_naive(),
3403            }),
3404            Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3405                kind: NullKind::NaT,
3406            }),
3407            Self::Period(p) => Err(TypeError::NonNumericValue {
3408                value: p.calendar_string(),
3409                dtype: DType::Period,
3410            }),
3411            Self::Interval(v) => Err(TypeError::NonNumericValue {
3412                value: v.to_string(),
3413                dtype: DType::Interval,
3414            }),
3415            Self::Object(object) => Err(TypeError::NonNumericValue {
3416                value: object.repr(),
3417                dtype: DType::Utf8,
3418            }),
3419        }
3420    }
3421
3422    /// Try to convert to i64. Returns error for missing or non-numeric values.
3423    pub fn to_i64(&self) -> Result<i64, TypeError> {
3424        match self {
3425            Self::Bool(v) => Ok(if *v { 1 } else { 0 }),
3426            Self::Int64(v) => Ok(*v),
3427            Self::Float64(v) => Ok(*v as i64),
3428            Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3429            Self::Utf8(v) => Err(TypeError::NonNumericValue {
3430                value: v.clone(),
3431                dtype: DType::Utf8,
3432            }),
3433            Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3434                kind: NullKind::NaT,
3435            }),
3436            Self::Timedelta64(v) => Ok(*v),
3437            Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3438                kind: NullKind::NaT,
3439            }),
3440            Self::Datetime64(v) => Ok(*v),
3441            Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3442                kind: NullKind::NaT,
3443            }),
3444            Self::Period(p) => Ok(p.ordinal),
3445            Self::Interval(v) => Err(TypeError::NonNumericValue {
3446                value: v.to_string(),
3447                dtype: DType::Interval,
3448            }),
3449            Self::Object(object) => Err(TypeError::NonNumericValue {
3450                value: object.repr(),
3451                dtype: DType::Utf8,
3452            }),
3453        }
3454    }
3455
3456    /// Try to convert to bool. Returns error for missing values.
3457    pub fn to_bool(&self) -> Result<bool, TypeError> {
3458        match self {
3459            Self::Bool(v) => Ok(*v),
3460            Self::Int64(v) => Ok(*v != 0),
3461            Self::Float64(v) => Ok(*v != 0.0 && !v.is_nan()),
3462            Self::Null(kind) => Err(TypeError::ValueIsMissing { kind: *kind }),
3463            Self::Utf8(v) => Ok(!v.is_empty()),
3464            Self::Timedelta64(v) if *v == Timedelta::NAT => Err(TypeError::ValueIsMissing {
3465                kind: NullKind::NaT,
3466            }),
3467            Self::Timedelta64(v) => Ok(*v != 0),
3468            Self::Datetime64(v) if *v == Timestamp::NAT => Err(TypeError::ValueIsMissing {
3469                kind: NullKind::NaT,
3470            }),
3471            Self::Datetime64(v) => Ok(*v != 0),
3472            Self::Period(p) if p.ordinal == i64::MIN => Err(TypeError::ValueIsMissing {
3473                kind: NullKind::NaT,
3474            }),
3475            Self::Period(p) => Ok(p.ordinal != 0),
3476            Self::Interval(_) => Ok(true),
3477            // Python's truth: a list or bytes is true when it has items, any
3478            // other object true.
3479            Self::Object(ObjectValue::List(items)) => Ok(!items.is_empty()),
3480            Self::Object(ObjectValue::Bytes(data)) => Ok(!data.is_empty()),
3481            Self::Object(ObjectValue::Host(_)) => Ok(true),
3482        }
3483    }
3484
3485    /// Try to convert to string representation.
3486    pub fn to_str(&self) -> String {
3487        match self {
3488            Self::Bool(v) => if *v { "True" } else { "False" }.to_string(),
3489            Self::Int64(v) => v.to_string(),
3490            Self::Float64(v) => {
3491                if v.is_nan() {
3492                    "nan".to_string()
3493                } else if v.is_infinite() {
3494                    if *v > 0.0 { "inf" } else { "-inf" }.to_string()
3495                } else {
3496                    v.to_string()
3497                }
3498            }
3499            Self::Null(_) => "NaN".to_string(),
3500            Self::Utf8(v) => v.clone(),
3501            Self::Timedelta64(v) => Timedelta::format(*v),
3502            Self::Datetime64(v) if *v == Timestamp::NAT => "NaT".to_string(),
3503            Self::Datetime64(v) => Timestamp::from_nanos(*v).isoformat(),
3504            Self::Period(p) if p.ordinal == i64::MIN => "NaT".to_string(),
3505            Self::Period(p) => p.calendar_string(),
3506            Self::Interval(v) => v.to_string(),
3507            Self::Object(object) => object.to_string(),
3508        }
3509    }
3510}
3511
3512#[derive(Debug, Error, Clone, PartialEq)]
3513pub enum TypeError {
3514    #[error("dtype coercion from {left:?} to {right:?} has no compatible common type")]
3515    IncompatibleDtypes { left: DType, right: DType },
3516    #[error("cannot cast scalar of dtype {from:?} to {to:?}")]
3517    InvalidCast { from: DType, to: DType },
3518    #[error("cannot cast float {value} to int64 without loss")]
3519    LossyFloatToInt { value: f64 },
3520    #[error("expected 0/1 for bool cast from int64 but found {value}")]
3521    InvalidBoolInt { value: i64 },
3522    #[error("expected 0.0/1.0 for bool cast from float64 but found {value}")]
3523    InvalidBoolFloat { value: f64 },
3524    #[error("value {value:?} has non-numeric dtype {dtype:?}")]
3525    NonNumericValue { value: String, dtype: DType },
3526    #[error("value is missing ({kind:?})")]
3527    ValueIsMissing { kind: NullKind },
3528    #[error("sparse value dtype cannot be {dtype:?}")]
3529    InvalidSparseValueDType { dtype: DType },
3530    #[error("interval_range step must be finite, positive, and not NaN (got {step})")]
3531    InvalidIntervalStep { step: f64 },
3532    #[error("interval_range step {step} does not evenly divide range end-start={span}")]
3533    IntervalStepDoesNotDivide { step: f64, span: f64 },
3534    #[error("interval_range requires exactly 3 of (start, end, periods, freq) to be specified")]
3535    IntervalRangeParameterCount,
3536    #[error("cannot parse '{value}' as {target}")]
3537    ValueNotParseable { value: String, target: String },
3538}
3539
3540pub fn common_dtype(left: DType, right: DType) -> Result<DType, TypeError> {
3541    use DType::{
3542        Bool, BoolNullable, Categorical, Float64, Float64Nullable, Int64, Int64Nullable, Null,
3543        Sparse, Timedelta64,
3544    };
3545
3546    let out = match (&left, &right) {
3547        (a, b) if a == b => a.clone(),
3548        (Null, other) | (other, Null) => other.clone(),
3549        (Categorical, Categorical) => Categorical,
3550
3551        // Bool promotions (nullable absorbs non-nullable)
3552        (Bool, Int64) | (Int64, Bool) => Int64,
3553        (Bool, Int64Nullable) | (Int64Nullable, Bool) => Int64Nullable,
3554        (BoolNullable, Int64) | (Int64, BoolNullable) => Int64Nullable,
3555        (BoolNullable, Int64Nullable) | (Int64Nullable, BoolNullable) => Int64Nullable,
3556        (Bool, BoolNullable) | (BoolNullable, Bool) => BoolNullable,
3557        (Bool, Float64) | (Float64, Bool) => Float64,
3558        // MEASURED, live pandas 2.2.3:
3559        //     pd.Series([True,None],dtype="boolean") + pd.Series([1.5,2.5,3.5])
3560        //         -> Float64        (the EXTENSION dtype, not numpy float64)
3561        // Flipped together with the Int64Nullable arm below; see the
3562        // associativity note there for why they cannot move independently.
3563        (BoolNullable, Float64) | (Float64, BoolNullable) => Float64Nullable,
3564
3565        // Int64 promotions (nullable absorbs non-nullable)
3566        (Int64, Float64) | (Float64, Int64) => Float64,
3567        // MEASURED, live pandas 2.2.3, both spellings agree:
3568        //     find_common_type([Int64, float64])                        -> Float64
3569        //     pd.Series([1,None],dtype="Int64") + pd.Series([1.5,2.5])  -> Float64
3570        // i.e. the NULLABLE flavour wins, so the answer is Float64Nullable.
3571        //
3572        // ⚠ THIS ARM AND THE BoolNullable ARM ABOVE ARE ONE ATOMIC CHANGE. The
3573        // lattice is checked for associativity over ALL dtypes by
3574        // `common_dtype_lattice_axioms_be314`, and flipping only this arm breaks
3575        // it on (BoolNullable, Int64, Float64):
3576        //     (BN ∨ I64) ∨ F64 = Int64Nullable ∨ Float64 = Float64Nullable
3577        //     BN ∨ (I64 ∨ F64) = BN ∨ Float64            = Float64      ✗
3578        // Both arms flip, or neither does. (br-frankenpandas-qkqfb, unblocks
3579        // br-frankenpandas-f0aaa)
3580        (Int64Nullable, Float64) | (Float64, Int64Nullable) => Float64Nullable,
3581        (Int64, Int64Nullable) | (Int64Nullable, Int64) => Int64Nullable,
3582
3583        // Float64Nullable promotions. These are now REACHABLE: the two arms
3584        // above produce Float64Nullable, so anything that folds a dtype list
3585        // (melt's try_fold, combine_first's target_dtype) can feed it back in
3586        // here. They are what makes that fold associative.
3587        //
3588        // MEASURED, live pandas 2.2.3 ARITHMETIC (which is what this function
3589        // models -- see the Bool arms above, which follow arithmetic rather than
3590        // find_common_type, since find_common_type answers `object` for every
3591        // bool+numeric pair and FrankenPandas has no object dtype yet, that
3592        // being br-frankenpandas-hlcgl):
3593        //     Float64(ext) + float64(numpy)          -> Float64
3594        //     Int64(ext)   + Float64(ext)            -> Float64
3595        //     boolean(ext) + Float64(ext)            -> Float64
3596        // The nullable float absorbs every other numeric flavour, which also
3597        // makes it the top of the numeric lattice and keeps promotion
3598        // associative.
3599        (Float64Nullable, Float64) | (Float64, Float64Nullable) => Float64Nullable,
3600        (Float64Nullable, Int64) | (Int64, Float64Nullable) => Float64Nullable,
3601        (Float64Nullable, Int64Nullable) | (Int64Nullable, Float64Nullable) => Float64Nullable,
3602        (Float64Nullable, Bool) | (Bool, Float64Nullable) => Float64Nullable,
3603        (Float64Nullable, BoolNullable) | (BoolNullable, Float64Nullable) => Float64Nullable,
3604
3605        // Datetime/Timedelta
3606        (Timedelta64, Timedelta64) => Timedelta64,
3607        (DType::Datetime64 { tz: left_tz }, DType::Datetime64 { tz: right_tz })
3608            if left_tz == right_tz =>
3609        {
3610            DType::Datetime64 {
3611                tz: left_tz.clone(),
3612            }
3613        }
3614
3615        (Sparse, _) | (_, Sparse) => {
3616            return Err(TypeError::IncompatibleDtypes {
3617                left: left.clone(),
3618                right: right.clone(),
3619            });
3620        }
3621        _ => {
3622            return Err(TypeError::IncompatibleDtypes { left, right });
3623        }
3624    };
3625
3626    Ok(out)
3627}
3628
3629pub fn infer_dtype(values: &[Scalar]) -> Result<DType, TypeError> {
3630    let mut current = DType::Null;
3631    let mut saw_utf8 = false;
3632    let mut saw_timedelta = false;
3633    let mut saw_datetime = false;
3634    let mut saw_non_utf8_non_null = false;
3635    // br-frankenpandas-rh1od: pandas constructs OBJECT columns whenever a
3636    // Python bool mixes with any numeric scalar ([True, 2] -> object,
3637    // measured live 2.2.3); numpy's bool<int common-type never fires at the
3638    // constructor. FrankenPandas coerced to Int64 here, which no pandas
3639    // constructor path produces. Strings already take the object bucket
3640    // below (DISC-005); bool+numeric joins them.
3641    let mut saw_bool = false;
3642    let mut saw_numeric = false;
3643
3644    // NOTE (br-frankenpandas-nywa8): inferring Float64 from a NaN-KIND missing
3645    // looks like the right central fix for pandas' int64 -> float64 promotion,
3646    // and it is NOT. `NullKind::NaN` is used throughout FrankenPandas as the
3647    // GENERIC missing marker, not specifically as "a float NaN" — e.g. short-row
3648    // padding and `missing_for_dtype(Float64)` both produce it. Promoting on it
3649    // broke 19 pre-existing fp-columnar tests (ffill returning Float64(1.0)
3650    // where Int64(1) was pinned, isin flipping a bool) because those columns are
3651    // legitimately Int64 with a generic missing. Measured, then reverted.
3652    //
3653    // The promotion has to be applied where a gap is INTRODUCED and the
3654    // introducer knows it is inventing one — see `concat_dataframes_*`, which
3655    // promotes locally. Do not move it back here without first giving
3656    // "pandas-introduced gap" a marker distinct from generic missingness.
3657    for value in values {
3658        match value.dtype() {
3659            DType::Null => {}
3660            DType::Utf8 => saw_utf8 = true,
3661            DType::Bool => {
3662                saw_bool = true;
3663                saw_non_utf8_non_null = true;
3664                current = common_dtype(current, DType::Bool)?;
3665            }
3666            DType::Int64 | DType::Float64 => {
3667                saw_numeric = true;
3668                saw_non_utf8_non_null = true;
3669                current = common_dtype(current, value.dtype())?;
3670            }
3671            DType::Timedelta64 => {
3672                saw_timedelta = true;
3673                if current == DType::Null {
3674                    current = DType::Timedelta64;
3675                } else if current != DType::Timedelta64 {
3676                    return Err(TypeError::IncompatibleDtypes {
3677                        left: current,
3678                        right: DType::Timedelta64,
3679                    });
3680                }
3681            }
3682            DType::Datetime64 { .. } => {
3683                saw_datetime = true;
3684                if current == DType::Null {
3685                    current = DType::datetime64_naive();
3686                } else if !current.is_datetime() {
3687                    return Err(TypeError::IncompatibleDtypes {
3688                        left: current,
3689                        right: DType::datetime64_naive(),
3690                    });
3691                }
3692            }
3693            other => {
3694                saw_non_utf8_non_null = true;
3695                current = common_dtype(current, other)?;
3696            }
3697        }
3698
3699        if saw_bool && saw_numeric {
3700            // Constructor inference follows pandas object-dtype behavior for
3701            // heterogeneous string/scalar payloads while arithmetic coercion
3702            // remains governed by the stricter common_dtype lattice.
3703            return Ok(DType::Utf8);
3704        }
3705        if saw_utf8 && saw_non_utf8_non_null {
3706            // Constructor inference follows pandas object-dtype behavior for
3707            // heterogeneous string/scalar payloads while arithmetic coercion
3708            // remains governed by the stricter common_dtype lattice.
3709            return Ok(DType::Utf8);
3710        }
3711        if saw_timedelta && saw_non_utf8_non_null {
3712            return Err(TypeError::IncompatibleDtypes {
3713                left: DType::Timedelta64,
3714                right: current,
3715            });
3716        }
3717        if saw_datetime && saw_non_utf8_non_null {
3718            return Err(TypeError::IncompatibleDtypes {
3719                left: DType::datetime64_naive(),
3720                right: current,
3721            });
3722        }
3723    }
3724
3725    if saw_utf8 {
3726        Ok(DType::Utf8)
3727    } else {
3728        Ok(current)
3729    }
3730}
3731
3732/// Cast a scalar to a target dtype, taking ownership to avoid redundant clones
3733/// when the value already has the correct type (AG-03: identity-cast skip).
3734pub fn cast_scalar_owned(value: Scalar, target: DType) -> Result<Scalar, TypeError> {
3735    let from = value.dtype();
3736    if from == target {
3737        return Ok(value);
3738    }
3739    // Int64 <-> Int64Nullable: same representation, just different dtype tracking
3740    if (from == DType::Int64 && target == DType::Int64Nullable)
3741        || (from == DType::Int64Nullable && target == DType::Int64)
3742    {
3743        return Ok(value);
3744    }
3745    // Bool <-> BoolNullable: same representation
3746    if (from == DType::Bool && target == DType::BoolNullable)
3747        || (from == DType::BoolNullable && target == DType::Bool)
3748    {
3749        return Ok(value);
3750    }
3751    // Float64 <-> Float64Nullable: same 8-byte payload, and a PRESENT value
3752    // round-trips unchanged in both directions. MEASURED, live pandas 2.2.3:
3753    //     pd.Series([1.5, None], dtype="Float64").astype("float64") -> [1.5, nan]
3754    //     pd.Series([1.5, None]).astype("Float64")                  -> [1.5, <NA>]
3755    // Only the MISSING marker differs, and a missing input never reaches here --
3756    // `value.is_missing()` below routes it to `missing_for_dtype(target)`, which
3757    // is what converts NaN <-> pd.NA. (br-frankenpandas-qkqfb)
3758    if (from == DType::Float64 && target == DType::Float64Nullable)
3759        || (from == DType::Float64Nullable && target == DType::Float64)
3760    {
3761        return Ok(value);
3762    }
3763    // A datetime scalar is an instant and a zone is its column's metadata, so
3764    // it takes any datetime64 dtype as it is (a fill or set value on a
3765    // tz-aware column was refused as an invalid cast).
3766    if from.is_datetime() && target.is_datetime() {
3767        return Ok(value);
3768    }
3769    if target == DType::Utf8 {
3770        return Ok(Scalar::Utf8(scalar_to_string_for_astype(value)));
3771    }
3772    // Per br-frankenpandas-cyi4h: pandas astype(bool) (the numpy bool dtype)
3773    // treats a float NaN as truthy -> True (bool(nan) is True), unlike the
3774    // nullable 'boolean' dtype which keeps NA. FP's NaN=missing model would
3775    // otherwise fall through to the missing branch below and yield a null.
3776    // Verified vs live pandas 2.2.3.
3777    if target == DType::Bool
3778        && let Scalar::Float64(v) = &value
3779        && v.is_nan()
3780    {
3781        return Ok(Scalar::Bool(true));
3782    }
3783    // TEMPORAL -> NUMPY bool IS NONZERO-TRUTHY ON THE RAW NANOSECONDS, and it
3784    // sits here for exactly the reason the NaN check above does: FP's
3785    // missing-value model would otherwise swallow NaT below, and pandas does not
3786    // treat it as missing here.
3787    //
3788    // MEASURED, live pandas 2.2.3, `.astype('bool')` beside `.astype('int64')`
3789    // so the rule is visible as one rule rather than four cases:
3790    //
3791    //   value                                 nanos                  bool
3792    //   Timestamp(0)                              0                 False
3793    //   Timestamp('2024-03-15 10:30:45.123..')  1.71e18               True
3794    //   Timestamp('1969-12-31 23:59:59.999..')       -1               True
3795    //   NaT (either dtype)          -9223372036854775808              True
3796    //   Timedelta(0)                              0                 False
3797    //   Timedelta('1 days')          86400000000000                   True
3798    //   Timedelta('-1 ns')                       -1                   True
3799    //
3800    // So `nanos != 0` is the whole rule, and NaT needs no case of its own: it IS
3801    // i64::MIN, which is nonzero. Only the epoch and a zero duration are False.
3802    //
3803    // ⚠️ THE NULLABLE `boolean` REFUSES ALL OF THESE, including the ones whose
3804    // nanos are 0 or 1 — `.astype('boolean')` raises "Need to pass bool-like
3805    // values" for EVERY row above, so it is the dtype it rejects, not the value.
3806    // That is why this is guarded on `DType::Bool` alone and why the strict
3807    // `BoolNullable` arm below is left without a temporal case.
3808    if target == DType::Bool {
3809        match &value {
3810            Scalar::Datetime64(nanos) | Scalar::Timedelta64(nanos) => {
3811                return Ok(Scalar::Bool(*nanos != 0));
3812            }
3813            _ => {}
3814        }
3815    }
3816    // TEMPORAL -> NUMPY int64 IS RAW NANOSECONDS, and this sits ABOVE the
3817    // missing-value branch on purpose.
3818    //
3819    // MEASURED, live pandas 2.2.3:
3820    //     pd.Series([Timestamp('2024-03-15 10:30:45.123456789')]).astype('int64')
3821    //       -> 1710498645123456789
3822    //     pd.Series([Timedelta('1 days 02:03:04.005006007')]).astype('int64')
3823    //       -> 93784005006007
3824    //     pd.Series([pd.NaT], dtype='datetime64[ns]').astype('int64')
3825    //       -> -9223372036854775808        <- THE SENTINEL, not a missing value
3826    //
3827    // ⚠️ NaT IS WHY THE ORDER MATTERS. Below this point `value.is_missing()`
3828    // would turn NaT into `Null(Null)`, and pandas emphatically does not: it
3829    // hands back i64::MIN, which is the same bit pattern NaT already IS. Doing
3830    // the cast here makes the sentinel round-trip by construction rather than by
3831    // a second special case.
3832    //
3833    // ⚠️ NUMPY `int64` ONLY — the NULLABLE `Int64` REFUSES this, and so must we:
3834    //     .astype('Int64')   -> TypeError: datetime64[ns] cannot be converted
3835    //                          to IntegerDtype
3836    //     .astype('float64') -> TypeError: Cannot cast DatetimeArray to dtype
3837    //                          float64
3838    // which is why this is guarded on the exact target rather than folded into
3839    // the `Int64 | Int64Nullable` arm below, and why no Float64 arm is added.
3840    if target == DType::Int64 {
3841        match &value {
3842            Scalar::Datetime64(nanos) | Scalar::Timedelta64(nanos) => {
3843                return Ok(Scalar::Int64(*nanos));
3844            }
3845            _ => {}
3846        }
3847    }
3848    if value.is_missing() {
3849        return Ok(Scalar::missing_for_dtype(target));
3850    }
3851
3852    // Note: identity casts (from == target) are handled above, so same-type
3853    // arms are omitted from the match below.
3854    match target {
3855        DType::Null => Ok(Scalar::Null(NullKind::Null)),
3856        DType::Bool => match &value {
3857            // numpy bool: zero -> False, ANY nonzero -> True (it does not
3858            // restrict to 0/1). e.g. bool of -3 / 2.5 is True.
3859            Scalar::Int64(v) => Ok(Scalar::Bool(*v != 0)),
3860            // 0.0 and -0.0 -> False; every other value, INCLUDING NaN, -> True
3861            // (NaN != 0.0 is true), matching numpy/pandas truthiness.
3862            Scalar::Float64(v) => Ok(Scalar::Bool(*v != 0.0)),
3863            _ => Err(TypeError::InvalidCast { from, to: target }),
3864        },
3865        DType::BoolNullable => match &value {
3866            // pandas nullable Boolean ('boolean') is STRICT: only 0/1 (or
3867            // True/False) are accepted — any other value raises "Need to pass
3868            // bool-like values", UNLIKE numpy bool which is nonzero-truthy.
3869            // (br-frankenpandas-tjomg)
3870            Scalar::Bool(b) => Ok(Scalar::Bool(*b)),
3871            Scalar::Int64(0) => Ok(Scalar::Bool(false)),
3872            Scalar::Int64(1) => Ok(Scalar::Bool(true)),
3873            Scalar::Int64(v) => Err(TypeError::InvalidBoolInt { value: *v }),
3874            Scalar::Float64(v) if *v == 0.0 => Ok(Scalar::Bool(false)),
3875            Scalar::Float64(v) if *v == 1.0 => Ok(Scalar::Bool(true)),
3876            Scalar::Float64(v) => Err(TypeError::InvalidBoolFloat { value: *v }),
3877            _ => Err(TypeError::InvalidCast { from, to: target }),
3878        },
3879        DType::Int64 | DType::Int64Nullable => match &value {
3880            Scalar::Bool(v) => Ok(Scalar::Int64(i64::from(*v))),
3881            Scalar::Float64(v) => {
3882                // pandas astype(int64) truncates a finite float toward zero
3883                // (1.9 -> 1, -1.9 -> -1, 2.5 -> 2); only non-finite (NaN/±inf)
3884                // or out-of-i64-range values raise. Verified vs pandas 2.2.3
3885                // (br-frankenpandas-qcutc). NaN is handled as missing above, so
3886                // here non-finite means ±inf. `as i64` performs the toward-zero
3887                // truncation for in-range finite values.
3888                if !v.is_finite() {
3889                    return Err(TypeError::LossyFloatToInt { value: *v });
3890                }
3891                if *v < i64::MIN as f64 || *v >= 9223372036854775808.0 {
3892                    return Err(TypeError::LossyFloatToInt { value: *v });
3893                }
3894                Ok(Scalar::Int64(*v as i64))
3895            }
3896            Scalar::Utf8(s) => {
3897                // Try direct int parse first, then try float parse + truncate
3898                // (pandas accepts "1.0" as valid int via float intermediate)
3899                if let Ok(v) = s.parse::<i64>() {
3900                    return Ok(Scalar::Int64(v));
3901                }
3902                if let Ok(f) = s.parse::<f64>()
3903                    && f.is_finite()
3904                    && f.fract() == 0.0
3905                    && f >= i64::MIN as f64
3906                    && f < 9223372036854775808.0
3907                {
3908                    return Ok(Scalar::Int64(f as i64));
3909                }
3910                Err(TypeError::InvalidCast { from, to: target })
3911            }
3912            _ => Err(TypeError::InvalidCast { from, to: target }),
3913        },
3914        // Both float flavours accept the same source values; they differ only in
3915        // the missing marker, which is handled above. MEASURED:
3916        //     pd.Series([1,None],dtype="Int64").astype("Float64") -> [1.0, <NA>]
3917        DType::Float64 | DType::Float64Nullable => match &value {
3918            Scalar::Bool(v) => Ok(Scalar::Float64(if *v { 1.0 } else { 0.0 })),
3919            Scalar::Int64(v) => Ok(Scalar::Float64(*v as f64)),
3920            Scalar::Utf8(s) => s
3921                .parse::<f64>()
3922                .map(Scalar::Float64)
3923                .map_err(|_| TypeError::InvalidCast { from, to: target }),
3924            _ => Err(TypeError::InvalidCast { from, to: target }),
3925        },
3926        DType::Utf8 => Ok(Scalar::Utf8(scalar_to_string_for_astype(value))),
3927        DType::Categorical => Err(TypeError::InvalidCast { from, to: target }),
3928        DType::Timedelta64 => match &value {
3929            // A BOOL IS 0 OR 1 NANOSECONDS on the astype path. Measured:
3930            //     pd.Series([True]).astype('timedelta64[ns]') -> 1ns
3931            //     pd.Series([True]).astype('datetime64[ns]')  -> 1970-01-01 ...001
3932            // ⚠️ The CONSTRUCTOR refuses the same thing —
3933            //     pd.DataFrame([[True]], dtype='datetime64[ns]')
3934            //       -> TypeError: dtype bool cannot be converted to datetime64[ns]
3935            // -- the same astype/constructor split `float_to_temporal_nanos`
3936            // documents for non-finite input. This cast is shared, so it takes
3937            // astype's answer and the constructor's refusal belongs in
3938            // `DataFrame::with_constructor_dtype`.
3939            Scalar::Bool(v) => Ok(Scalar::Timedelta64(i64::from(*v))),
3940            Scalar::Int64(v) => Ok(Scalar::Timedelta64(*v)),
3941            Scalar::Float64(v) => Ok(Scalar::Timedelta64(float_to_temporal_nanos(*v))),
3942            Scalar::Utf8(s) => Timedelta::parse(s)
3943                .map(Scalar::Timedelta64)
3944                .map_err(|_| TypeError::InvalidCast { from, to: target }),
3945            _ => Err(TypeError::InvalidCast { from, to: target }),
3946        },
3947        DType::Datetime64 { .. } => match &value {
3948            // See the Timedelta64 arm above for the measurement and for why the
3949            // constructor's stricter refusal is not encoded here.
3950            Scalar::Bool(v) => Ok(Scalar::Datetime64(i64::from(*v))),
3951            Scalar::Int64(v) => Ok(Scalar::Datetime64(*v)),
3952            Scalar::Float64(v) => Ok(Scalar::Datetime64(float_to_temporal_nanos(*v))),
3953            Scalar::Utf8(s) => Timestamp::parse(s)
3954                .map(|timestamp| Scalar::Datetime64(timestamp.nanos))
3955                .map_err(|_| TypeError::InvalidCast { from, to: target }),
3956            _ => Err(TypeError::InvalidCast { from, to: target }),
3957        },
3958        DType::Period => match &value {
3959            // Int cast to a freq-less DType::Period: default to Daily (pandas
3960            // requires an explicit freq in the dtype; ours is freq-less).
3961            Scalar::Int64(v) => Ok(Scalar::Period(Period::new(*v, PeriodFreq::Daily))),
3962            Scalar::Utf8(s) => Period::parse(s)
3963                .map(Scalar::Period)
3964                .map_err(|_| TypeError::InvalidCast { from, to: target }),
3965            _ => Err(TypeError::InvalidCast { from, to: target }),
3966        },
3967        DType::Interval => match &value {
3968            Scalar::Utf8(s) => Interval::parse(s)
3969                .map(Scalar::Interval)
3970                .map_err(|_| TypeError::InvalidCast { from, to: target }),
3971            _ => Err(TypeError::InvalidCast { from, to: target }),
3972        },
3973        DType::Sparse => Err(TypeError::InvalidCast { from, to: target }),
3974    }
3975}
3976
3977/// A float reinterpreted as integer NANOSECONDS, the way pandas casts to
3978/// `datetime64[ns]` / `timedelta64[ns]`.
3979///
3980/// ⚠️ THIS IS NOT THE `int64` RULE, and the difference is the whole reason this
3981/// helper exists rather than a reuse. The explicit constructor REFUSES a lossy
3982/// float -> int64 (`TypeError::LossyFloatToInt`, mirroring pandas' "Trying to
3983/// coerce float values to integers"), but the temporal dtypes silently truncate.
3984/// MEASURED side by side, live pandas 2.2.3, on the single value `1.5`:
3985///
3986/// ```text
3987/// pd.DataFrame([[1.5]], dtype="int64")           -> ValueError
3988/// pd.DataFrame([[1.5]], dtype="datetime64[ns]")  -> 1ns
3989/// pd.DataFrame([[1.5]], dtype="timedelta64[ns]") -> 1ns
3990/// ```
3991///
3992/// TRUNCATION IS TOWARD ZERO, NOT FLOOR. Measured on both signs, where the two
3993/// disagree: 0.9 -> 0 and -0.9 -> 0; 1.5 -> 1 and -1.5 -> -1; -2.5 -> -2 (a
3994/// floor would give -1, -2 and -3). Rust's `as i64` is exactly this truncation.
3995///
3996/// ANYTHING NOT REPRESENTABLE AS `i64` BECOMES NaT, which is why this cannot be
3997/// a bare `as` — Rust's saturating cast would hand back `i64::MAX` where pandas
3998/// hands back NaT, and would map NaN to 0, i.e. the epoch. Measured, all NaT:
3999/// NaN, +inf, -inf, 1e30, -1e30, 9.3e18, and exactly 2^63 and -2^63; while
4000/// 2^63 - 1024 IS representable and converts (2262-04-11 23:47:16.854774784).
4001/// The bounds are therefore strict on both ends — `i64::MIN as f64` is exactly
4002/// -2^63, which pandas already reads as NaT because it IS the NaT sentinel.
4003///
4004/// ⚠️ ONE KNOWN DIVERGENCE, RECORDED RATHER THAN GUESSED. For `timedelta64[ns]`
4005/// pandas' two paths disagree on the non-finite input: `astype` yields NaT but
4006/// the constructor raises OverflowError. `datetime64[ns]` has no such split —
4007/// both give NaT. This cast is shared by both paths, so it takes the behaviour
4008/// they agree on for datetimes and `astype`'s for timedeltas; the constructor's
4009/// stricter refusal belongs in `DataFrame::with_constructor_dtype`, which is
4010/// already where the constructor-only `int64`-rejects-NA check lives, and for
4011/// the same reason.
4012fn float_to_temporal_nanos(value: f64) -> i64 {
4013    // Strict on both ends: `i64::MIN as f64` and `i64::MAX as f64` are -2^63 and
4014    // 2^63, and pandas reads both of those as NaT.
4015    if value.is_finite() && value > (i64::MIN as f64) && value < (i64::MAX as f64) {
4016        // Truncates toward zero, and the guard above means it cannot saturate.
4017        value as i64
4018    } else {
4019        // `Timestamp::NAT` and `Timedelta::NAT` are the same value (`i64::MIN`),
4020        // so this one sentinel is correct for both callers.
4021        Timestamp::NAT
4022    }
4023}
4024
4025fn scalar_to_string_for_astype(value: Scalar) -> String {
4026    match value {
4027        Scalar::Null(NullKind::Null) => "None".to_owned(),
4028        Scalar::Null(NullKind::NaN) => "nan".to_owned(),
4029        Scalar::Null(NullKind::NaT) => "NaT".to_owned(),
4030        Scalar::Bool(true) => "True".to_owned(),
4031        Scalar::Bool(false) => "False".to_owned(),
4032        Scalar::Int64(v) => v.to_string(),
4033        Scalar::Float64(v) => float_to_string_for_astype(v),
4034        Scalar::Utf8(s) => s,
4035        Scalar::Timedelta64(v) if v == Timedelta::NAT => "NaT".to_owned(),
4036        Scalar::Timedelta64(v) => Timedelta::format(v),
4037        Scalar::Datetime64(v) if v == Timestamp::NAT => "NaT".to_owned(),
4038        Scalar::Datetime64(v) => timestamp_text(v),
4039        Scalar::Period(p) if p.ordinal == i64::MIN => "NaT".to_owned(),
4040        Scalar::Period(p) => p.calendar_string(),
4041        Scalar::Interval(v) => v.to_string(),
4042        // astype(str) of a list cell is its repr, of a host value its str.
4043        Scalar::Object(object) => object.to_string(),
4044    }
4045}
4046
4047pub fn float_to_string_for_astype(value: f64) -> String {
4048    use std::fmt::Write as _;
4049
4050    if value.is_nan() {
4051        return "nan".to_owned();
4052    }
4053    if value.is_infinite() {
4054        return value.to_string(); // "inf" / "-inf"
4055    }
4056    // pandas astype(str) renders floats via Python str(float): whole numbers
4057    // keep ".0", decimals use the shortest round-trip, and extreme magnitudes use
4058    // scientific notation ("1e+16", "1e-05"). Rust's Debug formatter matches this
4059    // (shortest round-trip, ".0" on whole numbers, scientific at Python's
4060    // boundaries); only the exponent spelling differs (Rust "1e16"/"1e-5" vs
4061    // Python "1e+16"/"1e-05"), so normalize that. The old `{:.1}` whole / Display
4062    // decimal path lost scientific notation (1e16 -> "10000000000000000.0").
4063    // Leave enough spare capacity for the positive sign and one exponent pad
4064    // digit, then normalize the formatter output in place. The former branch
4065    // allocated a second String and copied the mantissa solely to change
4066    // `e16`/`e-5` into pandas' `e+16`/`e-05` spelling.
4067    let mut rendered = String::with_capacity(32);
4068    let _ = write!(rendered, "{value:?}");
4069    let Some(exponent_marker) = rendered.find('e') else {
4070        return rendered;
4071    };
4072
4073    let sign_position = exponent_marker + 1;
4074    let digits_position = match rendered.as_bytes().get(sign_position) {
4075        Some(b'+' | b'-') => sign_position + 1,
4076        _ => {
4077            rendered.insert(sign_position, '+');
4078            sign_position + 1
4079        }
4080    };
4081    if rendered.len() - digits_position == 1 {
4082        rendered.insert(digits_position, '0');
4083    }
4084    rendered
4085}
4086
4087static ENG_FLOAT_ACCURACY: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(3);
4088static ENG_FLOAT_USE_PREFIX: std::sync::atomic::AtomicBool =
4089    std::sync::atomic::AtomicBool::new(false);
4090static ENG_FLOAT_ACTIVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
4091
4092/// Format float values according to engineering format, matching pandas `EngFormatter`.
4093pub fn eng_float_format(num: f64, accuracy: Option<usize>, use_eng_prefix: bool) -> String {
4094    if num.is_nan() {
4095        return "NaN".to_string();
4096    }
4097    if num.is_infinite() {
4098        return if num < 0.0 {
4099            "-inf".to_string()
4100        } else {
4101            "inf".to_string()
4102        };
4103    }
4104
4105    let sign = if num < 0.0 { -1.0 } else { 1.0 };
4106    let abs_num = num.abs();
4107
4108    let pow10 = if abs_num != 0.0 {
4109        let p = (abs_num.log10() / 3.0).floor() as i32 * 3;
4110        p.clamp(-24, 24)
4111    } else {
4112        0
4113    };
4114
4115    let prefix = if use_eng_prefix {
4116        match pow10 {
4117            -24 => "y",
4118            -21 => "z",
4119            -18 => "a",
4120            -15 => "f",
4121            -12 => "p",
4122            -9 => "n",
4123            -6 => "u",
4124            -3 => "m",
4125            0 => "",
4126            3 => "k",
4127            6 => "M",
4128            9 => "G",
4129            12 => "T",
4130            15 => "P",
4131            18 => "E",
4132            21 => "Z",
4133            24 => "Y",
4134            _ => "",
4135        }
4136        .to_string()
4137    } else if pow10 < 0 {
4138        format!("E-{:02}", -pow10)
4139    } else {
4140        format!("E+{:02}", pow10)
4141    };
4142
4143    let mant = (sign * abs_num) / 10f64.powi(pow10);
4144
4145    if let Some(acc) = accuracy {
4146        format!("{mant:.acc$}{prefix}", acc = acc)
4147    } else {
4148        format!("{mant}{prefix}")
4149    }
4150}
4151
4152/// Set pandas-compatible engineering float formatting option.
4153/// Matches `pd.set_eng_float_format(accuracy=3, use_eng_prefix=False)`.
4154pub fn set_eng_float_format(accuracy: usize, use_eng_prefix: bool) {
4155    use std::sync::atomic::Ordering;
4156    ENG_FLOAT_ACCURACY.store(accuracy, Ordering::Relaxed);
4157    ENG_FLOAT_USE_PREFIX.store(use_eng_prefix, Ordering::Relaxed);
4158    ENG_FLOAT_ACTIVE.store(true, Ordering::Relaxed);
4159}
4160
4161/// Reset engineering float formatting back to default.
4162pub fn reset_eng_float_format() {
4163    use std::sync::atomic::Ordering;
4164    ENG_FLOAT_ACTIVE.store(false, Ordering::Relaxed);
4165}
4166
4167/// Get the current engineering float format configuration if active.
4168pub fn get_eng_float_format() -> Option<(usize, bool)> {
4169    use std::sync::atomic::Ordering;
4170    if ENG_FLOAT_ACTIVE.load(Ordering::Relaxed) {
4171        Some((
4172            ENG_FLOAT_ACCURACY.load(Ordering::Relaxed),
4173            ENG_FLOAT_USE_PREFIX.load(Ordering::Relaxed),
4174        ))
4175    } else {
4176        None
4177    }
4178}
4179
4180// ── Global Configuration Options (matching pd.options) ───────────────────
4181
4182/// Error encountered when inspecting or modifying configuration options.
4183#[derive(Debug, Error, Clone, PartialEq, Eq)]
4184pub enum OptionError {
4185    #[error("no such option: '{pat}'")]
4186    NotFound { pat: String },
4187    #[error("option pattern '{pat}' matches multiple options: {matches:?}")]
4188    Ambiguous { pat: String, matches: Vec<String> },
4189    #[error("invalid option value for '{pat}': {reason}")]
4190    InvalidValue { pat: String, reason: String },
4191}
4192
4193/// Represents a configuration option value, matching pandas `pd.options`.
4194#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
4195pub enum OptionValue {
4196    None,
4197    Int(i64),
4198    Float(f64),
4199    Bool(bool),
4200    Str(String),
4201}
4202
4203impl OptionValue {
4204    #[must_use]
4205    pub const fn is_none(&self) -> bool {
4206        matches!(self, Self::None)
4207    }
4208
4209    #[must_use]
4210    pub const fn as_int(&self) -> Option<i64> {
4211        match self {
4212            Self::Int(i) => Some(*i),
4213            _ => None,
4214        }
4215    }
4216
4217    #[must_use]
4218    pub const fn as_float(&self) -> Option<f64> {
4219        match self {
4220            Self::Float(f) => Some(*f),
4221            _ => None,
4222        }
4223    }
4224
4225    #[must_use]
4226    pub const fn as_bool(&self) -> Option<bool> {
4227        match self {
4228            Self::Bool(b) => Some(*b),
4229            _ => None,
4230        }
4231    }
4232
4233    #[must_use]
4234    pub fn as_str(&self) -> Option<&str> {
4235        match self {
4236            Self::Str(s) => Some(s.as_str()),
4237            _ => None,
4238        }
4239    }
4240}
4241
4242impl std::fmt::Display for OptionValue {
4243    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4244        match self {
4245            Self::None => write!(f, "None"),
4246            Self::Int(i) => write!(f, "{i}"),
4247            Self::Float(fl) => write!(f, "{fl}"),
4248            Self::Bool(b) => write!(f, "{b}"),
4249            Self::Str(s) => write!(f, "{s}"),
4250        }
4251    }
4252}
4253
4254impl From<i64> for OptionValue {
4255    fn from(v: i64) -> Self {
4256        Self::Int(v)
4257    }
4258}
4259
4260impl From<i32> for OptionValue {
4261    fn from(v: i32) -> Self {
4262        Self::Int(i64::from(v))
4263    }
4264}
4265
4266impl From<usize> for OptionValue {
4267    fn from(v: usize) -> Self {
4268        Self::Int(i64::try_from(v).unwrap_or(i64::MAX))
4269    }
4270}
4271
4272impl From<f64> for OptionValue {
4273    fn from(v: f64) -> Self {
4274        Self::Float(v)
4275    }
4276}
4277
4278impl From<bool> for OptionValue {
4279    fn from(v: bool) -> Self {
4280        Self::Bool(v)
4281    }
4282}
4283
4284impl From<&str> for OptionValue {
4285    fn from(v: &str) -> Self {
4286        Self::Str(v.to_string())
4287    }
4288}
4289
4290impl From<String> for OptionValue {
4291    fn from(v: String) -> Self {
4292        Self::Str(v)
4293    }
4294}
4295
4296impl From<()> for OptionValue {
4297    fn from(_: ()) -> Self {
4298        Self::None
4299    }
4300}
4301
4302fn default_options_map() -> std::collections::BTreeMap<String, OptionValue> {
4303    let mut m = std::collections::BTreeMap::new();
4304    m.insert("display.max_rows".to_string(), OptionValue::Int(60));
4305    m.insert("display.min_rows".to_string(), OptionValue::Int(10));
4306    m.insert("display.max_columns".to_string(), OptionValue::Int(0));
4307    m.insert("display.width".to_string(), OptionValue::Int(80));
4308    m.insert("display.precision".to_string(), OptionValue::Int(6));
4309    m.insert("display.max_colwidth".to_string(), OptionValue::Int(50));
4310    m.insert(
4311        "display.show_dimensions".to_string(),
4312        OptionValue::Bool(true),
4313    );
4314    m.insert("display.float_format".to_string(), OptionValue::None);
4315    m.insert(
4316        "display.large_repr".to_string(),
4317        OptionValue::Str("truncate".to_string()),
4318    );
4319    m.insert(
4320        "display.max_info_columns".to_string(),
4321        OptionValue::Int(100),
4322    );
4323    m.insert(
4324        "display.max_info_rows".to_string(),
4325        OptionValue::Int(1690785),
4326    );
4327    m.insert("display.memory_usage".to_string(), OptionValue::Bool(true));
4328    m.insert(
4329        "display.colheader_justify".to_string(),
4330        OptionValue::Str("right".to_string()),
4331    );
4332    m.insert("display.chop_threshold".to_string(), OptionValue::None);
4333    m.insert(
4334        "display.date_dayfirst".to_string(),
4335        OptionValue::Bool(false),
4336    );
4337    m.insert(
4338        "display.date_yearfirst".to_string(),
4339        OptionValue::Bool(false),
4340    );
4341    m.insert(
4342        "display.encoding".to_string(),
4343        OptionValue::Str("utf-8".to_string()),
4344    );
4345    m.insert("mode.sim_interactive".to_string(), OptionValue::Bool(false));
4346    m.insert(
4347        "mode.chained_assignment".to_string(),
4348        OptionValue::Str("warn".to_string()),
4349    );
4350    m.insert("mode.use_inf_as_na".to_string(), OptionValue::Bool(false));
4351    m.insert("mode.copy_on_write".to_string(), OptionValue::Bool(false));
4352    m.insert(
4353        "mode.data_manager".to_string(),
4354        OptionValue::Str("block".to_string()),
4355    );
4356    m.insert(
4357        "compute.use_bottleneck".to_string(),
4358        OptionValue::Bool(true),
4359    );
4360    m.insert("compute.use_numba".to_string(), OptionValue::Bool(false));
4361    m.insert(
4362        "io.excel.zip.reader".to_string(),
4363        OptionValue::Str("zipfile".to_string()),
4364    );
4365    m.insert(
4366        "io.parquet.engine".to_string(),
4367        OptionValue::Str("auto".to_string()),
4368    );
4369    m.insert(
4370        "io.sql.engine".to_string(),
4371        OptionValue::Str("auto".to_string()),
4372    );
4373    m.insert(
4374        "plotting.backend".to_string(),
4375        OptionValue::Str("matplotlib".to_string()),
4376    );
4377    m.insert(
4378        "plotting.matplotlib.register_converters".to_string(),
4379        OptionValue::Bool(true),
4380    );
4381    m
4382}
4383
4384static GLOBAL_OPTIONS: std::sync::LazyLock<
4385    std::sync::Mutex<std::collections::BTreeMap<String, OptionValue>>,
4386> = std::sync::LazyLock::new(|| std::sync::Mutex::new(default_options_map()));
4387
4388fn resolve_option_key(
4389    pat: &str,
4390    map: &std::collections::BTreeMap<String, OptionValue>,
4391) -> Result<String, OptionError> {
4392    if map.contains_key(pat) {
4393        return Ok(pat.to_string());
4394    }
4395    let matches: Vec<String> = map
4396        .keys()
4397        .filter(|k| k.ends_with(pat) || k.contains(pat))
4398        .cloned()
4399        .collect();
4400    if matches.len() == 1 {
4401        Ok(matches[0].clone())
4402    } else if matches.is_empty() {
4403        Err(OptionError::NotFound {
4404            pat: pat.to_string(),
4405        })
4406    } else {
4407        Err(OptionError::Ambiguous {
4408            pat: pat.to_string(),
4409            matches,
4410        })
4411    }
4412}
4413
4414/// Retrieve the current value of a configuration option, matching `pd.get_option(pat)`.
4415///
4416/// # Errors
4417/// Returns [`OptionError::NotFound`] if `pat` does not match any known option,
4418/// or [`OptionError::Ambiguous`] if it matches multiple options.
4419pub fn get_option(pat: &str) -> Result<OptionValue, OptionError> {
4420    let map = GLOBAL_OPTIONS
4421        .lock()
4422        .unwrap_or_else(std::sync::PoisonError::into_inner);
4423    let key = resolve_option_key(pat, &map)?;
4424    Ok(map.get(&key).cloned().unwrap_or(OptionValue::None))
4425}
4426
4427/// Set the value of a configuration option, matching `pd.set_option(pat, value)`.
4428///
4429/// # Errors
4430/// Returns [`OptionError::NotFound`] if `pat` does not match any known option,
4431/// or [`OptionError::Ambiguous`] if it matches multiple options.
4432pub fn set_option(pat: &str, val: impl Into<OptionValue>) -> Result<(), OptionError> {
4433    let mut map = GLOBAL_OPTIONS
4434        .lock()
4435        .unwrap_or_else(std::sync::PoisonError::into_inner);
4436    let key = resolve_option_key(pat, &map)?;
4437    let v = val.into();
4438    map.insert(key, v);
4439    Ok(())
4440}
4441
4442/// Reset one or all configuration options to their defaults, matching `pd.reset_option(pat)`.
4443///
4444/// If `pat` is `None` or `"all"`, all options are reset to defaults.
4445///
4446/// # Errors
4447/// Returns [`OptionError::NotFound`] or [`OptionError::Ambiguous`] if `pat` does not uniquely match an option.
4448pub fn reset_option(pat: Option<&str>) -> Result<(), OptionError> {
4449    let mut map = GLOBAL_OPTIONS
4450        .lock()
4451        .unwrap_or_else(std::sync::PoisonError::into_inner);
4452    let defaults = default_options_map();
4453    let p = pat.unwrap_or("all");
4454    if p == "all" {
4455        *map = defaults;
4456        return Ok(());
4457    }
4458    let key = resolve_option_key(p, &defaults)?;
4459    if let Some(def_val) = defaults.get(&key) {
4460        map.insert(key, def_val.clone());
4461    }
4462    Ok(())
4463}
4464
4465/// Return formatted descriptions of one or all options, matching `pd.describe_option(pat)`.
4466///
4467/// # Errors
4468/// Returns [`OptionError::NotFound`] if `pat` is provided but matches no options.
4469pub fn describe_option(pat: Option<&str>) -> Result<String, OptionError> {
4470    use std::fmt::Write as _;
4471    let map = GLOBAL_OPTIONS
4472        .lock()
4473        .unwrap_or_else(std::sync::PoisonError::into_inner);
4474    let mut out = String::with_capacity(map.len() * 40);
4475    let mut matched = 0;
4476    for (k, v) in map.iter() {
4477        if let Some(p) = pat
4478            && !k.contains(p)
4479        {
4480            continue;
4481        }
4482        if matched > 0 {
4483            out.push('\n');
4484        }
4485        let _ = write!(out, "{k} : [currently: {v}]");
4486        matched += 1;
4487    }
4488    if matched == 0
4489        && let Some(p) = pat
4490    {
4491        return Err(OptionError::NotFound { pat: p.to_string() });
4492    }
4493    Ok(out)
4494}
4495
4496/// RAII scope guard that restores options to their prior values when dropped.
4497#[derive(Debug)]
4498pub struct OptionContextGuard {
4499    saved: Vec<(String, OptionValue)>,
4500}
4501
4502impl Drop for OptionContextGuard {
4503    fn drop(&mut self) {
4504        let mut map = GLOBAL_OPTIONS
4505            .lock()
4506            .unwrap_or_else(std::sync::PoisonError::into_inner);
4507        for (k, old) in self.saved.drain(..) {
4508            map.insert(k, old);
4509        }
4510    }
4511}
4512
4513/// Temporarily override options within a scoped context, matching `pd.option_context(...)`.
4514///
4515/// # Errors
4516/// Returns [`OptionError::NotFound`] or [`OptionError::Ambiguous`] if any pattern is invalid.
4517pub fn option_context(entries: &[(&str, OptionValue)]) -> Result<OptionContextGuard, OptionError> {
4518    let mut map = GLOBAL_OPTIONS
4519        .lock()
4520        .unwrap_or_else(std::sync::PoisonError::into_inner);
4521    let mut saved = Vec::with_capacity(entries.len());
4522    for (pat, new_val) in entries {
4523        let key = resolve_option_key(pat, &map)?;
4524        if let Some(old) = map.get(&key) {
4525            saved.push((key.clone(), old.clone()));
4526        }
4527        map.insert(key, new_val.clone());
4528    }
4529    Ok(OptionContextGuard { saved })
4530}
4531
4532/// Cast a scalar reference to a target dtype (clones only when conversion is needed).
4533pub fn cast_scalar(value: &Scalar, target: DType) -> Result<Scalar, TypeError> {
4534    cast_scalar_owned(value.clone(), target)
4535}
4536
4537// ── Timedelta support ──────────────────────────────────────────────────
4538
4539#[derive(Debug, Error, Clone, PartialEq)]
4540pub enum TimedeltaError {
4541    #[error("invalid timedelta string: {0}")]
4542    InvalidFormat(String),
4543    #[error("overflow in timedelta computation")]
4544    Overflow,
4545}
4546
4547impl TimedeltaError {
4548    /// The pandas exception class this corresponds to, per
4549    /// br-frankenpandas-fyr1z-strict-raise-arms-t7ht2.
4550    ///
4551    /// Returns `None` for [`Self::InvalidFormat`], which is a parse failure
4552    /// rather than a member of the temporal-arithmetic taxonomy.
4553    #[must_use]
4554    pub const fn pandas_error(&self) -> Option<PandasTemporalError> {
4555        match self {
4556            // Probed: pd.Timedelta(float('inf'), 's') raises
4557            // OutOfBoundsTimedelta, NOT a bare OverflowError.
4558            Self::Overflow => Some(PandasTemporalError::OutOfBoundsTimedelta),
4559            Self::InvalidFormat(_) => None,
4560        }
4561    }
4562}
4563
4564#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
4565pub struct CategoricalMetadata {
4566    /// The unique category values, in order.
4567    pub categories: Vec<Scalar>,
4568    /// Whether the categories have a meaningful total ordering.
4569    pub ordered: bool,
4570}
4571
4572impl CategoricalMetadata {
4573    #[must_use]
4574    pub fn new(categories: Vec<Scalar>, ordered: bool) -> Self {
4575        Self {
4576            categories,
4577            ordered,
4578        }
4579    }
4580}
4581
4582#[derive(Debug, Clone, Copy, Default)]
4583pub struct TimedeltaComponents {
4584    pub days: i64,
4585    pub hours: i64,
4586    pub minutes: i64,
4587    pub seconds: i64,
4588    pub milliseconds: i64,
4589    pub microseconds: i64,
4590    pub nanoseconds: i64,
4591}
4592
4593/// The pandas-side exception class a failed temporal operation corresponds to.
4594///
4595/// Introduced by br-frankenpandas-fyr1z-policy-carrier-f29nz and completed by
4596/// fyr1z.3, which established that pandas uses FIVE distinct classes here — so
4597/// a STRICT arm must raise the RIGHT one per op rather than a blanket type.
4598/// Every mapping below was probed against live pandas 2.2.3, not inferred.
4599///
4600/// Named `...TemporalError` rather than `...OverflowError` because
4601/// [`Self::ZeroDivision`] is not an overflow; a type whose name promised
4602/// "overflow" while carrying divide-by-zero would be exactly the kind of stale
4603/// label this codebase keeps having to correct.
4604#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4605pub enum PandasTemporalError {
4606    /// `OverflowError`. e.g. `pd.Timedelta.max + pd.Timedelta('1ns')`, and
4607    /// `Series + Timedelta` / `Series - Series` / `.diff()` which report
4608    /// "Overflow in int64 addition".
4609    Overflow,
4610    /// `OutOfBoundsDatetime`. e.g. `pd.Timestamp.max + pd.Timedelta('1ns')`
4611    /// and `pd.Timestamp.min - pd.Timestamp.max`.
4612    OutOfBoundsDatetime,
4613    /// `OutOfBoundsTimedelta`. Raised by the `pd.Timedelta(value, unit=...)`
4614    /// constructor path (see br-frankenpandas-8v92m), not by the six
4615    /// arithmetic helpers below. Probed: `pd.Timedelta(float('inf'), 's')` ->
4616    /// "Cannot cast inf from s to 'ns' without overflow."
4617    OutOfBoundsTimedelta,
4618    /// `ValueError("overflow in timedelta operation")`. Raised by the
4619    /// REDUCTIONS `Series.sum()` and `Series.std()` over timedelta64.
4620    OverflowInTimedeltaOperation,
4621    /// `ZeroDivisionError`. Raised by SCALAR `Timedelta // 0`, `Timedelta / 0`
4622    /// and `Timedelta // 0.0` ONLY.
4623    ///
4624    /// ⚠ The VECTORIZED division family does NOT raise: probed,
4625    /// `Series([Timedelta]) // 0` and `/ 0` both return NaT. A STRICT arm must
4626    /// not widen this class to the vectorized surface — doing so would create
4627    /// divergence where FrankenPandas is already bit-for-bit correct, which is
4628    /// the central finding of br-frankenpandas-fyr1z (see DISC-018).
4629    ZeroDivision,
4630}
4631
4632/// A temporal overflow, naming the operation that overflowed and the pandas
4633/// exception it corresponds to.
4634#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4635pub struct TemporalFailure {
4636    /// The FrankenPandas operation, e.g. `"Timedelta::add"`.
4637    pub op: &'static str,
4638    /// What pandas raises for this operation.
4639    pub pandas_error: PandasTemporalError,
4640    /// The operand pair whose exact result left the representable range, when
4641    /// the failing operation had one. Carried for the HARDENED audit trail
4642    /// (br-frankenpandas-fyr1z-hardened-audit-vllv6) so a recovery entry can
4643    /// name the range violation rather than merely that one occurred.
4644    pub operands: Option<(i64, i64)>,
4645}
4646
4647impl TemporalFailure {
4648    #[must_use]
4649    pub const fn new(op: &'static str, pandas_error: PandasTemporalError) -> Self {
4650        Self {
4651            op,
4652            pandas_error,
4653            operands: None,
4654        }
4655    }
4656
4657    /// Attach the operands that produced this failure.
4658    #[must_use]
4659    pub const fn with_operands(mut self, lhs: i64, rhs: i64) -> Self {
4660        self.operands = Some((lhs, rhs));
4661        self
4662    }
4663}
4664
4665/// A bounded defensive recovery that HARDENED mode performed, recorded so a run
4666/// can be audited after the fact.
4667///
4668/// br-frankenpandas-fyr1z-hardened-audit-vllv6. AGENTS.md's security doctrine
4669/// requires "deterministic audit logs for recoveries and policy overrides", and
4670/// overflow-to-NaT is exactly a bounded defensive recovery. Until now it was
4671/// SILENT: a caller could not distinguish a NaT produced by an overflow from a
4672/// NaT that was already in the input, which is the whole substance of the
4673/// DISC-018 impact statement.
4674#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4675pub struct TemporalRecovery {
4676    /// The operation that overflowed.
4677    pub op: &'static str,
4678    /// The pandas exception this would have been under STRICT.
4679    pub pandas_error: PandasTemporalError,
4680    /// The operands whose exact result was unrepresentable, when known.
4681    pub operands: Option<(i64, i64)>,
4682    /// The value actually returned. Always the family's NaT sentinel today.
4683    pub recovered_as: i64,
4684}
4685
4686/// Deterministic, opt-in audit trail for HARDENED-mode recoveries.
4687///
4688/// Disabled by default and costs one `Option` check when off, so the default
4689/// path is unchanged. The log is THREAD-LOCAL: FrankenPandas parallelises many
4690/// kernels, and a shared log would impose a lock on hot arithmetic and make the
4691/// entry ORDER nondeterministic — which would defeat the point. Each worker
4692/// therefore accumulates its own deterministic sequence; a caller auditing a
4693/// parallel op drains per thread.
4694pub mod overflow_audit {
4695    use std::cell::RefCell;
4696
4697    use super::TemporalRecovery;
4698
4699    thread_local! {
4700        static LOG: RefCell<Option<Vec<TemporalRecovery>>> = const { RefCell::new(None) };
4701    }
4702
4703    /// Begin recording on THIS thread, discarding anything already buffered.
4704    pub fn enable() {
4705        LOG.with(|log| *log.borrow_mut() = Some(Vec::new()));
4706    }
4707
4708    /// Stop recording on this thread and discard the buffer.
4709    pub fn disable() {
4710        LOG.with(|log| *log.borrow_mut() = None);
4711    }
4712
4713    /// Whether recording is active on this thread.
4714    #[must_use]
4715    pub fn is_enabled() -> bool {
4716        LOG.with(|log| log.borrow().is_some())
4717    }
4718
4719    /// Take the recorded recoveries, leaving recording enabled and empty.
4720    #[must_use]
4721    pub fn drain() -> Vec<TemporalRecovery> {
4722        LOG.with(|log| match log.borrow_mut().as_mut() {
4723            Some(entries) => std::mem::take(entries),
4724            None => Vec::new(),
4725        })
4726    }
4727
4728    /// Record a recovery. A no-op — and allocation-free — when disabled.
4729    pub(super) fn record(entry: TemporalRecovery) {
4730        LOG.with(|log| {
4731            if let Some(entries) = log.borrow_mut().as_mut() {
4732                entries.push(entry);
4733            }
4734        });
4735    }
4736}
4737
4738/// How a temporal overflow should be surfaced.
4739///
4740/// br-frankenpandas-fyr1z-policy-carrier-f29nz adds this carrier WITHOUT
4741/// changing any default behavior: every existing call site is on
4742/// [`OverflowPolicy::SurfaceNat`], which is exactly what the codebase did
4743/// before. `Strict` exists so fyr1z.3 can wire per-op raise arms in a separate,
4744/// reviewable step, and NOTHING routes to it yet.
4745///
4746/// Note DISC-018: a blanket "STRICT raises everywhere" is NOT pandas parity —
4747/// pandas silently wraps on `Series * int` and `.cumsum()`, and returns NaT for
4748/// `.mean()`. The strict arm therefore needs a per-op table, which is why the
4749/// policy is carried per operation rather than set globally.
4750#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
4751pub enum OverflowPolicy {
4752    /// Today's behavior, and the only arm currently wired up: overflow becomes
4753    /// the family's NaT sentinel.
4754    #[default]
4755    SurfaceNat,
4756    /// Reserved for fyr1z.3. Surfaces the [`TemporalFailure`] to the caller.
4757    Strict,
4758    /// HARDENED mode (br-frankenpandas-fyr1z-hardened-audit-vllv6): returns the
4759    /// SAME NaT as [`Self::SurfaceNat`], bit-for-bit, and additionally records a
4760    /// [`TemporalRecovery`] into [`overflow_audit`] when that log is enabled.
4761    ///
4762    /// This adds observability, never semantics. AGENTS.md defines hardened
4763    /// mode as "bounded defensive recovery" and requires a deterministic audit
4764    /// log for exactly that.
4765    HardenedNat,
4766}
4767
4768impl OverflowPolicy {
4769    /// Resolve a fallible temporal result under this policy.
4770    ///
4771    /// `SurfaceNat` discards the overflow and yields `nat`, reproducing the
4772    /// pre-f29nz behavior bit-for-bit. `Strict` propagates the overflow.
4773    ///
4774    /// # Errors
4775    /// Returns the [`TemporalFailure`] unchanged under [`Self::Strict`].
4776    pub fn resolve<T>(
4777        self,
4778        outcome: Result<T, TemporalFailure>,
4779        nat: T,
4780    ) -> Result<T, TemporalFailure> {
4781        self.resolve_recording(outcome, nat, i64::MIN)
4782    }
4783
4784    /// [`Self::resolve`] plus the sentinel value to record in the audit trail.
4785    ///
4786    /// Split out because the recovered value is generic (`T`) but the audit
4787    /// entry needs its i64 backing; `recovered_as` supplies that without
4788    /// constraining `T`.
4789    ///
4790    /// # Errors
4791    /// Returns the [`TemporalFailure`] unchanged under [`Self::Strict`].
4792    pub fn resolve_recording<T>(
4793        self,
4794        outcome: Result<T, TemporalFailure>,
4795        nat: T,
4796        recovered_as: i64,
4797    ) -> Result<T, TemporalFailure> {
4798        match (self, outcome) {
4799            (_, Ok(value)) => Ok(value),
4800            (Self::SurfaceNat, Err(_)) => Ok(nat),
4801            (Self::Strict, Err(failure)) => Err(failure),
4802            (Self::HardenedNat, Err(failure)) => {
4803                // Same value as SurfaceNat; the ONLY difference is the record.
4804                overflow_audit::record(TemporalRecovery {
4805                    op: failure.op,
4806                    pandas_error: failure.pandas_error,
4807                    operands: failure.operands,
4808                    recovered_as,
4809                });
4810                Ok(nat)
4811            }
4812        }
4813    }
4814}
4815
4816pub struct Timedelta;
4817
4818impl Timedelta {
4819    pub const NANOS_PER_MICRO: i64 = 1_000;
4820    pub const NANOS_PER_MILLI: i64 = 1_000_000;
4821    pub const NANOS_PER_SEC: i64 = 1_000_000_000;
4822    pub const NANOS_PER_MIN: i64 = 60 * Self::NANOS_PER_SEC;
4823    pub const NANOS_PER_HOUR: i64 = 60 * Self::NANOS_PER_MIN;
4824    pub const NANOS_PER_DAY: i64 = 24 * Self::NANOS_PER_HOUR;
4825    pub const NANOS_PER_WEEK: i64 = 7 * Self::NANOS_PER_DAY;
4826
4827    pub const NAT: i64 = i64::MIN;
4828
4829    pub fn parse(s: &str) -> Result<i64, TimedeltaError> {
4830        let s = s.trim();
4831
4832        if s.eq_ignore_ascii_case("nat") {
4833            return Ok(Self::NAT);
4834        }
4835
4836        let (negative, s) = if let Some(rest) = s.strip_prefix('-') {
4837            (true, rest.trim())
4838        } else {
4839            (false, s)
4840        };
4841
4842        if let Some(nanos) = Self::try_parse_time_format(s) {
4843            return Ok(if negative { -nanos } else { nanos });
4844        }
4845
4846        if let Some(nanos) = Self::try_parse_iso8601_duration(s) {
4847            return Ok(if negative { -nanos } else { nanos });
4848        }
4849
4850        // pandas' leading '-' negates the unit values but not an HH:MM:SS
4851        // part that follows one: "-1 days +02:03:04" (how pandas prints a
4852        // negative Timedelta) is -1 day + 2:03:04. Negating the whole
4853        // compound read it as -(1 day 2:03:04), so a printed Timedelta did
4854        // not parse back to itself.
4855        let (units, clock) = Self::parse_compound(s)?;
4856        let units = if negative { -units } else { units };
4857        units.checked_add(clock).ok_or(TimedeltaError::Overflow)
4858    }
4859
4860    /// Parse an ISO-8601 duration the way pandas `Timedelta` accepts it:
4861    /// a leading uppercase `P`, an optional `T` separator that is otherwise
4862    /// ignored, and unit letters `W`/`D`/`H`/`M`/`S` in any position. `M` is
4863    /// always MINUTES (never months), and only seconds may be fractional —
4864    /// years/months and lowercase units are rejected, matching pandas.
4865    /// (pandas mis-handles fractional non-second components; those are rejected
4866    /// here rather than reproducing the buggy value.) (br-frankenpandas-c3p8b)
4867    fn try_parse_iso8601_duration(s: &str) -> Option<i64> {
4868        let mut rest = s.strip_prefix('P')?;
4869        if rest.is_empty() {
4870            return None;
4871        }
4872        let mut total: i64 = 0;
4873        let mut saw_component = false;
4874        while !rest.is_empty() {
4875            if let Some(after_t) = rest.strip_prefix('T') {
4876                rest = after_t;
4877                continue;
4878            }
4879            let num_end = rest.find(|c: char| !c.is_ascii_digit() && c != '.')?;
4880            if num_end == 0 {
4881                return None;
4882            }
4883            let num_str = &rest[..num_end];
4884            let unit = rest.as_bytes()[num_end];
4885            let is_fractional = num_str.contains('.');
4886            rest = &rest[num_end + 1..];
4887
4888            let (multiplier, frac_ok) = match unit {
4889                b'W' => (Self::NANOS_PER_WEEK, false),
4890                b'D' => (Self::NANOS_PER_DAY, false),
4891                b'H' => (Self::NANOS_PER_HOUR, false),
4892                b'M' => (Self::NANOS_PER_MIN, false),
4893                b'S' => (Self::NANOS_PER_SEC, true),
4894                _ => return None,
4895            };
4896            if is_fractional {
4897                if !frac_ok {
4898                    return None;
4899                }
4900                let value: f64 = num_str.parse().ok()?;
4901                let product = value * multiplier as f64;
4902                if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
4903                    return None;
4904                }
4905                total = total.checked_add(product.round() as i64)?;
4906            } else {
4907                let value: i64 = num_str.parse().ok()?;
4908                total = total.checked_add(value.checked_mul(multiplier)?)?;
4909            }
4910            saw_component = true;
4911        }
4912        saw_component.then_some(total)
4913    }
4914
4915    fn try_parse_time_format(s: &str) -> Option<i64> {
4916        let parts: Vec<&str> = s.split(':').collect();
4917        if parts.len() < 2 || parts.len() > 3 {
4918            return None;
4919        }
4920
4921        let hours: i64 = parts[0].parse().ok()?;
4922        let minutes: i64 = parts[1].parse().ok()?;
4923
4924        let (seconds, frac_nanos) = if parts.len() == 3 {
4925            if let Some((sec_str, frac_str)) = parts[2].split_once('.') {
4926                let sec: i64 = sec_str.parse().ok()?;
4927                if !frac_str.bytes().all(|byte| byte.is_ascii_digit()) {
4928                    return None;
4929                }
4930                let mut frac = 0_i64;
4931                let taken = frac_str.len().min(9);
4932                for byte in frac_str.bytes().take(9) {
4933                    frac = frac * 10 + i64::from(byte - b'0');
4934                }
4935                for _ in taken..9 {
4936                    frac *= 10;
4937                }
4938                (sec, frac)
4939            } else {
4940                let sec: i64 = parts[2].parse().ok()?;
4941                (sec, 0)
4942            }
4943        } else {
4944            (0, 0)
4945        };
4946
4947        hours
4948            .checked_mul(Self::NANOS_PER_HOUR)?
4949            .checked_add(minutes.checked_mul(Self::NANOS_PER_MIN)?)?
4950            .checked_add(seconds.checked_mul(Self::NANOS_PER_SEC)?)?
4951            .checked_add(frac_nanos)
4952    }
4953
4954    /// The number-and-unit values of a compound Timedelta string, and the
4955    /// HH:MM:SS part that may end it (which the leading sign does not
4956    /// negate; see [`Self::parse`]). A sign inside the string is pandas'
4957    /// "only leading negative signs are allowed" error ("1 days -02:00:00"
4958    /// read as 22 hours).
4959    fn parse_compound(s: &str) -> Result<(i64, i64), TimedeltaError> {
4960        let mut total: i64 = 0;
4961        let mut clock: i64 = 0;
4962        let mut remaining = s;
4963
4964        while !remaining.is_empty() {
4965            remaining = remaining.trim_start();
4966            if remaining.is_empty() {
4967                break;
4968            }
4969            if remaining.starts_with('-') {
4970                return Err(TimedeltaError::InvalidFormat(format!(
4971                    "only leading negative signs are allowed: {s}"
4972                )));
4973            }
4974
4975            // Per br-frankenpandas-i9bah: check if remaining is a time format
4976            // (HH:MM:SS) which can appear after "N days " in pandas timedelta strings.
4977            if remaining.contains(':')
4978                && let Some(time_nanos) = Self::try_parse_time_format(remaining)
4979            {
4980                clock = time_nanos;
4981                break;
4982            }
4983
4984            let num_end = remaining
4985                .find(|c: char| !c.is_ascii_digit() && c != '.' && c != '-')
4986                .unwrap_or(remaining.len());
4987
4988            if num_end == 0 {
4989                return Err(TimedeltaError::InvalidFormat(s.to_string()));
4990            }
4991
4992            let num_str = &remaining[..num_end];
4993            let num: f64 = num_str
4994                .parse()
4995                .map_err(|_| TimedeltaError::InvalidFormat(s.to_string()))?;
4996
4997            remaining = remaining[num_end..].trim_start();
4998
4999            let unit_end = remaining
5000                .find(|c: char| c.is_ascii_digit() || c.is_whitespace())
5001                .unwrap_or(remaining.len());
5002
5003            let unit = &remaining[..unit_end];
5004            remaining = &remaining[unit_end..];
5005
5006            let multiplier = Self::unit_to_nanos(unit)
5007                .ok_or_else(|| TimedeltaError::InvalidFormat(s.to_string()))?;
5008
5009            // Per br-frankenpandas-zw3mg: pandas raises OverflowError on
5010            // huge scientific-notation Timedeltas like "1e100 days". The
5011            // raw `as i64` cast silently saturated to i64::MAX, masking
5012            // overflow before checked_add could catch it.
5013            let product = num * multiplier as f64;
5014            if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
5015                return Err(TimedeltaError::Overflow);
5016            }
5017            let nanos = product.round() as i64;
5018            total = total.checked_add(nanos).ok_or(TimedeltaError::Overflow)?;
5019        }
5020
5021        // NOTE: there is deliberately no "total == 0 is suspicious" guard here.
5022        // One used to live at this spot and rejected every legitimately-zero
5023        // compound -- `to_timedelta("0 seconds")` raised while `"1 second"` and
5024        // `"10 seconds"` parsed, because the only exemption was the literal
5025        // string "0". pandas 2.2.3 accepts all of `0 seconds` / `0 days` / `0s`
5026        // / `0.0 hours` / `-0 seconds` as a zero Timedelta. The guard was also
5027        // unnecessary: the loop above returns `InvalidFormat` on an unparseable
5028        // number AND on an unknown unit, so the only way to reach here with
5029        // `total == 0` is an input whose components genuinely sum to zero.
5030        Ok((total, clock))
5031    }
5032
5033    /// Map a pandas-style frequency-alias string to a nanosecond-count.
5034    ///
5035    /// Recognizes pandas's offset alias core set plus common word forms:
5036    /// W/week(s), D/day(s), H/hr/hour(s), m/T/min/minute(s), s/sec/second(s),
5037    /// ms/milli/millisecond(s)/L, us/µs/micro/microsecond(s)/U, ns/nano/
5038    /// nanosecond(s)/N. Empty string maps to days (matches pandas default).
5039    /// Returns `None` for unrecognized aliases — callers can choose to map
5040    /// that to NaT (consistent with the rest of fp-types) or surface as a
5041    /// typed error.
5042    ///
5043    /// Per br-frankenpandas-lbsx (9p0u Phase 2.6): public surface so
5044    /// downstream crates can consume the same alias map fp-types uses for
5045    /// `Timedelta::from_unit` / `Timestamp::*_to_unit`.
5046    #[must_use]
5047    pub fn unit_to_nanos(unit: &str) -> Option<i64> {
5048        match unit.to_lowercase().as_str() {
5049            "w" | "week" | "weeks" => Some(Self::NANOS_PER_WEEK),
5050            "d" | "day" | "days" => Some(Self::NANOS_PER_DAY),
5051            "h" | "hr" | "hour" | "hours" => Some(Self::NANOS_PER_HOUR),
5052            "m" | "min" | "minute" | "minutes" | "t" => Some(Self::NANOS_PER_MIN),
5053            "s" | "sec" | "second" | "seconds" => Some(Self::NANOS_PER_SEC),
5054            "ms" | "milli" | "millis" | "millisecond" | "milliseconds" | "l" => {
5055                Some(Self::NANOS_PER_MILLI)
5056            }
5057            "us" | "µs" | "micro" | "micros" | "microsecond" | "microseconds" | "u" => {
5058                Some(Self::NANOS_PER_MICRO)
5059            }
5060            "ns" | "nano" | "nanos" | "nanosecond" | "nanoseconds" | "n" => Some(1),
5061            "" => Some(Self::NANOS_PER_DAY),
5062            _ => None,
5063        }
5064    }
5065
5066    pub fn components(nanos: i64) -> TimedeltaComponents {
5067        if nanos == Self::NAT {
5068            return TimedeltaComponents::default();
5069        }
5070
5071        // pandas/Python normalize via FLOOR division (like format()): the days
5072        // component can be negative while the time-of-day remainder is always in
5073        // [0, 1 day). So pd.Timedelta(-1,'s').components == (-1, 23, 59, 59, 0, 0, 0),
5074        // NOT the abs-based (0, 0, 0, 1, 0, 0, 0).
5075        let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5076        let rem = nanos.rem_euclid(Self::NANOS_PER_DAY);
5077
5078        let hours = rem / Self::NANOS_PER_HOUR;
5079        let rem = rem % Self::NANOS_PER_HOUR;
5080
5081        let minutes = rem / Self::NANOS_PER_MIN;
5082        let rem = rem % Self::NANOS_PER_MIN;
5083
5084        let seconds = rem / Self::NANOS_PER_SEC;
5085        let rem = rem % Self::NANOS_PER_SEC;
5086
5087        let milliseconds = rem / Self::NANOS_PER_MILLI;
5088        let rem = rem % Self::NANOS_PER_MILLI;
5089
5090        let microseconds = rem / Self::NANOS_PER_MICRO;
5091        let nanoseconds = rem % Self::NANOS_PER_MICRO;
5092
5093        TimedeltaComponents {
5094            days,
5095            hours,
5096            minutes,
5097            seconds,
5098            milliseconds,
5099            microseconds,
5100            nanoseconds,
5101        }
5102    }
5103
5104    pub fn total_seconds(nanos: i64) -> f64 {
5105        if nanos == Self::NAT {
5106            f64::NAN
5107        } else {
5108            nanos as f64 / Self::NANOS_PER_SEC as f64
5109        }
5110    }
5111
5112    /// Convert to specified time unit.
5113    ///
5114    /// Matches pd.Timedelta.as_unit(). Supported units: ns, us, ms, s, m, h, D.
5115    #[must_use]
5116    pub fn as_unit(nanos: i64, unit: &str) -> f64 {
5117        if nanos == Self::NAT {
5118            return f64::NAN;
5119        }
5120        let nanos_f = nanos as f64;
5121        match unit {
5122            "ns" | "nanoseconds" => nanos_f,
5123            "us" | "microseconds" => nanos_f / Self::NANOS_PER_MICRO as f64,
5124            "ms" | "milliseconds" => nanos_f / Self::NANOS_PER_MILLI as f64,
5125            "s" | "seconds" => nanos_f / Self::NANOS_PER_SEC as f64,
5126            "m" | "minutes" => nanos_f / Self::NANOS_PER_MIN as f64,
5127            "h" | "hours" => nanos_f / Self::NANOS_PER_HOUR as f64,
5128            "D" | "days" => nanos_f / Self::NANOS_PER_DAY as f64,
5129            _ => f64::NAN,
5130        }
5131    }
5132
5133    /// Return the days component, or `None` for `NaT`. Matches
5134    /// `pd.Timedelta.days`.
5135    ///
5136    /// ⚠️ `None`, NOT `0`, AND THE TYPE IS THE FIX
5137    /// (br-frankenpandas-timedelta-nat-days-returns-zero-406ni). All four
5138    /// component helpers used to return `0` for `NaT`, one of them behind a
5139    /// comment asserting "pandas returns 0 for NaT.days (no error)". MEASURED,
5140    /// live pandas 2.2.3: `pd.NaT.days` is **nan**, and
5141    /// `pd.to_timedelta([1, None, -1], unit='s').dt.days` is float64
5142    /// `[0.0, nan, -1.0]` — pandas promotes the whole column because NaN cannot
5143    /// live in int64.
5144    ///
5145    /// An `i64` return cannot express that, so correctness depended on every
5146    /// caller remembering to test `NAT` first. It did — `timedelta_component`
5147    /// checked in three separate arms — but that is a convention, and the bead
5148    /// filed it as a landmine for the next person to wire a `.dt` accessor: a
5149    /// function whose doc says "matches pandas" handing back a plausible integer
5150    /// where pandas has a missing value. `Option<i64>` moves the fact into the
5151    /// type, so a caller cannot forget and the duplicated `NAT` tests go away.
5152    #[must_use]
5153    pub fn days(nanos: i64) -> Option<i64> {
5154        if nanos == Self::NAT {
5155            return None;
5156        }
5157        // FLOOR division like pandas: pd.Timedelta(-1,'s').days == -1, not 0.
5158        Some(nanos.div_euclid(Self::NANOS_PER_DAY))
5159    }
5160
5161    /// Return the seconds component (0-86399), or `None` for `NaT`. Matches
5162    /// `pd.Timedelta.seconds`. See [`Self::days`] for why this is an `Option`.
5163    #[must_use]
5164    pub fn seconds(nanos: i64) -> Option<i64> {
5165        if nanos == Self::NAT {
5166            return None;
5167        }
5168        // Floor-normalized time-of-day remainder: pd.Timedelta(-1,'s').seconds == 86399.
5169        Some(nanos.rem_euclid(Self::NANOS_PER_DAY) / Self::NANOS_PER_SEC)
5170    }
5171
5172    /// Return the microseconds component (0-999999), or `None` for `NaT`.
5173    /// Matches `pd.Timedelta.microseconds`. See [`Self::days`].
5174    #[must_use]
5175    pub fn microseconds(nanos: i64) -> Option<i64> {
5176        if nanos == Self::NAT {
5177            return None;
5178        }
5179        Some(nanos.rem_euclid(Self::NANOS_PER_SEC) / Self::NANOS_PER_MICRO)
5180    }
5181
5182    /// Return the nanoseconds component (0-999), or `None` for `NaT`. Matches
5183    /// `pd.Timedelta.nanoseconds`. See [`Self::days`].
5184    #[must_use]
5185    pub fn nanoseconds(nanos: i64) -> Option<i64> {
5186        if nanos == Self::NAT {
5187            return None;
5188        }
5189        Some(nanos.rem_euclid(Self::NANOS_PER_MICRO))
5190    }
5191
5192    /// The coarsest [`TimedeltaStringResolution`] that renders `nanos`
5193    /// losslessly. Fold over a column with `max`.
5194    ///
5195    /// `NaT` reports `Days`, the identity of that fold, because pandas excludes
5196    /// it from the scan: `[1 days, NaT]` still renders `['1 days', 'NaT']`.
5197    #[must_use]
5198    pub const fn string_resolution(nanos: i64) -> TimedeltaStringResolution {
5199        if nanos == Self::NAT || nanos.rem_euclid(Self::NANOS_PER_DAY) == 0 {
5200            TimedeltaStringResolution::Days
5201        } else {
5202            TimedeltaStringResolution::Full
5203        }
5204    }
5205
5206    /// Render `nanos` the way `astype(str)` does, at a resolution chosen for the
5207    /// whole column by [`Self::string_resolution`].
5208    ///
5209    /// The `Full` arm is [`Self::format`] verbatim — the per-value sub-second
5210    /// width was already right. Only the `Days` arm is new, and it exists
5211    /// because a column of whole days drops its time part completely:
5212    /// `'1 days'`, not `'1 days 00:00:00'`.
5213    #[must_use]
5214    pub fn format_at_resolution(nanos: i64, resolution: TimedeltaStringResolution) -> String {
5215        if nanos == Self::NAT {
5216            return "NaT".to_string();
5217        }
5218        match resolution {
5219            TimedeltaStringResolution::Full => Self::format(nanos),
5220            // Euclidean division, so a negative whole-day value keeps pandas'
5221            // spelling: -2 days is "-2 days", never "-1 days -24:00:00".
5222            TimedeltaStringResolution::Days => {
5223                format!("{} days", nanos.div_euclid(Self::NANOS_PER_DAY))
5224            }
5225        }
5226    }
5227
5228    pub fn format(nanos: i64) -> String {
5229        use std::fmt::Write as _;
5230
5231        if nanos == Self::NAT {
5232            return "NaT".to_string();
5233        }
5234
5235        // pandas / Python timedelta normalize via FLOOR division: the days
5236        // component can be negative while the time-of-day remainder is always
5237        // non-negative, and a negative-days value prints a '+' before the time
5238        // (e.g. -1s -> "-1 days +23:59:59", not "-0 days 00:00:01"). Compute the
5239        // components with Euclidean div/rem so the remainder is in [0, 1 day).
5240        let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5241        let rem = nanos.rem_euclid(Self::NANOS_PER_DAY);
5242        let hours = rem / Self::NANOS_PER_HOUR;
5243        let minutes = (rem % Self::NANOS_PER_HOUR) / Self::NANOS_PER_MIN;
5244        let seconds = (rem % Self::NANOS_PER_MIN) / Self::NANOS_PER_SEC;
5245        let frac = rem % Self::NANOS_PER_SEC;
5246
5247        // Build directly into the returned allocation. The former path first
5248        // allocated an `HH:MM:SS` string, then copied it into the result.
5249        let mut result = String::with_capacity(32);
5250        let _ = write!(result, "{days} days ");
5251        // '+' joins the negative day count to the positive time remainder.
5252        if days < 0 {
5253            result.push('+');
5254        }
5255        let _ = write!(result, "{hours:02}:{minutes:02}:{seconds:02}");
5256        if frac > 0 {
5257            // pandas renders the sub-second part with microsecond precision
5258            // (6 digits) unless a sub-microsecond (nanosecond) component is
5259            // present, in which case it widens to 9 digits.
5260            if frac % 1_000 == 0 {
5261                let _ = write!(result, ".{:06}", frac / 1_000);
5262            } else {
5263                let _ = write!(result, ".{frac:09}");
5264            }
5265        }
5266        result
5267    }
5268
5269    /// Build a nanosecond Timedelta from a float quantity of `unit`.
5270    ///
5271    /// Matches `pd.Timedelta(value, unit=...)`:
5272    /// - `NaN` → `NAT`. pandas returns `NaT`, and `NAT` is how NaT is spelled
5273    ///   in this i64 representation. Rust's float→int `as` maps `NaN` to
5274    ///   **0**, so the unguarded cast used to hand back a ZERO DURATION for a
5275    ///   missing value (br-frankenpandas-8v92m).
5276    /// - non-finite or out-of-range product → [`TimedeltaError::Overflow`].
5277    ///   pandas raises `OutOfBoundsTimedelta` ("Cannot cast inf from s to 'ns'
5278    ///   without overflow"); the `as` cast used to SATURATE to `i64::MAX`,
5279    ///   returning a finite, plausible ~106751-day duration instead.
5280    /// - unknown unit → [`TimedeltaError::InvalidFormat`], unchanged.
5281    ///
5282    /// The overflow guard is the same one `parse` and the component parser
5283    /// already use (added by br-frankenpandas-zw3mg, which fixed two of the
5284    /// three sites sharing this expression and missed this one).
5285    pub fn from_unit(value: f64, unit: &str) -> Result<i64, TimedeltaError> {
5286        let multiplier = Self::unit_to_nanos(unit)
5287            .ok_or_else(|| TimedeltaError::InvalidFormat(unit.to_string()))?;
5288        if value.is_nan() {
5289            return Ok(Self::NAT);
5290        }
5291        let product = value * multiplier as f64;
5292        if !product.is_finite() || product.abs() >= 9223372036854775808.0 {
5293            return Err(TimedeltaError::Overflow);
5294        }
5295        Ok(product.round() as i64)
5296    }
5297
5298    // ── Arithmetic (br-frankenpandas-4r56 Phase 1) ──────────────────────
5299    //
5300    // NaT propagation: any arithmetic with `NAT` returns `NAT`. Matches
5301    // pandas `pd.NaT + anything == NaT`, `pd.NaT - anything == NaT`, etc.
5302    //
5303    // Overflow (br-frankenpandas-lgyy8): i64 overflow yields `NAT` in BOTH
5304    // directions. It never wraps and never fabricates a finite value.
5305    //
5306    // These previously used `saturating_*`, which was asymmetric and failed
5307    // OPEN on one side. Because `NAT == i64::MIN`, negative overflow clamped
5308    // onto the sentinel and already surfaced as missing — but POSITIVE
5309    // overflow clamped to `i64::MAX`, a perfectly valid, finite, plausible
5310    // duration (and, for `Timestamp`, a ~year-2262 instant) returned as if it
5311    // were real data. Live pandas 2.2.3 never does that, in either the scalar
5312    // or the vectorized path:
5313    //
5314    //   pd.Timedelta.min + Timedelta('-1ns')      -> NaT  (lands on the sentinel)
5315    //   pd.Series[datetime64] + Timedelta('-1ns') -> [NaT, ...]
5316    //   pd.Timedelta.max + Timedelta('1ns')       -> raises OverflowError
5317    //   pd.Timestamp.max + Timedelta('1ns')       -> raises OutOfBoundsDatetime
5318    //   pd.Series[datetime64] + Timedelta('1ns')  -> raises OverflowError
5319    //   pd.Timestamp.min - pd.Timestamp.max       -> raises OutOfBoundsDatetime
5320    //   pd.Timedelta.max * 2                      -> raises OverflowError
5321    //
5322    // We surface NaT where pandas raises, rather than making these infallible
5323    // `#[must_use]` helpers fallible: that is the SAME documented divergence
5324    // `div_scalar` already takes for divide-by-zero ("matches pandas, which
5325    // raises, but we surface as NaT to avoid panics at the type-system
5326    // boundary"). Every input whose exact result is representable is
5327    // unaffected bit-for-bit; only overflow moves.
5328
5329    /// Add two Timedelta nanosecond values, reporting overflow.
5330    ///
5331    /// br-frankenpandas-fyr1z-policy-carrier-f29nz. NaT propagation is NOT an
5332    /// overflow — a NaT operand yields `Ok(NAT)`, exactly as before. Only an
5333    /// unrepresentable result is an `Err`.
5334    ///
5335    /// # Errors
5336    /// [`PandasTemporalError::Overflow`] when the sum exceeds i64.
5337    pub fn try_add(a: i64, b: i64) -> Result<i64, TemporalFailure> {
5338        if a == Self::NAT || b == Self::NAT {
5339            return Ok(Self::NAT);
5340        }
5341        a.checked_add(b).ok_or(
5342            TemporalFailure::new("Timedelta::add", PandasTemporalError::Overflow)
5343                .with_operands(a, b),
5344        )
5345    }
5346
5347    /// Add two Timedelta nanosecond values. NaT propagates; overflow → NaT.
5348    #[must_use]
5349    pub fn add(a: i64, b: i64) -> i64 {
5350        Self::try_add(a, b).unwrap_or(Self::NAT)
5351    }
5352
5353    /// Subtract two Timedelta nanosecond values, reporting overflow.
5354    ///
5355    /// # Errors
5356    /// [`PandasTemporalError::Overflow`] when the difference exceeds i64.
5357    pub fn try_sub(a: i64, b: i64) -> Result<i64, TemporalFailure> {
5358        if a == Self::NAT || b == Self::NAT {
5359            return Ok(Self::NAT);
5360        }
5361        a.checked_sub(b).ok_or(
5362            TemporalFailure::new("Timedelta::sub", PandasTemporalError::Overflow)
5363                .with_operands(a, b),
5364        )
5365    }
5366
5367    /// Subtract two Timedelta nanosecond values. NaT propagates; overflow → NaT.
5368    #[must_use]
5369    pub fn sub(a: i64, b: i64) -> i64 {
5370        Self::try_sub(a, b).unwrap_or(Self::NAT)
5371    }
5372
5373    /// Negate a Timedelta value. NaT stays NaT.
5374    ///
5375    /// There is no overflow case to handle, and the `saturating_` call is a
5376    /// belt-and-braces no-op: the only `i64` whose negation overflows is
5377    /// `i64::MIN`, and `i64::MIN` IS the NaT sentinel, so it is consumed by
5378    /// the guard above. The representable range is `[i64::MIN + 1, i64::MAX]`,
5379    /// which is symmetric about zero.
5380    ///
5381    /// CORRECTED br-frankenpandas-fyr1z: this used to claim "pandas:
5382    /// `-pd.Timedelta.min` is NaT since min == -max - 1 cannot be negated".
5383    /// That is false in both halves. pandas' `Timedelta.min.value` is
5384    /// `-9223372036854775807` == `-Timedelta.max.value`, NOT `-max - 1`
5385    /// (`-max - 1` is `i64::MIN`, which pandas also reserves for NaT), and
5386    /// live pandas 2.2.3 returns `Timedelta('106751 days 23:47:16.854775807')`
5387    /// — i.e. `Timedelta.max` — for `-pd.Timedelta.min`, `abs(pd.Timedelta
5388    /// .min)`, and the vectorized `-Series[timedelta64]` / `.abs()` forms.
5389    /// Do not "fix" this to return NaT; that would be the parity regression.
5390    #[must_use]
5391    pub fn neg(a: i64) -> i64 {
5392        if a == Self::NAT {
5393            return Self::NAT;
5394        }
5395        a.saturating_neg()
5396    }
5397
5398    /// Absolute value of a Timedelta. NaT stays NaT.
5399    ///
5400    /// As with [`Timedelta::neg`], no overflow is reachable: `i64::MIN` is the
5401    /// NaT sentinel and is consumed by the guard, and `|i64::MIN + 1|` is
5402    /// exactly `i64::MAX`. pandas agrees — `abs(pd.Timedelta.min)` is
5403    /// `Timedelta.max`, not NaT.
5404    #[must_use]
5405    pub fn abs(a: i64) -> i64 {
5406        if a == Self::NAT {
5407            return Self::NAT;
5408        }
5409        a.saturating_abs()
5410    }
5411
5412    /// Multiply a Timedelta value by an integer factor. NaT propagates;
5413    /// overflow → NaT (see the overflow note above).
5414    ///
5415    /// Matches pandas `pd.Timedelta(...) * int`, which raises `OverflowError`
5416    /// rather than returning a saturated duration.
5417    #[must_use]
5418    pub fn mul_scalar(a: i64, factor: i64) -> i64 {
5419        Self::try_mul_scalar(a, factor).unwrap_or(Self::NAT)
5420    }
5421
5422    /// Multiply a Timedelta by an integer factor under an explicit policy.
5423    ///
5424    /// br-frankenpandas-fyr1z-wrap-signoff-s4lkx, DECIDED BY THE MAINTAINER:
5425    /// **STRICT REPRODUCES PANDAS' SILENT WRAP.** The rationale is that this is
5426    /// a PORT — STRICT means bit-for-bit observable parity with the incumbent
5427    /// *including its quirks*, so the wrap is a deliberately reproduced pandas
5428    /// behaviour, not a defect of ours.
5429    ///
5430    /// Verified against live pandas 2.2.3: `Series([Timedelta.max]) * 2` returns
5431    /// `-2` ns (displayed `-1 days +23:59:59.999999998`), which is exactly
5432    /// `i64::MAX.wrapping_mul(2)`. Rust's wrapping arithmetic reproduces numpy's
5433    /// int64 wraparound bit-for-bit, so no emulation is needed.
5434    ///
5435    /// The wrap is INTEGER-MULTIPLIER ONLY: `Series * 2.0` returns NaT in
5436    /// pandas, so a float multiplier must not route here.
5437    ///
5438    /// Every other policy keeps today's behaviour — NaT, with HARDENED also
5439    /// recording the recovery. So the fail-open shape br-frankenpandas-lgyy8
5440    /// removed is reachable ONLY when a caller explicitly asks for STRICT
5441    /// incumbent parity, never by default. See DISC-020.
5442    #[must_use]
5443    pub fn mul_scalar_with_policy(a: i64, factor: i64, policy: OverflowPolicy) -> i64 {
5444        if a == Self::NAT {
5445            return Self::NAT;
5446        }
5447        if matches!(policy, OverflowPolicy::Strict) {
5448            return a.wrapping_mul(factor);
5449        }
5450        policy
5451            .resolve_recording(Self::try_mul_scalar(a, factor), Self::NAT, Self::NAT)
5452            .unwrap_or(Self::NAT)
5453    }
5454
5455    /// Multiply a Timedelta value by an integer factor, reporting overflow.
5456    ///
5457    /// # Errors
5458    /// [`PandasTemporalError::Overflow`] when the product exceeds i64 — which
5459    /// is what the SCALAR `pd.Timedelta.max * 2` raises. Note DISC-018: the
5460    /// VECTORIZED `Series * int` wraps silently instead, so a strict arm for
5461    /// this op must decide per-surface rather than inherit this class blindly.
5462    pub fn try_mul_scalar(a: i64, factor: i64) -> Result<i64, TemporalFailure> {
5463        if a == Self::NAT {
5464            return Ok(Self::NAT);
5465        }
5466        a.checked_mul(factor).ok_or(
5467            TemporalFailure::new("Timedelta::mul_scalar", PandasTemporalError::Overflow)
5468                .with_operands(a, factor),
5469        )
5470    }
5471
5472    /// Floor-divide a Timedelta value by an integer divisor. NaT propagates.
5473    /// Returns NaT on divide-by-zero (matches pandas, which raises, but we
5474    /// surface as NaT to avoid panics at the type-system boundary).
5475    ///
5476    /// Matches pandas / Python `pd.Timedelta(...) // int`: floor division,
5477    /// not truncation toward zero. `-100 // 3 == -34`, and `100 // -3 ==
5478    /// -34`. Rust's `/` truncates toward zero and `div_euclid` keeps the
5479    /// remainder non-negative — neither matches pandas when the divisor is
5480    /// negative. This helper adjusts trunc-toward-zero into floor.
5481    #[must_use]
5482    pub fn div_scalar(a: i64, divisor: i64) -> i64 {
5483        Self::try_div_scalar(a, divisor).unwrap_or(Self::NAT)
5484    }
5485
5486    /// Floor-divide a Timedelta by an integer divisor, reporting divide-by-zero.
5487    ///
5488    /// br-frankenpandas-fyr1z-strict-raise-arms-t7ht2. NaT propagation is not a
5489    /// failure and yields `Ok(NAT)`; only a zero divisor is an `Err`.
5490    ///
5491    /// ⚠ SCALAR SEMANTICS ONLY. pandas raises `ZeroDivisionError` for the
5492    /// scalar `pd.Timedelta('1s') // 0`, but the VECTORIZED
5493    /// `Series([Timedelta]) // 0` returns NaT (both probed on 2.2.3). The
5494    /// infallible [`Self::div_scalar`] above keeps the NaT behavior that the
5495    /// vectorized callers depend on, and a STRICT arm must route only the
5496    /// scalar surface here.
5497    ///
5498    /// # Errors
5499    /// [`PandasTemporalError::ZeroDivision`] when `divisor == 0`.
5500    pub fn try_div_scalar(a: i64, divisor: i64) -> Result<i64, TemporalFailure> {
5501        if divisor == 0 {
5502            return Err(TemporalFailure::new(
5503                "Timedelta::div_scalar",
5504                PandasTemporalError::ZeroDivision,
5505            )
5506            .with_operands(a, divisor));
5507        }
5508        if a == Self::NAT {
5509            return Ok(Self::NAT);
5510        }
5511        Ok(Self::div_scalar_inner(a, divisor))
5512    }
5513
5514    fn div_scalar_inner(a: i64, divisor: i64) -> i64 {
5515        // NAT == i64::MIN so the classic `i64::MIN / -1` overflow path is
5516        // already handled by the NAT check above. `(i64::MIN + 1) / -1`
5517        // equals `i64::MAX` with no overflow, so we never need a
5518        // saturation branch here.
5519        let q = a / divisor;
5520        let r = a % divisor;
5521        // If remainder is non-zero and has opposite sign from divisor,
5522        // Rust's trunc-toward-zero `/` is one step above the floor. Adjust
5523        // down by 1 to match Python/pandas floor division.
5524        if r != 0 && (r < 0) != (divisor < 0) {
5525            q - 1
5526        } else {
5527            q
5528        }
5529    }
5530
5531    /// Divide two Timedelta values, returning the ratio as f64.
5532    /// Matches pandas `pd.Timedelta(...) / pd.Timedelta(...)` → float.
5533    /// NaT in either operand → NaN. Zero divisor → ±Inf (per IEEE 754).
5534    #[must_use]
5535    pub fn div_timedelta(a: i64, b: i64) -> f64 {
5536        if a == Self::NAT || b == Self::NAT {
5537            return f64::NAN;
5538        }
5539        (a as f64) / (b as f64)
5540    }
5541
5542    /// Returns ISO 8601 duration format string.
5543    ///
5544    /// Matches pandas `pd.Timedelta.isoformat()`. Returns format like
5545    /// "P1DT2H3M4.567890123S" for 1 day, 2 hours, 3 minutes, 4.567890123 seconds.
5546    /// A negative duration is pandas' components form: whole days rounded
5547    /// down, then a non-negative clock (-1 day -1 hour is "P-2DT23H0M0S";
5548    /// it was "-P1DT1H0M0S"). NaT returns "NaT".
5549    #[must_use]
5550    pub fn isoformat(nanos: i64) -> String {
5551        use std::fmt::Write as _;
5552
5553        if nanos == Self::NAT {
5554            return "NaT".to_string();
5555        }
5556
5557        let days = nanos.div_euclid(Self::NANOS_PER_DAY);
5558        let remaining = nanos.rem_euclid(Self::NANOS_PER_DAY);
5559
5560        let hours = remaining / Self::NANOS_PER_HOUR;
5561        let remaining = remaining % Self::NANOS_PER_HOUR;
5562
5563        let minutes = remaining / Self::NANOS_PER_MIN;
5564        let remaining = remaining % Self::NANOS_PER_MIN;
5565
5566        let seconds = remaining / Self::NANOS_PER_SEC;
5567        let sub_sec_nanos = remaining % Self::NANOS_PER_SEC;
5568
5569        // Build directly into the returned allocation. The former sequence of
5570        // `format!` calls allocated two temporary strings for integral values
5571        // and three for fractional values before copying them into `result`.
5572        let mut result = String::with_capacity(40);
5573        // `fmt::Write for String` is infallible.
5574        let _ = write!(result, "P{days}DT{hours}H{minutes}M{seconds}");
5575        if sub_sec_nanos != 0 {
5576            result.push('.');
5577            let _ = write!(result, "{sub_sec_nanos:09}");
5578            while result.ends_with('0') {
5579                result.pop();
5580            }
5581        }
5582        result.push('S');
5583        result
5584    }
5585
5586    /// Rounds down to the nearest frequency unit.
5587    ///
5588    /// Matches pandas `pd.Timedelta.floor(freq)`. NaT is preserved.
5589    #[must_use]
5590    pub fn floor(nanos: i64, freq: &str) -> i64 {
5591        if nanos == Self::NAT {
5592            return Self::NAT;
5593        }
5594        let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5595            return Self::NAT;
5596        };
5597        if unit_nanos == 0 {
5598            return Self::NAT;
5599        }
5600        nanos
5601            .div_euclid(unit_nanos)
5602            .checked_mul(unit_nanos)
5603            .unwrap_or(Self::NAT)
5604    }
5605
5606    /// Rounds up to the nearest frequency unit.
5607    ///
5608    /// Matches pandas `pd.Timedelta.ceil(freq)`. NaT is preserved; overflow
5609    /// → NaT (`pd.Timedelta.max.ceil('D')` raises `OutOfBoundsTimedelta:
5610    /// Cannot round ... without overflow`, so a clamped `i64::MAX` would be a
5611    /// fabricated finite duration — see br-frankenpandas-kyd16).
5612    #[must_use]
5613    pub fn ceil(nanos: i64, freq: &str) -> i64 {
5614        if nanos == Self::NAT {
5615            return Self::NAT;
5616        }
5617        let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5618            return Self::NAT;
5619        };
5620        if unit_nanos == 0 {
5621            return Self::NAT;
5622        }
5623        let remainder = nanos.rem_euclid(unit_nanos);
5624        if remainder == 0 {
5625            nanos
5626        } else {
5627            nanos
5628                .checked_add(unit_nanos - remainder)
5629                .unwrap_or(Self::NAT)
5630        }
5631    }
5632
5633    /// Rounds to the nearest frequency unit.
5634    ///
5635    /// Matches pandas `pd.Timedelta.round(freq)`. Uses banker's rounding
5636    /// (round half to even). NaT is preserved.
5637    #[must_use]
5638    pub fn round(nanos: i64, freq: &str) -> i64 {
5639        if nanos == Self::NAT {
5640            return Self::NAT;
5641        }
5642        let Some(unit_nanos) = Self::unit_to_nanos(freq) else {
5643            return Self::NAT;
5644        };
5645        if unit_nanos == 0 {
5646            return Self::NAT;
5647        }
5648        let negative = nanos < 0;
5649        let abs_nanos = nanos.saturating_abs();
5650
5651        let quotient = abs_nanos / unit_nanos;
5652        let remainder = abs_nanos % unit_nanos;
5653        let half = unit_nanos / 2;
5654
5655        // Round-UP must be checked (br-frankenpandas-kyd16). `quotient *
5656        // unit_nanos` is always <= abs_nanos and cannot overflow, but
5657        // `(quotient + 1) * unit_nanos` can exceed i64::MAX — and this used
5658        // UNCHECKED arithmetic, so it panicked in debug and WRAPPED to a
5659        // large-negative duration in release. pandas raises
5660        // OutOfBoundsTimedelta ("Cannot round ... without overflow"); we
5661        // surface NaT, consistent with the rest of this block.
5662        let round_up = || {
5663            quotient
5664                .checked_add(1)
5665                .and_then(|q| q.checked_mul(unit_nanos))
5666        };
5667        let rounded = if remainder > half {
5668            round_up()
5669        } else if remainder < half {
5670            Some(quotient * unit_nanos)
5671        } else {
5672            // Exactly half: round to even
5673            if quotient % 2 == 0 {
5674                Some(quotient * unit_nanos)
5675            } else {
5676                round_up()
5677            }
5678        };
5679
5680        match rounded {
5681            // Negating is safe: `rounded` is non-negative and at most i64::MAX,
5682            // so `-rounded` is at worst i64::MIN + 1 — never the NaT sentinel.
5683            Some(rounded) => {
5684                if negative {
5685                    -rounded
5686                } else {
5687                    rounded
5688                }
5689            }
5690            None => Self::NAT,
5691        }
5692    }
5693}
5694
5695// ── Time zones ──────────────────────────────────────────────────────────
5696//
5697// A tz-aware value is a UTC instant plus a zone name; what the zone adds is
5698// the wall clock the instant shows there. These are the conversions every
5699// crate shares (Timestamp, DatetimeIndex, datetime columns).
5700
5701/// Why a time-zone conversion failed, as pandas (pytz) classifies it.
5702#[derive(Debug, Clone, PartialEq, Eq, Error)]
5703pub enum TimeZoneError {
5704    /// Neither 'UTC', a fixed offset ('+05:30') nor an IANA name - pandas'
5705    /// `UnknownTimeZoneError`, a `KeyError` whose message is the quoted name.
5706    #[error("'{0}'")]
5707    Unknown(String),
5708    /// A wall-clock time a DST change skips - pandas' `NonExistentTimeError`,
5709    /// whose message is the wall time.
5710    #[error("{0}")]
5711    NonExistent(String),
5712    /// A wall-clock time a DST change repeats - pandas' `AmbiguousTimeError`.
5713    #[error("Cannot infer dst time from {0}, try using the 'ambiguous' argument")]
5714    Ambiguous(String),
5715}
5716
5717/// A parsed zone: UTC or a fixed offset, or an IANA zone with DST rules.
5718enum Zone {
5719    Fixed(chrono::FixedOffset),
5720    Named(chrono_tz::Tz),
5721}
5722
5723impl Zone {
5724    /// pandas' zone spellings: 'UTC' / 'Z', a `+HH:MM` / `-HH:MM` offset (also
5725    /// as `UTC+HH:MM`, how a fixed-offset dtype names its zone), or an IANA
5726    /// name ('US/Eastern', 'Asia/Tokyo', 'Etc/GMT+5').
5727    fn parse(tz: &str) -> Result<Self, TimeZoneError> {
5728        use chrono::Offset;
5729        let name = tz.trim();
5730        if name == "UTC" || name == "Z" {
5731            return Ok(Self::Fixed(chrono::Utc.fix()));
5732        }
5733        let offset = name
5734            .strip_prefix("UTC")
5735            .filter(|rest| rest.starts_with(['+', '-']))
5736            .unwrap_or(name);
5737        let bytes = offset.as_bytes();
5738        if bytes.len() == 6
5739            && matches!(bytes[0], b'+' | b'-')
5740            && bytes[3] == b':'
5741            && [1, 2, 4, 5].iter().all(|&i| bytes[i].is_ascii_digit())
5742        {
5743            let hours: i32 = offset[1..3].parse().unwrap_or(24);
5744            let minutes: i32 = offset[4..6].parse().unwrap_or(60);
5745            let sign = if bytes[0] == b'-' { -1 } else { 1 };
5746            return (hours <= 23 && minutes <= 59)
5747                .then(|| chrono::FixedOffset::east_opt(sign * (hours * 3_600 + minutes * 60)))
5748                .flatten()
5749                .map(Self::Fixed)
5750                .ok_or_else(|| TimeZoneError::Unknown(name.to_owned()));
5751        }
5752        name.parse::<chrono_tz::Tz>()
5753            .map(Self::Named)
5754            .map_err(|_| TimeZoneError::Unknown(name.to_owned()))
5755    }
5756
5757    /// Seconds east of UTC this zone is at the UTC instant `utc_nanos`.
5758    fn offset_seconds(&self, utc_nanos: i64) -> i32 {
5759        use chrono::{Offset, TimeZone};
5760        match self {
5761            Self::Fixed(offset) => offset.local_minus_utc(),
5762            Self::Named(zone) => {
5763                let utc = chrono::DateTime::from_timestamp_nanos(utc_nanos).naive_utc();
5764                zone.offset_from_utc_datetime(&utc).fix().local_minus_utc()
5765            }
5766        }
5767    }
5768}
5769
5770/// Whether `tz` names a zone pandas accepts ('UTC', `+HH:MM`, an IANA name).
5771pub fn tz_validate(tz: &str) -> Result<(), TimeZoneError> {
5772    Zone::parse(tz).map(|_| ())
5773}
5774
5775/// The name pandas gives the zone `tz`: a fixed offset is `UTC+HH:MM`
5776/// ('+05:30' and 'UTC+05:30' alike; a zero offset or 'Z' is 'UTC'), an
5777/// IANA name stays as given.
5778pub fn tz_canonical_name(tz: &str) -> Result<String, TimeZoneError> {
5779    Ok(match Zone::parse(tz)? {
5780        Zone::Fixed(offset) if offset.local_minus_utc() == 0 => "UTC".to_owned(),
5781        Zone::Fixed(offset) => format!("UTC{offset}"),
5782        Zone::Named(_) => tz.trim().to_owned(),
5783    })
5784}
5785
5786/// The zone's name at the UTC instant `utc_nanos` as `strftime('%Z')` prints
5787/// it: an IANA zone's abbreviation then ('EST' / 'EDT'), a fixed offset's
5788/// `UTC+HH:MM` ('UTC' for zero).
5789pub fn tz_abbreviation(tz: &str, utc_nanos: i64) -> Result<String, TimeZoneError> {
5790    use chrono::TimeZone;
5791    match Zone::parse(tz)? {
5792        Zone::Named(zone) => {
5793            let utc = chrono::DateTime::from_timestamp_nanos(utc_nanos).naive_utc();
5794            let offset = zone.offset_from_utc_datetime(&utc);
5795            Ok(chrono_tz::OffsetName::abbreviation(&offset)
5796                .map_or_else(|| tz.trim().to_owned(), str::to_owned))
5797        }
5798        Zone::Fixed(_) => tz_canonical_name(tz),
5799    }
5800}
5801
5802/// The UTC offset, in seconds east of UTC, that `tz` has at the UTC instant
5803/// `utc_nanos` - what a tz-aware timestamp adds to its instant to show its
5804/// wall clock.
5805pub fn tz_offset_seconds(tz: &str, utc_nanos: i64) -> Result<i32, TimeZoneError> {
5806    Ok(Zone::parse(tz)?.offset_seconds(utc_nanos))
5807}
5808
5809/// The wall clock the UTC instant `utc_nanos` shows in `tz`, as naive
5810/// nanoseconds (NaT, `i64::MIN`, stays NaT).
5811pub fn tz_utc_to_wall_nanos(tz: &str, utc_nanos: i64) -> Result<i64, TimeZoneError> {
5812    if utc_nanos == i64::MIN {
5813        return Ok(utc_nanos);
5814    }
5815    let offset = Zone::parse(tz)?.offset_seconds(utc_nanos);
5816    Ok(utc_nanos.saturating_add(i64::from(offset) * 1_000_000_000))
5817}
5818
5819/// The UTC instant of the wall-clock time `wall_nanos` in `tz`, as pandas'
5820/// `tz_localize` with ambiguous / nonexistent = 'raise': a wall time a DST
5821/// change skips is [`TimeZoneError::NonExistent`], one it repeats
5822/// [`TimeZoneError::Ambiguous`]. NaT (`i64::MIN`) stays NaT.
5823pub fn tz_wall_to_utc_nanos(tz: &str, wall_nanos: i64) -> Result<i64, TimeZoneError> {
5824    tz_wall_to_utc_nanos_with(tz, wall_nanos, AmbiguousTime::Raise, NonexistentTime::Raise)
5825}
5826
5827/// What `tz_localize` does with a wall time a DST change repeats (pandas'
5828/// `ambiguous=`, for one value): refuse it, take its first occurrence (DST,
5829/// pandas' `True`) or its second (standard time, `False`), or make it NaT.
5830#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5831pub enum AmbiguousTime {
5832    Raise,
5833    Earliest,
5834    Latest,
5835    NaT,
5836}
5837
5838/// What `tz_localize` does with a wall time a DST change skips (pandas'
5839/// `nonexistent=`): refuse it, move it to the first instant after the gap
5840/// (`shift_forward`) or the last nanosecond before it (`shift_backward`),
5841/// make it NaT, or move the wall time by a duration (nanoseconds) and
5842/// localize that.
5843#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5844pub enum NonexistentTime {
5845    Raise,
5846    ShiftForward,
5847    ShiftBackward,
5848    NaT,
5849    Shift(i64),
5850}
5851
5852/// [`tz_wall_to_utc_nanos`] under pandas' `ambiguous` / `nonexistent`
5853/// policies; NaT (`i64::MIN`) where a policy says NaT.
5854pub fn tz_wall_to_utc_nanos_with(
5855    tz: &str,
5856    wall_nanos: i64,
5857    ambiguous: AmbiguousTime,
5858    nonexistent: NonexistentTime,
5859) -> Result<i64, TimeZoneError> {
5860    use chrono::{LocalResult, TimeZone};
5861    if wall_nanos == i64::MIN {
5862        return Ok(wall_nanos);
5863    }
5864    let zone = Zone::parse(tz)?;
5865    let naive = chrono::DateTime::from_timestamp_nanos(wall_nanos).naive_utc();
5866    let local = match &zone {
5867        Zone::Fixed(offset) => offset
5868            .from_local_datetime(&naive)
5869            .map(|at| at.fixed_offset()),
5870        Zone::Named(zone) => zone.from_local_datetime(&naive).map(|at| at.fixed_offset()),
5871    };
5872    let nanos_of = |at: chrono::DateTime<chrono::FixedOffset>| {
5873        at.timestamp_nanos_opt()
5874            .ok_or_else(|| TimeZoneError::NonExistent(naive.to_string()))
5875    };
5876    match local {
5877        LocalResult::Single(at) => nanos_of(at),
5878        LocalResult::Ambiguous(earliest, latest) => match ambiguous {
5879            AmbiguousTime::Raise => Err(TimeZoneError::Ambiguous(naive.to_string())),
5880            AmbiguousTime::Earliest => nanos_of(earliest),
5881            AmbiguousTime::Latest => nanos_of(latest),
5882            AmbiguousTime::NaT => Ok(i64::MIN),
5883        },
5884        LocalResult::None => match nonexistent {
5885            NonexistentTime::Raise => Err(TimeZoneError::NonExistent(naive.to_string())),
5886            NonexistentTime::NaT => Ok(i64::MIN),
5887            NonexistentTime::Shift(delta) => {
5888                let shifted = wall_nanos
5889                    .checked_add(delta)
5890                    .ok_or_else(|| TimeZoneError::NonExistent(naive.to_string()))?;
5891                tz_wall_to_utc_nanos_with(tz, shifted, ambiguous, NonexistentTime::Raise)
5892            }
5893            NonexistentTime::ShiftForward | NonexistentTime::ShiftBackward => {
5894                // The gap's UTC transition: the wall time read with the
5895                // offset in force before the change lands after it, read
5896                // with the offset after the change lands before it; the
5897                // first instant between them carrying the later offset is
5898                // the transition (exact to the nanosecond - pandas'
5899                // shift_backward is one nanosecond before it).
5900                const DAY: i64 = 86_400_000_000_000;
5901                let offset_at = |utc: i64| i64::from(zone.offset_seconds(utc)) * 1_000_000_000;
5902                let before = wall_nanos.saturating_sub(offset_at(wall_nanos.saturating_sub(DAY)));
5903                let after = wall_nanos.saturating_sub(offset_at(wall_nanos.saturating_add(DAY)));
5904                let (mut low, mut high) = (before.min(after), before.max(after));
5905                let later = offset_at(high);
5906                while high - low > 1 {
5907                    let middle = low + (high - low) / 2;
5908                    if offset_at(middle) == later {
5909                        high = middle;
5910                    } else {
5911                        low = middle;
5912                    }
5913                }
5914                Ok(if nonexistent == NonexistentTime::ShiftForward {
5915                    high
5916                } else {
5917                    high - 1
5918                })
5919            }
5920        },
5921    }
5922}
5923
5924/// `wall_nanos` formatted as Python's (glibc's) `strftime` does - what
5925/// pandas' `Timestamp.strftime` / `Series.dt.strftime` / `to_csv(date_format=)`
5926/// run per value: the C-locale directives (`%a %A %b %B %c %d %e %f %H %I
5927/// %j %m %M %p %S %U %w %W %x %X %y %Y %z %Z %%`), glibc's (`%C %D %F %g %G
5928/// %h %k %l %n %P %r %R %t %T %u %V`) and its `-` (no padding), `_` (space
5929/// padding), `0` and `^` (upper case) flags. An unknown directive is echoed
5930/// as written, as glibc does. `zone` is a tz-aware value's UTC offset (in
5931/// seconds) and abbreviation at that instant, which `%z` / `%Z` print (empty
5932/// for a naive value).
5933#[must_use]
5934pub fn strftime_python(wall_nanos: i64, format: &str, zone: Option<(i32, &str)>) -> String {
5935    const DAYS: [&str; 7] = [
5936        "Sunday",
5937        "Monday",
5938        "Tuesday",
5939        "Wednesday",
5940        "Thursday",
5941        "Friday",
5942        "Saturday",
5943    ];
5944    const MONTHS: [&str; 12] = [
5945        "January",
5946        "February",
5947        "March",
5948        "April",
5949        "May",
5950        "June",
5951        "July",
5952        "August",
5953        "September",
5954        "October",
5955        "November",
5956        "December",
5957    ];
5958    // Floor both boundaries so a pre-epoch instant keeps a consistent date
5959    // and time (1969-12-31 23:59:59.999999 for -1 ns).
5960    let total_secs = wall_nanos.div_euclid(1_000_000_000);
5961    let sub_nanos = wall_nanos.rem_euclid(1_000_000_000);
5962    let days = total_secs.div_euclid(86_400);
5963    let secs_of_day = total_secs.rem_euclid(86_400);
5964    let (year, month, day) = civil_from_days(days);
5965    let (hour, minute, second) = (
5966        secs_of_day / 3_600,
5967        (secs_of_day % 3_600) / 60,
5968        secs_of_day % 60,
5969    );
5970    let hour12 = if hour % 12 == 0 { 12 } else { hour % 12 };
5971    let weekday = (days + 4).rem_euclid(7); // 0 = Sunday
5972    let yday = days - days_from_civil(year, 1, 1); // 0-based
5973    let iso_weekday = if weekday == 0 { 7 } else { weekday };
5974    let (iso_year, iso_week) = {
5975        let week = (yday + 1 - iso_weekday + 10).div_euclid(7);
5976        if week < 1 {
5977            (year - 1, iso_weeks_in_year(year - 1))
5978        } else if week > iso_weeks_in_year(year) {
5979            (year + 1, 1)
5980        } else {
5981            (year, week)
5982        }
5983    };
5984    let month_name = MONTHS[(month as usize).saturating_sub(1) % 12];
5985    let day_name = DAYS[weekday as usize];
5986
5987    let mut out = String::with_capacity(format.len().saturating_add(16));
5988    let mut chars = format.chars().peekable();
5989    while let Some(ch) = chars.next() {
5990        if ch != '%' {
5991            out.push(ch);
5992            continue;
5993        }
5994        let flag = chars.next_if(|c| matches!(c, '-' | '_' | '0' | '^'));
5995        let Some(conversion) = chars.next() else {
5996            out.push('%');
5997            if let Some(flag) = flag {
5998                out.push(flag);
5999            }
6000            break;
6001        };
6002        // A number `width` wide, padded with `pad` unless a flag says
6003        // otherwise.
6004        let number = |value: i64, width: usize, pad: char| -> String {
6005            match flag.unwrap_or(pad) {
6006                '-' => value.to_string(),
6007                '_' | ' ' => format!("{value:>width$}"),
6008                _ => format!("{value:0width$}"),
6009            }
6010        };
6011        let text = |value: &str| -> String {
6012            if flag == Some('^') {
6013                value.to_uppercase()
6014            } else {
6015                value.to_owned()
6016            }
6017        };
6018        let piece = match conversion {
6019            'a' => text(&day_name[..3]),
6020            'A' => text(day_name),
6021            'b' | 'h' => text(&month_name[..3]),
6022            'B' => text(month_name),
6023            'c' => text(&strftime_python(wall_nanos, "%a %b %e %H:%M:%S %Y", zone)),
6024            'C' => number(year.div_euclid(100), 2, '0'),
6025            'd' => number(i64::from(day), 2, '0'),
6026            'D' | 'x' => strftime_python(wall_nanos, "%m/%d/%y", zone),
6027            'e' => number(i64::from(day), 2, ' '),
6028            'f' => number(sub_nanos / 1_000, 6, '0'),
6029            'F' => strftime_python(wall_nanos, "%Y-%m-%d", zone),
6030            'g' => number(iso_year.rem_euclid(100), 2, '0'),
6031            'G' => number(iso_year, 1, '0'),
6032            'H' => number(hour, 2, '0'),
6033            'I' => number(hour12, 2, '0'),
6034            'j' => number(yday + 1, 3, '0'),
6035            'k' => number(hour, 2, ' '),
6036            'l' => number(hour12, 2, ' '),
6037            'm' => number(i64::from(month), 2, '0'),
6038            'M' => number(minute, 2, '0'),
6039            'n' => "\n".to_owned(),
6040            'p' => text(if hour < 12 { "AM" } else { "PM" }),
6041            'P' => (if hour < 12 { "am" } else { "pm" }).to_owned(),
6042            'r' => strftime_python(wall_nanos, "%I:%M:%S %p", zone),
6043            'R' => strftime_python(wall_nanos, "%H:%M", zone),
6044            'S' => number(second, 2, '0'),
6045            't' => "\t".to_owned(),
6046            'T' | 'X' => strftime_python(wall_nanos, "%H:%M:%S", zone),
6047            'u' => number(iso_weekday, 1, '0'),
6048            'U' => number((yday + 7 - weekday).div_euclid(7), 2, '0'),
6049            'V' => number(iso_week, 2, '0'),
6050            'w' => number(weekday, 1, '0'),
6051            'W' => number(
6052                (yday + 7 - (weekday + 6).rem_euclid(7)).div_euclid(7),
6053                2,
6054                '0',
6055            ),
6056            'y' => number(year.rem_euclid(100), 2, '0'),
6057            'Y' => number(year, 1, '0'),
6058            'z' => zone.map_or_else(String::new, |(offset, _)| {
6059                let sign = if offset < 0 { '-' } else { '+' };
6060                let offset = offset.unsigned_abs();
6061                let (h, m, s) = (offset / 3_600, (offset % 3_600) / 60, offset % 60);
6062                if s == 0 {
6063                    format!("{sign}{h:02}{m:02}")
6064                } else {
6065                    format!("{sign}{h:02}{m:02}{s:02}")
6066                }
6067            }),
6068            'Z' => zone.map_or_else(String::new, |(_, name)| text(name)),
6069            '%' => "%".to_owned(),
6070            other => {
6071                // glibc echoes a conversion it does not know.
6072                out.push('%');
6073                if let Some(flag) = flag {
6074                    out.push(flag);
6075                }
6076                out.push(other);
6077                continue;
6078            }
6079        };
6080        out.push_str(&piece);
6081    }
6082    out
6083}
6084
6085/// The instant `nanos` formatted by [`strftime_python`]: a naive value as
6086/// it is; in `tz` (a tz-aware value, `nanos` its UTC instant) on the zone's
6087/// wall clock with the offset and abbreviation of that instant.
6088#[must_use]
6089pub fn strftime_in_zone(nanos: i64, format: &str, tz: Option<&str>) -> String {
6090    let aware = tz.and_then(|zone| {
6091        let offset = tz_offset_seconds(zone, nanos).ok()?;
6092        let name = tz_abbreviation(zone, nanos).ok()?;
6093        Some((offset, name))
6094    });
6095    match aware {
6096        Some((offset, name)) => strftime_python(
6097            nanos.saturating_add(i64::from(offset) * 1_000_000_000),
6098            format,
6099            Some((offset, &name)),
6100        ),
6101        None => strftime_python(nanos, format, None),
6102    }
6103}
6104
6105/// `str(Timestamp)` of the naive instant `nanos`: its wall clock
6106/// 'YYYY-MM-DD HH:MM:SS' and its own fraction when it has one (six digits,
6107/// nine for nanoseconds) - how pandas prints a naive Timestamp an object
6108/// column holds (`astype(str)` spelled it 'Timestamp[<nanos>]';
6109/// br-frankenpandas-srzqw).
6110#[must_use]
6111pub fn timestamp_text(nanos: i64) -> String {
6112    let mut text = strftime_python(nanos, "%Y-%m-%d %H:%M:%S", None);
6113    let fraction = nanos.rem_euclid(1_000_000_000);
6114    if fraction % 1_000 != 0 {
6115        text.push_str(&format!(".{fraction:09}"));
6116    } else if fraction != 0 {
6117        text.push_str(&format!(".{:06}", fraction / 1_000));
6118    }
6119    text
6120}
6121
6122/// `str(Timestamp)` of the instant `nanos` in `tz`, as pandas prints a
6123/// tz-aware value (repr cells, `astype(str)`): its [`timestamp_text`] wall
6124/// clock and the zone's `+HH:MM` offset then.
6125#[must_use]
6126pub fn timestamp_text_in_zone(nanos: i64, tz: &str) -> String {
6127    let offset = tz_offset_seconds(tz, nanos).unwrap_or(0);
6128    let mut text = timestamp_text(nanos.saturating_add(i64::from(offset) * 1_000_000_000));
6129    let sign = if offset < 0 { '-' } else { '+' };
6130    let minutes = offset.unsigned_abs() / 60;
6131    text.push_str(&format!("{sign}{:02}:{:02}", minutes / 60, minutes % 60));
6132    text
6133}
6134
6135/// Days since 1970-01-01 of the proleptic-Gregorian date `(year, month,
6136/// day)` (Howard Hinnant's days-from-civil; the inverse of
6137/// `civil_from_days`).
6138fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
6139    let (month, day) = (i64::from(month), i64::from(day));
6140    let year = if month <= 2 { year - 1 } else { year };
6141    let era = if year >= 0 { year } else { year - 399 } / 400;
6142    let yoe = year - era * 400;
6143    let doy = (153 * ((month + 9) % 12) + 2) / 5 + day - 1;
6144    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
6145    era * 146_097 + doe - 719_468
6146}
6147
6148// ── Timestamp types (br-frankenpandas-9p0u — 4r56 Phase 2) ─────────────
6149//
6150// Nanosecond-precision i64 since Unix epoch + optional IANA tz name. The
6151// zone's DST-aware conversions are the time-zone functions above
6152// (`tz_offset_seconds`, `tz_wall_to_utc_nanos`); arithmetic here stays on
6153// the absolute nanos axis.
6154
6155/// Number of days in a given month (1-12) of a given year.
6156fn days_in_month(year: i64, month: u32) -> Option<u32> {
6157    if !(1..=12).contains(&month) {
6158        return None;
6159    }
6160    let is_leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
6161    let days: [u32; 12] = [
6162        31,
6163        if is_leap { 29 } else { 28 },
6164        31,
6165        30,
6166        31,
6167        30,
6168        31,
6169        31,
6170        30,
6171        31,
6172        30,
6173        31,
6174    ];
6175    Some(days[(month - 1) as usize])
6176}
6177
6178/// Number of ISO-8601 weeks in a year (52 or 53).
6179///
6180/// A year has 53 ISO weeks iff its first day falls on a Thursday, or it is a
6181/// leap year whose first day is a Wednesday — captured by the dominical
6182/// closed form `p(year) == 4 || p(year - 1) == 3`, where
6183/// `p(y) = (y + ⌊y/4⌋ − ⌊y/100⌋ + ⌊y/400⌋) mod 7` is the weekday of Dec 31.
6184fn iso_weeks_in_year(year: i64) -> i64 {
6185    fn p(y: i64) -> i64 {
6186        (y + y.div_euclid(4) - y.div_euclid(100) + y.div_euclid(400)).rem_euclid(7)
6187    }
6188    if p(year) == 4 || p(year - 1) == 3 {
6189        53
6190    } else {
6191        52
6192    }
6193}
6194
6195/// A nanosecond-precision point in time, Unix-epoch anchored.
6196///
6197/// Phase 2 scope: construction, arithmetic, equality, ordering, serde.
6198/// TZ semantics (IANA tz lookup, DST-aware shift) are deferred to Phase
6199/// 3 — see br-frankenpandas-4r56.
6200#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
6201pub struct Timestamp {
6202    /// Nanoseconds since Unix epoch. `i64::MIN` is NaT.
6203    pub nanos: i64,
6204    /// Optional IANA time-zone name (e.g. `"US/Eastern"`). `None` means
6205    /// naive / UTC-anchored. Phase 2 treats this as opaque metadata;
6206    /// Phase 3 wires chrono_tz interpretation.
6207    #[serde(default, skip_serializing_if = "Option::is_none")]
6208    pub tz: Option<String>,
6209}
6210
6211/// How `astype(str)` renders a `timedelta64[ns]` COLUMN.
6212///
6213/// ⚠️ THE TIMEDELTA LADDER IS NOT THE DATETIME ONE, and copying the sibling
6214/// across is the mistake this type exists to prevent. It has exactly TWO rungs,
6215/// and — unlike [`DatetimeStringResolution`] — THE SUB-SECOND WIDTH IS PER
6216/// VALUE, not per column. MEASURED, live pandas 2.2.3:
6217///
6218/// ```text
6219/// [1 days, 2 days]              -> ['1 days', '2 days']
6220/// [1 days, 5 ms]                -> ['1 days 00:00:00', '0 days 00:00:00.005000']
6221/// [1 days 02:03:04.005, 1 ns]   -> ['1 days 02:03:04.005000',
6222///                                   '0 days 00:00:00.000000001']
6223/// ```
6224///
6225/// That last row is the whole distinction: a millisecond value keeps its SIX
6226/// digits while its neighbour prints NINE. On the datetime side the same pair
6227/// would have been widened to a common nine. So the only column-wide question
6228/// here is whether the time-of-day part can be dropped entirely, which is what
6229/// [`Timedelta::string_resolution`] answers; [`Timedelta::format`] already gets
6230/// the per-value part right and is reused unchanged.
6231#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6232pub enum TimedeltaStringResolution {
6233    /// `1 days` / `-2 days` / `0 days` — every value is a whole day.
6234    Days,
6235    /// `1 days 02:03:04.005000` — the full rendering, sub-second width per value.
6236    Full,
6237}
6238
6239/// How wide `astype(str)` renders a `datetime64[ns]` value.
6240///
6241/// ⚠️ THIS IS A PROPERTY OF THE COLUMN, NOT OF THE VALUE, which is the whole
6242/// reason it is a separate type rather than a branch inside a per-scalar
6243/// formatter. MEASURED, live pandas 2.2.3 — the SAME midnight timestamp renders
6244/// three different ways depending only on what it shares a column with:
6245///
6246/// ```text
6247/// Series([midnight, midnight]).astype(str)   -> '2024-03-15'
6248/// Series([midnight, one_nanosecond]).astype(str)
6249///                                            -> '2024-03-15 00:00:00.000000000'
6250/// str(Timestamp(midnight))                   -> '2024-03-15 00:00:00'
6251/// ```
6252///
6253/// pandas picks the coarsest rung that is lossless for EVERY element and
6254/// imposes it on all of them. The `Ord` derive is the fold: scan the column
6255/// with `max` over [`Timestamp::string_resolution`], then format every value at
6256/// the winner. Variants are declared coarsest-first so that `max` means
6257/// "finest needed".
6258#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6259pub enum DatetimeStringResolution {
6260    /// `2024-03-15` — every value in the column is midnight.
6261    Date,
6262    /// `2024-03-15 10:30:45` — every value is a whole second.
6263    Second,
6264    /// `2024-03-15 10:30:45.123`
6265    Milli,
6266    /// `2024-03-15 10:30:45.123456`
6267    Micro,
6268    /// `2024-03-15 10:30:45.123456789`
6269    Nano,
6270}
6271
6272impl Timestamp {
6273    /// NaT sentinel, parallel to `Timedelta::NAT`.
6274    pub const NAT: i64 = i64::MIN;
6275
6276    /// Construct a UTC-anchored (tz=None) Timestamp from nanoseconds
6277    /// since Unix epoch.
6278    #[must_use]
6279    pub const fn from_nanos(nanos: i64) -> Self {
6280        Self { nanos, tz: None }
6281    }
6282
6283    /// Construct a Timestamp tagged with an IANA tz name.
6284    ///
6285    /// Phase 2 doesn't interpret the tz — it only carries the name
6286    /// through arithmetic + serde. Phase 3 wires chrono_tz conversion.
6287    #[must_use]
6288    pub fn from_nanos_tz(nanos: i64, tz_name: impl Into<String>) -> Self {
6289        Self {
6290            nanos,
6291            tz: Some(tz_name.into()),
6292        }
6293    }
6294
6295    /// Returns the current UTC timestamp.
6296    ///
6297    /// ⚠️ THIS MATCHES `pd.Timestamp.utcnow()`, NOT `pd.Timestamp.now()`, and the
6298    /// old doc claimed both. They are different functions: pandas' `now()` returns
6299    /// LOCAL time with no timezone attached, while `utcnow()` returns UTC.
6300    /// MEASURED, live pandas 2.2.3 (CrimsonPine 2026-08-19) on a UTC-4 host:
6301    /// ```text
6302    ///   pd.Timestamp.now()    2026-08-19 07:17:07.266940        tz None
6303    ///   pd.Timestamp.utcnow() 2026-08-19 11:17:07.267100+00:00  tz UTC
6304    ///   difference: 14400 s
6305    /// ```
6306    /// A caller who trusted the old claim and ran on a non-UTC host would be off by
6307    /// their whole UTC offset — four hours here — with no error and no NaT to notice.
6308    /// This crate has no local-timezone concept, so the UTC answer is the only one it
6309    /// can give; only the false half of the claim is removed.
6310    #[must_use]
6311    pub fn now() -> Self {
6312        use std::time::{SystemTime, UNIX_EPOCH};
6313        let duration = SystemTime::now()
6314            .duration_since(UNIX_EPOCH)
6315            .unwrap_or_default();
6316        let nanos = duration.as_nanos() as i64;
6317        Self { nanos, tz: None }
6318    }
6319
6320    /// Alias for `now()`. Matches `pd.Timestamp.utcnow()`.
6321    #[must_use]
6322    pub fn utcnow() -> Self {
6323        Self::now()
6324    }
6325
6326    /// Returns today's date at midnight UTC.
6327    ///
6328    /// Matches `pd.Timestamp.today()`.
6329    #[must_use]
6330    pub fn today() -> Self {
6331        let now = Self::now();
6332        now.normalize()
6333    }
6334
6335    /// The NaT sentinel value for a Timestamp.
6336    #[must_use]
6337    pub const fn nat() -> Self {
6338        Self {
6339            nanos: Self::NAT,
6340            tz: None,
6341        }
6342    }
6343
6344    /// True iff this Timestamp is NaT.
6345    #[must_use]
6346    pub const fn is_nat(&self) -> bool {
6347        self.nanos == Self::NAT
6348    }
6349
6350    /// Nanoseconds since Unix epoch, matching `pd.Timestamp.value`.
6351    #[must_use]
6352    pub const fn value(&self) -> i64 {
6353        self.nanos
6354    }
6355
6356    /// Stored resolution unit, matching `pd.Timestamp.unit`.
6357    ///
6358    /// FrankenPandas `Timestamp` stores nanoseconds internally, so non-NaT
6359    /// values report `ns`. `NaT` has no unit.
6360    #[must_use]
6361    pub const fn unit(&self) -> Option<&'static str> {
6362        if self.is_nat() { None } else { Some("ns") }
6363    }
6364
6365    /// Return the resolution of the timestamp (always "ns" for nanoseconds).
6366    ///
6367    /// Matches `pd.Timestamp.resolution`. Returns None for NaT.
6368    #[must_use]
6369    pub const fn resolution(&self) -> Option<&'static str> {
6370        if self.is_nat() { None } else { Some("ns") }
6371    }
6372
6373    /// Numpy datetime64 scalar payload, matching `pd.Timestamp.asm8`.
6374    #[must_use]
6375    pub const fn asm8(&self) -> i64 {
6376        self.value()
6377    }
6378
6379    /// Convert to a datetime64 payload, matching `pd.Timestamp.to_datetime64()`.
6380    #[must_use]
6381    pub const fn to_datetime64(&self) -> i64 {
6382        self.value()
6383    }
6384
6385    /// Convert to a numpy scalar payload, matching `pd.Timestamp.to_numpy()`.
6386    #[must_use]
6387    pub const fn to_numpy(&self) -> i64 {
6388        self.value()
6389    }
6390
6391    /// POSIX timestamp in seconds, matching `pd.Timestamp.timestamp()`.
6392    ///
6393    /// Pandas exposes this through Python's datetime surface, so sub-microsecond
6394    /// nanoseconds are rounded to six decimal places. `NaT` raises in pandas;
6395    /// fp-types surfaces the same condition as a missing-value error.
6396    pub fn timestamp(&self) -> Result<f64, TypeError> {
6397        if self.is_nat() {
6398            return Err(TypeError::ValueIsMissing {
6399                kind: NullKind::NaT,
6400            });
6401        }
6402        let seconds = self.nanos as f64 / 1_000_000_000.0;
6403        let rounded = format!("{seconds:.6}").parse().unwrap_or(seconds);
6404        Ok(rounded)
6405    }
6406
6407    /// Add a Timedelta. NaT in either operand → NaT; overflow → NaT.
6408    /// TZ is preserved from `self`.
6409    ///
6410    /// Overflow is NaT in both directions (br-frankenpandas-lgyy8) — see the
6411    /// overflow note on [`Timedelta::add`]. A saturated `i64::MAX` would be a
6412    /// finite, plausible ~year-2262 instant returned as if it were real data;
6413    /// `pd.Timestamp.max + pd.Timedelta('1ns')` raises `OutOfBoundsDatetime`.
6414    #[must_use]
6415    pub fn add_timedelta(&self, td_nanos: i64) -> Self {
6416        self.try_add_timedelta(td_nanos)
6417            .unwrap_or_else(|_| Self::nat())
6418    }
6419
6420    /// Shift by a Timedelta, reporting overflow.
6421    ///
6422    /// br-frankenpandas-fyr1z-policy-carrier-f29nz. A NaT operand is
6423    /// propagation, not overflow, so it yields `Ok(nat())`. On overflow the
6424    /// caller gets the error INSTEAD of the tz-dropped NaT; the infallible
6425    /// `add_timedelta` above still produces that NaT, unchanged.
6426    ///
6427    /// # Errors
6428    /// [`PandasTemporalError::OutOfBoundsDatetime`], matching
6429    /// `pd.Timestamp.max + pd.Timedelta('1ns')`.
6430    pub fn try_add_timedelta(&self, td_nanos: i64) -> Result<Self, TemporalFailure> {
6431        if self.is_nat() || td_nanos == Timedelta::NAT {
6432            return Ok(Self::nat());
6433        }
6434        match self.nanos.checked_add(td_nanos) {
6435            Some(nanos) => Ok(Self {
6436                nanos,
6437                tz: self.tz.clone(),
6438            }),
6439            // Overflow drops the tz with the value: an out-of-range instant has
6440            // no zone, and `Self::nat()` is the one canonical NaT (matching the
6441            // NaT-operand arms above, which also return an untagged NaT).
6442            None => Err(TemporalFailure::new(
6443                "Timestamp::add_timedelta",
6444                PandasTemporalError::OutOfBoundsDatetime,
6445            )
6446            .with_operands(self.nanos, td_nanos)),
6447        }
6448    }
6449
6450    /// Subtract a Timedelta. NaT propagation; overflow → NaT. TZ preserved.
6451    #[must_use]
6452    pub fn sub_timedelta(&self, td_nanos: i64) -> Self {
6453        self.try_sub_timedelta(td_nanos)
6454            .unwrap_or_else(|_| Self::nat())
6455    }
6456
6457    /// Shift back by a Timedelta, reporting overflow. See
6458    /// [`Self::try_add_timedelta`].
6459    ///
6460    /// # Errors
6461    /// [`PandasTemporalError::OutOfBoundsDatetime`].
6462    pub fn try_sub_timedelta(&self, td_nanos: i64) -> Result<Self, TemporalFailure> {
6463        if self.is_nat() || td_nanos == Timedelta::NAT {
6464            return Ok(Self::nat());
6465        }
6466        match self.nanos.checked_sub(td_nanos) {
6467            Some(nanos) => Ok(Self {
6468                nanos,
6469                tz: self.tz.clone(),
6470            }),
6471            None => Err(TemporalFailure::new(
6472                "Timestamp::sub_timedelta",
6473                PandasTemporalError::OutOfBoundsDatetime,
6474            )
6475            .with_operands(self.nanos, td_nanos)),
6476        }
6477    }
6478
6479    /// Subtract another Timestamp. Returns a Timedelta (i64 nanos).
6480    /// NaT in either → `Timedelta::NAT`; overflow → `Timedelta::NAT`
6481    /// (`pd.Timestamp.min - pd.Timestamp.max` raises `OutOfBoundsDatetime`).
6482    #[must_use]
6483    pub fn sub_timestamp(&self, other: &Self) -> i64 {
6484        self.try_sub_timestamp(other).unwrap_or(Timedelta::NAT)
6485    }
6486
6487    /// Elapsed nanoseconds between two Timestamps, reporting overflow.
6488    ///
6489    /// # Errors
6490    /// [`PandasTemporalError::OutOfBoundsDatetime`], matching
6491    /// `pd.Timestamp.min - pd.Timestamp.max`.
6492    pub fn try_sub_timestamp(&self, other: &Self) -> Result<i64, TemporalFailure> {
6493        if self.is_nat() || other.is_nat() {
6494            return Ok(Timedelta::NAT);
6495        }
6496        self.nanos.checked_sub(other.nanos).ok_or(
6497            TemporalFailure::new(
6498                "Timestamp::sub_timestamp",
6499                PandasTemporalError::OutOfBoundsDatetime,
6500            )
6501            .with_operands(self.nanos, other.nanos),
6502        )
6503    }
6504
6505    /// NaT-aware semantic equality: two NaT Timestamps are equal to each
6506    /// other (matches pandas `pd.NaT == pd.NaT` under `equals()`, though
6507    /// pandas's `==` operator returns False for NaT==NaT — we follow the
6508    /// `semantic_eq` convention used elsewhere in fp-types).
6509    #[must_use]
6510    pub fn semantic_eq(&self, other: &Self) -> bool {
6511        if self.is_nat() && other.is_nat() {
6512            return true;
6513        }
6514        if self.is_nat() || other.is_nat() {
6515            return false;
6516        }
6517        self.nanos == other.nanos && self.tz == other.tz
6518    }
6519
6520    // ── Rounding to a Timedelta unit (br-frankenpandas-5h6n) ────────────
6521    //
6522    // Pure i64 arithmetic on the nanos axis. tz is preserved. Phase 3
6523    // chrono_tz integration will add a tz-aware variant that handles DST
6524    // boundaries correctly; these methods operate on the absolute time
6525    // axis, matching pandas's tz-naive `.floor` / `.ceil` / `.round`
6526    // semantics for unit values smaller than a day.
6527
6528    /// Round down to the nearest multiple of `unit_nanos`.
6529    ///
6530    /// Matches `pd.Timestamp(...).floor(unit)`. NaT in `self` or a
6531    /// non-positive `unit_nanos` returns NaT.
6532    #[must_use]
6533    pub fn floor_to(&self, unit_nanos: i64) -> Self {
6534        if self.is_nat() || unit_nanos <= 0 {
6535            return Self::nat();
6536        }
6537        let Some(nanos) = self.nanos.div_euclid(unit_nanos).checked_mul(unit_nanos) else {
6538            return Self::nat();
6539        };
6540        Self {
6541            nanos,
6542            tz: self.tz.clone(),
6543        }
6544    }
6545
6546    /// Round up to the nearest multiple of `unit_nanos`.
6547    ///
6548    /// Matches `pd.Timestamp(...).ceil(unit)`. NaT or non-positive
6549    /// `unit_nanos` returns NaT. Already-multiple inputs return self.
6550    #[must_use]
6551    pub fn ceil_to(&self, unit_nanos: i64) -> Self {
6552        if self.is_nat() || unit_nanos <= 0 {
6553            return Self::nat();
6554        }
6555        let rem = self.nanos.rem_euclid(unit_nanos);
6556        let nanos = if rem == 0 {
6557            self.nanos
6558        } else {
6559            // Checked, matching the sibling `floor_to` directly above
6560            // (br-frankenpandas-kyd16). A clamped i64::MAX would be a finite,
6561            // plausible ~year-2262 instant; `pd.Timestamp.max.ceil('D')`
6562            // raises OutOfBoundsDatetime "Cannot round ... without overflow".
6563            let Some(nanos) = self.nanos.checked_add(unit_nanos - rem) else {
6564                return Self::nat();
6565            };
6566            nanos
6567        };
6568        Self {
6569            nanos,
6570            tz: self.tz.clone(),
6571        }
6572    }
6573
6574    /// Round to the nearest multiple of `unit_nanos`, banker's rounding
6575    /// (half-to-even) on ties.
6576    ///
6577    /// Matches `pd.Timestamp(...).round(unit)`. NaT or non-positive
6578    /// `unit_nanos` returns NaT.
6579    #[must_use]
6580    pub fn round_to(&self, unit_nanos: i64) -> Self {
6581        if self.is_nat() || unit_nanos <= 0 {
6582            return Self::nat();
6583        }
6584        let floor = self.nanos.div_euclid(unit_nanos);
6585        let rem = self.nanos.rem_euclid(unit_nanos);
6586        let half = unit_nanos / 2;
6587        let chosen_floor = if rem < half {
6588            floor
6589        } else if rem > half {
6590            floor + 1
6591        } else if unit_nanos % 2 != 0 {
6592            // Odd unit can't have a true half; treat as round-up.
6593            floor + 1
6594        } else {
6595            // Tie: pick the even multiple.
6596            if floor % 2 == 0 { floor } else { floor + 1 }
6597        };
6598        // Checked, matching the sibling `floor_to` (br-frankenpandas-kyd16):
6599        // `pd.Timestamp.max.round('D')` raises OutOfBoundsDatetime rather than
6600        // returning the clamped i64::MAX instant.
6601        let Some(nanos) = chosen_floor.checked_mul(unit_nanos) else {
6602            return Self::nat();
6603        };
6604        Self {
6605            nanos,
6606            tz: self.tz.clone(),
6607        }
6608    }
6609
6610    // ── String-unit rounding (br-frankenpandas-lbsx) ────────────────────
6611    //
6612    // Pandas convenience: `.floor('H')` / `.ceil('1D')` / `.round('15min')`.
6613    // These read the frequency with `fixed_freq_nanos`, then delegate to
6614    // the nanos-based `floor_to`/`ceil_to`/`round_to`. Unknown unit strings
6615    // return NaT, matching the rest of fp-types' "missing-input → missing-
6616    // output" convention.
6617
6618    /// A fixed frequency's length: a bare unit (`Timedelta::unit_to_nanos`)
6619    /// or a multiple of one ('15min', '1D', '30s' - they were unknown, so
6620    /// `round('15min')` was NaT); None for anything else.
6621    fn fixed_freq_nanos(freq: &str) -> Option<i64> {
6622        Timedelta::unit_to_nanos(freq).or_else(|| Timedelta::parse(freq).ok())
6623    }
6624
6625    /// Round down to the nearest multiple of the named unit.
6626    ///
6627    /// Matches `pd.Timestamp(...).floor(unit)`. Unknown unit → NaT.
6628    #[must_use]
6629    pub fn floor_to_unit(&self, unit: &str) -> Self {
6630        match Self::fixed_freq_nanos(unit) {
6631            Some(unit_nanos) => self.floor_to(unit_nanos),
6632            None => Self::nat(),
6633        }
6634    }
6635
6636    /// Round up to the nearest multiple of the named unit.
6637    ///
6638    /// Matches `pd.Timestamp(...).ceil(unit)`. Unknown unit → NaT.
6639    #[must_use]
6640    pub fn ceil_to_unit(&self, unit: &str) -> Self {
6641        match Self::fixed_freq_nanos(unit) {
6642            Some(unit_nanos) => self.ceil_to(unit_nanos),
6643            None => Self::nat(),
6644        }
6645    }
6646
6647    /// Round to the nearest multiple of the named unit, banker's rounding.
6648    ///
6649    /// Matches `pd.Timestamp(...).round(unit)`. Unknown unit → NaT.
6650    #[must_use]
6651    pub fn round_to_unit(&self, unit: &str) -> Self {
6652        match Self::fixed_freq_nanos(unit) {
6653            Some(unit_nanos) => self.round_to(unit_nanos),
6654            None => Self::nat(),
6655        }
6656    }
6657
6658    /// Pandas-named alias for [`floor_to_unit`](Self::floor_to_unit).
6659    #[must_use]
6660    pub fn floor(&self, freq: &str) -> Self {
6661        self.floor_to_unit(freq)
6662    }
6663
6664    /// Pandas-named alias for [`ceil_to_unit`](Self::ceil_to_unit).
6665    #[must_use]
6666    pub fn ceil(&self, freq: &str) -> Self {
6667        self.ceil_to_unit(freq)
6668    }
6669
6670    /// Pandas-named alias for [`round_to_unit`](Self::round_to_unit).
6671    #[must_use]
6672    pub fn round(&self, freq: &str) -> Self {
6673        self.round_to_unit(freq)
6674    }
6675
6676    /// Extract the year component from the timestamp.
6677    ///
6678    /// Matches `pd.Timestamp.year`. Returns None for NaT.
6679    #[must_use]
6680    pub fn year(&self) -> Option<i64> {
6681        if self.is_nat() {
6682            return None;
6683        }
6684        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
6685        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
6686        // for the post-1970 positive case.
6687        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
6688        let days = days_since_epoch + 719_468;
6689        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
6690        let doe = days - era * 146_097;
6691        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
6692        let y = yoe + era * 400;
6693        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
6694        let mp = (5 * doy + 2) / 153;
6695        let m = if mp < 10 { mp + 3 } else { mp - 9 };
6696        Some(if m <= 2 { y + 1 } else { y })
6697    }
6698
6699    /// Extract the month component (1-12) from the timestamp.
6700    ///
6701    /// Matches `pd.Timestamp.month`. Returns None for NaT.
6702    #[must_use]
6703    pub fn month(&self) -> Option<i64> {
6704        if self.is_nat() {
6705            return None;
6706        }
6707        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
6708        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
6709        // for the post-1970 positive case.
6710        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
6711        let days = days_since_epoch + 719_468;
6712        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
6713        let doe = days - era * 146_097;
6714        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
6715        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
6716        let mp = (5 * doy + 2) / 153;
6717        Some(if mp < 10 { mp + 3 } else { mp - 9 })
6718    }
6719
6720    /// Extract the day component (1-31) from the timestamp.
6721    ///
6722    /// Matches `pd.Timestamp.day`. Returns None for NaT.
6723    #[must_use]
6724    pub fn day(&self) -> Option<i64> {
6725        if self.is_nat() {
6726            return None;
6727        }
6728        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
6729        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
6730        // for the post-1970 positive case.
6731        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
6732        let days = days_since_epoch + 719_468;
6733        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
6734        let doe = days - era * 146_097;
6735        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
6736        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
6737        let mp = (5 * doy + 2) / 153;
6738        Some(doy - (153 * mp + 2) / 5 + 1)
6739    }
6740
6741    /// Extract the hour component (0-23) from the timestamp.
6742    ///
6743    /// Matches `pd.Timestamp.hour`. Returns None for NaT.
6744    #[must_use]
6745    pub fn hour(&self) -> Option<i64> {
6746        if self.is_nat() {
6747            return None;
6748        }
6749        // rem_euclid keeps the seconds-of-day in [0, 86400) even for negative
6750        // (pre-1970) nanos with a sub-second part (br-frankenpandas-wkjtw);
6751        // rem_euclid == `%` for the post-1970 positive case.
6752        let secs_of_day =
6753            self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
6754        Some(secs_of_day / 3600)
6755    }
6756
6757    /// Extract the minute component (0-59) from the timestamp.
6758    ///
6759    /// Matches `pd.Timestamp.minute`. Returns None for NaT.
6760    #[must_use]
6761    pub fn minute(&self) -> Option<i64> {
6762        if self.is_nat() {
6763            return None;
6764        }
6765        // rem_euclid keeps the seconds-of-day in [0, 86400) even for negative
6766        // (pre-1970) nanos with a sub-second part (br-frankenpandas-wkjtw);
6767        // rem_euclid == `%` for the post-1970 positive case.
6768        let secs_of_day =
6769            self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
6770        Some((secs_of_day % 3600) / 60)
6771    }
6772
6773    /// Extract the second component (0-59) from the timestamp.
6774    ///
6775    /// Matches `pd.Timestamp.second`. Returns None for NaT.
6776    #[must_use]
6777    pub fn second(&self) -> Option<i64> {
6778        if self.is_nat() {
6779            return None;
6780        }
6781        // rem_euclid keeps the seconds-of-day in [0, 86400) even for negative
6782        // (pre-1970) nanos with a sub-second part (br-frankenpandas-wkjtw);
6783        // rem_euclid == `%` for the post-1970 positive case.
6784        let secs_of_day =
6785            self.nanos.rem_euclid(Timedelta::NANOS_PER_DAY) / Timedelta::NANOS_PER_SEC;
6786        Some(secs_of_day % 60)
6787    }
6788
6789    /// Extract the microsecond component (0-999999) from the timestamp.
6790    ///
6791    /// Matches `pd.Timestamp.microsecond`. Returns None for NaT.
6792    #[must_use]
6793    pub fn microsecond(&self) -> Option<i64> {
6794        if self.is_nat() {
6795            return None;
6796        }
6797        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos
6798        // (br-frankenpandas-wkjtw); == `%` for the post-1970 positive case.
6799        let sub_nanos = self.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
6800        Some((sub_nanos / 1000) as i64)
6801    }
6802
6803    /// Extract the nanosecond component (0-999) from the timestamp.
6804    ///
6805    /// Matches `pd.Timestamp.nanosecond`. Returns None for NaT.
6806    #[must_use]
6807    pub fn nanosecond(&self) -> Option<i64> {
6808        if self.is_nat() {
6809            return None;
6810        }
6811        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos
6812        // (br-frankenpandas-wkjtw); == `%` for the post-1970 positive case.
6813        let sub_nanos = self.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
6814        Some((sub_nanos % 1000) as i64)
6815    }
6816
6817    /// Return the day of the week (Monday=0, Sunday=6).
6818    ///
6819    /// Matches `pd.Timestamp.dayofweek`. Returns None for NaT.
6820    #[must_use]
6821    pub fn dayofweek(&self) -> Option<i64> {
6822        if self.is_nat() {
6823            return None;
6824        }
6825        // Floor days for pre-1970 (br-frankenpandas-wkjtw); == `/` for positive.
6826        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
6827        let dow = ((days_since_epoch + 3) % 7 + 7) % 7;
6828        Some(dow)
6829    }
6830
6831    /// Alias for dayofweek(). Matches `pd.Timestamp.weekday`.
6832    #[must_use]
6833    pub fn weekday(&self) -> Option<i64> {
6834        self.dayofweek()
6835    }
6836
6837    /// Alias for dayofweek(). Matches `pd.Timestamp.day_of_week`.
6838    #[must_use]
6839    pub fn day_of_week(&self) -> Option<i64> {
6840        self.dayofweek()
6841    }
6842
6843    /// Return the day of the year (1-366).
6844    ///
6845    /// Matches `pd.Timestamp.dayofyear`. Returns None for NaT.
6846    #[must_use]
6847    pub fn dayofyear(&self) -> Option<i64> {
6848        if self.is_nat() {
6849            return None;
6850        }
6851        let m = self.month()?;
6852        let d = self.day()?;
6853        let y = self.year()?;
6854        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
6855        let days_before: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
6856        let base = days_before[(m - 1) as usize] + d;
6857        if is_leap && m > 2 {
6858            Some(base + 1)
6859        } else {
6860            Some(base)
6861        }
6862    }
6863
6864    /// Alias for dayofyear(). Matches `pd.Timestamp.day_of_year`.
6865    #[must_use]
6866    pub fn day_of_year(&self) -> Option<i64> {
6867        self.dayofyear()
6868    }
6869
6870    /// Return the proleptic Gregorian ordinal (number of days since Jan 1, year 1).
6871    ///
6872    /// Matches `pd.Timestamp.toordinal()`. Returns None for NaT.
6873    #[must_use]
6874    pub fn toordinal(&self) -> Option<i64> {
6875        if self.is_nat() {
6876            return None;
6877        }
6878        let y = self.year()?;
6879        let m = self.month()?;
6880        let d = self.day()?;
6881        // Algorithm: count days from year 1 to the start of the given year,
6882        // add days in the months before the given month, add the day of month.
6883        // Account for leap years.
6884        let y_minus_1 = y - 1;
6885        let mut ordinal = y_minus_1 * 365 + y_minus_1 / 4 - y_minus_1 / 100 + y_minus_1 / 400;
6886        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
6887        let days_before: [i64; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
6888        ordinal += days_before[(m - 1) as usize];
6889        if is_leap && m > 2 {
6890            ordinal += 1;
6891        }
6892        ordinal += d;
6893        Some(ordinal)
6894    }
6895
6896    /// Construct a Timestamp from a proleptic Gregorian ordinal.
6897    ///
6898    /// Matches `pd.Timestamp.fromordinal(ordinal)`. Returns NaT for invalid ordinals.
6899    #[must_use]
6900    pub fn fromordinal(ordinal: i64) -> Self {
6901        if ordinal <= 0 {
6902            return Self {
6903                nanos: Self::NAT,
6904                tz: None,
6905            };
6906        }
6907        // Convert y/m/d to days since Unix epoch, then to nanos
6908        // Unix epoch is 1970-01-01, which is ordinal 719163
6909        let days_since_epoch = ordinal - 719163;
6910        match days_since_epoch.checked_mul(Timedelta::NANOS_PER_DAY) {
6911            Some(nanos) => Self { nanos, tz: None },
6912            None => Self::nat(),
6913        }
6914    }
6915
6916    /// Return the Julian Date (astronomical day number).
6917    ///
6918    /// Matches `pd.Timestamp.to_julian_date()`. Returns NaN for NaT.
6919    /// The Julian Date is the continuous count of days since the beginning
6920    /// of the Julian Period (January 1, 4713 BC in the proleptic Julian calendar).
6921    #[must_use]
6922    pub fn to_julian_date(&self) -> f64 {
6923        if self.is_nat() {
6924            return f64::NAN;
6925        }
6926        // Gregorian ordinal 1 (Jan 1, year 1) corresponds to Julian Day 1721425.5
6927        // (at noon, since JD starts at noon)
6928        // For a timestamp at midnight, we subtract 0.5
6929        let ordinal = match self.toordinal() {
6930            Some(o) => o,
6931            None => return f64::NAN,
6932        };
6933        // Fractional day from time components
6934        let h = self.hour().unwrap_or(0) as f64;
6935        let m = self.minute().unwrap_or(0) as f64;
6936        let s = self.second().unwrap_or(0) as f64;
6937        let us = self.microsecond().unwrap_or(0) as f64;
6938        let ns = self.nanosecond().unwrap_or(0) as f64;
6939        let frac_day =
6940            (h + m / 60.0 + s / 3600.0 + us / 3_600_000_000.0 + ns / 3_600_000_000_000.0) / 24.0;
6941        // Julian day at midnight of ordinal 1 is 1721424.5
6942        1721424.5 + ordinal as f64 + frac_day
6943    }
6944
6945    /// Return the quarter (1-4) of the year.
6946    ///
6947    /// Matches `pd.Timestamp.quarter`. Returns None for NaT.
6948    #[must_use]
6949    pub fn quarter(&self) -> Option<i64> {
6950        self.month().map(|m| (m - 1) / 3 + 1)
6951    }
6952
6953    /// Return the ISO week number (1-53).
6954    ///
6955    /// Matches `pd.Timestamp.week`. Returns None for NaT.
6956    #[must_use]
6957    pub fn weekofyear(&self) -> Option<i64> {
6958        if self.is_nat() {
6959            return None;
6960        }
6961        let doy = self.dayofyear()?;
6962        let dow = self.dayofweek()?;
6963        let year = self.year()?;
6964        let iso_dow = if dow == 6 { 7 } else { dow + 1 };
6965        let week = (doy - iso_dow + 10) / 7;
6966        // ISO-8601 has 53-week years, so the clamps must consult the actual
6967        // week count, not hardcode 52/1: a week<1 belongs to the LAST week of
6968        // the previous year (52 OR 53), and a week beyond this year's count
6969        // wraps to week 1 of the next year. pandas isocalendar().week agrees:
6970        // 2021-01-01 -> 53 (2020 is a 53-week year), 2026-12-31 -> 53.
6971        if week < 1 {
6972            Some(iso_weeks_in_year(year - 1))
6973        } else if week > iso_weeks_in_year(year) {
6974            Some(1)
6975        } else {
6976            Some(week)
6977        }
6978    }
6979
6980    /// Alias for weekofyear(). Matches `pd.Timestamp.week`.
6981    #[must_use]
6982    pub fn week(&self) -> Option<i64> {
6983        self.weekofyear()
6984    }
6985
6986    /// Return the timestamp value in the specified unit.
6987    ///
6988    /// Matches `pd.Timestamp.value` when unit is nanoseconds.
6989    /// Supported units: "ns", "us", "ms", "s".
6990    #[must_use]
6991    pub fn to_unit(&self, unit: &str) -> Option<i64> {
6992        if self.is_nat() {
6993            return None;
6994        }
6995        match unit {
6996            "ns" | "nanosecond" | "nanoseconds" => Some(self.nanos),
6997            "us" | "microsecond" | "microseconds" => Some(self.nanos / 1_000),
6998            "ms" | "millisecond" | "milliseconds" => Some(self.nanos / 1_000_000),
6999            "s" | "second" | "seconds" => Some(self.nanos / 1_000_000_000),
7000            _ => None,
7001        }
7002    }
7003
7004    /// Whether the year is a leap year.
7005    ///
7006    /// Matches `pd.Timestamp.is_leap_year`. Returns None for NaT.
7007    #[must_use]
7008    pub fn is_leap_year(&self) -> Option<bool> {
7009        self.year()
7010            .map(|y| (y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
7011    }
7012
7013    /// Whether the day is the first day of the month.
7014    ///
7015    /// Matches `pd.Timestamp.is_month_start`. Returns None for NaT.
7016    #[must_use]
7017    pub fn is_month_start(&self) -> Option<bool> {
7018        self.day().map(|d| d == 1)
7019    }
7020
7021    /// Whether the day is the last day of the month.
7022    ///
7023    /// Matches `pd.Timestamp.is_month_end`. Returns None for NaT.
7024    #[must_use]
7025    pub fn is_month_end(&self) -> Option<bool> {
7026        let y = self.year()?;
7027        let m = self.month()?;
7028        let d = self.day()?;
7029        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7030        let days_in_month: [i64; 12] = [
7031            31,
7032            if is_leap { 29 } else { 28 },
7033            31,
7034            30,
7035            31,
7036            30,
7037            31,
7038            31,
7039            30,
7040            31,
7041            30,
7042            31,
7043        ];
7044        Some(d == days_in_month[(m - 1) as usize])
7045    }
7046
7047    /// Whether the day is the first day of a quarter.
7048    ///
7049    /// Matches `pd.Timestamp.is_quarter_start`. Returns None for NaT.
7050    #[must_use]
7051    pub fn is_quarter_start(&self) -> Option<bool> {
7052        let m = self.month()?;
7053        let d = self.day()?;
7054        Some(d == 1 && (m == 1 || m == 4 || m == 7 || m == 10))
7055    }
7056
7057    /// Whether the day is the last day of a quarter.
7058    ///
7059    /// Matches `pd.Timestamp.is_quarter_end`. Returns None for NaT.
7060    #[must_use]
7061    pub fn is_quarter_end(&self) -> Option<bool> {
7062        let m = self.month()?;
7063        let d = self.day()?;
7064        Some(
7065            (m == 3 && d == 31)
7066                || (m == 6 && d == 30)
7067                || (m == 9 && d == 30)
7068                || (m == 12 && d == 31),
7069        )
7070    }
7071
7072    /// Whether the day is the first day of the year (Jan 1).
7073    ///
7074    /// Matches `pd.Timestamp.is_year_start`. Returns None for NaT.
7075    #[must_use]
7076    pub fn is_year_start(&self) -> Option<bool> {
7077        let m = self.month()?;
7078        let d = self.day()?;
7079        Some(m == 1 && d == 1)
7080    }
7081
7082    /// Whether the day is the last day of the year (Dec 31).
7083    ///
7084    /// Matches `pd.Timestamp.is_year_end`. Returns None for NaT.
7085    #[must_use]
7086    pub fn is_year_end(&self) -> Option<bool> {
7087        let m = self.month()?;
7088        let d = self.day()?;
7089        Some(m == 12 && d == 31)
7090    }
7091
7092    /// Return the number of days in the month of this timestamp.
7093    ///
7094    /// Matches `pd.Timestamp.days_in_month`. Returns None for NaT.
7095    #[must_use]
7096    pub fn days_in_month(&self) -> Option<i64> {
7097        let y = self.year()?;
7098        let m = self.month()?;
7099        let is_leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
7100        let days: [i64; 12] = [
7101            31,
7102            if is_leap { 29 } else { 28 },
7103            31,
7104            30,
7105            31,
7106            30,
7107            31,
7108            31,
7109            30,
7110            31,
7111            30,
7112            31,
7113        ];
7114        Some(days[(m - 1) as usize])
7115    }
7116
7117    /// Alias for days_in_month(). Matches `pd.Timestamp.daysinmonth`.
7118    #[must_use]
7119    pub fn daysinmonth(&self) -> Option<i64> {
7120        self.days_in_month()
7121    }
7122
7123    /// Normalize to midnight/day boundary, matching `pd.Timestamp.normalize()`.
7124    #[must_use]
7125    pub fn normalize(&self) -> Self {
7126        self.floor_to(Timedelta::NANOS_PER_DAY)
7127    }
7128
7129    /// Replace timestamp components with new values.
7130    ///
7131    /// Matches pd.Timestamp.replace(). None values keep the existing component.
7132    #[must_use]
7133    #[allow(clippy::too_many_arguments)]
7134    pub fn replace(
7135        &self,
7136        year: Option<i64>,
7137        month: Option<i64>,
7138        day: Option<i64>,
7139        hour: Option<i64>,
7140        minute: Option<i64>,
7141        second: Option<i64>,
7142        microsecond: Option<i64>,
7143        nanosecond: Option<i64>,
7144    ) -> Self {
7145        if self.is_nat() {
7146            return self.clone();
7147        }
7148        let cur_year = self.year().unwrap_or(1970);
7149        let cur_month = self.month().unwrap_or(1);
7150        let cur_day = self.day().unwrap_or(1);
7151        let cur_hour = self.hour().unwrap_or(0);
7152        let cur_minute = self.minute().unwrap_or(0);
7153        let cur_second = self.second().unwrap_or(0);
7154        let cur_micro = self.microsecond().unwrap_or(0);
7155        let cur_nano = self.nanosecond().unwrap_or(0);
7156
7157        let y = year.unwrap_or(cur_year);
7158        let mo = month.unwrap_or(cur_month);
7159        let d = day.unwrap_or(cur_day);
7160        let h = hour.unwrap_or(cur_hour);
7161        let mi = minute.unwrap_or(cur_minute);
7162        let s = second.unwrap_or(cur_second);
7163        let us = microsecond.unwrap_or(cur_micro);
7164        let ns = nanosecond.unwrap_or(cur_nano);
7165
7166        if !(1..=12).contains(&mo)
7167            || !(1..=days_in_month(y, mo as u32).unwrap_or(0) as i64).contains(&d)
7168            || !(0..=23).contains(&h)
7169            || !(0..=59).contains(&mi)
7170            || !(0..=59).contains(&s)
7171            || !(0..=999_999).contains(&us)
7172            || !(0..=999).contains(&ns)
7173        {
7174            return Self::nat();
7175        }
7176
7177        // Checked nanosecond arithmetic (br-frankenpandas-dzz6x). The component
7178        // validation above rejects an out-of-range month/day/hour/... but says
7179        // nothing about the YEAR, and i64 nanoseconds run out at
7180        // `i64::MAX / NANOS_PER_DAY` = 106_751 days from the epoch — about year
7181        // 2262, the same bound pandas documents for ns-resolution Timestamps.
7182        // Unchecked, `replace(year=3000)` wrapped in release mode and returned a
7183        // silently wrong, plausible-looking in-range instant. Overflow now folds
7184        // to NaT, matching both the validation arm above and the sibling
7185        // constructors `fromordinal` / `floor_to`, which already fail this way.
7186        // In-range results are unchanged: the checked ops return exactly the
7187        // value the plain operators produced whenever no overflow occurred.
7188        let days_from_epoch = Self::days_from_ymd(y, mo, d);
7189        let secs = h * 3600 + mi * 60 + s;
7190        let Some(total_nanos) = days_from_epoch
7191            .checked_mul(Timedelta::NANOS_PER_DAY)
7192            .and_then(|nanos| {
7193                secs.checked_mul(Timedelta::NANOS_PER_SEC)
7194                    .and_then(|s_nanos| nanos.checked_add(s_nanos))
7195            })
7196            .and_then(|nanos| {
7197                us.checked_mul(Timedelta::NANOS_PER_MICRO)
7198                    .and_then(|us_nanos| nanos.checked_add(us_nanos))
7199            })
7200            .and_then(|nanos| nanos.checked_add(ns))
7201        else {
7202            return Self::nat();
7203        };
7204
7205        Self {
7206            nanos: total_nanos,
7207            tz: self.tz.clone(),
7208        }
7209    }
7210
7211    fn days_from_ymd(year: i64, month: i64, day: i64) -> i64 {
7212        let y = if month <= 2 { year - 1 } else { year };
7213        let era = if y >= 0 { y } else { y - 399 } / 400;
7214        let yoe = y - era * 400;
7215        let doy = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1;
7216        let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
7217        era * 146097 + doe - 719468
7218    }
7219
7220    /// Return an ISO 8601 string representation of the timestamp.
7221    ///
7222    /// Matches `pd.Timestamp.isoformat()`. NaT returns "NaT".
7223    #[must_use]
7224    pub fn isoformat(&self) -> String {
7225        use std::fmt::Write as _;
7226
7227        if self.is_nat() {
7228            return "NaT".to_string();
7229        }
7230        let display_nanos = self
7231            .tz
7232            .as_deref()
7233            .and_then(Self::fixed_utc_offset_seconds)
7234            .and_then(|offset| self.nanos.checked_add(offset * Timedelta::NANOS_PER_SEC))
7235            .unwrap_or(self.nanos);
7236        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos
7237        // (br-frankenpandas-wkjtw); == `%` for the post-1970 positive case.
7238        let days_since_epoch = display_nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7239        let nanos_of_day = display_nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
7240        let secs_of_day = nanos_of_day / Timedelta::NANOS_PER_SEC;
7241        let sub_nanos = nanos_of_day.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
7242
7243        let days = days_since_epoch + 719_468;
7244        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7245        let doe = days - era * 146_097;
7246        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7247        let y = yoe + era * 400;
7248        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7249        let mp = (5 * doy + 2) / 153;
7250        let d = doy - (153 * mp + 2) / 5 + 1;
7251        let m = if mp < 10 { mp + 3 } else { mp - 9 };
7252        let year = if m <= 2 { y + 1 } else { y };
7253
7254        let hour = secs_of_day / 3600;
7255        let minute = (secs_of_day % 3600) / 60;
7256        let second = secs_of_day % 60;
7257
7258        // Build the timestamp and its optional timezone suffix in the returned
7259        // allocation. The former timezone-aware path first allocated `base`,
7260        // then allocated again to copy `base` into the suffixed result.
7261        let suffix_capacity = self
7262            .tz
7263            .as_ref()
7264            .map_or(0, |tz| if tz == "UTC" { 6 } else { tz.len() + 2 });
7265        let mut result = String::with_capacity(29 + suffix_capacity);
7266        if sub_nanos == 0 {
7267            let _ = write!(
7268                result,
7269                "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}"
7270            );
7271        } else if sub_nanos.is_multiple_of(1_000) {
7272            let _ = write!(
7273                result,
7274                "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{:06}",
7275                sub_nanos / 1_000
7276            );
7277        } else {
7278            let _ = write!(
7279                result,
7280                "{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{sub_nanos:09}"
7281            );
7282        }
7283        match &self.tz {
7284            Some(tz) if tz == "UTC" => result.push_str("+00:00"),
7285            Some(tz) if Self::fixed_utc_offset_seconds(tz).is_some() => {
7286                result.push_str(tz.strip_prefix("UTC").unwrap_or(tz));
7287            }
7288            Some(tz) => {
7289                result.push('[');
7290                result.push_str(tz);
7291                result.push(']');
7292            }
7293            None => {}
7294        }
7295        result
7296    }
7297
7298    /// Alias for isoformat.
7299    #[must_use]
7300    pub fn to_iso8601(&self) -> String {
7301        self.isoformat()
7302    }
7303
7304    /// The coarsest [`DatetimeStringResolution`] that renders `nanos` losslessly.
7305    ///
7306    /// Fold this over a column with `max` to get the column's width — see
7307    /// [`DatetimeStringResolution`] for why the width is a property of the
7308    /// COLUMN and not of the value. `NaT` reports [`DatetimeStringResolution`]
7309    /// `::Date`, the identity for that fold, because pandas excludes it from the
7310    /// scan entirely: a column of one midnight plus one NaT still renders
7311    /// `['2024-03-15', 'NaT']`.
7312    #[must_use]
7313    pub const fn string_resolution(nanos: i64) -> DatetimeStringResolution {
7314        if nanos == Self::NAT {
7315            return DatetimeStringResolution::Date;
7316        }
7317        if nanos.rem_euclid(Timedelta::NANOS_PER_DAY) == 0 {
7318            DatetimeStringResolution::Date
7319        } else if nanos.rem_euclid(Timedelta::NANOS_PER_SEC) == 0 {
7320            DatetimeStringResolution::Second
7321        } else if nanos.rem_euclid(Timedelta::NANOS_PER_MILLI) == 0 {
7322            DatetimeStringResolution::Milli
7323        } else if nanos.rem_euclid(Timedelta::NANOS_PER_MICRO) == 0 {
7324            DatetimeStringResolution::Micro
7325        } else {
7326            DatetimeStringResolution::Nano
7327        }
7328    }
7329
7330    /// Render `nanos` the way `astype(str)` does, at a resolution chosen for the
7331    /// whole column by [`Self::string_resolution`].
7332    ///
7333    /// ⚠️ NOT [`Self::isoformat`]. That one is `pd.Timestamp.isoformat()` — a `T`
7334    /// separator, and a width chosen per VALUE. This is the array formatter:
7335    /// a SPACE separator, and a width imposed on every element alike. MEASURED,
7336    /// live pandas 2.2.3, one column per rung:
7337    ///
7338    /// ```text
7339    /// all midnight       -> '2024-03-15'
7340    /// all whole seconds  -> '2024-03-15 10:30:45'
7341    /// all whole millis   -> '2024-03-15 10:30:45.123'
7342    /// all whole micros   -> '2024-03-15 10:30:45.123456'
7343    /// anything finer     -> '2024-03-15 10:30:45.123456789'
7344    /// NaT                -> 'NaT'          (a STRING, not a missing value)
7345    /// ```
7346    ///
7347    /// There is NO minute rung: a column of whole minutes still renders its
7348    /// seconds (`'2024-01-01 00:05:00'`).
7349    #[must_use]
7350    pub fn format_at_resolution(nanos: i64, resolution: DatetimeStringResolution) -> String {
7351        use std::fmt::Write as _;
7352
7353        if nanos == Self::NAT {
7354            return "NaT".to_string();
7355        }
7356        // rem_euclid keeps the sub-second part in [0, 1e9) for negative nanos,
7357        // the same correction isoformat makes (br-frankenpandas-wkjtw): a
7358        // pre-epoch value must render 1969-12-31 23:59:59.999999999, not a
7359        // negative fraction.
7360        let days_since_epoch = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7361        let nanos_of_day = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
7362        let secs_of_day = nanos_of_day / Timedelta::NANOS_PER_SEC;
7363        let sub_nanos = nanos_of_day.rem_euclid(Timedelta::NANOS_PER_SEC);
7364        // The crate's existing Hinnant civil-from-days, NOT a second copy: two
7365        // implementations of a calendar algorithm are two chances to drift.
7366        let (year, month, day) = civil_from_days(days_since_epoch);
7367
7368        // pandas' datetime64[ns] range is 1677..=2262, so the year is always
7369        // four digits and `{:04}` never truncates.
7370        let mut result = String::with_capacity(30);
7371        // `fmt::Write for String` is infallible.
7372        let _ = write!(result, "{year:04}-{month:02}-{day:02}");
7373        if matches!(resolution, DatetimeStringResolution::Date) {
7374            return result;
7375        }
7376        let _ = write!(
7377            result,
7378            " {:02}:{:02}:{:02}",
7379            secs_of_day / 3600,
7380            (secs_of_day % 3600) / 60,
7381            secs_of_day % 60
7382        );
7383        let (fraction, width) = match resolution {
7384            DatetimeStringResolution::Date | DatetimeStringResolution::Second => return result,
7385            DatetimeStringResolution::Milli => (sub_nanos / Timedelta::NANOS_PER_MILLI, 3_usize),
7386            DatetimeStringResolution::Micro => (sub_nanos / Timedelta::NANOS_PER_MICRO, 6_usize),
7387            DatetimeStringResolution::Nano => (sub_nanos, 9_usize),
7388        };
7389        let _ = write!(result, ".{fraction:0width$}", width = width);
7390        result
7391    }
7392
7393    /// Parse a datetime string into a Timestamp.
7394    ///
7395    /// Supports ISO 8601 formats:
7396    /// - "2024-01-15" (date only, time defaults to 00:00:00)
7397    /// - "2024-01-15T10:30:00" (datetime)
7398    /// - "2024-01-15 10:30:00" (space separator)
7399    /// - "2024-01-15T10:30:00.123456" (with fractional seconds)
7400    /// - "2024-01-15T10:30:00Z" (UTC timezone)
7401    /// - "2024-01-15T10:30:00+05:30" (offset timezone)
7402    /// - "NaT" (Not a Timestamp)
7403    ///
7404    /// Matches `pd.Timestamp()` constructor behavior.
7405    pub fn parse(s: &str) -> Result<Self, TypeError> {
7406        let s = s.trim();
7407
7408        if s.eq_ignore_ascii_case("nat") {
7409            return Ok(Self::nat());
7410        }
7411
7412        let Some((datetime_part, tz)) = Self::split_timezone(s) else {
7413            return Err(TypeError::ValueNotParseable {
7414                value: s.to_string(),
7415                target: "Timestamp".to_string(),
7416            });
7417        };
7418
7419        let (date_part, time_part) = if datetime_part.contains('T') {
7420            datetime_part
7421                .split_once('T')
7422                .ok_or_else(|| TypeError::ValueNotParseable {
7423                    value: s.to_string(),
7424                    target: "Timestamp".to_string(),
7425                })?
7426        } else if datetime_part.contains(' ')
7427            && datetime_part.chars().filter(|&c| c == ' ').count() == 1
7428        {
7429            datetime_part
7430                .split_once(' ')
7431                .ok_or_else(|| TypeError::ValueNotParseable {
7432                    value: s.to_string(),
7433                    target: "Timestamp".to_string(),
7434                })?
7435        } else {
7436            (datetime_part, "00:00:00")
7437        };
7438
7439        let (year, month, day) =
7440            Self::parse_date(date_part).ok_or_else(|| TypeError::ValueNotParseable {
7441                value: s.to_string(),
7442                target: "Timestamp".to_string(),
7443            })?;
7444
7445        let (hour, minute, second, nanos) =
7446            Self::parse_time(time_part).ok_or_else(|| TypeError::ValueNotParseable {
7447                value: s.to_string(),
7448                target: "Timestamp".to_string(),
7449            })?;
7450
7451        // br-frankenpandas-94o1u: an unrepresentable instant is a parse
7452        // failure, not a wrapped value.
7453        let wall_nanos = Self::ymd_hms_to_nanos(year, month, day, hour, minute, second, nanos)
7454            .ok_or_else(|| TypeError::ValueNotParseable {
7455                value: s.to_string(),
7456                target: "Timestamp".to_string(),
7457            })?;
7458        // The digits are the wall clock at the offset; the instant is that
7459        // wall time less the offset ('10:00+09:00' is 01:00 UTC - it was
7460        // read as 10:00 UTC, so it showed as 19:00+09:00).
7461        let offset = tz
7462            .as_deref()
7463            .and_then(Self::fixed_utc_offset_seconds)
7464            .unwrap_or(0);
7465        let total_nanos = offset
7466            .checked_mul(1_000_000_000)
7467            .and_then(|offset| wall_nanos.checked_sub(offset))
7468            .ok_or_else(|| TypeError::ValueNotParseable {
7469                value: s.to_string(),
7470                target: "Timestamp".to_string(),
7471            })?;
7472
7473        Ok(if let Some(tz_name) = tz {
7474            Self::from_nanos_tz(total_nanos, tz_name)
7475        } else {
7476            Self::from_nanos(total_nanos)
7477        })
7478    }
7479
7480    fn split_timezone(s: &str) -> Option<(&str, Option<String>)> {
7481        if let Some(stripped) = s.strip_suffix('Z') {
7482            Some((stripped, Some("UTC".to_string())))
7483        } else if let Some(idx) = s.rfind('+') {
7484            if idx > 10 && Self::is_timezone_offset(&s[idx..]) {
7485                Some((&s[..idx], Some(s[idx..].to_string())))
7486            } else if idx > 10 {
7487                None
7488            } else {
7489                Some((s, None))
7490            }
7491        } else if let Some(idx) = s.rfind('-') {
7492            if idx > 10 && Self::is_timezone_offset(&s[idx..]) {
7493                Some((&s[..idx], Some(s[idx..].to_string())))
7494            } else if idx > 10 {
7495                None
7496            } else {
7497                Some((s, None))
7498            }
7499        } else {
7500            Some((s, None))
7501        }
7502    }
7503
7504    fn fixed_utc_offset_seconds(tz: &str) -> Option<i64> {
7505        if tz == "UTC" {
7506            return Some(0);
7507        }
7508        let offset = tz.strip_prefix("UTC").unwrap_or(tz);
7509        if !Self::is_timezone_offset(offset) {
7510            return None;
7511        }
7512        let sign = if offset.starts_with('+') { 1 } else { -1 };
7513        let hours = offset[1..3].parse::<i64>().ok()?;
7514        let minutes = offset[4..6].parse::<i64>().ok()?;
7515        Some(sign * (hours * 3_600 + minutes * 60))
7516    }
7517
7518    fn is_timezone_offset(s: &str) -> bool {
7519        let bytes = s.as_bytes();
7520        if bytes.len() != 6 || !matches!(bytes[0], b'+' | b'-') || bytes[3] != b':' {
7521            return false;
7522        }
7523        if !bytes[1..3].iter().all(u8::is_ascii_digit)
7524            || !bytes[4..6].iter().all(u8::is_ascii_digit)
7525        {
7526            return false;
7527        }
7528        let hour = u32::from(bytes[1] - b'0') * 10 + u32::from(bytes[2] - b'0');
7529        let minute = u32::from(bytes[4] - b'0') * 10 + u32::from(bytes[5] - b'0');
7530        hour <= 23 && minute <= 59
7531    }
7532
7533    fn parse_date(s: &str) -> Option<(i64, u32, u32)> {
7534        let parts: Vec<&str> = s.split('-').collect();
7535        if parts.len() != 3 {
7536            return None;
7537        }
7538        let year: i64 = parts[0].parse().ok()?;
7539        let month: u32 = parts[1].parse().ok()?;
7540        let day: u32 = parts[2].parse().ok()?;
7541        if !(1..=days_in_month(year, month)?).contains(&day) {
7542            return None;
7543        }
7544        Some((year, month, day))
7545    }
7546
7547    fn parse_time(s: &str) -> Option<(u32, u32, u32, u64)> {
7548        let (time_str, frac_str) = match s.split_once('.') {
7549            Some((time, frac)) => (time, Some(frac)),
7550            None => (s, None),
7551        };
7552        let parts: Vec<&str> = time_str.split(':').collect();
7553        if parts.is_empty() || parts.len() > 3 {
7554            return None;
7555        }
7556        let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
7557        let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
7558        let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
7559
7560        if hour > 23 || minute > 59 || second > 59 {
7561            return None;
7562        }
7563
7564        let nanos = match frac_str {
7565            None => 0,
7566            Some(frac) => {
7567                if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
7568                    return None;
7569                }
7570                let digits = frac.len().min(9);
7571                let mut nanos = 0_u64;
7572                for byte in frac.bytes().take(digits) {
7573                    nanos = nanos * 10 + u64::from(byte - b'0');
7574                }
7575                for _ in digits..9 {
7576                    nanos *= 10;
7577                }
7578                nanos
7579            }
7580        };
7581
7582        Some((hour, minute, second, nanos))
7583    }
7584
7585    /// Compose a civil date-time into i64 nanoseconds since the epoch, or
7586    /// `None` when the instant is not representable.
7587    ///
7588    /// Checked composition (br-frankenpandas-94o1u). `parse_date` validates the
7589    /// month and the day-of-month but parses the YEAR as an unbounded `i64`,
7590    /// and i64 nanoseconds top out around year 2262 — the bound pandas
7591    /// documents for ns-resolution Timestamps. Unchecked, the two multiplies
7592    /// below wrapped in release, so `Timestamp::parse("300000-01-01")` returned
7593    /// `Ok` holding a silently wrong, plausible-looking in-range instant.
7594    /// pandas raises `OutOfBoundsDatetime`.
7595    ///
7596    /// This is the ingestion path — CSV/JSON date columns and user strings —
7597    /// so failing OPEN with corrupt data is the failure mode the security
7598    /// doctrine specifically forbids. `None` here becomes the same
7599    /// `ValueNotParseable` the caller already returns for any other
7600    /// unparseable input, so no new error variant and no API change.
7601    ///
7602    /// The day-count arithmetic above the multiplies cannot overflow for any
7603    /// `year` that survives `str::parse::<i64>` minus the era arithmetic's own
7604    /// bounds, but it is routed through checked ops anyway so an extreme year
7605    /// is rejected rather than wrapped before it ever reaches the seconds step.
7606    fn ymd_hms_to_nanos(
7607        year: i64,
7608        month: u32,
7609        day: u32,
7610        hour: u32,
7611        minute: u32,
7612        second: u32,
7613        sub_nanos: u64,
7614    ) -> Option<i64> {
7615        let m = month as i64;
7616        let d = day as i64;
7617
7618        let y = if m <= 2 { year.checked_sub(1)? } else { year };
7619        let era = if y >= 0 { y } else { y.checked_sub(399)? } / 400;
7620        let yoe = y.checked_sub(era.checked_mul(400)?)?;
7621        let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
7622        let doe = yoe
7623            .checked_mul(365)?
7624            .checked_add(yoe / 4 - yoe / 100)?
7625            .checked_add(doy)?;
7626        let days_since_epoch = era
7627            .checked_mul(146_097)?
7628            .checked_add(doe)?
7629            .checked_sub(719_468)?;
7630
7631        let total_seconds = days_since_epoch
7632            .checked_mul(86400)?
7633            .checked_add(i64::from(hour) * 3600)?
7634            .checked_add(i64::from(minute) * 60)?
7635            .checked_add(i64::from(second))?;
7636        total_seconds
7637            .checked_mul(Timedelta::NANOS_PER_SEC)?
7638            .checked_add(sub_nanos as i64)
7639    }
7640
7641    /// Format timestamp using strftime directives.
7642    ///
7643    /// Matches `pd.Timestamp.strftime(format)`: Python's (glibc's) directive
7644    /// set, see [`strftime_python`] (it knew only %Y %m %d %H %M %S %f and
7645    /// printed `%%Y` as `%2024`). A tz-aware Timestamp formats its wall clock,
7646    /// `%z` / `%Z` its zone's offset and abbreviation then. NaT returns "NaT".
7647    #[must_use]
7648    pub fn strftime(&self, format: &str) -> String {
7649        if self.is_nat() {
7650            return "NaT".to_string();
7651        }
7652        strftime_in_zone(self.nanos, format, self.tz.as_deref())
7653    }
7654
7655    /// Return the day of the week as a string (e.g., "Monday").
7656    ///
7657    /// Matches `pd.Timestamp.day_name()`. NaT returns "NaT".
7658    #[must_use]
7659    pub fn day_name(&self) -> String {
7660        const NAMES: [&str; 7] = [
7661            "Thursday",
7662            "Friday",
7663            "Saturday",
7664            "Sunday",
7665            "Monday",
7666            "Tuesday",
7667            "Wednesday",
7668        ];
7669        if self.is_nat() {
7670            return "NaT".to_string();
7671        }
7672        // Floor days for pre-1970 (br-frankenpandas-wkjtw); == `/` for positive.
7673        // Truncating `/` rounds a negative, non-midnight instant TOWARD zero, so
7674        // it lands on the following day and names the wrong weekday: pandas 2.2.3
7675        // gives 1969-07-20T20:17:40 -> "Sunday", truncation gave "Monday". The
7676        // wkjtw fix was applied to `dayofweek` but never here.
7677        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7678        let dow = ((days_since_epoch % 7) + 7) % 7;
7679        NAMES[dow as usize].to_string()
7680    }
7681
7682    /// Return the month name as a string (e.g., "January").
7683    ///
7684    /// Matches `pd.Timestamp.month_name()`. NaT returns "NaT".
7685    #[must_use]
7686    pub fn month_name(&self) -> String {
7687        const NAMES: [&str; 12] = [
7688            "January",
7689            "February",
7690            "March",
7691            "April",
7692            "May",
7693            "June",
7694            "July",
7695            "August",
7696            "September",
7697            "October",
7698            "November",
7699            "December",
7700        ];
7701        if self.is_nat() {
7702            return "NaT".to_string();
7703        }
7704        // Floor (not truncate) so pre-1970 instants with a sub-day part map to
7705        // the correct calendar day (br-frankenpandas-wkjtw); div_euclid == `/`
7706        // for the post-1970 positive case.
7707        let days_since_epoch = self.nanos.div_euclid(Timedelta::NANOS_PER_DAY);
7708        let days = days_since_epoch + 719_468;
7709        let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
7710        let doe = days - era * 146_097;
7711        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
7712        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
7713        let mp = (5 * doy + 2) / 153;
7714        let m = if mp < 10 { mp + 3 } else { mp - 9 };
7715        NAMES[(m - 1) as usize].to_string()
7716    }
7717
7718    /// Localize a naive timestamp to a timezone.
7719    ///
7720    /// Matches `pd.Timestamp.tz_localize(tz)`. If `tz` is None, removes the
7721    /// timezone (makes timestamp naive). NaT propagates.
7722    #[must_use]
7723    pub fn tz_localize(&self, tz: Option<&str>) -> Self {
7724        if self.is_nat() {
7725            return Self::nat();
7726        }
7727        Self {
7728            nanos: self.nanos,
7729            tz: tz.map(String::from),
7730        }
7731    }
7732
7733    /// Convert timezone-aware timestamp to another timezone.
7734    ///
7735    /// Matches `pd.Timestamp.tz_convert(tz)`. If timestamp is naive (no tz),
7736    /// the timezone is simply attached without conversion. NaT propagates.
7737    /// Note: actual UTC offset conversion requires chrono-tz (Phase 3).
7738    #[must_use]
7739    pub fn tz_convert(&self, tz: &str) -> Self {
7740        if self.is_nat() {
7741            return Self::nat();
7742        }
7743        Self {
7744            nanos: self.nanos,
7745            tz: Some(tz.to_string()),
7746        }
7747    }
7748
7749    /// Create a Timestamp from a Unix timestamp (seconds since epoch).
7750    ///
7751    /// Matches `pd.Timestamp.fromtimestamp(ts)`. The optional `tz` parameter
7752    /// specifies the timezone to localize to.
7753    #[must_use]
7754    pub fn fromtimestamp(ts: f64, tz: Option<&str>) -> Self {
7755        if ts.is_nan() || ts.is_infinite() {
7756            return Self::nat();
7757        }
7758        let nanos_f64 = ts * 1_000_000_000.0;
7759        // Check for overflow before casting - i64 range is roughly ±9.2e18
7760        const MAX_NANOS: f64 = i64::MAX as f64;
7761        const MIN_NANOS: f64 = i64::MIN as f64;
7762        if !(MIN_NANOS..=MAX_NANOS).contains(&nanos_f64) {
7763            return Self::nat();
7764        }
7765        Self {
7766            nanos: nanos_f64 as i64,
7767            tz: tz.map(String::from),
7768        }
7769    }
7770
7771    /// Create a Timestamp from milliseconds since epoch.
7772    ///
7773    /// Convenience constructor complementing fromtimestamp. An `ms` outside
7774    /// the representable nanosecond range → NaT, matching `fromtimestamp`
7775    /// directly above (br-frankenpandas-kyd16); the previous
7776    /// `saturating_mul` handed back a finite ~year-2262 instant instead.
7777    #[must_use]
7778    pub fn from_millis(ms: i64, tz: Option<&str>) -> Self {
7779        let Some(nanos) = ms.checked_mul(1_000_000) else {
7780            return Self::nat();
7781        };
7782        Self {
7783            nanos,
7784            tz: tz.map(String::from),
7785        }
7786    }
7787
7788    /// Create a Timestamp from microseconds since epoch.
7789    ///
7790    /// Convenience constructor complementing fromtimestamp.
7791    #[must_use]
7792    pub fn from_micros(us: i64, tz: Option<&str>) -> Self {
7793        let Some(nanos) = us.checked_mul(1_000) else {
7794            return Self::nat();
7795        };
7796        Self {
7797            nanos,
7798            tz: tz.map(String::from),
7799        }
7800    }
7801
7802    /// Return the timezone string, or None if naive.
7803    #[must_use]
7804    pub fn tzinfo(&self) -> Option<&str> {
7805        self.tz.as_deref()
7806    }
7807
7808    /// Return the timezone name, or None if naive.
7809    ///
7810    /// Alias for tzinfo() matching pandas Timestamp.tzname().
7811    #[must_use]
7812    pub fn tzname(&self) -> Option<&str> {
7813        self.tzinfo()
7814    }
7815}
7816
7817impl std::fmt::Display for Timestamp {
7818    /// Phase 2 debug-style format; Phase 3 replaces with pandas ISO-8601
7819    /// notation once chrono interpretation lands.
7820    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7821        if self.is_nat() {
7822            return f.write_str("NaT");
7823        }
7824        match &self.tz {
7825            Some(tz) => write!(f, "Timestamp[{}, {}]", self.nanos, tz),
7826            None => write!(f, "Timestamp[{}, UTC]", self.nanos),
7827        }
7828    }
7829}
7830
7831impl PartialOrd for Timestamp {
7832    /// Orders by nanos axis; NaT is incomparable (`None`). Tz difference
7833    /// does not affect ordering — two Timestamps at the same absolute
7834    /// nanos compare equal regardless of tz label (Phase 3 will revisit
7835    /// whether tz affects ordering semantics).
7836    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
7837        if self.is_nat() || other.is_nat() {
7838            return None;
7839        }
7840        Some(self.nanos.cmp(&other.nanos))
7841    }
7842}
7843
7844// ── Missingness utilities ──────────────────────────────────────────────
7845
7846pub fn isna(values: &[Scalar]) -> Vec<bool> {
7847    values.iter().map(Scalar::is_missing).collect()
7848}
7849
7850pub fn isnull(values: &[Scalar]) -> Vec<bool> {
7851    isna(values)
7852}
7853
7854pub fn notna(values: &[Scalar]) -> Vec<bool> {
7855    values.iter().map(|v| !v.is_missing()).collect()
7856}
7857
7858pub fn notnull(values: &[Scalar]) -> Vec<bool> {
7859    notna(values)
7860}
7861
7862pub fn count_na(values: &[Scalar]) -> usize {
7863    values.iter().filter(|v| v.is_missing()).count()
7864}
7865
7866pub fn fill_na(values: &[Scalar], fill: &Scalar) -> Vec<Scalar> {
7867    values
7868        .iter()
7869        .map(|v| {
7870            if v.is_missing() {
7871                fill.clone()
7872            } else {
7873                v.clone()
7874            }
7875        })
7876        .collect()
7877}
7878
7879pub fn dropna(values: &[Scalar]) -> Vec<Scalar> {
7880    values.iter().filter(|v| !v.is_missing()).cloned().collect()
7881}
7882
7883// ── Nanops: null-skipping numeric reductions ───────────────────────────
7884
7885fn collect_finite(values: &[Scalar]) -> Vec<f64> {
7886    values
7887        .iter()
7888        .filter(|v| !v.is_missing())
7889        .filter_map(|v| v.to_f64().ok())
7890        .collect()
7891}
7892
7893/// Per br-frankenpandas-620mj: if a column is uniformly Timedelta64
7894/// (with optional NAT/Null missing), sum/mean preserve Timedelta dtype
7895/// matching pandas — instead of silently coercing to Float64(0.0) via
7896/// the collect_finite path (which drops Timedelta64 because to_f64
7897/// errors). A NaT-only input remains a Timedelta family so sum returns
7898/// zero Timedelta and mean returns NaT. Returns Some(sum_in_ns,
7899/// observed_count) when applicable.
7900fn collect_timedelta_ns(values: &[Scalar]) -> Option<(i128, usize)> {
7901    let mut sum: i128 = 0;
7902    let mut count: usize = 0;
7903    let mut saw_timedelta = false;
7904    for v in values {
7905        match v {
7906            Scalar::Timedelta64(ns) => {
7907                saw_timedelta = true;
7908                if v.is_missing() {
7909                    continue;
7910                }
7911                sum += i128::from(*ns);
7912                count += 1;
7913            }
7914            _ if v.is_missing() => continue,
7915            // Any non-Timedelta non-missing value bails out to the
7916            // existing Float64 path, preserving cross-type behavior.
7917            _ => return None,
7918        }
7919    }
7920    if saw_timedelta {
7921        Some((sum, count))
7922    } else {
7923        None
7924    }
7925}
7926
7927/// Narrow an exact `i128` nanosecond quantity back to a `Timedelta64` scalar,
7928/// surfacing NaT when the value is not representable.
7929///
7930/// Per br-frankenpandas-opz27, this replaces the `clamp(i64::MIN, i64::MAX)`
7931/// the reduction paths used to do, which failed open twice over:
7932///
7933/// - a positive overflow became `i64::MAX`, a fabricated finite ~106751-day
7934///   Timedelta presented as real data (the br-frankenpandas-lgyy8 class);
7935/// - `Timedelta::NAT` *is* `i64::MIN`, so the clamp's lower bound landed
7936///   exactly on the missing sentinel — a negative overflow silently became
7937///   NaT by accident, and the bound was off by one against the true minimum.
7938///
7939/// The representable range is therefore `[i64::MIN + 1, i64::MAX]`, and both
7940/// overflow directions now yield NaT deliberately. Live pandas 2.2.3 raises
7941/// (`OverflowError` / `ValueError: overflow in timedelta operation`) where
7942/// these reductions overflow; FP surfaces NaT instead, matching the
7943/// infallible-helper convention established by `Timedelta::div_scalar` and
7944/// br-frankenpandas-lgyy8. Every exactly-representable result is unaffected.
7945fn timedelta_ns_to_scalar(ns: i128) -> Scalar {
7946    if ns > i128::from(i64::MAX) || ns <= i128::from(i64::MIN) {
7947        return Scalar::Timedelta64(Timedelta::NAT);
7948    }
7949    Scalar::Timedelta64(ns as i64)
7950}
7951
7952pub fn nansum(values: &[Scalar]) -> Scalar {
7953    if let Some((sum, _)) = collect_timedelta_ns(values) {
7954        return timedelta_ns_to_scalar(sum);
7955    }
7956    // Fused single-pass fold: filter missing / non-f64-coercible and accumulate
7957    // in one scan, avoiding the intermediate `collect_finite` Vec<f64> and its
7958    // second pass. Bit-identical to `collect_finite(..).iter().sum()`: same
7959    // finite values in the same order, same left-fold f64 `+` (empty -> 0.0).
7960    let mut sum = 0.0_f64;
7961    for v in values {
7962        if v.is_missing() {
7963            continue;
7964        }
7965        if let Ok(x) = v.to_f64() {
7966            sum += x;
7967        }
7968    }
7969    Scalar::Float64(sum)
7970}
7971
7972/// Sum of a STRING group: pandas concatenates, skipping missing entries.
7973///
7974/// br-frankenpandas-a7faz. `nansum` cannot serve this: it coerces through
7975/// `to_f64`, which fails for every `Utf8`, so a string column sums to
7976/// `Float64(0.0)` — a wrong value rather than a refusal. This is a separate
7977/// reducer rather than a branch inside `nansum` on purpose: the SUM SURFACES
7978/// DISAGREE in pandas and a shared change would silently move the others.
7979///
7980/// MEASURED, live pandas 2.2.3 (CrimsonPine 2026-08-18):
7981/// ```text
7982///   Series(['a','b','c']).sum()              -> 'abc'
7983///   Series(['a',None,'c']).sum()             -> TypeError: can only concatenate str
7984///   DataFrame({'v':['a',None]}).sum()        -> TypeError (same)
7985///   df.groupby(k)['v'].sum()  with a None    -> 'a'      SKIPS, does not raise
7986///   s.resample('ME').sum()    with a None    -> 'ps'     SKIPS, does not raise
7987/// ```
7988/// So the REDUCTION surfaces raise on a missing entry while the GROUPED surfaces
7989/// skip it. This function implements the grouped rule and must not be wired into
7990/// `Series::sum`/`DataFrame::sum` without implementing their raise.
7991///
7992/// ⚠️ AND AN EMPTY OR ALL-MISSING GROUP IS INTEGER `0`, NOT `""`. Measured:
7993/// ```text
7994///   Series(['p','q'], index=[Jan-01, Mar-01]).resample('ME').sum()
7995///     -> ['p', 0, 'q']        <- the empty February bucket is int 0
7996///   Series([None,None,'r','u'], ...).resample('ME').sum()
7997///     -> [0, 'ru']            <- an all-missing bucket is int 0 too
7998///   types: ['int', 'str']     <- the output column is genuinely MIXED
7999/// ```
8000/// That is pandas' `sum()` identity element leaking through unchanged, and it is
8001/// why this returns `Scalar::Int64(0)` rather than an empty string: matching the
8002/// incumbent here means reproducing a mixed-dtype column.
8003///
8004/// Concatenation is POSITIONAL, not sorted — `Series(['z','a','m']).sum()` is
8005/// `'zam'`. Callers that bucket by time therefore hand the values over in index
8006/// order, which is what produced `'psq'` for a Jan bucket holding Jan-01 'p',
8007/// Jan-05 's', Jan-15 'q'.
8008#[must_use]
8009pub fn nansum_utf8(values: &[Scalar]) -> Scalar {
8010    let mut out: Option<String> = None;
8011    for v in values {
8012        if v.is_missing() {
8013            continue;
8014        }
8015        if let Scalar::Utf8(part) = v {
8016            out.get_or_insert_with(String::new).push_str(part);
8017        }
8018    }
8019    match out {
8020        Some(joined) => Scalar::Utf8(joined),
8021        // Not `Utf8(String::new())`: pandas yields the integer identity here.
8022        None => Scalar::Int64(0),
8023    }
8024}
8025
8026pub fn nanmean(values: &[Scalar]) -> Scalar {
8027    if let Some((sum, count)) = collect_timedelta_ns(values) {
8028        if count == 0 {
8029            return Scalar::Timedelta64(Timedelta::NAT);
8030        }
8031        // |sum / count| <= max|ns| for count >= 1, so the mean of representable
8032        // inputs is always representable; the narrowing is defensive only.
8033        return timedelta_ns_to_scalar(sum / count as i128);
8034    }
8035    // br-frankenpandas-adv58: Datetime64 mean is the mean of the epoch-ns
8036    // backing, re-read as an instant. Accumulated in i128 and divided with
8037    // Rust's toward-zero integer division, which is exactly the rounding pandas
8038    // shows where it is exact ([0,1] -> 0, [0,3] -> 1, [-3,0] -> -1; floor and
8039    // ties-to-even are both refuted). Where pandas is NOT exact it snaps to its
8040    // f64 grid — even for a constant series — and FP stays exact. See DISC-019.
8041    if let Some((sum, count)) = collect_datetime_ns(values) {
8042        if count == 0 {
8043            return Scalar::Datetime64(Timestamp::NAT);
8044        }
8045        let mean = sum / count as i128;
8046        if mean > i128::from(i64::MAX) || mean <= i128::from(i64::MIN) {
8047            return Scalar::Datetime64(Timestamp::NAT);
8048        }
8049        return Scalar::Datetime64(mean as i64);
8050    }
8051    // Fused single-pass fold (see `nansum`): accumulate sum + count of finite
8052    // values in one scan. Bit-identical to the prior `collect_finite` two-pass:
8053    // count == nums.len(), sum folds the same values in the same order.
8054    let mut sum = 0.0_f64;
8055    let mut count = 0usize;
8056    for v in values {
8057        if v.is_missing() {
8058            continue;
8059        }
8060        if let Ok(x) = v.to_f64() {
8061            sum += x;
8062            count += 1;
8063        }
8064    }
8065    if count == 0 {
8066        return Scalar::Null(NullKind::NaN);
8067    }
8068    Scalar::Float64(sum / count as f64)
8069}
8070
8071pub fn nanany(values: &[Scalar]) -> Scalar {
8072    for v in values {
8073        if v.is_missing() {
8074            continue;
8075        }
8076        match v {
8077            Scalar::Bool(flag) if *flag => return Scalar::Bool(true),
8078            Scalar::Int64(val) if *val != 0 => return Scalar::Bool(true),
8079            Scalar::Float64(val) if !val.is_nan() && *val != 0.0 => return Scalar::Bool(true),
8080            Scalar::Utf8(val) if !val.is_empty() => return Scalar::Bool(true),
8081            // pandas Series([td]).any() returns True for any non-zero
8082            // Timedelta. NaT is already filtered by is_missing() above.
8083            Scalar::Timedelta64(ns) if *ns != 0 => return Scalar::Bool(true),
8084            _ => continue,
8085        }
8086    }
8087    Scalar::Bool(false)
8088}
8089
8090pub fn nanall(values: &[Scalar]) -> Scalar {
8091    for v in values {
8092        if v.is_missing() {
8093            continue;
8094        }
8095        match v {
8096            Scalar::Bool(flag) if !*flag => return Scalar::Bool(false),
8097            Scalar::Int64(val) if *val == 0 => return Scalar::Bool(false),
8098            Scalar::Float64(val) if val.is_nan() || *val == 0.0 => return Scalar::Bool(false),
8099            Scalar::Utf8(val) if val.is_empty() => return Scalar::Bool(false),
8100            // pandas Series([td(0)]).all() returns False; any non-zero
8101            // Timedelta is truthy. NaT is already filtered by is_missing.
8102            Scalar::Timedelta64(ns) if *ns == 0 => return Scalar::Bool(false),
8103            _ => continue,
8104        }
8105    }
8106    Scalar::Bool(true)
8107}
8108
8109pub fn nancount(values: &[Scalar]) -> Scalar {
8110    let n = values.iter().filter(|v| !v.is_missing()).count();
8111    Scalar::Int64(n as i64)
8112}
8113
8114pub fn nanmin(values: &[Scalar]) -> Scalar {
8115    let mut min: Option<&Scalar> = None;
8116    for v in values {
8117        if v.is_missing() {
8118            continue;
8119        }
8120        match (min, v) {
8121            (None, _) => min = Some(v),
8122            (Some(Scalar::Int64(a)), Scalar::Int64(b)) => {
8123                if b < a {
8124                    min = Some(v)
8125                }
8126            }
8127            (Some(Scalar::Float64(a)), Scalar::Float64(b)) => {
8128                if *b < *a {
8129                    min = Some(v)
8130                }
8131            }
8132            (Some(Scalar::Utf8(a)), Scalar::Utf8(b)) => {
8133                if b < a {
8134                    min = Some(v)
8135                }
8136            }
8137            (Some(Scalar::Bool(a)), Scalar::Bool(b)) => {
8138                if b < a {
8139                    min = Some(v)
8140                }
8141            }
8142            // Per br-frankenpandas-yic5m: Timedelta64.to_f64() errors, so
8143            // the catch-all below would silently return NaN. Compare ns
8144            // representations directly; NAT is already filtered by
8145            // is_missing() above.
8146            (Some(Scalar::Timedelta64(a)), Scalar::Timedelta64(b)) => {
8147                if b < a {
8148                    min = Some(v)
8149                }
8150            }
8151            // br-frankenpandas-axhhk: Datetime64 needs the same arm for the
8152            // same reason — its to_f64() errors too. Without it a 2+-element
8153            // datetime column returned Null(NaN), while a 1-element one
8154            // returned the right answer via the (None, _) seed above.
8155            (Some(Scalar::Datetime64(a)), Scalar::Datetime64(b)) => {
8156                if b < a {
8157                    min = Some(v)
8158                }
8159            }
8160            // br-frankenpandas-qoabs: Period, third dtype with the same
8161            // to_f64() failure. Ordinals are ONLY comparable within one freq —
8162            // pandas refuses mixed freq outright (IncompatibleFrequency), so a
8163            // differing freq must NOT be ordered here. Comparing the raw
8164            // ordinals across freqs would invent an ordering pandas rejects
8165            // (monthly 2020-01 is ordinal 600, daily 2020-01-05 is 18267).
8166            // br-frankenpandas-qoabs: Period, third dtype with the same
8167            // to_f64() failure. Ordinals are ONLY comparable within one freq —
8168            // pandas refuses mixed freq outright (IncompatibleFrequency), so a
8169            // differing freq must NOT be ordered here. Comparing the raw
8170            // ordinals across freqs would invent an ordering pandas rejects
8171            // (monthly 2020-01 is ordinal 600, daily 2020-01-05 is 18267).
8172            (Some(Scalar::Period(a)), Scalar::Period(b)) => {
8173                if a.freq != b.freq {
8174                    return Scalar::Null(NullKind::NaN);
8175                }
8176                if b.ordinal < a.ordinal {
8177                    min = Some(v)
8178                }
8179            }
8180            // br-frankenpandas-srqdo: Interval, fourth dtype whose to_f64()
8181            // errors. pandas orders Intervals by (left, right) — a tie on left
8182            // falls through to right. `closed` is NOT part of the comparison:
8183            // pandas does order scalar Intervals that tie on both bounds by an
8184            // internal `closed` ordering, but a real IntervalArray requires a
8185            // UNIFORM closed, so that case cannot arise from an Interval
8186            // column, and guessing an undocumented enum order would be worse
8187            // than keeping the first on an exact tie.
8188            //
8189            // A NaN bound is not orderable and has no pandas counterpart —
8190            // IntervalArray refuses to build one ("missing values must be
8191            // missing in the same location both left and right") — so bail to
8192            // missing rather than impose an arbitrary order. Note this avoids
8193            // `partial_cmp().unwrap()`, which would be a panic in library code.
8194            (Some(Scalar::Interval(a)), Scalar::Interval(b)) => {
8195                if a.left.is_nan() || a.right.is_nan() || b.left.is_nan() || b.right.is_nan() {
8196                    return Scalar::Null(NullKind::NaN);
8197                }
8198                if (b.left, b.right) < (a.left, a.right) {
8199                    min = Some(v)
8200                }
8201            }
8202            (Some(a), b) => match (a.to_f64(), b.to_f64()) {
8203                (Ok(af), Ok(bf)) if bf < af => min = Some(v),
8204                (Ok(_), Ok(_)) => {}
8205                _ => return Scalar::Null(NullKind::NaN),
8206            },
8207        }
8208    }
8209    match min {
8210        Some(v) => v.clone(),
8211        None => Scalar::Null(NullKind::NaN),
8212    }
8213}
8214
8215pub fn nanmax(values: &[Scalar]) -> Scalar {
8216    let mut max: Option<&Scalar> = None;
8217    for v in values {
8218        if v.is_missing() {
8219            continue;
8220        }
8221        match (max, v) {
8222            (None, _) => max = Some(v),
8223            (Some(Scalar::Int64(a)), Scalar::Int64(b)) => {
8224                if b > a {
8225                    max = Some(v)
8226                }
8227            }
8228            (Some(Scalar::Float64(a)), Scalar::Float64(b)) => {
8229                if *b > *a {
8230                    max = Some(v)
8231                }
8232            }
8233            (Some(Scalar::Utf8(a)), Scalar::Utf8(b)) => {
8234                if b > a {
8235                    max = Some(v)
8236                }
8237            }
8238            (Some(Scalar::Bool(a)), Scalar::Bool(b)) => {
8239                if b > a {
8240                    max = Some(v)
8241                }
8242            }
8243            // Per br-frankenpandas-yic5m: Timedelta64.to_f64() errors, so
8244            // the catch-all below would silently return NaN. Compare ns
8245            // representations directly; NAT is already filtered above.
8246            (Some(Scalar::Timedelta64(a)), Scalar::Timedelta64(b)) => {
8247                if b > a {
8248                    max = Some(v)
8249                }
8250            }
8251            // br-frankenpandas-axhhk: Datetime64 sibling of the arm above.
8252            (Some(Scalar::Datetime64(a)), Scalar::Datetime64(b)) => {
8253                if b > a {
8254                    max = Some(v)
8255                }
8256            }
8257            // br-frankenpandas-qoabs: Period, freq-guarded — see `nanmin`.
8258            (Some(Scalar::Period(a)), Scalar::Period(b)) => {
8259                if a.freq != b.freq {
8260                    return Scalar::Null(NullKind::NaN);
8261                }
8262                if b.ordinal > a.ordinal {
8263                    max = Some(v)
8264                }
8265            }
8266            // br-frankenpandas-srqdo: Interval, ordered by (left, right) with
8267            // NaN bounds refused — see `nanmin` for the full reasoning.
8268            (Some(Scalar::Interval(a)), Scalar::Interval(b)) => {
8269                if a.left.is_nan() || a.right.is_nan() || b.left.is_nan() || b.right.is_nan() {
8270                    return Scalar::Null(NullKind::NaN);
8271                }
8272                if (b.left, b.right) > (a.left, a.right) {
8273                    max = Some(v)
8274                }
8275            }
8276            (Some(a), b) => match (a.to_f64(), b.to_f64()) {
8277                (Ok(af), Ok(bf)) if bf > af => max = Some(v),
8278                (Ok(_), Ok(_)) => {}
8279                _ => return Scalar::Null(NullKind::NaN),
8280            },
8281        }
8282    }
8283    match max {
8284        Some(v) => v.clone(),
8285        None => Scalar::Null(NullKind::NaN),
8286    }
8287}
8288
8289/// Which temporal family a uniformly-temporal input belongs to, and everything
8290/// needed to rebuild a `Scalar` of it from a raw i64 backing.
8291///
8292/// br-frankenpandas-d7zjp replaced the previous `fn(i64) -> Scalar` constructor
8293/// with this enum for one reason: a plain fn pointer CANNOT CARRY A FREQ, and a
8294/// `Period` is `{ordinal, freq}`. That limitation is what blocked Period from
8295/// joining median/quantile/cummax/cummin when Datetime64 did.
8296///
8297/// The i64 payload is nanoseconds for Timedelta64/Datetime64 and an ORDINAL for
8298/// Period — different units, but every operation here is pure ordering or an
8299/// average over that backing, which is meaningful in both.
8300#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8301enum TemporalFamily {
8302    Timedelta,
8303    Datetime,
8304    /// Periods only compare within ONE freq; see [`collect_temporal_backing`].
8305    Period(PeriodFreq),
8306}
8307
8308impl TemporalFamily {
8309    /// Rebuild a scalar of this family from its raw backing.
8310    fn make(self, raw: i64) -> Scalar {
8311        match self {
8312            Self::Timedelta => Scalar::Timedelta64(raw),
8313            Self::Datetime => Scalar::Datetime64(raw),
8314            Self::Period(freq) => Scalar::Period(Period::new(raw, freq)),
8315        }
8316    }
8317
8318    /// The family's missing sentinel, dtype preserved.
8319    fn nat(self) -> Scalar {
8320        self.make(i64::MIN)
8321    }
8322}
8323
8324/// Per br-frankenpandas-j8ntk: harvest the raw backing of a uniformly-temporal
8325/// input as f64 (53 bits of mantissa, exact for ns spans up to ~104 days;
8326/// beyond that pandas itself loses precision the same way), together with the
8327/// family to rebuild results in. A NaT-only input keeps its family.
8328///
8329/// Returns `None` unless every non-missing value belongs to ONE family — which
8330/// for Period means one FREQ as well, because pandas refuses to order Periods
8331/// of differing freq at all (`IncompatibleFrequency`) and their ordinals are
8332/// not comparable across freqs.
8333///
8334/// br-frankenpandas-adv58 widened this to Datetime64 and d7zjp to Period. The
8335/// f64 hop is inherited deliberately: quantile interpolates by a fractional
8336/// weight, so the newer families keep the SAME accuracy contract the Timedelta
8337/// arm already had rather than inventing a stricter one per dtype.
8338fn collect_temporal_backing(values: &[Scalar]) -> Option<(Vec<f64>, TemporalFamily)> {
8339    let mut out = Vec::with_capacity(values.len());
8340    let mut family: Option<TemporalFamily> = None;
8341    for v in values {
8342        let (raw, this) = match v {
8343            Scalar::Timedelta64(ns) => (*ns, TemporalFamily::Timedelta),
8344            Scalar::Datetime64(ns) => (*ns, TemporalFamily::Datetime),
8345            Scalar::Period(p) => (p.ordinal, TemporalFamily::Period(p.freq)),
8346            _ if v.is_missing() => continue,
8347            _ => return None,
8348        };
8349        // Mixing families — or, for Period, mixing freqs — is not one family.
8350        match family {
8351            Some(existing) if existing != this => return None,
8352            _ => family = Some(this),
8353        }
8354        if v.is_missing() {
8355            continue;
8356        }
8357        out.push(raw as f64);
8358    }
8359    family.map(|f| (out, f))
8360}
8361
8362/// Timedelta64-ONLY view of [`collect_temporal_backing`].
8363///
8364/// var/sem keep this narrower gate on purpose: live pandas 2.2.3 RAISES
8365/// `TypeError: 'DatetimeArray' ... does not support reduction 'var'` (and the
8366/// same for 'sem', and for every one of them on Period), so widening them would
8367/// invent a value pandas refuses to produce.
8368fn collect_timedelta_ns_f64(values: &[Scalar]) -> Option<Vec<f64>> {
8369    match collect_temporal_backing(values) {
8370        Some((out, TemporalFamily::Timedelta)) => Some(out),
8371        _ => None,
8372    }
8373}
8374
8375/// Clamp an f64 result into i64 range and wrap as Scalar::Timedelta64.
8376fn float_ns_to_timedelta(value: f64) -> Scalar {
8377    float_ns_to_temporal(value, TemporalFamily::Timedelta)
8378}
8379
8380/// Family-generic form of [`float_ns_to_timedelta`], per br-frankenpandas-adv58:
8381/// NaT for a non-finite input, otherwise the value in the caller's family.
8382fn float_ns_to_temporal(value: f64, make: TemporalFamily) -> Scalar {
8383    if !value.is_finite() {
8384        return make.nat();
8385    }
8386    let clamped = value.clamp(i64::MIN as f64, i64::MAX as f64);
8387    make.make(clamped as i64)
8388}
8389
8390pub fn nanmedian(values: &[Scalar]) -> Scalar {
8391    // Preserve exact nanosecond ordering for uniformly-temporal input.
8392    // Converting to f64 loses distinct ticks beyond the 53-bit boundary.
8393    //
8394    // br-frankenpandas-adv58: Datetime64 joins Timedelta64 here, and keeps the
8395    // SAME exact i128 treatment its Timedelta sibling already had. Note that
8396    // this makes FP strictly more precise than pandas 2.2.3, which routes
8397    // datetime median through f64 and therefore snaps to a 256 ns grid at
8398    // 2020-era timestamps — returning, for an odd-count input, a Timestamp that
8399    // is not even one of the supplied values. See DISC-019.
8400    // br-frankenpandas-d7zjp: Period joins via the family enum, which — unlike
8401    // the fn-pointer constructor this replaced — can carry its freq. A
8402    // mixed-freq input is not one family, so it falls through rather than
8403    // being ordered by raw ordinal, matching pandas refusing it outright.
8404    let Some((_, make)) = collect_temporal_backing(values) else {
8405        // Not uniformly temporal: fall through to the numeric arm below.
8406        return nanmedian_numeric(values);
8407    };
8408    let mut td: Vec<i64> = values
8409        .iter()
8410        .filter(|value| !value.is_missing())
8411        .filter_map(|value| match value {
8412            Scalar::Timedelta64(ns) | Scalar::Datetime64(ns) => Some(*ns),
8413            Scalar::Period(p) => Some(p.ordinal),
8414            _ => None,
8415        })
8416        .collect();
8417    if td.is_empty() {
8418        // All-missing temporal input falls through to the numeric arm, which
8419        // yields Null(NaN). Do NOT "improve" this to a family-typed NaT: the
8420        // Null(NaN) result is pinned by the oracle test
8421        // `nanmedian_matches_numeric_and_timedelta_oracle_oabhi`, and the old
8422        // `is_timedelta_input` gate produced it by returning false for an
8423        // all-missing input. `collect_temporal_backing` marks the family on
8424        // seeing the VARIANT instead, so the fall-through has to be explicit.
8425        return nanmedian_numeric(values);
8426    }
8427    // O(n) selection instead of a full sort: order statistics depend only
8428    // on values, so the unstable partition yields the same middle values.
8429    let n = td.len();
8430    let mid = n / 2;
8431    let (left, mid_ref, _right) = td.select_nth_unstable(mid);
8432    let mid_val = *mid_ref;
8433    let median_ns = if n.is_multiple_of(2) {
8434        let lower = left.iter().copied().fold(i64::MIN, i64::max);
8435        // Toward-zero division, matching pandas where pandas is exact.
8436        (i128::from(lower) + i128::from(mid_val)) / 2
8437    } else {
8438        i128::from(mid_val)
8439    };
8440    make.make(median_ns as i64)
8441}
8442
8443/// Numeric (f64) median arm, split out of [`nanmedian`] by
8444/// br-frankenpandas-adv58 so the temporal arm can return early. Also the
8445/// fall-through for non-uniform input, e.g. mixed Datetime64 + Int64.
8446fn nanmedian_numeric(values: &[Scalar]) -> Scalar {
8447    let mut nums = collect_finite(values);
8448    if nums.is_empty() {
8449        return Scalar::Null(NullKind::NaN);
8450    }
8451    // O(n) selection instead of an O(n log n) full sort: select_nth_unstable_by
8452    // places the `mid`-th smallest at index `mid` with all smaller elements
8453    // (unordered) in the left partition. For even n the (mid-1)-th smallest is
8454    // the MAX of that left partition. Bit-identical to the sort path: order
8455    // statistics depend only on VALUES, and ties share a value, so the
8456    // unstable partition yields the same nums[mid-1]/nums[mid] the sort did.
8457    let n = nums.len();
8458    let mid = n / 2;
8459    let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
8460    let (left, mid_ref, _right) = nums.select_nth_unstable_by(mid, cmp);
8461    let mid_val = *mid_ref;
8462    if n.is_multiple_of(2) {
8463        let lower = left.iter().copied().fold(f64::NEG_INFINITY, f64::max);
8464        Scalar::Float64((lower + mid_val) / 2.0)
8465    } else {
8466        Scalar::Float64(mid_val)
8467    }
8468}
8469
8470pub fn nanvar(values: &[Scalar], ddof: usize) -> Scalar {
8471    // Per br-frankenpandas-j8ntk: Timedelta64 var preserves dtype — pandas
8472    // returns Timedelta even though variance is ns² conceptually; matching.
8473    if let Some(td) = collect_timedelta_ns_f64(values) {
8474        if td.len() <= ddof {
8475            return Scalar::Timedelta64(Timedelta::NAT);
8476        }
8477        let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
8478        let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
8479        return float_ns_to_timedelta(sum_sq / (td.len() - ddof) as f64);
8480    }
8481    let nums = collect_finite(values);
8482    if nums.len() <= ddof {
8483        return Scalar::Null(NullKind::NaN);
8484    }
8485    let mean: f64 = nums.iter().sum::<f64>() / nums.len() as f64;
8486    let sum_sq: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
8487    Scalar::Float64(sum_sq / (nums.len() - ddof) as f64)
8488}
8489
8490pub fn nanstd(values: &[Scalar], ddof: usize) -> Scalar {
8491    // Per br-frankenpandas-j8ntk: Timedelta64 std preserves dtype.
8492    //
8493    // br-frankenpandas-40ujm: Datetime64 is accepted here too, and the family
8494    // constructor is deliberately DISCARDED — the dispersion of a set of
8495    // instants is a DURATION, so datetime std returns a Timedelta, exactly as
8496    // pandas does. Verified against the oracle: pandas gives the identical
8497    // value for a Datetime64 series and a Timedelta64 series built from the
8498    // same ns (both 2592479955563784 for [0, 60d, 31d]).
8499    //
8500    // This is the ONLY reduction in the std/var/sem group that widens. pandas
8501    // RAISES for datetime64 var and sem ("does not support reduction"), so
8502    // those keep the Timedelta-only `collect_timedelta_ns_f64` gate rather than
8503    // inventing a value pandas refuses to produce.
8504    //
8505    // br-frankenpandas-d7zjp: PERIOD IS EXCLUDED HERE. pandas raises
8506    // "'PeriodArray' with dtype period[M] does not support reduction 'std'",
8507    // so widening std to Period alongside Datetime64 would invent a value —
8508    // and the family enum makes that mistake one line away, hence the guard.
8509    if let Some((td, family)) = collect_temporal_backing(values)
8510        && !matches!(family, TemporalFamily::Period(_))
8511    {
8512        if td.len() <= ddof {
8513            return Scalar::Timedelta64(Timedelta::NAT);
8514        }
8515        let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
8516        let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
8517        let var = sum_sq / (td.len() - ddof) as f64;
8518        return float_ns_to_timedelta(var.sqrt());
8519    }
8520    match nanvar(values, ddof) {
8521        Scalar::Float64(v) => Scalar::Float64(v.sqrt()),
8522        other => other,
8523    }
8524}
8525
8526/// Standard error of the mean over non-missing values.
8527///
8528/// Matches `pd.Series.sem(ddof=1)` / `scipy.stats.sem`. Computed as
8529/// `std(values, ddof) / sqrt(n)` where `n` is the non-missing count.
8530/// Returns `Null(NaN)` when `n <= ddof`.
8531pub fn nansem(values: &[Scalar], ddof: usize) -> Scalar {
8532    // Per br-frankenpandas-j8ntk: Timedelta64 sem preserves dtype.
8533    if let Some(td) = collect_timedelta_ns_f64(values) {
8534        if td.len() <= ddof {
8535            return Scalar::Timedelta64(Timedelta::NAT);
8536        }
8537        let mean: f64 = td.iter().sum::<f64>() / td.len() as f64;
8538        let sum_sq: f64 = td.iter().map(|x| (x - mean).powi(2)).sum();
8539        let var = sum_sq / (td.len() - ddof) as f64;
8540        let std = var.sqrt();
8541        return float_ns_to_timedelta(std / (td.len() as f64).sqrt());
8542    }
8543    let nums = collect_finite(values);
8544    if nums.len() <= ddof {
8545        return Scalar::Null(NullKind::NaN);
8546    }
8547    let n = nums.len();
8548    let mean = nums.iter().sum::<f64>() / n as f64;
8549    let sum_sq = nums.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
8550    let var = sum_sq / (n - ddof) as f64;
8551    let std = var.sqrt();
8552    Scalar::Float64(std / (n as f64).sqrt())
8553}
8554
8555/// Standard error of the mean as pandas' groupby, resample and pivot_table
8556/// compute it: `sqrt(var / n)` (libgroupby's `group_var(name="sem")`), which
8557/// can differ in the last bit from [`nansem`]'s `std / sqrt(n)` (Series.sem):
8558/// for `[1.0, 4.0]` this is `1.5` and nansem `1.4999999999999998`
8559/// (br-frankenpandas-7hxqv). Timedelta input keeps [`nansem`].
8560pub fn nansem_grouped(values: &[Scalar], ddof: usize) -> Scalar {
8561    if collect_timedelta_ns_f64(values).is_some() {
8562        return nansem(values, ddof);
8563    }
8564    grouped_moments(values)
8565        .sem(ddof)
8566        .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
8567}
8568
8569/// pandas' compensated running sum: its cython `group_sum`, `group_mean`
8570/// and `group_cumsum` add each float as `y = v - comp; t = sum + y;
8571/// comp = t - sum - y; sum = t` (Kahan), `comp` reset to 0 where it is NaN
8572/// (an inf added; GH#53606). A plain `+=` fold differs from it in the last
8573/// bits - groupby sum of ten 0.1 is 1.0 in pandas, 0.9999999999999999
8574/// naively (br-frankenpandas-xhogl).
8575#[derive(Clone, Copy, Debug, Default, PartialEq)]
8576pub struct KahanSum {
8577    sum: f64,
8578    compensation: f64,
8579}
8580
8581impl KahanSum {
8582    /// `value` added, as pandas' group kernels add it.
8583    #[inline]
8584    pub fn add(&mut self, value: f64) {
8585        let y = value - self.compensation;
8586        let t = self.sum + y;
8587        self.compensation = t - self.sum - y;
8588        if self.compensation.is_nan() {
8589            self.compensation = 0.0;
8590        }
8591        self.sum = t;
8592    }
8593
8594    /// The sum so far.
8595    #[inline]
8596    #[must_use]
8597    pub fn sum(self) -> f64 {
8598        self.sum
8599    }
8600}
8601
8602/// pandas' online variance: its cython `group_var` folds each float as
8603/// Welford (`mean += (v - old) / n; m2 += (v - mean) * (v - old)`) and
8604/// answers `m2 / (n - ddof)`, std its square root and sem
8605/// `sqrt(m2 / (n - ddof) / n)` - where the two-pass form differs in the
8606/// last bits (a constant group's var is 0.0, not 1e-34;
8607/// br-frankenpandas-xhogl).
8608#[derive(Clone, Copy, Debug, Default, PartialEq)]
8609pub struct WelfordVar {
8610    count: usize,
8611    mean: f64,
8612    m2: f64,
8613}
8614
8615impl WelfordVar {
8616    /// `value` folded in.
8617    #[inline]
8618    pub fn add(&mut self, value: f64) {
8619        self.count += 1;
8620        let old = self.mean;
8621        self.mean += (value - old) / self.count as f64;
8622        self.m2 += (value - self.mean) * (value - old);
8623    }
8624
8625    /// The values folded in.
8626    #[must_use]
8627    pub fn count(self) -> usize {
8628        self.count
8629    }
8630
8631    /// `m2 / (n - ddof)`; None while `n <= ddof`.
8632    #[must_use]
8633    pub fn var(self, ddof: usize) -> Option<f64> {
8634        (self.count > ddof).then(|| self.m2 / (self.count - ddof) as f64)
8635    }
8636
8637    /// The square root of [`Self::var`].
8638    #[must_use]
8639    pub fn std(self, ddof: usize) -> Option<f64> {
8640        self.var(ddof).map(f64::sqrt)
8641    }
8642
8643    /// `sqrt(var / n)`, pandas' grouped sem.
8644    #[must_use]
8645    pub fn sem(self, ddof: usize) -> Option<f64> {
8646        self.var(ddof).map(|var| (var / self.count as f64).sqrt())
8647    }
8648}
8649
8650/// pandas' online skewness: its cython `group_skew` folds each float into
8651/// running moments (`delta = v - m1; delta_n = delta / n; term1 = delta *
8652/// delta_n * (n - 1); m1 += delta_n; m3 += term1 * delta_n * (n - 2) -
8653/// 3 * delta_n * m2; m2 += term1`) and answers
8654/// `n * (n - 1) ** 0.5 / (n - 2) * (m3 / m2 ** 1.5)` - 0 when `m2` is 0,
8655/// missing below 3 values - where the two-pass [`nanskew`] (Series.skew)
8656/// differs in the last bits (br-frankenpandas-vjfq9).
8657#[derive(Clone, Copy, Debug, Default, PartialEq)]
8658pub struct SkewMoments {
8659    count: usize,
8660    m1: f64,
8661    m2: f64,
8662    m3: f64,
8663}
8664
8665impl SkewMoments {
8666    /// `value` folded in.
8667    #[inline]
8668    pub fn add(&mut self, value: f64) {
8669        let before = self.count as f64;
8670        self.count += 1;
8671        let n = self.count as f64;
8672        let delta = value - self.m1;
8673        let delta_n = delta / n;
8674        let term1 = delta * delta_n * before;
8675        self.m1 += delta_n;
8676        self.m3 += term1 * delta_n * (n - 2.0) - 3.0 * delta_n * self.m2;
8677        self.m2 += term1;
8678    }
8679
8680    /// The values folded in.
8681    #[must_use]
8682    pub fn count(self) -> usize {
8683        self.count
8684    }
8685
8686    /// The bias-corrected skewness; None below 3 values.
8687    #[must_use]
8688    pub fn skew(self) -> Option<f64> {
8689        if self.count < 3 {
8690            return None;
8691        }
8692        if self.m2 == 0.0 {
8693            return Some(0.0);
8694        }
8695        let n = self.count as f64;
8696        // pandas raises with libm pow: pow(n - 1, 0.5) is not always sqrt's
8697        // correctly rounded answer (n = 2922 differs), and a constant 0.5
8698        // exponent would let LLVM substitute sqrt.
8699        let half = std::hint::black_box(0.5);
8700        Some((n * (n - 1.0).powf(half) / (n - 2.0)) * (self.m3 / self.m2.powf(1.5)))
8701    }
8702}
8703
8704/// [`nanskew`] as pandas' grouped skew: [`SkewMoments`] over the present
8705/// values.
8706#[must_use]
8707pub fn nanskew_grouped(values: &[Scalar]) -> Scalar {
8708    let mut moments = SkewMoments::default();
8709    for value in values {
8710        if value.is_missing() {
8711            continue;
8712        }
8713        if let Ok(x) = value.to_f64() {
8714            moments.add(x);
8715        }
8716    }
8717    moments
8718        .skew()
8719        .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
8720}
8721
8722/// The present values' Welford moments, as [`nanvar_grouped`] reads them.
8723fn grouped_moments(values: &[Scalar]) -> WelfordVar {
8724    let mut moments = WelfordVar::default();
8725    for value in values {
8726        if value.is_missing() {
8727            continue;
8728        }
8729        if let Ok(x) = value.to_f64() {
8730            moments.add(x);
8731        }
8732    }
8733    moments
8734}
8735
8736/// [`nansum`] as pandas' groupby / resample / pivot_table add floats: the
8737/// compensated [`KahanSum`] (br-frankenpandas-xhogl). Timedelta input keeps
8738/// [`nansum`]'s exact integer sum.
8739#[must_use]
8740pub fn nansum_grouped(values: &[Scalar]) -> Scalar {
8741    if collect_timedelta_ns(values).is_some() {
8742        return nansum(values);
8743    }
8744    let mut sum = KahanSum::default();
8745    for value in values {
8746        if value.is_missing() {
8747            continue;
8748        }
8749        if let Ok(x) = value.to_f64() {
8750            sum.add(x);
8751        }
8752    }
8753    Scalar::Float64(sum.sum())
8754}
8755
8756/// [`nanmean`] as pandas' grouped mean: the [`KahanSum`] over the count.
8757/// Temporal input keeps [`nanmean`].
8758#[must_use]
8759pub fn nanmean_grouped(values: &[Scalar]) -> Scalar {
8760    if collect_timedelta_ns(values).is_some() || collect_datetime_ns(values).is_some() {
8761        return nanmean(values);
8762    }
8763    let mut sum = KahanSum::default();
8764    let mut count = 0_usize;
8765    for value in values {
8766        if value.is_missing() {
8767            continue;
8768        }
8769        if let Ok(x) = value.to_f64() {
8770            sum.add(x);
8771            count += 1;
8772        }
8773    }
8774    if count == 0 {
8775        return Scalar::Null(NullKind::NaN);
8776    }
8777    Scalar::Float64(sum.sum() / count as f64)
8778}
8779
8780/// [`nanvar`] as pandas' grouped var: [`WelfordVar`]. Timedelta input keeps
8781/// [`nanvar`].
8782#[must_use]
8783pub fn nanvar_grouped(values: &[Scalar], ddof: usize) -> Scalar {
8784    if collect_timedelta_ns_f64(values).is_some() {
8785        return nanvar(values, ddof);
8786    }
8787    grouped_moments(values)
8788        .var(ddof)
8789        .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
8790}
8791
8792/// [`nanstd`] as pandas' grouped std: [`WelfordVar`]. Temporal input keeps
8793/// [`nanstd`].
8794#[must_use]
8795pub fn nanstd_grouped(values: &[Scalar], ddof: usize) -> Scalar {
8796    if collect_temporal_backing(values).is_some() {
8797        return nanstd(values, ddof);
8798    }
8799    grouped_moments(values)
8800        .std(ddof)
8801        .map_or(Scalar::Null(NullKind::NaN), Scalar::Float64)
8802}
8803
8804/// Peak-to-peak range of non-missing values (max − min).
8805///
8806/// Matches `np.ptp` behavior on nan-safe inputs. Returns `Null(NaN)`
8807/// for empty or all-missing inputs.
8808pub fn nanptp(values: &[Scalar]) -> Scalar {
8809    // br-frankenpandas-axhhk: Datetime64 ptp is NOT a dtype-preserving sibling
8810    // of the Timedelta64 arm below — the span between two instants is a
8811    // DURATION, so pandas returns a Timedelta here (`s.max() - s.min()` on a
8812    // datetime64 Series). Subtract in i128 and narrow through the shared
8813    // opz27 helper so an unrepresentable span becomes NaT rather than a
8814    // fabricated extreme. Previously to_f64() errored on every element, `seen`
8815    // stayed false, and this returned Null(NaN).
8816    if is_datetime_input(values) {
8817        let (mut lo, mut hi) = (i64::MAX, i64::MIN);
8818        for value in values {
8819            if value.is_missing() {
8820                continue;
8821            }
8822            if let Scalar::Datetime64(ns) = value {
8823                lo = lo.min(*ns);
8824                hi = hi.max(*ns);
8825            }
8826        }
8827        return timedelta_ns_to_scalar(i128::from(hi) - i128::from(lo));
8828    }
8829    // Preserve every nanosecond in the uniformly-Timedelta64 case. Converting
8830    // to f64 before subtracting loses ranges below one f64 ULP beyond 104 days.
8831    // The Scalar fallback below retains mixed-family behavior.
8832    let (mut td_lo, mut td_hi) = (i64::MAX, i64::MIN);
8833    let mut saw_timedelta = false;
8834    let mut all_timedelta = true;
8835    for value in values {
8836        if value.is_missing() {
8837            continue;
8838        }
8839        match value {
8840            Scalar::Timedelta64(ns) => {
8841                saw_timedelta = true;
8842                td_lo = td_lo.min(*ns);
8843                td_hi = td_hi.max(*ns);
8844            }
8845            _ => {
8846                all_timedelta = false;
8847                break;
8848            }
8849        }
8850    }
8851    if all_timedelta && saw_timedelta {
8852        // Subtract in i128: the true range of two representable Timedeltas can
8853        // exceed i64 (max - min overflows), where live pandas 2.2.3 raises
8854        // OverflowError. Saturating here fabricated a finite Timedelta.max.
8855        return timedelta_ns_to_scalar(i128::from(td_hi) - i128::from(td_lo));
8856    }
8857    // Fused single-pass min/max (see `nansum`): track lo/hi while filtering, no
8858    // intermediate Vec<f64>. Bit-identical to the prior collect_finite two-pass:
8859    // `seen` is true exactly when collect_finite would be non-empty, and the
8860    // lo/hi comparisons fold the same finite values in the same order.
8861    let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
8862    let mut seen = false;
8863    for v in values {
8864        if v.is_missing() {
8865            continue;
8866        }
8867        if let Ok(x) = v.to_f64() {
8868            seen = true;
8869            if x < lo {
8870                lo = x;
8871            }
8872            if x > hi {
8873                hi = x;
8874            }
8875        }
8876    }
8877    if !seen {
8878        return Scalar::Null(NullKind::NaN);
8879    }
8880    Scalar::Float64(hi - lo)
8881}
8882
8883/// Sample skewness (bias-corrected, Fisher-Pearson) over non-missing values.
8884///
8885/// Matches `pd.Series.skew()`. Requires at least 3 non-missing values;
8886/// returns `Null(NaN)` otherwise, and when the sample standard deviation
8887/// is zero.
8888pub fn nanskew(values: &[Scalar]) -> Scalar {
8889    let nums = collect_finite(values);
8890    let n = nums.len() as f64;
8891    if n < 3.0 {
8892        return Scalar::Null(NullKind::NaN);
8893    }
8894    let mean = nums.iter().sum::<f64>() / n;
8895    // Accumulate both central moments while the collected values are hot. Each
8896    // sum still observes the same terms in the same order as the former two
8897    // iterator passes, preserving floating-point results bit-for-bit.
8898    let (mut m2, mut m3) = (0.0_f64, 0.0_f64);
8899    for x in nums {
8900        let delta = x - mean;
8901        // d2 reuse: 2 multiplies per element instead of 3. powi(3) lowers to two
8902        // multiplies of {delta, delta*delta}, and float MULTIPLY is commutative
8903        // bit-for-bit, so both sums observe the identical terms — the comment above
8904        // about preserving results bit-for-bit still holds. No ADDITION order changed.
8905        // (br-frankenpandas-8s4mb)
8906        let d2 = delta * delta;
8907        m2 += d2;
8908        m3 += d2 * delta;
8909    }
8910    let s2 = m2 / (n - 1.0);
8911    if s2 == 0.0 {
8912        return Scalar::Float64(0.0);
8913    }
8914    let s3 = s2.powf(1.5);
8915    Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
8916}
8917
8918/// Excess sample kurtosis (Fisher's definition, bias-corrected) over
8919/// non-missing values.
8920///
8921/// Matches `pd.Series.kurt()`. Requires at least 4 non-missing values;
8922/// returns `Null(NaN)` otherwise, and when the sample standard deviation
8923/// is zero.
8924pub fn nankurt(values: &[Scalar]) -> Scalar {
8925    let nums = collect_finite(values);
8926    let n = nums.len() as f64;
8927    if n < 4.0 {
8928        return Scalar::Null(NullKind::NaN);
8929    }
8930    let mean = nums.iter().sum::<f64>() / n;
8931    // Accumulate both central moments while the collected values are hot. Each
8932    // sum still observes the same terms in the same order as the former two
8933    // iterator passes, preserving floating-point results bit-for-bit.
8934    let (mut m2, mut m4) = (0.0_f64, 0.0_f64);
8935    for x in nums {
8936        let delta = x - mean;
8937        // d2 reuse; see `nanskew`. powi(4) lowers to (d*d)*(d*d), which is exactly
8938        // d2 * d2, so this is bit-identical.
8939        let d2 = delta * delta;
8940        m2 += d2;
8941        m4 += d2 * d2;
8942    }
8943    let s2 = m2 / (n - 1.0);
8944    if s2 == 0.0 {
8945        return Scalar::Float64(0.0);
8946    }
8947    let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
8948    let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
8949    Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
8950}
8951
8952/// Product of non-missing values. Returns 1.0 for empty input (matching pandas).
8953pub fn nanprod(values: &[Scalar]) -> Scalar {
8954    // Per br-frankenpandas-szq6a: pandas raises TypeError on
8955    // td_series.prod() because Timedelta² has no dimension. Returning the
8956    // misleading Float64(1.0) (empty-iterator default after collect_finite
8957    // drops every Timedelta64) is worse than surfacing missing. NaT
8958    // propagates the "type-incompatible" signal in lieu of a Result-level
8959    // error.
8960    if is_timedelta_input(values) {
8961        return Scalar::Null(NullKind::NaN);
8962    }
8963    // Fused single-pass fold (see `nansum`): filter missing / non-coercible and
8964    // multiply in one scan, no intermediate Vec<f64>. Bit-identical to
8965    // `collect_finite(..).iter().product()`: same finite values, same order,
8966    // same f64 `*` (Product for f64 == fold(1.0, *)); empty -> 1.0.
8967    let mut prod = 1.0_f64;
8968    for v in values {
8969        if v.is_missing() {
8970            continue;
8971        }
8972        if let Ok(x) = v.to_f64() {
8973            prod *= x;
8974        }
8975    }
8976    Scalar::Float64(prod)
8977}
8978
8979/// Cumulative sum respecting null propagation.
8980///
8981/// Per br-frankenpandas-x0x91: detect uniformly-Timedelta64 input
8982/// (allowing Null/NAT missing markers). Returns true when at least one
8983/// non-missing value is Timedelta64 and no other dtype appears.
8984fn is_timedelta_input(values: &[Scalar]) -> bool {
8985    let mut saw_td = false;
8986    for v in values {
8987        if v.is_missing() {
8988            continue;
8989        }
8990        match v {
8991            Scalar::Timedelta64(_) => saw_td = true,
8992            _ => return false,
8993        }
8994    }
8995    saw_td
8996}
8997
8998/// Datetime64 mirror of [`collect_timedelta_ns`], per br-frankenpandas-adv58.
8999///
9000/// Note the deliberate difference from [`is_datetime_input`]: the family is
9001/// marked on seeing the *variant*, before the missing check, so an ALL-NaT
9002/// datetime input still reports as the Datetime family with `count == 0`. That
9003/// is what lets `nanmean` return `Datetime64(NaT)` — preserving dtype the way
9004/// pandas does — instead of degrading to a numeric NaN. `collect_timedelta_ns`
9005/// has used this convention all along; matching it keeps the two families
9006/// symmetric.
9007fn collect_datetime_ns(values: &[Scalar]) -> Option<(i128, usize)> {
9008    let mut sum: i128 = 0;
9009    let mut count: usize = 0;
9010    let mut saw_datetime = false;
9011    for v in values {
9012        match v {
9013            Scalar::Datetime64(ns) => {
9014                saw_datetime = true;
9015                if v.is_missing() {
9016                    continue;
9017                }
9018                sum += i128::from(*ns);
9019                count += 1;
9020            }
9021            _ if v.is_missing() => continue,
9022            _ => return None,
9023        }
9024    }
9025    if saw_datetime {
9026        Some((sum, count))
9027    } else {
9028        None
9029    }
9030}
9031
9032/// Sibling of [`is_timedelta_input`] for Datetime64, per br-frankenpandas-axhhk.
9033///
9034/// `Datetime64::to_f64()` errors exactly like `Timedelta64::to_f64()` does, so
9035/// every reduction that routed datetimes through the f64 catch-all silently
9036/// produced `Null(NaN)`. Datetime64 orders exactly like its i64 nanosecond
9037/// backing, and NaT (`Timestamp::NAT`) is already filtered by `is_missing`.
9038fn is_datetime_input(values: &[Scalar]) -> bool {
9039    let mut saw_dt = false;
9040    for v in values {
9041        if v.is_missing() {
9042            continue;
9043        }
9044        match v {
9045            Scalar::Datetime64(_) => saw_dt = true,
9046            _ => return false,
9047        }
9048    }
9049    saw_dt
9050}
9051
9052/// Returns true for uniformly-Int64 input with optional missing markers.
9053fn is_int64_input(values: &[Scalar]) -> bool {
9054    let mut saw_int = false;
9055    for value in values {
9056        if value.is_missing() {
9057            continue;
9058        }
9059        match value {
9060            Scalar::Int64(_) => saw_int = true,
9061            _ => return false,
9062        }
9063    }
9064    saw_int
9065}
9066
9067/// First-position arg-extremum over a uniformly i64-backed scalar family.
9068/// True when every non-missing value is an Interval, per br-frankenpandas-2h9dm.
9069fn is_interval_input(values: &[Scalar]) -> bool {
9070    let mut saw_interval = false;
9071    for v in values {
9072        if v.is_missing() {
9073            continue;
9074        }
9075        match v {
9076            Scalar::Interval(_) => saw_interval = true,
9077            _ => return false,
9078        }
9079    }
9080    saw_interval
9081}
9082
9083/// Positional extreme over a uniformly-Interval input, per br-frankenpandas-2h9dm.
9084///
9085/// Intervals cannot use [`nanarg_i64`] (they are two f64s, not an i64 newtype)
9086/// and cannot use the f64 fallback in the callers (`to_f64` errors on them), so
9087/// they get this dedicated lexicographic (left, right) walk. `closed` is not
9088/// part of the comparison, for the reasons documented on `nanmin`.
9089///
9090/// Returns `None` if any bound is NaN: such an interval is not orderable and
9091/// pandas will not even construct one, so an arbitrary index would be worse
9092/// than declining. This is also why the comparison is a plain `<`/`>` on a
9093/// tuple rather than `partial_cmp().unwrap()`, which would panic.
9094fn nanarg_interval(values: &[Scalar], find_max: bool) -> Option<usize> {
9095    let mut best: Option<(usize, (f64, f64))> = None;
9096    for (index, value) in values.iter().enumerate() {
9097        if value.is_missing() {
9098            continue;
9099        }
9100        let Scalar::Interval(iv) = value else {
9101            continue;
9102        };
9103        if iv.left.is_nan() || iv.right.is_nan() {
9104            return None;
9105        }
9106        let key = (iv.left, iv.right);
9107        match best {
9108            None => best = Some((index, key)),
9109            // Strict comparison keeps the FIRST occurrence of a duplicated
9110            // extreme, which is what pandas' idxmin/idxmax return.
9111            Some((_, current)) if (find_max && key > current) || (!find_max && key < current) => {
9112                best = Some((index, key));
9113            }
9114            _ => {}
9115        }
9116    }
9117    best.map(|(index, _)| index)
9118}
9119
9120fn nanarg_i64(values: &[Scalar], find_max: bool) -> Option<usize> {
9121    let mut best: Option<(usize, i64)> = None;
9122    for (index, value) in values.iter().enumerate() {
9123        if value.is_missing() {
9124            continue;
9125        }
9126        // br-frankenpandas-axhhk: Datetime64 joins the typed i64 families here.
9127        // Its ns backing orders identically, and routing it through the f64
9128        // path instead returned None for any 2+-element datetime input.
9129        //
9130        // br-frankenpandas-d7zjp: Period cannot join this or-pattern — it is a
9131        // STRUCT, not an i64 newtype — so it contributes its ordinal here. The
9132        // caller has already established a single freq via
9133        // `collect_temporal_backing`, so these ordinals are comparable.
9134        let candidate = match value {
9135            Scalar::Int64(raw) | Scalar::Timedelta64(raw) | Scalar::Datetime64(raw) => raw,
9136            Scalar::Period(p) => &p.ordinal,
9137            _ => continue,
9138        };
9139        match best {
9140            None => best = Some((index, *candidate)),
9141            Some((_, current))
9142                if (find_max && *candidate > current) || (!find_max && *candidate < current) =>
9143            {
9144                best = Some((index, *candidate));
9145            }
9146            _ => {}
9147        }
9148    }
9149    best.map(|(index, _)| index)
9150}
9151
9152/// Per br-frankenpandas-x0x91: cumulative running aggregation over a
9153/// uniformly-Timedelta64 input. NaT/Null positions emit NaT and skip
9154/// the accumulator. Saturating i128 keeps overflow contained at i64
9155/// bounds when emitting.
9156fn timedelta_cumulative<F>(values: &[Scalar], init: i128, mut step: F) -> Vec<Scalar>
9157where
9158    F: FnMut(i128, i128) -> i128,
9159{
9160    let mut out = Vec::with_capacity(values.len());
9161    let mut running: i128 = init;
9162    for v in values {
9163        if v.is_missing() {
9164            out.push(Scalar::Null(NullKind::NaT));
9165            continue;
9166        }
9167        if let Scalar::Timedelta64(ns) = v {
9168            // `running` is exact: i128 has enough headroom that folding i64
9169            // nanoseconds cannot overflow it for any constructible input. Only
9170            // the narrowing to the output element can fail, so a running sum
9171            // that overflows i64 and later returns to range emits its true
9172            // value again instead of poisoning the tail — nothing is
9173            // fabricated at any index.
9174            running = step(running, i128::from(*ns));
9175            out.push(timedelta_ns_to_scalar(running));
9176        } else {
9177            out.push(Scalar::Null(NullKind::NaT));
9178        }
9179    }
9180    out
9181}
9182
9183/// Per br-frankenpandas-x0x91: running extrema (min/max) over a
9184/// uniformly-Timedelta64 input. `sentinel` is the identity element
9185/// (i64::MAX for min, i64::MIN for max) used until the first
9186/// non-missing value initializes the accumulator.
9187/// `make` builds the output scalar from the running ns value, so the same
9188/// walk serves Timedelta64 and — per br-frankenpandas-axhhk — Datetime64,
9189/// whose running extrema are Timestamps rather than durations.
9190fn timedelta_cumulative_extrema<F>(
9191    values: &[Scalar],
9192    sentinel: i64,
9193    make: TemporalFamily,
9194    mut step: F,
9195) -> Vec<Scalar>
9196where
9197    F: FnMut(i64, i64) -> i64,
9198{
9199    let mut out = Vec::with_capacity(values.len());
9200    let mut running: Option<i64> = None;
9201    for v in values {
9202        if v.is_missing() {
9203            out.push(Scalar::Null(NullKind::NaT));
9204            continue;
9205        }
9206        // br-frankenpandas-d7zjp: a Period contributes its ordinal.
9207        let raw = match v {
9208            Scalar::Timedelta64(ns) | Scalar::Datetime64(ns) => Some(*ns),
9209            Scalar::Period(p) => Some(p.ordinal),
9210            _ => None,
9211        };
9212        if let Some(ns) = raw.as_ref() {
9213            let new_val = match running {
9214                Some(prev) => step(prev, *ns),
9215                None => *ns,
9216            };
9217            running = Some(new_val);
9218            out.push(make.make(new_val));
9219        } else {
9220            out.push(Scalar::Null(NullKind::NaT));
9221        }
9222    }
9223    let _ = sentinel; // silence unused warning if closure ignores it
9224    out
9225}
9226
9227/// Matches `np.nancumsum` / `pd.Series.cumsum()`. Missing input positions
9228/// pass through as `Null(NaN)` in the output; the running sum ignores
9229/// those positions when accumulating.
9230/// Cumulative sum under an explicit overflow policy.
9231///
9232/// br-frankenpandas-fyr1z-wrap-signoff-s4lkx, DECIDED BY THE MAINTAINER: under
9233/// [`OverflowPolicy::Strict`] this REPRODUCES pandas' silent int64 wraparound,
9234/// because STRICT means bit-for-bit observable parity with the incumbent
9235/// including its quirks.
9236///
9237/// Verified against live pandas 2.2.3:
9238/// `Series([Timedelta.max, Timedelta.max]).cumsum()` returns
9239/// `[9223372036854775807, -2]` and the three-element case
9240/// `[max, -2, 9223372036854775805]` — exactly `wrapping_add` accumulation in
9241/// i64. Note the third element proves the accumulator KEEPS WRAPPING rather
9242/// than sticking: it is `(-2).wrapping_add(max)`.
9243///
9244/// Under every other policy this delegates to [`nancumsum`], which keeps the
9245/// exact-i128 accumulation and NaT-on-unrepresentable behaviour from
9246/// br-frankenpandas-opz27. See DISC-020.
9247#[must_use]
9248pub fn nancumsum_with_policy(values: &[Scalar], policy: OverflowPolicy) -> Vec<Scalar> {
9249    if !matches!(policy, OverflowPolicy::Strict) || !is_timedelta_input(values) {
9250        return nancumsum(values);
9251    }
9252    let mut out = Vec::with_capacity(values.len());
9253    let mut running: i64 = 0;
9254    for value in values {
9255        if value.is_missing() {
9256            out.push(Scalar::Null(NullKind::NaT));
9257            continue;
9258        }
9259        if let Scalar::Timedelta64(ns) = value {
9260            // Deliberately WRAPPING, not checked: this is the incumbent's
9261            // observable behaviour and STRICT exists to reproduce it.
9262            running = running.wrapping_add(*ns);
9263            out.push(Scalar::Timedelta64(running));
9264        } else {
9265            out.push(Scalar::Null(NullKind::NaT));
9266        }
9267    }
9268    out
9269}
9270
9271pub fn nancumsum(values: &[Scalar]) -> Vec<Scalar> {
9272    // Per br-frankenpandas-x0x91: when input is uniformly Timedelta64 (with
9273    // optional NaT/Null missing markers), preserve Timedelta dtype to match
9274    // pandas td_series.cumsum() returning Timedelta64.
9275    if is_timedelta_input(values) {
9276        return timedelta_cumulative(values, 0_i128, |acc, x| acc.saturating_add(x));
9277    }
9278    let mut out = Vec::with_capacity(values.len());
9279    let mut running = 0.0_f64;
9280    for v in values {
9281        if v.is_missing() {
9282            out.push(Scalar::Null(NullKind::NaN));
9283            continue;
9284        }
9285        match v.to_f64() {
9286            Ok(x) if !x.is_nan() => {
9287                running += x;
9288                out.push(Scalar::Float64(running));
9289            }
9290            _ => out.push(Scalar::Null(NullKind::NaN)),
9291        }
9292    }
9293    out
9294}
9295
9296/// Cumulative product respecting null propagation.
9297///
9298/// Matches `np.nancumprod` / `pd.Series.cumprod()`. Missing positions
9299/// pass through as `Null(NaN)` without advancing the running product.
9300pub fn nancumprod(values: &[Scalar]) -> Vec<Scalar> {
9301    let mut out = Vec::with_capacity(values.len());
9302    let mut running = 1.0_f64;
9303    for v in values {
9304        if v.is_missing() {
9305            out.push(Scalar::Null(NullKind::NaN));
9306            continue;
9307        }
9308        match v.to_f64() {
9309            Ok(x) if !x.is_nan() => {
9310                running *= x;
9311                out.push(Scalar::Float64(running));
9312            }
9313            _ => out.push(Scalar::Null(NullKind::NaN)),
9314        }
9315    }
9316    out
9317}
9318
9319/// Cumulative maximum respecting null propagation.
9320///
9321/// Matches `pd.Series.cummax()`. Missing positions pass through as
9322/// `Null(NaN)` without updating the running maximum. The first
9323/// non-missing value initializes the running maximum.
9324pub fn nancummax(values: &[Scalar]) -> Vec<Scalar> {
9325    // Per br-frankenpandas-x0x91 (Timedelta64), -axhhk (Datetime64) and
9326    // -d7zjp (Period): every uniformly-temporal family preserves its dtype
9327    // here. Without this the f64 path below errors on every element and
9328    // produces an all-NaN column. A mixed-freq Period input is not one family,
9329    // so it correctly does not take this path.
9330    if let Some((_, family)) = collect_temporal_backing(values) {
9331        return timedelta_cumulative_extrema(values, i64::MAX, family, |acc, x| acc.max(x));
9332    }
9333    let mut out = Vec::with_capacity(values.len());
9334    let mut running: Option<f64> = None;
9335    for v in values {
9336        if v.is_missing() {
9337            out.push(Scalar::Null(NullKind::NaN));
9338            continue;
9339        }
9340        match v.to_f64() {
9341            Ok(x) if !x.is_nan() => {
9342                let new_val = match running {
9343                    Some(prev) => prev.max(x),
9344                    None => x,
9345                };
9346                running = Some(new_val);
9347                out.push(Scalar::Float64(new_val));
9348            }
9349            _ => out.push(Scalar::Null(NullKind::NaN)),
9350        }
9351    }
9352    out
9353}
9354
9355/// Cumulative minimum respecting null propagation.
9356///
9357/// Matches `pd.Series.cummin()`. Symmetric to `nancummax`.
9358pub fn nancummin(values: &[Scalar]) -> Vec<Scalar> {
9359    // Per br-frankenpandas-x0x91: Timedelta64 preserves dtype.
9360    if is_timedelta_input(values) {
9361        return timedelta_cumulative_extrema(
9362            values,
9363            i64::MIN,
9364            TemporalFamily::Timedelta,
9365            |acc, x| acc.min(x),
9366        );
9367    }
9368    // br-frankenpandas-axhhk / -d7zjp: Datetime64 and Period siblings.
9369    if let Some((_, family)) = collect_temporal_backing(values) {
9370        return timedelta_cumulative_extrema(values, i64::MIN, family, |acc, x| acc.min(x));
9371    }
9372    let mut out = Vec::with_capacity(values.len());
9373    let mut running: Option<f64> = None;
9374    for v in values {
9375        if v.is_missing() {
9376            out.push(Scalar::Null(NullKind::NaN));
9377            continue;
9378        }
9379        match v.to_f64() {
9380            Ok(x) if !x.is_nan() => {
9381                let new_val = match running {
9382                    Some(prev) => prev.min(x),
9383                    None => x,
9384                };
9385                running = Some(new_val);
9386                out.push(Scalar::Float64(new_val));
9387            }
9388            _ => out.push(Scalar::Null(NullKind::NaN)),
9389        }
9390    }
9391    out
9392}
9393
9394/// Linear-interpolation quantile over non-missing numeric values.
9395///
9396/// Matches `np.nanquantile(values, q)` with `interpolation='linear'`.
9397/// Returns `Null(NaN)` for empty inputs or when `q` is outside
9398/// `[0.0, 1.0]`.
9399pub fn nanquantile(values: &[Scalar], q: f64) -> Scalar {
9400    if !(0.0..=1.0).contains(&q) {
9401        return Scalar::Null(NullKind::NaN);
9402    }
9403    // Per br-frankenpandas-5djk7: pandas td_series.quantile(q) returns
9404    // Timedelta64 with linear-interpolated ns. Was silently NaN before.
9405    if let Some((mut td, make)) = collect_temporal_backing(values) {
9406        if td.is_empty() {
9407            return make.nat();
9408        }
9409        let n = td.len();
9410        if n == 1 {
9411            return float_ns_to_temporal(td[0], make);
9412        }
9413        let pos = q * (n - 1) as f64;
9414        let lo = pos.floor() as usize;
9415        let hi = pos.ceil() as usize;
9416        // O(n) selection instead of a full sort (see the numeric arm below):
9417        // select the lo-th order statistic; the (lo+1)-th is the MIN of the
9418        // right partition. Bit-identical (finite ns, values-only order stats).
9419        let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
9420        let (_left, lo_ref, right) = td.select_nth_unstable_by(lo, cmp);
9421        let lo_val = *lo_ref;
9422        let ns = if lo == hi {
9423            lo_val
9424        } else {
9425            let hi_val = right.iter().copied().fold(f64::INFINITY, f64::min);
9426            let weight = pos - lo as f64;
9427            lo_val + (hi_val - lo_val) * weight
9428        };
9429        return float_ns_to_temporal(ns, make);
9430    }
9431    let mut nums = collect_finite(values);
9432    if nums.is_empty() {
9433        return Scalar::Null(NullKind::NaN);
9434    }
9435    let n = nums.len();
9436    if n == 1 {
9437        return Scalar::Float64(nums[0]);
9438    }
9439    let pos = q * (n - 1) as f64;
9440    let lo = pos.floor() as usize;
9441    let hi = pos.ceil() as usize;
9442    // O(n) selection instead of a full sort: select the `lo`-th order statistic;
9443    // when interpolation is needed (hi == lo+1) the (lo+1)-th smallest is the
9444    // MIN of the right partition. Bit-identical to the sort path (same
9445    // nums[lo]/nums[hi] values, since order statistics depend only on values).
9446    let cmp = |a: &f64, b: &f64| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal);
9447    let (_left, lo_ref, right) = nums.select_nth_unstable_by(lo, cmp);
9448    let lo_val = *lo_ref;
9449    if lo == hi {
9450        return Scalar::Float64(lo_val);
9451    }
9452    let hi_val = right.iter().copied().fold(f64::INFINITY, f64::min);
9453    let weight = pos - lo as f64;
9454    Scalar::Float64(lo_val + (hi_val - lo_val) * weight)
9455}
9456
9457/// Position (in the original slice) of the non-missing maximum.
9458///
9459/// Matches `np.nanargmax`. Returns `None` if every value is missing.
9460/// Ties resolve to the first position seen (matching numpy).
9461pub fn nanargmax(values: &[Scalar]) -> Option<usize> {
9462    // Compare typed 64-bit families directly: f64 coercion loses ordering for
9463    // adjacent Int64 values beyond the 53-bit exactness boundary.
9464    // br-frankenpandas-axhhk: Datetime64 belongs here too — it not only loses
9465    // ordering under f64, its to_f64() errors outright, so it returned None.
9466    if is_int64_input(values) || collect_temporal_backing(values).is_some() {
9467        return nanarg_i64(values, true);
9468    }
9469    // br-frankenpandas-2h9dm: Intervals order lexicographically by
9470    // (left, right) and fit neither the i64 walk above nor the f64 fallback
9471    // below, whose to_f64() errors on them — so they returned None.
9472    if is_interval_input(values) {
9473        return nanarg_interval(values, true);
9474    }
9475    let mut best: Option<(usize, f64)> = None;
9476    for (i, v) in values.iter().enumerate() {
9477        if v.is_missing() {
9478            continue;
9479        }
9480        if let Ok(x) = v.to_f64() {
9481            if x.is_nan() {
9482                continue;
9483            }
9484            match best {
9485                None => best = Some((i, x)),
9486                Some((_, cur)) if x > cur => best = Some((i, x)),
9487                _ => {}
9488            }
9489        }
9490    }
9491    best.map(|(i, _)| i)
9492}
9493
9494/// Position (in the original slice) of the non-missing minimum.
9495///
9496/// Matches `np.nanargmin`. Returns `None` if every value is missing.
9497pub fn nanargmin(values: &[Scalar]) -> Option<usize> {
9498    // See nanargmax: preserve exact ordering for typed 64-bit families
9499    // (Datetime64 included, per br-frankenpandas-axhhk).
9500    if is_int64_input(values) || collect_temporal_backing(values).is_some() {
9501        return nanarg_i64(values, false);
9502    }
9503    // br-frankenpandas-2h9dm: Interval sibling of the branch in `nanargmax`.
9504    if is_interval_input(values) {
9505        return nanarg_interval(values, false);
9506    }
9507    let mut best: Option<(usize, f64)> = None;
9508    for (i, v) in values.iter().enumerate() {
9509        if v.is_missing() {
9510            continue;
9511        }
9512        if let Ok(x) = v.to_f64() {
9513            if x.is_nan() {
9514                continue;
9515            }
9516            match best {
9517                None => best = Some((i, x)),
9518                Some((_, cur)) if x < cur => best = Some((i, x)),
9519                _ => {}
9520            }
9521        }
9522    }
9523    best.map(|(i, _)| i)
9524}
9525
9526/// Count of unique non-missing values.
9527pub fn nannunique(values: &[Scalar]) -> Scalar {
9528    use rustc_hash::FxHashSet;
9529    #[derive(Hash, PartialEq, Eq)]
9530    enum ScalarKey<'a> {
9531        Bool(bool),
9532        Int64(i64),
9533        FloatBits(u64),
9534        Utf8(&'a str),
9535        Timedelta64(i64),
9536        Datetime64(i64),
9537        Period(i64, PeriodFreq),
9538        Interval(u64, u64, IntervalClosed),
9539        // An object cell counts by its repr (pandas hashes the object; a
9540        // list would be unhashable there).
9541        Object(String),
9542    }
9543
9544    let mut seen = FxHashSet::default();
9545    for val in values {
9546        if val.is_missing() {
9547            continue;
9548        }
9549        let key = match val {
9550            Scalar::Bool(v) => ScalarKey::Bool(*v),
9551            Scalar::Int64(v) => ScalarKey::Int64(*v),
9552            Scalar::Float64(v) => {
9553                let normalized = if *v == 0.0 { 0.0 } else { *v };
9554                ScalarKey::FloatBits(normalized.to_bits())
9555            }
9556            Scalar::Utf8(v) => ScalarKey::Utf8(v.as_str()),
9557            Scalar::Timedelta64(v) => ScalarKey::Timedelta64(*v),
9558            Scalar::Datetime64(v) => ScalarKey::Datetime64(*v),
9559            Scalar::Period(p) => ScalarKey::Period(p.ordinal, p.freq),
9560            Scalar::Interval(v) => ScalarKey::Interval(
9561                normalized_float_bits(v.left),
9562                normalized_float_bits(v.right),
9563                v.closed,
9564            ),
9565            Scalar::Object(object) => ScalarKey::Object(object.repr()),
9566            Scalar::Null(_) => continue,
9567        };
9568        seen.insert(key);
9569    }
9570    Scalar::Int64(seen.len() as i64)
9571}
9572
9573fn normalized_float_bits(value: f64) -> u64 {
9574    let normalized = if value == 0.0 { 0.0 } else { value };
9575    normalized.to_bits()
9576}
9577
9578// ── Interval types (br-frankenpandas-j8k4 Phase 1) ──────────────────────
9579//
9580// Scaffolding for pandas `pd.Interval` / `pd.IntervalIndex` / `pd.IntervalDtype`.
9581//
9582// Phase 1 ships float-valued intervals only (matches `cut`/`qcut` output on
9583// numeric bins — the dominant pandas use case). Generic-subtype intervals
9584// over Int64 / Timestamp are deferred to Phase 2 alongside the DType::Interval
9585// enum-variant wiring. See br-j8k4 for the phased roadmap.
9586//
9587// Semantics mirror pandas: closed tells which endpoints are included.
9588//   Left    → [left, right)
9589//   Right   → (left, right]       ← pandas default
9590//   Both    → [left, right]
9591//   Neither → (left, right)
9592
9593/// Endpoint-inclusion policy for an `Interval`.
9594///
9595/// Matches pandas `pd.Interval.closed` / `pd.IntervalDtype.closed` string
9596/// values ("left" / "right" / "both" / "neither").
9597#[derive(
9598    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize,
9599)]
9600#[serde(rename_all = "snake_case")]
9601#[non_exhaustive]
9602pub enum IntervalClosed {
9603    /// `[left, right)` — left-inclusive, right-exclusive.
9604    Left,
9605    /// `(left, right]` — left-exclusive, right-inclusive. Pandas default.
9606    #[default]
9607    Right,
9608    /// `[left, right]` — both endpoints included.
9609    Both,
9610    /// `(left, right)` — neither endpoint included.
9611    Neither,
9612}
9613
9614impl IntervalClosed {
9615    /// Left endpoint included?
9616    #[must_use]
9617    pub fn left_closed(self) -> bool {
9618        matches!(self, Self::Left | Self::Both)
9619    }
9620
9621    /// Right endpoint included?
9622    #[must_use]
9623    pub fn right_closed(self) -> bool {
9624        matches!(self, Self::Right | Self::Both)
9625    }
9626}
9627
9628impl std::fmt::Display for IntervalClosed {
9629    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9630        match self {
9631            Self::Left => write!(f, "left"),
9632            Self::Right => write!(f, "right"),
9633            Self::Both => write!(f, "both"),
9634            Self::Neither => write!(f, "neither"),
9635        }
9636    }
9637}
9638
9639/// The type of an interval's endpoints, pandas' `interval[int64]` or
9640/// `interval[float64]` subtype: integer endpoints print without '.0'
9641/// (`pd.cut(s, [0, 3, 6])` is `(0, 3]`, where float edges are `(0.0, 3.0]`).
9642/// The endpoints themselves are `f64` either way (fvsao.54).
9643#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
9644#[serde(rename_all = "snake_case")]
9645pub enum IntervalSubtype {
9646    #[default]
9647    Float64,
9648    Int64,
9649}
9650
9651impl IntervalSubtype {
9652    /// Whether this is the float subtype (serde skips it, the default).
9653    #[must_use]
9654    pub const fn is_float(&self) -> bool {
9655        matches!(self, Self::Float64)
9656    }
9657
9658    /// The subtype's dtype name ('int64' / 'float64').
9659    #[must_use]
9660    pub const fn name(&self) -> &'static str {
9661        match self {
9662            Self::Float64 => "float64",
9663            Self::Int64 => "int64",
9664        }
9665    }
9666}
9667
9668/// A bounded numeric interval between two `f64` endpoints.
9669///
9670/// Matches `pd.Interval(left, right, closed)` on the numeric-subtype path.
9671/// Accessors match pandas: `.left`, `.right`, `.closed`, `.length`, `.mid`,
9672/// `.contains`, `.is_empty`, `.overlaps`. Equality ignores the `subtype`, as
9673/// pandas' `Interval(0, 3) == Interval(0.0, 3.0)`.
9674#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
9675pub struct Interval {
9676    pub left: f64,
9677    pub right: f64,
9678    #[serde(default)]
9679    pub closed: IntervalClosed,
9680    /// The endpoints' type as pandas reports and prints it.
9681    #[serde(default, skip_serializing_if = "IntervalSubtype::is_float")]
9682    pub subtype: IntervalSubtype,
9683}
9684
9685impl PartialEq for Interval {
9686    fn eq(&self, other: &Self) -> bool {
9687        self.left == other.left && self.right == other.right && self.closed == other.closed
9688    }
9689}
9690
9691/// An interval as a label (an IntervalIndex's; br-frankenpandas-c27hq): its
9692/// endpoints compare as floats, so only an interval with a NaN endpoint,
9693/// which pandas never builds, is unequal to itself.
9694impl Eq for Interval {}
9695
9696impl Interval {
9697    /// An endpoint as it compares: -0.0 is 0.0, as `==` has it.
9698    fn endpoint_key(value: f64) -> f64 {
9699        if value == 0.0 { 0.0 } else { value }
9700    }
9701}
9702
9703/// Hashed as it compares: the endpoints (-0.0 as 0.0) and the closed side;
9704/// the subtype is not part of the value.
9705impl std::hash::Hash for Interval {
9706    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
9707        Self::endpoint_key(self.left).to_bits().hash(state);
9708        Self::endpoint_key(self.right).to_bits().hash(state);
9709        self.closed.hash(state);
9710    }
9711}
9712
9713/// pandas' IntervalIndex order: by the left endpoint, then the right, then
9714/// the closed side.
9715impl Ord for Interval {
9716    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
9717        Self::endpoint_key(self.left)
9718            .total_cmp(&Self::endpoint_key(other.left))
9719            .then_with(|| {
9720                Self::endpoint_key(self.right).total_cmp(&Self::endpoint_key(other.right))
9721            })
9722            .then_with(|| self.closed.cmp(&other.closed))
9723    }
9724}
9725
9726impl PartialOrd for Interval {
9727    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
9728        Some(self.cmp(other))
9729    }
9730}
9731
9732impl Interval {
9733    /// Construct an interval. No validation on `left <= right` — pandas also
9734    /// accepts reversed intervals (they're non-empty only if empty-by-design).
9735    #[must_use]
9736    pub const fn new(left: f64, right: f64, closed: IntervalClosed) -> Self {
9737        Self {
9738            left,
9739            right,
9740            closed,
9741            subtype: IntervalSubtype::Float64,
9742        }
9743    }
9744
9745    /// This interval with integer endpoints (pandas' `interval[int64]`)
9746    /// when both are whole numbers; unchanged otherwise.
9747    #[must_use]
9748    pub fn with_int_endpoints(self) -> Self {
9749        if self.left.fract() == 0.0 && self.right.fract() == 0.0 {
9750            Self {
9751                subtype: IntervalSubtype::Int64,
9752                ..self
9753            }
9754        } else {
9755            self
9756        }
9757    }
9758
9759    /// `right - left` (pandas `.length`). Negative for reversed intervals.
9760    #[must_use]
9761    pub fn length(&self) -> f64 {
9762        self.right - self.left
9763    }
9764
9765    /// Midpoint `(left + right) / 2` (pandas `.mid`).
9766    #[must_use]
9767    pub fn mid(&self) -> f64 {
9768        (self.left + self.right) / 2.0
9769    }
9770
9771    /// Empty iff endpoints coincide AND at least one side is open.
9772    /// Pandas semantics: `pd.Interval(3, 3, 'right').is_empty → True`.
9773    #[must_use]
9774    pub fn is_empty(&self) -> bool {
9775        self.left == self.right && !matches!(self.closed, IntervalClosed::Both)
9776    }
9777
9778    /// Does `value` fall inside this interval?
9779    ///
9780    /// NaN always returns false, matching pandas `pd.Interval.__contains__`
9781    /// behavior (NaN doesn't compare equal to anything).
9782    #[must_use]
9783    pub fn contains(&self, value: f64) -> bool {
9784        if value.is_nan() {
9785            return false;
9786        }
9787        let left_ok = if self.closed.left_closed() {
9788            value >= self.left
9789        } else {
9790            value > self.left
9791        };
9792        let right_ok = if self.closed.right_closed() {
9793            value <= self.right
9794        } else {
9795            value < self.right
9796        };
9797        left_ok && right_ok
9798    }
9799
9800    /// Do `self` and `other` share any point?
9801    ///
9802    /// Matches `pd.Interval.overlaps(other)`. Two intervals overlap iff the
9803    /// max of their lefts is less than the min of their rights, with
9804    /// endpoint-inclusion determining the strictness of the comparison when
9805    /// they touch exactly.
9806    #[must_use]
9807    pub fn overlaps(&self, other: &Self) -> bool {
9808        if self.left > other.right || other.left > self.right {
9809            return false;
9810        }
9811        // Touching-at-a-point: overlap iff both sides at that touchpoint are closed.
9812        if self.right == other.left {
9813            return self.closed.right_closed() && other.closed.left_closed();
9814        }
9815        if other.right == self.left {
9816            return other.closed.right_closed() && self.closed.left_closed();
9817        }
9818        true
9819    }
9820
9821    /// Parse an interval string. Supports bracket notation:
9822    /// - '[0, 1]' -> closed on both ends
9823    /// - '(0, 1)' -> open on both ends
9824    /// - '[0, 1)' -> closed left, open right (pandas default)
9825    /// - '(0, 1]' -> open left, closed right
9826    pub fn parse(s: &str) -> Result<Self, TypeError> {
9827        let s = s.trim();
9828        if s.len() < 5 {
9829            return Err(TypeError::ValueNotParseable {
9830                value: s.to_string(),
9831                target: "Interval".to_string(),
9832            });
9833        }
9834
9835        let first_char = s.chars().next().unwrap();
9836        let last_char = s.chars().last().unwrap();
9837
9838        let left_closed = match first_char {
9839            '[' => true,
9840            '(' => false,
9841            _ => {
9842                return Err(TypeError::ValueNotParseable {
9843                    value: s.to_string(),
9844                    target: "Interval".to_string(),
9845                });
9846            }
9847        };
9848
9849        let right_closed = match last_char {
9850            ']' => true,
9851            ')' => false,
9852            _ => {
9853                return Err(TypeError::ValueNotParseable {
9854                    value: s.to_string(),
9855                    target: "Interval".to_string(),
9856                });
9857            }
9858        };
9859
9860        let closed = match (left_closed, right_closed) {
9861            (true, true) => IntervalClosed::Both,
9862            (true, false) => IntervalClosed::Left,
9863            (false, true) => IntervalClosed::Right,
9864            (false, false) => IntervalClosed::Neither,
9865        };
9866
9867        let inner = &s[1..s.len() - 1];
9868        let Some((left_text, right_text)) = inner.split_once(',') else {
9869            return Err(TypeError::ValueNotParseable {
9870                value: s.to_string(),
9871                target: "Interval".to_string(),
9872            });
9873        };
9874        if right_text.contains(',') {
9875            return Err(TypeError::ValueNotParseable {
9876                value: s.to_string(),
9877                target: "Interval".to_string(),
9878            });
9879        }
9880
9881        let left: f64 = left_text
9882            .trim()
9883            .parse()
9884            .map_err(|_| TypeError::ValueNotParseable {
9885                value: s.to_string(),
9886                target: "Interval".to_string(),
9887            })?;
9888
9889        let right: f64 = right_text
9890            .trim()
9891            .parse()
9892            .map_err(|_| TypeError::ValueNotParseable {
9893                value: s.to_string(),
9894                target: "Interval".to_string(),
9895            })?;
9896
9897        Ok(Self::new(left, right, closed))
9898    }
9899}
9900
9901impl std::fmt::Display for Interval {
9902    /// Matches `str(pd.Interval(...))`: `interval[float64]` endpoints render
9903    /// with Python `str(float)` semantics, so whole numbers KEEP ".0"
9904    /// (`str(pd.Interval(0.0, 5.0, 'right'))` is `"(0.0, 5.0]"`, not `"(0, 5]"`).
9905    /// Verified vs pandas 2.2.3 across whole/fractional/negative/scientific
9906    /// endpoints. (br-frankenpandas-5xw1b) The `interval[int64]` subtype
9907    /// prints integers (`"(0, 5]"`).
9908    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9909        let left_bracket = if self.closed.left_closed() { '[' } else { '(' };
9910        let right_bracket = if self.closed.right_closed() { ']' } else { ')' };
9911        // The int64 subtype prints its endpoints as integers ('(0, 3]').
9912        #[allow(clippy::cast_possible_truncation)] // whole numbers, checked
9913        let endpoint = |value: f64| match self.subtype {
9914            IntervalSubtype::Int64 if value.fract() == 0.0 => format!("{}", value as i64),
9915            _ => float_to_string_for_astype(value),
9916        };
9917        write!(
9918            f,
9919            "{left_bracket}{}, {}{right_bracket}",
9920            endpoint(self.left),
9921            endpoint(self.right)
9922        )
9923    }
9924}
9925
9926// ── interval_range builders (br-frankenpandas-xaom — Phase 2 of j8k4) ────
9927
9928/// Build `periods` equal-width intervals spanning `[start, end]`.
9929///
9930/// Matches `pd.interval_range(start, end, periods=N, closed=...)` for the
9931/// numeric-subtype case. Returns exactly `periods` intervals; when
9932/// `periods == 0` or `start >= end`, returns an empty vector (matches
9933/// pandas's empty IntervalIndex).
9934///
9935/// ```
9936/// use fp_types::{interval_range_by_periods, IntervalClosed};
9937/// let bins = interval_range_by_periods(0.0, 10.0, 5, IntervalClosed::Right);
9938/// assert_eq!(bins.len(), 5);
9939/// assert_eq!(bins[0].left, 0.0);
9940/// assert_eq!(bins[0].right, 2.0);
9941/// assert_eq!(bins[4].right, 10.0);
9942/// ```
9943#[must_use]
9944pub fn interval_range_by_periods(
9945    start: f64,
9946    end: f64,
9947    periods: usize,
9948    closed: IntervalClosed,
9949) -> Vec<Interval> {
9950    if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
9951        return Vec::new();
9952    }
9953    let step = (end - start) / (periods as f64);
9954    let mut out = Vec::with_capacity(periods);
9955    for i in 0..periods {
9956        let left = start + step * (i as f64);
9957        // Use end exactly for the final right edge to avoid float drift.
9958        let right = if i + 1 == periods {
9959            end
9960        } else {
9961            start + step * ((i + 1) as f64)
9962        };
9963        out.push(Interval::new(left, right, closed));
9964    }
9965    out
9966}
9967
9968/// Build equal-`step`-width intervals spanning `[start, end]`.
9969///
9970/// Matches `pd.interval_range(start, end, freq=step, closed=...)` for the
9971/// numeric-subtype case. `step` must be finite and positive; `(end - start)`
9972/// must be an integer multiple of `step` (within float tolerance) — pandas
9973/// raises `ValueError` otherwise; this fn returns `Err(TypeError::IntervalStepDoesNotDivide)`.
9974///
9975/// Returns an empty vector when `start == end` (matches pandas' zero-bin
9976/// IntervalIndex); returns an empty vector when `start > end` (pandas also
9977/// returns empty rather than erroring in this case).
9978pub fn interval_range_by_step(
9979    start: f64,
9980    end: f64,
9981    step: f64,
9982    closed: IntervalClosed,
9983) -> Result<Vec<Interval>, TypeError> {
9984    if !step.is_finite() || !step.is_sign_positive() || step == 0.0 {
9985        return Err(TypeError::InvalidIntervalStep { step });
9986    }
9987    if !start.is_finite() || !end.is_finite() || start >= end {
9988        return Ok(Vec::new());
9989    }
9990    let span = end - start;
9991    let periods_f = span / step;
9992    let periods = periods_f.round() as i64;
9993    if periods <= 0 {
9994        return Ok(Vec::new());
9995    }
9996    let reconstructed = step * (periods as f64);
9997    // Relative tolerance: allow float-rounding noise proportional to span.
9998    if (span - reconstructed).abs() > span.abs() * 1e-9 + 1e-12 {
9999        return Err(TypeError::IntervalStepDoesNotDivide { step, span });
10000    }
10001    let periods = periods as usize;
10002    let mut out = Vec::with_capacity(periods);
10003    for i in 0..periods {
10004        let left = start + step * (i as f64);
10005        let right = if i + 1 == periods {
10006            end
10007        } else {
10008            start + step * ((i + 1) as f64)
10009        };
10010        out.push(Interval::new(left, right, closed));
10011    }
10012    Ok(out)
10013}
10014
10015/// Build equal-width intervals spanning a range, matching `pd.interval_range`.
10016///
10017/// Of the four parameters `start`, `end`, `periods`, and `freq`, exactly three must
10018/// be specified (`Some`). `closed` defaults to `IntervalClosed::Right` when `None`.
10019///
10020/// # Errors
10021/// Returns `TypeError::IntervalRangeParameterCount` if not exactly 3 of the 4 parameters
10022/// are specified.
10023/// Returns `TypeError::InvalidIntervalStep` if `freq` is not finite, not positive, or zero.
10024/// Returns `TypeError::IntervalStepDoesNotDivide` if `start`, `end`, and `freq` are given
10025/// but `(end - start)` is not an integer multiple of `freq`.
10026pub fn interval_range(
10027    start: Option<f64>,
10028    end: Option<f64>,
10029    periods: Option<usize>,
10030    freq: Option<f64>,
10031    closed: Option<IntervalClosed>,
10032) -> Result<Vec<Interval>, TypeError> {
10033    let count = usize::from(start.is_some())
10034        + usize::from(end.is_some())
10035        + usize::from(periods.is_some())
10036        + usize::from(freq.is_some());
10037    if count != 3 {
10038        return Err(TypeError::IntervalRangeParameterCount);
10039    }
10040    let closed = closed.unwrap_or(IntervalClosed::Right);
10041
10042    match (start, end, periods, freq) {
10043        (Some(start), Some(end), Some(periods), None) => {
10044            Ok(interval_range_by_periods(start, end, periods, closed))
10045        }
10046        (Some(start), Some(end), None, Some(freq)) => {
10047            interval_range_by_step(start, end, freq, closed)
10048        }
10049        (Some(start), None, Some(periods), Some(freq)) => {
10050            if !freq.is_finite() || !freq.is_sign_positive() || freq == 0.0 {
10051                return Err(TypeError::InvalidIntervalStep { step: freq });
10052            }
10053            if !start.is_finite() || periods == 0 {
10054                return Ok(Vec::new());
10055            }
10056            let mut out = Vec::with_capacity(periods);
10057            for i in 0..periods {
10058                let left = start + freq * (i as f64);
10059                let right = start + freq * ((i + 1) as f64);
10060                out.push(Interval::new(left, right, closed));
10061            }
10062            Ok(out)
10063        }
10064        (None, Some(end), Some(periods), Some(freq)) => {
10065            if !freq.is_finite() || !freq.is_sign_positive() || freq == 0.0 {
10066                return Err(TypeError::InvalidIntervalStep { step: freq });
10067            }
10068            if !end.is_finite() || periods == 0 {
10069                return Ok(Vec::new());
10070            }
10071            let start = end - freq * (periods as f64);
10072            let mut out = Vec::with_capacity(periods);
10073            for i in 0..periods {
10074                let left = start + freq * (i as f64);
10075                let right = if i + 1 == periods {
10076                    end
10077                } else {
10078                    start + freq * ((i + 1) as f64)
10079                };
10080                out.push(Interval::new(left, right, closed));
10081            }
10082            Ok(out)
10083        }
10084        _ => Err(TypeError::IntervalRangeParameterCount),
10085    }
10086}
10087
10088// ── Period types (br-frankenpandas-epoj Phase 1) ────────────────────────
10089//
10090// Scaffolding for pandas `pd.Period` / `pd.PeriodIndex` / `pd.PeriodDtype`.
10091//
10092// A Period is a calendar *span* (Q1 2024, Jan 2024, 2024-03-15), distinct
10093// from a Timestamp (an instant). Phase 1 ships the PeriodFreq enum +
10094// Period struct with ordinal-based arithmetic (Period + n, Period - Period),
10095// Display in pandas notation, and parse from standard strings. Calendar-
10096// conversion (ordinal ↔ ymd) and DType::Period wiring land in Phase 2.
10097
10098/// Period frequency code. Matches pandas offset alias core set.
10099///
10100/// The ordinal axis is frequency-specific: for Monthly, ordinal 0 is a
10101/// fixed anchor (pandas uses months since 1970-01). Phase 1 doesn't
10102/// commit to a specific epoch yet — the ordinal scheme is opaque until
10103/// Phase 2 wires calendar arithmetic. What Phase 1 DOES nail down is:
10104/// same-freq Periods compare + subtract; Period + i64 shifts by `n`
10105/// periods of the declared frequency.
10106#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10107#[serde(rename_all = "SCREAMING-KEBAB-CASE")]
10108#[non_exhaustive]
10109pub enum PeriodFreq {
10110    /// `Y-<MON>` / `A` / `Y` — annual periods of a fiscal year ending in the
10111    /// month carried (1-12; `Y` is `Y-DEC`). The ordinal counts fiscal years
10112    /// from 1970: `Period('2024', 'Y-JUN')` spans 2023-07-01..2024-06-30.
10113    Annual(u8),
10114    /// `Q-<MON>` / `Q` — quarters of a fiscal year ending in the month
10115    /// carried (1-12; `Q` is `Q-DEC`): `Period('2025Q1', 'Q-JAN')` spans
10116    /// 2024-02-01..2024-04-30.
10117    Quarterly(u8),
10118    /// `M` — monthly periods.
10119    Monthly,
10120    /// `W-<DAY>` / `W` — weeks ending on the weekday carried (0 = Monday ..
10121    /// 6 = Sunday; `W` is `W-SUN`).
10122    Weekly(u8),
10123    /// `D` — daily periods.
10124    Daily,
10125    /// `B` — business-day periods.
10126    Business,
10127    /// `h` / `H` — hourly periods.
10128    Hourly,
10129    /// `min` / `T` — minutely periods.
10130    Minutely,
10131    /// `s` / `S` — secondly periods.
10132    Secondly,
10133    /// `ms` — millisecond periods. NOT `MS`, which pandas reads as month start.
10134    Milliseconds,
10135    /// `us` / `US` — microsecond periods.
10136    Microseconds,
10137    /// `ns` / `NS` — nanosecond periods.
10138    Nanoseconds,
10139}
10140
10141/// The month abbreviations pandas anchors annual / quarterly frequencies on.
10142const PERIOD_MONTHS: [&str; 12] = [
10143    "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
10144];
10145/// The weekday abbreviations pandas anchors weekly frequencies on, Monday 0.
10146const PERIOD_WEEKDAYS: [&str; 7] = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"];
10147
10148impl PeriodFreq {
10149    /// `Y` / `Y-DEC`: calendar years.
10150    pub const ANNUAL: Self = Self::Annual(12);
10151    /// `Q` / `Q-DEC`: calendar quarters.
10152    pub const QUARTERLY: Self = Self::Quarterly(12);
10153    /// `W` / `W-SUN`: weeks Monday to Sunday.
10154    pub const WEEKLY: Self = Self::Weekly(6);
10155
10156    /// Months a date's month count moves forward to land on its fiscal
10157    /// calendar: a fiscal year ending in month `m` starts in month `m + 1`,
10158    /// so `(months since 1970-01 + shift)` divided by 12 (3) is the annual
10159    /// (quarterly) ordinal. 0 for a year ending in December and for every
10160    /// unanchored frequency.
10161    #[must_use]
10162    pub const fn fiscal_month_shift(self) -> i64 {
10163        match self {
10164            Self::Annual(month) | Self::Quarterly(month) => (12 - (month as i64 % 12)) % 12,
10165            _ => 0,
10166        }
10167    }
10168
10169    /// Days a week starts after the Monday of `W-SUN`'s week: a week ending
10170    /// on weekday `d` (Monday 0) starts on `d + 1`, so `W-MON` weeks start a
10171    /// day later and `W-SAT` ones six days later (a Sunday). 0 for `W-SUN`
10172    /// and every other frequency.
10173    #[must_use]
10174    pub const fn week_start_shift(self) -> i64 {
10175        match self {
10176            Self::Weekly(day) => (day as i64 % 7 + 1) % 7,
10177            _ => 0,
10178        }
10179    }
10180
10181    /// The anchored form `prefix-ANCHOR` of a frequency alias (`Y-JUN`,
10182    /// `Q-JAN`, `W-MON`), with pandas' deprecated `A-` annual spelling.
10183    fn parse_anchored(alias: &str) -> Option<Self> {
10184        let (prefix, anchor) = alias.split_once('-')?;
10185        let month = PERIOD_MONTHS.iter().position(|name| *name == anchor);
10186        let day = PERIOD_WEEKDAYS.iter().position(|name| *name == anchor);
10187        match (prefix, month, day) {
10188            ("A" | "Y", Some(month), _) => Some(Self::Annual(month as u8 + 1)),
10189            ("Q", Some(month), _) => Some(Self::Quarterly(month as u8 + 1)),
10190            ("W", _, Some(day)) => Some(Self::Weekly(day as u8)),
10191            _ => None,
10192        }
10193    }
10194
10195    /// Parse a pandas-style frequency alias. Recognizes the common subset
10196    /// (Y-<MON>/A/Y, Q-<MON>/Q, M, W-<DAY>/W, D, B, h/H, min/T, s/S) plus the
10197    /// sub-second units ms, us/US, ns/NS.
10198    ///
10199    /// Case-insensitive with ONE exception: bare `MS` is month start in pandas,
10200    /// not milliseconds, and is refused here the way pandas refuses it for
10201    /// `to_period`. See the check at the top of the body.
10202    pub fn parse(alias: &str) -> Option<Self> {
10203        // ⚠️ CASE MATTERS FOR EXACTLY ONE ALIAS, and this parser uppercases
10204        // everything. MEASURED, live pandas 2.2.3, Timestamp.to_period(f):
10205        //     'ms' -> millisecond      'Ms' -> millisecond
10206        //     'MS' -> ValueError       (it is month start, a date_range-only freq)
10207        //     'us' -> microsecond      'US' -> microsecond
10208        //     'ns' -> nanosecond       'NS' -> nanosecond
10209        // So only the fully-capitalised `MS` is excluded; every other casing of
10210        // "ms" is milliseconds, while us/ns are case-insensitive and belong in
10211        // the table below. Checked here, before the uppercase collapses it.
10212        if alias.eq_ignore_ascii_case("ms") && alias != "MS" {
10213            return Some(Self::Milliseconds);
10214        }
10215        match alias.to_ascii_uppercase().as_str() {
10216            "A" | "Y" | "ANNUAL" | "YEARLY" => Some(Self::ANNUAL),
10217            "Q" | "QUARTERLY" => Some(Self::QUARTERLY),
10218            "M" | "MONTHLY" => Some(Self::Monthly),
10219            "W" | "WEEKLY" => Some(Self::WEEKLY),
10220            "D" | "DAILY" => Some(Self::Daily),
10221            "B" | "BUSINESS" => Some(Self::Business),
10222            "H" | "HOURLY" => Some(Self::Hourly),
10223            "T" | "MIN" | "MINUTELY" => Some(Self::Minutely),
10224            "S" | "SECONDLY" => Some(Self::Secondly),
10225            "US" | "MICROSECOND" | "MICROSECONDS" => Some(Self::Microseconds),
10226            "NS" | "NANOSECOND" | "NANOSECONDS" => Some(Self::Nanoseconds),
10227            // The spelled-out form only; bare "MS" is deliberately absent, and
10228            // every other casing of it was taken above.
10229            "MILLISECOND" | "MILLISECONDS" => Some(Self::Milliseconds),
10230            anchored => Self::parse_anchored(anchored),
10231        }
10232    }
10233
10234    /// Canonical pandas alias string.
10235    #[must_use]
10236    pub const fn alias(self) -> &'static str {
10237        const ANNUAL: [&str; 12] = [
10238            "Y-JAN", "Y-FEB", "Y-MAR", "Y-APR", "Y-MAY", "Y-JUN", "Y-JUL", "Y-AUG", "Y-SEP",
10239            "Y-OCT", "Y-NOV", "Y-DEC",
10240        ];
10241        const QUARTERLY: [&str; 12] = [
10242            "Q-JAN", "Q-FEB", "Q-MAR", "Q-APR", "Q-MAY", "Q-JUN", "Q-JUL", "Q-AUG", "Q-SEP",
10243            "Q-OCT", "Q-NOV", "Q-DEC",
10244        ];
10245        const WEEKLY: [&str; 7] = [
10246            "W-MON", "W-TUE", "W-WED", "W-THU", "W-FRI", "W-SAT", "W-SUN",
10247        ];
10248        match self {
10249            Self::Annual(month) => ANNUAL[(month as usize + 11) % 12],
10250            Self::Quarterly(month) => QUARTERLY[(month as usize + 11) % 12],
10251            Self::Monthly => "M",
10252            Self::Weekly(day) => WEEKLY[day as usize % 7],
10253            Self::Daily => "D",
10254            Self::Business => "B",
10255            Self::Hourly => "h",
10256            Self::Minutely => "min",
10257            Self::Secondly => "s",
10258            Self::Milliseconds => "ms",
10259            Self::Microseconds => "us",
10260            Self::Nanoseconds => "ns",
10261        }
10262    }
10263
10264    /// Resolution word for `PeriodIndex.resolution`, or `None` where pandas has
10265    /// no answer.
10266    ///
10267    /// ⚠️ THIS IS NOT THE ALIAS TABLE. pandas' `.resolution` names the period's
10268    /// *component*, in the same vocabulary `DatetimeIndex::resolution` already
10269    /// uses here -- it is not the frequency string, which is what
10270    /// [`PeriodFreq::alias`] is for. MEASURED, live pandas 2.2.3, one-element
10271    /// `PeriodIndex` per freq:
10272    ///     Y   -> 'year'        Q   -> 'quarter'     M  -> 'month'
10273    ///     D   -> 'day'         h   -> 'hour'        min-> 'minute'
10274    ///     s   -> 'second'
10275    ///     W   -> raises AttributeError
10276    ///     B   -> raises AttributeError
10277    /// Every arm below previously returned the alias instead ("A-DEC", "M", "H",
10278    /// "T", "S", ...), so all nine disagreed with the incumbent; W and B answered
10279    /// where pandas refuses. The refusal is modelled as `None` rather than a
10280    /// wrong word, because the caller already returns `Option` for the empty
10281    /// index and pandas' own failure there is an absence, not a value.
10282    #[must_use]
10283    pub const fn resolution(self) -> Option<&'static str> {
10284        match self {
10285            Self::Annual(_) => Some("year"),
10286            Self::Quarterly(_) => Some("quarter"),
10287            Self::Monthly => Some("month"),
10288            Self::Daily => Some("day"),
10289            Self::Hourly => Some("hour"),
10290            Self::Minutely => Some("minute"),
10291            Self::Secondly => Some("second"),
10292            Self::Milliseconds => Some("millisecond"),
10293            Self::Microseconds => Some("microsecond"),
10294            Self::Nanoseconds => Some("nanosecond"),
10295            // pandas' Week and BusinessDay offsets carry no `_resolution_obj`,
10296            // so `.resolution` raises AttributeError rather than answering.
10297            Self::Weekly(_) | Self::Business => None,
10298        }
10299    }
10300}
10301
10302impl std::fmt::Display for PeriodFreq {
10303    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10304        f.write_str(self.alias())
10305    }
10306}
10307
10308/// A single pandas-style Period value.
10309///
10310/// Stored as an integer ordinal on a frequency-specific axis plus the
10311/// frequency code. Two Periods with different `freq` are incompatible —
10312/// arithmetic and comparison require same-freq operands. The derived order
10313/// (ordinal, then freq) is a total one for index labels (45fzr): within one
10314/// freq it is the periods' own.
10315#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10316pub struct Period {
10317    pub ordinal: i64,
10318    pub freq: PeriodFreq,
10319}
10320
10321impl Period {
10322    #[must_use]
10323    pub const fn new(ordinal: i64, freq: PeriodFreq) -> Self {
10324        Self { ordinal, freq }
10325    }
10326
10327    /// Whether this is NaT: the missing period, ordinal `i64::MIN` (what a
10328    /// missing element of a PeriodIndex holds and what renders `NaT`).
10329    #[must_use]
10330    pub const fn is_nat(&self) -> bool {
10331        self.ordinal == i64::MIN
10332    }
10333
10334    /// Integer position on this period's frequency axis, matching
10335    /// `pd.Period.ordinal`.
10336    #[must_use]
10337    pub const fn ordinal(&self) -> i64 {
10338        self.ordinal
10339    }
10340
10341    /// Frequency code for this period, matching `pd.Period.freq`.
10342    #[must_use]
10343    pub const fn freq(&self) -> PeriodFreq {
10344        self.freq
10345    }
10346
10347    /// Canonical pandas frequency alias, matching `pd.Period.freqstr`.
10348    #[must_use]
10349    pub const fn freqstr(&self) -> &'static str {
10350        self.freq.alias()
10351    }
10352
10353    /// Same-freq ordinal comparison. Returns `None` if `freq` differs —
10354    /// caller decides whether that's an error or a panic site.
10355    #[must_use]
10356    pub fn cmp_same_freq(&self, other: &Self) -> Option<std::cmp::Ordering> {
10357        if self.freq != other.freq {
10358            return None;
10359        }
10360        Some(self.ordinal.cmp(&other.ordinal))
10361    }
10362
10363    /// Shift by `n` periods of the current frequency.
10364    /// Matches `pd.Period + n` and `pd.Period - n`.
10365    #[must_use]
10366    pub fn shift(&self, n: i64) -> Self {
10367        Self {
10368            ordinal: self.ordinal.saturating_add(n),
10369            freq: self.freq,
10370        }
10371    }
10372
10373    /// Period-difference in units of the shared frequency.
10374    /// Returns `None` if `freq` differs (pandas raises IncompatibleFrequency).
10375    #[must_use]
10376    pub fn diff(&self, other: &Self) -> Option<i64> {
10377        if self.freq != other.freq {
10378            return None;
10379        }
10380        Some(self.ordinal.saturating_sub(other.ordinal))
10381    }
10382
10383    /// Parse common pandas `Period(...)` strings and infer the frequency.
10384    ///
10385    /// Supported forms mirror pandas' unambiguous scalar constructor cases:
10386    /// annual (`"2024"`), quarterly (`"2024Q1"`), monthly (`"2024-01"`),
10387    /// and daily (`"2024-01-15"`). The ordinal axes match pandas:
10388    /// 1970, 1970Q1, 1970-01, and 1970-01-01 all have ordinal 0.
10389    pub fn parse(s: &str) -> Result<Self, TypeError> {
10390        let trimmed = s.trim();
10391        if trimmed.eq_ignore_ascii_case("nat") {
10392            return Ok(Self::new(i64::MIN, PeriodFreq::Daily));
10393        }
10394
10395        if let Some((year, quarter)) = parse_quarter_period(trimmed) {
10396            let ordinal = year
10397                .checked_sub(1970)
10398                .and_then(|offset| offset.checked_mul(4))
10399                .and_then(|base| base.checked_add(i64::from(quarter) - 1))
10400                .ok_or_else(|| TypeError::ValueNotParseable {
10401                    value: s.to_owned(),
10402                    target: "Period".to_owned(),
10403                })?;
10404            return Ok(Self::new(ordinal, PeriodFreq::QUARTERLY));
10405        }
10406
10407        if let Some((year, month, day)) = parse_ymd_period(trimmed) {
10408            let ordinal = Timestamp::days_from_ymd(year, i64::from(month), i64::from(day));
10409            return Ok(Self::new(ordinal, PeriodFreq::Daily));
10410        }
10411
10412        if let Some((year, month)) = parse_year_month_period(trimmed) {
10413            let ordinal = year
10414                .checked_sub(1970)
10415                .and_then(|offset| offset.checked_mul(12))
10416                .and_then(|base| base.checked_add(i64::from(month) - 1))
10417                .ok_or_else(|| TypeError::ValueNotParseable {
10418                    value: s.to_owned(),
10419                    target: "Period".to_owned(),
10420                })?;
10421            return Ok(Self::new(ordinal, PeriodFreq::Monthly));
10422        }
10423
10424        if let Some(year) = parse_annual_period(trimmed) {
10425            let ordinal = year
10426                .checked_sub(1970)
10427                .ok_or_else(|| TypeError::ValueNotParseable {
10428                    value: s.to_owned(),
10429                    target: "Period".to_owned(),
10430                })?;
10431            return Ok(Self::new(ordinal, PeriodFreq::ANNUAL));
10432        }
10433
10434        Err(TypeError::ValueNotParseable {
10435            value: s.to_owned(),
10436            target: "Period".to_owned(),
10437        })
10438    }
10439
10440    /// Pandas calendar string for this period, matching `str(pd.Period)`.
10441    ///
10442    /// Inverts the frequency-specific ordinal axes anchored at 1970:
10443    /// `1970`/`1970Q1`/`1970-01`/`1970-01-01`/`1970-01-01 00:00` all have
10444    /// ordinal 0. Returns `"NaT"` for the missing sentinel (`i64::MIN`).
10445    ///
10446    /// EVERY frequency is exact, Weekly and Business included.
10447    ///
10448    /// ⚠️ THOSE TWO ARE NOT INDEXED IN DAYS, which is what made them wrong until
10449    /// 08363d42f: a weekly ordinal counts WEEKS from the Monday 1969-12-22 and
10450    /// renders as the RANGE it spans (`2024-03-11/2024-03-17`), and a business
10451    /// ordinal counts BUSINESS DAYS at five per week. Both used to be handed to
10452    /// `civil_from_days`, which reads its argument as days since the epoch, so
10453    /// ordinal 2829 rendered `1977-09-30` instead of the week of 2024-03-15.
10454    ///
10455    /// The note that used to sit here called them "best-effort" and said neither
10456    /// was "reachable through the current parse/cast paths". The first half was
10457    /// a real limitation; the second was too narrow a survey. [`Self::parse`]
10458    /// indeed cannot produce them and neither can `cast_scalar` — but
10459    /// `DatetimeIndex::to_period("W")` builds them directly, and fp-index then
10460    /// renders those values through `Display` in `PeriodIndex::format`,
10461    /// `to_index`, `to_flat_index`, the `.str` accessor and the `get_loc` error
10462    /// message. The frequencies were unreachable only from the two paths the
10463    /// note happened to check.
10464    #[must_use]
10465    pub fn calendar_string(&self) -> String {
10466        let mut rendered = String::new();
10467        // `fmt::Write for String` is infallible.
10468        let _ = self.write_calendar(&mut rendered);
10469        rendered
10470    }
10471
10472    fn write_calendar(&self, rendered: &mut impl std::fmt::Write) -> std::fmt::Result {
10473        if self.ordinal == i64::MIN {
10474            return rendered.write_str("NaT");
10475        }
10476        let ord = self.ordinal;
10477        match self.freq {
10478            // An anchored year or quarter is labelled by the fiscal year its
10479            // ordinal counts (Period('2024', 'Y-JUN') ends 2024-06-30), so
10480            // the label does not depend on the anchor.
10481            PeriodFreq::Annual(_) => {
10482                let year = 1970 + ord;
10483                write!(rendered, "{year}")
10484            }
10485            PeriodFreq::Quarterly(_) => {
10486                let year = 1970 + ord.div_euclid(4);
10487                let quarter = ord.rem_euclid(4) + 1;
10488                write!(rendered, "{year}Q{quarter}")
10489            }
10490            PeriodFreq::Monthly => {
10491                let year = 1970 + ord.div_euclid(12);
10492                let month = ord.rem_euclid(12) + 1;
10493                write!(rendered, "{year:04}-{month:02}")
10494            }
10495            PeriodFreq::Daily => {
10496                let (y, m, d) = civil_from_days(ord);
10497                write!(rendered, "{y:04}-{m:02}-{d:02}")
10498            }
10499            // ⚠️ NOT DAYS SINCE THE EPOCH. A business ordinal counts BUSINESS
10500            // DAYS — five per week — so handing it to `civil_from_days` (which
10501            // wants a day count) put the label decades out: ordinal 14141 is
10502            // 2024-03-15 and rendered as 2008-09-19.
10503            //
10504            // The forward map in fp-index is
10505            //     days.div_euclid(7) * 5 + {Thu:0, Fri:1, Mon:2, Tue:3, Wed:4}
10506            // measured against pandas at every sampled date, so this is its
10507            // inverse: five ordinals per seven days, with the remainder naming a
10508            // weekday offset from the Thursday the epoch falls on.
10509            PeriodFreq::Business => {
10510                const WEEKDAY_OFFSET: [i64; 5] = [0, 1, 4, 5, 6];
10511                // Euclidean, so a pre-epoch ordinal keeps a remainder in 0..5:
10512                // ordinal -1 is 1969-12-31, not a negative weekday index.
10513                let offset = WEEKDAY_OFFSET[ord.rem_euclid(5) as usize];
10514                let days = ord.div_euclid(5).saturating_mul(7).saturating_add(offset);
10515                let (y, m, d) = civil_from_days(days);
10516                write!(rendered, "{y:04}-{m:02}-{d:02}")
10517            }
10518            // ⚠️ TWO BUGS IN ONE ARM. A weekly ordinal counts WEEKS from the
10519            // Monday 1969-12-22 (ten days before the epoch), and pandas renders a
10520            // weekly period as the RANGE it spans, not as one date:
10521            //     Period('2024-03-15', 'W') -> '2024-03-11/2024-03-17'
10522            // ordinal 2829, which this arm rendered as '1977-09-30'.
10523            //
10524            // fp-frame's `format_period_label` already produced the range form
10525            // for the same freq, so the two renderers disagreed on every weekly
10526            // period; this makes them agree.
10527            PeriodFreq::Weekly(_) => {
10528                // Days-since-epoch of the anchor Monday 1969-12-22; a week
10529                // ending on another weekday starts that many days later
10530                // (W-MON weeks run Tuesday..Monday).
10531                const WEEK_ANCHOR_DAY: i64 = -10;
10532                let start = ord
10533                    .saturating_mul(7)
10534                    .saturating_add(WEEK_ANCHOR_DAY + self.freq.week_start_shift());
10535                let (sy, sm, sd) = civil_from_days(start);
10536                let (ey, em, ed) = civil_from_days(start.saturating_add(6));
10537                write!(rendered, "{sy:04}-{sm:02}-{sd:02}/{ey:04}-{em:02}-{ed:02}")
10538            }
10539            PeriodFreq::Hourly => {
10540                let (y, m, d) = civil_from_days(ord.div_euclid(24));
10541                let hour = ord.rem_euclid(24);
10542                write!(rendered, "{y:04}-{m:02}-{d:02} {hour:02}:00")
10543            }
10544            PeriodFreq::Minutely => {
10545                let day = ord.div_euclid(1440);
10546                let mins = ord.rem_euclid(1440);
10547                let (y, m, d) = civil_from_days(day);
10548                write!(
10549                    rendered,
10550                    "{y:04}-{m:02}-{d:02} {:02}:{:02}",
10551                    mins / 60,
10552                    mins % 60
10553                )
10554            }
10555            PeriodFreq::Secondly => {
10556                let day = ord.div_euclid(86_400);
10557                let secs = ord.rem_euclid(86_400);
10558                let (y, m, d) = civil_from_days(day);
10559                write!(
10560                    rendered,
10561                    "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}",
10562                    secs / 3600,
10563                    (secs % 3600) / 60,
10564                    secs % 60
10565                )
10566            }
10567            // The three sub-second frequencies differ only in the divisor and
10568            // the FIXED fraction width -- pandas pads to the full width and
10569            // never trims trailing zeros. MEASURED on 2024-03-15 10:30:45.123456789:
10570            //     ms -> "2024-03-15 10:30:45.123"
10571            //     us -> "2024-03-15 10:30:45.123456"
10572            //     ns -> "2024-03-15 10:30:45.123456789"
10573            PeriodFreq::Milliseconds | PeriodFreq::Microseconds | PeriodFreq::Nanoseconds => {
10574                let (per_sec, width) = match self.freq {
10575                    PeriodFreq::Milliseconds => (1_000_i64, 3_usize),
10576                    PeriodFreq::Microseconds => (1_000_000_i64, 6_usize),
10577                    _ => (1_000_000_000_i64, 9_usize),
10578                };
10579                // 86_400 * 1e9 = 8.64e13 -- the widest of these is well inside i64.
10580                let per_day = 86_400 * per_sec;
10581                let day = ord.div_euclid(per_day);
10582                let rest = ord.rem_euclid(per_day);
10583                let secs = rest / per_sec;
10584                let frac = rest % per_sec;
10585                let (y, m, d) = civil_from_days(day);
10586                write!(
10587                    rendered,
10588                    "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}.{:0width$}",
10589                    secs / 3600,
10590                    (secs % 3600) / 60,
10591                    secs % 60,
10592                    frac,
10593                    width = width
10594                )
10595            }
10596        }
10597    }
10598}
10599
10600/// Convert a day count (days since 1970-01-01) to a proleptic-Gregorian
10601/// `(year, month, day)`, using Howard Hinnant's civil-from-days algorithm
10602/// (same kernel as `Timestamp::isoformat`).
10603fn civil_from_days(days_since_epoch: i64) -> (i64, u32, u32) {
10604    let days = days_since_epoch + 719_468;
10605    let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
10606    let doe = days - era * 146_097;
10607    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
10608    let y = yoe + era * 400;
10609    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
10610    let mp = (5 * doy + 2) / 153;
10611    let d = doy - (153 * mp + 2) / 5 + 1;
10612    let m = if mp < 10 { mp + 3 } else { mp - 9 };
10613    let year = if m <= 2 { y + 1 } else { y };
10614    (year, m as u32, d as u32)
10615}
10616
10617fn parse_annual_period(value: &str) -> Option<i64> {
10618    (value.len() == 4 && value.chars().all(|ch| ch.is_ascii_digit()))
10619        .then(|| value.parse::<i64>().ok())
10620        .flatten()
10621}
10622
10623fn parse_year_month_period(value: &str) -> Option<(i64, u32)> {
10624    let (year, month) = value.split_once('-')?;
10625    if year.len() != 4 || month.len() != 2 {
10626        return None;
10627    }
10628    let year = year.parse::<i64>().ok()?;
10629    let month = month.parse::<u32>().ok()?;
10630    (1..=12).contains(&month).then_some((year, month))
10631}
10632
10633fn parse_ymd_period(value: &str) -> Option<(i64, u32, u32)> {
10634    let mut parts = value.split('-');
10635    let year = parts.next()?;
10636    let month = parts.next()?;
10637    let day = parts.next()?;
10638    if parts.next().is_some() || year.len() != 4 || month.len() != 2 || day.len() != 2 {
10639        return None;
10640    }
10641    let year = year.parse::<i64>().ok()?;
10642    let month = month.parse::<u32>().ok()?;
10643    let day = day.parse::<u32>().ok()?;
10644    (1..=days_in_month(year, month)?)
10645        .contains(&day)
10646        .then_some((year, month, day))
10647}
10648
10649fn parse_quarter_period(value: &str) -> Option<(i64, u32)> {
10650    let (year, quarter) = value.split_once('Q').or_else(|| value.split_once('q'))?;
10651    if year.len() != 4 || quarter.len() != 1 {
10652        return None;
10653    }
10654    let year = year.parse::<i64>().ok()?;
10655    let quarter = quarter.parse::<u32>().ok()?;
10656    (1..=4).contains(&quarter).then_some((year, quarter))
10657}
10658
10659impl std::fmt::Display for Period {
10660    /// Pandas `str(Period)` form: the calendar string (`2024`, `2024Q1`,
10661    /// `2024-03`, `2024-01-15`, ...). NaT (ordinal `i64::MIN`) renders `NaT`.
10662    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10663        self.write_calendar(f)
10664    }
10665}
10666
10667/// Build `periods` consecutive Periods starting at `start`.
10668///
10669/// Matches `pd.period_range(start, periods=N, freq=start.freq)` for the
10670/// count-based form. The frequency is taken from `start` — pandas requires
10671/// `freq` to match when both are passed; mismatches are an error in
10672/// pandas, but here we sidestep ambiguity by deriving from `start.freq`.
10673///
10674/// Per br-frankenpandas-2jef (epoj Phase 2). Pure ordinal arithmetic — no
10675/// calendar conversion (Phase 3 wires chrono). `periods=0` returns empty.
10676///
10677/// ```
10678/// use fp_types::{period_range, Period, PeriodFreq};
10679/// let q1 = Period::new(216, PeriodFreq::QUARTERLY);
10680/// let year = period_range(q1, 4);
10681/// assert_eq!(year.len(), 4);
10682/// assert_eq!(year[0].ordinal, 216);
10683/// assert_eq!(year[3].ordinal, 219);
10684/// ```
10685#[must_use]
10686pub fn period_range(start: Period, periods: usize) -> Vec<Period> {
10687    (0..periods).map(|i| start.shift(i as i64)).collect()
10688}
10689
10690#[cfg(test)]
10691mod tests {
10692    use super::{
10693        DType, Interval, IntervalClosed, NullKind, Period, PeriodFreq, Scalar, SparseDType,
10694        cast_scalar, common_dtype, infer_dtype,
10695    };
10696
10697    /// A host value for the tests: a named thing, equal by name, unhashable
10698    /// when the name is empty.
10699    struct Named(&'static str);
10700
10701    impl super::HostObject for Named {
10702        fn host_eq(&self, other: &dyn super::HostObject) -> bool {
10703            other
10704                .as_any()
10705                .downcast_ref::<Named>()
10706                .is_some_and(|other| other.0 == self.0)
10707        }
10708        fn host_repr(&self) -> String {
10709            format!("Named({:?})", self.0)
10710        }
10711        fn host_str(&self) -> String {
10712            self.0.to_owned()
10713        }
10714        fn host_hash(&self) -> Option<u64> {
10715            (!self.0.is_empty()).then_some(self.0.len() as u64)
10716        }
10717        // Names starting with '!' cannot be ordered (as a date against a time).
10718        fn host_cmp(&self, other: &dyn super::HostObject) -> Option<std::cmp::Ordering> {
10719            let other = other.as_any().downcast_ref::<Named>()?;
10720            (!self.0.starts_with('!') && !other.0.starts_with('!')).then(|| self.0.cmp(other.0))
10721        }
10722        fn as_any(&self) -> &dyn std::any::Any {
10723            self
10724        }
10725    }
10726
10727    #[test]
10728    fn host_values_block_workers_only_under_a_declared_host_lock_4qg5w_13() {
10729        use std::sync::atomic::Ordering;
10730
10731        use super::{HostValue, LIVE_HOST_VALUES, workers_blocked};
10732        // The rule: inline only when a host lock may be held AND a host value
10733        // is alive. NEGATIVE: without a declared lock (pure Rust callers, this
10734        // test process) nothing is blocked however many host values live.
10735        assert!(workers_blocked(true, 1));
10736        assert!(!workers_blocked(true, 0));
10737        assert!(!workers_blocked(false, 3));
10738        // The count: non-zero while a handle is held, clones included (other
10739        // tests may hold host values concurrently, so only "alive while held"
10740        // is asserted, never "dead after drop"; the lock is never declared
10741        // here, so no concurrent test loses its workers).
10742        let first = HostValue::new(Named("held"));
10743        assert!(LIVE_HOST_VALUES.load(Ordering::Relaxed) > 0);
10744        let clone = first.clone();
10745        drop(first);
10746        assert!(LIVE_HOST_VALUES.load(Ordering::Relaxed) > 0);
10747        assert_eq!(clone.object().host_str(), "held");
10748    }
10749
10750    #[test]
10751    fn object_cells_order_like_python_then_totally_fvsao_66() {
10752        use std::cmp::Ordering;
10753
10754        use super::{HostValue, ObjectValue};
10755        let host = |name: &'static str| ObjectValue::Host(HostValue::new(Named(name)));
10756        let list = |items: Vec<Scalar>| ObjectValue::list(items);
10757        // Host values order as the host orders them (a date before a later
10758        // date), not by their reprs.
10759        assert_eq!(host("a").python_cmp(&host("b")), Some(Ordering::Less));
10760        assert!(host("b") > host("a"));
10761        assert_eq!(host("a").cmp(&host("a")), Ordering::Equal);
10762        // Lists item by item, numbers by value (1 < 10, where the reprs sort
10763        // "10" first), a shorter prefix first.
10764        let one_ten = list(vec![Scalar::Int64(1), Scalar::Int64(10)]);
10765        let one_two = list(vec![Scalar::Int64(1), Scalar::Int64(2)]);
10766        assert_eq!(one_two.python_cmp(&one_ten), Some(Ordering::Less));
10767        assert!(list(vec![Scalar::Int64(1)]) < one_two);
10768        // Python's 1 == 1.0: an equal item pair is skipped, not the answer.
10769        let mixed = list(vec![Scalar::Float64(1.0), Scalar::Int64(3)]);
10770        assert_eq!(one_two.python_cmp(&mixed), Some(Ordering::Less));
10771        // Where Python raises there is no python_cmp, but the total order
10772        // still separates the cells: a list before a host value, then reprs.
10773        assert_eq!(one_two.python_cmp(&host("a")), None);
10774        assert!(one_two < host("a"));
10775        assert_eq!(host("!z").python_cmp(&host("!a")), None);
10776        assert!(host("!a") < host("!z"));
10777        let text = list(vec![Scalar::Utf8("a".to_owned())]);
10778        assert_eq!(one_two.python_cmp(&text), None);
10779        assert_ne!(one_two.cmp(&text), Ordering::Equal);
10780        // NEGATIVE: unequal cells that print alike are never Equal (NaN is not
10781        // equal to itself), so an ordered map cannot merge them.
10782        let nan = || list(vec![Scalar::Float64(f64::NAN)]);
10783        let (first, second) = (nan(), nan());
10784        assert_ne!(first, second);
10785        assert_ne!(first.cmp(&second), Ordering::Equal);
10786        assert_eq!(first.cmp(&second), second.cmp(&first).reverse());
10787    }
10788
10789    #[test]
10790    fn bytes_cells_print_order_and_serialize_like_python_bytes_4qg5w_8() {
10791        use std::cmp::Ordering;
10792
10793        use super::ObjectValue;
10794        let bytes = |data: &[u8]| Scalar::Object(ObjectValue::bytes(data.to_vec()));
10795        // Python's repr: single quotes unless the bytes hold a ' and no ",
10796        // \xNN for the unprintable, \\ \t \n \r escaped.
10797        assert_eq!(bytes(b"ab").python_repr(), "b'ab'");
10798        assert_eq!(bytes(b"a'b").python_repr(), "b\"a'b\"");
10799        assert_eq!(bytes(b"a'\"").python_repr(), "b'a\\'\"'");
10800        assert_eq!(bytes(b"\x00\t\\\xff").python_repr(), "b'\\x00\\t\\\\\\xff'");
10801        assert_eq!(bytes(b"ab").python_type_name(), "bytes");
10802        // Ordered byte by byte, a prefix first; never equal to a str.
10803        assert_eq!(bytes(b"ab").python_cmp(&bytes(b"b")), Some(Ordering::Less));
10804        assert_eq!(bytes(b"a").python_cmp(&bytes(b"ab")), Some(Ordering::Less));
10805        assert_eq!(bytes(b"a").python_cmp(&Scalar::Utf8("a".to_owned())), None);
10806        assert_ne!(bytes(b"a"), Scalar::Utf8("a".to_owned()));
10807        assert!(!bytes(b"").to_bool().unwrap());
10808        // The serde form the conformance fixtures carry, both ways.
10809        let json = serde_json::to_string(&bytes(b"hi")).unwrap();
10810        assert_eq!(json, r#"{"kind":"object","value":{"bytes":[104,105]}}"#);
10811        let back: Scalar = serde_json::from_str(&json).unwrap();
10812        assert_eq!(back, bytes(b"hi"));
10813        // NEGATIVE: a list cell still (de)serializes as its items.
10814        let list: Scalar =
10815            serde_json::from_str(r#"{"kind":"object","value":[{"kind":"int64","value":1}]}"#)
10816                .unwrap();
10817        assert_eq!(
10818            list,
10819            Scalar::Object(ObjectValue::list(vec![Scalar::Int64(1)]))
10820        );
10821    }
10822
10823    #[test]
10824    fn values_order_and_name_their_types_as_python_does_fvsao_71() {
10825        use std::cmp::Ordering;
10826
10827        use super::{HostValue, ObjectValue};
10828        let text = |value: &str| Scalar::Utf8(value.to_owned());
10829        let host =
10830            |name: &'static str| Scalar::Object(ObjectValue::Host(HostValue::new(Named(name))));
10831        let list = |items: Vec<Scalar>| Scalar::Object(ObjectValue::list(items));
10832        // Numbers across kinds by value, text by code point, instants,
10833        // intervals by (left, right), cells as the host orders them.
10834        assert_eq!(
10835            Scalar::Bool(true).python_cmp(&Scalar::Float64(1.5)),
10836            Some(Ordering::Less)
10837        );
10838        assert_eq!(
10839            Scalar::Int64(2).python_cmp(&Scalar::Float64(2.0)),
10840            Some(Ordering::Equal)
10841        );
10842        assert_eq!(text("b").python_cmp(&text("a")), Some(Ordering::Greater));
10843        assert_eq!(
10844            Scalar::Datetime64(5).python_cmp(&Scalar::Datetime64(9)),
10845            Some(Ordering::Less)
10846        );
10847        let interval = |left: f64, right: f64| {
10848            Scalar::Interval(Interval::new(left, right, IntervalClosed::Right))
10849        };
10850        assert_eq!(
10851            interval(0.0, 5.0).python_cmp(&interval(0.0, 2.0)),
10852            Some(Ordering::Greater)
10853        );
10854        assert_eq!(host("a").python_cmp(&host("b")), Some(Ordering::Less));
10855        // NEGATIVES: what Python cannot order - a str and an int, an instant
10856        // and a duration, a cell and a number, unorderable host values.
10857        assert_eq!(text("a").python_cmp(&Scalar::Int64(1)), None);
10858        assert_eq!(
10859            Scalar::Datetime64(1).python_cmp(&Scalar::Timedelta64(1)),
10860            None
10861        );
10862        assert_eq!(host("a").python_cmp(&Scalar::Int64(1)), None);
10863        assert_eq!(host("!a").python_cmp(&host("b")), None);
10864        // Their types as Python's TypeError names them; a host value by its
10865        // host (the default for a host that cannot say is 'object'), a list
10866        // pair by the first unequal items it holds.
10867        assert_eq!(text("a").python_type_name(), "str");
10868        assert_eq!(Scalar::Bool(true).python_type_name(), "bool");
10869        assert_eq!(Scalar::Datetime64(1).python_type_name(), "Timestamp");
10870        assert_eq!(list(vec![]).python_type_name(), "list");
10871        assert_eq!(host("a").python_type_name(), "object");
10872        let (left, right) = list(vec![Scalar::Int64(1), Scalar::Int64(2)])
10873            .python_cmp_type_names(&list(vec![Scalar::Int64(1), text("x")]));
10874        assert_eq!((left.as_str(), right.as_str()), ("int", "str"));
10875        let (left, right) = text("a").python_cmp_type_names(&list(vec![]));
10876        assert_eq!((left.as_str(), right.as_str()), ("str", "list"));
10877    }
10878
10879    #[test]
10880    fn object_cells_print_compare_and_hash_like_python_fvsao_33() {
10881        use std::hash::{Hash, Hasher};
10882
10883        use super::{HostValue, ObjectValue};
10884        let hash = |value: &ObjectValue| {
10885            let mut hasher = std::collections::hash_map::DefaultHasher::new();
10886            value.hash(&mut hasher);
10887            hasher.finish()
10888        };
10889        let list = ObjectValue::list(vec![
10890            Scalar::Int64(1),
10891            Scalar::Utf8("a".to_owned()),
10892            Scalar::Null(NullKind::Null),
10893            Scalar::Float64(2.0),
10894            Scalar::Object(ObjectValue::list(vec![Scalar::Utf8("b".to_owned())])),
10895        ]);
10896        // repr / str (astype(str), writers) quote strings; pandas' display
10897        // (pprint) does not.
10898        assert_eq!(list.repr(), "[1, 'a', None, 2.0, ['b']]");
10899        assert_eq!(list.to_string(), "[1, 'a', None, 2.0, ['b']]");
10900        assert_eq!(list.pprint(), "[1, a, None, 2.0, [b]]");
10901        // An object cell is object data (pandas' object dtype, Utf8 here).
10902        assert_eq!(Scalar::Object(list.clone()).dtype(), DType::Utf8);
10903        assert!(!Scalar::Object(list.clone()).is_missing());
10904        // Equal lists are equal and hash alike; a different item is not
10905        // equal; a list never equals a host value.
10906        let same = ObjectValue::list(list.as_list().unwrap().to_vec());
10907        assert_eq!(list, same);
10908        assert_eq!(hash(&list), hash(&same));
10909        let other = ObjectValue::list(vec![Scalar::Int64(1)]);
10910        assert_ne!(list, other);
10911        let host = ObjectValue::Host(HostValue::new(Named("x")));
10912        assert_ne!(list, host);
10913        // Host values compare and print through the host.
10914        assert_eq!(host, ObjectValue::Host(HostValue::new(Named("x"))));
10915        assert_ne!(host, ObjectValue::Host(HostValue::new(Named("y"))));
10916        assert_eq!(host.repr(), "Named(\"x\")");
10917        assert_eq!(host.to_string(), "x");
10918        // Python truth: an empty list is false, a host value true.
10919        assert!(
10920            !Scalar::Object(ObjectValue::list(Vec::new()))
10921                .to_bool()
10922                .unwrap()
10923        );
10924        assert!(Scalar::Object(host.clone()).to_bool().unwrap());
10925        // A list is not a number.
10926        assert!(Scalar::Object(list.clone()).to_f64().is_err());
10927        // A list cell serializes as its items and reads back; a host value
10928        // refuses to serialize.
10929        let json = serde_json::to_string(&Scalar::Object(other.clone())).unwrap();
10930        assert_eq!(
10931            serde_json::from_str::<Scalar>(&json).unwrap(),
10932            Scalar::Object(other)
10933        );
10934        assert!(serde_json::to_string(&Scalar::Object(host)).is_err());
10935    }
10936
10937    #[test]
10938    fn a_host_cell_displays_by_its_pprint_and_stringifies_by_its_str() {
10939        use super::{HostValue, ObjectValue};
10940
10941        /// A host tuple: Python's str quotes its items, pandas' display not.
10942        struct Pair;
10943        impl super::HostObject for Pair {
10944            fn host_eq(&self, _other: &dyn super::HostObject) -> bool {
10945                false
10946            }
10947            fn host_repr(&self) -> String {
10948                "('a', 1)".to_owned()
10949            }
10950            fn host_str(&self) -> String {
10951                "('a', 1)".to_owned()
10952            }
10953            fn host_pprint(&self) -> String {
10954                "(a, 1)".to_owned()
10955            }
10956            fn host_hash(&self) -> Option<u64> {
10957                None
10958            }
10959            fn host_cmp(&self, _other: &dyn super::HostObject) -> Option<std::cmp::Ordering> {
10960                None
10961            }
10962            fn as_any(&self) -> &dyn std::any::Any {
10963                self
10964            }
10965        }
10966        let pair = ObjectValue::Host(HostValue::new(Pair));
10967        assert_eq!(pair.pprint(), "(a, 1)");
10968        // Inside a list cell too.
10969        let list = ObjectValue::list(vec![Scalar::Object(pair.clone())]);
10970        assert_eq!(list.pprint(), "[(a, 1)]");
10971        // NEGATIVE: str (astype(str), writers) stays the host's str.
10972        assert_eq!(pair.to_string(), "('a', 1)");
10973        // NEGATIVE: a host without its own pprint displays by its str.
10974        let named = ObjectValue::Host(HostValue::new(Named("x")));
10975        assert_eq!(named.pprint(), "x");
10976    }
10977
10978    #[test]
10979    fn float64_json_spells_infinity_and_round_trips() {
10980        // br-frankenpandas-rc0923-epic-rust-parity-bugs-4qg5w.3: serde_json
10981        // wrote +-inf as `null` and could not read it back, so pandas'
10982        // division-by-zero answers could not reach a fixture.
10983        let json = |s: &Scalar| serde_json::to_string(s).expect("serialize");
10984        let back = |text: &str| serde_json::from_str::<Scalar>(text);
10985        assert_eq!(
10986            json(&Scalar::Float64(f64::INFINITY)),
10987            r#"{"kind":"float64","value":"inf"}"#
10988        );
10989        assert_eq!(
10990            json(&Scalar::Float64(f64::NEG_INFINITY)),
10991            r#"{"kind":"float64","value":"-inf"}"#
10992        );
10993        // Unchanged spellings: finite numbers, -0.0, and NaN as null.
10994        assert_eq!(
10995            json(&Scalar::Float64(1.5)),
10996            r#"{"kind":"float64","value":1.5}"#
10997        );
10998        assert_eq!(
10999            json(&Scalar::Float64(-0.0)),
11000            r#"{"kind":"float64","value":-0.0}"#
11001        );
11002        assert_eq!(
11003            json(&Scalar::Float64(f64::NAN)),
11004            r#"{"kind":"float64","value":null}"#
11005        );
11006        for value in [f64::INFINITY, f64::NEG_INFINITY, 1.5, -2.25e300] {
11007            let scalar = Scalar::Float64(value);
11008            assert_eq!(back(&json(&scalar)).expect("round trip"), scalar);
11009        }
11010        let negative_zero = back(r#"{"kind":"float64","value":-0.0}"#).expect("-0.0");
11011        assert!(matches!(negative_zero, Scalar::Float64(v) if v == 0.0 && v.is_sign_negative()));
11012        assert!(matches!(
11013            back(r#"{"kind":"float64","value":null}"#).expect("null"),
11014            Scalar::Float64(v) if v.is_nan()
11015        ));
11016        // Anything else is an error, not a silent NaN.
11017        assert!(back(r#"{"kind":"float64","value":"Infinity"}"#).is_err());
11018        assert!(back(r#"{"kind":"float64","value":"1.5"}"#).is_err());
11019    }
11020
11021    /// br-frankenpandas-ay8o9: Scalar::semantic_cmp underpins ALL ordering in
11022    /// the library (sort, min/max, is_monotonic, searchsorted, groupby key
11023    /// order) and is the reference the differential harnesses rely on. Property
11024    /// test of its total-order axioms over finite/non-NaT same-dtype scalars,
11025    /// plus the intentional NaN degeneracy. Deterministic seeded LCG — no rand
11026    /// crate, no mocks.
11027    /// br-frankenpandas-767ak: extends ay8o9's NaN pinning to the temporal NAT
11028    /// sentinels (i64::MIN). semantic_cmp treats NAT as degenerate (Equal to all
11029    /// same-dtype), which is why temporal ordering ops must treat NAT as missing.
11030    #[test]
11031    fn semantic_cmp_cross_numeric_int_float_cdpai() {
11032        // Property (br-frankenpandas-cdpai): semantic_cmp compares Int64 vs Float64
11033        // as f64, antisymmetric across the operand order. Seeded LCG, no mocks.
11034        use std::cmp::Ordering;
11035        let mut st: u64 = 0xc205_a1b2_c3d4_e5f6;
11036        let mut next = || {
11037            st = st
11038                .wrapping_mul(6_364_136_223_846_793_005)
11039                .wrapping_add(1_442_695_040_888_963_407);
11040            (st >> 33) as u32
11041        };
11042        for _ in 0..3000u32 {
11043            let i = (next() % 21) as i64 - 10;
11044            let f = (next() % 400) as f64 / 20.0 - 10.0; // finite
11045            let exp = (i as f64).partial_cmp(&f).unwrap();
11046            assert_eq!(Scalar::Int64(i).semantic_cmp(&Scalar::Float64(f)), exp);
11047            assert_eq!(
11048                Scalar::Float64(f).semantic_cmp(&Scalar::Int64(i)),
11049                exp.reverse()
11050            );
11051        }
11052        // Exact int/float equality compares Equal in both directions.
11053        assert_eq!(
11054            Scalar::Int64(5).semantic_cmp(&Scalar::Float64(5.0)),
11055            Ordering::Equal
11056        );
11057        assert_eq!(
11058            Scalar::Float64(5.0).semantic_cmp(&Scalar::Int64(5)),
11059            Ordering::Equal
11060        );
11061        assert_eq!(
11062            Scalar::Int64(3).semantic_cmp(&Scalar::Float64(3.5)),
11063            Ordering::Less
11064        );
11065        assert_eq!(
11066            Scalar::Int64(4).semantic_cmp(&Scalar::Float64(3.5)),
11067            Ordering::Greater
11068        );
11069    }
11070
11071    #[test]
11072    fn semantic_cmp_nat_degeneracy_temporal_767ak() {
11073        use std::cmp::Ordering;
11074        const NAT: i64 = i64::MIN;
11075
11076        // Timedelta64 NAT is degenerate (Equal to finite and to itself).
11077        let td_nat = Scalar::Timedelta64(NAT);
11078        for v in [-3i64, 0, 5, 99] {
11079            let td = Scalar::Timedelta64(v);
11080            assert_eq!(td_nat.semantic_cmp(&td), Ordering::Equal, "td NAT vs {v}");
11081            assert_eq!(td.semantic_cmp(&td_nat), Ordering::Equal, "td {v} vs NAT");
11082        }
11083        assert_eq!(td_nat.semantic_cmp(&td_nat), Ordering::Equal);
11084
11085        // Datetime64 NAT likewise.
11086        let dt_nat = Scalar::Datetime64(NAT);
11087        for v in [-3i64, 0, 5, 99] {
11088            let dt = Scalar::Datetime64(v);
11089            assert_eq!(dt_nat.semantic_cmp(&dt), Ordering::Equal, "dt NAT vs {v}");
11090            assert_eq!(dt.semantic_cmp(&dt_nat), Ordering::Equal, "dt {v} vs NAT");
11091        }
11092        assert_eq!(dt_nat.semantic_cmp(&dt_nat), Ordering::Equal);
11093
11094        // Non-NAT temporal values order normally (reflexive, antisymmetric, lt).
11095        for (a, b) in [(1i64, 2i64), (5, 5), (9, -1)] {
11096            let (ta, tb) = (Scalar::Timedelta64(a), Scalar::Timedelta64(b));
11097            assert_eq!(ta.semantic_cmp(&ta), Ordering::Equal);
11098            assert_eq!(ta.semantic_cmp(&tb), b.cmp(&a).reverse()); // a.cmp(b)
11099            assert_eq!(ta.semantic_cmp(&tb), a.cmp(&b));
11100            let (da, db) = (Scalar::Datetime64(a), Scalar::Datetime64(b));
11101            assert_eq!(da.semantic_cmp(&db), a.cmp(&b));
11102        }
11103    }
11104
11105    fn semantic_cmp_cross_variant_values_d5ikg() -> [Scalar; 9] {
11106        [
11107            Scalar::Null(NullKind::Null),
11108            Scalar::Bool(true),
11109            Scalar::Int64(-7),
11110            Scalar::Float64(3.5),
11111            Scalar::Utf8("mixed".to_owned()),
11112            Scalar::Timedelta64(11),
11113            Scalar::Datetime64(1_735_732_800_123_456_789),
11114            Scalar::Period(Period::new(649, PeriodFreq::Monthly)),
11115            Scalar::Interval(Interval::new(-1.5, 2.5, IntervalClosed::Right)),
11116        ]
11117    }
11118
11119    fn semantic_cmp_uses_debug_fallback_d5ikg(left: &Scalar, right: &Scalar) -> bool {
11120        !matches!(
11121            (left, right),
11122            (Scalar::Int64(_), Scalar::Float64(_)) | (Scalar::Float64(_), Scalar::Int64(_))
11123        )
11124    }
11125
11126    #[test]
11127    fn semantic_cmp_cross_variant_matches_debug_order_d5ikg() {
11128        let values = semantic_cmp_cross_variant_values_d5ikg();
11129        for (left_index, left) in values.iter().enumerate() {
11130            for (right_index, right) in values.iter().enumerate() {
11131                if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
11132                {
11133                    assert_eq!(
11134                        left.semantic_cmp(right),
11135                        format!("{left:?}").cmp(&format!("{right:?}")),
11136                        "cross-variant order mismatch: {left:?} vs {right:?}"
11137                    );
11138                }
11139            }
11140        }
11141    }
11142
11143    #[test]
11144    #[ignore = "foreground release attribution harness"]
11145    fn semantic_cmp_cross_variant_debug_alloc_ab_d5ikg() {
11146        use std::cmp::Ordering;
11147
11148        const BATCH: usize = 4_096;
11149        const BLOCKS: usize = 9;
11150
11151        fn former(left: &Scalar, right: &Scalar) -> Ordering {
11152            format!("{left:?}").cmp(&format!("{right:?}"))
11153        }
11154
11155        fn candidate(left: &Scalar, right: &Scalar) -> Ordering {
11156            left.semantic_cmp(right)
11157        }
11158
11159        fn elapsed(values: &[Scalar], compare: fn(&Scalar, &Scalar) -> Ordering) -> u128 {
11160            let mut less = 0usize;
11161            let started = std::time::Instant::now();
11162            for _ in 0..BATCH {
11163                for (left_index, left) in values.iter().enumerate() {
11164                    for (right_index, right) in values.iter().enumerate() {
11165                        if left_index != right_index
11166                            && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
11167                            && compare(std::hint::black_box(left), std::hint::black_box(right))
11168                                == Ordering::Less
11169                        {
11170                            less += 1;
11171                        }
11172                    }
11173                }
11174            }
11175            std::hint::black_box(less);
11176            started.elapsed().as_nanos()
11177        }
11178
11179        fn median(samples: &mut [u128]) -> u128 {
11180            samples.sort_unstable();
11181            samples[samples.len() / 2]
11182        }
11183
11184        let values = semantic_cmp_cross_variant_values_d5ikg();
11185
11186        for (left_index, left) in values.iter().enumerate() {
11187            for (right_index, right) in values.iter().enumerate() {
11188                if left_index != right_index && semantic_cmp_uses_debug_fallback_d5ikg(left, right)
11189                {
11190                    assert_eq!(
11191                        former(left, right),
11192                        candidate(left, right),
11193                        "cross-variant order mismatch: {left:?} vs {right:?}"
11194                    );
11195                }
11196            }
11197        }
11198
11199        std::hint::black_box(elapsed(&values, former));
11200        std::hint::black_box(elapsed(&values, candidate));
11201
11202        let mut former_samples = Vec::with_capacity(BLOCKS * 2);
11203        let mut candidate_samples = Vec::with_capacity(BLOCKS * 2);
11204        for block in 0..BLOCKS {
11205            if block.is_multiple_of(2) {
11206                former_samples.push(elapsed(&values, former));
11207                candidate_samples.push(elapsed(&values, candidate));
11208                candidate_samples.push(elapsed(&values, candidate));
11209                former_samples.push(elapsed(&values, former));
11210            } else {
11211                candidate_samples.push(elapsed(&values, candidate));
11212                former_samples.push(elapsed(&values, former));
11213                former_samples.push(elapsed(&values, former));
11214                candidate_samples.push(elapsed(&values, candidate));
11215            }
11216        }
11217
11218        let former_p50 = median(&mut former_samples);
11219        let candidate_p50 = median(&mut candidate_samples);
11220        eprintln!(
11221            "semantic_cmp_cross_variant_debug_alloc former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} speedup={:.6}",
11222            former_p50 as f64 / candidate_p50 as f64
11223        );
11224    }
11225
11226    #[test]
11227    fn semantic_cmp_total_order_axioms_ay8o9() {
11228        use std::cmp::Ordering;
11229
11230        let mut state: u64 = 0xc0ff_eeba_df00_d123;
11231        let mut next = || {
11232            state = state
11233                .wrapping_mul(6_364_136_223_846_793_005)
11234                .wrapping_add(1_442_695_040_888_963_407);
11235            (state >> 33) as u32
11236        };
11237
11238        for iter in 0..6000u32 {
11239            let dt = next() % 4;
11240            // Build a same-dtype, finite, non-NaT scalar from a random u32.
11241            let mk = |r: u32| match dt {
11242                0 => Scalar::Int64((r % 11) as i64 - 5),
11243                // finite, in -5.0..=5.0 by 0.5 — no NaN/inf.
11244                1 => Scalar::Float64(f64::from((r % 21) as i32 - 10) / 2.0),
11245                2 => Scalar::Utf8(format!("s{}", r % 5)),
11246                _ => Scalar::Bool(r.is_multiple_of(2)),
11247            };
11248            let a = mk(next());
11249            let b = mk(next());
11250            let c = mk(next());
11251            let ctx = format!("iter={iter} a={a:?} b={b:?} c={c:?}");
11252
11253            // Reflexivity.
11254            assert_eq!(a.semantic_cmp(&a), Ordering::Equal, "reflexive {ctx}");
11255            // Antisymmetry.
11256            assert_eq!(
11257                a.semantic_cmp(&b),
11258                b.semantic_cmp(&a).reverse(),
11259                "antisymmetric {ctx}"
11260            );
11261            // le / ge / eq consistency with the ordering.
11262            let ab = a.semantic_cmp(&b);
11263            assert_eq!(
11264                a.semantic_le(&b),
11265                ab != Ordering::Greater,
11266                "le-consistent {ctx}"
11267            );
11268            assert_eq!(
11269                a.semantic_ge(&b),
11270                ab != Ordering::Less,
11271                "ge-consistent {ctx}"
11272            );
11273            assert_eq!(
11274                a.semantic_le(&b) && a.semantic_ge(&b),
11275                ab == Ordering::Equal,
11276                "le&ge<=>eq {ctx}"
11277            );
11278            // Transitivity: a<=b && b<=c  =>  a<=c.
11279            if a.semantic_cmp(&b) != Ordering::Greater && b.semantic_cmp(&c) != Ordering::Greater {
11280                assert_ne!(a.semantic_cmp(&c), Ordering::Greater, "transitivity {ctx}");
11281            }
11282        }
11283
11284        // Pin the intentional NaN degeneracy: a Float64 NaN compares Equal to
11285        // every finite Float64 (and to itself) — this is why ordering ops must
11286        // treat NaN as missing rather than relying on semantic_cmp to order it.
11287        let nan = Scalar::Float64(f64::NAN);
11288        for v in [
11289            Scalar::Float64(-3.5),
11290            Scalar::Float64(0.0),
11291            Scalar::Float64(7.25),
11292        ] {
11293            assert_eq!(nan.semantic_cmp(&v), Ordering::Equal, "NaN cmp finite");
11294            assert_eq!(v.semantic_cmp(&nan), Ordering::Equal, "finite cmp NaN");
11295        }
11296        assert_eq!(nan.semantic_cmp(&nan), Ordering::Equal, "NaN cmp NaN");
11297    }
11298
11299    /// br-frankenpandas-be314: common_dtype is the dtype-promotion lattice
11300    /// underpinning every binary op, alignment, and concat (dtype coercion is a
11301    /// crown-jewel correctness area). Exhaustively (all 14x14 DType pairs) assert
11302    /// its lattice axioms — an asymmetric arm would make df1+df2 and df2+df1
11303    /// disagree on dtype.
11304    #[test]
11305    fn common_dtype_lattice_axioms_be314() {
11306        let all: [DType; 14] = [
11307            DType::Null,
11308            DType::Bool,
11309            DType::BoolNullable,
11310            DType::Int64,
11311            DType::Int64Nullable,
11312            DType::Float64,
11313            // br-frankenpandas-qkqfb: a new variant is only safe once the
11314            // commutativity and associativity sweeps below cover it.
11315            DType::Float64Nullable,
11316            DType::Utf8,
11317            DType::Categorical,
11318            DType::Timedelta64,
11319            DType::datetime64_naive(),
11320            DType::Period,
11321            DType::Interval,
11322            DType::Sparse,
11323        ];
11324
11325        for a in &all {
11326            // Idempotence: a promoted with itself is itself.
11327            assert_eq!(
11328                common_dtype(a.clone(), a.clone()),
11329                Ok(a.clone()),
11330                "idempotent {a:?}"
11331            );
11332            // Null is the identity element of the promotion lattice.
11333            assert_eq!(
11334                common_dtype(DType::Null, a.clone()),
11335                Ok(a.clone()),
11336                "null-left identity {a:?}"
11337            );
11338            assert_eq!(
11339                common_dtype(a.clone(), DType::Null),
11340                Ok(a.clone()),
11341                "null-right identity {a:?}"
11342            );
11343
11344            for b in &all {
11345                // Commutativity: same Ok value AND same ok-ness. An asymmetric
11346                // match arm would make binary-op output dtype order-dependent.
11347                assert_eq!(
11348                    common_dtype(a.clone(), b.clone()).ok(),
11349                    common_dtype(b.clone(), a.clone()).ok(),
11350                    "commutative value {a:?},{b:?}"
11351                );
11352                assert_eq!(
11353                    common_dtype(a.clone(), b.clone()).is_ok(),
11354                    common_dtype(b.clone(), a.clone()).is_ok(),
11355                    "commutative ok-ness {a:?},{b:?}"
11356                );
11357            }
11358        }
11359
11360        // Associativity over the Ok-closed subset: when both nestings succeed,
11361        // promotion order must not change the result.
11362        for a in &all {
11363            for b in &all {
11364                for c in &all {
11365                    if let (Ok(ab), Ok(bc)) = (
11366                        common_dtype(a.clone(), b.clone()),
11367                        common_dtype(b.clone(), c.clone()),
11368                    ) && let (Ok(left), Ok(right)) =
11369                        (common_dtype(ab, c.clone()), common_dtype(a.clone(), bc))
11370                    {
11371                        assert_eq!(left, right, "associative {a:?},{b:?},{c:?}");
11372                    }
11373                }
11374            }
11375        }
11376    }
11377
11378    /// br-frankenpandas-e3sfq: infer_dtype drives Column/Series construction
11379    /// dtype inference. Assert its homogeneous + mixed-coercion rules.
11380    #[test]
11381    fn infer_dtype_coercion_rules_e3sfq() {
11382        use DType::{Bool, Float64, Int64, Null, Utf8};
11383
11384        // Empty and all-null infer to Null.
11385        assert_eq!(infer_dtype(&[]), Ok(Null));
11386        assert_eq!(
11387            infer_dtype(&[Scalar::Null(NullKind::Null), Scalar::Null(NullKind::NaN)]),
11388            Ok(Null)
11389        );
11390
11391        // Homogeneous slices infer to their own dtype (random, seeded LCG).
11392        let mut s: u64 = 0x132d_a7e0_0e3f_c0de;
11393        let mut next = || {
11394            s = s
11395                .wrapping_mul(6_364_136_223_846_793_005)
11396                .wrapping_add(1_442_695_040_888_963_407);
11397            (s >> 33) as u32
11398        };
11399        for _ in 0..600u32 {
11400            let n = (next() % 6) as usize + 1;
11401            let ints: Vec<Scalar> = (0..n)
11402                .map(|_| Scalar::Int64((next() % 9) as i64 - 4))
11403                .collect();
11404            assert_eq!(infer_dtype(&ints), Ok(Int64));
11405            let floats: Vec<Scalar> = (0..n)
11406                .map(|_| Scalar::Float64(f64::from((next() % 7) as i32)))
11407                .collect();
11408            assert_eq!(infer_dtype(&floats), Ok(Float64));
11409            let bools: Vec<Scalar> = (0..n).map(|_| Scalar::Bool(next() % 2 == 0)).collect();
11410            assert_eq!(infer_dtype(&bools), Ok(Bool));
11411            let strs: Vec<Scalar> = (0..n)
11412                .map(|_| Scalar::Utf8(format!("s{}", next() % 4)))
11413                .collect();
11414            assert_eq!(infer_dtype(&strs), Ok(Utf8));
11415        }
11416
11417        // Mixed-coercion rules.
11418        assert_eq!(
11419            infer_dtype(&[
11420                Scalar::Int64(1),
11421                Scalar::Null(NullKind::Null),
11422                Scalar::Int64(2)
11423            ]),
11424            Ok(Int64),
11425            "Int64 + nulls -> Int64"
11426        );
11427        assert_eq!(
11428            infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]),
11429            Ok(Float64),
11430            "Int64 + Float64 -> Float64"
11431        );
11432        // br-frankenpandas-rh1od: MEASURED live pandas 2.2.3 — a bool mixed
11433        // with numerics constructs OBJECT; the old Int64 coercion here was
11434        // numpy common-type behavior no pandas constructor path produces.
11435        assert_eq!(
11436            infer_dtype(&[Scalar::Bool(true), Scalar::Int64(3)]),
11437            Ok(Utf8),
11438            "Bool + Int64 -> object bucket (pandas constructs object)"
11439        );
11440        assert_eq!(
11441            infer_dtype(&[Scalar::Utf8("a".into()), Scalar::Int64(3)]),
11442            Ok(Utf8),
11443            "Utf8 + Int64 -> Utf8 (object fallback)"
11444        );
11445    }
11446
11447    /// br-frankenpandas-1ews0: missing_for_dtype is the canonical per-dtype
11448    /// missing sentinel (used by null-fill / with_validity / cast). Exhaustively
11449    /// assert it is always missing, and that casting any missing to any dtype
11450    /// stays missing.
11451    #[test]
11452    fn missing_for_dtype_always_missing_1ews0() {
11453        let all: [DType; 14] = [
11454            DType::Null,
11455            DType::Bool,
11456            DType::BoolNullable,
11457            DType::Int64,
11458            DType::Int64Nullable,
11459            DType::Float64,
11460            DType::Float64Nullable,
11461            DType::Utf8,
11462            DType::Categorical,
11463            DType::Timedelta64,
11464            DType::datetime64_naive(),
11465            DType::Period,
11466            DType::Interval,
11467            DType::Sparse,
11468        ];
11469        for dt in &all {
11470            let m = Scalar::missing_for_dtype(dt.clone());
11471            assert!(m.is_missing(), "missing_for_dtype({dt:?}) must be missing");
11472            for target in &all {
11473                let cast = cast_scalar(&m, target.clone()).expect("cast of missing");
11474                if target == &DType::Utf8 {
11475                    // Casting a missing value to string follows pandas astype(str):
11476                    // it yields a string ("None"/"NaN"/"NaT"), NOT a missing value.
11477                    assert!(
11478                        matches!(cast, Scalar::Utf8(_)),
11479                        "cast(missing {dt:?} -> Utf8) yields a string, got {cast:?}"
11480                    );
11481                } else if matches!(dt, DType::Timedelta64 | DType::Datetime64 { .. })
11482                    && matches!(target, DType::Bool | DType::Int64)
11483                {
11484                    // ⚠️ TWO MORE PLACES pandas BREAKS this invariant, and both
11485                    // are the same underlying fact: NaT is not a separate
11486                    // representation, it IS i64::MIN, and the numpy casts read
11487                    // the bits. MEASURED, live pandas 2.2.3:
11488                    //
11489                    //   pd.Series([pd.NaT], dtype='datetime64[ns]').astype('int64')
11490                    //     -> -9223372036854775808      the SENTINEL, not a missing
11491                    //   pd.Series([pd.NaT], dtype='timedelta64[ns]').astype('bool')
11492                    //     -> True                      nonzero, so truthy
11493                    //
11494                    // Same shape as the Utf8 carve-out above: the invariant is
11495                    // FrankenPandas' own, and pandas does not honour it wherever
11496                    // a cast is defined to reinterpret rather than to convert.
11497                    // Narrowly scoped on purpose — every other missing, and these
11498                    // two toward every other target, still stay missing.
11499                    match target {
11500                        DType::Bool => assert_eq!(
11501                            cast,
11502                            Scalar::Bool(true),
11503                            "cast(missing {dt:?} -> Bool) is pandas' nonzero-truthy \
11504                             read of the NaT bits"
11505                        ),
11506                        _ => assert_eq!(
11507                            cast,
11508                            Scalar::Int64(i64::MIN),
11509                            "cast(missing {dt:?} -> Int64) is the NaT sentinel itself"
11510                        ),
11511                    }
11512                } else {
11513                    // Every other target preserves missingness via cast_scalar's
11514                    // value.is_missing() -> missing_for_dtype(target) branch.
11515                    assert!(
11516                        cast.is_missing(),
11517                        "cast(missing {dt:?} -> {target:?}) must stay missing, got {cast:?}"
11518                    );
11519                }
11520            }
11521        }
11522    }
11523
11524    #[test]
11525    fn cast_scalar_bool_int_roundtrip_6w07b() {
11526        use super::cast_scalar;
11527        // Property (br-frankenpandas-6w07b): Bool<->Int64 cast. Seeded LCG, no mocks.
11528        assert_eq!(
11529            cast_scalar(&Scalar::Bool(true), DType::Int64).unwrap(),
11530            Scalar::Int64(1)
11531        );
11532        assert_eq!(
11533            cast_scalar(&Scalar::Bool(false), DType::Int64).unwrap(),
11534            Scalar::Int64(0)
11535        );
11536        assert_eq!(
11537            cast_scalar(&Scalar::Int64(0), DType::Bool).unwrap(),
11538            Scalar::Bool(false)
11539        );
11540        let mut st: u64 = 0x4b07_0b1c_2d3e_4f50;
11541        let mut next = || {
11542            st = st
11543                .wrapping_mul(6_364_136_223_846_793_005)
11544                .wrapping_add(1_442_695_040_888_963_407);
11545            (st >> 33) as u32
11546        };
11547        for _ in 0..2000u32 {
11548            let v = (next() % 21) as i64 - 10;
11549            assert_eq!(
11550                cast_scalar(&Scalar::Int64(v), DType::Bool).unwrap(),
11551                Scalar::Bool(v != 0),
11552                "int->bool v={v}"
11553            );
11554        }
11555    }
11556
11557    /// br-frankenpandas-6a83t: cast_scalar is the scalar dtype-coercion path
11558    #[test]
11559    fn cast_scalar_float_to_int_truncates_toward_zero_u9lec() {
11560        use super::cast_scalar;
11561        // Property (br-frankenpandas-u9lec): Float64->Int64 truncates toward zero, not
11562        // floor (-3.7 -> -3). Seeded LCG, no mocks.
11563        let mut st: u64 = 0x4ca5_0b1c_2d3e_4f50;
11564        let mut next = || {
11565            st = st
11566                .wrapping_mul(6_364_136_223_846_793_005)
11567                .wrapping_add(1_442_695_040_888_963_407);
11568            (st >> 33) as u32
11569        };
11570        // Explicit negative-direction checks (the gotcha).
11571        for (f, exp) in [
11572            (-3.7, -3i64),
11573            (3.7, 3),
11574            (-3.2, -3),
11575            (3.2, 3),
11576            (-0.9, 0),
11577            (0.9, 0),
11578            (-5.0, -5),
11579            (5.0, 5),
11580        ] {
11581            assert_eq!(
11582                cast_scalar(&Scalar::Float64(f), DType::Int64).unwrap(),
11583                Scalar::Int64(exp),
11584                "cast {f}"
11585            );
11586        }
11587        // Property over random signed fractional values.
11588        for _ in 0..3000u32 {
11589            let v = (next() % 2_000_001) as f64 / 1000.0 - 1000.0; // [-1000, 1000]
11590            let got = cast_scalar(&Scalar::Float64(v), DType::Int64).unwrap();
11591            assert_eq!(
11592                got,
11593                Scalar::Int64(v.trunc() as i64),
11594                "trunc-toward-zero v={v}"
11595            );
11596        }
11597    }
11598
11599    /// Float -> `datetime64[ns]` / `timedelta64[ns]` reinterprets the float as
11600    /// integer NANOSECONDS. Every value here is transcribed from live pandas
11601    /// 2.2.3, measured on both the constructor and `astype` paths.
11602    ///
11603    /// ⚠️ THE CONTRAST WITH `int64` IS THE POINT: the explicit constructor
11604    /// REFUSES a lossy float -> int64, and silently truncates the same float
11605    /// into a temporal dtype. Assuming one rule covers both is how this gets
11606    /// re-broken, so both are asserted here on the same input.
11607    #[test]
11608    fn cast_scalar_float_to_temporal_truncates_to_nanoseconds() {
11609        use super::{Timedelta, Timestamp, cast_scalar};
11610
11611        // TRUNCATION TOWARD ZERO, on both signs, where a floor would disagree.
11612        // pandas: 0.9 -> 0, -0.9 -> 0, 1.5 -> 1, -1.5 -> -1, -2.5 -> -2.
11613        for (input, want) in [
11614            (1.5_f64, 1_i64),
11615            (-1.5, -1),
11616            (0.9, 0),
11617            (-0.9, 0),
11618            (2.5, 2),
11619            (-2.5, -2),
11620            (1.999_999, 1),
11621            (-1.999_999, -1),
11622            (2.0, 2),
11623            (1e18, 1_000_000_000_000_000_000),
11624        ] {
11625            assert_eq!(
11626                cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
11627                Scalar::Datetime64(want),
11628                "datetime64 cast of {input}"
11629            );
11630            assert_eq!(
11631                cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
11632                Scalar::Timedelta64(want),
11633                "timedelta64 cast of {input}"
11634            );
11635        }
11636
11637        // ANYTHING NOT REPRESENTABLE AS i64 IS NaT — not a saturated i64::MAX,
11638        // and not the epoch. A bare `as i64` would produce both of those wrong
11639        // answers (saturation for the large values, 0 for NaN).
11640        for input in [
11641            f64::NAN,
11642            f64::INFINITY,
11643            f64::NEG_INFINITY,
11644            1e30,
11645            -1e30,
11646            9.3e18,
11647            -9.3e18,
11648            9_223_372_036_854_775_808.0,  // exactly 2^63
11649            -9_223_372_036_854_775_808.0, // exactly -2^63, which IS the NaT sentinel
11650        ] {
11651            assert_eq!(
11652                cast_scalar(&Scalar::Float64(input), DType::datetime64_naive()).unwrap(),
11653                Scalar::Datetime64(Timestamp::NAT),
11654                "datetime64 cast of {input} must be NaT"
11655            );
11656            assert_eq!(
11657                cast_scalar(&Scalar::Float64(input), DType::Timedelta64).unwrap(),
11658                Scalar::Timedelta64(Timedelta::NAT),
11659                "timedelta64 cast of {input} must be NaT"
11660            );
11661        }
11662
11663        // ...but the largest float BELOW 2^63 is representable and converts.
11664        // pandas renders it 2262-04-11 23:47:16.854774784.
11665        let just_inside = 9_223_372_036_854_774_784.0_f64; // 2^63 - 1024
11666        assert_eq!(
11667            cast_scalar(&Scalar::Float64(just_inside), DType::datetime64_naive()).unwrap(),
11668            Scalar::Datetime64(9_223_372_036_854_774_784),
11669            "the largest representable float must NOT be treated as NaT"
11670        );
11671
11672        // THE CONTRAST. Same input, three dtypes, two different rules — the
11673        // temporal ones truncate where int64 refuses outright.
11674        assert_eq!(
11675            cast_scalar(&Scalar::Float64(1.5), DType::datetime64_naive()).unwrap(),
11676            Scalar::Datetime64(1)
11677        );
11678        assert_eq!(
11679            cast_scalar(&Scalar::Float64(1.5), DType::Int64).unwrap(),
11680            Scalar::Int64(1),
11681            "the SHARED cast truncates here too; it is the explicit constructor \
11682             that refuses, via Column::new's LossyFloatToInt pre-check"
11683        );
11684    }
11685
11686    /// The MIRROR direction: `datetime64[ns]` / `timedelta64[ns]` -> numpy
11687    /// `int64` is the raw nanosecond count, and a bool is 0 or 1 nanoseconds
11688    /// going the other way. Every value transcribed from live pandas 2.2.3
11689    /// `astype`.
11690    #[test]
11691    fn cast_scalar_temporal_to_int64_is_raw_nanoseconds() {
11692        use super::{Timedelta, Timestamp, cast_scalar};
11693
11694        // Timestamp('2024-03-15 10:30:45.123456789') and
11695        // Timedelta('1 days 02:03:04.005006007').
11696        for nanos in [1_710_498_645_123_456_789_i64, 93_784_005_006_007, 0, -1] {
11697            assert_eq!(
11698                cast_scalar(&Scalar::Datetime64(nanos), DType::Int64).unwrap(),
11699                Scalar::Int64(nanos),
11700                "datetime64 -> int64 must be the raw nanos ({nanos})"
11701            );
11702            assert_eq!(
11703                cast_scalar(&Scalar::Timedelta64(nanos), DType::Int64).unwrap(),
11704                Scalar::Int64(nanos)
11705            );
11706        }
11707
11708        // ⚠️ NaT BECOMES THE SENTINEL, NOT A MISSING VALUE. pandas:
11709        //     pd.Series([pd.NaT], dtype='datetime64[ns]').astype('int64')
11710        //       -> -9223372036854775808
11711        // This is the assertion that pins the cast ABOVE the is_missing()
11712        // branch; move it below and both of these become Null.
11713        assert_eq!(
11714            cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Int64).unwrap(),
11715            Scalar::Int64(i64::MIN),
11716            "NaT -> int64 is the sentinel i64::MIN, not a missing value"
11717        );
11718        assert_eq!(
11719            cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Int64).unwrap(),
11720            Scalar::Int64(i64::MIN)
11721        );
11722
11723        // ⚠️ THE NULLABLE Int64 REFUSES WHAT numpy int64 ACCEPTS:
11724        //     .astype('Int64')   -> TypeError: datetime64[ns] cannot be
11725        //                          converted to IntegerDtype
11726        //     .astype('float64') -> TypeError: Cannot cast DatetimeArray
11727        // Both must stay refused, which is what makes the guard on the exact
11728        // target load-bearing rather than cosmetic.
11729        // `DType` stopped being `Copy` when `Datetime64 { tz }` landed
11730        // (2f159e68f), so the loop variable is cloned into each call.
11731        for target in [DType::Int64Nullable, DType::Float64, DType::Float64Nullable] {
11732            assert!(
11733                cast_scalar(
11734                    &Scalar::Datetime64(1_710_498_645_123_456_789),
11735                    target.clone()
11736                )
11737                .is_err(),
11738                "datetime64 -> {target:?} must stay refused"
11739            );
11740            assert!(
11741                cast_scalar(&Scalar::Timedelta64(93_784_005_006_007), target.clone()).is_err(),
11742                "timedelta64 -> {target:?} must stay refused"
11743            );
11744        }
11745
11746        // A bool is 0 or 1 NANOSECONDS on the astype path.
11747        for (flag, want) in [(true, 1_i64), (false, 0)] {
11748            assert_eq!(
11749                cast_scalar(&Scalar::Bool(flag), DType::datetime64_naive()).unwrap(),
11750                Scalar::Datetime64(want)
11751            );
11752            assert_eq!(
11753                cast_scalar(&Scalar::Bool(flag), DType::Timedelta64).unwrap(),
11754                Scalar::Timedelta64(want)
11755            );
11756        }
11757    }
11758
11759    /// The two halves of the column-width datetime formatter, checked apart:
11760    /// which rung a value NEEDS, and how a value RENDERS at a given rung.
11761    /// Transcribed from live pandas 2.2.3 `.astype(str)`, one column per rung.
11762    #[test]
11763    fn timestamp_string_resolution_and_formatting_match_pandas() {
11764        use super::{DatetimeStringResolution as Res, Timestamp};
11765
11766        const MIDNIGHT: i64 = 1_710_460_800_000_000_000; // 2024-03-15 00:00:00
11767
11768        // Which rung each value needs, on its own.
11769        assert_eq!(Timestamp::string_resolution(MIDNIGHT), Res::Date);
11770        assert_eq!(
11771            Timestamp::string_resolution(MIDNIGHT + 37_845_000_000_000),
11772            Res::Second
11773        );
11774        assert_eq!(
11775            Timestamp::string_resolution(MIDNIGHT + 37_845_123_000_000),
11776            Res::Milli
11777        );
11778        assert_eq!(
11779            Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_000),
11780            Res::Micro
11781        );
11782        assert_eq!(
11783            Timestamp::string_resolution(MIDNIGHT + 37_845_123_456_789),
11784            Res::Nano
11785        );
11786        // A whole MINUTE is not its own rung — it still needs Second.
11787        assert_eq!(
11788            Timestamp::string_resolution(MIDNIGHT + 300_000_000_000),
11789            Res::Second
11790        );
11791        // NaT reports the coarsest rung, the identity of the `max` fold, which
11792        // is what keeps it from dragging a column to nanoseconds.
11793        assert_eq!(Timestamp::string_resolution(Timestamp::NAT), Res::Date);
11794
11795        // Coarsest-first ordering is what makes `max` mean "finest needed".
11796        assert!(Res::Date < Res::Second);
11797        assert!(Res::Second < Res::Milli);
11798        assert!(Res::Milli < Res::Micro);
11799        assert!(Res::Micro < Res::Nano);
11800
11801        // ...and how ONE value renders at each rung it might be forced into.
11802        let value = MIDNIGHT + 37_845_123_456_789;
11803        assert_eq!(
11804            Timestamp::format_at_resolution(value, Res::Date),
11805            "2024-03-15"
11806        );
11807        assert_eq!(
11808            Timestamp::format_at_resolution(value, Res::Second),
11809            "2024-03-15 10:30:45"
11810        );
11811        assert_eq!(
11812            Timestamp::format_at_resolution(value, Res::Milli),
11813            "2024-03-15 10:30:45.123"
11814        );
11815        assert_eq!(
11816            Timestamp::format_at_resolution(value, Res::Micro),
11817            "2024-03-15 10:30:45.123456"
11818        );
11819        assert_eq!(
11820            Timestamp::format_at_resolution(value, Res::Nano),
11821            "2024-03-15 10:30:45.123456789"
11822        );
11823
11824        // A midnight forced to the nanosecond rung keeps its zero fraction --
11825        // pandas pads, it does not trim.
11826        assert_eq!(
11827            Timestamp::format_at_resolution(MIDNIGHT, Res::Nano),
11828            "2024-03-15 00:00:00.000000000"
11829        );
11830
11831        // ⚠️ NOT isoformat: a SPACE separator, not a `T`.
11832        assert_eq!(
11833            Timestamp::format_at_resolution(MIDNIGHT, Res::Second),
11834            "2024-03-15 00:00:00"
11835        );
11836
11837        // NaT is the STRING "NaT" at every rung.
11838        for resolution in [Res::Date, Res::Second, Res::Milli, Res::Micro, Res::Nano] {
11839            assert_eq!(
11840                Timestamp::format_at_resolution(Timestamp::NAT, resolution),
11841                "NaT"
11842            );
11843        }
11844
11845        // Pre-epoch: rem_euclid must keep the fraction on the right side of
11846        // midnight, or -1ns renders as 1970-01-01 with a negative fraction.
11847        assert_eq!(
11848            Timestamp::format_at_resolution(-1, Res::Nano),
11849            "1969-12-31 23:59:59.999999999"
11850        );
11851
11852        // Both ends of pandas' datetime64[ns] range.
11853        assert_eq!(
11854            Timestamp::format_at_resolution(-9_223_372_036_854_775_806, Res::Nano),
11855            "1677-09-21 00:12:43.145224194"
11856        );
11857        assert_eq!(
11858            Timestamp::format_at_resolution(9_223_372_036_854_775_807, Res::Nano),
11859            "2262-04-11 23:47:16.854775807"
11860        );
11861    }
11862
11863    /// Temporal -> numpy `bool` is nonzero-truthy on the RAW NANOSECONDS, which
11864    /// makes NaT `true`. Transcribed from live pandas 2.2.3 `.astype('bool')`,
11865    /// measured beside `.astype('int64')` so the one rule is visible as one rule.
11866    #[test]
11867    fn cast_scalar_temporal_to_bool_is_nonzero_on_the_nanos() {
11868        use super::{Timedelta, Timestamp, cast_scalar};
11869
11870        // Only the epoch and a zero duration are false.
11871        for (nanos, want) in [
11872            (0_i64, false),
11873            (1_710_498_645_123_456_789, true),
11874            (-1, true),
11875            (86_400_000_000_000, true),
11876            (1, true),
11877        ] {
11878            assert_eq!(
11879                cast_scalar(&Scalar::Datetime64(nanos), DType::Bool).unwrap(),
11880                Scalar::Bool(want),
11881                "datetime64 {nanos} -> bool"
11882            );
11883            assert_eq!(
11884                cast_scalar(&Scalar::Timedelta64(nanos), DType::Bool).unwrap(),
11885                Scalar::Bool(want),
11886                "timedelta64 {nanos} -> bool"
11887            );
11888        }
11889
11890        // ⚠️ NaT IS TRUE, not missing. It needs no case of its own — NaT IS
11891        // i64::MIN, which is nonzero — but it only reaches the rule because the
11892        // cast sits ABOVE is_missing(); below it, both of these become Null.
11893        assert_eq!(
11894            cast_scalar(&Scalar::Datetime64(Timestamp::NAT), DType::Bool).unwrap(),
11895            Scalar::Bool(true),
11896            "NaT -> bool is true in pandas, not a missing value"
11897        );
11898        assert_eq!(
11899            cast_scalar(&Scalar::Timedelta64(Timedelta::NAT), DType::Bool).unwrap(),
11900            Scalar::Bool(true)
11901        );
11902
11903        // ⚠️ THE NULLABLE `boolean` REFUSES THE WHOLE DTYPE, not just the odd
11904        // value: pandas raises "Need to pass bool-like values" for every row
11905        // above, INCLUDING the ones whose nanos are 0 or 1. That exclusion is
11906        // what the `DType::Bool` guard buys, so it is asserted rather than
11907        // assumed.
11908        //
11909        // NaT is deliberately NOT in this loop, and the reason is a KNOWN
11910        // DIVERGENCE rather than an oversight: `is_missing()` catches NaT before
11911        // any BoolNullable arm can refuse it, so FP answers `Null` where pandas
11912        // raises. Asserting `is_err()` for it here would fail. Left visible.
11913        for nanos in [0_i64, 1, -1, 1_710_498_645_123_456_789] {
11914            assert!(
11915                cast_scalar(&Scalar::Datetime64(nanos), DType::BoolNullable).is_err(),
11916                "datetime64 {nanos} -> nullable boolean must stay refused"
11917            );
11918            assert!(
11919                cast_scalar(&Scalar::Timedelta64(nanos), DType::BoolNullable).is_err(),
11920                "timedelta64 {nanos} -> nullable boolean must stay refused"
11921            );
11922        }
11923    }
11924
11925    #[test]
11926    fn nancount_nunique_prod_any_all_mx60x() {
11927        use super::{nanall, nanany, nancount, nannunique, nanprod};
11928        // br-frankenpandas-mx60x: nancount/nannunique/nanprod/nanany/nanall skip NaN
11929        // and match finite-only oracles. Seeded LCG, no mocks.
11930        let mut s: u64 = 0x4e2a_0b1c_2d3e_4f50;
11931        let mut next = || {
11932            s = s
11933                .wrapping_mul(6_364_136_223_846_793_005)
11934                .wrapping_add(1_442_695_040_888_963_407);
11935            (s >> 33) as u32
11936        };
11937        let asf = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
11938        let asb = |sc: Scalar| -> bool { matches!(sc, Scalar::Bool(true)) };
11939        for iter in 0..1000u32 {
11940            let n = (next() % 10) as usize + 1;
11941            let raw: Vec<f64> = (0..n)
11942                .map(|_| {
11943                    if next() % 4 == 0 {
11944                        f64::NAN
11945                    } else {
11946                        (next() % 5) as f64
11947                    }
11948                })
11949                .collect();
11950            let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
11951            if finite.is_empty() {
11952                continue;
11953            }
11954            let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
11955            let distinct: std::collections::HashSet<u64> =
11956                finite.iter().map(|x| x.to_bits()).collect();
11957            let prod: f64 = finite.iter().product();
11958            assert!(
11959                (asf(nancount(&scalars)) - finite.len() as f64).abs() < 1e-9,
11960                "nancount iter={iter}"
11961            );
11962            assert!(
11963                (asf(nannunique(&scalars)) - distinct.len() as f64).abs() < 1e-9,
11964                "nannunique iter={iter}"
11965            );
11966            assert!(
11967                (asf(nanprod(&scalars)) - prod).abs() < 1e-7,
11968                "nanprod iter={iter}"
11969            );
11970            assert_eq!(
11971                asb(nanany(&scalars)),
11972                finite.iter().any(|&x| x != 0.0),
11973                "nanany iter={iter}"
11974            );
11975            assert_eq!(
11976                asb(nanall(&scalars)),
11977                finite.iter().all(|&x| x != 0.0),
11978                "nanall iter={iter}"
11979            );
11980        }
11981    }
11982
11983    #[test]
11984    fn nan_reduction_kernels_skip_correctness_1uagc() {
11985        use super::{nanmax, nanmedian, nanmin, nansum};
11986        // br-frankenpandas-1uagc: nansum/nanmin/nanmax/nanmedian skip NaN and match
11987        // finite-only oracles. Seeded LCG, no mocks.
11988        let mut s: u64 = 0x4e1a_0b2c_2d3e_4f50;
11989        let mut next = || {
11990            s = s
11991                .wrapping_mul(6_364_136_223_846_793_005)
11992                .wrapping_add(1_442_695_040_888_963_407);
11993            (s >> 33) as u32
11994        };
11995        let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
11996        for iter in 0..1000u32 {
11997            let n = (next() % 12) as usize + 1;
11998            let raw: Vec<f64> = (0..n)
11999                .map(|_| {
12000                    if next() % 4 == 0 {
12001                        f64::NAN
12002                    } else {
12003                        (next() % 200) as f64 - 100.0
12004                    }
12005                })
12006                .collect();
12007            let mut finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
12008            if finite.is_empty() {
12009                continue;
12010            }
12011            let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
12012            let sum: f64 = finite.iter().sum();
12013            let mn = finite.iter().copied().fold(f64::INFINITY, f64::min);
12014            let mx = finite.iter().copied().fold(f64::NEG_INFINITY, f64::max);
12015            finite.sort_by(|a, b| a.partial_cmp(b).unwrap());
12016            let m = finite.len();
12017            let med = if m % 2 == 1 {
12018                finite[m / 2]
12019            } else {
12020                (finite[m / 2 - 1] + finite[m / 2]) / 2.0
12021            };
12022            assert!(
12023                (val(nansum(&scalars)) - sum).abs() < 1e-7,
12024                "nansum iter={iter}"
12025            );
12026            assert!(
12027                (val(nanmin(&scalars)) - mn).abs() < 1e-9,
12028                "nanmin iter={iter}"
12029            );
12030            assert!(
12031                (val(nanmax(&scalars)) - mx).abs() < 1e-9,
12032                "nanmax iter={iter}"
12033            );
12034            assert!(
12035                (val(nanmedian(&scalars)) - med).abs() < 1e-9,
12036                "nanmedian iter={iter}"
12037            );
12038        }
12039    }
12040
12041    #[test]
12042    fn nanvar_ddof_nanstd_nan_skip_p00ag() {
12043        use super::{nanmean, nanstd, nanvar};
12044        // br-frankenpandas-p00ag: nanmean/nanvar/nanstd skip NaN; ddof picks the
12045        // denominator; nanstd==sqrt(nanvar). Seeded LCG, no mocks.
12046        let mut s: u64 = 0x4e0a_0b1c_2d3e_4f50;
12047        let mut next = || {
12048            s = s
12049                .wrapping_mul(6_364_136_223_846_793_005)
12050                .wrapping_add(1_442_695_040_888_963_407);
12051            (s >> 33) as u32
12052        };
12053        let val = |sc: Scalar| -> f64 { sc.to_f64().unwrap_or(f64::NAN) };
12054        for iter in 0..1000u32 {
12055            let n = (next() % 10) as usize + 2;
12056            let raw: Vec<f64> = (0..n)
12057                .map(|_| {
12058                    if next() % 4 == 0 {
12059                        f64::NAN
12060                    } else {
12061                        (next() % 200) as f64 / 7.0
12062                    }
12063                })
12064                .collect();
12065            let finite: Vec<f64> = raw.iter().copied().filter(|x| !x.is_nan()).collect();
12066            if finite.len() < 2 {
12067                continue;
12068            }
12069            let scalars: Vec<Scalar> = raw.iter().map(|&x| Scalar::Float64(x)).collect();
12070            let nf = finite.len() as f64;
12071            let mean = finite.iter().sum::<f64>() / nf;
12072            let ss = finite.iter().map(|x| (x - mean).powi(2)).sum::<f64>();
12073            assert!(
12074                (val(nanmean(&scalars)) - mean).abs() < 1e-7,
12075                "nanmean iter={iter}"
12076            );
12077            assert!(
12078                (val(nanvar(&scalars, 0)) - ss / nf).abs() < 1e-7,
12079                "nanvar ddof0 iter={iter}"
12080            );
12081            assert!(
12082                (val(nanvar(&scalars, 1)) - ss / (nf - 1.0)).abs() < 1e-7,
12083                "nanvar ddof1 iter={iter}"
12084            );
12085            assert!(
12086                (val(nanstd(&scalars, 1)) - (ss / (nf - 1.0)).sqrt()).abs() < 1e-7,
12087                "nanstd ddof1 iter={iter}"
12088            );
12089        }
12090    }
12091
12092    #[test]
12093    fn nanskew_nankurt_min_sample_and_known_xybnq() {
12094        // br-frankenpandas-xybnq: guard nanskew/nankurt min-sample-size (NaN below
12095        // threshold) + known pandas G1/G2 values (the f4dc5540 inline-copy bug area).
12096        use super::{nankurt, nanskew};
12097        let f = |xs: &[f64]| -> Vec<Scalar> { xs.iter().map(|&x| Scalar::Float64(x)).collect() };
12098        let val = |s: Scalar| -> Option<f64> {
12099            if s.is_missing() {
12100                None
12101            } else {
12102                s.to_f64().ok()
12103            }
12104        };
12105
12106        // skew needs >= 3 observations.
12107        assert_eq!(val(nanskew(&f(&[1.0, 2.0]))), None, "skew n=2 -> NaN");
12108        let sym = val(nanskew(&f(&[1.0, 2.0, 3.0]))).expect("skew n=3");
12109        assert!(sym.abs() < 1e-9, "symmetric skew ~0, got {sym}");
12110        let right = val(nanskew(&f(&[1.0, 1.0, 1.0, 5.0]))).expect("skew n=4");
12111        assert!(right > 0.0, "right-skewed -> positive skew, got {right}");
12112
12113        // kurt needs >= 4 observations.
12114        assert_eq!(val(nankurt(&f(&[1.0, 2.0, 3.0]))), None, "kurt n=3 -> NaN");
12115        let k = val(nankurt(&f(&[1.0, 2.0, 3.0, 4.0, 5.0]))).expect("kurt n=5");
12116        assert!(
12117            (k - (-1.2)).abs() < 1e-6,
12118            "pandas kurt([1..5]) == -1.2, got {k}"
12119        );
12120    }
12121
12122    #[test]
12123    #[ignore = "foreground release attribution harness"]
12124    fn nanskew_fused_moment_scan_ab_mavln() {
12125        const ROWS: usize = 100_000;
12126        const BATCH: usize = 8;
12127
12128        fn former(values: &[Scalar]) -> Scalar {
12129            let nums = super::collect_finite(values);
12130            let n = nums.len() as f64;
12131            if n < 3.0 {
12132                return Scalar::Null(NullKind::NaN);
12133            }
12134            let mean = nums.iter().sum::<f64>() / n;
12135            let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
12136            let m3: f64 = nums.iter().map(|x| (x - mean).powi(3)).sum();
12137            let s2 = m2 / (n - 1.0);
12138            if s2 == 0.0 {
12139                return Scalar::Float64(0.0);
12140            }
12141            let s3 = s2.powf(1.5);
12142            Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s3))
12143        }
12144
12145        fn assert_bits_eq(former: Scalar, candidate: Scalar) {
12146            match (former, candidate) {
12147                (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
12148                (a, b) => assert_eq!(a, b),
12149            }
12150        }
12151
12152        fn elapsed(values: &[Scalar], skew: fn(&[Scalar]) -> Scalar) -> u128 {
12153            std::hint::black_box(skew(std::hint::black_box(values)));
12154            let started = std::time::Instant::now();
12155            for _ in 0..BATCH {
12156                std::hint::black_box(skew(std::hint::black_box(values)));
12157            }
12158            started.elapsed().as_nanos()
12159        }
12160
12161        fn median(samples: &mut [u128]) -> u128 {
12162            samples.sort_unstable();
12163            samples[samples.len() / 2]
12164        }
12165
12166        for values in [
12167            vec![],
12168            vec![Scalar::Int64(1), Scalar::Int64(2)],
12169            vec![Scalar::Int64(7); 16],
12170            vec![
12171                Scalar::Int64(-3),
12172                Scalar::Null(NullKind::NaN),
12173                Scalar::Float64(2.5),
12174                Scalar::Utf8("skip".to_owned()),
12175                Scalar::Int64(11),
12176            ],
12177        ] {
12178            assert_bits_eq(former(&values), super::nanskew(&values));
12179        }
12180
12181        let values = (0..ROWS)
12182            .map(|i| {
12183                if i % 257 == 0 {
12184                    Scalar::Null(NullKind::NaN)
12185                } else {
12186                    Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
12187                }
12188            })
12189            .collect::<Vec<_>>();
12190        assert_bits_eq(former(&values), super::nanskew(&values));
12191
12192        for _ in 0..2 {
12193            std::hint::black_box(elapsed(&values, former));
12194            std::hint::black_box(elapsed(&values, super::nanskew));
12195        }
12196
12197        let mut former_samples = Vec::with_capacity(18);
12198        let mut candidate_samples = Vec::with_capacity(18);
12199        for block in 0_usize..9 {
12200            if block.is_multiple_of(2) {
12201                former_samples.push(elapsed(&values, former));
12202                candidate_samples.push(elapsed(&values, super::nanskew));
12203                candidate_samples.push(elapsed(&values, super::nanskew));
12204                former_samples.push(elapsed(&values, former));
12205            } else {
12206                candidate_samples.push(elapsed(&values, super::nanskew));
12207                former_samples.push(elapsed(&values, former));
12208                former_samples.push(elapsed(&values, former));
12209                candidate_samples.push(elapsed(&values, super::nanskew));
12210            }
12211        }
12212
12213        let former_p50 = median(&mut former_samples);
12214        let candidate_p50 = median(&mut candidate_samples);
12215        eprintln!(
12216            "NANSKEW_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
12217            former_p50 as f64 / candidate_p50 as f64,
12218        );
12219        eprintln!("NANSKEW_FUSED_AB former_samples_ns={former_samples:?}");
12220        eprintln!("NANSKEW_FUSED_AB candidate_samples_ns={candidate_samples:?}");
12221    }
12222
12223    #[test]
12224    #[ignore = "foreground performance probe"]
12225    fn nankurt_fused_moment_scan_ab_idka7() {
12226        const ROWS: usize = 65_536;
12227        const BATCH: usize = 4;
12228
12229        fn former(values: &[Scalar]) -> Scalar {
12230            let nums = super::collect_finite(values);
12231            let n = nums.len() as f64;
12232            if n < 4.0 {
12233                return Scalar::Null(NullKind::NaN);
12234            }
12235            let mean = nums.iter().sum::<f64>() / n;
12236            let m2: f64 = nums.iter().map(|x| (x - mean).powi(2)).sum();
12237            let m4: f64 = nums.iter().map(|x| (x - mean).powi(4)).sum();
12238            let s2 = m2 / (n - 1.0);
12239            if s2 == 0.0 {
12240                return Scalar::Float64(0.0);
12241            }
12242            let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
12243            let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
12244            Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
12245        }
12246
12247        fn assert_bits_eq(former: Scalar, candidate: Scalar) {
12248            match (former, candidate) {
12249                (Scalar::Float64(a), Scalar::Float64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
12250                (a, b) => assert_eq!(a, b),
12251            }
12252        }
12253
12254        fn elapsed(values: &[Scalar], kurt: fn(&[Scalar]) -> Scalar) -> u128 {
12255            let started = std::time::Instant::now();
12256            for _ in 0..BATCH {
12257                std::hint::black_box(kurt(std::hint::black_box(values)));
12258            }
12259            started.elapsed().as_nanos()
12260        }
12261
12262        fn median(samples: &mut [u128]) -> u128 {
12263            samples.sort_unstable();
12264            samples[samples.len() / 2]
12265        }
12266
12267        for values in [
12268            vec![],
12269            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
12270            vec![Scalar::Int64(7); 16],
12271            vec![
12272                Scalar::Int64(-3),
12273                Scalar::Null(NullKind::NaN),
12274                Scalar::Float64(2.5),
12275                Scalar::Utf8("skip".to_owned()),
12276                Scalar::Int64(11),
12277                Scalar::Float64(-7.25),
12278            ],
12279        ] {
12280            assert_bits_eq(former(&values), super::nankurt(&values));
12281        }
12282
12283        let values = (0..ROWS)
12284            .map(|i| {
12285                if i % 257 == 0 {
12286                    Scalar::Null(NullKind::NaN)
12287                } else {
12288                    Scalar::Int64(((i * 37 + i / 11) % 10_003) as i64 - 5_001)
12289                }
12290            })
12291            .collect::<Vec<_>>();
12292        assert_bits_eq(former(&values), super::nankurt(&values));
12293
12294        for _ in 0..2 {
12295            std::hint::black_box(elapsed(&values, former));
12296            std::hint::black_box(elapsed(&values, super::nankurt));
12297        }
12298
12299        let mut former_samples = Vec::with_capacity(10);
12300        let mut candidate_samples = Vec::with_capacity(10);
12301        for block in 0_usize..5 {
12302            if block.is_multiple_of(2) {
12303                former_samples.push(elapsed(&values, former));
12304                candidate_samples.push(elapsed(&values, super::nankurt));
12305                candidate_samples.push(elapsed(&values, super::nankurt));
12306                former_samples.push(elapsed(&values, former));
12307            } else {
12308                candidate_samples.push(elapsed(&values, super::nankurt));
12309                former_samples.push(elapsed(&values, former));
12310                former_samples.push(elapsed(&values, former));
12311                candidate_samples.push(elapsed(&values, super::nankurt));
12312            }
12313        }
12314
12315        let former_p50 = median(&mut former_samples);
12316        let candidate_p50 = median(&mut candidate_samples);
12317        eprintln!(
12318            "NANKURT_FUSED_AB rows={ROWS} batch={BATCH} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
12319            former_p50 as f64 / candidate_p50 as f64,
12320        );
12321        eprintln!("NANKURT_FUSED_AB former_samples_ns={former_samples:?}");
12322        eprintln!("NANKURT_FUSED_AB candidate_samples_ns={candidate_samples:?}");
12323    }
12324
12325    /// behind astype/promotion. Property test of its confirmed identity +
12326    /// numeric/bool coercion rules over random scalars. Deterministic seeded LCG.
12327    #[test]
12328    fn cast_scalar_to_utf8_formatting_yes7i() {
12329        // Property (br-frankenpandas-yes7i): cast to Utf8 formats per pandas
12330        // astype(str): Int64 -> decimal, Bool -> True/False. Seeded LCG, no mocks.
12331        let mut st: u64 = 0x4e57_0b1c_2d3e_4f50;
12332        let mut next = || {
12333            st = st
12334                .wrapping_mul(6_364_136_223_846_793_005)
12335                .wrapping_add(1_442_695_040_888_963_407);
12336            (st >> 33) as u32
12337        };
12338        for _ in 0..3000u32 {
12339            let n = (next() % 4_000_001) as i64 - 2_000_000;
12340            assert_eq!(
12341                cast_scalar(&Scalar::Int64(n), DType::Utf8).unwrap(),
12342                Scalar::Utf8(n.to_string())
12343            );
12344        }
12345        assert_eq!(
12346            cast_scalar(&Scalar::Bool(true), DType::Utf8).unwrap(),
12347            Scalar::Utf8("True".to_string())
12348        );
12349        assert_eq!(
12350            cast_scalar(&Scalar::Bool(false), DType::Utf8).unwrap(),
12351            Scalar::Utf8("False".to_string())
12352        );
12353    }
12354
12355    #[test]
12356    fn cast_scalar_coercion_rules_6a83t() {
12357        let mut state: u64 = 0x5a17_c0de_1234_abcd;
12358        let mut next = || {
12359            state = state
12360                .wrapping_mul(6_364_136_223_846_793_005)
12361                .wrapping_add(1_442_695_040_888_963_407);
12362            (state >> 33) as u32
12363        };
12364
12365        for _ in 0..4000u32 {
12366            let n = (next() % 21) as i64 - 10; // -10..=10, incl 0
12367            let b = next() % 2 == 0;
12368            let f = f64::from((next() % 41) as i32 - 20) / 4.0; // finite, incl 0.0
12369
12370            let i = Scalar::Int64(n);
12371            let bo = Scalar::Bool(b);
12372            let fl = Scalar::Float64(f);
12373
12374            // Identity casts.
12375            assert_eq!(cast_scalar(&i, DType::Int64), Ok(i.clone()));
12376            assert_eq!(cast_scalar(&bo, DType::Bool), Ok(bo.clone()));
12377            assert_eq!(cast_scalar(&fl, DType::Float64), Ok(fl.clone()));
12378
12379            // Representation-preserving nullable identities.
12380            assert_eq!(cast_scalar(&i, DType::Int64Nullable), Ok(i.clone()));
12381            assert_eq!(cast_scalar(&bo, DType::BoolNullable), Ok(bo.clone()));
12382
12383            // Int64 coercions.
12384            assert_eq!(cast_scalar(&i, DType::Bool), Ok(Scalar::Bool(n != 0)));
12385            assert_eq!(
12386                cast_scalar(&i, DType::Float64),
12387                Ok(Scalar::Float64(n as f64))
12388            );
12389
12390            // Bool coercions.
12391            assert_eq!(
12392                cast_scalar(&bo, DType::Int64),
12393                Ok(Scalar::Int64(i64::from(b)))
12394            );
12395            assert_eq!(
12396                cast_scalar(&bo, DType::Float64),
12397                Ok(Scalar::Float64(if b { 1.0 } else { 0.0 }))
12398            );
12399
12400            // Finite Float64 -> Int64 truncates toward zero (x as i64).
12401            assert_eq!(cast_scalar(&fl, DType::Int64), Ok(Scalar::Int64(f as i64)));
12402        }
12403    }
12404
12405    /// br-frankenpandas-esjjy / fd90.182: ergonomic From impls for Scalar.
12406    #[test]
12407    fn scalar_from_primitive_types() {
12408        // Each primitive maps to its canonical Scalar variant.
12409        assert_eq!(Scalar::from(true), Scalar::Bool(true));
12410        assert_eq!(Scalar::from(42i64), Scalar::Int64(42));
12411        assert_eq!(Scalar::from(1.5f64), Scalar::Float64(1.5));
12412        assert_eq!(Scalar::from("hi"), Scalar::Utf8("hi".to_owned()));
12413        assert_eq!(
12414            Scalar::from(String::from("world")),
12415            Scalar::Utf8("world".to_owned())
12416        );
12417
12418        // .into() works in mixed-type Vec<Scalar> contexts (the README's
12419        // case_when example pattern, and what fd90.181 needed for apply_row
12420        // closures).
12421        let mixed: Vec<Scalar> = vec![1i64.into(), 2.0f64.into(), "three".into()];
12422        assert_eq!(mixed[0], Scalar::Int64(1));
12423        assert_eq!(mixed[1], Scalar::Float64(2.0));
12424        assert_eq!(mixed[2], Scalar::Utf8("three".to_owned()));
12425    }
12426
12427    #[test]
12428    fn dtype_inference_routes_bool_numeric_mix_to_object_bucket_rh1od() {
12429        // Was `dtype_inference_coerces_numeric_values` (Bool+Int64+Float64 ->
12430        // Float64). br-frankenpandas-rh1od, MEASURED live pandas 2.2.3:
12431        // pd.Series([True, 7, 3.5]) constructs OBJECT — no pandas constructor
12432        // path produces the numpy common-type Float64 here.
12433        let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Float64(3.5)];
12434        assert_eq!(
12435            infer_dtype(&values).expect("dtype should infer"),
12436            DType::Utf8
12437        );
12438    }
12439
12440    #[test]
12441    fn interval_scalar_has_dtype_storage_and_unique_semantics_5g5uj() {
12442        let left = Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right));
12443        let right = Scalar::Interval(Interval::new(1.0, 2.0, IntervalClosed::Right));
12444        assert_eq!(left.dtype(), DType::Interval);
12445        assert!(!left.is_missing());
12446        assert_eq!(
12447            infer_dtype(&[left.clone(), right.clone()]).expect("interval dtype"),
12448            DType::Interval
12449        );
12450        assert_eq!(
12451            common_dtype(DType::Interval, DType::Interval).expect("same interval dtype"),
12452            DType::Interval
12453        );
12454        assert_eq!(
12455            cast_scalar(&Scalar::Null(NullKind::Null), DType::Interval).expect("missing casts"),
12456            Scalar::Null(NullKind::Null)
12457        );
12458        assert_eq!(
12459            cast_scalar(&left, DType::Utf8).expect("interval string cast"),
12460            Scalar::Utf8("(0.0, 1.0]".to_owned())
12461        );
12462        assert_eq!(
12463            super::nannunique(&[left.clone(), right, left, Scalar::Null(NullKind::Null)]),
12464            Scalar::Int64(2)
12465        );
12466    }
12467
12468    #[test]
12469    fn cast_scalar_parses_temporal_extension_strings_avm08() {
12470        let expected_nanos = super::Timestamp::parse("2024-01-15T10:30:45")
12471            .expect("timestamp parse")
12472            .nanos;
12473        assert_eq!(
12474            cast_scalar(
12475                &Scalar::Utf8("2024-01-15T10:30:45".to_owned()),
12476                DType::datetime64_naive()
12477            )
12478            .expect("datetime cast"),
12479            Scalar::Datetime64(expected_nanos)
12480        );
12481        assert_eq!(
12482            cast_scalar(&Scalar::Utf8("2024Q1".to_owned()), DType::Period).expect("period cast"),
12483            Scalar::Period(Period::new(216, PeriodFreq::QUARTERLY))
12484        );
12485        assert_eq!(
12486            cast_scalar(&Scalar::Utf8("(0, 1]".to_owned()), DType::Interval)
12487                .expect("interval cast"),
12488            Scalar::Interval(Interval::new(0.0, 1.0, IntervalClosed::Right))
12489        );
12490    }
12491
12492    #[test]
12493    fn missing_values_get_target_missing_marker() {
12494        let missing = Scalar::Null(NullKind::Null);
12495        let cast = cast_scalar(&missing, DType::Float64).expect("missing casts");
12496        assert_eq!(cast, Scalar::Null(NullKind::NaN));
12497    }
12498
12499    #[test]
12500    fn cast_scalar_to_utf8_uses_pandas_string_spellings() {
12501        let cases = [
12502            (Scalar::Bool(true), "True"),
12503            (Scalar::Bool(false), "False"),
12504            (Scalar::Int64(-7), "-7"),
12505            (Scalar::Float64(1.0), "1.0"),
12506            (Scalar::Float64(1.5), "1.5"),
12507            (Scalar::Float64(f64::NAN), "nan"),
12508            (Scalar::Null(NullKind::Null), "None"),
12509            (Scalar::Null(NullKind::NaN), "nan"),
12510            (Scalar::Null(NullKind::NaT), "NaT"),
12511        ];
12512
12513        for (value, expected) in cases {
12514            assert_eq!(
12515                cast_scalar(&value, DType::Utf8).expect("cast"),
12516                Scalar::Utf8(expected.to_owned())
12517            );
12518        }
12519    }
12520
12521    #[test]
12522    fn semantic_eq_treats_nan_as_equal() {
12523        let left = Scalar::Float64(f64::NAN);
12524        let right = Scalar::Null(NullKind::NaN);
12525        assert!(left.semantic_eq(&right));
12526    }
12527
12528    #[test]
12529    fn semantic_eq_treats_nan_as_missing_null() {
12530        let left = Scalar::Float64(f64::NAN);
12531        let right = Scalar::Null(NullKind::Null);
12532        assert!(left.semantic_eq(&right));
12533    }
12534
12535    /// A DTYPE-SENTINEL missing equals a `Null` marker, for every dtype that
12536    /// has one.
12537    ///
12538    /// `missing_for_dtype` DEFINES the canonical missing for Timedelta64 as
12539    /// `Timedelta64(NAT)`, for Datetime64 as `Datetime64(NAT)` and for Period as
12540    /// ordinal `i64::MIN`, and `is_missing()` agrees — but `semantic_eq` used to
12541    /// unify only the `Null`/NaN flavours, so an oracle's `null` for pandas' NaT
12542    /// could never match FP's sentinel. Observed on
12543    /// `fp_p2d_021_series_to_timedelta_negative_null_hardened`, where the
12544    /// fixture pinned the raw `-9223372036854775808` as though it were data.
12545    ///
12546    /// THE NEGATIVE CASES ARE THE POINT — "both missing" must not become "any
12547    /// sentinel matches anything":
12548    /// - a NaT sentinel must NOT equal a PRESENT timedelta;
12549    /// - two DIFFERENT present timedeltas must stay unequal;
12550    /// - Period and Datetime64 must unify too, or the fix is Timedelta-only.
12551    ///
12552    /// (br-frankenpandas-xwxci)
12553    #[test]
12554    fn semantic_eq_unifies_dtype_sentinel_missing_with_null_xwxci() {
12555        for sentinel in [
12556            Scalar::Timedelta64(Timedelta::NAT),
12557            Scalar::Datetime64(Timestamp::NAT),
12558            Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)),
12559        ] {
12560            assert!(sentinel.is_missing(), "{sentinel:?} must report missing");
12561            for marker in [
12562                Scalar::Null(NullKind::Null),
12563                Scalar::Null(NullKind::NaN),
12564                Scalar::Null(NullKind::NaT),
12565            ] {
12566                assert!(
12567                    sentinel.semantic_eq(&marker),
12568                    "{sentinel:?} vs {marker:?} are both missing"
12569                );
12570                assert!(marker.semantic_eq(&sentinel), "and symmetrically");
12571            }
12572        }
12573
12574        // NOT a blanket match: a sentinel differs from a PRESENT value.
12575        let present = Scalar::Timedelta64(-60);
12576        assert!(!Scalar::Timedelta64(Timedelta::NAT).semantic_eq(&present));
12577        assert!(!present.semantic_eq(&Scalar::Null(NullKind::Null)));
12578        // And two distinct present values stay distinct.
12579        assert!(!present.semantic_eq(&Scalar::Timedelta64(-61)));
12580    }
12581
12582    #[test]
12583    fn common_dtype_rejects_string_numeric_mix() {
12584        let err = common_dtype(DType::Utf8, DType::Int64).expect_err("must fail");
12585        assert_eq!(
12586            err.to_string(),
12587            "dtype coercion from Utf8 to Int64 has no compatible common type"
12588        );
12589        let err = common_dtype(DType::Float64, DType::Utf8).expect_err("must fail");
12590        assert_eq!(
12591            err.to_string(),
12592            "dtype coercion from Float64 to Utf8 has no compatible common type"
12593        );
12594    }
12595
12596    #[test]
12597    fn sparse_dtype_normalizes_fill_value_to_value_dtype() {
12598        let dtype = SparseDType::new(DType::Float64, Scalar::Int64(0)).expect("fill should cast");
12599
12600        assert_eq!(dtype.value_dtype, DType::Float64);
12601        assert_eq!(dtype.fill_value, Scalar::Float64(0.0));
12602    }
12603
12604    #[test]
12605    fn sparse_dtype_rejects_sparse_value_dtype() {
12606        let err = SparseDType::new(DType::Sparse, Scalar::Int64(0)).expect_err("must reject");
12607
12608        assert_eq!(err.to_string(), "sparse value dtype cannot be Sparse");
12609    }
12610
12611    #[test]
12612    fn common_dtype_rejects_sparse_dense_mix() {
12613        let err = common_dtype(DType::Sparse, DType::Int64).expect_err("must fail");
12614
12615        assert_eq!(
12616            err.to_string(),
12617            "dtype coercion from Sparse to Int64 has no compatible common type"
12618        );
12619    }
12620
12621    // ── Nullable Int64/Bool dtype tests (br-frankenpandas-rg8ys.6.4) ────
12622
12623    #[test]
12624    fn nullable_int64_promotion_matrix() {
12625        // Int64 + Int64Nullable -> Int64Nullable (nullable absorbs)
12626        assert_eq!(
12627            common_dtype(DType::Int64, DType::Int64Nullable).unwrap(),
12628            DType::Int64Nullable
12629        );
12630        assert_eq!(
12631            common_dtype(DType::Int64Nullable, DType::Int64).unwrap(),
12632            DType::Int64Nullable
12633        );
12634
12635        // Int64Nullable + Float64 -> Float64Nullable. The old comment here said
12636        // "float always wins"; that is half right. The float wins, but the
12637        // NULLABLE flavour of it does — MEASURED, live pandas 2.2.3:
12638        //   pd.Series([1,None],dtype="Int64") + pd.Series([1.5,2.5]) -> Float64
12639        // where that Float64 is the extension dtype (missing = pd.NA), not
12640        // numpy float64 (missing = NaN). (br-frankenpandas-qkqfb)
12641        assert_eq!(
12642            common_dtype(DType::Int64Nullable, DType::Float64).unwrap(),
12643            DType::Float64Nullable
12644        );
12645        assert_eq!(
12646            common_dtype(DType::Float64, DType::Int64Nullable).unwrap(),
12647            DType::Float64Nullable
12648        );
12649
12650        // Int64Nullable + Int64Nullable -> Int64Nullable
12651        assert_eq!(
12652            common_dtype(DType::Int64Nullable, DType::Int64Nullable).unwrap(),
12653            DType::Int64Nullable
12654        );
12655
12656        // Bool + Int64Nullable -> Int64Nullable
12657        assert_eq!(
12658            common_dtype(DType::Bool, DType::Int64Nullable).unwrap(),
12659            DType::Int64Nullable
12660        );
12661
12662        // BoolNullable + Int64 -> Int64Nullable
12663        assert_eq!(
12664            common_dtype(DType::BoolNullable, DType::Int64).unwrap(),
12665            DType::Int64Nullable
12666        );
12667    }
12668
12669    #[test]
12670    fn nullable_bool_promotion_matrix() {
12671        // Bool + BoolNullable -> BoolNullable
12672        assert_eq!(
12673            common_dtype(DType::Bool, DType::BoolNullable).unwrap(),
12674            DType::BoolNullable
12675        );
12676        assert_eq!(
12677            common_dtype(DType::BoolNullable, DType::Bool).unwrap(),
12678            DType::BoolNullable
12679        );
12680
12681        // BoolNullable + Float64 -> Float64Nullable. MEASURED, live pandas 2.2.3:
12682        //   pd.Series([True,None],dtype="boolean") + pd.Series([1.5,2.5,3.5])
12683        //     -> Float64   (extension)
12684        // This arm moves together with the Int64Nullable one in
12685        // nullable_int64_promotion_matrix; flipping either alone breaks lattice
12686        // associativity. (br-frankenpandas-qkqfb)
12687        assert_eq!(
12688            common_dtype(DType::BoolNullable, DType::Float64).unwrap(),
12689            DType::Float64Nullable
12690        );
12691
12692        // CONTROL: the all-numpy pair is untouched and stays on the numpy side.
12693        //   pd.Series([True,False],dtype="bool") + pd.Series([1.5,2.5]) -> float64
12694        assert_eq!(
12695            common_dtype(DType::Bool, DType::Float64).unwrap(),
12696            DType::Float64
12697        );
12698    }
12699
12700    #[test]
12701    fn dtype_is_nullable_helper() {
12702        assert!(DType::Int64Nullable.is_nullable());
12703        assert!(DType::BoolNullable.is_nullable());
12704        assert!(!DType::Int64.is_nullable());
12705        assert!(!DType::Bool.is_nullable());
12706        assert!(!DType::Float64.is_nullable());
12707        assert!(!DType::Utf8.is_nullable());
12708    }
12709
12710    #[test]
12711    fn dtype_to_nullable_conversions() {
12712        assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
12713        assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
12714        // ⚠ THIS LINE WAS RED ON main SINCE fa6caee91 AND NOBODY SAW IT.
12715        // It used to read `Float64.to_nullable() == Float64  // unchanged`,
12716        // which was true only while FP had no nullable float at all. fa6caee91
12717        // (br-frankenpandas-qkqfb slice 1) added DType::Float64Nullable and
12718        // pointed to_nullable at it, but that commit was gated with
12719        // `cargo check --all-targets` plus a NAME-FILTERED test run, so this
12720        // pre-existing test was never executed and the break went unnoticed.
12721        // Float64's nullable flavour IS Float64Nullable — that is the dtype's
12722        // entire reason to exist — so the assertion is what was stale.
12723        assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
12724        assert_eq!(
12725            DType::Float64Nullable.to_nullable(),
12726            DType::Float64Nullable,
12727            "idempotent: already nullable"
12728        );
12729        assert_eq!(DType::Int64Nullable.to_nullable(), DType::Int64Nullable);
12730    }
12731
12732    #[test]
12733    fn dtype_to_non_nullable_conversions() {
12734        assert_eq!(DType::Int64Nullable.to_non_nullable(), DType::Int64);
12735        assert_eq!(DType::BoolNullable.to_non_nullable(), DType::Bool);
12736        assert_eq!(DType::Int64.to_non_nullable(), DType::Int64); // unchanged
12737        assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
12738    }
12739
12740    #[test]
12741    fn nullable_dtype_name_reports_pandas_style() {
12742        assert_eq!(DType::Int64.name(), "int64");
12743        assert_eq!(DType::Int64Nullable.name(), "Int64"); // capital I
12744        assert_eq!(DType::Bool.name(), "bool");
12745        assert_eq!(DType::BoolNullable.name(), "boolean");
12746    }
12747
12748    #[test]
12749    fn cast_scalar_int64_nullable_identity() {
12750        let val = Scalar::Int64(42);
12751        // Int64 -> Int64Nullable is identity (no actual conversion)
12752        let result = cast_scalar(&val, DType::Int64Nullable).unwrap();
12753        assert_eq!(result, Scalar::Int64(42));
12754
12755        // Int64Nullable -> Int64 is also identity
12756        let result2 = cast_scalar(&val, DType::Int64).unwrap();
12757        assert_eq!(result2, Scalar::Int64(42));
12758    }
12759
12760    #[test]
12761    fn cast_float_to_utf8_uses_pandas_str_float_with_scientific() {
12762        // pandas astype(str) of floats == Python str(float): whole -> ".0",
12763        // shortest round-trip decimals, scientific (e+NN/e-NN) for large/small,
12764        // inf -> "inf", NaN -> "nan". Verified vs live pandas 2.2.3. (Previously
12765        // large/small lost scientific notation, e.g. 1e16 -> "10000000000000000.0".)
12766        let cases: &[(f64, &str)] = &[
12767            (1.0, "1.0"),
12768            (2.5, "2.5"),
12769            (100.0, "100.0"),
12770            (0.1, "0.1"),
12771            (0.0001, "0.0001"),
12772            (1e16, "1e+16"),
12773            (1e20, "1e+20"),
12774            (1e-5, "1e-05"),
12775            (1e-7, "1e-07"),
12776            (f64::INFINITY, "inf"),
12777            (f64::NEG_INFINITY, "-inf"),
12778        ];
12779        for (v, expected) in cases {
12780            assert_eq!(
12781                cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
12782                Scalar::Utf8((*expected).to_owned()),
12783                "float {v} -> str"
12784            );
12785        }
12786    }
12787
12788    fn float_to_string_for_astype_former(value: f64) -> String {
12789        if value.is_nan() {
12790            return "nan".to_owned();
12791        }
12792        if value.is_infinite() {
12793            return value.to_string();
12794        }
12795        let rendered = format!("{value:?}");
12796        match rendered.split_once('e') {
12797            None => rendered,
12798            Some((mantissa, exponent)) => {
12799                let (sign, digits) = match exponent.strip_prefix('-') {
12800                    Some(digits) => ('-', digits),
12801                    None => ('+', exponent.strip_prefix('+').unwrap_or(exponent)),
12802                };
12803                format!("{mantissa}e{sign}{digits:0>2}")
12804            }
12805        }
12806    }
12807
12808    fn scientific_astype_values(len: usize) -> Vec<f64> {
12809        const EXPONENTS: [i32; 16] = [
12810            -300, -200, -100, -50, -10, -7, -6, -5, 16, 17, 20, 50, 100, 200, 300, 307,
12811        ];
12812        (0..len)
12813            .map(|position| {
12814                let mantissa = 1.0 + (position % 997) as f64 / 997.0;
12815                let magnitude = mantissa * 10.0_f64.powi(EXPONENTS[position % EXPONENTS.len()]);
12816                if position.is_multiple_of(2) {
12817                    magnitude
12818                } else {
12819                    -magnitude
12820                }
12821            })
12822            .collect()
12823    }
12824
12825    #[test]
12826    fn float_to_string_for_astype_in_place_matches_former() {
12827        let fixed = [
12828            f64::NAN,
12829            f64::INFINITY,
12830            f64::NEG_INFINITY,
12831            0.0,
12832            -0.0,
12833            f64::MIN_POSITIVE,
12834            f64::MAX,
12835            f64::MIN,
12836            1e16,
12837            -1e16,
12838            1e-5,
12839            -1e-5,
12840            1.234_567_890_123_456_8e20,
12841            -9.876_543_210_987_654e-123,
12842        ];
12843        for value in fixed.into_iter().chain(scientific_astype_values(16_384)) {
12844            assert_eq!(
12845                super::float_to_string_for_astype(value),
12846                float_to_string_for_astype_former(value),
12847                "value={value:?}"
12848            );
12849        }
12850    }
12851
12852    #[test]
12853    #[ignore = "foreground performance probe"]
12854    fn float_to_string_for_astype_in_place_ab() {
12855        use std::time::Instant;
12856
12857        const VALUES: usize = 16_384;
12858        const SAMPLES: usize = 10;
12859        let values = scientific_astype_values(VALUES);
12860        for &value in &values {
12861            let former = float_to_string_for_astype_former(value);
12862            assert!(former.contains('e'), "benchmark value must be scientific");
12863            assert_eq!(super::float_to_string_for_astype(value), former);
12864        }
12865
12866        for _ in 0..2 {
12867            for &value in &values {
12868                std::hint::black_box(float_to_string_for_astype_former(value));
12869                std::hint::black_box(super::float_to_string_for_astype(value));
12870            }
12871        }
12872
12873        let mut former_ns = Vec::with_capacity(SAMPLES);
12874        let mut public_ns = Vec::with_capacity(SAMPLES);
12875        for sample in 0..SAMPLES {
12876            let run = |formatter: fn(f64) -> String| {
12877                let started = Instant::now();
12878                for &value in std::hint::black_box(&values) {
12879                    std::hint::black_box(formatter(std::hint::black_box(value)));
12880                }
12881                started.elapsed().as_nanos()
12882            };
12883            if sample.is_multiple_of(2) {
12884                former_ns.push(run(float_to_string_for_astype_former));
12885                public_ns.push(run(super::float_to_string_for_astype));
12886            } else {
12887                public_ns.push(run(super::float_to_string_for_astype));
12888                former_ns.push(run(float_to_string_for_astype_former));
12889            }
12890        }
12891
12892        former_ns.sort_unstable();
12893        public_ns.sort_unstable();
12894        let former_p50 = former_ns[SAMPLES / 2];
12895        let public_p50 = public_ns[SAMPLES / 2];
12896        println!(
12897            "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:?}",
12898            former_p50 as f64 / public_p50 as f64
12899        );
12900    }
12901
12902    #[test]
12903    fn cast_float_to_utf8_threshold_boundaries_match_python() {
12904        // Python str(float) switches to scientific notation only at |x| >= 1e16
12905        // or |x| < 1e-4. Values JUST INSIDE those bounds must stay decimal — a
12906        // formatter that switches to sci early (or late) diverges. All expected
12907        // values verified against Python 3 str()/repr (== pandas astype(str)).
12908        let cases: &[(f64, &str)] = &[
12909            (1e15, "1000000000000000.0"),
12910            (9_999_999_999_999_998.0, "9999999999999998.0"),
12911            (1_234_567_890_123_456.0, "1234567890123456.0"),
12912            (123_456_789_012_345.0, "123456789012345.0"),
12913            (12_345_678_901_234_567.0, "1.2345678901234568e+16"),
12914            (1e16, "1e+16"),
12915            (1.5e16, "1.5e+16"),
12916            (1e17, "1e+17"),
12917            (1e-4, "0.0001"),
12918            (5e-5, "5e-05"),
12919            (-1e15, "-1000000000000000.0"),
12920            (-1e16, "-1e+16"),
12921            (-1e-5, "-1e-05"),
12922        ];
12923        for (v, expected) in cases {
12924            assert_eq!(
12925                cast_scalar(&Scalar::Float64(*v), DType::Utf8).unwrap(),
12926                Scalar::Utf8((*expected).to_owned()),
12927                "float {v} -> str"
12928            );
12929        }
12930    }
12931
12932    #[test]
12933    fn cast_to_bool_uses_pandas_nonzero_truthiness() {
12934        // pandas astype(bool): zero -> False, any nonzero -> True (not just 0/1),
12935        // -0.0 -> False, and NaN -> True (numpy bool(nan), br-cyi4h). Verified vs
12936        // live pandas 2.2.3.
12937        let cases_int: &[(i64, bool)] = &[(0, false), (1, true), (-3, true), (2, true)];
12938        for (v, expected) in cases_int {
12939            assert_eq!(
12940                cast_scalar(&Scalar::Int64(*v), DType::Bool).unwrap(),
12941                Scalar::Bool(*expected),
12942                "int {v} -> bool"
12943            );
12944        }
12945        let cases_float: &[(f64, bool)] = &[
12946            (0.0, false),
12947            (-0.0, false),
12948            (0.1, true),
12949            (2.5, true),
12950            (1.0, true),
12951            // pandas astype(bool): NaN is truthy -> True (numpy bool). br-cyi4h.
12952            (f64::NAN, true),
12953        ];
12954        for (v, expected) in cases_float {
12955            assert_eq!(
12956                cast_scalar(&Scalar::Float64(*v), DType::Bool).unwrap(),
12957                Scalar::Bool(*expected),
12958                "float {v} -> bool"
12959            );
12960        }
12961    }
12962
12963    #[test]
12964    fn nullable_dtype_is_extension() {
12965        assert!(DType::Int64Nullable.is_extension());
12966        assert!(DType::BoolNullable.is_extension());
12967        assert!(!DType::Int64.is_extension());
12968        assert!(!DType::Bool.is_extension());
12969    }
12970
12971    #[test]
12972    fn infer_dtype_preserves_string_numeric_mix_as_utf8_bucket() {
12973        let values = vec![Scalar::Utf8("x".into()), Scalar::Int64(7)];
12974        assert_eq!(
12975            infer_dtype(&values).expect("dtype should infer"),
12976            DType::Utf8
12977        );
12978    }
12979
12980    #[test]
12981    fn infer_dtype_routes_bool_numeric_mix_to_utf8_object_bucket_rh1od() {
12982        // br-frankenpandas-rh1od, MEASURED live pandas 2.2.3: a bool mixed
12983        // with any numeric scalar constructs OBJECT ([True, 2] -> object,
12984        // payloads preserved); numpy's bool<int common-type never fires at
12985        // the constructor. Discriminating: before the change this inferred
12986        // Int64 and coerced True -> 1.
12987        let values = vec![Scalar::Bool(true), Scalar::Int64(7), Scalar::Bool(false)];
12988        assert_eq!(
12989            infer_dtype(&values).expect("dtype should infer"),
12990            DType::Utf8
12991        );
12992        let with_float = vec![Scalar::Int64(1), Scalar::Float64(2.5), Scalar::Bool(true)];
12993        assert_eq!(
12994            infer_dtype(&with_float).expect("dtype should infer"),
12995            DType::Utf8
12996        );
12997        let with_null = vec![
12998            Scalar::Bool(true),
12999            Scalar::Null(NullKind::Null),
13000            Scalar::Int64(2),
13001        ];
13002        assert_eq!(
13003            infer_dtype(&with_null).expect("dtype should infer"),
13004            DType::Utf8
13005        );
13006    }
13007
13008    #[test]
13009    fn infer_dtype_keeps_nonmixed_bool_and_numeric_paths_rh1od() {
13010        // Pure bool stays bool; numeric-only mixes keep the common_dtype
13011        // lattice (int+float -> float64) — the object bucket is ONLY for the
13012        // cross-family mix.
13013        assert_eq!(
13014            infer_dtype(&[Scalar::Bool(true), Scalar::Bool(false)]).expect("dtype should infer"),
13015            DType::Bool
13016        );
13017        assert_eq!(
13018            infer_dtype(&[Scalar::Int64(1), Scalar::Float64(2.5)]).expect("dtype should infer"),
13019            DType::Float64
13020        );
13021    }
13022
13023    // ── Scalar missingness methods ─────────────────────────────────────
13024
13025    #[test]
13026    fn is_null_detects_explicit_nulls() {
13027        assert!(Scalar::Null(NullKind::Null).is_null());
13028        assert!(Scalar::Null(NullKind::NaN).is_null());
13029        assert!(!Scalar::Int64(42).is_null());
13030        assert!(!Scalar::Float64(f64::NAN).is_null());
13031    }
13032
13033    #[test]
13034    fn is_na_matches_is_missing() {
13035        let vals = vec![
13036            Scalar::Null(NullKind::Null),
13037            Scalar::Float64(f64::NAN),
13038            Scalar::Int64(0),
13039            Scalar::Bool(false),
13040        ];
13041        for v in &vals {
13042            assert_eq!(v.is_na(), v.is_missing());
13043        }
13044    }
13045
13046    #[test]
13047    fn coalesce_picks_first_non_missing() {
13048        let null = Scalar::Null(NullKind::Null);
13049        let fill = Scalar::Int64(99);
13050        assert_eq!(null.coalesce(&fill), fill);
13051        assert_eq!(fill.coalesce(&null), fill);
13052    }
13053
13054    // ── Missingness utilities ──────────────────────────────────────────
13055
13056    #[test]
13057    fn isna_notna_complement() {
13058        let vals = vec![
13059            Scalar::Int64(1),
13060            Scalar::Null(NullKind::Null),
13061            Scalar::Float64(f64::NAN),
13062            Scalar::Float64(3.0),
13063        ];
13064        let na = super::isna(&vals);
13065        let not = super::notna(&vals);
13066        assert_eq!(na, vec![false, true, true, false]);
13067        for (a, b) in na.iter().zip(not.iter()) {
13068            assert_ne!(a, b);
13069        }
13070    }
13071
13072    #[test]
13073    fn count_na_counts_missing() {
13074        let vals = vec![
13075            Scalar::Int64(1),
13076            Scalar::Null(NullKind::Null),
13077            Scalar::Float64(f64::NAN),
13078        ];
13079        assert_eq!(super::count_na(&vals), 2);
13080    }
13081
13082    #[test]
13083    fn fill_na_replaces_missing() {
13084        let vals = vec![
13085            Scalar::Int64(1),
13086            Scalar::Null(NullKind::Null),
13087            Scalar::Float64(f64::NAN),
13088            Scalar::Int64(4),
13089        ];
13090        let filled = super::fill_na(&vals, &Scalar::Int64(0));
13091        assert_eq!(filled[0], Scalar::Int64(1));
13092        assert_eq!(filled[1], Scalar::Int64(0));
13093        assert_eq!(filled[2], Scalar::Int64(0));
13094        assert_eq!(filled[3], Scalar::Int64(4));
13095    }
13096
13097    #[test]
13098    fn dropna_removes_missing() {
13099        let vals = vec![
13100            Scalar::Int64(1),
13101            Scalar::Null(NullKind::Null),
13102            Scalar::Int64(3),
13103            Scalar::Float64(f64::NAN),
13104        ];
13105        let kept = super::dropna(&vals);
13106        assert_eq!(kept.len(), 2);
13107        assert_eq!(kept[0], Scalar::Int64(1));
13108        assert_eq!(kept[1], Scalar::Int64(3));
13109    }
13110
13111    #[test]
13112    fn null_helpers_match_scalar_oracle_imt0c() {
13113        // Differential vs independent scalar null-helper oracle
13114        // (br-frankenpandas-imt0c). Seeded LCG, no mocks.
13115        fn next(seed: &mut u64) -> u64 {
13116            *seed = seed
13117                .wrapping_mul(3202034522624059733)
13118                .wrapping_add(4354685564936845319);
13119            *seed
13120        }
13121
13122        fn assert_null_helpers(case: usize, values: &[Scalar], fill: &Scalar) {
13123            let expected_missing = values.iter().filter(|value| value.is_missing()).count();
13124            let expected_dropped = values
13125                .iter()
13126                .filter(|value| !value.is_missing())
13127                .cloned()
13128                .collect::<Vec<_>>();
13129            let expected_filled = values
13130                .iter()
13131                .map(|value| {
13132                    if value.is_missing() {
13133                        fill.clone()
13134                    } else {
13135                        value.clone()
13136                    }
13137                })
13138                .collect::<Vec<_>>();
13139
13140            assert_eq!(
13141                super::count_na(values),
13142                expected_missing,
13143                "case={case}: count_na mismatch for {values:?}"
13144            );
13145
13146            let dropped = super::dropna(values);
13147            assert_eq!(
13148                dropped.len(),
13149                expected_dropped.len(),
13150                "case={case}: dropna length mismatch for {values:?}"
13151            );
13152            for (pos, (actual, expected)) in dropped.iter().zip(expected_dropped.iter()).enumerate()
13153            {
13154                assert!(
13155                    actual.semantic_eq(expected),
13156                    "case={case} pos={pos}: dropna expected {expected:?}, got {actual:?}"
13157                );
13158            }
13159
13160            let filled = super::fill_na(values, fill);
13161            assert_eq!(
13162                filled.len(),
13163                expected_filled.len(),
13164                "case={case}: fill_na length mismatch for {values:?}"
13165            );
13166            for (pos, (actual, expected)) in filled.iter().zip(expected_filled.iter()).enumerate() {
13167                assert!(
13168                    actual.semantic_eq(expected),
13169                    "case={case} pos={pos}: fill_na expected {expected:?}, got {actual:?}"
13170                );
13171            }
13172        }
13173
13174        let all_missing = [
13175            Scalar::Null(NullKind::Null),
13176            Scalar::Null(NullKind::NaN),
13177            Scalar::Float64(f64::NAN),
13178            Scalar::Timedelta64(i64::MIN),
13179        ];
13180        assert_null_helpers(usize::MAX, &all_missing, &Scalar::Utf8("filled".into()));
13181
13182        let mut seed = 0xc011_a7ed_0b5e_1a55_u64;
13183        for case in 0..260 {
13184            let len = (next(&mut seed) % 83 + 1) as usize;
13185            let mut values = Vec::with_capacity(len);
13186            for pos in 0..len {
13187                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
13188                values.push(match next(&mut seed) % 11 {
13189                    0 => Scalar::Null(NullKind::Null),
13190                    1 => Scalar::Null(NullKind::NaN),
13191                    2 => Scalar::Float64(f64::NAN),
13192                    3 => Scalar::Timedelta64(i64::MIN),
13193                    4 => Scalar::Bool(raw & 1 == 0),
13194                    5 => Scalar::Int64(raw),
13195                    6 => Scalar::Float64(raw as f64 / 37.0),
13196                    7 => Scalar::Float64(if raw & 1 == 0 { 0.0 } else { -0.0 }),
13197                    8 => Scalar::Utf8(format!("null_helper_{case}_{pos}")),
13198                    9 => Scalar::Utf8(String::new()),
13199                    _ => Scalar::Timedelta64(raw),
13200                });
13201            }
13202
13203            let fill = match case % 5 {
13204                0 => Scalar::Bool(true),
13205                1 => Scalar::Int64(-777),
13206                2 => Scalar::Float64(12.5),
13207                3 => Scalar::Utf8("filled".into()),
13208                _ => Scalar::Timedelta64(123_456),
13209            };
13210            assert_null_helpers(case, &values, &fill);
13211        }
13212    }
13213
13214    // ── Nanops ─────────────────────────────────────────────────────────
13215
13216    #[test]
13217    fn nansum_skips_nulls() {
13218        let vals = vec![
13219            Scalar::Float64(1.0),
13220            Scalar::Null(NullKind::Null),
13221            Scalar::Float64(2.0),
13222            Scalar::Float64(f64::NAN),
13223            Scalar::Int64(7),
13224        ];
13225        assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
13226    }
13227
13228    #[test]
13229    fn nansum_empty_returns_zero() {
13230        assert_eq!(super::nansum(&[]), Scalar::Float64(0.0));
13231    }
13232
13233    #[test]
13234    fn nansum_nanmean_match_numeric_and_timedelta_oracle_1xmi7() {
13235        // Differential vs independent sum/mean oracles
13236        // (br-frankenpandas-1xmi7). Seeded LCG, no mocks.
13237        fn next(seed: &mut u64) -> u64 {
13238            *seed = seed
13239                .wrapping_mul(6364136223846793005)
13240                .wrapping_add(1442695040888963407);
13241            *seed
13242        }
13243
13244        fn expected_numeric(values: &[Scalar]) -> (Scalar, Scalar) {
13245            let mut sum = 0.0;
13246            let mut count = 0usize;
13247            for value in values {
13248                if value.is_missing() {
13249                    continue;
13250                }
13251                if let Ok(value) = value.to_f64() {
13252                    sum += value;
13253                    count += 1;
13254                }
13255            }
13256            let mean = if count == 0 {
13257                Scalar::Null(NullKind::NaN)
13258            } else {
13259                Scalar::Float64(sum / count as f64)
13260            };
13261            (Scalar::Float64(sum), mean)
13262        }
13263
13264        fn expected_timedelta(values: &[Scalar]) -> (Scalar, Scalar) {
13265            let mut sum = 0_i128;
13266            let mut count = 0_i128;
13267            for value in values {
13268                if let Scalar::Timedelta64(ns) = value
13269                    && !value.is_missing()
13270                {
13271                    sum += i128::from(*ns);
13272                    count += 1;
13273                }
13274            }
13275            if count == 0 {
13276                return (Scalar::Timedelta64(0), Scalar::Timedelta64(Timedelta::NAT));
13277            }
13278            // br-frankenpandas-opz27: this reference oracle used to clamp, which
13279            // is the exact behaviour the production path was just fixed away
13280            // from. Keeping the clamp here would leave the oracle blessing a
13281            // contradicted rule (it only ever agreed because these inputs do
13282            // not overflow). Mirror the representable-range contract instead.
13283            (
13284                super::timedelta_ns_to_scalar(sum),
13285                super::timedelta_ns_to_scalar(sum / count),
13286            )
13287        }
13288
13289        fn assert_sum_mean(
13290            case: usize,
13291            family: &str,
13292            values: &[Scalar],
13293            expected_sum: Scalar,
13294            expected_mean: Scalar,
13295        ) {
13296            let actual_sum = super::nansum(values);
13297            let actual_mean = super::nanmean(values);
13298            assert!(
13299                actual_sum.semantic_eq(&expected_sum),
13300                "case={case} family={family}: expected sum {expected_sum:?}, got {actual_sum:?} for {values:?}"
13301            );
13302            assert!(
13303                actual_mean.semantic_eq(&expected_mean),
13304                "case={case} family={family}: expected mean {expected_mean:?}, got {actual_mean:?} for {values:?}"
13305            );
13306        }
13307
13308        let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
13309        let (sum, mean) = expected_numeric(&all_missing);
13310        assert_sum_mean(usize::MAX, "numeric_all_missing", &all_missing, sum, mean);
13311
13312        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
13313        let (sum, mean) = expected_timedelta(&td_all_missing);
13314        assert_sum_mean(
13315            usize::MAX - 1,
13316            "timedelta_all_missing",
13317            &td_all_missing,
13318            sum,
13319            mean,
13320        );
13321
13322        let mut seed = 0x511d_ed5a_7a11_1a55_u64;
13323        for case in 0..260 {
13324            let len = (next(&mut seed) % 89 + 1) as usize;
13325
13326            let mut numeric = Vec::with_capacity(len);
13327            numeric.push(Scalar::Int64(case as i64 - 130));
13328            for _ in 1..len {
13329                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
13330                numeric.push(match next(&mut seed) % 8 {
13331                    0 => Scalar::Null(NullKind::Null),
13332                    1 => Scalar::Null(NullKind::NaN),
13333                    2 => Scalar::Float64(f64::NAN),
13334                    3 => Scalar::Bool(raw & 1 == 0),
13335                    4 => Scalar::Int64(raw % 257),
13336                    5 => Scalar::Float64(raw as f64 / 67.0),
13337                    6 => Scalar::Float64(0.0),
13338                    _ => Scalar::Float64(-0.0),
13339                });
13340            }
13341            let (sum, mean) = expected_numeric(&numeric);
13342            assert_sum_mean(case, "numeric", &numeric, sum, mean);
13343
13344            let mut timedeltas = Vec::with_capacity(len);
13345            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
13346            for _ in 1..len {
13347                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
13348                timedeltas.push(match next(&mut seed) % 7 {
13349                    0 => Scalar::Null(NullKind::Null),
13350                    1 => Scalar::Timedelta64(i64::MIN),
13351                    _ => Scalar::Timedelta64(raw),
13352                });
13353            }
13354            let (sum, mean) = expected_timedelta(&timedeltas);
13355            assert_sum_mean(case, "timedelta", &timedeltas, sum, mean);
13356        }
13357    }
13358
13359    #[test]
13360    fn nannunique_merges_negative_zero_and_zero() {
13361        let vals = vec![
13362            Scalar::Float64(-0.0),
13363            Scalar::Float64(0.0),
13364            Scalar::Float64(1.0),
13365        ];
13366        assert_eq!(super::nannunique(&vals), Scalar::Int64(2));
13367    }
13368
13369    #[test]
13370    fn nannunique_matches_scalar_bucket_oracle_elvbg() {
13371        // Differential vs independent scalar unique-bucket oracle
13372        // (br-frankenpandas-elvbg). Seeded LCG, no mocks.
13373        fn next(seed: &mut u64) -> u64 {
13374            *seed = seed
13375                .wrapping_mul(2862933555777941757)
13376                .wrapping_add(3037000493);
13377            *seed
13378        }
13379
13380        fn same_bucket(left: &Scalar, right: &Scalar) -> bool {
13381            match (left, right) {
13382                (Scalar::Float64(left), Scalar::Float64(right)) => {
13383                    let left = if *left == 0.0 { 0.0 } else { *left };
13384                    let right = if *right == 0.0 { 0.0 } else { *right };
13385                    left.to_bits() == right.to_bits()
13386                }
13387                _ => left == right,
13388            }
13389        }
13390
13391        fn expected_nunique(values: &[Scalar]) -> i64 {
13392            let mut seen = Vec::<Scalar>::new();
13393            for value in values {
13394                if value.is_missing() {
13395                    continue;
13396                }
13397                if !seen.iter().any(|existing| same_bucket(existing, value)) {
13398                    seen.push(value.clone());
13399                }
13400            }
13401            seen.len() as i64
13402        }
13403
13404        fn assert_nannunique(case: usize, values: &[Scalar]) {
13405            assert_eq!(
13406                super::nannunique(values),
13407                Scalar::Int64(expected_nunique(values)),
13408                "case={case}: nannunique mismatch for {values:?}"
13409            );
13410        }
13411
13412        assert_nannunique(
13413            usize::MAX,
13414            &[
13415                Scalar::Float64(-0.0),
13416                Scalar::Float64(0.0),
13417                Scalar::Float64(f64::NAN),
13418                Scalar::Null(NullKind::Null),
13419                Scalar::Timedelta64(i64::MIN),
13420            ],
13421        );
13422
13423        let mut seed = 0x0e1b_60d0_b5e7_u64;
13424        for case in 0..320 {
13425            let len = (next(&mut seed) % 97 + 1) as usize;
13426            let mut values = Vec::with_capacity(len);
13427            for pos in 0..len {
13428                let raw = (next(&mut seed) % 1_001) as i64 - 500;
13429                values.push(match next(&mut seed) % 11 {
13430                    0 => Scalar::Null(NullKind::Null),
13431                    1 => Scalar::Null(NullKind::NaN),
13432                    2 => Scalar::Float64(f64::NAN),
13433                    3 => Scalar::Bool(raw & 1 == 0),
13434                    4 => Scalar::Int64(raw % 37),
13435                    5 => Scalar::Float64(raw as f64 / 19.0),
13436                    6 => Scalar::Float64(0.0),
13437                    7 => Scalar::Float64(-0.0),
13438                    8 => Scalar::Utf8(format!("uniq_{}", pos % 13)),
13439                    9 => Scalar::Utf8(String::new()),
13440                    _ => Scalar::Timedelta64(raw % 41),
13441                });
13442            }
13443            assert_nannunique(case, &values);
13444        }
13445    }
13446
13447    #[test]
13448    fn nanmean_basic() {
13449        let vals = vec![
13450            Scalar::Float64(2.0),
13451            Scalar::Null(NullKind::Null),
13452            Scalar::Float64(4.0),
13453        ];
13454        assert_eq!(super::nanmean(&vals), Scalar::Float64(3.0));
13455    }
13456
13457    #[test]
13458    fn nanmean_all_null_returns_nan() {
13459        let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
13460        assert!(super::nanmean(&vals).is_missing());
13461    }
13462
13463    #[test]
13464    fn nansum_nanmean_timedelta64_preserves_dtype_620mj() {
13465        // Per br-frankenpandas-620mj: pandas td_series.sum()/mean() return
13466        // Timedelta64, not Float64(0.0). Was silently zero before because
13467        // collect_finite drops Timedelta64 (to_f64 errors).
13468        let one_hour = 3_600 * 1_000_000_000_i64;
13469        let vals = vec![
13470            Scalar::Timedelta64(one_hour),
13471            Scalar::Timedelta64(2 * one_hour),
13472            Scalar::Timedelta64(3 * one_hour),
13473        ];
13474        assert_eq!(super::nansum(&vals), Scalar::Timedelta64(6 * one_hour));
13475        assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
13476    }
13477
13478    #[test]
13479    fn nansum_nanmean_timedelta64_skips_nat_620mj() {
13480        let one_hour = 3_600 * 1_000_000_000_i64;
13481        let vals = vec![
13482            Scalar::Timedelta64(Timedelta::NAT),
13483            Scalar::Timedelta64(one_hour),
13484            Scalar::Timedelta64(3 * one_hour),
13485            Scalar::Timedelta64(Timedelta::NAT),
13486        ];
13487        // NAT is missing → skipped. Sum: 1h+3h=4h; mean: 2h.
13488        assert_eq!(super::nansum(&vals), Scalar::Timedelta64(4 * one_hour));
13489        assert_eq!(super::nanmean(&vals), Scalar::Timedelta64(2 * one_hour));
13490    }
13491
13492    /// br-frankenpandas-opz27: the Timedelta reduction surface used to narrow
13493    /// its exact i128 accumulator with `clamp(i64::MIN, i64::MAX)`, which
13494    /// fabricated a finite Timedelta.max on positive overflow. Live pandas
13495    /// 2.2.3 raises `ValueError: overflow in timedelta operation` here; FP
13496    /// surfaces NaT per the lgyy8 convention. A clamping implementation
13497    /// returns `Timedelta64(i64::MAX)` and fails this.
13498    #[test]
13499    fn nansum_timedelta_overflow_is_nat_not_fabricated_max_opz27() {
13500        let vals = vec![Scalar::Timedelta64(i64::MAX), Scalar::Timedelta64(i64::MAX)];
13501        let got = super::nansum(&vals);
13502        assert!(
13503            got.is_missing(),
13504            "overflowing sum must be missing, got {got:?}"
13505        );
13506        assert_eq!(got, Scalar::Timedelta64(Timedelta::NAT));
13507        assert_ne!(got, Scalar::Timedelta64(i64::MAX));
13508    }
13509
13510    /// The negative direction used to reach NaT only *by accident*, because
13511    /// `Timedelta::NAT == i64::MIN` is exactly the clamp's lower bound — and
13512    /// that bound is off by one against the true minimum (`i64::MIN + 1`).
13513    /// Pin both the sentinel and the boundary so the accident becomes a rule.
13514    #[test]
13515    fn nansum_timedelta_negative_overflow_is_nat_opz27() {
13516        let min_repr = i64::MIN + 1; // Timedelta.min; i64::MIN is the NaT sentinel
13517        let vals = vec![Scalar::Timedelta64(min_repr), Scalar::Timedelta64(min_repr)];
13518        assert_eq!(super::nansum(&vals), Scalar::Timedelta64(Timedelta::NAT));
13519
13520        // Exactly the most-negative representable total stays a real value and
13521        // must NOT collapse into the sentinel one nanosecond above it.
13522        let exact = vec![Scalar::Timedelta64(min_repr + 1), Scalar::Timedelta64(-1)];
13523        let got = super::nansum(&exact);
13524        assert_eq!(got, Scalar::Timedelta64(min_repr));
13525        assert!(!got.is_missing(), "Timedelta.min is representable, not NaT");
13526    }
13527
13528    /// pandas 2.2.3: `Series([Timedelta.min, Timedelta.max]).max() - .min()`
13529    /// raises OverflowError. FP used `saturating_sub`, fabricating
13530    /// Timedelta.max as a plausible range.
13531    #[test]
13532    fn nanptp_timedelta_overflow_is_nat_opz27() {
13533        let vals = vec![
13534            Scalar::Timedelta64(i64::MIN + 1),
13535            Scalar::Timedelta64(i64::MAX),
13536        ];
13537        let got = super::nanptp(&vals);
13538        assert!(
13539            got.is_missing(),
13540            "unrepresentable range must be NaT, got {got:?}"
13541        );
13542        assert_ne!(got, Scalar::Timedelta64(i64::MAX));
13543
13544        // A representable range is still exact to the nanosecond (the reason
13545        // this path avoids f64 at all).
13546        let hour = 3_600 * 1_000_000_000_i64;
13547        let ok = vec![Scalar::Timedelta64(hour), Scalar::Timedelta64(4 * hour)];
13548        assert_eq!(super::nanptp(&ok), Scalar::Timedelta64(3 * hour));
13549    }
13550
13551    /// The load-bearing cumsum case: accumulation stays exact in i128, so only
13552    /// the *unrepresentable* index goes NaT and a later index that returns to
13553    /// range emits its true value. A clamping implementation pins `running` at
13554    /// i64::MAX and can never produce the final value, so it fails this test.
13555    #[test]
13556    fn nancumsum_timedelta_overflow_recovers_exact_value_opz27() {
13557        let vals = vec![
13558            Scalar::Timedelta64(i64::MAX),
13559            Scalar::Timedelta64(i64::MAX), // true total 2*i64::MAX: unrepresentable
13560            Scalar::Timedelta64(i64::MIN + 1), // back in range: total == i64::MAX
13561        ];
13562        let out = super::nancumsum(&vals);
13563        assert_eq!(out.len(), 3);
13564        assert_eq!(out[0], Scalar::Timedelta64(i64::MAX));
13565        assert!(
13566            out[1].is_missing(),
13567            "overflowed index must be NaT, got {:?}",
13568            out[1]
13569        );
13570        assert_eq!(
13571            out[2],
13572            Scalar::Timedelta64(i64::MAX),
13573            "exact i128 accumulation must recover; a clamped running sum cannot"
13574        );
13575    }
13576
13577    /// Non-overflowing cumsum is unchanged bit-for-bit, and input NaT still
13578    /// passes through without advancing the running total.
13579    #[test]
13580    fn nancumsum_timedelta_exact_path_unchanged_opz27() {
13581        let sec = 1_000_000_000_i64;
13582        let vals = vec![
13583            Scalar::Timedelta64(sec),
13584            Scalar::Timedelta64(Timedelta::NAT),
13585            Scalar::Timedelta64(2 * sec),
13586        ];
13587        let out = super::nancumsum(&vals);
13588        assert_eq!(out[0], Scalar::Timedelta64(sec));
13589        assert!(out[1].is_missing());
13590        assert_eq!(out[2], Scalar::Timedelta64(3 * sec));
13591    }
13592
13593    const DAY_NS: i64 = 86_400 * 1_000_000_000;
13594    /// 2020-01-01T00:00:00Z in epoch nanoseconds.
13595    const DT_2020: i64 = 1_577_836_800_000_000_000;
13596
13597    /// br-frankenpandas-axhhk: every one of these returned `Null(NaN)` (or
13598    /// `None`) before the Datetime64 arms existed, because `Datetime64::to_f64()`
13599    /// errors and each reduction fell through to the f64 catch-all. Expectations
13600    /// are the live pandas 2.2.3 answers for
13601    /// `Series([2020-01-01, +60d, +31d])`:
13602    ///   min 2020-01-01 · max 2020-03-01 · ptp Timedelta 60 days
13603    ///   argmin 0 · argmax 1 · cummax/cummin Timestamps
13604    #[test]
13605    fn datetime64_ordering_reductions_match_pandas_axhhk() {
13606        let d = Scalar::Datetime64;
13607        let vals = vec![
13608            d(DT_2020),
13609            d(DT_2020 + 60 * DAY_NS),
13610            d(DT_2020 + 31 * DAY_NS),
13611        ];
13612
13613        assert_eq!(super::nanmin(&vals), d(DT_2020));
13614        assert_eq!(super::nanmax(&vals), d(DT_2020 + 60 * DAY_NS));
13615        assert_eq!(super::nanargmin(&vals), Some(0));
13616        assert_eq!(super::nanargmax(&vals), Some(1));
13617
13618        // ptp of two INSTANTS is a DURATION: Timedelta64, not Datetime64.
13619        let span = super::nanptp(&vals);
13620        assert_eq!(span, Scalar::Timedelta64(60 * DAY_NS));
13621        assert_eq!(span.dtype(), DType::Timedelta64);
13622
13623        assert_eq!(
13624            super::nancummax(&vals),
13625            vec![
13626                d(DT_2020),
13627                d(DT_2020 + 60 * DAY_NS),
13628                d(DT_2020 + 60 * DAY_NS)
13629            ]
13630        );
13631        assert_eq!(
13632            super::nancummin(&vals),
13633            vec![d(DT_2020), d(DT_2020), d(DT_2020)]
13634        );
13635    }
13636
13637    /// The size-dependence is the part that made this bug quiet, so pin it
13638    /// explicitly rather than only asserting the headline. A ONE-element
13639    /// datetime slice was always correct (the `(None, _)` arm seeds `min`
13640    /// before any comparison runs); TWO elements hit the catch-all and
13641    /// returned NaN. A regression that drops the Datetime64 arm would still
13642    /// pass a single-element test.
13643    #[test]
13644    fn datetime64_min_max_size_dependence_pinned_axhhk() {
13645        let d = Scalar::Datetime64;
13646        let one = vec![d(DT_2020)];
13647        assert_eq!(super::nanmin(&one), d(DT_2020));
13648        assert_eq!(super::nanmax(&one), d(DT_2020));
13649
13650        let two = vec![d(DT_2020 + DAY_NS), d(DT_2020)];
13651        let got_min = super::nanmin(&two);
13652        assert!(
13653            !got_min.is_missing(),
13654            "2-element datetime min must not be missing, got {got_min:?}"
13655        );
13656        assert_eq!(got_min, d(DT_2020));
13657        assert_eq!(super::nanmax(&two), d(DT_2020 + DAY_NS));
13658    }
13659
13660    /// NaT still skips, and a datetime span too large for i64 surfaces NaT via
13661    /// the shared opz27 narrowing rather than a fabricated extreme.
13662    #[test]
13663    fn datetime64_reductions_skip_nat_and_guard_span_overflow_axhhk() {
13664        let d = Scalar::Datetime64;
13665        let with_nat = vec![
13666            d(Timestamp::NAT),
13667            d(DT_2020 + 31 * DAY_NS),
13668            d(DT_2020),
13669            d(Timestamp::NAT),
13670        ];
13671        assert_eq!(super::nanmin(&with_nat), d(DT_2020));
13672        assert_eq!(super::nanmax(&with_nat), d(DT_2020 + 31 * DAY_NS));
13673        assert_eq!(super::nanptp(&with_nat), Scalar::Timedelta64(31 * DAY_NS));
13674        // argmin/argmax report positions in the ORIGINAL slice, NaT skipped.
13675        assert_eq!(super::nanargmin(&with_nat), Some(2));
13676        assert_eq!(super::nanargmax(&with_nat), Some(1));
13677
13678        // Span exceeding i64 ns: NaT, never a fabricated Timedelta.max.
13679        let huge = vec![d(i64::MIN + 1), d(i64::MAX)];
13680        let span = super::nanptp(&huge);
13681        assert!(span.is_missing(), "unrepresentable span must be NaT");
13682        assert_ne!(span, Scalar::Timedelta64(i64::MAX));
13683    }
13684
13685    /// br-frankenpandas-adv58: mean/median/quantile returned `Null(NaN)` for
13686    /// datetime input. Expectations are the live pandas 2.2.3 answers for
13687    /// `Series([2020-01-01, +60d, +31d])`, which at day granularity pandas
13688    /// computes exactly:
13689    ///   mean 2020-01-31T08:00 · median 2020-02-01 · q0.5 2020-02-01
13690    ///   q0.25 2020-01-16T12:00
13691    #[test]
13692    fn datetime64_averaging_reductions_match_pandas_adv58() {
13693        let d = Scalar::Datetime64;
13694        let vals = vec![
13695            d(DT_2020),
13696            d(DT_2020 + 60 * DAY_NS),
13697            d(DT_2020 + 31 * DAY_NS),
13698        ];
13699        // 1580457600e9 / 1580515200e9 / 1579176000e9, straight from the probe.
13700        assert_eq!(super::nanmean(&vals), d(1_580_457_600_000_000_000));
13701        assert_eq!(super::nanmedian(&vals), d(1_580_515_200_000_000_000));
13702        assert_eq!(super::nanquantile(&vals, 0.5), d(1_580_515_200_000_000_000));
13703        assert_eq!(
13704            super::nanquantile(&vals, 0.25),
13705            d(1_579_176_000_000_000_000)
13706        );
13707    }
13708
13709    /// The even-count rounding rule, probed at 1 ns granularity where pandas is
13710    /// exact. It is TRUNCATION TOWARD ZERO — plain Rust integer division.
13711    /// `floor` would give -1 for [-1,0]; ties-to-even would give 2 for [1,2].
13712    /// Both are refuted by these cases, so this test discriminates against the
13713    /// two rounding rules a reimplementation is most likely to pick.
13714    #[test]
13715    fn datetime64_mean_median_round_toward_zero_adv58() {
13716        let d = Scalar::Datetime64;
13717        for (a, b, want) in [
13718            (0_i64, 1_i64, 0_i64),
13719            (0, 3, 1),
13720            (1, 2, 1),
13721            (-1, 0, 0),
13722            (-3, 0, -1),
13723            (-2, -1, -1),
13724            (0, 2, 1),
13725            (-2, 0, -1),
13726        ] {
13727            let vals = vec![d(a), d(b)];
13728            assert_eq!(
13729                super::nanmean(&vals),
13730                d(want),
13731                "mean of [{a}, {b}] should be {want}"
13732            );
13733            assert_eq!(
13734                super::nanmedian(&vals),
13735                d(want),
13736                "median of [{a}, {b}] should be {want}"
13737            );
13738        }
13739    }
13740
13741    /// NaT is skipped, and an all-NaT datetime input stays in the Datetime
13742    /// family rather than degrading to a numeric NaN.
13743    #[test]
13744    fn datetime64_averaging_skips_nat_adv58() {
13745        let d = Scalar::Datetime64;
13746        let vals = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
13747        // pandas: mean == median == 2020-01-02, count 2.
13748        assert_eq!(super::nanmean(&vals), d(DT_2020 + DAY_NS));
13749        assert_eq!(super::nanmedian(&vals), d(DT_2020 + DAY_NS));
13750
13751        let all_nat = vec![d(Timestamp::NAT), d(Timestamp::NAT)];
13752        let got = super::nanmean(&all_nat);
13753        assert!(
13754            got.is_missing(),
13755            "all-NaT mean must be missing, got {got:?}"
13756        );
13757        assert_eq!(
13758            got.dtype(),
13759            DType::datetime64_naive(),
13760            "must stay Datetime64"
13761        );
13762    }
13763
13764    /// FP is EXACT here and pandas is not: pandas routes datetime
13765    /// mean/median/quantile through f64, so at 2020-era magnitudes (~1.58e18,
13766    /// f64 ULP 256 ns) it snaps to a 256 ns grid — it returns B+0 for the mean
13767    /// of the CONSTANT series [B+1, B+1], and for an odd-count median it can
13768    /// return a Timestamp that is not even one of the inputs. FP keeps the
13769    /// exact i128 treatment its Timedelta sibling already had. DISC-019.
13770    #[test]
13771    fn datetime64_averaging_is_exact_where_pandas_snaps_adv58() {
13772        let d = Scalar::Datetime64;
13773
13774        // Constant series: the answer is unambiguous; pandas still loses it.
13775        let constant = vec![d(DT_2020 + 1), d(DT_2020 + 1)];
13776        assert_eq!(super::nanmean(&constant), d(DT_2020 + 1));
13777        assert_eq!(super::nanmedian(&constant), d(DT_2020 + 1));
13778
13779        // Odd-count median is a SELECTION: the result must be an input value.
13780        let odd = vec![d(DT_2020), d(DT_2020 + 129), d(DT_2020 + 258)];
13781        let med = super::nanmedian(&odd);
13782        assert_eq!(med, d(DT_2020 + 129));
13783        assert!(
13784            odd.contains(&med),
13785            "odd-count median must be one of the inputs; pandas returns B+256, which is not"
13786        );
13787    }
13788
13789    /// br-frankenpandas-40ujm: datetime std returned `Null(NaN)`; pandas 2.2.3
13790    /// returns a Timedelta. Every value below is the probed oracle answer for
13791    /// `Series([2020-01-01, +60d, +31d])`, in raw ns:
13792    ///   ddof=1 (default) 2592479955563784   ddof=0 2116751019841492
13793    ///   ddof=2           3666320313338702   ddof=3 NaT (n - ddof <= 0)
13794    /// pandas truncates the sqrt toward zero (ddof=0 is 2116751019841492.8).
13795    #[test]
13796    fn datetime64_std_matches_pandas_ddof_variants_40ujm() {
13797        let d = Scalar::Datetime64;
13798        let vals = vec![
13799            d(DT_2020),
13800            d(DT_2020 + 60 * DAY_NS),
13801            d(DT_2020 + 31 * DAY_NS),
13802        ];
13803        // Dispersion of instants is a DURATION: Timedelta64, not Datetime64.
13804        let s1 = super::nanstd(&vals, 1);
13805        assert_eq!(s1, Scalar::Timedelta64(2_592_479_955_563_784));
13806        assert_eq!(s1.dtype(), DType::Timedelta64);
13807        assert_eq!(
13808            super::nanstd(&vals, 0),
13809            Scalar::Timedelta64(2_116_751_019_841_492)
13810        );
13811        assert_eq!(
13812            super::nanstd(&vals, 2),
13813            Scalar::Timedelta64(3_666_320_313_338_702)
13814        );
13815        // n - ddof <= 0 => NaT, matching pandas.
13816        assert!(super::nanstd(&vals, 3).is_missing());
13817    }
13818
13819    /// pandas returns the SAME std for a Datetime64 series and a Timedelta64
13820    /// series built from identical ns. That equivalence is the whole basis for
13821    /// routing both families through one computation, so pin it directly.
13822    #[test]
13823    fn datetime64_std_equals_timedelta64_std_on_same_ns_40ujm() {
13824        let offsets = [0_i64, 60 * DAY_NS, 31 * DAY_NS];
13825        let dt: Vec<Scalar> = offsets.iter().map(|o| Scalar::Datetime64(*o)).collect();
13826        let td: Vec<Scalar> = offsets.iter().map(|o| Scalar::Timedelta64(*o)).collect();
13827        assert_eq!(super::nanstd(&dt, 1), super::nanstd(&td, 1));
13828        assert_eq!(
13829            super::nanstd(&dt, 1),
13830            Scalar::Timedelta64(2_592_479_955_563_784)
13831        );
13832    }
13833
13834    /// NaT skips (a 3-element series with one NaT must equal the 2-element
13835    /// series without it), a single element gives NaT at the default ddof, and
13836    /// var/sem stay REFUSED for datetimes because pandas raises on them.
13837    #[test]
13838    fn datetime64_std_skips_nat_and_var_sem_stay_unsupported_40ujm() {
13839        let d = Scalar::Datetime64;
13840        let with_nat = vec![d(DT_2020), d(Timestamp::NAT), d(DT_2020 + 2 * DAY_NS)];
13841        let without = vec![d(DT_2020), d(DT_2020 + 2 * DAY_NS)];
13842        // pandas: both are Timedelta 1 days 09:56:28.051789035.
13843        assert_eq!(super::nanstd(&with_nat, 1), super::nanstd(&without, 1));
13844        assert_eq!(
13845            super::nanstd(&with_nat, 1),
13846            Scalar::Timedelta64(122_188_051_789_035)
13847        );
13848
13849        // n=1 with ddof=1 -> NaT, as pandas returns.
13850        assert!(super::nanstd(&[d(DT_2020)], 1).is_missing());
13851        assert!(super::nanstd(&[d(Timestamp::NAT)], 1).is_missing());
13852
13853        // pandas RAISES TypeError for datetime64 var and sem. FP must not
13854        // invent a value: these stay on the Timedelta-only gate and report
13855        // missing. A regression that widened them would return a number here.
13856        let vals = vec![d(DT_2020), d(DT_2020 + 60 * DAY_NS)];
13857        assert!(super::nanvar(&vals, 1).is_missing());
13858        assert!(super::nansem(&vals, 1).is_missing());
13859    }
13860
13861    /// br-frankenpandas-qoabs: Period is the THIRD dtype whose `to_f64()`
13862    /// errors, so min/max fell into the f64 catch-all and returned
13863    /// `Null(NaN)`. pandas 2.2.3 on `Series([2020-01, 2020-03, 2020-02], M)`
13864    /// gives min 2020-01 and max 2020-03; ordinals are 600/601/602.
13865    #[test]
13866    fn period_min_max_match_pandas_qoabs() {
13867        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
13868        let vals = vec![p(600), p(602), p(601)];
13869        assert_eq!(super::nanmin(&vals), p(600));
13870        assert_eq!(super::nanmax(&vals), p(602));
13871
13872        // Size-dependence, exactly as in axhhk: ONE element always worked via
13873        // the `(None, _)` seed, so a test with a single value would pass even
13874        // with no Period arm at all. Assert both sizes.
13875        assert_eq!(super::nanmin(&[p(600)]), p(600));
13876        let two = vec![p(602), p(600)];
13877        assert!(!super::nanmin(&two).is_missing());
13878        assert_eq!(super::nanmin(&two), p(600));
13879        assert_eq!(super::nanmax(&two), p(602));
13880    }
13881
13882    /// A Period whose ordinal is the NaT sentinel is missing and skipped, and
13883    /// an all-missing Period input reports missing rather than a value.
13884    #[test]
13885    fn period_min_max_skip_nat_qoabs() {
13886        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
13887        let nat = Scalar::Period(Period::new(i64::MIN, PeriodFreq::Monthly));
13888        let vals = vec![nat.clone(), p(602), p(600), nat.clone()];
13889        assert_eq!(super::nanmin(&vals), p(600));
13890        assert_eq!(super::nanmax(&vals), p(602));
13891        assert!(super::nanmin(&[nat.clone(), nat]).is_missing());
13892    }
13893
13894    /// MIXED FREQ must not be ordered. pandas refuses it outright
13895    /// (`IncompatibleFrequency: Input has different freq=D from Period(freq=M)`),
13896    /// so FP reports missing rather than inventing an order. This is the test
13897    /// that discriminates: an implementation comparing raw ordinals would
13898    /// happily return a value here, because monthly 2020-01 is ordinal 600
13899    /// while daily 2020-01-05 is 18267 — it would call the daily period later.
13900    #[test]
13901    fn period_mixed_freq_is_not_ordered_qoabs() {
13902        let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
13903        let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
13904        let vals = vec![month.clone(), day.clone()];
13905        let got_min = super::nanmin(&vals);
13906        assert!(
13907            got_min.is_missing(),
13908            "mixed-freq Period min must not be ordered, got {got_min:?}"
13909        );
13910        assert_ne!(
13911            got_min, day,
13912            "must not rank the daily period by raw ordinal"
13913        );
13914        assert!(super::nanmax(&vals).is_missing());
13915    }
13916
13917    /// br-frankenpandas-d7zjp: the rest of the Period reduction family, which
13918    /// qoabs deferred because a `fn(i64) -> Scalar` constructor cannot carry a
13919    /// freq. Expectations are the probed pandas 2.2.3 answers for
13920    /// `Series([2020-01, 2020-03, 2020-02], freq=M)` (ordinals 600/601/602):
13921    ///   median 2020-02 · quantile(0.5) 2020-02 · idxmin 0 · idxmax 1
13922    ///   cummax ends 2020-03 · cummin ends 2020-01
13923    #[test]
13924    fn period_full_reduction_family_matches_pandas_d7zjp() {
13925        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
13926        let vals = vec![p(600), p(602), p(601)];
13927
13928        assert_eq!(super::nanmedian(&vals), p(601));
13929        assert_eq!(super::nanquantile(&vals, 0.5), p(601));
13930        assert_eq!(super::nanargmin(&vals), Some(0));
13931        assert_eq!(super::nanargmax(&vals), Some(1));
13932        assert_eq!(super::nancummax(&vals), vec![p(600), p(602), p(602)]);
13933        assert_eq!(super::nancummin(&vals), vec![p(600), p(600), p(600)]);
13934    }
13935
13936    /// Even-count Period median picks by TRUNCATION TOWARD ZERO on the ordinal,
13937    /// the same rule the datetime family uses. Probed: pandas gives 2020-02 for
13938    /// [2020-01, 2020-04] (ordinals 600/603, midpoint 601.5) and 2020-01 for
13939    /// [2020-01, 2020-02] (600/601, midpoint 600.5).
13940    #[test]
13941    fn period_even_count_median_truncates_toward_zero_d7zjp() {
13942        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
13943        assert_eq!(super::nanmedian(&[p(600), p(603)]), p(601));
13944        assert_eq!(super::nanmedian(&[p(600), p(601)]), p(600));
13945    }
13946
13947    /// MIXED FREQ must not be ordered by ANY of these, for the same reason as
13948    /// in qoabs: pandas raises IncompatibleFrequency, and raw ordinals are not
13949    /// comparable across freqs (monthly 2020-01 is 600, daily 2020-01-05 is
13950    /// 18267). The family enum encodes the freq, so a mixed input is simply not
13951    /// one family and never reaches a typed arm.
13952    #[test]
13953    fn period_mixed_freq_not_ordered_by_any_reduction_d7zjp() {
13954        let month = Scalar::Period(Period::new(600, PeriodFreq::Monthly));
13955        let day = Scalar::Period(Period::new(18_267, PeriodFreq::Daily));
13956        let vals = vec![month, day];
13957
13958        assert!(super::nanmedian(&vals).is_missing());
13959        assert!(super::nanquantile(&vals, 0.5).is_missing());
13960        assert_eq!(super::nanargmin(&vals), None);
13961        assert_eq!(super::nanargmax(&vals), None);
13962        // The cumulative ops must not emit an ordered Period column either.
13963        assert!(super::nancummax(&vals).iter().all(Scalar::is_missing));
13964        assert!(super::nancummin(&vals).iter().all(Scalar::is_missing));
13965    }
13966
13967    /// pandas RAISES for Period mean/sum/std/var ("does not support reduction",
13968    /// and for mean explicitly "the meaning is ambiguous"). FP must not invent
13969    /// values. `std` is the trap here: the family enum puts Period one line
13970    /// away from the Datetime64 arm that 40ujm deliberately widened, so this
13971    /// asserts the guard holds.
13972    #[test]
13973    fn period_unsupported_reductions_stay_missing_d7zjp() {
13974        let p = |ordinal: i64| Scalar::Period(Period::new(ordinal, PeriodFreq::Monthly));
13975        let vals = vec![p(600), p(602), p(601)];
13976        assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
13977        assert!(super::nanvar(&vals, 1).is_missing(), "pandas raises var");
13978        assert!(super::nansem(&vals, 1).is_missing(), "pandas raises sem");
13979        assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
13980    }
13981
13982    /// br-frankenpandas-srqdo: Interval is the FOURTH dtype whose `to_f64()`
13983    /// errors, so min/max fell into the f64 catch-all and returned
13984    /// `Null(NaN)`. pandas 2.2.3 on `IntervalArray.from_tuples([(0,1),(4,5),(2,3)])`
13985    /// gives min `(0, 1]` and max `(4, 5]`.
13986    #[test]
13987    fn interval_min_max_match_pandas_srqdo() {
13988        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
13989        let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
13990        assert_eq!(super::nanmin(&vals), iv(0.0, 1.0));
13991        assert_eq!(super::nanmax(&vals), iv(4.0, 5.0));
13992
13993        // Size-dependence, per the axhhk lesson: ONE element always worked via
13994        // the `(None, _)` seed, so a single-value test passes even with no arm.
13995        assert_eq!(super::nanmin(&[iv(2.0, 3.0)]), iv(2.0, 3.0));
13996        let two = vec![iv(4.0, 5.0), iv(0.0, 1.0)];
13997        assert!(!super::nanmin(&two).is_missing());
13998        assert_eq!(super::nanmin(&two), iv(0.0, 1.0));
13999        assert_eq!(super::nanmax(&two), iv(4.0, 5.0));
14000    }
14001
14002    /// The tie-on-left case, which is what discriminates a correct (left, right)
14003    /// comparison from one that only looks at `left`. pandas: Interval(0,2) <
14004    /// Interval(0,5) is True. An implementation comparing left alone keeps
14005    /// whichever came first and returns the wrong element here.
14006    #[test]
14007    fn interval_ties_on_left_order_by_right_srqdo() {
14008        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14009        let vals = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
14010        assert_eq!(super::nanmin(&vals), iv(0.0, 2.0));
14011        assert_eq!(super::nanmax(&vals), iv(0.0, 9.0));
14012    }
14013
14014    /// A NaN bound has no pandas counterpart — `IntervalArray` refuses to build
14015    /// one ("missing values must be missing in the same location both left and
14016    /// right") — so it must report missing rather than impose an arbitrary
14017    /// order. Critically this must NOT panic: the obvious
14018    /// `partial_cmp().unwrap()` implementation would.
14019    #[test]
14020    fn interval_nan_bound_is_not_ordered_srqdo() {
14021        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14022        let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
14023        assert!(super::nanmin(&vals).is_missing());
14024        assert!(super::nanmax(&vals).is_missing());
14025    }
14026
14027    /// pandas RAISES or NotImplementedErrors every other reduction for
14028    /// Interval (median/mean/sum/std/quantile/cummax). FP must not invent
14029    /// values, so they stay missing.
14030    #[test]
14031    fn interval_unsupported_reductions_stay_missing_srqdo() {
14032        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14033        let vals = vec![iv(0.0, 1.0), iv(4.0, 5.0), iv(2.0, 3.0)];
14034        assert!(super::nanmedian(&vals).is_missing(), "pandas raises median");
14035        assert!(super::nanmean(&vals).is_missing(), "pandas raises mean");
14036        assert!(super::nanstd(&vals, 1).is_missing(), "pandas raises std");
14037        assert!(
14038            super::nanquantile(&vals, 0.5).is_missing(),
14039            "pandas raises quantile"
14040        );
14041        assert!(
14042            super::nancummax(&vals).iter().all(Scalar::is_missing),
14043            "pandas NotImplementedErrors cummax"
14044        );
14045    }
14046
14047    /// br-frankenpandas-2h9dm: Interval argmin/argmax returned None, because
14048    /// `Interval::to_f64()` errors and the f64 fallback skipped every element.
14049    /// All four expectations are probed pandas 2.2.3 `idxmin`/`idxmax`.
14050    #[test]
14051    fn interval_argmin_argmax_match_pandas_2h9dm() {
14052        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14053        // pandas: idxmin 1, idxmax 0
14054        let vals = vec![iv(4.0, 5.0), iv(0.0, 1.0), iv(2.0, 3.0)];
14055        assert_eq!(super::nanargmin(&vals), Some(1));
14056        assert_eq!(super::nanargmax(&vals), Some(0));
14057
14058        // Left-tie resolves by RIGHT. pandas: idxmin 1, idxmax 2. An
14059        // implementation comparing only `left` keeps index 0 for both.
14060        let tie = vec![iv(0.0, 5.0), iv(0.0, 2.0), iv(0.0, 9.0)];
14061        assert_eq!(super::nanargmin(&tie), Some(1));
14062        assert_eq!(super::nanargmax(&tie), Some(2));
14063    }
14064
14065    /// Duplicated extreme returns the FIRST occurrence (pandas idxmin 0 on
14066    /// [(0,1),(0,1),(9,9)]), and missing entries are skipped while the returned
14067    /// index stays a position in the ORIGINAL slice (pandas idxmin 2 / idxmax 0
14068    /// on [(4,5), None, (0,1)]).
14069    #[test]
14070    fn interval_arg_first_occurrence_and_missing_2h9dm() {
14071        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14072        let dup = vec![iv(0.0, 1.0), iv(0.0, 1.0), iv(9.0, 9.0)];
14073        assert_eq!(
14074            super::nanargmin(&dup),
14075            Some(0),
14076            "first occurrence, not last"
14077        );
14078        assert_eq!(super::nanargmax(&dup), Some(2));
14079
14080        let with_missing = vec![iv(4.0, 5.0), Scalar::Null(NullKind::NaN), iv(0.0, 1.0)];
14081        assert_eq!(super::nanargmin(&with_missing), Some(2));
14082        assert_eq!(super::nanargmax(&with_missing), Some(0));
14083    }
14084
14085    /// A NaN bound is not orderable, so decline rather than return an arbitrary
14086    /// index — and critically, do not panic the way `partial_cmp().unwrap()`
14087    /// would.
14088    #[test]
14089    fn interval_arg_nan_bound_declines_2h9dm() {
14090        let iv = |l: f64, r: f64| Scalar::Interval(Interval::new(l, r, IntervalClosed::Right));
14091        let vals = vec![iv(0.0, 1.0), iv(f64::NAN, 5.0)];
14092        assert_eq!(super::nanargmin(&vals), None);
14093        assert_eq!(super::nanargmax(&vals), None);
14094    }
14095
14096    /// br-frankenpandas-fyr1z-policy-carrier-f29nz: the load-bearing guarantee
14097    /// of this bead is NO DEFAULT BEHAVIOR CHANGE. Prove it rather than assert
14098    /// it: over a seeded corpus that deliberately straddles the i64 boundary
14099    /// and the NaT sentinel, every infallible helper must equal its fallible
14100    /// sibling resolved under the default `SurfaceNat` policy — which is also
14101    /// exactly what the pre-f29nz bodies computed.
14102    #[test]
14103    fn overflow_policy_carrier_preserves_default_behavior_f29nz() {
14104        // Seeded LCG, no rand dependency (see [[differential-test-coverage]]).
14105        let mut state: u64 = 0x5DEE_CE66_D125_1F00;
14106        let mut next = || {
14107            state = state
14108                .wrapping_mul(6_364_136_223_846_793_005)
14109                .wrapping_add(1_442_695_040_888_963_407);
14110            state
14111        };
14112        // Edge values first, then random ones. i64::MIN is the NaT sentinel.
14113        let mut corpus: Vec<i64> = vec![
14114            0,
14115            1,
14116            -1,
14117            2,
14118            -2,
14119            i64::MAX,
14120            i64::MIN,
14121            i64::MIN + 1,
14122            i64::MAX - 1,
14123            i64::MAX / 2,
14124            -(i64::MAX / 2),
14125        ];
14126        for _ in 0..400 {
14127            let raw = next() as i64;
14128            corpus.push(raw);
14129            corpus.push(raw / 3);
14130        }
14131
14132        let policy = super::OverflowPolicy::default();
14133        assert_eq!(
14134            policy,
14135            super::OverflowPolicy::SurfaceNat,
14136            "default must not move"
14137        );
14138
14139        for &a in &corpus {
14140            for &b in &corpus {
14141                // Timedelta::add / sub / mul_scalar
14142                assert_eq!(
14143                    Timedelta::add(a, b),
14144                    policy
14145                        .resolve(Timedelta::try_add(a, b), Timedelta::NAT)
14146                        .expect("SurfaceNat never errors"),
14147                    "add({a}, {b}) diverged"
14148                );
14149                assert_eq!(
14150                    Timedelta::sub(a, b),
14151                    policy
14152                        .resolve(Timedelta::try_sub(a, b), Timedelta::NAT)
14153                        .expect("SurfaceNat never errors"),
14154                    "sub({a}, {b}) diverged"
14155                );
14156                assert_eq!(
14157                    Timedelta::mul_scalar(a, b),
14158                    policy
14159                        .resolve(Timedelta::try_mul_scalar(a, b), Timedelta::NAT)
14160                        .expect("SurfaceNat never errors"),
14161                    "mul_scalar({a}, {b}) diverged"
14162                );
14163
14164                // Timestamp::{add,sub}_timedelta / sub_timestamp — including tz,
14165                // since overflow deliberately drops it.
14166                let ts = Timestamp::from_nanos(a);
14167                assert_eq!(
14168                    ts.add_timedelta(b),
14169                    ts.try_add_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
14170                    "add_timedelta({a}, {b}) diverged"
14171                );
14172                assert_eq!(
14173                    ts.sub_timedelta(b),
14174                    ts.try_sub_timedelta(b).unwrap_or_else(|_| Timestamp::nat()),
14175                    "sub_timedelta({a}, {b}) diverged"
14176                );
14177                let other = Timestamp::from_nanos(b);
14178                assert_eq!(
14179                    ts.sub_timestamp(&other),
14180                    ts.try_sub_timestamp(&other).unwrap_or(Timedelta::NAT),
14181                    "sub_timestamp({a}, {b}) diverged"
14182                );
14183            }
14184        }
14185    }
14186
14187    /// The carrier must actually CARRY something: `Strict` propagates the
14188    /// overflow with the right op name and the pandas error class probed from
14189    /// live 2.2.3. Without this, `resolve` could ignore its policy and the
14190    /// equivalence test above would still pass.
14191    #[test]
14192    fn overflow_policy_strict_reports_op_and_pandas_class_f29nz() {
14193        use super::{OverflowPolicy, PandasTemporalError};
14194
14195        let strict = OverflowPolicy::Strict;
14196
14197        // pd.Timedelta.max + pd.Timedelta('1ns') -> OverflowError
14198        let err = strict
14199            .resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT)
14200            .expect_err("must surface under Strict");
14201        assert_eq!(err.op, "Timedelta::add");
14202        assert_eq!(err.pandas_error, PandasTemporalError::Overflow);
14203
14204        // pd.Timestamp.max + pd.Timedelta('1ns') -> OutOfBoundsDatetime
14205        let ts = Timestamp::from_nanos(i64::MAX);
14206        let err = strict
14207            .resolve(ts.try_add_timedelta(1), Timestamp::nat())
14208            .expect_err("must surface under Strict");
14209        assert_eq!(err.op, "Timestamp::add_timedelta");
14210        assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
14211
14212        // pd.Timestamp.min - pd.Timestamp.max -> OutOfBoundsDatetime
14213        let err = strict
14214            .resolve(
14215                Timestamp::from_nanos(i64::MIN + 1)
14216                    .try_sub_timestamp(&Timestamp::from_nanos(i64::MAX)),
14217                Timedelta::NAT,
14218            )
14219            .expect_err("must surface under Strict");
14220        assert_eq!(err.op, "Timestamp::sub_timestamp");
14221        assert_eq!(err.pandas_error, PandasTemporalError::OutOfBoundsDatetime);
14222
14223        // A NaT operand is PROPAGATION, not overflow: Strict must still be Ok.
14224        assert_eq!(
14225            strict
14226                .resolve(Timedelta::try_add(Timedelta::NAT, 1), Timedelta::NAT)
14227                .expect("NaT propagation is not an overflow"),
14228            Timedelta::NAT
14229        );
14230        // And a representable result is untouched under either policy.
14231        assert_eq!(
14232            strict
14233                .resolve(Timedelta::try_add(2, 3), Timedelta::NAT)
14234                .expect("no overflow"),
14235            5
14236        );
14237    }
14238
14239    /// br-frankenpandas-fyr1z-strict-raise-arms-t7ht2: the scalar divide-by-zero
14240    /// row, and the boundary a STRICT arm must not cross. All four expectations
14241    /// probed on live pandas 2.2.3:
14242    ///   SCALAR  Timedelta('1s') // 0   -> ZeroDivisionError
14243    ///   SCALAR  Timedelta('1s') / 0    -> ZeroDivisionError
14244    ///   VECTOR  Series([Td]) // 0      -> NaT   (must NOT raise)
14245    ///   VECTOR  Series([Td]) / 0       -> NaT   (must NOT raise)
14246    #[test]
14247    fn timedelta_scalar_zero_division_taxonomy_t7ht2() {
14248        use super::{OverflowPolicy, PandasTemporalError};
14249
14250        // The fallible scalar sibling reports ZeroDivision with its op name.
14251        let err = Timedelta::try_div_scalar(1_000_000_000, 0)
14252            .expect_err("scalar divide-by-zero must be reportable");
14253        assert_eq!(err.op, "Timedelta::div_scalar");
14254        assert_eq!(err.pandas_error, PandasTemporalError::ZeroDivision);
14255
14256        // THE BOUNDARY: the infallible helper the vectorized callers use keeps
14257        // returning NaT. If this ever starts raising, FrankenPandas diverges
14258        // from pandas on a row where it is currently bit-for-bit correct.
14259        assert_eq!(Timedelta::div_scalar(1_000_000_000, 0), Timedelta::NAT);
14260        assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 0), Timedelta::NAT);
14261
14262        // Under the default policy the failure resolves back to NaT, so
14263        // nothing changes for existing callers.
14264        assert_eq!(
14265            OverflowPolicy::default()
14266                .resolve(Timedelta::try_div_scalar(1_000_000_000, 0), Timedelta::NAT)
14267                .expect("SurfaceNat never errors"),
14268            Timedelta::NAT
14269        );
14270
14271        // Non-zero divisors are untouched, including the floor-division
14272        // adjustment for mixed signs (-7 // 2 == -4, not -3).
14273        assert_eq!(Timedelta::try_div_scalar(-7, 2), Ok(-4));
14274        assert_eq!(Timedelta::div_scalar(-7, 2), -4);
14275        assert_eq!(Timedelta::try_div_scalar(7, 2), Ok(3));
14276        // NaT propagates as Ok, not as a failure.
14277        assert_eq!(
14278            Timedelta::try_div_scalar(Timedelta::NAT, 2),
14279            Ok(Timedelta::NAT)
14280        );
14281    }
14282
14283    /// The constructor row of the taxonomy. Probed:
14284    /// `pd.Timedelta(float('inf'), 's')` raises OutOfBoundsTimedelta —
14285    /// specifically NOT a bare OverflowError, which is why the mapping is
14286    /// explicit rather than assumed.
14287    #[test]
14288    fn timedelta_constructor_error_maps_to_out_of_bounds_t7ht2() {
14289        use super::{PandasTemporalError, TimedeltaError};
14290
14291        assert_eq!(
14292            TimedeltaError::Overflow.pandas_error(),
14293            Some(PandasTemporalError::OutOfBoundsTimedelta)
14294        );
14295        // A parse failure is not part of the arithmetic taxonomy.
14296        assert_eq!(
14297            TimedeltaError::InvalidFormat("nonsense".into()).pandas_error(),
14298            None
14299        );
14300        // And the live path still errors on a non-finite input (8v92m).
14301        assert!(Timedelta::from_unit(f64::INFINITY, "s").is_err());
14302        assert_eq!(
14303            Timedelta::from_unit(f64::INFINITY, "s")
14304                .unwrap_err()
14305                .pandas_error(),
14306            Some(PandasTemporalError::OutOfBoundsTimedelta)
14307        );
14308    }
14309
14310    /// br-frankenpandas-fyr1z-hardened-audit-vllv6: HARDENED mode adds
14311    /// observability, NEVER semantics. Every value it returns must be
14312    /// bit-for-bit what SurfaceNat returns — proven over the same seeded corpus
14313    /// the f29nz equivalence test uses, with the audit log ENABLED throughout so
14314    /// recording cannot perturb results.
14315    #[test]
14316    fn hardened_audit_values_are_bit_identical_to_surface_nat_vllv6() {
14317        use super::{OverflowPolicy, overflow_audit};
14318
14319        overflow_audit::enable();
14320        let mut state: u64 = 0x1234_5678_9ABC_DEF0;
14321        let mut next = || {
14322            state = state
14323                .wrapping_mul(6_364_136_223_846_793_005)
14324                .wrapping_add(1_442_695_040_888_963_407);
14325            state
14326        };
14327        let mut corpus: Vec<i64> = vec![
14328            0,
14329            1,
14330            -1,
14331            2,
14332            -2,
14333            i64::MAX,
14334            i64::MIN,
14335            i64::MIN + 1,
14336            i64::MAX - 1,
14337        ];
14338        for _ in 0..120 {
14339            corpus.push(next() as i64);
14340        }
14341
14342        for &a in &corpus {
14343            for &b in &corpus {
14344                for op in [
14345                    Timedelta::try_add as fn(i64, i64) -> Result<i64, super::TemporalFailure>,
14346                    Timedelta::try_sub,
14347                    Timedelta::try_mul_scalar,
14348                    Timedelta::try_div_scalar,
14349                ] {
14350                    let soft = OverflowPolicy::SurfaceNat
14351                        .resolve(op(a, b), Timedelta::NAT)
14352                        .expect("SurfaceNat never errors");
14353                    let hard = OverflowPolicy::HardenedNat
14354                        .resolve(op(a, b), Timedelta::NAT)
14355                        .expect("HardenedNat never errors");
14356                    assert_eq!(hard, soft, "HARDENED changed a value for ({a}, {b})");
14357                }
14358            }
14359        }
14360        overflow_audit::disable();
14361    }
14362
14363    /// The audit trail itself: HARDENED records the op, the pandas class it
14364    /// would have raised, the OPERANDS whose exact result left the
14365    /// representable range, and the value actually returned — deterministically
14366    /// and in order. SurfaceNat and Strict record nothing.
14367    #[test]
14368    fn hardened_audit_records_deterministic_recovery_entries_vllv6() {
14369        use super::{OverflowPolicy, PandasTemporalError, overflow_audit};
14370
14371        overflow_audit::enable();
14372        assert!(overflow_audit::is_enabled());
14373        assert!(overflow_audit::drain().is_empty(), "starts empty");
14374
14375        // Two overflows and one representable result, in a fixed order.
14376        let _ =
14377            OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14378        let _ = OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(2, 3), Timedelta::NAT);
14379        let _ =
14380            OverflowPolicy::HardenedNat.resolve(Timedelta::try_div_scalar(5, 0), Timedelta::NAT);
14381
14382        let entries = overflow_audit::drain();
14383        assert_eq!(entries.len(), 2, "only the two failures are recorded");
14384
14385        assert_eq!(entries[0].op, "Timedelta::add");
14386        assert_eq!(entries[0].pandas_error, PandasTemporalError::Overflow);
14387        assert_eq!(entries[0].operands, Some((i64::MAX, 1)));
14388        assert_eq!(entries[0].recovered_as, i64::MIN);
14389
14390        assert_eq!(entries[1].op, "Timedelta::div_scalar");
14391        assert_eq!(entries[1].pandas_error, PandasTemporalError::ZeroDivision);
14392        assert_eq!(entries[1].operands, Some((5, 0)));
14393
14394        // Draining leaves recording enabled and empty.
14395        assert!(overflow_audit::drain().is_empty());
14396
14397        // The OTHER policies must stay silent — the audit is HARDENED-only.
14398        let _ = OverflowPolicy::SurfaceNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14399        let _ = OverflowPolicy::Strict.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14400        assert!(
14401            overflow_audit::drain().is_empty(),
14402            "SurfaceNat/Strict must not write to the audit trail"
14403        );
14404
14405        overflow_audit::disable();
14406        assert!(!overflow_audit::is_enabled());
14407        // Disabled: recording is a no-op and drain yields nothing.
14408        let _ =
14409            OverflowPolicy::HardenedNat.resolve(Timedelta::try_add(i64::MAX, 1), Timedelta::NAT);
14410        assert!(
14411            overflow_audit::drain().is_empty(),
14412            "disabled must not record"
14413        );
14414    }
14415
14416    /// br-frankenpandas-fyr1z-wrap-signoff-s4lkx.
14417    ///
14418    /// THIS TEST PINS A PANDAS QUIRK THAT WE REPRODUCE ON PURPOSE. The values
14419    /// below are NOT what a careful implementation would choose: multiplying a
14420    /// positive duration by 2 yields a NEGATIVE one. They are what live pandas
14421    /// 2.2.3 returns, because numpy int64 wraps silently, and the maintainer
14422    /// decided that STRICT means bit-for-bit observable parity with the
14423    /// incumbent INCLUDING its quirks — this being a port.
14424    ///
14425    /// So: if this test fails, do NOT "fix" the wrap. Either pandas changed, or
14426    /// someone routed a non-STRICT caller into the STRICT path. Both need
14427    /// investigating rather than correcting the arithmetic.
14428    ///
14429    /// Oracle values, probed directly:
14430    ///   Series([Timedelta.max]) * 2            -> -2 ns
14431    ///   Series([max, max]).cumsum()            -> [max, -2]
14432    ///   Series([max, max, max]).cumsum()       -> [max, -2, max - 2]
14433    #[test]
14434    fn strict_reproduces_pandas_silent_timedelta_wrap_s4lkx() {
14435        use super::{OverflowPolicy, nancumsum_with_policy};
14436
14437        // Series * int -- pandas returns -2, i.e. i64::MAX.wrapping_mul(2).
14438        assert_eq!(
14439            Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::Strict),
14440            -2,
14441            "STRICT must reproduce pandas' wrap, not repair it"
14442        );
14443
14444        // cumsum -- and the THIRD element is the important one: it proves the
14445        // accumulator keeps wrapping rather than sticking at a bound.
14446        let max = Scalar::Timedelta64(i64::MAX);
14447        let out = nancumsum_with_policy(
14448            &[max.clone(), max.clone(), max.clone()],
14449            OverflowPolicy::Strict,
14450        );
14451        assert_eq!(
14452            out,
14453            vec![
14454                Scalar::Timedelta64(i64::MAX),
14455                Scalar::Timedelta64(-2),
14456                Scalar::Timedelta64(i64::MAX - 2),
14457            ],
14458            "STRICT cumsum must reproduce pandas' int64 wraparound exactly"
14459        );
14460
14461        // NaT still propagates; the wrap is about overflow, not missingness.
14462        assert_eq!(
14463            Timedelta::mul_scalar_with_policy(Timedelta::NAT, 2, OverflowPolicy::Strict),
14464            Timedelta::NAT
14465        );
14466    }
14467
14468    /// The other half of the s4lkx decision, and the reason reproducing a
14469    /// fail-open quirk is acceptable at all: it is reachable ONLY when a caller
14470    /// explicitly asks for STRICT incumbent parity. Every other policy — and
14471    /// crucially the DEFAULT — still refuses to fabricate a plausible value,
14472    /// keeping the br-frankenpandas-lgyy8 guarantee intact.
14473    #[test]
14474    fn non_strict_policies_still_refuse_to_wrap_s4lkx() {
14475        use super::{OverflowPolicy, nancumsum_with_policy, overflow_audit};
14476
14477        for policy in [OverflowPolicy::SurfaceNat, OverflowPolicy::HardenedNat] {
14478            assert_eq!(
14479                Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
14480                Timedelta::NAT,
14481                "{policy:?} must NOT wrap"
14482            );
14483            assert_ne!(
14484                Timedelta::mul_scalar_with_policy(i64::MAX, 2, policy),
14485                -2,
14486                "{policy:?} must not reproduce the pandas quirk"
14487            );
14488        }
14489        // The bare default is SurfaceNat, so an unconfigured caller is safe.
14490        assert_eq!(
14491            Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::default()),
14492            Timedelta::NAT
14493        );
14494
14495        // cumsum likewise keeps the exact-i128 / NaT behaviour off STRICT.
14496        let max = Scalar::Timedelta64(i64::MAX);
14497        let soft = nancumsum_with_policy(&[max.clone(), max.clone()], OverflowPolicy::SurfaceNat);
14498        assert!(soft[1].is_missing(), "non-STRICT cumsum must NaT, not wrap");
14499        assert_eq!(soft, super::nancumsum(&[max.clone(), max]));
14500
14501        // HARDENED wrapping would be doubly wrong: it would fabricate a value
14502        // AND leave nothing in the audit trail to explain it.
14503        overflow_audit::enable();
14504        let _ = Timedelta::mul_scalar_with_policy(i64::MAX, 2, OverflowPolicy::HardenedNat);
14505        assert_eq!(
14506            overflow_audit::drain().len(),
14507            1,
14508            "HARDENED must record the recovery it performed"
14509        );
14510        overflow_audit::disable();
14511    }
14512
14513    /// Mixed Datetime64 + another dtype must NOT take the typed arm — it falls
14514    /// back exactly as before, so this fix cannot change cross-type behavior.
14515    #[test]
14516    fn datetime64_mixed_input_still_falls_back_axhhk() {
14517        let vals = vec![Scalar::Datetime64(DT_2020), Scalar::Int64(5)];
14518        // `is_datetime_input` is false here, so both keep their PRE-EXISTING
14519        // cross-type behavior, which differs between the two by construction:
14520        //   nanmin  — the catch-all compares via to_f64(); the Datetime64 side
14521        //             errors, so it bails to Null(NaN).
14522        //   nanptp  — its f64 loop SKIPS values whose to_f64() errors, so the
14523        //             datetime is dropped and the range is taken over the lone
14524        //             Int64 => Float64(0.0). Same shape as the documented
14525        //             mixed-timedelta fallback in ..._620mj (which yields 5.0).
14526        // Neither is changed by this bead; pinning both stops the new typed arm
14527        // from silently widening to mixed input later.
14528        assert!(super::nanmin(&vals).is_missing());
14529        assert_eq!(super::nanptp(&vals), Scalar::Float64(0.0));
14530    }
14531
14532    #[test]
14533    fn nansum_nanmean_mixed_timedelta_other_falls_back_620mj() {
14534        // Mixed Timedelta64 + other type bails out of the Timedelta path
14535        // and uses Float64 collect_finite (which drops Timedelta).
14536        // Preserves existing cross-type behavior (effectively ignores TD).
14537        let vals = vec![Scalar::Timedelta64(3600 * 1_000_000_000), Scalar::Int64(5)];
14538        // Int64(5) makes it through to_f64 → 5.0; Timedelta is dropped.
14539        assert_eq!(super::nansum(&vals), Scalar::Float64(5.0));
14540    }
14541
14542    #[test]
14543    fn nancount_counts_non_missing() {
14544        let vals = vec![
14545            Scalar::Int64(1),
14546            Scalar::Null(NullKind::Null),
14547            Scalar::Float64(3.0),
14548        ];
14549        assert_eq!(super::nancount(&vals), Scalar::Int64(2));
14550    }
14551
14552    #[test]
14553    fn nanany_nanall_nancount_match_scalar_oracle_zr2qg() {
14554        // Differential vs scalar truthiness/count oracle
14555        // (br-frankenpandas-zr2qg). Seeded LCG, no mocks.
14556        fn next(seed: &mut u64) -> u64 {
14557            *seed = seed
14558                .wrapping_mul(6364136223846793005)
14559                .wrapping_add(1442695040888963407);
14560            *seed
14561        }
14562
14563        fn truthy(value: &Scalar) -> Option<bool> {
14564            if value.is_missing() {
14565                return None;
14566            }
14567            match value {
14568                Scalar::Bool(value) => Some(*value),
14569                Scalar::Int64(value) => Some(*value != 0),
14570                Scalar::Float64(value) => Some(*value != 0.0),
14571                Scalar::Utf8(value) => Some(!value.is_empty()),
14572                Scalar::Timedelta64(value) => Some(*value != 0),
14573                _ => None,
14574            }
14575        }
14576
14577        fn assert_nanops(case: usize, values: &[Scalar]) {
14578            let truth_values = values.iter().filter_map(truthy).collect::<Vec<_>>();
14579            let expected_any = truth_values.iter().any(|value| *value);
14580            let expected_all = !truth_values.iter().any(|value| !*value);
14581            let expected_count = values.iter().filter(|value| !value.is_missing()).count() as i64;
14582
14583            assert_eq!(
14584                super::nanany(values),
14585                Scalar::Bool(expected_any),
14586                "case={case}: nanany mismatch for {values:?}"
14587            );
14588            assert_eq!(
14589                super::nanall(values),
14590                Scalar::Bool(expected_all),
14591                "case={case}: nanall mismatch for {values:?}"
14592            );
14593            assert_eq!(
14594                super::nancount(values),
14595                Scalar::Int64(expected_count),
14596                "case={case}: nancount mismatch for {values:?}"
14597            );
14598        }
14599
14600        assert_nanops(
14601            usize::MAX,
14602            &[
14603                Scalar::Null(NullKind::Null),
14604                Scalar::Null(NullKind::NaN),
14605                Scalar::Float64(f64::NAN),
14606                Scalar::Timedelta64(i64::MIN),
14607            ],
14608        );
14609
14610        let mut seed = 0x7a20_2f7e_5ca1_ab1e_u64;
14611        for case in 0..320 {
14612            let len = (next(&mut seed) % 89 + 1) as usize;
14613            let mut values = Vec::with_capacity(len);
14614            for pos in 0..len {
14615                let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
14616                let value = match next(&mut seed) % 12 {
14617                    0 => Scalar::Null(NullKind::Null),
14618                    1 => Scalar::Null(NullKind::NaN),
14619                    2 => Scalar::Float64(f64::NAN),
14620                    3 => Scalar::Bool(raw & 1 == 0),
14621                    4 => Scalar::Bool(false),
14622                    5 => Scalar::Int64(raw % 17),
14623                    6 => Scalar::Int64(0),
14624                    7 => Scalar::Float64(raw as f64 / 23.0),
14625                    8 => Scalar::Float64(0.0),
14626                    9 => Scalar::Utf8(if raw & 1 == 0 {
14627                        String::new()
14628                    } else {
14629                        format!("nanops_{case}_{pos}")
14630                    }),
14631                    10 => Scalar::Timedelta64(raw),
14632                    _ => Scalar::Timedelta64(0),
14633                };
14634                values.push(value);
14635            }
14636            assert_nanops(case, &values);
14637        }
14638    }
14639
14640    #[test]
14641    fn nanmin_basic() {
14642        let vals = vec![
14643            Scalar::Float64(5.0),
14644            Scalar::Null(NullKind::Null),
14645            Scalar::Float64(2.0),
14646            Scalar::Float64(8.0),
14647        ];
14648        assert_eq!(super::nanmin(&vals), Scalar::Float64(2.0));
14649    }
14650
14651    #[test]
14652    fn nanmax_basic() {
14653        let vals = vec![
14654            Scalar::Float64(5.0),
14655            Scalar::Float64(f64::NAN),
14656            Scalar::Float64(8.0),
14657        ];
14658        assert_eq!(super::nanmax(&vals), Scalar::Float64(8.0));
14659    }
14660
14661    #[test]
14662    fn nanmin_nanmax_empty_returns_nan() {
14663        assert!(super::nanmin(&[]).is_missing());
14664        assert!(super::nanmax(&[]).is_missing());
14665    }
14666
14667    #[test]
14668    fn nanmin_nanmax_match_same_family_oracle_vj7ds() {
14669        // Differential vs independent same-family comparator oracle
14670        // (br-frankenpandas-vj7ds). Seeded LCG, no mocks.
14671        fn next(seed: &mut u64) -> u64 {
14672            *seed = seed
14673                .wrapping_mul(6364136223846793005)
14674                .wrapping_add(1442695040888963407);
14675            *seed
14676        }
14677
14678        fn family_cmp(left: &Scalar, right: &Scalar) -> std::cmp::Ordering {
14679            match (left, right) {
14680                (Scalar::Bool(left), Scalar::Bool(right)) => left.cmp(right),
14681                (Scalar::Int64(left), Scalar::Int64(right)) => left.cmp(right),
14682                (Scalar::Float64(left), Scalar::Float64(right)) => {
14683                    left.partial_cmp(right).expect("finite floats")
14684                }
14685                (Scalar::Utf8(left), Scalar::Utf8(right)) => left.cmp(right),
14686                (Scalar::Timedelta64(left), Scalar::Timedelta64(right)) => left.cmp(right),
14687                // `assert_minmax` verifies that every present value belongs
14688                // to one generated family before it invokes this comparator.
14689                _ => std::cmp::Ordering::Equal,
14690            }
14691        }
14692
14693        fn assert_minmax(case: usize, family: &str, values: &[Scalar]) {
14694            let present = values
14695                .iter()
14696                .filter(|value| !value.is_missing())
14697                .cloned()
14698                .collect::<Vec<_>>();
14699            let actual_min = super::nanmin(values);
14700            let actual_max = super::nanmax(values);
14701            if present.is_empty() {
14702                assert!(
14703                    actual_min.is_missing(),
14704                    "case={case} family={family}: expected missing min for {values:?}, got {actual_min:?}"
14705                );
14706                assert!(
14707                    actual_max.is_missing(),
14708                    "case={case} family={family}: expected missing max for {values:?}, got {actual_max:?}"
14709                );
14710                return;
14711            }
14712
14713            let is_expected_family = |value: &Scalar| match family {
14714                "int" => matches!(value, Scalar::Int64(_)),
14715                "float" => matches!(value, Scalar::Float64(_)),
14716                "bool" => matches!(value, Scalar::Bool(_)),
14717                "utf8" => matches!(value, Scalar::Utf8(_)),
14718                "timedelta" => matches!(value, Scalar::Timedelta64(_)),
14719                _ => false,
14720            };
14721            assert!(
14722                present.iter().all(is_expected_family),
14723                "case={case} family={family}: mixed family escaped generator: {values:?}"
14724            );
14725
14726            let expected_min = present.iter().min_by(|left, right| family_cmp(left, right));
14727            let expected_max = present.iter().max_by(|left, right| family_cmp(left, right));
14728            assert!(
14729                actual_min.semantic_eq(expected_min.expect("min")),
14730                "case={case} family={family}: expected min {:?}, got {actual_min:?} for {values:?}",
14731                expected_min.expect("min")
14732            );
14733            assert!(
14734                actual_max.semantic_eq(expected_max.expect("max")),
14735                "case={case} family={family}: expected max {:?}, got {actual_max:?} for {values:?}",
14736                expected_max.expect("max")
14737            );
14738        }
14739
14740        let all_missing = [
14741            Scalar::Null(NullKind::Null),
14742            Scalar::Null(NullKind::NaN),
14743            Scalar::Float64(f64::NAN),
14744            Scalar::Timedelta64(i64::MIN),
14745        ];
14746        assert_minmax(usize::MAX, "all_missing", &all_missing);
14747
14748        let mut seed = 0xa11c_0aba_2e7d_f00d_u64;
14749        for case in 0..240 {
14750            let len = (next(&mut seed) % 73 + 1) as usize;
14751
14752            let mut ints = Vec::with_capacity(len);
14753            ints.push(Scalar::Int64(case as i64 - 120));
14754            for _ in 1..len {
14755                let raw = (next(&mut seed) % 1_001) as i64 - 500;
14756                ints.push(match next(&mut seed) % 6 {
14757                    0 => Scalar::Null(NullKind::Null),
14758                    1 => Scalar::Null(NullKind::NaN),
14759                    _ => Scalar::Int64(raw),
14760                });
14761            }
14762            assert_minmax(case, "int", &ints);
14763
14764            let mut floats = Vec::with_capacity(len);
14765            floats.push(Scalar::Float64(case as f64 / 11.0));
14766            for _ in 1..len {
14767                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14768                floats.push(match next(&mut seed) % 8 {
14769                    0 | 1 => Scalar::Float64(f64::NAN),
14770                    2 => Scalar::Float64(f64::INFINITY),
14771                    3 => Scalar::Float64(f64::NEG_INFINITY),
14772                    4 => Scalar::Float64(0.0),
14773                    5 => Scalar::Float64(-0.0),
14774                    _ => Scalar::Float64(raw as f64 / 41.0),
14775                });
14776            }
14777            assert_minmax(case, "float", &floats);
14778
14779            let mut bools = Vec::with_capacity(len);
14780            bools.push(Scalar::Bool(case & 1 == 0));
14781            for _ in 1..len {
14782                bools.push(match next(&mut seed) % 5 {
14783                    0 => Scalar::Null(NullKind::Null),
14784                    1 => Scalar::Null(NullKind::NaN),
14785                    raw => Scalar::Bool(raw & 1 == 0),
14786                });
14787            }
14788            assert_minmax(case, "bool", &bools);
14789
14790            let mut utf8 = Vec::with_capacity(len);
14791            utf8.push(Scalar::Utf8(format!("minmax_{}", case % 17)));
14792            for pos in 1..len {
14793                utf8.push(match next(&mut seed) % 7 {
14794                    0 => Scalar::Null(NullKind::Null),
14795                    1 => Scalar::Null(NullKind::NaN),
14796                    raw => Scalar::Utf8(format!("minmax_{}_{}", raw, pos % 11)),
14797                });
14798            }
14799            assert_minmax(case, "utf8", &utf8);
14800
14801            let mut timedeltas = Vec::with_capacity(len);
14802            timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
14803            for _ in 1..len {
14804                let raw = (next(&mut seed) % 1_003) as i64 - 501;
14805                timedeltas.push(match next(&mut seed) % 7 {
14806                    0 => Scalar::Null(NullKind::Null),
14807                    1 => Scalar::Timedelta64(i64::MIN),
14808                    _ => Scalar::Timedelta64(raw),
14809                });
14810            }
14811            assert_minmax(case, "timedelta", &timedeltas);
14812        }
14813    }
14814
14815    #[test]
14816    fn nanmin_nanmax_mixed_incompatible_types_returns_nan() {
14817        let vals = vec![Scalar::Int64(5), Scalar::Utf8("hello".into())];
14818        assert!(super::nanmin(&vals).is_missing());
14819        assert!(super::nanmax(&vals).is_missing());
14820
14821        let vals2 = vec![Scalar::Utf8("a".into()), Scalar::Float64(3.0)];
14822        assert!(super::nanmin(&vals2).is_missing());
14823        assert!(super::nanmax(&vals2).is_missing());
14824    }
14825
14826    #[test]
14827    fn nanmin_nanmax_compatible_numeric_types_ok() {
14828        let vals = vec![Scalar::Int64(5), Scalar::Float64(3.0), Scalar::Bool(true)];
14829        assert_eq!(super::nanmin(&vals), Scalar::Bool(true));
14830        assert_eq!(super::nanmax(&vals), Scalar::Int64(5));
14831    }
14832
14833    #[test]
14834    fn nanmin_nanmax_timedelta64_returns_timedelta_yic5m() {
14835        // Per br-frankenpandas-yic5m: nanmin/nanmax on Timedelta64 returns
14836        // the smallest/largest Timedelta64 — was silently NaN before
14837        // because Timedelta64.to_f64() errors and the catch-all swallowed it.
14838        let one_hour = 3_600 * 1_000_000_000_i64;
14839        let vals = vec![
14840            Scalar::Timedelta64(3 * one_hour),
14841            Scalar::Timedelta64(one_hour),
14842            Scalar::Timedelta64(2 * one_hour),
14843        ];
14844        assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
14845        assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(3 * one_hour));
14846    }
14847
14848    #[test]
14849    fn nanmin_nanmax_timedelta64_skips_nat_yic5m() {
14850        let one_hour = 3_600 * 1_000_000_000_i64;
14851        let vals = vec![
14852            Scalar::Timedelta64(Timedelta::NAT),
14853            Scalar::Timedelta64(one_hour),
14854            Scalar::Timedelta64(2 * one_hour),
14855            Scalar::Timedelta64(Timedelta::NAT),
14856        ];
14857        assert_eq!(super::nanmin(&vals), Scalar::Timedelta64(one_hour));
14858        assert_eq!(super::nanmax(&vals), Scalar::Timedelta64(2 * one_hour));
14859    }
14860
14861    #[test]
14862    fn nanmedian_odd_count() {
14863        let vals = vec![
14864            Scalar::Float64(3.0),
14865            Scalar::Null(NullKind::Null),
14866            Scalar::Float64(1.0),
14867            Scalar::Float64(2.0),
14868        ];
14869        assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.0));
14870    }
14871
14872    #[test]
14873    fn nanmedian_even_count() {
14874        let vals = vec![
14875            Scalar::Float64(1.0),
14876            Scalar::Float64(3.0),
14877            Scalar::Float64(2.0),
14878            Scalar::Float64(4.0),
14879        ];
14880        assert_eq!(super::nanmedian(&vals), Scalar::Float64(2.5));
14881    }
14882
14883    #[test]
14884    fn nanmedian_matches_numeric_and_timedelta_oracle_oabhi() {
14885        // Differential vs independent sort-based median oracles
14886        // (br-frankenpandas-oabhi). Seeded LCG, no mocks.
14887        fn next(seed: &mut u64) -> u64 {
14888            *seed = seed
14889                .wrapping_mul(6364136223846793005)
14890                .wrapping_add(1442695040888963407);
14891            *seed
14892        }
14893
14894        fn expected_numeric(values: &[Scalar]) -> Scalar {
14895            let mut finite = values
14896                .iter()
14897                .filter(|value| !value.is_missing())
14898                .filter_map(|value| value.to_f64().ok())
14899                .filter(|value| !value.is_nan())
14900                .collect::<Vec<_>>();
14901            if finite.is_empty() {
14902                return Scalar::Null(NullKind::NaN);
14903            }
14904            finite.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
14905            let mid = finite.len() / 2;
14906            if finite.len().is_multiple_of(2) {
14907                Scalar::Float64((finite[mid - 1] + finite[mid]) / 2.0)
14908            } else {
14909                Scalar::Float64(finite[mid])
14910            }
14911        }
14912
14913        fn expected_timedelta(values: &[Scalar]) -> Scalar {
14914            let mut finite = values
14915                .iter()
14916                .filter_map(|value| match value {
14917                    Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns),
14918                    _ => None,
14919                })
14920                .collect::<Vec<_>>();
14921            if finite.is_empty() {
14922                return Scalar::Null(NullKind::NaN);
14923            }
14924            finite.sort_unstable();
14925            let mid = finite.len() / 2;
14926            let median = if finite.len().is_multiple_of(2) {
14927                (i128::from(finite[mid - 1]) + i128::from(finite[mid])) / 2
14928            } else {
14929                i128::from(finite[mid])
14930            };
14931            Scalar::Timedelta64(median as i64)
14932        }
14933
14934        fn assert_median(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
14935            let actual = super::nanmedian(values);
14936            assert!(
14937                actual.semantic_eq(&expected),
14938                "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
14939            );
14940        }
14941
14942        assert_median(
14943            usize::MAX,
14944            "numeric_all_missing",
14945            &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
14946            Scalar::Null(NullKind::NaN),
14947        );
14948        assert_median(
14949            usize::MAX - 1,
14950            "timedelta_all_missing",
14951            &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
14952            Scalar::Null(NullKind::NaN),
14953        );
14954        let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
14955        assert_median(
14956            usize::MAX - 2,
14957            "timedelta_odd_median_beyond_f64_exactness",
14958            &[
14959                Scalar::Timedelta64(beyond_f64_exact_ns),
14960                Scalar::Timedelta64(beyond_f64_exact_ns + 1),
14961                Scalar::Timedelta64(beyond_f64_exact_ns + 2),
14962                Scalar::Timedelta64(Timedelta::NAT),
14963            ],
14964            Scalar::Timedelta64(beyond_f64_exact_ns + 1),
14965        );
14966
14967        let mut seed = 0x0ab1_1eda_57a7_15e5_u64;
14968        for case in 0..220 {
14969            let len = (next(&mut seed) % 79 + 1) as usize;
14970
14971            let mut numeric = Vec::with_capacity(len);
14972            numeric.push(Scalar::Int64(case as i64 - 110));
14973            for _ in 1..len {
14974                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14975                numeric.push(match next(&mut seed) % 8 {
14976                    0 => Scalar::Null(NullKind::Null),
14977                    1 => Scalar::Null(NullKind::NaN),
14978                    2 => Scalar::Float64(f64::NAN),
14979                    3 => Scalar::Bool(raw & 1 == 0),
14980                    4 => Scalar::Int64(raw % 251),
14981                    5 => Scalar::Float64(raw as f64 / 61.0),
14982                    6 => Scalar::Float64(0.0),
14983                    _ => Scalar::Float64(-0.0),
14984                });
14985            }
14986            assert_median(case, "numeric", &numeric, expected_numeric(&numeric));
14987
14988            let mut timedeltas = Vec::with_capacity(len);
14989            timedeltas.push(Scalar::Timedelta64(case as i64 - 110));
14990            for _ in 1..len {
14991                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
14992                timedeltas.push(match next(&mut seed) % 7 {
14993                    0 => Scalar::Null(NullKind::Null),
14994                    1 => Scalar::Timedelta64(i64::MIN),
14995                    _ => Scalar::Timedelta64(raw),
14996                });
14997            }
14998            assert_median(
14999                case,
15000                "timedelta",
15001                &timedeltas,
15002                expected_timedelta(&timedeltas),
15003            );
15004        }
15005    }
15006
15007    #[test]
15008    fn nanvar_nanstd_nansem_match_numeric_and_timedelta_oracle_k7apg() {
15009        // Differential vs independent variance/std/sem oracles
15010        // (br-frankenpandas-k7apg). Seeded LCG, no mocks.
15011        fn next(seed: &mut u64) -> u64 {
15012            *seed = seed
15013                .wrapping_mul(2862933555777941757)
15014                .wrapping_add(3037000493);
15015            *seed
15016        }
15017
15018        fn numeric_samples(values: &[Scalar]) -> Vec<f64> {
15019            values
15020                .iter()
15021                .filter(|value| !value.is_missing())
15022                .filter_map(|value| value.to_f64().ok())
15023                .collect()
15024        }
15025
15026        fn timedelta_samples(values: &[Scalar]) -> Vec<f64> {
15027            values
15028                .iter()
15029                .filter_map(|value| match value {
15030                    Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
15031                    _ => None,
15032                })
15033                .collect()
15034        }
15035
15036        fn reductions_from_samples(samples: &[f64], ddof: usize) -> Option<(f64, f64, f64)> {
15037            if samples.len() <= ddof {
15038                return None;
15039            }
15040            let mean = samples.iter().sum::<f64>() / samples.len() as f64;
15041            let sum_sq = samples
15042                .iter()
15043                .map(|value| (value - mean).powi(2))
15044                .sum::<f64>();
15045            let var = sum_sq / (samples.len() - ddof) as f64;
15046            let std = var.sqrt();
15047            let sem = std / (samples.len() as f64).sqrt();
15048            Some((var, std, sem))
15049        }
15050
15051        fn expected_numeric(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
15052            let samples = numeric_samples(values);
15053            let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
15054                let missing = Scalar::Null(NullKind::NaN);
15055                return (missing.clone(), missing.clone(), missing);
15056            };
15057            (
15058                Scalar::Float64(var),
15059                Scalar::Float64(std),
15060                Scalar::Float64(sem),
15061            )
15062        }
15063
15064        fn expected_timedelta(values: &[Scalar], ddof: usize) -> (Scalar, Scalar, Scalar) {
15065            let samples = timedelta_samples(values);
15066            if samples.is_empty() {
15067                let missing = Scalar::Timedelta64(Timedelta::NAT);
15068                return (missing.clone(), missing.clone(), missing);
15069            }
15070            let Some((var, std, sem)) = reductions_from_samples(&samples, ddof) else {
15071                let missing = Scalar::Timedelta64(i64::MIN);
15072                return (missing.clone(), missing.clone(), missing);
15073            };
15074            (
15075                Scalar::Timedelta64(var as i64),
15076                Scalar::Timedelta64(std as i64),
15077                Scalar::Timedelta64(sem as i64),
15078            )
15079        }
15080
15081        fn assert_reductions(
15082            case: usize,
15083            family: &str,
15084            values: &[Scalar],
15085            ddof: usize,
15086            expected: (Scalar, Scalar, Scalar),
15087        ) {
15088            let (expected_var, expected_std, expected_sem) = expected;
15089            let actual_var = super::nanvar(values, ddof);
15090            let actual_std = super::nanstd(values, ddof);
15091            let actual_sem = super::nansem(values, ddof);
15092            assert!(
15093                actual_var.semantic_eq(&expected_var),
15094                "case={case} family={family} ddof={ddof}: expected var {expected_var:?}, got {actual_var:?} for {values:?}"
15095            );
15096            assert!(
15097                actual_std.semantic_eq(&expected_std),
15098                "case={case} family={family} ddof={ddof}: expected std {expected_std:?}, got {actual_std:?} for {values:?}"
15099            );
15100            assert!(
15101                actual_sem.semantic_eq(&expected_sem),
15102                "case={case} family={family} ddof={ddof}: expected sem {expected_sem:?}, got {actual_sem:?} for {values:?}"
15103            );
15104        }
15105
15106        let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
15107        assert_reductions(
15108            usize::MAX,
15109            "numeric_all_missing",
15110            &numeric_all_missing,
15111            0,
15112            expected_numeric(&numeric_all_missing, 0),
15113        );
15114
15115        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
15116        assert_reductions(
15117            usize::MAX - 1,
15118            "timedelta_all_missing",
15119            &td_all_missing,
15120            0,
15121            expected_timedelta(&td_all_missing, 0),
15122        );
15123
15124        let mut seed = 0x7a11_c0de_5eed_0421_u64;
15125        for case in 0..240 {
15126            let len = (next(&mut seed) % 83 + 1) as usize;
15127            let ddof = (next(&mut seed) % 4) as usize;
15128
15129            let mut numeric = Vec::with_capacity(len);
15130            numeric.push(Scalar::Float64(case as f64 / 13.0));
15131            for _ in 1..len {
15132                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15133                numeric.push(match next(&mut seed) % 8 {
15134                    0 => Scalar::Null(NullKind::Null),
15135                    1 => Scalar::Null(NullKind::NaN),
15136                    2 => Scalar::Float64(f64::NAN),
15137                    3 => Scalar::Bool(raw & 1 == 0),
15138                    4 => Scalar::Int64(raw % 251),
15139                    5 => Scalar::Float64(raw as f64 / 73.0),
15140                    6 => Scalar::Float64(0.0),
15141                    _ => Scalar::Float64(-0.0),
15142                });
15143            }
15144            assert_reductions(
15145                case,
15146                "numeric",
15147                &numeric,
15148                ddof,
15149                expected_numeric(&numeric, ddof),
15150            );
15151
15152            let mut timedeltas = Vec::with_capacity(len);
15153            timedeltas.push(Scalar::Timedelta64(case as i64 - 120));
15154            for _ in 1..len {
15155                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
15156                timedeltas.push(match next(&mut seed) % 7 {
15157                    0 => Scalar::Null(NullKind::Null),
15158                    1 => Scalar::Timedelta64(i64::MIN),
15159                    _ => Scalar::Timedelta64(raw),
15160                });
15161            }
15162            assert_reductions(
15163                case,
15164                "timedelta",
15165                &timedeltas,
15166                ddof,
15167                expected_timedelta(&timedeltas, ddof),
15168            );
15169        }
15170    }
15171
15172    #[test]
15173    fn nanvar_population() {
15174        let vals = vec![
15175            Scalar::Float64(2.0),
15176            Scalar::Float64(4.0),
15177            Scalar::Float64(4.0),
15178            Scalar::Float64(4.0),
15179            Scalar::Float64(5.0),
15180            Scalar::Float64(5.0),
15181            Scalar::Float64(7.0),
15182            Scalar::Float64(9.0),
15183        ];
15184        let var = super::nanvar(&vals, 0);
15185        assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
15186        if let Scalar::Float64(v) = var {
15187            assert!((v - 4.0).abs() < 1e-10);
15188        }
15189    }
15190
15191    #[test]
15192    fn nanvar_sample_ddof1() {
15193        let vals = vec![
15194            Scalar::Float64(2.0),
15195            Scalar::Float64(4.0),
15196            Scalar::Float64(4.0),
15197            Scalar::Float64(4.0),
15198            Scalar::Float64(5.0),
15199            Scalar::Float64(5.0),
15200            Scalar::Float64(7.0),
15201            Scalar::Float64(9.0),
15202        ];
15203        let var = super::nanvar(&vals, 1);
15204        assert!(matches!(var, Scalar::Float64(_)), "expected Float64");
15205        if let Scalar::Float64(v) = var {
15206            assert!((v - 32.0 / 7.0).abs() < 1e-10);
15207        }
15208    }
15209
15210    #[test]
15211    fn nanvar_insufficient_values_returns_nan() {
15212        let vals = vec![Scalar::Float64(5.0)];
15213        assert!(super::nanvar(&vals, 1).is_missing());
15214    }
15215
15216    #[test]
15217    fn nanstd_is_sqrt_of_var() {
15218        let vals = vec![
15219            Scalar::Float64(2.0),
15220            Scalar::Float64(4.0),
15221            Scalar::Float64(4.0),
15222            Scalar::Float64(4.0),
15223            Scalar::Float64(5.0),
15224            Scalar::Float64(5.0),
15225            Scalar::Float64(7.0),
15226            Scalar::Float64(9.0),
15227        ];
15228        let std = super::nanstd(&vals, 0);
15229        assert!(matches!(std, Scalar::Float64(_)), "expected Float64");
15230        if let Scalar::Float64(v) = std {
15231            assert!((v - 2.0).abs() < 1e-10);
15232        }
15233    }
15234
15235    #[test]
15236    fn nanmedian_timedelta64_preserves_dtype_j8ntk() {
15237        // Per br-frankenpandas-j8ntk: pandas td_series.median() returns
15238        // Timedelta64; was silently NaN before via collect_finite.
15239        let one_hour = 3_600 * 1_000_000_000_i64;
15240        let vals = vec![
15241            Scalar::Timedelta64(one_hour),
15242            Scalar::Timedelta64(2 * one_hour),
15243            Scalar::Timedelta64(3 * one_hour),
15244        ];
15245        assert_eq!(super::nanmedian(&vals), Scalar::Timedelta64(2 * one_hour));
15246    }
15247
15248    #[test]
15249    fn nanstd_timedelta64_preserves_dtype_j8ntk() {
15250        // Per br-frankenpandas-j8ntk: pandas td_series.std() returns
15251        // Timedelta64. Check Timedelta64 output and reasonable magnitude
15252        // for population std of [1h, 2h, 3h] = sqrt(2/3) * 1h.
15253        let one_hour: i64 = 3_600 * 1_000_000_000;
15254        let vals = vec![
15255            Scalar::Timedelta64(one_hour),
15256            Scalar::Timedelta64(2 * one_hour),
15257            Scalar::Timedelta64(3 * one_hour),
15258        ];
15259        let std = super::nanstd(&vals, 0);
15260        assert!(matches!(std, Scalar::Timedelta64(_)));
15261        if let Scalar::Timedelta64(ns) = std {
15262            let expected = (2.0_f64 / 3.0).sqrt() * one_hour as f64;
15263            assert!(
15264                (ns as f64 - expected).abs() < 1e6,
15265                "expected ~{expected} ns, got {ns}"
15266            );
15267        }
15268    }
15269
15270    #[test]
15271    fn nanstd_nansem_timedelta64_insufficient_returns_nat_j8ntk() {
15272        let one_hour = 3_600 * 1_000_000_000_i64;
15273        let vals = vec![Scalar::Timedelta64(one_hour)];
15274        // ddof=1 with n=1 → underflow, returns NaT
15275        assert_eq!(super::nanstd(&vals, 1), Scalar::Timedelta64(Timedelta::NAT));
15276        assert_eq!(super::nansem(&vals, 1), Scalar::Timedelta64(Timedelta::NAT));
15277    }
15278
15279    #[test]
15280    fn nanops_with_mixed_types() {
15281        let vals = vec![
15282            Scalar::Bool(true),
15283            Scalar::Int64(3),
15284            Scalar::Float64(6.0),
15285            Scalar::Null(NullKind::Null),
15286        ];
15287        assert_eq!(super::nansum(&vals), Scalar::Float64(10.0));
15288        assert_eq!(super::nancount(&vals), Scalar::Int64(3));
15289    }
15290
15291    #[test]
15292    fn nanops_all_missing_returns_identity() {
15293        let vals = vec![Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
15294        assert_eq!(super::nansum(&vals), Scalar::Float64(0.0));
15295        assert!(super::nanmean(&vals).is_missing());
15296        assert!(super::nanmedian(&vals).is_missing());
15297        assert!(super::nanvar(&vals, 0).is_missing());
15298        assert!(super::nanstd(&vals, 0).is_missing());
15299    }
15300
15301    // ── Timedelta tests ────────────────────────────────────────────────
15302
15303    #[test]
15304    fn timedelta_parse_simple_units() {
15305        use super::Timedelta;
15306        assert_eq!(Timedelta::parse("1d").unwrap(), Timedelta::NANOS_PER_DAY);
15307        assert_eq!(
15308            Timedelta::parse("2h").unwrap(),
15309            2 * Timedelta::NANOS_PER_HOUR
15310        );
15311        assert_eq!(
15312            Timedelta::parse("30m").unwrap(),
15313            30 * Timedelta::NANOS_PER_MIN
15314        );
15315        assert_eq!(
15316            Timedelta::parse("45s").unwrap(),
15317            45 * Timedelta::NANOS_PER_SEC
15318        );
15319        assert_eq!(
15320            Timedelta::parse("100ms").unwrap(),
15321            100 * Timedelta::NANOS_PER_MILLI
15322        );
15323        assert_eq!(
15324            Timedelta::parse("500us").unwrap(),
15325            500 * Timedelta::NANOS_PER_MICRO
15326        );
15327        assert_eq!(Timedelta::parse("1000ns").unwrap(), 1000);
15328    }
15329
15330    #[test]
15331    fn timedelta_parse_zero_valued_compound() {
15332        use super::Timedelta;
15333        // Each of these is a Timedelta of zero, not a parse failure. Verified
15334        // against live pandas 2.2.3: every form below yields
15335        // `Timedelta('0 days 00:00:00')`. A guard in `parse_compound` used to
15336        // reject them all except the bare "0", which made
15337        // `to_timedelta(["10 seconds", "1 second", "0 seconds"])` raise on the
15338        // third element only.
15339        for s in [
15340            "0 seconds",
15341            "0 second",
15342            "0 sec",
15343            "0s",
15344            "0 days",
15345            "0d",
15346            "0 hours",
15347            "0.0 hours",
15348            "0 minutes",
15349            "0ms",
15350            "0us",
15351            "0ns",
15352            "0",
15353            "0 days 0 seconds",
15354        ] {
15355            assert_eq!(Timedelta::parse(s).unwrap(), 0, "parse({s:?}) should be 0");
15356        }
15357        // The sign is carried by the caller, so a negative zero is still zero.
15358        assert_eq!(Timedelta::parse("-0 seconds").unwrap(), 0);
15359        // Removing the guard must NOT admit garbage: an unknown unit and a
15360        // missing number are still rejected inside the loop.
15361        assert!(Timedelta::parse("0 fortnights").is_err());
15362        assert!(Timedelta::parse("seconds").is_err());
15363    }
15364
15365    #[test]
15366    fn timedelta_parse_compound() {
15367        use super::Timedelta;
15368        let expected = Timedelta::NANOS_PER_DAY
15369            + 2 * Timedelta::NANOS_PER_HOUR
15370            + 30 * Timedelta::NANOS_PER_MIN;
15371        assert_eq!(Timedelta::parse("1d 2h 30m").unwrap(), expected);
15372        assert_eq!(Timedelta::parse("1d2h30m").unwrap(), expected);
15373    }
15374
15375    #[test]
15376    fn timedelta_parse_leading_sign_spares_the_clock_part() {
15377        use super::Timedelta;
15378        const S: i64 = Timedelta::NANOS_PER_SEC;
15379        // Verified vs pandas 2.2.3 Timedelta(...).total_seconds(); the second
15380        // is how pandas prints a negative Timedelta.
15381        assert_eq!(Timedelta::parse("-1 days 02:03:04").unwrap(), -79_016 * S);
15382        assert_eq!(Timedelta::parse("-1 days +02:03:04").unwrap(), -79_016 * S);
15383        assert_eq!(
15384            Timedelta::parse("-3 days +23:59:59.5").unwrap(),
15385            -172_800 * S - S / 2
15386        );
15387        assert_eq!(Timedelta::parse("-0 days 01:00:00").unwrap(), 3_600 * S);
15388        // Without a clock part after a unit, the whole value is negated.
15389        assert_eq!(Timedelta::parse("-1d2h").unwrap(), -93_600 * S);
15390        assert_eq!(Timedelta::parse("-02:03:04").unwrap(), -7_384 * S);
15391        // A sign inside the string is pandas' "only leading negative signs".
15392        assert!(Timedelta::parse("-1 days -02:03:04").is_err());
15393        assert!(Timedelta::parse("1 days -02:00:00").is_err());
15394    }
15395
15396    #[test]
15397    fn timedelta_parse_iso8601_matches_pandas_tdiso() {
15398        use super::Timedelta;
15399        // Verified vs pandas 2.2.3 Timedelta(...).value.
15400        assert_eq!(Timedelta::parse("P1DT2H3M4S").unwrap(), 93_784_000_000_000);
15401        assert_eq!(Timedelta::parse("PT1H").unwrap(), 3_600_000_000_000);
15402        assert_eq!(Timedelta::parse("PT1H30M").unwrap(), 5_400_000_000_000);
15403        assert_eq!(Timedelta::parse("P1D").unwrap(), 86_400_000_000_000);
15404        assert_eq!(Timedelta::parse("P2W").unwrap(), 1_209_600_000_000_000);
15405        assert_eq!(Timedelta::parse("PT0.5S").unwrap(), 500_000_000);
15406        // pandas quirks: T ignored, M is minutes everywhere, units in any order.
15407        assert_eq!(Timedelta::parse("P1M").unwrap(), 60_000_000_000);
15408        assert_eq!(Timedelta::parse("P1H").unwrap(), 3_600_000_000_000);
15409        assert_eq!(Timedelta::parse("PT1D").unwrap(), 86_400_000_000_000);
15410        assert_eq!(Timedelta::parse("P1D1H").unwrap(), 90_000_000_000_000);
15411        assert_eq!(Timedelta::parse("-P1DT2H").unwrap(), -93_600_000_000_000);
15412        // Rejected like pandas: years, lowercase, bare P/PT.
15413        assert!(Timedelta::parse("P1Y").is_err());
15414        assert!(Timedelta::parse("p1d").is_err());
15415        assert!(Timedelta::parse("P").is_err());
15416        assert!(Timedelta::parse("PT").is_err());
15417    }
15418
15419    #[test]
15420    fn timedelta_parse_time_format() {
15421        use super::Timedelta;
15422        let expected = Timedelta::NANOS_PER_HOUR
15423            + 30 * Timedelta::NANOS_PER_MIN
15424            + 45 * Timedelta::NANOS_PER_SEC;
15425        assert_eq!(Timedelta::parse("01:30:45").unwrap(), expected);
15426    }
15427
15428    #[test]
15429    fn timedelta_parse_time_fraction_rejects_unicode_without_panic() {
15430        use super::{Timedelta, TimedeltaError};
15431        let err = Timedelta::parse("00:00:00.\u{00e9}\u{00e9}\u{00e9}\u{00e9}\u{00e9}")
15432            .expect_err("non-ASCII fractional seconds must reject");
15433        assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
15434    }
15435
15436    #[test]
15437    fn timedelta_parse_time_format_rejects_overflow_without_panic() {
15438        use super::{Timedelta, TimedeltaError};
15439        let err = Timedelta::parse("9223372036854775807:00")
15440            .expect_err("oversized hour component must reject");
15441        assert!(matches!(err, TimedeltaError::InvalidFormat(_)));
15442    }
15443
15444    #[test]
15445    fn timedelta_parse_rejects_huge_value_overflow_zw3mg() {
15446        // Per br-frankenpandas-zw3mg: the compound parser used a raw
15447        // `as i64` cast that silently saturated to i64::MAX when the
15448        // product of (decimal-digit f64) × unit multiplier overflows.
15449        // Use a large literal (no scientific notation — the lexer only
15450        // accepts digits, '.', '-'). 1e18 days × NANOS_PER_DAY (~8.64e13)
15451        // overflows i64.
15452        use super::{Timedelta, TimedeltaError};
15453        let huge = format!("{} days", "9".repeat(18));
15454        assert!(matches!(
15455            Timedelta::parse(&huge).expect_err("9...(18 9s) days must overflow"),
15456            TimedeltaError::Overflow
15457        ));
15458    }
15459
15460    #[test]
15461    fn timedelta_parse_nat() {
15462        use super::Timedelta;
15463        assert_eq!(Timedelta::parse("NaT").unwrap(), Timedelta::NAT);
15464        assert_eq!(Timedelta::parse("nat").unwrap(), Timedelta::NAT);
15465    }
15466
15467    #[test]
15468    fn timedelta_parse_negative() {
15469        use super::Timedelta;
15470        assert_eq!(Timedelta::parse("-1d").unwrap(), -Timedelta::NANOS_PER_DAY);
15471    }
15472
15473    #[test]
15474    fn timedelta_components() {
15475        use super::Timedelta;
15476        let nanos = Timedelta::NANOS_PER_DAY
15477            + Timedelta::NANOS_PER_HOUR
15478            + Timedelta::NANOS_PER_MIN
15479            + Timedelta::NANOS_PER_SEC
15480            + Timedelta::NANOS_PER_MILLI
15481            + 2 * Timedelta::NANOS_PER_MICRO
15482            + 3;
15483        let comp = Timedelta::components(nanos);
15484        assert_eq!(comp.days, 1);
15485        assert_eq!(comp.hours, 1);
15486        assert_eq!(comp.minutes, 1);
15487        assert_eq!(comp.seconds, 1);
15488        assert_eq!(comp.milliseconds, 1);
15489        assert_eq!(comp.microseconds, 2);
15490        assert_eq!(comp.nanoseconds, 3);
15491    }
15492
15493    #[test]
15494    fn timedelta_negative_components_floor_div() {
15495        use super::Timedelta;
15496        // pandas floor-normalizes negative timedeltas: pd.Timedelta(-1,'s') has
15497        // days=-1, seconds=86399, components=(-1, 23, 59, 59, 0, 0, 0).
15498        let neg_1s = -Timedelta::NANOS_PER_SEC;
15499        assert_eq!(Timedelta::days(neg_1s), Some(-1));
15500        assert_eq!(Timedelta::seconds(neg_1s), Some(86399));
15501        assert_eq!(Timedelta::microseconds(neg_1s), Some(0));
15502        assert_eq!(Timedelta::nanoseconds(neg_1s), Some(0));
15503        let comp = Timedelta::components(neg_1s);
15504        assert_eq!(
15505            (
15506                comp.days,
15507                comp.hours,
15508                comp.minutes,
15509                comp.seconds,
15510                comp.milliseconds,
15511                comp.microseconds,
15512                comp.nanoseconds
15513            ),
15514            (-1, 23, 59, 59, 0, 0, 0)
15515        );
15516
15517        // pd.Timedelta(-86401,'s'): days=-2, seconds=86399.
15518        let neg = -86_401 * Timedelta::NANOS_PER_SEC;
15519        assert_eq!(Timedelta::days(neg), Some(-2));
15520        assert_eq!(Timedelta::seconds(neg), Some(86399));
15521    }
15522
15523    /// br-frankenpandas-timedelta-nat-days-returns-zero-406ni.
15524    ///
15525    /// All four component helpers returned `0` for `NaT`, one of them behind a
15526    /// comment asserting "pandas returns 0 for NaT.days (no error)". MEASURED,
15527    /// live pandas 2.2.3: `pd.NaT.days` is **nan**, and
15528    /// `pd.to_timedelta([1, None, -1], unit='s').dt.days` is float64
15529    /// `[0.0, nan, -1.0]`.
15530    ///
15531    /// ⚠️ `0` IS THE ONE WRONG ANSWER THAT LOOKS RIGHT. It is a legal value for
15532    /// three of these four accessors — `seconds`, `microseconds` and
15533    /// `nanoseconds` all legitimately return 0 for a whole number of days — so a
15534    /// caller cannot distinguish "midnight" from "missing" by inspecting the
15535    /// result. That is the fail-open-as-plausible-data class, and it is why the
15536    /// fix is the return TYPE and not a corrected comment.
15537    #[test]
15538    fn timedelta_components_are_missing_for_nat_not_zero_406ni() {
15539        use super::Timedelta;
15540        assert_eq!(Timedelta::days(Timedelta::NAT), None);
15541        assert_eq!(Timedelta::seconds(Timedelta::NAT), None);
15542        assert_eq!(Timedelta::microseconds(Timedelta::NAT), None);
15543        assert_eq!(Timedelta::nanoseconds(Timedelta::NAT), None);
15544
15545        // NON-VACUITY: a whole number of days legitimately answers 0 for the
15546        // three sub-day components, so `Some(0)` and `None` must be reachable
15547        // from the same accessor. A test that only checked NaT could pass
15548        // against a helper that returned `None` unconditionally.
15549        let one_day = Timedelta::NANOS_PER_DAY;
15550        assert_eq!(Timedelta::days(one_day), Some(1));
15551        assert_eq!(Timedelta::seconds(one_day), Some(0));
15552        assert_eq!(Timedelta::microseconds(one_day), Some(0));
15553        assert_eq!(Timedelta::nanoseconds(one_day), Some(0));
15554    }
15555
15556    #[test]
15557    fn timedelta_total_seconds() {
15558        use super::Timedelta;
15559        let nanos = 90_000_000_000i64; // 90 seconds
15560        assert!((Timedelta::total_seconds(nanos) - 90.0).abs() < 1e-9);
15561        assert!(Timedelta::total_seconds(Timedelta::NAT).is_nan());
15562    }
15563
15564    #[test]
15565    fn timedelta_format_basic() {
15566        use super::Timedelta;
15567        assert_eq!(Timedelta::format(Timedelta::NAT), "NaT");
15568        assert_eq!(
15569            Timedelta::format(Timedelta::NANOS_PER_DAY),
15570            "1 days 00:00:00"
15571        );
15572        assert_eq!(
15573            Timedelta::format(Timedelta::NANOS_PER_DAY + 2 * Timedelta::NANOS_PER_HOUR),
15574            "1 days 02:00:00"
15575        );
15576    }
15577
15578    #[test]
15579    fn timedelta_format_subsecond_matches_pandas() {
15580        use super::Timedelta;
15581        // pandas str(Timedelta) uses 6 fractional digits (microseconds) unless a
15582        // sub-microsecond (nanosecond) component is present, then 9 digits.
15583        // Verified vs live pandas 2.2.3.
15584        assert_eq!(
15585            Timedelta::format(1_500_000_000), // 1.5s
15586            "0 days 00:00:01.500000"
15587        );
15588        assert_eq!(
15589            Timedelta::format(1_000_000), // 1ms
15590            "0 days 00:00:00.001000"
15591        );
15592        assert_eq!(
15593            Timedelta::format(123_456_000), // 123456us
15594            "0 days 00:00:00.123456"
15595        );
15596        // Nanosecond component -> 9 digits.
15597        assert_eq!(
15598            Timedelta::format(500), // 500ns
15599            "0 days 00:00:00.000000500"
15600        );
15601        assert_eq!(Timedelta::format(123_456_789), "0 days 00:00:00.123456789");
15602    }
15603
15604    #[test]
15605    fn timedelta_format_negative_uses_python_borrow_form() {
15606        use super::Timedelta;
15607        // pandas/Python normalize negatives via floor division: the days count
15608        // goes negative, the time remainder stays non-negative, and a '+' joins
15609        // them. Verified vs live pandas 2.2.3.
15610        assert_eq!(Timedelta::format(-1_000_000_000), "-1 days +23:59:59");
15611        assert_eq!(
15612            Timedelta::format(-Timedelta::NANOS_PER_DAY),
15613            "-1 days +00:00:00"
15614        );
15615        assert_eq!(
15616            Timedelta::format(-25 * Timedelta::NANOS_PER_HOUR),
15617            "-2 days +23:00:00"
15618        );
15619        assert_eq!(
15620            Timedelta::format(-1_500_000_000),
15621            "-1 days +23:59:58.500000"
15622        );
15623        assert_eq!(Timedelta::format(-500), "-1 days +23:59:59.999999500");
15624        assert_eq!(Timedelta::format(-1), "-1 days +23:59:59.999999999");
15625    }
15626
15627    #[test]
15628    #[ignore = "foreground release attribution harness"]
15629    fn timedelta_format_single_buffer_ab_5ro9h() {
15630        use std::{hint::black_box, time::Instant};
15631
15632        use super::Timedelta;
15633
15634        fn former(nanos: i64) -> String {
15635            if nanos == Timedelta::NAT {
15636                return "NaT".to_string();
15637            }
15638
15639            let days = nanos.div_euclid(Timedelta::NANOS_PER_DAY);
15640            let rem = nanos.rem_euclid(Timedelta::NANOS_PER_DAY);
15641            let hours = rem / Timedelta::NANOS_PER_HOUR;
15642            let minutes = (rem % Timedelta::NANOS_PER_HOUR) / Timedelta::NANOS_PER_MIN;
15643            let seconds = (rem % Timedelta::NANOS_PER_MIN) / Timedelta::NANOS_PER_SEC;
15644            let frac = rem % Timedelta::NANOS_PER_SEC;
15645
15646            let time_part = format!("{hours:02}:{minutes:02}:{seconds:02}");
15647            let sep = if days < 0 { "+" } else { "" };
15648            if frac > 0 {
15649                if frac % 1_000 == 0 {
15650                    format!("{days} days {sep}{time_part}.{:06}", frac / 1_000)
15651                } else {
15652                    format!("{days} days {sep}{time_part}.{frac:09}")
15653                }
15654            } else {
15655                format!("{days} days {sep}{time_part}")
15656            }
15657        }
15658
15659        fn candidate(nanos: i64) -> String {
15660            Timedelta::format(nanos)
15661        }
15662
15663        fn elapsed(values: &[i64], format: fn(i64) -> String) -> u128 {
15664            let started = Instant::now();
15665            let mut digest = 0_usize;
15666            for &value in values {
15667                digest = digest.wrapping_add(black_box(format(black_box(value))).len());
15668            }
15669            black_box(digest);
15670            started.elapsed().as_nanos()
15671        }
15672
15673        fn median(samples: &mut [u128]) -> u128 {
15674            samples.sort_unstable();
15675            samples[samples.len() / 2]
15676        }
15677
15678        let mut seed = 0x8f42_67a1_b3d9_c50e_u64;
15679        let values: Vec<i64> = (0..16_384)
15680            .map(|i| {
15681                seed = seed
15682                    .wrapping_mul(6_364_136_223_846_793_005)
15683                    .wrapping_add(1_442_695_040_888_963_407);
15684                let magnitude = (seed & i64::MAX as u64) as i64;
15685                match i % 4 {
15686                    0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
15687                    1 => magnitude,
15688                    2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
15689                    _ => -magnitude,
15690                }
15691            })
15692            .collect();
15693
15694        for &value in &[
15695            Timedelta::NAT,
15696            0,
15697            1,
15698            -1,
15699            Timedelta::NANOS_PER_DAY,
15700            -Timedelta::NANOS_PER_DAY,
15701            i64::MAX,
15702            i64::MIN + 1,
15703        ] {
15704            assert_eq!(former(value), candidate(value));
15705        }
15706        for &value in &values {
15707            assert_eq!(former(value), candidate(value));
15708        }
15709
15710        for _ in 0..2 {
15711            black_box(elapsed(&values, former));
15712            black_box(elapsed(&values, candidate));
15713        }
15714
15715        let mut former_samples = Vec::with_capacity(18);
15716        let mut candidate_samples = Vec::with_capacity(18);
15717        for block in 0_usize..9 {
15718            if block.is_multiple_of(2) {
15719                former_samples.push(elapsed(&values, former));
15720                candidate_samples.push(elapsed(&values, candidate));
15721                candidate_samples.push(elapsed(&values, candidate));
15722                former_samples.push(elapsed(&values, former));
15723            } else {
15724                candidate_samples.push(elapsed(&values, candidate));
15725                former_samples.push(elapsed(&values, former));
15726                former_samples.push(elapsed(&values, former));
15727                candidate_samples.push(elapsed(&values, candidate));
15728            }
15729        }
15730
15731        let former_p50 = median(&mut former_samples);
15732        let candidate_p50 = median(&mut candidate_samples);
15733        eprintln!(
15734            "TIMEDELTA_FORMAT_SINGLE_BUFFER_AB rows={} former_p50_ns={former_p50} candidate_p50_ns={candidate_p50} ratio={:.6}",
15735            values.len(),
15736            former_p50 as f64 / candidate_p50 as f64,
15737        );
15738        eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB former_samples_ns={former_samples:?}");
15739        eprintln!("TIMEDELTA_FORMAT_SINGLE_BUFFER_AB candidate_samples_ns={candidate_samples:?}");
15740    }
15741
15742    #[test]
15743    fn timedelta_isoformat_basic() {
15744        use super::Timedelta;
15745        assert_eq!(Timedelta::isoformat(Timedelta::NAT), "NaT");
15746        assert_eq!(Timedelta::isoformat(0), "P0DT0H0M0S");
15747        assert_eq!(Timedelta::isoformat(Timedelta::NANOS_PER_DAY), "P1DT0H0M0S");
15748        assert_eq!(
15749            Timedelta::isoformat(
15750                Timedelta::NANOS_PER_DAY
15751                    + 2 * Timedelta::NANOS_PER_HOUR
15752                    + 30 * Timedelta::NANOS_PER_MIN
15753                    + 45 * Timedelta::NANOS_PER_SEC
15754            ),
15755            "P1DT2H30M45S"
15756        );
15757        assert_eq!(
15758            Timedelta::isoformat(Timedelta::NANOS_PER_SEC + 500_000_000),
15759            "P0DT0H0M1.5S"
15760        );
15761        // TEST-CHANGE (fvsao.68): this pinned "-P1DT1H0M0S"; pandas 2.2.3's
15762        // pd.Timedelta(-90000000000000).isoformat() is "P-2DT23H0M0S" (whole
15763        // days rounded down, then a non-negative clock), and -1ns is
15764        // "P-1DT23H59M59.999999999S" (both measured live).
15765        assert_eq!(
15766            Timedelta::isoformat(-(Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR)),
15767            "P-2DT23H0M0S"
15768        );
15769        assert_eq!(Timedelta::isoformat(-1), "P-1DT23H59M59.999999999S");
15770    }
15771
15772    #[test]
15773    #[ignore = "foreground release attribution harness"]
15774    fn timedelta_isoformat_single_buffer_ab_7jra1() {
15775        use std::{hint::black_box, time::Instant};
15776
15777        use super::Timedelta;
15778
15779        fn former_impl(nanos: i64) -> String {
15780            if nanos == Timedelta::NAT {
15781                return "NaT".to_string();
15782            }
15783
15784            let negative = nanos < 0;
15785            let abs_nanos = nanos.saturating_abs();
15786            let days = abs_nanos / Timedelta::NANOS_PER_DAY;
15787            let remaining = abs_nanos % Timedelta::NANOS_PER_DAY;
15788            let hours = remaining / Timedelta::NANOS_PER_HOUR;
15789            let remaining = remaining % Timedelta::NANOS_PER_HOUR;
15790            let minutes = remaining / Timedelta::NANOS_PER_MIN;
15791            let remaining = remaining % Timedelta::NANOS_PER_MIN;
15792            let seconds = remaining / Timedelta::NANOS_PER_SEC;
15793            let sub_sec_nanos = remaining % Timedelta::NANOS_PER_SEC;
15794
15795            let mut result = String::new();
15796            if negative {
15797                result.push('-');
15798            }
15799
15800            result.push_str(&format!("P{days}DT{hours}H{minutes}M"));
15801
15802            if sub_sec_nanos == 0 {
15803                result.push_str(&format!("{seconds}S"));
15804            } else {
15805                let frac = format!("{sub_sec_nanos:09}");
15806                let trimmed = frac.trim_end_matches('0');
15807                result.push_str(&format!("{seconds}.{trimmed}S"));
15808            }
15809
15810            result
15811        }
15812
15813        fn elapsed(values: &[i64], format: impl Fn(i64) -> String) -> u128 {
15814            let start = Instant::now();
15815            let mut digest = 0_usize;
15816            for &value in values {
15817                digest = digest.wrapping_add(black_box(format(black_box(value))).len());
15818            }
15819            black_box(digest);
15820            start.elapsed().as_nanos()
15821        }
15822
15823        fn median(values: &mut [u128]) -> u128 {
15824            values.sort_unstable();
15825            values[values.len() / 2]
15826        }
15827
15828        let mut seed = 0x7d5a_4c31_91e2_b607_u64;
15829        let values: Vec<i64> = (0..16_384)
15830            .map(|i| {
15831                seed = seed
15832                    .wrapping_mul(6_364_136_223_846_793_005)
15833                    .wrapping_add(1_442_695_040_888_963_407);
15834                let magnitude =
15835                    (seed & i64::MAX as u64) as i64 % (3_650 * Timedelta::NANOS_PER_DAY);
15836                match i % 4 {
15837                    0 => magnitude - magnitude % Timedelta::NANOS_PER_SEC,
15838                    1 => magnitude,
15839                    2 => -(magnitude - magnitude % Timedelta::NANOS_PER_MICRO),
15840                    _ => -magnitude,
15841                }
15842            })
15843            .collect();
15844
15845        // The former implementation wrote a negative duration "-P..."; since
15846        // fvsao.68 it is pandas' "P-..." form, so the two agree on
15847        // non-negative durations only (the timing still covers both signs).
15848        for &value in &[Timedelta::NAT, 0, 1, Timedelta::NANOS_PER_DAY, i64::MAX] {
15849            assert_eq!(former_impl(value), Timedelta::isoformat(value));
15850        }
15851        for &value in values.iter().filter(|value| **value >= 0) {
15852            assert_eq!(former_impl(value), Timedelta::isoformat(value));
15853        }
15854
15855        for _ in 0..2 {
15856            black_box(elapsed(&values, former_impl));
15857            black_box(elapsed(&values, Timedelta::isoformat));
15858        }
15859
15860        let mut former = Vec::with_capacity(18);
15861        let mut candidate = Vec::with_capacity(18);
15862        for block in 0..9 {
15863            if block % 2 == 0 {
15864                former.push(elapsed(&values, former_impl));
15865                candidate.push(elapsed(&values, Timedelta::isoformat));
15866                candidate.push(elapsed(&values, Timedelta::isoformat));
15867                former.push(elapsed(&values, former_impl));
15868            } else {
15869                candidate.push(elapsed(&values, Timedelta::isoformat));
15870                former.push(elapsed(&values, former_impl));
15871                former.push(elapsed(&values, former_impl));
15872                candidate.push(elapsed(&values, Timedelta::isoformat));
15873            }
15874        }
15875
15876        let former_p50 = median(&mut former);
15877        let candidate_p50 = median(&mut candidate);
15878        eprintln!(
15879            "ISOFORMAT_AB rows={} former_p50_ns={} candidate_p50_ns={} ratio={:.6} former_ns_per_row={:.3} candidate_ns_per_row={:.3}",
15880            values.len(),
15881            former_p50,
15882            candidate_p50,
15883            former_p50 as f64 / candidate_p50 as f64,
15884            former_p50 as f64 / values.len() as f64,
15885            candidate_p50 as f64 / values.len() as f64,
15886        );
15887        eprintln!("ISOFORMAT_AB former_samples_ns={former:?}");
15888        eprintln!("ISOFORMAT_AB candidate_samples_ns={candidate:?}");
15889    }
15890
15891    #[test]
15892    fn timedelta_floor_ceil_round() {
15893        use super::Timedelta;
15894        let nanos = Timedelta::NANOS_PER_HOUR + 30 * Timedelta::NANOS_PER_MIN;
15895
15896        // floor: rounds down
15897        assert_eq!(Timedelta::floor(nanos, "h"), Timedelta::NANOS_PER_HOUR);
15898        assert_eq!(Timedelta::floor(nanos, "d"), 0);
15899
15900        // ceil: rounds up
15901        assert_eq!(Timedelta::ceil(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
15902        assert_eq!(Timedelta::ceil(nanos, "d"), Timedelta::NANOS_PER_DAY);
15903
15904        // round: rounds to nearest (banker's rounding on tie)
15905        assert_eq!(Timedelta::round(nanos, "h"), 2 * Timedelta::NANOS_PER_HOUR);
15906
15907        // NaT preserved
15908        assert_eq!(Timedelta::floor(Timedelta::NAT, "h"), Timedelta::NAT);
15909        assert_eq!(Timedelta::ceil(Timedelta::NAT, "h"), Timedelta::NAT);
15910        assert_eq!(Timedelta::round(Timedelta::NAT, "h"), Timedelta::NAT);
15911
15912        // Invalid freq returns NAT
15913        assert_eq!(Timedelta::floor(nanos, "invalid"), Timedelta::NAT);
15914    }
15915
15916    #[test]
15917    fn timedelta_floor_ceil_negative_use_euclidean_rounding_t79yh() {
15918        use super::Timedelta;
15919
15920        assert_eq!(
15921            Timedelta::floor(-1, "s"),
15922            -Timedelta::NANOS_PER_SEC,
15923            "floor(-1ns, 1s)"
15924        );
15925        assert_eq!(Timedelta::ceil(-1, "s"), 0, "ceil(-1ns, 1s)");
15926        assert_eq!(
15927            Timedelta::floor(-1_500_000_000, "s"),
15928            -2 * Timedelta::NANOS_PER_SEC
15929        );
15930        assert_eq!(
15931            Timedelta::ceil(-1_500_000_000, "s"),
15932            -Timedelta::NANOS_PER_SEC
15933        );
15934        assert_eq!(
15935            Timedelta::floor(-Timedelta::NANOS_PER_SEC, "s"),
15936            -Timedelta::NANOS_PER_SEC
15937        );
15938        assert_eq!(
15939            Timedelta::ceil(-Timedelta::NANOS_PER_SEC, "s"),
15940            -Timedelta::NANOS_PER_SEC
15941        );
15942        assert_eq!(
15943            Timedelta::floor(1_500_000_000, "s"),
15944            Timedelta::NANOS_PER_SEC
15945        );
15946        assert_eq!(
15947            Timedelta::ceil(1_500_000_000, "s"),
15948            2 * Timedelta::NANOS_PER_SEC
15949        );
15950    }
15951
15952    #[test]
15953    fn timedelta_scalar_dtype() {
15954        let td = Scalar::Timedelta64(86_400_000_000_000);
15955        assert_eq!(td.dtype(), DType::Timedelta64);
15956    }
15957
15958    #[test]
15959    fn timedelta_scalar_is_missing() {
15960        use super::Timedelta;
15961        let valid = Scalar::Timedelta64(1000);
15962        let nat = Scalar::Timedelta64(Timedelta::NAT);
15963        assert!(!valid.is_missing());
15964        assert!(nat.is_missing());
15965    }
15966
15967    #[test]
15968    fn dtype_utf8_deserializes_legacy_aliases() {
15969        let dtype: DType = serde_json::from_str("\"str\"").unwrap();
15970        assert_eq!(dtype, DType::Utf8);
15971
15972        let dtype: DType = serde_json::from_str("\"string\"").unwrap();
15973        assert_eq!(dtype, DType::Utf8);
15974    }
15975
15976    #[test]
15977    fn datetime64_dtype_carries_timezone_00ze3() {
15978        let naive = DType::datetime64_naive();
15979        assert_eq!(naive.timezone(), None);
15980        assert_eq!(naive.display_name(), "datetime64[ns]");
15981
15982        let aware = DType::datetime64_tz("America/New_York");
15983        assert_eq!(aware.timezone(), Some("America/New_York"));
15984        assert_eq!(aware.display_name(), "datetime64[ns, America/New_York]");
15985        assert_ne!(aware, naive, "timezone must participate in dtype identity");
15986
15987        let json = serde_json::to_string(&aware).expect("serialize timezone dtype");
15988        assert_eq!(
15989            serde_json::from_str::<DType>(&json).expect("deserialize timezone dtype"),
15990            aware
15991        );
15992    }
15993
15994    #[test]
15995    fn scalar_utf8_deserializes_legacy_aliases() {
15996        let scalar: Scalar = serde_json::from_str(r#"{"kind":"str","value":"x"}"#).unwrap();
15997        assert_eq!(scalar, Scalar::Utf8("x".to_owned()));
15998
15999        let scalar: Scalar = serde_json::from_str(r#"{"kind":"string","value":"y"}"#).unwrap();
16000        assert_eq!(scalar, Scalar::Utf8("y".to_owned()));
16001    }
16002
16003    #[test]
16004    fn nancumsum_skips_nulls_and_accumulates() {
16005        let values = vec![
16006            Scalar::Float64(1.0),
16007            Scalar::Null(NullKind::NaN),
16008            Scalar::Float64(2.0),
16009            Scalar::Float64(3.0),
16010        ];
16011        let out = super::nancumsum(&values);
16012        assert!(matches!(out[0], Scalar::Float64(v) if (v - 1.0).abs() < 1e-9));
16013        assert!(out[1].is_missing());
16014        assert!(matches!(out[2], Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
16015        assert!(matches!(out[3], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
16016    }
16017
16018    #[test]
16019    fn nancumprod_skips_nulls_and_multiplies() {
16020        let values = vec![
16021            Scalar::Float64(2.0),
16022            Scalar::Null(NullKind::NaN),
16023            Scalar::Float64(3.0),
16024            Scalar::Float64(4.0),
16025        ];
16026        let out = super::nancumprod(&values);
16027        assert!(matches!(out[0], Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
16028        assert!(out[1].is_missing());
16029        assert!(matches!(out[2], Scalar::Float64(v) if (v - 6.0).abs() < 1e-9));
16030        assert!(matches!(out[3], Scalar::Float64(v) if (v - 24.0).abs() < 1e-9));
16031    }
16032
16033    #[test]
16034    fn nancummax_tracks_running_max() {
16035        let values = vec![
16036            Scalar::Float64(1.0),
16037            Scalar::Float64(3.0),
16038            Scalar::Null(NullKind::NaN),
16039            Scalar::Float64(2.0),
16040            Scalar::Float64(5.0),
16041        ];
16042        let out = super::nancummax(&values);
16043        assert_eq!(out[0], Scalar::Float64(1.0));
16044        assert_eq!(out[1], Scalar::Float64(3.0));
16045        assert!(out[2].is_missing());
16046        assert_eq!(out[3], Scalar::Float64(3.0));
16047        assert_eq!(out[4], Scalar::Float64(5.0));
16048    }
16049
16050    #[test]
16051    fn nancummin_tracks_running_min() {
16052        let values = vec![
16053            Scalar::Float64(5.0),
16054            Scalar::Float64(3.0),
16055            Scalar::Null(NullKind::NaN),
16056            Scalar::Float64(4.0),
16057            Scalar::Float64(1.0),
16058        ];
16059        let out = super::nancummin(&values);
16060        assert_eq!(out[0], Scalar::Float64(5.0));
16061        assert_eq!(out[1], Scalar::Float64(3.0));
16062        assert!(out[2].is_missing());
16063        assert_eq!(out[3], Scalar::Float64(3.0));
16064        assert_eq!(out[4], Scalar::Float64(1.0));
16065    }
16066
16067    #[test]
16068    fn nancumsum_timedelta64_preserves_dtype_x0x91() {
16069        // Per br-frankenpandas-x0x91: pandas td_series.cumsum() returns
16070        // Timedelta64 running sums. Was silently NaN before.
16071        let one_hour = 3_600 * 1_000_000_000_i64;
16072        let values = vec![
16073            Scalar::Timedelta64(one_hour),
16074            Scalar::Timedelta64(2 * one_hour),
16075            Scalar::Timedelta64(3 * one_hour),
16076        ];
16077        let out = super::nancumsum(&values);
16078        assert_eq!(out[0], Scalar::Timedelta64(one_hour));
16079        assert_eq!(out[1], Scalar::Timedelta64(3 * one_hour));
16080        assert_eq!(out[2], Scalar::Timedelta64(6 * one_hour));
16081    }
16082
16083    #[test]
16084    fn nancummax_nancummin_timedelta64_preserves_dtype_x0x91() {
16085        let one_hour = 3_600 * 1_000_000_000_i64;
16086        let values = vec![
16087            Scalar::Timedelta64(2 * one_hour),
16088            Scalar::Timedelta64(5 * one_hour),
16089            Scalar::Timedelta64(one_hour),
16090            Scalar::Timedelta64(3 * one_hour),
16091        ];
16092        let mx = super::nancummax(&values);
16093        assert_eq!(mx[0], Scalar::Timedelta64(2 * one_hour));
16094        assert_eq!(mx[1], Scalar::Timedelta64(5 * one_hour));
16095        assert_eq!(mx[2], Scalar::Timedelta64(5 * one_hour));
16096        assert_eq!(mx[3], Scalar::Timedelta64(5 * one_hour));
16097
16098        let mn = super::nancummin(&values);
16099        assert_eq!(mn[0], Scalar::Timedelta64(2 * one_hour));
16100        assert_eq!(mn[1], Scalar::Timedelta64(2 * one_hour));
16101        assert_eq!(mn[2], Scalar::Timedelta64(one_hour));
16102        assert_eq!(mn[3], Scalar::Timedelta64(one_hour));
16103    }
16104
16105    #[test]
16106    fn nancumulative_timedelta64_skips_nat_x0x91() {
16107        let one_hour = 3_600 * 1_000_000_000_i64;
16108        let values = vec![
16109            Scalar::Timedelta64(one_hour),
16110            Scalar::Timedelta64(Timedelta::NAT),
16111            Scalar::Timedelta64(2 * one_hour),
16112        ];
16113        let cs = super::nancumsum(&values);
16114        assert_eq!(cs[0], Scalar::Timedelta64(one_hour));
16115        assert!(cs[1].is_missing());
16116        assert_eq!(cs[2], Scalar::Timedelta64(3 * one_hour));
16117    }
16118
16119    #[test]
16120    fn nancumulative_matches_numeric_and_timedelta_oracle_k63oz() {
16121        // Differential vs independent cumulative nanops oracles
16122        // (br-frankenpandas-k63oz). Seeded LCG, no mocks.
16123        fn next(seed: &mut u64) -> u64 {
16124            *seed = seed
16125                .wrapping_mul(3202034522624059733)
16126                .wrapping_add(4354685564936845319);
16127            *seed
16128        }
16129
16130        fn assert_vec(case: usize, family: &str, op: &str, actual: &[Scalar], expected: &[Scalar]) {
16131            assert_eq!(
16132                actual.len(),
16133                expected.len(),
16134                "case={case} family={family} op={op}: length mismatch"
16135            );
16136            for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
16137                assert!(
16138                    actual.semantic_eq(expected),
16139                    "case={case} family={family} op={op} pos={pos}: expected {expected:?}, got {actual:?}"
16140                );
16141            }
16142        }
16143
16144        fn expected_numeric(
16145            values: &[Scalar],
16146        ) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
16147            let mut sum = Vec::with_capacity(values.len());
16148            let mut prod = Vec::with_capacity(values.len());
16149            let mut max = Vec::with_capacity(values.len());
16150            let mut min = Vec::with_capacity(values.len());
16151            let mut running_sum = 0.0_f64;
16152            let mut running_prod = 1.0_f64;
16153            let mut running_max: Option<f64> = None;
16154            let mut running_min: Option<f64> = None;
16155
16156            for value in values {
16157                if value.is_missing() {
16158                    sum.push(Scalar::Null(NullKind::NaN));
16159                    prod.push(Scalar::Null(NullKind::NaN));
16160                    max.push(Scalar::Null(NullKind::NaN));
16161                    min.push(Scalar::Null(NullKind::NaN));
16162                    continue;
16163                }
16164                let Ok(value) = value.to_f64() else {
16165                    sum.push(Scalar::Null(NullKind::NaN));
16166                    prod.push(Scalar::Null(NullKind::NaN));
16167                    max.push(Scalar::Null(NullKind::NaN));
16168                    min.push(Scalar::Null(NullKind::NaN));
16169                    continue;
16170                };
16171                if value.is_nan() {
16172                    sum.push(Scalar::Null(NullKind::NaN));
16173                    prod.push(Scalar::Null(NullKind::NaN));
16174                    max.push(Scalar::Null(NullKind::NaN));
16175                    min.push(Scalar::Null(NullKind::NaN));
16176                    continue;
16177                }
16178                running_sum += value;
16179                running_prod *= value;
16180                running_max = Some(running_max.map_or(value, |current| current.max(value)));
16181                running_min = Some(running_min.map_or(value, |current| current.min(value)));
16182                sum.push(Scalar::Float64(running_sum));
16183                prod.push(Scalar::Float64(running_prod));
16184                max.push(Scalar::Float64(running_max.expect("initialized")));
16185                min.push(Scalar::Float64(running_min.expect("initialized")));
16186            }
16187
16188            (sum, prod, max, min)
16189        }
16190
16191        fn expected_timedelta(values: &[Scalar]) -> (Vec<Scalar>, Vec<Scalar>, Vec<Scalar>) {
16192            let mut sum = Vec::with_capacity(values.len());
16193            let mut max = Vec::with_capacity(values.len());
16194            let mut min = Vec::with_capacity(values.len());
16195            let mut running_sum = 0_i128;
16196            let mut running_max: Option<i64> = None;
16197            let mut running_min: Option<i64> = None;
16198
16199            for value in values {
16200                if value.is_missing() {
16201                    sum.push(Scalar::Null(NullKind::NaT));
16202                    max.push(Scalar::Null(NullKind::NaT));
16203                    min.push(Scalar::Null(NullKind::NaT));
16204                    continue;
16205                }
16206                let Scalar::Timedelta64(ns) = value else {
16207                    sum.push(Scalar::Null(NullKind::NaT));
16208                    max.push(Scalar::Null(NullKind::NaT));
16209                    min.push(Scalar::Null(NullKind::NaT));
16210                    continue;
16211                };
16212                running_sum = running_sum.saturating_add(i128::from(*ns));
16213                running_max = Some(running_max.map_or(*ns, |current| current.max(*ns)));
16214                running_min = Some(running_min.map_or(*ns, |current| current.min(*ns)));
16215                // br-frankenpandas-opz27: mirror the production contract (NaT
16216                // outside the representable range), not the old clamp.
16217                sum.push(super::timedelta_ns_to_scalar(running_sum));
16218                max.push(Scalar::Timedelta64(running_max.expect("initialized")));
16219                min.push(Scalar::Timedelta64(running_min.expect("initialized")));
16220            }
16221
16222            (sum, max, min)
16223        }
16224
16225        let mut seed = 0xc0de_c63a_5eed_0421_u64;
16226        for case in 0..260 {
16227            let len = (next(&mut seed) % 89 + 1) as usize;
16228
16229            let mut numeric = Vec::with_capacity(len);
16230            numeric.push(Scalar::Int64(case as i64 - 130));
16231            for _ in 1..len {
16232                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16233                numeric.push(match next(&mut seed) % 8 {
16234                    0 => Scalar::Null(NullKind::Null),
16235                    1 => Scalar::Null(NullKind::NaN),
16236                    2 => Scalar::Float64(f64::NAN),
16237                    3 => Scalar::Bool(raw & 1 == 0),
16238                    4 => Scalar::Int64(raw % 251),
16239                    5 => Scalar::Float64(raw as f64 / 79.0),
16240                    6 => Scalar::Float64(0.0),
16241                    _ => Scalar::Float64(-0.0),
16242                });
16243            }
16244            let (sum, prod, max, min) = expected_numeric(&numeric);
16245            assert_vec(case, "numeric", "cumsum", &super::nancumsum(&numeric), &sum);
16246            assert_vec(
16247                case,
16248                "numeric",
16249                "cumprod",
16250                &super::nancumprod(&numeric),
16251                &prod,
16252            );
16253            assert_vec(case, "numeric", "cummax", &super::nancummax(&numeric), &max);
16254            assert_vec(case, "numeric", "cummin", &super::nancummin(&numeric), &min);
16255
16256            let mut timedeltas = Vec::with_capacity(len);
16257            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
16258            for _ in 1..len {
16259                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16260                timedeltas.push(match next(&mut seed) % 7 {
16261                    0 => Scalar::Null(NullKind::Null),
16262                    1 => Scalar::Timedelta64(i64::MIN),
16263                    _ => Scalar::Timedelta64(raw),
16264                });
16265            }
16266            let (td_sum, td_max, td_min) = expected_timedelta(&timedeltas);
16267            assert_vec(
16268                case,
16269                "timedelta",
16270                "cumsum",
16271                &super::nancumsum(&timedeltas),
16272                &td_sum,
16273            );
16274            assert_vec(
16275                case,
16276                "timedelta",
16277                "cummax",
16278                &super::nancummax(&timedeltas),
16279                &td_max,
16280            );
16281            assert_vec(
16282                case,
16283                "timedelta",
16284                "cummin",
16285                &super::nancummin(&timedeltas),
16286                &td_min,
16287            );
16288        }
16289    }
16290
16291    #[test]
16292    fn nanquantile_linear_interpolation_matches_numpy() {
16293        let values = vec![
16294            Scalar::Float64(1.0),
16295            Scalar::Float64(2.0),
16296            Scalar::Float64(3.0),
16297            Scalar::Float64(4.0),
16298            Scalar::Float64(5.0),
16299        ];
16300        // median
16301        let q = super::nanquantile(&values, 0.5);
16302        assert!(matches!(q, Scalar::Float64(v) if (v - 3.0).abs() < 1e-9));
16303        // 25th percentile: interpolate between 2.0 and 3.0 at pos 1.0 → 2.0
16304        let q25 = super::nanquantile(&values, 0.25);
16305        assert!(matches!(q25, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
16306    }
16307
16308    #[test]
16309    fn nanquantile_ignores_nulls() {
16310        let values = vec![
16311            Scalar::Float64(1.0),
16312            Scalar::Null(NullKind::NaN),
16313            Scalar::Float64(3.0),
16314        ];
16315        let q = super::nanquantile(&values, 0.5);
16316        assert!(matches!(q, Scalar::Float64(v) if (v - 2.0).abs() < 1e-9));
16317    }
16318
16319    #[test]
16320    fn nanquantile_empty_and_out_of_range_yield_null() {
16321        assert!(super::nanquantile(&[], 0.5).is_missing());
16322        assert!(super::nanquantile(&[Scalar::Float64(1.0)], 1.5).is_missing());
16323        assert!(super::nanquantile(&[Scalar::Float64(1.0)], -0.1).is_missing());
16324    }
16325
16326    #[test]
16327    fn nanquantile_timedelta64_preserves_dtype_5djk7() {
16328        // Per br-frankenpandas-5djk7: pandas td_series.quantile(q) returns
16329        // Timedelta64 — was silently NaN before via collect_finite.
16330        let one_hour: i64 = 3_600 * 1_000_000_000;
16331        let vals = vec![
16332            Scalar::Timedelta64(one_hour),
16333            Scalar::Timedelta64(2 * one_hour),
16334            Scalar::Timedelta64(3 * one_hour),
16335            Scalar::Timedelta64(4 * one_hour),
16336            Scalar::Timedelta64(5 * one_hour),
16337        ];
16338        assert_eq!(
16339            super::nanquantile(&vals, 0.5),
16340            Scalar::Timedelta64(3 * one_hour)
16341        );
16342        assert_eq!(
16343            super::nanquantile(&vals, 0.0),
16344            Scalar::Timedelta64(one_hour)
16345        );
16346        assert_eq!(
16347            super::nanquantile(&vals, 1.0),
16348            Scalar::Timedelta64(5 * one_hour)
16349        );
16350    }
16351
16352    #[test]
16353    fn nanquantile_timedelta64_linear_interpolation_5djk7() {
16354        let one_hour: i64 = 3_600 * 1_000_000_000;
16355        let vals = vec![
16356            Scalar::Timedelta64(one_hour),
16357            Scalar::Timedelta64(3 * one_hour),
16358        ];
16359        // Linear interpolation: at q=0.5, midpoint = 2h
16360        assert_eq!(
16361            super::nanquantile(&vals, 0.5),
16362            Scalar::Timedelta64(2 * one_hour)
16363        );
16364    }
16365
16366    #[test]
16367    fn nanquantile_matches_numeric_and_timedelta_oracle_ecb7r() {
16368        // Differential vs independent sort-based quantile oracles
16369        // (br-frankenpandas-ecb7r). Seeded LCG, no mocks.
16370        fn next(seed: &mut u64) -> u64 {
16371            *seed = seed
16372                .wrapping_mul(3202034522624059733)
16373                .wrapping_add(4354685564936845319);
16374            *seed
16375        }
16376
16377        fn interpolated(sorted: &[f64], q: f64) -> f64 {
16378            if sorted.len() == 1 {
16379                return sorted[0];
16380            }
16381            let pos = q * (sorted.len() - 1) as f64;
16382            let lo = pos.floor() as usize;
16383            let hi = pos.ceil() as usize;
16384            if lo == hi {
16385                sorted[lo]
16386            } else {
16387                let weight = pos - lo as f64;
16388                sorted[lo] + (sorted[hi] - sorted[lo]) * weight
16389            }
16390        }
16391
16392        fn expected_numeric(values: &[Scalar], q: f64) -> Scalar {
16393            if !(0.0..=1.0).contains(&q) {
16394                return Scalar::Null(NullKind::NaN);
16395            }
16396            let mut samples = values
16397                .iter()
16398                .filter(|value| !value.is_missing())
16399                .filter_map(|value| value.to_f64().ok())
16400                .collect::<Vec<_>>();
16401            if samples.is_empty() {
16402                return Scalar::Null(NullKind::NaN);
16403            }
16404            samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
16405            Scalar::Float64(interpolated(&samples, q))
16406        }
16407
16408        fn expected_timedelta(values: &[Scalar], q: f64) -> Scalar {
16409            if !(0.0..=1.0).contains(&q) {
16410                return Scalar::Null(NullKind::NaN);
16411            }
16412            let mut samples = values
16413                .iter()
16414                .filter_map(|value| match value {
16415                    Scalar::Timedelta64(ns) if !value.is_missing() => Some(*ns as f64),
16416                    _ => None,
16417                })
16418                .collect::<Vec<_>>();
16419            if samples.is_empty() {
16420                // Per br-frankenpandas-k7apg: a NaT-only Timedelta input stays in
16421                // the Timedelta family (pandas returns NaT, not float NaN).
16422                return Scalar::Timedelta64(Timedelta::NAT);
16423            }
16424            samples.sort_by(|left, right| left.partial_cmp(right).expect("finite values"));
16425            Scalar::Timedelta64(interpolated(&samples, q) as i64)
16426        }
16427
16428        fn assert_quantile(case: usize, family: &str, values: &[Scalar], q: f64, expected: Scalar) {
16429            let actual = super::nanquantile(values, q);
16430            assert!(
16431                actual.semantic_eq(&expected),
16432                "case={case} family={family} q={q}: expected {expected:?}, got {actual:?} for {values:?}"
16433            );
16434        }
16435
16436        let numeric_all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
16437        assert_quantile(
16438            usize::MAX,
16439            "numeric_all_missing",
16440            &numeric_all_missing,
16441            0.5,
16442            expected_numeric(&numeric_all_missing, 0.5),
16443        );
16444        assert_quantile(
16445            usize::MAX - 1,
16446            "numeric_out_of_range",
16447            &[Scalar::Float64(1.0), Scalar::Float64(2.0)],
16448            1.25,
16449            Scalar::Null(NullKind::NaN),
16450        );
16451
16452        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
16453        assert_quantile(
16454            usize::MAX - 2,
16455            "timedelta_all_missing",
16456            &td_all_missing,
16457            0.5,
16458            expected_timedelta(&td_all_missing, 0.5),
16459        );
16460        assert_quantile(
16461            usize::MAX - 3,
16462            "timedelta_out_of_range",
16463            &[Scalar::Timedelta64(1), Scalar::Timedelta64(2)],
16464            -0.25,
16465            Scalar::Null(NullKind::NaN),
16466        );
16467
16468        let mut seed = 0x4a17_1e5e_0b5e_a11d_u64;
16469        for case in 0..260 {
16470            let len = (next(&mut seed) % 83 + 1) as usize;
16471            let q = match next(&mut seed) % 8 {
16472                0 => 0.0,
16473                1 => 0.25,
16474                2 => 0.5,
16475                3 => 0.75,
16476                4 => 1.0,
16477                _ => (next(&mut seed) % 1_001) as f64 / 1_000.0,
16478            };
16479
16480            let mut numeric = Vec::with_capacity(len);
16481            numeric.push(Scalar::Int64(case as i64 - 130));
16482            for _ in 1..len {
16483                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16484                numeric.push(match next(&mut seed) % 8 {
16485                    0 => Scalar::Null(NullKind::Null),
16486                    1 => Scalar::Null(NullKind::NaN),
16487                    2 => Scalar::Float64(f64::NAN),
16488                    3 => Scalar::Bool(raw & 1 == 0),
16489                    4 => Scalar::Int64(raw % 251),
16490                    5 => Scalar::Float64(raw as f64 / 67.0),
16491                    6 => Scalar::Float64(0.0),
16492                    _ => Scalar::Float64(-0.0),
16493                });
16494            }
16495            assert_quantile(case, "numeric", &numeric, q, expected_numeric(&numeric, q));
16496
16497            let mut timedeltas = Vec::with_capacity(len);
16498            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
16499            for _ in 1..len {
16500                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16501                timedeltas.push(match next(&mut seed) % 7 {
16502                    0 => Scalar::Null(NullKind::Null),
16503                    1 => Scalar::Timedelta64(i64::MIN),
16504                    _ => Scalar::Timedelta64(raw),
16505                });
16506            }
16507            assert_quantile(
16508                case,
16509                "timedelta",
16510                &timedeltas,
16511                q,
16512                expected_timedelta(&timedeltas, q),
16513            );
16514        }
16515    }
16516
16517    #[test]
16518    fn nanargmax_returns_first_position() {
16519        let values = vec![
16520            Scalar::Float64(1.0),
16521            Scalar::Null(NullKind::NaN),
16522            Scalar::Float64(4.0),
16523            Scalar::Float64(4.0),
16524            Scalar::Float64(2.0),
16525        ];
16526        assert_eq!(super::nanargmax(&values), Some(2));
16527    }
16528
16529    #[test]
16530    fn nanargmin_returns_first_position() {
16531        let values = vec![
16532            Scalar::Float64(3.0),
16533            Scalar::Null(NullKind::NaN),
16534            Scalar::Float64(1.0),
16535            Scalar::Float64(1.0),
16536        ];
16537        assert_eq!(super::nanargmin(&values), Some(2));
16538    }
16539
16540    #[test]
16541    fn nanargmax_all_missing_returns_none() {
16542        let values = vec![Scalar::Null(NullKind::NaN), Scalar::Null(NullKind::Null)];
16543        assert_eq!(super::nanargmax(&values), None);
16544        assert_eq!(super::nanargmin(&values), None);
16545    }
16546
16547    #[test]
16548    fn nanargmax_nanargmin_match_numeric_and_timedelta_oracle_unkj6() {
16549        // Differential vs independent first-tie arg oracles
16550        // (br-frankenpandas-unkj6). Seeded LCG, no mocks.
16551        fn next(seed: &mut u64) -> u64 {
16552            *seed = seed
16553                .wrapping_mul(2862933555777941757)
16554                .wrapping_add(3037000493);
16555            *seed
16556        }
16557
16558        fn expected_numeric(values: &[Scalar], find_max: bool) -> Option<usize> {
16559            let mut best: Option<(usize, f64)> = None;
16560            for (idx, value) in values.iter().enumerate() {
16561                if value.is_missing() {
16562                    continue;
16563                }
16564                let Ok(value) = value.to_f64() else {
16565                    continue;
16566                };
16567                if value.is_nan() {
16568                    continue;
16569                }
16570                match best {
16571                    None => best = Some((idx, value)),
16572                    Some((_, current))
16573                        if (find_max && value > current) || (!find_max && value < current) =>
16574                    {
16575                        best = Some((idx, value));
16576                    }
16577                    _ => {}
16578                }
16579            }
16580            best.map(|(idx, _)| idx)
16581        }
16582
16583        fn expected_timedelta(values: &[Scalar], find_max: bool) -> Option<usize> {
16584            let mut best: Option<(usize, i64)> = None;
16585            for (idx, value) in values.iter().enumerate() {
16586                if value.is_missing() {
16587                    continue;
16588                }
16589                let Scalar::Timedelta64(ns) = value else {
16590                    continue;
16591                };
16592                match best {
16593                    None => best = Some((idx, *ns)),
16594                    Some((_, current))
16595                        if (find_max && *ns > current) || (!find_max && *ns < current) =>
16596                    {
16597                        best = Some((idx, *ns));
16598                    }
16599                    _ => {}
16600                }
16601            }
16602            best.map(|(idx, _)| idx)
16603        }
16604
16605        fn assert_args(
16606            case: usize,
16607            family: &str,
16608            values: &[Scalar],
16609            expected_min: Option<usize>,
16610            expected_max: Option<usize>,
16611        ) {
16612            assert_eq!(
16613                super::nanargmin(values),
16614                expected_min,
16615                "case={case} family={family}: nanargmin mismatch for {values:?}"
16616            );
16617            assert_eq!(
16618                super::nanargmax(values),
16619                expected_max,
16620                "case={case} family={family}: nanargmax mismatch for {values:?}"
16621            );
16622        }
16623
16624        let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
16625        assert_args(usize::MAX, "numeric_all_missing", &all_missing, None, None);
16626        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
16627        assert_args(
16628            usize::MAX - 1,
16629            "timedelta_all_missing",
16630            &td_all_missing,
16631            None,
16632            None,
16633        );
16634        let positive_int64_endpoint = [
16635            Scalar::Int64(i64::MAX - 1),
16636            Scalar::Null(NullKind::Null),
16637            Scalar::Int64(i64::MAX),
16638        ];
16639        assert_args(
16640            usize::MAX - 2,
16641            "int64_positive_endpoint_exact_order",
16642            &positive_int64_endpoint,
16643            Some(0),
16644            Some(2),
16645        );
16646        let negative_int64_endpoint = [
16647            Scalar::Int64(i64::MIN + 2),
16648            Scalar::Null(NullKind::NaN),
16649            Scalar::Int64(i64::MIN + 1),
16650        ];
16651        assert_args(
16652            usize::MAX - 3,
16653            "int64_negative_endpoint_exact_order",
16654            &negative_int64_endpoint,
16655            Some(2),
16656            Some(0),
16657        );
16658
16659        let mut seed = 0xa126_5eed_ed9e_u64;
16660        for case in 0..260 {
16661            let len = (next(&mut seed) % 83 + 1) as usize;
16662
16663            let mut numeric = Vec::with_capacity(len);
16664            numeric.push(Scalar::Int64(case as i64 - 130));
16665            if len > 1 {
16666                numeric.push(Scalar::Int64(case as i64 - 130));
16667            }
16668            for _ in numeric.len()..len {
16669                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16670                numeric.push(match next(&mut seed) % 9 {
16671                    0 => Scalar::Null(NullKind::Null),
16672                    1 => Scalar::Null(NullKind::NaN),
16673                    2 => Scalar::Float64(f64::NAN),
16674                    3 => Scalar::Bool(raw & 1 == 0),
16675                    4 => Scalar::Int64(raw % 211),
16676                    5 => Scalar::Float64(raw as f64 / 47.0),
16677                    6 => Scalar::Float64(0.0),
16678                    7 => Scalar::Float64(-0.0),
16679                    _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
16680                });
16681            }
16682            assert_args(
16683                case,
16684                "numeric",
16685                &numeric,
16686                expected_numeric(&numeric, false),
16687                expected_numeric(&numeric, true),
16688            );
16689
16690            let mut timedeltas = Vec::with_capacity(len);
16691            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
16692            if len > 1 {
16693                timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
16694            }
16695            for _ in timedeltas.len()..len {
16696                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
16697                timedeltas.push(match next(&mut seed) % 7 {
16698                    0 => Scalar::Null(NullKind::Null),
16699                    1 => Scalar::Timedelta64(i64::MIN),
16700                    _ => Scalar::Timedelta64(raw),
16701                });
16702            }
16703            assert_args(
16704                case,
16705                "timedelta",
16706                &timedeltas,
16707                expected_timedelta(&timedeltas, false),
16708                expected_timedelta(&timedeltas, true),
16709            );
16710        }
16711    }
16712
16713    #[test]
16714    fn nansem_matches_std_over_sqrt_n() {
16715        let values = vec![
16716            Scalar::Float64(2.0),
16717            Scalar::Float64(4.0),
16718            Scalar::Float64(4.0),
16719            Scalar::Float64(4.0),
16720            Scalar::Float64(5.0),
16721            Scalar::Float64(5.0),
16722            Scalar::Float64(7.0),
16723            Scalar::Float64(9.0),
16724        ];
16725        // numpy/scipy: std(ddof=1) = 2.138089935299395; sem = std/sqrt(8) = 0.7559
16726        let sem = super::nansem(&values, 1);
16727        assert!(matches!(sem, Scalar::Float64(_)));
16728        let Scalar::Float64(v) = sem else {
16729            return;
16730        };
16731        assert!((v - 0.7559289460184544).abs() < 1e-9);
16732    }
16733
16734    #[test]
16735    fn nansem_grouped_is_sqrt_var_over_n_7hxqv() {
16736        // pandas 2.2.3: Series([1.0, 4.0]).groupby([0, 0]).sem() == 1.5 while
16737        // Series([1.0, 4.0]).sem() == 1.4999999999999998.
16738        let values = [
16739            Scalar::Float64(1.0),
16740            Scalar::Null(NullKind::NaN),
16741            Scalar::Float64(4.0),
16742        ];
16743        assert_eq!(super::nansem_grouped(&values, 1), Scalar::Float64(1.5));
16744        // NEGATIVE: Series.sem keeps std / sqrt(n).
16745        assert_eq!(
16746            super::nansem(&values, 1),
16747            Scalar::Float64(1.499_999_999_999_999_8)
16748        );
16749        assert!(super::nansem_grouped(&values[..1], 1).is_missing());
16750    }
16751
16752    #[test]
16753    fn grouped_reducers_add_as_pandas_group_kernels_xhogl() {
16754        // pandas 2.2.3 groupby of ten 0.1: sum 1.0, mean 0.1, var 0.0 - a
16755        // plain fold gives 0.9999999999999999, 0.09999999999999999 and
16756        // 2.1e-34 (br-frankenpandas-xhogl).
16757        let tenths: Vec<Scalar> = (0..10).map(|_| Scalar::Float64(0.1)).collect();
16758        assert_eq!(super::nansum_grouped(&tenths), Scalar::Float64(1.0));
16759        assert_eq!(super::nanmean_grouped(&tenths), Scalar::Float64(0.1));
16760        assert_eq!(super::nanvar_grouped(&tenths, 1), Scalar::Float64(0.0));
16761        assert_eq!(super::nanstd_grouped(&tenths, 1), Scalar::Float64(0.0));
16762        // NEGATIVE: the Series reductions keep their plain fold.
16763        assert_eq!(
16764            super::nansum(&tenths),
16765            Scalar::Float64(0.999_999_999_999_999_9)
16766        );
16767        // An inf keeps the sum inf (the compensation would go NaN).
16768        let mut sum = super::KahanSum::default();
16769        for value in [1.0, f64::INFINITY, 2.0] {
16770            sum.add(value);
16771        }
16772        assert_eq!(sum.sum(), f64::INFINITY);
16773        // Missing values are skipped; too few for ddof is missing.
16774        let gapped = [
16775            Scalar::Float64(1.0),
16776            Scalar::Null(NullKind::NaN),
16777            Scalar::Float64(4.0),
16778        ];
16779        assert_eq!(super::nanmean_grouped(&gapped), Scalar::Float64(2.5));
16780        assert_eq!(super::nanvar_grouped(&gapped, 1), Scalar::Float64(4.5));
16781        assert!(super::nanvar_grouped(&gapped[..1], 1).is_missing());
16782        // Timedelta input keeps the exact integer paths.
16783        let spans = [Scalar::Timedelta64(1), Scalar::Timedelta64(2)];
16784        assert_eq!(super::nansum_grouped(&spans), super::nansum(&spans));
16785    }
16786
16787    #[test]
16788    fn grouped_skew_is_pandas_online_group_skew_vjfq9() {
16789        // pandas 2.2.3 groupby skew of [1, 4, 8] is 0.42327316026800615 - a
16790        // two-pass form gives 0.4232731602680071 (br-frankenpandas-vjfq9).
16791        let group = [
16792            Scalar::Float64(1.0),
16793            Scalar::Null(NullKind::NaN),
16794            Scalar::Float64(4.0),
16795            Scalar::Float64(8.0),
16796        ];
16797        assert_eq!(
16798            super::nanskew_grouped(&group),
16799            Scalar::Float64(0.423_273_160_268_006_15)
16800        );
16801        // 2922 values: pandas raises (n - 1) ** 0.5 with libm pow, which is not
16802        // sqrt's answer for n - 1 = 2921 (sqrt gives -0.002284383734800802).
16803        let long: Vec<Scalar> = (0..2922_i32)
16804            .map(|i| Scalar::Float64(f64::from((i * 7919) % 1000) / 7.0))
16805            .collect();
16806        let glibc_pow = Scalar::Float64(-0.002_284_383_734_800_801_4);
16807        // That is pandas on glibc, the oracle's platform. pandas' Cython
16808        // `** 0.5` calls the platform's pow, as fp does, and Apple's libm
16809        // returns sqrt's answer for 2921 (CI 36847809394 macos-latest), so
16810        // another libm may give that one - never anything else
16811        // (br-frankenpandas-3bo1g).
16812        if cfg!(all(target_os = "linux", target_env = "gnu")) {
16813            assert_eq!(super::nanskew_grouped(&long), glibc_pow);
16814        } else {
16815            let sqrt = Scalar::Float64(-0.002_284_383_734_800_802);
16816            assert!([glibc_pow, sqrt].contains(&super::nanskew_grouped(&long)));
16817        }
16818        // A constant group is 0; below 3 values missing; an inf poisons its
16819        // group (pandas skips only NaN), where dropping it would leave [1, 2, 5].
16820        let constant = [7.0; 3].map(Scalar::Float64);
16821        assert_eq!(super::nanskew_grouped(&constant), Scalar::Float64(0.0));
16822        assert!(super::nanskew_grouped(&group[..2]).is_missing());
16823        let with_inf = [1.0, f64::INFINITY, 2.0, 5.0].map(Scalar::Float64);
16824        assert!(super::nanskew_grouped(&with_inf).is_missing());
16825    }
16826
16827    #[test]
16828    fn nansem_single_buffer_matches_former_numeric_bits_jgwg4() {
16829        fn former(values: &[Scalar], ddof: usize) -> Scalar {
16830            let nums = super::collect_finite(values);
16831            if nums.len() <= ddof {
16832                return Scalar::Null(NullKind::NaN);
16833            }
16834            match super::nanstd(values, ddof) {
16835                Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
16836                other => other,
16837            }
16838        }
16839
16840        fn assert_same_bits(values: &[Scalar], ddof: usize) {
16841            let expected = former(values, ddof);
16842            let actual = super::nansem(values, ddof);
16843            match (&expected, &actual) {
16844                (Scalar::Float64(expected), Scalar::Float64(actual)) => {
16845                    assert_eq!(
16846                        actual.to_bits(),
16847                        expected.to_bits(),
16848                        "values={values:?} ddof={ddof}"
16849                    );
16850                }
16851                _ => assert!(
16852                    actual.semantic_eq(&expected),
16853                    "values={values:?} ddof={ddof}: expected {expected:?}, got {actual:?}"
16854                ),
16855            }
16856        }
16857
16858        let mut generated = Vec::with_capacity(4_096);
16859        for idx in 0..4_096_i64 {
16860            generated.push(match idx % 257 {
16861                0 => Scalar::Null(NullKind::NaN),
16862                1 => Scalar::Float64(-0.0),
16863                2 => Scalar::Float64(0.0),
16864                _ if idx % 2 == 0 => Scalar::Int64(idx - 2_048),
16865                _ => Scalar::Float64((idx - 2_048) as f64 / 17.0),
16866            });
16867        }
16868
16869        let cases = [
16870            Vec::new(),
16871            vec![Scalar::Int64(1)],
16872            vec![
16873                Scalar::Null(NullKind::Null),
16874                Scalar::Float64(f64::NAN),
16875                Scalar::Int64(i64::MIN),
16876                Scalar::Int64(i64::MAX),
16877                Scalar::Float64(-0.0),
16878                Scalar::Float64(0.0),
16879            ],
16880            generated,
16881        ];
16882        for values in &cases {
16883            for ddof in [0, 1, values.len(), values.len().saturating_add(1)] {
16884                assert_same_bits(values, ddof);
16885            }
16886        }
16887    }
16888
16889    #[test]
16890    #[ignore = "foreground release A/B harness"]
16891    fn nansem_single_buffer_allocator_preconditioned_ab_jgwg4() {
16892        const ROWS: usize = 262_144;
16893        const BATCH: usize = 8;
16894        const BLOCKS: usize = 9;
16895        const PRECONDITION_CALLS: usize = 2;
16896
16897        fn former(values: &[Scalar], ddof: usize) -> Scalar {
16898            let nums = super::collect_finite(values);
16899            if nums.len() <= ddof {
16900                return Scalar::Null(NullKind::NaN);
16901            }
16902            match super::nanstd(values, ddof) {
16903                Scalar::Float64(std) => Scalar::Float64(std / (nums.len() as f64).sqrt()),
16904                other => other,
16905            }
16906        }
16907
16908        fn evaluate(values: &[Scalar], candidate: bool) -> Scalar {
16909            let values = std::hint::black_box(values);
16910            if candidate {
16911                super::nansem(values, 1)
16912            } else {
16913                former(values, 1)
16914            }
16915        }
16916
16917        fn elapsed_ns(values: &[Scalar], candidate: bool) -> u128 {
16918            for _ in 0..PRECONDITION_CALLS {
16919                std::hint::black_box(evaluate(values, candidate));
16920            }
16921            let started = std::time::Instant::now();
16922            for _ in 0..BATCH {
16923                std::hint::black_box(evaluate(values, candidate));
16924            }
16925            started.elapsed().as_nanos()
16926        }
16927
16928        fn median(mut samples: Vec<u128>) -> u128 {
16929            samples.sort_unstable();
16930            samples[samples.len() / 2]
16931        }
16932
16933        fn spread(a: u128, b: u128) -> f64 {
16934            a.abs_diff(b) as f64 / ((a + b) as f64 / 2.0)
16935        }
16936
16937        let values = (0..ROWS)
16938            .map(|idx| {
16939                if idx % 257 == 0 {
16940                    Scalar::Null(NullKind::NaN)
16941                } else {
16942                    Scalar::Int64((idx % 8_191) as i64 - 4_095)
16943                }
16944            })
16945            .collect::<Vec<_>>();
16946
16947        let expected_bits = match former(&values, 1) {
16948            Scalar::Float64(value) => Some(value.to_bits()),
16949            _ => None,
16950        };
16951        let actual_bits = match super::nansem(&values, 1) {
16952            Scalar::Float64(value) => Some(value.to_bits()),
16953            _ => None,
16954        };
16955        assert!(
16956            expected_bits.is_some(),
16957            "numeric nansem must return Float64"
16958        );
16959        assert_eq!(actual_bits, expected_bits, "A/B output bits");
16960
16961        std::hint::black_box(evaluate(&values, false));
16962        std::hint::black_box(evaluate(&values, true));
16963
16964        let body_started = std::time::Instant::now();
16965        let mut former_a = Vec::with_capacity(BLOCKS);
16966        let mut former_b = Vec::with_capacity(BLOCKS);
16967        let mut candidate_a = Vec::with_capacity(BLOCKS);
16968        let mut candidate_b = Vec::with_capacity(BLOCKS);
16969        for block in 0..BLOCKS {
16970            let order = if block % 2 == 0 {
16971                [(false, 0), (true, 0), (true, 1), (false, 1)]
16972            } else {
16973                [(true, 1), (false, 1), (false, 0), (true, 0)]
16974            };
16975            for (candidate, duplicate) in order {
16976                let elapsed = elapsed_ns(&values, candidate);
16977                match (candidate, duplicate) {
16978                    (false, 0) => former_a.push(elapsed),
16979                    (false, _) => former_b.push(elapsed),
16980                    (true, 0) => candidate_a.push(elapsed),
16981                    (true, _) => candidate_b.push(elapsed),
16982                }
16983            }
16984        }
16985
16986        let former_a = median(former_a) / BATCH as u128;
16987        let former_b = median(former_b) / BATCH as u128;
16988        let candidate_a = median(candidate_a) / BATCH as u128;
16989        let candidate_b = median(candidate_b) / BATCH as u128;
16990        let former_mean = (former_a + former_b) as f64 / 2.0;
16991        let candidate_mean = (candidate_a + candidate_b) as f64 / 2.0;
16992        println!(
16993            "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}",
16994            spread(former_a, former_b),
16995            spread(candidate_a, candidate_b),
16996            former_mean / candidate_mean,
16997            body_started.elapsed().as_secs_f64()
16998        );
16999    }
17000
17001    #[test]
17002    fn nansem_empty_returns_null() {
17003        assert!(super::nansem(&[], 1).is_missing());
17004        assert!(super::nansem(&[Scalar::Float64(1.0)], 1).is_missing());
17005    }
17006
17007    #[test]
17008    fn nanptp_returns_max_minus_min() {
17009        let values = vec![
17010            Scalar::Float64(3.0),
17011            Scalar::Null(NullKind::NaN),
17012            Scalar::Float64(7.0),
17013            Scalar::Float64(1.0),
17014        ];
17015        assert_eq!(super::nanptp(&values), Scalar::Float64(6.0));
17016    }
17017
17018    #[test]
17019    fn nanptp_empty_returns_null() {
17020        assert!(super::nanptp(&[]).is_missing());
17021        assert!(super::nanptp(&[Scalar::Null(NullKind::NaN)]).is_missing());
17022    }
17023
17024    #[test]
17025    fn nanptp_timedelta64_preserves_dtype_u2g0r() {
17026        // Per br-frankenpandas-u2g0r: ptp on Timedelta64 returns Timedelta64.
17027        let one_hour: i64 = 3_600 * 1_000_000_000;
17028        let values = vec![
17029            Scalar::Timedelta64(one_hour),
17030            Scalar::Timedelta64(5 * one_hour),
17031            Scalar::Timedelta64(2 * one_hour),
17032        ];
17033        assert_eq!(super::nanptp(&values), Scalar::Timedelta64(4 * one_hour));
17034    }
17035
17036    #[test]
17037    fn nanptp_matches_numeric_and_timedelta_oracle_affjt() {
17038        // Differential vs independent max-min oracles
17039        // (br-frankenpandas-affjt). Seeded LCG, no mocks.
17040        fn next(seed: &mut u64) -> u64 {
17041            *seed = seed
17042                .wrapping_mul(3202034522624059733)
17043                .wrapping_add(4354685564936845319);
17044            *seed
17045        }
17046
17047        fn expected_numeric(values: &[Scalar]) -> Scalar {
17048            let mut lo = f64::INFINITY;
17049            let mut hi = f64::NEG_INFINITY;
17050            let mut seen = false;
17051            for value in values {
17052                if value.is_missing() {
17053                    continue;
17054                }
17055                if let Ok(value) = value.to_f64() {
17056                    seen = true;
17057                    lo = lo.min(value);
17058                    hi = hi.max(value);
17059                }
17060            }
17061            if seen {
17062                Scalar::Float64(hi - lo)
17063            } else {
17064                Scalar::Null(NullKind::NaN)
17065            }
17066        }
17067
17068        fn expected_timedelta(values: &[Scalar]) -> Scalar {
17069            let mut lo = i64::MAX;
17070            let mut hi = i64::MIN;
17071            let mut seen = false;
17072            for value in values {
17073                if let Scalar::Timedelta64(ns) = value
17074                    && !value.is_missing()
17075                {
17076                    seen = true;
17077                    lo = lo.min(*ns);
17078                    hi = hi.max(*ns);
17079                }
17080            }
17081            if seen {
17082                Scalar::Timedelta64(hi - lo)
17083            } else {
17084                Scalar::Null(NullKind::NaN)
17085            }
17086        }
17087
17088        fn assert_ptp(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
17089            let actual = super::nanptp(values);
17090            assert!(
17091                actual.semantic_eq(&expected),
17092                "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
17093            );
17094        }
17095
17096        assert_ptp(
17097            usize::MAX,
17098            "numeric_all_missing",
17099            &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
17100            Scalar::Null(NullKind::NaN),
17101        );
17102        assert_ptp(
17103            usize::MAX - 1,
17104            "timedelta_all_missing",
17105            &[Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)],
17106            Scalar::Null(NullKind::NaN),
17107        );
17108        let beyond_f64_exact_ns = 200 * Timedelta::NANOS_PER_DAY;
17109        assert_ptp(
17110            usize::MAX - 2,
17111            "timedelta_one_ns_range_beyond_f64_exactness",
17112            &[
17113                Scalar::Timedelta64(beyond_f64_exact_ns),
17114                Scalar::Timedelta64(beyond_f64_exact_ns - 1),
17115                Scalar::Timedelta64(Timedelta::NAT),
17116            ],
17117            Scalar::Timedelta64(1),
17118        );
17119
17120        let mut seed = 0xa22f_17ed_57a7_15e5_u64;
17121        for case in 0..260 {
17122            let len = (next(&mut seed) % 83 + 1) as usize;
17123
17124            let mut numeric = Vec::with_capacity(len);
17125            numeric.push(Scalar::Int64(case as i64 - 130));
17126            for _ in 1..len {
17127                let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17128                numeric.push(match next(&mut seed) % 9 {
17129                    0 => Scalar::Null(NullKind::Null),
17130                    1 => Scalar::Null(NullKind::NaN),
17131                    2 => Scalar::Float64(f64::NAN),
17132                    3 => Scalar::Bool(raw & 1 == 0),
17133                    4 => Scalar::Int64(raw),
17134                    5 => Scalar::Float64(raw as f64 / 53.0),
17135                    6 => Scalar::Float64(0.0),
17136                    7 => Scalar::Float64(-0.0),
17137                    _ => Scalar::Float64(raw.signum() as f64 * f64::INFINITY),
17138                });
17139            }
17140            assert_ptp(case, "numeric", &numeric, expected_numeric(&numeric));
17141
17142            let mut timedeltas = Vec::with_capacity(len);
17143            timedeltas.push(Scalar::Timedelta64(case as i64 - 130));
17144            for _ in 1..len {
17145                let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
17146                timedeltas.push(match next(&mut seed) % 7 {
17147                    0 => Scalar::Null(NullKind::Null),
17148                    1 => Scalar::Timedelta64(i64::MIN),
17149                    _ => Scalar::Timedelta64(raw),
17150                });
17151            }
17152            assert_ptp(
17153                case,
17154                "timedelta",
17155                &timedeltas,
17156                expected_timedelta(&timedeltas),
17157            );
17158        }
17159    }
17160
17161    #[test]
17162    fn nanargmax_nanargmin_timedelta64_compare_by_ns_ql1t5() {
17163        // Per br-frankenpandas-ql1t5: argmax/argmin on Timedelta64 compare
17164        // i64 ns directly instead of silently skipping via to_f64.
17165        let one_hour: i64 = 3_600 * 1_000_000_000;
17166        let values = vec![
17167            Scalar::Timedelta64(2 * one_hour),
17168            Scalar::Timedelta64(5 * one_hour),
17169            Scalar::Timedelta64(one_hour),
17170            Scalar::Timedelta64(3 * one_hour),
17171        ];
17172        assert_eq!(super::nanargmax(&values), Some(1));
17173        assert_eq!(super::nanargmin(&values), Some(2));
17174    }
17175
17176    #[test]
17177    fn nanprod_timedelta64_returns_null_szq6a() {
17178        // Per br-frankenpandas-szq6a: pandas raises on Timedelta prod
17179        // (dimensionally undefined). We surface Null instead of the
17180        // misleading Float64(1.0) the old empty-iterator default emitted.
17181        let one_hour: i64 = 3_600 * 1_000_000_000;
17182        let values = vec![
17183            Scalar::Timedelta64(2 * one_hour),
17184            Scalar::Timedelta64(3 * one_hour),
17185        ];
17186        assert!(super::nanprod(&values).is_missing());
17187    }
17188
17189    #[test]
17190    fn nanprod_matches_numeric_and_timedelta_oracle_9938h() {
17191        // Differential vs independent product oracles
17192        // (br-frankenpandas-9938h). Seeded LCG, no mocks.
17193        fn next(seed: &mut u64) -> u64 {
17194            *seed = seed
17195                .wrapping_mul(6364136223846793005)
17196                .wrapping_add(1442695040888963407);
17197            *seed
17198        }
17199
17200        fn expected_numeric(values: &[Scalar]) -> Scalar {
17201            let mut product = 1.0_f64;
17202            for value in values {
17203                if value.is_missing() {
17204                    continue;
17205                }
17206                if let Ok(value) = value.to_f64() {
17207                    product *= value;
17208                }
17209            }
17210            Scalar::Float64(product)
17211        }
17212
17213        fn expected_timedelta(values: &[Scalar]) -> Scalar {
17214            if values
17215                .iter()
17216                .any(|value| matches!(value, Scalar::Timedelta64(_)) && !value.is_missing())
17217            {
17218                Scalar::Null(NullKind::NaN)
17219            } else {
17220                Scalar::Float64(1.0)
17221            }
17222        }
17223
17224        fn assert_prod(case: usize, family: &str, values: &[Scalar], expected: Scalar) {
17225            let actual = super::nanprod(values);
17226            assert!(
17227                actual.semantic_eq(&expected),
17228                "case={case} family={family}: expected {expected:?}, got {actual:?} for {values:?}"
17229            );
17230        }
17231
17232        let all_missing = [Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)];
17233        assert_prod(
17234            usize::MAX,
17235            "numeric_all_missing",
17236            &all_missing,
17237            Scalar::Float64(1.0),
17238        );
17239
17240        let td_all_missing = [Scalar::Timedelta64(i64::MIN), Scalar::Null(NullKind::NaN)];
17241        assert_prod(
17242            usize::MAX - 1,
17243            "timedelta_all_missing",
17244            &td_all_missing,
17245            expected_timedelta(&td_all_missing),
17246        );
17247
17248        let mut seed = 0x6e0d_9938_a11c_0de5_u64;
17249        for case in 0..280 {
17250            let len = (next(&mut seed) % 89 + 1) as usize;
17251
17252            let mut numeric = Vec::with_capacity(len);
17253            numeric.push(Scalar::Int64((case % 17) as i64 - 8));
17254            for _ in 1..len {
17255                let raw = (next(&mut seed) % 2_001) as i64 - 1_000;
17256                numeric.push(match next(&mut seed) % 9 {
17257                    0 => Scalar::Null(NullKind::Null),
17258                    1 => Scalar::Null(NullKind::NaN),
17259                    2 => Scalar::Float64(f64::NAN),
17260                    3 => Scalar::Bool(raw & 1 == 0),
17261                    4 => Scalar::Int64(raw % 19),
17262                    5 => Scalar::Float64(raw as f64 / 97.0),
17263                    6 => Scalar::Float64(0.0),
17264                    7 => Scalar::Float64(-0.0),
17265                    _ => Scalar::Float64(1.0),
17266                });
17267            }
17268            assert_prod(case, "numeric", &numeric, expected_numeric(&numeric));
17269
17270            let mut timedeltas = Vec::with_capacity(len);
17271            timedeltas.push(Scalar::Timedelta64(case as i64 - 140));
17272            for _ in 1..len {
17273                let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
17274                timedeltas.push(match next(&mut seed) % 7 {
17275                    0 => Scalar::Null(NullKind::Null),
17276                    1 => Scalar::Timedelta64(i64::MIN),
17277                    _ => Scalar::Timedelta64(raw),
17278                });
17279            }
17280            assert_prod(
17281                case,
17282                "timedelta",
17283                &timedeltas,
17284                expected_timedelta(&timedeltas),
17285            );
17286        }
17287    }
17288
17289    #[test]
17290    fn nanskew_symmetric_distribution_near_zero() {
17291        let values = vec![
17292            Scalar::Float64(1.0),
17293            Scalar::Float64(2.0),
17294            Scalar::Float64(3.0),
17295            Scalar::Float64(4.0),
17296            Scalar::Float64(5.0),
17297        ];
17298        // Perfectly symmetric -> skew = 0
17299        let skew = super::nanskew(&values);
17300        assert!(matches!(skew, Scalar::Float64(_)));
17301        let Scalar::Float64(v) = skew else {
17302            return;
17303        };
17304        assert!(v.abs() < 1e-9);
17305    }
17306
17307    #[test]
17308    fn nanskew_too_few_values_returns_null() {
17309        assert!(super::nanskew(&[]).is_missing());
17310        assert!(super::nanskew(&[Scalar::Float64(1.0), Scalar::Float64(2.0)]).is_missing());
17311    }
17312
17313    #[test]
17314    fn nankurt_symmetric_uniform_distribution() {
17315        let values = vec![
17316            Scalar::Float64(1.0),
17317            Scalar::Float64(2.0),
17318            Scalar::Float64(3.0),
17319            Scalar::Float64(4.0),
17320            Scalar::Float64(5.0),
17321        ];
17322        // pandas kurt([1,2,3,4,5]) = -1.2
17323        let kurt = super::nankurt(&values);
17324        assert!(matches!(kurt, Scalar::Float64(_)));
17325        let Scalar::Float64(v) = kurt else {
17326            return;
17327        };
17328        assert!((v + 1.2).abs() < 1e-9);
17329    }
17330
17331    #[test]
17332    fn nankurt_too_few_values_returns_null() {
17333        let vals: Vec<Scalar> = (0..3).map(|i| Scalar::Float64(i as f64)).collect();
17334        assert!(super::nankurt(&vals).is_missing());
17335    }
17336
17337    #[test]
17338    fn nanskew_constant_series_returns_zero() {
17339        let values = vec![
17340            Scalar::Float64(5.0),
17341            Scalar::Float64(5.0),
17342            Scalar::Float64(5.0),
17343        ];
17344        assert_eq!(super::nanskew(&values), Scalar::Float64(0.0));
17345        assert_eq!(
17346            super::nankurt(&[
17347                Scalar::Float64(5.0),
17348                Scalar::Float64(5.0),
17349                Scalar::Float64(5.0),
17350                Scalar::Float64(5.0),
17351            ]),
17352            Scalar::Float64(0.0)
17353        );
17354    }
17355
17356    #[test]
17357    fn nanskew_nankurt_match_numeric_oracle_jr7zk() {
17358        // Differential vs independent bias-corrected moment oracles
17359        // (br-frankenpandas-jr7zk). Seeded LCG, no mocks.
17360        fn next(seed: &mut u64) -> u64 {
17361            *seed = seed
17362                .wrapping_mul(2862933555777941757)
17363                .wrapping_add(3037000493);
17364            *seed
17365        }
17366
17367        fn samples(values: &[Scalar]) -> Vec<f64> {
17368            values
17369                .iter()
17370                .filter(|value| !value.is_missing())
17371                .filter_map(|value| value.to_f64().ok())
17372                .collect()
17373        }
17374
17375        fn expected_skew(values: &[Scalar]) -> Scalar {
17376            let samples = samples(values);
17377            let n = samples.len() as f64;
17378            if n < 3.0 {
17379                return Scalar::Null(NullKind::NaN);
17380            }
17381            let mean = samples.iter().sum::<f64>() / n;
17382            let m2 = samples
17383                .iter()
17384                .map(|value| (value - mean).powi(2))
17385                .sum::<f64>();
17386            let m3 = samples
17387                .iter()
17388                .map(|value| (value - mean).powi(3))
17389                .sum::<f64>();
17390            let s2 = m2 / (n - 1.0);
17391            if s2 == 0.0 {
17392                return Scalar::Float64(0.0);
17393            }
17394            Scalar::Float64((n / ((n - 1.0) * (n - 2.0))) * (m3 / s2.powf(1.5)))
17395        }
17396
17397        fn expected_kurt(values: &[Scalar]) -> Scalar {
17398            let samples = samples(values);
17399            let n = samples.len() as f64;
17400            if n < 4.0 {
17401                return Scalar::Null(NullKind::NaN);
17402            }
17403            let mean = samples.iter().sum::<f64>() / n;
17404            let m2 = samples
17405                .iter()
17406                .map(|value| (value - mean).powi(2))
17407                .sum::<f64>();
17408            let m4 = samples
17409                .iter()
17410                .map(|value| (value - mean).powi(4))
17411                .sum::<f64>();
17412            let s2 = m2 / (n - 1.0);
17413            if s2 == 0.0 {
17414                return Scalar::Float64(0.0);
17415            }
17416            let adj = (n * (n + 1.0)) / ((n - 1.0) * (n - 2.0) * (n - 3.0));
17417            let sub = (3.0 * (n - 1.0).powi(2)) / ((n - 2.0) * (n - 3.0));
17418            Scalar::Float64(adj * (m4 / (s2 * s2)) - sub)
17419        }
17420
17421        fn assert_moments(case: usize, values: &[Scalar]) {
17422            let expected_skew = expected_skew(values);
17423            let expected_kurt = expected_kurt(values);
17424            let actual_skew = super::nanskew(values);
17425            let actual_kurt = super::nankurt(values);
17426            assert!(
17427                actual_skew.semantic_eq(&expected_skew),
17428                "case={case}: expected skew {expected_skew:?}, got {actual_skew:?} for {values:?}"
17429            );
17430            assert!(
17431                actual_kurt.semantic_eq(&expected_kurt),
17432                "case={case}: expected kurt {expected_kurt:?}, got {actual_kurt:?} for {values:?}"
17433            );
17434        }
17435
17436        assert_moments(
17437            usize::MAX,
17438            &[Scalar::Null(NullKind::Null), Scalar::Float64(f64::NAN)],
17439        );
17440        assert_moments(
17441            usize::MAX - 1,
17442            &[
17443                Scalar::Float64(7.0),
17444                Scalar::Float64(7.0),
17445                Scalar::Float64(7.0),
17446                Scalar::Float64(7.0),
17447            ],
17448        );
17449
17450        let mut seed = 0x5ce7_9a55_a11c_0de5_u64;
17451        for case in 0..260 {
17452            let len = (next(&mut seed) % 89 + 1) as usize;
17453            let mut values = Vec::with_capacity(len);
17454            if case % 11 == 0 {
17455                values.extend((0..len).map(|_| Scalar::Float64(3.0)));
17456            } else {
17457                values.push(Scalar::Float64(case as f64 / 19.0));
17458                for _ in 1..len {
17459                    let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
17460                    values.push(match next(&mut seed) % 8 {
17461                        0 => Scalar::Null(NullKind::Null),
17462                        1 => Scalar::Null(NullKind::NaN),
17463                        2 => Scalar::Float64(f64::NAN),
17464                        3 => Scalar::Bool(raw & 1 == 0),
17465                        4 => Scalar::Int64(raw % 251),
17466                        5 => Scalar::Float64(raw as f64 / 83.0),
17467                        6 => Scalar::Float64(0.0),
17468                        _ => Scalar::Float64(-0.0),
17469                    });
17470                }
17471            }
17472            assert_moments(case, &values);
17473        }
17474    }
17475
17476    // ── Interval tests (br-frankenpandas-j8k4) ──────────────────────────
17477
17478    #[test]
17479    fn interval_default_closed_is_right() {
17480        assert_eq!(IntervalClosed::default(), IntervalClosed::Right);
17481    }
17482
17483    #[test]
17484    fn interval_left_and_right_closed_helpers() {
17485        assert!(IntervalClosed::Left.left_closed());
17486        assert!(!IntervalClosed::Left.right_closed());
17487        assert!(!IntervalClosed::Right.left_closed());
17488        assert!(IntervalClosed::Right.right_closed());
17489        assert!(IntervalClosed::Both.left_closed());
17490        assert!(IntervalClosed::Both.right_closed());
17491        assert!(!IntervalClosed::Neither.left_closed());
17492        assert!(!IntervalClosed::Neither.right_closed());
17493    }
17494
17495    #[test]
17496    fn interval_display_matches_pandas_notation() {
17497        assert_eq!(
17498            Interval::new(0.0, 5.0, IntervalClosed::Right).to_string(),
17499            "(0.0, 5.0]"
17500        );
17501        assert_eq!(
17502            Interval::new(0.0, 5.0, IntervalClosed::Left).to_string(),
17503            "[0.0, 5.0)"
17504        );
17505        assert_eq!(
17506            Interval::new(0.0, 5.0, IntervalClosed::Both).to_string(),
17507            "[0.0, 5.0]"
17508        );
17509        assert_eq!(
17510            Interval::new(0.0, 5.0, IntervalClosed::Neither).to_string(),
17511            "(0.0, 5.0)"
17512        );
17513        assert_eq!(
17514            Interval::new(2.5, 3.5, IntervalClosed::Right).to_string(),
17515            "(2.5, 3.5]"
17516        );
17517        assert_eq!(
17518            Interval::new(-1.0, 0.0, IntervalClosed::Right).to_string(),
17519            "(-1.0, 0.0]"
17520        );
17521        assert_eq!(
17522            Interval::new(1e20, 2e20, IntervalClosed::Right).to_string(),
17523            "(1e+20, 2e+20]"
17524        );
17525    }
17526
17527    #[test]
17528    fn interval_length_and_mid() {
17529        let i = Interval::new(2.0, 10.0, IntervalClosed::Right);
17530        assert_eq!(i.length(), 8.0);
17531        assert_eq!(i.mid(), 6.0);
17532    }
17533
17534    #[test]
17535    fn interval_contains_matches_closed_policy() {
17536        let right = Interval::new(0.0, 5.0, IntervalClosed::Right);
17537        assert!(!right.contains(0.0));
17538        assert!(right.contains(2.5));
17539        assert!(right.contains(5.0));
17540
17541        let left = Interval::new(0.0, 5.0, IntervalClosed::Left);
17542        assert!(left.contains(0.0));
17543        assert!(left.contains(2.5));
17544        assert!(!left.contains(5.0));
17545
17546        let both = Interval::new(0.0, 5.0, IntervalClosed::Both);
17547        assert!(both.contains(0.0));
17548        assert!(both.contains(5.0));
17549
17550        let neither = Interval::new(0.0, 5.0, IntervalClosed::Neither);
17551        assert!(!neither.contains(0.0));
17552        assert!(!neither.contains(5.0));
17553        assert!(neither.contains(2.5));
17554    }
17555
17556    #[test]
17557    fn interval_contains_nan_returns_false() {
17558        let i = Interval::new(0.0, 10.0, IntervalClosed::Both);
17559        assert!(!i.contains(f64::NAN));
17560    }
17561
17562    #[test]
17563    fn interval_is_empty_matches_pandas() {
17564        // pd.Interval(3, 3, 'right').is_empty → True
17565        assert!(Interval::new(3.0, 3.0, IntervalClosed::Right).is_empty());
17566        assert!(Interval::new(3.0, 3.0, IntervalClosed::Left).is_empty());
17567        assert!(Interval::new(3.0, 3.0, IntervalClosed::Neither).is_empty());
17568        // pd.Interval(3, 3, 'both').is_empty → False (single point)
17569        assert!(!Interval::new(3.0, 3.0, IntervalClosed::Both).is_empty());
17570        // Non-degenerate intervals are never empty.
17571        assert!(!Interval::new(0.0, 5.0, IntervalClosed::Right).is_empty());
17572    }
17573
17574    #[test]
17575    fn interval_overlaps_disjoint_returns_false() {
17576        let a = Interval::new(0.0, 1.0, IntervalClosed::Right);
17577        let b = Interval::new(2.0, 3.0, IntervalClosed::Right);
17578        assert!(!a.overlaps(&b));
17579        assert!(!b.overlaps(&a));
17580    }
17581
17582    #[test]
17583    fn interval_overlaps_nested_returns_true() {
17584        let outer = Interval::new(0.0, 10.0, IntervalClosed::Right);
17585        let inner = Interval::new(3.0, 7.0, IntervalClosed::Right);
17586        assert!(outer.overlaps(&inner));
17587        assert!(inner.overlaps(&outer));
17588    }
17589
17590    #[test]
17591    fn interval_overlaps_touching_respects_closed_policy() {
17592        // (0, 1] touching (1, 2] at point 1.
17593        let right_right = (
17594            Interval::new(0.0, 1.0, IntervalClosed::Right),
17595            Interval::new(1.0, 2.0, IntervalClosed::Right),
17596        );
17597        // right_right.0 is closed at 1; right_right.1 is open at 1 → no overlap.
17598        assert!(!right_right.0.overlaps(&right_right.1));
17599
17600        // [0, 1] touching [1, 2] — both closed at 1 → overlap.
17601        let both_both = (
17602            Interval::new(0.0, 1.0, IntervalClosed::Both),
17603            Interval::new(1.0, 2.0, IntervalClosed::Both),
17604        );
17605        assert!(both_both.0.overlaps(&both_both.1));
17606    }
17607
17608    #[test]
17609    fn interval_roundtrips_through_serde_json() {
17610        let i = Interval::new(1.5, 3.25, IntervalClosed::Both);
17611        let json = serde_json::to_string(&i).expect("serialize");
17612        let back: Interval = serde_json::from_str(&json).expect("deserialize");
17613        assert_eq!(i, back);
17614    }
17615
17616    #[test]
17617    fn interval_serde_default_closed_is_right_when_missing() {
17618        // JSON payloads that omit `closed` deserialize with the pandas default.
17619        let back: Interval =
17620            serde_json::from_str(r#"{"left":0.0,"right":5.0}"#).expect("deserialize");
17621        assert_eq!(back.closed, IntervalClosed::Right);
17622    }
17623
17624    // ── Period tests (br-frankenpandas-epoj) ────────────────────────────
17625
17626    #[test]
17627    fn period_freq_parses_canonical_aliases() {
17628        assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::ANNUAL));
17629        assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::ANNUAL));
17630        assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::QUARTERLY));
17631        assert_eq!(PeriodFreq::parse("M"), Some(PeriodFreq::Monthly));
17632        assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::WEEKLY));
17633        assert_eq!(PeriodFreq::parse("D"), Some(PeriodFreq::Daily));
17634        assert_eq!(PeriodFreq::parse("B"), Some(PeriodFreq::Business));
17635        assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
17636        assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
17637        assert_eq!(PeriodFreq::parse("min"), Some(PeriodFreq::Minutely));
17638        assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
17639    }
17640
17641    #[test]
17642    fn period_freq_parse_is_case_insensitive() {
17643        assert_eq!(PeriodFreq::parse("quarterly"), Some(PeriodFreq::QUARTERLY));
17644        assert_eq!(PeriodFreq::parse("MONTHLY"), Some(PeriodFreq::Monthly));
17645    }
17646
17647    #[test]
17648    fn period_freq_rejects_unknown_aliases() {
17649        assert_eq!(PeriodFreq::parse("nanosec"), None);
17650        assert_eq!(PeriodFreq::parse(""), None);
17651        assert_eq!(PeriodFreq::parse("xyz"), None);
17652    }
17653
17654    #[test]
17655    fn period_freq_alias_roundtrip() {
17656        for freq in [
17657            PeriodFreq::ANNUAL,
17658            PeriodFreq::QUARTERLY,
17659            PeriodFreq::Monthly,
17660            PeriodFreq::WEEKLY,
17661            PeriodFreq::Daily,
17662            PeriodFreq::Business,
17663            PeriodFreq::Hourly,
17664            PeriodFreq::Minutely,
17665            PeriodFreq::Secondly,
17666            PeriodFreq::Milliseconds,
17667            PeriodFreq::Microseconds,
17668            PeriodFreq::Nanoseconds,
17669        ] {
17670            assert_eq!(PeriodFreq::parse(freq.alias()), Some(freq));
17671        }
17672    }
17673
17674    /// Anchored aliases parse to their anchor and print back; the shifts move
17675    /// a month count / week start onto the fiscal calendar; a W-MON label
17676    /// spans Tuesday..Monday (live pandas 2.2.3: Period('2024-03-01', 'W-MON')
17677    /// is '2024-02-27/2024-03-04', ordinal 2827; br-frankenpandas-39h5n).
17678    #[test]
17679    fn anchored_period_freqs_parse_print_and_shift_39h5n() {
17680        for month in 1..=12_u8 {
17681            for freq in [PeriodFreq::Annual(month), PeriodFreq::Quarterly(month)] {
17682                assert_eq!(PeriodFreq::parse(freq.alias()), Some(freq));
17683            }
17684        }
17685        for day in 0..7_u8 {
17686            assert_eq!(
17687                PeriodFreq::parse(PeriodFreq::Weekly(day).alias()),
17688                Some(PeriodFreq::Weekly(day))
17689            );
17690        }
17691        assert_eq!(PeriodFreq::parse("Y-JUN"), Some(PeriodFreq::Annual(6)));
17692        assert_eq!(PeriodFreq::parse("A-JUN"), Some(PeriodFreq::Annual(6)));
17693        assert_eq!(PeriodFreq::parse("q-jan"), Some(PeriodFreq::Quarterly(1)));
17694        assert_eq!(PeriodFreq::parse("W-MON"), Some(PeriodFreq::Weekly(0)));
17695        assert_eq!(PeriodFreq::parse("Q-DEC"), Some(PeriodFreq::QUARTERLY));
17696        // NEGATIVE: not an anchor, or not an anchorable frequency.
17697        assert_eq!(PeriodFreq::parse("Q-XYZ"), None);
17698        assert_eq!(PeriodFreq::parse("M-JAN"), None);
17699        assert_eq!(PeriodFreq::parse("W-JAN"), None);
17700        assert_eq!(PeriodFreq::Annual(6).fiscal_month_shift(), 6);
17701        assert_eq!(PeriodFreq::Quarterly(1).fiscal_month_shift(), 11);
17702        assert_eq!(PeriodFreq::QUARTERLY.fiscal_month_shift(), 0);
17703        assert_eq!(PeriodFreq::Weekly(0).week_start_shift(), 1);
17704        assert_eq!(PeriodFreq::WEEKLY.week_start_shift(), 0);
17705        assert_eq!(
17706            Period::new(2827, PeriodFreq::Weekly(0)).to_string(),
17707            "2024-02-27/2024-03-04"
17708        );
17709        assert_eq!(
17710            Period::new(2826, PeriodFreq::Weekly(5)).to_string(),
17711            "2024-02-25/2024-03-02"
17712        );
17713        assert_eq!(
17714            Period::new(220, PeriodFreq::Quarterly(1)).to_string(),
17715            "2025Q1"
17716        );
17717    }
17718
17719    /// The three sub-second frequencies pandas' `to_period` accepts and this
17720    /// crate used to reject. Transcribed from live pandas 2.2.3 on
17721    /// `Timestamp('2024-03-15 10:30:45.123456789')`.
17722    #[test]
17723    fn period_freq_subsecond_units_match_pandas() {
17724        // Aliases and resolution words.
17725        assert_eq!(PeriodFreq::Milliseconds.alias(), "ms");
17726        assert_eq!(PeriodFreq::Microseconds.alias(), "us");
17727        assert_eq!(PeriodFreq::Nanoseconds.alias(), "ns");
17728        assert_eq!(PeriodFreq::Milliseconds.resolution(), Some("millisecond"));
17729        assert_eq!(PeriodFreq::Microseconds.resolution(), Some("microsecond"));
17730        assert_eq!(PeriodFreq::Nanoseconds.resolution(), Some("nanosecond"));
17731
17732        // ⚠️ THE ONE CASE-SENSITIVE ALIAS. pandas reads bare "MS" as month start
17733        // and refuses it here, while every other casing of "ms" is milliseconds.
17734        assert_eq!(PeriodFreq::parse("ms"), Some(PeriodFreq::Milliseconds));
17735        assert_eq!(PeriodFreq::parse("Ms"), Some(PeriodFreq::Milliseconds));
17736        assert_eq!(PeriodFreq::parse("mS"), Some(PeriodFreq::Milliseconds));
17737        assert_eq!(PeriodFreq::parse("MS"), None);
17738        // us/ns are case-insensitive in pandas, so both casings resolve.
17739        assert_eq!(PeriodFreq::parse("us"), Some(PeriodFreq::Microseconds));
17740        assert_eq!(PeriodFreq::parse("US"), Some(PeriodFreq::Microseconds));
17741        assert_eq!(PeriodFreq::parse("ns"), Some(PeriodFreq::Nanoseconds));
17742        assert_eq!(PeriodFreq::parse("NS"), Some(PeriodFreq::Nanoseconds));
17743
17744        // Ordinals are unit counts since the epoch; labels pad the fraction to
17745        // the full width of the frequency and never trim trailing zeros.
17746        assert_eq!(
17747            Period::new(1_710_498_645_123, PeriodFreq::Milliseconds).calendar_string(),
17748            "2024-03-15 10:30:45.123"
17749        );
17750        assert_eq!(
17751            Period::new(1_710_498_645_123_456, PeriodFreq::Microseconds).calendar_string(),
17752            "2024-03-15 10:30:45.123456"
17753        );
17754        assert_eq!(
17755            Period::new(1_710_498_645_123_456_789, PeriodFreq::Nanoseconds).calendar_string(),
17756            "2024-03-15 10:30:45.123456789"
17757        );
17758
17759        // A whole-second instant still shows its zero fraction, and the
17760        // pre-epoch ordinals are the FLOOR, not a truncation toward zero:
17761        // Timestamp('1969-12-31 23:59:59.999') at 'ms' has ordinal -1.
17762        assert_eq!(
17763            Period::new(0, PeriodFreq::Milliseconds).calendar_string(),
17764            "1970-01-01 00:00:00.000"
17765        );
17766        assert_eq!(
17767            Period::new(-1, PeriodFreq::Milliseconds).calendar_string(),
17768            "1969-12-31 23:59:59.999"
17769        );
17770        assert_eq!(
17771            Period::new(-1_000, PeriodFreq::Microseconds).calendar_string(),
17772            "1969-12-31 23:59:59.999000"
17773        );
17774        assert_eq!(
17775            Period::new(-999_999, PeriodFreq::Nanoseconds).calendar_string(),
17776            "1969-12-31 23:59:59.999000001"
17777        );
17778    }
17779
17780    #[test]
17781    fn period_freq_anchored_aliases_are_pandas_canonical_h2wiv() {
17782        assert_eq!(PeriodFreq::ANNUAL.alias(), "Y-DEC");
17783        assert_eq!(PeriodFreq::QUARTERLY.alias(), "Q-DEC");
17784        assert_eq!(PeriodFreq::WEEKLY.alias(), "W-SUN");
17785
17786        assert_eq!(PeriodFreq::parse("A"), Some(PeriodFreq::ANNUAL));
17787        assert_eq!(PeriodFreq::parse("Y"), Some(PeriodFreq::ANNUAL));
17788        assert_eq!(PeriodFreq::parse("Y-DEC"), Some(PeriodFreq::ANNUAL));
17789        assert_eq!(PeriodFreq::parse("Q"), Some(PeriodFreq::QUARTERLY));
17790        assert_eq!(PeriodFreq::parse("Q-DEC"), Some(PeriodFreq::QUARTERLY));
17791        assert_eq!(PeriodFreq::parse("W"), Some(PeriodFreq::WEEKLY));
17792        assert_eq!(PeriodFreq::parse("W-SUN"), Some(PeriodFreq::WEEKLY));
17793    }
17794
17795    #[test]
17796    fn period_freq_intraday_aliases_are_pandas_canonical_8kfdo() {
17797        assert_eq!(PeriodFreq::Hourly.alias(), "h");
17798        assert_eq!(PeriodFreq::Minutely.alias(), "min");
17799        assert_eq!(PeriodFreq::Secondly.alias(), "s");
17800
17801        assert_eq!(PeriodFreq::parse("H"), Some(PeriodFreq::Hourly));
17802        assert_eq!(PeriodFreq::parse("T"), Some(PeriodFreq::Minutely));
17803        assert_eq!(PeriodFreq::parse("S"), Some(PeriodFreq::Secondly));
17804    }
17805
17806    /// The resolution table is the COMPONENT WORD, never the frequency alias.
17807    /// Transcribed from live pandas 2.2.3: `pd.PeriodIndex([ts], freq=f).resolution`
17808    /// for each f, with W and B raising AttributeError.
17809    #[test]
17810    fn period_freq_resolution_is_the_component_word_not_the_alias() {
17811        assert_eq!(PeriodFreq::ANNUAL.resolution(), Some("year"));
17812        assert_eq!(PeriodFreq::QUARTERLY.resolution(), Some("quarter"));
17813        assert_eq!(PeriodFreq::Monthly.resolution(), Some("month"));
17814        assert_eq!(PeriodFreq::Daily.resolution(), Some("day"));
17815        assert_eq!(PeriodFreq::Hourly.resolution(), Some("hour"));
17816        assert_eq!(PeriodFreq::Minutely.resolution(), Some("minute"));
17817        assert_eq!(PeriodFreq::Secondly.resolution(), Some("second"));
17818
17819        // pandas raises AttributeError for these two rather than answering.
17820        assert_eq!(PeriodFreq::WEEKLY.resolution(), None);
17821        assert_eq!(PeriodFreq::Business.resolution(), None);
17822
17823        // The bug this replaces was the alias table copied into the resolution
17824        // slot, so pin the two apart: no frequency may report the same string
17825        // for both. (Every pandas alias is short and lowercase-ish; every
17826        // resolution word is a full English noun -- they never coincide.)
17827        for freq in [
17828            PeriodFreq::ANNUAL,
17829            PeriodFreq::QUARTERLY,
17830            PeriodFreq::Monthly,
17831            PeriodFreq::WEEKLY,
17832            PeriodFreq::Daily,
17833            PeriodFreq::Business,
17834            PeriodFreq::Hourly,
17835            PeriodFreq::Minutely,
17836            PeriodFreq::Secondly,
17837        ] {
17838            assert_ne!(
17839                Some(freq.alias()),
17840                freq.resolution(),
17841                "{freq:?} reports its alias as its resolution again"
17842            );
17843        }
17844    }
17845
17846    #[test]
17847    fn period_scalar_accessors_match_pandas_star8() {
17848        let period = Period::new(600, PeriodFreq::Monthly);
17849
17850        assert_eq!(period.ordinal(), 600);
17851        assert_eq!(period.freq(), PeriodFreq::Monthly);
17852        assert_eq!(period.freqstr(), "M");
17853    }
17854
17855    #[test]
17856    fn period_parse_common_pandas_ordinals_avm08() {
17857        assert_eq!(
17858            Period::parse("2024").unwrap(),
17859            Period::new(54, PeriodFreq::ANNUAL)
17860        );
17861        assert_eq!(
17862            Period::parse("2024Q1").unwrap(),
17863            Period::new(216, PeriodFreq::QUARTERLY)
17864        );
17865        assert_eq!(
17866            Period::parse("2024-01").unwrap(),
17867            Period::new(648, PeriodFreq::Monthly)
17868        );
17869        assert_eq!(
17870            Period::parse("2024-01-15").unwrap(),
17871            Period::new(19_737, PeriodFreq::Daily)
17872        );
17873        assert!(Period::parse("216").is_err());
17874    }
17875
17876    #[test]
17877    fn period_shift_advances_ordinal() {
17878        let q1 = Period::new(216, PeriodFreq::QUARTERLY);
17879        let q2 = q1.shift(1);
17880        assert_eq!(q2.ordinal, 217);
17881        assert_eq!(q2.freq, PeriodFreq::QUARTERLY);
17882        let q0 = q1.shift(-1);
17883        assert_eq!(q0.ordinal, 215);
17884    }
17885
17886    #[test]
17887    fn period_shift_saturates_on_overflow() {
17888        let p = Period::new(i64::MAX - 2, PeriodFreq::Daily);
17889        assert_eq!(p.shift(100).ordinal, i64::MAX);
17890        let p = Period::new(i64::MIN + 2, PeriodFreq::Daily);
17891        assert_eq!(p.shift(-100).ordinal, i64::MIN);
17892    }
17893
17894    #[test]
17895    fn period_diff_returns_period_count() {
17896        let a = Period::new(216, PeriodFreq::QUARTERLY);
17897        let b = Period::new(220, PeriodFreq::QUARTERLY);
17898        assert_eq!(b.diff(&a), Some(4));
17899        assert_eq!(a.diff(&b), Some(-4));
17900    }
17901
17902    #[test]
17903    fn period_diff_rejects_mismatched_freq() {
17904        let monthly = Period::new(100, PeriodFreq::Monthly);
17905        let quarterly = Period::new(100, PeriodFreq::QUARTERLY);
17906        assert_eq!(monthly.diff(&quarterly), None);
17907        assert_eq!(quarterly.diff(&monthly), None);
17908    }
17909
17910    #[test]
17911    fn period_cmp_same_freq_respects_ordinal_order() {
17912        use std::cmp::Ordering;
17913        let a = Period::new(10, PeriodFreq::Monthly);
17914        let b = Period::new(20, PeriodFreq::Monthly);
17915        assert_eq!(a.cmp_same_freq(&b), Some(Ordering::Less));
17916        assert_eq!(b.cmp_same_freq(&a), Some(Ordering::Greater));
17917        assert_eq!(a.cmp_same_freq(&a), Some(Ordering::Equal));
17918    }
17919
17920    #[test]
17921    fn period_cmp_cross_freq_returns_none() {
17922        let m = Period::new(1, PeriodFreq::Monthly);
17923        let q = Period::new(1, PeriodFreq::QUARTERLY);
17924        assert_eq!(m.cmp_same_freq(&q), None);
17925    }
17926
17927    #[test]
17928    fn period_arithmetic_matches_seeded_oracles_bac28() {
17929        use std::cmp::Ordering;
17930
17931        fn next(seed: &mut u64) -> u64 {
17932            *seed = seed
17933                .wrapping_mul(2862933555777941757)
17934                .wrapping_add(3037000493);
17935            *seed
17936        }
17937
17938        fn freq_for(raw: u64) -> PeriodFreq {
17939            // All TWELVE frequencies. This stopped at nine, so no property
17940            // test here ever generated a sub-second period.
17941            match raw % 12 {
17942                0 => PeriodFreq::ANNUAL,
17943                1 => PeriodFreq::QUARTERLY,
17944                2 => PeriodFreq::Monthly,
17945                3 => PeriodFreq::WEEKLY,
17946                4 => PeriodFreq::Daily,
17947                5 => PeriodFreq::Business,
17948                6 => PeriodFreq::Hourly,
17949                7 => PeriodFreq::Minutely,
17950                8 => PeriodFreq::Secondly,
17951                9 => PeriodFreq::Milliseconds,
17952                10 => PeriodFreq::Microseconds,
17953                _ => PeriodFreq::Nanoseconds,
17954            }
17955        }
17956
17957        fn different_freq(freq: PeriodFreq) -> PeriodFreq {
17958            match freq {
17959                PeriodFreq::Annual(_) => PeriodFreq::QUARTERLY,
17960                PeriodFreq::Quarterly(_) => PeriodFreq::Monthly,
17961                PeriodFreq::Monthly => PeriodFreq::WEEKLY,
17962                PeriodFreq::Weekly(_) => PeriodFreq::Daily,
17963                PeriodFreq::Daily => PeriodFreq::Business,
17964                PeriodFreq::Business => PeriodFreq::Hourly,
17965                PeriodFreq::Hourly => PeriodFreq::Minutely,
17966                PeriodFreq::Minutely => PeriodFreq::Secondly,
17967                // The cycle closes through the sub-second units, so every
17968                // frequency still maps to a DIFFERENT one — the only property
17969                // this helper owes its callers.
17970                PeriodFreq::Secondly => PeriodFreq::Milliseconds,
17971                PeriodFreq::Milliseconds => PeriodFreq::Microseconds,
17972                PeriodFreq::Microseconds => PeriodFreq::Nanoseconds,
17973                PeriodFreq::Nanoseconds => PeriodFreq::ANNUAL,
17974            }
17975        }
17976
17977        fn assert_period_case(
17978            case: usize,
17979            freq: PeriodFreq,
17980            ordinal: i64,
17981            shift_by: i64,
17982            other_ordinal: i64,
17983        ) {
17984            let period = Period::new(ordinal, freq);
17985            let shifted = period.shift(shift_by);
17986            assert_eq!(
17987                shifted.ordinal,
17988                ordinal.saturating_add(shift_by),
17989                "case {case}: shift ordinal"
17990            );
17991            assert_eq!(shifted.freq, freq, "case {case}: shift freq");
17992
17993            let same_freq_other = Period::new(other_ordinal, freq);
17994            assert_eq!(
17995                period.diff(&same_freq_other),
17996                Some(ordinal.saturating_sub(other_ordinal)),
17997                "case {case}: same-freq diff"
17998            );
17999            assert_eq!(
18000                period.cmp_same_freq(&same_freq_other),
18001                Some(ordinal.cmp(&other_ordinal)),
18002                "case {case}: same-freq cmp"
18003            );
18004
18005            let cross_freq_other = Period::new(other_ordinal, different_freq(freq));
18006            assert_eq!(
18007                period.diff(&cross_freq_other),
18008                None,
18009                "case {case}: cross-freq diff"
18010            );
18011            assert_eq!(
18012                period.cmp_same_freq(&cross_freq_other),
18013                None,
18014                "case {case}: cross-freq cmp"
18015            );
18016        }
18017
18018        assert_period_case(usize::MAX, PeriodFreq::Daily, i64::MAX - 2, 10, i64::MIN);
18019        assert_period_case(
18020            usize::MAX - 1,
18021            PeriodFreq::Daily,
18022            i64::MIN + 2,
18023            -10,
18024            i64::MAX,
18025        );
18026        assert_eq!(
18027            Period::new(10, PeriodFreq::Monthly)
18028                .cmp_same_freq(&Period::new(10, PeriodFreq::Monthly)),
18029            Some(Ordering::Equal)
18030        );
18031
18032        let mut seed = 0xbac2_8d1f_0d1c_5eed_u64;
18033        for case in 0..260 {
18034            let freq = freq_for(next(&mut seed));
18035            let ordinal = match case % 53 {
18036                0 => i64::MAX - (next(&mut seed) % 8) as i64,
18037                1 => i64::MIN + (next(&mut seed) % 8) as i64,
18038                _ => (next(&mut seed) % 200_001) as i64 - 100_000,
18039            };
18040            let shift_by = match case % 47 {
18041                0 => 512,
18042                1 => -512,
18043                _ => (next(&mut seed) % 4097) as i64 - 2048,
18044            };
18045            let other_ordinal = match case % 41 {
18046                0 => i64::MAX,
18047                1 => i64::MIN,
18048                _ => (next(&mut seed) % 200_001) as i64 - 100_000,
18049            };
18050            assert_period_case(case, freq, ordinal, shift_by, other_ordinal);
18051        }
18052    }
18053
18054    #[test]
18055    fn period_display_is_pandas_calendar_string() {
18056        // Ordinal 216 on the quarterly axis (1970Q1 == 0) is 1970 + 54y = 2024Q1.
18057        assert_eq!(
18058            Period::new(216, PeriodFreq::QUARTERLY).to_string(),
18059            "2024Q1"
18060        );
18061        // 1970 + 54 == 2024 on the annual axis.
18062        assert_eq!(Period::new(54, PeriodFreq::ANNUAL).to_string(), "2024");
18063        // 1970-01 == 0 -> 2024-03 is 54*12 + 2 == 650 months.
18064        assert_eq!(Period::new(650, PeriodFreq::Monthly).to_string(), "2024-03");
18065        // Day 0 == 1970-01-01; 2024-01-15.
18066        assert_eq!(
18067            Period::new(fp_days("2024-01-15"), PeriodFreq::Daily).to_string(),
18068            "2024-01-15"
18069        );
18070        assert_eq!(
18071            Scalar::Period(Period::new(i64::MIN, PeriodFreq::Daily)).to_string(),
18072            "NaT"
18073        );
18074    }
18075
18076    /// The two frequencies whose ordinal is NOT a day count. Both rendered
18077    /// through `civil_from_days` and came out decades wrong; the test above
18078    /// covered Y/Q/M/D and never touched either, which is how it survived.
18079    ///
18080    /// Every string is `str(pd.Period(ordinal=..., freq=...))` on live pandas
18081    /// 2.2.3, and FrankenPandas' own ordinals were confirmed to agree with
18082    /// pandas' at each sampled date before these were taken.
18083    #[test]
18084    fn weekly_and_business_periods_do_not_index_days() {
18085        // ⚠️ WEEKLY IS A RANGE, not a date: the ordinal counts WEEKS from the
18086        // Monday 1969-12-22, and pandas prints the seven days it spans.
18087        // Ordinal 2829 is the week of 2024-03-15 and used to render
18088        // "1977-09-30" — the result of reading a week count as a day count.
18089        for (ordinal, want) in [
18090            (0_i64, "1969-12-22/1969-12-28"),
18091            (1, "1969-12-29/1970-01-04"),
18092            (2829, "2024-03-11/2024-03-17"),
18093            (1540, "1999-06-28/1999-07-04"),
18094            (15237, "2261-12-30/2262-01-05"),
18095            // Pre-epoch, where Euclidean division matters.
18096            (-1, "1969-12-15/1969-12-21"),
18097            (-2829, "1915-10-04/1915-10-10"),
18098        ] {
18099            assert_eq!(
18100                Period::new(ordinal, PeriodFreq::WEEKLY).to_string(),
18101                want,
18102                "weekly ordinal {ordinal}"
18103            );
18104        }
18105
18106        // ⚠️ BUSINESS COUNTS BUSINESS DAYS — five per week — so consecutive
18107        // ordinals skip the weekend. Ordinal 14141 is 2024-03-15 and used to
18108        // render "2008-09-19".
18109        for (ordinal, want) in [
18110            (0_i64, "1970-01-01"), // a Thursday: the epoch anchors the cycle
18111            (1, "1970-01-02"),     // Friday
18112            (2, "1970-01-05"),     // Monday — the weekend is SKIPPED
18113            (3, "1970-01-06"),
18114            (4, "1970-01-07"),
18115            (5, "1970-01-08"),
18116            (14141, "2024-03-15"),
18117            (76179, "2262-01-01"),
18118            // A Sunday input rolls FORWARD when the ordinal is taken, so 7697
18119            // is the Monday 1999-07-05 rather than 1999-07-04.
18120            (7697, "1999-07-05"),
18121            (-1, "1969-12-31"),
18122            (-5, "1969-12-25"),
18123            (-6, "1969-12-24"),
18124        ] {
18125            assert_eq!(
18126                Period::new(ordinal, PeriodFreq::Business).to_string(),
18127                want,
18128                "business ordinal {ordinal}"
18129            );
18130        }
18131
18132        // Five business ordinals per seven calendar days, checked as a property
18133        // rather than as a table: the same arithmetic the forward map in
18134        // fp-index uses, read backwards.
18135        for ordinal in -400_i64..400 {
18136            let rendered = Period::new(ordinal, PeriodFreq::Business).to_string();
18137            let later = Period::new(ordinal + 5, PeriodFreq::Business).to_string();
18138            assert_ne!(rendered, later, "business ordinals must not repeat");
18139        }
18140
18141        assert_eq!(Period::new(i64::MIN, PeriodFreq::WEEKLY).to_string(), "NaT");
18142        assert_eq!(
18143            Period::new(i64::MIN, PeriodFreq::Business).to_string(),
18144            "NaT"
18145        );
18146    }
18147
18148    fn period_display_former_profile(period: &Period) -> String {
18149        let calendar = period.calendar_string();
18150        let mut rendered = String::new();
18151        rendered.push_str(&calendar);
18152        rendered
18153    }
18154
18155    fn measure_period_renderer(periods: &[Period], render: impl Fn(&Period) -> String) -> u128 {
18156        use std::{hint::black_box, time::Instant};
18157
18158        let started = Instant::now();
18159        let mut checksum = 0usize;
18160        for period in periods {
18161            let rendered = render(black_box(period));
18162            checksum = checksum.wrapping_add(rendered.len());
18163            drop(black_box(rendered));
18164        }
18165        black_box(checksum);
18166        started.elapsed().as_nanos()
18167    }
18168
18169    #[test]
18170    #[ignore = "release-only attribution probe for br-frankenpandas-6pqra"]
18171    fn profile_period_display_direct_sink_ab_6pqra() {
18172        const FREQUENCIES: [PeriodFreq; 9] = [
18173            PeriodFreq::ANNUAL,
18174            PeriodFreq::QUARTERLY,
18175            PeriodFreq::Monthly,
18176            PeriodFreq::WEEKLY,
18177            PeriodFreq::Daily,
18178            PeriodFreq::Business,
18179            PeriodFreq::Hourly,
18180            PeriodFreq::Minutely,
18181            PeriodFreq::Secondly,
18182        ];
18183        const SAMPLES: usize = 10;
18184
18185        let periods = (0..65_536)
18186            .map(|index| {
18187                let ordinal = if index % 4093 == 0 {
18188                    i64::MIN
18189                } else {
18190                    ((index as i64 * 7_919) % 4_000_001) - 2_000_000
18191                };
18192                Period::new(ordinal, FREQUENCIES[index % FREQUENCIES.len()])
18193            })
18194            .collect::<Vec<_>>();
18195
18196        for period in &periods {
18197            assert_eq!(period_display_former_profile(period), period.to_string());
18198        }
18199
18200        for _ in 0..2 {
18201            measure_period_renderer(&periods, period_display_former_profile);
18202            measure_period_renderer(&periods, Period::to_string);
18203        }
18204
18205        let mut former_ns = Vec::with_capacity(SAMPLES);
18206        let mut public_ns = Vec::with_capacity(SAMPLES);
18207        for sample in 0..SAMPLES {
18208            if sample % 2 == 0 {
18209                former_ns.push(measure_period_renderer(
18210                    &periods,
18211                    period_display_former_profile,
18212                ));
18213                public_ns.push(measure_period_renderer(&periods, Period::to_string));
18214            } else {
18215                public_ns.push(measure_period_renderer(&periods, Period::to_string));
18216                former_ns.push(measure_period_renderer(
18217                    &periods,
18218                    period_display_former_profile,
18219                ));
18220            }
18221        }
18222        former_ns.sort_unstable();
18223        public_ns.sort_unstable();
18224        let former_p50 = former_ns[SAMPLES / 2];
18225        let public_p50 = public_ns[SAMPLES / 2];
18226        let former_p95 = former_ns[SAMPLES - 1];
18227        let public_p95 = public_ns[SAMPLES - 1];
18228        println!("PROFILE_PERIOD_DISPLAY_FORMER_NS={former_ns:?}");
18229        println!("PROFILE_PERIOD_DISPLAY_PUBLIC_NS={public_ns:?}");
18230        println!(
18231            "PROFILE_PERIOD_DISPLAY_P50_RATIO={:.6}",
18232            former_p50 as f64 / public_p50 as f64
18233        );
18234        println!(
18235            "PROFILE_PERIOD_DISPLAY_P95_RATIO={:.6}",
18236            former_p95 as f64 / public_p95 as f64
18237        );
18238    }
18239
18240    #[cfg(test)]
18241    fn fp_days(ymd: &str) -> i64 {
18242        Period::parse(ymd).expect("daily period").ordinal
18243    }
18244
18245    #[test]
18246    fn period_roundtrips_through_serde_json() {
18247        let p = Period::new(42, PeriodFreq::WEEKLY);
18248        let json = serde_json::to_string(&p).expect("serialize");
18249        let back: Period = serde_json::from_str(&json).expect("deserialize");
18250        assert_eq!(p, back);
18251    }
18252
18253    // ── period_range tests (br-frankenpandas-2jef — epoj Phase 2) ───────
18254
18255    use super::period_range;
18256
18257    #[test]
18258    fn period_range_zero_periods_is_empty() {
18259        let start = Period::new(216, PeriodFreq::QUARTERLY);
18260        assert!(period_range(start, 0).is_empty());
18261    }
18262
18263    #[test]
18264    fn period_range_single_period_returns_start_only() {
18265        let start = Period::new(216, PeriodFreq::QUARTERLY);
18266        let r = period_range(start, 1);
18267        assert_eq!(r.len(), 1);
18268        assert_eq!(r[0], start);
18269    }
18270
18271    #[test]
18272    fn period_range_increments_ordinal_by_one_per_step() {
18273        let start = Period::new(216, PeriodFreq::QUARTERLY);
18274        let r = period_range(start, 4);
18275        assert_eq!(r.len(), 4);
18276        assert_eq!(r[0].ordinal, 216);
18277        assert_eq!(r[1].ordinal, 217);
18278        assert_eq!(r[2].ordinal, 218);
18279        assert_eq!(r[3].ordinal, 219);
18280    }
18281
18282    #[test]
18283    fn period_range_preserves_frequency() {
18284        let start = Period::new(0, PeriodFreq::Monthly);
18285        let r = period_range(start, 12);
18286        assert!(r.iter().all(|p| p.freq == PeriodFreq::Monthly));
18287    }
18288
18289    #[test]
18290    fn period_range_negative_starting_ordinal_works() {
18291        // Ordinal axis is signed — pre-epoch periods are valid.
18292        let start = Period::new(-3, PeriodFreq::ANNUAL);
18293        let r = period_range(start, 5);
18294        assert_eq!(
18295            r.iter().map(|p| p.ordinal).collect::<Vec<_>>(),
18296            vec![-3, -2, -1, 0, 1]
18297        );
18298    }
18299
18300    #[test]
18301    fn period_range_large_n_does_not_panic() {
18302        // 1024 monthly periods — large enough to catch any allocation bug.
18303        let start = Period::new(0, PeriodFreq::Monthly);
18304        let r = period_range(start, 1024);
18305        assert_eq!(r.len(), 1024);
18306        assert_eq!(r[1023].ordinal, 1023);
18307    }
18308
18309    #[test]
18310    fn period_range_matches_seeded_ordinal_oracle_z3zh2() {
18311        fn next(seed: &mut u64) -> u64 {
18312            *seed = seed
18313                .wrapping_mul(6364136223846793005)
18314                .wrapping_add(1442695040888963407);
18315            *seed
18316        }
18317
18318        fn freq_for(raw: u64) -> PeriodFreq {
18319            // All TWELVE frequencies. This stopped at nine, so no property
18320            // test here ever generated a sub-second period.
18321            match raw % 12 {
18322                0 => PeriodFreq::ANNUAL,
18323                1 => PeriodFreq::QUARTERLY,
18324                2 => PeriodFreq::Monthly,
18325                3 => PeriodFreq::WEEKLY,
18326                4 => PeriodFreq::Daily,
18327                5 => PeriodFreq::Business,
18328                6 => PeriodFreq::Hourly,
18329                7 => PeriodFreq::Minutely,
18330                8 => PeriodFreq::Secondly,
18331                9 => PeriodFreq::Milliseconds,
18332                10 => PeriodFreq::Microseconds,
18333                _ => PeriodFreq::Nanoseconds,
18334            }
18335        }
18336
18337        fn assert_oracle_case(case: usize, start: Period, periods: usize) {
18338            let got = period_range(start, periods);
18339            assert_eq!(got.len(), periods, "case {case}: length");
18340
18341            for (position, period) in got.iter().enumerate() {
18342                let expected_ordinal = start.ordinal.saturating_add(position as i64);
18343                assert_eq!(
18344                    period.ordinal, expected_ordinal,
18345                    "case {case}: ordinal at {position}"
18346                );
18347                assert_eq!(period.freq, start.freq, "case {case}: freq at {position}");
18348            }
18349        }
18350
18351        assert_oracle_case(usize::MAX, Period::new(42, PeriodFreq::Monthly), 0);
18352        assert_oracle_case(
18353            usize::MAX - 1,
18354            Period::new(i64::MAX - 3, PeriodFreq::Daily),
18355            8,
18356        );
18357
18358        let mut seed = 0x9e21_0d1c_5eed_0421_u64;
18359        for case in 0..260 {
18360            let freq = freq_for(next(&mut seed));
18361            let periods = (next(&mut seed) % 80) as usize;
18362            let start_ordinal = if case % 37 == 0 {
18363                i64::MAX - 7
18364            } else {
18365                (next(&mut seed) % 20_001) as i64 - 10_000
18366            };
18367            assert_oracle_case(case, Period::new(start_ordinal, freq), periods);
18368        }
18369    }
18370
18371    // ── interval_range tests (br-frankenpandas-xaom) ────────────────────
18372
18373    use super::{TypeError, interval_range, interval_range_by_periods, interval_range_by_step};
18374
18375    #[test]
18376    fn interval_range_by_periods_matches_pandas_default_case() {
18377        // pd.interval_range(0, 10, periods=5) → [(0,2],(2,4],(4,6],(6,8],(8,10]]
18378        let bins = interval_range_by_periods(0.0, 10.0, 5, IntervalClosed::Right);
18379        assert_eq!(bins.len(), 5);
18380        for (i, bin) in bins.iter().enumerate() {
18381            assert_eq!(bin.left, (i as f64) * 2.0);
18382            assert_eq!(bin.right, ((i + 1) as f64) * 2.0);
18383            assert_eq!(bin.closed, IntervalClosed::Right);
18384        }
18385    }
18386
18387    #[test]
18388    fn interval_range_by_periods_final_edge_is_exact_end() {
18389        // Guards against accumulated float drift on the last right edge.
18390        let bins = interval_range_by_periods(0.0, 1.0, 7, IntervalClosed::Right);
18391        assert_eq!(bins.last().unwrap().right, 1.0);
18392    }
18393
18394    #[test]
18395    fn interval_range_by_periods_zero_periods_is_empty() {
18396        assert!(interval_range_by_periods(0.0, 10.0, 0, IntervalClosed::Right).is_empty());
18397    }
18398
18399    #[test]
18400    fn interval_range_by_periods_reversed_range_is_empty() {
18401        // pandas: pd.interval_range(10, 0, periods=5) → IntervalIndex([]).
18402        assert!(interval_range_by_periods(10.0, 0.0, 5, IntervalClosed::Right).is_empty());
18403    }
18404
18405    #[test]
18406    fn interval_range_by_periods_preserves_closed_policy() {
18407        for closed in [
18408            IntervalClosed::Left,
18409            IntervalClosed::Right,
18410            IntervalClosed::Both,
18411            IntervalClosed::Neither,
18412        ] {
18413            let bins = interval_range_by_periods(0.0, 4.0, 2, closed);
18414            assert!(bins.iter().all(|b| b.closed == closed));
18415        }
18416    }
18417
18418    #[test]
18419    fn interval_range_by_step_matches_pandas_default_case() {
18420        // pd.interval_range(0, 10, freq=2) → [(0,2],(2,4],(4,6],(6,8],(8,10]]
18421        let bins = interval_range_by_step(0.0, 10.0, 2.0, IntervalClosed::Right).expect("ok");
18422        assert_eq!(bins.len(), 5);
18423        assert_eq!(bins[0].left, 0.0);
18424        assert_eq!(bins[4].right, 10.0);
18425    }
18426
18427    #[test]
18428    fn interval_range_by_step_rejects_non_positive_step() {
18429        assert!(matches!(
18430            interval_range_by_step(0.0, 10.0, 0.0, IntervalClosed::Right),
18431            Err(TypeError::InvalidIntervalStep { .. })
18432        ));
18433        assert!(matches!(
18434            interval_range_by_step(0.0, 10.0, -2.0, IntervalClosed::Right),
18435            Err(TypeError::InvalidIntervalStep { .. })
18436        ));
18437        assert!(matches!(
18438            interval_range_by_step(0.0, 10.0, f64::NAN, IntervalClosed::Right),
18439            Err(TypeError::InvalidIntervalStep { .. })
18440        ));
18441        assert!(matches!(
18442            interval_range_by_step(0.0, 10.0, f64::INFINITY, IntervalClosed::Right),
18443            Err(TypeError::InvalidIntervalStep { .. })
18444        ));
18445    }
18446
18447    #[test]
18448    fn interval_range_by_step_rejects_non_dividing_step() {
18449        // pandas: pd.interval_range(0, 10, freq=3) → ValueError
18450        // (span=10 not divisible by step=3). Reject with IntervalStepDoesNotDivide.
18451        assert!(matches!(
18452            interval_range_by_step(0.0, 10.0, 3.0, IntervalClosed::Right),
18453            Err(TypeError::IntervalStepDoesNotDivide { .. })
18454        ));
18455    }
18456
18457    #[test]
18458    fn interval_range_by_step_reversed_range_is_empty() {
18459        let bins = interval_range_by_step(10.0, 0.0, 2.0, IntervalClosed::Right).expect("ok");
18460        assert!(bins.is_empty());
18461    }
18462
18463    #[test]
18464    fn interval_range_by_step_degenerate_zero_span_is_empty() {
18465        let bins = interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right).expect("ok");
18466        assert!(bins.is_empty());
18467    }
18468
18469    #[test]
18470    fn interval_range_by_step_accepts_float_step_within_tolerance() {
18471        // step=0.1 ten times == 1.0 but float arithmetic produces 0.9999...
18472        let bins = interval_range_by_step(0.0, 1.0, 0.1, IntervalClosed::Right).expect("ok");
18473        assert_eq!(bins.len(), 10);
18474        assert_eq!(bins.last().unwrap().right, 1.0);
18475    }
18476
18477    #[test]
18478    fn interval_range_unified_api_tests() {
18479        // Case 1: start, end, periods
18480        let r1 = interval_range(Some(0.0), Some(10.0), Some(5), None, None).expect("ok");
18481        assert_eq!(r1.len(), 5);
18482        assert_eq!(r1[0].left, 0.0);
18483        assert_eq!(r1[0].right, 2.0);
18484        assert_eq!(r1[4].right, 10.0);
18485        assert_eq!(r1[0].closed, IntervalClosed::Right);
18486
18487        // Case 2: start, end, freq
18488        let r2 = interval_range(Some(0.0), Some(10.0), None, Some(2.0), None).expect("ok");
18489        assert_eq!(r2.len(), 5);
18490        assert_eq!(r2[0].left, 0.0);
18491        assert_eq!(r2[4].right, 10.0);
18492
18493        // Case 3: start, periods, freq
18494        let r3 = interval_range(
18495            Some(0.0),
18496            None,
18497            Some(5),
18498            Some(2.0),
18499            Some(IntervalClosed::Both),
18500        )
18501        .expect("ok");
18502        assert_eq!(r3.len(), 5);
18503        assert_eq!(r3[0].left, 0.0);
18504        assert_eq!(r3[4].right, 10.0);
18505        assert_eq!(r3[0].closed, IntervalClosed::Both);
18506
18507        // Case 4: end, periods, freq
18508        let r4 = interval_range(
18509            None,
18510            Some(10.0),
18511            Some(5),
18512            Some(2.0),
18513            Some(IntervalClosed::Left),
18514        )
18515        .expect("ok");
18516        assert_eq!(r4.len(), 5);
18517        assert_eq!(r4[0].left, 0.0);
18518        assert_eq!(r4[4].right, 10.0);
18519        assert_eq!(r4[0].closed, IntervalClosed::Left);
18520
18521        // Errors: not exactly 3 arguments
18522        assert!(matches!(
18523            interval_range(None, None, None, None, None),
18524            Err(TypeError::IntervalRangeParameterCount)
18525        ));
18526        assert!(matches!(
18527            interval_range(Some(0.0), Some(10.0), None, None, None),
18528            Err(TypeError::IntervalRangeParameterCount)
18529        ));
18530        assert!(matches!(
18531            interval_range(Some(0.0), Some(10.0), Some(5), Some(2.0), None),
18532            Err(TypeError::IntervalRangeParameterCount)
18533        ));
18534
18535        // Errors: non-positive freq
18536        assert!(matches!(
18537            interval_range(Some(0.0), None, Some(5), Some(-1.0), None),
18538            Err(TypeError::InvalidIntervalStep { .. })
18539        ));
18540        assert!(matches!(
18541            interval_range(Some(0.0), None, Some(5), Some(0.0), None),
18542            Err(TypeError::InvalidIntervalStep { .. })
18543        ));
18544    }
18545
18546    #[test]
18547    fn interval_range_matches_seeded_arithmetic_oracle_t9ozf() {
18548        // Differential vs independent interval edge oracles
18549        // (br-frankenpandas-t9ozf). Seeded LCG, no mocks.
18550        fn next(seed: &mut u64) -> u64 {
18551            *seed = seed
18552                .wrapping_mul(2862933555777941757)
18553                .wrapping_add(3037000493);
18554            *seed
18555        }
18556
18557        fn closed_for(raw: u64) -> IntervalClosed {
18558            match raw % 4 {
18559                0 => IntervalClosed::Left,
18560                1 => IntervalClosed::Right,
18561                2 => IntervalClosed::Both,
18562                _ => IntervalClosed::Neither,
18563            }
18564        }
18565
18566        fn assert_interval(
18567            case: usize,
18568            kind: &str,
18569            pos: usize,
18570            actual: &Interval,
18571            expected: &Interval,
18572        ) {
18573            assert!(
18574                (actual.left - expected.left).abs() < 1e-12,
18575                "case={case} kind={kind} pos={pos}: expected left {}, got {}",
18576                expected.left,
18577                actual.left
18578            );
18579            assert!(
18580                (actual.right - expected.right).abs() < 1e-12,
18581                "case={case} kind={kind} pos={pos}: expected right {}, got {}",
18582                expected.right,
18583                actual.right
18584            );
18585            assert_eq!(
18586                actual.closed, expected.closed,
18587                "case={case} kind={kind} pos={pos}: closed mismatch"
18588            );
18589        }
18590
18591        fn expected_by_periods(
18592            start: f64,
18593            end: f64,
18594            periods: usize,
18595            closed: IntervalClosed,
18596        ) -> Vec<Interval> {
18597            if periods == 0 || !start.is_finite() || !end.is_finite() || start >= end {
18598                return Vec::new();
18599            }
18600            let step = (end - start) / periods as f64;
18601            (0..periods)
18602                .map(|pos| {
18603                    let left = start + step * pos as f64;
18604                    let right = if pos + 1 == periods {
18605                        end
18606                    } else {
18607                        start + step * (pos + 1) as f64
18608                    };
18609                    Interval::new(left, right, closed)
18610                })
18611                .collect()
18612        }
18613
18614        fn expected_by_step(
18615            start: f64,
18616            end: f64,
18617            step: f64,
18618            closed: IntervalClosed,
18619        ) -> Vec<Interval> {
18620            if start >= end {
18621                return Vec::new();
18622            }
18623            let count = ((end - start) / step).round() as usize;
18624            (0..count)
18625                .map(|pos| {
18626                    let left = start + step * pos as f64;
18627                    let right = if pos + 1 == count {
18628                        end
18629                    } else {
18630                        start + step * (pos + 1) as f64
18631                    };
18632                    Interval::new(left, right, closed)
18633                })
18634                .collect()
18635        }
18636
18637        assert!(interval_range_by_periods(5.0, 5.0, 4, IntervalClosed::Right).is_empty());
18638        assert!(interval_range_by_periods(5.0, 4.0, 4, IntervalClosed::Right).is_empty());
18639        assert!(
18640            interval_range_by_step(5.0, 5.0, 1.0, IntervalClosed::Right)
18641                .expect("zero span")
18642                .is_empty()
18643        );
18644
18645        let mut seed = 0x171e_7a11_c0de_5eed_u64;
18646        for case in 0..220 {
18647            let start = (next(&mut seed) % 2_001) as f64 / 10.0 - 100.0;
18648            let periods = (next(&mut seed) % 24 + 1) as usize;
18649            let width = (next(&mut seed) % 1_000 + 1) as f64 / 4.0;
18650            let end = start + width;
18651            let closed = closed_for(next(&mut seed));
18652
18653            let actual = interval_range_by_periods(start, end, periods, closed);
18654            let expected = expected_by_periods(start, end, periods, closed);
18655            assert_eq!(
18656                actual.len(),
18657                expected.len(),
18658                "case={case} periods: length mismatch"
18659            );
18660            for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
18661                assert_interval(case, "periods", pos, actual, expected);
18662            }
18663
18664            let step_count = (next(&mut seed) % 20 + 1) as usize;
18665            let step = (next(&mut seed) % 25 + 1) as f64;
18666            let step_end = start + step * step_count as f64;
18667            let actual = interval_range_by_step(start, step_end, step, closed).expect("divides");
18668            let expected = expected_by_step(start, step_end, step, closed);
18669            assert_eq!(
18670                actual.len(),
18671                expected.len(),
18672                "case={case} step: length mismatch"
18673            );
18674            for (pos, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() {
18675                assert_interval(case, "step", pos, actual, expected);
18676            }
18677        }
18678    }
18679
18680    // ── Timedelta arithmetic tests (br-frankenpandas-4r56 Phase 1) ──────
18681
18682    use super::Timedelta;
18683
18684    #[test]
18685    fn timedelta_add_sums_non_nat() {
18686        let one_hour = Timedelta::NANOS_PER_HOUR;
18687        let one_day = Timedelta::NANOS_PER_DAY;
18688        assert_eq!(Timedelta::add(one_hour, one_day), one_hour + one_day);
18689    }
18690
18691    #[test]
18692    fn timedelta_add_propagates_nat() {
18693        assert_eq!(Timedelta::add(Timedelta::NAT, 100), Timedelta::NAT);
18694        assert_eq!(Timedelta::add(100, Timedelta::NAT), Timedelta::NAT);
18695        assert_eq!(
18696            Timedelta::add(Timedelta::NAT, Timedelta::NAT),
18697            Timedelta::NAT
18698        );
18699    }
18700
18701    #[test]
18702    fn timedelta_add_returns_nat_on_overflow() {
18703        // CORRECTED br-frankenpandas-lgyy8. This test previously asserted
18704        // `add(i64::MAX - 10, 100) == i64::MAX`, i.e. that positive overflow
18705        // yields a finite, plausible duration. Live pandas 2.2.3 raises
18706        // OverflowError for `pd.Timedelta.max + pd.Timedelta('1ns')` and never
18707        // returns a fabricated finite value, so the old expectation encoded a
18708        // fail-open bug. Overflow is now NaT in BOTH directions.
18709        assert_eq!(Timedelta::add(i64::MAX - 10, 100), Timedelta::NAT);
18710        // Negative side is unchanged: i64::MIN IS the NaT sentinel, so this
18711        // already surfaced as missing (pandas: Timedelta.min + -1ns -> NaT).
18712        assert_eq!(Timedelta::add(i64::MIN + 10, -100), Timedelta::NAT);
18713    }
18714
18715    #[test]
18716    fn timedelta_sub_subtracts_non_nat() {
18717        let one_hour = Timedelta::NANOS_PER_HOUR;
18718        assert_eq!(
18719            Timedelta::sub(one_hour, Timedelta::NANOS_PER_MIN),
18720            one_hour - Timedelta::NANOS_PER_MIN
18721        );
18722    }
18723
18724    #[test]
18725    fn timedelta_sub_propagates_nat() {
18726        assert_eq!(Timedelta::sub(Timedelta::NAT, 100), Timedelta::NAT);
18727        assert_eq!(Timedelta::sub(100, Timedelta::NAT), Timedelta::NAT);
18728    }
18729
18730    #[test]
18731    fn timedelta_neg_flips_sign_non_nat() {
18732        assert_eq!(Timedelta::neg(5), -5);
18733        assert_eq!(Timedelta::neg(-5), 5);
18734        assert_eq!(Timedelta::neg(0), 0);
18735    }
18736
18737    #[test]
18738    fn timedelta_neg_preserves_nat() {
18739        assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
18740    }
18741
18742    #[test]
18743    fn timedelta_abs_returns_magnitude() {
18744        assert_eq!(Timedelta::abs(-5), 5);
18745        assert_eq!(Timedelta::abs(5), 5);
18746        assert_eq!(Timedelta::abs(0), 0);
18747        assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
18748    }
18749
18750    #[test]
18751    fn neg_and_abs_at_the_representable_floor_are_not_overflow_fyr1z() {
18752        // br-frankenpandas-fyr1z. Until this test existed, `neg`/`abs` were
18753        // only exercised at ±5 and 0, and the doc comment on `neg` asserted
18754        // the OPPOSITE of pandas: "pandas: `-pd.Timedelta.min` is NaT since
18755        // min == -max - 1 cannot be negated". Both halves are false, so an
18756        // implementer trusting the comment could have replaced
18757        // `saturating_neg()` with a NaT arm and broken parity without failing
18758        // a single existing assertion. Measured against the installed oracle,
18759        // pandas 2.2.3:
18760        //   pd.Timedelta.min.value                 == -9223372036854775807
18761        //   -pd.Timedelta.min                      -> Timedelta.max (NOT NaT)
18762        //   abs(pd.Timedelta.min)                  -> Timedelta.max (NOT NaT)
18763        //   -Series([Timedelta.min])               -> [Timedelta.max]
18764        //   Series([Timedelta.min]).abs()          -> [Timedelta.max]
18765        //
18766        // The reason there is no overflow to handle: pandas' representable
18767        // range is symmetric about zero because i64::MIN is spent on the NaT
18768        // sentinel, exactly as it is here.
18769        const MAX: i64 = i64::MAX;
18770        const MIN_OK: i64 = i64::MIN + 1; // most-negative NON-NaT value
18771
18772        // The range really is symmetric — this is the premise the old comment
18773        // denied, and everything below follows from it.
18774        assert_eq!(MIN_OK, -MAX);
18775        assert_eq!(Timedelta::NAT, i64::MIN);
18776
18777        // The cases the false comment would have turned into NaT.
18778        assert_eq!(Timedelta::neg(MIN_OK), MAX);
18779        assert_eq!(Timedelta::neg(MAX), MIN_OK);
18780        assert_eq!(Timedelta::abs(MIN_OK), MAX);
18781        assert_eq!(Timedelta::abs(MAX), MAX);
18782
18783        // Round-tripping the floor must be exact, not sticky at a saturation
18784        // clamp: a `saturating_*` impl that ever clamped would land on
18785        // i64::MIN here and read as NaT.
18786        assert_eq!(Timedelta::neg(Timedelta::neg(MIN_OK)), MIN_OK);
18787        assert_ne!(Timedelta::neg(MIN_OK), Timedelta::NAT);
18788        assert_ne!(Timedelta::abs(MIN_OK), Timedelta::NAT);
18789
18790        // NaT itself is still the one input that stays NaT — the guard, not a
18791        // saturation branch, is what handles it.
18792        assert_eq!(Timedelta::neg(Timedelta::NAT), Timedelta::NAT);
18793        assert_eq!(Timedelta::abs(Timedelta::NAT), Timedelta::NAT);
18794    }
18795
18796    #[test]
18797    fn overflow_divergence_surface_is_only_where_pandas_refuses_fyr1z() {
18798        // br-frankenpandas-fyr1z, the decision bead for DISC-018. The bead was
18799        // filed on the premise "pandas raises; FP returns NaT", which would
18800        // make EVERY overflow a divergence. Probing live pandas 2.2.3 refutes
18801        // that: on the vectorized surface — the one users actually meet —
18802        // pandas returns NaT itself in several of these cases, so FP already
18803        // agrees there and a blanket "STRICT raises" mode would INTRODUCE
18804        // divergence rather than remove it.
18805        //
18806        // This test pins the agreement half. It is the negative control for
18807        // the divergence half already pinned by
18808        // `arithmetic_overflow_never_fabricates_a_finite_value_lgyy8`.
18809        const MAX: i64 = i64::MAX;
18810        const MIN_OK: i64 = i64::MIN + 1;
18811
18812        // ── AGREEMENT: pandas returns NaT here too, measured ───────────────
18813        // Series([Timedelta.max]) / 0    -> [NaT]
18814        // Series([Timedelta.max]) // 0   -> [NaT]
18815        // Series([Timedelta.max]) / 0.0  -> [NaT]
18816        assert_eq!(Timedelta::div_scalar(MAX, 0), Timedelta::NAT);
18817        assert_eq!(Timedelta::div_scalar(MIN_OK, 0), Timedelta::NAT);
18818        assert_eq!(Timedelta::div_scalar(0, 0), Timedelta::NAT);
18819
18820        // Series([Timedelta.min]) - Timedelta('1ns') -> [NaT], because the
18821        // result lands exactly on the i64::MIN sentinel. FP and pandas agree
18822        // — but only by SENTINEL COLLISION, not by policy. One further step
18823        // (`min - 2ns`) is `OverflowError: Overflow in int64 addition` in
18824        // pandas while FP still says NaT, which is the real divergence. A
18825        // test that only checked the 1ns case would therefore prove nothing;
18826        // both depths are asserted so the pair stays honest.
18827        assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT); // pandas: NaT
18828        assert_eq!(Timedelta::sub(MIN_OK, 2), Timedelta::NAT); // pandas: RAISES
18829        assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(1).is_nat());
18830        assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(2).is_nat());
18831
18832        // ── DIVERGENCE: pandas refuses, FP surfaces NaT ────────────────────
18833        // Kept adjacent to the agreement cases so the boundary between the
18834        // two halves is visible in one place; DISC-018 is the prose record.
18835        assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
18836        assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
18837        assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
18838
18839        // ── CONTROL: representable results are untouched by any of this ────
18840        assert_eq!(Timedelta::div_scalar(MAX, 1), MAX);
18841        assert_eq!(Timedelta::div_scalar(-100, 3), -34); // floor, not trunc
18842        assert_eq!(Timedelta::div_scalar(100, -3), -34);
18843        assert_eq!(Timedelta::sub(MIN_OK + 2, 1), MIN_OK + 1);
18844    }
18845
18846    #[test]
18847    fn timedelta_mul_scalar_scales() {
18848        let three_hours = Timedelta::NANOS_PER_HOUR * 3;
18849        assert_eq!(
18850            Timedelta::mul_scalar(Timedelta::NANOS_PER_HOUR, 3),
18851            three_hours
18852        );
18853        assert_eq!(Timedelta::mul_scalar(100, 0), 0);
18854        assert_eq!(Timedelta::mul_scalar(100, -2), -200);
18855    }
18856
18857    #[test]
18858    fn timedelta_mul_scalar_returns_nat_on_overflow() {
18859        // CORRECTED br-frankenpandas-lgyy8: previously asserted i64::MAX.
18860        // pandas `pd.Timedelta.max * 2` raises OverflowError.
18861        assert_eq!(Timedelta::mul_scalar(i64::MAX, 2), Timedelta::NAT);
18862        assert_eq!(Timedelta::mul_scalar(i64::MIN + 1, 2), Timedelta::NAT);
18863    }
18864
18865    #[test]
18866    fn from_unit_nan_is_nat_and_overflow_is_err_8v92m() {
18867        use super::TimedeltaError;
18868
18869        // br-frankenpandas-8v92m. Rust's float->int `as` maps NaN to 0 and
18870        // saturates infinities, so the unguarded
18871        //     Ok((value * multiplier as f64).round() as i64)
18872        // failed OPEN twice: NaN became a ZERO DURATION, and inf/1e30 became a
18873        // finite plausible ~106751-day duration. Live pandas 2.2.3:
18874        //   pd.Timedelta(nan, unit='s')   -> NaT
18875        //   pd.Timedelta(inf, unit='s')   -> OutOfBoundsTimedelta
18876        //                                    "Cannot cast inf from s to 'ns' without overflow."
18877        //   pd.Timedelta(1e30, unit='s')  -> OutOfBoundsTimedelta
18878        //   pd.Timedelta(1.5, unit='s')   -> Timedelta('0 days 00:00:01.5')  <- must NOT change
18879        // The guard is copied from the two siblings that already had it
18880        // (br-frankenpandas-zw3mg), which is why `parse` behaviour is pinned
18881        // below too: all three copies must now agree.
18882
18883        // ── NaN -> NaT, NOT zero. This is the load-bearing case: an impl that
18884        // returns Ok(0) fails, and so does one that returns Err, because
18885        // pandas gives NaT rather than raising.
18886        assert_eq!(Timedelta::from_unit(f64::NAN, "s"), Ok(Timedelta::NAT));
18887        assert_ne!(Timedelta::from_unit(f64::NAN, "s"), Ok(0));
18888        assert_eq!(Timedelta::from_unit(f64::NAN, "D"), Ok(Timedelta::NAT));
18889
18890        // ── non-finite / out-of-range -> Overflow, not a saturated duration.
18891        assert_eq!(
18892            Timedelta::from_unit(f64::INFINITY, "s"),
18893            Err(TimedeltaError::Overflow)
18894        );
18895        assert_eq!(
18896            Timedelta::from_unit(f64::NEG_INFINITY, "s"),
18897            Err(TimedeltaError::Overflow)
18898        );
18899        assert_eq!(
18900            Timedelta::from_unit(1e30, "s"),
18901            Err(TimedeltaError::Overflow)
18902        );
18903        assert_eq!(
18904            Timedelta::from_unit(1e30, "D"),
18905            Err(TimedeltaError::Overflow)
18906        );
18907
18908        // ── CONTROL: ordinary values must be untouched, bit-for-bit. An
18909        // over-eager guard that rejected anything large would fail here.
18910        assert_eq!(Timedelta::from_unit(1.5, "s"), Ok(1_500_000_000));
18911        assert_eq!(Timedelta::from_unit(0.0, "s"), Ok(0));
18912        assert_eq!(Timedelta::from_unit(-2.5, "s"), Ok(-2_500_000_000));
18913        assert_eq!(Timedelta::from_unit(1.0, "D"), Ok(Timedelta::NANOS_PER_DAY));
18914        assert_eq!(
18915            Timedelta::from_unit(3.0, "h"),
18916            Ok(3 * Timedelta::NANOS_PER_HOUR)
18917        );
18918        // Just inside the representable range still returns its exact product,
18919        // so the boundary is pinned from the accepting side as well.
18920        let big_days = 100_000.0_f64;
18921        let expected = (big_days * Timedelta::NANOS_PER_DAY as f64).round() as i64;
18922        assert_eq!(Timedelta::from_unit(big_days, "D"), Ok(expected));
18923        assert!(expected > 0, "fixture must stay in range to be a control");
18924
18925        // ── an unknown unit is still InvalidFormat, NOT Overflow — the unit
18926        // check must keep running before the range check.
18927        assert!(matches!(
18928            Timedelta::from_unit(1.0, "nonsense-unit"),
18929            Err(TimedeltaError::InvalidFormat(_))
18930        ));
18931        assert!(matches!(
18932            Timedelta::from_unit(f64::NAN, "nonsense-unit"),
18933            Err(TimedeltaError::InvalidFormat(_)),
18934        ));
18935
18936        // ── the already-guarded sibling is unchanged. NOTE the input shape:
18937        // the compound lexer accepts only digits, '.' and '-', so scientific
18938        // notation is an InvalidFormat, not an Overflow — the overflow case
18939        // needs a long decimal literal (this is zw3mg's own fixture).
18940        let huge = format!("{} days", "9".repeat(18));
18941        assert!(matches!(
18942            Timedelta::parse(&huge),
18943            Err(TimedeltaError::Overflow)
18944        ));
18945        assert!(matches!(
18946            Timedelta::parse("1e100 days"),
18947            Err(TimedeltaError::InvalidFormat(_))
18948        ));
18949    }
18950
18951    #[test]
18952    fn rounding_and_ms_us_overflow_never_fabricates_a_finite_value_kyd16() {
18953        // br-frankenpandas-kyd16, the sibling sweep of lgyy8. Three defects:
18954        //   (1) Timedelta::round used UNCHECKED `(quotient + 1) * unit_nanos`
18955        //       on the round-up branch — debug PANIC, release WRAP to a
18956        //       large-negative duration.
18957        //   (2) Timedelta::floor/ceil and Timestamp::ceil_to/round_to
18958        //       saturated to i64::MAX, a finite plausible duration / ~year-2262
18959        //       instant handed back as real data — while their own sibling
18960        //       Timestamp::floor_to was ALREADY checked.
18961        //   (3) Timestamp::from_millis/from_micros saturated likewise, while
18962        //       their neighbour `fromtimestamp` already returned NaT.
18963        // Live pandas 2.2.3 raises on every one of these and names the cause:
18964        //   Timestamp.max.ceil('D')/round('D') -> OutOfBoundsDatetime
18965        //       "Cannot round 2262-04-11 23:47:16.854775807 to freq=<Day> without overflow"
18966        //   Timestamp.min.floor('D')           -> OutOfBoundsDatetime (same)
18967        //   Timedelta.max.ceil('D')/round('D') -> OutOfBoundsTimedelta (same shape)
18968        //   Timedelta.min.floor('D')           -> OutOfBoundsTimedelta (same)
18969        // ...but Timestamp.max.floor('D') is an ordinary in-range answer and
18970        // must NOT change. Both halves are asserted below.
18971        const MAX: i64 = i64::MAX;
18972        const MIN_OK: i64 = i64::MIN + 1;
18973        const DAY: i64 = Timedelta::NANOS_PER_DAY;
18974
18975        // ── (1) round(): must not panic, must not wrap negative ────────────
18976        let rounded = Timedelta::round(MAX, "D");
18977        assert_eq!(
18978            rounded,
18979            Timedelta::NAT,
18980            "rounding i64::MAX up to a whole day overflows; the old unchecked \
18981             multiply panicked in debug and wrapped in release"
18982        );
18983        // The wrap signature specifically: a positive input must never round
18984        // to a negative duration. This fails for a wrapping impl even if the
18985        // debug panic is somehow avoided.
18986        assert!(
18987            rounded == Timedelta::NAT || rounded > 0,
18988            "a positive duration must never round to a negative one"
18989        );
18990        assert_eq!(Timedelta::round(MIN_OK, "D"), Timedelta::NAT);
18991
18992        // ── (2) floor/ceil overflow -> NaT, not a fabricated finite value ──
18993        assert_eq!(Timedelta::ceil(MAX, "D"), Timedelta::NAT);
18994        assert_eq!(Timedelta::floor(MIN_OK, "D"), Timedelta::NAT);
18995        assert!(Timestamp::from_nanos(MAX).ceil_to(DAY).is_nat());
18996        assert!(Timestamp::from_nanos(MAX).round_to(DAY).is_nat());
18997        assert!(Timestamp::from_nanos(MIN_OK).floor_to(DAY).is_nat());
18998        assert!(Timestamp::from_nanos(MIN_OK).round_to(DAY).is_nat());
18999
19000        // ── (3) ms/us constructors out of range -> NaT ─────────────────────
19001        assert!(Timestamp::from_millis(MAX, None).is_nat());
19002        assert!(Timestamp::from_millis(MIN_OK, None).is_nat());
19003        assert!(Timestamp::from_micros(MAX, None).is_nat());
19004        assert!(Timestamp::from_micros(MIN_OK, Some("US/Eastern")).is_nat());
19005
19006        // ── CONTROL: in-range rounding is untouched. An implementation that
19007        // NaT'd too eagerly — or that treated "near the limit" as overflow —
19008        // fails every assertion below.
19009        //
19010        // Timestamp.max.floor('D') is the exact case pandas ANSWERS rather
19011        // than raising, so it pins the boundary from the other side.
19012        let max_floor = Timestamp::from_nanos(MAX).floor_to(DAY);
19013        assert!(!max_floor.is_nat(), "Timestamp.max.floor(D) must succeed");
19014        assert_eq!(max_floor.nanos, (MAX / DAY) * DAY);
19015        assert_eq!(Timedelta::floor(MAX, "D"), (MAX / DAY) * DAY);
19016        assert_eq!(
19017            Timedelta::ceil(MIN_OK, "D"),
19018            (MIN_OK.div_euclid(DAY) + 1) * DAY
19019        );
19020
19021        // Ordinary values, bit-for-bit.
19022        let hour = Timedelta::NANOS_PER_HOUR;
19023        assert_eq!(Timedelta::floor(90 * 60 * 1_000_000_000, "h"), hour);
19024        assert_eq!(Timedelta::ceil(90 * 60 * 1_000_000_000, "h"), 2 * hour);
19025        assert_eq!(Timedelta::round(90 * 60 * 1_000_000_000, "h"), 2 * hour);
19026        assert_eq!(Timedelta::round(-90 * 60 * 1_000_000_000, "h"), -2 * hour);
19027        assert_eq!(Timedelta::round(29 * 60 * 1_000_000_000, "h"), 0);
19028        assert_eq!(Timestamp::from_millis(1_500, None).nanos, 1_500_000_000);
19029        assert_eq!(Timestamp::from_micros(-2_000, None).nanos, -2_000_000);
19030        assert_eq!(
19031            Timestamp::from_nanos(hour + 1).floor_to(hour).nanos,
19032            hour,
19033            "in-range floor unchanged"
19034        );
19035        assert_eq!(
19036            Timestamp::from_nanos(hour + 1).ceil_to(hour).nanos,
19037            2 * hour,
19038            "in-range ceil unchanged"
19039        );
19040
19041        // NaT / degenerate-unit inputs unchanged.
19042        assert_eq!(Timedelta::round(Timedelta::NAT, "D"), Timedelta::NAT);
19043        assert_eq!(Timedelta::floor(Timedelta::NAT, "D"), Timedelta::NAT);
19044        assert_eq!(Timedelta::ceil(1_000, "nonsense-unit"), Timedelta::NAT);
19045        assert!(Timestamp::nat().ceil_to(DAY).is_nat());
19046        assert!(Timestamp::from_nanos(0).round_to(0).is_nat());
19047        // A non-overflowing round still carries its zone.
19048        assert_eq!(
19049            Timestamp::from_nanos_tz(hour + 1, "US/Eastern")
19050                .ceil_to(hour)
19051                .tz
19052                .as_deref(),
19053            Some("US/Eastern")
19054        );
19055    }
19056
19057    #[test]
19058    fn timedelta_mul_scalar_propagates_nat() {
19059        assert_eq!(Timedelta::mul_scalar(Timedelta::NAT, 5), Timedelta::NAT);
19060    }
19061
19062    #[test]
19063    fn arithmetic_overflow_never_fabricates_a_finite_value_lgyy8() {
19064        // br-frankenpandas-lgyy8. The bug: these six helpers used
19065        // `saturating_*`, so POSITIVE overflow returned i64::MAX — a valid,
19066        // finite, plausible duration / ~year-2262 instant — as if it were real
19067        // data. (Negative overflow landed on i64::MIN, which IS the NaT
19068        // sentinel, so that direction already surfaced as missing.) Live
19069        // pandas 2.2.3 never returns a fabricated finite value on overflow in
19070        // either direction, scalar or vectorized:
19071        //   pd.Timedelta.max + Timedelta('1ns')  -> OverflowError
19072        //   pd.Timestamp.max + Timedelta('1ns')  -> OutOfBoundsDatetime
19073        //   pd.Timestamp.min - pd.Timestamp.max  -> OutOfBoundsDatetime
19074        //   pd.Timedelta.max * 2                 -> OverflowError
19075        //   pd.Timedelta.min + Timedelta('-1ns') -> NaT
19076        //
19077        // Every assertion below is a case a saturating implementation FAILS.
19078        const MAX: i64 = i64::MAX;
19079        const MIN_OK: i64 = i64::MIN + 1; // most-negative NON-NaT value
19080
19081        // ── positive overflow: the actual bug ──────────────────────────────
19082        assert_eq!(Timedelta::add(MAX, 1), Timedelta::NAT);
19083        assert_eq!(Timedelta::add(MAX - 10, 100), Timedelta::NAT);
19084        assert_eq!(Timedelta::sub(MAX, -1), Timedelta::NAT);
19085        assert_eq!(Timedelta::mul_scalar(MAX, 2), Timedelta::NAT);
19086        assert_eq!(Timedelta::mul_scalar(MAX / 2 + 2, 2), Timedelta::NAT);
19087        assert!(Timestamp::from_nanos(MAX).add_timedelta(1).is_nat());
19088        assert!(Timestamp::from_nanos(MAX).sub_timedelta(-1).is_nat());
19089        // Timestamp.max - Timestamp.min: the true difference is ~2^64, far
19090        // outside i64. Saturation returned MAX (a ~292-year duration presented
19091        // as the real answer); pandas raises OutOfBoundsDatetime.
19092        assert_eq!(
19093            Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(MIN_OK)),
19094            Timedelta::NAT
19095        );
19096
19097        // ── negative overflow: unchanged, still NaT ────────────────────────
19098        assert_eq!(Timedelta::add(MIN_OK, -1), Timedelta::NAT);
19099        assert_eq!(Timedelta::add(MIN_OK, -2), Timedelta::NAT);
19100        assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
19101        assert_eq!(Timedelta::mul_scalar(MIN_OK, 2), Timedelta::NAT);
19102        assert!(Timestamp::from_nanos(MIN_OK).sub_timedelta(1).is_nat());
19103        assert!(Timestamp::from_nanos(MIN_OK).add_timedelta(-1).is_nat());
19104        assert_eq!(
19105            Timestamp::from_nanos(MIN_OK).sub_timestamp(&Timestamp::from_nanos(MAX)),
19106            Timedelta::NAT
19107        );
19108
19109        // ── the boundary: the largest REPRESENTABLE results must still be
19110        // returned exactly. This is what stops the fix from being bought with
19111        // an over-eager NaT that swallows valid arithmetic — an implementation
19112        // that NaT'd one step early fails here, as does one that NaT'd on any
19113        // operand near the limits.
19114        assert_eq!(Timedelta::add(MAX - 1, 1), MAX);
19115        assert_eq!(Timedelta::add(MAX, 0), MAX);
19116        assert_eq!(Timedelta::sub(MAX, 1), MAX - 1);
19117        assert_eq!(Timedelta::add(MIN_OK + 1, -1), MIN_OK);
19118        assert_eq!(Timedelta::mul_scalar(MAX / 2, 2), (MAX / 2) * 2);
19119        assert_eq!(Timedelta::mul_scalar(MIN_OK, 1), MIN_OK);
19120        assert_eq!(Timestamp::from_nanos(MAX - 1).add_timedelta(1).nanos, MAX);
19121        assert_eq!(
19122            Timestamp::from_nanos(MIN_OK + 1).sub_timedelta(1).nanos,
19123            MIN_OK
19124        );
19125        assert_eq!(
19126            Timestamp::from_nanos(MAX).sub_timestamp(&Timestamp::from_nanos(0)),
19127            MAX
19128        );
19129        // Ordinary values are untouched bit-for-bit.
19130        assert_eq!(Timedelta::add(1_000, 2_345), 3_345);
19131        assert_eq!(Timedelta::sub(1_000, 2_345), -1_345);
19132        assert_eq!(Timedelta::mul_scalar(-7, 6), -42);
19133
19134        // ── a result landing EXACTLY on i64::MIN is representable, but i64::MIN
19135        // IS the NaT sentinel, so it must read as NaT rather than as the most
19136        // negative duration. pandas agrees: Timedelta.min + -1ns -> NaT. Note
19137        // `MIN_OK - 1 == i64::MIN` does not overflow, so this case survives the
19138        // switch from saturating_* to checked_* only because the sentinel and
19139        // the clamp coincide — assert it explicitly rather than by accident.
19140        assert_eq!(MIN_OK - 1, i64::MIN);
19141        assert_eq!(Timedelta::sub(MIN_OK, 1), Timedelta::NAT);
19142        assert_eq!(Timedelta::add(MIN_OK, 0), MIN_OK);
19143
19144        // ── NaT operands still propagate, and tz no longer rides along with a
19145        // fabricated instant: an overflowed Timestamp is the canonical NaT.
19146        assert!(Timestamp::nat().add_timedelta(1).is_nat());
19147        assert!(
19148            Timestamp::from_nanos(0)
19149                .add_timedelta(Timedelta::NAT)
19150                .is_nat()
19151        );
19152        let tzed = Timestamp::from_nanos_tz(MAX, "US/Eastern");
19153        let overflowed = tzed.add_timedelta(1);
19154        assert!(overflowed.is_nat());
19155        assert_eq!(overflowed.tz, None, "an overflow NaT carries no zone");
19156        // ...while a NON-overflowing shift still preserves the zone.
19157        assert_eq!(
19158            Timestamp::from_nanos_tz(0, "US/Eastern")
19159                .add_timedelta(Timedelta::NANOS_PER_DAY)
19160                .tz
19161                .as_deref(),
19162            Some("US/Eastern")
19163        );
19164    }
19165
19166    #[test]
19167    fn timedelta_div_scalar_floor_divides() {
19168        // Floor division (matches Python / pandas): -100 // 3 == -34, not -33.
19169        assert_eq!(Timedelta::div_scalar(100, 3), 33);
19170        assert_eq!(Timedelta::div_scalar(-100, 3), -34);
19171        assert_eq!(Timedelta::div_scalar(100, -3), -34);
19172        assert_eq!(Timedelta::div_scalar(-100, -3), 33);
19173    }
19174
19175    #[test]
19176    fn timedelta_div_scalar_zero_divisor_returns_nat() {
19177        assert_eq!(Timedelta::div_scalar(100, 0), Timedelta::NAT);
19178    }
19179
19180    #[test]
19181    fn timedelta_div_scalar_min_neg_one_propagates_nat() {
19182        // i64::MIN aliases NaT, so `div_scalar(i64::MIN, _)` propagates NaT
19183        // — the `i64::MIN / -1` arithmetic-overflow case is subsumed.
19184        assert_eq!(Timedelta::div_scalar(i64::MIN, -1), Timedelta::NAT);
19185        // (i64::MIN + 1) is a real timedelta; `/ -1` does not overflow.
19186        assert_eq!(Timedelta::div_scalar(i64::MIN + 1, -1), i64::MAX);
19187    }
19188
19189    #[test]
19190    fn timedelta_div_scalar_propagates_nat() {
19191        assert_eq!(Timedelta::div_scalar(Timedelta::NAT, 10), Timedelta::NAT);
19192    }
19193
19194    #[test]
19195    fn timedelta_div_timedelta_returns_float_ratio() {
19196        let two_hours = Timedelta::NANOS_PER_HOUR * 2;
19197        let one_hour = Timedelta::NANOS_PER_HOUR;
19198        assert!((Timedelta::div_timedelta(two_hours, one_hour) - 2.0).abs() < 1e-12);
19199        assert!((Timedelta::div_timedelta(one_hour, two_hours) - 0.5).abs() < 1e-12);
19200    }
19201
19202    #[test]
19203    fn timedelta_div_timedelta_nat_returns_nan() {
19204        assert!(Timedelta::div_timedelta(Timedelta::NAT, 100).is_nan());
19205        assert!(Timedelta::div_timedelta(100, Timedelta::NAT).is_nan());
19206    }
19207
19208    // ── Timestamp tests (br-frankenpandas-9p0u — 4r56 Phase 2) ──────────
19209
19210    use super::Timestamp;
19211
19212    #[test]
19213    fn timestamp_from_nanos_is_naive_utc() {
19214        let ts = Timestamp::from_nanos(1_700_000_000_000_000_000);
19215        assert_eq!(ts.nanos, 1_700_000_000_000_000_000);
19216        assert_eq!(ts.tz, None);
19217        assert!(!ts.is_nat());
19218    }
19219
19220    #[test]
19221    fn timestamp_from_nanos_tz_carries_tz_name() {
19222        let ts = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
19223        assert_eq!(ts.tz.as_deref(), Some("US/Eastern"));
19224    }
19225
19226    #[test]
19227    fn timestamp_now_returns_current_time() {
19228        let before = std::time::SystemTime::now()
19229            .duration_since(std::time::UNIX_EPOCH)
19230            .unwrap()
19231            .as_nanos() as i64;
19232        let ts = Timestamp::now();
19233        let after = std::time::SystemTime::now()
19234            .duration_since(std::time::UNIX_EPOCH)
19235            .unwrap()
19236            .as_nanos() as i64;
19237        assert!(ts.nanos >= before);
19238        assert!(ts.nanos <= after);
19239        assert!(!ts.is_nat());
19240    }
19241
19242    #[test]
19243    fn timestamp_today_returns_midnight() {
19244        let ts = Timestamp::today();
19245        assert!(!ts.is_nat());
19246        // Today should be normalized (midnight), so hour/min/sec should be 0
19247        assert_eq!(ts.hour(), Some(0));
19248        assert_eq!(ts.minute(), Some(0));
19249        assert_eq!(ts.second(), Some(0));
19250    }
19251
19252    #[test]
19253    fn timestamp_add_timedelta_shifts_nanos_and_preserves_tz() {
19254        let ts = Timestamp::from_nanos_tz(0, "US/Eastern");
19255        let one_day = Timedelta::NANOS_PER_DAY;
19256        let shifted = ts.add_timedelta(one_day);
19257        assert_eq!(shifted.nanos, one_day);
19258        assert_eq!(shifted.tz.as_deref(), Some("US/Eastern"));
19259    }
19260
19261    #[test]
19262    fn timestamp_add_timedelta_returns_nat_on_overflow() {
19263        // CORRECTED br-frankenpandas-lgyy8: previously asserted i64::MAX, i.e.
19264        // a finite ~year-2262 instant handed back as real data. pandas
19265        // `pd.Timestamp.max + pd.Timedelta('1ns')` raises OutOfBoundsDatetime.
19266        let ts = Timestamp::from_nanos(i64::MAX - 10);
19267        assert!(ts.add_timedelta(100).is_nat());
19268    }
19269
19270    #[test]
19271    fn timestamp_add_timedelta_propagates_nat() {
19272        // NaT Timestamp + anything = NaT.
19273        assert!(Timestamp::nat().add_timedelta(100).is_nat());
19274        // Timestamp + NaT Timedelta = NaT.
19275        assert!(
19276            Timestamp::from_nanos(0)
19277                .add_timedelta(Timedelta::NAT)
19278                .is_nat()
19279        );
19280    }
19281
19282    #[test]
19283    fn timestamp_sub_timedelta_shifts_backward() {
19284        let ts = Timestamp::from_nanos(1_000);
19285        let shifted = ts.sub_timedelta(Timedelta::NANOS_PER_MICRO);
19286        assert_eq!(shifted.nanos, 0);
19287    }
19288
19289    #[test]
19290    fn timestamp_sub_timestamp_returns_timedelta_nanos() {
19291        let t0 = Timestamp::from_nanos(0);
19292        let t1 = Timestamp::from_nanos(Timedelta::NANOS_PER_HOUR);
19293        assert_eq!(t1.sub_timestamp(&t0), Timedelta::NANOS_PER_HOUR);
19294        assert_eq!(t0.sub_timestamp(&t1), -Timedelta::NANOS_PER_HOUR);
19295    }
19296
19297    #[test]
19298    fn timestamp_sub_timestamp_nat_propagates() {
19299        let ts = Timestamp::from_nanos(1_000);
19300        assert_eq!(Timestamp::nat().sub_timestamp(&ts), Timedelta::NAT);
19301        assert_eq!(ts.sub_timestamp(&Timestamp::nat()), Timedelta::NAT);
19302    }
19303
19304    #[test]
19305    fn timestamp_semantic_eq_treats_two_nat_as_equal() {
19306        assert!(Timestamp::nat().semantic_eq(&Timestamp::nat()));
19307        assert!(!Timestamp::nat().semantic_eq(&Timestamp::from_nanos(0)));
19308        assert!(!Timestamp::from_nanos(0).semantic_eq(&Timestamp::nat()));
19309    }
19310
19311    #[test]
19312    fn timestamp_partial_cmp_orders_by_nanos_nat_is_incomparable() {
19313        use std::cmp::Ordering;
19314        let a = Timestamp::from_nanos(0);
19315        let b = Timestamp::from_nanos(100);
19316        assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
19317        assert_eq!(b.partial_cmp(&a), Some(Ordering::Greater));
19318        assert_eq!(a.partial_cmp(&a), Some(Ordering::Equal));
19319        assert_eq!(a.partial_cmp(&Timestamp::nat()), None);
19320        assert_eq!(Timestamp::nat().partial_cmp(&Timestamp::nat()), None);
19321    }
19322
19323    #[test]
19324    fn time_zone_offsets_and_wall_clock_conversions_follow_pandas() {
19325        use crate::{
19326            TimeZoneError, tz_abbreviation, tz_canonical_name, tz_offset_seconds,
19327            tz_utc_to_wall_nanos, tz_validate, tz_wall_to_utc_nanos,
19328        };
19329        let hour = 3_600_000_000_000_i64;
19330        // 2024-03-10 14:30 UTC: Tokyo is +9h; New York is on EDT (-4h) after
19331        // 07:00 UTC that day and on EST (-5h) the day before.
19332        let instant = 1_710_081_000_000_000_000_i64;
19333        assert_eq!(tz_offset_seconds("Asia/Tokyo", instant), Ok(9 * 3_600));
19334        assert_eq!(tz_offset_seconds("US/Eastern", instant), Ok(-4 * 3_600));
19335        assert_eq!(
19336            tz_offset_seconds("US/Eastern", instant - 24 * hour),
19337            Ok(-5 * 3_600)
19338        );
19339        assert_eq!(tz_offset_seconds("+05:30", 0), Ok(19_800));
19340        assert_eq!(tz_offset_seconds("UTC+05:30", 0), Ok(19_800));
19341        assert_eq!(tz_offset_seconds("-03:00", 0), Ok(-10_800));
19342        assert_eq!(tz_offset_seconds("UTC", instant), Ok(0));
19343        assert_eq!(
19344            tz_utc_to_wall_nanos("Asia/Tokyo", instant),
19345            Ok(instant + 9 * hour)
19346        );
19347        // Wall 12:00 in New York on 2024-01-01 is 17:00 UTC, and back.
19348        let wall_noon = 19_723 * 24 * hour + 12 * hour;
19349        assert_eq!(
19350            tz_wall_to_utc_nanos("US/Eastern", wall_noon),
19351            Ok(wall_noon + 5 * hour)
19352        );
19353        assert_eq!(
19354            tz_utc_to_wall_nanos("US/Eastern", wall_noon + 5 * hour),
19355            Ok(wall_noon)
19356        );
19357        // NaT passes through both ways.
19358        assert_eq!(tz_wall_to_utc_nanos("US/Eastern", i64::MIN), Ok(i64::MIN));
19359        assert_eq!(tz_utc_to_wall_nanos("US/Eastern", i64::MIN), Ok(i64::MIN));
19360        // NEGATIVES: 02:30 on 2024-03-10 does not exist in New York; 01:30
19361        // on 2024-11-03 happens twice; unknown zones and malformed offsets
19362        // are pandas' UnknownTimeZoneError.
19363        let skipped = 19_792 * 24 * hour + 2 * hour + 30 * 60_000_000_000;
19364        assert_eq!(
19365            tz_wall_to_utc_nanos("US/Eastern", skipped),
19366            Err(TimeZoneError::NonExistent("2024-03-10 02:30:00".to_owned()))
19367        );
19368        let repeated = 20_030 * 24 * hour + hour + 30 * 60_000_000_000;
19369        assert_eq!(
19370            tz_wall_to_utc_nanos("US/Eastern", repeated),
19371            Err(TimeZoneError::Ambiguous("2024-11-03 01:30:00".to_owned()))
19372        );
19373        assert_eq!(
19374            tz_offset_seconds("Mars/Olympus", 0),
19375            Err(TimeZoneError::Unknown("Mars/Olympus".to_owned()))
19376        );
19377        assert!(tz_validate("+24:00").is_err());
19378        assert!(tz_validate("+5:30").is_err());
19379        assert!(tz_validate("Europe/Paris").is_ok());
19380        // pandas' names: a fixed offset is UTC+HH:MM, a zero one UTC.
19381        assert_eq!(tz_canonical_name("+05:30").as_deref(), Ok("UTC+05:30"));
19382        assert_eq!(tz_canonical_name("UTC-03:00").as_deref(), Ok("UTC-03:00"));
19383        assert_eq!(tz_canonical_name("+00:00").as_deref(), Ok("UTC"));
19384        assert_eq!(tz_canonical_name("Z").as_deref(), Ok("UTC"));
19385        assert_eq!(tz_canonical_name("US/Eastern").as_deref(), Ok("US/Eastern"));
19386        // strftime('%Z'): the abbreviation in force at the instant.
19387        assert_eq!(tz_abbreviation("US/Eastern", instant).as_deref(), Ok("EDT"));
19388        assert_eq!(
19389            tz_abbreviation("US/Eastern", instant - 24 * hour).as_deref(),
19390            Ok("EST")
19391        );
19392        assert_eq!(tz_abbreviation("+05:30", 0).as_deref(), Ok("UTC+05:30"));
19393    }
19394
19395    /// pandas' `tz_localize(ambiguous=, nonexistent=)` for one wall time
19396    /// (br-frankenpandas-84w06), live pandas 2.2.3 in America/New_York:
19397    /// 02:30 on 2024-03-10 does not exist - shift_forward 03:00-04:00 (07:00
19398    /// UTC), shift_backward 01:59:59.999999999-05:00, NaT, or +1h 03:30-04:00;
19399    /// 01:30 on 2024-11-03 happens twice - True (DST) 05:30 UTC, False
19400    /// (standard) 06:30 UTC, NaT.
19401    #[test]
19402    fn tz_localize_policies_follow_pandas_84w06() {
19403        use super::{
19404            AmbiguousTime as A, NonexistentTime as N, TimeZoneError,
19405            tz_wall_to_utc_nanos_with as at,
19406        };
19407        let hour = 3_600_000_000_000_i64;
19408        let minute = 60_000_000_000_i64;
19409        let skipped = 19_792 * 24 * hour + 2 * hour + 30 * minute;
19410        let transition = 19_792 * 24 * hour + 7 * hour;
19411        let zone = "America/New_York";
19412        assert_eq!(at(zone, skipped, A::Raise, N::ShiftForward), Ok(transition));
19413        assert_eq!(
19414            at(zone, skipped, A::Raise, N::ShiftBackward),
19415            Ok(transition - 1)
19416        );
19417        assert_eq!(at(zone, skipped, A::Raise, N::NaT), Ok(i64::MIN));
19418        assert_eq!(
19419            at(zone, skipped, A::Raise, N::Shift(hour)),
19420            Ok(transition + 30 * minute)
19421        );
19422        let repeated = 20_030 * 24 * hour + hour + 30 * minute;
19423        assert_eq!(
19424            at(zone, repeated, A::Earliest, N::Raise),
19425            Ok(repeated + 4 * hour)
19426        );
19427        assert_eq!(
19428            at(zone, repeated, A::Latest, N::Raise),
19429            Ok(repeated + 5 * hour)
19430        );
19431        assert_eq!(at(zone, repeated, A::NaT, N::Raise), Ok(i64::MIN));
19432        // NEGATIVES: the policies leave a wall time that exists once alone,
19433        // and 'raise' still refuses as before.
19434        let noon = 19_723 * 24 * hour + 12 * hour;
19435        assert_eq!(at(zone, noon, A::NaT, N::NaT), Ok(noon + 5 * hour));
19436        assert_eq!(
19437            at(zone, skipped, A::NaT, N::Raise),
19438            Err(TimeZoneError::NonExistent("2024-03-10 02:30:00".to_owned()))
19439        );
19440        assert_eq!(
19441            at(zone, repeated, A::Raise, N::NaT),
19442            Err(TimeZoneError::Ambiguous("2024-11-03 01:30:00".to_owned()))
19443        );
19444    }
19445
19446    #[test]
19447    fn timestamp_display_matches_phase2_debug_format() {
19448        assert_eq!(Timestamp::from_nanos(42).to_string(), "Timestamp[42, UTC]");
19449        assert_eq!(
19450            Timestamp::from_nanos_tz(42, "US/Eastern").to_string(),
19451            "Timestamp[42, US/Eastern]"
19452        );
19453        assert_eq!(Timestamp::nat().to_string(), "NaT");
19454    }
19455
19456    #[test]
19457    fn a_naive_timestamp_cell_casts_to_its_str_srzqw() {
19458        // astype(str) of an object column's naive Timestamp is str(Timestamp)
19459        // - its own fraction, none when whole - not the 'Timestamp[<nanos>]'
19460        // placeholder (br-frankenpandas-srzqw).
19461        let text = |nanos: i64| cast_scalar(&Scalar::Datetime64(nanos), DType::Utf8);
19462        let midnight = 1_711_929_600_000_000_000;
19463        assert_eq!(
19464            text(midnight),
19465            Ok(Scalar::Utf8("2024-04-01 00:00:00".into()))
19466        );
19467        assert_eq!(
19468            text(midnight + 1_000),
19469            Ok(Scalar::Utf8("2024-04-01 00:00:00.000001".into()))
19470        );
19471        assert_eq!(
19472            text(midnight + 1),
19473            Ok(Scalar::Utf8("2024-04-01 00:00:00.000000001".into()))
19474        );
19475        assert_eq!(
19476            text(-1),
19477            Ok(Scalar::Utf8("1969-12-31 23:59:59.999999999".into()))
19478        );
19479        assert_eq!(text(Timestamp::NAT), Ok(Scalar::Utf8("NaT".into())));
19480        // The zoned spelling is the same wall clock and its offset.
19481        assert_eq!(
19482            crate::timestamp_text_in_zone(midnight, "US/Eastern"),
19483            "2024-03-31 20:00:00-04:00"
19484        );
19485    }
19486
19487    #[test]
19488    fn timestamp_value_and_unit_match_pandas_l0edr() {
19489        let ts = Timestamp::from_nanos(1_000_000_123);
19490        assert_eq!(ts.value(), 1_000_000_123);
19491        assert_eq!(ts.unit(), Some("ns"));
19492
19493        let nat = Timestamp::nat();
19494        assert_eq!(nat.value(), Timestamp::NAT);
19495        assert_eq!(nat.unit(), None);
19496    }
19497
19498    #[test]
19499    fn timestamp_numpy_datetime64_materializers_match_value_twksi() {
19500        let ts = Timestamp::from_nanos(1_000_000_123);
19501        assert_eq!(ts.asm8(), ts.value());
19502        assert_eq!(ts.to_datetime64(), ts.value());
19503        assert_eq!(ts.to_numpy(), ts.value());
19504
19505        let nat = Timestamp::nat();
19506        assert_eq!(nat.asm8(), Timestamp::NAT);
19507        assert_eq!(nat.to_datetime64(), Timestamp::NAT);
19508        assert_eq!(nat.to_numpy(), Timestamp::NAT);
19509    }
19510
19511    #[test]
19512    fn timestamp_timestamp_accessor_matches_pandas_microsecond_rounding_py0h3() {
19513        assert_eq!(Timestamp::from_nanos(0).timestamp(), Ok(0.0));
19514        assert_eq!(Timestamp::from_nanos(1_500_000_000).timestamp(), Ok(1.5));
19515        assert_eq!(Timestamp::from_nanos(500).timestamp(), Ok(0.0));
19516        assert_eq!(Timestamp::from_nanos(501).timestamp(), Ok(0.000001));
19517        assert_eq!(Timestamp::from_nanos(2_500).timestamp(), Ok(0.000003));
19518
19519        assert!(matches!(
19520            Timestamp::from_nanos(-500).timestamp(),
19521            Ok(value) if value == -0.0 && value.is_sign_negative()
19522        ));
19523        assert_eq!(Timestamp::from_nanos(-2_500).timestamp(), Ok(-0.000003));
19524        assert_eq!(
19525            Timestamp::nat().timestamp(),
19526            Err(TypeError::ValueIsMissing {
19527                kind: NullKind::NaT,
19528            })
19529        );
19530    }
19531
19532    #[test]
19533    fn timestamp_roundtrips_through_serde_json() {
19534        let naive = Timestamp::from_nanos(1_700_000_000_000_000_000);
19535        let json = serde_json::to_string(&naive).expect("serialize");
19536        let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
19537        assert_eq!(naive, back);
19538
19539        let tz_aware = Timestamp::from_nanos_tz(1_700_000_000_000_000_000, "US/Eastern");
19540        let json = serde_json::to_string(&tz_aware).expect("serialize");
19541        let back: Timestamp = serde_json::from_str(&json).expect("deserialize");
19542        assert_eq!(tz_aware, back);
19543    }
19544
19545    #[test]
19546    fn timestamp_is_send_and_sync() {
19547        fn assert_send_sync<T: Send + Sync>() {}
19548        assert_send_sync::<Timestamp>();
19549    }
19550
19551    // ── Timestamp rounding tests (br-frankenpandas-5h6n) ────────────────
19552
19553    #[test]
19554    fn timestamp_pre_epoch_accessors_floor_not_truncate() {
19555        // br-frankenpandas-wkjtw: pre-1970 instants with a sub-day part used to
19556        // truncate toward zero, landing on the wrong calendar day. -1 ns is
19557        // 1969-12-31 23:59:59.999999999 UTC.
19558        let ts = Timestamp::from_nanos(-1);
19559        assert_eq!(ts.year(), Some(1969));
19560        assert_eq!(ts.month(), Some(12));
19561        assert_eq!(ts.day(), Some(31));
19562        assert_eq!(ts.hour(), Some(23));
19563        assert_eq!(ts.minute(), Some(59));
19564        assert_eq!(ts.second(), Some(59));
19565        assert_eq!(ts.microsecond(), Some(999_999));
19566        assert_eq!(ts.nanosecond(), Some(999));
19567        // 1969-12-31 is a Wednesday (pandas Monday=0 -> 2).
19568        assert_eq!(ts.dayofweek(), Some(2));
19569
19570        // 1969-12-31 12:00:00 — the classic truncation case (-43200 s).
19571        let noon = Timestamp::from_nanos(-43200 * Timedelta::NANOS_PER_SEC);
19572        assert_eq!(noon.year(), Some(1969));
19573        assert_eq!(noon.month(), Some(12));
19574        assert_eq!(noon.day(), Some(31));
19575        assert_eq!(noon.hour(), Some(12));
19576
19577        // Exact midnight pre-epoch was already correct; keep it green.
19578        let midnight = Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY);
19579        assert_eq!(midnight.year(), Some(1969));
19580        assert_eq!(midnight.day(), Some(31));
19581        assert_eq!(midnight.hour(), Some(0));
19582    }
19583
19584    #[test]
19585    fn timestamp_floor_to_rounds_down() {
19586        // 12:34:56 → floor by 1H → 12:00:00
19587        let h = Timedelta::NANOS_PER_HOUR;
19588        let twelve_h = h * 12;
19589        let twelve_thirty_four =
19590            twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
19591        let ts = Timestamp::from_nanos(twelve_thirty_four);
19592        let floored = ts.floor_to(h);
19593        assert_eq!(floored.nanos, twelve_h);
19594    }
19595
19596    #[test]
19597    fn timestamp_floor_to_handles_already_aligned() {
19598        // 12:00:00 floored by 1H → 12:00:00 (no change).
19599        let h = Timedelta::NANOS_PER_HOUR;
19600        let twelve_h = h * 12;
19601        let ts = Timestamp::from_nanos(twelve_h);
19602        assert_eq!(ts.floor_to(h).nanos, twelve_h);
19603    }
19604
19605    #[test]
19606    fn timestamp_floor_to_handles_negative_nanos() {
19607        // -100 ns floored by 60 ns:
19608        //   div_euclid(-100, 60) = -2 (since -2*60=-120, rem=20 ≥ 0).
19609        //   result = -2 * 60 = -120.
19610        let ts = Timestamp::from_nanos(-100);
19611        assert_eq!(ts.floor_to(60).nanos, -120);
19612    }
19613
19614    #[test]
19615    fn timestamp_floor_to_returns_nat_on_axis_underflow_30hdi() {
19616        let ts = Timestamp::from_nanos(i64::MIN + 1);
19617        assert!(ts.floor_to(10).is_nat());
19618
19619        let safe = Timestamp::from_nanos(i64::MIN + 10);
19620        assert_eq!(safe.floor_to(10).nanos, i64::MIN + 8);
19621
19622        let tz = Timestamp::from_nanos_tz(-100, "UTC").floor_to(60);
19623        assert_eq!(tz.nanos, -120);
19624        assert_eq!(tz.tz.as_deref(), Some("UTC"));
19625    }
19626
19627    #[test]
19628    fn timestamp_ceil_to_rounds_up() {
19629        // 12:34:56 → ceil by 1H → 13:00:00.
19630        let h = Timedelta::NANOS_PER_HOUR;
19631        let twelve_h = h * 12;
19632        let thirteen_h = h * 13;
19633        let twelve_thirty_four =
19634            twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
19635        let ts = Timestamp::from_nanos(twelve_thirty_four);
19636        assert_eq!(ts.ceil_to(h).nanos, thirteen_h);
19637    }
19638
19639    #[test]
19640    fn timestamp_ceil_to_no_op_on_aligned() {
19641        let h = Timedelta::NANOS_PER_HOUR;
19642        let twelve_h = h * 12;
19643        let ts = Timestamp::from_nanos(twelve_h);
19644        assert_eq!(ts.ceil_to(h).nanos, twelve_h);
19645    }
19646
19647    #[test]
19648    fn timestamp_round_to_rounds_to_nearest() {
19649        // 12:30:01 (one second past the half-hour): round to 1H → 13:00:00.
19650        let h = Timedelta::NANOS_PER_HOUR;
19651        let twelve_h = h * 12;
19652        let twelve_thirty_one_sec =
19653            twelve_h + Timedelta::NANOS_PER_MIN * 30 + Timedelta::NANOS_PER_SEC;
19654        let ts = Timestamp::from_nanos(twelve_thirty_one_sec);
19655        assert_eq!(ts.round_to(h).nanos, h * 13);
19656
19657        // 12:29:59 (one second before half): round to 1H → 12:00:00.
19658        let twelve_twenty_nine_sec =
19659            twelve_h + Timedelta::NANOS_PER_MIN * 29 + Timedelta::NANOS_PER_SEC * 59;
19660        let ts = Timestamp::from_nanos(twelve_twenty_nine_sec);
19661        assert_eq!(ts.round_to(h).nanos, twelve_h);
19662    }
19663
19664    #[test]
19665    fn timestamp_round_to_bankers_tie_to_even() {
19666        // Tie cases: rem == unit/2 exactly. Pick even-multiple floor.
19667        // unit=10, so half=5. nanos=5: floor=0 (even), so → 0.
19668        // nanos=15: floor=1 (odd), so → 20.
19669        // nanos=25: floor=2 (even), so → 20.
19670        // nanos=35: floor=3 (odd), so → 40.
19671        assert_eq!(Timestamp::from_nanos(5).round_to(10).nanos, 0);
19672        assert_eq!(Timestamp::from_nanos(15).round_to(10).nanos, 20);
19673        assert_eq!(Timestamp::from_nanos(25).round_to(10).nanos, 20);
19674        assert_eq!(Timestamp::from_nanos(35).round_to(10).nanos, 40);
19675    }
19676
19677    #[test]
19678    fn timestamp_round_to_zero_unit_returns_nat() {
19679        let ts = Timestamp::from_nanos(100);
19680        assert!(ts.round_to(0).is_nat());
19681        assert!(ts.floor_to(0).is_nat());
19682        assert!(ts.ceil_to(0).is_nat());
19683    }
19684
19685    #[test]
19686    fn timestamp_round_to_negative_unit_returns_nat() {
19687        let ts = Timestamp::from_nanos(100);
19688        assert!(ts.round_to(-10).is_nat());
19689        assert!(ts.floor_to(-10).is_nat());
19690        assert!(ts.ceil_to(-10).is_nat());
19691    }
19692
19693    #[test]
19694    fn timestamp_rounding_propagates_nat() {
19695        let nat = Timestamp::nat();
19696        assert!(nat.floor_to(60).is_nat());
19697        assert!(nat.ceil_to(60).is_nat());
19698        assert!(nat.round_to(60).is_nat());
19699    }
19700
19701    #[test]
19702    fn timestamp_rounding_preserves_tz() {
19703        let ts = Timestamp::from_nanos_tz(100, "US/Eastern");
19704        assert_eq!(ts.floor_to(60).tz.as_deref(), Some("US/Eastern"));
19705        assert_eq!(ts.ceil_to(60).tz.as_deref(), Some("US/Eastern"));
19706        assert_eq!(ts.round_to(60).tz.as_deref(), Some("US/Eastern"));
19707    }
19708
19709    // ── Timestamp string-unit rounding tests (br-frankenpandas-lbsx) ────
19710
19711    #[test]
19712    fn timestamp_floor_to_unit_h_rounds_to_hour() {
19713        let h = Timedelta::NANOS_PER_HOUR;
19714        let twelve_h = h * 12;
19715        let twelve_thirty_four =
19716            twelve_h + Timedelta::NANOS_PER_MIN * 34 + Timedelta::NANOS_PER_SEC * 56;
19717        let ts = Timestamp::from_nanos(twelve_thirty_four);
19718        assert_eq!(ts.floor_to_unit("H").nanos, twelve_h);
19719        assert_eq!(ts.floor_to_unit("h").nanos, twelve_h);
19720        assert_eq!(ts.floor_to_unit("hour").nanos, twelve_h);
19721        assert_eq!(ts.floor_to_unit("hours").nanos, twelve_h);
19722        assert_eq!(ts.floor_to_unit("hr").nanos, twelve_h);
19723    }
19724
19725    #[test]
19726    fn timestamp_ceil_to_unit_d_rounds_to_day() {
19727        // 12:34:56 → ceil to 1 day → 24:00:00 (next day).
19728        let h = Timedelta::NANOS_PER_HOUR;
19729        let d = Timedelta::NANOS_PER_DAY;
19730        let twelve_thirty_four = h * 12 + Timedelta::NANOS_PER_MIN * 34;
19731        let ts = Timestamp::from_nanos(twelve_thirty_four);
19732        assert_eq!(ts.ceil_to_unit("D").nanos, d);
19733        assert_eq!(ts.ceil_to_unit("day").nanos, d);
19734        assert_eq!(ts.ceil_to_unit("days").nanos, d);
19735    }
19736
19737    #[test]
19738    fn timestamp_round_to_unit_min_rounds_to_minute() {
19739        // 12:34:31 → round to 1 minute → 12:35:00.
19740        let m = Timedelta::NANOS_PER_MIN;
19741        let twelve_thirty_four_thirty_one =
19742            Timedelta::NANOS_PER_HOUR * 12 + m * 34 + Timedelta::NANOS_PER_SEC * 31;
19743        let ts = Timestamp::from_nanos(twelve_thirty_four_thirty_one);
19744        let expected = Timedelta::NANOS_PER_HOUR * 12 + m * 35;
19745        assert_eq!(ts.round_to_unit("min").nanos, expected);
19746        assert_eq!(ts.round_to_unit("T").nanos, expected); // pandas pre-2.2 alias
19747        assert_eq!(ts.round_to_unit("minute").nanos, expected);
19748    }
19749
19750    #[test]
19751    fn timestamp_floor_ceil_round_aliases_match_unit_methods_li897() {
19752        let ts = Timestamp::from_nanos(
19753            Timedelta::NANOS_PER_HOUR * 12
19754                + Timedelta::NANOS_PER_MIN * 34
19755                + Timedelta::NANOS_PER_SEC * 31,
19756        );
19757
19758        assert_eq!(ts.floor("H"), ts.floor_to_unit("H"));
19759        assert_eq!(ts.ceil("D"), ts.ceil_to_unit("D"));
19760        assert_eq!(ts.round("min"), ts.round_to_unit("min"));
19761    }
19762
19763    #[test]
19764    fn timestamp_normalize_floors_to_day_and_preserves_tz_455op() {
19765        let ts = Timestamp::from_nanos_tz(
19766            Timedelta::NANOS_PER_DAY * 3
19767                + Timedelta::NANOS_PER_HOUR * 12
19768                + Timedelta::NANOS_PER_MIN * 34,
19769            "US/Eastern",
19770        );
19771        let normalized = ts.normalize();
19772
19773        assert_eq!(normalized.nanos, Timedelta::NANOS_PER_DAY * 3);
19774        assert_eq!(normalized.tz.as_deref(), Some("US/Eastern"));
19775        assert!(Timestamp::nat().normalize().is_nat());
19776        for nanos in [
19777            i64::MIN + 1,
19778            -Timedelta::NANOS_PER_DAY - 1,
19779            -Timedelta::NANOS_PER_DAY,
19780            -1,
19781            0,
19782            Timedelta::NANOS_PER_DAY - 1,
19783            Timedelta::NANOS_PER_DAY,
19784            i64::MAX,
19785        ] {
19786            let timestamp = Timestamp::from_nanos(nanos);
19787            assert_eq!(timestamp.normalize(), timestamp.floor_to_unit("D"));
19788        }
19789    }
19790
19791    #[test]
19792    #[ignore = "foreground profile-first A/B"]
19793    fn timestamp_normalize_direct_day_profile_dk721() {
19794        use std::{hint::black_box, time::Instant};
19795
19796        fn former(timestamp: &Timestamp) -> Timestamp {
19797            timestamp.floor_to_unit("D")
19798        }
19799
19800        fn candidate(timestamp: &Timestamp) -> Timestamp {
19801            timestamp.normalize()
19802        }
19803
19804        fn elapsed(input: &[Timestamp], normalize: impl Fn(&Timestamp) -> Timestamp) -> u128 {
19805            let started = Instant::now();
19806            let mut checksum = 0_u64;
19807            for timestamp in input {
19808                let normalized = normalize(black_box(timestamp));
19809                checksum = checksum.rotate_left(7) ^ normalized.nanos as u64;
19810            }
19811            black_box(checksum);
19812            started.elapsed().as_nanos()
19813        }
19814
19815        fn percentile(samples: &mut [u128], percent: usize) -> u128 {
19816            samples.sort_unstable();
19817            let rank = (samples.len() * percent).div_ceil(100).saturating_sub(1);
19818            samples[rank]
19819        }
19820
19821        let parity_cases = [
19822            Timestamp::nat(),
19823            Timestamp::from_nanos(i64::MIN + 1),
19824            Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY - 1),
19825            Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY),
19826            Timestamp::from_nanos(-1),
19827            Timestamp::from_nanos(0),
19828            Timestamp::from_nanos(Timedelta::NANOS_PER_DAY - 1),
19829            Timestamp::from_nanos(Timedelta::NANOS_PER_DAY),
19830            Timestamp::from_nanos(i64::MAX),
19831            Timestamp::from_nanos_tz(-1, "US/Eastern"),
19832            Timestamp::from_nanos_tz(
19833                Timedelta::NANOS_PER_DAY + Timedelta::NANOS_PER_HOUR,
19834                "Asia/Tokyo",
19835            ),
19836        ];
19837        for timestamp in &parity_cases {
19838            assert_eq!(former(timestamp), candidate(timestamp));
19839            assert_eq!(timestamp.normalize(), former(timestamp));
19840        }
19841
19842        const ROWS: usize = 16_384;
19843        const SAMPLES: usize = 20;
19844        let input = (0..ROWS)
19845            .map(|index| {
19846                let day = index as i64 % 4_096 - 2_048;
19847                let offset = ((index as u64).wrapping_mul(6_364_136_223_846_793_005_u64)
19848                    % Timedelta::NANOS_PER_DAY as u64) as i64;
19849                Timestamp::from_nanos(day * Timedelta::NANOS_PER_DAY + offset)
19850            })
19851            .collect::<Vec<_>>();
19852        for timestamp in &input {
19853            assert_eq!(former(timestamp), candidate(timestamp));
19854        }
19855
19856        for _ in 0..3 {
19857            black_box(elapsed(&input, former));
19858            black_box(elapsed(&input, candidate));
19859        }
19860
19861        let mut former_ns = Vec::with_capacity(SAMPLES);
19862        let mut candidate_ns = Vec::with_capacity(SAMPLES);
19863        for sample in 0..SAMPLES {
19864            if sample % 2 == 0 {
19865                former_ns.push(elapsed(&input, former));
19866                candidate_ns.push(elapsed(&input, candidate));
19867            } else {
19868                candidate_ns.push(elapsed(&input, candidate));
19869                former_ns.push(elapsed(&input, former));
19870            }
19871        }
19872
19873        let mut former_sorted = former_ns.clone();
19874        let mut candidate_sorted = candidate_ns.clone();
19875        let former_p50 = percentile(&mut former_sorted, 50);
19876        let former_p95 = percentile(&mut former_sorted, 95);
19877        let former_p99 = percentile(&mut former_sorted, 99);
19878        let candidate_p50 = percentile(&mut candidate_sorted, 50);
19879        let candidate_p95 = percentile(&mut candidate_sorted, 95);
19880        let candidate_p99 = percentile(&mut candidate_sorted, 99);
19881        println!(
19882            "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:?}",
19883            former_p50 as f64 / candidate_p50 as f64,
19884            former_p95 as f64 / candidate_p95 as f64,
19885            former_p99 as f64 / candidate_p99 as f64,
19886        );
19887    }
19888
19889    #[test]
19890    fn timestamp_unit_rounding_unknown_unit_returns_nat() {
19891        let ts = Timestamp::from_nanos(100);
19892        assert!(ts.floor_to_unit("fortnight").is_nat());
19893        assert!(ts.ceil_to_unit("century").is_nat());
19894        assert!(ts.round_to_unit("xyz").is_nat());
19895    }
19896
19897    /// pd.Timestamp('2024-03-15 13:47:21').round('15min') is 13:45 (a
19898    /// multiple of a unit was unknown here: NaT).
19899    #[test]
19900    fn timestamp_rounding_reads_a_multiple_of_a_unit_3agof() {
19901        let (min, sec) = (Timedelta::NANOS_PER_MIN, Timedelta::NANOS_PER_SEC);
19902        let base = 1_710_460_800 * sec; // 2024-03-15 00:00:00
19903        let ts = Timestamp::from_nanos(base + 13 * Timedelta::NANOS_PER_HOUR + 47 * min + 21 * sec);
19904        let at = |minutes: i64, seconds: i64| base + minutes * min + seconds * sec;
19905        assert_eq!(ts.round("15min").nanos, at(13 * 60 + 45, 0));
19906        assert_eq!(ts.floor("15min").nanos, at(13 * 60 + 45, 0));
19907        assert_eq!(ts.ceil("15min").nanos, at(14 * 60, 0));
19908        assert_eq!(ts.round("30s").nanos, at(13 * 60 + 47, 30));
19909        assert_eq!(ts.ceil("1D").nanos, base + Timedelta::NANOS_PER_DAY);
19910        // 2024-03-15 is 19797 days after the epoch: the 7-day floor is day
19911        // 19796 (2024-03-14), as pandas'.
19912        assert_eq!(ts.floor("7D").nanos, 19_796 * Timedelta::NANOS_PER_DAY);
19913        // NEGATIVE: a calendar frequency is no fixed length.
19914        assert!(ts.round("ME").is_nat());
19915    }
19916
19917    #[test]
19918    fn timestamp_unit_rounding_propagates_nat() {
19919        let nat = Timestamp::nat();
19920        assert!(nat.floor_to_unit("H").is_nat());
19921        assert!(nat.ceil_to_unit("H").is_nat());
19922        assert!(nat.round_to_unit("H").is_nat());
19923    }
19924
19925    #[test]
19926    fn timestamp_unit_rounding_preserves_tz() {
19927        let ts = Timestamp::from_nanos_tz(Timedelta::NANOS_PER_HOUR * 12 + 100, "US/Eastern");
19928        assert_eq!(ts.floor_to_unit("H").tz.as_deref(), Some("US/Eastern"));
19929        assert_eq!(ts.ceil_to_unit("H").tz.as_deref(), Some("US/Eastern"));
19930        assert_eq!(ts.round_to_unit("H").tz.as_deref(), Some("US/Eastern"));
19931    }
19932
19933    #[test]
19934    fn timedelta_unit_to_nanos_is_now_public_and_matches_pandas_aliases() {
19935        // Public surface check: pandas alias core set.
19936        assert_eq!(
19937            Timedelta::unit_to_nanos("W"),
19938            Some(Timedelta::NANOS_PER_WEEK)
19939        );
19940        assert_eq!(
19941            Timedelta::unit_to_nanos("D"),
19942            Some(Timedelta::NANOS_PER_DAY)
19943        );
19944        assert_eq!(
19945            Timedelta::unit_to_nanos("H"),
19946            Some(Timedelta::NANOS_PER_HOUR)
19947        );
19948        assert_eq!(
19949            Timedelta::unit_to_nanos("min"),
19950            Some(Timedelta::NANOS_PER_MIN)
19951        );
19952        assert_eq!(
19953            Timedelta::unit_to_nanos("s"),
19954            Some(Timedelta::NANOS_PER_SEC)
19955        );
19956        assert_eq!(
19957            Timedelta::unit_to_nanos("ms"),
19958            Some(Timedelta::NANOS_PER_MILLI)
19959        );
19960        assert_eq!(
19961            Timedelta::unit_to_nanos("us"),
19962            Some(Timedelta::NANOS_PER_MICRO)
19963        );
19964        assert_eq!(Timedelta::unit_to_nanos("ns"), Some(1));
19965        // Empty string → days (pandas default).
19966        assert_eq!(Timedelta::unit_to_nanos(""), Some(Timedelta::NANOS_PER_DAY));
19967        // Unknown alias → None.
19968        assert_eq!(Timedelta::unit_to_nanos("century"), None);
19969    }
19970
19971    #[test]
19972    fn timestamp_isoformat_basic() {
19973        let ts = Timestamp::from_nanos(0);
19974        assert_eq!(ts.isoformat(), "1970-01-01T00:00:00");
19975
19976        let ts_utc = Timestamp::from_nanos_tz(0, "UTC");
19977        assert_eq!(ts_utc.isoformat(), "1970-01-01T00:00:00+00:00");
19978
19979        let ts_fixed_offset = Timestamp::from_nanos_tz(0, "UTC+05:30");
19980        assert_eq!(
19981            ts_fixed_offset.isoformat(),
19982            "1970-01-01T05:30:00+05:30",
19983            "a fixed-offset timestamp must render local wall time rather than a UTC instant with an annotation"
19984        );
19985
19986        let ts_tz = Timestamp::from_nanos_tz(
19987            Timedelta::NANOS_PER_DAY
19988                + Timedelta::NANOS_PER_HOUR * 14
19989                + Timedelta::NANOS_PER_MIN * 30,
19990            "America/New_York",
19991        );
19992        assert!(ts_tz.isoformat().contains("1970-01-02T14:30:00"));
19993        assert!(ts_tz.isoformat().contains("[America/New_York]"));
19994
19995        assert_eq!(Timestamp::nat().isoformat(), "NaT");
19996    }
19997
19998    #[test]
19999    fn timestamp_isoformat_pre_epoch_subsecond_uses_floor_day_263m5() {
20000        assert_eq!(
20001            Timestamp::from_nanos(-1).isoformat(),
20002            "1969-12-31T23:59:59.999999999"
20003        );
20004        assert_eq!(
20005            Timestamp::from_nanos(-Timedelta::NANOS_PER_SEC).isoformat(),
20006            "1969-12-31T23:59:59"
20007        );
20008        assert_eq!(
20009            Timestamp::from_nanos(-Timedelta::NANOS_PER_DAY).isoformat(),
20010            "1969-12-31T00:00:00"
20011        );
20012        assert_eq!(
20013            Timestamp::from_nanos_tz(-1, "UTC").isoformat(),
20014            "1969-12-31T23:59:59.999999999+00:00"
20015        );
20016    }
20017
20018    #[test]
20019    fn timestamp_isoformat_preserves_nanosecond_fraction_4r99y() {
20020        assert_eq!(
20021            Timestamp::from_nanos(123_456_789).isoformat(),
20022            "1970-01-01T00:00:00.123456789"
20023        );
20024        assert_eq!(
20025            Timestamp::from_nanos(123_456_000).isoformat(),
20026            "1970-01-01T00:00:00.123456"
20027        );
20028        assert_eq!(
20029            Timestamp::from_nanos(123_000_000).isoformat(),
20030            "1970-01-01T00:00:00.123000"
20031        );
20032        assert_eq!(
20033            Timestamp::from_nanos_tz(1, "UTC").isoformat(),
20034            "1970-01-01T00:00:00.000000001+00:00"
20035        );
20036    }
20037
20038    fn timestamp_isoformat_former_q8g50(timestamp: &Timestamp) -> String {
20039        if timestamp.is_nat() {
20040            return "NaT".to_owned();
20041        }
20042        let base = Timestamp::from_nanos(timestamp.nanos).isoformat();
20043        match &timestamp.tz {
20044            Some(tz) if tz == "UTC" => format!("{base}+00:00"),
20045            Some(tz) => format!("{base}[{tz}]"),
20046            None => base,
20047        }
20048    }
20049
20050    #[test]
20051    fn timestamp_isoformat_one_buffer_matches_former_q8g50() {
20052        let nanos = [
20053            Timestamp::NAT,
20054            -Timedelta::NANOS_PER_DAY - 1,
20055            -Timedelta::NANOS_PER_SEC,
20056            -1,
20057            0,
20058            1,
20059            123_456_000,
20060            123_456_789,
20061            i64::MAX,
20062        ];
20063        let timezones = [
20064            None,
20065            Some("UTC"),
20066            Some("America/New_York"),
20067            Some(""),
20068            Some("Etc/Γ"),
20069        ];
20070        for value in nanos {
20071            for timezone in timezones {
20072                let timestamp = Timestamp {
20073                    nanos: value,
20074                    tz: timezone.map(str::to_owned),
20075                };
20076                assert_eq!(
20077                    timestamp.isoformat(),
20078                    timestamp_isoformat_former_q8g50(&timestamp),
20079                    "nanos={value} timezone={timezone:?}"
20080                );
20081            }
20082        }
20083    }
20084
20085    #[test]
20086    #[ignore = "foreground release A/B only"]
20087    fn timestamp_isoformat_one_buffer_ab_q8g50() {
20088        use std::{hint::black_box, time::Instant};
20089
20090        const ITEMS: usize = 8_192;
20091        const SAMPLES: usize = 10;
20092
20093        fn elapsed(values: &[Timestamp], render: fn(&Timestamp) -> String) -> u128 {
20094            let started = Instant::now();
20095            let mut checksum = 0usize;
20096            for timestamp in black_box(values) {
20097                checksum = checksum.wrapping_add(black_box(render(black_box(timestamp))).len());
20098            }
20099            black_box(checksum);
20100            started.elapsed().as_nanos()
20101        }
20102
20103        let values = (0..ITEMS)
20104            .map(|idx| {
20105                let nanos = (idx as i64 - ITEMS as i64 / 2) * 1_000_123_456_789;
20106                let timezone = if idx.is_multiple_of(2) {
20107                    "UTC"
20108                } else {
20109                    "America/New_York"
20110                };
20111                Timestamp::from_nanos_tz(nanos, timezone)
20112            })
20113            .collect::<Vec<_>>();
20114        for timestamp in &values {
20115            assert_eq!(
20116                timestamp.isoformat(),
20117                timestamp_isoformat_former_q8g50(timestamp)
20118            );
20119        }
20120
20121        black_box(elapsed(&values, timestamp_isoformat_former_q8g50));
20122        black_box(elapsed(&values, Timestamp::isoformat));
20123
20124        let mut former_ns = Vec::with_capacity(SAMPLES);
20125        let mut one_buffer_ns = Vec::with_capacity(SAMPLES);
20126        for sample in 0..SAMPLES {
20127            if sample.is_multiple_of(2) {
20128                former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
20129                one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
20130            } else {
20131                one_buffer_ns.push(elapsed(&values, Timestamp::isoformat));
20132                former_ns.push(elapsed(&values, timestamp_isoformat_former_q8g50));
20133            }
20134        }
20135        former_ns.sort_unstable();
20136        one_buffer_ns.sort_unstable();
20137        let former_p50 = former_ns[SAMPLES / 2];
20138        let one_buffer_p50 = one_buffer_ns[SAMPLES / 2];
20139        println!(
20140            "timestamp_isoformat_one_buffer_ab items={ITEMS} samples={SAMPLES} former_p50_ns={former_p50} one_buffer_p50_ns={one_buffer_p50} speedup={:.6}x",
20141            former_p50 as f64 / one_buffer_p50 as f64
20142        );
20143        println!("former_samples_ns={former_ns:?}");
20144        println!("one_buffer_samples_ns={one_buffer_ns:?}");
20145    }
20146
20147    #[test]
20148    fn timestamp_strftime_basic() {
20149        let ts = Timestamp::from_nanos(
20150            Timedelta::NANOS_PER_DAY * 365
20151                + Timedelta::NANOS_PER_HOUR * 9
20152                + Timedelta::NANOS_PER_MIN * 15,
20153        );
20154        assert_eq!(ts.strftime("%Y-%m-%d"), "1971-01-01");
20155        assert_eq!(ts.strftime("%H:%M:%S"), "09:15:00");
20156        assert_eq!(ts.strftime("%Y/%m/%d %H:%M"), "1971/01/01 09:15");
20157        // TEST-CHANGE: this pinned `%%Y` -> `%1971`; Python (CPython 3.13,
20158        // measured) prints `%%` as a literal `%` and echoes unknown `%Q`.
20159        assert_eq!(ts.strftime("%%Y|%%%m|%Q|%|λ"), "%Y|%01|%Q|%|λ");
20160        assert_eq!(Timestamp::nat().strftime("%Y-%m-%d"), "NaT");
20161    }
20162
20163    #[test]
20164    fn strftime_follows_python_directives_and_zones() {
20165        // 1971-01-01 09:15 (a Friday; ISO week 53 of 1970). Expected texts
20166        // are CPython 3.13's datetime.strftime on Linux.
20167        let ts = Timestamp::from_nanos(
20168            Timedelta::NANOS_PER_DAY * 365
20169                + Timedelta::NANOS_PER_HOUR * 9
20170                + Timedelta::NANOS_PER_MIN * 15,
20171        );
20172        assert_eq!(
20173            ts.strftime("%-d %_m %^a %e %k %l %P %C %g %D %F %T %R %r %h %n %t|"),
20174            "1  1 FRI  1  9  9 am 19 70 01/01/71 1971-01-01 09:15:00 09:15 09:15:00 AM Jan \n \t|"
20175        );
20176        assert_eq!(
20177            ts.strftime("%a %A %b %B %c|%x %X|%I %p %j %U %W %w %y"),
20178            "Fri Friday Jan January Fri Jan  1 09:15:00 1971|01/01/71 09:15:00|09 AM 001 00 00 5 71"
20179        );
20180        // 2021-01-03: a Sunday, ISO 2020-W53-7.
20181        let sunday = Timestamp::parse("2021-01-03").expect("date");
20182        assert_eq!(sunday.strftime("%G-%V-%u %U %W %j"), "2020-53-7 01 00 003");
20183        // Microseconds only; a trailing lone percent stays; naive %z / %Z empty.
20184        let fraction = Timestamp::parse("2024-03-05 14:07:09.123456789").expect("ts");
20185        assert_eq!(fraction.strftime("%f|%z|%Z|abc%"), "123456|||abc%");
20186        // A tz-aware Timestamp prints its wall clock and zone.
20187        let eastern = Timestamp::from_nanos_tz(fraction.nanos, "US/Eastern");
20188        assert_eq!(
20189            eastern.strftime("%Y-%m-%d %H:%M %z %Z"),
20190            "2024-03-05 09:07 -0500 EST"
20191        );
20192        assert_eq!(
20193            crate::strftime_in_zone(fraction.nanos, "%H:%M %z", Some("+05:30")),
20194            "19:37 +0530"
20195        );
20196    }
20197
20198    #[test]
20199    fn timestamp_strftime_floors_pre_epoch_instants_1pmlp() {
20200        let apollo = Timestamp::parse("1969-07-20T20:17:40").unwrap();
20201        assert_eq!(
20202            apollo.strftime("%Y-%m-%d %H:%M:%S.%f"),
20203            "1969-07-20 20:17:40.000000"
20204        );
20205
20206        // The smallest negative instant catches both truncation defects:
20207        // second flooring and day flooring.
20208        let one_ns_before_epoch = Timestamp::from_nanos(-1);
20209        assert_eq!(
20210            one_ns_before_epoch.strftime("%Y-%m-%d %H:%M:%S.%f"),
20211            "1969-12-31 23:59:59.999999"
20212        );
20213    }
20214
20215    #[test]
20216    #[ignore = "foreground normal-release attribution harness"]
20217    fn timestamp_strftime_one_buffer_profile_8qzbo() {
20218        use std::{hint::black_box, time::Instant};
20219
20220        const ITEMS: usize = 8_192;
20221        const SAMPLES: usize = 10;
20222        const FORMAT: &str = "%Y-%m-%d %H:%M:%S.%f|%Y%m%d|%%Y|λ%Q";
20223
20224        fn former(timestamp: &Timestamp, format: &str) -> String {
20225            if timestamp.is_nat() {
20226                return "NaT".to_string();
20227            }
20228            let total_secs = timestamp.nanos / Timedelta::NANOS_PER_SEC;
20229            let sub_nanos = timestamp.nanos.rem_euclid(Timedelta::NANOS_PER_SEC) as u64;
20230
20231            let days_since_epoch = total_secs / 86400;
20232            let secs_of_day = (total_secs % 86400 + 86400) % 86400;
20233            let days = days_since_epoch + 719_468;
20234            let era = (if days >= 0 { days } else { days - 146_096 }) / 146_097;
20235            let doe = days - era * 146_097;
20236            let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
20237            let y = yoe + era * 400;
20238            let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
20239            let mp = (5 * doy + 2) / 153;
20240            let d = doy - (153 * mp + 2) / 5 + 1;
20241            let m = if mp < 10 { mp + 3 } else { mp - 9 };
20242            let year = if m <= 2 { y + 1 } else { y };
20243            let hour = secs_of_day / 3600;
20244            let minute = (secs_of_day % 3600) / 60;
20245            let second = secs_of_day % 60;
20246            let micros = sub_nanos / 1000;
20247
20248            format
20249                .replace("%Y", &format!("{year:04}"))
20250                .replace("%m", &format!("{m:02}"))
20251                .replace("%d", &format!("{d:02}"))
20252                .replace("%H", &format!("{hour:02}"))
20253                .replace("%M", &format!("{minute:02}"))
20254                .replace("%S", &format!("{second:02}"))
20255                .replace("%f", &format!("{micros:06}"))
20256        }
20257
20258        fn elapsed(timestamps: &[Timestamp], formatter: fn(&Timestamp, &str) -> String) -> u128 {
20259            let started = Instant::now();
20260            let mut digest = 0_usize;
20261            for timestamp in timestamps {
20262                let value = formatter(black_box(timestamp), black_box(FORMAT));
20263                digest = digest.wrapping_add(value.len());
20264                digest ^= usize::from(value.as_bytes().first().copied().unwrap_or_default());
20265                black_box(value);
20266            }
20267            black_box(digest);
20268            started.elapsed().as_nanos()
20269        }
20270
20271        fn percentile(samples: &mut [u128], pct: usize) -> u128 {
20272            samples.sort_unstable();
20273            let rank = (samples.len() * pct).div_ceil(100).saturating_sub(1);
20274            samples[rank]
20275        }
20276
20277        let edge_timestamps = [
20278            Timestamp::nat(),
20279            Timestamp::from_nanos(i64::MIN + 1),
20280            Timestamp::from_nanos(-1_234_567_890),
20281            Timestamp::from_nanos(0),
20282            Timestamp::from_nanos(1_735_732_800_123_456_789),
20283            Timestamp::from_nanos(i64::MAX),
20284        ];
20285        let edge_formats = [
20286            "",
20287            "%Y-%m-%d %H:%M:%S.%f",
20288            "%Y%Y%m%m%d%d%H%H%M%M%S%S%f%f",
20289            "%%Y|%%%m|%Q|%|λ",
20290            FORMAT,
20291        ];
20292        for timestamp in &edge_timestamps {
20293            for format in edge_formats {
20294                assert_eq!(former(timestamp, format), timestamp.strftime(format));
20295            }
20296        }
20297
20298        let timestamps = (0..ITEMS)
20299            .map(|index| {
20300                let centered = index as i64 - ITEMS as i64 / 2;
20301                Timestamp::from_nanos(centered * 987_654_321_123_456)
20302            })
20303            .collect::<Vec<_>>();
20304        for timestamp in &timestamps {
20305            assert_eq!(former(timestamp, FORMAT), timestamp.strftime(FORMAT));
20306        }
20307
20308        black_box(elapsed(&timestamps, former));
20309        black_box(elapsed(&timestamps, Timestamp::strftime));
20310
20311        let mut former_samples = Vec::with_capacity(SAMPLES);
20312        let mut public_samples = Vec::with_capacity(SAMPLES);
20313        for sample in 0..SAMPLES {
20314            if sample.is_multiple_of(2) {
20315                former_samples.push(elapsed(&timestamps, former));
20316                public_samples.push(elapsed(&timestamps, Timestamp::strftime));
20317            } else {
20318                public_samples.push(elapsed(&timestamps, Timestamp::strftime));
20319                former_samples.push(elapsed(&timestamps, former));
20320            }
20321        }
20322        let former_p50 = percentile(&mut former_samples, 50);
20323        let former_p95 = percentile(&mut former_samples, 95);
20324        let public_p50 = percentile(&mut public_samples, 50);
20325        let public_p95 = percentile(&mut public_samples, 95);
20326        println!(
20327            "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}",
20328            former_p50 as f64 / public_p50 as f64,
20329            former_p95 as f64 / public_p95 as f64,
20330        );
20331        println!("TIMESTAMP_STRFTIME_AB former_samples_ns={former_samples:?}");
20332        println!("TIMESTAMP_STRFTIME_AB public_samples_ns={public_samples:?}");
20333    }
20334
20335    #[test]
20336    fn timestamp_day_name_and_month_name() {
20337        let ts = Timestamp::from_nanos(0);
20338        assert_eq!(ts.day_name(), "Thursday");
20339        assert_eq!(ts.month_name(), "January");
20340
20341        let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
20342        assert_eq!(ts2.day_name(), "Friday");
20343        assert_eq!(ts2.month_name(), "January");
20344
20345        assert_eq!(Timestamp::nat().day_name(), "NaT");
20346        assert_eq!(Timestamp::nat().month_name(), "NaT");
20347    }
20348
20349    #[test]
20350    fn timestamp_replace_validates_components_zw0y2() {
20351        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
20352        let replaced = ts.replace(
20353            Some(2024),
20354            Some(2),
20355            Some(29),
20356            Some(23),
20357            Some(59),
20358            Some(58),
20359            Some(987_654),
20360            Some(321),
20361        );
20362        assert_eq!(replaced.year(), Some(2024));
20363        assert_eq!(replaced.month(), Some(2));
20364        assert_eq!(replaced.day(), Some(29));
20365        assert_eq!(replaced.hour(), Some(23));
20366        assert_eq!(replaced.minute(), Some(59));
20367        assert_eq!(replaced.second(), Some(58));
20368        assert_eq!(replaced.microsecond(), Some(987_654));
20369        assert_eq!(replaced.nanosecond(), Some(321));
20370
20371        let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
20372        assert_eq!(
20373            tz.replace(None, Some(2), Some(29), None, None, None, None, None)
20374                .tz
20375                .as_deref(),
20376            Some("UTC")
20377        );
20378
20379        assert!(
20380            ts.replace(None, Some(13), None, None, None, None, None, None)
20381                .is_nat()
20382        );
20383        assert!(
20384            ts.replace(Some(2023), Some(2), Some(29), None, None, None, None, None)
20385                .is_nat()
20386        );
20387        assert!(
20388            ts.replace(None, None, None, Some(24), None, None, None, None)
20389                .is_nat()
20390        );
20391        assert!(
20392            ts.replace(None, None, None, None, Some(60), None, None, None)
20393                .is_nat()
20394        );
20395        assert!(
20396            ts.replace(None, None, None, None, None, Some(60), None, None)
20397                .is_nat()
20398        );
20399        assert!(
20400            ts.replace(None, None, None, None, None, None, Some(1_000_000), None)
20401                .is_nat()
20402        );
20403        assert!(
20404            ts.replace(None, None, None, None, None, None, None, Some(1_000))
20405                .is_nat()
20406        );
20407        assert!(
20408            Timestamp::nat()
20409                .replace(Some(2024), Some(1), Some(1), None, None, None, None, None)
20410                .is_nat()
20411        );
20412    }
20413
20414    /// br-frankenpandas-dzz6x: `replace` validates every component EXCEPT the
20415    /// year, and i64 nanoseconds run out around year 2262. The old unchecked
20416    /// multiply wrapped in release mode and handed back a plausible-looking
20417    /// in-range instant for an unrepresentable year — the exact failure a naive
20418    /// implementation still produces, so each far-out year below is a real
20419    /// negative case, not a restatement of the code.
20420    #[test]
20421    fn timestamp_replace_returns_nat_on_nanosecond_overflow_dzz6x() {
20422        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
20423
20424        for year in [3000, 10_000, 300_000, i64::MAX / 400] {
20425            let out = ts.replace(Some(year), None, None, None, None, None, None, None);
20426            assert!(
20427                out.is_nat(),
20428                "replace(year={year}) is unrepresentable in i64 ns and must be \
20429                 NaT, got nanos={:?} (year {:?}) — this is the silent wrap",
20430                out.nanos,
20431                out.year()
20432            );
20433        }
20434        for year in [-3000, -100_000, i64::MIN / 400] {
20435            let out = ts.replace(Some(year), None, None, None, None, None, None, None);
20436            assert!(out.is_nat(), "replace(year={year}) must be NaT");
20437        }
20438
20439        // Boundary: i64 ns tops out at 106_751 days from the epoch, so 2262 is
20440        // representable at the start of the year and 2263 is not. This pins the
20441        // fix to the real limit — a guard that merely rejected "big" years by
20442        // some rounder cutoff would fail one side of this pair.
20443        let in_range = ts.replace(
20444            Some(2262),
20445            Some(1),
20446            Some(1),
20447            Some(0),
20448            Some(0),
20449            Some(0),
20450            Some(0),
20451            Some(0),
20452        );
20453        assert!(
20454            !in_range.is_nat(),
20455            "2262-01-01 is representable and must survive"
20456        );
20457        assert_eq!(in_range.year(), Some(2262));
20458        assert!(
20459            ts.replace(
20460                Some(2263),
20461                Some(12),
20462                Some(31),
20463                Some(23),
20464                Some(59),
20465                Some(59),
20466                Some(999_999),
20467                Some(999)
20468            )
20469            .is_nat(),
20470            "end of 2263 exceeds the i64 ns axis and must be NaT"
20471        );
20472
20473        // In-range results are untouched by the checked arithmetic, including
20474        // the timezone, so the guard cannot have been bought with a behavior
20475        // change on the normal path.
20476        let unchanged = ts.replace(
20477            Some(1999),
20478            Some(6),
20479            Some(30),
20480            Some(12),
20481            Some(1),
20482            Some(2),
20483            Some(3),
20484            Some(4),
20485        );
20486        assert_eq!(unchanged.year(), Some(1999));
20487        assert_eq!(unchanged.month(), Some(6));
20488        assert_eq!(unchanged.day(), Some(30));
20489        assert_eq!(unchanged.hour(), Some(12));
20490        assert_eq!(unchanged.minute(), Some(1));
20491        assert_eq!(unchanged.second(), Some(2));
20492        assert_eq!(unchanged.microsecond(), Some(3));
20493        assert_eq!(unchanged.nanosecond(), Some(4));
20494        let tz = Timestamp::from_nanos_tz(ts.nanos, "UTC");
20495        assert_eq!(
20496            tz.replace(Some(1999), None, None, None, None, None, None, None)
20497                .tz
20498                .as_deref(),
20499            Some("UTC")
20500        );
20501    }
20502
20503    #[test]
20504    fn timestamp_component_accessors() {
20505        let ts = Timestamp::from_nanos(0);
20506        assert_eq!(ts.year(), Some(1970));
20507        assert_eq!(ts.month(), Some(1));
20508        assert_eq!(ts.day(), Some(1));
20509        assert_eq!(ts.hour(), Some(0));
20510        assert_eq!(ts.minute(), Some(0));
20511        assert_eq!(ts.second(), Some(0));
20512        assert_eq!(ts.microsecond(), Some(0));
20513        assert_eq!(ts.nanosecond(), Some(0));
20514
20515        let ts2 = Timestamp::from_nanos(
20516            Timedelta::NANOS_PER_DAY * 365
20517                + Timedelta::NANOS_PER_HOUR * 14
20518                + Timedelta::NANOS_PER_MIN * 30
20519                + Timedelta::NANOS_PER_SEC * 45
20520                + 123_456_789,
20521        );
20522        assert_eq!(ts2.year(), Some(1971));
20523        assert_eq!(ts2.month(), Some(1));
20524        assert_eq!(ts2.day(), Some(1));
20525        assert_eq!(ts2.hour(), Some(14));
20526        assert_eq!(ts2.minute(), Some(30));
20527        assert_eq!(ts2.second(), Some(45));
20528        assert_eq!(ts2.microsecond(), Some(123456));
20529        assert_eq!(ts2.nanosecond(), Some(789));
20530
20531        assert_eq!(Timestamp::nat().year(), None);
20532        assert_eq!(Timestamp::nat().month(), None);
20533        assert_eq!(Timestamp::nat().day(), None);
20534    }
20535
20536    #[test]
20537    fn timestamp_dayofweek_dayofyear_quarter() {
20538        let ts = Timestamp::from_nanos(0);
20539        assert_eq!(ts.dayofweek(), Some(3));
20540        assert_eq!(ts.weekday(), Some(3));
20541        assert_eq!(ts.dayofyear(), Some(1));
20542        assert_eq!(ts.quarter(), Some(1));
20543
20544        let ts2 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 90);
20545        assert_eq!(ts2.quarter(), Some(2));
20546
20547        let ts3 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 365);
20548        assert_eq!(ts3.dayofyear(), Some(1));
20549        assert_eq!(ts3.dayofweek(), Some(4));
20550
20551        assert_eq!(Timestamp::nat().dayofweek(), None);
20552        assert_eq!(Timestamp::nat().dayofyear(), None);
20553        assert_eq!(Timestamp::nat().quarter(), None);
20554    }
20555
20556    #[test]
20557    fn timestamp_is_boundary_methods() {
20558        let jan1 = Timestamp::from_nanos(0);
20559        assert_eq!(jan1.is_leap_year(), Some(false));
20560        assert_eq!(jan1.is_month_start(), Some(true));
20561        assert_eq!(jan1.is_month_end(), Some(false));
20562        assert_eq!(jan1.is_quarter_start(), Some(true));
20563        assert_eq!(jan1.is_quarter_end(), Some(false));
20564        assert_eq!(jan1.is_year_start(), Some(true));
20565        assert_eq!(jan1.is_year_end(), Some(false));
20566
20567        let dec31 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 364);
20568        assert_eq!(dec31.is_month_start(), Some(false));
20569        assert_eq!(dec31.is_month_end(), Some(true));
20570        assert_eq!(dec31.is_quarter_end(), Some(true));
20571        assert_eq!(dec31.is_year_end(), Some(true));
20572
20573        assert_eq!(Timestamp::nat().is_leap_year(), None);
20574        assert_eq!(Timestamp::nat().is_month_start(), None);
20575    }
20576
20577    #[test]
20578    fn timestamp_days_in_month() {
20579        let jan = Timestamp::from_nanos(0);
20580        assert_eq!(jan.days_in_month(), Some(31));
20581        assert_eq!(jan.daysinmonth(), Some(31));
20582
20583        let feb_non_leap = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 31);
20584        assert_eq!(feb_non_leap.days_in_month(), Some(28));
20585
20586        assert_eq!(Timestamp::nat().days_in_month(), None);
20587    }
20588
20589    #[test]
20590    fn timestamp_weekofyear() {
20591        let jan1 = Timestamp::from_nanos(0);
20592        assert_eq!(jan1.weekofyear(), Some(1));
20593        assert_eq!(jan1.week(), Some(1));
20594
20595        let jan8 = Timestamp::from_nanos(Timedelta::NANOS_PER_DAY * 7);
20596        assert_eq!(jan8.weekofyear(), Some(2));
20597
20598        assert_eq!(Timestamp::nat().weekofyear(), None);
20599        assert_eq!(Timestamp::nat().week(), None);
20600    }
20601
20602    #[test]
20603    fn timestamp_weekofyear_iso_53_week_boundaries() {
20604        // ISO-8601 53-week-year boundaries vs pandas 2.2.3 isocalendar().week.
20605        // (br-frankenpandas-xmfmd) Date -> nanos via days since 1970-01-01.
20606        fn week_of(date_days: i64) -> Option<i64> {
20607            Timestamp::from_nanos(date_days * Timedelta::NANOS_PER_DAY).weekofyear()
20608        }
20609        // Days from 1970-01-01 for each date (UTC, no tz).
20610        // 2021-01-01 -> week 53 (2020 is a 53-week year); FP used to give 52.
20611        assert_eq!(week_of(18_628), Some(53)); // 2021-01-01
20612        // 2016-01-01 -> week 53 (2015 is a 53-week year).
20613        assert_eq!(week_of(16_801), Some(53)); // 2016-01-01
20614        // 2026-12-31 -> week 53; FP used to give 1.
20615        assert_eq!(week_of(20_818), Some(53)); // 2026-12-31
20616        // 2020-12-31 -> week 53.
20617        assert_eq!(week_of(18_627), Some(53)); // 2020-12-31
20618        // Cases that must stay correct (non-53 boundaries):
20619        assert_eq!(week_of(19_358), Some(52)); // 2023-01-01 -> week 52
20620        assert_eq!(week_of(20_087), Some(1)); // 2024-12-30 -> week 1
20621        assert_eq!(week_of(18_260), Some(1)); // 2019-12-30 -> week 1
20622    }
20623
20624    #[test]
20625    fn iso_weeks_in_year_53_week_years() {
20626        use super::iso_weeks_in_year;
20627        // Known 53-week years; everything else is 52.
20628        for y in [2004, 2009, 2015, 2020, 2026] {
20629            assert_eq!(iso_weeks_in_year(y), 53, "{y} should have 53 ISO weeks");
20630        }
20631        for y in [2018, 2019, 2021, 2022, 2023, 2024] {
20632            assert_eq!(iso_weeks_in_year(y), 52, "{y} should have 52 ISO weeks");
20633        }
20634    }
20635
20636    #[test]
20637    fn timestamp_to_unit() {
20638        let ts = Timestamp::from_nanos(1_000_000_000);
20639        assert_eq!(ts.to_unit("ns"), Some(1_000_000_000));
20640        assert_eq!(ts.to_unit("us"), Some(1_000_000));
20641        assert_eq!(ts.to_unit("ms"), Some(1_000));
20642        assert_eq!(ts.to_unit("s"), Some(1));
20643        assert_eq!(ts.to_unit("invalid"), None);
20644
20645        assert_eq!(Timestamp::nat().to_unit("ns"), None);
20646    }
20647
20648    #[test]
20649    fn timestamp_toordinal() {
20650        // 2026-01-01 is ordinal 738886 (days since Jan 1, year 1)
20651        // Days from Unix epoch: 738886 - 719163 = 19723
20652        let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
20653        let ts = Timestamp::from_nanos(nanos_2026_01_01);
20654        assert_eq!(ts.toordinal(), Some(738886));
20655
20656        // NaT returns None
20657        assert_eq!(Timestamp::nat().toordinal(), None);
20658    }
20659
20660    #[test]
20661    fn timestamp_fromordinal() {
20662        // Round-trip test: create a timestamp from ordinal derived from toordinal
20663        // First create a known timestamp
20664        let nanos_2026_01_01 = 19723_i64 * 24 * 60 * 60 * 1_000_000_000;
20665        let ts_orig = Timestamp::from_nanos(nanos_2026_01_01);
20666        let ordinal = ts_orig.toordinal().unwrap();
20667
20668        // Now convert back using fromordinal
20669        let ts = Timestamp::fromordinal(ordinal);
20670        assert_eq!(ts.year(), ts_orig.year());
20671        assert_eq!(ts.month(), ts_orig.month());
20672        assert_eq!(ts.day(), ts_orig.day());
20673
20674        // Invalid ordinal returns NaT
20675        let nat = Timestamp::fromordinal(0);
20676        assert!(nat.is_nat());
20677    }
20678
20679    #[test]
20680    fn timestamp_fromordinal_guards_nanosecond_overflow_ycvrd() {
20681        const EPOCH_ORDINAL: i64 = 719_163;
20682        let max_day_offset = i64::MAX / Timedelta::NANOS_PER_DAY;
20683        let max_valid_ordinal = EPOCH_ORDINAL + max_day_offset;
20684
20685        let max_valid = Timestamp::fromordinal(max_valid_ordinal);
20686        assert!(!max_valid.is_nat());
20687        assert_eq!(max_valid.nanos, max_day_offset * Timedelta::NANOS_PER_DAY);
20688
20689        assert!(Timestamp::fromordinal(max_valid_ordinal + 1).is_nat());
20690        assert!(Timestamp::fromordinal(i64::MAX).is_nat());
20691    }
20692
20693    #[test]
20694    fn timestamp_ordinal_matches_seeded_epoch_oracle_l2f0p() {
20695        const EPOCH_ORDINAL: i64 = 719_163;
20696        const DAY: i64 = Timedelta::NANOS_PER_DAY;
20697
20698        fn next(seed: &mut u64) -> u64 {
20699            *seed = seed
20700                .wrapping_mul(3202034522624059733)
20701                .wrapping_add(4354685564936845319);
20702            *seed
20703        }
20704
20705        fn assert_ordinal_case(case: usize, day_offset: i64, subday_nanos: i64) {
20706            let nanos = day_offset.saturating_mul(DAY).saturating_add(subday_nanos);
20707            let ts = Timestamp::from_nanos(nanos);
20708            let expected_day_offset = nanos.div_euclid(DAY);
20709            let expected_ordinal = EPOCH_ORDINAL + expected_day_offset;
20710
20711            assert_eq!(
20712                ts.toordinal(),
20713                Some(expected_ordinal),
20714                "case {case}: toordinal"
20715            );
20716
20717            let midnight = Timestamp::fromordinal(expected_ordinal);
20718            assert_eq!(
20719                midnight.nanos,
20720                expected_day_offset * DAY,
20721                "case {case}: fromordinal nanos"
20722            );
20723            assert_eq!(
20724                midnight.toordinal(),
20725                Some(expected_ordinal),
20726                "case {case}: fromordinal roundtrip"
20727            );
20728        }
20729
20730        assert_eq!(Timestamp::nat().toordinal(), None);
20731        assert!(Timestamp::fromordinal(0).is_nat());
20732        assert!(Timestamp::fromordinal(-1).is_nat());
20733
20734        assert_ordinal_case(usize::MAX, -1, DAY - 1);
20735        assert_ordinal_case(usize::MAX - 1, 0, -1);
20736        assert_ordinal_case(usize::MAX - 2, 19_723, 0);
20737
20738        let mut seed = 0x1f20_f0d1_0a11_0d1e_u64;
20739        for case in 0..260 {
20740            let day_offset = (next(&mut seed) % 40_001) as i64 - 10_000;
20741            let subday_nanos = match case % 7 {
20742                0 => 0,
20743                1 => DAY - 1,
20744                2 => -1,
20745                _ => (next(&mut seed) % (2 * DAY as u64 - 1)) as i64 - (DAY - 1),
20746            };
20747            assert_ordinal_case(case, day_offset, subday_nanos);
20748        }
20749    }
20750
20751    /// br-frankenpandas-94o1u: `parse_date` bounds the month and the day but
20752    /// parses the YEAR as an unbounded i64, and i64 nanoseconds top out around
20753    /// 2262. The old unchecked composition wrapped in release, so these inputs
20754    /// returned `Ok` holding a plausible in-range instant instead of failing —
20755    /// on the INGESTION path, where the input is untrusted. Each case below is
20756    /// a real negative case: a naive implementation still returns Ok here.
20757    #[test]
20758    fn timestamp_parse_rejects_unrepresentable_years_94o1u() {
20759        for s in [
20760            "300000-01-01",
20761            "10000000-06-15T12:30:45",
20762            "999999999-01-01",
20763            "-300000-01-01",
20764            "-99999999-12-31T23:59:59",
20765        ] {
20766            let got = Timestamp::parse(s);
20767            assert!(
20768                got.is_err(),
20769                "parse({s:?}) is unrepresentable in i64 ns and must be Err, got {:?} \
20770                 — this is the silent wrap",
20771                got.map(|ts| (ts.nanos, ts.year()))
20772            );
20773        }
20774
20775        // Boundary: the i64 ns axis reaches into 2262 but not 2263. Pins the
20776        // guard to the real limit — a cutoff at some rounder year fails a side.
20777        let ok = Timestamp::parse("2262-01-01").expect("2262-01-01 is representable");
20778        assert_eq!(ok.year(), Some(2262));
20779        assert!(
20780            Timestamp::parse("2263-12-31T23:59:59").is_err(),
20781            "end of 2263 exceeds the i64 ns axis and must be Err"
20782        );
20783
20784        // A rejected year must not poison the normal path: ordinary parses,
20785        // including every accepted shape (date-only, T- and space-separated,
20786        // fractional seconds, tz suffix), still succeed and are unchanged.
20787        assert_eq!(Timestamp::parse("2024-01-15").unwrap().year(), Some(2024));
20788        assert_eq!(
20789            Timestamp::parse("2024-01-15T10:30:45").unwrap().hour(),
20790            Some(10)
20791        );
20792        assert_eq!(
20793            Timestamp::parse("2024-01-15 10:30:45").unwrap().minute(),
20794            Some(30)
20795        );
20796        assert_eq!(
20797            Timestamp::parse("2024-01-15T10:30:45.123456789")
20798                .unwrap()
20799                .nanosecond(),
20800            Some(789)
20801        );
20802        assert_eq!(
20803            Timestamp::parse("2024-01-15T00:00:00Z").unwrap().year(),
20804            Some(2024)
20805        );
20806        // Pre-epoch (negative nanos) is representable and must keep working.
20807        assert_eq!(Timestamp::parse("1900-01-01").unwrap().year(), Some(1900));
20808    }
20809
20810    #[test]
20811    fn timestamp_parse_iso8601_date_only() {
20812        let ts = Timestamp::parse("2024-01-15").unwrap();
20813        assert_eq!(ts.year(), Some(2024));
20814        assert_eq!(ts.month(), Some(1));
20815        assert_eq!(ts.day(), Some(15));
20816        assert_eq!(ts.hour(), Some(0));
20817        assert_eq!(ts.minute(), Some(0));
20818        assert_eq!(ts.second(), Some(0));
20819    }
20820
20821    #[test]
20822    fn timestamp_parse_iso8601_datetime() {
20823        let ts = Timestamp::parse("2024-01-15T10:30:45").unwrap();
20824        assert_eq!(ts.year(), Some(2024));
20825        assert_eq!(ts.month(), Some(1));
20826        assert_eq!(ts.day(), Some(15));
20827        assert_eq!(ts.hour(), Some(10));
20828        assert_eq!(ts.minute(), Some(30));
20829        assert_eq!(ts.second(), Some(45));
20830    }
20831
20832    #[test]
20833    fn timestamp_parse_space_separator() {
20834        let ts = Timestamp::parse("2024-01-15 10:30:45").unwrap();
20835        assert_eq!(ts.year(), Some(2024));
20836        assert_eq!(ts.hour(), Some(10));
20837    }
20838
20839    #[test]
20840    fn timestamp_parse_with_fractional_seconds() {
20841        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789").unwrap();
20842        assert_eq!(ts.second(), Some(45));
20843        assert_eq!(ts.microsecond(), Some(123456));
20844        assert_eq!(ts.nanosecond(), Some(789));
20845    }
20846
20847    #[test]
20848    fn timestamp_parse_utc_timezone() {
20849        let ts = Timestamp::parse("2024-01-15T10:30:45Z").unwrap();
20850        assert_eq!(ts.tz, Some("UTC".to_string()));
20851    }
20852
20853    #[test]
20854    fn timestamp_parse_offset_timezone() {
20855        let ts = Timestamp::parse("2024-01-15T10:30:45+05:30").unwrap();
20856        assert_eq!(ts.tz, Some("+05:30".to_string()));
20857        // The instant is the wall time less the offset (it was the wall
20858        // time read as UTC).
20859        let utc = |text: &str| Timestamp::parse(text).unwrap().nanos;
20860        assert_eq!(ts.nanos, utc("2024-01-15T05:00:45"));
20861
20862        let ts = Timestamp::parse("2024-01-15T10:30:45-05:30").unwrap();
20863        assert_eq!(ts.tz, Some("-05:30".to_string()));
20864        assert_eq!(ts.nanos, utc("2024-01-15T16:00:45"));
20865        // 'Z' is UTC itself.
20866        assert_eq!(
20867            Timestamp::parse("2024-01-15T10:30:45Z").unwrap().nanos,
20868            utc("2024-01-15T10:30:45")
20869        );
20870    }
20871
20872    #[test]
20873    fn timestamp_parse_rejects_invalid_timezone_offsets_0v676() {
20874        assert!(Timestamp::parse("2024-01-15T10:30:45+bad").is_err());
20875        assert!(Timestamp::parse("2024-01-15T10:30:45+0500").is_err());
20876        assert!(Timestamp::parse("2024-01-15T10:30:45+24:00").is_err());
20877        assert!(Timestamp::parse("2024-01-15T10:30:45+05:60").is_err());
20878        assert!(Timestamp::parse("2024-01-15T10:30:45-25:00").is_err());
20879    }
20880
20881    #[test]
20882    fn timestamp_parse_nat() {
20883        let ts = Timestamp::parse("NaT").unwrap();
20884        assert!(ts.is_nat());
20885        let ts2 = Timestamp::parse("nat").unwrap();
20886        assert!(ts2.is_nat());
20887    }
20888
20889    #[test]
20890    fn timestamp_parse_invalid() {
20891        assert!(Timestamp::parse("not a date").is_err());
20892        assert!(Timestamp::parse("2024-13-01").is_err()); // invalid month
20893        assert!(Timestamp::parse("2024-01-32").is_err()); // invalid day
20894    }
20895
20896    #[test]
20897    fn timestamp_parse_rejects_invalid_fractional_seconds_87se2() {
20898        assert!(Timestamp::parse("2024-01-15T10:30:45.").is_err());
20899        assert!(Timestamp::parse("2024-01-15T10:30:45.abc").is_err());
20900        assert!(Timestamp::parse("2024-01-15T10:30:45.-1").is_err());
20901        assert!(Timestamp::parse("2024-01-15T10:30:45.123").is_err());
20902        assert!(Timestamp::parse("2024-01-15T10:30:45.123456789x").is_err());
20903
20904        let ts = Timestamp::parse("2024-01-15T10:30:45.123456789987").unwrap();
20905        assert_eq!(ts.second(), Some(45));
20906        assert_eq!(ts.microsecond(), Some(123456));
20907        assert_eq!(ts.nanosecond(), Some(789));
20908    }
20909
20910    #[test]
20911    #[ignore = "foreground profile-first A/B"]
20912    fn timestamp_parse_fraction_digit_fold_profile_pdiku() {
20913        use std::{hint::black_box, time::Instant};
20914
20915        const CALLS: usize = 131_072;
20916        const SAMPLES: usize = 12;
20917        type ParsedTime = Option<(u32, u32, u32, u64)>;
20918        const VALID: [&str; 16] = [
20919            "00:00:00.0",
20920            "01:02:03.1",
20921            "02:03:04.01",
20922            "03:04:05.001",
20923            "04:05:06.0001",
20924            "05:06:07.00001",
20925            "06:07:08.000001",
20926            "07:08:09.0000001",
20927            "08:09:10.00000001",
20928            "09:10:11.000000001",
20929            "10:11:12.123456789",
20930            "11:12:13.999999999",
20931            "12:13:14.123456789987",
20932            "13:14:15.000000000001",
20933            "14:15:16.101010101010",
20934            "23:59:59.987654321234",
20935        ];
20936
20937        #[inline(never)]
20938        fn former(s: &str) -> ParsedTime {
20939            let (time_str, frac_str) = match s.split_once('.') {
20940                Some((time, frac)) => (time, Some(frac)),
20941                None => (s, None),
20942            };
20943            let parts: Vec<&str> = time_str.split(':').collect();
20944            if parts.is_empty() || parts.len() > 3 {
20945                return None;
20946            }
20947            let hour: u32 = parts.first().and_then(|p| p.parse().ok())?;
20948            let minute: u32 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
20949            let second: u32 = parts.get(2).and_then(|p| p.parse().ok()).unwrap_or(0);
20950
20951            if hour > 23 || minute > 59 || second > 59 {
20952                return None;
20953            }
20954
20955            let nanos = match frac_str {
20956                None => 0,
20957                Some(frac) => {
20958                    if frac.is_empty() || !frac.bytes().all(|b| b.is_ascii_digit()) {
20959                        return None;
20960                    }
20961                    let truncated = &frac[..frac.len().min(9)];
20962                    let padded = format!("{truncated:0<9}");
20963                    padded.parse::<u64>().ok()?
20964                }
20965            };
20966
20967            Some((hour, minute, second, nanos))
20968        }
20969
20970        #[inline(never)]
20971        fn candidate(s: &str) -> ParsedTime {
20972            Timestamp::parse_time(s)
20973        }
20974
20975        fn elapsed(inputs: &[&str], parser: fn(&str) -> ParsedTime) -> u128 {
20976            let started = Instant::now();
20977            for input in black_box(inputs) {
20978                black_box(parser(black_box(*input)));
20979            }
20980            started.elapsed().as_nanos()
20981        }
20982
20983        fn percentile(samples: &[u128], percent: usize) -> u128 {
20984            let mut sorted = samples.to_vec();
20985            sorted.sort_unstable();
20986            let rank = (sorted.len() * percent).div_ceil(100).saturating_sub(1);
20987            sorted[rank]
20988        }
20989
20990        let invalid = [
20991            "",
20992            "24:00:00.1",
20993            "12:60:00.1",
20994            "12:00:60.1",
20995            "12:00:00.",
20996            "12:00:00.abc",
20997            "12:00:00.-1",
20998            "12:00:00.123",
20999            "12:00:00.123456789x",
21000            "12:00:00.1.2",
21001            "12:00:00:01.1",
21002        ];
21003        for input in VALID.iter().chain(invalid.iter()) {
21004            assert_eq!(candidate(input), former(input), "input={input:?}");
21005        }
21006
21007        let inputs = (0..CALLS)
21008            .map(|index| VALID[index % VALID.len()])
21009            .collect::<Vec<_>>();
21010        for _ in 0..2 {
21011            black_box(elapsed(&inputs, former));
21012            black_box(elapsed(&inputs, candidate));
21013        }
21014
21015        let mut former_ns = Vec::with_capacity(SAMPLES);
21016        let mut candidate_ns = Vec::with_capacity(SAMPLES);
21017        for sample in 0..SAMPLES {
21018            if sample.is_multiple_of(2) {
21019                former_ns.push(elapsed(&inputs, former));
21020                candidate_ns.push(elapsed(&inputs, candidate));
21021            } else {
21022                candidate_ns.push(elapsed(&inputs, candidate));
21023                former_ns.push(elapsed(&inputs, former));
21024            }
21025        }
21026
21027        let former_p50 = percentile(&former_ns, 50);
21028        let former_p95 = percentile(&former_ns, 95);
21029        let former_p99 = percentile(&former_ns, 99);
21030        let candidate_p50 = percentile(&candidate_ns, 50);
21031        let candidate_p95 = percentile(&candidate_ns, 95);
21032        let candidate_p99 = percentile(&candidate_ns, 99);
21033        println!(
21034            "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:?}",
21035            former_p50 as f64 / candidate_p50 as f64,
21036            former_p95 as f64 / candidate_p95 as f64,
21037            former_p99 as f64 / candidate_p99 as f64,
21038        );
21039    }
21040
21041    #[test]
21042    fn timestamp_parse_matches_seeded_iso_component_oracle_1u7a0() {
21043        fn next(seed: &mut u64) -> u64 {
21044            *seed = seed
21045                .wrapping_mul(3935559000370003845)
21046                .wrapping_add(2691343689449507681);
21047            *seed
21048        }
21049
21050        fn leap(year: i64) -> bool {
21051            (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
21052        }
21053
21054        fn month_len(year: i64, month: u32) -> u32 {
21055            match month {
21056                1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
21057                4 | 6 | 9 | 11 => 30,
21058                2 if leap(year) => 29,
21059                2 => 28,
21060                _ => 0,
21061            }
21062        }
21063
21064        struct Components {
21065            year: i64,
21066            month: u32,
21067            day: u32,
21068            hour: u32,
21069            minute: u32,
21070            second: u32,
21071            nanos: u64,
21072        }
21073
21074        fn assert_components(case: usize, text: &str, expected: Components) {
21075            let ts = Timestamp::parse(text).expect("seeded valid timestamp");
21076            let Components {
21077                year,
21078                month,
21079                day,
21080                hour,
21081                minute,
21082                second,
21083                nanos,
21084            } = expected;
21085            assert_eq!(ts.year(), Some(year), "case {case}: year");
21086            assert_eq!(ts.month(), Some(month as i64), "case {case}: month");
21087            assert_eq!(ts.day(), Some(day as i64), "case {case}: day");
21088            assert_eq!(ts.hour(), Some(hour as i64), "case {case}: hour");
21089            assert_eq!(ts.minute(), Some(minute as i64), "case {case}: minute");
21090            assert_eq!(ts.second(), Some(second as i64), "case {case}: second");
21091            assert_eq!(
21092                ts.microsecond(),
21093                Some((nanos / 1000) as i64),
21094                "case {case}: microsecond"
21095            );
21096            assert_eq!(
21097                ts.nanosecond(),
21098                Some((nanos % 1000) as i64),
21099                "case {case}: nanosecond"
21100            );
21101        }
21102
21103        assert!(Timestamp::parse("NaT").expect("NaT parses").is_nat());
21104        assert!(
21105            Timestamp::parse("nAt")
21106                .expect("mixed-case NaT parses")
21107                .is_nat()
21108        );
21109        assert!(Timestamp::parse("1900-02-29").is_err());
21110        assert!(Timestamp::parse("2001-04-31").is_err());
21111        assert!(Timestamp::parse("2024-00-15").is_err());
21112
21113        assert_components(
21114            usize::MAX,
21115            "2000-02-29",
21116            Components {
21117                year: 2000,
21118                month: 2,
21119                day: 29,
21120                hour: 0,
21121                minute: 0,
21122                second: 0,
21123                nanos: 0,
21124            },
21125        );
21126        assert_components(
21127            usize::MAX - 1,
21128            "2024-02-29T23:59:59.000000001",
21129            Components {
21130                year: 2024,
21131                month: 2,
21132                day: 29,
21133                hour: 23,
21134                minute: 59,
21135                second: 59,
21136                nanos: 1,
21137            },
21138        );
21139
21140        let mut seed = 0x15e0_1d50_1f0a_cade_u64;
21141        for case in 0..260 {
21142            let year = 1900 + (next(&mut seed) % 201) as i64;
21143            let month = 1 + (next(&mut seed) % 12) as u32;
21144            let day = 1 + (next(&mut seed) % month_len(year, month) as u64) as u32;
21145            let hour = (next(&mut seed) % 24) as u32;
21146            let minute = (next(&mut seed) % 60) as u32;
21147            let second = (next(&mut seed) % 60) as u32;
21148            let nanos = next(&mut seed) % 1_000_000_000;
21149
21150            match case % 4 {
21151                0 => {
21152                    let text = format!("{year:04}-{month:02}-{day:02}");
21153                    assert_components(
21154                        case,
21155                        &text,
21156                        Components {
21157                            year,
21158                            month,
21159                            day,
21160                            hour: 0,
21161                            minute: 0,
21162                            second: 0,
21163                            nanos: 0,
21164                        },
21165                    );
21166                }
21167                1 => {
21168                    let text =
21169                        format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}");
21170                    assert_components(
21171                        case,
21172                        &text,
21173                        Components {
21174                            year,
21175                            month,
21176                            day,
21177                            hour,
21178                            minute,
21179                            second,
21180                            nanos: 0,
21181                        },
21182                    );
21183                }
21184                2 => {
21185                    let text =
21186                        format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}");
21187                    assert_components(
21188                        case,
21189                        &text,
21190                        Components {
21191                            year,
21192                            month,
21193                            day,
21194                            hour,
21195                            minute,
21196                            second,
21197                            nanos: 0,
21198                        },
21199                    );
21200                }
21201                _ => {
21202                    let text = format!(
21203                        "{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{nanos:09}"
21204                    );
21205                    assert_components(
21206                        case,
21207                        &text,
21208                        Components {
21209                            year,
21210                            month,
21211                            day,
21212                            hour,
21213                            minute,
21214                            second,
21215                            nanos,
21216                        },
21217                    );
21218                }
21219            }
21220        }
21221    }
21222
21223    #[test]
21224    fn period_parse_annual() {
21225        let p = Period::parse("2024").unwrap();
21226        assert_eq!(p.freq(), PeriodFreq::ANNUAL);
21227        assert_eq!(p.ordinal(), 2024 - 1970);
21228    }
21229
21230    #[test]
21231    fn period_parse_quarterly() {
21232        let p = Period::parse("2024Q1").unwrap();
21233        assert_eq!(p.freq(), PeriodFreq::QUARTERLY);
21234        assert_eq!(p.ordinal(), (2024 - 1970) * 4);
21235
21236        let p2 = Period::parse("2024q3").unwrap();
21237        assert_eq!(p2.freq(), PeriodFreq::QUARTERLY);
21238        assert_eq!(p2.ordinal(), (2024 - 1970) * 4 + 2);
21239    }
21240
21241    #[test]
21242    fn period_parse_monthly() {
21243        let p = Period::parse("2024-01").unwrap();
21244        assert_eq!(p.freq(), PeriodFreq::Monthly);
21245        assert_eq!(p.ordinal(), (2024 - 1970) * 12);
21246
21247        let p2 = Period::parse("2024-12").unwrap();
21248        assert_eq!(p2.freq(), PeriodFreq::Monthly);
21249        assert_eq!(p2.ordinal(), (2024 - 1970) * 12 + 11);
21250    }
21251
21252    #[test]
21253    fn period_parse_nat() {
21254        let p = Period::parse("NaT").unwrap();
21255        assert_eq!(p.ordinal(), i64::MIN);
21256    }
21257
21258    #[test]
21259    fn period_parse_invalid() {
21260        assert!(Period::parse("not a period").is_err());
21261        assert!(Period::parse("2024Q5").is_err()); // invalid quarter
21262        assert!(Period::parse("2024-13").is_err()); // invalid month
21263    }
21264
21265    #[test]
21266    fn interval_parse_basic() {
21267        let i = Interval::parse("[0, 1]").unwrap();
21268        assert_eq!(i.left, 0.0);
21269        assert_eq!(i.right, 1.0);
21270        assert_eq!(i.closed, IntervalClosed::Both);
21271
21272        let i2 = Interval::parse("(0, 1)").unwrap();
21273        assert_eq!(i2.left, 0.0);
21274        assert_eq!(i2.right, 1.0);
21275        assert_eq!(i2.closed, IntervalClosed::Neither);
21276
21277        let i3 = Interval::parse("[0, 1)").unwrap();
21278        assert_eq!(i3.closed, IntervalClosed::Left);
21279
21280        let i4 = Interval::parse("(0, 1]").unwrap();
21281        assert_eq!(i4.closed, IntervalClosed::Right);
21282    }
21283
21284    #[test]
21285    fn interval_parse_floats() {
21286        let i = Interval::parse("[-1.5, 2.5)").unwrap();
21287        assert_eq!(i.left, -1.5);
21288        assert_eq!(i.right, 2.5);
21289        assert_eq!(i.closed, IntervalClosed::Left);
21290    }
21291
21292    #[test]
21293    fn interval_parse_invalid() {
21294        assert!(Interval::parse("invalid").is_err());
21295        assert!(Interval::parse("[0]").is_err());
21296        assert!(Interval::parse("0, 1").is_err()); // missing brackets
21297    }
21298
21299    fn interval_parse_error_profile(s: &str) -> super::TypeError {
21300        super::TypeError::ValueNotParseable {
21301            value: s.to_string(),
21302            target: "Interval".to_string(),
21303        }
21304    }
21305
21306    #[inline(never)]
21307    fn interval_parse_former_profile(s: &str) -> Result<Interval, super::TypeError> {
21308        let s = std::hint::black_box(s).trim();
21309        if s.len() < 5 {
21310            return Err(interval_parse_error_profile(s));
21311        }
21312
21313        let first_char = s.chars().next().unwrap();
21314        let last_char = s.chars().last().unwrap();
21315        let left_closed = match first_char {
21316            '[' => true,
21317            '(' => false,
21318            _ => return Err(interval_parse_error_profile(s)),
21319        };
21320        let right_closed = match last_char {
21321            ']' => true,
21322            ')' => false,
21323            _ => return Err(interval_parse_error_profile(s)),
21324        };
21325        let closed = match (left_closed, right_closed) {
21326            (true, true) => IntervalClosed::Both,
21327            (true, false) => IntervalClosed::Left,
21328            (false, true) => IntervalClosed::Right,
21329            (false, false) => IntervalClosed::Neither,
21330        };
21331
21332        let inner = &s[1..s.len() - 1];
21333        let parts: Vec<&str> = inner.split(',').collect();
21334        if parts.len() != 2 {
21335            return Err(interval_parse_error_profile(s));
21336        }
21337        let left = parts[0]
21338            .trim()
21339            .parse()
21340            .map_err(|_| interval_parse_error_profile(s))?;
21341        let right = parts[1]
21342            .trim()
21343            .parse()
21344            .map_err(|_| interval_parse_error_profile(s))?;
21345        Ok(Interval::new(left, right, closed))
21346    }
21347
21348    #[inline(never)]
21349    fn interval_parse_split_once_profile(s: &str) -> Result<Interval, super::TypeError> {
21350        Interval::parse(std::hint::black_box(s))
21351    }
21352
21353    fn assert_interval_parse_profile_parity(s: &str) {
21354        match (
21355            interval_parse_former_profile(s),
21356            interval_parse_split_once_profile(s),
21357        ) {
21358            (Ok(former), Ok(candidate)) => {
21359                assert_eq!(former.left.to_bits(), candidate.left.to_bits(), "left: {s}");
21360                assert_eq!(
21361                    former.right.to_bits(),
21362                    candidate.right.to_bits(),
21363                    "right: {s}"
21364                );
21365                assert_eq!(former.closed, candidate.closed, "closed: {s}");
21366            }
21367            (Err(former), Err(candidate)) => assert_eq!(former, candidate, "error: {s}"),
21368            (former, candidate) => assert_eq!(
21369                former.is_ok(),
21370                candidate.is_ok(),
21371                "parse result mismatch for {s}: {former:?} != {candidate:?}"
21372            ),
21373        }
21374    }
21375
21376    #[inline(never)]
21377    fn measure_interval_parser_profile(
21378        parser: fn(&str) -> Result<Interval, super::TypeError>,
21379        inputs: &[&str],
21380        rounds: usize,
21381    ) -> u128 {
21382        use std::{hint::black_box, time::Instant};
21383
21384        let started = Instant::now();
21385        let mut checksum = 0_u64;
21386        for _ in 0..rounds {
21387            for input in inputs {
21388                let parsed = parser(black_box(input)).expect("profile input must parse");
21389                let closed = match parsed.closed {
21390                    IntervalClosed::Left => 1_u64,
21391                    IntervalClosed::Right => 2,
21392                    IntervalClosed::Both => 3,
21393                    IntervalClosed::Neither => 4,
21394                };
21395                checksum = checksum
21396                    .wrapping_add(parsed.left.to_bits().rotate_left(7))
21397                    .wrapping_add(parsed.right.to_bits().rotate_right(11))
21398                    .wrapping_add(closed);
21399                black_box(parsed);
21400            }
21401        }
21402        black_box(checksum);
21403        started.elapsed().as_nanos()
21404    }
21405
21406    #[test]
21407    #[ignore = "release-only attribution probe for br-frankenpandas-81jjv"]
21408    fn profile_interval_parse_endpoint_split_ab_81jjv() {
21409        const VALID: [&str; 8] = [
21410            "[0, 1]",
21411            "(-0.0, 0.0]",
21412            " [ -1.5e3 , 2.75E-4 ) ",
21413            "(NaN, -0]",
21414            "[-inf, inf)",
21415            "[9.25, -7.5]",
21416            "(4.9406564584124654e-324, 1.7976931348623157e308)",
21417            "[-42, 17.125)",
21418        ];
21419        const INVALID: [&str; 12] = [
21420            "invalid",
21421            "[0]",
21422            "0, 1",
21423            "[0 1]",
21424            "[0, 1, 2]",
21425            "[0, 1,]",
21426            "[0,,1]",
21427            "[, 1]",
21428            "[0, ]",
21429            "{0, 1}",
21430            "[0, 1}",
21431            "  ⟦0, 1⟧  ",
21432        ];
21433        const ROUNDS: usize = 16_384;
21434        const SAMPLES: usize = 10;
21435
21436        for input in VALID.iter().chain(INVALID.iter()) {
21437            assert_interval_parse_profile_parity(input);
21438        }
21439        for _ in 0..2 {
21440            measure_interval_parser_profile(interval_parse_former_profile, &VALID, ROUNDS);
21441            measure_interval_parser_profile(interval_parse_split_once_profile, &VALID, ROUNDS);
21442        }
21443
21444        let mut former_ns = Vec::with_capacity(SAMPLES);
21445        let mut candidate_ns = Vec::with_capacity(SAMPLES);
21446        for sample in 0..SAMPLES {
21447            if sample % 2 == 0 {
21448                former_ns.push(measure_interval_parser_profile(
21449                    interval_parse_former_profile,
21450                    &VALID,
21451                    ROUNDS,
21452                ));
21453                candidate_ns.push(measure_interval_parser_profile(
21454                    interval_parse_split_once_profile,
21455                    &VALID,
21456                    ROUNDS,
21457                ));
21458            } else {
21459                candidate_ns.push(measure_interval_parser_profile(
21460                    interval_parse_split_once_profile,
21461                    &VALID,
21462                    ROUNDS,
21463                ));
21464                former_ns.push(measure_interval_parser_profile(
21465                    interval_parse_former_profile,
21466                    &VALID,
21467                    ROUNDS,
21468                ));
21469            }
21470        }
21471        former_ns.sort_unstable();
21472        candidate_ns.sort_unstable();
21473        let former_p50 = former_ns[SAMPLES / 2];
21474        let candidate_p50 = candidate_ns[SAMPLES / 2];
21475        let former_p95 = former_ns[SAMPLES - 1];
21476        let candidate_p95 = candidate_ns[SAMPLES - 1];
21477        println!("PROFILE_INTERVAL_PARSE_FORMER_NS={former_ns:?}");
21478        println!("PROFILE_INTERVAL_PARSE_CANDIDATE_NS={candidate_ns:?}");
21479        println!(
21480            "PROFILE_INTERVAL_PARSE_P50_RATIO={:.6}",
21481            former_p50 as f64 / candidate_p50 as f64
21482        );
21483        println!(
21484            "PROFILE_INTERVAL_PARSE_P95_RATIO={:.6}",
21485            former_p95 as f64 / candidate_p95 as f64
21486        );
21487    }
21488}
21489
21490/// `DType::Float64Nullable` — pandas' `Float64Dtype()`, the dtype a nullable
21491/// Int64 lane widens INTO (br-frankenpandas-qkqfb).
21492///
21493/// Every rule asserted here was measured against live pandas 2.2.3 before it was
21494/// written; the measurement is quoted next to the assertion it justifies.
21495#[cfg(test)]
21496mod float64_nullable_qkqfb {
21497    use super::{DType, NullKind, Scalar, cast_scalar, common_dtype};
21498
21499    /// THE POINT OF THE DTYPE. A numpy float lane's missing value is a real NaN;
21500    /// the extension lane's is pd.NA. If both mapped to the same marker the two
21501    /// flavours would be indistinguishable and the dtype would buy nothing.
21502    ///
21503    /// MEASURED, live pandas 2.2.3:
21504    /// ```text
21505    ///   pd.Series([1.5, None], dtype="Float64")[1]     -> <NA>   (is pd.NA)
21506    ///   pd.Series([1.5, None])[1]                      -> nan
21507    ///   pd.Series([float("nan")], dtype="Float64")[0]  -> <NA>   COERCED
21508    /// ```
21509    #[test]
21510    fn the_two_float_flavours_have_different_missing_markers_qkqfb() {
21511        assert_eq!(
21512            Scalar::missing_for_dtype(DType::Float64Nullable),
21513            Scalar::Null(NullKind::Null),
21514            "the extension lane stores pd.NA"
21515        );
21516        assert_eq!(
21517            Scalar::missing_for_dtype(DType::Float64),
21518            Scalar::Null(NullKind::NaN),
21519            "the numpy lane stores a real NaN"
21520        );
21521        // The negative case: collapsing these two is precisely the defect, so
21522        // assert they are NOT equal rather than only asserting each value.
21523        assert_ne!(
21524            Scalar::missing_for_dtype(DType::Float64Nullable),
21525            Scalar::missing_for_dtype(DType::Float64),
21526        );
21527    }
21528
21529    /// MEASURED: `str(pd.Float64Dtype())` is `"Float64"`, and the numpy dtype is
21530    /// `"float64"`. dtype-check fixtures assert pandas' SPELLING
21531    /// (br-frankenpandas-62d1s), so the capital F is load-bearing, not cosmetic.
21532    #[test]
21533    fn spelling_is_pandas_spelling_qkqfb() {
21534        assert_eq!(DType::Float64Nullable.name(), "Float64");
21535        assert_eq!(DType::Float64.name(), "float64");
21536        assert_ne!(DType::Float64Nullable.name(), DType::Float64.name());
21537    }
21538
21539    /// The serde spelling has to survive a round trip AND stay distinct from the
21540    /// numpy flavour. `rename_all = "snake_case"` turns `Float64` into
21541    /// `"float64"`, which is what leaves `"Float64"` free for the extension —
21542    /// the same trick `Int64Nullable` already relies on. A naive
21543    /// `#[serde(rename = "Float64")]` on the WRONG variant would collide, and
21544    /// this test is what would catch it.
21545    #[test]
21546    fn serde_round_trips_and_does_not_collide_with_numpy_float64_qkqfb() {
21547        let ext = serde_json::to_string(&DType::Float64Nullable).expect("serialize");
21548        let numpy = serde_json::to_string(&DType::Float64).expect("serialize");
21549        assert_eq!(ext, "\"Float64\"");
21550        assert_eq!(numpy, "\"float64\"");
21551        assert_ne!(ext, numpy);
21552
21553        assert_eq!(
21554            serde_json::from_str::<DType>(&ext).expect("deserialize"),
21555            DType::Float64Nullable
21556        );
21557        assert_eq!(
21558            serde_json::from_str::<DType>(&numpy).expect("deserialize"),
21559            DType::Float64
21560        );
21561    }
21562
21563    /// It is a float, it is numeric, and it is a nullable extension — all three,
21564    /// or downstream dtype dispatch silently skips it.
21565    #[test]
21566    fn predicates_place_it_in_the_right_families_qkqfb() {
21567        assert!(DType::Float64Nullable.is_floating());
21568        assert!(DType::Float64Nullable.is_numeric());
21569        assert!(DType::Float64Nullable.is_any_real_numeric());
21570        assert!(DType::Float64Nullable.is_nullable());
21571        assert!(DType::Float64Nullable.is_extension());
21572        // And NOT these: an integer predicate that accepted it would let a
21573        // float value through an int-only fast path.
21574        assert!(!DType::Float64Nullable.is_integer());
21575        assert!(!DType::Float64Nullable.is_signed_integer());
21576        assert!(!DType::Float64Nullable.is_bool());
21577        // MEASURED: pd.Float64Dtype().kind == 'f', matching numpy float64 --
21578        // the extension reports its UNDERLYING kind, as Int64Nullable does.
21579        assert_eq!(DType::Float64Nullable.kind(), 'f');
21580        assert_eq!(DType::Float64Nullable.kind(), DType::Float64.kind());
21581        assert_eq!(DType::Float64Nullable.itemsize(), 8);
21582    }
21583
21584    /// The nullable/non-nullable pairing must be a genuine involution, or a
21585    /// round trip through either accessor silently changes flavour.
21586    #[test]
21587    fn nullable_pairing_is_an_involution_qkqfb() {
21588        assert_eq!(DType::Float64.to_nullable(), DType::Float64Nullable);
21589        assert_eq!(DType::Float64Nullable.to_non_nullable(), DType::Float64);
21590        // Idempotent at both ends.
21591        assert_eq!(DType::Float64Nullable.to_nullable(), DType::Float64Nullable);
21592        assert_eq!(DType::Float64.to_non_nullable(), DType::Float64);
21593        // The other families are untouched by the new variant.
21594        assert_eq!(DType::Int64.to_nullable(), DType::Int64Nullable);
21595        assert_eq!(DType::Bool.to_nullable(), DType::BoolNullable);
21596    }
21597
21598    /// MEASURED ARITHMETIC, live pandas 2.2.3 -- this function models arithmetic
21599    /// promotion, not `find_common_type` (see the Bool arms in `common_dtype`):
21600    /// ```text
21601    ///   Float64(ext) + float64(numpy)  -> Float64
21602    ///   Int64(ext)   + Float64(ext)    -> Float64
21603    ///   boolean(ext) + Float64(ext)    -> Float64
21604    ///   Float64(ext) - Float64(ext)    -> Float64
21605    /// ```
21606    /// The nullable float absorbs every other numeric flavour.
21607    #[test]
21608    fn the_nullable_float_absorbs_every_numeric_flavour_qkqfb() {
21609        for other in [
21610            DType::Float64,
21611            DType::Int64,
21612            DType::Int64Nullable,
21613            DType::Bool,
21614            DType::BoolNullable,
21615            DType::Float64Nullable,
21616        ] {
21617            assert_eq!(
21618                common_dtype(DType::Float64Nullable, other.clone()),
21619                Ok(DType::Float64Nullable),
21620                "Float64Nullable + {other:?}"
21621            );
21622            // Commutativity is asserted wholesale by
21623            // common_dtype_lattice_axioms_be314; repeated here because an
21624            // asymmetric arm makes df1+df2 disagree with df2+df1.
21625            assert_eq!(
21626                common_dtype(other.clone(), DType::Float64Nullable),
21627                Ok(DType::Float64Nullable),
21628                "{other:?} + Float64Nullable"
21629            );
21630        }
21631        // Null is the lattice identity and must not absorb it.
21632        assert_eq!(
21633            common_dtype(DType::Null, DType::Float64Nullable),
21634            Ok(DType::Float64Nullable)
21635        );
21636    }
21637
21638    /// A PRESENT value crosses between the two float flavours unchanged; only the
21639    /// MISSING marker is converted.
21640    ///
21641    /// MEASURED:
21642    /// ```text
21643    ///   pd.Series([1.5,None],dtype="Float64").astype("float64") -> [1.5, nan]
21644    ///   pd.Series([1,None],  dtype="Int64").astype("Float64")   -> [1.0, <NA>]
21645    /// ```
21646    #[test]
21647    fn casts_preserve_values_and_convert_only_the_marker_qkqfb() {
21648        let present = Scalar::Float64(1.5);
21649        assert_eq!(
21650            cast_scalar(&present, DType::Float64Nullable),
21651            Ok(Scalar::Float64(1.5))
21652        );
21653        assert_eq!(
21654            cast_scalar(&Scalar::Float64(1.5), DType::Float64),
21655            Ok(Scalar::Float64(1.5))
21656        );
21657        // Int -> nullable float widens the value, as pandas does.
21658        assert_eq!(
21659            cast_scalar(&Scalar::Int64(1), DType::Float64Nullable),
21660            Ok(Scalar::Float64(1.0))
21661        );
21662        assert_eq!(
21663            cast_scalar(&Scalar::Bool(true), DType::Float64Nullable),
21664            Ok(Scalar::Float64(1.0))
21665        );
21666
21667        // THE MARKER CONVERSION, in both directions. This is the assertion a
21668        // "just alias Float64Nullable to Float64" implementation fails.
21669        assert_eq!(
21670            cast_scalar(&Scalar::Null(NullKind::NaN), DType::Float64Nullable),
21671            Ok(Scalar::Null(NullKind::Null)),
21672            "numpy NaN entering an extension lane becomes pd.NA"
21673        );
21674        assert_eq!(
21675            cast_scalar(&Scalar::Null(NullKind::Null), DType::Float64),
21676            Ok(Scalar::Null(NullKind::NaN)),
21677            "pd.NA entering a numpy lane becomes NaN"
21678        );
21679    }
21680
21681    /// The slice boundary this test used to pin has now been crossed: a
21682    /// nullable lane widening against a numpy float answers the NULLABLE float.
21683    /// MEASURED, live pandas 2.2.3, both spellings:
21684    /// ```text
21685    ///   find_common_type([Int64, float64])                        ->  Float64
21686    ///   pd.Series([1,None],dtype="Int64") + pd.Series([1.5,2.5])  ->  Float64
21687    /// ```
21688    /// (`Float64` there is the EXTENSION dtype — `Float64Dtype()` — not numpy
21689    /// `float64`.) br-frankenpandas-qkqfb; unblocks br-frankenpandas-f0aaa.
21690    #[test]
21691    fn int64nullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
21692        assert_eq!(
21693            common_dtype(DType::Int64Nullable, DType::Float64),
21694            Ok(DType::Float64Nullable)
21695        );
21696        assert_eq!(
21697            common_dtype(DType::Float64, DType::Int64Nullable),
21698            Ok(DType::Float64Nullable)
21699        );
21700    }
21701
21702    /// The BoolNullable sibling, MEASURED on the same pandas:
21703    /// ```text
21704    ///   pd.Series([True,None],dtype="boolean") + pd.Series([1.5,2.5,3.5])
21705    ///       -> Float64   (extension)
21706    /// ```
21707    /// The numpy-bool lane is NOT affected and stays on numpy float64, which is
21708    /// the control that keeps this from being a blanket "nullable everywhere".
21709    #[test]
21710    fn boolnullable_plus_numpy_float_answers_the_nullable_float_qkqfb() {
21711        assert_eq!(
21712            common_dtype(DType::BoolNullable, DType::Float64),
21713            Ok(DType::Float64Nullable)
21714        );
21715        assert_eq!(
21716            common_dtype(DType::Bool, DType::Float64),
21717            Ok(DType::Float64),
21718            "numpy bool + numpy float stays entirely on the numpy side"
21719        );
21720    }
21721
21722    /// ⚠ WHY THOSE TWO ARMS CANNOT MOVE INDEPENDENTLY. This is the exact triple
21723    /// that fails if only the Int64Nullable arm is flipped, spelled out so the
21724    /// coupling survives someone later "simplifying" one arm back:
21725    /// ```text
21726    ///   (BoolNullable ∨ Int64) ∨ Float64 = Int64Nullable ∨ Float64 = Float64Nullable
21727    ///   BoolNullable ∨ (Int64 ∨ Float64) = BoolNullable  ∨ Float64 = ???
21728    /// ```
21729    /// `common_dtype_lattice_axioms_be314` sweeps this for all 14 dtypes; this
21730    /// test names the single witness so a failure is diagnosable without
21731    /// re-deriving it from a 14³ sweep. (br-frankenpandas-qkqfb)
21732    #[test]
21733    fn the_nullable_float_flip_is_associative_on_its_witness_triple_qkqfb() {
21734        let (bn, i64n, f64d) = (DType::BoolNullable, DType::Int64, DType::Float64);
21735
21736        let left = common_dtype(
21737            common_dtype(bn.clone(), i64n.clone()).unwrap(),
21738            f64d.clone(),
21739        )
21740        .unwrap();
21741        let right = common_dtype(bn, common_dtype(i64n, f64d).unwrap()).unwrap();
21742
21743        assert_eq!(left, right, "promotion order must not change the result");
21744        assert_eq!(left, DType::Float64Nullable);
21745    }
21746}
21747
21748/// br-frankenpandas-3gxc6: the Sparse dtype NAME is parameterized in pandas.
21749///
21750/// Every expectation below was read off live pandas 2.2.3 before the code was
21751/// written, via `str(dtype)` / `dtype.name` on a `pd.SparseDtype`.
21752#[cfg(test)]
21753mod sparse_dtype_pandas_name_3gxc6 {
21754    use super::{DType, Scalar, SparseDType};
21755
21756    fn name(value_dtype: DType, fill: Scalar) -> String {
21757        SparseDType::new(value_dtype, fill)
21758            .expect("sparse descriptor")
21759            .pandas_name()
21760    }
21761
21762    /// The row the corpus fixture `fp_p2d_017_series_dtype_sparse_strict`
21763    /// exercises. FrankenPandas used to answer the bare `"Sparse"`.
21764    #[test]
21765    fn int64_fill_zero_is_the_fixture_row() {
21766        assert_eq!(name(DType::Int64, Scalar::Int64(0)), "Sparse[int64, 0]");
21767    }
21768
21769    /// A non-default fill must appear, or the name would be a constant wearing
21770    /// a parameterized shape.
21771    #[test]
21772    fn the_fill_value_is_actually_rendered() {
21773        assert_eq!(name(DType::Int64, Scalar::Int64(7)), "Sparse[int64, 7]");
21774        assert_ne!(
21775            name(DType::Int64, Scalar::Int64(0)),
21776            name(DType::Int64, Scalar::Int64(7)),
21777            "two different fills must not collapse to one name"
21778        );
21779    }
21780
21781    /// pandas spells this `nan`, lowercase, not `NaN` and not `None`.
21782    #[test]
21783    fn float64_nan_fill_is_lowercase_nan() {
21784        assert_eq!(
21785            name(DType::Float64, Scalar::Float64(f64::NAN)),
21786            "Sparse[float64, nan]"
21787        );
21788    }
21789
21790    /// pandas keeps the trailing `.0` here. A `{}`-style float format would
21791    /// render `0` and silently make this name collide with the int64 one.
21792    #[test]
21793    fn float64_zero_fill_keeps_its_trailing_point_zero() {
21794        assert_eq!(
21795            name(DType::Float64, Scalar::Float64(0.0)),
21796            "Sparse[float64, 0.0]"
21797        );
21798        assert_ne!(
21799            name(DType::Float64, Scalar::Float64(0.0)),
21800            name(DType::Int64, Scalar::Int64(0)),
21801            "float64 and int64 zero fills are different dtypes"
21802        );
21803    }
21804
21805    /// Python capitalisation, not Rust's `false`.
21806    #[test]
21807    fn bool_fill_uses_python_capitalisation() {
21808        assert_eq!(
21809            name(DType::Bool, Scalar::Bool(false)),
21810            "Sparse[bool, False]"
21811        );
21812        assert_eq!(name(DType::Bool, Scalar::Bool(true)), "Sparse[bool, True]");
21813    }
21814
21815    /// FP spells its object dtype `object`, which is what pandas prints for a
21816    /// `SparseDtype(object, nan)`.
21817    #[test]
21818    fn utf8_subtype_renders_as_object() {
21819        let rendered = name(DType::Utf8, Scalar::Null(crate::NullKind::NaN));
21820        assert!(
21821            rendered.starts_with("Sparse[object, "),
21822            "expected an object subtype, got {rendered}"
21823        );
21824    }
21825
21826    /// The bare name is what this bead removed; guard against a regression
21827    /// that reintroduces it for any constructible descriptor.
21828    #[test]
21829    fn no_constructible_descriptor_renders_the_bare_name() {
21830        for (dtype, fill) in [
21831            (DType::Int64, Scalar::Int64(0)),
21832            (DType::Float64, Scalar::Float64(1.5)),
21833            (DType::Bool, Scalar::Bool(true)),
21834            (DType::Utf8, Scalar::Utf8("x".to_owned())),
21835        ] {
21836            let rendered = name(dtype.clone(), fill);
21837            assert_ne!(rendered, "Sparse", "bare name regressed for {dtype:?}");
21838            assert!(
21839                rendered.starts_with("Sparse[") && rendered.ends_with(']'),
21840                "malformed sparse name {rendered}"
21841            );
21842        }
21843    }
21844
21845    #[test]
21846    fn test_dtype_from_str_and_display() {
21847        use std::str::FromStr;
21848
21849        use crate::DType;
21850
21851        assert_eq!(DType::from_str("int64").unwrap(), DType::Int64);
21852        assert_eq!(DType::from_str("Int64").unwrap(), DType::Int64Nullable);
21853        assert_eq!(DType::from_str("float64").unwrap(), DType::Float64);
21854        assert_eq!(DType::from_str("Float64").unwrap(), DType::Float64Nullable);
21855        assert_eq!(DType::from_str("bool").unwrap(), DType::Bool);
21856        assert_eq!(DType::from_str("boolean").unwrap(), DType::BoolNullable);
21857        assert_eq!(DType::from_str("string").unwrap(), DType::Utf8);
21858        assert_eq!(DType::from_str("category").unwrap(), DType::Categorical);
21859        assert_eq!(
21860            DType::from_str("timedelta64[ns]").unwrap(),
21861            DType::Timedelta64
21862        );
21863        assert_eq!(
21864            DType::from_str("datetime64[ns]").unwrap(),
21865            DType::Datetime64 { tz: None }
21866        );
21867        assert_eq!(
21868            DType::from_str("datetime64[ns, UTC]").unwrap(),
21869            DType::Datetime64 {
21870                tz: Some("UTC".to_string())
21871            }
21872        );
21873        assert_eq!(DType::from_str("period").unwrap(), DType::Period);
21874        assert_eq!(DType::from_str("interval").unwrap(), DType::Interval);
21875        assert_eq!(DType::from_str("sparse").unwrap(), DType::Sparse);
21876
21877        assert_eq!(format!("{}", DType::Int64), "int64");
21878        assert_eq!(
21879            format!(
21880                "{}",
21881                DType::Datetime64 {
21882                    tz: Some("UTC".to_string())
21883                }
21884            ),
21885            "datetime64[ns, UTC]"
21886        );
21887    }
21888
21889    #[test]
21890    fn test_api_types_inspection_and_infer_dtype() {
21891        use crate::{
21892            DType, Scalar,
21893            api::types::{
21894                infer_dtype, is_bool_dtype, is_categorical_dtype, is_datetime64_any_dtype,
21895                is_dtype_equal, is_extension_array_dtype, is_float_dtype, is_int64_dtype,
21896                is_integer_dtype, is_interval_dtype, is_numeric_dtype, is_object_dtype,
21897                is_period_dtype, is_scalar, is_signed_integer_dtype, is_sparse, is_string_dtype,
21898                is_timedelta64_dtype, is_unsigned_integer_dtype, pandas_dtype,
21899            },
21900        };
21901
21902        assert!(is_numeric_dtype(&DType::Int64));
21903        assert!(is_numeric_dtype(&DType::Float64));
21904        assert!(!is_numeric_dtype(&DType::Utf8));
21905        assert!(!is_numeric_dtype(&DType::Bool));
21906
21907        assert!(is_integer_dtype(&DType::Int64));
21908        assert!(is_integer_dtype(&DType::Int64Nullable));
21909        assert!(!is_integer_dtype(&DType::Float64));
21910
21911        assert!(is_int64_dtype(&DType::Int64));
21912        assert!(is_int64_dtype(&DType::Int64Nullable));
21913        assert!(!is_int64_dtype(&DType::Float64));
21914
21915        assert!(is_object_dtype(&DType::Utf8));
21916        assert!(!is_object_dtype(&DType::Int64));
21917
21918        assert!(is_dtype_equal(&DType::Int64, &DType::Int64));
21919        assert!(is_dtype_equal(&"int64", &DType::Int64));
21920        assert!(!is_dtype_equal(&DType::Int64, &DType::Float64));
21921
21922        assert!(is_signed_integer_dtype(&DType::Int64));
21923        assert!(!is_unsigned_integer_dtype(&DType::Int64));
21924
21925        assert!(is_float_dtype(&DType::Float64));
21926        assert!(is_bool_dtype(&DType::Bool));
21927        assert!(is_string_dtype(&DType::Utf8));
21928        assert!(is_datetime64_any_dtype(&DType::Datetime64 { tz: None }));
21929        assert!(is_timedelta64_dtype(&DType::Timedelta64));
21930        assert!(is_categorical_dtype(&DType::Categorical));
21931        assert!(is_period_dtype(&DType::Period));
21932        assert!(is_interval_dtype(&DType::Interval));
21933        assert!(is_sparse(&DType::Sparse));
21934        assert!(is_extension_array_dtype(&DType::Categorical));
21935        assert!(is_scalar(&Scalar::Int64(42)));
21936
21937        assert_eq!(pandas_dtype("float64").unwrap(), DType::Float64);
21938        assert!(pandas_dtype("invalid_dtype_xyz").is_err());
21939
21940        let ints = vec![Scalar::Int64(1), Scalar::Int64(2)];
21941        assert_eq!(infer_dtype(&ints, true), "integer");
21942
21943        let floats = vec![Scalar::Float64(1.0), Scalar::Float64(2.5)];
21944        assert_eq!(infer_dtype(&floats, true), "floating");
21945
21946        let bools = vec![Scalar::Bool(true), Scalar::Bool(false)];
21947        assert_eq!(infer_dtype(&bools, true), "boolean");
21948
21949        let strings = vec![Scalar::Utf8("a".to_string()), Scalar::Utf8("b".to_string())];
21950        assert_eq!(infer_dtype(&strings, true), "string");
21951
21952        let mixed = vec![Scalar::Int64(1), Scalar::Utf8("a".to_string())];
21953        assert_eq!(infer_dtype(&mixed, true), "mixed");
21954
21955        assert_eq!(infer_dtype(&[], true), "empty");
21956    }
21957
21958    #[test]
21959    fn test_na_nat_sentinels_and_eng_float_format() {
21960        use super::{
21961            NA, NAT, NaT, eng_float_format, get_eng_float_format, reset_eng_float_format,
21962            set_eng_float_format,
21963        };
21964
21965        // NA and NAT sentinels
21966        assert!(NA.is_null());
21967        assert!(NAT.is_null());
21968        assert_eq!(NAT, NaT);
21969        assert_eq!(format!("{NA}"), "None");
21970        assert_eq!(format!("{NAT}"), "NaT");
21971
21972        // Engineering float format tests
21973        assert_eq!(eng_float_format(1000.0, Some(3), false), "1.000E+03");
21974        assert_eq!(eng_float_format(0.005, Some(3), false), "5.000E-03");
21975        assert_eq!(eng_float_format(1234567.0, Some(3), false), "1.235E+06");
21976        assert_eq!(eng_float_format(-9876.54, Some(3), false), "-9.877E+03");
21977        assert_eq!(eng_float_format(0.0, Some(3), false), "0.000E+00");
21978
21979        // With prefixes
21980        assert_eq!(eng_float_format(1000.0, Some(3), true), "1.000k");
21981        assert_eq!(eng_float_format(0.005, Some(3), true), "5.000m");
21982        assert_eq!(eng_float_format(1234567.0, Some(3), true), "1.235M");
21983        assert_eq!(eng_float_format(-9876.54, Some(3), true), "-9.877k");
21984        assert_eq!(eng_float_format(0.0, Some(3), true), "0.000");
21985        assert_eq!(eng_float_format(1.5, Some(3), true), "1.500");
21986
21987        // Special numbers
21988        assert_eq!(eng_float_format(f64::NAN, Some(3), true), "NaN");
21989        assert_eq!(eng_float_format(f64::INFINITY, Some(3), true), "inf");
21990        assert_eq!(eng_float_format(f64::NEG_INFINITY, Some(3), true), "-inf");
21991
21992        // Configuration helpers
21993        reset_eng_float_format();
21994        assert_eq!(get_eng_float_format(), None);
21995        set_eng_float_format(4, true);
21996        assert_eq!(get_eng_float_format(), Some((4, true)));
21997        reset_eng_float_format();
21998        assert_eq!(get_eng_float_format(), None);
21999    }
22000
22001    #[test]
22002    fn test_options_system() {
22003        use super::{
22004            OptionError, OptionValue, describe_option, get_option, option_context, reset_option,
22005            set_option,
22006        };
22007
22008        // Reset to clean state
22009        reset_option(None).unwrap();
22010
22011        // 1. Default option checks
22012        let max_rows = get_option("display.max_rows").unwrap();
22013        assert_eq!(max_rows.as_int(), Some(60));
22014        assert_eq!(max_rows, OptionValue::Int(60));
22015        assert!(!max_rows.is_none());
22016
22017        // Partial key matching (suffix)
22018        let min_rows = get_option("min_rows").unwrap();
22019        assert_eq!(min_rows.as_int(), Some(10));
22020
22021        // 2. Setting options
22022        set_option("display.max_rows", 100).unwrap();
22023        assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(100));
22024
22025        set_option("mode.sim_interactive", true).unwrap();
22026        assert_eq!(
22027            get_option("mode.sim_interactive").unwrap().as_bool(),
22028            Some(true)
22029        );
22030
22031        set_option("mode.chained_assignment", "raise").unwrap();
22032        assert_eq!(
22033            get_option("mode.chained_assignment").unwrap().as_str(),
22034            Some("raise")
22035        );
22036
22037        // 3. OptionError handling
22038        assert!(matches!(
22039            get_option("nonexistent.option"),
22040            Err(OptionError::NotFound { .. })
22041        ));
22042        assert!(matches!(
22043            get_option("display"),
22044            Err(OptionError::Ambiguous { .. })
22045        ));
22046
22047        // 4. describe_option
22048        let desc = describe_option(Some("max_rows")).unwrap();
22049        assert!(desc.contains("display.max_rows : [currently: 100]"));
22050
22051        let desc_all = describe_option(None).unwrap();
22052        assert!(desc_all.contains("display.width"));
22053        assert!(desc_all.contains("compute.use_bottleneck"));
22054
22055        // 5. Scoped option_context
22056        {
22057            let _guard = option_context(&[
22058                ("display.max_rows", OptionValue::Int(999)),
22059                ("display.precision", OptionValue::Int(2)),
22060            ])
22061            .unwrap();
22062
22063            assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(999));
22064            assert_eq!(get_option("display.precision").unwrap().as_int(), Some(2));
22065        }
22066        // Restored after guard drop
22067        assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(100));
22068        assert_eq!(get_option("display.precision").unwrap().as_int(), Some(6));
22069
22070        // 6. Reset single option and all options
22071        reset_option(Some("display.max_rows")).unwrap();
22072        assert_eq!(get_option("display.max_rows").unwrap().as_int(), Some(60));
22073
22074        reset_option(Some("all")).unwrap();
22075        assert_eq!(
22076            get_option("mode.chained_assignment").unwrap().as_str(),
22077            Some("warn")
22078        );
22079
22080        // 7. Expanded standard options
22081        assert_eq!(
22082            get_option("mode.copy_on_write").unwrap().as_bool(),
22083            Some(false)
22084        );
22085        assert_eq!(
22086            get_option("mode.data_manager").unwrap().as_str(),
22087            Some("block")
22088        );
22089        assert_eq!(
22090            get_option("display.large_repr").unwrap().as_str(),
22091            Some("truncate")
22092        );
22093        assert_eq!(
22094            get_option("display.max_info_columns").unwrap().as_int(),
22095            Some(100)
22096        );
22097        assert_eq!(
22098            get_option("display.memory_usage").unwrap().as_bool(),
22099            Some(true)
22100        );
22101        assert_eq!(
22102            get_option("display.colheader_justify").unwrap().as_str(),
22103            Some("right")
22104        );
22105        assert!(get_option("display.chop_threshold").unwrap().is_none());
22106        assert_eq!(
22107            get_option("io.parquet.engine").unwrap().as_str(),
22108            Some("auto")
22109        );
22110        assert_eq!(
22111            get_option("plotting.backend").unwrap().as_str(),
22112            Some("matplotlib")
22113        );
22114        assert_eq!(
22115            get_option("plotting.matplotlib.register_converters")
22116                .unwrap()
22117                .as_bool(),
22118            Some(true)
22119        );
22120
22121        // From<()> for OptionValue
22122        set_option("display.chop_threshold", ()).unwrap();
22123        assert!(get_option("display.chop_threshold").unwrap().is_none());
22124    }
22125
22126    #[test]
22127    fn test_scalar_typed_accessors() {
22128        use super::{Interval, IntervalClosed, Period, PeriodFreq, Scalar};
22129
22130        let s_i64 = Scalar::Int64(42);
22131        assert_eq!(s_i64.as_i64(), Some(42));
22132        assert_eq!(s_i64.as_int(), Some(42));
22133        assert_eq!(s_i64.as_f64(), None);
22134        assert_eq!(s_i64.as_float(), None);
22135        assert_eq!(s_i64.as_bool(), None);
22136        assert_eq!(s_i64.as_str(), None);
22137
22138        let s_f64 = Scalar::Float64(2.75);
22139        assert_eq!(s_f64.as_f64(), Some(2.75));
22140        assert_eq!(s_f64.as_float(), Some(2.75));
22141        assert_eq!(s_f64.as_i64(), None);
22142        assert_eq!(s_f64.as_int(), None);
22143
22144        let s_bool = Scalar::Bool(true);
22145        assert_eq!(s_bool.as_bool(), Some(true));
22146        assert_eq!(s_bool.as_int(), None);
22147
22148        let s_str = Scalar::Utf8("pandas".to_string());
22149        assert_eq!(s_str.as_str(), Some("pandas"));
22150        assert_eq!(s_str.as_bool(), None);
22151
22152        let s_dt = Scalar::Datetime64(1_000_000_000);
22153        assert_eq!(s_dt.as_datetime_nanos(), Some(1_000_000_000));
22154        assert_eq!(s_dt.as_str(), None);
22155
22156        let s_td = Scalar::Timedelta64(500_000);
22157        assert_eq!(s_td.as_timedelta_nanos(), Some(500_000));
22158        assert_eq!(s_td.as_int(), None);
22159
22160        let s_per = Scalar::Period(Period::new(2024, PeriodFreq::Daily));
22161        assert_eq!(s_per.as_period_ordinal(), Some(2024));
22162
22163        let s_iv = Scalar::Interval(Interval::new(0.0, 10.0, IntervalClosed::Both));
22164        assert_eq!(
22165            s_iv.as_interval(),
22166            Some(Interval::new(0.0, 10.0, IntervalClosed::Both))
22167        );
22168    }
22169
22170    #[test]
22171    fn test_api_submodules_and_types_inspectors() {
22172        use super::{
22173            DType, Scalar,
22174            api::{extensions, indexers, types},
22175        };
22176
22177        // api::types scalar inspectors
22178        assert!(types::is_number(&Scalar::Int64(42)));
22179        assert!(types::is_number(&Scalar::Float64(42.5)));
22180        assert!(types::is_number(&Scalar::Bool(true)));
22181        assert!(!types::is_number(&Scalar::Utf8("pandas".into())));
22182
22183        assert!(types::is_bool(&Scalar::Bool(false)));
22184        assert!(!types::is_bool(&Scalar::Int64(0)));
22185
22186        assert!(types::is_integer(&Scalar::Int64(10)));
22187        assert!(!types::is_integer(&Scalar::Float64(10.0)));
22188
22189        assert!(types::is_float(&Scalar::Float64(10.0)));
22190        assert!(!types::is_float(&Scalar::Int64(10)));
22191
22192        // api::types dtype inspectors
22193        assert!(types::is_float64_dtype(&DType::Float64));
22194        assert!(types::is_float64_dtype(&DType::Float64Nullable));
22195        assert!(!types::is_float64_dtype(&DType::Int64));
22196        assert!(!types::is_int32_dtype(&DType::Int64));
22197
22198        // api::extensions compatibility hooks
22199        extensions::register_dataframe_accessor("geo");
22200        extensions::register_series_accessor("geo");
22201        extensions::register_index_accessor("geo");
22202
22203        // api::indexers
22204        let base = indexers::BaseIndexer::new(5, 1);
22205        assert_eq!(base.window_size, 5);
22206        assert_eq!(base.step, 1);
22207
22208        let fwd = indexers::FixedForwardWindowIndexer::new(3);
22209        assert_eq!(fwd.window_size, 3);
22210
22211        let var = indexers::VariableOffsetWindowIndexer::new(100);
22212        assert_eq!(var.index_offset, 100);
22213    }
22214
22215    #[test]
22216    fn test_extension_dtypes_and_parameterized_parsing() {
22217        use super::{
22218            AsDType, CategoricalDtype, DType, IntervalClosed, IntervalDtype, PeriodDtype, Scalar,
22219            SparseDType, api::types, pandas_dtype,
22220        };
22221
22222        // CategoricalDtype
22223        let cat_default = CategoricalDtype::default();
22224        assert_eq!(cat_default.name(), "category");
22225        assert_eq!(cat_default.kind(), "O");
22226        assert!(!cat_default.ordered());
22227        assert_eq!(cat_default.categories(), None);
22228        assert_eq!(cat_default.as_dtype(), DType::Categorical);
22229        assert!(types::is_categorical_dtype(&cat_default));
22230        assert_eq!(
22231            cat_default.to_string(),
22232            "CategoricalDtype(categories=None, ordered=False)"
22233        );
22234
22235        let cat_custom =
22236            CategoricalDtype::new(Some(vec!["low".to_string(), "high".to_string()]), true);
22237        assert!(cat_custom.ordered());
22238        assert_eq!(
22239            cat_custom.categories(),
22240            Some(&["low".to_string(), "high".to_string()][..])
22241        );
22242        assert!(cat_custom.to_string().contains("ordered=True"));
22243
22244        // PeriodDtype
22245        let per_default = PeriodDtype::default();
22246        assert_eq!(per_default.freq(), "D");
22247        assert_eq!(per_default.name(), "period[D]");
22248        assert_eq!(per_default.kind(), "O");
22249        assert_eq!(per_default.as_dtype(), DType::Period);
22250        assert!(types::is_period_dtype(&per_default));
22251        assert_eq!(per_default.to_string(), "period[D]");
22252
22253        let per_custom = PeriodDtype::new("M");
22254        assert_eq!(per_custom.freq(), "M");
22255        assert_eq!(per_custom.to_string(), "period[M]");
22256
22257        // IntervalDtype
22258        let int_default = IntervalDtype::default();
22259        assert_eq!(*int_default.subtype(), DType::Float64);
22260        assert_eq!(int_default.closed(), Some(IntervalClosed::Right));
22261        assert_eq!(int_default.name(), "interval");
22262        assert_eq!(int_default.kind(), "O");
22263        assert_eq!(int_default.as_dtype(), DType::Interval);
22264        assert!(types::is_interval_dtype(&int_default));
22265        assert_eq!(int_default.to_string(), "interval[float64, right]");
22266
22267        let int_custom = IntervalDtype::new(DType::Int64, Some(IntervalClosed::Both));
22268        assert_eq!(*int_custom.subtype(), DType::Int64);
22269        assert_eq!(int_custom.closed(), Some(IntervalClosed::Both));
22270        assert_eq!(int_custom.to_string(), "interval[int64, both]");
22271
22272        // SparseDType AsDType
22273        let sp = SparseDType::new(DType::Float64, Scalar::Float64(0.0)).unwrap();
22274        assert_eq!(sp.as_dtype(), DType::Sparse);
22275        assert!(types::is_sparse(&sp));
22276
22277        // Parameterized pandas_dtype parsing
22278        assert_eq!(pandas_dtype("period[D]").unwrap(), DType::Period);
22279        assert_eq!(pandas_dtype("Period[M]").unwrap(), DType::Period);
22280        assert_eq!(pandas_dtype("interval[float64]").unwrap(), DType::Interval);
22281        assert_eq!(pandas_dtype("Interval[int64]").unwrap(), DType::Interval);
22282        assert_eq!(pandas_dtype("sparse[float64]").unwrap(), DType::Sparse);
22283        assert_eq!(pandas_dtype("Sparse[int64, 0]").unwrap(), DType::Sparse);
22284    }
22285}
22286
22287/// `NumericWidth` / `NumpyNumeric` — numpy's narrow numeric dtypes and their
22288/// promotion (fvsao.23). Expected values are live pandas 2.2.3 / numpy 2.4.6.
22289#[cfg(test)]
22290mod numeric_width_fvsao23 {
22291    use super::{DType, NumericWidth, NumpyNumeric, numpy_pairwise_sum};
22292
22293    #[test]
22294    fn float32_sum_is_numpys_pairwise_sum_bit_for_bit() {
22295        // numpy 2.4.6: a = ((arange(n) * 37) % 1000).astype(float32) *
22296        // float32(0.013); a.sum().view(uint32). Lengths 5 and 64 are ones
22297        // where a float64 sum rounded once gives another float32 (NEGATIVE).
22298        let cases: [(usize, u32); 5] = [
22299            (5, 1_083_829_126),
22300            (64, 1_136_679_190),
22301            (129, 1_145_981_108),
22302            (1000, 1_170_926_592),
22303            (4097, 1_188_011_795),
22304        ];
22305        for (n, bits) in cases {
22306            #[allow(clippy::cast_precision_loss)] // below 1000
22307            let values: Vec<f32> = (0..n)
22308                .map(|k| ((k * 37) % 1000) as f32 * 0.013_f32)
22309                .collect();
22310            assert_eq!(numpy_pairwise_sum(&values).to_bits(), bits, "n={n}");
22311            if n < 100 {
22312                #[allow(clippy::cast_possible_truncation)]
22313                let rounded_once = values.iter().map(|&v| f64::from(v)).sum::<f64>() as f32;
22314                assert_ne!(rounded_once.to_bits(), bits, "n={n}");
22315            }
22316        }
22317        assert_eq!(numpy_pairwise_sum::<f32>(&[]), 0.0);
22318    }
22319
22320    #[test]
22321    fn names_parse_and_round_trip() {
22322        for width in NumericWidth::ALL {
22323            for nullable in [false, true] {
22324                assert_eq!(
22325                    NumericWidth::parse(width.name(nullable)),
22326                    Some((width, nullable))
22327                );
22328            }
22329        }
22330        for (name, expected) in [
22331            ("<i4", (NumericWidth::Int32, false)),
22332            ("f4", (NumericWidth::Float32, false)),
22333            ("UInt8Dtype", (NumericWidth::UInt8, true)),
22334        ] {
22335            assert_eq!(NumericWidth::parse(name), Some(expected), "{name}");
22336        }
22337        // The 64-bit names are DType's, not a width: 'i8' is numpy's int64.
22338        for name in ["int64", "Int64", "float64", "i8", "f8", "int", "float"] {
22339            assert_eq!(NumericWidth::parse(name), None, "{name}");
22340        }
22341    }
22342
22343    #[test]
22344    fn wrapping_is_numpys_modular_cast_not_saturation() {
22345        // pd.Series([1, 2, 300, -5]).astype('int8') -> [1, 2, 44, -5]
22346        assert_eq!(NumericWidth::Int8.wrap_int(300), Some(44));
22347        // .astype('uint8') -> [1, 2, 44, 251]; uint16 -5 -> 65531
22348        assert_eq!(NumericWidth::UInt8.wrap_int(-5), Some(251));
22349        assert_eq!(NumericWidth::UInt16.wrap_int(-5), Some(65531));
22350        assert_eq!(NumericWidth::UInt32.wrap_int(-5), Some(4_294_967_291));
22351        // int8 100 + 100 -> -56; 100 * 2 -> -56
22352        assert_eq!(NumericWidth::Int8.wrap_int(200), Some(-56));
22353        assert_eq!(
22354            NumericWidth::Int32.wrap_int(i64::from(i32::MAX) + 1),
22355            Some(i64::from(i32::MIN))
22356        );
22357        // A wrapped i64 product reduces to the width's product.
22358        let product = 50_000_i64.wrapping_pow(5);
22359        assert_eq!(
22360            NumericWidth::Int32.wrap_int(product),
22361            Some(i64::from(50_000_i32.wrapping_pow(5)))
22362        );
22363        // uint64 at or above 2**63 is refused, never stored negative.
22364        assert_eq!(NumericWidth::UInt64.wrap_int(-1), None);
22365        assert_eq!(NumericWidth::UInt64.wrap_int(7), Some(7));
22366        assert_eq!(NumericWidth::Float32.wrap_int(1), None);
22367        assert!(NumericWidth::Int8.holds_int(-128) && !NumericWidth::Int8.holds_int(128));
22368    }
22369
22370    #[test]
22371    fn float32_rounding_is_to_nearest_not_truncation() {
22372        // np.float32(0.1) as float64 -> 0.10000000149011612
22373        assert_eq!(NumericWidth::round_f32(0.1), 0.100_000_001_490_116_12);
22374        // float32 0.1 + 0.2 -> 0.30000001192092896 (not float64's
22375        // 0.30000000000000004)
22376        let sum =
22377            NumericWidth::round_f32(NumericWidth::round_f32(0.1) + NumericWidth::round_f32(0.2));
22378        assert_eq!(sum, 0.300_000_011_920_928_96);
22379        // 1 + 2**-24 is a tie between 1 and 1 + 2**-23: ties to even -> 1.
22380        // 1 + 3 * 2**-25 is above the tie: rounds up, where truncation stays 1.
22381        assert_eq!(NumericWidth::round_f32(1.0 + 2f64.powi(-24)), 1.0);
22382        let above_tie = 1.0 + 3.0 * 2f64.powi(-25);
22383        assert_eq!(NumericWidth::round_f32(above_tie), 1.0 + 2f64.powi(-23));
22384        assert!(NumericWidth::round_f32(f64::NAN).is_nan());
22385        assert_eq!(NumericWidth::round_f32(1e300), f64::INFINITY);
22386    }
22387
22388    #[test]
22389    fn result_type_matches_numpy_promotion() {
22390        use NumpyNumeric::{Bool, Float, Int, UInt};
22391        let cases = [
22392            (Int(32), Int(64), Int(64)), // int32 + int64 -> int64
22393            (Int(8), UInt(8), Int(16)),  // int8 + uint8 -> int16
22394            (Int(16), UInt(8), Int(16)),
22395            (Int(8), UInt(16), Int(32)),
22396            (Int(32), UInt(32), Int(64)),
22397            (Int(64), UInt(64), Float(64)), // no integer holds both
22398            (UInt(8), UInt(32), UInt(32)),
22399            (Float(32), Int(8), Float(32)), // float32 * int8 -> float32
22400            (Float(32), UInt(16), Float(32)),
22401            (Float(32), Int(32), Float(64)), // float32 * int32 -> float64
22402            (Float(32), Float(64), Float(64)),
22403            (Bool, Int(8), Int(8)),
22404            (Bool, Float(32), Float(32)),
22405        ];
22406        for (a, b, expected) in cases {
22407            assert_eq!(a.result_type(b), expected, "{a:?} {b:?}");
22408            assert_eq!(b.result_type(a), expected, "{b:?} {a:?}");
22409        }
22410        // NEP 50: int32 + 1 -> int32; int32 + 0.5 -> float64;
22411        // float32 + 0.2 -> float32
22412        assert_eq!(Int(32).with_python_int(), Int(32));
22413        assert_eq!(Int(32).with_python_float(), Float(64));
22414        assert_eq!(Float(32).with_python_float(), Float(32));
22415        assert_eq!(Bool.with_python_int(), Int(64));
22416    }
22417
22418    #[test]
22419    fn columns_map_to_numpy_dtypes() {
22420        let cases = [
22421            (DType::Int64, None, Some(NumpyNumeric::Int(64))),
22422            (
22423                DType::Int64Nullable,
22424                Some(NumericWidth::UInt8),
22425                Some(NumpyNumeric::UInt(8)),
22426            ),
22427            (
22428                DType::Float64,
22429                Some(NumericWidth::Float32),
22430                Some(NumpyNumeric::Float(32)),
22431            ),
22432            // A width its storage cannot carry is not a numpy dtype.
22433            (DType::Float64, Some(NumericWidth::Int8), None),
22434            (DType::Utf8, None, None),
22435        ];
22436        for (dtype, width, expected) in cases {
22437            assert_eq!(NumpyNumeric::of(&dtype, width), expected, "{dtype:?}");
22438        }
22439        for width in NumericWidth::ALL {
22440            assert_eq!(NumpyNumeric::of_width(width).width(), Some(width));
22441            assert!(width.fits_storage(&width.storage(false)));
22442            assert!(width.fits_storage(&width.storage(true)));
22443        }
22444        assert_eq!(NumpyNumeric::Int(64).width(), None);
22445    }
22446
22447    #[test]
22448    fn downcast_and_category_code_widths() {
22449        // to_numeric([1, 2], downcast='integer') -> int8; [1, 300] signed ->
22450        // int16, unsigned -> uint16
22451        let int32_max_plus_one = i64::from(i32::MAX) + 1;
22452        let signed = [
22453            ((1, 2), Some(NumericWidth::Int8)),
22454            ((1, 300), Some(NumericWidth::Int16)),
22455            ((0, int32_max_plus_one), None),
22456        ];
22457        for ((low, high), expected) in signed {
22458            assert_eq!(NumericWidth::smallest_signed(low, high), expected);
22459        }
22460        let unsigned = [((1, 300), Some(NumericWidth::UInt16)), ((-1, 3), None)];
22461        for ((low, high), expected) in unsigned {
22462            assert_eq!(NumericWidth::smallest_unsigned(low, high), expected);
22463        }
22464        // cat.codes: 2 categories int8, 200 int16; 126 int8, 127 int16
22465        for (categories, expected) in [
22466            (2, NumericWidth::Int8),
22467            (126, NumericWidth::Int8),
22468            (127, NumericWidth::Int16),
22469            (200, NumericWidth::Int16),
22470        ] {
22471            assert_eq!(NumericWidth::for_category_codes(categories), Some(expected));
22472        }
22473        assert_eq!(NumericWidth::itemsize(NumericWidth::Int8), 1);
22474        assert_eq!(NumericWidth::Float32.itemsize(), 4);
22475    }
22476}
22477
22478/// `PandasReductions` against live pandas 2.2.3 / numpy 2.3.5: the bits of
22479/// `Series(...).sum() / mean() / var() / std() / sem() / skew() / kurt()`
22480/// over data both sides build with the same integer arithmetic and one
22481/// division (br-frankenpandas-9iim6).
22482#[cfg(test)]
22483mod pandas_reductions_9iim6 {
22484    use super::{MissingLayout, PandasReductions, ReductionValues};
22485
22486    /// `((k * 7919 + 13) % 100003) / 7.0 - 7000.0`, times 1e6 where
22487    /// `k % 5 == 0`; missing where `k % 11 == 3`.
22488    #[allow(clippy::cast_precision_loss)] // below 100003
22489    fn floats(n: usize) -> (Vec<f64>, Vec<u64>) {
22490        let mut present = vec![0_u64; n.div_ceil(64)];
22491        let values = (0..n)
22492            .map(|k| {
22493                if k % 11 != 3 {
22494                    present[k / 64] |= 1 << (k % 64);
22495                }
22496                let base = ((k * 7919 + 13) % 100_003) as f64 / 7.0 - 7000.0;
22497                if k % 5 == 0 { base * 1e6 } else { base }
22498            })
22499            .collect();
22500        (values, present)
22501    }
22502
22503    /// `(k * 7919 + 13) % 100003 * 3_000_000_007`.
22504    fn ints(n: usize) -> Vec<i64> {
22505        (0..n)
22506            .map(|k| i64::try_from((k * 7919 + 13) % 100_003).unwrap() * 3_000_000_007)
22507            .collect()
22508    }
22509
22510    fn assert_bits(got: &[f64], expected: &[u64], case: &str) {
22511        let got: Vec<u64> = got.iter().map(|value| value.to_bits()).collect();
22512        assert_eq!(got, expected, "{case}");
22513    }
22514
22515    #[test]
22516    fn numpy_float64_with_nan_matches_pandas_bits() {
22517        // pandas: s = Series(floats(n)) with NaN at the missing slots.
22518        let cases: [(usize, [u64; 7]); 7] = [
22519            (
22520                7,
22521                [
22522                    0xc1ff_1185_2dcb_6db6,
22523                    0xc1d4_b658_c932_4924,
22524                    0x43db_301d_4a8d_87a3,
22525                    0x41e4_db58_e2f1_458e,
22526                    0x41d1_078f_09d3_9c5c,
22527                    0xc002_1f47_ceae_1b43,
22528                    0x4014_c8bc_93df_56e6,
22529                ],
22530            ),
22531            (
22532                8,
22533                [
22534                    0xc1ff_1184_f43d_b6da,
22535                    0xc1d1_c0de_426c_687d,
22536                    0x43d7_9d3c_ecd2_da2b,
22537                    0x41e3_7012_7d6c_71a5,
22538                    0x41cd_631d_3379_9929,
22539                    0xc003_b196_82f9_28dc,
22540                    0x4018_9de2_eba9_5ecc,
22541                ],
22542            ),
22543            (
22544                127,
22545                [
22546                    0x4200_324e_3389_2490,
22547                    0x4192_0704_ad1e_360d,
22548                    0x43c9_4a6b_3390_577d,
22549                    0x41dc_72bf_d6fa_9808,
22550                    0x41a5_38f5_8417_ae1e,
22551                    0x3fd0_b6bf_045c_e4d5,
22552                    0x4017_1585_bf13_21c4,
22553                ],
22554            ),
22555            (
22556                128,
22557                [
22558                    0x4200_324d_7236_db6e,
22559                    0x4191_df3a_f99d_a2ae,
22560                    0x43c9_1234_ffb7_4a93,
22561                    0x41dc_5310_c97c_292c,
22562                    0x41a5_09f4_cfcf_9206,
22563                    0x3fd0_d9df_0d68_00b0,
22564                    0x4017_61b6_5653_ae82,
22565                ],
22566            ),
22567            (
22568                129,
22569                [
22570                    0x4200_324c_d43e_db71,
22571                    0x4191_b81f_8a1d_61da,
22572                    0x43c8_daf6_85d3_386f,
22573                    0x41dc_33ca_af49_8c24,
22574                    0x41a4_dbc2_8609_a567,
22575                    0x3fd0_fcc5_39d9_6901,
22576                    0x4017_ade4_7855_7c25,
22577                ],
22578            ),
22579            (
22580                1000,
22581                [
22582                    0x421a_d4f6_8061_248e,
22583                    0x417e_39f9_3e1a_a248,
22584                    0x43c7_9481_cba1_263b,
22585                    0x41db_7825_28c0_37cc,
22586                    0x418d_27ba_a0ea_2f9a,
22587                    0x3fc8_e53a_e277_3d7f,
22588                    0x4018_3c97_3603_dfd0,
22589                ],
22590            ),
22591            (
22592                100_000,
22593                [
22594                    0x4283_088c_316e_46dc,
22595                    0x417b_7135_0c27_1185,
22596                    0x43c7_a0de_3b8e_ea34,
22597                    0x41db_7f57_6673_8d6b,
22598                    0x4157_58cc_33fd_4ae6,
22599                    0x3fc7_f1cf_b14a_14c8,
22600                    0x4018_06b5_f26a_c384,
22601                ],
22602            ),
22603        ];
22604        let all = |r: &PandasReductions<'_>| {
22605            [
22606                r.sum(),
22607                r.mean(),
22608                r.var(1),
22609                r.std(1),
22610                r.sem(1),
22611                r.skew(),
22612                r.kurt(),
22613            ]
22614        };
22615        for (n, expected) in cases {
22616            let (values, present) = floats(n);
22617            let r = PandasReductions::new(
22618                ReductionValues::Float(&values),
22619                Some(&present),
22620                MissingLayout::Numpy,
22621            );
22622            assert_bits(&all(&r), &expected, &format!("float64 n={n}"));
22623            // The same column holding NaN in its missing slots, whole and as
22624            // a concat's chunks.
22625            let with_nan: Vec<f64> = values
22626                .iter()
22627                .enumerate()
22628                .map(|(k, &value)| if k % 11 == 3 { f64::NAN } else { value })
22629                .collect();
22630            let r = PandasReductions::numpy_nan_missing(ReductionValues::Float(&with_nan));
22631            assert_bits(&all(&r), &expected, &format!("float64 NaN n={n}"));
22632            let (head, tail) = with_nan.split_at(n / 3);
22633            let chunks = [head, tail];
22634            let r = PandasReductions::numpy_nan_missing(ReductionValues::FloatChunks(&chunks));
22635            assert_bits(&all(&r), &expected, &format!("float64 NaN chunks n={n}"));
22636        }
22637        // NEGATIVE: the present values added left to right are not pandas'.
22638        let (values, present) = floats(100_000);
22639        let left_fold: f64 = values
22640            .iter()
22641            .enumerate()
22642            .filter(|&(k, _)| present[k / 64] >> (k % 64) & 1 == 1)
22643            .map(|(_, value)| value)
22644            .sum();
22645        assert_ne!(left_fold.to_bits(), 0x4283_088c_316e_46dc);
22646    }
22647
22648    #[test]
22649    fn numpy_int64_mean_sums_through_the_cast_buffer() {
22650        // pandas: Series(ints(n)) (int64): mean, var, sem, skew, kurt.
22651        let cases: [(usize, [u64; 5]); 3] = [
22652            (
22653                129,
22654                [
22655                    0x42e0_dda2_9987_3f9e,
22656                    0x45b9_0e2a_887d_aeda,
22657                    0x429c_34a1_c273_372f,
22658                    0x3f95_9e9d_c69e_ec88,
22659                    0xbff3_844b_ba13_eac1,
22660                ],
22661            ),
22662            (
22663                8193,
22664                [
22665                    0x42e1_0d5b_e407_5aa7,
22666                    0x45b8_3bf5_04f5_f2fc,
22667                    0x426b_d893_c5c9_85b1,
22668                    0x3f42_7452_ff15_86c7,
22669                    0xbff3_318c_611b_b59c,
22670                ],
22671            ),
22672            (
22673                20_000,
22674                [
22675                    0x42e1_0d17_ebf8_272d,
22676                    0x45b8_3c24_c921_82b6,
22677                    0x4261_d2a2_f139_68e2,
22678                    0x3f31_a21c_d4bb_ff52,
22679                    0xbff3_328c_4edc_26ee,
22680                ],
22681            ),
22682        ];
22683        for (n, expected) in cases {
22684            let values = ints(n);
22685            let r =
22686                PandasReductions::new(ReductionValues::Int(&values), None, MissingLayout::Numpy);
22687            let got = [r.mean(), r.var(1), r.sem(1), r.skew(), r.kurt()];
22688            assert_bits(&got, &expected, &format!("int64 n={n}"));
22689            // The same values read as chunks give the same bits.
22690            let (head, tail) = values.split_at(n / 3);
22691            let (middle, rest) = tail.split_at(1);
22692            let chunks = [head, middle, &[][..], rest];
22693            let chunked = PandasReductions::new(
22694                ReductionValues::IntChunks(&chunks),
22695                None,
22696                MissingLayout::Numpy,
22697            );
22698            let got = [
22699                chunked.mean(),
22700                chunked.var(1),
22701                chunked.sem(1),
22702                chunked.skew(),
22703                chunked.kurt(),
22704            ];
22705            assert_bits(&got, &expected, &format!("int64 chunks n={n}"));
22706        }
22707    }
22708
22709    #[test]
22710    fn masked_columns_add_runs_of_present_values() {
22711        // pandas: Series(pd.array(floats(n), dtype="Float64")) with NA at the
22712        // missing slots: sum, mean, var, sem. sum / mean differ from the
22713        // float64 column's above (n = 129: ...6e against ...71) - the runs.
22714        let cases: [(usize, [u64; 4]); 3] = [
22715            (
22716                129,
22717                [
22718                    0x4200_324c_d43e_db6e,
22719                    0x4191_b81f_8a1d_61d6,
22720                    0x43c8_daf6_85d3_3872,
22721                    0x41a4_dbc2_8609_a567,
22722                ],
22723            ),
22724            (
22725                1000,
22726                [
22727                    0x421a_d4f6_8061_2492,
22728                    0x417e_39f9_3e1a_a24c,
22729                    0x43c7_9481_cba1_263a,
22730                    0x418d_27ba_a0ea_2f9a,
22731                ],
22732            ),
22733            (
22734                100_000,
22735                [
22736                    0x4283_088c_316e_46de,
22737                    0x417b_7135_0c27_1188,
22738                    0x43c7_a0de_3b8e_ea37,
22739                    0x4157_58cc_33fd_4ae6,
22740                ],
22741            ),
22742        ];
22743        for (n, expected) in cases {
22744            let (values, present) = floats(n);
22745            let r = PandasReductions::new(
22746                ReductionValues::Float(&values),
22747                Some(&present),
22748                MissingLayout::Masked,
22749            );
22750            assert_bits(
22751                &[r.sum(), r.mean(), r.var(1), r.sem(1)],
22752                &expected,
22753                &format!("Float64 n={n}"),
22754            );
22755            let (head, tail) = values.split_at(n / 2 + 1);
22756            let chunks = [head, tail];
22757            let chunked = PandasReductions::new(
22758                ReductionValues::FloatChunks(&chunks),
22759                Some(&present),
22760                MissingLayout::Masked,
22761            );
22762            let got = [
22763                chunked.sum(),
22764                chunked.mean(),
22765                chunked.var(1),
22766                chunked.sem(1),
22767            ];
22768            assert_bits(&got, &expected, &format!("Float64 chunks n={n}"));
22769        }
22770        // pandas: pd.array(ints(n), dtype="Int64") with NA where k % 997 == 5:
22771        // mean and var, the runs summed within numpy's 8192-value buffers.
22772        for (n, expected) in [
22773            (8193, [0x42e1_0f35_29c2_807b_u64, 0x45b8_39ed_8746_bdcc]),
22774            (20_000, [0x42e1_0cf2_cc56_752a, 0x45b8_3c63_72fc_fad5]),
22775        ] {
22776            let values = ints(n);
22777            let mut present = vec![0_u64; n.div_ceil(64)];
22778            for k in (0..n).filter(|k| k % 997 != 5) {
22779                present[k / 64] |= 1 << (k % 64);
22780            }
22781            let r = PandasReductions::new(
22782                ReductionValues::Int(&values),
22783                Some(&present),
22784                MissingLayout::Masked,
22785            );
22786            assert_bits(&[r.mean(), r.var(1)], &expected, &format!("Int64 n={n}"));
22787        }
22788    }
22789
22790    #[test]
22791    fn edge_cases_match_pandas() {
22792        let reductions = |values: &[f64], present: Option<&[u64]>| {
22793            let r = PandasReductions::new(
22794                ReductionValues::Float(values),
22795                present,
22796                MissingLayout::Numpy,
22797            );
22798            [r.sum(), r.mean(), r.var(1), r.sem(1), r.skew(), r.kurt()]
22799        };
22800        // pandas: [1.5] * 10 -> 15.0 1.5 0.0 0.0 0.0 0.0 (a constant's kurt
22801        // is 0, not 0 minus the bias term); [2.0] * 3 kurt NaN.
22802        let constant = reductions(&[1.5; 10], None);
22803        assert_eq!(constant, [15.0, 1.5, 0.0, 0.0, 0.0, 0.0]);
22804        assert!(reductions(&[2.0; 3], None)[5].is_nan());
22805        // [1, 2] skew NaN; [1, 2, 4] skew 0.9352195295828237.
22806        assert!(reductions(&[1.0, 2.0], None)[4].is_nan());
22807        assert_eq!(
22808            reductions(&[1.0, 2.0, 4.0], None)[4],
22809            0.935_219_529_582_823_7
22810        );
22811        // Empty / all missing: sum 0.0, the rest NaN.
22812        let empty = reductions(&[], None);
22813        assert_eq!(empty[0], 0.0);
22814        assert!(empty[1..].iter().all(|value| value.is_nan()));
22815        let all_missing = reductions(&[3.0; 5], Some(&[0]));
22816        assert_eq!(all_missing[0], 0.0);
22817        assert!(all_missing[1].is_nan());
22818        // -0.0 * 10 sums to 0.0 (numpy adds onto the identity 0.0).
22819        assert_eq!(
22820            reductions(&[-0.0; 10], None)[0].to_bits(),
22821            0.0_f64.to_bits()
22822        );
22823        // An inf: sum / mean inf, the spread NaN.
22824        let inf = reductions(&[1.0, f64::INFINITY, 2.0, 5.0], None);
22825        assert_eq!(inf[0], f64::INFINITY);
22826        assert!(inf[2..].iter().all(|value| value.is_nan()));
22827    }
22828}
22829
22830/// pandas' default text-to-float64 conversion against live pandas 2.2.3
22831/// bits: `read_csv(StringIO('x\n' + token), dtype={'x': 'float64'})`
22832/// (br-frankenpandas-py3c0).
22833#[cfg(test)]
22834mod pandas_decimal_py3c0 {
22835    use super::{PandasDecimal, pandas_decimal_to_f64, pandas_int_to_f64};
22836
22837    fn bits(token: &str) -> u64 {
22838        match pandas_decimal_to_f64(token.as_bytes()) {
22839            PandasDecimal::Value(value) => value.to_bits(),
22840            other => panic!("{token:?}: {other:?}"),
22841        }
22842    }
22843
22844    #[test]
22845    fn tokens_convert_to_pandas_bits() {
22846        let cases = [
22847            ("9.890295358649789", 0x4023_c7d4_cb12_5ce4),
22848            ("0.8690736625851781286570704999", 0x3feb_cf73_91d3_c8f1),
22849            ("0.000000068288360759838675650889", 0x3e72_54bd_8bcd_610b),
22850            ("-0.0080749473608410608782560", 0xbf80_8999_16a7_63f3),
22851            ("99999999999999999", 0x4376_3457_85d8_a001),
22852            ("1234567890123456789012345", 0x44f0_56e0_f36a_6444),
22853            // 17 leading zeros are the 17 digits kept.
22854            ("00000000000000000.5", 0x0000_0000_0000_0000),
22855            ("-00000000000000000.5", 0x8000_0000_0000_0000),
22856            ("1.5E+10", 0x420b_f08e_b000_0000),
22857            ("-.5e-3", 0xbf40_624d_d2f1_a9fc),
22858            ("5.", 0x4014_0000_0000_0000),
22859            ("1e-320", 0x0000_0000_0000_07e8),
22860            ("2.5e-310", 0x0000_2e05_5c9a_3f6c),
22861            ("-1e-400", 0x8000_0000_0000_0000),
22862            // Below 1e-616: +0.0, the sign dropped.
22863            ("-1e-700", 0x0000_0000_0000_0000),
22864            // The exponent wraps as a 32-bit integer.
22865            ("1e-4294967296", 0x3ff0_0000_0000_0000),
22866            ("1.7976931348623157e308", 0x7fef_ffff_ffff_ffff),
22867            ("0.001e310", 0x7fac_7b1f_3cac_7433),
22868        ];
22869        for (token, expected) in cases {
22870            assert_eq!(bits(token), expected, "{token:?}");
22871        }
22872        // NEGATIVE: the correctly rounded value is not pandas'.
22873        let correctly_rounded: f64 = "9.890295358649789".parse().unwrap();
22874        assert_ne!(correctly_rounded.to_bits(), 0x4023_c7d4_cb12_5ce4);
22875    }
22876
22877    #[test]
22878    fn what_pandas_does_not_read_as_a_float() {
22879        for token in [
22880            "1e309",
22881            "0e400",
22882            "1.8e308",
22883            "1e+0000000000000000001",
22884            "1e-2147483649",
22885            "1e",
22886            "1e+",
22887            "1.5d3",
22888            "0x10",
22889            "1_000.5",
22890            "1..5",
22891        ] {
22892            assert_eq!(
22893                pandas_decimal_to_f64(token.as_bytes()),
22894                PandasDecimal::Rejected,
22895                "{token:?}"
22896            );
22897        }
22898        for token in ["inf", "-Infinity", "nan", ".", "-", "e5", "+.e1", "--1", ""] {
22899            assert_eq!(
22900                pandas_decimal_to_f64(token.as_bytes()),
22901                PandasDecimal::NotDecimal,
22902                "{token:?}"
22903            );
22904        }
22905    }
22906
22907    #[test]
22908    fn an_integer_in_a_float_column_takes_the_same_conversion() {
22909        assert_eq!(pandas_int_to_f64(-42).to_bits(), (-42.0_f64).to_bits());
22910        assert_eq!(
22911            pandas_int_to_f64(99_999_999_999_999_999).to_bits(),
22912            0x4376_3457_85d8_a001
22913        );
22914        assert_eq!(
22915            pandas_int_to_f64(-99_999_999_999_999_999).to_bits(),
22916            0xc376_3457_85d8_a001
22917        );
22918    }
22919}