Skip to main content

fp_conformance/
lib.rs

1#![forbid(unsafe_code)]
2#![warn(rustdoc::broken_intra_doc_links)]
3
4//! Conformance harness for **frankenpandas** — mechanically verifies
5//! that frankenpandas matches pandas behavior across the supported
6//! API surface, by running parallel computations and diffing
7//! results.
8//!
9//! ## Architecture
10//!
11//! Conformance verification uses two complementary modes:
12//!
13//! - **Live oracle**: spawn a Python subprocess running real
14//!   `pandas`, feed it the same inputs as frankenpandas, then
15//!   diff the outputs. Picks up version drift and the "everything
16//!   pandas exposes" surface area without authors having to encode
17//!   each contract by hand.
18//! - **Fixture replay**: load packet fixtures (DataFrame / Series
19//!   inputs + expected outputs captured from a known-good
20//!   reference run) and compare frankenpandas's output to the
21//!   captured expectation. Fast, deterministic, runs in CI without
22//!   needing a Python install.
23//!
24//! [`OracleMode`] selects between the two; the harness falls back
25//! to fixture mode when the live oracle isn't reachable so the
26//! CI build still produces a green/red signal.
27//!
28//! ## Top-level entry points
29//!
30//! - [`HarnessConfig`]: harness setup — fixture-dir paths, oracle
31//!   mode, suite-level options.
32//! - [`run_smoke`]: smoke-test entry point. Runs the
33//!   smallest-possible packet set against both modes and emits a
34//!   [`HarnessReport`].
35//! - [`HarnessReport`]: aggregated suite verdict with per-case
36//!   [`CaseResult`] entries.
37//! - [`SuiteOptions`]: per-suite knobs (parallelism, timeout,
38//!   continue-on-fail vs fail-fast).
39//!
40//! ## Fixture format
41//!
42//! Packet fixtures encode "operation X on inputs Y produces output
43//! Z" in a shape both modes can consume:
44//!
45//! - [`PacketFixture`]: top-level fixture record. Tagged with
46//!   provenance ([`FixtureProvenance`]), references its inputs
47//!   ([`FixtureDataFrame`] / [`FixtureSeries`]), the
48//!   [`FixtureOperation`] to apply, and the expected outputs
49//!   ([`FixtureExpectedDataFrame`] / [`FixtureExpectedSeries`] /
50//!   [`FixtureExpectedAlignment`] / [`FixtureExpectedJoin`]).
51//! - [`FixtureCategoricalColumn`] / [`FixtureMultiIndex`]:
52//!   typed sub-fixtures for the harder-to-encode inputs.
53//! - [`FixtureColumnAssignment`] / [`FixtureColumnRename`]:
54//!   structured operation payloads for the assign / rename
55//!   variants of [`FixtureOperation`].
56//! - [`FixtureJoinType`]: enum tag for join-style operations.
57//! - [`FixtureOracleSource`]: where the expected output came
58//!   from (live oracle capture vs author-curated golden file).
59//!
60//! ## Case verdicts
61//!
62//! Per-case results carry rich diagnostic detail so failures map
63//! cleanly back to the offending input shape:
64//!
65//! - [`CaseResult`]: one operation's verdict.
66//! - [`CaseStatus`]: pass / fail / xfail / skip.
67//! - [`DriftLevel`]: how big the divergence was (within-tolerance,
68//!   numeric drift, structural mismatch).
69//! - [`ComparisonCategory`]: what the diff bucket was (dtype /
70//!   value / index / column-order / metadata).
71//! - [`RequirementLevel`]: MUST / SHOULD / MAY tagging for the
72//!   coverage matrix output (matches the
73//!   testing-conformance-harnesses skill's classification).
74//!
75//! ## Cross-crate relationships
76//!
77//! Built on top of fp-frame, fp-io, fp-join, fp-groupby, fp-expr.
78//! Forwards the `asupersync` cargo feature down to fp-runtime.
79//! Test-only — no production callers should depend on this crate.
80
81use std::{
82    collections::{BTreeMap, BTreeSet, HashMap},
83    fs,
84    io::Write,
85    path::{Path, PathBuf},
86    process::{Command, Stdio},
87    time::{Instant, SystemTime, UNIX_EPOCH},
88};
89
90use fp_columnar::{ArithmeticOp, Column};
91use fp_expr::{eval_str_with_locals, parse_expr, query_str, query_str_with_locals};
92use fp_frame::{
93    ConcatJoin, DataFrame, FrameError, Series, ToNumericErrors, ToNumericOptions,
94    concat_dataframes_with_axis_join, concat_series, cut, qcut, to_numeric_with_options,
95};
96use fp_groupby::{
97    GroupByExecutionOptions, GroupByOptions, groupby_count, groupby_first, groupby_last,
98    groupby_max, groupby_mean, groupby_median, groupby_min, groupby_std, groupby_sum,
99    groupby_sum_with_options, groupby_var,
100};
101use fp_index::{
102    AlignmentPlan, DuplicateKeep, Index, IndexLabel, align_union, format_datetime_ns,
103    validate_alignment_plan,
104};
105use fp_io::{
106    CsvOnBadLines, CsvReadOptions, CsvWriteOptions, ExcelReadOptions, IoError as FpIoError,
107    JsonOrient, SqlReadOptions, read_csv_str, read_csv_with_options, read_excel_bytes,
108    read_feather_bytes, read_ipc_stream_bytes, read_json_str, read_jsonl_str, read_parquet_bytes,
109    read_sql, read_sql_query, read_sql_query_with_options,
110    read_sql_query_with_options_and_index_col, read_sql_table_with_index_col,
111    read_sql_table_with_options_and_index_col, read_sql_with_index_col, read_sql_with_options,
112    series_from_arrow_array, series_to_arrow_array, write_csv_string_with_options,
113    write_excel_bytes, write_feather_bytes, write_ipc_stream_bytes, write_json_string,
114    write_jsonl_string, write_parquet_bytes,
115};
116use fp_join::{
117    JoinExecutionOptions, JoinType, JoinedSeries, MergeExecutionOptions, MergeValidateMode,
118    join_series, join_series_with_options, merge_dataframes, merge_dataframes_on_with_options,
119    merge_ordered,
120};
121#[cfg(feature = "asupersync")]
122use fp_runtime::asupersync::{
123    ArtifactCodec, ArtifactPayload, Fnv1aVerifier, IntegrityVerifier, PassthroughCodec,
124    RuntimeAsupersyncConfig,
125};
126use fp_runtime::{
127    DecisionAction, DecodeProof, EvidenceLedger, MAX_DECODE_PROOFS, RaptorQEnvelope,
128    RaptorQMetadata, RuntimeMode, RuntimePolicy, ScrubStatus,
129};
130use fp_types::{
131    DType, NullKind, Period, PeriodFreq, Scalar, Timedelta, Timestamp, cast_scalar,
132    cast_scalar_owned, common_dtype, dropna, fill_na, nancount, nanmax, nanmean, nanmin, nanstd,
133    nansum, nanvar,
134};
135use raptorq::{Decoder, Encoder, EncodingPacket, ObjectTransmissionInformation};
136use serde::{Deserialize, Serialize};
137use sha2::{Digest, Sha256};
138use thiserror::Error;
139
140mod fuzz;
141
142pub use fuzz::{fuzz_format_cross_round_trip_bytes, fuzz_index_align_bytes};
143
144#[derive(Debug, Clone)]
145pub struct HarnessConfig {
146    pub repo_root: PathBuf,
147    pub oracle_root: PathBuf,
148    pub fixture_root: PathBuf,
149    pub strict_mode: bool,
150    pub python_bin: String,
151    /// Permit the oracle subprocess to import installed system pandas when the
152    /// vendored legacy checkout is unavailable.
153    pub allow_system_pandas_fallback: bool,
154    /// Permit a live-oracle request to use a fixture's stored expectation when
155    /// neither the vendored nor system pandas oracle is available.
156    ///
157    /// This is deliberately independent from
158    /// [`Self::allow_system_pandas_fallback`]: opting into system pandas must
159    /// never turn a differential test into a fixture-vs-FrankenPandas comparison
160    /// (br-frankenpandas-mlnu3).
161    pub allow_fixture_fallback: bool,
162    pub require_live_oracle: bool,
163}
164
165impl HarnessConfig {
166    #[must_use]
167    fn env_flag(name: &str) -> bool {
168        std::env::var(name).ok().is_some_and(|value| {
169            matches!(
170                value.trim().to_ascii_lowercase().as_str(),
171                "1" | "true" | "yes" | "on"
172            )
173        })
174    }
175
176    /// The repository's pinned pandas oracle interpreter, when it has been
177    /// created: `<repo>/.venv-oracle/bin/python`, the venv CI builds from
178    /// `crates/fp-conformance/oracle/requirements.txt` (`pandas==2.2.3`).
179    ///
180    /// br-frankenpandas-00de2: before this, `default_paths` looked only for a
181    /// vendored `legacy_pandas_code/pandas` tree (present on no host) and a
182    /// bare `python3` (no pandas here), so every `live_oracle_*` and
183    /// `conformance_*` test returned early as PASS unless `FP_PYTHON_BIN` and
184    /// `FP_ALLOW_SYSTEM_PANDAS_FALLBACK` were exported by hand — the
185    /// pass-by-skip defect of br-frankenpandas-l7r1p. The pinned venv is the
186    /// same interpreter CI uses, so finding it is a wiring fix, not a policy
187    /// change.
188    #[must_use]
189    pub fn pinned_oracle_interpreter(repo_root: &std::path::Path) -> Option<PathBuf> {
190        let candidate = repo_root.join(".venv-oracle/bin/python");
191        candidate.is_file().then_some(candidate)
192    }
193
194    /// True when `python_bin` IS the pinned oracle interpreter (compared by
195    /// canonical path, because `repo_root` carries a `../..` segment).
196    #[must_use]
197    pub fn uses_pinned_oracle_interpreter(&self) -> bool {
198        let Some(pinned) = Self::pinned_oracle_interpreter(&self.repo_root) else {
199            return false;
200        };
201        let configured = std::path::Path::new(&self.python_bin);
202        match (
203            std::fs::canonicalize(configured),
204            std::fs::canonicalize(&pinned),
205        ) {
206            (Ok(a), Ok(b)) => a == b,
207            _ => configured == pinned,
208        }
209    }
210
211    #[must_use]
212    pub fn default_paths() -> Self {
213        let repo_root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
214        let python_bin = std::env::var("FP_PYTHON_BIN")
215            .ok()
216            .and_then(|value| {
217                let trimmed = value.trim();
218                if trimmed.is_empty() {
219                    None
220                } else {
221                    let path = std::path::Path::new(trimmed);
222                    if path.is_relative() && repo_root.join(path).is_file() {
223                        Some(repo_root.join(path).display().to_string())
224                    } else {
225                        Some(trimmed.to_owned())
226                    }
227                }
228            })
229            .or_else(|| {
230                Self::pinned_oracle_interpreter(&repo_root).map(|path| path.display().to_string())
231            })
232            .unwrap_or_else(|| "python3".to_owned());
233        let allow_system_pandas_fallback = Self::env_flag("FP_ALLOW_SYSTEM_PANDAS_FALLBACK");
234        let allow_fixture_fallback = Self::env_flag("FP_ALLOW_FIXTURE_FALLBACK");
235        let require_live_oracle = Self::env_flag("FP_REQUIRE_LIVE_ORACLE");
236        Self {
237            oracle_root: repo_root.join("legacy_pandas_code/pandas"),
238            fixture_root: PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures"),
239            strict_mode: true,
240            python_bin,
241            allow_system_pandas_fallback,
242            allow_fixture_fallback,
243            require_live_oracle,
244            repo_root,
245        }
246    }
247
248    #[must_use]
249    pub fn packet_fixture_root(&self) -> PathBuf {
250        self.fixture_root.join("packets")
251    }
252
253    #[must_use]
254    pub fn packet_artifact_root(&self, packet_id: &str) -> PathBuf {
255        self.repo_root.join("artifacts/phase2c").join(packet_id)
256    }
257
258    #[must_use]
259    pub fn parity_gate_path(&self, packet_id: &str) -> PathBuf {
260        self.packet_artifact_root(packet_id)
261            .join("parity_gate.yaml")
262    }
263
264    #[must_use]
265    pub fn oracle_script_path(&self) -> PathBuf {
266        self.repo_root
267            .join("crates/fp-conformance/oracle/pandas_oracle.py")
268    }
269
270    #[must_use]
271    pub fn allows_system_pandas_fallback(&self) -> bool {
272        // `require_live_oracle` is DELIBERATELY not probe-gated: when a caller
273        // (CI sets FP_REQUIRE_LIVE_ORACLE=1) demands a live oracle, a missing
274        // pandas must stay a LOUD FAILURE. Softening it here would reintroduce
275        // exactly the pass-by-skip defect br-frankenpandas-l7r1p exists to remove.
276        if self.require_live_oracle {
277            return true;
278        }
279        // An OPT-IN, by contrast, is a preference and not a demand, so it must
280        // answer honestly: "may I fall back to system pandas" is false when there
281        // is no system pandas to fall back to.
282        //
283        // br-frankenpandas-l7r1p: ad3e05d1c opted 161 conformance_* tests into the
284        // system pandas, which is right on a machine that HAS it and wrong on one
285        // that does not. The script-backed helpers (JSONL, to_html, tseries,
286        // groupby.apply) re-raise ModuleNotFoundError, and their callers `.expect`
287        // it, so 30 tests HARD-FAILED on an rch worker with no pandas installed
288        // while passing here. Skipping is the correct outcome there; failing is not.
289        //
290        // br-frankenpandas-00de2: the repository's pinned oracle venv is not a
291        // "system" fallback at all — it is the interpreter CI builds from the
292        // pandas pin — so when `python_bin` is that interpreter the differential
293        // runs whether or not a caller opted in. The 49 test sites that set
294        // `allow_system_pandas_fallback = false` were refusing an UNPINNED
295        // system pandas; against the pinned venv that refusal only reproduces
296        // pass-by-skip.
297        if self.uses_pinned_oracle_interpreter() {
298            return Self::pandas_importable(&self.python_bin);
299        }
300        (self.allow_system_pandas_fallback || Self::env_flag("FP_ALLOW_SYSTEM_PANDAS_FALLBACK"))
301            && Self::pandas_importable(&self.python_bin)
302    }
303
304    /// Is ANY pandas oracle reachable from this configuration: the vendored
305    /// legacy tree, or an interpreter this config is allowed to use?
306    ///
307    /// br-frankenpandas-00de2: `oracle_present` on every report used to be
308    /// `oracle_root.exists()`, so all 445 committed parity reports said the
309    /// oracle was absent even when CI had just run every case through the
310    /// pinned venv. This is the predicate those sites now use.
311    #[must_use]
312    pub fn oracle_reachable(&self) -> bool {
313        self.oracle_root.exists() || self.allows_system_pandas_fallback()
314    }
315
316    /// Can `python` actually `import pandas`? Probed ONCE per interpreter per
317    /// process and cached, because it is asked per fixture.
318    fn pandas_importable(python: &str) -> bool {
319        static PROBES: std::sync::OnceLock<std::sync::Mutex<BTreeMap<String, bool>>> =
320            std::sync::OnceLock::new();
321        let probes = PROBES.get_or_init(|| std::sync::Mutex::new(BTreeMap::new()));
322        let mut guard = probes
323            .lock()
324            .unwrap_or_else(std::sync::PoisonError::into_inner);
325        if let Some(known) = guard.get(python) {
326            return *known;
327        }
328        let importable = std::process::Command::new(python)
329            .args(["-c", "import pandas"])
330            .stdout(std::process::Stdio::null())
331            .stderr(std::process::Stdio::null())
332            .status()
333            .map(|status| status.success())
334            .unwrap_or(false);
335        guard.insert(python.to_owned(), importable);
336        importable
337    }
338
339    #[must_use]
340    pub fn allows_live_oracle_fallback(&self) -> bool {
341        self.allows_system_pandas_fallback()
342    }
343}
344
345impl Default for HarnessConfig {
346    fn default() -> Self {
347        Self::default_paths()
348    }
349}
350
351#[derive(Debug, Clone, PartialEq, Eq)]
352pub struct HarnessReport {
353    pub suite: &'static str,
354    pub oracle_present: bool,
355    pub fixture_count: usize,
356    pub strict_mode: bool,
357}
358
359#[must_use]
360pub fn run_smoke(config: &HarnessConfig) -> HarnessReport {
361    let fixture_count = fs::read_dir(&config.fixture_root)
362        .ok()
363        .into_iter()
364        .flat_map(|it| it.filter_map(Result::ok))
365        .count();
366
367    HarnessReport {
368        suite: "smoke",
369        oracle_present: config.oracle_reachable(),
370        fixture_count,
371        strict_mode: config.strict_mode,
372    }
373}
374
375#[derive(Debug, Clone, Copy, PartialEq, Eq)]
376pub enum OracleMode {
377    FixtureExpected,
378    LiveLegacyPandas,
379}
380
381#[derive(Debug, Clone)]
382pub struct SuiteOptions {
383    pub packet_filter: Option<String>,
384    pub oracle_mode: OracleMode,
385}
386
387impl Default for SuiteOptions {
388    fn default() -> Self {
389        Self {
390            packet_filter: None,
391            oracle_mode: OracleMode::FixtureExpected,
392        }
393    }
394}
395
396#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
397#[serde(rename_all = "snake_case")]
398pub enum FixtureOperation {
399    SeriesAdd,
400    SeriesSub,
401    SeriesMul,
402    SeriesDiv,
403    SeriesJoin,
404    #[serde(rename = "series_constructor", alias = "series_from_values")]
405    SeriesConstructor,
406    #[serde(rename = "series_to_datetime", alias = "to_datetime")]
407    SeriesToDatetime,
408    #[serde(rename = "series_to_timedelta", alias = "to_timedelta")]
409    SeriesToTimedelta,
410    #[serde(
411        rename = "series_timedelta_total_seconds",
412        alias = "timedelta_total_seconds"
413    )]
414    SeriesTimedeltaTotalSeconds,
415    #[serde(rename = "dataframe_from_series", alias = "data_frame_from_series")]
416    DataFrameFromSeries,
417    #[serde(rename = "dataframe_from_dict", alias = "data_frame_from_dict")]
418    DataFrameFromDict,
419    #[serde(rename = "dataframe_from_records", alias = "data_frame_from_records")]
420    DataFrameFromRecords,
421    #[serde(
422        rename = "dataframe_constructor_kwargs",
423        alias = "data_frame_constructor_kwargs"
424    )]
425    DataFrameConstructorKwargs,
426    #[serde(
427        rename = "dataframe_constructor_scalar",
428        alias = "data_frame_constructor_scalar"
429    )]
430    DataFrameConstructorScalar,
431    #[serde(
432        rename = "dataframe_constructor_dict_of_series",
433        alias = "data_frame_constructor_dict_of_series"
434    )]
435    DataFrameConstructorDictOfSeries,
436    #[serde(
437        rename = "dataframe_constructor_list_like",
438        alias = "data_frame_constructor_list_like",
439        alias = "dataframe_constructor_2d",
440        alias = "data_frame_constructor_2d"
441    )]
442    DataFrameConstructorListLike,
443    #[serde(rename = "groupby_sum", alias = "group_by_sum")]
444    GroupBySum,
445    IndexAlignUnion,
446    IndexHasDuplicates,
447    IndexIsMonotonicIncreasing,
448    IndexIsMonotonicDecreasing,
449    IndexFirstPositions,
450    // FP-P2C-006: Join + concat
451    SeriesConcat,
452    #[serde(
453        rename = "series_combine_first",
454        alias = "series_combine_first_default"
455    )]
456    SeriesCombineFirst,
457    #[serde(rename = "series_asof", alias = "series_asof_default")]
458    SeriesAsof,
459    #[serde(rename = "series_autocorr", alias = "series_autocorr_default")]
460    SeriesAutocorr,
461    // FP-P2C-007: Missingness + nanops
462    NanSum,
463    NanMean,
464    NanMin,
465    NanMax,
466    NanStd,
467    NanVar,
468    NanCount,
469    FillNa,
470    DropNa,
471    #[serde(
472        rename = "series_to_arrow_round_trip",
473        alias = "series_arrow_round_trip",
474        alias = "series_to_arrow"
475    )]
476    SeriesToArrowRoundTrip,
477    // FP-P2C-008: IO round-trip
478    CsvRoundTrip,
479    #[serde(rename = "csv_read_frame", alias = "csv_read_frame_default")]
480    CsvReadFrame,
481    #[serde(rename = "json_round_trip", alias = "json_round_trip_default")]
482    JsonRoundTrip,
483    #[serde(rename = "jsonl_round_trip", alias = "jsonl_round_trip_default")]
484    JsonlRoundTrip,
485    #[serde(rename = "parquet_round_trip", alias = "parquet_round_trip_default")]
486    ParquetRoundTrip,
487    #[serde(rename = "feather_round_trip", alias = "feather_round_trip_default")]
488    FeatherRoundTrip,
489    #[serde(rename = "excel_round_trip", alias = "excel_round_trip_default")]
490    ExcelRoundTrip,
491    #[serde(
492        rename = "ipc_stream_round_trip",
493        alias = "ipc_stream_round_trip_default"
494    )]
495    IpcStreamRoundTrip,
496    // FP-P2C-009: Storage invariants
497    ColumnDtypeCheck,
498    SeriesDtypeCheck,
499    // FP-P2C-010: loc/iloc
500    SeriesFilter,
501    SeriesHead,
502    #[serde(rename = "series_tail", alias = "series_tail_default")]
503    SeriesTail,
504    SeriesAny,
505    SeriesAll,
506    #[serde(rename = "series_bool", alias = "series_bool_default")]
507    SeriesBool,
508    #[serde(rename = "series_repeat", alias = "series_repeat_default")]
509    SeriesRepeat,
510    #[serde(rename = "series_to_numeric", alias = "series_to_numeric_default")]
511    SeriesToNumeric,
512    #[serde(
513        rename = "series_convert_dtypes",
514        alias = "series_convert_dtypes_default"
515    )]
516    SeriesConvertDtypes,
517    #[serde(rename = "series_astype", alias = "series_astype_default")]
518    SeriesAstype,
519    #[serde(rename = "series_clip", alias = "series_clip_default")]
520    SeriesClip,
521    #[serde(rename = "series_abs", alias = "series_abs_default")]
522    SeriesAbs,
523    #[serde(rename = "series_round", alias = "series_round_default")]
524    SeriesRound,
525    #[serde(rename = "series_cumsum", alias = "series_cumsum_default")]
526    SeriesCumsum,
527    #[serde(rename = "series_cumprod", alias = "series_cumprod_default")]
528    SeriesCumprod,
529    #[serde(rename = "series_cummax", alias = "series_cummax_default")]
530    SeriesCummax,
531    #[serde(rename = "series_cummin", alias = "series_cummin_default")]
532    SeriesCummin,
533    #[serde(rename = "series_nlargest", alias = "series_nlargest_default")]
534    SeriesNlargest,
535    #[serde(rename = "series_nsmallest", alias = "series_nsmallest_default")]
536    SeriesNsmallest,
537    #[serde(rename = "series_between", alias = "series_between_default")]
538    SeriesBetween,
539    #[serde(rename = "dataframe_cumsum", alias = "dataframe_cumsum_default")]
540    DataFrameCumsum,
541    #[serde(rename = "dataframe_cumprod", alias = "dataframe_cumprod_default")]
542    DataFrameCumprod,
543    #[serde(rename = "dataframe_cummax", alias = "dataframe_cummax_default")]
544    DataFrameCummax,
545    #[serde(rename = "dataframe_cummin", alias = "dataframe_cummin_default")]
546    DataFrameCummin,
547    #[serde(rename = "dataframe_astype", alias = "dataframe_astype_default")]
548    DataFrameAstype,
549    #[serde(rename = "dataframe_clip", alias = "dataframe_clip_default")]
550    DataFrameClip,
551    #[serde(rename = "dataframe_abs", alias = "dataframe_abs_default")]
552    DataFrameAbs,
553    #[serde(rename = "dataframe_describe", alias = "dataframe_describe_default")]
554    DataFrameDescribe,
555    #[serde(rename = "dataframe_corr", alias = "dataframe_corr_default")]
556    DataFrameCorr,
557    #[serde(rename = "dataframe_cov", alias = "dataframe_cov_default")]
558    DataFrameCov,
559    #[serde(rename = "dataframe_idxmin", alias = "dataframe_idxmin_default")]
560    DataFrameIdxmin,
561    #[serde(rename = "dataframe_idxmax", alias = "dataframe_idxmax_default")]
562    DataFrameIdxmax,
563    #[serde(rename = "dataframe_sem", alias = "dataframe_sem_default")]
564    DataFrameSem,
565    #[serde(
566        rename = "dataframe_apply_sem_axis0",
567        alias = "data_frame_apply_sem_axis0"
568    )]
569    DataFrameApplySemAxis0,
570    #[serde(rename = "dataframe_skew", alias = "dataframe_skew_default")]
571    DataFrameSkew,
572    #[serde(rename = "dataframe_kurtosis", alias = "dataframe_kurtosis_default")]
573    DataFrameKurtosis,
574    #[serde(rename = "dataframe_prod", alias = "dataframe_prod_default")]
575    DataFrameProd,
576    #[serde(
577        rename = "dataframe_apply_prod_axis1",
578        alias = "data_frame_apply_prod_axis1"
579    )]
580    DataFrameApplyProdAxis1,
581    #[serde(
582        rename = "dataframe_apply_product_axis1",
583        alias = "data_frame_apply_product_axis1"
584    )]
585    DataFrameApplyProductAxis1,
586    #[serde(rename = "dataframe_sum", alias = "dataframe_sum_default")]
587    DataFrameSum,
588    #[serde(rename = "dataframe_mean", alias = "dataframe_mean_default")]
589    DataFrameMean,
590    #[serde(rename = "dataframe_std", alias = "dataframe_std_default")]
591    DataFrameStd,
592    #[serde(rename = "dataframe_var", alias = "dataframe_var_default")]
593    DataFrameVar,
594    #[serde(rename = "dataframe_min", alias = "dataframe_min_default")]
595    DataFrameMin,
596    #[serde(rename = "dataframe_max", alias = "dataframe_max_default")]
597    DataFrameMax,
598    #[serde(rename = "dataframe_median", alias = "dataframe_median_default")]
599    DataFrameMedian,
600    #[serde(rename = "dataframe_any", alias = "dataframe_any_default")]
601    DataFrameAny,
602    #[serde(rename = "dataframe_all", alias = "dataframe_all_default")]
603    DataFrameAll,
604    #[serde(rename = "dataframe_nunique", alias = "dataframe_nunique_default")]
605    DataFrameNunique,
606    #[serde(
607        rename = "dataframe_apply_nunique_axis0",
608        alias = "data_frame_apply_nunique_axis0"
609    )]
610    DataFrameApplyNuniqueAxis0,
611    #[serde(rename = "dataframe_quantile", alias = "dataframe_quantile_default")]
612    DataFrameQuantile,
613    #[serde(
614        rename = "dataframe_value_counts",
615        alias = "dataframe_value_counts_default"
616    )]
617    DataFrameValueCounts,
618    #[serde(
619        rename = "dataframe_memory_usage",
620        alias = "dataframe_memory_usage_default"
621    )]
622    DataFrameMemoryUsage,
623    #[serde(rename = "dataframe_round", alias = "dataframe_round_default")]
624    DataFrameRound,
625    #[serde(rename = "dataframe_binary_alias", alias = "data_frame_binary_alias")]
626    DataFrameBinaryAlias,
627    #[serde(rename = "series_cut", alias = "series_cut_default")]
628    SeriesCut,
629    #[serde(rename = "series_qcut", alias = "series_qcut_default")]
630    SeriesQcut,
631    #[serde(rename = "series_value_counts", alias = "series_value_counts_default")]
632    SeriesValueCounts,
633    #[serde(rename = "series_sort_index", alias = "series_sort_index_default")]
634    SeriesSortIndex,
635    #[serde(rename = "series_sort_values", alias = "series_sort_values_default")]
636    SeriesSortValues,
637    #[serde(rename = "series_isna", alias = "series_isna_default")]
638    SeriesIsNa,
639    #[serde(rename = "series_notna", alias = "series_notna_default")]
640    SeriesNotNa,
641    #[serde(rename = "series_isnull", alias = "series_isnull_default")]
642    SeriesIsNull,
643    #[serde(rename = "series_notnull", alias = "series_notnull_default")]
644    SeriesNotNull,
645    #[serde(rename = "series_fillna", alias = "series_fillna_default")]
646    SeriesFillNa,
647    #[serde(rename = "series_dropna", alias = "series_dropna_default")]
648    SeriesDropNa,
649    #[serde(rename = "series_count", alias = "series_count_default")]
650    SeriesCount,
651    #[serde(rename = "series_nunique", alias = "series_nunique_default")]
652    SeriesNunique,
653    #[serde(
654        rename = "series_first_valid_index",
655        alias = "series_first_valid_index_default"
656    )]
657    SeriesFirstValidIndex,
658    #[serde(
659        rename = "series_last_valid_index",
660        alias = "series_last_valid_index_default"
661    )]
662    SeriesLastValidIndex,
663    #[serde(rename = "series_idxmin", alias = "series_idxmin_default")]
664    SeriesIdxmin,
665    #[serde(rename = "series_idxmax", alias = "series_idxmax_default")]
666    SeriesIdxmax,
667    #[serde(rename = "series_argmin", alias = "series_argmin_default")]
668    SeriesArgmin,
669    #[serde(rename = "series_argmax", alias = "series_argmax_default")]
670    SeriesArgmax,
671    #[serde(rename = "series_mode", alias = "series_mode_default")]
672    SeriesMode,
673    #[serde(rename = "series_rank", alias = "series_rank_default")]
674    SeriesRank,
675    #[serde(rename = "series_argsort", alias = "series_argsort_default")]
676    SeriesArgsort,
677    #[serde(rename = "series_searchsorted", alias = "series_searchsorted_default")]
678    SeriesSearchsorted,
679    #[serde(rename = "series_dot", alias = "series_dot_default")]
680    SeriesDot,
681    #[serde(rename = "series_describe", alias = "series_describe_default")]
682    SeriesDescribe,
683    #[serde(rename = "series_duplicated", alias = "series_duplicated_default")]
684    SeriesDuplicated,
685    #[serde(
686        rename = "series_drop_duplicates",
687        alias = "series_drop_duplicates_default"
688    )]
689    SeriesDropDuplicates,
690    #[serde(rename = "series_unique", alias = "series_unique_default")]
691    SeriesUnique,
692    #[serde(rename = "series_factorize", alias = "series_factorize_default")]
693    SeriesFactorize,
694    #[serde(rename = "series_where", alias = "series_where_default")]
695    SeriesWhere,
696    #[serde(rename = "series_mask", alias = "series_mask_default")]
697    SeriesMask,
698    #[serde(rename = "series_replace", alias = "series_replace_default")]
699    SeriesReplace,
700    #[serde(rename = "series_update", alias = "series_update_default")]
701    SeriesUpdate,
702    #[serde(rename = "series_map", alias = "series_map_default")]
703    SeriesMap,
704    #[serde(
705        rename = "series_categorical_from_codes",
706        alias = "categorical_from_codes"
707    )]
708    SeriesCategoricalFromCodes,
709    #[serde(rename = "series_to_frame", alias = "series_to_frame_default")]
710    SeriesToFrame,
711    #[serde(rename = "series_unstack", alias = "series_unstack_default")]
712    SeriesUnstack,
713    #[serde(rename = "series_diff", alias = "series_diff_default")]
714    SeriesDiff,
715    #[serde(rename = "series_shift", alias = "series_shift_default")]
716    SeriesShift,
717    #[serde(rename = "series_pct_change", alias = "series_pct_change_default")]
718    SeriesPctChange,
719    #[serde(rename = "series_xs", alias = "series_xs_default")]
720    SeriesXs,
721    SeriesLoc,
722    SeriesIloc,
723    #[serde(rename = "series_take", alias = "series_take_default")]
724    SeriesTake,
725    #[serde(rename = "series_at_time", alias = "series_at_time_default")]
726    SeriesAtTime,
727    #[serde(rename = "series_between_time", alias = "series_between_time_default")]
728    SeriesBetweenTime,
729    #[serde(rename = "series_partition_df", alias = "series_str_partition_df")]
730    SeriesPartitionDf,
731    #[serde(rename = "series_rpartition_df", alias = "series_str_rpartition_df")]
732    SeriesRpartitionDf,
733    #[serde(rename = "series_split_df", alias = "series_str_split_df")]
734    SeriesSplitDf,
735    #[serde(rename = "series_extract_df", alias = "series_str_extract_df")]
736    SeriesExtractDf,
737    #[serde(rename = "series_extractall", alias = "series_str_extractall")]
738    SeriesExtractAll,
739    #[serde(
740        rename = "series_str_get_dummies",
741        alias = "series_str_get_dummies_default"
742    )]
743    SeriesStrGetDummies,
744    #[serde(rename = "series_str_lower", alias = "series_str_lower_default")]
745    SeriesStrLower,
746    #[serde(rename = "series_str_upper", alias = "series_str_upper_default")]
747    SeriesStrUpper,
748    #[serde(
749        rename = "series_str_capitalize",
750        alias = "series_str_capitalize_default"
751    )]
752    SeriesStrCapitalize,
753    #[serde(rename = "series_str_strip", alias = "series_str_strip_default")]
754    SeriesStrStrip,
755    #[serde(rename = "series_str_len", alias = "series_str_len_default")]
756    SeriesStrLen,
757    #[serde(rename = "series_str_contains", alias = "series_str_contains_default")]
758    SeriesStrContains,
759    #[serde(
760        rename = "series_str_startswith",
761        alias = "series_str_startswith_default"
762    )]
763    SeriesStrStartswith,
764    #[serde(rename = "series_str_endswith", alias = "series_str_endswith_default")]
765    SeriesStrEndswith,
766    #[serde(rename = "series_str_replace", alias = "series_str_replace_default")]
767    SeriesStrReplace,
768    #[serde(rename = "series_str_lstrip", alias = "series_str_lstrip_default")]
769    SeriesStrLstrip,
770    #[serde(rename = "series_str_rstrip", alias = "series_str_rstrip_default")]
771    SeriesStrRstrip,
772    #[serde(rename = "series_str_title", alias = "series_str_title_default")]
773    SeriesStrTitle,
774    #[serde(rename = "series_str_swapcase", alias = "series_str_swapcase_default")]
775    SeriesStrSwapcase,
776    #[serde(rename = "series_str_zfill", alias = "series_str_zfill_default")]
777    SeriesStrZfill,
778    #[serde(rename = "series_str_center", alias = "series_str_center_default")]
779    SeriesStrCenter,
780    #[serde(rename = "series_str_ljust", alias = "series_str_ljust_default")]
781    SeriesStrLjust,
782    #[serde(rename = "series_str_rjust", alias = "series_str_rjust_default")]
783    SeriesStrRjust,
784    #[serde(rename = "series_str_pad", alias = "series_str_pad_default")]
785    SeriesStrPad,
786    #[serde(rename = "series_str_isdigit", alias = "series_str_isdigit_default")]
787    SeriesStrIsdigit,
788    #[serde(rename = "series_str_isalpha", alias = "series_str_isalpha_default")]
789    SeriesStrIsalpha,
790    #[serde(rename = "series_str_isalnum", alias = "series_str_isalnum_default")]
791    SeriesStrIsalnum,
792    #[serde(rename = "series_str_isspace", alias = "series_str_isspace_default")]
793    SeriesStrIsspace,
794    #[serde(rename = "series_str_islower", alias = "series_str_islower_default")]
795    SeriesStrIslower,
796    #[serde(rename = "series_str_isupper", alias = "series_str_isupper_default")]
797    SeriesStrIsupper,
798    #[serde(
799        rename = "series_str_isnumeric",
800        alias = "series_str_isnumeric_default"
801    )]
802    SeriesStrIsnumeric,
803    #[serde(rename = "series_str_find", alias = "series_str_find_default")]
804    SeriesStrFind,
805    #[serde(rename = "series_str_rfind", alias = "series_str_rfind_default")]
806    SeriesStrRfind,
807    #[serde(rename = "series_str_slice", alias = "series_str_slice_default")]
808    SeriesStrSlice,
809    #[serde(rename = "series_str_get", alias = "series_str_get_default")]
810    SeriesStrGet,
811    #[serde(rename = "series_str_repeat", alias = "series_str_repeat_default")]
812    SeriesStrRepeat,
813    #[serde(rename = "series_str_count", alias = "series_str_count_default")]
814    SeriesStrCount,
815    #[serde(rename = "series_str_wrap", alias = "series_str_wrap_default")]
816    SeriesStrWrap,
817    #[serde(
818        rename = "series_str_normalize",
819        alias = "series_str_normalize_default"
820    )]
821    SeriesStrNormalize,
822    #[serde(
823        rename = "series_str_fullmatch",
824        alias = "series_str_fullmatch_default"
825    )]
826    SeriesStrFullmatch,
827    #[serde(rename = "series_str_match", alias = "series_str_match_default")]
828    SeriesStrMatch,
829    #[serde(
830        rename = "series_str_removeprefix",
831        alias = "series_str_removeprefix_default"
832    )]
833    SeriesStrRemoveprefix,
834    #[serde(
835        rename = "series_str_removesuffix",
836        alias = "series_str_removesuffix_default"
837    )]
838    SeriesStrRemovesuffix,
839    #[serde(
840        rename = "series_str_split_get",
841        alias = "series_str_split_get_default"
842    )]
843    SeriesStrSplitGet,
844    #[serde(rename = "series_str_join", alias = "series_str_join_default")]
845    SeriesStrJoin,
846    #[serde(
847        rename = "series_str_isdecimal",
848        alias = "series_str_isdecimal_default"
849    )]
850    SeriesStrIsdecimal,
851    #[serde(rename = "series_str_istitle", alias = "series_str_istitle_default")]
852    SeriesStrIstitle,
853    #[serde(rename = "series_str_casefold", alias = "series_str_casefold_default")]
854    SeriesStrCasefold,
855    #[serde(rename = "series_str_encode", alias = "series_str_encode_default")]
856    SeriesStrEncode,
857    #[serde(rename = "series_str_decode", alias = "series_str_decode_default")]
858    SeriesStrDecode,
859    #[serde(
860        rename = "series_str_translate",
861        alias = "series_str_translate_default"
862    )]
863    SeriesStrTranslate,
864    #[serde(
865        rename = "series_str_expandtabs",
866        alias = "series_str_expandtabs_default"
867    )]
868    SeriesStrExpandtabs,
869    #[serde(rename = "series_str_index_of", alias = "series_str_index_of_default")]
870    SeriesStrIndexOf,
871    #[serde(
872        rename = "series_str_rindex_of",
873        alias = "series_str_rindex_of_default"
874    )]
875    SeriesStrRindexOf,
876    #[serde(
877        rename = "series_str_split_count",
878        alias = "series_str_split_count_default"
879    )]
880    SeriesStrSplitCount,
881    #[serde(
882        rename = "series_str_rsplit_get",
883        alias = "series_str_rsplit_get_default"
884    )]
885    SeriesStrRsplitGet,
886    #[serde(
887        rename = "series_str_split_regex_get",
888        alias = "series_str_split_regex_get_default"
889    )]
890    SeriesStrSplitRegexGet,
891    #[serde(
892        rename = "series_str_count_matches",
893        alias = "series_str_count_matches_default"
894    )]
895    SeriesStrCountMatches,
896    #[serde(
897        rename = "series_str_count_literal",
898        alias = "series_str_count_literal_default"
899    )]
900    SeriesStrCountLiteral,
901    #[serde(rename = "series_str_findall", alias = "series_str_findall_default")]
902    SeriesStrFindall,
903    #[serde(
904        rename = "series_str_contains_any",
905        alias = "series_str_contains_any_default"
906    )]
907    SeriesStrContainsAny,
908    #[serde(
909        rename = "series_str_startswith_any",
910        alias = "series_str_startswith_any_default"
911    )]
912    SeriesStrStartswithAny,
913    #[serde(
914        rename = "series_str_endswith_any",
915        alias = "series_str_endswith_any_default"
916    )]
917    SeriesStrEndswithAny,
918    #[serde(rename = "series_dt_year", alias = "series_dt_year_default")]
919    SeriesDtYear,
920    #[serde(rename = "series_dt_month", alias = "series_dt_month_default")]
921    SeriesDtMonth,
922    #[serde(rename = "series_dt_day", alias = "series_dt_day_default")]
923    SeriesDtDay,
924    #[serde(rename = "series_dt_hour", alias = "series_dt_hour_default")]
925    SeriesDtHour,
926    #[serde(rename = "series_dt_minute", alias = "series_dt_minute_default")]
927    SeriesDtMinute,
928    #[serde(rename = "series_dt_second", alias = "series_dt_second_default")]
929    SeriesDtSecond,
930    #[serde(
931        rename = "series_dt_microsecond",
932        alias = "series_dt_microsecond_default"
933    )]
934    SeriesDtMicrosecond,
935    #[serde(
936        rename = "series_dt_nanosecond",
937        alias = "series_dt_nanosecond_default"
938    )]
939    SeriesDtNanosecond,
940    #[serde(rename = "series_dt_dayofweek", alias = "series_dt_dayofweek_default")]
941    SeriesDtDayofweek,
942    #[serde(rename = "series_dt_quarter", alias = "series_dt_quarter_default")]
943    SeriesDtQuarter,
944    #[serde(rename = "series_dt_dayofyear", alias = "series_dt_dayofyear_default")]
945    SeriesDtDayofyear,
946    #[serde(
947        rename = "series_dt_weekofyear",
948        alias = "series_dt_weekofyear_default"
949    )]
950    SeriesDtWeekofyear,
951    #[serde(
952        rename = "series_dt_is_month_start",
953        alias = "series_dt_is_month_start_default"
954    )]
955    SeriesDtIsMonthStart,
956    #[serde(
957        rename = "series_dt_is_month_end",
958        alias = "series_dt_is_month_end_default"
959    )]
960    SeriesDtIsMonthEnd,
961    #[serde(
962        rename = "series_dt_is_year_start",
963        alias = "series_dt_is_year_start_default"
964    )]
965    SeriesDtIsYearStart,
966    #[serde(
967        rename = "series_dt_is_year_end",
968        alias = "series_dt_is_year_end_default"
969    )]
970    SeriesDtIsYearEnd,
971    #[serde(rename = "series_dt_date", alias = "series_dt_date_default")]
972    SeriesDtDate,
973    #[serde(
974        rename = "series_dt_days_in_month",
975        alias = "series_dt_days_in_month_default"
976    )]
977    SeriesDtDaysInMonth,
978    #[serde(
979        rename = "series_dt_is_leap_year",
980        alias = "series_dt_is_leap_year_default"
981    )]
982    SeriesDtIsLeapYear,
983    #[serde(
984        rename = "series_dt_is_quarter_start",
985        alias = "series_dt_is_quarter_start_default"
986    )]
987    SeriesDtIsQuarterStart,
988    #[serde(
989        rename = "series_dt_is_quarter_end",
990        alias = "series_dt_is_quarter_end_default"
991    )]
992    SeriesDtIsQuarterEnd,
993    #[serde(rename = "series_dt_strftime", alias = "series_dt_strftime_default")]
994    SeriesDtStrftime,
995    #[serde(rename = "series_dt_tz_convert")]
996    SeriesDtTzConvert,
997    #[serde(rename = "series_dt_tz_localize")]
998    SeriesDtTzLocalize,
999    #[serde(rename = "series_dt_timetz")]
1000    SeriesDtTimetz,
1001    #[serde(rename = "series_dt_floor", alias = "series_dt_floor_default")]
1002    SeriesDtFloor,
1003    #[serde(rename = "series_dt_to_period", alias = "series_dt_to_period_default")]
1004    SeriesDtToPeriod,
1005    #[serde(rename = "series_dt_ceil", alias = "series_dt_ceil_default")]
1006    SeriesDtCeil,
1007    #[serde(rename = "series_dt_round", alias = "series_dt_round_default")]
1008    SeriesDtRound,
1009    #[serde(
1010        rename = "series_dt_month_name",
1011        alias = "series_dt_month_name_default"
1012    )]
1013    SeriesDtMonthName,
1014    #[serde(rename = "series_dt_day_name", alias = "series_dt_day_name_default")]
1015    SeriesDtDayName,
1016    #[serde(
1017        rename = "series_dt_total_seconds",
1018        alias = "series_dt_total_seconds_default"
1019    )]
1020    SeriesDtTotalSeconds,
1021    #[serde(rename = "series_dt_days", alias = "series_dt_days_default")]
1022    SeriesDtDays,
1023    #[serde(rename = "series_dt_seconds", alias = "series_dt_seconds_default")]
1024    SeriesDtSeconds,
1025    #[serde(
1026        rename = "series_dt_microseconds",
1027        alias = "series_dt_microseconds_default"
1028    )]
1029    SeriesDtMicroseconds,
1030    #[serde(
1031        rename = "series_dt_nanoseconds",
1032        alias = "series_dt_nanoseconds_default"
1033    )]
1034    SeriesDtNanoseconds,
1035    #[serde(
1036        rename = "series_dt_to_timestamp",
1037        alias = "series_dt_to_timestamp_default"
1038    )]
1039    SeriesDtToTimestamp,
1040    #[serde(
1041        rename = "series_dt_to_pydatetime",
1042        alias = "series_dt_to_pydatetime_default"
1043    )]
1044    SeriesDtToPydatetime,
1045    #[serde(
1046        rename = "series_dt_to_pytimedelta",
1047        alias = "series_dt_to_pytimedelta_default"
1048    )]
1049    SeriesDtToPytimedelta,
1050    #[serde(rename = "dataframe_loc", alias = "data_frame_loc")]
1051    DataFrameLoc,
1052    #[serde(rename = "dataframe_identity", alias = "data_frame_identity")]
1053    DataFrameIdentity,
1054    #[serde(rename = "dataframe_iloc", alias = "data_frame_iloc")]
1055    DataFrameIloc,
1056    #[serde(rename = "dataframe_take", alias = "data_frame_take")]
1057    DataFrameTake,
1058    #[serde(rename = "dataframe_filter", alias = "data_frame_filter")]
1059    DataFrameFilter,
1060    #[serde(rename = "dataframe_groupby_sum", alias = "data_frame_groupby_sum")]
1061    DataFrameGroupBySum,
1062    #[serde(
1063        rename = "dataframe_groupby_agg_multi",
1064        alias = "data_frame_groupby_agg_multi"
1065    )]
1066    DataFrameGroupByAggMulti,
1067    #[serde(
1068        rename = "dataframe_groupby_idxmin",
1069        alias = "data_frame_groupby_idxmin"
1070    )]
1071    DataFrameGroupByIdxMin,
1072    #[serde(
1073        rename = "dataframe_groupby_idxmax",
1074        alias = "data_frame_groupby_idxmax"
1075    )]
1076    DataFrameGroupByIdxMax,
1077    #[serde(rename = "dataframe_groupby_any", alias = "data_frame_groupby_any")]
1078    DataFrameGroupByAny,
1079    #[serde(rename = "dataframe_groupby_all", alias = "data_frame_groupby_all")]
1080    DataFrameGroupByAll,
1081    #[serde(
1082        rename = "dataframe_groupby_get_group",
1083        alias = "data_frame_groupby_get_group"
1084    )]
1085    DataFrameGroupByGetGroup,
1086    #[serde(rename = "dataframe_groupby_ffill", alias = "data_frame_groupby_ffill")]
1087    DataFrameGroupByFfill,
1088    #[serde(rename = "dataframe_groupby_bfill", alias = "data_frame_groupby_bfill")]
1089    DataFrameGroupByBfill,
1090    #[serde(rename = "dataframe_groupby_sem", alias = "data_frame_groupby_sem")]
1091    DataFrameGroupBySem,
1092    #[serde(rename = "dataframe_groupby_skew", alias = "data_frame_groupby_skew")]
1093    DataFrameGroupBySkew,
1094    #[serde(
1095        rename = "dataframe_groupby_kurtosis",
1096        alias = "data_frame_groupby_kurtosis"
1097    )]
1098    DataFrameGroupByKurtosis,
1099    #[serde(rename = "dataframe_groupby_ohlc", alias = "data_frame_groupby_ohlc")]
1100    DataFrameGroupByOhlc,
1101    #[serde(
1102        rename = "dataframe_groupby_cumcount",
1103        alias = "data_frame_groupby_cumcount"
1104    )]
1105    DataFrameGroupByCumcount,
1106    #[serde(
1107        rename = "dataframe_groupby_ngroup",
1108        alias = "data_frame_groupby_ngroup"
1109    )]
1110    DataFrameGroupByNgroup,
1111    #[serde(
1112        rename = "dataframe_groupby_rolling_mean",
1113        alias = "data_frame_groupby_rolling_mean"
1114    )]
1115    DataFrameGroupByRollingMean,
1116    #[serde(
1117        rename = "dataframe_groupby_rolling_sum",
1118        alias = "data_frame_groupby_rolling_sum"
1119    )]
1120    DataFrameGroupByRollingSum,
1121    #[serde(
1122        rename = "dataframe_groupby_rolling_min",
1123        alias = "data_frame_groupby_rolling_min"
1124    )]
1125    DataFrameGroupByRollingMin,
1126    #[serde(
1127        rename = "dataframe_groupby_rolling_max",
1128        alias = "data_frame_groupby_rolling_max"
1129    )]
1130    DataFrameGroupByRollingMax,
1131    #[serde(
1132        rename = "dataframe_groupby_rolling_count",
1133        alias = "data_frame_groupby_rolling_count"
1134    )]
1135    DataFrameGroupByRollingCount,
1136    #[serde(
1137        rename = "dataframe_groupby_rolling_std",
1138        alias = "data_frame_groupby_rolling_std"
1139    )]
1140    DataFrameGroupByRollingStd,
1141    #[serde(
1142        rename = "dataframe_groupby_rolling_var",
1143        alias = "data_frame_groupby_rolling_var"
1144    )]
1145    DataFrameGroupByRollingVar,
1146    #[serde(
1147        rename = "dataframe_groupby_resample_min",
1148        alias = "data_frame_groupby_resample_min"
1149    )]
1150    DataFrameGroupByResampleMin,
1151    #[serde(
1152        rename = "dataframe_groupby_resample_max",
1153        alias = "data_frame_groupby_resample_max"
1154    )]
1155    DataFrameGroupByResampleMax,
1156    #[serde(
1157        rename = "dataframe_groupby_resample_count",
1158        alias = "data_frame_groupby_resample_count"
1159    )]
1160    DataFrameGroupByResampleCount,
1161    #[serde(
1162        rename = "dataframe_groupby_resample_first",
1163        alias = "data_frame_groupby_resample_first"
1164    )]
1165    DataFrameGroupByResampleFirst,
1166    #[serde(
1167        rename = "dataframe_groupby_resample_last",
1168        alias = "data_frame_groupby_resample_last"
1169    )]
1170    DataFrameGroupByResampleLast,
1171    #[serde(rename = "dataframe_asof", alias = "data_frame_asof")]
1172    DataFrameAsof,
1173    #[serde(rename = "dataframe_at_time", alias = "data_frame_at_time")]
1174    DataFrameAtTime,
1175    #[serde(rename = "dataframe_between_time", alias = "data_frame_between_time")]
1176    DataFrameBetweenTime,
1177    #[serde(rename = "dataframe_bool", alias = "data_frame_bool")]
1178    DataFrameBool,
1179    #[serde(rename = "dataframe_head", alias = "data_frame_head")]
1180    DataFrameHead,
1181    #[serde(rename = "dataframe_tail", alias = "data_frame_tail")]
1182    DataFrameTail,
1183    #[serde(rename = "dataframe_eval", alias = "data_frame_eval")]
1184    DataFrameEval,
1185    #[serde(rename = "dataframe_compare", alias = "data_frame_compare")]
1186    DataFrameCompare,
1187    #[serde(rename = "dataframe_explode", alias = "data_frame_explode")]
1188    DataFrameExplode,
1189    #[serde(rename = "dataframe_query", alias = "data_frame_query")]
1190    DataFrameQuery,
1191    #[serde(rename = "dataframe_xs", alias = "data_frame_xs")]
1192    DataFrameXs,
1193    #[serde(rename = "dataframe_isna", alias = "data_frame_isna")]
1194    DataFrameIsNa,
1195    #[serde(rename = "dataframe_notna", alias = "data_frame_notna")]
1196    DataFrameNotNa,
1197    #[serde(rename = "dataframe_isnull", alias = "data_frame_isnull")]
1198    DataFrameIsNull,
1199    #[serde(rename = "dataframe_notnull", alias = "data_frame_notnull")]
1200    DataFrameNotNull,
1201    #[serde(rename = "dataframe_count", alias = "data_frame_count")]
1202    DataFrameCount,
1203    #[serde(rename = "dataframe_mode", alias = "data_frame_mode")]
1204    DataFrameMode,
1205    #[serde(rename = "dataframe_rank", alias = "data_frame_rank")]
1206    DataFrameRank,
1207    #[serde(rename = "dataframe_fillna", alias = "data_frame_fillna")]
1208    DataFrameFillNa,
1209    #[serde(rename = "dataframe_dropna", alias = "data_frame_dropna")]
1210    DataFrameDropNa,
1211    #[serde(
1212        rename = "dataframe_dropna_columns",
1213        alias = "data_frame_dropna_columns"
1214    )]
1215    DataFrameDropNaColumns,
1216    #[serde(rename = "dataframe_set_index", alias = "data_frame_set_index")]
1217    DataFrameSetIndex,
1218    #[serde(rename = "dataframe_reset_index", alias = "data_frame_reset_index")]
1219    DataFrameResetIndex,
1220    #[serde(rename = "dataframe_insert", alias = "data_frame_insert")]
1221    DataFrameInsert,
1222    #[serde(rename = "dataframe_assign", alias = "data_frame_assign")]
1223    DataFrameAssign,
1224    #[serde(
1225        rename = "dataframe_rename_columns",
1226        alias = "data_frame_rename_columns"
1227    )]
1228    DataFrameRenameColumns,
1229    #[serde(rename = "dataframe_reindex", alias = "data_frame_reindex")]
1230    DataFrameReindex,
1231    #[serde(
1232        rename = "dataframe_reindex_columns",
1233        alias = "data_frame_reindex_columns"
1234    )]
1235    DataFrameReindexColumns,
1236    #[serde(rename = "dataframe_drop_columns", alias = "data_frame_drop_columns")]
1237    DataFrameDropColumns,
1238    #[serde(rename = "dataframe_replace", alias = "data_frame_replace")]
1239    DataFrameReplace,
1240    #[serde(rename = "dataframe_where", alias = "data_frame_where")]
1241    DataFrameWhere,
1242    #[serde(rename = "dataframe_where_df", alias = "data_frame_where_df")]
1243    DataFrameWhereDf,
1244    #[serde(rename = "dataframe_mask", alias = "data_frame_mask")]
1245    DataFrameMask,
1246    #[serde(rename = "dataframe_mask_df", alias = "data_frame_mask_df")]
1247    DataFrameMaskDf,
1248    #[serde(rename = "dataframe_duplicated", alias = "data_frame_duplicated")]
1249    DataFrameDuplicated,
1250    #[serde(
1251        rename = "dataframe_drop_duplicates",
1252        alias = "data_frame_drop_duplicates"
1253    )]
1254    DataFrameDropDuplicates,
1255    // FP-P2D-040: DataFrame ordering parity matrix
1256    #[serde(rename = "dataframe_sort_index", alias = "data_frame_sort_index")]
1257    DataFrameSortIndex,
1258    #[serde(rename = "dataframe_sort_values", alias = "data_frame_sort_values")]
1259    DataFrameSortValues,
1260    #[serde(rename = "dataframe_nlargest", alias = "data_frame_nlargest")]
1261    DataFrameNlargest,
1262    #[serde(rename = "dataframe_nsmallest", alias = "data_frame_nsmallest")]
1263    DataFrameNsmallest,
1264    #[serde(rename = "dataframe_diff", alias = "data_frame_diff")]
1265    DataFrameDiff,
1266    #[serde(rename = "dataframe_shift", alias = "data_frame_shift")]
1267    DataFrameShift,
1268    #[serde(rename = "dataframe_pct_change", alias = "data_frame_pct_change")]
1269    DataFramePctChange,
1270    #[serde(rename = "dataframe_melt", alias = "data_frame_melt")]
1271    DataFrameMelt,
1272    #[serde(rename = "dataframe_pivot", alias = "data_frame_pivot")]
1273    DataFramePivot,
1274    #[serde(rename = "dataframe_pivot_table", alias = "data_frame_pivot_table")]
1275    DataFramePivotTable,
1276    #[serde(rename = "dataframe_stack", alias = "data_frame_stack")]
1277    DataFrameStack,
1278    #[serde(rename = "dataframe_transpose", alias = "data_frame_transpose")]
1279    DataFrameTranspose,
1280    #[serde(rename = "dataframe_crosstab", alias = "data_frame_crosstab")]
1281    DataFrameCrosstab,
1282    #[serde(
1283        rename = "dataframe_crosstab_normalize",
1284        alias = "data_frame_crosstab_normalize"
1285    )]
1286    DataFrameCrosstabNormalize,
1287    #[serde(rename = "dataframe_get_dummies", alias = "data_frame_get_dummies")]
1288    DataFrameGetDummies,
1289    // FP-P2D-014: DataFrame merge/join/concat parity matrix
1290    #[serde(rename = "dataframe_merge", alias = "data_frame_merge")]
1291    DataFrameMerge,
1292    #[serde(rename = "dataframe_merge_index", alias = "data_frame_merge_index")]
1293    DataFrameMergeIndex,
1294    #[serde(rename = "dataframe_merge_asof", alias = "data_frame_merge_asof")]
1295    DataFrameMergeAsof,
1296    #[serde(rename = "dataframe_merge_ordered", alias = "data_frame_merge_ordered")]
1297    DataFrameMergeOrdered,
1298    #[serde(rename = "dataframe_concat", alias = "data_frame_concat")]
1299    DataFrameConcat,
1300    #[serde(rename = "dataframe_combine_first", alias = "data_frame_combine_first")]
1301    DataFrameCombineFirst,
1302    // FP-P2C-011: Full GroupBy aggregate matrix
1303    #[serde(rename = "groupby_mean", alias = "group_by_mean")]
1304    GroupByMean,
1305    #[serde(rename = "groupby_count", alias = "group_by_count")]
1306    GroupByCount,
1307    #[serde(rename = "groupby_min", alias = "group_by_min")]
1308    GroupByMin,
1309    #[serde(rename = "groupby_max", alias = "group_by_max")]
1310    GroupByMax,
1311    #[serde(rename = "groupby_first", alias = "group_by_first")]
1312    GroupByFirst,
1313    #[serde(rename = "groupby_last", alias = "group_by_last")]
1314    GroupByLast,
1315    #[serde(rename = "groupby_std", alias = "group_by_std")]
1316    GroupByStd,
1317    #[serde(rename = "groupby_var", alias = "group_by_var")]
1318    GroupByVar,
1319    #[serde(rename = "groupby_median", alias = "group_by_median")]
1320    GroupByMedian,
1321    // Window operations (rolling, expanding, ewm)
1322    #[serde(rename = "series_rolling_mean", alias = "series_rolling_mean_default")]
1323    SeriesRollingMean,
1324    #[serde(rename = "series_rolling_sum", alias = "series_rolling_sum_default")]
1325    SeriesRollingSum,
1326    #[serde(rename = "series_rolling_std", alias = "series_rolling_std_default")]
1327    SeriesRollingStd,
1328    #[serde(rename = "series_rolling_min", alias = "series_rolling_min_default")]
1329    SeriesRollingMin,
1330    #[serde(rename = "series_rolling_max", alias = "series_rolling_max_default")]
1331    SeriesRollingMax,
1332    #[serde(rename = "series_rolling_var", alias = "series_rolling_var_default")]
1333    SeriesRollingVar,
1334    #[serde(
1335        rename = "series_rolling_count",
1336        alias = "series_rolling_count_default"
1337    )]
1338    SeriesRollingCount,
1339    #[serde(
1340        rename = "series_expanding_count",
1341        alias = "series_expanding_count_default"
1342    )]
1343    SeriesExpandingCount,
1344    #[serde(
1345        rename = "series_expanding_quantile",
1346        alias = "series_expanding_quantile_default"
1347    )]
1348    SeriesExpandingQuantile,
1349    #[serde(
1350        rename = "series_expanding_sum",
1351        alias = "series_expanding_sum_default"
1352    )]
1353    SeriesExpandingSum,
1354    #[serde(
1355        rename = "series_expanding_mean",
1356        alias = "series_expanding_mean_default"
1357    )]
1358    SeriesExpandingMean,
1359    #[serde(
1360        rename = "series_expanding_min",
1361        alias = "series_expanding_min_default"
1362    )]
1363    SeriesExpandingMin,
1364    #[serde(
1365        rename = "series_expanding_max",
1366        alias = "series_expanding_max_default"
1367    )]
1368    SeriesExpandingMax,
1369    #[serde(
1370        rename = "series_expanding_std",
1371        alias = "series_expanding_std_default"
1372    )]
1373    SeriesExpandingStd,
1374    #[serde(
1375        rename = "series_expanding_var",
1376        alias = "series_expanding_var_default"
1377    )]
1378    SeriesExpandingVar,
1379    #[serde(rename = "series_ewm_mean", alias = "series_ewm_mean_default")]
1380    SeriesEwmMean,
1381    // Resample operations
1382    #[serde(rename = "series_resample_sum", alias = "series_resample_sum_default")]
1383    SeriesResampleSum,
1384    #[serde(
1385        rename = "series_resample_mean",
1386        alias = "series_resample_mean_default"
1387    )]
1388    SeriesResampleMean,
1389    #[serde(
1390        rename = "series_resample_count",
1391        alias = "series_resample_count_default"
1392    )]
1393    SeriesResampleCount,
1394    #[serde(rename = "series_resample_asfreq")]
1395    SeriesResampleAsfreq,
1396    #[serde(rename = "series_resample_ffill")]
1397    SeriesResampleFfill,
1398    #[serde(rename = "series_resample_bfill")]
1399    SeriesResampleBfill,
1400    #[serde(rename = "dataframe_rolling_mean", alias = "data_frame_rolling_mean")]
1401    DataFrameRollingMean,
1402    #[serde(rename = "dataframe_resample_sum", alias = "data_frame_resample_sum")]
1403    DataFrameResampleSum,
1404    #[serde(rename = "dataframe_resample_mean", alias = "data_frame_resample_mean")]
1405    DataFrameResampleMean,
1406    #[serde(
1407        rename = "dataframe_to_json_records",
1408        alias = "data_frame_to_json_records"
1409    )]
1410    DataFrameToJsonRecords,
1411}
1412
1413impl FixtureOperation {
1414    #[must_use]
1415    pub fn operation_name(self) -> &'static str {
1416        match self {
1417            Self::SeriesAdd => "series_add",
1418            Self::SeriesSub => "series_sub",
1419            Self::SeriesMul => "series_mul",
1420            Self::SeriesDiv => "series_div",
1421            Self::SeriesJoin => "series_join",
1422            Self::SeriesConstructor => "series_constructor",
1423            Self::SeriesToDatetime => "series_to_datetime",
1424            Self::SeriesToTimedelta => "series_to_timedelta",
1425            Self::SeriesTimedeltaTotalSeconds => "series_timedelta_total_seconds",
1426            Self::DataFrameFromSeries => "dataframe_from_series",
1427            Self::DataFrameFromDict => "dataframe_from_dict",
1428            Self::DataFrameFromRecords => "dataframe_from_records",
1429            Self::DataFrameConstructorKwargs => "dataframe_constructor_kwargs",
1430            Self::DataFrameConstructorScalar => "dataframe_constructor_scalar",
1431            Self::DataFrameConstructorDictOfSeries => "dataframe_constructor_dict_of_series",
1432            Self::DataFrameConstructorListLike => "dataframe_constructor_list_like",
1433            Self::GroupBySum => "groupby_sum",
1434            Self::IndexAlignUnion => "index_align_union",
1435            Self::IndexHasDuplicates => "index_has_duplicates",
1436            Self::IndexIsMonotonicIncreasing => "index_is_monotonic_increasing",
1437            Self::IndexIsMonotonicDecreasing => "index_is_monotonic_decreasing",
1438            Self::IndexFirstPositions => "index_first_positions",
1439            Self::SeriesConcat => "series_concat",
1440            Self::SeriesCombineFirst => "series_combine_first",
1441            Self::SeriesAsof => "series_asof",
1442            Self::SeriesAutocorr => "series_autocorr",
1443            Self::NanSum => "nan_sum",
1444            Self::NanMean => "nan_mean",
1445            Self::NanMin => "nan_min",
1446            Self::NanMax => "nan_max",
1447            Self::NanStd => "nan_std",
1448            Self::NanVar => "nan_var",
1449            Self::NanCount => "nan_count",
1450            Self::FillNa => "fill_na",
1451            Self::DropNa => "drop_na",
1452            Self::SeriesToArrowRoundTrip => "series_to_arrow_round_trip",
1453            Self::CsvRoundTrip => "csv_round_trip",
1454            Self::CsvReadFrame => "csv_read_frame",
1455            Self::JsonRoundTrip => "json_round_trip",
1456            Self::JsonlRoundTrip => "jsonl_round_trip",
1457            Self::ParquetRoundTrip => "parquet_round_trip",
1458            Self::FeatherRoundTrip => "feather_round_trip",
1459            Self::ExcelRoundTrip => "excel_round_trip",
1460            Self::IpcStreamRoundTrip => "ipc_stream_round_trip",
1461            Self::ColumnDtypeCheck => "column_dtype_check",
1462            Self::SeriesDtypeCheck => "series_dtype_check",
1463            Self::SeriesFilter => "series_filter",
1464            Self::SeriesHead => "series_head",
1465            Self::SeriesTail => "series_tail",
1466            Self::SeriesAny => "series_any",
1467            Self::SeriesAll => "series_all",
1468            Self::SeriesBool => "series_bool",
1469            Self::SeriesRepeat => "series_repeat",
1470            Self::SeriesToNumeric => "series_to_numeric",
1471            Self::SeriesConvertDtypes => "series_convert_dtypes",
1472            Self::SeriesAstype => "series_astype",
1473            Self::SeriesClip => "series_clip",
1474            Self::SeriesAbs => "series_abs",
1475            Self::SeriesRound => "series_round",
1476            Self::SeriesCumsum => "series_cumsum",
1477            Self::SeriesCumprod => "series_cumprod",
1478            Self::SeriesCummax => "series_cummax",
1479            Self::SeriesCummin => "series_cummin",
1480            Self::SeriesNlargest => "series_nlargest",
1481            Self::SeriesNsmallest => "series_nsmallest",
1482            Self::SeriesBetween => "series_between",
1483            Self::DataFrameCumsum => "dataframe_cumsum",
1484            Self::DataFrameCumprod => "dataframe_cumprod",
1485            Self::DataFrameCummax => "dataframe_cummax",
1486            Self::DataFrameCummin => "dataframe_cummin",
1487            Self::DataFrameAstype => "dataframe_astype",
1488            Self::DataFrameClip => "dataframe_clip",
1489            Self::DataFrameAbs => "dataframe_abs",
1490            Self::DataFrameDescribe => "dataframe_describe",
1491            Self::DataFrameCorr => "dataframe_corr",
1492            Self::DataFrameCov => "dataframe_cov",
1493            Self::DataFrameIdxmin => "dataframe_idxmin",
1494            Self::DataFrameIdxmax => "dataframe_idxmax",
1495            Self::DataFrameSem => "dataframe_sem",
1496            Self::DataFrameApplySemAxis0 => "dataframe_apply_sem_axis0",
1497            Self::DataFrameSkew => "dataframe_skew",
1498            Self::DataFrameKurtosis => "dataframe_kurtosis",
1499            Self::DataFrameProd => "dataframe_prod",
1500            Self::DataFrameApplyProdAxis1 => "dataframe_apply_prod_axis1",
1501            Self::DataFrameApplyProductAxis1 => "dataframe_apply_product_axis1",
1502            Self::DataFrameSum => "dataframe_sum",
1503            Self::DataFrameMean => "dataframe_mean",
1504            Self::DataFrameStd => "dataframe_std",
1505            Self::DataFrameVar => "dataframe_var",
1506            Self::DataFrameMin => "dataframe_min",
1507            Self::DataFrameMax => "dataframe_max",
1508            Self::DataFrameMedian => "dataframe_median",
1509            Self::DataFrameAny => "dataframe_any",
1510            Self::DataFrameAll => "dataframe_all",
1511            Self::DataFrameNunique => "dataframe_nunique",
1512            Self::DataFrameApplyNuniqueAxis0 => "dataframe_apply_nunique_axis0",
1513            Self::DataFrameQuantile => "dataframe_quantile",
1514            Self::DataFrameValueCounts => "dataframe_value_counts",
1515            Self::DataFrameMemoryUsage => "dataframe_memory_usage",
1516            Self::DataFrameRound => "dataframe_round",
1517            Self::DataFrameBinaryAlias => "dataframe_binary_alias",
1518            Self::SeriesCut => "series_cut",
1519            Self::SeriesQcut => "series_qcut",
1520            Self::SeriesValueCounts => "series_value_counts",
1521            Self::SeriesSortIndex => "series_sort_index",
1522            Self::SeriesSortValues => "series_sort_values",
1523            Self::SeriesIsNa => "series_isna",
1524            Self::SeriesNotNa => "series_notna",
1525            Self::SeriesIsNull => "series_isnull",
1526            Self::SeriesNotNull => "series_notnull",
1527            Self::SeriesFillNa => "series_fillna",
1528            Self::SeriesDropNa => "series_dropna",
1529            Self::SeriesCount => "series_count",
1530            Self::SeriesNunique => "series_nunique",
1531            Self::SeriesFirstValidIndex => "series_first_valid_index",
1532            Self::SeriesLastValidIndex => "series_last_valid_index",
1533            Self::SeriesIdxmin => "series_idxmin",
1534            Self::SeriesIdxmax => "series_idxmax",
1535            Self::SeriesArgmin => "series_argmin",
1536            Self::SeriesArgmax => "series_argmax",
1537            Self::SeriesMode => "series_mode",
1538            Self::SeriesRank => "series_rank",
1539            Self::SeriesArgsort => "series_argsort",
1540            Self::SeriesSearchsorted => "series_searchsorted",
1541            Self::SeriesDot => "series_dot",
1542            Self::SeriesDescribe => "series_describe",
1543            Self::SeriesDuplicated => "series_duplicated",
1544            Self::SeriesDropDuplicates => "series_drop_duplicates",
1545            Self::SeriesUnique => "series_unique",
1546            Self::SeriesFactorize => "series_factorize",
1547            Self::SeriesWhere => "series_where",
1548            Self::SeriesMask => "series_mask",
1549            Self::SeriesReplace => "series_replace",
1550            Self::SeriesUpdate => "series_update",
1551            Self::SeriesMap => "series_map",
1552            Self::SeriesCategoricalFromCodes => "series_categorical_from_codes",
1553            Self::SeriesToFrame => "series_to_frame",
1554            Self::SeriesUnstack => "series_unstack",
1555            Self::SeriesXs => "series_xs",
1556            Self::SeriesLoc => "series_loc",
1557            Self::SeriesIloc => "series_iloc",
1558            Self::SeriesTake => "series_take",
1559            Self::SeriesAtTime => "series_at_time",
1560            Self::SeriesBetweenTime => "series_between_time",
1561            Self::SeriesPartitionDf => "series_partition_df",
1562            Self::SeriesRpartitionDf => "series_rpartition_df",
1563            Self::SeriesSplitDf => "series_split_df",
1564            Self::SeriesExtractDf => "series_extract_df",
1565            Self::SeriesExtractAll => "series_extractall",
1566            Self::SeriesStrGetDummies => "series_str_get_dummies",
1567            Self::SeriesStrLower => "series_str_lower",
1568            Self::SeriesStrUpper => "series_str_upper",
1569            Self::SeriesStrCapitalize => "series_str_capitalize",
1570            Self::SeriesStrStrip => "series_str_strip",
1571            Self::SeriesStrLen => "series_str_len",
1572            Self::SeriesStrContains => "series_str_contains",
1573            Self::SeriesStrStartswith => "series_str_startswith",
1574            Self::SeriesStrEndswith => "series_str_endswith",
1575            Self::SeriesStrReplace => "series_str_replace",
1576            Self::SeriesStrLstrip => "series_str_lstrip",
1577            Self::SeriesStrRstrip => "series_str_rstrip",
1578            Self::SeriesStrTitle => "series_str_title",
1579            Self::SeriesStrSwapcase => "series_str_swapcase",
1580            Self::SeriesStrZfill => "series_str_zfill",
1581            Self::SeriesStrCenter => "series_str_center",
1582            Self::SeriesStrLjust => "series_str_ljust",
1583            Self::SeriesStrRjust => "series_str_rjust",
1584            Self::SeriesStrPad => "series_str_pad",
1585            Self::SeriesStrIsdigit => "series_str_isdigit",
1586            Self::SeriesStrIsalpha => "series_str_isalpha",
1587            Self::SeriesStrIsalnum => "series_str_isalnum",
1588            Self::SeriesStrIsspace => "series_str_isspace",
1589            Self::SeriesStrIslower => "series_str_islower",
1590            Self::SeriesStrIsupper => "series_str_isupper",
1591            Self::SeriesStrIsnumeric => "series_str_isnumeric",
1592            Self::SeriesStrFind => "series_str_find",
1593            Self::SeriesStrRfind => "series_str_rfind",
1594            Self::SeriesStrSlice => "series_str_slice",
1595            Self::SeriesStrGet => "series_str_get",
1596            Self::SeriesStrRepeat => "series_str_repeat",
1597            Self::SeriesStrCount => "series_str_count",
1598            Self::SeriesStrWrap => "series_str_wrap",
1599            Self::SeriesStrNormalize => "series_str_normalize",
1600            Self::SeriesStrFullmatch => "series_str_fullmatch",
1601            Self::SeriesStrMatch => "series_str_match",
1602            Self::SeriesStrRemoveprefix => "series_str_removeprefix",
1603            Self::SeriesStrRemovesuffix => "series_str_removesuffix",
1604            Self::SeriesStrSplitGet => "series_str_split_get",
1605            Self::SeriesStrJoin => "series_str_join",
1606            Self::SeriesStrIsdecimal => "series_str_isdecimal",
1607            Self::SeriesStrIstitle => "series_str_istitle",
1608            Self::SeriesStrCasefold => "series_str_casefold",
1609            Self::SeriesStrEncode => "series_str_encode",
1610            Self::SeriesStrDecode => "series_str_decode",
1611            Self::SeriesStrTranslate => "series_str_translate",
1612            Self::SeriesStrExpandtabs => "series_str_expandtabs",
1613            Self::SeriesStrIndexOf => "series_str_index_of",
1614            Self::SeriesStrRindexOf => "series_str_rindex_of",
1615            Self::SeriesStrSplitCount => "series_str_split_count",
1616            Self::SeriesStrRsplitGet => "series_str_rsplit_get",
1617            Self::SeriesStrSplitRegexGet => "series_str_split_regex_get",
1618            Self::SeriesStrCountMatches => "series_str_count_matches",
1619            Self::SeriesStrCountLiteral => "series_str_count_literal",
1620            Self::SeriesStrFindall => "series_str_findall",
1621            Self::SeriesStrContainsAny => "series_str_contains_any",
1622            Self::SeriesStrStartswithAny => "series_str_startswith_any",
1623            Self::SeriesStrEndswithAny => "series_str_endswith_any",
1624            Self::SeriesDtYear => "series_dt_year",
1625            Self::SeriesDtMonth => "series_dt_month",
1626            Self::SeriesDtDay => "series_dt_day",
1627            Self::SeriesDtHour => "series_dt_hour",
1628            Self::SeriesDtMinute => "series_dt_minute",
1629            Self::SeriesDtSecond => "series_dt_second",
1630            Self::SeriesDtMicrosecond => "series_dt_microsecond",
1631            Self::SeriesDtNanosecond => "series_dt_nanosecond",
1632            Self::SeriesDtDayofweek => "series_dt_dayofweek",
1633            Self::SeriesDtQuarter => "series_dt_quarter",
1634            Self::SeriesDtDayofyear => "series_dt_dayofyear",
1635            Self::SeriesDtWeekofyear => "series_dt_weekofyear",
1636            Self::SeriesDtIsMonthStart => "series_dt_is_month_start",
1637            Self::SeriesDtIsMonthEnd => "series_dt_is_month_end",
1638            Self::SeriesDtIsYearStart => "series_dt_is_year_start",
1639            Self::SeriesDtIsYearEnd => "series_dt_is_year_end",
1640            Self::SeriesDtDate => "series_dt_date",
1641            Self::SeriesDtDaysInMonth => "series_dt_days_in_month",
1642            Self::SeriesDtIsLeapYear => "series_dt_is_leap_year",
1643            Self::SeriesDtIsQuarterStart => "series_dt_is_quarter_start",
1644            Self::SeriesDtIsQuarterEnd => "series_dt_is_quarter_end",
1645            Self::SeriesDtStrftime => "series_dt_strftime",
1646            Self::SeriesDtTzConvert => "series_dt_tz_convert",
1647            Self::SeriesDtTzLocalize => "series_dt_tz_localize",
1648            Self::SeriesDtTimetz => "series_dt_timetz",
1649            Self::SeriesDtFloor => "series_dt_floor",
1650            Self::SeriesDtToPeriod => "series_dt_to_period",
1651            Self::SeriesDtCeil => "series_dt_ceil",
1652            Self::SeriesDtRound => "series_dt_round",
1653            Self::SeriesDtMonthName => "series_dt_month_name",
1654            Self::SeriesDtDayName => "series_dt_day_name",
1655            Self::SeriesDtTotalSeconds => "series_dt_total_seconds",
1656            Self::SeriesDtDays => "series_dt_days",
1657            Self::SeriesDtSeconds => "series_dt_seconds",
1658            Self::SeriesDtMicroseconds => "series_dt_microseconds",
1659            Self::SeriesDtNanoseconds => "series_dt_nanoseconds",
1660            Self::SeriesDtToTimestamp => "series_dt_to_timestamp",
1661            Self::SeriesDtToPydatetime => "series_dt_to_pydatetime",
1662            Self::SeriesDtToPytimedelta => "series_dt_to_pytimedelta",
1663            Self::DataFrameLoc => "dataframe_loc",
1664            Self::DataFrameIdentity => "dataframe_identity",
1665            Self::DataFrameIloc => "dataframe_iloc",
1666            Self::DataFrameTake => "dataframe_take",
1667            Self::DataFrameFilter => "dataframe_filter",
1668            Self::DataFrameGroupBySum => "dataframe_groupby_sum",
1669            Self::DataFrameGroupByAggMulti => "dataframe_groupby_agg_multi",
1670            Self::DataFrameGroupByIdxMin => "dataframe_groupby_idxmin",
1671            Self::DataFrameGroupByIdxMax => "dataframe_groupby_idxmax",
1672            Self::DataFrameGroupByAny => "dataframe_groupby_any",
1673            Self::DataFrameGroupByAll => "dataframe_groupby_all",
1674            Self::DataFrameGroupByGetGroup => "dataframe_groupby_get_group",
1675            Self::DataFrameGroupByFfill => "dataframe_groupby_ffill",
1676            Self::DataFrameGroupByBfill => "dataframe_groupby_bfill",
1677            Self::DataFrameGroupBySem => "dataframe_groupby_sem",
1678            Self::DataFrameGroupBySkew => "dataframe_groupby_skew",
1679            Self::DataFrameGroupByKurtosis => "dataframe_groupby_kurtosis",
1680            Self::DataFrameGroupByOhlc => "dataframe_groupby_ohlc",
1681            Self::DataFrameGroupByCumcount => "dataframe_groupby_cumcount",
1682            Self::DataFrameGroupByNgroup => "dataframe_groupby_ngroup",
1683            Self::DataFrameGroupByRollingMean => "dataframe_groupby_rolling_mean",
1684            Self::DataFrameGroupByRollingSum => "dataframe_groupby_rolling_sum",
1685            Self::DataFrameGroupByRollingMin => "dataframe_groupby_rolling_min",
1686            Self::DataFrameGroupByRollingMax => "dataframe_groupby_rolling_max",
1687            Self::DataFrameGroupByRollingCount => "dataframe_groupby_rolling_count",
1688            Self::DataFrameGroupByRollingStd => "dataframe_groupby_rolling_std",
1689            Self::DataFrameGroupByRollingVar => "dataframe_groupby_rolling_var",
1690            Self::DataFrameGroupByResampleMin => "dataframe_groupby_resample_min",
1691            Self::DataFrameGroupByResampleMax => "dataframe_groupby_resample_max",
1692            Self::DataFrameGroupByResampleCount => "dataframe_groupby_resample_count",
1693            Self::DataFrameGroupByResampleFirst => "dataframe_groupby_resample_first",
1694            Self::DataFrameGroupByResampleLast => "dataframe_groupby_resample_last",
1695            Self::DataFrameAsof => "dataframe_asof",
1696            Self::DataFrameAtTime => "dataframe_at_time",
1697            Self::DataFrameBetweenTime => "dataframe_between_time",
1698            Self::DataFrameBool => "dataframe_bool",
1699            Self::DataFrameHead => "dataframe_head",
1700            Self::DataFrameTail => "dataframe_tail",
1701            Self::DataFrameEval => "dataframe_eval",
1702            Self::DataFrameCompare => "dataframe_compare",
1703            Self::DataFrameExplode => "dataframe_explode",
1704            Self::DataFrameQuery => "dataframe_query",
1705            Self::DataFrameXs => "dataframe_xs",
1706            Self::DataFrameIsNa => "dataframe_isna",
1707            Self::DataFrameNotNa => "dataframe_notna",
1708            Self::DataFrameIsNull => "dataframe_isnull",
1709            Self::DataFrameNotNull => "dataframe_notnull",
1710            Self::DataFrameCount => "dataframe_count",
1711            Self::DataFrameMode => "dataframe_mode",
1712            Self::DataFrameRank => "dataframe_rank",
1713            Self::DataFrameFillNa => "dataframe_fillna",
1714            Self::DataFrameDropNa => "dataframe_dropna",
1715            Self::DataFrameDropNaColumns => "dataframe_dropna_columns",
1716            Self::DataFrameSetIndex => "dataframe_set_index",
1717            Self::DataFrameResetIndex => "dataframe_reset_index",
1718            Self::DataFrameInsert => "dataframe_insert",
1719            Self::DataFrameAssign => "dataframe_assign",
1720            Self::DataFrameRenameColumns => "dataframe_rename_columns",
1721            Self::DataFrameReindex => "dataframe_reindex",
1722            Self::DataFrameReindexColumns => "dataframe_reindex_columns",
1723            Self::DataFrameDropColumns => "dataframe_drop_columns",
1724            Self::DataFrameReplace => "dataframe_replace",
1725            Self::DataFrameWhere => "dataframe_where",
1726            Self::DataFrameWhereDf => "dataframe_where_df",
1727            Self::DataFrameMask => "dataframe_mask",
1728            Self::DataFrameMaskDf => "dataframe_mask_df",
1729            Self::DataFrameDuplicated => "dataframe_duplicated",
1730            Self::DataFrameDropDuplicates => "dataframe_drop_duplicates",
1731            Self::DataFrameSortIndex => "dataframe_sort_index",
1732            Self::DataFrameSortValues => "dataframe_sort_values",
1733            Self::DataFrameNlargest => "dataframe_nlargest",
1734            Self::DataFrameNsmallest => "dataframe_nsmallest",
1735            Self::DataFrameDiff => "dataframe_diff",
1736            Self::DataFrameShift => "dataframe_shift",
1737            Self::DataFramePctChange => "dataframe_pct_change",
1738            Self::DataFrameMelt => "dataframe_melt",
1739            Self::DataFramePivot => "dataframe_pivot",
1740            Self::DataFramePivotTable => "dataframe_pivot_table",
1741            Self::DataFrameStack => "dataframe_stack",
1742            Self::DataFrameTranspose => "dataframe_transpose",
1743            Self::DataFrameCrosstab => "dataframe_crosstab",
1744            Self::DataFrameCrosstabNormalize => "dataframe_crosstab_normalize",
1745            Self::DataFrameGetDummies => "dataframe_get_dummies",
1746            Self::DataFrameMerge => "dataframe_merge",
1747            Self::DataFrameMergeIndex => "dataframe_merge_index",
1748            Self::DataFrameMergeAsof => "dataframe_merge_asof",
1749            Self::DataFrameMergeOrdered => "dataframe_merge_ordered",
1750            Self::DataFrameConcat => "dataframe_concat",
1751            Self::DataFrameCombineFirst => "dataframe_combine_first",
1752            Self::GroupByMean => "groupby_mean",
1753            Self::GroupByCount => "groupby_count",
1754            Self::GroupByMin => "groupby_min",
1755            Self::GroupByMax => "groupby_max",
1756            Self::GroupByFirst => "groupby_first",
1757            Self::GroupByLast => "groupby_last",
1758            Self::GroupByStd => "groupby_std",
1759            Self::GroupByVar => "groupby_var",
1760            Self::GroupByMedian => "groupby_median",
1761            Self::SeriesDiff => "series_diff",
1762            Self::SeriesShift => "series_shift",
1763            Self::SeriesPctChange => "series_pct_change",
1764            Self::SeriesRollingMean => "series_rolling_mean",
1765            Self::SeriesRollingSum => "series_rolling_sum",
1766            Self::SeriesRollingStd => "series_rolling_std",
1767            Self::SeriesRollingMin => "series_rolling_min",
1768            Self::SeriesRollingMax => "series_rolling_max",
1769            Self::SeriesRollingVar => "series_rolling_var",
1770            Self::SeriesRollingCount => "series_rolling_count",
1771            Self::SeriesExpandingCount => "series_expanding_count",
1772            Self::SeriesExpandingQuantile => "series_expanding_quantile",
1773            Self::SeriesExpandingSum => "series_expanding_sum",
1774            Self::SeriesExpandingMean => "series_expanding_mean",
1775            Self::SeriesExpandingMin => "series_expanding_min",
1776            Self::SeriesExpandingMax => "series_expanding_max",
1777            Self::SeriesExpandingStd => "series_expanding_std",
1778            Self::SeriesExpandingVar => "series_expanding_var",
1779            Self::SeriesEwmMean => "series_ewm_mean",
1780            Self::SeriesResampleSum => "series_resample_sum",
1781            Self::SeriesResampleMean => "series_resample_mean",
1782            Self::SeriesResampleCount => "series_resample_count",
1783            Self::SeriesResampleAsfreq => "series_resample_asfreq",
1784            Self::SeriesResampleFfill => "series_resample_ffill",
1785            Self::SeriesResampleBfill => "series_resample_bfill",
1786            Self::DataFrameRollingMean => "dataframe_rolling_mean",
1787            Self::DataFrameResampleSum => "dataframe_resample_sum",
1788            Self::DataFrameResampleMean => "dataframe_resample_mean",
1789            Self::DataFrameToJsonRecords => "dataframe_to_json_records",
1790        }
1791    }
1792}
1793
1794#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1795#[serde(rename_all = "snake_case")]
1796pub enum FixtureJoinType {
1797    Inner,
1798    Left,
1799    Right,
1800    Outer,
1801    Cross,
1802}
1803
1804impl FixtureJoinType {
1805    #[must_use]
1806    pub fn into_join_type(self) -> JoinType {
1807        match self {
1808            Self::Inner => JoinType::Inner,
1809            Self::Left => JoinType::Left,
1810            Self::Right => JoinType::Right,
1811            Self::Outer => JoinType::Outer,
1812            Self::Cross => JoinType::Cross,
1813        }
1814    }
1815}
1816
1817#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1818#[serde(rename_all = "snake_case")]
1819pub enum FixtureOracleSource {
1820    Fixture,
1821    LiveLegacyPandas,
1822}
1823
1824/// Per-fixture conformance requirement level, mirroring RFC 2119
1825/// conventions (MUST / SHOULD / MAY).
1826///
1827/// Per br-frankenpandas-nato. A fixture tagged `Must` represents a
1828/// contract clause we ship only if the test passes. `Should` is a
1829/// strong preference; regressions are warnings but not ship-blockers.
1830/// `May` is optional behavior that divergence gets documented in
1831/// DISCREPANCIES.md rather than blocking a release.
1832///
1833/// Fixtures without an explicit tag default to `Must` (the most
1834/// conservative assumption) via `RequirementLevel::default()`.
1835#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1836#[serde(rename_all = "snake_case")]
1837#[non_exhaustive]
1838pub enum RequirementLevel {
1839    #[default]
1840    Must,
1841    Should,
1842    May,
1843}
1844
1845#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1846#[serde(deny_unknown_fields)]
1847pub struct FixtureSeries {
1848    pub name: String,
1849    pub index: Vec<IndexLabel>,
1850    pub values: Vec<Scalar>,
1851}
1852
1853#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1854#[serde(deny_unknown_fields)]
1855pub struct FixtureExpectedSeries {
1856    pub index: Vec<IndexLabel>,
1857    pub values: Vec<Scalar>,
1858    /// The result series' NAME, when the fixture pins one.
1859    ///
1860    /// br-frankenpandas-xi5li. This field did not exist, so the 28 fixtures that
1861    /// carry a `name` key had it dropped at deserialization and then, of course,
1862    /// never compared — dead twice over. The input struct immediately above has
1863    /// carried `pub name: String` all along, so a fixture could state the name it
1864    /// fed in and not the name it expected back.
1865    ///
1866    /// `Option` + `serde(default)` because ~569 fixtures legitimately omit it and
1867    /// must keep meaning "not asserted" rather than "asserted absent".
1868    #[serde(default)]
1869    pub name: Option<String>,
1870}
1871
1872#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1873#[serde(deny_unknown_fields)]
1874pub struct FixtureDataFrame {
1875    pub index: Vec<IndexLabel>,
1876    /// Column data, plus the order the fixture WROTE the columns in.
1877    ///
1878    /// A plain `BTreeMap` here sorted the names, so a frame whose JSON reads
1879    /// `{lk1, lk2, left_v}` was handed to FrankenPandas as `left_v, lk1, lk2`
1880    /// while the oracle — a Python dict, which preserves document order — got
1881    /// the original. The two sides were being given different frames.
1882    /// (br-frankenpandas-i9mgp)
1883    pub columns: OrderedColumnData,
1884    #[serde(default)]
1885    pub column_order: Option<Vec<String>>,
1886    #[serde(default)]
1887    pub categorical_columns: Option<BTreeMap<String, FixtureCategoricalColumn>>,
1888    #[serde(default)]
1889    pub row_multiindex: Option<FixtureMultiIndex>,
1890}
1891
1892#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1893#[serde(deny_unknown_fields)]
1894pub struct FixtureCategoricalColumn {
1895    pub categories: Vec<Scalar>,
1896    #[serde(default)]
1897    pub ordered: Option<bool>,
1898}
1899
1900/// `{column: [func, ...]}` in the order the fixture wrote it.
1901///
1902/// Ordered pairs rather than a map, so the request order pandas' agg column axis
1903/// follows survives deserialization. (br-frankenpandas-nv5ct)
1904pub type OrderedFuncMap = Vec<(String, Vec<String>)>;
1905
1906/// A fixture frame's `columns` object, keeping the order the fixture wrote.
1907///
1908/// Derefs to the `BTreeMap` it wraps, so every existing `.columns.get(..)` /
1909/// `.keys()` / `.len()` / iteration site is unchanged; the only new capability
1910/// is [`Self::document_order`], which `resolve_frame_column_order` consults
1911/// instead of the sorted keys.
1912///
1913/// WHY THE MAP IS STILL THERE: name lookup is what the harness does with this
1914/// everywhere else, and a fixture that repeats a column name is a separate
1915/// question owned by br-frankenpandas-ih4t0. This type records order without
1916/// claiming to represent duplicates — `document_order` therefore lists each
1917/// name once, at its first occurrence. (br-frankenpandas-i9mgp)
1918#[derive(Debug, Clone, Default, PartialEq)]
1919pub struct OrderedColumnData {
1920    map: BTreeMap<String, Vec<Scalar>>,
1921    order: Vec<String>,
1922}
1923
1924impl OrderedColumnData {
1925    /// Column names in the order the fixture's JSON listed them.
1926    #[must_use]
1927    pub fn document_order(&self) -> &[String] {
1928        &self.order
1929    }
1930}
1931
1932impl std::ops::Deref for OrderedColumnData {
1933    type Target = BTreeMap<String, Vec<Scalar>>;
1934
1935    fn deref(&self) -> &Self::Target {
1936        &self.map
1937    }
1938}
1939
1940impl From<BTreeMap<String, Vec<Scalar>>> for OrderedColumnData {
1941    fn from(map: BTreeMap<String, Vec<Scalar>>) -> Self {
1942        let order = map.keys().cloned().collect();
1943        Self { map, order }
1944    }
1945}
1946
1947impl Serialize for OrderedColumnData {
1948    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1949        use serde::ser::SerializeMap;
1950        // Written back in DOCUMENT order so a re-banked fixture keeps the
1951        // spelling it came in with rather than being silently re-sorted.
1952        let mut map = serializer.serialize_map(Some(self.order.len()))?;
1953        for name in &self.order {
1954            if let Some(values) = self.map.get(name) {
1955                map.serialize_entry(name, values)?;
1956            }
1957        }
1958        map.end()
1959    }
1960}
1961
1962impl<'de> Deserialize<'de> for OrderedColumnData {
1963    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1964        struct Visitor;
1965
1966        impl<'de> serde::de::Visitor<'de> for Visitor {
1967            type Value = OrderedColumnData;
1968
1969            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
1970                formatter.write_str("a map of column name to values")
1971            }
1972
1973            fn visit_map<A>(self, mut access: A) -> Result<Self::Value, A::Error>
1974            where
1975                A: serde::de::MapAccess<'de>,
1976            {
1977                let mut map = BTreeMap::new();
1978                let mut order = Vec::with_capacity(access.size_hint().unwrap_or(0));
1979                while let Some((name, values)) = access.next_entry::<String, Vec<Scalar>>()? {
1980                    if map.insert(name.clone(), values).is_none() {
1981                        order.push(name);
1982                    }
1983                }
1984                Ok(OrderedColumnData { map, order })
1985            }
1986        }
1987
1988        deserializer.deserialize_map(Visitor)
1989    }
1990}
1991
1992/// Read a `{column: [func, ...]}` JSON object into ordered pairs.
1993///
1994/// `serde_json` streams an object to a `MapAccess` visitor in DOCUMENT order, so
1995/// collecting the entries here preserves what the fixture wrote — which
1996/// `BTreeMap` (sorted) and `HashMap` (arbitrary) both destroy. That order is
1997/// load-bearing: pandas' `agg(dict-of-lists)` column axis follows the request,
1998/// so `{'y': [...], 'x': [...]}` must not come back x-first.
1999/// (br-frankenpandas-nv5ct)
2000fn deserialize_ordered_func_map<'de, D>(deserializer: D) -> Result<Option<OrderedFuncMap>, D::Error>
2001where
2002    D: serde::Deserializer<'de>,
2003{
2004    struct OrderedFuncMapVisitor;
2005
2006    impl<'de> serde::de::Visitor<'de> for OrderedFuncMapVisitor {
2007        type Value = Option<OrderedFuncMap>;
2008
2009        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
2010            formatter.write_str("a map of column name to list of aggregation names")
2011        }
2012
2013        fn visit_none<E>(self) -> Result<Self::Value, E> {
2014            Ok(None)
2015        }
2016
2017        fn visit_unit<E>(self) -> Result<Self::Value, E> {
2018            Ok(None)
2019        }
2020
2021        fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
2022        where
2023            D: serde::Deserializer<'de>,
2024        {
2025            deserializer.deserialize_map(OrderedFuncMapVisitor)
2026        }
2027
2028        fn visit_map<A>(self, mut access: A) -> Result<Self::Value, A::Error>
2029        where
2030            A: serde::de::MapAccess<'de>,
2031        {
2032            let mut pairs = Vec::with_capacity(access.size_hint().unwrap_or(0));
2033            while let Some((column, funcs)) = access.next_entry::<String, Vec<String>>()? {
2034                pairs.push((column, funcs));
2035            }
2036            Ok(Some(pairs))
2037        }
2038    }
2039
2040    deserializer.deserialize_option(OrderedFuncMapVisitor)
2041}
2042
2043fn serialize_ordered_func_map<S>(
2044    value: &Option<OrderedFuncMap>,
2045    serializer: S,
2046) -> Result<S::Ok, S::Error>
2047where
2048    S: serde::Serializer,
2049{
2050    use serde::ser::SerializeMap as _;
2051    match value {
2052        None => serializer.serialize_none(),
2053        Some(pairs) => {
2054            let mut map = serializer.serialize_map(Some(pairs.len()))?;
2055            for (col, funcs) in pairs {
2056                map.serialize_entry(col, funcs)?;
2057            }
2058            map.end()
2059        }
2060    }
2061}
2062
2063#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2064#[serde(deny_unknown_fields)]
2065pub struct FixtureMultiIndex {
2066    pub tuples: Vec<Vec<IndexLabel>>,
2067    #[serde(default)]
2068    pub names: Vec<Option<String>>,
2069}
2070
2071#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2072#[serde(deny_unknown_fields)]
2073pub struct FixtureExpectedDataFrame {
2074    pub index: Vec<IndexLabel>,
2075    pub columns: BTreeMap<String, Vec<Scalar>>,
2076    #[serde(default)]
2077    pub column_order: Option<Vec<String>>,
2078    #[serde(default)]
2079    pub row_multiindex: Option<FixtureMultiIndex>,
2080    /// The COLUMN axis when pandas returns more than one level, e.g.
2081    /// `df.groupby(k).agg({'x': ['sum','mean']})` -> `[('x','sum'),('x','mean')]`.
2082    ///
2083    /// Absent means a flat axis, so every existing fixture keeps its meaning.
2084    /// Without this key the format could not express pandas' answer for the
2085    /// dict-of-lists agg at all, which is why `fp_p2d_430` diverged as a column
2086    /// SET mismatch against stringified tuples. (br-frankenpandas-nv5ct)
2087    #[serde(default)]
2088    pub column_multiindex: Option<FixtureMultiIndex>,
2089}
2090
2091#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2092#[serde(deny_unknown_fields)]
2093pub struct FixtureColumnAssignment {
2094    pub name: String,
2095    pub values: Vec<Scalar>,
2096}
2097
2098#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2099#[serde(deny_unknown_fields)]
2100pub struct FixtureColumnRename {
2101    pub from: String,
2102    pub to: String,
2103}
2104
2105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2106#[serde(deny_unknown_fields)]
2107pub struct FixtureExpectedAlignment {
2108    pub union_index: Vec<IndexLabel>,
2109    pub left_positions: Vec<Option<usize>>,
2110    pub right_positions: Vec<Option<usize>>,
2111}
2112
2113#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2114#[serde(deny_unknown_fields)]
2115pub struct FixtureExpectedJoin {
2116    pub index: Vec<IndexLabel>,
2117    pub left_values: Vec<Scalar>,
2118    pub right_values: Vec<Scalar>,
2119}
2120
2121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2122#[serde(deny_unknown_fields)]
2123pub struct FixtureProvenance {
2124    pub pandas_version: String,
2125    pub oracle_script_sha256: String,
2126    pub generated_at: String,
2127    #[serde(default, skip_serializing_if = "Option::is_none")]
2128    pub generation_command: Option<String>,
2129    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2130    pub input_matrix: Vec<String>,
2131    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2132    pub intentional_divergence_notes: Vec<String>,
2133    #[serde(default, skip_serializing_if = "Option::is_none")]
2134    pub oracle_attestation: Option<String>,
2135}
2136
2137/// Why a fixture was retired, recorded in the fixture itself.
2138///
2139/// br-frankenpandas-fixture-corpus-stale-vs-oracle-p6srr. The reason is
2140/// mandatory: a retirement without one is indistinguishable from a fixture
2141/// someone quietly disabled.
2142#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2143#[serde(deny_unknown_fields)]
2144pub struct FixtureRetirement {
2145    pub reason: String,
2146    #[serde(default)]
2147    pub retired_at: Option<String>,
2148    #[serde(default)]
2149    pub bead: Option<String>,
2150}
2151
2152#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2153#[serde(deny_unknown_fields)]
2154pub struct PacketFixture {
2155    pub packet_id: String,
2156    pub case_id: String,
2157    pub mode: RuntimeMode,
2158    pub operation: FixtureOperation,
2159    #[serde(default)]
2160    pub fixture_provenance: Option<FixtureProvenance>,
2161    /// Present when this fixture has been RETIRED, per
2162    /// br-frankenpandas-fixture-corpus-stale-vs-oracle-p6srr. Written by
2163    /// `scripts/regenerate_fixtures.py --apply` for fixtures whose operation the
2164    /// oracle no longer supports. The fixture keeps its expected values — it
2165    /// stops claiming to be regenerable, it does not stop being evidence.
2166    #[serde(default)]
2167    pub retired: Option<FixtureRetirement>,
2168    #[serde(default)]
2169    pub oracle_source: Option<FixtureOracleSource>,
2170    /// Conformance requirement level (MUST / SHOULD / MAY). Per
2171    /// br-frankenpandas-nato. Absence in fixture JSON deserializes to
2172    /// `None`, which the comparator treats as `Must` (conservative
2173    /// default). Populating this across the 1,249-fixture corpus is
2174    /// Phase 3 of the nato tracker.
2175    #[serde(default)]
2176    pub requirement_level: Option<RequirementLevel>,
2177    #[serde(default)]
2178    pub left: Option<FixtureSeries>,
2179    #[serde(default)]
2180    pub right: Option<FixtureSeries>,
2181    #[serde(default)]
2182    pub groupby_keys: Option<Vec<FixtureSeries>>,
2183    #[serde(default)]
2184    pub groupby_columns: Option<Vec<String>>,
2185    #[serde(default)]
2186    pub groupby_observed: Option<bool>,
2187    /// `{column: [func, ...]}` in the order the FIXTURE WROTE IT.
2188    ///
2189    /// Ordered pairs, not a `BTreeMap`: pandas' agg column axis follows the
2190    /// request order, and a `BTreeMap` sorts the keys, so the format itself
2191    /// could not express the request. Deserialized from the same JSON object
2192    /// shape as before via `deserialize_ordered_func_map`, so no fixture file
2193    /// changes. (br-frankenpandas-nv5ct)
2194    #[serde(
2195        default,
2196        deserialize_with = "deserialize_ordered_func_map",
2197        serialize_with = "serialize_ordered_func_map"
2198    )]
2199    pub groupby_agg_multi: Option<OrderedFuncMap>,
2200    #[serde(default)]
2201    pub frame: Option<FixtureDataFrame>,
2202    #[serde(default)]
2203    pub expr: Option<String>,
2204    #[serde(default)]
2205    pub locals: Option<BTreeMap<String, Scalar>>,
2206    #[serde(default)]
2207    pub frame_right: Option<FixtureDataFrame>,
2208    #[serde(default)]
2209    pub frame_other: Option<FixtureDataFrame>,
2210    #[serde(default)]
2211    pub dict_columns: Option<BTreeMap<String, Vec<Scalar>>>,
2212    #[serde(default)]
2213    pub column_order: Option<Vec<String>>,
2214    #[serde(default)]
2215    pub constructor_dtype: Option<String>,
2216    #[serde(default)]
2217    pub constructor_copy: Option<bool>,
2218    #[serde(default)]
2219    pub records: Option<Vec<BTreeMap<String, Scalar>>>,
2220    #[serde(default)]
2221    pub matrix_rows: Option<Vec<Vec<Scalar>>>,
2222    #[serde(default)]
2223    pub index: Option<Vec<IndexLabel>>,
2224    #[serde(default)]
2225    pub join_type: Option<FixtureJoinType>,
2226    #[serde(default)]
2227    pub merge_on: Option<String>,
2228    #[serde(default)]
2229    pub merge_on_keys: Option<Vec<String>>,
2230    #[serde(default)]
2231    pub left_on_keys: Option<Vec<String>>,
2232    #[serde(default)]
2233    pub right_on_keys: Option<Vec<String>>,
2234    #[serde(default)]
2235    pub left_index: Option<bool>,
2236    #[serde(default)]
2237    pub right_index: Option<bool>,
2238    #[serde(default)]
2239    pub merge_indicator: Option<bool>,
2240    #[serde(default)]
2241    pub merge_indicator_name: Option<String>,
2242    #[serde(default)]
2243    pub merge_validate: Option<String>,
2244    #[serde(default)]
2245    pub merge_suffixes: Option<[Option<String>; 2]>,
2246    #[serde(default)]
2247    pub merge_sort: Option<bool>,
2248    #[serde(default)]
2249    pub compare_result_names: Option<[String; 2]>,
2250    #[serde(default)]
2251    pub expected_series: Option<FixtureExpectedSeries>,
2252    #[serde(default)]
2253    pub expected_join: Option<FixtureExpectedJoin>,
2254    #[serde(default)]
2255    pub expected_frame: Option<FixtureExpectedDataFrame>,
2256    #[serde(default)]
2257    pub expected_error_contains: Option<String>,
2258    #[serde(default)]
2259    pub expected_alignment: Option<FixtureExpectedAlignment>,
2260    #[serde(default)]
2261    pub expected_bool: Option<bool>,
2262    #[serde(default)]
2263    pub expected_positions: Option<Vec<Option<usize>>>,
2264    #[serde(default)]
2265    pub expected_scalar: Option<Scalar>,
2266    #[serde(default)]
2267    pub expected_dtype: Option<String>,
2268    #[serde(default)]
2269    pub datetime_unit: Option<String>,
2270    #[serde(default)]
2271    pub datetime_origin: Option<serde_json::Value>,
2272    #[serde(default)]
2273    pub datetime_utc: Option<bool>,
2274    #[serde(default)]
2275    pub fill_value: Option<Scalar>,
2276    #[serde(default)]
2277    pub clip_lower: Option<f64>,
2278    #[serde(default)]
2279    pub clip_upper: Option<f64>,
2280    #[serde(default)]
2281    pub clip_lower_series: Option<FixtureSeries>,
2282    #[serde(default)]
2283    pub clip_upper_series: Option<FixtureSeries>,
2284    #[serde(default)]
2285    pub round_decimals: Option<i32>,
2286    #[serde(default)]
2287    pub dataframe_binary_method: Option<String>,
2288    #[serde(default)]
2289    pub nlargest_n: Option<usize>,
2290    #[serde(default)]
2291    pub between_left: Option<Scalar>,
2292    #[serde(default)]
2293    pub between_right: Option<Scalar>,
2294    #[serde(default)]
2295    pub between_inclusive: Option<String>,
2296    #[serde(default)]
2297    pub head_n: Option<i64>,
2298    #[serde(default)]
2299    pub tail_n: Option<i64>,
2300    #[serde(default)]
2301    pub diff_periods: Option<i64>,
2302    #[serde(default)]
2303    pub shift_periods: Option<i64>,
2304    #[serde(default)]
2305    pub shift_axis: Option<usize>,
2306    #[serde(default)]
2307    pub pct_change_periods: Option<i64>,
2308    #[serde(default)]
2309    pub pct_change_axis: Option<usize>,
2310    #[serde(default)]
2311    pub mode_dropna: Option<bool>,
2312    #[serde(default)]
2313    pub idxmin_skipna: Option<bool>,
2314    #[serde(default)]
2315    pub idxmax_skipna: Option<bool>,
2316    #[serde(default)]
2317    pub argmin_skipna: Option<bool>,
2318    #[serde(default)]
2319    pub argmax_skipna: Option<bool>,
2320    #[serde(default)]
2321    pub searchsorted_value: Option<Scalar>,
2322    #[serde(default)]
2323    pub searchsorted_side: Option<String>,
2324    #[serde(default)]
2325    pub autocorr_lag: Option<usize>,
2326    #[serde(default)]
2327    pub diff_axis: Option<usize>,
2328    #[serde(default)]
2329    pub rank_method: Option<String>,
2330    #[serde(default)]
2331    pub rank_na_option: Option<String>,
2332    #[serde(default)]
2333    pub rank_axis: Option<usize>,
2334    #[serde(default)]
2335    pub rank_pct: Option<bool>,
2336    #[serde(default)]
2337    pub corr_method: Option<String>,
2338    #[serde(default)]
2339    pub corr_min_periods: Option<usize>,
2340    #[serde(default)]
2341    pub corr_numeric_only: Option<bool>,
2342    /// pandas 2.x `numeric_only` for the DataFrame reduction family.
2343    /// Absent = pandas' own default, which is what every fixture predating
2344    /// br-frankenpandas-reductions-numeric-only-default-zx21n relies on.
2345    /// Paired with the oracle's `reduction_numeric_only_kwargs`, so a
2346    /// fixture states the path once and BOTH sides honour it — an option
2347    /// only one side reads is the latent defect 9s0c4 catalogued.
2348    #[serde(default)]
2349    pub sum_numeric_only: Option<bool>,
2350    #[serde(default)]
2351    pub mean_numeric_only: Option<bool>,
2352    #[serde(default)]
2353    pub min_numeric_only: Option<bool>,
2354    #[serde(default)]
2355    pub max_numeric_only: Option<bool>,
2356    #[serde(default)]
2357    pub prod_numeric_only: Option<bool>,
2358    #[serde(default)]
2359    pub median_numeric_only: Option<bool>,
2360    #[serde(default)]
2361    pub std_numeric_only: Option<bool>,
2362    #[serde(default)]
2363    pub var_numeric_only: Option<bool>,
2364    #[serde(default)]
2365    pub sem_numeric_only: Option<bool>,
2366    #[serde(default)]
2367    pub skew_numeric_only: Option<bool>,
2368    #[serde(default)]
2369    pub kurtosis_numeric_only: Option<bool>,
2370    #[serde(default)]
2371    pub count_numeric_only: Option<bool>,
2372    #[serde(default)]
2373    pub quantile_numeric_only: Option<bool>,
2374    #[serde(default)]
2375    pub sort_column: Option<String>,
2376    #[serde(default)]
2377    pub sort_ascending: Option<bool>,
2378    // br-frankenpandas-l7r1p: `series_sort_values` fixtures could declare
2379    // `sort_ascending` but not a na_position, so the oracle hardcoded
2380    // na_position="last" and a fixture exercising "first" could not be
2381    // expressed at all -- it deserialized as an unknown field and panicked.
2382    #[serde(default)]
2383    pub sort_na_position: Option<String>,
2384    #[serde(default)]
2385    pub value_counts_normalize: Option<bool>,
2386    // br-frankenpandas-l7r1p: same for `dropna`, which the oracle pinned True.
2387    #[serde(default)]
2388    pub value_counts_dropna: Option<bool>,
2389    // br-frankenpandas-l7r1p: `op_series_to_frame` has always READ `frame_name`;
2390    // no fixture could set it because the field did not exist here.
2391    #[serde(default)]
2392    pub frame_name: Option<String>,
2393    #[serde(default)]
2394    pub memory_usage_index: Option<bool>,
2395    #[serde(default)]
2396    pub memory_usage_deep: Option<bool>,
2397    #[serde(default)]
2398    pub concat_axis: Option<i64>,
2399    #[serde(default)]
2400    pub concat_join: Option<String>,
2401    #[serde(default)]
2402    pub direction: Option<String>,
2403    /// For merge_asof: allow matching with same key value (default true)
2404    #[serde(default)]
2405    pub allow_exact_matches: Option<bool>,
2406    /// For merge_asof: maximum distance between keys for a match
2407    #[serde(default)]
2408    pub tolerance: Option<f64>,
2409    /// For merge_asof: columns to match exactly before asof matching
2410    #[serde(default, rename = "by")]
2411    pub merge_asof_by: Option<Vec<String>>,
2412    #[serde(default)]
2413    pub merge_fill_method: Option<String>,
2414    #[serde(default)]
2415    pub set_index_column: Option<String>,
2416    #[serde(default)]
2417    pub set_index_drop: Option<bool>,
2418    #[serde(default)]
2419    pub set_index_verify_integrity: Option<bool>,
2420    #[serde(default)]
2421    pub reset_index_drop: Option<bool>,
2422    #[serde(default)]
2423    pub insert_loc: Option<usize>,
2424    #[serde(default)]
2425    pub insert_column: Option<String>,
2426    #[serde(default)]
2427    pub insert_values: Option<Vec<Scalar>>,
2428    #[serde(default)]
2429    pub assignments: Option<Vec<FixtureColumnAssignment>>,
2430    #[serde(default)]
2431    pub rename_columns: Option<Vec<FixtureColumnRename>>,
2432    #[serde(default)]
2433    pub reindex_labels: Option<Vec<IndexLabel>>,
2434    #[serde(default)]
2435    pub reindex_columns: Option<Vec<String>>,
2436    #[serde(default)]
2437    pub drop_columns: Option<Vec<String>>,
2438    #[serde(default)]
2439    pub subset: Option<Vec<String>>,
2440    #[serde(default)]
2441    pub keep: Option<String>,
2442    #[serde(default)]
2443    pub ignore_index: Option<bool>,
2444    #[serde(default)]
2445    pub explode_column: Option<String>,
2446    #[serde(default)]
2447    pub csv_input: Option<String>,
2448    #[serde(default)]
2449    pub csv_decimal: Option<String>,
2450    #[serde(default)]
2451    pub csv_on_bad_lines: Option<String>,
2452    #[serde(default)]
2453    pub csv_parse_dates: Option<Vec<String>>,
2454    #[serde(default)]
2455    pub csv_parse_date_combinations: Option<Vec<Vec<String>>>,
2456    #[serde(default)]
2457    pub csv_true_values: Option<Vec<String>>,
2458    #[serde(default)]
2459    pub csv_false_values: Option<Vec<String>>,
2460    #[serde(default)]
2461    pub json_input: Option<String>,
2462    #[serde(default)]
2463    pub json_orient: Option<String>,
2464    #[serde(default)]
2465    pub jsonl_input: Option<String>,
2466    #[serde(default)]
2467    pub parquet_input_base64: Option<String>,
2468    #[serde(default)]
2469    pub feather_input_base64: Option<String>,
2470    #[serde(default)]
2471    pub excel_input_base64: Option<String>,
2472    #[serde(default)]
2473    pub ipc_stream_input_base64: Option<String>,
2474    #[serde(default)]
2475    pub loc_labels: Option<Vec<IndexLabel>>,
2476    #[serde(default)]
2477    pub iloc_positions: Option<Vec<i64>>,
2478    #[serde(default)]
2479    pub take_indices: Option<Vec<i64>>,
2480    #[serde(default)]
2481    pub filter_items: Option<Vec<String>>,
2482    #[serde(default)]
2483    pub filter_like: Option<String>,
2484    #[serde(default)]
2485    pub filter_regex: Option<String>,
2486    #[serde(default)]
2487    pub filter_axis: Option<usize>,
2488    #[serde(default)]
2489    pub repeat_n: Option<i64>,
2490    #[serde(default)]
2491    pub repeat_counts: Option<Vec<i64>>,
2492    #[serde(default)]
2493    pub group_name: Option<String>,
2494    #[serde(default)]
2495    pub xs_key: Option<IndexLabel>,
2496    #[serde(default)]
2497    pub xs_level: Option<usize>,
2498    #[serde(default)]
2499    pub cut_bins: Option<usize>,
2500    #[serde(default)]
2501    pub qcut_quantiles: Option<usize>,
2502    #[serde(default)]
2503    pub take_axis: Option<usize>,
2504    #[serde(default)]
2505    pub asof_label: Option<IndexLabel>,
2506    #[serde(default)]
2507    pub time_value: Option<String>,
2508    #[serde(default)]
2509    pub start_time: Option<String>,
2510    #[serde(default)]
2511    pub end_time: Option<String>,
2512    #[serde(default)]
2513    pub string_sep: Option<String>,
2514    #[serde(default)]
2515    pub regex_pattern: Option<String>,
2516    #[serde(default)]
2517    pub replace_value: Option<String>,
2518    #[serde(default)]
2519    pub str_width: Option<usize>,
2520    #[serde(default)]
2521    pub str_fillchar: Option<char>,
2522    #[serde(default)]
2523    pub str_pad_side: Option<String>,
2524    #[serde(default)]
2525    pub str_sub: Option<String>,
2526    #[serde(default)]
2527    pub str_slice_start: Option<i64>,
2528    #[serde(default)]
2529    pub str_slice_end: Option<i64>,
2530    #[serde(default)]
2531    pub str_slice_step: Option<i64>,
2532    #[serde(default)]
2533    pub str_get_index: Option<i64>,
2534    #[serde(default)]
2535    pub str_repeat_n: Option<usize>,
2536    #[serde(default)]
2537    pub str_wrap_width: Option<usize>,
2538    #[serde(default)]
2539    pub str_wrap_drop_whitespace: Option<bool>,
2540    #[serde(default)]
2541    pub str_normalize_form: Option<String>,
2542    #[serde(default)]
2543    pub str_prefix: Option<String>,
2544    #[serde(default)]
2545    pub str_suffix: Option<String>,
2546    #[serde(default)]
2547    pub str_split_pat: Option<String>,
2548    #[serde(default)]
2549    pub str_split_n: Option<usize>,
2550    #[serde(default)]
2551    pub str_join_from: Option<String>,
2552    #[serde(default)]
2553    pub str_join_sep: Option<String>,
2554    #[serde(default)]
2555    pub str_translate_from: Option<String>,
2556    #[serde(default)]
2557    pub str_translate_to: Option<String>,
2558    #[serde(default)]
2559    pub str_expandtabs_size: Option<usize>,
2560    #[serde(default)]
2561    pub str_findall_sep: Option<String>,
2562    #[serde(default)]
2563    pub str_patterns: Option<Vec<String>>,
2564    #[serde(default)]
2565    pub melt_id_vars: Option<Vec<String>>,
2566    #[serde(default)]
2567    pub melt_value_vars: Option<Vec<String>>,
2568    #[serde(default)]
2569    pub melt_var_name: Option<String>,
2570    #[serde(default)]
2571    pub melt_value_name: Option<String>,
2572    #[serde(default)]
2573    pub pivot_values: Option<Vec<String>>,
2574    #[serde(default)]
2575    pub pivot_index: Option<String>,
2576    #[serde(default)]
2577    pub pivot_columns: Option<String>,
2578    #[serde(default)]
2579    pub pivot_aggfunc: Option<String>,
2580    #[serde(default)]
2581    pub pivot_margins: Option<bool>,
2582    /// `pivot_table(dropna=...)`. `None` keeps the oracle's historical
2583    /// `dropna=False`, so every fixture banked before this knob existed is
2584    /// byte-unchanged. br-frankenpandas-eay9h.
2585    #[serde(default)]
2586    pub pivot_dropna: Option<bool>,
2587    /// `pivot_table(sort=...)`. Sibling of `pivot_dropna` and the last of the two
2588    /// pandas defaults this oracle overrode with no way to ask for them. `None`
2589    /// keeps the historical `sort=False`. MEASURED before adding it: of the eight
2590    /// banked pivot_table fixtures, exactly ONE changes under pandas' default —
2591    /// `fp_p2d_127_dataframe_pivot_table_multi_values_strict` — six are
2592    /// byte-identical and one errors for an unrelated reason.
2593    /// br-frankenpandas-eay9h.
2594    #[serde(default)]
2595    pub pivot_sort: Option<bool>,
2596    #[serde(default)]
2597    pub pivot_margins_name: Option<String>,
2598    #[serde(default)]
2599    pub dummy_columns: Option<Vec<String>>,
2600    #[serde(default)]
2601    pub crosstab_normalize: Option<String>,
2602    #[serde(default)]
2603    pub replace_to_find: Option<Vec<Scalar>>,
2604    #[serde(default)]
2605    pub replace_to_value: Option<Vec<Scalar>>,
2606    #[serde(default)]
2607    pub na_action_ignore: Option<bool>,
2608    #[serde(default)]
2609    pub categorical_categories: Option<Vec<Scalar>>,
2610    #[serde(default)]
2611    pub categorical_ordered: Option<bool>,
2612    // Window operation parameters
2613    // Per gauntlet mm77i root-cause: packets historically carry the window under
2614    // the key `rolling_window` (not `window_size`) and the min_periods under
2615    // `rolling_min_periods`. Without these aliases the harness silently ignored
2616    // the packet's window (defaulting to 3) and min_periods (defaulting to the
2617    // window), so faithful replay used the wrong params and diverged from the
2618    // oracle-pinned expected. The rolling SUBJECT code was correct all along.
2619    #[serde(default, alias = "rolling_window")]
2620    pub window_size: Option<usize>,
2621    #[serde(default, alias = "rolling_min_periods")]
2622    pub min_periods: Option<usize>,
2623    #[serde(default)]
2624    pub window_center: Option<bool>,
2625    #[serde(default)]
2626    pub ewm_span: Option<f64>,
2627    #[serde(default)]
2628    pub ewm_alpha: Option<f64>,
2629    #[serde(default)]
2630    pub resample_freq: Option<String>,
2631    #[serde(default)]
2632    pub resample_limit: Option<usize>,
2633    #[serde(default)]
2634    pub resample_closed: Option<String>,
2635    #[serde(default)]
2636    pub resample_label: Option<String>,
2637    #[serde(default)]
2638    pub resample_origin: Option<String>,
2639    #[serde(default)]
2640    pub quantile_value: Option<f64>,
2641    #[serde(default)]
2642    pub dt_freq: Option<String>,
2643    /// `tz` for `series_dt_tz_convert` / `series_dt_tz_localize`. ABSENT means
2644    /// None, which pandas gives a real meaning in both calls, so this is not a
2645    /// "required but missing" field. Spelled identically in the oracle
2646    /// (br-frankenpandas-t2n6i).
2647    #[serde(default)]
2648    pub dt_tz: Option<String>,
2649    #[serde(default)]
2650    pub dt_strftime_format: Option<String>,
2651    #[serde(default)]
2652    pub dt_how: Option<String>,
2653    #[serde(default)]
2654    pub dt_warn: Option<bool>,
2655}
2656
2657#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2658#[serde(rename_all = "snake_case")]
2659pub enum CaseStatus {
2660    Pass,
2661    Fail,
2662    /// The fixture is retired: it was NOT executed, and it is NOT a pass.
2663    ///
2664    /// br-frankenpandas-fixture-corpus-stale-vs-oracle-p6srr. Retirement exists
2665    /// for fixtures whose operation the oracle no longer supports, which cannot
2666    /// be regenerated and must not be silently rewritten. A retired fixture
2667    /// stays in the DENOMINATOR (`fixture_count`) and carries its reason, so a
2668    /// skipped case can never be mistaken for a checked one — the exact
2669    /// pass-by-skip hazard tracked by
2670    /// br-frankenpandas-live-oracle-passes-by-skip-l7r1p.
2671    Retired,
2672}
2673
2674#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2675pub struct CaseResult {
2676    pub packet_id: String,
2677    pub case_id: String,
2678    pub mode: RuntimeMode,
2679    pub operation: FixtureOperation,
2680    pub status: CaseStatus,
2681    pub mismatch: Option<String>,
2682    #[serde(default)]
2683    pub mismatch_class: Option<String>,
2684    #[serde(default)]
2685    pub replay_key: String,
2686    #[serde(default)]
2687    pub trace_id: String,
2688    #[serde(default)]
2689    pub elapsed_us: u64,
2690    pub evidence_records: usize,
2691}
2692
2693// === Differential Harness: Comparator Taxonomy + Drift Classification ===
2694
2695/// Drift severity classification following frankenlibc fail-closed doctrine.
2696#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2697#[serde(rename_all = "snake_case")]
2698pub enum DriftLevel {
2699    /// Hard parity failure: no tolerance, blocks gates.
2700    Critical,
2701    /// Soft divergence: within configured tolerance budget.
2702    NonCritical,
2703    /// Known behavioral gap, documented and accepted.
2704    Informational,
2705}
2706
2707/// Comparison dimension in the differential taxonomy.
2708#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
2709#[serde(rename_all = "snake_case")]
2710pub enum ComparisonCategory {
2711    /// Scalar value equality (exact or within tolerance).
2712    Value,
2713    /// Data type agreement between actual and expected.
2714    Type,
2715    /// Shape: length or dimensionality mismatch.
2716    Shape,
2717    /// Index labels and ordering.
2718    Index,
2719    /// Null/NaN propagation behavior.
2720    Nullness,
2721}
2722
2723/// A single drift observation from a differential comparison.
2724#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2725pub struct DriftRecord {
2726    pub category: ComparisonCategory,
2727    pub level: DriftLevel,
2728    #[serde(default)]
2729    pub mismatch_class: String,
2730    pub location: String,
2731    pub message: String,
2732}
2733
2734/// Full differential comparison result for a single fixture case.
2735#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2736pub struct DifferentialResult {
2737    pub case_id: String,
2738    pub packet_id: String,
2739    pub operation: FixtureOperation,
2740    pub mode: RuntimeMode,
2741    #[serde(default)]
2742    pub replay_key: String,
2743    #[serde(default)]
2744    pub trace_id: String,
2745    pub oracle_source: FixtureOracleSource,
2746    pub status: CaseStatus,
2747    pub drift_records: Vec<DriftRecord>,
2748    pub evidence_records: usize,
2749    /// Why this case was retired, when `status` is [`CaseStatus::Retired`].
2750    ///
2751    /// br-frankenpandas-fixture-corpus-stale-vs-oracle-p6srr. Deliberately a
2752    /// dedicated field rather than a synthetic drift record: a retirement is
2753    /// not drift, and folding it into `drift_records` would inflate the drift
2754    /// summary with cases that were never even executed.
2755    #[serde(default)]
2756    pub retired_reason: Option<String>,
2757}
2758
2759impl DifferentialResult {
2760    /// A case that was retired and therefore NOT executed.
2761    ///
2762    /// No drift records and no evidence: nothing ran. The status is
2763    /// [`CaseStatus::Retired`], never `Pass`, so it cannot be mistaken for a
2764    /// fixture that was checked.
2765    #[must_use]
2766    pub fn retired(fixture: &PacketFixture, reason: &str) -> Self {
2767        Self {
2768            case_id: fixture.case_id.clone(),
2769            packet_id: fixture.packet_id.clone(),
2770            operation: fixture.operation,
2771            mode: fixture.mode,
2772            replay_key: String::new(),
2773            trace_id: String::new(),
2774            oracle_source: fixture
2775                .oracle_source
2776                .unwrap_or(FixtureOracleSource::Fixture),
2777            status: CaseStatus::Retired,
2778            drift_records: Vec::new(),
2779            evidence_records: 0,
2780            retired_reason: Some(reason.to_owned()),
2781        }
2782    }
2783}
2784
2785fn runtime_mode_slug(mode: RuntimeMode) -> &'static str {
2786    match mode {
2787        RuntimeMode::Strict => "strict",
2788        RuntimeMode::Hardened => "hardened",
2789    }
2790}
2791
2792fn comparison_category_slug(category: ComparisonCategory) -> &'static str {
2793    match category {
2794        ComparisonCategory::Value => "value",
2795        ComparisonCategory::Type => "type",
2796        ComparisonCategory::Shape => "shape",
2797        ComparisonCategory::Index => "index",
2798        ComparisonCategory::Nullness => "nullness",
2799    }
2800}
2801
2802fn drift_level_slug(level: DriftLevel) -> &'static str {
2803    match level {
2804        DriftLevel::Critical => "critical",
2805        DriftLevel::NonCritical => "non_critical",
2806        DriftLevel::Informational => "informational",
2807    }
2808}
2809
2810fn mismatch_class_for(category: ComparisonCategory, level: DriftLevel) -> String {
2811    format!(
2812        "{}_{}",
2813        comparison_category_slug(category),
2814        drift_level_slug(level)
2815    )
2816}
2817
2818fn deterministic_trace_id(packet_id: &str, case_id: &str, mode: RuntimeMode) -> String {
2819    format!("{packet_id}:{case_id}:{}", runtime_mode_slug(mode))
2820}
2821
2822fn deterministic_replay_key(packet_id: &str, case_id: &str, mode: RuntimeMode) -> String {
2823    format!("{packet_id}/{case_id}/{}", runtime_mode_slug(mode))
2824}
2825
2826fn deterministic_scenario_id(suite: &str, packet_id: &str) -> String {
2827    format!("{suite}:{packet_id}")
2828}
2829
2830fn parity_report_artifact_id(packet_id: &str) -> String {
2831    format!("{packet_id}/parity_report")
2832}
2833
2834fn deterministic_step_id(case_id: &str) -> String {
2835    format!("case:{case_id}")
2836}
2837
2838fn deterministic_seed(packet_id: &str, case_id: &str, mode: RuntimeMode) -> u64 {
2839    let key = format!("{packet_id}:{case_id}:{}", runtime_mode_slug(mode));
2840    let mut hash = 0xcbf29ce484222325_u64;
2841    for byte in key.as_bytes() {
2842        hash ^= u64::from(*byte);
2843        hash = hash.wrapping_mul(0x100000001b3);
2844    }
2845    hash
2846}
2847
2848fn assertion_path_for_case(packet_id: &str, case_id: &str) -> String {
2849    format!("ASUPERSYNC-G/{packet_id}/{case_id}")
2850}
2851
2852fn replay_cmd_for_case(case_id: &str) -> String {
2853    format!("cargo test -p fp-conformance -- {case_id} --nocapture")
2854}
2855
2856fn result_label_for_status(status: &CaseStatus) -> &'static str {
2857    match status {
2858        CaseStatus::Pass => "pass",
2859        CaseStatus::Fail => "fail",
2860        // NOT "pass". A retired case was never executed, and labelling it as a
2861        // pass anywhere is the pass-by-skip hazard this status exists to close.
2862        CaseStatus::Retired => "retired",
2863    }
2864}
2865
2866fn decision_action_for(status: &CaseStatus) -> &'static str {
2867    match status {
2868        CaseStatus::Pass => "allow",
2869        CaseStatus::Fail => "repair",
2870        // Neither allowed nor repaired: nothing was decided because nothing ran.
2871        CaseStatus::Retired => "skipped",
2872    }
2873}
2874
2875const COMPAT_CLOSURE_SUITE_ID: &str = "COMPAT-CLOSURE-E";
2876const COMPAT_CLOSURE_COVERAGE_FLOOR_PERCENT: usize = 100;
2877const COMPAT_CLOSURE_REQUIRED_ROWS: [&str; 9] = [
2878    "CC-001", "CC-002", "CC-003", "CC-004", "CC-005", "CC-006", "CC-007", "CC-008", "CC-009",
2879];
2880
2881fn compat_contract_rows_for_operation(operation: FixtureOperation) -> &'static [&'static str] {
2882    match operation {
2883        FixtureOperation::SeriesAdd
2884        | FixtureOperation::SeriesSub
2885        | FixtureOperation::SeriesMul
2886        | FixtureOperation::SeriesDiv => &["CC-004", "CC-005"],
2887        FixtureOperation::SeriesConstructor
2888        | FixtureOperation::SeriesToDatetime
2889        | FixtureOperation::SeriesToTimedelta
2890        | FixtureOperation::SeriesTimedeltaTotalSeconds
2891        | FixtureOperation::DataFrameFromDict
2892        | FixtureOperation::DataFrameFromRecords
2893        | FixtureOperation::DataFrameConstructorKwargs
2894        | FixtureOperation::DataFrameConstructorScalar
2895        | FixtureOperation::DataFrameConstructorDictOfSeries
2896        | FixtureOperation::DataFrameConstructorListLike => &["CC-001", "CC-003", "CC-005"],
2897        FixtureOperation::SeriesJoin
2898        | FixtureOperation::SeriesConcat
2899        | FixtureOperation::SeriesCombineFirst
2900        | FixtureOperation::DataFrameMerge
2901        | FixtureOperation::DataFrameMergeIndex
2902        | FixtureOperation::DataFrameMergeAsof
2903        | FixtureOperation::DataFrameMergeOrdered
2904        | FixtureOperation::DataFrameConcat
2905        | FixtureOperation::DataFrameCombineFirst => &["CC-006"],
2906        FixtureOperation::DataFrameFromSeries => &["CC-003", "CC-005", "CC-006"],
2907        FixtureOperation::GroupBySum
2908        | FixtureOperation::GroupByMean
2909        | FixtureOperation::GroupByCount
2910        | FixtureOperation::GroupByMin
2911        | FixtureOperation::GroupByMax
2912        | FixtureOperation::GroupByFirst
2913        | FixtureOperation::GroupByLast
2914        | FixtureOperation::GroupByStd
2915        | FixtureOperation::GroupByVar
2916        | FixtureOperation::GroupByMedian
2917        | FixtureOperation::SeriesValueCounts => &["CC-007"],
2918        FixtureOperation::IndexAlignUnion
2919        | FixtureOperation::IndexHasDuplicates
2920        | FixtureOperation::IndexIsMonotonicIncreasing
2921        | FixtureOperation::IndexIsMonotonicDecreasing
2922        | FixtureOperation::IndexFirstPositions => &["CC-003"],
2923        FixtureOperation::NanSum
2924        | FixtureOperation::NanMean
2925        | FixtureOperation::NanMin
2926        | FixtureOperation::NanMax
2927        | FixtureOperation::NanStd
2928        | FixtureOperation::NanVar
2929        | FixtureOperation::NanCount
2930        | FixtureOperation::SeriesCount
2931        | FixtureOperation::SeriesNunique
2932        | FixtureOperation::SeriesFirstValidIndex
2933        | FixtureOperation::SeriesLastValidIndex
2934        | FixtureOperation::SeriesIdxmin
2935        | FixtureOperation::SeriesIdxmax
2936        | FixtureOperation::SeriesArgmin
2937        | FixtureOperation::SeriesArgmax
2938        | FixtureOperation::SeriesSearchsorted
2939        | FixtureOperation::SeriesDot
2940        | FixtureOperation::DataFrameCount
2941        | FixtureOperation::DataFrameMode
2942        | FixtureOperation::DataFrameCumsum
2943        | FixtureOperation::DataFrameCumprod
2944        | FixtureOperation::DataFrameCummax
2945        | FixtureOperation::DataFrameCummin
2946        | FixtureOperation::DataFrameAstype
2947        | FixtureOperation::DataFrameClip
2948        | FixtureOperation::DataFrameAbs
2949        | FixtureOperation::DataFrameDescribe
2950        | FixtureOperation::DataFrameCorr
2951        | FixtureOperation::DataFrameCov
2952        | FixtureOperation::DataFrameIdxmin
2953        | FixtureOperation::DataFrameIdxmax
2954        | FixtureOperation::DataFrameSem
2955        | FixtureOperation::DataFrameApplySemAxis0
2956        | FixtureOperation::DataFrameSkew
2957        | FixtureOperation::DataFrameKurtosis
2958        | FixtureOperation::DataFrameProd
2959        | FixtureOperation::DataFrameApplyProdAxis1
2960        | FixtureOperation::DataFrameApplyProductAxis1
2961        | FixtureOperation::DataFrameSum
2962        | FixtureOperation::DataFrameMean
2963        | FixtureOperation::DataFrameStd
2964        | FixtureOperation::DataFrameVar
2965        | FixtureOperation::DataFrameMin
2966        | FixtureOperation::DataFrameMax
2967        | FixtureOperation::DataFrameMedian
2968        | FixtureOperation::DataFrameAny
2969        | FixtureOperation::DataFrameAll
2970        | FixtureOperation::DataFrameNunique
2971        | FixtureOperation::DataFrameApplyNuniqueAxis0
2972        | FixtureOperation::DataFrameQuantile
2973        | FixtureOperation::DataFrameValueCounts
2974        | FixtureOperation::DataFrameMemoryUsage
2975        | FixtureOperation::DataFrameRound
2976        | FixtureOperation::DataFrameBinaryAlias => &["CC-005"],
2977        FixtureOperation::FillNa
2978        | FixtureOperation::DropNa
2979        | FixtureOperation::SeriesToNumeric
2980        | FixtureOperation::SeriesConvertDtypes
2981        | FixtureOperation::SeriesAstype
2982        | FixtureOperation::SeriesClip
2983        | FixtureOperation::SeriesAbs
2984        | FixtureOperation::SeriesRound
2985        | FixtureOperation::SeriesCumsum
2986        | FixtureOperation::SeriesCumprod
2987        | FixtureOperation::SeriesCummax
2988        | FixtureOperation::SeriesCummin
2989        | FixtureOperation::SeriesNlargest
2990        | FixtureOperation::SeriesNsmallest
2991        | FixtureOperation::SeriesBetween
2992        | FixtureOperation::SeriesCut
2993        | FixtureOperation::SeriesQcut
2994        | FixtureOperation::SeriesStrLower
2995        | FixtureOperation::SeriesStrUpper
2996        | FixtureOperation::SeriesStrCapitalize
2997        | FixtureOperation::SeriesStrStrip
2998        | FixtureOperation::SeriesStrLen
2999        | FixtureOperation::SeriesStrContains
3000        | FixtureOperation::SeriesStrStartswith
3001        | FixtureOperation::SeriesStrEndswith
3002        | FixtureOperation::SeriesStrReplace
3003        | FixtureOperation::SeriesStrLstrip
3004        | FixtureOperation::SeriesStrRstrip
3005        | FixtureOperation::SeriesStrTitle
3006        | FixtureOperation::SeriesStrSwapcase
3007        | FixtureOperation::SeriesStrZfill
3008        | FixtureOperation::SeriesStrCenter
3009        | FixtureOperation::SeriesStrLjust
3010        | FixtureOperation::SeriesStrRjust
3011        | FixtureOperation::SeriesStrPad
3012        | FixtureOperation::SeriesStrIsdigit
3013        | FixtureOperation::SeriesStrIsalpha
3014        | FixtureOperation::SeriesStrIsalnum
3015        | FixtureOperation::SeriesStrIsspace
3016        | FixtureOperation::SeriesStrIslower
3017        | FixtureOperation::SeriesStrIsupper
3018        | FixtureOperation::SeriesStrIsnumeric
3019        | FixtureOperation::SeriesStrFind
3020        | FixtureOperation::SeriesStrRfind
3021        | FixtureOperation::SeriesStrSlice
3022        | FixtureOperation::SeriesStrGet
3023        | FixtureOperation::SeriesStrRepeat
3024        | FixtureOperation::SeriesStrCount
3025        | FixtureOperation::SeriesStrWrap
3026        | FixtureOperation::SeriesStrNormalize
3027        | FixtureOperation::SeriesStrFullmatch
3028        | FixtureOperation::SeriesStrMatch
3029        | FixtureOperation::SeriesStrRemoveprefix
3030        | FixtureOperation::SeriesStrRemovesuffix
3031        | FixtureOperation::SeriesStrSplitGet
3032        | FixtureOperation::SeriesStrJoin
3033        | FixtureOperation::SeriesStrIsdecimal
3034        | FixtureOperation::SeriesStrIstitle
3035        | FixtureOperation::SeriesStrCasefold
3036        | FixtureOperation::SeriesStrEncode
3037        | FixtureOperation::SeriesStrDecode
3038        | FixtureOperation::SeriesStrTranslate
3039        | FixtureOperation::SeriesStrExpandtabs
3040        | FixtureOperation::SeriesStrIndexOf
3041        | FixtureOperation::SeriesStrRindexOf
3042        | FixtureOperation::SeriesStrSplitCount
3043        | FixtureOperation::SeriesStrRsplitGet
3044        | FixtureOperation::SeriesStrSplitRegexGet
3045        | FixtureOperation::SeriesStrCountMatches
3046        | FixtureOperation::SeriesStrCountLiteral
3047        | FixtureOperation::SeriesStrFindall
3048        | FixtureOperation::SeriesStrContainsAny
3049        | FixtureOperation::SeriesStrStartswithAny
3050        | FixtureOperation::SeriesStrEndswithAny
3051        | FixtureOperation::SeriesDtYear
3052        | FixtureOperation::SeriesDtMonth
3053        | FixtureOperation::SeriesDtDay
3054        | FixtureOperation::SeriesDtHour
3055        | FixtureOperation::SeriesDtMinute
3056        | FixtureOperation::SeriesDtSecond
3057        | FixtureOperation::SeriesDtMicrosecond
3058        | FixtureOperation::SeriesDtNanosecond
3059        | FixtureOperation::SeriesDtDayofweek
3060        | FixtureOperation::SeriesDtQuarter
3061        | FixtureOperation::SeriesDtDayofyear
3062        | FixtureOperation::SeriesDtWeekofyear
3063        | FixtureOperation::SeriesDtIsMonthStart
3064        | FixtureOperation::SeriesDtIsMonthEnd
3065        | FixtureOperation::SeriesDtIsYearStart
3066        | FixtureOperation::SeriesDtIsYearEnd
3067        | FixtureOperation::SeriesDtDate
3068        | FixtureOperation::SeriesDtDaysInMonth
3069        | FixtureOperation::SeriesDtIsLeapYear
3070        | FixtureOperation::SeriesDtIsQuarterStart
3071        | FixtureOperation::SeriesDtIsQuarterEnd
3072        | FixtureOperation::SeriesDtStrftime
3073        | FixtureOperation::SeriesDtTzConvert
3074        | FixtureOperation::SeriesDtTzLocalize
3075        | FixtureOperation::SeriesDtTimetz
3076        | FixtureOperation::SeriesDtToPeriod
3077        | FixtureOperation::SeriesDtFloor
3078        | FixtureOperation::SeriesDtCeil
3079        | FixtureOperation::SeriesDtRound
3080        | FixtureOperation::SeriesDtMonthName
3081        | FixtureOperation::SeriesDtDayName
3082        | FixtureOperation::SeriesDtTotalSeconds
3083        | FixtureOperation::SeriesDtDays
3084        | FixtureOperation::SeriesDtSeconds
3085        | FixtureOperation::SeriesDtMicroseconds
3086        | FixtureOperation::SeriesDtNanoseconds
3087        | FixtureOperation::SeriesDtToTimestamp
3088        | FixtureOperation::SeriesDtToPytimedelta
3089        | FixtureOperation::SeriesDtToPydatetime
3090        | FixtureOperation::SeriesIsNa
3091        | FixtureOperation::SeriesNotNa
3092        | FixtureOperation::SeriesIsNull
3093        | FixtureOperation::SeriesNotNull
3094        | FixtureOperation::SeriesFillNa
3095        | FixtureOperation::SeriesDropNa
3096        | FixtureOperation::DataFrameIsNa
3097        | FixtureOperation::DataFrameNotNa
3098        | FixtureOperation::DataFrameIsNull
3099        | FixtureOperation::DataFrameNotNull
3100        | FixtureOperation::DataFrameFillNa
3101        | FixtureOperation::DataFrameDropNa
3102        | FixtureOperation::DataFrameDropNaColumns => &["CC-002", "CC-005"],
3103        FixtureOperation::SeriesToArrowRoundTrip
3104        | FixtureOperation::CsvRoundTrip
3105        | FixtureOperation::CsvReadFrame
3106        | FixtureOperation::DataFrameToJsonRecords
3107        | FixtureOperation::JsonRoundTrip
3108        | FixtureOperation::JsonlRoundTrip
3109        | FixtureOperation::ParquetRoundTrip
3110        | FixtureOperation::FeatherRoundTrip
3111        | FixtureOperation::ExcelRoundTrip
3112        | FixtureOperation::IpcStreamRoundTrip => &["CC-006"],
3113        FixtureOperation::ColumnDtypeCheck | FixtureOperation::SeriesDtypeCheck => &["CC-001"],
3114        FixtureOperation::SeriesFilter
3115        | FixtureOperation::SeriesHead
3116        | FixtureOperation::SeriesTail
3117        | FixtureOperation::SeriesAny
3118        | FixtureOperation::SeriesAll
3119        | FixtureOperation::SeriesBool
3120        | FixtureOperation::SeriesRepeat
3121        | FixtureOperation::SeriesSortIndex
3122        | FixtureOperation::SeriesSortValues
3123        | FixtureOperation::SeriesDiff
3124        | FixtureOperation::SeriesShift
3125        | FixtureOperation::SeriesPctChange
3126        | FixtureOperation::SeriesMode
3127        | FixtureOperation::SeriesRank
3128        | FixtureOperation::SeriesArgsort
3129        | FixtureOperation::SeriesDescribe
3130        | FixtureOperation::SeriesDuplicated
3131        | FixtureOperation::SeriesDropDuplicates
3132        | FixtureOperation::SeriesUnique
3133        | FixtureOperation::SeriesFactorize
3134        | FixtureOperation::SeriesWhere
3135        | FixtureOperation::SeriesMask
3136        | FixtureOperation::SeriesReplace
3137        | FixtureOperation::SeriesUpdate
3138        | FixtureOperation::SeriesMap
3139        | FixtureOperation::SeriesCategoricalFromCodes
3140        | FixtureOperation::SeriesXs
3141        | FixtureOperation::SeriesLoc
3142        | FixtureOperation::SeriesIloc
3143        | FixtureOperation::SeriesTake
3144        | FixtureOperation::SeriesAtTime
3145        | FixtureOperation::SeriesBetweenTime
3146        | FixtureOperation::SeriesPartitionDf
3147        | FixtureOperation::SeriesRpartitionDf
3148        | FixtureOperation::SeriesSplitDf
3149        | FixtureOperation::SeriesExtractDf
3150        | FixtureOperation::SeriesExtractAll
3151        | FixtureOperation::SeriesToFrame
3152        | FixtureOperation::SeriesUnstack
3153        | FixtureOperation::SeriesStrGetDummies
3154        | FixtureOperation::DataFrameLoc
3155        | FixtureOperation::DataFrameIdentity
3156        | FixtureOperation::DataFrameIloc
3157        | FixtureOperation::DataFrameTake
3158        | FixtureOperation::DataFrameFilter
3159        | FixtureOperation::DataFrameGroupBySum
3160        | FixtureOperation::DataFrameGroupByAggMulti
3161        | FixtureOperation::DataFrameGroupByIdxMin
3162        | FixtureOperation::DataFrameGroupByIdxMax
3163        | FixtureOperation::DataFrameGroupByAny
3164        | FixtureOperation::DataFrameGroupByAll
3165        | FixtureOperation::DataFrameGroupByGetGroup
3166        | FixtureOperation::DataFrameGroupByFfill
3167        | FixtureOperation::DataFrameGroupByBfill
3168        | FixtureOperation::DataFrameGroupBySem
3169        | FixtureOperation::DataFrameGroupBySkew
3170        | FixtureOperation::DataFrameGroupByKurtosis
3171        | FixtureOperation::DataFrameGroupByOhlc
3172        | FixtureOperation::DataFrameGroupByCumcount
3173        | FixtureOperation::DataFrameGroupByNgroup
3174        | FixtureOperation::DataFrameAsof
3175        | FixtureOperation::DataFrameAtTime
3176        | FixtureOperation::DataFrameBetweenTime
3177        | FixtureOperation::DataFrameBool
3178        | FixtureOperation::DataFrameHead
3179        | FixtureOperation::DataFrameTail
3180        | FixtureOperation::DataFrameEval
3181        | FixtureOperation::DataFrameCompare
3182        | FixtureOperation::DataFrameExplode
3183        | FixtureOperation::DataFrameQuery
3184        | FixtureOperation::DataFrameXs
3185        | FixtureOperation::DataFrameSetIndex
3186        | FixtureOperation::DataFrameResetIndex
3187        | FixtureOperation::DataFrameInsert
3188        | FixtureOperation::DataFrameAssign
3189        | FixtureOperation::DataFrameRenameColumns
3190        | FixtureOperation::DataFrameReindex
3191        | FixtureOperation::DataFrameReindexColumns
3192        | FixtureOperation::DataFrameDropColumns
3193        | FixtureOperation::DataFrameReplace
3194        | FixtureOperation::DataFrameWhere
3195        | FixtureOperation::DataFrameWhereDf
3196        | FixtureOperation::DataFrameMask
3197        | FixtureOperation::DataFrameMaskDf
3198        | FixtureOperation::DataFrameDuplicated
3199        | FixtureOperation::DataFrameDropDuplicates
3200        | FixtureOperation::DataFrameSortIndex
3201        | FixtureOperation::DataFrameSortValues
3202        | FixtureOperation::DataFrameNlargest
3203        | FixtureOperation::DataFrameNsmallest
3204        | FixtureOperation::DataFrameRank
3205        | FixtureOperation::DataFrameDiff
3206        | FixtureOperation::DataFrameShift
3207        | FixtureOperation::DataFramePctChange
3208        | FixtureOperation::DataFrameMelt
3209        | FixtureOperation::DataFramePivot
3210        | FixtureOperation::DataFramePivotTable
3211        | FixtureOperation::DataFrameStack
3212        | FixtureOperation::DataFrameTranspose
3213        | FixtureOperation::DataFrameCrosstab
3214        | FixtureOperation::DataFrameCrosstabNormalize
3215        | FixtureOperation::DataFrameGetDummies
3216        | FixtureOperation::SeriesRollingMean
3217        | FixtureOperation::SeriesRollingSum
3218        | FixtureOperation::SeriesRollingStd
3219        | FixtureOperation::SeriesRollingMin
3220        | FixtureOperation::SeriesRollingMax
3221        | FixtureOperation::SeriesRollingVar
3222        | FixtureOperation::SeriesRollingCount
3223        | FixtureOperation::SeriesExpandingCount
3224        | FixtureOperation::SeriesExpandingQuantile
3225        | FixtureOperation::SeriesExpandingSum
3226        | FixtureOperation::SeriesExpandingMean
3227        | FixtureOperation::SeriesExpandingMin
3228        | FixtureOperation::SeriesExpandingMax
3229        | FixtureOperation::SeriesExpandingStd
3230        | FixtureOperation::SeriesExpandingVar
3231        | FixtureOperation::SeriesEwmMean
3232        | FixtureOperation::SeriesAsof
3233        | FixtureOperation::SeriesAutocorr
3234        | FixtureOperation::SeriesResampleSum
3235        | FixtureOperation::SeriesResampleMean
3236        | FixtureOperation::SeriesResampleCount
3237        | FixtureOperation::SeriesResampleAsfreq
3238        | FixtureOperation::SeriesResampleFfill
3239        | FixtureOperation::SeriesResampleBfill
3240        | FixtureOperation::DataFrameRollingMean
3241        | FixtureOperation::DataFrameResampleSum
3242        | FixtureOperation::DataFrameResampleMean
3243        | FixtureOperation::DataFrameGroupByRollingMean
3244        | FixtureOperation::DataFrameGroupByRollingSum
3245        | FixtureOperation::DataFrameGroupByRollingMin
3246        | FixtureOperation::DataFrameGroupByRollingMax
3247        | FixtureOperation::DataFrameGroupByRollingCount
3248        | FixtureOperation::DataFrameGroupByRollingStd
3249        | FixtureOperation::DataFrameGroupByRollingVar
3250        | FixtureOperation::DataFrameGroupByResampleMin
3251        | FixtureOperation::DataFrameGroupByResampleMax
3252        | FixtureOperation::DataFrameGroupByResampleCount
3253        | FixtureOperation::DataFrameGroupByResampleFirst
3254        | FixtureOperation::DataFrameGroupByResampleLast => &["CC-004"],
3255    }
3256}
3257
3258fn compat_primary_api_surface_id(operation: FixtureOperation) -> &'static str {
3259    compat_contract_rows_for_operation(operation)
3260        .first()
3261        .copied()
3262        .unwrap_or("CC-UNKNOWN")
3263}
3264
3265fn stable_json_digest<T: Serialize>(value: &T) -> String {
3266    let payload = serde_json::to_vec(value).unwrap_or_else(|_| Vec::new());
3267    hash_bytes(&payload)
3268}
3269
3270fn relative_to_repo(config: &HarnessConfig, path: &Path) -> String {
3271    path.strip_prefix(&config.repo_root)
3272        .map(|relative| relative.display().to_string())
3273        .unwrap_or_else(|_| path.display().to_string())
3274}
3275
3276fn compat_closure_artifact_refs(config: &HarnessConfig, packet_id: &str) -> Vec<String> {
3277    let packet_root = config.packet_artifact_root(packet_id);
3278    vec![
3279        relative_to_repo(config, &packet_root.join("parity_report.json")),
3280        relative_to_repo(config, &packet_root.join("parity_report.raptorq.json")),
3281        relative_to_repo(config, &packet_root.join("parity_report.decode_proof.json")),
3282        relative_to_repo(config, &packet_root.join("parity_gate_result.json")),
3283        relative_to_repo(config, &packet_root.join("parity_mismatch_corpus.json")),
3284    ]
3285}
3286
3287fn compat_closure_env_fingerprint(config: &HarnessConfig) -> String {
3288    stable_json_digest(&serde_json::json!({
3289        "repo_root": config.repo_root.display().to_string(),
3290        "oracle_root": config.oracle_root.display().to_string(),
3291        "fixture_root": config.fixture_root.display().to_string(),
3292        "strict_mode": config.strict_mode,
3293        "platform": std::env::consts::OS,
3294        "arch": std::env::consts::ARCH,
3295        "pkg": env!("CARGO_PKG_NAME"),
3296        "version": env!("CARGO_PKG_VERSION"),
3297    }))
3298}
3299
3300fn runtime_mode_split_contracts_hold() -> bool {
3301    let mut strict_ledger = EvidenceLedger::new();
3302    let mut hardened_ledger = EvidenceLedger::new();
3303    let strict = RuntimePolicy::strict();
3304    let hardened = RuntimePolicy::hardened(Some(1024));
3305
3306    let strict_action = strict.decide_unknown_feature(
3307        "compat-closure-matrix",
3308        "coverage-check",
3309        &mut strict_ledger,
3310    );
3311    let hardened_action = hardened.decide_join_admission(2048, &mut hardened_ledger);
3312
3313    strict_action == DecisionAction::Reject && hardened_action == DecisionAction::Repair
3314}
3315
3316#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3317pub struct CompatClosureCaseLog {
3318    pub ts_utc: u64,
3319    pub suite_id: String,
3320    pub test_id: String,
3321    pub api_surface_id: String,
3322    pub packet_id: String,
3323    pub mode: RuntimeMode,
3324    pub seed: u64,
3325    pub input_digest: String,
3326    pub output_digest: String,
3327    pub env_fingerprint: String,
3328    pub artifact_refs: Vec<String>,
3329    pub duration_ms: u64,
3330    pub outcome: String,
3331    pub reason_code: String,
3332}
3333
3334fn build_compat_closure_case_log(
3335    config: &HarnessConfig,
3336    suite_id: &str,
3337    case: &CaseResult,
3338    ts_utc: u64,
3339) -> CompatClosureCaseLog {
3340    let mode_slug = runtime_mode_slug(case.mode);
3341    let seed = deterministic_seed(&case.packet_id, &case.case_id, case.mode);
3342    let input_digest = stable_json_digest(&serde_json::json!({
3343        "packet_id": case.packet_id.clone(),
3344        "case_id": case.case_id.clone(),
3345        "mode": mode_slug,
3346        "operation": case.operation,
3347        "seed": seed,
3348    }));
3349    let output_digest = stable_json_digest(&serde_json::json!({
3350        "status": result_label_for_status(&case.status),
3351        "mismatch": case.mismatch.clone(),
3352        "mismatch_class": case.mismatch_class.clone(),
3353        "replay_key": case.replay_key.clone(),
3354        "trace_id": case.trace_id.clone(),
3355    }));
3356    let duration_ms = case.elapsed_us.saturating_add(999) / 1000;
3357    let outcome = result_label_for_status(&case.status).to_owned();
3358
3359    CompatClosureCaseLog {
3360        ts_utc,
3361        suite_id: suite_id.to_owned(),
3362        test_id: case.case_id.clone(),
3363        api_surface_id: compat_primary_api_surface_id(case.operation).to_owned(),
3364        packet_id: case.packet_id.clone(),
3365        mode: case.mode,
3366        seed,
3367        input_digest,
3368        output_digest,
3369        env_fingerprint: compat_closure_env_fingerprint(config),
3370        artifact_refs: compat_closure_artifact_refs(config, &case.packet_id),
3371        duration_ms: duration_ms.max(1),
3372        outcome: outcome.clone(),
3373        reason_code: case.mismatch_class.clone().unwrap_or_else(|| {
3374            if outcome == "pass" {
3375                "ok".to_owned()
3376            } else {
3377                "execution_critical".to_owned()
3378            }
3379        }),
3380    }
3381}
3382
3383#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3384pub struct CompatClosureCoverageReport {
3385    pub suite_id: String,
3386    pub required_rows: Vec<String>,
3387    pub covered_rows: Vec<String>,
3388    pub uncovered_rows: Vec<String>,
3389    pub coverage_floor_percent: usize,
3390    pub achieved_percent: usize,
3391}
3392
3393impl CompatClosureCoverageReport {
3394    #[must_use]
3395    pub fn is_complete(&self) -> bool {
3396        self.uncovered_rows.is_empty()
3397            && self.achieved_percent >= self.coverage_floor_percent
3398            && self.coverage_floor_percent == COMPAT_CLOSURE_COVERAGE_FLOOR_PERCENT
3399    }
3400}
3401
3402pub fn build_compat_closure_coverage_report(
3403    config: &HarnessConfig,
3404) -> Result<CompatClosureCoverageReport, HarnessError> {
3405    let fixtures = load_fixtures(config, None)?;
3406    let mut covered_rows: BTreeSet<String> = BTreeSet::new();
3407    for fixture in &fixtures {
3408        for row in compat_contract_rows_for_operation(fixture.operation) {
3409            covered_rows.insert((*row).to_owned());
3410        }
3411    }
3412
3413    if runtime_mode_split_contracts_hold() {
3414        covered_rows.insert("CC-008".to_owned());
3415        covered_rows.insert("CC-009".to_owned());
3416    }
3417
3418    let required_rows = COMPAT_CLOSURE_REQUIRED_ROWS
3419        .iter()
3420        .map(|row| (*row).to_owned())
3421        .collect::<Vec<_>>();
3422    let uncovered_rows = required_rows
3423        .iter()
3424        .filter(|row| !covered_rows.contains(*row))
3425        .cloned()
3426        .collect::<Vec<_>>();
3427    let achieved_percent = (covered_rows.len() * 100) / required_rows.len().max(1);
3428
3429    Ok(CompatClosureCoverageReport {
3430        suite_id: COMPAT_CLOSURE_SUITE_ID.to_owned(),
3431        required_rows,
3432        covered_rows: covered_rows.into_iter().collect(),
3433        uncovered_rows,
3434        coverage_floor_percent: COMPAT_CLOSURE_COVERAGE_FLOOR_PERCENT,
3435        achieved_percent,
3436    })
3437}
3438
3439fn make_drift_record(
3440    category: ComparisonCategory,
3441    level: DriftLevel,
3442    location: impl Into<String>,
3443    message: impl Into<String>,
3444) -> DriftRecord {
3445    DriftRecord {
3446        category,
3447        level,
3448        mismatch_class: mismatch_class_for(category, level),
3449        location: location.into(),
3450        message: message.into(),
3451    }
3452}
3453
3454impl DifferentialResult {
3455    /// Convert to backward-compatible CaseResult.
3456    #[must_use]
3457    pub fn to_case_result(&self) -> CaseResult {
3458        // A retired case carries its REASON where a failing case carries its
3459        // mismatch, so every reporting path that already surfaces `mismatch`
3460        // surfaces the retirement too, without needing to know about it.
3461        let mismatch = if matches!(self.status, CaseStatus::Retired) {
3462            Some(
3463                self.retired_reason
3464                    .clone()
3465                    .unwrap_or_else(|| "retired without a recorded reason".to_owned()),
3466            )
3467        } else if self.drift_records.is_empty() {
3468            None
3469        } else {
3470            Some(
3471                self.drift_records
3472                    .iter()
3473                    .map(|d| {
3474                        format!(
3475                            "[{:?}/{:?}] {}: {}",
3476                            d.category, d.level, d.location, d.message
3477                        )
3478                    })
3479                    .collect::<Vec<_>>()
3480                    .join("; "),
3481            )
3482        };
3483        CaseResult {
3484            packet_id: self.packet_id.clone(),
3485            case_id: self.case_id.clone(),
3486            mode: self.mode,
3487            operation: self.operation,
3488            status: self.status.clone(),
3489            mismatch,
3490            mismatch_class: self
3491                .drift_records
3492                .iter()
3493                .find(|drift| matches!(drift.level, DriftLevel::Critical))
3494                .or_else(|| self.drift_records.first())
3495                .map(|drift| drift.mismatch_class.clone()),
3496            replay_key: self.replay_key.clone(),
3497            trace_id: self.trace_id.clone(),
3498            elapsed_us: 0,
3499            evidence_records: self.evidence_records,
3500        }
3501    }
3502}
3503
3504/// Per-category drift count in a summary.
3505#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3506pub struct CategoryCount {
3507    pub category: ComparisonCategory,
3508    pub count: usize,
3509}
3510
3511/// Aggregate drift statistics across all differential results.
3512#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
3513pub struct DriftSummary {
3514    pub total_drift_records: usize,
3515    pub critical_count: usize,
3516    pub non_critical_count: usize,
3517    pub informational_count: usize,
3518    pub categories: Vec<CategoryCount>,
3519}
3520
3521/// Differential report: extends PacketParityReport with structured drift details.
3522#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
3523pub struct DifferentialReport {
3524    pub report: PacketParityReport,
3525    pub differential_results: Vec<DifferentialResult>,
3526    pub drift_summary: DriftSummary,
3527}
3528
3529#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3530pub struct DifferentialValidationLogEntry {
3531    pub packet_id: String,
3532    pub case_id: String,
3533    pub mode: RuntimeMode,
3534    pub trace_id: String,
3535    pub oracle_source: FixtureOracleSource,
3536    pub mismatch_class: String,
3537    pub replay_key: String,
3538}
3539
3540#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3541#[serde(rename_all = "snake_case")]
3542pub enum FaultInjectionClassification {
3543    StrictViolation,
3544    HardenedAllowlisted,
3545}
3546
3547#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3548pub struct FaultInjectionValidationEntry {
3549    pub packet_id: String,
3550    pub case_id: String,
3551    pub mode: RuntimeMode,
3552    pub trace_id: String,
3553    pub oracle_source: FixtureOracleSource,
3554    pub mismatch_class: String,
3555    pub replay_key: String,
3556    pub classification: FaultInjectionClassification,
3557}
3558
3559#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3560pub struct FaultInjectionValidationReport {
3561    pub packet_id: String,
3562    pub entry_count: usize,
3563    pub strict_violation_count: usize,
3564    pub hardened_allowlisted_count: usize,
3565    pub entries: Vec<FaultInjectionValidationEntry>,
3566}
3567
3568#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
3569pub struct PacketParityReport {
3570    pub suite: String,
3571    pub packet_id: Option<String>,
3572    pub oracle_present: bool,
3573    pub fixture_count: usize,
3574    pub passed: usize,
3575    pub failed: usize,
3576    /// Cases that were RETIRED and therefore never executed
3577    /// (br-frankenpandas-fixture-corpus-stale-vs-oracle-p6srr). Counted
3578    /// separately and kept inside `fixture_count`, so
3579    /// `passed + failed + retired == fixture_count`.
3580    #[serde(default)]
3581    pub retired: usize,
3582    pub results: Vec<CaseResult>,
3583}
3584
3585impl PacketParityReport {
3586    #[must_use]
3587    pub fn is_green(&self) -> bool {
3588        self.failed == 0 && self.fixture_count > 0
3589    }
3590
3591    /// Cases actually executed and compared against an oracle.
3592    ///
3593    /// Use this, not `fixture_count`, when reporting coverage: a suite whose
3594    /// fixtures are largely retired is green but barely checked, and the two
3595    /// numbers must not be conflated.
3596    #[must_use]
3597    pub const fn executed(&self) -> usize {
3598        self.fixture_count - self.retired
3599    }
3600
3601    /// Human-readable retirement summary, empty when nothing is retired.
3602    ///
3603    /// Every retired case is named WITH its reason: a retirement nobody can see
3604    /// is ceremony, and a silent skip is the pass-by-skip hazard this guards.
3605    #[must_use]
3606    pub fn retirement_report(&self) -> Vec<String> {
3607        self.results
3608            .iter()
3609            .filter(|r| matches!(r.status, CaseStatus::Retired))
3610            .map(|r| {
3611                format!(
3612                    "RETIRED {}::{} — {}",
3613                    r.packet_id,
3614                    r.case_id,
3615                    r.mismatch.as_deref().unwrap_or("no reason recorded")
3616                )
3617            })
3618            .collect()
3619    }
3620}
3621
3622#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
3623pub struct PacketGateResult {
3624    pub packet_id: String,
3625    pub pass: bool,
3626    pub fixture_count: usize,
3627    pub strict_total: usize,
3628    pub strict_failed: usize,
3629    pub hardened_total: usize,
3630    pub hardened_failed: usize,
3631    pub reasons: Vec<String>,
3632    #[serde(default, skip_serializing_if = "Option::is_none")]
3633    pub validation_source: Option<String>,
3634}
3635
3636#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
3637pub struct RaptorQPacketRecord {
3638    pub source_block_number: u8,
3639    pub encoding_symbol_id: u32,
3640    pub is_source: bool,
3641    pub serialized_hex: String,
3642    pub symbol_hash: String,
3643}
3644
3645#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
3646pub struct RaptorQScrubReport {
3647    pub verified_at_unix_ms: u64,
3648    pub status: String,
3649    pub packet_count: usize,
3650    pub invalid_packets: usize,
3651    pub source_hash_verified: bool,
3652}
3653
3654#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
3655pub struct RaptorQSidecarArtifact {
3656    #[serde(flatten)]
3657    pub envelope: RaptorQEnvelope,
3658    pub oti_serialized_hex: String,
3659    pub source_packets: usize,
3660    pub repair_packets: usize,
3661    pub repair_packets_per_block: u32,
3662    pub packet_records: Vec<RaptorQPacketRecord>,
3663    pub scrub_report: RaptorQScrubReport,
3664    #[serde(default, skip_serializing_if = "Option::is_none")]
3665    pub asupersync_codec: Option<AsupersyncCodecEvidence>,
3666}
3667
3668#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3669pub struct AsupersyncCodecEvidence {
3670    pub codec: String,
3671    pub verifier: String,
3672    pub encoded_bytes: usize,
3673    pub repair_symbols: u32,
3674    pub integrity_verified: bool,
3675}
3676
3677#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
3678pub struct WrittenPacketArtifacts {
3679    pub packet_id: String,
3680    pub parity_report_path: PathBuf,
3681    pub raptorq_sidecar_path: PathBuf,
3682    pub decode_proof_path: PathBuf,
3683    pub gate_result_path: PathBuf,
3684    pub mismatch_corpus_path: PathBuf,
3685}
3686
3687#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
3688pub struct FixtureGenerationRequest {
3689    pub method_family: String,
3690    pub packet_id: String,
3691    pub case_id: String,
3692    pub output_fixture_path: PathBuf,
3693    pub artifact_dir: PathBuf,
3694    pub generation_command: String,
3695    #[serde(default)]
3696    pub input_matrix: Vec<String>,
3697    #[serde(default)]
3698    pub intentional_divergence_notes: Vec<String>,
3699    #[serde(default = "default_repair_packets_per_block")]
3700    pub repair_packets_per_block: u32,
3701}
3702
3703#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
3704pub struct GeneratedFixtureBundle {
3705    pub packet_id: String,
3706    pub case_id: String,
3707    pub method_family: String,
3708    pub fixture_path: PathBuf,
3709    pub manifest_path: PathBuf,
3710    pub repair_symbol_manifest_path: PathBuf,
3711    pub raptorq_sidecar_path: PathBuf,
3712    pub integrity_scrub_path: PathBuf,
3713    pub decode_proof_path: PathBuf,
3714}
3715
3716const fn default_repair_packets_per_block() -> u32 {
3717    8
3718}
3719
3720#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
3721pub struct PacketDriftHistoryEntry {
3722    pub ts_unix_ms: u64,
3723    pub packet_id: String,
3724    pub suite: String,
3725    pub fixture_count: usize,
3726    pub passed: usize,
3727    pub failed: usize,
3728    pub strict_failed: usize,
3729    pub hardened_failed: usize,
3730    pub gate_pass: bool,
3731    pub report_hash: String,
3732}
3733
3734#[derive(Debug, Error)]
3735#[non_exhaustive]
3736pub enum HarnessError {
3737    #[error(transparent)]
3738    Io(#[from] std::io::Error),
3739    #[error(transparent)]
3740    Json(#[from] serde_json::Error),
3741    #[error(transparent)]
3742    Yaml(#[from] serde_yaml::Error),
3743    #[error(transparent)]
3744    Frame(#[from] FrameError),
3745    #[error("fixture format error: {0}")]
3746    FixtureFormat(String),
3747    #[error("oracle is unavailable: {0}")]
3748    OracleUnavailable(String),
3749    #[error("live oracle is required but unavailable: {0}")]
3750    LiveOracleRequired(String),
3751    /// The oracle ran and pandas raised. A case that does not expect an error
3752    /// must fail on this, never skip: it is the pandas answer.
3753    #[error("pandas raised: {0}")]
3754    OracleRaised(String),
3755    /// The oracle ran but its adapter refused the request before pandas saw it
3756    /// (missing payload key, unsupported operation, malformed request): a
3757    /// harness defect, not a missing oracle.
3758    #[error("oracle adapter refused the request: {0}")]
3759    OracleAdapterRefused(String),
3760    #[error("oracle command failed: status={status}, stderr={stderr}")]
3761    OracleCommandFailed { status: i32, stderr: String },
3762    #[error("raptorq error: {0}")]
3763    RaptorQ(String),
3764}
3765
3766#[derive(Debug, Clone, Serialize, Deserialize)]
3767struct ParityGateConfig {
3768    packet_id: String,
3769    strict: StrictGateConfig,
3770    hardened: HardenedGateConfig,
3771    machine_check: MachineCheckConfig,
3772}
3773
3774#[derive(Debug, Clone, Serialize, Deserialize)]
3775struct StrictGateConfig {
3776    critical_drift_budget: usize,
3777    non_critical_drift_budget_percent: f64,
3778}
3779
3780#[derive(Debug, Clone, Serialize, Deserialize)]
3781struct HardenedGateConfig {
3782    divergence_budget_percent: f64,
3783    allowlisted_divergence_categories: Option<Vec<String>>,
3784}
3785
3786#[derive(Debug, Clone, Serialize, Deserialize)]
3787struct MachineCheckConfig {
3788    suite: String,
3789    require_fixture_count_at_least: usize,
3790    require_failed: usize,
3791}
3792
3793fn synthesize_parity_gate(report: &PacketParityReport) -> Result<ParityGateConfig, HarnessError> {
3794    let packet_id = report
3795        .packet_id
3796        .clone()
3797        .ok_or_else(|| HarnessError::FixtureFormat("report has no packet_id".to_owned()))?;
3798
3799    Ok(ParityGateConfig {
3800        packet_id,
3801        strict: StrictGateConfig {
3802            critical_drift_budget: 0,
3803            non_critical_drift_budget_percent: 0.1,
3804        },
3805        hardened: HardenedGateConfig {
3806            divergence_budget_percent: 1.0,
3807            allowlisted_divergence_categories: None,
3808        },
3809        machine_check: MachineCheckConfig {
3810            suite: "phase2c_packets".to_owned(),
3811            require_fixture_count_at_least: report.fixture_count,
3812            require_failed: 0,
3813        },
3814    })
3815}
3816
3817fn load_or_create_parity_gate(
3818    config: &HarnessConfig,
3819    report: &PacketParityReport,
3820) -> Result<ParityGateConfig, HarnessError> {
3821    let packet_id = report
3822        .packet_id
3823        .clone()
3824        .ok_or_else(|| HarnessError::FixtureFormat("report has no packet_id".to_owned()))?;
3825    let gate_path = config.parity_gate_path(&packet_id);
3826
3827    if gate_path.exists() {
3828        return Ok(serde_yaml::from_str(&fs::read_to_string(&gate_path)?)?);
3829    }
3830
3831    let gate = synthesize_parity_gate(report)?;
3832    if let Some(parent) = gate_path.parent() {
3833        fs::create_dir_all(parent)?;
3834    }
3835    fs::write(&gate_path, serde_yaml::to_string(&gate)?)?;
3836    Ok(gate)
3837}
3838
3839#[derive(Debug, Serialize, Deserialize)]
3840struct OracleRequest {
3841    operation: FixtureOperation,
3842    left: Option<FixtureSeries>,
3843    right: Option<FixtureSeries>,
3844    #[serde(default)]
3845    series: Option<FixtureSeries>,
3846    #[serde(default)]
3847    groupby_keys: Option<Vec<FixtureSeries>>,
3848    #[serde(default)]
3849    groupby_columns: Option<Vec<String>>,
3850    #[serde(default)]
3851    groupby_observed: Option<bool>,
3852    #[serde(
3853        default,
3854        deserialize_with = "deserialize_ordered_func_map",
3855        serialize_with = "serialize_ordered_func_map"
3856    )]
3857    groupby_agg_multi: Option<OrderedFuncMap>,
3858    frame: Option<FixtureDataFrame>,
3859    #[serde(default)]
3860    expr: Option<String>,
3861    #[serde(default)]
3862    locals: Option<BTreeMap<String, Scalar>>,
3863    #[serde(default)]
3864    frame_right: Option<FixtureDataFrame>,
3865    #[serde(default)]
3866    frame_other: Option<FixtureDataFrame>,
3867    #[serde(default)]
3868    dict_columns: Option<BTreeMap<String, Vec<Scalar>>>,
3869    #[serde(default)]
3870    column_order: Option<Vec<String>>,
3871    #[serde(default)]
3872    records: Option<Vec<BTreeMap<String, Scalar>>>,
3873    #[serde(default)]
3874    matrix_rows: Option<Vec<Vec<Scalar>>>,
3875    index: Option<Vec<IndexLabel>>,
3876    join_type: Option<FixtureJoinType>,
3877    merge_on: Option<String>,
3878    #[serde(default)]
3879    merge_on_keys: Option<Vec<String>>,
3880    #[serde(default)]
3881    left_on_keys: Option<Vec<String>>,
3882    #[serde(default)]
3883    right_on_keys: Option<Vec<String>>,
3884    #[serde(default)]
3885    left_index: Option<bool>,
3886    #[serde(default)]
3887    right_index: Option<bool>,
3888    #[serde(default)]
3889    merge_indicator: Option<bool>,
3890    #[serde(default)]
3891    merge_indicator_name: Option<String>,
3892    #[serde(default)]
3893    merge_validate: Option<String>,
3894    #[serde(default)]
3895    merge_suffixes: Option<[Option<String>; 2]>,
3896    #[serde(default)]
3897    merge_sort: Option<bool>,
3898    #[serde(default)]
3899    fill_value: Option<Scalar>,
3900    #[serde(default)]
3901    constructor_dtype: Option<String>,
3902    #[serde(default)]
3903    datetime_unit: Option<String>,
3904    #[serde(default)]
3905    datetime_origin: Option<serde_json::Value>,
3906    #[serde(default)]
3907    datetime_utc: Option<bool>,
3908    #[serde(default)]
3909    pub head_n: Option<i64>,
3910    #[serde(default)]
3911    pub tail_n: Option<i64>,
3912    #[serde(default)]
3913    pub diff_periods: Option<i64>,
3914    #[serde(default)]
3915    pub shift_periods: Option<i64>,
3916    #[serde(default)]
3917    pub shift_axis: Option<usize>,
3918    #[serde(default)]
3919    pub pct_change_periods: Option<i64>,
3920    #[serde(default)]
3921    pub pct_change_axis: Option<usize>,
3922    #[serde(default)]
3923    pub mode_dropna: Option<bool>,
3924    #[serde(default)]
3925    pub idxmin_skipna: Option<bool>,
3926    #[serde(default)]
3927    pub idxmax_skipna: Option<bool>,
3928    #[serde(default)]
3929    pub argmin_skipna: Option<bool>,
3930    #[serde(default)]
3931    pub argmax_skipna: Option<bool>,
3932    #[serde(default)]
3933    pub searchsorted_value: Option<Scalar>,
3934    #[serde(default)]
3935    pub searchsorted_side: Option<String>,
3936    #[serde(default)]
3937    pub autocorr_lag: Option<usize>,
3938    #[serde(default)]
3939    pub diff_axis: Option<usize>,
3940    #[serde(default)]
3941    pub clip_lower: Option<f64>,
3942    #[serde(default)]
3943    pub clip_upper: Option<f64>,
3944    #[serde(default)]
3945    pub clip_lower_series: Option<FixtureSeries>,
3946    #[serde(default)]
3947    pub clip_upper_series: Option<FixtureSeries>,
3948    #[serde(default)]
3949    pub round_decimals: Option<i32>,
3950    #[serde(default)]
3951    pub dataframe_binary_method: Option<String>,
3952    #[serde(default)]
3953    pub rank_method: Option<String>,
3954    #[serde(default)]
3955    pub rank_na_option: Option<String>,
3956    #[serde(default)]
3957    pub rank_axis: Option<usize>,
3958    #[serde(default)]
3959    pub rank_pct: Option<bool>,
3960    #[serde(default)]
3961    pub corr_method: Option<String>,
3962    #[serde(default)]
3963    pub corr_min_periods: Option<usize>,
3964    #[serde(default)]
3965    pub corr_numeric_only: Option<bool>,
3966    /// pandas 2.x `numeric_only` for the DataFrame reduction family.
3967    /// Absent = pandas' own default, which is what every fixture predating
3968    /// br-frankenpandas-reductions-numeric-only-default-zx21n relies on.
3969    /// Paired with the oracle's `reduction_numeric_only_kwargs`, so a
3970    /// fixture states the path once and BOTH sides honour it — an option
3971    /// only one side reads is the latent defect 9s0c4 catalogued.
3972    #[serde(default)]
3973    pub sum_numeric_only: Option<bool>,
3974    #[serde(default)]
3975    pub mean_numeric_only: Option<bool>,
3976    #[serde(default)]
3977    pub min_numeric_only: Option<bool>,
3978    #[serde(default)]
3979    pub max_numeric_only: Option<bool>,
3980    #[serde(default)]
3981    pub prod_numeric_only: Option<bool>,
3982    #[serde(default)]
3983    pub median_numeric_only: Option<bool>,
3984    #[serde(default)]
3985    pub std_numeric_only: Option<bool>,
3986    #[serde(default)]
3987    pub var_numeric_only: Option<bool>,
3988    #[serde(default)]
3989    pub sem_numeric_only: Option<bool>,
3990    #[serde(default)]
3991    pub skew_numeric_only: Option<bool>,
3992    #[serde(default)]
3993    pub kurtosis_numeric_only: Option<bool>,
3994    #[serde(default)]
3995    pub count_numeric_only: Option<bool>,
3996    #[serde(default)]
3997    pub quantile_numeric_only: Option<bool>,
3998    #[serde(default)]
3999    pub sort_column: Option<String>,
4000    #[serde(default)]
4001    sort_ascending: Option<bool>,
4002    #[serde(default)]
4003    sort_na_position: Option<String>,
4004    #[serde(default)]
4005    value_counts_normalize: Option<bool>,
4006    #[serde(default)]
4007    value_counts_dropna: Option<bool>,
4008    #[serde(default)]
4009    frame_name: Option<String>,
4010    #[serde(default)]
4011    memory_usage_index: Option<bool>,
4012    #[serde(default)]
4013    memory_usage_deep: Option<bool>,
4014    #[serde(default)]
4015    concat_axis: Option<i64>,
4016    #[serde(default)]
4017    concat_join: Option<String>,
4018    #[serde(default)]
4019    set_index_column: Option<String>,
4020    #[serde(default)]
4021    set_index_drop: Option<bool>,
4022    #[serde(default)]
4023    set_index_verify_integrity: Option<bool>,
4024    #[serde(default)]
4025    reset_index_drop: Option<bool>,
4026    #[serde(default)]
4027    insert_loc: Option<usize>,
4028    #[serde(default)]
4029    insert_column: Option<String>,
4030    #[serde(default)]
4031    insert_values: Option<Vec<Scalar>>,
4032    #[serde(default)]
4033    assignments: Option<Vec<FixtureColumnAssignment>>,
4034    #[serde(default)]
4035    rename_columns: Option<Vec<FixtureColumnRename>>,
4036    #[serde(default)]
4037    reindex_labels: Option<Vec<IndexLabel>>,
4038    #[serde(default)]
4039    reindex_columns: Option<Vec<String>>,
4040    #[serde(default)]
4041    drop_columns: Option<Vec<String>>,
4042    #[serde(default)]
4043    replace_to_find: Option<Vec<Scalar>>,
4044    #[serde(default)]
4045    replace_to_value: Option<Vec<Scalar>>,
4046    #[serde(default)]
4047    na_action_ignore: Option<bool>,
4048    #[serde(default)]
4049    categorical_categories: Option<Vec<Scalar>>,
4050    #[serde(default)]
4051    categorical_ordered: Option<bool>,
4052    #[serde(default)]
4053    subset: Option<Vec<String>>,
4054    #[serde(default)]
4055    keep: Option<String>,
4056    #[serde(default)]
4057    ignore_index: Option<bool>,
4058    #[serde(default)]
4059    explode_column: Option<String>,
4060    #[serde(default)]
4061    csv_input: Option<String>,
4062    #[serde(default)]
4063    csv_decimal: Option<String>,
4064    #[serde(default)]
4065    csv_on_bad_lines: Option<String>,
4066    #[serde(default)]
4067    csv_parse_dates: Option<Vec<String>>,
4068    #[serde(default)]
4069    csv_parse_date_combinations: Option<Vec<Vec<String>>>,
4070    #[serde(default)]
4071    csv_true_values: Option<Vec<String>>,
4072    #[serde(default)]
4073    csv_false_values: Option<Vec<String>>,
4074    #[serde(default)]
4075    loc_labels: Option<Vec<IndexLabel>>,
4076    #[serde(default)]
4077    iloc_positions: Option<Vec<i64>>,
4078    #[serde(default)]
4079    take_indices: Option<Vec<i64>>,
4080    #[serde(default)]
4081    filter_items: Option<Vec<String>>,
4082    #[serde(default)]
4083    filter_like: Option<String>,
4084    #[serde(default)]
4085    filter_regex: Option<String>,
4086    #[serde(default)]
4087    filter_axis: Option<usize>,
4088    #[serde(default)]
4089    repeat_n: Option<i64>,
4090    #[serde(default)]
4091    repeat_counts: Option<Vec<i64>>,
4092    #[serde(default)]
4093    group_name: Option<String>,
4094    #[serde(default)]
4095    xs_key: Option<IndexLabel>,
4096    #[serde(default)]
4097    xs_level: Option<usize>,
4098    #[serde(default)]
4099    cut_bins: Option<usize>,
4100    #[serde(default)]
4101    qcut_quantiles: Option<usize>,
4102    #[serde(default)]
4103    take_axis: Option<usize>,
4104    #[serde(default)]
4105    asof_label: Option<IndexLabel>,
4106    #[serde(default)]
4107    time_value: Option<String>,
4108    #[serde(default)]
4109    start_time: Option<String>,
4110    #[serde(default)]
4111    end_time: Option<String>,
4112    #[serde(default)]
4113    string_sep: Option<String>,
4114    #[serde(default)]
4115    regex_pattern: Option<String>,
4116    #[serde(default)]
4117    str_prefix: Option<String>,
4118    #[serde(default)]
4119    str_suffix: Option<String>,
4120    #[serde(default)]
4121    replace_value: Option<String>,
4122    #[serde(default)]
4123    str_pad_side: Option<String>,
4124    #[serde(default)]
4125    str_repeat_n: Option<usize>,
4126    #[serde(default)]
4127    str_normalize_form: Option<String>,
4128    #[serde(default)]
4129    str_slice_start: Option<i64>,
4130    #[serde(default)]
4131    str_slice_end: Option<i64>,
4132    #[serde(default)]
4133    str_slice_step: Option<i64>,
4134    #[serde(default)]
4135    str_split_pat: Option<String>,
4136    #[serde(default)]
4137    str_split_n: Option<usize>,
4138    #[serde(default)]
4139    str_sub: Option<String>,
4140    #[serde(default)]
4141    str_get_index: Option<i64>,
4142    #[serde(default)]
4143    str_fillchar: Option<char>,
4144    #[serde(default)]
4145    str_width: Option<usize>,
4146    #[serde(default)]
4147    str_wrap_width: Option<usize>,
4148    #[serde(default)]
4149    str_expandtabs_size: Option<usize>,
4150    #[serde(default)]
4151    str_findall_sep: Option<String>,
4152    #[serde(default)]
4153    str_join_sep: Option<String>,
4154    #[serde(default)]
4155    str_translate_from: Option<String>,
4156    #[serde(default)]
4157    str_translate_to: Option<String>,
4158    #[serde(default)]
4159    nlargest_n: Option<usize>,
4160    #[serde(default)]
4161    between_left: Option<Scalar>,
4162    #[serde(default)]
4163    between_right: Option<Scalar>,
4164    // br-frankenpandas-00de2: declared on PacketFixture and read by the FP arm,
4165    // but never copied into this payload, so the oracle always ran pandas'
4166    // default `inclusive="both"` and four live between tests pinned the
4167    // wrong expectation the moment the oracle actually executed.
4168    #[serde(default)]
4169    between_inclusive: Option<String>,
4170    // Same defect class, found by a census of PacketFixture fields against
4171    // this struct: every option below is read by the FrankenPandas arm and by
4172    // pandas_oracle.py, but was never forwarded, so the oracle silently ran
4173    // pandas' DEFAULT for it and the live test compared FP against the wrong
4174    // question (merge_asof direction/tolerance/allow_exact_matches/by,
4175    // merge_ordered fill_method, DataFrame.compare result_names,
4176    // constructor copy, str.wrap drop_whitespace).
4177    #[serde(default)]
4178    direction: Option<String>,
4179    #[serde(default)]
4180    allow_exact_matches: Option<bool>,
4181    #[serde(default)]
4182    tolerance: Option<f64>,
4183    // PacketFixture serializes this field as `by`, and that is the key the
4184    // oracle's merge_asof handler reads.
4185    #[serde(default, rename = "by")]
4186    merge_asof_by: Option<Vec<String>>,
4187    #[serde(default)]
4188    merge_fill_method: Option<String>,
4189    #[serde(default)]
4190    compare_result_names: Option<[String; 2]>,
4191    #[serde(default)]
4192    constructor_copy: Option<bool>,
4193    #[serde(default)]
4194    str_wrap_drop_whitespace: Option<bool>,
4195    // These five were never forwarded either; the oracle rejected the op
4196    // ("requires str_patterns: list[str]") and the harness rendered that
4197    // rejection as OracleUnavailable, so 9 str.*_any / JSON tests passed by
4198    // skipping while looking like a missing oracle.
4199    #[serde(default)]
4200    str_patterns: Option<Vec<String>>,
4201    #[serde(default)]
4202    str_join_from: Option<String>,
4203    #[serde(default)]
4204    json_input: Option<String>,
4205    #[serde(default)]
4206    json_orient: Option<String>,
4207    #[serde(default)]
4208    jsonl_input: Option<String>,
4209    #[serde(default)]
4210    melt_id_vars: Option<Vec<String>>,
4211    #[serde(default)]
4212    melt_value_vars: Option<Vec<String>>,
4213    #[serde(default)]
4214    melt_var_name: Option<String>,
4215    #[serde(default)]
4216    melt_value_name: Option<String>,
4217    #[serde(default)]
4218    pivot_values: Option<Vec<String>>,
4219    #[serde(default)]
4220    pivot_index: Option<String>,
4221    #[serde(default)]
4222    pivot_columns: Option<String>,
4223    #[serde(default)]
4224    pivot_aggfunc: Option<String>,
4225    #[serde(default)]
4226    pivot_margins: Option<bool>,
4227    #[serde(default)]
4228    pivot_dropna: Option<bool>,
4229    #[serde(default)]
4230    pivot_sort: Option<bool>,
4231    #[serde(default)]
4232    pivot_margins_name: Option<String>,
4233    #[serde(default)]
4234    dummy_columns: Option<Vec<String>>,
4235    #[serde(default)]
4236    crosstab_normalize: Option<String>,
4237    #[serde(default)]
4238    window_size: Option<usize>,
4239    #[serde(default)]
4240    min_periods: Option<usize>,
4241    #[serde(default)]
4242    window_center: Option<bool>,
4243    #[serde(default)]
4244    ewm_span: Option<f64>,
4245    #[serde(default)]
4246    ewm_alpha: Option<f64>,
4247    #[serde(default)]
4248    resample_freq: Option<String>,
4249    #[serde(default)]
4250    resample_limit: Option<usize>,
4251    #[serde(default)]
4252    resample_closed: Option<String>,
4253    #[serde(default)]
4254    resample_label: Option<String>,
4255    #[serde(default)]
4256    resample_origin: Option<String>,
4257    #[serde(default)]
4258    quantile_value: Option<f64>,
4259    #[serde(default)]
4260    dt_freq: Option<String>,
4261    #[serde(default)]
4262    dt_tz: Option<String>,
4263    #[serde(default)]
4264    dt_strftime_format: Option<String>,
4265    #[serde(default)]
4266    dt_how: Option<String>,
4267    #[serde(default)]
4268    dt_warn: Option<bool>,
4269}
4270
4271#[derive(Debug, Serialize, Deserialize)]
4272struct OracleResponse {
4273    #[serde(default)]
4274    expected_series: Option<FixtureExpectedSeries>,
4275    #[serde(default)]
4276    expected_join: Option<FixtureExpectedJoin>,
4277    #[serde(default)]
4278    expected_frame: Option<FixtureExpectedDataFrame>,
4279    #[serde(default)]
4280    expected_alignment: Option<FixtureExpectedAlignment>,
4281    #[serde(default)]
4282    expected_bool: Option<bool>,
4283    #[serde(default)]
4284    expected_positions: Option<Vec<Option<usize>>>,
4285    #[serde(default)]
4286    expected_scalar: Option<Scalar>,
4287    #[serde(default)]
4288    expected_dtype: Option<String>,
4289    #[serde(default)]
4290    fixture_provenance: Option<FixtureProvenance>,
4291    #[serde(default)]
4292    error: Option<String>,
4293    /// Where `error` came from (pandas_oracle.py ERROR_ORIGIN_*).
4294    #[serde(default)]
4295    error_origin: Option<String>,
4296}
4297
4298/// Classify an oracle error response by the origin the oracle self-reports.
4299///
4300/// Only a pandas that never loaded (or a response too old to say) is
4301/// unavailability. Every error response used to become `OracleUnavailable`,
4302/// which the live-oracle tests skip on, so a case where pandas raised and
4303/// FrankenPandas returned a value passed by skipping
4304/// (br-frankenpandas-rc0923-epic-rust-parity-bugs-4qg5w.2).
4305fn classify_oracle_error(
4306    error: String,
4307    origin: Option<&str>,
4308    require_live_oracle: bool,
4309) -> HarnessError {
4310    match origin {
4311        Some("pandas") => HarnessError::OracleRaised(error),
4312        Some("oracle_adapter" | "request" | "unexpected") => {
4313            HarnessError::OracleAdapterRefused(error)
4314        }
4315        _ if require_live_oracle => HarnessError::LiveOracleRequired(error),
4316        _ => HarnessError::OracleUnavailable(error),
4317    }
4318}
4319
4320#[derive(Debug, Clone, PartialEq)]
4321enum ResolvedExpected {
4322    Series(FixtureExpectedSeries),
4323    Join(FixtureExpectedJoin),
4324    Frame(FixtureExpectedDataFrame),
4325    ErrorContains(String),
4326    ErrorAny,
4327    Alignment(FixtureExpectedAlignment),
4328    Bool(bool),
4329    Positions(Vec<Option<usize>>),
4330    Scalar(Scalar),
4331    Dtype(String),
4332}
4333
4334pub fn run_packet_suite(config: &HarnessConfig) -> Result<PacketParityReport, HarnessError> {
4335    run_packet_suite_with_options(config, &SuiteOptions::default())
4336}
4337
4338pub fn run_packet_suite_with_options(
4339    config: &HarnessConfig,
4340    options: &SuiteOptions,
4341) -> Result<PacketParityReport, HarnessError> {
4342    let fixtures = load_fixtures(config, options.packet_filter.as_deref())?;
4343    build_report(
4344        config,
4345        "phase2c_packets".to_owned(),
4346        None,
4347        &fixtures,
4348        options,
4349    )
4350}
4351
4352pub fn run_packet_by_id(
4353    config: &HarnessConfig,
4354    packet_id: &str,
4355    oracle_mode: OracleMode,
4356) -> Result<PacketParityReport, HarnessError> {
4357    let options = SuiteOptions {
4358        packet_filter: Some(packet_id.to_owned()),
4359        oracle_mode,
4360    };
4361    let fixtures = load_fixtures(config, Some(packet_id))?;
4362    build_report(
4363        config,
4364        format!("phase2c_packets:{packet_id}"),
4365        Some(packet_id.to_owned()),
4366        &fixtures,
4367        &options,
4368    )
4369}
4370
4371pub fn run_packets_grouped(
4372    config: &HarnessConfig,
4373    options: &SuiteOptions,
4374) -> Result<Vec<PacketParityReport>, HarnessError> {
4375    let fixtures = load_fixtures(config, options.packet_filter.as_deref())?;
4376    let mut grouped = BTreeMap::<String, Vec<PacketFixture>>::new();
4377    for fixture in fixtures {
4378        grouped
4379            .entry(fixture.packet_id.clone())
4380            .or_default()
4381            .push(fixture);
4382    }
4383
4384    let mut reports = Vec::with_capacity(grouped.len());
4385    for (packet_id, mut packet_fixtures) in grouped {
4386        packet_fixtures.sort_by(|a, b| a.case_id.cmp(&b.case_id));
4387        reports.push(build_report(
4388            config,
4389            format!("phase2c_packets:{packet_id}"),
4390            Some(packet_id),
4391            &packet_fixtures,
4392            options,
4393        )?);
4394    }
4395    Ok(reports)
4396}
4397
4398pub fn write_grouped_artifacts(
4399    config: &HarnessConfig,
4400    reports: &[PacketParityReport],
4401) -> Result<Vec<WrittenPacketArtifacts>, HarnessError> {
4402    reports
4403        .iter()
4404        .map(|report| write_packet_artifacts(config, report))
4405        .collect()
4406}
4407
4408pub fn enforce_packet_gates(
4409    config: &HarnessConfig,
4410    reports: &[PacketParityReport],
4411) -> Result<(), HarnessError> {
4412    ensure_phase2c_parity_reports(config)?;
4413    let mut failures = Vec::new();
4414    for report in reports {
4415        let packet_id = report.packet_id.as_deref().unwrap_or("<unknown>");
4416        if !report.is_green() {
4417            failures.push(format!(
4418                "{packet_id}: parity report failed fixtures={}",
4419                report.failed
4420            ));
4421        }
4422        let gate = evaluate_parity_gate(config, report)?;
4423        if !gate.pass {
4424            failures.push(format!(
4425                "{packet_id}: gate failed reasons={}",
4426                gate.reasons.join("; ")
4427            ));
4428        }
4429    }
4430
4431    if failures.is_empty() {
4432        Ok(())
4433    } else {
4434        Err(HarnessError::FixtureFormat(format!(
4435            "phase2c enforcement failed: {}",
4436            failures.join(" | ")
4437        )))
4438    }
4439}
4440
4441pub fn append_phase2c_drift_history(
4442    config: &HarnessConfig,
4443    reports: &[PacketParityReport],
4444) -> Result<PathBuf, HarnessError> {
4445    let history_path = config
4446        .repo_root
4447        .join("artifacts/phase2c/drift_history.jsonl");
4448    if let Some(parent) = history_path.parent() {
4449        fs::create_dir_all(parent)?;
4450    }
4451
4452    let mut file = fs::OpenOptions::new()
4453        .create(true)
4454        .append(true)
4455        .open(&history_path)?;
4456
4457    for report in reports {
4458        let gate = evaluate_parity_gate(config, report)?;
4459        let report_json = serde_json::to_vec(report)?;
4460        let entry = PacketDriftHistoryEntry {
4461            ts_unix_ms: now_unix_ms(),
4462            packet_id: report
4463                .packet_id
4464                .clone()
4465                .unwrap_or_else(|| "<unknown>".to_owned()),
4466            suite: report.suite.clone(),
4467            fixture_count: report.fixture_count,
4468            passed: report.passed,
4469            failed: report.failed,
4470            strict_failed: gate.strict_failed,
4471            hardened_failed: gate.hardened_failed,
4472            gate_pass: gate.pass,
4473            report_hash: format!("sha256:{}", hash_bytes(&report_json)),
4474        };
4475        writeln!(file, "{}", serde_json::to_string(&entry)?)?;
4476    }
4477
4478    Ok(history_path)
4479}
4480
4481/// Newest drift-ledger row per packet id. The ledger is append-ordered, so the
4482/// last row for a packet wins. A missing ledger yields an empty map and callers
4483/// keep their pre-ledger behavior.
4484fn latest_drift_rows_by_packet(
4485    config: &HarnessConfig,
4486) -> Result<BTreeMap<String, PacketDriftHistoryEntry>, HarnessError> {
4487    let path = config
4488        .repo_root
4489        .join("artifacts/phase2c/drift_history.jsonl");
4490    let mut map = BTreeMap::new();
4491    if !path.exists() {
4492        return Ok(map);
4493    }
4494    for line in fs::read_to_string(&path)?.lines() {
4495        if line.trim().is_empty() {
4496            continue;
4497        }
4498        if let Ok(entry) = serde_json::from_str::<PacketDriftHistoryEntry>(line) {
4499            map.insert(entry.packet_id.clone(), entry);
4500        }
4501    }
4502    Ok(map)
4503}
4504
4505/// Outcome of a per-packet gate reconciliation attempt.
4506#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4507pub enum GateReconciliation {
4508    /// On-disk gate already agrees with the newest drift row (or the drift row
4509    /// itself carries the reconciliation stamp); nothing was written.
4510    UpToDate,
4511    /// The on-disk gate disagreed with the newest drift row and was rewritten
4512    /// from it, with the drift provenance stamped into the artifact.
4513    Reconciled,
4514}
4515/// Bring one packet's on-disk `parity_gate_result.json` in line with its
4516/// newest drift-ledger row.
4517///
4518/// Reconciliation fires ONLY when the on-disk gate verdict DISAGREES with the
4519/// newer drift row. A real packet run writes its detailed artifacts and its
4520/// drift row in the same invocation, so an agreeing gate is a real artifact and
4521/// is never overwritten (its per-fixture detail would be lost). A disagreeing
4522/// gate means either a synthetic placeholder or a pre-fix run — the newer drift
4523/// row is the later measurement and wins. The rewritten gate carries the drift
4524/// timestamp + report hash so the artifact records WHICH object it describes.
4525///
4526/// Idempotent: after reconciliation the verdicts agree and the next call is a
4527/// no-op.
4528pub fn reconcile_packet_gate_with_drift(
4529    config: &HarnessConfig,
4530    packet_id: &str,
4531    entry: &PacketDriftHistoryEntry,
4532) -> Result<GateReconciliation, HarnessError> {
4533    let gate_path = config
4534        .packet_artifact_root(packet_id)
4535        .join("parity_gate_result.json");
4536    let on_disk = fs::read_to_string(&gate_path).ok();
4537    if let Some(body) = on_disk.as_deref() {
4538        let agrees = serde_json::from_str::<serde_json::Value>(body)
4539            .ok()
4540            .and_then(|gate| gate.get("pass").and_then(|p| p.as_bool()))
4541            == Some(entry.gate_pass);
4542        let already_stamped = body.contains(&format!("\"drift_ts_unix_ms\": {}", entry.ts_unix_ms));
4543        if agrees || already_stamped {
4544            return Ok(GateReconciliation::UpToDate);
4545        }
4546    }
4547
4548    // Reconstruct the run from the drift row's own counts and push it through
4549    // the normal artifact writer so report, sidecar, decode proof, gate, and
4550    // mismatch corpus all stay mutually consistent.
4551    let report = PacketParityReport {
4552        suite: entry.suite.clone(),
4553        packet_id: Some(packet_id.to_owned()),
4554        oracle_present: config.oracle_reachable(),
4555        fixture_count: entry.fixture_count,
4556        passed: entry.passed,
4557        failed: entry.failed,
4558        retired: 0,
4559        results: Vec::new(),
4560    };
4561    write_packet_artifacts(config, &report)?;
4562
4563    // Stamp provenance into the freshly written gate artifact.
4564    let gate_path = config
4565        .packet_artifact_root(packet_id)
4566        .join("parity_gate_result.json");
4567    let mut gate: serde_json::Value = serde_json::from_str(&fs::read_to_string(&gate_path)?)?;
4568    if let Some(obj) = gate.as_object_mut() {
4569        obj.insert(
4570            "source".to_owned(),
4571            serde_json::Value::String("drift_history_reconciliation".to_owned()),
4572        );
4573        obj.insert(
4574            "drift_ts_unix_ms".to_owned(),
4575            serde_json::json!(entry.ts_unix_ms),
4576        );
4577        obj.insert(
4578            "report_hash".to_owned(),
4579            serde_json::Value::String(entry.report_hash.clone()),
4580        );
4581        if entry.gate_pass {
4582            obj.insert("reasons".to_owned(), serde_json::Value::Array(Vec::new()));
4583        }
4584    }
4585    fs::write(&gate_path, serde_json::to_string_pretty(&gate)?)?;
4586    Ok(GateReconciliation::Reconciled)
4587}
4588
4589fn ensure_phase2c_parity_reports(config: &HarnessConfig) -> Result<(), HarnessError> {
4590    let phase_root = config.repo_root.join("artifacts/phase2c");
4591    if !phase_root.exists() {
4592        return Ok(());
4593    }
4594    let packet_root = config.packet_fixture_root();
4595    if !packet_root.exists() {
4596        return Ok(());
4597    }
4598    let mut packet_ids: BTreeSet<String> = BTreeSet::new();
4599    for entry in fs::read_dir(&packet_root)? {
4600        let entry = entry?;
4601        if !entry.file_type()?.is_file() {
4602            continue;
4603        }
4604        let path = entry.path();
4605        if path.extension().and_then(|s| s.to_str()) != Some("json") {
4606            continue;
4607        }
4608        let fixture = load_fixture(&path)?;
4609        packet_ids.insert(fixture.packet_id);
4610    }
4611
4612    let drift = latest_drift_rows_by_packet(config)?;
4613    for packet_id in packet_ids {
4614        // Newer drift verdict disagrees with the on-disk gate: reconcile (the
4615        // helper no-ops when they already agree, so real run artifacts with
4616        // per-fixture detail are never clobbered).
4617        if let Some(entry) = drift.get(&packet_id) {
4618            reconcile_packet_gate_with_drift(config, &packet_id, entry)?;
4619            if phase_root
4620                .join(&packet_id)
4621                .join("parity_report.json")
4622                .exists()
4623            {
4624                continue;
4625            }
4626        }
4627        let fixture_count = load_fixtures(config, Some(&packet_id))?.len();
4628        let synthetic = PacketParityReport {
4629            suite: format!("phase2c_packets:{packet_id}"),
4630            packet_id: Some(packet_id.clone()),
4631            oracle_present: config.oracle_reachable(),
4632            fixture_count,
4633            passed: 0,
4634            failed: fixture_count,
4635            // Nothing ran, so nothing is retired either — this synthetic report
4636            // records an unrun packet as wholly failed, not partly skipped.
4637            retired: 0,
4638            results: Vec::new(),
4639        };
4640        write_packet_artifacts(config, &synthetic)?;
4641    }
4642    Ok(())
4643}
4644
4645// === Differential Harness: Public API ===
4646
4647/// Run a differential suite over all matching fixtures with taxonomy-based comparison.
4648pub fn run_differential_suite(
4649    config: &HarnessConfig,
4650    options: &SuiteOptions,
4651) -> Result<DifferentialReport, HarnessError> {
4652    let fixtures = load_fixtures(config, options.packet_filter.as_deref())?;
4653    build_differential_report_internal(
4654        config,
4655        "phase2c_packets".to_owned(),
4656        None,
4657        &fixtures,
4658        options,
4659    )
4660}
4661
4662/// Run a differential suite filtered by packet ID.
4663pub fn run_differential_by_id(
4664    config: &HarnessConfig,
4665    packet_id: &str,
4666    oracle_mode: OracleMode,
4667) -> Result<DifferentialReport, HarnessError> {
4668    let options = SuiteOptions {
4669        packet_filter: Some(packet_id.to_owned()),
4670        oracle_mode,
4671    };
4672    let fixtures = load_fixtures(config, Some(packet_id))?;
4673    build_differential_report_internal(
4674        config,
4675        format!("phase2c_packets:{packet_id}"),
4676        Some(packet_id.to_owned()),
4677        &fixtures,
4678        &options,
4679    )
4680}
4681
4682/// Build a DifferentialReport from pre-computed DifferentialResults.
4683#[must_use]
4684pub fn build_differential_report(
4685    suite: String,
4686    packet_id: Option<String>,
4687    oracle_present: bool,
4688    results: Vec<DifferentialResult>,
4689) -> DifferentialReport {
4690    let drift_summary = summarize_drift(&results);
4691    let case_results: Vec<CaseResult> = results
4692        .iter()
4693        .map(DifferentialResult::to_case_result)
4694        .collect();
4695    let failed = case_results
4696        .iter()
4697        .filter(|r| matches!(r.status, CaseStatus::Fail))
4698        .count();
4699    // br-frankenpandas-fixture-corpus-stale-vs-oracle-p6srr: count PASSES, do
4700    // not infer them as "everything that did not fail". Under the old
4701    // `len - failed` arithmetic a RETIRED case — which was never executed —
4702    // silently counted as a pass, making a skipped fixture indistinguishable
4703    // from a checked one. Retired cases stay in `fixture_count`, so
4704    // `passed + failed + retired == fixture_count` and the gap is visible.
4705    let passed = case_results
4706        .iter()
4707        .filter(|r| matches!(r.status, CaseStatus::Pass))
4708        .count();
4709    let retired = case_results
4710        .iter()
4711        .filter(|r| matches!(r.status, CaseStatus::Retired))
4712        .count();
4713    DifferentialReport {
4714        report: PacketParityReport {
4715            suite,
4716            packet_id,
4717            oracle_present,
4718            fixture_count: case_results.len(),
4719            passed,
4720            failed,
4721            retired,
4722            results: case_results,
4723        },
4724        differential_results: results,
4725        drift_summary,
4726    }
4727}
4728
4729#[must_use]
4730pub fn build_differential_validation_log(
4731    report: &DifferentialReport,
4732) -> Vec<DifferentialValidationLogEntry> {
4733    let mut entries: Vec<_> = report
4734        .differential_results
4735        .iter()
4736        .map(|result| DifferentialValidationLogEntry {
4737            packet_id: result.packet_id.clone(),
4738            case_id: result.case_id.clone(),
4739            mode: result.mode,
4740            trace_id: if result.trace_id.is_empty() {
4741                deterministic_trace_id(&result.packet_id, &result.case_id, result.mode)
4742            } else {
4743                result.trace_id.clone()
4744            },
4745            oracle_source: result.oracle_source,
4746            mismatch_class: result
4747                .drift_records
4748                .iter()
4749                .find(|record| matches!(record.level, DriftLevel::Critical))
4750                .or_else(|| result.drift_records.first())
4751                .map(|record| record.mismatch_class.clone())
4752                .unwrap_or_else(|| "none".to_owned()),
4753            replay_key: if result.replay_key.is_empty() {
4754                deterministic_replay_key(&result.packet_id, &result.case_id, result.mode)
4755            } else {
4756                result.replay_key.clone()
4757            },
4758        })
4759        .collect();
4760
4761    entries.sort_by(|a, b| {
4762        (
4763            a.packet_id.as_str(),
4764            a.case_id.as_str(),
4765            runtime_mode_slug(a.mode),
4766        )
4767            .cmp(&(
4768                b.packet_id.as_str(),
4769                b.case_id.as_str(),
4770                runtime_mode_slug(b.mode),
4771            ))
4772    });
4773    entries
4774}
4775
4776pub fn write_differential_validation_log(
4777    config: &HarnessConfig,
4778    report: &DifferentialReport,
4779) -> Result<PathBuf, HarnessError> {
4780    let entries = build_differential_validation_log(report);
4781    let output_path = if let Some(packet_id) = &report.report.packet_id {
4782        config
4783            .packet_artifact_root(packet_id)
4784            .join("differential_validation_log.jsonl")
4785    } else {
4786        config
4787            .repo_root
4788            .join("artifacts/phase2c/differential_validation_log.jsonl")
4789    };
4790
4791    if let Some(parent) = output_path.parent() {
4792        fs::create_dir_all(parent)?;
4793    }
4794
4795    let mut file = fs::File::create(&output_path)?;
4796    for entry in entries {
4797        writeln!(file, "{}", serde_json::to_string(&entry)?)?;
4798    }
4799
4800    Ok(output_path)
4801}
4802
4803pub fn run_fault_injection_validation_by_id(
4804    config: &HarnessConfig,
4805    packet_id: &str,
4806    oracle_mode: OracleMode,
4807) -> Result<FaultInjectionValidationReport, HarnessError> {
4808    let options = SuiteOptions {
4809        packet_filter: Some(packet_id.to_owned()),
4810        oracle_mode,
4811    };
4812    let mut fixtures = load_fixtures(config, Some(packet_id))?;
4813    fixtures.sort_by(|a, b| a.case_id.cmp(&b.case_id));
4814
4815    let mut entries = Vec::new();
4816    let mut strict_violation_count = 0usize;
4817    let mut hardened_allowlisted_count = 0usize;
4818
4819    for fixture in fixtures {
4820        for mode in [RuntimeMode::Strict, RuntimeMode::Hardened] {
4821            let mut mode_fixture = fixture.clone();
4822            mode_fixture.mode = mode;
4823            let mut differential = run_differential_fixture(config, &mode_fixture, &options)?;
4824
4825            let (classification, injected_mismatch_class, injected_level) = match mode {
4826                RuntimeMode::Strict => (
4827                    FaultInjectionClassification::StrictViolation,
4828                    "fault_injected_strict_violation",
4829                    DriftLevel::Critical,
4830                ),
4831                RuntimeMode::Hardened => (
4832                    FaultInjectionClassification::HardenedAllowlisted,
4833                    "fault_injected_hardened_allowlist",
4834                    DriftLevel::Informational,
4835                ),
4836            };
4837
4838            if differential.drift_records.is_empty() {
4839                let injected = make_drift_record(
4840                    ComparisonCategory::Value,
4841                    injected_level,
4842                    format!("fault_injection/{}", runtime_mode_slug(mode)),
4843                    format!(
4844                        "synthetic deterministic fault injected for case={} mode={}",
4845                        differential.case_id,
4846                        runtime_mode_slug(mode)
4847                    ),
4848                );
4849                differential.drift_records.push(DriftRecord {
4850                    mismatch_class: injected_mismatch_class.to_owned(),
4851                    ..injected
4852                });
4853            }
4854
4855            let mismatch_class = differential
4856                .drift_records
4857                .iter()
4858                .find(|record| matches!(record.level, DriftLevel::Critical))
4859                .or_else(|| differential.drift_records.first())
4860                .map(|record| record.mismatch_class.clone())
4861                .unwrap_or_else(|| injected_mismatch_class.to_owned());
4862
4863            match classification {
4864                FaultInjectionClassification::StrictViolation => strict_violation_count += 1,
4865                FaultInjectionClassification::HardenedAllowlisted => {
4866                    hardened_allowlisted_count += 1;
4867                }
4868            }
4869
4870            entries.push(FaultInjectionValidationEntry {
4871                packet_id: differential.packet_id,
4872                case_id: differential.case_id,
4873                mode: differential.mode,
4874                trace_id: if differential.trace_id.is_empty() {
4875                    deterministic_trace_id(packet_id, &mode_fixture.case_id, mode)
4876                } else {
4877                    differential.trace_id
4878                },
4879                oracle_source: differential.oracle_source,
4880                mismatch_class,
4881                replay_key: if differential.replay_key.is_empty() {
4882                    deterministic_replay_key(packet_id, &mode_fixture.case_id, mode)
4883                } else {
4884                    differential.replay_key
4885                },
4886                classification,
4887            });
4888        }
4889    }
4890
4891    entries.sort_by(|a, b| {
4892        (
4893            a.case_id.as_str(),
4894            runtime_mode_slug(a.mode),
4895            a.trace_id.as_str(),
4896        )
4897            .cmp(&(
4898                b.case_id.as_str(),
4899                runtime_mode_slug(b.mode),
4900                b.trace_id.as_str(),
4901            ))
4902    });
4903
4904    Ok(FaultInjectionValidationReport {
4905        packet_id: packet_id.to_owned(),
4906        entry_count: entries.len(),
4907        strict_violation_count,
4908        hardened_allowlisted_count,
4909        entries,
4910    })
4911}
4912
4913pub fn write_fault_injection_validation_report(
4914    config: &HarnessConfig,
4915    report: &FaultInjectionValidationReport,
4916) -> Result<PathBuf, HarnessError> {
4917    let output_path = config
4918        .packet_artifact_root(&report.packet_id)
4919        .join("fault_injection_validation.json");
4920
4921    if let Some(parent) = output_path.parent() {
4922        fs::create_dir_all(parent)?;
4923    }
4924
4925    fs::write(&output_path, serde_json::to_string_pretty(report)?)?;
4926    Ok(output_path)
4927}
4928
4929pub fn write_packet_artifacts(
4930    config: &HarnessConfig,
4931    report: &PacketParityReport,
4932) -> Result<WrittenPacketArtifacts, HarnessError> {
4933    let packet_id = report
4934        .packet_id
4935        .as_deref()
4936        .ok_or_else(|| HarnessError::FixtureFormat("packet_id is required".to_owned()))?;
4937
4938    let root = config.packet_artifact_root(packet_id);
4939    fs::create_dir_all(&root)?;
4940
4941    let parity_report_path = root.join("parity_report.json");
4942    fs::write(&parity_report_path, serde_json::to_string_pretty(report)?)?;
4943
4944    let report_bytes = fs::read(&parity_report_path)?;
4945    let mut sidecar = generate_raptorq_sidecar(
4946        &parity_report_artifact_id(packet_id),
4947        "conformance",
4948        &report_bytes,
4949        8,
4950    )?;
4951    let decode_proof = run_raptorq_decode_recovery_drill(&sidecar, &report_bytes)?;
4952    sidecar
4953        .envelope
4954        .push_decode_proof_capped(decode_proof.clone());
4955    sidecar.envelope.scrub = ScrubStatus {
4956        last_ok_unix_ms: sidecar.scrub_report.verified_at_unix_ms,
4957        status: if sidecar.scrub_report.source_hash_verified {
4958            "ok".to_owned()
4959        } else {
4960            "failed".to_owned()
4961        },
4962    };
4963
4964    let raptorq_sidecar_path = root.join("parity_report.raptorq.json");
4965    fs::write(
4966        &raptorq_sidecar_path,
4967        serde_json::to_string_pretty(&sidecar)?,
4968    )?;
4969
4970    let decode_proof_path = root.join("parity_report.decode_proof.json");
4971    let decode_artifact = DecodeProofArtifact {
4972        packet_id: packet_id.to_owned(),
4973        decode_proofs: vec![decode_proof],
4974        status: DecodeProofStatus::Recovered,
4975    };
4976    fs::write(
4977        &decode_proof_path,
4978        serde_json::to_string_pretty(&decode_artifact)?,
4979    )?;
4980
4981    let gate_result = evaluate_parity_gate(config, report)?;
4982    let gate_result_path = root.join("parity_gate_result.json");
4983    fs::write(
4984        &gate_result_path,
4985        serde_json::to_string_pretty(&gate_result)?,
4986    )?;
4987
4988    let mismatch_corpus_path = root.join("parity_mismatch_corpus.json");
4989    let mismatches = report
4990        .results
4991        .iter()
4992        .filter(|result| matches!(result.status, CaseStatus::Fail))
4993        .cloned()
4994        .collect::<Vec<_>>();
4995    let mismatch_payload = serde_json::json!({
4996        "packet_id": packet_id,
4997        "mismatch_count": mismatches.len(),
4998        "mismatches": mismatches,
4999    });
5000    fs::write(
5001        &mismatch_corpus_path,
5002        serde_json::to_string_pretty(&mismatch_payload)?,
5003    )?;
5004
5005    Ok(WrittenPacketArtifacts {
5006        packet_id: packet_id.to_owned(),
5007        parity_report_path,
5008        raptorq_sidecar_path,
5009        decode_proof_path,
5010        gate_result_path,
5011        mismatch_corpus_path,
5012    })
5013}
5014
5015pub fn generate_fixture_pilot_bundle(
5016    config: &HarnessConfig,
5017    request: &FixtureGenerationRequest,
5018) -> Result<GeneratedFixtureBundle, HarnessError> {
5019    let mut fixture =
5020        fixture_generation_template(&request.method_family, &request.packet_id, &request.case_id)?;
5021    let template_matrix = fixture_generation_input_matrix(&request.method_family)?;
5022    let input_matrix = if request.input_matrix.is_empty() {
5023        template_matrix
5024    } else {
5025        request.input_matrix.clone()
5026    };
5027
5028    let response = capture_live_oracle_response_for_generation(config, &fixture)?;
5029    apply_oracle_response_to_generated_fixture(
5030        &mut fixture,
5031        response,
5032        &request.generation_command,
5033        &input_matrix,
5034        &request.intentional_divergence_notes,
5035    )?;
5036
5037    if let Some(parent) = request.output_fixture_path.parent() {
5038        fs::create_dir_all(parent)?;
5039    }
5040    fs::write(
5041        &request.output_fixture_path,
5042        serde_json::to_string_pretty(&fixture)?,
5043    )?;
5044
5045    fs::create_dir_all(&request.artifact_dir)?;
5046    let fixture_bytes = fs::read(&request.output_fixture_path)?;
5047    let fixture_hash = hash_bytes(&fixture_bytes);
5048    let artifact_id = format!("{}/fixture_bundle", request.packet_id);
5049    let mut sidecar = generate_raptorq_sidecar(
5050        &artifact_id,
5051        "fixture_packet",
5052        &fixture_bytes,
5053        request.repair_packets_per_block,
5054    )?;
5055    let decode_proof = run_raptorq_decode_recovery_drill(&sidecar, &fixture_bytes)?;
5056    sidecar
5057        .envelope
5058        .push_decode_proof_capped(decode_proof.clone());
5059    sidecar.envelope.scrub = ScrubStatus {
5060        last_ok_unix_ms: sidecar.scrub_report.verified_at_unix_ms,
5061        status: if sidecar.scrub_report.source_hash_verified {
5062            "ok".to_owned()
5063        } else {
5064            "failed".to_owned()
5065        },
5066    };
5067
5068    let manifest_path = request
5069        .artifact_dir
5070        .join("fixture_generation_manifest.json");
5071    let repair_symbol_manifest_path = request.artifact_dir.join("repair_symbol_manifest.json");
5072    let raptorq_sidecar_path = request.artifact_dir.join("fixture_bundle.raptorq.json");
5073    let integrity_scrub_path = request.artifact_dir.join("integrity_scrub_report.json");
5074    let decode_proof_path = request
5075        .artifact_dir
5076        .join("fixture_bundle.decode_proof.json");
5077
5078    let manifest = serde_json::json!({
5079        "packet_id": request.packet_id.clone(),
5080        "case_id": request.case_id.clone(),
5081        "method_family": request.method_family.clone(),
5082        "fixture_path": relative_to_repo(config, &request.output_fixture_path),
5083        "fixture_sha256": format!("sha256:{fixture_hash}"),
5084        "generation_command": request.generation_command.clone(),
5085        "input_matrix": input_matrix.clone(),
5086        "intentional_divergence_notes": request.intentional_divergence_notes.clone(),
5087        "fixture_provenance": fixture.fixture_provenance.clone(),
5088    });
5089    fs::write(&manifest_path, serde_json::to_string_pretty(&manifest)?)?;
5090
5091    let repair_symbol_hashes = sidecar
5092        .packet_records
5093        .iter()
5094        .filter(|record| !record.is_source)
5095        .map(|record| record.symbol_hash.clone())
5096        .collect::<Vec<_>>();
5097    let repair_manifest = serde_json::json!({
5098        "packet_id": request.packet_id.clone(),
5099        "case_id": request.case_id.clone(),
5100        "artifact_id": sidecar.envelope.artifact_id.clone(),
5101        "source_packets": sidecar.source_packets,
5102        "repair_packets": sidecar.repair_packets,
5103        "repair_packets_per_block": sidecar.repair_packets_per_block,
5104        "repair_symbol_hashes": repair_symbol_hashes,
5105    });
5106    fs::write(
5107        &repair_symbol_manifest_path,
5108        serde_json::to_string_pretty(&repair_manifest)?,
5109    )?;
5110    fs::write(
5111        &raptorq_sidecar_path,
5112        serde_json::to_string_pretty(&sidecar)?,
5113    )?;
5114    fs::write(
5115        &integrity_scrub_path,
5116        serde_json::to_string_pretty(&sidecar.scrub_report)?,
5117    )?;
5118    let decode_artifact = DecodeProofArtifact {
5119        packet_id: request.packet_id.clone(),
5120        decode_proofs: vec![decode_proof],
5121        status: DecodeProofStatus::Recovered,
5122    };
5123    fs::write(
5124        &decode_proof_path,
5125        serde_json::to_string_pretty(&decode_artifact)?,
5126    )?;
5127
5128    Ok(GeneratedFixtureBundle {
5129        packet_id: request.packet_id.clone(),
5130        case_id: request.case_id.clone(),
5131        method_family: request.method_family.clone(),
5132        fixture_path: request.output_fixture_path.clone(),
5133        manifest_path,
5134        repair_symbol_manifest_path,
5135        raptorq_sidecar_path,
5136        integrity_scrub_path,
5137        decode_proof_path,
5138    })
5139}
5140
5141fn fixture_generation_template(
5142    method_family: &str,
5143    packet_id: &str,
5144    case_id: &str,
5145) -> Result<PacketFixture, HarnessError> {
5146    match method_family {
5147        "series_add" | "series-add" | "series_add_basic" | "series-add-basic" => {
5148            serde_json::from_value(serde_json::json!({
5149                "packet_id": packet_id,
5150                "case_id": case_id,
5151                "mode": "strict",
5152                "operation": "series_add",
5153                "left": {
5154                    "name": "left",
5155                    "index": [
5156                        { "kind": "int64", "value": 0 },
5157                        { "kind": "int64", "value": 1 },
5158                        { "kind": "int64", "value": 2 }
5159                    ],
5160                    "values": [
5161                        { "kind": "float64", "value": 1.0 },
5162                        { "kind": "float64", "value": 2.0 },
5163                        { "kind": "float64", "value": 3.0 }
5164                    ]
5165                },
5166                "right": {
5167                    "name": "right",
5168                    "index": [
5169                        { "kind": "int64", "value": 1 },
5170                        { "kind": "int64", "value": 2 },
5171                        { "kind": "int64", "value": 3 }
5172                    ],
5173                    "values": [
5174                        { "kind": "float64", "value": 10.0 },
5175                        { "kind": "float64", "value": 20.0 },
5176                        { "kind": "float64", "value": 30.0 }
5177                    ]
5178                }
5179            }))
5180            .map_err(HarnessError::from)
5181        }
5182        other => Err(HarnessError::FixtureFormat(format!(
5183            "unsupported fixture generation method family: {other}"
5184        ))),
5185    }
5186}
5187
5188fn fixture_generation_input_matrix(method_family: &str) -> Result<Vec<String>, HarnessError> {
5189    match method_family {
5190        "series_add" | "series-add" | "series_add_basic" | "series-add-basic" => Ok(vec![
5191            "operation=series_add".to_owned(),
5192            "mode=strict".to_owned(),
5193            "left.index=[0,1,2]".to_owned(),
5194            "right.index=[1,2,3]".to_owned(),
5195            "overlap=[1,2], left_only=[0], right_only=[3]".to_owned(),
5196            "values=float64 arithmetic with pandas alignment".to_owned(),
5197        ]),
5198        other => Err(HarnessError::FixtureFormat(format!(
5199            "unsupported fixture generation method family: {other}"
5200        ))),
5201    }
5202}
5203
5204fn apply_oracle_response_to_generated_fixture(
5205    fixture: &mut PacketFixture,
5206    mut response: OracleResponse,
5207    generation_command: &str,
5208    input_matrix: &[String],
5209    intentional_divergence_notes: &[String],
5210) -> Result<(), HarnessError> {
5211    if let Some(error) = response.error {
5212        return Err(classify_oracle_error(
5213            error,
5214            response.error_origin.as_deref(),
5215            false,
5216        ));
5217    }
5218
5219    fixture.expected_series = response.expected_series.take();
5220    fixture.expected_join = response.expected_join.take();
5221    fixture.expected_frame = response.expected_frame.take();
5222    fixture.expected_alignment = response.expected_alignment.take();
5223    fixture.expected_bool = response.expected_bool.take();
5224    fixture.expected_positions = response.expected_positions.take();
5225    fixture.expected_scalar = response.expected_scalar.take();
5226    fixture.expected_dtype = response.expected_dtype.take();
5227    fixture.expected_error_contains = None;
5228    fixture.oracle_source = Some(FixtureOracleSource::Fixture);
5229
5230    let has_expected = fixture.expected_series.is_some()
5231        || fixture.expected_join.is_some()
5232        || fixture.expected_frame.is_some()
5233        || fixture.expected_alignment.is_some()
5234        || fixture.expected_bool.is_some()
5235        || fixture.expected_positions.is_some()
5236        || fixture.expected_scalar.is_some()
5237        || fixture.expected_dtype.is_some();
5238    if !has_expected {
5239        return Err(HarnessError::FixtureFormat(format!(
5240            "oracle response for case {} did not contain an expected value",
5241            fixture.case_id
5242        )));
5243    }
5244
5245    let mut provenance = response.fixture_provenance.ok_or_else(|| {
5246        HarnessError::FixtureFormat("oracle response omitted fixture_provenance".to_owned())
5247    })?;
5248    provenance.generation_command = Some(generation_command.to_owned());
5249    provenance.input_matrix = input_matrix.to_vec();
5250    provenance.intentional_divergence_notes = intentional_divergence_notes.to_vec();
5251    fixture.fixture_provenance = Some(provenance);
5252
5253    Ok(())
5254}
5255
5256fn capture_live_oracle_response_for_generation(
5257    config: &HarnessConfig,
5258    fixture: &PacketFixture,
5259) -> Result<OracleResponse, HarnessError> {
5260    fn oracle_unavailable(config: &HarnessConfig, message: String) -> HarnessError {
5261        if config.require_live_oracle {
5262            HarnessError::LiveOracleRequired(message)
5263        } else {
5264            HarnessError::OracleUnavailable(message)
5265        }
5266    }
5267
5268    let allow_system_pandas_fallback = config.allows_system_pandas_fallback();
5269
5270    if !config.oracle_root.exists() && !allow_system_pandas_fallback {
5271        return Err(oracle_unavailable(
5272            config,
5273            format!(
5274                "legacy oracle root does not exist: {}",
5275                config.oracle_root.display()
5276            ),
5277        ));
5278    }
5279    let script = config.oracle_script_path();
5280    if !script.exists() {
5281        return Err(oracle_unavailable(
5282            config,
5283            format!("oracle script does not exist: {}", script.display()),
5284        ));
5285    }
5286
5287    let input = serde_json::to_vec(fixture)?;
5288    let mut child = Command::new(&config.python_bin)
5289        .arg(&script)
5290        .arg("--legacy-root")
5291        .arg(&config.oracle_root)
5292        .arg("--strict-legacy")
5293        .args(allow_system_pandas_fallback.then_some("--allow-system-pandas-fallback"))
5294        .stdin(Stdio::piped())
5295        .stdout(Stdio::piped())
5296        .stderr(Stdio::piped())
5297        .spawn()?;
5298    let stdin_handle = child.stdin.take();
5299    let stdin_writer = std::thread::spawn(move || -> std::io::Result<()> {
5300        use std::io::Write;
5301        if let Some(mut stdin) = stdin_handle {
5302            stdin.write_all(&input)?;
5303        }
5304        Ok(())
5305    });
5306    let output = child.wait_with_output()?;
5307    stdin_writer
5308        .join()
5309        .map_err(|_| std::io::Error::other("oracle stdin writer thread panicked"))??;
5310
5311    if !output.status.success() {
5312        if let Ok(response) = serde_json::from_slice::<OracleResponse>(&output.stdout)
5313            && let Some(error) = response.error
5314        {
5315            return Err(classify_oracle_error(
5316                error,
5317                response.error_origin.as_deref(),
5318                config.require_live_oracle,
5319            ));
5320        }
5321
5322        let code = output.status.code().unwrap_or(-1);
5323        let stderr = String::from_utf8_lossy(&output.stderr).to_string();
5324        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
5325        return Err(HarnessError::OracleCommandFailed {
5326            status: code,
5327            stderr: format!("{stderr}\nstdout={stdout}"),
5328        });
5329    }
5330
5331    serde_json::from_slice(&output.stdout).map_err(HarnessError::from)
5332}
5333
5334pub fn evaluate_parity_gate(
5335    config: &HarnessConfig,
5336    report: &PacketParityReport,
5337) -> Result<PacketGateResult, HarnessError> {
5338    let packet_id = report
5339        .packet_id
5340        .clone()
5341        .ok_or_else(|| HarnessError::FixtureFormat("report has no packet_id".to_owned()))?;
5342    let gate = load_or_create_parity_gate(config, report)?;
5343
5344    let strict_total = report
5345        .results
5346        .iter()
5347        .filter(|result| matches!(result.mode, RuntimeMode::Strict))
5348        .count();
5349    let strict_failed = report
5350        .results
5351        .iter()
5352        .filter(|result| {
5353            matches!(result.mode, RuntimeMode::Strict) && matches!(result.status, CaseStatus::Fail)
5354        })
5355        .count();
5356    let hardened_total = report
5357        .results
5358        .iter()
5359        .filter(|result| matches!(result.mode, RuntimeMode::Hardened))
5360        .count();
5361    let hardened_failed = report
5362        .results
5363        .iter()
5364        .filter(|result| {
5365            matches!(result.mode, RuntimeMode::Hardened)
5366                && matches!(result.status, CaseStatus::Fail)
5367        })
5368        .count();
5369
5370    let strict_failure_percent = percent(strict_failed, strict_total);
5371    let hardened_failure_percent = percent(hardened_failed, hardened_total);
5372
5373    let mut reasons = Vec::new();
5374    if gate.packet_id != packet_id {
5375        reasons.push(format!(
5376            "packet_id mismatch between gate ({}) and report ({packet_id})",
5377            gate.packet_id
5378        ));
5379    }
5380    if gate.machine_check.suite != "phase2c_packets"
5381        && gate.machine_check.suite != report.suite
5382        && !report.suite.starts_with(&gate.machine_check.suite)
5383    {
5384        reasons.push(format!(
5385            "suite mismatch: gate={}, report={}",
5386            gate.machine_check.suite, report.suite
5387        ));
5388    }
5389    if report.fixture_count < gate.machine_check.require_fixture_count_at_least {
5390        reasons.push(format!(
5391            "fixture_count={} below required {}",
5392            report.fixture_count, gate.machine_check.require_fixture_count_at_least
5393        ));
5394    }
5395    if report.failed != gate.machine_check.require_failed {
5396        reasons.push(format!(
5397            "failed={} but gate requires {}",
5398            report.failed, gate.machine_check.require_failed
5399        ));
5400    }
5401    if strict_failed > gate.strict.critical_drift_budget {
5402        reasons.push(format!(
5403            "strict_failed={} exceeds critical_drift_budget={}",
5404            strict_failed, gate.strict.critical_drift_budget
5405        ));
5406    }
5407    if strict_failure_percent > gate.strict.non_critical_drift_budget_percent {
5408        reasons.push(format!(
5409            "strict failure percent {:.3}% exceeds {:.3}%",
5410            strict_failure_percent, gate.strict.non_critical_drift_budget_percent
5411        ));
5412    }
5413    if hardened_failure_percent > gate.hardened.divergence_budget_percent {
5414        reasons.push(format!(
5415            "hardened failure percent {:.3}% exceeds {:.3}%",
5416            hardened_failure_percent, gate.hardened.divergence_budget_percent
5417        ));
5418    }
5419    if let Some(categories) = &gate.hardened.allowlisted_divergence_categories
5420        && categories.is_empty()
5421    {
5422        reasons.push("hardened allowlist categories must not be empty".to_owned());
5423    }
5424
5425    Ok(PacketGateResult {
5426        packet_id,
5427        pass: reasons.is_empty(),
5428        fixture_count: report.fixture_count,
5429        strict_total,
5430        strict_failed,
5431        hardened_total,
5432        hardened_failed,
5433        reasons,
5434        validation_source: None,
5435    })
5436}
5437
5438pub fn generate_raptorq_sidecar(
5439    artifact_id: &str,
5440    artifact_type: &str,
5441    report_bytes: &[u8],
5442    repair_packets_per_block: u32,
5443) -> Result<RaptorQSidecarArtifact, HarnessError> {
5444    if report_bytes.is_empty() {
5445        return Err(HarnessError::RaptorQ(
5446            "cannot generate sidecar for empty payload".to_owned(),
5447        ));
5448    }
5449
5450    let encoder = Encoder::with_defaults(report_bytes, 1400);
5451    let config = encoder.get_config();
5452
5453    let mut packet_records = Vec::new();
5454    let mut symbol_hashes = Vec::new();
5455    let mut source_packets = 0usize;
5456
5457    for block in encoder.get_block_encoders() {
5458        for packet in block.source_packets() {
5459            source_packets += 1;
5460            let record = packet_record(packet, true);
5461            symbol_hashes.push(record.symbol_hash.clone());
5462            packet_records.push(record);
5463        }
5464        for packet in block.repair_packets(0, repair_packets_per_block) {
5465            let record = packet_record(packet, false);
5466            symbol_hashes.push(record.symbol_hash.clone());
5467            packet_records.push(record);
5468        }
5469    }
5470
5471    let repair_packets = packet_records.len().saturating_sub(source_packets);
5472    let source_hash = hash_bytes(report_bytes);
5473    let mut scrub_report = verify_raptorq_sidecar_internal(
5474        report_bytes,
5475        &source_hash,
5476        &packet_records,
5477        now_unix_ms(),
5478    )?;
5479    scrub_report.status = if scrub_report.invalid_packets == 0 && scrub_report.source_hash_verified
5480    {
5481        "ok".to_owned()
5482    } else {
5483        "failed".to_owned()
5484    };
5485    let asupersync_codec = generate_asupersync_codec_evidence(artifact_id, report_bytes)?;
5486
5487    let envelope = RaptorQEnvelope {
5488        artifact_id: artifact_id.to_owned(),
5489        artifact_type: artifact_type.to_owned(),
5490        source_hash: format!("sha256:{source_hash}"),
5491        raptorq: RaptorQMetadata {
5492            k: source_packets as u32,
5493            repair_symbols: repair_packets as u32,
5494            overhead_ratio: if source_packets == 0 {
5495                0.0
5496            } else {
5497                repair_packets as f64 / source_packets as f64
5498            },
5499            symbol_hashes,
5500        },
5501        scrub: ScrubStatus {
5502            last_ok_unix_ms: scrub_report.verified_at_unix_ms,
5503            status: scrub_report.status.clone(),
5504        },
5505        decode_proofs: Vec::new(),
5506    };
5507
5508    Ok(RaptorQSidecarArtifact {
5509        envelope,
5510        oti_serialized_hex: hex_encode(&config.serialize()),
5511        source_packets,
5512        repair_packets,
5513        repair_packets_per_block,
5514        packet_records,
5515        scrub_report,
5516        asupersync_codec,
5517    })
5518}
5519
5520pub fn run_raptorq_decode_recovery_drill(
5521    sidecar: &RaptorQSidecarArtifact,
5522    report_bytes: &[u8],
5523) -> Result<DecodeProof, HarnessError> {
5524    if sidecar.packet_records.is_empty() {
5525        return Err(HarnessError::RaptorQ(
5526            "sidecar has no packet records".to_owned(),
5527        ));
5528    }
5529
5530    let oti_bytes = hex_decode(&sidecar.oti_serialized_hex)?;
5531    if oti_bytes.len() != 12 {
5532        return Err(HarnessError::RaptorQ(format!(
5533            "invalid OTI byte length: {}",
5534            oti_bytes.len()
5535        )));
5536    }
5537    let mut oti = [0_u8; 12];
5538    oti.copy_from_slice(&oti_bytes);
5539    let config = ObjectTransmissionInformation::deserialize(&oti);
5540
5541    let drop_count = sidecar.source_packets.saturating_div(4).max(1);
5542    let mut dropped_sources = 0usize;
5543    let mut packets = Vec::with_capacity(sidecar.packet_records.len());
5544    for record in &sidecar.packet_records {
5545        if record.is_source && dropped_sources < drop_count {
5546            dropped_sources += 1;
5547            continue;
5548        }
5549
5550        let packet_bytes = hex_decode(&record.serialized_hex)?;
5551        packets.push(EncodingPacket::deserialize(&packet_bytes));
5552    }
5553
5554    let mut decoder = Decoder::new(config);
5555    let mut recovered = None;
5556    for packet in packets {
5557        recovered = decoder.decode(packet);
5558        if recovered.is_some() {
5559            break;
5560        }
5561    }
5562
5563    let recovered = recovered.ok_or_else(|| {
5564        HarnessError::RaptorQ("decode drill could not reconstruct payload".to_owned())
5565    })?;
5566    if recovered != report_bytes {
5567        return Err(HarnessError::RaptorQ(
5568            "decode drill recovered bytes do not match source payload".to_owned(),
5569        ));
5570    }
5571
5572    let proof_material = format!(
5573        "{}:{}:{}",
5574        sidecar.envelope.artifact_id,
5575        dropped_sources,
5576        hash_bytes(&recovered)
5577    );
5578
5579    Ok(DecodeProof {
5580        ts_unix_ms: now_unix_ms(),
5581        reason: format!(
5582            "raptorq decode drill dropped {dropped_sources} source packets and recovered payload"
5583        ),
5584        recovered_blocks: dropped_sources as u32,
5585        proof_hash: format!("sha256:{}", hash_bytes(proof_material.as_bytes())),
5586    })
5587}
5588
5589pub fn verify_raptorq_sidecar(
5590    sidecar: &RaptorQSidecarArtifact,
5591    report_bytes: &[u8],
5592) -> Result<RaptorQScrubReport, HarnessError> {
5593    verify_asupersync_codec_evidence(sidecar, report_bytes)?;
5594    let expected = sidecar
5595        .envelope
5596        .source_hash
5597        .strip_prefix("sha256:")
5598        .ok_or_else(|| {
5599            HarnessError::RaptorQ("source hash must be prefixed with sha256:".to_owned())
5600        })?
5601        .to_owned();
5602    verify_raptorq_sidecar_internal(
5603        report_bytes,
5604        &expected,
5605        &sidecar.packet_records,
5606        now_unix_ms(),
5607    )
5608}
5609
5610fn verify_raptorq_sidecar_internal(
5611    report_bytes: &[u8],
5612    expected_source_hash: &str,
5613    records: &[RaptorQPacketRecord],
5614    ts_unix_ms: u64,
5615) -> Result<RaptorQScrubReport, HarnessError> {
5616    let source_hash_verified = hash_bytes(report_bytes) == expected_source_hash;
5617    let mut invalid_packets = 0usize;
5618    for record in records {
5619        let bytes = hex_decode(&record.serialized_hex)?;
5620        if hash_bytes(&bytes) != record.symbol_hash {
5621            invalid_packets += 1;
5622        }
5623    }
5624
5625    Ok(RaptorQScrubReport {
5626        verified_at_unix_ms: ts_unix_ms,
5627        status: if source_hash_verified && invalid_packets == 0 {
5628            "ok".to_owned()
5629        } else {
5630            "failed".to_owned()
5631        },
5632        packet_count: records.len(),
5633        invalid_packets,
5634        source_hash_verified,
5635    })
5636}
5637
5638#[cfg(feature = "asupersync")]
5639fn generate_asupersync_codec_evidence(
5640    artifact_id: &str,
5641    report_bytes: &[u8],
5642) -> Result<Option<AsupersyncCodecEvidence>, HarnessError> {
5643    let config = RuntimeAsupersyncConfig::default();
5644    let codec = PassthroughCodec;
5645    let verifier = Fnv1aVerifier;
5646    let expected_digest = fnv1a_hex(report_bytes);
5647    let payload = ArtifactPayload {
5648        artifact_id: artifact_id.to_owned(),
5649        bytes: report_bytes.to_vec(),
5650        expected_digest: Some(expected_digest.clone()),
5651    };
5652
5653    let encoded = codec
5654        .encode(&payload, &config)
5655        .map_err(|err| HarnessError::RaptorQ(format!("asupersync encode failed: {err}")))?;
5656    let decoded = codec
5657        .decode(&encoded, &config)
5658        .map_err(|err| HarnessError::RaptorQ(format!("asupersync decode failed: {err}")))?;
5659    if decoded.bytes != report_bytes {
5660        return Err(HarnessError::RaptorQ(
5661            "asupersync codec round-trip diverged from source payload".to_owned(),
5662        ));
5663    }
5664    verifier
5665        .verify(artifact_id, &decoded.bytes, &expected_digest)
5666        .map_err(|err| HarnessError::RaptorQ(format!("asupersync verify failed: {err}")))?;
5667
5668    Ok(Some(AsupersyncCodecEvidence {
5669        codec: "passthrough".to_owned(),
5670        verifier: "fnv1a64".to_owned(),
5671        encoded_bytes: encoded.encoded_bytes.len(),
5672        repair_symbols: encoded.repair_symbols,
5673        integrity_verified: true,
5674    }))
5675}
5676
5677#[cfg(not(feature = "asupersync"))]
5678fn generate_asupersync_codec_evidence(
5679    _artifact_id: &str,
5680    _report_bytes: &[u8],
5681) -> Result<Option<AsupersyncCodecEvidence>, HarnessError> {
5682    Ok(None)
5683}
5684
5685#[cfg(feature = "asupersync")]
5686fn verify_asupersync_codec_evidence(
5687    sidecar: &RaptorQSidecarArtifact,
5688    report_bytes: &[u8],
5689) -> Result<(), HarnessError> {
5690    let Some(evidence) = &sidecar.asupersync_codec else {
5691        return Ok(());
5692    };
5693    if !evidence.integrity_verified {
5694        return Err(HarnessError::RaptorQ(
5695            "asupersync integrity evidence was not marked verified".to_owned(),
5696        ));
5697    }
5698
5699    let verifier = Fnv1aVerifier;
5700    let expected_digest = fnv1a_hex(report_bytes);
5701    verifier
5702        .verify(
5703            &sidecar.envelope.artifact_id,
5704            report_bytes,
5705            &expected_digest,
5706        )
5707        .map_err(|err| HarnessError::RaptorQ(format!("asupersync verify failed: {err}")))?;
5708    Ok(())
5709}
5710
5711#[cfg(not(feature = "asupersync"))]
5712fn verify_asupersync_codec_evidence(
5713    sidecar: &RaptorQSidecarArtifact,
5714    _report_bytes: &[u8],
5715) -> Result<(), HarnessError> {
5716    if sidecar.asupersync_codec.is_some() {
5717        return Err(HarnessError::RaptorQ(
5718            "asupersync codec evidence is present, but fp-conformance was built without the \
5719             asupersync feature needed to verify it"
5720                .to_owned(),
5721        ));
5722    }
5723    Ok(())
5724}
5725
5726#[cfg(feature = "asupersync")]
5727fn fnv1a_hex(bytes: &[u8]) -> String {
5728    let mut hash = 0xcbf29ce484222325_u64;
5729    for byte in bytes {
5730        hash ^= u64::from(*byte);
5731        hash = hash.wrapping_mul(0x100000001b3);
5732    }
5733    format!("{hash:016x}")
5734}
5735
5736fn packet_record(packet: EncodingPacket, is_source: bool) -> RaptorQPacketRecord {
5737    let payload = packet.payload_id();
5738    let serialized = packet.serialize();
5739    RaptorQPacketRecord {
5740        source_block_number: payload.source_block_number(),
5741        encoding_symbol_id: payload.encoding_symbol_id(),
5742        is_source,
5743        serialized_hex: hex_encode(&serialized),
5744        symbol_hash: hash_bytes(&serialized),
5745    }
5746}
5747
5748// === RaptorQ CI Enforcement (bd-2gi.9) ===
5749
5750/// Typed decode proof artifact matching `decode_proof_artifact.schema.json`.
5751#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
5752pub struct DecodeProofArtifact {
5753    pub packet_id: String,
5754    pub decode_proofs: Vec<DecodeProof>,
5755    pub status: DecodeProofStatus,
5756}
5757
5758/// Outcome of a decode drill.
5759#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
5760#[serde(rename_all = "snake_case")]
5761pub enum DecodeProofStatus {
5762    Recovered,
5763    Failed,
5764    NotAttempted,
5765}
5766
5767impl std::fmt::Display for DecodeProofStatus {
5768    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5769        match self {
5770            Self::Recovered => write!(f, "recovered"),
5771            Self::Failed => write!(f, "failed"),
5772            Self::NotAttempted => write!(f, "not_attempted"),
5773        }
5774    }
5775}
5776
5777/// Result of verifying a single packet's RaptorQ sidecar integrity (Rule T5).
5778#[derive(Debug, Clone)]
5779pub struct SidecarIntegrityResult {
5780    pub packet_id: String,
5781    pub parity_report_exists: bool,
5782    pub sidecar_exists: bool,
5783    pub decode_proof_exists: bool,
5784    pub source_hash_matches: bool,
5785    pub scrub_ok: bool,
5786    pub decode_proof_valid: bool,
5787    pub errors: Vec<String>,
5788}
5789
5790impl SidecarIntegrityResult {
5791    pub fn is_ok(&self) -> bool {
5792        self.errors.is_empty()
5793            && self.parity_report_exists
5794            && self.sidecar_exists
5795            && self.decode_proof_exists
5796            && self.source_hash_matches
5797            && self.scrub_ok
5798            && self.decode_proof_valid
5799    }
5800}
5801
5802/// Verify Rule T5 for a single packet directory: parity_report.json must have
5803/// a corresponding raptorq sidecar and decode proof with matching hashes.
5804pub fn verify_packet_sidecar_integrity(
5805    packet_dir: &Path,
5806    packet_id: &str,
5807) -> SidecarIntegrityResult {
5808    let mut result = SidecarIntegrityResult {
5809        packet_id: packet_id.to_owned(),
5810        parity_report_exists: false,
5811        sidecar_exists: false,
5812        decode_proof_exists: false,
5813        source_hash_matches: false,
5814        scrub_ok: false,
5815        decode_proof_valid: false,
5816        errors: Vec::new(),
5817    };
5818
5819    let report_path = packet_dir.join("parity_report.json");
5820    let sidecar_path = packet_dir.join("parity_report.raptorq.json");
5821    let proof_path = packet_dir.join("parity_report.decode_proof.json");
5822
5823    // Check file existence (Rule T5)
5824    result.parity_report_exists = report_path.exists();
5825    result.sidecar_exists = sidecar_path.exists();
5826    result.decode_proof_exists = proof_path.exists();
5827
5828    if !result.parity_report_exists {
5829        result
5830            .errors
5831            .push(format!("{packet_id}: missing parity_report.json"));
5832        return result;
5833    }
5834    if !result.sidecar_exists {
5835        result.errors.push(format!(
5836            "{packet_id}: missing parity_report.raptorq.json (Rule T5)"
5837        ));
5838    }
5839    if !result.decode_proof_exists {
5840        result.errors.push(format!(
5841            "{packet_id}: missing parity_report.decode_proof.json (Rule T5)"
5842        ));
5843    }
5844    if !result.sidecar_exists || !result.decode_proof_exists {
5845        return result;
5846    }
5847
5848    // Read artifacts
5849    let report_bytes = match fs::read(&report_path) {
5850        Ok(b) => b,
5851        Err(e) => {
5852            result
5853                .errors
5854                .push(format!("{packet_id}: cannot read parity_report.json: {e}"));
5855            return result;
5856        }
5857    };
5858    let sidecar: RaptorQSidecarArtifact = match fs::read_to_string(&sidecar_path)
5859        .map_err(|e| e.to_string())
5860        .and_then(|s| serde_json::from_str(&s).map_err(|e| e.to_string()))
5861    {
5862        Ok(s) => s,
5863        Err(e) => {
5864            result.errors.push(format!(
5865                "{packet_id}: cannot parse parity_report.raptorq.json: {e}"
5866            ));
5867            return result;
5868        }
5869    };
5870    let proof: DecodeProofArtifact = match fs::read_to_string(&proof_path)
5871        .map_err(|e| e.to_string())
5872        .and_then(|s| serde_json::from_str(&s).map_err(|e| e.to_string()))
5873    {
5874        Ok(p) => p,
5875        Err(e) => {
5876            result.errors.push(format!(
5877                "{packet_id}: cannot parse parity_report.decode_proof.json: {e}"
5878            ));
5879            return result;
5880        }
5881    };
5882
5883    if sidecar.envelope.decode_proofs.len() > MAX_DECODE_PROOFS {
5884        result.errors.push(format!(
5885            "{packet_id}: sidecar envelope decode_proofs exceeds cap {MAX_DECODE_PROOFS} (found {})",
5886            sidecar.envelope.decode_proofs.len()
5887        ));
5888        return result;
5889    }
5890    if proof.decode_proofs.len() > MAX_DECODE_PROOFS {
5891        result.errors.push(format!(
5892            "{packet_id}: decode proof artifact exceeds cap {MAX_DECODE_PROOFS} (found {})",
5893            proof.decode_proofs.len()
5894        ));
5895        return result;
5896    }
5897    let expected_artifact_id = parity_report_artifact_id(packet_id);
5898    if sidecar.envelope.artifact_id != expected_artifact_id {
5899        result.decode_proof_valid = false;
5900        result.errors.push(format!(
5901            "{packet_id}: sidecar artifact_id mismatch (expected {expected_artifact_id}, found {})",
5902            sidecar.envelope.artifact_id
5903        ));
5904        return result;
5905    }
5906    let mut envelope_counts_valid = true;
5907    let envelope_source_packets = sidecar.envelope.raptorq.k as usize;
5908    if envelope_source_packets != sidecar.source_packets {
5909        envelope_counts_valid = false;
5910        result.errors.push(format!(
5911            "{packet_id}: envelope.raptorq.k ({envelope_source_packets}) does not match source_packets ({})",
5912            sidecar.source_packets
5913        ));
5914    }
5915    let envelope_repair_packets = sidecar.envelope.raptorq.repair_symbols as usize;
5916    if envelope_repair_packets != sidecar.repair_packets {
5917        envelope_counts_valid = false;
5918        result.errors.push(format!(
5919            "{packet_id}: envelope.raptorq.repair_symbols ({envelope_repair_packets}) does not match repair_packets ({})",
5920            sidecar.repair_packets
5921        ));
5922    }
5923    if !envelope_counts_valid {
5924        result.decode_proof_valid = false;
5925        return result;
5926    }
5927
5928    // Verify source hash matches (sidecar.source_hash == SHA-256 of parity_report.json)
5929    let actual_hash = hash_bytes(&report_bytes);
5930    let expected_hash = sidecar
5931        .envelope
5932        .source_hash
5933        .strip_prefix("sha256:")
5934        .unwrap_or(&sidecar.envelope.source_hash);
5935    result.source_hash_matches = actual_hash == expected_hash;
5936    if !result.source_hash_matches {
5937        result.errors.push(format!(
5938            "{packet_id}: source_hash mismatch (expected {expected_hash}, got {actual_hash})"
5939        ));
5940    }
5941
5942    // Verify scrub status
5943    result.scrub_ok = sidecar.scrub_report.status == "ok"
5944        && sidecar.scrub_report.source_hash_verified
5945        && sidecar.scrub_report.invalid_packets == 0;
5946    if !result.scrub_ok {
5947        result.errors.push(format!(
5948            "{packet_id}: scrub report not ok (status={}, invalid={})",
5949            sidecar.scrub_report.status, sidecar.scrub_report.invalid_packets
5950        ));
5951    }
5952
5953    // Verify decode proof
5954    result.decode_proof_valid = proof.status == DecodeProofStatus::Recovered
5955        && !proof.decode_proofs.is_empty()
5956        && proof.packet_id == packet_id;
5957    if !result.decode_proof_valid {
5958        result.errors.push(format!(
5959            "{packet_id}: decode proof invalid (status={}, proofs={})",
5960            proof.status,
5961            proof.decode_proofs.len()
5962        ));
5963        return result;
5964    }
5965
5966    let sidecar_hashes: BTreeSet<&str> = sidecar
5967        .envelope
5968        .decode_proofs
5969        .iter()
5970        .map(|entry| entry.proof_hash.as_str())
5971        .collect();
5972    let artifact_hashes: BTreeSet<&str> = proof
5973        .decode_proofs
5974        .iter()
5975        .map(|entry| entry.proof_hash.as_str())
5976        .collect();
5977
5978    if sidecar_hashes.is_empty() {
5979        result.decode_proof_valid = false;
5980        result.errors.push(format!(
5981            "{packet_id}: sidecar envelope has no decode proofs to pair against artifact (Rule T5)"
5982        ));
5983    }
5984
5985    if artifact_hashes
5986        .iter()
5987        .any(|hash| !hash.starts_with("sha256:"))
5988    {
5989        result.decode_proof_valid = false;
5990        result.errors.push(format!(
5991            "{packet_id}: decode proof hash missing sha256: prefix"
5992        ));
5993    }
5994
5995    if !artifact_hashes
5996        .iter()
5997        .all(|hash| sidecar_hashes.contains(hash))
5998    {
5999        result.decode_proof_valid = false;
6000        result.errors.push(format!(
6001            "{packet_id}: decode proof hash mismatch between sidecar envelope and decode proof artifact"
6002        ));
6003    }
6004
6005    result
6006}
6007
6008/// CI gate function: verify all packet sidecars under an artifact root directory.
6009/// Returns Ok with results if all pass, Err with failures if any fail.
6010pub fn verify_all_sidecars_ci(
6011    artifact_root: &Path,
6012) -> Result<Vec<SidecarIntegrityResult>, Vec<SidecarIntegrityResult>> {
6013    let phase2c = artifact_root.join("phase2c");
6014    if !phase2c.exists() {
6015        return Ok(Vec::new());
6016    }
6017
6018    let mut results = Vec::new();
6019    let mut entries: Vec<_> = fs::read_dir(&phase2c)
6020        .unwrap_or_else(|_| fs::read_dir(".").unwrap())
6021        .filter_map(|e| e.ok())
6022        .filter(|e| {
6023            e.file_type().map(|t| t.is_dir()).unwrap_or(false)
6024                && e.file_name()
6025                    .to_str()
6026                    .map(|n| n.starts_with("FP-P2"))
6027                    .unwrap_or(false)
6028        })
6029        .collect();
6030    entries.sort_by_key(|e| e.file_name());
6031
6032    for entry in &entries {
6033        let packet_id = entry.file_name().to_string_lossy().to_string();
6034        let result = verify_packet_sidecar_integrity(&entry.path(), &packet_id);
6035        results.push(result);
6036    }
6037
6038    let failures: Vec<_> = results.iter().filter(|r| !r.is_ok()).cloned().collect();
6039    if failures.is_empty() {
6040        Ok(results)
6041    } else {
6042        Err(failures)
6043    }
6044}
6045
6046// === CI Gate Topology (bd-2gi.10) ===
6047
6048/// CI gate identifiers matching the G1..G8 pipeline from COVERAGE_FLAKE_BUDGETS.md.
6049#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
6050pub enum CiGate {
6051    /// G1: Compilation + formatting
6052    G1Compile,
6053    /// G2: Lint (clippy)
6054    G2Lint,
6055    /// G3: Unit tests
6056    G3Unit,
6057    /// G4: Property tests
6058    G4Property,
6059    /// G4.5: Fuzz regression (nightly only)
6060    G4_5Fuzz,
6061    /// G5: Integration tests
6062    G5Integration,
6063    /// G6: Conformance tests
6064    G6Conformance,
6065    /// G7: Coverage floor
6066    G7Coverage,
6067    /// G8: E2E orchestrator
6068    G8E2e,
6069}
6070
6071impl CiGate {
6072    /// Stable rule identifier for forensic reports.
6073    pub fn rule_id(self) -> &'static str {
6074        match self {
6075            Self::G1Compile => "G1",
6076            Self::G2Lint => "G2",
6077            Self::G3Unit => "G3",
6078            Self::G4Property => "G4",
6079            Self::G4_5Fuzz => "G4.5",
6080            Self::G5Integration => "G5",
6081            Self::G6Conformance => "G6",
6082            Self::G7Coverage => "G7",
6083            Self::G8E2e => "G8",
6084        }
6085    }
6086
6087    /// Gate ordering index for pipeline sequencing.
6088    pub fn order(self) -> u8 {
6089        match self {
6090            Self::G1Compile => 1,
6091            Self::G2Lint => 2,
6092            Self::G3Unit => 3,
6093            Self::G4Property => 4,
6094            Self::G4_5Fuzz => 5,
6095            Self::G5Integration => 6,
6096            Self::G6Conformance => 7,
6097            Self::G7Coverage => 8,
6098            Self::G8E2e => 9,
6099        }
6100    }
6101
6102    /// Human-readable gate label.
6103    pub fn label(self) -> &'static str {
6104        match self {
6105            Self::G1Compile => "G1: Compile + Format",
6106            Self::G2Lint => "G2: Lint (Clippy)",
6107            Self::G3Unit => "G3: Unit Tests",
6108            Self::G4Property => "G4: Property Tests",
6109            Self::G4_5Fuzz => "G4.5: Fuzz Regression",
6110            Self::G5Integration => "G5: Integration Tests",
6111            Self::G6Conformance => "G6: Conformance",
6112            Self::G7Coverage => "G7: Coverage Floor",
6113            Self::G8E2e => "G8: E2E Pipeline",
6114        }
6115    }
6116
6117    /// Shell command(s) for this gate (when run via external CI).
6118    pub fn commands(self) -> Vec<&'static str> {
6119        match self {
6120            // Format is checked per crate over the crates rustfmt can format -
6121            // the same list as the CI `fmt` job and the Fast gate. A bare
6122            // workspace `cargo fmt --check` also formats fp-columnar (62k
6123            // lines) and fp-frame (208k), which need tens of GB (run
6124            // 33488811029 died allocating 172 GB, br-frankenpandas-3bu58), so
6125            // G1 could not pass on any runner. Those two stay unenforced until
6126            // they are split (3bu58). br-frankenpandas-rc0923-epic-first-green-ci-kyvo0.6
6127            Self::G1Compile => vec![
6128                "cargo check --workspace --all-targets",
6129                "cargo fmt --check -p fp-types",
6130                "cargo fmt --check -p fp-dot-kernel",
6131                "cargo fmt --check -p fp-index",
6132                "cargo fmt --check -p fp-expr",
6133                "cargo fmt --check -p fp-groupby",
6134                "cargo fmt --check -p fp-join",
6135                "cargo fmt --check -p fp-io",
6136                "cargo fmt --check -p fp-conformance",
6137                "cargo fmt --check -p fp-bench",
6138                "cargo fmt --check -p fp-runtime",
6139                "cargo fmt --check -p fp-frankentui",
6140                "cargo fmt --check -p fp-python",
6141                "cargo fmt --check -p frankenpandas",
6142            ],
6143            Self::G2Lint => vec!["cargo clippy --workspace --all-targets -- -D warnings"],
6144            Self::G3Unit => vec!["cargo test --workspace --lib"],
6145            Self::G4Property => vec!["cargo test -p fp-conformance --test proptest_properties"],
6146            Self::G4_5Fuzz => vec![], // nightly only, defined in ADVERSARIAL_FUZZ_CORPUS.md
6147            Self::G5Integration => vec!["cargo test -p fp-conformance --test smoke"],
6148            Self::G6Conformance => vec!["cargo test -p fp-conformance -- --nocapture"],
6149            Self::G7Coverage => vec!["cargo llvm-cov --workspace --summary-only"],
6150            Self::G8E2e => vec![], // Rust-native, uses run_e2e_suite()
6151        }
6152    }
6153
6154    /// One-command reproduction string for failure forensics.
6155    #[must_use]
6156    pub fn repro_command(self) -> String {
6157        let commands = self.commands();
6158        if !commands.is_empty() {
6159            return commands.join(" && ");
6160        }
6161
6162        match self {
6163            Self::G4_5Fuzz => {
6164                "cargo fuzz run <target>  # see artifacts/phase2c/ADVERSARIAL_FUZZ_CORPUS.md"
6165                    .to_owned()
6166            }
6167            Self::G8E2e => "cargo test -p fp-conformance --test ag_e2e -- --nocapture".to_owned(),
6168            // All remaining gates should define shell commands.
6169            _ => format!("cargo run -p fp-conformance --bin fp-ci-gates -- --gate {self:?}"),
6170        }
6171    }
6172
6173    /// All gates in pipeline order.
6174    pub fn pipeline() -> Vec<CiGate> {
6175        vec![
6176            Self::G1Compile,
6177            Self::G2Lint,
6178            Self::G3Unit,
6179            Self::G4Property,
6180            Self::G5Integration,
6181            Self::G6Conformance,
6182            Self::G7Coverage,
6183            Self::G8E2e,
6184        ]
6185    }
6186
6187    /// Default pipeline for per-commit CI (excludes G4.5 fuzz and G7 coverage).
6188    pub fn commit_pipeline() -> Vec<CiGate> {
6189        vec![
6190            Self::G1Compile,
6191            Self::G2Lint,
6192            Self::G3Unit,
6193            Self::G4Property,
6194            Self::G5Integration,
6195            Self::G6Conformance,
6196        ]
6197    }
6198}
6199
6200impl std::fmt::Display for CiGate {
6201    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6202        write!(f, "{}", self.label())
6203    }
6204}
6205
6206/// Result of a single CI gate evaluation.
6207#[derive(Debug, Clone, Serialize, Deserialize)]
6208pub struct CiGateResult {
6209    pub gate: CiGate,
6210    pub passed: bool,
6211    pub elapsed_ms: u64,
6212    pub summary: String,
6213    pub errors: Vec<String>,
6214}
6215
6216const LIVE_ORACLE_SKIP_MARKER: &str = "live pandas unavailable; skipping";
6217
6218/// Aggregate outcome for the dedicated live-oracle parity test slice.
6219#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
6220pub struct LiveOracleReport {
6221    pub expected_tests: usize,
6222    pub total_tests: usize,
6223    pub passed: usize,
6224    pub ran: usize,
6225    pub skipped: usize,
6226    pub failed: usize,
6227    pub command_ok: bool,
6228    pub exit_code: Option<i32>,
6229}
6230
6231impl LiveOracleReport {
6232    #[must_use]
6233    pub fn is_green(&self, require_live_oracle: bool) -> bool {
6234        self.command_ok
6235            && self.failed == 0
6236            && self.total_tests == self.expected_tests
6237            && (!require_live_oracle || self.skipped == 0)
6238    }
6239}
6240
6241/// Result of a full CI gate pipeline run.
6242#[derive(Debug, Clone, Serialize, Deserialize)]
6243pub struct CiPipelineResult {
6244    pub gates: Vec<CiGateResult>,
6245    pub all_passed: bool,
6246    pub first_failure: Option<CiGate>,
6247    pub elapsed_ms: u64,
6248}
6249
6250/// Gate-level forensic result with stable identifiers and replay metadata.
6251#[derive(Debug, Clone, Serialize, Deserialize)]
6252pub struct CiGateForensicsEntry {
6253    pub rule_id: String,
6254    pub gate: CiGate,
6255    pub order: u8,
6256    pub label: String,
6257    pub passed: bool,
6258    pub elapsed_ms: u64,
6259    pub summary: String,
6260    pub errors: Vec<String>,
6261    pub commands: Vec<String>,
6262    pub repro_cmd: String,
6263}
6264
6265/// Machine-readable CI forensic report for G1..G8 gate failures.
6266#[derive(Debug, Clone, Serialize, Deserialize)]
6267pub struct CiForensicsReport {
6268    pub generated_unix_ms: u128,
6269    pub all_passed: bool,
6270    pub first_failure: Option<CiGate>,
6271    pub elapsed_ms: u64,
6272    pub passed_count: usize,
6273    pub total_count: usize,
6274    pub gate_results: Vec<CiGateForensicsEntry>,
6275    pub violations: Vec<CiGateForensicsEntry>,
6276}
6277
6278impl CiPipelineResult {
6279    pub fn passed_count(&self) -> usize {
6280        self.gates.iter().filter(|g| g.passed).count()
6281    }
6282
6283    pub fn total_count(&self) -> usize {
6284        self.gates.len()
6285    }
6286}
6287
6288/// Build a deterministic, machine-readable forensic report from a CI pipeline run.
6289#[must_use]
6290pub fn build_ci_forensics_report(result: &CiPipelineResult) -> CiForensicsReport {
6291    let mut gate_results = Vec::with_capacity(result.gates.len());
6292    let mut violations = Vec::new();
6293
6294    for gate in &result.gates {
6295        let entry = CiGateForensicsEntry {
6296            rule_id: gate.gate.rule_id().to_owned(),
6297            gate: gate.gate,
6298            order: gate.gate.order(),
6299            label: gate.gate.label().to_owned(),
6300            passed: gate.passed,
6301            elapsed_ms: gate.elapsed_ms,
6302            summary: gate.summary.clone(),
6303            errors: gate.errors.clone(),
6304            commands: gate
6305                .gate
6306                .commands()
6307                .into_iter()
6308                .map(ToOwned::to_owned)
6309                .collect(),
6310            repro_cmd: gate.gate.repro_command(),
6311        };
6312        if !entry.passed {
6313            violations.push(entry.clone());
6314        }
6315        gate_results.push(entry);
6316    }
6317
6318    let generated_unix_ms = SystemTime::now()
6319        .duration_since(UNIX_EPOCH)
6320        .map_or(0, |d| d.as_millis());
6321
6322    CiForensicsReport {
6323        generated_unix_ms,
6324        all_passed: result.all_passed,
6325        first_failure: result.first_failure,
6326        elapsed_ms: result.elapsed_ms,
6327        passed_count: result.passed_count(),
6328        total_count: result.total_count(),
6329        gate_results,
6330        violations,
6331    }
6332}
6333
6334fn live_oracle_report_path(config: &HarnessConfig) -> PathBuf {
6335    config
6336        .repo_root
6337        .join("artifacts/ci/live_oracle_report.json")
6338}
6339
6340fn configure_live_oracle_cargo_command<'a>(
6341    config: &HarnessConfig,
6342    command: &'a mut Command,
6343) -> &'a mut Command {
6344    command
6345        .current_dir(&config.repo_root)
6346        .arg("test")
6347        .arg("-p")
6348        .arg("fp-conformance")
6349        .arg("--lib")
6350        .arg("live_oracle_")
6351        .env("CARGO_TERM_COLOR", "never")
6352        .env("FP_PYTHON_BIN", &config.python_bin)
6353        .env(
6354            "FP_REQUIRE_LIVE_ORACLE",
6355            if config.require_live_oracle { "1" } else { "0" },
6356        );
6357
6358    if config.allows_system_pandas_fallback() {
6359        command.env("FP_ALLOW_SYSTEM_PANDAS_FALLBACK", "1");
6360    } else {
6361        command.env_remove("FP_ALLOW_SYSTEM_PANDAS_FALLBACK");
6362    }
6363
6364    if config.allow_fixture_fallback {
6365        command.env("FP_ALLOW_FIXTURE_FALLBACK", "1");
6366    } else {
6367        command.env_remove("FP_ALLOW_FIXTURE_FALLBACK");
6368    }
6369
6370    command
6371}
6372
6373fn count_live_oracle_selected_tests(config: &HarnessConfig) -> Result<usize, HarnessError> {
6374    let mut command = Command::new("cargo");
6375    configure_live_oracle_cargo_command(config, &mut command)
6376        .arg("--")
6377        .arg("--list");
6378    let output = command.output()?;
6379    if !output.status.success() {
6380        return Err(HarnessError::FixtureFormat(format!(
6381            "live oracle test listing failed (exit {}): {}",
6382            output.status.code().unwrap_or(-1),
6383            String::from_utf8_lossy(&output.stderr).trim()
6384        )));
6385    }
6386
6387    Ok(String::from_utf8_lossy(&output.stdout)
6388        .lines()
6389        .filter(|line| line.trim_end().ends_with(": test"))
6390        .count())
6391}
6392
6393fn parse_test_result_count(line: &str, label: &str) -> Option<usize> {
6394    let needle = format!(" {label};");
6395    let prefix = line.split(&needle).next()?;
6396    prefix.rsplit_once(' ')?.1.parse().ok()
6397}
6398
6399fn parse_live_oracle_report_output(
6400    output: &str,
6401    expected_tests: usize,
6402    command_ok: bool,
6403    exit_code: Option<i32>,
6404) -> LiveOracleReport {
6405    let mut total_tests = 0usize;
6406    let mut passed = 0usize;
6407    let mut failed = 0usize;
6408    let mut ignored = 0usize;
6409
6410    for line in output.lines() {
6411        let trimmed = line.trim();
6412        if let Some(rest) = trimmed.strip_prefix("running ")
6413            && let Some(count) = rest
6414                .strip_suffix(" tests")
6415                .and_then(|s| s.parse::<usize>().ok())
6416        {
6417            total_tests += count;
6418        }
6419        if trimmed.starts_with("test result:") {
6420            passed += parse_test_result_count(trimmed, "passed").unwrap_or(0);
6421            failed += parse_test_result_count(trimmed, "failed").unwrap_or(0);
6422            // Per br-frankenpandas-atag8: also harvest cargo's `ignored` count.
6423            // If a live-oracle test is #[ignore]d when pandas is unavailable
6424            // (or otherwise reports as ignored), the SKIP_MARKER substring
6425            // never appears and the test would silently count as passed.
6426            ignored += parse_test_result_count(trimmed, "ignored").unwrap_or(0);
6427        }
6428    }
6429
6430    let total_tests = total_tests.max(passed.saturating_add(failed));
6431    // Skipped count is the maximum of marker hits (legacy code path that
6432    // emits the LIVE_ORACLE_SKIP_MARKER and treats those as passed) and
6433    // cargo's structured ignored count. Both are clamped to `passed +
6434    // ignored` so we never claim more skips than tests reached the harness.
6435    let marker_hits = output.matches(LIVE_ORACLE_SKIP_MARKER).count();
6436    let skipped = marker_hits.max(ignored).min(passed.saturating_add(ignored));
6437    let ran = total_tests.saturating_sub(skipped.saturating_add(failed));
6438
6439    LiveOracleReport {
6440        expected_tests,
6441        total_tests,
6442        passed,
6443        ran,
6444        skipped,
6445        failed,
6446        command_ok,
6447        exit_code,
6448    }
6449}
6450
6451fn run_live_oracle_report(config: &HarnessConfig) -> Result<LiveOracleReport, HarnessError> {
6452    let expected_tests = count_live_oracle_selected_tests(config)?;
6453    let mut command = Command::new("cargo");
6454    configure_live_oracle_cargo_command(config, &mut command)
6455        .arg("--")
6456        .arg("--nocapture")
6457        .arg("--test-threads=1");
6458
6459    let output = command.output()?;
6460    let mut combined = String::from_utf8_lossy(&output.stdout).into_owned();
6461    if !combined.is_empty() && !output.stderr.is_empty() {
6462        combined.push('\n');
6463    }
6464    combined.push_str(&String::from_utf8_lossy(&output.stderr));
6465
6466    Ok(parse_live_oracle_report_output(
6467        &combined,
6468        expected_tests,
6469        output.status.success(),
6470        output.status.code(),
6471    ))
6472}
6473
6474fn write_live_oracle_report(
6475    config: &HarnessConfig,
6476    report: &LiveOracleReport,
6477) -> Result<PathBuf, HarnessError> {
6478    let path = live_oracle_report_path(config);
6479    if let Some(parent) = path.parent() {
6480        fs::create_dir_all(parent)?;
6481    }
6482    fs::write(&path, serde_json::to_string_pretty(report)?)?;
6483    Ok(path)
6484}
6485
6486impl std::fmt::Display for CiPipelineResult {
6487    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6488        if self.all_passed {
6489            writeln!(
6490                f,
6491                "CI PIPELINE: ALL GREEN ({}/{} gates passed in {}ms)",
6492                self.passed_count(),
6493                self.total_count(),
6494                self.elapsed_ms
6495            )?;
6496        } else {
6497            writeln!(
6498                f,
6499                "CI PIPELINE: FAILED ({}/{} gates passed)",
6500                self.passed_count(),
6501                self.total_count()
6502            )?;
6503        }
6504        for gate in &self.gates {
6505            let status = if gate.passed { "PASS" } else { "FAIL" };
6506            writeln!(f, "  [{status}] {} ({}ms)", gate.gate, gate.elapsed_ms)?;
6507            if !gate.passed {
6508                writeln!(f, "         {}", gate.summary)?;
6509                for err in &gate.errors {
6510                    writeln!(f, "         - {err}")?;
6511                }
6512            }
6513        }
6514        Ok(())
6515    }
6516}
6517
6518/// Configuration for a CI pipeline run.
6519#[derive(Debug, Clone)]
6520pub struct CiPipelineConfig {
6521    /// Which gates to run (default: commit pipeline)
6522    pub gates: Vec<CiGate>,
6523    /// Stop on first failure (default: true)
6524    pub fail_fast: bool,
6525    /// Harness config for Rust-native gates
6526    pub harness_config: HarnessConfig,
6527    /// Whether to run RaptorQ sidecar verification
6528    pub verify_sidecars: bool,
6529}
6530
6531impl Default for CiPipelineConfig {
6532    fn default() -> Self {
6533        Self {
6534            gates: CiGate::commit_pipeline(),
6535            fail_fast: true,
6536            harness_config: HarnessConfig::default_paths(),
6537            verify_sidecars: true,
6538        }
6539    }
6540}
6541
6542/// The last `max_chars` characters of a command's output. A failed cargo
6543/// command ends with what names the failure - the failing test, its panic,
6544/// the rerun hint - after a head of `Compiling` lines; the head alone named
6545/// nothing on CI run 36377733707's G3 failure.
6546fn output_tail(text: &str, max_chars: usize) -> &str {
6547    let skip = text.chars().count().saturating_sub(max_chars);
6548    let mut rest = text.chars();
6549    rest.by_ref().take(skip).for_each(drop);
6550    rest.as_str()
6551}
6552
6553/// Evaluate a single CI gate using Rust-native checks where possible.
6554pub fn evaluate_ci_gate(gate: CiGate, config: &CiPipelineConfig) -> CiGateResult {
6555    let start = SystemTime::now();
6556
6557    let (passed, summary, errors) = match gate {
6558        CiGate::G6Conformance => {
6559            let options = SuiteOptions::default();
6560            let (mut passed, mut summary, mut errors) =
6561                match run_packet_suite_with_options(&config.harness_config, &options) {
6562                    Ok(report) => {
6563                        if report.is_green() {
6564                            (
6565                                true,
6566                                format!("All {} fixtures passed", report.fixture_count),
6567                                vec![],
6568                            )
6569                        } else {
6570                            let errs = build_g6_conformance_errors(&config.harness_config, &report);
6571                            (
6572                                false,
6573                                format!(
6574                                    "{}/{} fixtures failed",
6575                                    report.failed, report.fixture_count
6576                                ),
6577                                errs,
6578                            )
6579                        }
6580                    }
6581                    Err(e) => (false, format!("Harness error: {e}"), vec![e.to_string()]),
6582                };
6583
6584            if !cfg!(test) {
6585                match run_live_oracle_report(&config.harness_config) {
6586                    Ok(live_report) => {
6587                        match write_live_oracle_report(&config.harness_config, &live_report) {
6588                            Ok(path) => {
6589                                summary = format!(
6590                                    "{summary}; live-oracle ran={} skipped={} failed={} observed={}/{} report={}",
6591                                    live_report.ran,
6592                                    live_report.skipped,
6593                                    live_report.failed,
6594                                    live_report.total_tests,
6595                                    live_report.expected_tests,
6596                                    path.display()
6597                                );
6598                            }
6599                            Err(err) => {
6600                                passed = false;
6601                                errors.push(format!("live_oracle_report_write_failed={err}"));
6602                            }
6603                        }
6604
6605                        if !live_report.command_ok {
6606                            passed = false;
6607                            errors.push(format!(
6608                                "live_oracle_command_exit={}",
6609                                live_report
6610                                    .exit_code
6611                                    .map_or_else(|| "signal".to_owned(), |code| code.to_string())
6612                            ));
6613                        }
6614                        if live_report.total_tests != live_report.expected_tests {
6615                            passed = false;
6616                            errors.push(format!(
6617                                "live_oracle_total_tests={} expected={}",
6618                                live_report.total_tests, live_report.expected_tests
6619                            ));
6620                        }
6621                        if config.harness_config.require_live_oracle && live_report.skipped > 0 {
6622                            passed = false;
6623                            errors.push(format!(
6624                                "live_oracle_skipped={} while FP_REQUIRE_LIVE_ORACLE=1",
6625                                live_report.skipped
6626                            ));
6627                        }
6628                        if live_report.failed > 0 {
6629                            passed = false;
6630                            errors.push(format!("live_oracle_failed={}", live_report.failed));
6631                        }
6632                    }
6633                    Err(err) => {
6634                        passed = false;
6635                        errors.push(format!("live_oracle_report_error={err}"));
6636                    }
6637                }
6638            }
6639
6640            (passed, summary, errors)
6641        }
6642        CiGate::G8E2e => {
6643            let e2e_config = E2eConfig::default_all_phases();
6644            match run_e2e_suite(&e2e_config, &mut NoopHooks) {
6645                Ok(report) => {
6646                    if report.gates_pass {
6647                        (
6648                            true,
6649                            format!(
6650                                "E2E green: {}/{} passed",
6651                                report.total_passed, report.total_fixtures
6652                            ),
6653                            vec![],
6654                        )
6655                    } else {
6656                        (
6657                            false,
6658                            format!(
6659                                "E2E failed: {}/{} passed",
6660                                report.total_passed, report.total_fixtures
6661                            ),
6662                            report
6663                                .gate_results
6664                                .iter()
6665                                .filter(|g| !g.pass)
6666                                .map(|g| format!("{}: {}", g.packet_id, g.reasons.join(", ")))
6667                                .collect(),
6668                        )
6669                    }
6670                }
6671                Err(e) => (false, format!("E2E error: {e}"), vec![e.to_string()]),
6672            }
6673        }
6674        _ => {
6675            // External gates: check commands are defined, report as info
6676            let cmds = gate.commands();
6677            if cmds.is_empty() {
6678                (true, "Skipped (no commands defined)".to_owned(), vec![])
6679            } else {
6680                // Run shell commands for external gates
6681                let mut all_ok = true;
6682                let mut errs = Vec::new();
6683                for cmd in &cmds {
6684                    let parts: Vec<&str> = cmd.split_whitespace().collect();
6685                    if parts.is_empty() {
6686                        continue;
6687                    }
6688                    match Command::new(parts[0])
6689                        .args(&parts[1..])
6690                        .stdout(Stdio::piped())
6691                        .stderr(Stdio::piped())
6692                        .output()
6693                    {
6694                        Ok(output) => {
6695                            if !output.status.success() {
6696                                all_ok = false;
6697                                // cargo test prints its failures to stdout
6698                                // and the rerun hint last on stderr.
6699                                let stdout = String::from_utf8_lossy(&output.stdout);
6700                                let stderr = String::from_utf8_lossy(&output.stderr);
6701                                errs.push(format!(
6702                                    "`{cmd}` failed (exit {}):\n--- stdout (tail) ---\n{}\n--- stderr (tail) ---\n{}",
6703                                    output.status.code().unwrap_or(-1),
6704                                    output_tail(&stdout, 4000),
6705                                    output_tail(&stderr, 1500)
6706                                ));
6707                            }
6708                        }
6709                        Err(e) => {
6710                            all_ok = false;
6711                            errs.push(format!("`{cmd}` execution error: {e}"));
6712                        }
6713                    }
6714                }
6715                let summary = if all_ok {
6716                    format!("{} command(s) passed", cmds.len())
6717                } else {
6718                    format!("{} error(s)", errs.len())
6719                };
6720                (all_ok, summary, errs)
6721            }
6722        }
6723    };
6724
6725    let elapsed_ms = start.elapsed().map(|d| d.as_millis() as u64).unwrap_or(0);
6726
6727    CiGateResult {
6728        gate,
6729        passed,
6730        elapsed_ms,
6731        summary,
6732        errors,
6733    }
6734}
6735
6736fn build_g6_conformance_errors(config: &HarnessConfig, report: &PacketParityReport) -> Vec<String> {
6737    let mut errors: Vec<_> = build_failure_surface_entries_for_report(report)
6738        .into_iter()
6739        .map(|entry| {
6740            format!(
6741                "packet_id={} case_id={} mode={} mismatch_class={} mismatch={}",
6742                entry.packet_id,
6743                entry.case_id,
6744                runtime_mode_slug(entry.mode),
6745                entry.mismatch_class,
6746                entry.mismatch,
6747            )
6748        })
6749        .collect();
6750
6751    match write_case_evidence_jsonl(config, std::slice::from_ref(report)) {
6752        Ok(paths) => {
6753            errors.extend(
6754                paths
6755                    .into_iter()
6756                    .map(|path| format!("case_evidence_artifact={}", path.display())),
6757            );
6758        }
6759        Err(err) => {
6760            errors.push(format!("case_evidence_artifact_write_failed={err}"));
6761        }
6762    }
6763
6764    errors
6765}
6766
6767/// Run the full CI gate pipeline with fail-fast and forensics.
6768pub fn run_ci_pipeline(config: &CiPipelineConfig) -> CiPipelineResult {
6769    let start = SystemTime::now();
6770    let mut gates = Vec::new();
6771    let mut first_failure = None;
6772
6773    for &gate in &config.gates {
6774        let result = evaluate_ci_gate(gate, config);
6775        let failed = !result.passed;
6776        gates.push(result);
6777
6778        if failed {
6779            if first_failure.is_none() {
6780                first_failure = Some(gate);
6781            }
6782            if config.fail_fast {
6783                break;
6784            }
6785        }
6786    }
6787
6788    // RaptorQ sidecar verification (supplemental check)
6789    if config.verify_sidecars && first_failure.is_none() {
6790        let artifact_root = config.harness_config.repo_root.join("artifacts");
6791        if let Err(failures) = verify_all_sidecars_ci(&artifact_root) {
6792            let errs: Vec<String> = failures.iter().flat_map(|f| f.errors.clone()).collect();
6793            gates.push(CiGateResult {
6794                gate: CiGate::G6Conformance,
6795                passed: false,
6796                elapsed_ms: 0,
6797                summary: format!("{} sidecar integrity failure(s)", failures.len()),
6798                errors: errs,
6799            });
6800            if first_failure.is_none() {
6801                first_failure = Some(CiGate::G6Conformance);
6802            }
6803        }
6804    }
6805
6806    let all_passed = first_failure.is_none();
6807    let elapsed_ms = start.elapsed().map(|d| d.as_millis() as u64).unwrap_or(0);
6808
6809    CiPipelineResult {
6810        gates,
6811        all_passed,
6812        first_failure,
6813        elapsed_ms,
6814    }
6815}
6816
6817fn build_report(
6818    config: &HarnessConfig,
6819    suite: String,
6820    packet_id: Option<String>,
6821    fixtures: &[PacketFixture],
6822    options: &SuiteOptions,
6823) -> Result<PacketParityReport, HarnessError> {
6824    let mut results = Vec::with_capacity(fixtures.len());
6825    for fixture in fixtures {
6826        results.push(run_fixture(config, fixture, options)?);
6827    }
6828
6829    let failed = results
6830        .iter()
6831        .filter(|result| matches!(result.status, CaseStatus::Fail))
6832        .count();
6833    // Same p6srr correction as build_differential_report: count PASSES rather
6834    // than inferring them, so a retired (never-executed) case cannot land in
6835    // the passed column.
6836    let passed = results
6837        .iter()
6838        .filter(|result| matches!(result.status, CaseStatus::Pass))
6839        .count();
6840    let retired = results
6841        .iter()
6842        .filter(|result| matches!(result.status, CaseStatus::Retired))
6843        .count();
6844
6845    Ok(PacketParityReport {
6846        suite,
6847        packet_id,
6848        oracle_present: config.oracle_reachable(),
6849        fixture_count: results.len(),
6850        passed,
6851        retired,
6852        failed,
6853        results,
6854    })
6855}
6856
6857fn load_fixtures(
6858    config: &HarnessConfig,
6859    packet_filter: Option<&str>,
6860) -> Result<Vec<PacketFixture>, HarnessError> {
6861    let fixture_files = list_fixture_files(&config.packet_fixture_root())?;
6862    let mut fixtures = Vec::with_capacity(fixture_files.len());
6863
6864    for fixture_path in fixture_files {
6865        let fixture = load_fixture(&fixture_path)?;
6866        if packet_filter.is_none_or(|packet| fixture.packet_id == packet) {
6867            fixtures.push(fixture);
6868        }
6869    }
6870    fixtures.sort_by(|a, b| a.case_id.cmp(&b.case_id));
6871    Ok(fixtures)
6872}
6873
6874fn load_fixture(path: &Path) -> Result<PacketFixture, HarnessError> {
6875    let body = fs::read_to_string(path)?;
6876    Ok(serde_json::from_str(&body)?)
6877}
6878
6879/// Structure-aware fuzz entrypoint for the `PacketFixture` JSON boundary.
6880///
6881/// This targets parse + serialize + expectation resolution + fixture replay and
6882/// treats any semantic error as acceptable as long as the harness does not
6883/// panic.
6884pub fn fuzz_fixture_parse_bytes(input: &[u8]) -> Result<(), HarnessError> {
6885    let fixture: PacketFixture = serde_json::from_slice(input)?;
6886    let _ = serde_json::to_vec(&fixture)?;
6887
6888    let config = HarnessConfig {
6889        repo_root: PathBuf::new(),
6890        oracle_root: PathBuf::new(),
6891        fixture_root: PathBuf::new(),
6892        strict_mode: true,
6893        python_bin: "python3".to_owned(),
6894        allow_system_pandas_fallback: false,
6895        allow_fixture_fallback: false,
6896        require_live_oracle: false,
6897    };
6898    let policy = match fixture.mode {
6899        RuntimeMode::Strict => RuntimePolicy::strict(),
6900        RuntimeMode::Hardened => RuntimePolicy::hardened(Some(100_000)),
6901    };
6902    let mut ledger = EvidenceLedger::new();
6903
6904    let _ = fixture_expected(&fixture);
6905    let _ = run_fixture_operation(
6906        &config,
6907        &fixture,
6908        &policy,
6909        &mut ledger,
6910        OracleMode::FixtureExpected,
6911    );
6912
6913    Ok(())
6914}
6915
6916fn assert_csv_roundtrip(frame: &DataFrame) -> Result<(), FpIoError> {
6917    // Frames here come from read_csv (RangeIndex): the round trip is
6918    // to_csv(index=False) -> read_csv, as in pandas. (4qg5w.1)
6919    let encoded = write_csv_string_with_options(frame, &csv_index_false())?;
6920    let reparsed = read_csv_str(&encoded)?;
6921    if !frame.equals(&reparsed) {
6922        return Err(FpIoError::Io(std::io::Error::other(
6923            "csv round-trip drifted after parse/write/reparse",
6924        )));
6925    }
6926    Ok(())
6927}
6928
6929/// pandas' Excel round trip is `to_excel(p)` then `read_excel(p, index_col=0)`:
6930/// the index is written as the first column under its name, or under a blank
6931/// header that reads back as "Unnamed: 0". Reading with default options only
6932/// "round-tripped" while fp-io guessed that column was an index and dropped it,
6933/// which pandas never does (br-frankenpandas-rc0923-epic-rust-parity-bugs-4qg5w.19).
6934fn excel_round_trip_read_options(frame: &DataFrame) -> ExcelReadOptions {
6935    if frame.row_multiindex().is_some() {
6936        // Levels are written as ordinary named columns; nothing to promote.
6937        return ExcelReadOptions::default();
6938    }
6939    ExcelReadOptions {
6940        index_col: Some(
6941            frame
6942                .index()
6943                .name()
6944                .map_or_else(|| "Unnamed: 0".to_owned(), String::from),
6945        ),
6946        ..ExcelReadOptions::default()
6947    }
6948}
6949
6950fn assert_excel_roundtrip(frame: &DataFrame) -> Result<(), FpIoError> {
6951    let encoded = write_excel_bytes(frame)?;
6952    let reparsed = read_excel_bytes(&encoded, &excel_round_trip_read_options(frame))?;
6953    if !frame.equals(&reparsed) {
6954        return Err(FpIoError::Io(std::io::Error::other(
6955            "excel round-trip drifted after parse/write/reparse",
6956        )));
6957    }
6958    Ok(())
6959}
6960
6961fn assert_parquet_roundtrip(frame: &DataFrame) -> Result<(), FpIoError> {
6962    let encoded = write_parquet_bytes(frame)?;
6963    let reparsed = read_parquet_bytes(&encoded)?;
6964    if !frame.equals(&reparsed) {
6965        return Err(FpIoError::Io(std::io::Error::other(
6966            "parquet round-trip drifted after parse/write/reparse",
6967        )));
6968    }
6969    Ok(())
6970}
6971
6972fn assert_feather_roundtrip(frame: &DataFrame) -> Result<(), FpIoError> {
6973    let encoded = write_feather_bytes(frame)?;
6974    let reparsed = read_feather_bytes(&encoded)?;
6975    if !frame.equals(&reparsed) {
6976        return Err(FpIoError::Io(std::io::Error::other(
6977            "feather round-trip drifted after parse/write/reparse",
6978        )));
6979    }
6980    Ok(())
6981}
6982
6983fn assert_ipc_stream_roundtrip(frame: &DataFrame) -> Result<(), FpIoError> {
6984    let encoded = write_ipc_stream_bytes(frame)?;
6985    let reparsed = read_ipc_stream_bytes(&encoded)?;
6986    if !frame.equals(&reparsed) {
6987        return Err(FpIoError::Io(std::io::Error::other(
6988            "ipc stream round-trip drifted after parse/write/reparse",
6989        )));
6990    }
6991    Ok(())
6992}
6993
6994const FUZZ_PIVOT_AGGFUNCS: [&str; 10] = [
6995    "sum", "mean", "count", "min", "max", "prod", "median", "var", "std", "first",
6996];
6997
6998fn fuzz_pivot_key_scalar_from_bytes(bytes: &[u8], synth_mode: bool, prefix: char) -> Scalar {
6999    let tag = bytes.first().copied().unwrap_or_default();
7000    let payload = bytes.get(1).copied().unwrap_or_default();
7001
7002    if synth_mode {
7003        match tag % 5 {
7004            0 => Scalar::Null(NullKind::Null),
7005            1 => Scalar::Utf8(format!("{prefix}{}", payload % 3)),
7006            2 => Scalar::Utf8(format!("{prefix}{}", (payload / 3) % 3)),
7007            3 => Scalar::Utf8(format!("{prefix}{}", (payload / 3) % 3)),
7008            _ => Scalar::Utf8(format!("{prefix}{}", payload % 5)),
7009        }
7010    } else {
7011        match tag % 6 {
7012            0 => Scalar::Null(NullKind::Null),
7013            1 => Scalar::Utf8(format!("{prefix}{}", char::from(b'a' + (payload % 4)))),
7014            2 => Scalar::Utf8(format!("{prefix}{}", payload % 5)),
7015            3 => Scalar::Utf8(format!(
7016                "{prefix}{}{}",
7017                char::from(b'a' + (payload % 3)),
7018                payload % 2
7019            )),
7020            4 => Scalar::Utf8(format!("{prefix}{}", payload % 7)),
7021            _ => Scalar::Utf8(format!("{prefix}{}", payload % 5)),
7022        }
7023    }
7024}
7025
7026fn fuzz_pivot_value_scalar_from_bytes(bytes: &[u8], synth_mode: bool) -> Scalar {
7027    let tag = bytes.first().copied().unwrap_or_default();
7028    let payload = bytes.get(1).copied().unwrap_or_default();
7029
7030    if synth_mode {
7031        match tag % 6 {
7032            0 => Scalar::Null(NullKind::NaN),
7033            1 => Scalar::Int64(i64::from(payload % 9) - 4),
7034            2 => Scalar::Float64(f64::from(i16::from(payload % 11) - 5)),
7035            3 => Scalar::Float64(f64::from(payload % 8) / 2.0),
7036            4 => Scalar::Float64(-f64::from(payload % 8) / 2.0),
7037            _ => Scalar::Int64(i64::from(payload % 3)),
7038        }
7039    } else {
7040        match tag % 8 {
7041            0 => Scalar::Null(NullKind::NaN),
7042            1 => Scalar::Int64(i64::from(payload % 17) - 8),
7043            2 => Scalar::Float64(f64::from(i8::from_ne_bytes([payload])) / 8.0),
7044            3 => Scalar::Float64(0.0),
7045            4 => Scalar::Float64(1.5),
7046            5 => Scalar::Float64(-2.5),
7047            6 => Scalar::Int64(i64::from(payload % 5)),
7048            _ => Scalar::Float64(f64::from(i16::from(payload % 13) - 6)),
7049        }
7050    }
7051}
7052
7053fn fuzz_pivot_table_frame_from_bytes(
7054    bytes: &[u8],
7055    synth_mode: bool,
7056) -> Result<DataFrame, FrameError> {
7057    let row_count = if synth_mode {
7058        usize::from(bytes.first().copied().unwrap_or(4) % 5) + 4
7059    } else {
7060        usize::from(bytes.first().copied().unwrap_or(2) % 8) + 1
7061    };
7062    let byte_at = |idx: usize| -> u8 { bytes.get(idx).copied().unwrap_or_default() };
7063
7064    let index = Index::new(
7065        (0..row_count)
7066            .map(|idx| IndexLabel::Int64(idx as i64))
7067            .collect::<Vec<_>>(),
7068    );
7069
7070    let row_values = (0..row_count)
7071        .map(|row_idx| {
7072            fuzz_pivot_key_scalar_from_bytes(
7073                &[byte_at(1 + row_idx * 6), byte_at(2 + row_idx * 6)],
7074                synth_mode,
7075                'r',
7076            )
7077        })
7078        .collect::<Vec<_>>();
7079    let col_values = (0..row_count)
7080        .map(|row_idx| {
7081            fuzz_pivot_key_scalar_from_bytes(
7082                &[byte_at(3 + row_idx * 6), byte_at(4 + row_idx * 6)],
7083                synth_mode,
7084                'c',
7085            )
7086        })
7087        .collect::<Vec<_>>();
7088    let val_values = (0..row_count)
7089        .map(|row_idx| {
7090            fuzz_pivot_value_scalar_from_bytes(
7091                &[byte_at(5 + row_idx * 6), byte_at(6 + row_idx * 6)],
7092                synth_mode,
7093            )
7094        })
7095        .collect::<Vec<_>>();
7096
7097    let mut columns = BTreeMap::new();
7098    columns.insert("row".to_owned(), Column::from_values(row_values)?);
7099    columns.insert("col".to_owned(), Column::from_values(col_values)?);
7100    columns.insert("val".to_owned(), Column::from_values(val_values)?);
7101
7102    DataFrame::new_with_column_order(
7103        index,
7104        columns,
7105        vec!["row".to_owned(), "col".to_owned(), "val".to_owned()],
7106    )
7107}
7108
7109fn fuzz_pivot_key_name(value: &Scalar) -> Option<String> {
7110    if value.is_missing() {
7111        return None;
7112    }
7113
7114    Some(match value {
7115        Scalar::Int64(v) => v.to_string(),
7116        Scalar::Utf8(v) => v.clone(),
7117        Scalar::Bool(v) => v.to_string(),
7118        Scalar::Float64(v) => v.to_string(),
7119        Scalar::Timedelta64(v) => Timedelta::format(*v),
7120        other => format!("{other:?}"),
7121    })
7122}
7123
7124fn fuzz_pivot_cell_is_missing(value: &Scalar) -> bool {
7125    value.is_missing() || matches!(value, Scalar::Float64(v) if v.is_nan())
7126}
7127
7128fn fuzz_dtype_from_byte(byte: u8) -> DType {
7129    match byte % 5 {
7130        0 => DType::Null,
7131        1 => DType::Bool,
7132        2 => DType::Int64,
7133        3 => DType::Float64,
7134        _ => DType::Utf8,
7135    }
7136}
7137
7138fn fuzz_u64_from_bytes(bytes: &[u8]) -> u64 {
7139    let mut padded = [0_u8; 8];
7140    let copy_len = bytes.len().min(8);
7141    padded[..copy_len].copy_from_slice(&bytes[..copy_len]);
7142    u64::from_le_bytes(padded)
7143}
7144
7145fn fuzz_i64_from_bytes(bytes: &[u8]) -> i64 {
7146    let mut padded = [0_u8; 8];
7147    let copy_len = bytes.len().min(8);
7148    padded[..copy_len].copy_from_slice(&bytes[..copy_len]);
7149    i64::from_le_bytes(padded)
7150}
7151
7152fn fuzz_float64_from_bytes(bytes: &[u8]) -> f64 {
7153    match bytes.first().copied().unwrap_or_default() % 8 {
7154        0 => 0.0,
7155        1 => 1.0,
7156        2 => -1.0,
7157        3 => 1.5,
7158        4 => f64::INFINITY,
7159        5 => f64::NEG_INFINITY,
7160        6 => f64::NAN,
7161        _ => f64::from_bits(fuzz_u64_from_bytes(bytes)),
7162    }
7163}
7164
7165fn fuzz_scalar_from_bytes(bytes: &[u8]) -> Scalar {
7166    let Some((&tag, payload)) = bytes.split_first() else {
7167        return Scalar::Null(NullKind::Null);
7168    };
7169
7170    match tag % 8 {
7171        0 => Scalar::Null(NullKind::Null),
7172        1 => Scalar::Null(NullKind::NaN),
7173        2 => Scalar::Null(NullKind::NaT),
7174        3 => Scalar::Bool(payload.first().is_some_and(|byte| byte % 2 == 1)),
7175        4 => Scalar::Int64(fuzz_i64_from_bytes(payload)),
7176        5 => Scalar::Float64(fuzz_float64_from_bytes(payload)),
7177        _ => Scalar::Utf8(String::from_utf8_lossy(&payload[..payload.len().min(12)]).into_owned()),
7178    }
7179}
7180
7181fn fuzz_index_label_from_byte(byte: u8) -> IndexLabel {
7182    match byte {
7183        b'0'..=b'9' => IndexLabel::Int64(i64::from((byte - b'0') % 4)),
7184        b'a'..=b'z' => IndexLabel::Utf8(char::from(b'a' + ((byte - b'a') % 4)).to_string()),
7185        b'A'..=b'Z' => IndexLabel::Utf8(char::from(b'a' + ((byte - b'A') % 4)).to_string()),
7186        _ if byte.is_multiple_of(2) => IndexLabel::Int64(i64::from(byte % 4)),
7187        _ => IndexLabel::Utf8(char::from(b'a' + (byte % 4)).to_string()),
7188    }
7189}
7190
7191fn fuzz_index_from_bytes(bytes: &[u8]) -> Index {
7192    Index::new(
7193        bytes
7194            .iter()
7195            .take(32)
7196            .map(|byte| fuzz_index_label_from_byte(*byte))
7197            .collect(),
7198    )
7199}
7200
7201fn assert_json_roundtrip(frame: &DataFrame, orient: JsonOrient) -> Result<(), FpIoError> {
7202    let encoded = write_json_string(frame, orient)?;
7203    let reparsed = read_json_str(&encoded, orient)?;
7204    if !frame.equals(&reparsed) {
7205        return Err(FpIoError::JsonFormat(format!(
7206            "json {:?} round-trip drifted after parse/write/reparse",
7207            orient
7208        )));
7209    }
7210    Ok(())
7211}
7212
7213fn assert_jsonl_roundtrip(frame: &DataFrame) -> Result<(), FpIoError> {
7214    let encoded = write_jsonl_string(frame)?;
7215    let reparsed = read_jsonl_str(&encoded)?;
7216    if !frame.equals(&reparsed) {
7217        return Err(FpIoError::JsonFormat(
7218            "jsonl round-trip drifted after parse/write/reparse".to_owned(),
7219        ));
7220    }
7221    Ok(())
7222}
7223
7224/// Structure-aware fuzz entrypoint for the `fp-io` CSV reader.
7225///
7226/// Any parser error is acceptable, but successful parses must survive a
7227/// write/reparse round-trip without panicking or drifting.
7228pub fn fuzz_csv_parse_bytes(input: &[u8]) -> Result<(), FpIoError> {
7229    let input = String::from_utf8_lossy(input);
7230    let frame = read_csv_str(&input)?;
7231    assert_csv_roundtrip(&frame)
7232}
7233
7234/// Structure-aware fuzz entrypoint for the `fp-io` Excel reader.
7235///
7236/// Any parser error is acceptable, but successful parses must survive a
7237/// write/reparse round-trip without panicking or drifting.
7238pub fn fuzz_excel_io_bytes(input: &[u8]) -> Result<(), FpIoError> {
7239    let frame = read_excel_bytes(input, &ExcelReadOptions::default())?;
7240    assert_excel_roundtrip(&frame)
7241}
7242
7243/// Structure-aware fuzz entrypoint for the `fp-io` Parquet reader.
7244///
7245/// Inputs use the same dual-mode envelope as the Arrow-backed IPC harnesses.
7246/// Raw mode (`tag % 2 == 0`) feeds the remaining bytes directly into
7247/// `read_parquet_bytes()`, where parser errors are acceptable but successful
7248/// parses must round-trip. Synth mode projects bytes into a tiny typed
7249/// `DataFrame`, serializes it with `write_parquet_bytes()`, then checks the
7250/// reader against that valid payload.
7251pub fn fuzz_parquet_io_bytes(input: &[u8]) -> Result<(), FpIoError> {
7252    let Some((&mode, payload)) = input.split_first() else {
7253        return Ok(());
7254    };
7255
7256    if mode % 2 == 0 {
7257        let frame = read_parquet_bytes(payload)?;
7258        assert_parquet_roundtrip(&frame)
7259    } else {
7260        let frame = fuzz_feather_frame_from_bytes(payload)?;
7261        assert_parquet_roundtrip(&frame)
7262    }
7263}
7264
7265fn fuzz_feather_dtype_from_byte(byte: u8) -> DType {
7266    match byte % 4 {
7267        0 => DType::Bool,
7268        1 => DType::Int64,
7269        2 => DType::Float64,
7270        _ => DType::Utf8,
7271    }
7272}
7273
7274fn fuzz_feather_scalar_for_dtype(dtype: &DType, bytes: &[u8]) -> Scalar {
7275    let tag = bytes.first().copied().unwrap_or_default();
7276    let payload = bytes.get(1).copied().unwrap_or_default();
7277
7278    if tag % 5 == 0 {
7279        return Scalar::missing_for_dtype(dtype.clone());
7280    }
7281
7282    match dtype {
7283        DType::Bool | DType::BoolNullable => Scalar::Bool(payload % 2 == 1),
7284        DType::Int64 | DType::Int64Nullable => Scalar::Int64(i64::from(payload % 11) - 5),
7285        DType::Float64 | DType::Float64Nullable => Scalar::Float64(match payload % 6 {
7286            0 => 0.0,
7287            1 => 1.0,
7288            2 => -1.0,
7289            3 => 1.5,
7290            4 => f64::NAN,
7291            _ => -0.0,
7292        }),
7293        DType::Utf8 => Scalar::Utf8(format!(
7294            "s{}{}",
7295            char::from(b'a' + (payload % 26)),
7296            payload % 4
7297        )),
7298        DType::Categorical => Scalar::Int64(i64::from(payload % 5) - 1),
7299        DType::Null => Scalar::Null(NullKind::Null),
7300        DType::Sparse => Scalar::Null(NullKind::Null),
7301        DType::Timedelta64 => {
7302            Scalar::Timedelta64(i64::from(payload % 100) * Timedelta::NANOS_PER_HOUR)
7303        }
7304        DType::Datetime64 { .. } => Scalar::Datetime64(i64::from(payload % 100) * 1_000_000_000),
7305        DType::Period => Scalar::Period(Period::new(i64::from(payload % 100), PeriodFreq::Daily)),
7306        DType::Interval => Scalar::Interval(fp_types::Interval::new(
7307            f64::from(payload % 10),
7308            f64::from(payload % 10 + 5),
7309            fp_types::IntervalClosed::Both,
7310        )),
7311    }
7312}
7313
7314fn fuzz_feather_frame_from_bytes(bytes: &[u8]) -> Result<DataFrame, FpIoError> {
7315    let row_count = usize::from(bytes.first().copied().unwrap_or(2) % 4) + 1;
7316    let column_count = usize::from(bytes.get(1).copied().unwrap_or(1) % 3) + 1;
7317    let byte_at = |idx: usize| -> u8 { bytes.get(idx).copied().unwrap_or_default() };
7318
7319    let index = Index::new(
7320        (0..row_count)
7321            .map(|idx| IndexLabel::Int64(idx as i64))
7322            .collect::<Vec<_>>(),
7323    );
7324
7325    let mut columns = BTreeMap::new();
7326    let mut column_order = Vec::new();
7327
7328    for col_idx in 0..column_count {
7329        let dtype = fuzz_feather_dtype_from_byte(byte_at(2 + col_idx));
7330        let name = format!("c{col_idx}");
7331        let values = (0..row_count)
7332            .map(|row_idx| {
7333                fuzz_feather_scalar_for_dtype(
7334                    &dtype,
7335                    &[
7336                        byte_at(8 + col_idx * 11 + row_idx * 2),
7337                        byte_at(9 + col_idx * 11 + row_idx * 2),
7338                    ],
7339                )
7340            })
7341            .collect::<Vec<_>>();
7342        let column = Column::new(dtype, values)?;
7343        column_order.push(name.clone());
7344        columns.insert(name, column);
7345    }
7346
7347    DataFrame::new_with_column_order(index, columns, column_order).map_err(FpIoError::from)
7348}
7349
7350fn fuzz_eval_frame_from_bytes(bytes: &[u8]) -> Result<DataFrame, FrameError> {
7351    let row_count = usize::from(bytes.first().copied().unwrap_or(3) % 8) + 1;
7352    let column_count = usize::from(bytes.get(1).copied().unwrap_or(1) % 3) + 2;
7353    let byte_at = |idx: usize| -> u8 { bytes.get(idx).copied().unwrap_or_default() };
7354    let column_names = ["a", "b", "c", "d"];
7355
7356    let index = Index::new(
7357        (0..row_count)
7358            .map(|idx| IndexLabel::Int64(idx as i64))
7359            .collect::<Vec<_>>(),
7360    );
7361
7362    let mut columns = BTreeMap::new();
7363    let mut column_order = Vec::new();
7364
7365    for (col_idx, column_name) in column_names.iter().enumerate().take(column_count) {
7366        let dtype = if byte_at(2 + col_idx).is_multiple_of(2) {
7367            DType::Int64
7368        } else {
7369            DType::Float64
7370        };
7371        let name = (*column_name).to_owned();
7372        let values = (0..row_count)
7373            .map(|row_idx| {
7374                let tag = byte_at(8 + col_idx * 17 + row_idx * 2);
7375                let payload = byte_at(9 + col_idx * 17 + row_idx * 2);
7376                if tag % 7 == 0 {
7377                    Scalar::missing_for_dtype(dtype.clone())
7378                } else {
7379                    match &dtype {
7380                        DType::Int64 => Scalar::Int64(i64::from(payload % 17) - 8),
7381                        DType::Float64 => Scalar::Float64(match payload % 6 {
7382                            0 => 0.0,
7383                            1 => 1.0,
7384                            2 => -1.0,
7385                            3 => 1.5,
7386                            4 => 2.5,
7387                            _ => f64::NAN,
7388                        }),
7389                        _ => unreachable!("eval fuzz only projects numeric dtypes"),
7390                    }
7391                }
7392            })
7393            .collect::<Vec<_>>();
7394        let column = Column::new(dtype, values)?;
7395        column_order.push(name.clone());
7396        columns.insert(name, column);
7397    }
7398
7399    DataFrame::new_with_column_order(index, columns, column_order)
7400}
7401
7402/// Structure-aware fuzz entrypoint for `DataFrame.eval(...)`.
7403///
7404/// The first byte selects strict vs hardened runtime policy. The full byte
7405/// stream is projected into a small numeric `DataFrame` with columns `a..d`,
7406/// and the remaining bytes are interpreted as a lossy UTF-8 expression. Parser
7407/// errors are allowed; panics are not. Successful evals must preserve row
7408/// count.
7409pub fn fuzz_dataframe_eval_bytes(input: &[u8]) -> Result<(), String> {
7410    let Some((&policy_tag, expr_bytes)) = input.split_first() else {
7411        return Ok(());
7412    };
7413
7414    let frame = fuzz_eval_frame_from_bytes(input)
7415        .map_err(|err| format!("eval fuzz frame projection failed: {err}"))?;
7416    let expr = String::from_utf8_lossy(&expr_bytes[..expr_bytes.len().min(96)]).into_owned();
7417    let policy = if policy_tag.is_multiple_of(2) {
7418        RuntimePolicy::strict()
7419    } else {
7420        RuntimePolicy::hardened(Some(100_000))
7421    };
7422    let mut ledger = EvidenceLedger::new();
7423
7424    match eval_str_with_locals(&expr, &frame, &BTreeMap::new(), &policy, &mut ledger) {
7425        Ok(series) => {
7426            if series.len() != frame.index().len() {
7427                return Err(format!(
7428                    "eval result length mismatch: expr={expr:?} result_len={} frame_len={}",
7429                    series.len(),
7430                    frame.index().len()
7431                ));
7432            }
7433            Ok(())
7434        }
7435        Err(_) => Ok(()),
7436    }
7437}
7438
7439/// Structure-aware fuzz entrypoint for `fp_expr::parse_expr(...)`.
7440///
7441/// The narrowest expr-surface fuzz target per /testing-fuzzing Rule 2
7442/// ("fuzz the parser, not the application"). Every eval/query caller
7443/// inherits parser bugs, so this target catches bugs at their source.
7444///
7445/// Per br-frankenpandas-jkhg Rule 3 coverage. Input is clamped to 4096
7446/// bytes and interpreted as lossy UTF-8. Panics in parse_expr are
7447/// failures; Err returns are allowed.
7448pub fn fuzz_parse_expr_bytes(input: &[u8]) -> Result<(), String> {
7449    if input.len() > 4096 {
7450        return Ok(());
7451    }
7452    let expr_str = String::from_utf8_lossy(input);
7453    let _ = parse_expr(&expr_str);
7454    Ok(())
7455}
7456
7457/// Structure-aware fuzz entrypoint for `fp_expr::query_str(...)`.
7458///
7459/// Projects the input into a small numeric `DataFrame` (via
7460/// fuzz_eval_frame_from_bytes) and then issues a query against it.
7461/// query_str produces a DataFrame (filter-semantics), a different
7462/// post-parse code path than eval_str which covers it indirectly.
7463///
7464/// Per br-frankenpandas-jkhg Rule 3 coverage. Size guard matches
7465/// fuzz_dataframe_eval_bytes at 256 KB. Successful queries must not
7466/// expand the row count (filter can only shrink).
7467pub fn fuzz_query_str_bytes(input: &[u8]) -> Result<(), String> {
7468    let Some((&policy_tag, expr_bytes)) = input.split_first() else {
7469        return Ok(());
7470    };
7471
7472    let frame = fuzz_eval_frame_from_bytes(input)
7473        .map_err(|err| format!("query fuzz frame projection failed: {err}"))?;
7474    let expr = String::from_utf8_lossy(&expr_bytes[..expr_bytes.len().min(96)]).into_owned();
7475    let policy = if policy_tag.is_multiple_of(2) {
7476        RuntimePolicy::strict()
7477    } else {
7478        RuntimePolicy::hardened(Some(100_000))
7479    };
7480    let mut ledger = EvidenceLedger::new();
7481
7482    match query_str(&expr, &frame, &policy, &mut ledger) {
7483        Ok(filtered) => {
7484            if filtered.index().len() > frame.index().len() {
7485                return Err(format!(
7486                    "query result expanded rows: expr={expr:?} result_len={} frame_len={}",
7487                    filtered.index().len(),
7488                    frame.index().len()
7489                ));
7490            }
7491            Ok(())
7492        }
7493        Err(_) => Ok(()),
7494    }
7495}
7496
7497/// Structure-aware fuzz entrypoint for `fp_expr::query_str_with_locals(...)`.
7498///
7499/// Extends `fuzz_query_str_bytes` by constructing a 3-key `BTreeMap`
7500/// of local bindings from the first byte: one key deliberately named
7501/// to collide with an existing frame column, one with a reserved
7502/// dunder-style name. Locals-propagation has its own precedence
7503/// semantics that query_str alone cannot exercise.
7504///
7505/// Per br-frankenpandas-jkhg Rule 3 coverage. Same filter-shrinks
7506/// invariant as query_str.
7507pub fn fuzz_query_str_with_locals_bytes(input: &[u8]) -> Result<(), String> {
7508    let Some((&policy_tag, expr_bytes)) = input.split_first() else {
7509        return Ok(());
7510    };
7511
7512    let frame = fuzz_eval_frame_from_bytes(input)
7513        .map_err(|err| format!("query-with-locals fuzz frame projection failed: {err}"))?;
7514    let expr = String::from_utf8_lossy(&expr_bytes[..expr_bytes.len().min(96)]).into_owned();
7515    let policy = if policy_tag.is_multiple_of(2) {
7516        RuntimePolicy::strict()
7517    } else {
7518        RuntimePolicy::hardened(Some(100_000))
7519    };
7520    let mut ledger = EvidenceLedger::new();
7521
7522    let mut locals = BTreeMap::<String, Scalar>::new();
7523    let key_tag = policy_tag as usize;
7524    let key = match key_tag % 3 {
7525        0 => "x",
7526        1 => "a",          // collides with fuzz_eval_frame column name
7527        _ => "__secret__", // reserved-style identifier
7528    };
7529    let value = match (policy_tag >> 2) % 4 {
7530        0 => Scalar::Int64(0),
7531        1 => Scalar::Int64(1),
7532        2 => Scalar::Utf8("test".to_string()),
7533        _ => Scalar::Null(NullKind::Null),
7534    };
7535    locals.insert(key.to_string(), value);
7536
7537    match query_str_with_locals(&expr, &frame, &locals, &policy, &mut ledger) {
7538        Ok(filtered) => {
7539            if filtered.index().len() > frame.index().len() {
7540                return Err(format!(
7541                    "query-with-locals result expanded rows: expr={expr:?} result_len={} frame_len={}",
7542                    filtered.index().len(),
7543                    frame.index().len()
7544                ));
7545            }
7546            Ok(())
7547        }
7548        Err(_) => Ok(()),
7549    }
7550}
7551
7552/// Concurrency-oriented fuzz entrypoint: exercise an `Arc<DataFrame>`
7553/// shared across multiple reader threads.
7554///
7555/// Per br-frankenpandas-bahw Phase 1 + br-frankenpandas-i3t8 (Sync
7556/// contract fix). /testing-fuzzing Rule 6 + Rule 7 (concurrency
7557/// archetype, TSan campaign). As of br-i3t8, `Index`'s internal caches
7558/// switched from `std::cell::OnceCell` (!Sync) to `std::sync::OnceLock`
7559/// (Sync), so `DataFrame` is now `Send + Sync`. This harness exercises
7560/// the shared-Arc pattern directly — any hidden race in the lazy cache
7561/// initialization surfaces as a TSan report or as a divergent observed
7562/// shape across threads.
7563///
7564/// Shape:
7565/// - Project bytes into a small frame via the existing helper.
7566/// - Wrap in `Arc` and clone the Arc into 4 reader threads.
7567/// - Each thread does a read-only traversal (index len, column_names
7568///   len, has_duplicates, is_sorted — the last two trigger OnceLock
7569///   init) in a hot loop and returns the observed shape.
7570/// - Join all threads; assert all four observed shapes match.
7571///
7572/// Under TSan (`RUSTFLAGS="-Zsanitizer=thread" cargo +nightly fuzz run
7573/// fuzz_parallel_dataframe`) this harness detects races in the
7574/// OnceLock init path or in any other shared-state that future Sync
7575/// work might introduce.
7576pub fn fuzz_parallel_dataframe_bytes(input: &[u8]) -> Result<(), String> {
7577    use std::{sync::Arc, thread};
7578
7579    if input.is_empty() || input.len() > 64 * 1024 {
7580        return Ok(());
7581    }
7582
7583    let frame = fuzz_eval_frame_from_bytes(input)
7584        .map_err(|err| format!("parallel fuzz frame projection failed: {err}"))?;
7585    let expected_index_len = frame.index().len();
7586    let expected_col_count = frame.column_names().len();
7587
7588    let shared = Arc::new(frame);
7589    let mut handles = Vec::with_capacity(4);
7590    for _ in 0..4 {
7591        let f = Arc::clone(&shared);
7592        handles.push(thread::spawn(move || -> (usize, usize) {
7593            let mut last = (0, 0);
7594            for _ in 0..64 {
7595                // index().has_duplicates() + is_sorted() exercise the
7596                // OnceLock lazy-init path under contention.
7597                let _dup = f.index().has_duplicates();
7598                let _sorted = f.index().is_sorted();
7599                last = (f.index().len(), f.column_names().len());
7600            }
7601            last
7602        }));
7603    }
7604    for handle in handles {
7605        let (idx_len, col_count) = handle
7606            .join()
7607            .map_err(|_| "parallel fuzz thread panicked".to_string())?;
7608        if idx_len != expected_index_len || col_count != expected_col_count {
7609            return Err(format!(
7610                "parallel read divergence: expected ({expected_index_len}, {expected_col_count}) got ({idx_len}, {col_count})"
7611            ));
7612        }
7613    }
7614    Ok(())
7615}
7616
7617/// Stateful fuzz entrypoint: apply a sequence of `DataFrame` operations.
7618///
7619/// Per br-frankenpandas-wr9n Phase 1: all 22 existing fuzz targets run a
7620/// single op against a fresh frame. State bugs — where op N's output
7621/// becomes op N+1's input and only the compound sequence surfaces the
7622/// defect — are invisible to single-op targets. This harness walks a
7623/// 2-to-8-step op chain driven by the input byte tags and asserts the
7624/// frame-integrity invariants on every intermediate state.
7625///
7626/// Op alphabet (byte-tag % len):
7627/// 0: select_columns(first_column)
7628/// 1: drop_column(last_column)
7629/// 2: sort_values(selected_column, ascending from the next tag bit)
7630/// 3: reset_index(drop=false)
7631///
7632/// Invariants checked after every op:
7633/// - every column's length matches the index length
7634/// - `columns().len()` matches `column_order().len()`
7635pub fn fuzz_dataframe_op_chain_bytes(input: &[u8]) -> Result<(), String> {
7636    if input.len() < 3 || input.len() > 64 * 1024 {
7637        return Ok(());
7638    }
7639
7640    let mut frame = fuzz_eval_frame_from_bytes(input)
7641        .map_err(|err| format!("op-chain fuzz frame projection failed: {err}"))?;
7642
7643    assert_op_chain_invariants(&frame, "initial")?;
7644
7645    let op_count = usize::from(input.get(2).copied().unwrap_or(2) % 7) + 2;
7646    for (step, op_byte) in input.iter().skip(3).take(op_count).enumerate() {
7647        let tag = *op_byte % 4;
7648        let col_names: Vec<String> = frame.column_names().iter().map(|s| (*s).clone()).collect();
7649        if col_names.is_empty() {
7650            break;
7651        }
7652        let pick = |idx: usize| col_names[idx % col_names.len()].clone();
7653
7654        let outcome = match tag {
7655            0 => {
7656                let col = pick(0);
7657                frame.select_columns(&[col.as_str()])
7658            }
7659            1 => {
7660                let col = pick(col_names.len().saturating_sub(1));
7661                frame.drop_column(&col)
7662            }
7663            2 => {
7664                let col = pick(*op_byte as usize);
7665                let ascending = (*op_byte / 4).is_multiple_of(2);
7666                frame.sort_values(&col, ascending)
7667            }
7668            _ => frame.reset_index(false),
7669        };
7670
7671        match outcome {
7672            Ok(next) => {
7673                frame = next;
7674                assert_op_chain_invariants(&frame, &format!("step {step} (tag {tag})"))?;
7675            }
7676            Err(_) => break, // some op sequences are genuinely invalid
7677        }
7678    }
7679    Ok(())
7680}
7681
7682fn assert_op_chain_invariants(frame: &DataFrame, label: &str) -> Result<(), String> {
7683    let index_len = frame.index().len();
7684    let order_len = frame.column_names().len();
7685    let columns = frame.columns();
7686    if order_len != columns.len() {
7687        return Err(format!(
7688            "{label}: column_names len {order_len} != columns len {}",
7689            columns.len()
7690        ));
7691    }
7692    for name in frame.column_names() {
7693        let Some(column) = columns.get(name) else {
7694            return Err(format!(
7695                "{label}: column_names mentions missing column {name}"
7696            ));
7697        };
7698        if column.len() != index_len {
7699            return Err(format!(
7700                "{label}: column {name} len {} != index len {index_len}",
7701                column.len()
7702            ));
7703        }
7704    }
7705    Ok(())
7706}
7707
7708/// Structure-aware fuzz entrypoint for SQL read APIs against an in-memory
7709/// SQLite connection.
7710///
7711/// Per br-frankenpandas-gpxk Phase 1: fp-io exposes six pub fns that accept
7712/// untrusted query strings (`read_sql`, `read_sql_with_options`,
7713/// `read_sql_with_index_col`, `read_sql_table`, `read_sql_table_with_index_col`,
7714/// `read_sql_table_columns`). This target keeps the narrow query parser path
7715/// covered while also dispatching into the indexed read variants, where
7716/// `index_col` validation has separate edge cases.
7717///
7718/// Harness shape:
7719/// - Construct a fixed-schema in-memory SQLite (two small tables populated
7720///   with deterministic rows).
7721/// - Convert input bytes to lossy UTF-8, clamp to 4 KB. Legacy corpus entries
7722///   are interpreted entirely as SQL/table text; inputs prefixed with
7723///   `[0xff, mode]` use `mode` for API/index_col dispatch and the remaining
7724///   bytes as SQL/table text.
7725/// - Call one SQL read entrypoint; Ok and Err are both acceptable, panics are
7726///   not. Successful frames must preserve column/index length invariants.
7727pub fn fuzz_read_sql_bytes(input: &[u8]) -> Result<(), String> {
7728    if input.len() > 4 * 1024 {
7729        return Ok(());
7730    }
7731
7732    let conn = rusqlite::Connection::open_in_memory()
7733        .map_err(|e| format!("open_in_memory failed: {e}"))?;
7734    conn.execute_batch(
7735        "CREATE TABLE t1 (a INTEGER, b TEXT);
7736         INSERT INTO t1 (a, b) VALUES (1, 'one'), (2, 'two'), (3, 'three');
7737         CREATE TABLE t2 (k TEXT PRIMARY KEY, v REAL);
7738         INSERT INTO t2 (k, v) VALUES ('x', 1.5), ('y', 2.5), ('z', 3.5);
7739         CREATE TABLE empty_t (x INTEGER);",
7740    )
7741    .map_err(|e| format!("execute_batch failed: {e}"))?;
7742
7743    let (mode, payload) = match input {
7744        [0xff, mode, rest @ ..] => (*mode, rest),
7745        [mode, ..] => (*mode, input),
7746        [] => (0, input),
7747    };
7748    let text = String::from_utf8_lossy(payload);
7749    let index_col = fuzz_sql_index_col(mode);
7750    let options = SqlReadOptions {
7751        index_col: if mode & 0b1000 != 0 {
7752            index_col.map(str::to_owned)
7753        } else {
7754            None
7755        },
7756        ..SqlReadOptions::default()
7757    };
7758
7759    let result = match mode % 8 {
7760        0 => read_sql(&conn, &text),
7761        1 => read_sql_with_options(&conn, &text, &options),
7762        2 => read_sql_with_index_col(&conn, &text, index_col),
7763        3 => read_sql_query(&conn, &text),
7764        4 => read_sql_query_with_options(&conn, &text, &options),
7765        5 => read_sql_query_with_options_and_index_col(&conn, &text, &options, index_col),
7766        6 => read_sql_table_with_index_col(&conn, fuzz_sql_table_name(mode, &text), index_col),
7767        _ => read_sql_table_with_options_and_index_col(
7768            &conn,
7769            fuzz_sql_table_name(mode, &text),
7770            &options,
7771            index_col,
7772        ),
7773    };
7774    if let Ok(frame) = result {
7775        assert_sql_fuzz_frame_invariants(&frame)?;
7776    }
7777    Ok(())
7778}
7779
7780fn fuzz_sql_index_col(mode: u8) -> Option<&'static str> {
7781    match (mode >> 4) % 4 {
7782        0 => None,
7783        1 => Some("a"),
7784        2 => Some("k"),
7785        _ => Some(""),
7786    }
7787}
7788
7789fn fuzz_sql_table_name(mode: u8, text: &str) -> &str {
7790    match (mode >> 2) % 4 {
7791        0 => "t1",
7792        1 => "t2",
7793        2 => "empty_t",
7794        _ => text.trim(),
7795    }
7796}
7797
7798fn assert_sql_fuzz_frame_invariants(frame: &DataFrame) -> Result<(), String> {
7799    let index_len = frame.index().len();
7800    for name in frame.column_names() {
7801        let column = frame
7802            .column(name)
7803            .ok_or_else(|| format!("column_names mentions missing SQL column {name}"))?;
7804        if column.len() != index_len {
7805            return Err(format!(
7806                "SQL frame column {name} length {} != index length {index_len}",
7807                column.len()
7808            ));
7809        }
7810    }
7811    Ok(())
7812}
7813
7814/// Structure-aware fuzz entrypoint for `DataFrame::from_dict(...)`.
7815///
7816/// Per br-frankenpandas-d7lt. The input is projected into a small
7817/// `name → Vec<Scalar>` dict; on Ok, the resulting frame's row count must
7818/// equal the inferred row count and every column name must be present.
7819pub fn fuzz_dataframe_from_dict_bytes(input: &[u8]) -> Result<(), String> {
7820    if input.len() < 2 || input.len() > 64 * 1024 {
7821        return Ok(());
7822    }
7823    let n_cols = usize::from(input[0] % 4) + 1;
7824    let n_rows = usize::from(input[1] % 8) + 1;
7825    let names = ["a", "b", "c", "d"];
7826    let byte_at = |idx: usize| input.get(idx).copied().unwrap_or(0);
7827
7828    let mut data: Vec<(&str, Vec<Scalar>)> = Vec::with_capacity(n_cols);
7829    for (col_idx, col_name) in names.iter().take(n_cols).enumerate() {
7830        let mut values = Vec::with_capacity(n_rows);
7831        for row_idx in 0..n_rows {
7832            let b = byte_at(2 + col_idx * n_rows + row_idx);
7833            values.push(Scalar::Int64(i64::from(b)));
7834        }
7835        data.push((*col_name, values));
7836    }
7837    let column_order: Vec<&str> = names.iter().take(n_cols).copied().collect();
7838
7839    if let Ok(frame) = DataFrame::from_dict(&column_order, data) {
7840        if frame.index().len() != n_rows {
7841            return Err(format!(
7842                "from_dict row count mismatch: expected {n_rows} got {}",
7843                frame.index().len()
7844            ));
7845        }
7846        if frame.column_names().len() != n_cols {
7847            return Err(format!(
7848                "from_dict column count mismatch: expected {n_cols} got {}",
7849                frame.column_names().len()
7850            ));
7851        }
7852    }
7853    Ok(())
7854}
7855
7856/// Structure-aware fuzz entrypoint for `DataFrame::from_records(...)`.
7857///
7858/// Per br-frankenpandas-d7lt. Builds rectangular records; on Ok, the
7859/// result's row count matches the records-vec length.
7860pub fn fuzz_dataframe_from_records_bytes(input: &[u8]) -> Result<(), String> {
7861    if input.len() < 2 || input.len() > 64 * 1024 {
7862        return Ok(());
7863    }
7864    let n_cols = usize::from(input[0] % 4) + 1;
7865    let n_rows = usize::from(input[1] % 8) + 1;
7866    let byte_at = |idx: usize| input.get(idx).copied().unwrap_or(0);
7867
7868    let mut records: Vec<Vec<Scalar>> = Vec::with_capacity(n_rows);
7869    for row_idx in 0..n_rows {
7870        let mut row = Vec::with_capacity(n_cols);
7871        for col_idx in 0..n_cols {
7872            let b = byte_at(2 + row_idx * n_cols + col_idx);
7873            row.push(Scalar::Int64(i64::from(b)));
7874        }
7875        records.push(row);
7876    }
7877    let column_order: Vec<String> = ["a", "b", "c", "d"][..n_cols]
7878        .iter()
7879        .map(|s| (*s).to_owned())
7880        .collect();
7881
7882    if let Ok(frame) = DataFrame::from_records(records, Some(&column_order), None)
7883        && frame.index().len() != n_rows
7884    {
7885        return Err(format!(
7886            "from_records row count mismatch: expected {n_rows} got {}",
7887            frame.index().len()
7888        ));
7889    }
7890    Ok(())
7891}
7892
7893/// Structure-aware fuzz entrypoint for `DataFrame::from_series(...)`.
7894///
7895/// Per br-frankenpandas-d7lt. Builds a `Vec<Series>` with a shared `Index`
7896/// (aligned AACE path); on Ok, the resulting frame's column count
7897/// equals the input series count.
7898pub fn fuzz_dataframe_from_series_bytes(input: &[u8]) -> Result<(), String> {
7899    if input.len() < 2 || input.len() > 64 * 1024 {
7900        return Ok(());
7901    }
7902    let n_series = usize::from(input[0] % 4) + 1;
7903    let n_rows = usize::from(input[1] % 8) + 1;
7904    let names = ["a", "b", "c", "d"];
7905    let byte_at = |idx: usize| input.get(idx).copied().unwrap_or(0);
7906
7907    let labels: Vec<IndexLabel> = (0..n_rows).map(|i| IndexLabel::Int64(i as i64)).collect();
7908
7909    let mut series_list: Vec<Series> = Vec::with_capacity(n_series);
7910    for (s_idx, col_name) in names.iter().take(n_series).enumerate() {
7911        let values: Vec<Scalar> = (0..n_rows)
7912            .map(|row| Scalar::Int64(i64::from(byte_at(2 + s_idx * n_rows + row))))
7913            .collect();
7914        let series = Series::from_values(*col_name, labels.clone(), values)
7915            .map_err(|e| format!("from_series projection failed: {e}"))?;
7916        series_list.push(series);
7917    }
7918
7919    if let Ok(frame) = DataFrame::from_series(series_list) {
7920        if frame.column_names().len() != n_series {
7921            return Err(format!(
7922                "from_series column count mismatch: expected {n_series} got {}",
7923                frame.column_names().len()
7924            ));
7925        }
7926        if frame.index().len() != n_rows {
7927            return Err(format!(
7928                "from_series row count mismatch: expected {n_rows} got {}",
7929                frame.index().len()
7930            ));
7931        }
7932    }
7933    Ok(())
7934}
7935
7936/// Structure-aware fuzz entrypoint for `merge_dataframes(...)`.
7937///
7938/// Per br-frankenpandas-d7lt. Builds two small frames with a shared
7939/// `k` column + one value column each; calls merge_dataframes with
7940/// each of Inner/Left/Right/Outer.
7941///
7942/// Bound invariants:
7943/// - generated keys are unique within each side, so inner rows ≤ min input rows
7944/// - left/right/outer joins retain at least the matching input-side row counts
7945/// - result has (left_cols + right_cols - shared_cols) columns (the
7946///   suffix-resolved superset)
7947pub fn fuzz_dataframe_merge_bytes(input: &[u8]) -> Result<(), String> {
7948    if input.len() < 4 || input.len() > 64 * 1024 {
7949        return Ok(());
7950    }
7951    let join_tag = input[0] % 4;
7952    let left_rows = usize::from(input[1] % 6) + 1;
7953    let right_rows = usize::from(input[2] % 6) + 1;
7954    let byte_at = |idx: usize| input.get(idx).copied().unwrap_or(0);
7955
7956    let build_frame =
7957        |name_suffix: &str, n_rows: usize, offset: usize| -> Result<DataFrame, String> {
7958            let labels: Vec<IndexLabel> =
7959                (0..n_rows).map(|i| IndexLabel::Int64(i as i64)).collect();
7960            let keys: Vec<Scalar> = (0..n_rows)
7961                .map(|row| {
7962                    let overlap_bucket = i64::from(byte_at(offset + row) & 1);
7963                    Scalar::Int64(row as i64 + overlap_bucket * 8)
7964                })
7965                .collect();
7966            let values: Vec<Scalar> = (0..n_rows)
7967                .map(|row| Scalar::Int64(i64::from(byte_at(offset + n_rows + row))))
7968                .collect();
7969            let k_series = Series::from_values("k", labels.clone(), keys)
7970                .map_err(|e| format!("merge fuzz k-series failed: {e}"))?;
7971            let v_name = format!("v_{name_suffix}");
7972            let v_series = Series::from_values(&v_name, labels, values)
7973                .map_err(|e| format!("merge fuzz v-series failed: {e}"))?;
7974            DataFrame::from_series(vec![k_series, v_series])
7975                .map_err(|e| format!("merge fuzz frame build failed: {e}"))
7976        };
7977
7978    let left = build_frame("l", left_rows, 3)?;
7979    let right = build_frame("r", right_rows, 3 + left_rows * 2)?;
7980
7981    let join_type = match join_tag {
7982        0 => JoinType::Inner,
7983        1 => JoinType::Left,
7984        2 => JoinType::Right,
7985        _ => JoinType::Outer,
7986    };
7987
7988    let Ok(merged) = merge_dataframes(&left, &right, "k", join_type) else {
7989        return Ok(());
7990    };
7991
7992    let merged_rows = merged.index.len();
7993    let max_bound = left_rows * right_rows;
7994    if merged_rows > max_bound {
7995        return Err(format!(
7996            "merge row count exceeds left*right cross-product: join={join_type:?} \
7997             merged={merged_rows} left={left_rows} right={right_rows}"
7998        ));
7999    }
8000
8001    match join_type {
8002        JoinType::Inner if merged_rows > left_rows.min(right_rows) => {
8003            return Err(format!(
8004                "inner merge with unique keys exceeded min input rows: merged={merged_rows} \
8005                 left={left_rows} right={right_rows}"
8006            ));
8007        }
8008        JoinType::Left if merged_rows < left_rows => {
8009            return Err(format!(
8010                "left merge dropped left rows: merged={merged_rows} left={left_rows}"
8011            ));
8012        }
8013        JoinType::Right if merged_rows < right_rows => {
8014            return Err(format!(
8015                "right merge dropped right rows: merged={merged_rows} right={right_rows}"
8016            ));
8017        }
8018        JoinType::Outer if merged_rows < left_rows.max(right_rows) => {
8019            return Err(format!(
8020                "outer merge smaller than max input rows: merged={merged_rows} \
8021                 left={left_rows} right={right_rows}"
8022            ));
8023        }
8024        _ => {}
8025    }
8026
8027    if merged.columns.len() != 3 {
8028        return Err(format!(
8029            "merge column count mismatch: expected 3 got {}",
8030            merged.columns.len()
8031        ));
8032    }
8033    Ok(())
8034}
8035
8036/// Structure-aware fuzz entrypoint for `DataFrame::pivot_table(...)`.
8037///
8038/// The first byte selects raw-vs-synth projection mode, the second picks a
8039/// supported aggregation function, and the remaining bytes are projected into
8040/// a tiny frame with `row`, `col`, and `val` columns. Successful pivots must
8041/// preserve first-seen row/column ordering and only surface missing cells when
8042/// the source group lacked usable numeric values (or `std`/`var` had fewer
8043/// than two numeric observations).
8044pub fn fuzz_pivot_table_bytes(input: &[u8]) -> Result<(), String> {
8045    let Some((&mode, rest)) = input.split_first() else {
8046        return Ok(());
8047    };
8048    let Some((&agg_tag, payload)) = rest.split_first() else {
8049        return Ok(());
8050    };
8051
8052    let aggfunc = FUZZ_PIVOT_AGGFUNCS[usize::from(agg_tag) % FUZZ_PIVOT_AGGFUNCS.len()];
8053    let frame = fuzz_pivot_table_frame_from_bytes(payload, mode % 2 == 1)
8054        .map_err(|err| format!("pivot fuzz frame projection failed: {err:?}"))?;
8055    let pivot = frame
8056        .pivot_table("val", "row", "col", aggfunc)
8057        .map_err(|err| format!("pivot_table failed for aggfunc={aggfunc}: {err}"))?;
8058
8059    let row_series = frame.get_column("row");
8060    let col_series = frame.get_column("col");
8061    let val_series = frame.get_column("val");
8062
8063    let mut expected_row_pairs: Vec<(String, Scalar)> = Vec::new();
8064    let mut expected_col_pairs: Vec<(String, Scalar)> = Vec::new();
8065    let mut seen_rows = BTreeSet::new();
8066    let mut seen_cols = BTreeSet::new();
8067    let mut numeric_counts = BTreeMap::<(String, String), usize>::new();
8068
8069    for value in row_series.values() {
8070        let Some(row_key) = fuzz_pivot_key_name(value) else {
8071            continue;
8072        };
8073        if seen_rows.insert(row_key.clone()) {
8074            expected_row_pairs.push((row_key, value.clone()));
8075        }
8076    }
8077    for value in col_series.values() {
8078        let Some(col_key) = fuzz_pivot_key_name(value) else {
8079            continue;
8080        };
8081        if seen_cols.insert(col_key.clone()) {
8082            expected_col_pairs.push((col_key, value.clone()));
8083        }
8084    }
8085    // pandas pivot_table sorts both axes (sort=True default); FP matches as
8086    // of br-frankenpandas-s3x7k. Sort the independently collected keys with
8087    // the SAME typed comparator production uses (ascending, nulls last,
8088    // stable first-seen ties) instead of pinning the old first-seen order.
8089    expected_row_pairs.sort_by(|a, b| fp_frame::pivot_axis_scalar_cmp(&a.1, &b.1));
8090    expected_col_pairs.sort_by(|a, b| fp_frame::pivot_axis_scalar_cmp(&a.1, &b.1));
8091    let expected_rows: Vec<String> = expected_row_pairs.into_iter().map(|(k, _)| k).collect();
8092    let expected_cols: Vec<String> = expected_col_pairs.into_iter().map(|(k, _)| k).collect();
8093    for idx in 0..frame.index().len() {
8094        let Some(row_key) = fuzz_pivot_key_name(&row_series.values()[idx]) else {
8095            continue;
8096        };
8097        let Some(col_key) = fuzz_pivot_key_name(&col_series.values()[idx]) else {
8098            continue;
8099        };
8100        if val_series.values()[idx].to_f64().is_ok() && !val_series.values()[idx].is_missing() {
8101            *numeric_counts.entry((row_key, col_key)).or_insert(0) += 1;
8102        }
8103    }
8104
8105    let actual_rows = pivot
8106        .index()
8107        .labels()
8108        .iter()
8109        .map(ToString::to_string)
8110        .collect::<Vec<_>>();
8111    let actual_cols = pivot
8112        .column_names()
8113        .into_iter()
8114        .cloned()
8115        .collect::<Vec<_>>();
8116
8117    if pivot.shape() != (expected_rows.len(), expected_cols.len()) {
8118        return Err(format!(
8119            "pivot_table shape drifted for aggfunc={aggfunc}: actual={:?} expected=({}, {})",
8120            pivot.shape(),
8121            expected_rows.len(),
8122            expected_cols.len()
8123        ));
8124    }
8125    if actual_rows != expected_rows {
8126        return Err(format!(
8127            "pivot_table row order drifted for aggfunc={aggfunc}: actual={actual_rows:?} expected={expected_rows:?}"
8128        ));
8129    }
8130    if actual_cols != expected_cols {
8131        return Err(format!(
8132            "pivot_table column order drifted for aggfunc={aggfunc}: actual={actual_cols:?} expected={expected_cols:?}"
8133        ));
8134    }
8135
8136    for col_name in &actual_cols {
8137        let col = pivot.get_column(col_name);
8138        for (row_idx, value) in col.values().iter().enumerate() {
8139            let numeric_count = *numeric_counts
8140                .get(&(actual_rows[row_idx].clone(), col_name.clone()))
8141                .unwrap_or(&0);
8142            let allow_missing =
8143                numeric_count == 0 || (matches!(aggfunc, "std" | "var") && numeric_count < 2);
8144            if fuzz_pivot_cell_is_missing(value) {
8145                if !allow_missing {
8146                    return Err(format!(
8147                        "pivot_table emitted missing cell for aggfunc={aggfunc} at ({}, {}) despite {numeric_count} numeric source values",
8148                        actual_rows[row_idx], col_name
8149                    ));
8150                }
8151            } else if numeric_count == 0 {
8152                return Err(format!(
8153                    "pivot_table emitted value for aggfunc={aggfunc} at ({}, {}) without numeric source values",
8154                    actual_rows[row_idx], col_name
8155                ));
8156            }
8157        }
8158    }
8159
8160    Ok(())
8161}
8162
8163/// Structure-aware fuzz entrypoint for the `fp-io` Feather reader.
8164///
8165/// Inputs use a dual-mode envelope. Raw mode (`tag % 2 == 0`) feeds the
8166/// remaining bytes directly into `read_feather_bytes()`, where parser errors
8167/// are acceptable but successful parses must round-trip. Synth mode projects
8168/// bytes into a tiny typed `DataFrame`, serializes it with
8169/// `write_feather_bytes()`, then checks the reader against that valid payload.
8170pub fn fuzz_feather_io_bytes(input: &[u8]) -> Result<(), FpIoError> {
8171    let Some((&mode, payload)) = input.split_first() else {
8172        return Ok(());
8173    };
8174
8175    if mode % 2 == 0 {
8176        let frame = read_feather_bytes(payload)?;
8177        assert_feather_roundtrip(&frame)
8178    } else {
8179        let frame = fuzz_feather_frame_from_bytes(payload)?;
8180        assert_feather_roundtrip(&frame)
8181    }
8182}
8183
8184/// Structure-aware fuzz entrypoint for the `fp-io` Arrow IPC stream reader.
8185///
8186/// Inputs use the same dual-mode envelope as `fuzz_feather_io_bytes()`. Raw
8187/// mode (`tag % 2 == 0`) feeds the remaining bytes directly into
8188/// `read_ipc_stream_bytes()`, where parser errors are acceptable but
8189/// successful parses must round-trip. Synth mode projects bytes into a tiny
8190/// typed `DataFrame`, serializes it with `write_ipc_stream_bytes()`, then
8191/// checks the reader against that valid payload.
8192pub fn fuzz_ipc_stream_io_bytes(input: &[u8]) -> Result<(), FpIoError> {
8193    let Some((&mode, payload)) = input.split_first() else {
8194        return Ok(());
8195    };
8196
8197    if mode % 2 == 0 {
8198        let frame = read_ipc_stream_bytes(payload)?;
8199        assert_ipc_stream_roundtrip(&frame)
8200    } else {
8201        let frame = fuzz_feather_frame_from_bytes(payload)?;
8202        assert_ipc_stream_roundtrip(&frame)
8203    }
8204}
8205
8206fn fuzz_semantic_eq_scalar(dtype_tag: u8, value_tag: u8) -> Scalar {
8207    let dtype = fuzz_dtype_from_byte(dtype_tag);
8208    match value_tag % 8 {
8209        0 => Scalar::Null(NullKind::Null),
8210        1 => Scalar::Null(NullKind::NaN),
8211        2 => Scalar::Null(NullKind::NaT),
8212        3 if dtype == DType::Float64 => Scalar::Float64(f64::NAN),
8213        _ => fuzz_feather_scalar_for_dtype(&dtype, &[value_tag, value_tag.rotate_left(1)]),
8214    }
8215}
8216
8217/// Structure-aware fuzz entrypoint for `Scalar::semantic_eq(...)` invariants.
8218///
8219/// Four bytes select `(dtype_a, dtype_b, value_a, value_b)`, which are
8220/// projected into two `Scalar`s. Semantic equality must remain symmetric and
8221/// reflexive, all `Null(_)` pairs must remain equivalent, and `Float64(NaN)`
8222/// must stay bridged to missing null markers.
8223pub fn fuzz_semantic_eq_bytes(input: &[u8]) -> Result<(), String> {
8224    let [dtype_a, dtype_b, value_a, value_b, ..] = input else {
8225        return Ok(());
8226    };
8227
8228    let left = fuzz_semantic_eq_scalar(*dtype_a, *value_a);
8229    let right = fuzz_semantic_eq_scalar(*dtype_b, *value_b);
8230
8231    let forward = left.semantic_eq(&right);
8232    let reverse = right.semantic_eq(&left);
8233    if forward != reverse {
8234        return Err(format!(
8235            "semantic_eq symmetry mismatch: left={left:?} right={right:?} forward={forward} reverse={reverse}"
8236        ));
8237    }
8238
8239    if !left.semantic_eq(&left) {
8240        return Err(format!("semantic_eq lost reflexivity for left={left:?}"));
8241    }
8242    if !right.semantic_eq(&right) {
8243        return Err(format!("semantic_eq lost reflexivity for right={right:?}"));
8244    }
8245
8246    if matches!(left, Scalar::Null(_)) && matches!(right, Scalar::Null(_)) && !forward {
8247        return Err(format!(
8248            "semantic_eq no longer bridges null kinds: left={left:?} right={right:?}"
8249        ));
8250    }
8251
8252    let null_variants = [
8253        Scalar::Null(NullKind::Null),
8254        Scalar::Null(NullKind::NaN),
8255        Scalar::Null(NullKind::NaT),
8256    ];
8257    for lhs in &null_variants {
8258        for rhs in &null_variants {
8259            if !lhs.semantic_eq(rhs) || !rhs.semantic_eq(lhs) {
8260                return Err(format!(
8261                    "semantic_eq null bridge mismatch: left={lhs:?} right={rhs:?}"
8262                ));
8263            }
8264        }
8265    }
8266
8267    let nan = Scalar::Float64(f64::NAN);
8268    for missing in [
8269        Scalar::Null(NullKind::NaN),
8270        Scalar::Null(NullKind::Null),
8271        Scalar::Null(NullKind::NaT),
8272    ] {
8273        if !nan.semantic_eq(&missing) || !missing.semantic_eq(&nan) {
8274            return Err(format!(
8275                "semantic_eq NaN bridge mismatch: nan={nan:?} missing={missing:?}"
8276            ));
8277        }
8278    }
8279
8280    Ok(())
8281}
8282
8283/// Structure-aware fuzz entrypoint for the `fp-types` common-dtype lattice.
8284///
8285/// Two input bytes are projected onto `DType` variants. Incompatible pairs are
8286/// acceptable, but compatibility must remain symmetric and successful
8287/// promotions must remain idempotent.
8288pub fn fuzz_common_dtype_bytes(input: &[u8]) -> Result<(), String> {
8289    let [left_tag, right_tag, ..] = input else {
8290        return Ok(());
8291    };
8292
8293    let left = fuzz_dtype_from_byte(*left_tag);
8294    let right = fuzz_dtype_from_byte(*right_tag);
8295
8296    let forward = common_dtype(left.clone(), right.clone());
8297    let reverse = common_dtype(right.clone(), left.clone());
8298
8299    match (forward, reverse) {
8300        (Ok(common), Ok(reverse_common)) => {
8301            if common != reverse_common {
8302                return Err(format!(
8303                    "common_dtype symmetry mismatch: left={left:?} right={right:?} \
8304                     forward={common:?} reverse={reverse_common:?}"
8305                ));
8306            }
8307
8308            let left_idempotent = common_dtype(common.clone(), left.clone()).map_err(|err| {
8309                format!(
8310                    "common_dtype lost left compatibility: left={left:?} right={right:?} \
8311                     common={common:?} err={err}"
8312                )
8313            })?;
8314            if left_idempotent != common {
8315                return Err(format!(
8316                    "common_dtype left idempotence mismatch: left={left:?} right={right:?} \
8317                     common={common:?} got={left_idempotent:?}"
8318                ));
8319            }
8320
8321            let right_idempotent = common_dtype(common.clone(), right.clone()).map_err(|err| {
8322                format!(
8323                    "common_dtype lost right compatibility: left={left:?} right={right:?} \
8324                     common={common:?} err={err}"
8325                )
8326            })?;
8327            if right_idempotent != common {
8328                return Err(format!(
8329                    "common_dtype right idempotence mismatch: left={left:?} right={right:?} \
8330                     common={common:?} got={right_idempotent:?}"
8331                ));
8332            }
8333        }
8334        (Err(_), Err(_)) => {}
8335        (left_result, right_result) => {
8336            return Err(format!(
8337                "common_dtype compatibility mismatch: left={left:?} right={right:?} \
8338                 forward={left_result:?} reverse={right_result:?}"
8339            ));
8340        }
8341    }
8342
8343    Ok(())
8344}
8345
8346/// Structure-aware fuzz entrypoint for `fp-types` scalar casting semantics.
8347///
8348/// The first byte selects the target `DType`; remaining bytes project into a
8349/// `Scalar`. Any cast error is acceptable, but owned/ref cast paths must agree,
8350/// identity and missing casts must preserve their contracts, and successful
8351/// casts must be idempotent for the chosen target dtype.
8352pub fn fuzz_scalar_cast_bytes(input: &[u8]) -> Result<(), String> {
8353    let Some((&target_tag, scalar_bytes)) = input.split_first() else {
8354        return Ok(());
8355    };
8356
8357    let target = fuzz_dtype_from_byte(target_tag);
8358    let value = fuzz_scalar_from_bytes(scalar_bytes);
8359    let owned = cast_scalar_owned(value.clone(), target.clone());
8360    let borrowed = cast_scalar(&value, target.clone());
8361
8362    if format!("{owned:?}") != format!("{borrowed:?}") {
8363        return Err(format!(
8364            "owned/ref scalar cast mismatch: value={value:?} target={target:?} \
8365             owned={owned:?} borrowed={borrowed:?}"
8366        ));
8367    }
8368
8369    match owned {
8370        Ok(result) => {
8371            let scalars_equal = |a: &Scalar, b: &Scalar| -> bool {
8372                match (a, b) {
8373                    (Scalar::Float64(fa), Scalar::Float64(fb)) => {
8374                        (fa.is_nan() && fb.is_nan()) || fa.to_bits() == fb.to_bits() || fa == fb
8375                    }
8376                    _ => a == b,
8377                }
8378            };
8379
8380            if value.dtype() == target && !scalars_equal(&result, &value) {
8381                return Err(format!(
8382                    "identity cast drifted: value={value:?} target={target:?} result={result:?}"
8383                ));
8384            }
8385
8386            if value.is_missing() {
8387                if value.dtype() == target {
8388                    // Identity cast of missing value handled above.
8389                } else if target == DType::Utf8 {
8390                    if !matches!(result, Scalar::Utf8(_)) {
8391                        return Err(format!(
8392                            "missing cast to Utf8 should produce Utf8 string: value={value:?} result={result:?}"
8393                        ));
8394                    }
8395                } else {
8396                    let expected = Scalar::missing_for_dtype(target.clone());
8397                    if !scalars_equal(&result, &expected) && !result.semantic_eq(&expected) {
8398                        let is_known_non_missing_sentinel = match (&value, &target) {
8399                            (Scalar::Float64(v), DType::Bool) if v.is_nan() => {
8400                                result == Scalar::Bool(true)
8401                            }
8402                            (Scalar::Datetime64(_) | Scalar::Timedelta64(_), DType::Bool) => {
8403                                result == Scalar::Bool(true)
8404                            }
8405                            (Scalar::Datetime64(_) | Scalar::Timedelta64(_), DType::Int64) => {
8406                                result == Scalar::Int64(i64::MIN)
8407                            }
8408                            _ => false,
8409                        };
8410                        if !is_known_non_missing_sentinel {
8411                            return Err(format!(
8412                                "missing cast drifted: value={value:?} target={target:?} \
8413                                 result={result:?} expected={expected:?}"
8414                            ));
8415                        }
8416                    }
8417                }
8418            }
8419
8420            if target == DType::Null && !matches!(result, Scalar::Null(_)) {
8421                return Err(format!(
8422                    "cast-to-null contract drifted: value={value:?} result={result:?}"
8423                ));
8424            }
8425
8426            if !value.is_missing() && target != DType::Null && result.is_missing() {
8427                return Err(format!(
8428                    "successful non-null cast produced missing sentinel: \
8429                     value={value:?} target={target:?} result={result:?}"
8430                ));
8431            }
8432
8433            let owned_idempotent =
8434                cast_scalar_owned(result.clone(), target.clone()).map_err(|err| {
8435                    format!(
8436                        "successful cast lost idempotence on owned path: \
8437                     value={value:?} target={target:?} result={result:?} err={err:?}"
8438                    )
8439                })?;
8440            if !scalars_equal(&owned_idempotent, &result) {
8441                return Err(format!(
8442                    "owned cast idempotence mismatch: value={value:?} target={target:?} \
8443                     result={result:?} rerun={owned_idempotent:?}"
8444                ));
8445            }
8446
8447            let borrowed_idempotent = cast_scalar(&result, target.clone()).map_err(|err| {
8448                format!(
8449                    "successful cast lost idempotence on borrowed path: \
8450                     value={value:?} target={target:?} result={result:?} err={err:?}"
8451                )
8452            })?;
8453            if !scalars_equal(&borrowed_idempotent, &result) {
8454                return Err(format!(
8455                    "borrowed cast idempotence mismatch: value={value:?} target={target:?} \
8456                     result={result:?} rerun={borrowed_idempotent:?}"
8457                ));
8458            }
8459        }
8460        Err(err) => {
8461            if value.dtype() == target || value.is_missing() || target == DType::Null {
8462                return Err(format!(
8463                    "cast unexpectedly failed for guaranteed-success contract: \
8464                     value={value:?} target={target:?} err={err:?}"
8465                ));
8466            }
8467        }
8468    }
8469
8470    Ok(())
8471}
8472
8473fn fuzz_series_add_scalar_from_bytes(bytes: &[u8]) -> Scalar {
8474    let tag = bytes.first().copied().unwrap_or_default();
8475    let payload = bytes.get(1).copied().unwrap_or_default();
8476
8477    match tag % 6 {
8478        0 => Scalar::Null(NullKind::Null),
8479        1 => Scalar::Null(NullKind::NaN),
8480        2 => Scalar::Int64(i64::from(payload % 11) - 5),
8481        3 => Scalar::Float64(match payload % 8 {
8482            0 => 0.0,
8483            1 => 1.0,
8484            2 => -1.0,
8485            3 => 2.5,
8486            4 => f64::INFINITY,
8487            5 => f64::NEG_INFINITY,
8488            6 => f64::NAN,
8489            _ => -0.0,
8490        }),
8491        4 => Scalar::Int64(i64::from(payload % 5)),
8492        _ => Scalar::Float64(f64::from(i8::from_ne_bytes([payload])) / 8.0),
8493    }
8494}
8495
8496fn fuzz_column_scalars_from_bytes(bytes: &[u8]) -> Vec<Scalar> {
8497    bytes
8498        .chunks(2)
8499        .take(16)
8500        .map(fuzz_series_add_scalar_from_bytes)
8501        .collect()
8502}
8503
8504fn fuzz_arithmetic_op_from_byte(byte: u8) -> ArithmeticOp {
8505    match byte % 7 {
8506        0 => ArithmeticOp::Add,
8507        1 => ArithmeticOp::Sub,
8508        2 => ArithmeticOp::Mul,
8509        3 => ArithmeticOp::Div,
8510        4 => ArithmeticOp::Mod,
8511        5 => ArithmeticOp::Pow,
8512        _ => ArithmeticOp::FloorDiv,
8513    }
8514}
8515
8516fn fuzz_expected_column_arith_dtype(
8517    left: &Column,
8518    right: &Column,
8519    op: ArithmeticOp,
8520) -> Result<DType, String> {
8521    let mut out_dtype = common_dtype(left.dtype(), right.dtype())
8522        .map_err(|err| format!("common dtype failed: {err:?}"))?;
8523
8524    if matches!(out_dtype, DType::Bool) {
8525        out_dtype = DType::Int64;
8526    }
8527    if matches!(op, ArithmeticOp::Div) {
8528        out_dtype = DType::Float64;
8529    }
8530    // Per br-frankenpandas-3w0xn: Int64 ** Int64 stays Int64 (numpy/pandas:
8531    // int**int -> int64, with negative integer exponents raising in the kernel
8532    // before this oracle runs). Any float operand promotes Pow to Float64.
8533    //
8534    // br-frankenpandas-6dv9d: a Null-dtype operand (an all-missing column) also
8535    // promotes. `common_dtype(Int64, Null)` is Int64, but every power with a
8536    // missing base or exponent is itself missing, and pandas has no all-missing
8537    // int64 column: its analogue is float64 NaN, and measured on 2.2.3
8538    // `Series([2,3,4]) ** Series([nan,nan,nan])` is float64. The fuzzer found
8539    // exactly this input (CI run 33488811029, seed `ci_crash_20260901_b.bin`)
8540    // and this rule keyed on the PROMOTED dtype, so it demanded Int64 where
8541    // both pandas and fp-columnar answer Float64.
8542    let null_operand = matches!(left.dtype(), DType::Null) || matches!(right.dtype(), DType::Null);
8543    if matches!(op, ArithmeticOp::Pow) && (!matches!(out_dtype, DType::Int64) || null_operand) {
8544        out_dtype = DType::Float64;
8545    }
8546    if matches!(op, ArithmeticOp::Mod | ArithmeticOp::FloorDiv) && matches!(out_dtype, DType::Int64)
8547    {
8548        let has_zero_divisor = right
8549            .values()
8550            .iter()
8551            .filter(|value| !value.is_missing())
8552            .any(|value| matches!(cast_scalar(value, DType::Int64), Ok(Scalar::Int64(0))));
8553        if has_zero_divisor {
8554            out_dtype = DType::Float64;
8555        }
8556    }
8557
8558    Ok(out_dtype)
8559}
8560
8561/// numpy's power identities over a missing float operand, the one place a
8562/// missing operand gives a present value: numpy reads the missing float as
8563/// NaN, and NaN ** 0 / 1 ** NaN are 1 (live pandas 2.2.3:
8564/// `Series([nan, 2.0]) ** 0` is `[1.0, 1.0]`, `1 ** Series([nan])` `[1.0]`;
8565/// br-frankenpandas-oie6x). Only a numpy Float64 result, only the slot whose
8566/// other operand is a present 0 exponent / 1 base; None anywhere else, where
8567/// missing still propagates.
8568fn fuzz_numpy_pow_identity(
8569    left: &Scalar,
8570    right: &Scalar,
8571    op: ArithmeticOp,
8572    out_dtype: &DType,
8573) -> Option<Scalar> {
8574    if !matches!(op, ArithmeticOp::Pow)
8575        || !matches!(out_dtype, DType::Float64)
8576        || !(left.is_missing() || right.is_missing())
8577    {
8578        return None;
8579    }
8580    let present_equal = |value: &Scalar, wanted: f64| {
8581        !value.is_missing() && value.to_f64().is_ok_and(|value| value == wanted)
8582    };
8583    (present_equal(right, 0.0) || present_equal(left, 1.0)).then_some(Scalar::Float64(1.0))
8584}
8585
8586fn fuzz_column_arith_oracle_scalar(
8587    left: &Scalar,
8588    right: &Scalar,
8589    op: ArithmeticOp,
8590    out_dtype: DType,
8591    preserves_nan_missing: bool,
8592) -> Result<Scalar, String> {
8593    if let Some(one) = fuzz_numpy_pow_identity(left, right, op, &out_dtype) {
8594        return Ok(one);
8595    }
8596    if left.is_missing() || right.is_missing() {
8597        return Ok(
8598            if preserves_nan_missing && (left.is_nan() || right.is_nan()) {
8599                Scalar::Null(NullKind::NaN)
8600            } else {
8601                Scalar::missing_for_dtype(out_dtype)
8602            },
8603        );
8604    }
8605
8606    if matches!(out_dtype, DType::Int64) {
8607        let lhs = match cast_scalar(left, DType::Int64)
8608            .map_err(|err| format!("left int cast failed: {err:?}"))?
8609        {
8610            Scalar::Int64(value) => value,
8611            other => {
8612                return Err(format!(
8613                    "left int cast produced non-Int64 scalar: {other:?}"
8614                ));
8615            }
8616        };
8617        let rhs = match cast_scalar(right, DType::Int64)
8618            .map_err(|err| format!("right int cast failed: {err:?}"))?
8619        {
8620            Scalar::Int64(value) => value,
8621            other => {
8622                return Err(format!(
8623                    "right int cast produced non-Int64 scalar: {other:?}"
8624                ));
8625            }
8626        };
8627
8628        let result = match op {
8629            ArithmeticOp::Add => lhs.wrapping_add(rhs),
8630            ArithmeticOp::Sub => lhs.wrapping_sub(rhs),
8631            ArithmeticOp::Mul => lhs.wrapping_mul(rhs),
8632            ArithmeticOp::Mod => fuzz_python_mod_i64(lhs, rhs),
8633            ArithmeticOp::FloorDiv => fuzz_python_floor_div_i64(lhs, rhs),
8634            // Per br-frankenpandas-3w0xn: Int64 ** Int64 wraps like numpy for a
8635            // non-negative exponent. A negative exponent raises in Column::pow,
8636            // so the harness errors before reaching this oracle (rhs >= 0 here).
8637            ArithmeticOp::Pow => lhs.wrapping_pow(u32::try_from(rhs).unwrap_or(u32::MAX)),
8638            ArithmeticOp::Div => {
8639                return Err(format!(
8640                    "int oracle received unsupported op {:?} for dtype {:?}",
8641                    op, out_dtype
8642                ));
8643            }
8644        };
8645        return Ok(Scalar::Int64(result));
8646    }
8647
8648    let lhs = left
8649        .to_f64()
8650        .map_err(|err| format!("left float cast failed: {err:?}"))?;
8651    let rhs = right
8652        .to_f64()
8653        .map_err(|err| format!("right float cast failed: {err:?}"))?;
8654    let result = match op {
8655        ArithmeticOp::Add => lhs + rhs,
8656        ArithmeticOp::Sub => lhs - rhs,
8657        ArithmeticOp::Mul => lhs * rhs,
8658        ArithmeticOp::Div => lhs / rhs,
8659        ArithmeticOp::Mod => fuzz_python_mod_f64(lhs, rhs),
8660        ArithmeticOp::Pow => lhs.powf(rhs),
8661        ArithmeticOp::FloorDiv => fuzz_python_floor_div_f64(lhs, rhs),
8662    };
8663    Ok(Scalar::Float64(result))
8664}
8665
8666fn fuzz_python_floor_div_i64(lhs: i64, rhs: i64) -> i64 {
8667    debug_assert_ne!(rhs, 0);
8668    if lhs == i64::MIN && rhs == -1 {
8669        return i64::MIN;
8670    }
8671
8672    let quotient = lhs / rhs;
8673    let remainder = lhs % rhs;
8674    if remainder != 0 && ((remainder > 0) != (rhs > 0)) {
8675        quotient - 1
8676    } else {
8677        quotient
8678    }
8679}
8680
8681fn fuzz_python_mod_i64(lhs: i64, rhs: i64) -> i64 {
8682    debug_assert_ne!(rhs, 0);
8683    if lhs == i64::MIN && rhs == -1 {
8684        return 0;
8685    }
8686
8687    let quotient = i128::from(fuzz_python_floor_div_i64(lhs, rhs));
8688    let remainder = i128::from(lhs) - quotient * i128::from(rhs);
8689    let Ok(value) = i64::try_from(remainder) else {
8690        return 0;
8691    };
8692    value
8693}
8694
8695/// numpy's `npy_divmod`, which is what pandas' float64 `//` and `%` dispatch to.
8696///
8697/// ⚠️ THIS WAS A CHARACTER-FOR-CHARACTER COPY OF THE fp-columnar KERNEL, and that
8698/// is precisely why it was useless. Both sides carried the same wrong formula
8699/// (`lhs - floor(lhs / rhs) * rhs`), so the differential fuzzer compared FP
8700/// against FP and agreed on all 16 special-value cells where both differed from
8701/// pandas -- signed zeros, quotient overflow at subnormal divisors, and quotient
8702/// underflow. A fuzz oracle that mirrors the implementation cannot fail.
8703///
8704/// Rewriting it to the correct algorithm makes it CORRECT but does not make it
8705/// INDEPENDENT: it is still a shadow reimplementation, and the real fix is for
8706/// this path to call pandas. Until then, the bit-exact pandas-measured table in
8707/// fp-columnar's `floordiv_mod_f64_pandas_special_value_lock` is the binding
8708/// evidence for these two ops, not this function.
8709fn fuzz_npy_divmod_f64(lhs: f64, rhs: f64) -> (f64, f64) {
8710    let mut modulus = lhs % rhs; // fmod: exact, truncated toward zero
8711
8712    if rhs == 0.0 {
8713        return (lhs / rhs, modulus);
8714    }
8715
8716    let mut quotient = (lhs - modulus) / rhs;
8717    if modulus != 0.0 {
8718        if (rhs < 0.0) != (modulus < 0.0) {
8719            modulus += rhs;
8720            quotient -= 1.0;
8721        }
8722    } else {
8723        modulus = 0.0_f64.copysign(rhs);
8724    }
8725
8726    let floordiv = if quotient != 0.0 {
8727        let floored = quotient.floor();
8728        if quotient - floored > 0.5 {
8729            floored + 1.0
8730        } else {
8731            floored
8732        }
8733    } else {
8734        0.0_f64.copysign(lhs / rhs)
8735    };
8736
8737    (floordiv, modulus)
8738}
8739
8740fn fuzz_python_mod_f64(lhs: f64, rhs: f64) -> f64 {
8741    fuzz_npy_divmod_f64(lhs, rhs).1
8742}
8743
8744fn fuzz_python_floor_div_f64(lhs: f64, rhs: f64) -> f64 {
8745    fuzz_npy_divmod_f64(lhs, rhs).0
8746}
8747
8748fn scalars_equivalent(actual: &Scalar, expected: &Scalar, preserves_nan_missing: bool) -> bool {
8749    if (actual.is_nan() && expected.is_nan())
8750        || (!preserves_nan_missing && actual.is_missing() && expected.is_missing())
8751    {
8752        true
8753    } else {
8754        actual == expected
8755    }
8756}
8757
8758fn column_arith_preserves_nan_missing(left: &Column, right: &Column, out_dtype: &DType) -> bool {
8759    !(matches!(out_dtype, DType::Int64)
8760        && matches!(left.dtype(), DType::Int64)
8761        && matches!(right.dtype(), DType::Int64))
8762}
8763
8764fn fuzz_series_from_bytes(name: &str, bytes: &[u8]) -> Result<Series, FrameError> {
8765    let mut labels = Vec::new();
8766    let mut values = Vec::new();
8767
8768    for chunk in bytes.chunks(3).take(12) {
8769        let Some((&label_tag, scalar_bytes)) = chunk.split_first() else {
8770            continue;
8771        };
8772        labels.push(fuzz_index_label_from_byte(label_tag));
8773        values.push(fuzz_series_add_scalar_from_bytes(scalar_bytes));
8774    }
8775
8776    Series::from_values(name, labels, values)
8777}
8778
8779fn normalized_series_rows(series: &Series) -> Vec<String> {
8780    let mut rows: Vec<_> = series
8781        .index()
8782        .labels()
8783        .iter()
8784        .zip(series.values().iter())
8785        .map(|(label, value)| format!("{label:?}=>{value:?}"))
8786        .collect();
8787    rows.sort_unstable();
8788    rows
8789}
8790
8791fn normalized_join_rows(joined: &JoinedSeries) -> Vec<String> {
8792    let mut rows = joined
8793        .index
8794        .labels()
8795        .iter()
8796        .zip(joined.left_values.values().iter())
8797        .zip(joined.right_values.values().iter())
8798        .map(|((label, left_value), right_value)| {
8799            format!("{label:?}|{left_value:?}|{right_value:?}")
8800        })
8801        .collect::<Vec<_>>();
8802    rows.sort_unstable();
8803    rows
8804}
8805
8806fn normalized_join_rows_with_swapped_sides(joined: &JoinedSeries) -> Vec<String> {
8807    let mut rows = joined
8808        .index
8809        .labels()
8810        .iter()
8811        .zip(joined.left_values.values().iter())
8812        .zip(joined.right_values.values().iter())
8813        .map(|((label, left_value), right_value)| {
8814            format!("{label:?}|{right_value:?}|{left_value:?}")
8815        })
8816        .collect::<Vec<_>>();
8817    rows.sort_unstable();
8818    rows
8819}
8820
8821fn fuzz_join_type_from_byte(byte: u8) -> JoinType {
8822    match byte % 5 {
8823        0 => JoinType::Inner,
8824        1 => JoinType::Left,
8825        2 => JoinType::Right,
8826        3 => JoinType::Outer,
8827        _ => JoinType::Cross,
8828    }
8829}
8830
8831fn swapped_join_type(join_type: JoinType) -> JoinType {
8832    match join_type {
8833        JoinType::Inner => JoinType::Inner,
8834        JoinType::Left => JoinType::Right,
8835        JoinType::Right => JoinType::Left,
8836        JoinType::Outer => JoinType::Outer,
8837        JoinType::Cross => JoinType::Cross,
8838    }
8839}
8840
8841/// Structure-aware fuzz entrypoint for `Column::binary_numeric()` invariants.
8842///
8843/// The first byte selects an `ArithmeticOp`; remaining bytes are split at `|`
8844/// (or midpoint) into left/right payloads. These are projected into bounded
8845/// numeric-or-missing `Column`s of matching length. The harness checks output
8846/// length parity, dtype promotion rules, exact per-row scalar oracle agreement,
8847/// missing/NaN propagation, and commutativity for `Add`/`Mul`.
8848pub fn fuzz_column_arith_bytes(input: &[u8]) -> Result<(), String> {
8849    let Some((&op_tag, payload)) = input.split_first() else {
8850        return Ok(());
8851    };
8852
8853    let op = fuzz_arithmetic_op_from_byte(op_tag);
8854    let (left_bytes, right_bytes) =
8855        if let Some(split_at) = payload.iter().position(|byte| *byte == b'|') {
8856            (&payload[..split_at], &payload[split_at + 1..])
8857        } else {
8858            payload.split_at(payload.len() / 2)
8859        };
8860
8861    let mut left_values = fuzz_column_scalars_from_bytes(left_bytes);
8862    let mut right_values = fuzz_column_scalars_from_bytes(right_bytes);
8863    let shared_len = left_values.len().min(right_values.len());
8864    left_values.truncate(shared_len);
8865    right_values.truncate(shared_len);
8866
8867    let left = Column::from_values(left_values)
8868        .map_err(|err| format!("left column projection failed: {err:?}"))?;
8869    let right = Column::from_values(right_values)
8870        .map_err(|err| format!("right column projection failed: {err:?}"))?;
8871
8872    let result = match left.binary_numeric(&right, op) {
8873        Ok(result) => result,
8874        Err(fp_columnar::ColumnError::NegativeIntegerPower) => return Ok(()),
8875        Err(err) => return Err(format!("column arithmetic unexpectedly failed: {err:?}")),
8876    };
8877
8878    if result.len() != left.len() || result.len() != right.len() {
8879        return Err(format!(
8880            "column arithmetic length mismatch: op={op:?} left_len={} right_len={} result_len={}",
8881            left.len(),
8882            right.len(),
8883            result.len()
8884        ));
8885    }
8886
8887    let expected_dtype = fuzz_expected_column_arith_dtype(&left, &right, op)?;
8888    let preserves_nan_missing = column_arith_preserves_nan_missing(&left, &right, &expected_dtype);
8889    if result.dtype() != expected_dtype {
8890        return Err(format!(
8891            "column arithmetic dtype drifted: op={op:?} left_dtype={:?} right_dtype={:?} \
8892             actual_dtype={:?} expected_dtype={expected_dtype:?}",
8893            left.dtype(),
8894            right.dtype(),
8895            result.dtype()
8896        ));
8897    }
8898
8899    for (index, ((left_value, right_value), actual)) in left
8900        .values()
8901        .iter()
8902        .zip(right.values().iter())
8903        .zip(result.values().iter())
8904        .enumerate()
8905    {
8906        let expected = fuzz_column_arith_oracle_scalar(
8907            left_value,
8908            right_value,
8909            op,
8910            expected_dtype.clone(),
8911            preserves_nan_missing,
8912        )?;
8913        if !scalars_equivalent(actual, &expected, preserves_nan_missing) {
8914            return Err(format!(
8915                "column arithmetic oracle drifted at index={index}: op={op:?} \
8916                 left={left_value:?} right={right_value:?} actual={actual:?} expected={expected:?}"
8917            ));
8918        }
8919
8920        // Missing propagates everywhere but numpy's power identities.
8921        let pow_identity =
8922            fuzz_numpy_pow_identity(left_value, right_value, op, &expected_dtype).is_some();
8923        if (left_value.is_missing() || right_value.is_missing())
8924            && !actual.is_missing()
8925            && !pow_identity
8926        {
8927            return Err(format!(
8928                "missing propagation failed at index={index}: op={op:?} left={left_value:?} right={right_value:?} actual={actual:?}"
8929            ));
8930        }
8931        if preserves_nan_missing
8932            && (left_value.is_nan() || right_value.is_nan())
8933            && !actual.is_nan()
8934            && !pow_identity
8935        {
8936            return Err(format!(
8937                "NaN propagation failed at index={index}: op={op:?} left={left_value:?} right={right_value:?} actual={actual:?}"
8938            ));
8939        }
8940    }
8941
8942    if matches!(op, ArithmeticOp::Add | ArithmeticOp::Mul) {
8943        let reverse = right
8944            .binary_numeric(&left, op)
8945            .map_err(|err| format!("reverse column arithmetic unexpectedly failed: {err:?}"))?;
8946        if result.dtype() != reverse.dtype() {
8947            return Err(format!(
8948                "commutative op changed dtype under reversal: op={op:?} forward_dtype={:?} reverse_dtype={:?}",
8949                result.dtype(),
8950                reverse.dtype()
8951            ));
8952        }
8953        for (index, (forward, backward)) in result
8954            .values()
8955            .iter()
8956            .zip(reverse.values().iter())
8957            .enumerate()
8958        {
8959            if !scalars_equivalent(forward, backward, preserves_nan_missing) {
8960                return Err(format!(
8961                    "commutative op drifted under reversal at index={index}: op={op:?} forward={forward:?} reverse={backward:?}"
8962                ));
8963            }
8964        }
8965    }
8966
8967    Ok(())
8968}
8969
8970/// Structure-aware fuzz entrypoint for `Series::add()` alignment semantics.
8971///
8972/// Inputs are split at `|` (or midpoint when absent) and projected into small
8973/// numeric/missing `Series` pairs. Addition must succeed, preserve index/value
8974/// length parity, keep every input label in the union result, and remain
8975/// commutative after normalizing away output row order and synthetic names.
8976pub fn fuzz_series_add_bytes(input: &[u8]) -> Result<(), String> {
8977    let (left_bytes, right_bytes) =
8978        if let Some(split_at) = input.iter().position(|byte| *byte == b'|') {
8979            (&input[..split_at], &input[split_at + 1..])
8980        } else {
8981            input.split_at(input.len() / 2)
8982        };
8983
8984    let left = fuzz_series_from_bytes("left", left_bytes)
8985        .map_err(|err| format!("left series projection failed: {err:?}"))?;
8986    let right = fuzz_series_from_bytes("right", right_bytes)
8987        .map_err(|err| format!("right series projection failed: {err:?}"))?;
8988
8989    let forward = left
8990        .add(&right)
8991        .map_err(|err| format!("left.add(right) unexpectedly failed: {err:?}"))?;
8992    let reverse = right
8993        .add(&left)
8994        .map_err(|err| format!("right.add(left) unexpectedly failed: {err:?}"))?;
8995
8996    for (name, result) in [("forward", &forward), ("reverse", &reverse)] {
8997        if result.index().len() != result.values().len() {
8998            return Err(format!(
8999                "{name} index/value length mismatch: index_len={} value_len={}",
9000                result.index().len(),
9001                result.values().len()
9002            ));
9003        }
9004    }
9005
9006    let forward_labels = forward.index().labels();
9007    for label in left.index().labels() {
9008        if !forward_labels.contains(label) {
9009            return Err(format!("forward result dropped left label {label:?}"));
9010        }
9011    }
9012    for label in right.index().labels() {
9013        if !forward_labels.contains(label) {
9014            return Err(format!("forward result dropped right label {label:?}"));
9015        }
9016    }
9017
9018    let normalized_forward = normalized_series_rows(&forward);
9019    let normalized_reverse = normalized_series_rows(&reverse);
9020    if normalized_forward != normalized_reverse {
9021        return Err(format!(
9022            "series add lost commutativity after normalization: \
9023             left={left:?} right={right:?} forward_rows={normalized_forward:?} \
9024             reverse_rows={normalized_reverse:?}"
9025        ));
9026    }
9027
9028    Ok(())
9029}
9030
9031const FUZZ_ROLLING_AGGFUNCS: &[&str] = &[
9032    "sum", "mean", "min", "max", "std", "var", "count", "first", "last", "prod", "median",
9033];
9034
9035fn fuzz_rolling_series_from_bytes(bytes: &[u8]) -> Result<Series, FrameError> {
9036    let len = bytes
9037        .first()
9038        .map(|byte| 4 + (usize::from(*byte) % 29))
9039        .unwrap_or(4);
9040    let mut labels = Vec::with_capacity(len);
9041    let mut values = Vec::with_capacity(len);
9042
9043    for idx in 0..len {
9044        labels.push(
9045            i64::try_from(idx)
9046                .expect("bounded fuzz rolling index")
9047                .into(),
9048        );
9049        let tag = bytes.get(1 + idx * 2).copied().unwrap_or(idx as u8);
9050        let value = bytes
9051            .get(1 + idx * 2 + 1)
9052            .copied()
9053            .unwrap_or((idx as u8).wrapping_mul(17));
9054        if tag % 5 == 0 {
9055            values.push(Scalar::Null(NullKind::NaN));
9056        } else {
9057            values.push(Scalar::Float64((f64::from(value) - 96.0) / 8.0));
9058        }
9059    }
9060
9061    Series::from_values("x", labels, values)
9062}
9063
9064fn fuzz_rolling_window_from_byte(byte: u8, len: usize) -> usize {
9065    match byte % 6 {
9066        0 => 0,
9067        1 => 1,
9068        2 => len.max(1),
9069        3 => len.saturating_add(1),
9070        4 => usize::MAX,
9071        _ => 1 + (usize::from(byte) % len.max(1)),
9072    }
9073}
9074
9075fn fuzz_rolling_min_periods_from_byte(byte: u8, window: usize) -> Option<usize> {
9076    match byte % 6 {
9077        0 => None,
9078        1 => Some(0),
9079        2 => Some(1),
9080        3 => Some(window),
9081        4 => Some(window.saturating_add(1)),
9082        _ => Some(usize::from(byte) % window.saturating_add(2).max(1)),
9083    }
9084}
9085
9086fn fuzz_validate_rolling_result(
9087    aggfunc: &str,
9088    result: Result<Series, FrameError>,
9089    input_len: usize,
9090    window: usize,
9091    min_periods: Option<usize>,
9092) -> Result<(), String> {
9093    match result {
9094        Ok(series) => {
9095            if series.len() != input_len {
9096                return Err(format!(
9097                    "rolling {aggfunc} length mismatch: window={window} min_periods={min_periods:?} result_len={} input_len={input_len}",
9098                    series.len()
9099                ));
9100            }
9101            if window == 0 {
9102                return Err(format!(
9103                    "rolling {aggfunc} unexpectedly succeeded for window=0"
9104                ));
9105            }
9106
9107            if min_periods.is_none() {
9108                let required_missing = input_len.min(window.saturating_sub(1));
9109                for idx in 0..required_missing {
9110                    if !series.values()[idx].is_missing() {
9111                        return Err(format!(
9112                            "rolling {aggfunc} violated default-min_periods prefix null contract at index={idx}: window={window} value={:?}",
9113                            series.values()[idx]
9114                        ));
9115                    }
9116                }
9117            }
9118
9119            if let Some(min_periods) = min_periods
9120                && min_periods > window
9121                && series.values().iter().any(|value| !value.is_missing())
9122            {
9123                return Err(format!(
9124                    "rolling {aggfunc} produced non-missing output even though min_periods={min_periods} > window={window}: values={:?}",
9125                    series.values()
9126                ));
9127            }
9128
9129            Ok(())
9130        }
9131        Err(FrameError::CompatibilityRejected(_)) if window == 0 => Ok(()),
9132        // Per br-frankenpandas-d6x4v: pandas raises ValueError when
9133        // min_periods > window (locked in by br-7c962 as
9134        // CompatibilityRejected). The fuzz harness must tolerate this
9135        // rejection path the same way it tolerates window==0.
9136        Err(FrameError::CompatibilityRejected(_)) if min_periods.is_some_and(|m| m > window) => {
9137            Ok(())
9138        }
9139        Err(err) => Err(format!(
9140            "rolling {aggfunc} unexpectedly failed: window={window} min_periods={min_periods:?} err={err:?}"
9141        )),
9142    }
9143}
9144
9145/// Structure-aware fuzz entrypoint for `Series::rolling(window, min_periods)`.
9146///
9147/// The first two bytes select `window` and `min_periods`; remaining bytes are
9148/// projected into a small numeric-or-missing series. Successful runs must
9149/// preserve output length and the default-prefix-null contract. Invalid
9150/// `window=0` runs may reject via `FrameError::CompatibilityRejected` but must
9151/// never panic.
9152pub fn fuzz_rolling_window_bytes(input: &[u8]) -> Result<(), String> {
9153    let Some((&window_tag, rest)) = input.split_first() else {
9154        return Ok(());
9155    };
9156    let Some((&min_periods_tag, series_bytes)) = rest.split_first() else {
9157        return Ok(());
9158    };
9159
9160    let series = fuzz_rolling_series_from_bytes(series_bytes)
9161        .map_err(|err| format!("rolling fuzz series projection failed: {err:?}"))?;
9162    let window = fuzz_rolling_window_from_byte(window_tag, series.len());
9163    let min_periods = fuzz_rolling_min_periods_from_byte(min_periods_tag, window);
9164    let rolling = series.rolling(window, min_periods);
9165
9166    for aggfunc in FUZZ_ROLLING_AGGFUNCS {
9167        let result = match *aggfunc {
9168            "sum" => rolling.sum(),
9169            "mean" => rolling.mean(),
9170            "min" => rolling.min(),
9171            "max" => rolling.max(),
9172            "std" => rolling.std(),
9173            "var" => rolling.var(),
9174            "count" => rolling.count(),
9175            "first" => rolling.first(),
9176            "last" => rolling.last(),
9177            "prod" => rolling.prod(),
9178            "median" => rolling.median(),
9179            other => {
9180                return Err(format!("unknown rolling aggfunc in fuzz harness: {other}"));
9181            }
9182        };
9183        fuzz_validate_rolling_result(aggfunc, result, series.len(), window, min_periods)?;
9184    }
9185
9186    Ok(())
9187}
9188
9189/// Structure-aware fuzz entrypoint for `join_series()` invariants.
9190///
9191/// The first byte selects the join type; remaining bytes are split at `|`
9192/// (or midpoint) into left/right `Series` payloads. The harness projects these
9193fn columns_semantic_eq(left: &Column, right: &Column) -> bool {
9194    if left.dtype() != right.dtype()
9195        || left.len() != right.len()
9196        || left.validity() != right.validity()
9197    {
9198        return false;
9199    }
9200    left.values()
9201        .iter()
9202        .zip(right.values().iter())
9203        .all(|(l, r)| l.semantic_eq(r))
9204}
9205
9206fn joined_series_semantic_eq(left: &JoinedSeries, right: &JoinedSeries) -> bool {
9207    left.index == right.index
9208        && columns_semantic_eq(&left.left_values, &right.left_values)
9209        && columns_semantic_eq(&left.right_values, &right.right_values)
9210}
9211
9212/// Bounded differential fuzzer for `join_series`: parses raw byte payloads
9213/// into bounded numeric/missing series, then requires global, arena, and
9214/// forced-fallback execution paths to agree exactly. It also checks join-type
9215/// specific output contracts plus side-swapped dualities where pandas-visible
9216/// semantics should remain invariant.
9217pub fn fuzz_join_series_bytes(input: &[u8]) -> Result<(), String> {
9218    let Some((&join_tag, payload)) = input.split_first() else {
9219        return Ok(());
9220    };
9221
9222    let join_type = fuzz_join_type_from_byte(join_tag);
9223    let (left_bytes, right_bytes) =
9224        if let Some(split_at) = payload.iter().position(|byte| *byte == b'|') {
9225            (&payload[..split_at], &payload[split_at + 1..])
9226        } else {
9227            payload.split_at(payload.len() / 2)
9228        };
9229
9230    let left = fuzz_series_from_bytes("left", left_bytes)
9231        .map_err(|err| format!("left series projection failed: {err:?}"))?;
9232    let right = fuzz_series_from_bytes("right", right_bytes)
9233        .map_err(|err| format!("right series projection failed: {err:?}"))?;
9234
9235    let global = join_series_with_options(
9236        &left,
9237        &right,
9238        join_type,
9239        JoinExecutionOptions {
9240            use_arena: false,
9241            arena_budget_bytes: 0,
9242        },
9243    )
9244    .map_err(|err| format!("global join unexpectedly failed: {err:?}"))?;
9245
9246    let arena = join_series_with_options(&left, &right, join_type, JoinExecutionOptions::default())
9247        .map_err(|err| format!("arena join unexpectedly failed: {err:?}"))?;
9248
9249    let fallback = join_series_with_options(
9250        &left,
9251        &right,
9252        join_type,
9253        JoinExecutionOptions {
9254            use_arena: true,
9255            arena_budget_bytes: 1,
9256        },
9257    )
9258    .map_err(|err| format!("fallback join unexpectedly failed: {err:?}"))?;
9259
9260    if !joined_series_semantic_eq(&global, &arena) {
9261        return Err(format!(
9262            "arena join result drifted from global: \
9263             join_type={join_type:?} left={left:?} right={right:?} global={global:?} arena={arena:?}"
9264        ));
9265    }
9266    if !joined_series_semantic_eq(&global, &fallback) {
9267        return Err(format!(
9268            "fallback join result drifted from global: \
9269             join_type={join_type:?} left={left:?} right={right:?} global={global:?} fallback={fallback:?}"
9270        ));
9271    }
9272
9273    if global.index.len() != global.left_values.len()
9274        || global.index.len() != global.right_values.len()
9275    {
9276        return Err(format!(
9277            "join output length mismatch: join_type={join_type:?} index_len={} left_len={} right_len={}",
9278            global.index.len(),
9279            global.left_values.len(),
9280            global.right_values.len()
9281        ));
9282    }
9283
9284    match join_type {
9285        JoinType::Inner => {
9286            for label in global.index.labels() {
9287                if !left.index().labels().contains(label) || !right.index().labels().contains(label)
9288                {
9289                    return Err(format!(
9290                        "inner join emitted label not present on both sides: \
9291                         join_type={join_type:?} label={label:?} left={left:?} right={right:?}"
9292                    ));
9293                }
9294            }
9295        }
9296        JoinType::Left => {
9297            let joined_labels = global.index.labels();
9298            for label in left.index().labels() {
9299                if !joined_labels.contains(label) {
9300                    return Err(format!(
9301                        "left join dropped left label {label:?}: result={global:?}"
9302                    ));
9303                }
9304            }
9305        }
9306        JoinType::Right => {
9307            let joined_labels = global.index.labels();
9308            for label in right.index().labels() {
9309                if !joined_labels.contains(label) {
9310                    return Err(format!(
9311                        "right join dropped right label {label:?}: result={global:?}"
9312                    ));
9313                }
9314            }
9315        }
9316        JoinType::Outer => {
9317            let joined_labels = global.index.labels();
9318            for label in left.index().labels() {
9319                if !joined_labels.contains(label) {
9320                    return Err(format!(
9321                        "outer join dropped left label {label:?}: result={global:?}"
9322                    ));
9323                }
9324            }
9325            for label in right.index().labels() {
9326                if !joined_labels.contains(label) {
9327                    return Err(format!(
9328                        "outer join dropped right label {label:?}: result={global:?}"
9329                    ));
9330                }
9331            }
9332        }
9333        JoinType::Cross => {
9334            let expected_rows = left.index().len().saturating_mul(right.index().len());
9335            if global.index.len() != expected_rows {
9336                return Err(format!(
9337                    "cross join row count drifted: expected_rows={expected_rows} actual_rows={} \
9338                     left_rows={} right_rows={}",
9339                    global.index.len(),
9340                    left.index().len(),
9341                    right.index().len()
9342                ));
9343            }
9344        }
9345    }
9346
9347    if !matches!(join_type, JoinType::Cross) {
9348        let swapped = join_series(&right, &left, swapped_join_type(join_type))
9349            .map_err(|err| format!("swapped join unexpectedly failed: {err:?}"))?;
9350        if normalized_join_rows(&global) != normalized_join_rows_with_swapped_sides(&swapped) {
9351            return Err(format!(
9352                "join lost side-swapped duality after normalization: \
9353                 join_type={join_type:?} left={left:?} right={right:?} \
9354                 forward_rows={:?} swapped_rows={:?}",
9355                normalized_join_rows(&global),
9356                normalized_join_rows_with_swapped_sides(&swapped)
9357            ));
9358        }
9359    }
9360
9361    Ok(())
9362}
9363
9364fn fuzz_groupby_key_scalar_from_bytes(bytes: &[u8]) -> Scalar {
9365    let tag = bytes.first().copied().unwrap_or_default();
9366    let payload = bytes.get(1).copied().unwrap_or_default();
9367
9368    match tag % 4 {
9369        0 => Scalar::Null(NullKind::Null),
9370        1 => Scalar::Int64(i64::from(payload % 4)),
9371        2 => Scalar::Int64(i64::from(payload % 7) - 3),
9372        _ => Scalar::Int64(0),
9373    }
9374}
9375
9376fn fuzz_groupby_value_scalar_from_bytes(bytes: &[u8]) -> Scalar {
9377    let tag = bytes.first().copied().unwrap_or_default();
9378    let payload = bytes.get(1).copied().unwrap_or_default();
9379
9380    match tag % 5 {
9381        0 => Scalar::Null(NullKind::Null),
9382        1 => Scalar::Int64(i64::from(payload % 9) - 4),
9383        2 => Scalar::Float64(f64::from(i8::from_ne_bytes([payload])) / 4.0),
9384        3 => Scalar::Float64(0.0),
9385        _ => Scalar::Float64(1.5),
9386    }
9387}
9388
9389fn fuzz_groupby_series_from_bytes<F>(
9390    name: &str,
9391    bytes: &[u8],
9392    scalar_from_bytes: F,
9393) -> Result<Series, FrameError>
9394where
9395    F: Fn(&[u8]) -> Scalar,
9396{
9397    let mut labels = Vec::new();
9398    let mut values = Vec::new();
9399
9400    for chunk in bytes.chunks(3).take(12) {
9401        let Some((&label_tag, scalar_bytes)) = chunk.split_first() else {
9402            continue;
9403        };
9404        labels.push(fuzz_index_label_from_byte(label_tag));
9405        values.push(scalar_from_bytes(scalar_bytes));
9406    }
9407
9408    Series::from_values(name, labels, values)
9409}
9410
9411/// Structure-aware fuzz entrypoint for `groupby_sum()` invariants.
9412///
9413/// The first byte selects `dropna`; remaining bytes are split at `|` (or
9414/// midpoint) into key/value series payloads. The harness projects these into
9415/// bounded Int64-or-null keys plus numeric-or-missing values, then requires the
9416/// global, arena, and forced-fallback execution paths to agree exactly.
9417pub fn fuzz_groupby_sum_bytes(input: &[u8]) -> Result<(), String> {
9418    let Some((&option_tag, payload)) = input.split_first() else {
9419        return Ok(());
9420    };
9421
9422    let (key_bytes, value_bytes) =
9423        if let Some(split_at) = payload.iter().position(|byte| *byte == b'|') {
9424            (&payload[..split_at], &payload[split_at + 1..])
9425        } else {
9426            payload.split_at(payload.len() / 2)
9427        };
9428
9429    let keys =
9430        fuzz_groupby_series_from_bytes("keys", key_bytes, fuzz_groupby_key_scalar_from_bytes)
9431            .map_err(|err| format!("key series projection failed: {err:?}"))?;
9432    let values =
9433        fuzz_groupby_series_from_bytes("values", value_bytes, fuzz_groupby_value_scalar_from_bytes)
9434            .map_err(|err| format!("value series projection failed: {err:?}"))?;
9435
9436    let options = GroupByOptions {
9437        dropna: option_tag % 2 == 0,
9438        ..GroupByOptions::default()
9439    };
9440    let policy = RuntimePolicy::hardened(Some(100_000));
9441
9442    let mut global_ledger = EvidenceLedger::new();
9443    let global = groupby_sum_with_options(
9444        &keys,
9445        &values,
9446        options,
9447        &policy,
9448        &mut global_ledger,
9449        GroupByExecutionOptions {
9450            use_arena: false,
9451            arena_budget_bytes: 0,
9452        },
9453    );
9454
9455    let mut arena_ledger = EvidenceLedger::new();
9456    let arena = groupby_sum_with_options(
9457        &keys,
9458        &values,
9459        options,
9460        &policy,
9461        &mut arena_ledger,
9462        GroupByExecutionOptions::default(),
9463    );
9464
9465    let mut fallback_ledger = EvidenceLedger::new();
9466    let fallback = groupby_sum_with_options(
9467        &keys,
9468        &values,
9469        options,
9470        &policy,
9471        &mut fallback_ledger,
9472        GroupByExecutionOptions {
9473            use_arena: true,
9474            arena_budget_bytes: 1,
9475        },
9476    );
9477
9478    match (global, arena, fallback) {
9479        (Ok(global), Ok(arena), Ok(fallback)) => {
9480            if !global.equals(&arena) {
9481                return Err(format!(
9482                    "arena groupby result drifted from global: \
9483                     keys={keys:?} values={values:?} options={options:?} \
9484                     global={global:?} arena={arena:?}"
9485                ));
9486            }
9487            if !global.equals(&fallback) {
9488                return Err(format!(
9489                    "fallback groupby result drifted from global: \
9490                     keys={keys:?} values={values:?} options={options:?} \
9491                     global={global:?} fallback={fallback:?}"
9492                ));
9493            }
9494
9495            if global.index().len() != global.values().len() {
9496                return Err(format!(
9497                    "groupby result index/value length mismatch: \
9498                     index_len={} value_len={}",
9499                    global.index().len(),
9500                    global.values().len()
9501                ));
9502            }
9503
9504            let alignment = align_union(keys.index(), values.index());
9505            if global.index().len() > alignment.left_positions.len() {
9506                return Err(format!(
9507                    "groupby emitted more groups than aligned rows: \
9508                     groups={} aligned_rows={}",
9509                    global.index().len(),
9510                    alignment.left_positions.len()
9511                ));
9512            }
9513
9514            if options.dropna
9515                && global.index().labels().iter().any(|label| {
9516                    // Typed null labels replaced the '<null>' string for
9517                    // groupby null groups (br-frankenpandas-8m6ay); match
9518                    // both so the invariant survives either representation.
9519                    matches!(label, IndexLabel::Null(_))
9520                        || matches!(label, IndexLabel::Utf8(text) if text == "<null>")
9521                })
9522            {
9523                return Err(format!(
9524                    "dropna=true emitted a null group label: result={global:?}"
9525                ));
9526            }
9527        }
9528        (Err(_), Err(_), Err(_)) => {}
9529        (global_result, arena_result, fallback_result) => {
9530            return Err(format!(
9531                "groupby execution-path error mismatch: keys={keys:?} values={values:?} \
9532                 options={options:?} global={global_result:?} arena={arena_result:?} \
9533                 fallback={fallback_result:?}"
9534            ));
9535        }
9536    }
9537
9538    Ok(())
9539}
9540
9541const FUZZ_GROUPBY_AGG_FUNCS: &[&str] = &[
9542    "sum", "mean", "count", "min", "max", "std", "var", "median", "first", "last", "nunique",
9543    "prod", "product", "bogus",
9544];
9545
9546fn fuzz_groupby_agg_key_scalar_from_bytes(bytes: &[u8]) -> Scalar {
9547    let tag = bytes.first().copied().unwrap_or_default();
9548    let payload = bytes.get(1).copied().unwrap_or_default();
9549
9550    match tag % 4 {
9551        0 => Scalar::Null(NullKind::Null),
9552        1 => Scalar::Utf8(format!("g{}", payload % 4)),
9553        2 => Scalar::Utf8(format!("h{}", payload % 3)),
9554        _ => Scalar::Utf8("same".to_owned()),
9555    }
9556}
9557
9558fn fuzz_groupby_agg_value_scalar_from_bytes(bytes: &[u8]) -> Scalar {
9559    let tag = bytes.first().copied().unwrap_or_default();
9560    let payload = bytes.get(1).copied().unwrap_or_default();
9561
9562    match tag % 6 {
9563        0 => Scalar::Null(NullKind::Null),
9564        1 => Scalar::Int64(i64::from(payload % 11) - 5),
9565        2 => Scalar::Float64(f64::from(i8::from_ne_bytes([payload])) / 5.0),
9566        3 => Scalar::Float64(0.0),
9567        4 => Scalar::Float64(1.0),
9568        _ => Scalar::Int64(2),
9569    }
9570}
9571
9572fn fuzz_groupby_agg_funcs_from_bytes(bytes: &[u8]) -> Vec<&'static str> {
9573    let mut funcs = Vec::new();
9574
9575    for chunk in bytes.chunks(2).take(3) {
9576        let selector = chunk.first().copied().unwrap_or_default() as usize;
9577        let func = FUZZ_GROUPBY_AGG_FUNCS[selector % FUZZ_GROUPBY_AGG_FUNCS.len()];
9578        if !funcs.contains(&func) {
9579            funcs.push(func);
9580        }
9581    }
9582
9583    if funcs.is_empty() {
9584        funcs.push("sum");
9585    }
9586
9587    funcs
9588}
9589
9590fn fuzz_groupby_agg_frame_from_bytes(bytes: &[u8]) -> Result<(DataFrame, usize), FrameError> {
9591    let row_chunks: Vec<&[u8]> = if bytes.is_empty() {
9592        vec![&[]]
9593    } else {
9594        bytes.chunks(4).take(12).collect()
9595    };
9596
9597    let mut keys = Vec::with_capacity(row_chunks.len());
9598    let mut values = Vec::with_capacity(row_chunks.len());
9599    let mut expected_groups = BTreeSet::new();
9600
9601    for chunk in row_chunks {
9602        let key = fuzz_groupby_agg_key_scalar_from_bytes(chunk.get(..2).unwrap_or(&[]));
9603        if let Scalar::Utf8(label) = &key {
9604            expected_groups.insert(label.clone());
9605        }
9606        keys.push(key);
9607        values.push(fuzz_groupby_agg_value_scalar_from_bytes(
9608            chunk.get(2..4).unwrap_or(&[]),
9609        ));
9610    }
9611
9612    let frame = DataFrame::from_dict(&["grp", "val"], vec![("grp", keys), ("val", values)])?;
9613    Ok((frame, expected_groups.len()))
9614}
9615
9616fn fuzz_validate_groupby_agg_result(
9617    mode_name: &str,
9618    result: Result<DataFrame, FrameError>,
9619    expected_groups: usize,
9620    expected_columns: usize,
9621) -> Result<(), String> {
9622    match result {
9623        Ok(result) => {
9624            if result.index().len() != expected_groups {
9625                return Err(format!(
9626                    "{mode_name} emitted {} groups, expected {expected_groups}: result={result:?}",
9627                    result.index().len()
9628                ));
9629            }
9630            if result.column_names().len() != expected_columns {
9631                return Err(format!(
9632                    "{mode_name} emitted {} columns, expected {expected_columns}: result={result:?}",
9633                    result.column_names().len()
9634                ));
9635            }
9636            for column_name in result.column_names() {
9637                let column = result.column(column_name).ok_or_else(|| {
9638                    format!("{mode_name} result missing declared column {column_name:?}")
9639                })?;
9640                if column.values().len() != expected_groups {
9641                    return Err(format!(
9642                        "{mode_name} column {column_name:?} length drifted: \
9643                         values_len={} expected_groups={expected_groups}",
9644                        column.values().len()
9645                    ));
9646                }
9647            }
9648            Ok(())
9649        }
9650        Err(FrameError::CompatibilityRejected(_)) => Ok(()),
9651        Err(err) => Err(format!(
9652            "{mode_name} returned unexpected error variant: {err:?}"
9653        )),
9654    }
9655}
9656
9657/// Structure-aware fuzz entrypoint for `DataFrameGroupBy` aggregation dispatch.
9658///
9659/// The first byte selects the dispatch surface:
9660/// - `0`: `agg_list(&[funcs...])`
9661/// - `1`: `agg({\"val\": func})`
9662/// - `2`: `agg_dict_list({\"val\": [funcs...]})`
9663/// - `3`: `agg_named([(out, \"val\", func), ...])`
9664///
9665/// Remaining bytes are split at `|` (or midpoint) into function selectors and
9666/// row payload. Successful runs must produce exactly one row per non-null group
9667/// and one output column per requested aggregation. Unsupported functions are
9668/// allowed only if they return `FrameError::CompatibilityRejected`.
9669pub fn fuzz_groupby_agg_bytes(input: &[u8]) -> Result<(), String> {
9670    let Some((&mode_tag, payload)) = input.split_first() else {
9671        return Ok(());
9672    };
9673
9674    let (func_bytes, row_bytes) =
9675        if let Some(split_at) = payload.iter().position(|byte| *byte == b'|') {
9676            (&payload[..split_at], &payload[split_at + 1..])
9677        } else {
9678            payload.split_at(payload.len() / 3)
9679        };
9680
9681    let funcs = fuzz_groupby_agg_funcs_from_bytes(func_bytes);
9682    let (frame, expected_groups) = fuzz_groupby_agg_frame_from_bytes(row_bytes)
9683        .map_err(|err| format!("groupby agg frame projection failed: {err:?}"))?;
9684    let groupby = frame
9685        .groupby(&["grp"])
9686        .map_err(|err| format!("groupby setup failed: {err:?}"))?;
9687
9688    match mode_tag % 4 {
9689        0 => fuzz_validate_groupby_agg_result(
9690            "agg_list",
9691            groupby.agg_list(&funcs),
9692            expected_groups,
9693            funcs.len(),
9694        ),
9695        1 => {
9696            let mut func_map = HashMap::new();
9697            func_map.insert("val".to_owned(), funcs[0].to_owned());
9698            fuzz_validate_groupby_agg_result("agg", groupby.agg(&func_map), expected_groups, 1)
9699        }
9700        2 => {
9701            // Ordered pairs, not a map: agg_dict_list's column axis follows the
9702            // REQUEST order (br-frankenpandas-nv5ct).
9703            let func_map = vec![(
9704                "val".to_owned(),
9705                funcs.iter().map(|func| (*func).to_owned()).collect(),
9706            )];
9707            fuzz_validate_groupby_agg_result(
9708                "agg_dict_list",
9709                groupby.agg_dict_list(&func_map),
9710                expected_groups,
9711                funcs.len(),
9712            )
9713        }
9714        _ => {
9715            let specs_owned: Vec<(String, String, String)> = funcs
9716                .iter()
9717                .enumerate()
9718                .map(|(idx, func)| {
9719                    (
9720                        format!("out_{idx}_{func}"),
9721                        "val".to_owned(),
9722                        (*func).to_owned(),
9723                    )
9724                })
9725                .collect();
9726            let specs: Vec<(&str, &str, &str)> = specs_owned
9727                .iter()
9728                .map(|(output, column, func)| (output.as_str(), column.as_str(), func.as_str()))
9729                .collect();
9730            fuzz_validate_groupby_agg_result(
9731                "agg_named",
9732                groupby.agg_named(&specs),
9733                expected_groups,
9734                funcs.len(),
9735            )
9736        }
9737    }
9738}
9739
9740/// Structure-aware fuzz entrypoint for the `fp-io` JSON and JSONL readers.
9741///
9742/// The same textual payload is exercised across all supported JSON orients plus
9743/// JSONL. Any semantic parser error is acceptable, but successful parses must
9744/// survive a write/reparse round-trip without panicking or drifting.
9745pub fn fuzz_json_io_bytes(input: &[u8]) -> Result<(), FpIoError> {
9746    let input = String::from_utf8_lossy(input);
9747    let mut first_err = None;
9748    let mut saw_success = false;
9749
9750    for orient in [
9751        JsonOrient::Records,
9752        JsonOrient::Columns,
9753        JsonOrient::Index,
9754        JsonOrient::Split,
9755        JsonOrient::Values,
9756    ] {
9757        match read_json_str(&input, orient) {
9758            Ok(frame) => {
9759                saw_success = true;
9760                assert_json_roundtrip(&frame, orient)?;
9761            }
9762            Err(err) => {
9763                if first_err.is_none() {
9764                    first_err = Some(err);
9765                }
9766            }
9767        }
9768    }
9769
9770    match read_jsonl_str(&input) {
9771        Ok(frame) => {
9772            saw_success = true;
9773            assert_jsonl_roundtrip(&frame)?;
9774        }
9775        Err(err) => {
9776            if first_err.is_none() {
9777                first_err = Some(err);
9778            }
9779        }
9780    }
9781
9782    if saw_success {
9783        Ok(())
9784    } else {
9785        Err(first_err.unwrap_or_else(|| {
9786            FpIoError::JsonFormat("json fuzz input did not exercise any parser".to_owned())
9787        }))
9788    }
9789}
9790
9791fn list_fixture_files(root: &Path) -> Result<Vec<PathBuf>, HarnessError> {
9792    if !root.exists() {
9793        return Ok(Vec::new());
9794    }
9795
9796    let mut files = Vec::new();
9797    let mut stack = vec![root.to_path_buf()];
9798
9799    while let Some(current) = stack.pop() {
9800        for entry in fs::read_dir(current)? {
9801            let entry = entry?;
9802            let path = entry.path();
9803            if path.is_dir() {
9804                stack.push(path);
9805            } else if path.extension().is_some_and(|ext| ext == "json") {
9806                files.push(path);
9807            }
9808        }
9809    }
9810
9811    files.sort();
9812    Ok(files)
9813}
9814
9815fn run_fixture(
9816    config: &HarnessConfig,
9817    fixture: &PacketFixture,
9818    options: &SuiteOptions,
9819) -> Result<CaseResult, HarnessError> {
9820    if let Some(retirement) = &fixture.retired {
9821        let replay_key =
9822            deterministic_replay_key(&fixture.packet_id, &fixture.case_id, fixture.mode);
9823        let trace_id = deterministic_trace_id(&fixture.packet_id, &fixture.case_id, fixture.mode);
9824        return Ok(CaseResult {
9825            packet_id: fixture.packet_id.clone(),
9826            case_id: fixture.case_id.clone(),
9827            mode: fixture.mode,
9828            operation: fixture.operation,
9829            status: CaseStatus::Retired,
9830            mismatch: Some(format!("retired: {}", retirement.reason)),
9831            mismatch_class: None,
9832            replay_key,
9833            trace_id,
9834            elapsed_us: 1,
9835            evidence_records: 0,
9836        });
9837    }
9838
9839    let policy = match fixture.mode {
9840        RuntimeMode::Strict => RuntimePolicy::strict(),
9841        RuntimeMode::Hardened => RuntimePolicy::hardened(Some(100_000)),
9842    };
9843
9844    let mut ledger = EvidenceLedger::new();
9845    let started = Instant::now();
9846    let mismatch =
9847        run_fixture_operation(config, fixture, &policy, &mut ledger, options.oracle_mode).err();
9848    let elapsed_us = (started.elapsed().as_micros() as u64).max(1);
9849    let replay_key = deterministic_replay_key(&fixture.packet_id, &fixture.case_id, fixture.mode);
9850    let trace_id = deterministic_trace_id(&fixture.packet_id, &fixture.case_id, fixture.mode);
9851    let mismatch_class = mismatch.as_ref().map(|_| "execution_critical".to_owned());
9852
9853    Ok(CaseResult {
9854        packet_id: fixture.packet_id.clone(),
9855        case_id: fixture.case_id.clone(),
9856        mode: fixture.mode,
9857        operation: fixture.operation,
9858        status: if mismatch.is_none() {
9859            CaseStatus::Pass
9860        } else {
9861            CaseStatus::Fail
9862        },
9863        mismatch,
9864        mismatch_class,
9865        replay_key,
9866        trace_id,
9867        elapsed_us,
9868        evidence_records: ledger.records().len(),
9869    })
9870}
9871
9872fn run_fixture_operation(
9873    config: &HarnessConfig,
9874    fixture: &PacketFixture,
9875    policy: &RuntimePolicy,
9876    ledger: &mut EvidenceLedger,
9877    default_oracle_mode: OracleMode,
9878) -> Result<(), String> {
9879    let expected = resolve_expected(config, fixture, default_oracle_mode)
9880        .map_err(|err| format!("expected resolution failed: {err}"))?;
9881
9882    match fixture.operation {
9883        FixtureOperation::SeriesAdd
9884        | FixtureOperation::SeriesSub
9885        | FixtureOperation::SeriesMul
9886        | FixtureOperation::SeriesDiv => {
9887            let left = require_left_series(fixture)?;
9888            let right = require_right_series(fixture)?;
9889            let left_series = build_series(left)?;
9890            let right_series = build_series(right)?;
9891            let actual = match fixture.operation {
9892                FixtureOperation::SeriesAdd => {
9893                    left_series.add_with_policy(&right_series, policy, ledger)
9894                }
9895                FixtureOperation::SeriesSub => {
9896                    left_series.sub_with_policy(&right_series, policy, ledger)
9897                }
9898                FixtureOperation::SeriesMul => {
9899                    left_series.mul_with_policy(&right_series, policy, ledger)
9900                }
9901                FixtureOperation::SeriesDiv => {
9902                    left_series.div_with_policy(&right_series, policy, ledger)
9903                }
9904                _ => unreachable!("match arm constrained to series arithmetic operations"),
9905            }
9906            .map_err(|err| err.to_string())?;
9907
9908            let expected = match expected {
9909                ResolvedExpected::Series(series) => series,
9910                _ => {
9911                    return Err(format!(
9912                        "expected_series is required for {}",
9913                        fixture.operation.operation_name()
9914                    ));
9915                }
9916            };
9917            compare_series_expected(&actual, &expected)
9918        }
9919        FixtureOperation::SeriesJoin => {
9920            let left = require_left_series(fixture)?;
9921            let right = require_right_series(fixture)?;
9922            let joined = (|| -> Result<fp_join::JoinedSeries, String> {
9923                let left_series =
9924                    build_series(left).map_err(|err| format!("left series build failed: {err}"))?;
9925                let right_series = build_series(right)
9926                    .map_err(|err| format!("right series build failed: {err}"))?;
9927                let join_type = require_series_join_type(fixture)?;
9928                join_series(&left_series, &right_series, join_type).map_err(|err| err.to_string())
9929            })();
9930
9931            match expected {
9932                ResolvedExpected::Join(expected_join) => {
9933                    compare_join_expected(&joined?, &expected_join)
9934                }
9935                ResolvedExpected::ErrorContains(substr) => match joined {
9936                    Err(message) => {
9937                        if message.contains(&substr) {
9938                            Ok(())
9939                        } else {
9940                            Err(format!(
9941                                "expected series_join error containing '{substr}', got '{message}'"
9942                            ))
9943                        }
9944                    }
9945                    Ok(_) => Err(format!(
9946                        "expected series_join to fail with error containing '{substr}'"
9947                    )),
9948                },
9949                ResolvedExpected::ErrorAny => match joined {
9950                    Err(_) => Ok(()),
9951                    Ok(_) => Err("expected series_join to fail".to_owned()),
9952                },
9953                _ => Err("expected_join is required for series_join".to_owned()),
9954            }
9955        }
9956        FixtureOperation::SeriesConstructor => {
9957            let left = require_left_series(fixture)?;
9958            let actual = build_series(left);
9959            match expected {
9960                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
9961                ResolvedExpected::ErrorContains(substr) => match actual {
9962                    Err(message) if message.contains(&substr) => Ok(()),
9963                    Err(message) => Err(format!(
9964                        "expected series_constructor error containing '{substr}', got '{message}'"
9965                    )),
9966                    Ok(_) => Err(format!(
9967                        "expected series_constructor to fail with error containing '{substr}'"
9968                    )),
9969                },
9970                ResolvedExpected::ErrorAny => match actual {
9971                    Err(_) => Ok(()),
9972                    Ok(_) => Err("expected series_constructor to fail".to_owned()),
9973                },
9974                _ => Err(
9975                    "expected_series or expected_error is required for series_constructor"
9976                        .to_owned(),
9977                ),
9978            }
9979        }
9980        FixtureOperation::SeriesToDatetime => {
9981            let left = require_left_series(fixture)?;
9982            let series = build_series(left)?;
9983            let actual = resolve_datetime_origin_option(fixture.datetime_origin.as_ref()).and_then(
9984                |origin| {
9985                    fp_frame::to_datetime_with_options(
9986                        &series,
9987                        fp_frame::ToDatetimeOptions {
9988                            format: None,
9989                            unit: fixture.datetime_unit.as_deref(),
9990                            utc: fixture.datetime_utc.unwrap_or(false),
9991                            origin,
9992                            infer_mixed_timezone: true,
9993                            mixed_tz_as_object: false,
9994                            errors: fp_frame::DatetimeErrors::Coerce,
9995                            dayfirst: false,
9996                            yearfirst: false,
9997                            list_input: false,
9998                        },
9999                    )
10000                    .map_err(|err| err.to_string())
10001                },
10002            );
10003            match expected {
10004                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
10005                ResolvedExpected::ErrorContains(substr) => match actual {
10006                    Err(message) if message.contains(&substr) => Ok(()),
10007                    Err(message) => Err(format!(
10008                        "expected series_to_datetime error containing '{substr}', got '{message}'"
10009                    )),
10010                    Ok(_) => Err(format!(
10011                        "expected series_to_datetime to fail with error containing '{substr}'"
10012                    )),
10013                },
10014                ResolvedExpected::ErrorAny => match actual {
10015                    Err(_) => Ok(()),
10016                    Ok(_) => Err("expected series_to_datetime to fail".to_owned()),
10017                },
10018                _ => Err(
10019                    "expected_series or expected_error is required for series_to_datetime"
10020                        .to_owned(),
10021                ),
10022            }
10023        }
10024        FixtureOperation::SeriesToTimedelta => {
10025            let left = require_left_series(fixture)?;
10026            let series = build_series(left)?;
10027            let actual = fp_frame::to_timedelta(&series).map_err(|err| err.to_string());
10028            match expected {
10029                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
10030                ResolvedExpected::ErrorContains(substr) => match actual {
10031                    Err(message) if message.contains(&substr) => Ok(()),
10032                    Err(message) => Err(format!(
10033                        "expected series_to_timedelta error containing '{substr}', got '{message}'"
10034                    )),
10035                    Ok(_) => Err(format!(
10036                        "expected series_to_timedelta to fail with error containing '{substr}'"
10037                    )),
10038                },
10039                ResolvedExpected::ErrorAny => match actual {
10040                    Err(_) => Ok(()),
10041                    Ok(_) => Err("expected series_to_timedelta to fail".to_owned()),
10042                },
10043                _ => Err(
10044                    "expected_series or expected_error is required for series_to_timedelta"
10045                        .to_owned(),
10046                ),
10047            }
10048        }
10049        FixtureOperation::SeriesTimedeltaTotalSeconds => {
10050            let left = require_left_series(fixture)?;
10051            let series = build_series(left)?;
10052            let actual = fp_frame::timedelta_total_seconds(&series).map_err(|err| err.to_string());
10053            match expected {
10054                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
10055                ResolvedExpected::ErrorContains(substr) => match actual {
10056                    Err(message) if message.contains(&substr) => Ok(()),
10057                    Err(message) => Err(format!(
10058                        "expected timedelta_total_seconds error containing '{substr}', got '{message}'"
10059                    )),
10060                    Ok(_) => Err(format!(
10061                        "expected timedelta_total_seconds to fail with error containing '{substr}'"
10062                    )),
10063                },
10064                ResolvedExpected::ErrorAny => match actual {
10065                    Err(_) => Ok(()),
10066                    Ok(_) => Err("expected timedelta_total_seconds to fail".to_owned()),
10067                },
10068                _ => Err(
10069                    "expected_series or expected_error is required for timedelta_total_seconds"
10070                        .to_owned(),
10071                ),
10072            }
10073        }
10074        FixtureOperation::DataFrameFromSeries => {
10075            let actual = execute_dataframe_from_series_fixture_operation(fixture);
10076            match expected {
10077                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
10078                ResolvedExpected::ErrorContains(substr) => match actual {
10079                    Err(message) if message.contains(&substr) => Ok(()),
10080                    Err(message) => Err(format!(
10081                        "expected dataframe_from_series error containing '{substr}', got '{message}'"
10082                    )),
10083                    Ok(_) => Err(format!(
10084                        "expected dataframe_from_series to fail with error containing '{substr}'"
10085                    )),
10086                },
10087                ResolvedExpected::ErrorAny => match actual {
10088                    Err(_) => Ok(()),
10089                    Ok(_) => Err("expected dataframe_from_series to fail".to_owned()),
10090                },
10091                _ => Err(
10092                    "expected_frame or expected_error is required for dataframe_from_series"
10093                        .to_owned(),
10094                ),
10095            }
10096        }
10097        FixtureOperation::DataFrameFromDict => {
10098            let actual = execute_dataframe_from_dict_fixture_operation(fixture);
10099            match expected {
10100                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
10101                ResolvedExpected::ErrorContains(substr) => match actual {
10102                    Err(message) if message.contains(&substr) => Ok(()),
10103                    Err(message) => Err(format!(
10104                        "expected dataframe_from_dict error containing '{substr}', got '{message}'"
10105                    )),
10106                    Ok(_) => Err(format!(
10107                        "expected dataframe_from_dict to fail with error containing '{substr}'"
10108                    )),
10109                },
10110                ResolvedExpected::ErrorAny => match actual {
10111                    Err(_) => Ok(()),
10112                    Ok(_) => Err("expected dataframe_from_dict to fail".to_owned()),
10113                },
10114                _ => Err(
10115                    "expected_frame or expected_error is required for dataframe_from_dict"
10116                        .to_owned(),
10117                ),
10118            }
10119        }
10120        FixtureOperation::DataFrameFromRecords => {
10121            let actual = execute_dataframe_from_records_fixture_operation(fixture);
10122            match expected {
10123                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
10124                ResolvedExpected::ErrorContains(substr) => match actual {
10125                    Err(message) if message.contains(&substr) => Ok(()),
10126                    Err(message) => Err(format!(
10127                        "expected dataframe_from_records error containing '{substr}', got '{message}'"
10128                    )),
10129                    Ok(_) => Err(format!(
10130                        "expected dataframe_from_records to fail with error containing '{substr}'"
10131                    )),
10132                },
10133                ResolvedExpected::ErrorAny => match actual {
10134                    Err(_) => Ok(()),
10135                    Ok(_) => Err("expected dataframe_from_records to fail".to_owned()),
10136                },
10137                _ => Err(
10138                    "expected_frame or expected_error is required for dataframe_from_records"
10139                        .to_owned(),
10140                ),
10141            }
10142        }
10143        FixtureOperation::DataFrameConstructorKwargs => {
10144            let actual = execute_dataframe_constructor_kwargs_fixture_operation(fixture);
10145            match expected {
10146                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
10147                ResolvedExpected::ErrorContains(substr) => match actual {
10148                    Err(message) if message.contains(&substr) => Ok(()),
10149                    Err(message) => Err(format!(
10150                        "expected dataframe_constructor_kwargs error containing '{substr}', got '{message}'"
10151                    )),
10152                    Ok(_) => Err(format!(
10153                        "expected dataframe_constructor_kwargs to fail with error containing '{substr}'"
10154                    )),
10155                },
10156                ResolvedExpected::ErrorAny => match actual {
10157                    Err(_) => Ok(()),
10158                    Ok(_) => Err("expected dataframe_constructor_kwargs to fail".to_owned()),
10159                },
10160                _ => Err(
10161                    "expected_frame or expected_error is required for dataframe_constructor_kwargs"
10162                        .to_owned(),
10163                ),
10164            }
10165        }
10166        FixtureOperation::DataFrameConstructorScalar => {
10167            let actual = execute_dataframe_constructor_scalar_fixture_operation(fixture);
10168            match expected {
10169                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
10170                ResolvedExpected::ErrorContains(substr) => match actual {
10171                    Err(message) if message.contains(&substr) => Ok(()),
10172                    Err(message) => Err(format!(
10173                        "expected dataframe_constructor_scalar error containing '{substr}', got '{message}'"
10174                    )),
10175                    Ok(_) => Err(format!(
10176                        "expected dataframe_constructor_scalar to fail with error containing '{substr}'"
10177                    )),
10178                },
10179                ResolvedExpected::ErrorAny => match actual {
10180                    Err(_) => Ok(()),
10181                    Ok(_) => Err("expected dataframe_constructor_scalar to fail".to_owned()),
10182                },
10183                _ => Err(
10184                    "expected_frame or expected_error is required for dataframe_constructor_scalar"
10185                        .to_owned(),
10186                ),
10187            }
10188        }
10189        FixtureOperation::DataFrameConstructorDictOfSeries => {
10190            let actual = execute_dataframe_constructor_dict_of_series_fixture_operation(fixture);
10191            match expected {
10192                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
10193                ResolvedExpected::ErrorContains(substr) => match actual {
10194                    Err(message) if message.contains(&substr) => Ok(()),
10195                    Err(message) => Err(format!(
10196                        "expected dataframe_constructor_dict_of_series error containing '{substr}', got '{message}'"
10197                    )),
10198                    Ok(_) => Err(format!(
10199                        "expected dataframe_constructor_dict_of_series to fail with error containing '{substr}'"
10200                    )),
10201                },
10202                ResolvedExpected::ErrorAny => match actual {
10203                    Err(_) => Ok(()),
10204                    Ok(_) => {
10205                        Err("expected dataframe_constructor_dict_of_series to fail".to_owned())
10206                    }
10207                },
10208                _ => Err(
10209                    "expected_frame or expected_error is required for dataframe_constructor_dict_of_series"
10210                        .to_owned(),
10211                ),
10212            }
10213        }
10214        FixtureOperation::DataFrameConstructorListLike => {
10215            let actual = execute_dataframe_constructor_list_like_fixture_operation(fixture);
10216            match expected {
10217                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
10218                ResolvedExpected::ErrorContains(substr) => match actual {
10219                    Err(message) if message.contains(&substr) => Ok(()),
10220                    Err(message) => Err(format!(
10221                        "expected dataframe_constructor_list_like error containing '{substr}', got '{message}'"
10222                    )),
10223                    Ok(_) => Err(format!(
10224                        "expected dataframe_constructor_list_like to fail with error containing '{substr}'"
10225                    )),
10226                },
10227                ResolvedExpected::ErrorAny => match actual {
10228                    Err(_) => Ok(()),
10229                    Ok(_) => Err("expected dataframe_constructor_list_like to fail".to_owned()),
10230                },
10231                _ => Err(
10232                    "expected_frame or expected_error is required for dataframe_constructor_list_like"
10233                        .to_owned(),
10234                ),
10235            }
10236        }
10237        FixtureOperation::GroupBySum => {
10238            let actual =
10239                execute_groupby_fixture_operation(fixture, fixture.operation, policy, ledger)?;
10240
10241            let expected = match expected {
10242                ResolvedExpected::Series(series) => series,
10243                _ => return Err("expected_series is required for groupby_sum".to_owned()),
10244            };
10245            compare_series_expected(&actual, &expected)
10246        }
10247        FixtureOperation::IndexAlignUnion => {
10248            let left = require_left_series(fixture)?;
10249            let right = require_right_series(fixture)?;
10250            let plan = align_union(
10251                &Index::new(left.index.clone()),
10252                &Index::new(right.index.clone()),
10253            );
10254            validate_alignment_plan(&plan).map_err(|err| err.to_string())?;
10255
10256            let expected = match expected {
10257                ResolvedExpected::Alignment(alignment) => alignment,
10258                _ => return Err("expected_alignment is required for index_align_union".to_owned()),
10259            };
10260            compare_alignment_expected(&plan, &expected)
10261        }
10262        FixtureOperation::IndexHasDuplicates
10263        | FixtureOperation::IndexIsMonotonicIncreasing
10264        | FixtureOperation::IndexIsMonotonicDecreasing => {
10265            let index = require_index(fixture)?;
10266            let actual = match fixture.operation {
10267                FixtureOperation::IndexHasDuplicates => Index::new(index.clone()).has_duplicates(),
10268                FixtureOperation::IndexIsMonotonicIncreasing => {
10269                    Index::new(index.clone()).is_monotonic_increasing()
10270                }
10271                FixtureOperation::IndexIsMonotonicDecreasing => {
10272                    Index::new(index.clone()).is_monotonic_decreasing()
10273                }
10274                _ => unreachable!(),
10275            };
10276            let expected = match expected {
10277                ResolvedExpected::Bool(value) => value,
10278                _ => {
10279                    return Err(format!(
10280                        "expected_bool is required for {:?}",
10281                        fixture.operation
10282                    ));
10283                }
10284            };
10285            if actual != expected {
10286                return Err(format!(
10287                    "boolean mismatch for {:?}: actual={actual}, expected={expected}",
10288                    fixture.operation
10289                ));
10290            }
10291            Ok(())
10292        }
10293        FixtureOperation::IndexFirstPositions => {
10294            let index = require_index(fixture)?;
10295            let index = Index::new(index.clone());
10296            let positions = index.position_map_first();
10297            let actual = index
10298                .labels()
10299                .iter()
10300                .map(|label| positions.get(label).copied())
10301                .collect::<Vec<_>>();
10302            let expected = match expected {
10303                ResolvedExpected::Positions(values) => values,
10304                _ => {
10305                    return Err(
10306                        "expected_positions is required for index_first_positions".to_owned()
10307                    );
10308                }
10309            };
10310            if actual != expected {
10311                return Err(format!(
10312                    "first-position mismatch: actual={actual:?}, expected={expected:?}"
10313                ));
10314            }
10315            Ok(())
10316        }
10317        FixtureOperation::SeriesConcat => {
10318            let left = require_left_series(fixture)?;
10319            let right = require_right_series(fixture)?;
10320            let left_s = build_series(left)?;
10321            let right_s = build_series(right)?;
10322            let actual = concat_series(&[&left_s, &right_s]).map_err(|err| err.to_string())?;
10323            let expected = match expected {
10324                ResolvedExpected::Series(series) => series,
10325                _ => return Err("expected_series is required for series_concat".to_owned()),
10326            };
10327            compare_series_expected(&actual, &expected)
10328        }
10329        FixtureOperation::SeriesCombineFirst => {
10330            let actual = execute_series_combine_first_fixture_operation(fixture);
10331            let expected = match expected {
10332                ResolvedExpected::Series(series) => series,
10333                _ => return Err("expected_series is required for series_combine_first".to_owned()),
10334            };
10335            compare_series_expected(&actual?, &expected)
10336        }
10337        FixtureOperation::SeriesAsof => {
10338            let actual = execute_series_asof_fixture_operation(fixture)?;
10339            let expected = match expected {
10340                ResolvedExpected::Scalar(scalar) => scalar,
10341                _ => return Err("expected_scalar is required for series_asof".to_owned()),
10342            };
10343            compare_scalar(&actual, &expected, "series_asof")
10344        }
10345        FixtureOperation::SeriesAutocorr => {
10346            let actual = execute_series_autocorr_fixture_operation(fixture)?;
10347            let expected = match expected {
10348                ResolvedExpected::Scalar(scalar) => scalar,
10349                _ => return Err("expected_scalar is required for series_autocorr".to_owned()),
10350            };
10351            compare_scalar(&actual, &expected, "series_autocorr")
10352        }
10353        FixtureOperation::NanSum
10354        | FixtureOperation::NanMean
10355        | FixtureOperation::NanMin
10356        | FixtureOperation::NanMax
10357        | FixtureOperation::NanStd
10358        | FixtureOperation::NanVar
10359        | FixtureOperation::NanCount => {
10360            let actual = execute_nanop_fixture_operation(fixture, fixture.operation)?;
10361            let expected = match expected {
10362                ResolvedExpected::Scalar(scalar) => scalar,
10363                _ => {
10364                    return Err(format!(
10365                        "expected_scalar is required for {}",
10366                        fixture.operation.operation_name()
10367                    ));
10368                }
10369            };
10370            compare_scalar(&actual, &expected, fixture.operation.operation_name())
10371        }
10372        FixtureOperation::FillNa => {
10373            let left = require_left_series(fixture)?;
10374            let fill = fixture
10375                .fill_value
10376                .as_ref()
10377                .ok_or_else(|| "fill_value is required for fill_na".to_owned())?;
10378            let actual_values = fill_na(&left.values, fill);
10379            let expected = match expected {
10380                ResolvedExpected::Series(series) => series,
10381                _ => return Err("expected_series is required for fill_na".to_owned()),
10382            };
10383            if actual_values != expected.values {
10384                return Err(format!(
10385                    "fill_na value mismatch: actual={actual_values:?}, expected={:?}",
10386                    expected.values
10387                ));
10388            }
10389            Ok(())
10390        }
10391        FixtureOperation::DropNa => {
10392            let left = require_left_series(fixture)?;
10393            let actual_values = dropna(&left.values);
10394            let expected = match expected {
10395                ResolvedExpected::Series(series) => series,
10396                _ => return Err("expected_series is required for drop_na".to_owned()),
10397            };
10398            if actual_values != expected.values {
10399                return Err(format!(
10400                    "drop_na value mismatch: actual={actual_values:?}, expected={:?}",
10401                    expected.values
10402                ));
10403            }
10404            Ok(())
10405        }
10406        FixtureOperation::SeriesToArrowRoundTrip => {
10407            let actual = execute_series_to_arrow_round_trip_fixture_operation(fixture);
10408            match expected {
10409                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
10410                ResolvedExpected::ErrorContains(substr) => match actual {
10411                    Err(message) if message.contains(&substr) => Ok(()),
10412                    Err(message) => Err(format!(
10413                        "expected series_to_arrow_round_trip error containing '{substr}', got '{message}'"
10414                    )),
10415                    Ok(_) => Err(format!(
10416                        "expected series_to_arrow_round_trip to fail with error containing '{substr}'"
10417                    )),
10418                },
10419                ResolvedExpected::ErrorAny => match actual {
10420                    Err(_) => Ok(()),
10421                    Ok(_) => Err("expected series_to_arrow_round_trip to fail".to_owned()),
10422                },
10423                _ => Err(
10424                    "expected_series or expected_error is required for series_to_arrow_round_trip"
10425                        .to_owned(),
10426                ),
10427            }
10428        }
10429        FixtureOperation::CsvRoundTrip => {
10430            let actual = execute_csv_round_trip_fixture_operation(fixture);
10431            match expected {
10432                ResolvedExpected::Bool(value) => {
10433                    let round_trip_ok = actual?;
10434                    if round_trip_ok != value {
10435                        return Err(format!(
10436                            "csv_round_trip mismatch: actual={round_trip_ok}, expected={value}"
10437                        ));
10438                    }
10439                    Ok(())
10440                }
10441                ResolvedExpected::ErrorContains(substr) => match actual {
10442                    Err(message) if message.contains(&substr) => Ok(()),
10443                    Err(message) => Err(format!(
10444                        "expected csv_round_trip error containing '{substr}', got '{message}'"
10445                    )),
10446                    Ok(_) => Err(format!(
10447                        "expected csv_round_trip to fail with error containing '{substr}'"
10448                    )),
10449                },
10450                ResolvedExpected::ErrorAny => match actual {
10451                    Err(_) => Ok(()),
10452                    Ok(_) => Err("expected csv_round_trip to fail".to_owned()),
10453                },
10454                _ => {
10455                    Err("expected_bool or expected_error is required for csv_round_trip".to_owned())
10456                }
10457            }
10458        }
10459        FixtureOperation::CsvReadFrame => {
10460            let actual = execute_csv_read_frame_fixture_operation(fixture);
10461            match expected {
10462                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
10463                ResolvedExpected::ErrorContains(substr) => match actual {
10464                    Err(message) if message.contains(&substr) => Ok(()),
10465                    Err(message) => Err(format!(
10466                        "expected csv_read_frame error containing '{substr}', got '{message}'"
10467                    )),
10468                    Ok(_) => Err(format!(
10469                        "expected csv_read_frame to fail with error containing '{substr}'"
10470                    )),
10471                },
10472                ResolvedExpected::ErrorAny => match actual {
10473                    Err(_) => Ok(()),
10474                    Ok(_) => Err("expected csv_read_frame to fail".to_owned()),
10475                },
10476                _ => Err(
10477                    "expected_frame or expected_error is required for csv_read_frame".to_owned(),
10478                ),
10479            }
10480        }
10481        FixtureOperation::DataFrameToJsonRecords => {
10482            let actual = execute_dataframe_to_json_records_fixture_operation(fixture);
10483            match expected {
10484                ResolvedExpected::Scalar(expected) => {
10485                    compare_scalar(&actual?, &expected, fixture.operation.operation_name())
10486                }
10487                ResolvedExpected::ErrorContains(substr) => match actual {
10488                    Err(message) if message.contains(&substr) => Ok(()),
10489                    Err(message) => Err(format!(
10490                        "expected dataframe_to_json_records error containing '{substr}', got '{message}'"
10491                    )),
10492                    Ok(_) => Err(format!(
10493                        "expected dataframe_to_json_records to fail with error containing '{substr}'"
10494                    )),
10495                },
10496                ResolvedExpected::ErrorAny => match actual {
10497                    Err(_) => Ok(()),
10498                    Ok(_) => Err("expected dataframe_to_json_records to fail".to_owned()),
10499                },
10500                _ => Err(
10501                    "expected_scalar or expected_error is required for dataframe_to_json_records"
10502                        .to_owned(),
10503                ),
10504            }
10505        }
10506        FixtureOperation::JsonRoundTrip => {
10507            let actual = execute_json_round_trip_fixture_operation(fixture);
10508            run_bool_round_trip_match(actual, expected, "json_round_trip")
10509        }
10510        FixtureOperation::JsonlRoundTrip => {
10511            let actual = execute_jsonl_round_trip_fixture_operation(fixture);
10512            run_bool_round_trip_match(actual, expected, "jsonl_round_trip")
10513        }
10514        FixtureOperation::ParquetRoundTrip => {
10515            let actual = execute_parquet_round_trip_fixture_operation(fixture);
10516            run_bool_round_trip_match(actual, expected, "parquet_round_trip")
10517        }
10518        FixtureOperation::FeatherRoundTrip => {
10519            let actual = execute_feather_round_trip_fixture_operation(fixture);
10520            run_bool_round_trip_match(actual, expected, "feather_round_trip")
10521        }
10522        FixtureOperation::ExcelRoundTrip => {
10523            let actual = execute_excel_round_trip_fixture_operation(fixture);
10524            run_bool_round_trip_match(actual, expected, "excel_round_trip")
10525        }
10526        FixtureOperation::IpcStreamRoundTrip => {
10527            let actual = execute_ipc_stream_round_trip_fixture_operation(fixture);
10528            run_bool_round_trip_match(actual, expected, "ipc_stream_round_trip")
10529        }
10530        FixtureOperation::ColumnDtypeCheck => {
10531            let left = require_left_series(fixture)?;
10532            let series = build_series(left)?;
10533            // pandas SPELLING, not Rust `Debug`. `DType::name()` is documented
10534            // "Matches numpy dtype.name property" and yields int64/float64/
10535            // object/category/Int64/boolean; `{:?}` yields FrankenPandas
10536            // internals (Float64/Utf8/Categorical) that no oracle can produce,
10537            // which is why these fixtures were unverifiable.
10538            // (br-frankenpandas-62d1s)
10539            let actual_dtype = series.column().dtype().name().to_owned();
10540            let expected = match expected {
10541                ResolvedExpected::Dtype(dtype) => dtype,
10542                _ => return Err("expected_dtype is required for column_dtype_check".to_owned()),
10543            };
10544            if actual_dtype != expected {
10545                return Err(format!(
10546                    "dtype mismatch: actual={actual_dtype}, expected={expected}"
10547                ));
10548            }
10549            Ok(())
10550        }
10551        FixtureOperation::SeriesDtypeCheck => {
10552            let series = build_series_for_dtype_check(fixture)?;
10553            // See ColumnDtypeCheck above (br-frankenpandas-62d1s).
10554            //
10555            // `dtype_name()`, not `dtype().name()` (br-frankenpandas-3gxc6): a
10556            // sparse Series reports the parameterized `Sparse[int64, 0]` that
10557            // pandas spells, and `DType::name()` can only answer the bare
10558            // `"Sparse"` because `DType::Sparse` carries no subtype or fill.
10559            // Every other dtype is byte-identical through this call. Both the
10560            // strict and hardened arms route through it, so the two modes
10561            // cannot disagree about a dtype name.
10562            let actual_dtype = series.dtype_name();
10563            let expected = match expected {
10564                ResolvedExpected::Dtype(dtype) => dtype,
10565                _ => return Err("expected_dtype is required for series_dtype_check".to_owned()),
10566            };
10567            if actual_dtype != expected {
10568                return Err(format!(
10569                    "dtype mismatch: actual={actual_dtype}, expected={expected}"
10570                ));
10571            }
10572            Ok(())
10573        }
10574        FixtureOperation::SeriesFilter => {
10575            let left = require_left_series(fixture)?;
10576            let right = require_right_series(fixture)?;
10577            let data = build_series(left)?;
10578            let mask = build_series(right)?;
10579            let actual = data.filter(&mask).map_err(|err| err.to_string());
10580            match expected {
10581                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
10582                ResolvedExpected::ErrorContains(substr) => match actual {
10583                    Err(message) if message.contains(&substr) => Ok(()),
10584                    Err(message) => Err(format!(
10585                        "expected series_filter error containing '{substr}', got '{message}'"
10586                    )),
10587                    Ok(_) => Err(format!(
10588                        "expected series_filter to fail with error containing '{substr}'"
10589                    )),
10590                },
10591                ResolvedExpected::ErrorAny => {
10592                    if actual.is_err() {
10593                        Ok(())
10594                    } else {
10595                        Err("expected series_filter to fail but operation succeeded".to_owned())
10596                    }
10597                }
10598                _ => Err(
10599                    "expected_series or expected_error is required for series_filter".to_owned(),
10600                ),
10601            }
10602        }
10603        FixtureOperation::SeriesHead => {
10604            let left = require_left_series(fixture)?;
10605            let n = fixture
10606                .head_n
10607                .ok_or_else(|| "head_n is required for series_head".to_owned())?;
10608            let series = build_series(left)?;
10609            let take = normalize_head_take(n, series.len());
10610            let labels = series.index().labels()[..take].to_vec();
10611            let values = series.values()[..take].to_vec();
10612            let actual =
10613                Series::from_values(series.name(), labels, values).map_err(|e| e.to_string())?;
10614            let expected = match expected {
10615                ResolvedExpected::Series(series) => series,
10616                _ => return Err("expected_series is required for series_head".to_owned()),
10617            };
10618            compare_series_expected(&actual, &expected)
10619        }
10620        FixtureOperation::SeriesTail => {
10621            let left = require_left_series(fixture)?;
10622            let n = fixture
10623                .tail_n
10624                .ok_or_else(|| "tail_n is required for series_tail".to_owned())?;
10625            let series = build_series(left)?;
10626            let actual = series.tail(n).map_err(|err| err.to_string());
10627            match expected {
10628                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
10629                ResolvedExpected::ErrorContains(substr) => match actual {
10630                    Err(message) if message.contains(&substr) => Ok(()),
10631                    Err(message) => Err(format!(
10632                        "expected series_tail error containing '{substr}', got '{message}'"
10633                    )),
10634                    Ok(_) => Err(format!(
10635                        "expected series_tail to fail with error containing '{substr}'"
10636                    )),
10637                },
10638                ResolvedExpected::ErrorAny => {
10639                    if actual.is_err() {
10640                        Ok(())
10641                    } else {
10642                        Err("expected series_tail to fail but operation succeeded".to_owned())
10643                    }
10644                }
10645                _ => {
10646                    Err("expected_series or expected_error is required for series_tail".to_owned())
10647                }
10648            }
10649        }
10650        FixtureOperation::SeriesValueCounts => {
10651            let left = require_left_series(fixture)?;
10652            let series = build_series_with_optional_categorical(fixture, left)?;
10653            let actual = series
10654                .value_counts_with_options(
10655                    resolve_value_counts_normalize(fixture),
10656                    true,
10657                    resolve_value_counts_ascending(fixture),
10658                    true,
10659                )
10660                .map_err(|err| err.to_string());
10661            match expected {
10662                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
10663                ResolvedExpected::ErrorContains(substr) => match actual {
10664                    Err(message) if message.contains(&substr) => Ok(()),
10665                    Err(message) => Err(format!(
10666                        "expected series_value_counts error containing '{substr}', got '{message}'"
10667                    )),
10668                    Ok(_) => Err(format!(
10669                        "expected series_value_counts to fail with error containing '{substr}'"
10670                    )),
10671                },
10672                ResolvedExpected::ErrorAny => {
10673                    if actual.is_err() {
10674                        Ok(())
10675                    } else {
10676                        Err(
10677                            "expected series_value_counts to fail but operation succeeded"
10678                                .to_owned(),
10679                        )
10680                    }
10681                }
10682                _ => Err(
10683                    "expected_series or expected_error is required for series_value_counts"
10684                        .to_owned(),
10685                ),
10686            }
10687        }
10688        FixtureOperation::SeriesSortIndex => {
10689            let left = require_left_series(fixture)?;
10690            let series = build_series(left)?;
10691            let actual = series
10692                .sort_index(resolve_sort_ascending(fixture))
10693                .map_err(|err| err.to_string());
10694            match expected {
10695                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
10696                ResolvedExpected::ErrorContains(substr) => match actual {
10697                    Err(message) if message.contains(&substr) => Ok(()),
10698                    Err(message) => Err(format!(
10699                        "expected series_sort_index error containing '{substr}', got '{message}'"
10700                    )),
10701                    Ok(_) => Err(format!(
10702                        "expected series_sort_index to fail with error containing '{substr}'"
10703                    )),
10704                },
10705                ResolvedExpected::ErrorAny => {
10706                    if actual.is_err() {
10707                        Ok(())
10708                    } else {
10709                        Err("expected series_sort_index to fail but operation succeeded".to_owned())
10710                    }
10711                }
10712                _ => Err(
10713                    "expected_series or expected_error is required for series_sort_index"
10714                        .to_owned(),
10715                ),
10716            }
10717        }
10718        FixtureOperation::SeriesSortValues => {
10719            let left = require_left_series(fixture)?;
10720            let series = build_series(left)?;
10721            let actual = series
10722                .sort_values(resolve_sort_ascending(fixture))
10723                .map_err(|err| err.to_string());
10724            match expected {
10725                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
10726                ResolvedExpected::ErrorContains(substr) => match actual {
10727                    Err(message) if message.contains(&substr) => Ok(()),
10728                    Err(message) => Err(format!(
10729                        "expected series_sort_values error containing '{substr}', got '{message}'"
10730                    )),
10731                    Ok(_) => Err(format!(
10732                        "expected series_sort_values to fail with error containing '{substr}'"
10733                    )),
10734                },
10735                ResolvedExpected::ErrorAny => {
10736                    if actual.is_err() {
10737                        Ok(())
10738                    } else {
10739                        Err(
10740                            "expected series_sort_values to fail but operation succeeded"
10741                                .to_owned(),
10742                        )
10743                    }
10744                }
10745                _ => Err(
10746                    "expected_series or expected_error is required for series_sort_values"
10747                        .to_owned(),
10748                ),
10749            }
10750        }
10751        FixtureOperation::SeriesDiff => {
10752            let left = require_left_series(fixture)?;
10753            let series = build_series(left)?;
10754            let periods = fixture.diff_periods.unwrap_or(1);
10755            let actual = series.diff(periods).map_err(|err| err.to_string());
10756            match expected {
10757                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
10758                ResolvedExpected::ErrorContains(substr) => match actual {
10759                    Err(message) if message.contains(&substr) => Ok(()),
10760                    Err(message) => Err(format!(
10761                        "expected series_diff error containing '{substr}', got '{message}'"
10762                    )),
10763                    Ok(_) => Err(format!(
10764                        "expected series_diff to fail with error containing '{substr}'"
10765                    )),
10766                },
10767                ResolvedExpected::ErrorAny => {
10768                    if actual.is_err() {
10769                        Ok(())
10770                    } else {
10771                        Err("expected series_diff to fail but operation succeeded".to_owned())
10772                    }
10773                }
10774                _ => {
10775                    Err("expected_series or expected_error is required for series_diff".to_owned())
10776                }
10777            }
10778        }
10779        FixtureOperation::SeriesShift => {
10780            let left = require_left_series(fixture)?;
10781            let series = build_series(left)?;
10782            let periods = fixture.shift_periods.unwrap_or(1);
10783            let actual = series.shift(periods).map_err(|err| err.to_string());
10784            match expected {
10785                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
10786                ResolvedExpected::ErrorContains(substr) => match actual {
10787                    Err(message) if message.contains(&substr) => Ok(()),
10788                    Err(message) => Err(format!(
10789                        "expected series_shift error containing '{substr}', got '{message}'"
10790                    )),
10791                    Ok(_) => Err(format!(
10792                        "expected series_shift to fail with error containing '{substr}'"
10793                    )),
10794                },
10795                ResolvedExpected::ErrorAny => {
10796                    if actual.is_err() {
10797                        Ok(())
10798                    } else {
10799                        Err("expected series_shift to fail but operation succeeded".to_owned())
10800                    }
10801                }
10802                _ => {
10803                    Err("expected_series or expected_error is required for series_shift".to_owned())
10804                }
10805            }
10806        }
10807        FixtureOperation::SeriesPctChange => {
10808            let left = require_left_series(fixture)?;
10809            let series = build_series(left)?;
10810            let periods = fixture.pct_change_periods.unwrap_or(1);
10811            let actual = series.pct_change(periods).map_err(|err| err.to_string());
10812            match expected {
10813                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
10814                ResolvedExpected::ErrorContains(substr) => match actual {
10815                    Err(message) if message.contains(&substr) => Ok(()),
10816                    Err(message) => Err(format!(
10817                        "expected series_pct_change error containing '{substr}', got '{message}'"
10818                    )),
10819                    Ok(_) => Err(format!(
10820                        "expected series_pct_change to fail with error containing '{substr}'"
10821                    )),
10822                },
10823                ResolvedExpected::ErrorAny => {
10824                    if actual.is_err() {
10825                        Ok(())
10826                    } else {
10827                        Err("expected series_pct_change to fail but operation succeeded".to_owned())
10828                    }
10829                }
10830                _ => Err(
10831                    "expected_series or expected_error is required for series_pct_change"
10832                        .to_owned(),
10833                ),
10834            }
10835        }
10836        FixtureOperation::SeriesMode => {
10837            let left = require_left_series(fixture)?;
10838            let series = build_series(left)?;
10839            let actual = series
10840                .mode_with_dropna(fixture.mode_dropna.unwrap_or(true))
10841                .map_err(|err| err.to_string());
10842            match expected {
10843                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
10844                ResolvedExpected::ErrorContains(substr) => match actual {
10845                    Err(message) if message.contains(&substr) => Ok(()),
10846                    Err(message) => Err(format!(
10847                        "expected series_mode error containing '{substr}', got '{message}'"
10848                    )),
10849                    Ok(_) => Err(format!(
10850                        "expected series_mode to fail with error containing '{substr}'"
10851                    )),
10852                },
10853                ResolvedExpected::ErrorAny => {
10854                    if actual.is_err() {
10855                        Ok(())
10856                    } else {
10857                        Err("expected series_mode to fail but operation succeeded".to_owned())
10858                    }
10859                }
10860                _ => {
10861                    Err("expected_series or expected_error is required for series_mode".to_owned())
10862                }
10863            }
10864        }
10865        FixtureOperation::SeriesRank => {
10866            let left = require_left_series(fixture)?;
10867            let series = build_series(left)?;
10868            let method = fixture.rank_method.as_deref().unwrap_or("average");
10869            let ascending = resolve_sort_ascending(fixture);
10870            let na_option = fixture.rank_na_option.as_deref().unwrap_or("keep");
10871            let pct = resolve_rank_pct(fixture);
10872            let actual = series
10873                .rank_with_pct(method, ascending, na_option, pct)
10874                .map_err(|err| err.to_string());
10875            match expected {
10876                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
10877                ResolvedExpected::ErrorContains(substr) => match actual {
10878                    Err(message) if message.contains(&substr) => Ok(()),
10879                    Err(message) => Err(format!(
10880                        "expected series_rank error containing '{substr}', got '{message}'"
10881                    )),
10882                    Ok(_) => Err(format!(
10883                        "expected series_rank to fail with error containing '{substr}'"
10884                    )),
10885                },
10886                ResolvedExpected::ErrorAny => {
10887                    if actual.is_err() {
10888                        Ok(())
10889                    } else {
10890                        Err("expected series_rank to fail but operation succeeded".to_owned())
10891                    }
10892                }
10893                _ => {
10894                    Err("expected_series or expected_error is required for series_rank".to_owned())
10895                }
10896            }
10897        }
10898        FixtureOperation::SeriesArgsort => {
10899            let left = require_left_series(fixture)?;
10900            let series = build_series(left)?;
10901            let ascending = resolve_sort_ascending(fixture);
10902            let actual = series.argsort(ascending).map_err(|err| err.to_string());
10903            match expected {
10904                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
10905                ResolvedExpected::ErrorContains(substr) => match actual {
10906                    Err(message) if message.contains(&substr) => Ok(()),
10907                    Err(message) => Err(format!(
10908                        "expected series_argsort error containing '{substr}', got '{message}'"
10909                    )),
10910                    Ok(_) => Err(format!(
10911                        "expected series_argsort to fail with error containing '{substr}'"
10912                    )),
10913                },
10914                ResolvedExpected::ErrorAny => {
10915                    if actual.is_err() {
10916                        Ok(())
10917                    } else {
10918                        Err("expected series_argsort to fail but operation succeeded".to_owned())
10919                    }
10920                }
10921                _ => Err(
10922                    "expected_series or expected_error is required for series_argsort".to_owned(),
10923                ),
10924            }
10925        }
10926        FixtureOperation::SeriesDescribe => {
10927            let left = require_left_series(fixture)?;
10928            let series = build_series(left)?;
10929            let actual = series.describe().map_err(|err| err.to_string());
10930            match expected {
10931                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
10932                ResolvedExpected::ErrorContains(substr) => match actual {
10933                    Err(message) if message.contains(&substr) => Ok(()),
10934                    Err(message) => Err(format!(
10935                        "expected series_describe error containing '{substr}', got '{message}'"
10936                    )),
10937                    Ok(_) => Err(format!(
10938                        "expected series_describe to fail with error containing '{substr}'"
10939                    )),
10940                },
10941                ResolvedExpected::ErrorAny => {
10942                    if actual.is_err() {
10943                        Ok(())
10944                    } else {
10945                        Err("expected series_describe to fail but operation succeeded".to_owned())
10946                    }
10947                }
10948                _ => Err(
10949                    "expected_series or expected_error is required for series_describe".to_owned(),
10950                ),
10951            }
10952        }
10953        FixtureOperation::SeriesDuplicated => {
10954            let left = require_left_series(fixture)?;
10955            let series = build_series(left)?;
10956            let keep = resolve_duplicate_keep(fixture)?;
10957            let actual = series.duplicated_keep(keep).map_err(|err| err.to_string());
10958            match expected {
10959                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
10960                ResolvedExpected::ErrorContains(substr) => match actual {
10961                    Err(message) if message.contains(&substr) => Ok(()),
10962                    Err(message) => Err(format!(
10963                        "expected series_duplicated error containing '{substr}', got '{message}'"
10964                    )),
10965                    Ok(_) => Err(format!(
10966                        "expected series_duplicated to fail with error containing '{substr}'"
10967                    )),
10968                },
10969                ResolvedExpected::ErrorAny => {
10970                    if actual.is_err() {
10971                        Ok(())
10972                    } else {
10973                        Err("expected series_duplicated to fail but operation succeeded".to_owned())
10974                    }
10975                }
10976                _ => Err(
10977                    "expected_series or expected_error is required for series_duplicated"
10978                        .to_owned(),
10979                ),
10980            }
10981        }
10982        FixtureOperation::SeriesDropDuplicates => {
10983            let left = require_left_series(fixture)?;
10984            let series = build_series(left)?;
10985            let keep = resolve_duplicate_keep(fixture)?;
10986            let actual = series
10987                .drop_duplicates_keep(keep)
10988                .map_err(|err| err.to_string());
10989            match expected {
10990                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
10991                ResolvedExpected::ErrorContains(substr) => match actual {
10992                    Err(message) if message.contains(&substr) => Ok(()),
10993                    Err(message) => Err(format!(
10994                        "expected series_drop_duplicates error containing '{substr}', got '{message}'"
10995                    )),
10996                    Ok(_) => Err(format!(
10997                        "expected series_drop_duplicates to fail with error containing '{substr}'"
10998                    )),
10999                },
11000                ResolvedExpected::ErrorAny => {
11001                    if actual.is_err() {
11002                        Ok(())
11003                    } else {
11004                        Err(
11005                            "expected series_drop_duplicates to fail but operation succeeded"
11006                                .to_owned(),
11007                        )
11008                    }
11009                }
11010                _ => Err(
11011                    "expected_series or expected_error is required for series_drop_duplicates"
11012                        .to_owned(),
11013                ),
11014            }
11015        }
11016        FixtureOperation::SeriesUnique => {
11017            let left = require_left_series(fixture)?;
11018            let series = build_series(left)?;
11019            let unique_values = series.unique();
11020            let labels: Vec<IndexLabel> = (0..unique_values.len())
11021                .map(|i| IndexLabel::Int64(i as i64))
11022                .collect();
11023            let actual = Series::from_values(series.name().to_owned(), labels, unique_values)
11024                .map_err(|err| err.to_string());
11025            match expected {
11026                ResolvedExpected::Series(expected_series) => {
11027                    compare_series_expected(&actual?, &expected_series)
11028                }
11029                ResolvedExpected::ErrorContains(substr) => match actual {
11030                    Err(message) if message.contains(&substr) => Ok(()),
11031                    Err(message) => Err(format!(
11032                        "expected series_unique error containing '{substr}', got '{message}'"
11033                    )),
11034                    Ok(_) => Err(format!(
11035                        "expected series_unique to fail with error containing '{substr}'"
11036                    )),
11037                },
11038                ResolvedExpected::ErrorAny => {
11039                    if actual.is_err() {
11040                        Ok(())
11041                    } else {
11042                        Err("expected series_unique to fail but operation succeeded".to_owned())
11043                    }
11044                }
11045                _ => Err(
11046                    "expected_series or expected_error is required for series_unique".to_owned(),
11047                ),
11048            }
11049        }
11050        FixtureOperation::SeriesFactorize => {
11051            let left = require_left_series(fixture)?;
11052            let series = build_series(left)?;
11053            let actual = series
11054                .factorize()
11055                .map(|(codes, _uniques)| codes)
11056                .map_err(|err| err.to_string());
11057            match expected {
11058                ResolvedExpected::Series(expected_series) => {
11059                    compare_series_expected(&actual?, &expected_series)
11060                }
11061                ResolvedExpected::ErrorContains(substr) => match actual {
11062                    Err(message) if message.contains(&substr) => Ok(()),
11063                    Err(message) => Err(format!(
11064                        "expected series_factorize error containing '{substr}', got '{message}'"
11065                    )),
11066                    Ok(_) => Err(format!(
11067                        "expected series_factorize to fail with error containing '{substr}'"
11068                    )),
11069                },
11070                ResolvedExpected::ErrorAny => {
11071                    if actual.is_err() {
11072                        Ok(())
11073                    } else {
11074                        Err("expected series_factorize to fail but operation succeeded".to_owned())
11075                    }
11076                }
11077                _ => Err(
11078                    "expected_series or expected_error is required for series_factorize".to_owned(),
11079                ),
11080            }
11081        }
11082        FixtureOperation::SeriesWhere => {
11083            let left = require_left_series(fixture)?;
11084            let series = build_series(left)?;
11085            let cond = require_right_series(fixture)?;
11086            let cond_series = build_series(cond)?;
11087            let other = fixture.fill_value.as_ref();
11088            let actual = series
11089                .where_cond(&cond_series, other)
11090                .map_err(|err| err.to_string());
11091            match expected {
11092                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
11093                ResolvedExpected::ErrorContains(substr) => match actual {
11094                    Err(message) if message.contains(&substr) => Ok(()),
11095                    Err(message) => Err(format!(
11096                        "expected series_where error containing '{substr}', got '{message}'"
11097                    )),
11098                    Ok(_) => Err(format!(
11099                        "expected series_where to fail with error containing '{substr}'"
11100                    )),
11101                },
11102                ResolvedExpected::ErrorAny => {
11103                    if actual.is_err() {
11104                        Ok(())
11105                    } else {
11106                        Err("expected series_where to fail but operation succeeded".to_owned())
11107                    }
11108                }
11109                _ => {
11110                    Err("expected_series or expected_error is required for series_where".to_owned())
11111                }
11112            }
11113        }
11114        FixtureOperation::SeriesMask => {
11115            let left = require_left_series(fixture)?;
11116            let series = build_series(left)?;
11117            let cond = require_right_series(fixture)?;
11118            let cond_series = build_series(cond)?;
11119            let other = fixture.fill_value.as_ref();
11120            let actual = series
11121                .mask(&cond_series, other)
11122                .map_err(|err| err.to_string());
11123            match expected {
11124                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
11125                ResolvedExpected::ErrorContains(substr) => match actual {
11126                    Err(message) if message.contains(&substr) => Ok(()),
11127                    Err(message) => Err(format!(
11128                        "expected series_mask error containing '{substr}', got '{message}'"
11129                    )),
11130                    Ok(_) => Err(format!(
11131                        "expected series_mask to fail with error containing '{substr}'"
11132                    )),
11133                },
11134                ResolvedExpected::ErrorAny => {
11135                    if actual.is_err() {
11136                        Ok(())
11137                    } else {
11138                        Err("expected series_mask to fail but operation succeeded".to_owned())
11139                    }
11140                }
11141                _ => {
11142                    Err("expected_series or expected_error is required for series_mask".to_owned())
11143                }
11144            }
11145        }
11146        FixtureOperation::SeriesReplace => {
11147            let left = require_left_series(fixture)?;
11148            let series = build_series(left)?;
11149            let actual =
11150                require_replacement_pairs(fixture, "series_replace").and_then(|replacements| {
11151                    series.replace(&replacements).map_err(|err| err.to_string())
11152                });
11153            match expected {
11154                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
11155                ResolvedExpected::ErrorContains(substr) => match actual {
11156                    Err(message) if message.contains(&substr) => Ok(()),
11157                    Err(message) => Err(format!(
11158                        "expected series_replace error containing '{substr}', got '{message}'"
11159                    )),
11160                    Ok(_) => Err(format!(
11161                        "expected series_replace to fail with error containing '{substr}'"
11162                    )),
11163                },
11164                ResolvedExpected::ErrorAny => {
11165                    if actual.is_err() {
11166                        Ok(())
11167                    } else {
11168                        Err("expected series_replace to fail but operation succeeded".to_owned())
11169                    }
11170                }
11171                _ => Err(
11172                    "expected_series or expected_error is required for series_replace".to_owned(),
11173                ),
11174            }
11175        }
11176        FixtureOperation::SeriesUpdate => {
11177            let left = require_left_series(fixture)?;
11178            let series = build_series(left)?;
11179            let other = require_right_series(fixture)?;
11180            let other_series = build_series(other)?;
11181            let actual = series.update(&other_series).map_err(|err| err.to_string());
11182            match expected {
11183                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
11184                ResolvedExpected::ErrorContains(substr) => match actual {
11185                    Err(message) if message.contains(&substr) => Ok(()),
11186                    Err(message) => Err(format!(
11187                        "expected series_update error containing '{substr}', got '{message}'"
11188                    )),
11189                    Ok(_) => Err(format!(
11190                        "expected series_update to fail with error containing '{substr}'"
11191                    )),
11192                },
11193                ResolvedExpected::ErrorAny => {
11194                    if actual.is_err() {
11195                        Ok(())
11196                    } else {
11197                        Err("expected series_update to fail but operation succeeded".to_owned())
11198                    }
11199                }
11200                _ => Err(
11201                    "expected_series or expected_error is required for series_update".to_owned(),
11202                ),
11203            }
11204        }
11205        FixtureOperation::SeriesMap => {
11206            let left = require_left_series(fixture)?;
11207            let series = build_series(left)?;
11208            let to_find = fixture
11209                .replace_to_find
11210                .as_ref()
11211                .ok_or_else(|| "replace_to_find required for series_map".to_owned())?;
11212            let to_value = fixture
11213                .replace_to_value
11214                .as_ref()
11215                .ok_or_else(|| "replace_to_value required for series_map".to_owned())?;
11216            let mapping: Vec<(Scalar, Scalar)> = to_find
11217                .iter()
11218                .zip(to_value.iter())
11219                .map(|(f, v)| (f.clone(), v.clone()))
11220                .collect();
11221            let actual = if fixture.na_action_ignore.unwrap_or(false) {
11222                series
11223                    .map_with_na_action(&mapping, true)
11224                    .map_err(|err| err.to_string())
11225            } else {
11226                series.map(&mapping).map_err(|err| err.to_string())
11227            };
11228            match expected {
11229                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
11230                ResolvedExpected::ErrorContains(substr) => match actual {
11231                    Err(message) if message.contains(&substr) => Ok(()),
11232                    Err(message) => Err(format!(
11233                        "expected series_map error containing '{substr}', got '{message}'"
11234                    )),
11235                    Ok(_) => Err(format!(
11236                        "expected series_map to fail with error containing '{substr}'"
11237                    )),
11238                },
11239                ResolvedExpected::ErrorAny => {
11240                    if actual.is_err() {
11241                        Ok(())
11242                    } else {
11243                        Err("expected series_map to fail but operation succeeded".to_owned())
11244                    }
11245                }
11246                _ => Err("expected_series or expected_error is required for series_map".to_owned()),
11247            }
11248        }
11249        FixtureOperation::SeriesCategoricalFromCodes => {
11250            let actual = run_series_categorical_from_codes(fixture);
11251            match expected {
11252                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
11253                ResolvedExpected::ErrorContains(substr) => match actual {
11254                    Err(message) if message.contains(&substr) => Ok(()),
11255                    Err(message) => Err(format!(
11256                        "expected series_categorical_from_codes error containing '{substr}', got '{message}'"
11257                    )),
11258                    Ok(_) => Err(format!(
11259                        "expected series_categorical_from_codes to fail with error containing '{substr}'"
11260                    )),
11261                },
11262                ResolvedExpected::ErrorAny => {
11263                    if actual.is_err() {
11264                        Ok(())
11265                    } else {
11266                        Err("expected series_categorical_from_codes to fail but operation succeeded"
11267                            .to_owned())
11268                    }
11269                }
11270                _ => Err(
11271                    "expected_series or expected_error is required for series_categorical_from_codes"
11272                        .to_owned(),
11273                ),
11274            }
11275        }
11276        FixtureOperation::SeriesIsNa => {
11277            let left = require_left_series(fixture)?;
11278            let series = build_series(left)?;
11279            let actual = series.isna().map_err(|err| err.to_string());
11280            match expected {
11281                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
11282                ResolvedExpected::ErrorContains(substr) => match actual {
11283                    Err(message) if message.contains(&substr) => Ok(()),
11284                    Err(message) => Err(format!(
11285                        "expected series_isna error containing '{substr}', got '{message}'"
11286                    )),
11287                    Ok(_) => Err(format!(
11288                        "expected series_isna to fail with error containing '{substr}'"
11289                    )),
11290                },
11291                ResolvedExpected::ErrorAny => {
11292                    if actual.is_err() {
11293                        Ok(())
11294                    } else {
11295                        Err("expected series_isna to fail but operation succeeded".to_owned())
11296                    }
11297                }
11298                _ => {
11299                    Err("expected_series or expected_error is required for series_isna".to_owned())
11300                }
11301            }
11302        }
11303        FixtureOperation::SeriesNotNa => {
11304            let left = require_left_series(fixture)?;
11305            let series = build_series(left)?;
11306            let actual = series.notna().map_err(|err| err.to_string());
11307            match expected {
11308                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
11309                ResolvedExpected::ErrorContains(substr) => match actual {
11310                    Err(message) if message.contains(&substr) => Ok(()),
11311                    Err(message) => Err(format!(
11312                        "expected series_notna error containing '{substr}', got '{message}'"
11313                    )),
11314                    Ok(_) => Err(format!(
11315                        "expected series_notna to fail with error containing '{substr}'"
11316                    )),
11317                },
11318                ResolvedExpected::ErrorAny => {
11319                    if actual.is_err() {
11320                        Ok(())
11321                    } else {
11322                        Err("expected series_notna to fail but operation succeeded".to_owned())
11323                    }
11324                }
11325                _ => {
11326                    Err("expected_series or expected_error is required for series_notna".to_owned())
11327                }
11328            }
11329        }
11330        FixtureOperation::SeriesIsNull => {
11331            let left = require_left_series(fixture)?;
11332            let series = build_series(left)?;
11333            let actual = series.isnull().map_err(|err| err.to_string());
11334            match expected {
11335                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
11336                ResolvedExpected::ErrorContains(substr) => match actual {
11337                    Err(message) if message.contains(&substr) => Ok(()),
11338                    Err(message) => Err(format!(
11339                        "expected series_isnull error containing '{substr}', got '{message}'"
11340                    )),
11341                    Ok(_) => Err(format!(
11342                        "expected series_isnull to fail with error containing '{substr}'"
11343                    )),
11344                },
11345                ResolvedExpected::ErrorAny => {
11346                    if actual.is_err() {
11347                        Ok(())
11348                    } else {
11349                        Err("expected series_isnull to fail but operation succeeded".to_owned())
11350                    }
11351                }
11352                _ => Err(
11353                    "expected_series or expected_error is required for series_isnull".to_owned(),
11354                ),
11355            }
11356        }
11357        FixtureOperation::SeriesNotNull => {
11358            let left = require_left_series(fixture)?;
11359            let series = build_series(left)?;
11360            let actual = series.notnull().map_err(|err| err.to_string());
11361            match expected {
11362                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
11363                ResolvedExpected::ErrorContains(substr) => match actual {
11364                    Err(message) if message.contains(&substr) => Ok(()),
11365                    Err(message) => Err(format!(
11366                        "expected series_notnull error containing '{substr}', got '{message}'"
11367                    )),
11368                    Ok(_) => Err(format!(
11369                        "expected series_notnull to fail with error containing '{substr}'"
11370                    )),
11371                },
11372                ResolvedExpected::ErrorAny => {
11373                    if actual.is_err() {
11374                        Ok(())
11375                    } else {
11376                        Err("expected series_notnull to fail but operation succeeded".to_owned())
11377                    }
11378                }
11379                _ => Err(
11380                    "expected_series or expected_error is required for series_notnull".to_owned(),
11381                ),
11382            }
11383        }
11384        FixtureOperation::SeriesFillNa => {
11385            let left = require_left_series(fixture)?;
11386            let series = build_series(left)?;
11387            let fill_value = fixture
11388                .fill_value
11389                .as_ref()
11390                .ok_or_else(|| "fill_value is required for series_fillna".to_owned())?;
11391            let actual = series.fillna(fill_value).map_err(|err| err.to_string());
11392            match expected {
11393                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
11394                ResolvedExpected::ErrorContains(substr) => match actual {
11395                    Err(message) if message.contains(&substr) => Ok(()),
11396                    Err(message) => Err(format!(
11397                        "expected series_fillna error containing '{substr}', got '{message}'"
11398                    )),
11399                    Ok(_) => Err(format!(
11400                        "expected series_fillna to fail with error containing '{substr}'"
11401                    )),
11402                },
11403                ResolvedExpected::ErrorAny => {
11404                    if actual.is_err() {
11405                        Ok(())
11406                    } else {
11407                        Err("expected series_fillna to fail but operation succeeded".to_owned())
11408                    }
11409                }
11410                _ => Err(
11411                    "expected_series or expected_error is required for series_fillna".to_owned(),
11412                ),
11413            }
11414        }
11415        FixtureOperation::SeriesDropNa => {
11416            let left = require_left_series(fixture)?;
11417            let series = build_series(left)?;
11418            let actual = series.dropna().map_err(|err| err.to_string());
11419            match expected {
11420                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
11421                ResolvedExpected::ErrorContains(substr) => match actual {
11422                    Err(message) if message.contains(&substr) => Ok(()),
11423                    Err(message) => Err(format!(
11424                        "expected series_dropna error containing '{substr}', got '{message}'"
11425                    )),
11426                    Ok(_) => Err(format!(
11427                        "expected series_dropna to fail with error containing '{substr}'"
11428                    )),
11429                },
11430                ResolvedExpected::ErrorAny => {
11431                    if actual.is_err() {
11432                        Ok(())
11433                    } else {
11434                        Err("expected series_dropna to fail but operation succeeded".to_owned())
11435                    }
11436                }
11437                _ => Err(
11438                    "expected_series or expected_error is required for series_dropna".to_owned(),
11439                ),
11440            }
11441        }
11442        FixtureOperation::SeriesCount | FixtureOperation::SeriesNunique => {
11443            let left = require_left_series(fixture)?;
11444            let series = build_series(left)?;
11445            let value = match fixture.operation {
11446                FixtureOperation::SeriesCount => series.count(),
11447                FixtureOperation::SeriesNunique => series.nunique(),
11448                _ => unreachable!(),
11449            };
11450            let actual = Scalar::Int64(value as i64);
11451            match expected {
11452                ResolvedExpected::Scalar(scalar) => {
11453                    compare_scalar(&actual, &scalar, fixture.operation.operation_name())
11454                }
11455                _ => Err(format!(
11456                    "expected_scalar is required for {}",
11457                    fixture.operation.operation_name()
11458                )),
11459            }
11460        }
11461        FixtureOperation::SeriesFirstValidIndex | FixtureOperation::SeriesLastValidIndex => {
11462            let left = require_left_series(fixture)?;
11463            let series = build_series(left)?;
11464            let label_opt = match fixture.operation {
11465                FixtureOperation::SeriesFirstValidIndex => series.first_valid_index(),
11466                FixtureOperation::SeriesLastValidIndex => series.last_valid_index(),
11467                _ => unreachable!(),
11468            };
11469            let actual = optional_index_label_to_scalar(label_opt);
11470            match expected {
11471                ResolvedExpected::Scalar(scalar) => {
11472                    compare_scalar(&actual, &scalar, fixture.operation.operation_name())
11473                }
11474                _ => Err(format!(
11475                    "expected_scalar is required for {}",
11476                    fixture.operation.operation_name()
11477                )),
11478            }
11479        }
11480        FixtureOperation::SeriesIdxmin | FixtureOperation::SeriesIdxmax => {
11481            let actual_result = execute_series_idx_fixture_scalar(fixture);
11482            match (actual_result, expected) {
11483                (Ok(actual), ResolvedExpected::Scalar(scalar)) => {
11484                    compare_scalar(&actual, &scalar, fixture.operation.operation_name())
11485                }
11486                (Err(message), ResolvedExpected::ErrorContains(substr)) => {
11487                    if message.contains(&substr) {
11488                        Ok(())
11489                    } else {
11490                        Err(format!(
11491                            "{}: expected error containing '{}', got '{}'",
11492                            fixture.operation.operation_name(),
11493                            substr,
11494                            message
11495                        ))
11496                    }
11497                }
11498                (Ok(_), ResolvedExpected::ErrorContains(substr)) => Err(format!(
11499                    "{}: expected error containing '{}', but got Ok",
11500                    fixture.operation.operation_name(),
11501                    substr
11502                )),
11503                (Err(message), ResolvedExpected::Scalar(_)) => Err(format!(
11504                    "{}: expected scalar, got error: {}",
11505                    fixture.operation.operation_name(),
11506                    message
11507                )),
11508                (_, _) => Err(format!(
11509                    "expected_scalar or expected_error_contains required for {}",
11510                    fixture.operation.operation_name()
11511                )),
11512            }
11513        }
11514        FixtureOperation::SeriesArgmin | FixtureOperation::SeriesArgmax => {
11515            let actual_result = execute_series_arg_fixture_scalar(fixture);
11516            match (actual_result, expected) {
11517                (Ok(actual), ResolvedExpected::Scalar(scalar)) => {
11518                    compare_scalar(&actual, &scalar, fixture.operation.operation_name())
11519                }
11520                (Err(message), ResolvedExpected::ErrorContains(substr)) => {
11521                    if message.contains(&substr) {
11522                        Ok(())
11523                    } else {
11524                        Err(format!(
11525                            "{}: expected error containing '{}', got '{}'",
11526                            fixture.operation.operation_name(),
11527                            substr,
11528                            message
11529                        ))
11530                    }
11531                }
11532                (Ok(_), ResolvedExpected::ErrorContains(substr)) => Err(format!(
11533                    "{}: expected error containing '{}', but got Ok",
11534                    fixture.operation.operation_name(),
11535                    substr
11536                )),
11537                (Err(message), ResolvedExpected::Scalar(_)) => Err(format!(
11538                    "{}: expected scalar, got error: {}",
11539                    fixture.operation.operation_name(),
11540                    message
11541                )),
11542                (_, _) => Err(format!(
11543                    "expected_scalar or expected_error_contains required for {}",
11544                    fixture.operation.operation_name()
11545                )),
11546            }
11547        }
11548        FixtureOperation::SeriesSearchsorted => {
11549            let actual_result = execute_series_searchsorted_fixture(fixture);
11550            match (actual_result, expected) {
11551                (Ok(actual), ResolvedExpected::Scalar(scalar)) => {
11552                    compare_scalar(&actual, &scalar, fixture.operation.operation_name())
11553                }
11554                (Err(message), ResolvedExpected::ErrorContains(substr)) => {
11555                    if message.contains(&substr) {
11556                        Ok(())
11557                    } else {
11558                        Err(format!(
11559                            "{}: expected error containing '{}', got '{}'",
11560                            fixture.operation.operation_name(),
11561                            substr,
11562                            message
11563                        ))
11564                    }
11565                }
11566                (Ok(_), ResolvedExpected::ErrorContains(substr)) => Err(format!(
11567                    "{}: expected error containing '{}', but got Ok",
11568                    fixture.operation.operation_name(),
11569                    substr
11570                )),
11571                (Err(message), ResolvedExpected::Scalar(_)) => Err(format!(
11572                    "{}: expected scalar, got error: {}",
11573                    fixture.operation.operation_name(),
11574                    message
11575                )),
11576                (_, _) => Err(format!(
11577                    "expected_scalar or expected_error_contains required for {}",
11578                    fixture.operation.operation_name()
11579                )),
11580            }
11581        }
11582        FixtureOperation::SeriesDot => {
11583            let actual_result = execute_series_dot_fixture(fixture);
11584            match (actual_result, expected) {
11585                (Ok(actual), ResolvedExpected::Scalar(scalar)) => {
11586                    compare_scalar(&actual, &scalar, fixture.operation.operation_name())
11587                }
11588                (Err(message), ResolvedExpected::ErrorContains(substr)) => {
11589                    if message.contains(&substr) {
11590                        Ok(())
11591                    } else {
11592                        Err(format!(
11593                            "{}: expected error containing '{}', got '{}'",
11594                            fixture.operation.operation_name(),
11595                            substr,
11596                            message
11597                        ))
11598                    }
11599                }
11600                (Ok(_), ResolvedExpected::ErrorContains(substr)) => Err(format!(
11601                    "{}: expected error containing '{}', but got Ok",
11602                    fixture.operation.operation_name(),
11603                    substr
11604                )),
11605                (Err(message), ResolvedExpected::Scalar(_)) => Err(format!(
11606                    "{}: expected scalar, got error: {}",
11607                    fixture.operation.operation_name(),
11608                    message
11609                )),
11610                (_, _) => Err(format!(
11611                    "expected_scalar or expected_error_contains required for {}",
11612                    fixture.operation.operation_name()
11613                )),
11614            }
11615        }
11616        FixtureOperation::DataFrameCount => {
11617            let frame = build_dataframe(require_frame(fixture)?)
11618                .map_err(|err| format!("frame build failed: {err}"))?;
11619            let actual = frame.count().map_err(|err| err.to_string());
11620            match expected {
11621                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
11622                ResolvedExpected::ErrorContains(substr) => match actual {
11623                    Err(message) if message.contains(&substr) => Ok(()),
11624                    Err(message) => Err(format!(
11625                        "expected dataframe_count error containing '{substr}', got '{message}'"
11626                    )),
11627                    Ok(_) => Err(format!(
11628                        "expected dataframe_count to fail with error containing '{substr}'"
11629                    )),
11630                },
11631                ResolvedExpected::ErrorAny => {
11632                    if actual.is_err() {
11633                        Ok(())
11634                    } else {
11635                        Err("expected dataframe_count to fail but operation succeeded".to_owned())
11636                    }
11637                }
11638                _ => Err(
11639                    "expected_series or expected_error is required for dataframe_count".to_owned(),
11640                ),
11641            }
11642        }
11643        FixtureOperation::DataFrameIdxmin
11644        | FixtureOperation::DataFrameIdxmax
11645        | FixtureOperation::DataFrameSem
11646        | FixtureOperation::DataFrameApplySemAxis0
11647        | FixtureOperation::DataFrameSkew
11648        | FixtureOperation::DataFrameKurtosis
11649        | FixtureOperation::DataFrameProd
11650        | FixtureOperation::DataFrameApplyProdAxis1
11651        | FixtureOperation::DataFrameApplyProductAxis1
11652        | FixtureOperation::DataFrameSum
11653        | FixtureOperation::DataFrameMean
11654        | FixtureOperation::DataFrameStd
11655        | FixtureOperation::DataFrameVar
11656        | FixtureOperation::DataFrameMin
11657        | FixtureOperation::DataFrameMax
11658        | FixtureOperation::DataFrameMedian
11659        | FixtureOperation::DataFrameAny
11660        | FixtureOperation::DataFrameAll
11661        | FixtureOperation::DataFrameNunique
11662        | FixtureOperation::DataFrameApplyNuniqueAxis0
11663        | FixtureOperation::DataFrameQuantile
11664        | FixtureOperation::DataFrameValueCounts
11665        | FixtureOperation::DataFrameMemoryUsage => {
11666            let frame = build_dataframe(require_frame(fixture)?)
11667                .map_err(|err| format!("frame build failed: {err}"))?;
11668            let op_name = fixture.operation.operation_name();
11669            let actual = match fixture.operation {
11670                FixtureOperation::DataFrameIdxmin => frame.idxmin().map_err(|err| err.to_string()),
11671                FixtureOperation::DataFrameIdxmax => frame.idxmax().map_err(|err| err.to_string()),
11672                FixtureOperation::DataFrameSem => match fixture.sem_numeric_only {
11673                    Some(numeric_only) => frame.sem_agg_with_numeric_only(numeric_only),
11674                    None => frame.sem_agg(),
11675                }
11676                .map_err(|err| err.to_string()),
11677                FixtureOperation::DataFrameApplySemAxis0 => {
11678                    execute_dataframe_apply_alias_fixture_operation(fixture)
11679                }
11680                FixtureOperation::DataFrameSkew => match fixture.skew_numeric_only {
11681                    Some(numeric_only) => frame.skew_agg_with_numeric_only(numeric_only),
11682                    None => frame.skew_agg(),
11683                }
11684                .map_err(|err| err.to_string()),
11685                FixtureOperation::DataFrameKurtosis => match fixture.kurtosis_numeric_only {
11686                    Some(numeric_only) => frame.kurtosis_agg_with_numeric_only(numeric_only),
11687                    None => frame.kurtosis_agg(),
11688                }
11689                .map_err(|err| err.to_string()),
11690                FixtureOperation::DataFrameProd => match fixture.prod_numeric_only {
11691                    Some(numeric_only) => frame.prod_with_numeric_only(numeric_only),
11692                    None => frame.prod_agg(),
11693                }
11694                .map_err(|err| err.to_string()),
11695                FixtureOperation::DataFrameApplyProdAxis1
11696                | FixtureOperation::DataFrameApplyProductAxis1 => {
11697                    execute_dataframe_apply_alias_fixture_operation(fixture)
11698                }
11699                FixtureOperation::DataFrameSum => match fixture.sum_numeric_only {
11700                    Some(numeric_only) => frame.sum_with_numeric_only(numeric_only),
11701                    None => frame.sum(),
11702                }
11703                .map_err(|err| err.to_string()),
11704                FixtureOperation::DataFrameMean => match fixture.mean_numeric_only {
11705                    Some(numeric_only) => frame.mean_with_numeric_only(numeric_only),
11706                    None => frame.mean(),
11707                }
11708                .map_err(|err| err.to_string()),
11709                FixtureOperation::DataFrameStd => match fixture.std_numeric_only {
11710                    Some(numeric_only) => frame.std_agg_with_numeric_only(numeric_only),
11711                    None => frame.std_agg(),
11712                }
11713                .map_err(|err| err.to_string()),
11714                FixtureOperation::DataFrameVar => match fixture.var_numeric_only {
11715                    Some(numeric_only) => frame.var_agg_with_numeric_only(numeric_only),
11716                    None => frame.var_agg(),
11717                }
11718                .map_err(|err| err.to_string()),
11719                FixtureOperation::DataFrameMin => match fixture.min_numeric_only {
11720                    Some(numeric_only) => frame.min_agg_with_numeric_only(numeric_only),
11721                    None => frame.min_agg(),
11722                }
11723                .map_err(|err| err.to_string()),
11724                FixtureOperation::DataFrameMax => match fixture.max_numeric_only {
11725                    Some(numeric_only) => frame.max_agg_with_numeric_only(numeric_only),
11726                    None => frame.max_agg(),
11727                }
11728                .map_err(|err| err.to_string()),
11729                FixtureOperation::DataFrameMedian => match fixture.median_numeric_only {
11730                    Some(numeric_only) => frame.median_with_numeric_only(numeric_only),
11731                    None => frame.median_agg(),
11732                }
11733                .map_err(|err| err.to_string()),
11734                FixtureOperation::DataFrameAny => frame.any().map_err(|err| err.to_string()),
11735                FixtureOperation::DataFrameAll => frame.all().map_err(|err| err.to_string()),
11736                FixtureOperation::DataFrameNunique => {
11737                    frame.nunique().map_err(|err| err.to_string())
11738                }
11739                FixtureOperation::DataFrameApplyNuniqueAxis0 => {
11740                    execute_dataframe_apply_alias_fixture_operation(fixture)
11741                }
11742                FixtureOperation::DataFrameQuantile => {
11743                    frame.quantile(0.5).map_err(|err| err.to_string())
11744                }
11745                FixtureOperation::DataFrameValueCounts => {
11746                    frame.value_counts().map_err(|err| err.to_string())
11747                }
11748                FixtureOperation::DataFrameMemoryUsage => frame
11749                    .memory_usage_with_options(
11750                        resolve_memory_usage_index(fixture),
11751                        resolve_memory_usage_deep(fixture),
11752                    )
11753                    .map_err(|err| err.to_string()),
11754                _ => unreachable!(),
11755            };
11756            match expected {
11757                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
11758                ResolvedExpected::ErrorContains(substr) => match actual {
11759                    Err(message) if message.contains(&substr) => Ok(()),
11760                    Err(message) => Err(format!(
11761                        "expected {op_name} error containing '{substr}', got '{message}'"
11762                    )),
11763                    Ok(_) => Err(format!(
11764                        "expected {op_name} to fail with error containing '{substr}'"
11765                    )),
11766                },
11767                ResolvedExpected::ErrorAny => {
11768                    if actual.is_err() {
11769                        Ok(())
11770                    } else {
11771                        Err(format!(
11772                            "expected {op_name} to fail but operation succeeded"
11773                        ))
11774                    }
11775                }
11776                _ => Err(format!(
11777                    "expected_series or expected_error is required for {op_name}"
11778                )),
11779            }
11780        }
11781        FixtureOperation::DataFrameMode
11782        | FixtureOperation::DataFrameCumsum
11783        | FixtureOperation::DataFrameCumprod
11784        | FixtureOperation::DataFrameCummax
11785        | FixtureOperation::DataFrameCummin
11786        | FixtureOperation::DataFrameAstype
11787        | FixtureOperation::DataFrameClip
11788        | FixtureOperation::DataFrameAbs
11789        | FixtureOperation::DataFrameDescribe
11790        | FixtureOperation::DataFrameCorr
11791        | FixtureOperation::DataFrameCov
11792        | FixtureOperation::DataFrameRound
11793        | FixtureOperation::DataFrameBinaryAlias => {
11794            let frame = build_dataframe(require_frame(fixture)?)
11795                .map_err(|err| format!("frame build failed: {err}"))?;
11796            let op_name = fixture.operation.operation_name();
11797            let actual = match fixture.operation {
11798                FixtureOperation::DataFrameMode => frame.mode().map_err(|err| err.to_string()),
11799                FixtureOperation::DataFrameCumsum => frame.cumsum().map_err(|err| err.to_string()),
11800                FixtureOperation::DataFrameCumprod => {
11801                    frame.cumprod().map_err(|err| err.to_string())
11802                }
11803                FixtureOperation::DataFrameCummax => frame.cummax().map_err(|err| err.to_string()),
11804                FixtureOperation::DataFrameCummin => frame.cummin().map_err(|err| err.to_string()),
11805                FixtureOperation::DataFrameAstype => {
11806                    let dtype_spec = fixture
11807                        .constructor_dtype
11808                        .as_deref()
11809                        .ok_or_else(|| "constructor_dtype required for dataframe_astype".to_owned())
11810                        .and_then(parse_constructor_dtype_spec);
11811                    dtype_spec.and_then(|dtype| frame.astype(dtype).map_err(|err| err.to_string()))
11812                }
11813                FixtureOperation::DataFrameClip => frame
11814                    .clip(fixture.clip_lower, fixture.clip_upper)
11815                    .map_err(|err| err.to_string()),
11816                FixtureOperation::DataFrameAbs => frame.abs().map_err(|err| err.to_string()),
11817                FixtureOperation::DataFrameDescribe => {
11818                    frame.describe().map_err(|err| err.to_string())
11819                }
11820                FixtureOperation::DataFrameCorr => execute_dataframe_corr_fixture(&frame, fixture),
11821                FixtureOperation::DataFrameCov => frame.cov().map_err(|err| err.to_string()),
11822                FixtureOperation::DataFrameRound => {
11823                    let decimals = fixture.round_decimals.unwrap_or(0);
11824                    frame.round(decimals).map_err(|err| err.to_string())
11825                }
11826                FixtureOperation::DataFrameBinaryAlias => {
11827                    execute_dataframe_binary_alias_fixture_operation(fixture)
11828                }
11829                _ => unreachable!(),
11830            };
11831            match expected {
11832                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
11833                ResolvedExpected::ErrorContains(substr) => match actual {
11834                    Err(message) if message.contains(&substr) => Ok(()),
11835                    Err(message) => Err(format!(
11836                        "expected {op_name} error containing '{substr}', got '{message}'"
11837                    )),
11838                    Ok(_) => Err(format!(
11839                        "expected {op_name} to fail with error containing '{substr}'"
11840                    )),
11841                },
11842                ResolvedExpected::ErrorAny => {
11843                    if actual.is_err() {
11844                        Ok(())
11845                    } else {
11846                        Err(format!(
11847                            "expected {op_name} to fail but operation succeeded"
11848                        ))
11849                    }
11850                }
11851                _ => Err(format!(
11852                    "expected_frame or expected_error is required for {op_name}"
11853                )),
11854            }
11855        }
11856        FixtureOperation::DataFrameRank => {
11857            let frame = build_dataframe(require_frame(fixture)?)
11858                .map_err(|err| format!("frame build failed: {err}"))?;
11859            let method = fixture.rank_method.as_deref().unwrap_or("average");
11860            let na_option = fixture.rank_na_option.as_deref().unwrap_or("keep");
11861            let ascending = resolve_sort_ascending(fixture);
11862            let axis = resolve_rank_axis(fixture)?;
11863            let pct = resolve_rank_pct(fixture);
11864            let actual = if axis == 1 {
11865                frame.rank_axis1_with_pct(method, ascending, na_option, pct)
11866            } else {
11867                frame.rank_with_pct(method, ascending, na_option, pct)
11868            }
11869            .map_err(|err| err.to_string());
11870            match expected {
11871                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
11872                ResolvedExpected::ErrorContains(substr) => match actual {
11873                    Err(message) if message.contains(&substr) => Ok(()),
11874                    Err(message) => Err(format!(
11875                        "expected dataframe_rank error containing '{substr}', got '{message}'"
11876                    )),
11877                    Ok(_) => Err(format!(
11878                        "expected dataframe_rank to fail with error containing '{substr}'"
11879                    )),
11880                },
11881                ResolvedExpected::ErrorAny => {
11882                    if actual.is_err() {
11883                        Ok(())
11884                    } else {
11885                        Err("expected dataframe_rank to fail but operation succeeded".to_owned())
11886                    }
11887                }
11888                _ => Err(
11889                    "expected_frame or expected_error is required for dataframe_rank".to_owned(),
11890                ),
11891            }
11892        }
11893        FixtureOperation::DataFrameDuplicated => {
11894            let frame = build_dataframe(require_frame(fixture)?)
11895                .map_err(|err| format!("frame build failed: {err}"))?;
11896            let subset = resolve_duplicate_subset(fixture)?;
11897            let keep = resolve_duplicate_keep(fixture)?;
11898            let actual = frame
11899                .duplicated(subset.as_deref(), keep)
11900                .map_err(|err| err.to_string());
11901            match expected {
11902                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
11903                ResolvedExpected::ErrorContains(substr) => match actual {
11904                    Err(message) if message.contains(&substr) => Ok(()),
11905                    Err(message) => Err(format!(
11906                        "expected dataframe_duplicated error containing '{substr}', got '{message}'"
11907                    )),
11908                    Ok(_) => Err(format!(
11909                        "expected dataframe_duplicated to fail with error containing '{substr}'"
11910                    )),
11911                },
11912                ResolvedExpected::ErrorAny => {
11913                    if actual.is_err() {
11914                        Ok(())
11915                    } else {
11916                        Err(
11917                            "expected dataframe_duplicated to fail but operation succeeded"
11918                                .to_owned(),
11919                        )
11920                    }
11921                }
11922                _ => Err(
11923                    "expected_series or expected_error is required for dataframe_duplicated"
11924                        .to_owned(),
11925                ),
11926            }
11927        }
11928        FixtureOperation::SeriesAny => {
11929            let left = require_left_series(fixture)?;
11930            let series = build_series(left)?;
11931            let actual = series.any().map_err(|err| err.to_string());
11932            match expected {
11933                ResolvedExpected::Bool(value) => {
11934                    let actual = actual?;
11935                    if actual == value {
11936                        Ok(())
11937                    } else {
11938                        Err(format!(
11939                            "series_any mismatch: actual={actual}, expected={value}"
11940                        ))
11941                    }
11942                }
11943                ResolvedExpected::ErrorContains(substr) => match actual {
11944                    Err(message) if message.contains(&substr) => Ok(()),
11945                    Err(message) => Err(format!(
11946                        "expected series_any error containing '{substr}', got '{message}'"
11947                    )),
11948                    Ok(_) => Err(format!(
11949                        "expected series_any to fail with error containing '{substr}'"
11950                    )),
11951                },
11952                ResolvedExpected::ErrorAny => {
11953                    if actual.is_err() {
11954                        Ok(())
11955                    } else {
11956                        Err("expected series_any to fail but operation succeeded".to_owned())
11957                    }
11958                }
11959                _ => Err("expected_bool or expected_error is required for series_any".to_owned()),
11960            }
11961        }
11962        FixtureOperation::SeriesAll => {
11963            let left = require_left_series(fixture)?;
11964            let series = build_series(left)?;
11965            let actual = series.all().map_err(|err| err.to_string());
11966            match expected {
11967                ResolvedExpected::Bool(value) => {
11968                    let actual = actual?;
11969                    if actual == value {
11970                        Ok(())
11971                    } else {
11972                        Err(format!(
11973                            "series_all mismatch: actual={actual}, expected={value}"
11974                        ))
11975                    }
11976                }
11977                ResolvedExpected::ErrorContains(substr) => match actual {
11978                    Err(message) if message.contains(&substr) => Ok(()),
11979                    Err(message) => Err(format!(
11980                        "expected series_all error containing '{substr}', got '{message}'"
11981                    )),
11982                    Ok(_) => Err(format!(
11983                        "expected series_all to fail with error containing '{substr}'"
11984                    )),
11985                },
11986                ResolvedExpected::ErrorAny => {
11987                    if actual.is_err() {
11988                        Ok(())
11989                    } else {
11990                        Err("expected series_all to fail but operation succeeded".to_owned())
11991                    }
11992                }
11993                _ => Err("expected_bool or expected_error is required for series_all".to_owned()),
11994            }
11995        }
11996        FixtureOperation::SeriesBool => {
11997            let actual = execute_series_bool_fixture_operation(fixture);
11998            match expected {
11999                ResolvedExpected::Bool(value) => {
12000                    let actual = actual?;
12001                    if actual == value {
12002                        Ok(())
12003                    } else {
12004                        Err(format!(
12005                            "series_bool mismatch: actual={actual}, expected={value}"
12006                        ))
12007                    }
12008                }
12009                ResolvedExpected::ErrorContains(substr) => match actual {
12010                    Err(message) if message.contains(&substr) => Ok(()),
12011                    Err(message) => Err(format!(
12012                        "expected series_bool error containing '{substr}', got '{message}'"
12013                    )),
12014                    Ok(_) => Err(format!(
12015                        "expected series_bool to fail with error containing '{substr}'"
12016                    )),
12017                },
12018                ResolvedExpected::ErrorAny => {
12019                    if actual.is_err() {
12020                        Ok(())
12021                    } else {
12022                        Err("expected series_bool to fail but operation succeeded".to_owned())
12023                    }
12024                }
12025                _ => Err("expected_bool or expected_error is required for series_bool".to_owned()),
12026            }
12027        }
12028        FixtureOperation::SeriesRepeat => {
12029            let actual = execute_series_repeat_fixture_operation(fixture);
12030            match expected {
12031                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
12032                ResolvedExpected::ErrorContains(substr) => match actual {
12033                    Err(message) if message.contains(&substr) => Ok(()),
12034                    Err(message) => Err(format!(
12035                        "expected series_repeat error containing '{substr}', got '{message}'"
12036                    )),
12037                    Ok(_) => Err(format!(
12038                        "expected series_repeat to fail with error containing '{substr}'"
12039                    )),
12040                },
12041                ResolvedExpected::ErrorAny => {
12042                    if actual.is_err() {
12043                        Ok(())
12044                    } else {
12045                        Err("expected series_repeat to fail but operation succeeded".to_owned())
12046                    }
12047                }
12048                _ => Err(
12049                    "expected_series or expected_error is required for series_repeat".to_owned(),
12050                ),
12051            }
12052        }
12053        FixtureOperation::SeriesToNumeric
12054        | FixtureOperation::SeriesConvertDtypes
12055        | FixtureOperation::SeriesAstype
12056        | FixtureOperation::SeriesClip
12057        | FixtureOperation::SeriesAbs
12058        | FixtureOperation::SeriesRound
12059        | FixtureOperation::SeriesCumsum
12060        | FixtureOperation::SeriesCumprod
12061        | FixtureOperation::SeriesCummax
12062        | FixtureOperation::SeriesCummin
12063        | FixtureOperation::SeriesNlargest
12064        | FixtureOperation::SeriesNsmallest
12065        | FixtureOperation::SeriesBetween
12066        | FixtureOperation::SeriesCut
12067        | FixtureOperation::SeriesQcut
12068        | FixtureOperation::SeriesStrLower
12069        | FixtureOperation::SeriesStrUpper
12070        | FixtureOperation::SeriesStrCapitalize
12071        | FixtureOperation::SeriesStrStrip
12072        | FixtureOperation::SeriesStrLen
12073        | FixtureOperation::SeriesStrContains
12074        | FixtureOperation::SeriesStrStartswith
12075        | FixtureOperation::SeriesStrEndswith
12076        | FixtureOperation::SeriesStrReplace
12077        | FixtureOperation::SeriesStrLstrip
12078        | FixtureOperation::SeriesStrRstrip
12079        | FixtureOperation::SeriesStrTitle
12080        | FixtureOperation::SeriesStrSwapcase
12081        | FixtureOperation::SeriesStrZfill
12082        | FixtureOperation::SeriesStrCenter
12083        | FixtureOperation::SeriesStrLjust
12084        | FixtureOperation::SeriesStrRjust
12085        | FixtureOperation::SeriesStrPad
12086        | FixtureOperation::SeriesStrIsdigit
12087        | FixtureOperation::SeriesStrIsalpha
12088        | FixtureOperation::SeriesStrIsalnum
12089        | FixtureOperation::SeriesStrIsspace
12090        | FixtureOperation::SeriesStrIslower
12091        | FixtureOperation::SeriesStrIsupper
12092        | FixtureOperation::SeriesStrIsnumeric
12093        | FixtureOperation::SeriesStrFind
12094        | FixtureOperation::SeriesStrRfind
12095        | FixtureOperation::SeriesStrSlice
12096        | FixtureOperation::SeriesStrGet
12097        | FixtureOperation::SeriesStrRepeat
12098        | FixtureOperation::SeriesStrCount
12099        | FixtureOperation::SeriesStrWrap
12100        | FixtureOperation::SeriesStrNormalize
12101        | FixtureOperation::SeriesStrFullmatch
12102        | FixtureOperation::SeriesStrMatch
12103        | FixtureOperation::SeriesStrRemoveprefix
12104        | FixtureOperation::SeriesStrRemovesuffix
12105        | FixtureOperation::SeriesStrSplitGet
12106        | FixtureOperation::SeriesStrJoin
12107        | FixtureOperation::SeriesStrIsdecimal
12108        | FixtureOperation::SeriesStrIstitle
12109        | FixtureOperation::SeriesStrCasefold
12110        | FixtureOperation::SeriesStrEncode
12111        | FixtureOperation::SeriesStrDecode
12112        | FixtureOperation::SeriesStrTranslate
12113        | FixtureOperation::SeriesStrExpandtabs
12114        | FixtureOperation::SeriesStrIndexOf
12115        | FixtureOperation::SeriesStrRindexOf
12116        | FixtureOperation::SeriesStrSplitCount
12117        | FixtureOperation::SeriesStrRsplitGet
12118        | FixtureOperation::SeriesStrSplitRegexGet
12119        | FixtureOperation::SeriesStrCountMatches
12120        | FixtureOperation::SeriesStrCountLiteral
12121        | FixtureOperation::SeriesStrFindall
12122        | FixtureOperation::SeriesStrContainsAny
12123        | FixtureOperation::SeriesStrStartswithAny
12124        | FixtureOperation::SeriesStrEndswithAny
12125        | FixtureOperation::SeriesDtYear
12126        | FixtureOperation::SeriesDtMonth
12127        | FixtureOperation::SeriesDtDay
12128        | FixtureOperation::SeriesDtHour
12129        | FixtureOperation::SeriesDtMinute
12130        | FixtureOperation::SeriesDtSecond
12131        | FixtureOperation::SeriesDtMicrosecond
12132        | FixtureOperation::SeriesDtNanosecond
12133        | FixtureOperation::SeriesDtDayofweek
12134        | FixtureOperation::SeriesDtQuarter
12135        | FixtureOperation::SeriesDtDayofyear
12136        | FixtureOperation::SeriesDtWeekofyear
12137        | FixtureOperation::SeriesDtIsMonthStart
12138        | FixtureOperation::SeriesDtIsMonthEnd
12139        | FixtureOperation::SeriesDtIsYearStart
12140        | FixtureOperation::SeriesDtIsYearEnd
12141        | FixtureOperation::SeriesDtDate
12142        | FixtureOperation::SeriesDtDaysInMonth
12143        | FixtureOperation::SeriesDtIsLeapYear
12144        | FixtureOperation::SeriesDtIsQuarterStart
12145        | FixtureOperation::SeriesDtIsQuarterEnd
12146        | FixtureOperation::SeriesDtStrftime
12147        | FixtureOperation::SeriesDtTzConvert
12148        | FixtureOperation::SeriesDtTzLocalize
12149        | FixtureOperation::SeriesDtTimetz
12150        | FixtureOperation::SeriesDtToPeriod
12151        | FixtureOperation::SeriesDtFloor
12152        | FixtureOperation::SeriesDtCeil
12153        | FixtureOperation::SeriesDtRound
12154        | FixtureOperation::SeriesDtMonthName
12155        | FixtureOperation::SeriesDtDayName
12156        | FixtureOperation::SeriesDtTotalSeconds
12157        | FixtureOperation::SeriesDtDays
12158        | FixtureOperation::SeriesDtSeconds
12159        | FixtureOperation::SeriesDtMicroseconds
12160        | FixtureOperation::SeriesDtNanoseconds
12161        | FixtureOperation::SeriesDtToTimestamp
12162        | FixtureOperation::SeriesDtToPytimedelta
12163        | FixtureOperation::SeriesDtToPydatetime => {
12164            let actual = execute_series_module_utility_fixture_operation(fixture);
12165            let op_name = fixture.operation.operation_name();
12166            match expected {
12167                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
12168                ResolvedExpected::ErrorContains(substr) => match actual {
12169                    Err(message) if message.contains(&substr) => Ok(()),
12170                    Err(message) => Err(format!(
12171                        "expected {op_name} error containing '{substr}', got '{message}'"
12172                    )),
12173                    Ok(_) => Err(format!(
12174                        "expected {op_name} to fail with error containing '{substr}'"
12175                    )),
12176                },
12177                ResolvedExpected::ErrorAny => {
12178                    if actual.is_err() {
12179                        Ok(())
12180                    } else {
12181                        Err(format!(
12182                            "expected {op_name} to fail but operation succeeded"
12183                        ))
12184                    }
12185                }
12186                _ => Err(format!(
12187                    "expected_series or expected_error is required for {op_name}"
12188                )),
12189            }
12190        }
12191        FixtureOperation::SeriesLoc => {
12192            let left = require_left_series(fixture)?;
12193            let labels = require_loc_labels(fixture)?;
12194            let series = build_series(left)?;
12195            let actual = series.loc(labels).map_err(|err| err.to_string());
12196            match expected {
12197                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
12198                ResolvedExpected::ErrorContains(substr) => match actual {
12199                    Err(message) if message.contains(&substr) => Ok(()),
12200                    Err(message) => Err(format!(
12201                        "expected series_loc error containing '{substr}', got '{message}'"
12202                    )),
12203                    Ok(_) => Err(format!(
12204                        "expected series_loc to fail with error containing '{substr}'"
12205                    )),
12206                },
12207                ResolvedExpected::ErrorAny => {
12208                    if actual.is_err() {
12209                        Ok(())
12210                    } else {
12211                        Err("expected series_loc to fail but operation succeeded".to_owned())
12212                    }
12213                }
12214                _ => Err("expected_series or expected_error is required for series_loc".to_owned()),
12215            }
12216        }
12217        FixtureOperation::SeriesIloc => {
12218            let left = require_left_series(fixture)?;
12219            let positions = require_iloc_positions(fixture)?;
12220            let series = build_series(left)?;
12221            let actual = series.iloc(positions).map_err(|err| err.to_string());
12222            match expected {
12223                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
12224                ResolvedExpected::ErrorContains(substr) => match actual {
12225                    Err(message) if message.contains(&substr) => Ok(()),
12226                    Err(message) => Err(format!(
12227                        "expected series_iloc error containing '{substr}', got '{message}'"
12228                    )),
12229                    Ok(_) => Err(format!(
12230                        "expected series_iloc to fail with error containing '{substr}'"
12231                    )),
12232                },
12233                ResolvedExpected::ErrorAny => {
12234                    if actual.is_err() {
12235                        Ok(())
12236                    } else {
12237                        Err("expected series_iloc to fail but operation succeeded".to_owned())
12238                    }
12239                }
12240                _ => {
12241                    Err("expected_series or expected_error is required for series_iloc".to_owned())
12242                }
12243            }
12244        }
12245        FixtureOperation::SeriesTake => {
12246            let left = require_left_series(fixture)?;
12247            let indices = require_take_indices(fixture)?;
12248            let series = build_series(left)?;
12249            let actual = series.take(indices).map_err(|err| err.to_string());
12250            match expected {
12251                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
12252                ResolvedExpected::ErrorContains(substr) => match actual {
12253                    Err(message) if message.contains(&substr) => Ok(()),
12254                    Err(message) => Err(format!(
12255                        "expected series_take error containing '{substr}', got '{message}'"
12256                    )),
12257                    Ok(_) => Err(format!(
12258                        "expected series_take to fail with error containing '{substr}'"
12259                    )),
12260                },
12261                ResolvedExpected::ErrorAny => {
12262                    if actual.is_err() {
12263                        Ok(())
12264                    } else {
12265                        Err("expected series_take to fail but operation succeeded".to_owned())
12266                    }
12267                }
12268                _ => {
12269                    Err("expected_series or expected_error is required for series_take".to_owned())
12270                }
12271            }
12272        }
12273        FixtureOperation::SeriesXs => {
12274            let actual = execute_series_xs_fixture_operation(fixture);
12275            match expected {
12276                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
12277                ResolvedExpected::ErrorContains(substr) => match actual {
12278                    Err(message) if message.contains(&substr) => Ok(()),
12279                    Err(message) => Err(format!(
12280                        "expected series_xs error containing '{substr}', got '{message}'"
12281                    )),
12282                    Ok(_) => Err(format!(
12283                        "expected series_xs to fail with error containing '{substr}'"
12284                    )),
12285                },
12286                ResolvedExpected::ErrorAny => {
12287                    if actual.is_err() {
12288                        Ok(())
12289                    } else {
12290                        Err("expected series_xs to fail but operation succeeded".to_owned())
12291                    }
12292                }
12293                _ => Err("expected_series or expected_error is required for series_xs".to_owned()),
12294            }
12295        }
12296        FixtureOperation::SeriesAtTime => {
12297            let left = require_left_series(fixture)?;
12298            let time = require_time_value(fixture)?;
12299            let series = build_series(left)?;
12300            let actual = series.at_time(time).map_err(|err| err.to_string());
12301            match expected {
12302                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
12303                ResolvedExpected::ErrorContains(substr) => match actual {
12304                    Err(message) if message.contains(&substr) => Ok(()),
12305                    Err(message) => Err(format!(
12306                        "expected series_at_time error containing '{substr}', got '{message}'"
12307                    )),
12308                    Ok(_) => Err(format!(
12309                        "expected series_at_time to fail with error containing '{substr}'"
12310                    )),
12311                },
12312                ResolvedExpected::ErrorAny => {
12313                    if actual.is_err() {
12314                        Ok(())
12315                    } else {
12316                        Err("expected series_at_time to fail but operation succeeded".to_owned())
12317                    }
12318                }
12319                _ => Err(
12320                    "expected_series or expected_error is required for series_at_time".to_owned(),
12321                ),
12322            }
12323        }
12324        FixtureOperation::SeriesBetweenTime => {
12325            let left = require_left_series(fixture)?;
12326            let start = require_start_time(fixture)?;
12327            let end = require_end_time(fixture)?;
12328            let series = build_series(left)?;
12329            let actual = series
12330                .between_time(start, end)
12331                .map_err(|err| err.to_string());
12332            match expected {
12333                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
12334                ResolvedExpected::ErrorContains(substr) => match actual {
12335                    Err(message) if message.contains(&substr) => Ok(()),
12336                    Err(message) => Err(format!(
12337                        "expected series_between_time error containing '{substr}', got '{message}'"
12338                    )),
12339                    Ok(_) => Err(format!(
12340                        "expected series_between_time to fail with error containing '{substr}'"
12341                    )),
12342                },
12343                ResolvedExpected::ErrorAny => {
12344                    if actual.is_err() {
12345                        Ok(())
12346                    } else {
12347                        Err(
12348                            "expected series_between_time to fail but operation succeeded"
12349                                .to_owned(),
12350                        )
12351                    }
12352                }
12353                _ => Err(
12354                    "expected_series or expected_error is required for series_between_time"
12355                        .to_owned(),
12356                ),
12357            }
12358        }
12359        FixtureOperation::SeriesPartitionDf => {
12360            let actual = execute_dataframe_fixture_operation(fixture);
12361            match expected {
12362                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12363                ResolvedExpected::ErrorContains(substr) => match actual {
12364                    Err(message) if message.contains(&substr) => Ok(()),
12365                    Err(message) => Err(format!(
12366                        "expected series_partition_df error containing '{substr}', got '{message}'"
12367                    )),
12368                    Ok(_) => Err(format!(
12369                        "expected series_partition_df to fail with error containing '{substr}'"
12370                    )),
12371                },
12372                ResolvedExpected::ErrorAny => {
12373                    if actual.is_err() {
12374                        Ok(())
12375                    } else {
12376                        Err(
12377                            "expected series_partition_df to fail but operation succeeded"
12378                                .to_owned(),
12379                        )
12380                    }
12381                }
12382                _ => Err(
12383                    "expected_frame or expected_error is required for series_partition_df"
12384                        .to_owned(),
12385                ),
12386            }
12387        }
12388        FixtureOperation::SeriesRpartitionDf => {
12389            let actual = execute_dataframe_fixture_operation(fixture);
12390            match expected {
12391                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12392                ResolvedExpected::ErrorContains(substr) => match actual {
12393                    Err(message) if message.contains(&substr) => Ok(()),
12394                    Err(message) => Err(format!(
12395                        "expected series_rpartition_df error containing '{substr}', got '{message}'"
12396                    )),
12397                    Ok(_) => Err(format!(
12398                        "expected series_rpartition_df to fail with error containing '{substr}'"
12399                    )),
12400                },
12401                ResolvedExpected::ErrorAny => {
12402                    if actual.is_err() {
12403                        Ok(())
12404                    } else {
12405                        Err(
12406                            "expected series_rpartition_df to fail but operation succeeded"
12407                                .to_owned(),
12408                        )
12409                    }
12410                }
12411                _ => Err(
12412                    "expected_frame or expected_error is required for series_rpartition_df"
12413                        .to_owned(),
12414                ),
12415            }
12416        }
12417        FixtureOperation::SeriesSplitDf => {
12418            let actual = execute_dataframe_fixture_operation(fixture);
12419            match expected {
12420                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12421                ResolvedExpected::ErrorContains(substr) => match actual {
12422                    Err(message) if message.contains(&substr) => Ok(()),
12423                    Err(message) => Err(format!(
12424                        "expected series_split_df error containing '{substr}', got '{message}'"
12425                    )),
12426                    Ok(_) => Err(format!(
12427                        "expected series_split_df to fail with error containing '{substr}'"
12428                    )),
12429                },
12430                ResolvedExpected::ErrorAny => {
12431                    if actual.is_err() {
12432                        Ok(())
12433                    } else {
12434                        Err("expected series_split_df to fail but operation succeeded".to_owned())
12435                    }
12436                }
12437                _ => Err(
12438                    "expected_frame or expected_error is required for series_split_df".to_owned(),
12439                ),
12440            }
12441        }
12442        FixtureOperation::SeriesExtractAll => {
12443            let actual = execute_dataframe_fixture_operation(fixture);
12444            match expected {
12445                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12446                ResolvedExpected::ErrorContains(substr) => match actual {
12447                    Err(message) if message.contains(&substr) => Ok(()),
12448                    Err(message) => Err(format!(
12449                        "expected series_extractall error containing '{substr}', got '{message}'"
12450                    )),
12451                    Ok(_) => Err(format!(
12452                        "expected series_extractall to fail with error containing '{substr}'"
12453                    )),
12454                },
12455                ResolvedExpected::ErrorAny => {
12456                    if actual.is_err() {
12457                        Ok(())
12458                    } else {
12459                        Err("expected series_extractall to fail but operation succeeded".to_owned())
12460                    }
12461                }
12462                _ => Err(
12463                    "expected_frame or expected_error is required for series_extractall".to_owned(),
12464                ),
12465            }
12466        }
12467        FixtureOperation::SeriesToFrame => {
12468            let actual = execute_dataframe_fixture_operation(fixture);
12469            match expected {
12470                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12471                ResolvedExpected::ErrorContains(substr) => match actual {
12472                    Err(message) if message.contains(&substr) => Ok(()),
12473                    Err(message) => Err(format!(
12474                        "expected series_to_frame error containing '{substr}', got '{message}'"
12475                    )),
12476                    Ok(_) => Err(format!(
12477                        "expected series_to_frame to fail with error containing '{substr}'"
12478                    )),
12479                },
12480                ResolvedExpected::ErrorAny => {
12481                    if actual.is_err() {
12482                        Ok(())
12483                    } else {
12484                        Err("expected series_to_frame to fail but operation succeeded".to_owned())
12485                    }
12486                }
12487                _ => Err(
12488                    "expected_frame or expected_error is required for series_to_frame".to_owned(),
12489                ),
12490            }
12491        }
12492        FixtureOperation::SeriesExtractDf => {
12493            let actual = execute_dataframe_fixture_operation(fixture);
12494            match expected {
12495                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12496                ResolvedExpected::ErrorContains(substr) => match actual {
12497                    Err(message) if message.contains(&substr) => Ok(()),
12498                    Err(message) => Err(format!(
12499                        "expected series_extract_df error containing '{substr}', got '{message}'"
12500                    )),
12501                    Ok(_) => Err(format!(
12502                        "expected series_extract_df to fail with error containing '{substr}'"
12503                    )),
12504                },
12505                ResolvedExpected::ErrorAny => {
12506                    if actual.is_err() {
12507                        Ok(())
12508                    } else {
12509                        Err("expected series_extract_df to fail but operation succeeded".to_owned())
12510                    }
12511                }
12512                _ => Err(
12513                    "expected_frame or expected_error is required for series_extract_df".to_owned(),
12514                ),
12515            }
12516        }
12517        FixtureOperation::DataFrameLoc => {
12518            let frame = require_frame(fixture)?;
12519            let labels = require_loc_labels(fixture)?;
12520            let frame = build_dataframe(frame)?;
12521            let actual = if frame.row_multiindex().is_some() {
12522                frame
12523                    .loc_tuple_with_columns(labels, fixture.column_order.as_deref())
12524                    .map_err(|err| err.to_string())
12525            } else {
12526                frame
12527                    .loc_with_columns(labels, fixture.column_order.as_deref())
12528                    .map_err(|err| err.to_string())
12529            };
12530            match expected {
12531                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12532                ResolvedExpected::ErrorContains(substr) => match actual {
12533                    Err(message) if message.contains(&substr) => Ok(()),
12534                    Err(message) => Err(format!(
12535                        "expected dataframe_loc error containing '{substr}', got '{message}'"
12536                    )),
12537                    Ok(_) => Err(format!(
12538                        "expected dataframe_loc to fail with error containing '{substr}'"
12539                    )),
12540                },
12541                ResolvedExpected::ErrorAny => {
12542                    if actual.is_err() {
12543                        Ok(())
12544                    } else {
12545                        Err("expected dataframe_loc to fail but operation succeeded".to_owned())
12546                    }
12547                }
12548                _ => {
12549                    Err("expected_frame or expected_error is required for dataframe_loc".to_owned())
12550                }
12551            }
12552        }
12553        FixtureOperation::DataFrameIdentity => {
12554            let frame = build_dataframe(require_frame(fixture)?)?;
12555            match expected {
12556                ResolvedExpected::Frame(frame_expected) => {
12557                    compare_dataframe_expected(&frame, &frame_expected)
12558                }
12559                ResolvedExpected::ErrorContains(substr) => Err(format!(
12560                    "expected dataframe_identity error containing '{substr}', but operation succeeded"
12561                )),
12562                ResolvedExpected::ErrorAny => {
12563                    Err("expected dataframe_identity to fail but operation succeeded".to_owned())
12564                }
12565                _ => Err(
12566                    "expected_frame or expected_error is required for dataframe_identity"
12567                        .to_owned(),
12568                ),
12569            }
12570        }
12571        FixtureOperation::DataFrameIloc => {
12572            let frame = require_frame(fixture)?;
12573            let positions = require_iloc_positions(fixture)?;
12574            let frame = build_dataframe(frame)?;
12575            let actual = frame
12576                .iloc_with_columns(positions, fixture.column_order.as_deref())
12577                .map_err(|err| err.to_string());
12578            match expected {
12579                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12580                ResolvedExpected::ErrorContains(substr) => match actual {
12581                    Err(message) if message.contains(&substr) => Ok(()),
12582                    Err(message) => Err(format!(
12583                        "expected dataframe_iloc error containing '{substr}', got '{message}'"
12584                    )),
12585                    Ok(_) => Err(format!(
12586                        "expected dataframe_iloc to fail with error containing '{substr}'"
12587                    )),
12588                },
12589                ResolvedExpected::ErrorAny => {
12590                    if actual.is_err() {
12591                        Ok(())
12592                    } else {
12593                        Err("expected dataframe_iloc to fail but operation succeeded".to_owned())
12594                    }
12595                }
12596                _ => Err(
12597                    "expected_frame or expected_error is required for dataframe_iloc".to_owned(),
12598                ),
12599            }
12600        }
12601        FixtureOperation::DataFrameTake => {
12602            let actual = execute_dataframe_fixture_operation(fixture);
12603            match expected {
12604                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12605                ResolvedExpected::ErrorContains(substr) => match actual {
12606                    Err(message) if message.contains(&substr) => Ok(()),
12607                    Err(message) => Err(format!(
12608                        "expected dataframe_take error containing '{substr}', got '{message}'"
12609                    )),
12610                    Ok(_) => Err(format!(
12611                        "expected dataframe_take to fail with error containing '{substr}'"
12612                    )),
12613                },
12614                ResolvedExpected::ErrorAny => {
12615                    if actual.is_err() {
12616                        Ok(())
12617                    } else {
12618                        Err("expected dataframe_take to fail but operation succeeded".to_owned())
12619                    }
12620                }
12621                _ => Err(
12622                    "expected_frame or expected_error is required for dataframe_take".to_owned(),
12623                ),
12624            }
12625        }
12626        FixtureOperation::DataFrameFilter => {
12627            let actual = execute_dataframe_fixture_operation(fixture);
12628            match expected {
12629                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12630                ResolvedExpected::ErrorContains(substr) => match actual {
12631                    Err(message) if message.contains(&substr) => Ok(()),
12632                    Err(message) => Err(format!(
12633                        "expected dataframe_filter error containing '{substr}', got '{message}'"
12634                    )),
12635                    Ok(_) => Err(format!(
12636                        "expected dataframe_filter to fail with error containing '{substr}'"
12637                    )),
12638                },
12639                ResolvedExpected::ErrorAny => {
12640                    if actual.is_err() {
12641                        Ok(())
12642                    } else {
12643                        Err("expected dataframe_filter to fail but operation succeeded".to_owned())
12644                    }
12645                }
12646                _ => Err(
12647                    "expected_frame or expected_error is required for dataframe_filter".to_owned(),
12648                ),
12649            }
12650        }
12651        FixtureOperation::DataFrameXs => {
12652            let actual = execute_dataframe_fixture_operation(fixture);
12653            match expected {
12654                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12655                ResolvedExpected::ErrorContains(substr) => match actual {
12656                    Err(message) if message.contains(&substr) => Ok(()),
12657                    Err(message) => Err(format!(
12658                        "expected dataframe_xs error containing '{substr}', got '{message}'"
12659                    )),
12660                    Ok(_) => Err(format!(
12661                        "expected dataframe_xs to fail with error containing '{substr}'"
12662                    )),
12663                },
12664                ResolvedExpected::ErrorAny => {
12665                    if actual.is_err() {
12666                        Ok(())
12667                    } else {
12668                        Err("expected dataframe_xs to fail but operation succeeded".to_owned())
12669                    }
12670                }
12671                _ => {
12672                    Err("expected_frame or expected_error is required for dataframe_xs".to_owned())
12673                }
12674            }
12675        }
12676        FixtureOperation::DataFrameGroupByIdxMin => {
12677            let actual = execute_dataframe_fixture_operation(fixture);
12678            match expected {
12679                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12680                ResolvedExpected::ErrorContains(substr) => match actual {
12681                    Err(message) if message.contains(&substr) => Ok(()),
12682                    Err(message) => Err(format!(
12683                        "expected dataframe_groupby_idxmin error containing '{substr}', got '{message}'"
12684                    )),
12685                    Ok(_) => Err(format!(
12686                        "expected dataframe_groupby_idxmin to fail with error containing '{substr}'"
12687                    )),
12688                },
12689                ResolvedExpected::ErrorAny => {
12690                    if actual.is_err() {
12691                        Ok(())
12692                    } else {
12693                        Err(
12694                            "expected dataframe_groupby_idxmin to fail but operation succeeded"
12695                                .to_owned(),
12696                        )
12697                    }
12698                }
12699                _ => Err(
12700                    "expected_frame or expected_error is required for dataframe_groupby_idxmin"
12701                        .to_owned(),
12702                ),
12703            }
12704        }
12705        FixtureOperation::DataFrameGroupBySum => {
12706            let actual = execute_dataframe_fixture_operation(fixture);
12707            match expected {
12708                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12709                ResolvedExpected::ErrorContains(substr) => match actual {
12710                    Err(message) if message.contains(&substr) => Ok(()),
12711                    Err(message) => Err(format!(
12712                        "expected dataframe_groupby_sum error containing '{substr}', got '{message}'"
12713                    )),
12714                    Ok(_) => Err(format!(
12715                        "expected dataframe_groupby_sum to fail with error containing '{substr}'"
12716                    )),
12717                },
12718                ResolvedExpected::ErrorAny => {
12719                    if actual.is_err() {
12720                        Ok(())
12721                    } else {
12722                        Err(
12723                            "expected dataframe_groupby_sum to fail but operation succeeded"
12724                                .to_owned(),
12725                        )
12726                    }
12727                }
12728                _ => Err(
12729                    "expected_frame or expected_error is required for dataframe_groupby_sum"
12730                        .to_owned(),
12731                ),
12732            }
12733        }
12734        FixtureOperation::DataFrameGroupByAggMulti => {
12735            let actual = execute_dataframe_fixture_operation(fixture);
12736            match expected {
12737                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12738                ResolvedExpected::ErrorContains(substr) => match actual {
12739                    Err(message) if message.contains(&substr) => Ok(()),
12740                    Err(message) => Err(format!(
12741                        "expected dataframe_groupby_agg_multi error containing '{substr}', got '{message}'"
12742                    )),
12743                    Ok(_) => Err(format!(
12744                        "expected dataframe_groupby_agg_multi to fail with error containing '{substr}'"
12745                    )),
12746                },
12747                ResolvedExpected::ErrorAny => {
12748                    if actual.is_err() {
12749                        Ok(())
12750                    } else {
12751                        Err(
12752                            "expected dataframe_groupby_agg_multi to fail but operation succeeded"
12753                                .to_owned(),
12754                        )
12755                    }
12756                }
12757                _ => Err(
12758                    "expected_frame or expected_error is required for dataframe_groupby_agg_multi"
12759                        .to_owned(),
12760                ),
12761            }
12762        }
12763        FixtureOperation::DataFrameGroupByIdxMax => {
12764            let actual = execute_dataframe_fixture_operation(fixture);
12765            match expected {
12766                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12767                ResolvedExpected::ErrorContains(substr) => match actual {
12768                    Err(message) if message.contains(&substr) => Ok(()),
12769                    Err(message) => Err(format!(
12770                        "expected dataframe_groupby_idxmax error containing '{substr}', got '{message}'"
12771                    )),
12772                    Ok(_) => Err(format!(
12773                        "expected dataframe_groupby_idxmax to fail with error containing '{substr}'"
12774                    )),
12775                },
12776                ResolvedExpected::ErrorAny => {
12777                    if actual.is_err() {
12778                        Ok(())
12779                    } else {
12780                        Err(
12781                            "expected dataframe_groupby_idxmax to fail but operation succeeded"
12782                                .to_owned(),
12783                        )
12784                    }
12785                }
12786                _ => Err(
12787                    "expected_frame or expected_error is required for dataframe_groupby_idxmax"
12788                        .to_owned(),
12789                ),
12790            }
12791        }
12792        FixtureOperation::DataFrameGroupByAny => {
12793            let actual = execute_dataframe_fixture_operation(fixture);
12794            match expected {
12795                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12796                ResolvedExpected::ErrorContains(substr) => match actual {
12797                    Err(message) if message.contains(&substr) => Ok(()),
12798                    Err(message) => Err(format!(
12799                        "expected dataframe_groupby_any error containing '{substr}', got '{message}'"
12800                    )),
12801                    Ok(_) => Err(format!(
12802                        "expected dataframe_groupby_any to fail with error containing '{substr}'"
12803                    )),
12804                },
12805                ResolvedExpected::ErrorAny => {
12806                    if actual.is_err() {
12807                        Ok(())
12808                    } else {
12809                        Err(
12810                            "expected dataframe_groupby_any to fail but operation succeeded"
12811                                .to_owned(),
12812                        )
12813                    }
12814                }
12815                _ => Err(
12816                    "expected_frame or expected_error is required for dataframe_groupby_any"
12817                        .to_owned(),
12818                ),
12819            }
12820        }
12821        FixtureOperation::DataFrameGroupByAll => {
12822            let actual = execute_dataframe_fixture_operation(fixture);
12823            match expected {
12824                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12825                ResolvedExpected::ErrorContains(substr) => match actual {
12826                    Err(message) if message.contains(&substr) => Ok(()),
12827                    Err(message) => Err(format!(
12828                        "expected dataframe_groupby_all error containing '{substr}', got '{message}'"
12829                    )),
12830                    Ok(_) => Err(format!(
12831                        "expected dataframe_groupby_all to fail with error containing '{substr}'"
12832                    )),
12833                },
12834                ResolvedExpected::ErrorAny => {
12835                    if actual.is_err() {
12836                        Ok(())
12837                    } else {
12838                        Err(
12839                            "expected dataframe_groupby_all to fail but operation succeeded"
12840                                .to_owned(),
12841                        )
12842                    }
12843                }
12844                _ => Err(
12845                    "expected_frame or expected_error is required for dataframe_groupby_all"
12846                        .to_owned(),
12847                ),
12848            }
12849        }
12850        FixtureOperation::DataFrameGroupByGetGroup => {
12851            let actual = execute_dataframe_fixture_operation(fixture);
12852            match expected {
12853                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12854                ResolvedExpected::ErrorContains(substr) => match actual {
12855                    Err(message) if message.contains(&substr) => Ok(()),
12856                    Err(message) => Err(format!(
12857                        "expected dataframe_groupby_get_group error containing '{substr}', got '{message}'"
12858                    )),
12859                    Ok(_) => Err(format!(
12860                        "expected dataframe_groupby_get_group to fail with error containing '{substr}'"
12861                    )),
12862                },
12863                ResolvedExpected::ErrorAny => {
12864                    if actual.is_err() {
12865                        Ok(())
12866                    } else {
12867                        Err(
12868                            "expected dataframe_groupby_get_group to fail but operation succeeded"
12869                                .to_owned(),
12870                        )
12871                    }
12872                }
12873                _ => Err(
12874                    "expected_frame or expected_error is required for dataframe_groupby_get_group"
12875                        .to_owned(),
12876                ),
12877            }
12878        }
12879        FixtureOperation::DataFrameGroupByFfill => {
12880            let actual = execute_dataframe_fixture_operation(fixture);
12881            match expected {
12882                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12883                ResolvedExpected::ErrorContains(substr) => match actual {
12884                    Err(message) if message.contains(&substr) => Ok(()),
12885                    Err(message) => Err(format!(
12886                        "expected dataframe_groupby_ffill error containing '{substr}', got '{message}'"
12887                    )),
12888                    Ok(_) => Err(format!(
12889                        "expected dataframe_groupby_ffill to fail with error containing '{substr}'"
12890                    )),
12891                },
12892                ResolvedExpected::ErrorAny => {
12893                    if actual.is_err() {
12894                        Ok(())
12895                    } else {
12896                        Err(
12897                            "expected dataframe_groupby_ffill to fail but operation succeeded"
12898                                .to_owned(),
12899                        )
12900                    }
12901                }
12902                _ => Err(
12903                    "expected_frame or expected_error is required for dataframe_groupby_ffill"
12904                        .to_owned(),
12905                ),
12906            }
12907        }
12908        FixtureOperation::DataFrameGroupByBfill => {
12909            let actual = execute_dataframe_fixture_operation(fixture);
12910            match expected {
12911                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12912                ResolvedExpected::ErrorContains(substr) => match actual {
12913                    Err(message) if message.contains(&substr) => Ok(()),
12914                    Err(message) => Err(format!(
12915                        "expected dataframe_groupby_bfill error containing '{substr}', got '{message}'"
12916                    )),
12917                    Ok(_) => Err(format!(
12918                        "expected dataframe_groupby_bfill to fail with error containing '{substr}'"
12919                    )),
12920                },
12921                ResolvedExpected::ErrorAny => {
12922                    if actual.is_err() {
12923                        Ok(())
12924                    } else {
12925                        Err(
12926                            "expected dataframe_groupby_bfill to fail but operation succeeded"
12927                                .to_owned(),
12928                        )
12929                    }
12930                }
12931                _ => Err(
12932                    "expected_frame or expected_error is required for dataframe_groupby_bfill"
12933                        .to_owned(),
12934                ),
12935            }
12936        }
12937        FixtureOperation::DataFrameGroupBySem => {
12938            let actual = execute_dataframe_fixture_operation(fixture);
12939            match expected {
12940                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12941                ResolvedExpected::ErrorContains(substr) => match actual {
12942                    Err(message) if message.contains(&substr) => Ok(()),
12943                    Err(message) => Err(format!(
12944                        "expected dataframe_groupby_sem error containing '{substr}', got '{message}'"
12945                    )),
12946                    Ok(_) => Err(format!(
12947                        "expected dataframe_groupby_sem to fail with error containing '{substr}'"
12948                    )),
12949                },
12950                ResolvedExpected::ErrorAny => {
12951                    if actual.is_err() {
12952                        Ok(())
12953                    } else {
12954                        Err(
12955                            "expected dataframe_groupby_sem to fail but operation succeeded"
12956                                .to_owned(),
12957                        )
12958                    }
12959                }
12960                _ => Err(
12961                    "expected_frame or expected_error is required for dataframe_groupby_sem"
12962                        .to_owned(),
12963                ),
12964            }
12965        }
12966        FixtureOperation::DataFrameGroupBySkew => {
12967            let actual = execute_dataframe_fixture_operation(fixture);
12968            match expected {
12969                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12970                ResolvedExpected::ErrorContains(substr) => match actual {
12971                    Err(message) if message.contains(&substr) => Ok(()),
12972                    Err(message) => Err(format!(
12973                        "expected dataframe_groupby_skew error containing '{substr}', got '{message}'"
12974                    )),
12975                    Ok(_) => Err(format!(
12976                        "expected dataframe_groupby_skew to fail with error containing '{substr}'"
12977                    )),
12978                },
12979                ResolvedExpected::ErrorAny => {
12980                    if actual.is_err() {
12981                        Ok(())
12982                    } else {
12983                        Err(
12984                            "expected dataframe_groupby_skew to fail but operation succeeded"
12985                                .to_owned(),
12986                        )
12987                    }
12988                }
12989                _ => Err(
12990                    "expected_frame or expected_error is required for dataframe_groupby_skew"
12991                        .to_owned(),
12992                ),
12993            }
12994        }
12995        FixtureOperation::DataFrameGroupByKurtosis => {
12996            let actual = execute_dataframe_fixture_operation(fixture);
12997            match expected {
12998                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
12999                ResolvedExpected::ErrorContains(substr) => match actual {
13000                    Err(message) if message.contains(&substr) => Ok(()),
13001                    Err(message) => Err(format!(
13002                        "expected dataframe_groupby_kurtosis error containing '{substr}', got '{message}'"
13003                    )),
13004                    Ok(_) => Err(format!(
13005                        "expected dataframe_groupby_kurtosis to fail with error containing '{substr}'"
13006                    )),
13007                },
13008                ResolvedExpected::ErrorAny => {
13009                    if actual.is_err() {
13010                        Ok(())
13011                    } else {
13012                        Err(
13013                            "expected dataframe_groupby_kurtosis to fail but operation succeeded"
13014                                .to_owned(),
13015                        )
13016                    }
13017                }
13018                _ => Err(
13019                    "expected_frame or expected_error is required for dataframe_groupby_kurtosis"
13020                        .to_owned(),
13021                ),
13022            }
13023        }
13024        FixtureOperation::DataFrameGroupByOhlc => {
13025            let actual = execute_dataframe_fixture_operation(fixture);
13026            match expected {
13027                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
13028                ResolvedExpected::ErrorContains(substr) => match actual {
13029                    Err(message) if message.contains(&substr) => Ok(()),
13030                    Err(message) => Err(format!(
13031                        "expected dataframe_groupby_ohlc error containing '{substr}', got '{message}'"
13032                    )),
13033                    Ok(_) => Err(format!(
13034                        "expected dataframe_groupby_ohlc to fail with error containing '{substr}'"
13035                    )),
13036                },
13037                ResolvedExpected::ErrorAny => {
13038                    if actual.is_err() {
13039                        Ok(())
13040                    } else {
13041                        Err(
13042                            "expected dataframe_groupby_ohlc to fail but operation succeeded"
13043                                .to_owned(),
13044                        )
13045                    }
13046                }
13047                _ => Err(
13048                    "expected_frame or expected_error is required for dataframe_groupby_ohlc"
13049                        .to_owned(),
13050                ),
13051            }
13052        }
13053        FixtureOperation::DataFrameGroupByResampleMin
13054        | FixtureOperation::DataFrameGroupByResampleMax
13055        | FixtureOperation::DataFrameGroupByResampleCount
13056        | FixtureOperation::DataFrameGroupByResampleFirst
13057        | FixtureOperation::DataFrameGroupByResampleLast => {
13058            let op_name = fixture.operation.operation_name();
13059            let actual = execute_dataframe_groupby_resample_fixture_operation(fixture);
13060            match expected {
13061                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
13062                ResolvedExpected::ErrorContains(substr) => match actual {
13063                    Err(message) if message.contains(&substr) => Ok(()),
13064                    Err(message) => Err(format!(
13065                        "expected {op_name} error containing '{substr}', got '{message}'"
13066                    )),
13067                    Ok(_) => Err(format!(
13068                        "expected {op_name} to fail with error containing '{substr}'"
13069                    )),
13070                },
13071                ResolvedExpected::ErrorAny => {
13072                    if actual.is_err() {
13073                        Ok(())
13074                    } else {
13075                        Err(format!(
13076                            "expected {op_name} to fail but operation succeeded"
13077                        ))
13078                    }
13079                }
13080                _ => Err(format!(
13081                    "expected_frame or expected_error is required for {op_name}"
13082                )),
13083            }
13084        }
13085        FixtureOperation::DataFrameGroupByRollingMean
13086        | FixtureOperation::DataFrameGroupByRollingSum
13087        | FixtureOperation::DataFrameGroupByRollingMin
13088        | FixtureOperation::DataFrameGroupByRollingMax
13089        | FixtureOperation::DataFrameGroupByRollingCount
13090        | FixtureOperation::DataFrameGroupByRollingStd
13091        | FixtureOperation::DataFrameGroupByRollingVar => {
13092            let op_name = fixture.operation.operation_name();
13093            let actual = execute_dataframe_groupby_rolling_fixture_operation(fixture);
13094            match expected {
13095                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
13096                ResolvedExpected::ErrorContains(substr) => match actual {
13097                    Err(message) if message.contains(&substr) => Ok(()),
13098                    Err(message) => Err(format!(
13099                        "expected {op_name} error containing '{substr}', got '{message}'"
13100                    )),
13101                    Ok(_) => Err(format!(
13102                        "expected {op_name} to fail with error containing '{substr}'"
13103                    )),
13104                },
13105                ResolvedExpected::ErrorAny => {
13106                    if actual.is_err() {
13107                        Ok(())
13108                    } else {
13109                        Err(format!(
13110                            "expected {op_name} to fail but operation succeeded"
13111                        ))
13112                    }
13113                }
13114                _ => Err(format!(
13115                    "expected_frame or expected_error is required for {op_name}"
13116                )),
13117            }
13118        }
13119        FixtureOperation::DataFrameGroupByCumcount => {
13120            let actual = execute_dataframe_groupby_series_fixture_operation(fixture, false);
13121            match expected {
13122                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
13123                ResolvedExpected::ErrorContains(substr) => match actual {
13124                    Err(message) if message.contains(&substr) => Ok(()),
13125                    Err(message) => Err(format!(
13126                        "expected dataframe_groupby_cumcount error containing '{substr}', got '{message}'"
13127                    )),
13128                    Ok(_) => Err(format!(
13129                        "expected dataframe_groupby_cumcount to fail with error containing '{substr}'"
13130                    )),
13131                },
13132                ResolvedExpected::ErrorAny => {
13133                    if actual.is_err() {
13134                        Ok(())
13135                    } else {
13136                        Err(
13137                            "expected dataframe_groupby_cumcount to fail but operation succeeded"
13138                                .to_owned(),
13139                        )
13140                    }
13141                }
13142                _ => Err(
13143                    "expected_series or expected_error is required for dataframe_groupby_cumcount"
13144                        .to_owned(),
13145                ),
13146            }
13147        }
13148        FixtureOperation::DataFrameGroupByNgroup => {
13149            let actual = execute_dataframe_groupby_series_fixture_operation(fixture, true);
13150            match expected {
13151                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
13152                ResolvedExpected::ErrorContains(substr) => match actual {
13153                    Err(message) if message.contains(&substr) => Ok(()),
13154                    Err(message) => Err(format!(
13155                        "expected dataframe_groupby_ngroup error containing '{substr}', got '{message}'"
13156                    )),
13157                    Ok(_) => Err(format!(
13158                        "expected dataframe_groupby_ngroup to fail with error containing '{substr}'"
13159                    )),
13160                },
13161                ResolvedExpected::ErrorAny => {
13162                    if actual.is_err() {
13163                        Ok(())
13164                    } else {
13165                        Err(
13166                            "expected dataframe_groupby_ngroup to fail but operation succeeded"
13167                                .to_owned(),
13168                        )
13169                    }
13170                }
13171                _ => Err(
13172                    "expected_series or expected_error is required for dataframe_groupby_ngroup"
13173                        .to_owned(),
13174                ),
13175            }
13176        }
13177        FixtureOperation::DataFrameAsof => {
13178            let actual = execute_dataframe_asof_fixture_operation(fixture);
13179            match expected {
13180                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
13181                ResolvedExpected::ErrorContains(substr) => match actual {
13182                    Err(message) if message.contains(&substr) => Ok(()),
13183                    Err(message) => Err(format!(
13184                        "expected dataframe_asof error containing '{substr}', got '{message}'"
13185                    )),
13186                    Ok(_) => Err(format!(
13187                        "expected dataframe_asof to fail with error containing '{substr}'"
13188                    )),
13189                },
13190                ResolvedExpected::ErrorAny => {
13191                    if actual.is_err() {
13192                        Ok(())
13193                    } else {
13194                        Err("expected dataframe_asof to fail but operation succeeded".to_owned())
13195                    }
13196                }
13197                _ => Err(
13198                    "expected_series or expected_error is required for dataframe_asof".to_owned(),
13199                ),
13200            }
13201        }
13202        FixtureOperation::DataFrameAtTime => {
13203            let actual = execute_dataframe_fixture_operation(fixture);
13204            match expected {
13205                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
13206                ResolvedExpected::ErrorContains(substr) => match actual {
13207                    Err(message) if message.contains(&substr) => Ok(()),
13208                    Err(message) => Err(format!(
13209                        "expected dataframe_at_time error containing '{substr}', got '{message}'"
13210                    )),
13211                    Ok(_) => Err(format!(
13212                        "expected dataframe_at_time to fail with error containing '{substr}'"
13213                    )),
13214                },
13215                ResolvedExpected::ErrorAny => {
13216                    if actual.is_err() {
13217                        Ok(())
13218                    } else {
13219                        Err("expected dataframe_at_time to fail but operation succeeded".to_owned())
13220                    }
13221                }
13222                _ => Err(
13223                    "expected_frame or expected_error is required for dataframe_at_time".to_owned(),
13224                ),
13225            }
13226        }
13227        FixtureOperation::DataFrameBetweenTime => {
13228            let actual = execute_dataframe_fixture_operation(fixture);
13229            match expected {
13230                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
13231                ResolvedExpected::ErrorContains(substr) => match actual {
13232                    Err(message) if message.contains(&substr) => Ok(()),
13233                    Err(message) => Err(format!(
13234                        "expected dataframe_between_time error containing '{substr}', got '{message}'"
13235                    )),
13236                    Ok(_) => Err(format!(
13237                        "expected dataframe_between_time to fail with error containing '{substr}'"
13238                    )),
13239                },
13240                ResolvedExpected::ErrorAny => {
13241                    if actual.is_err() {
13242                        Ok(())
13243                    } else {
13244                        Err(
13245                            "expected dataframe_between_time to fail but operation succeeded"
13246                                .to_owned(),
13247                        )
13248                    }
13249                }
13250                _ => Err(
13251                    "expected_frame or expected_error is required for dataframe_between_time"
13252                        .to_owned(),
13253                ),
13254            }
13255        }
13256        FixtureOperation::DataFrameBool => {
13257            let actual = execute_dataframe_bool_fixture_operation(fixture);
13258            match expected {
13259                ResolvedExpected::Bool(value) => {
13260                    let actual = actual?;
13261                    if actual == value {
13262                        Ok(())
13263                    } else {
13264                        Err(format!(
13265                            "dataframe_bool mismatch: actual={actual}, expected={value}"
13266                        ))
13267                    }
13268                }
13269                ResolvedExpected::ErrorContains(substr) => match actual {
13270                    Err(message) if message.contains(&substr) => Ok(()),
13271                    Err(message) => Err(format!(
13272                        "expected dataframe_bool error containing '{substr}', got '{message}'"
13273                    )),
13274                    Ok(_) => Err(format!(
13275                        "expected dataframe_bool to fail with error containing '{substr}'"
13276                    )),
13277                },
13278                ResolvedExpected::ErrorAny => {
13279                    if actual.is_err() {
13280                        Ok(())
13281                    } else {
13282                        Err("expected dataframe_bool to fail but operation succeeded".to_owned())
13283                    }
13284                }
13285                _ => {
13286                    Err("expected_bool or expected_error is required for dataframe_bool".to_owned())
13287                }
13288            }
13289        }
13290        FixtureOperation::DataFrameHead => {
13291            let frame = require_frame(fixture)?;
13292            let n = fixture
13293                .head_n
13294                .ok_or_else(|| "head_n is required for dataframe_head".to_owned())?;
13295            let frame = build_dataframe(frame)?;
13296            let actual = frame.head(n).map_err(|err| err.to_string());
13297            match expected {
13298                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
13299                ResolvedExpected::ErrorContains(substr) => match actual {
13300                    Err(message) if message.contains(&substr) => Ok(()),
13301                    Err(message) => Err(format!(
13302                        "expected dataframe_head error containing '{substr}', got '{message}'"
13303                    )),
13304                    Ok(_) => Err(format!(
13305                        "expected dataframe_head to fail with error containing '{substr}'"
13306                    )),
13307                },
13308                ResolvedExpected::ErrorAny => {
13309                    if actual.is_err() {
13310                        Ok(())
13311                    } else {
13312                        Err("expected dataframe_head to fail but operation succeeded".to_owned())
13313                    }
13314                }
13315                _ => Err(
13316                    "expected_frame or expected_error is required for dataframe_head".to_owned(),
13317                ),
13318            }
13319        }
13320        FixtureOperation::DataFrameTail => {
13321            let frame = require_frame(fixture)?;
13322            let n = fixture
13323                .tail_n
13324                .ok_or_else(|| "tail_n is required for dataframe_tail".to_owned())?;
13325            let frame = build_dataframe(frame)?;
13326            let actual = frame.tail(n).map_err(|err| err.to_string());
13327            match expected {
13328                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
13329                ResolvedExpected::ErrorContains(substr) => match actual {
13330                    Err(message) if message.contains(&substr) => Ok(()),
13331                    Err(message) => Err(format!(
13332                        "expected dataframe_tail error containing '{substr}', got '{message}'"
13333                    )),
13334                    Ok(_) => Err(format!(
13335                        "expected dataframe_tail to fail with error containing '{substr}'"
13336                    )),
13337                },
13338                ResolvedExpected::ErrorAny => {
13339                    if actual.is_err() {
13340                        Ok(())
13341                    } else {
13342                        Err("expected dataframe_tail to fail but operation succeeded".to_owned())
13343                    }
13344                }
13345                _ => Err(
13346                    "expected_frame or expected_error is required for dataframe_tail".to_owned(),
13347                ),
13348            }
13349        }
13350        FixtureOperation::DataFrameEval => {
13351            let actual = execute_dataframe_eval_fixture_operation(fixture, policy, ledger);
13352            match expected {
13353                ResolvedExpected::Series(series) => compare_series_expected(&actual?, &series),
13354                ResolvedExpected::ErrorContains(substr) => match actual {
13355                    Err(message) if message.contains(&substr) => Ok(()),
13356                    Err(message) => Err(format!(
13357                        "expected dataframe_eval error containing '{substr}', got '{message}'"
13358                    )),
13359                    Ok(_) => Err(format!(
13360                        "expected dataframe_eval to fail with error containing '{substr}'"
13361                    )),
13362                },
13363                ResolvedExpected::ErrorAny => {
13364                    if actual.is_err() {
13365                        Ok(())
13366                    } else {
13367                        Err("expected dataframe_eval to fail but operation succeeded".to_owned())
13368                    }
13369                }
13370                _ => Err(
13371                    "expected_series or expected_error is required for dataframe_eval".to_owned(),
13372                ),
13373            }
13374        }
13375        FixtureOperation::DataFrameCompare => {
13376            let actual = execute_dataframe_fixture_operation(fixture);
13377            match expected {
13378                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
13379                ResolvedExpected::ErrorContains(substr) => match actual {
13380                    Err(message) if message.contains(&substr) => Ok(()),
13381                    Err(message) => Err(format!(
13382                        "expected dataframe_compare error containing '{substr}', got '{message}'"
13383                    )),
13384                    Ok(_) => Err(format!(
13385                        "expected dataframe_compare to fail with error containing '{substr}'"
13386                    )),
13387                },
13388                ResolvedExpected::ErrorAny => {
13389                    if actual.is_err() {
13390                        Ok(())
13391                    } else {
13392                        Err("expected dataframe_compare to fail but operation succeeded".to_owned())
13393                    }
13394                }
13395                _ => Err(
13396                    "expected_frame or expected_error is required for dataframe_compare".to_owned(),
13397                ),
13398            }
13399        }
13400        FixtureOperation::DataFrameQuery => {
13401            let actual = execute_dataframe_query_fixture_operation(fixture, policy, ledger);
13402            match expected {
13403                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
13404                ResolvedExpected::ErrorContains(substr) => match actual {
13405                    Err(message) if message.contains(&substr) => Ok(()),
13406                    Err(message) => Err(format!(
13407                        "expected dataframe_query error containing '{substr}', got '{message}'"
13408                    )),
13409                    Ok(_) => Err(format!(
13410                        "expected dataframe_query to fail with error containing '{substr}'"
13411                    )),
13412                },
13413                ResolvedExpected::ErrorAny => {
13414                    if actual.is_err() {
13415                        Ok(())
13416                    } else {
13417                        Err("expected dataframe_query to fail but operation succeeded".to_owned())
13418                    }
13419                }
13420                _ => Err(
13421                    "expected_frame or expected_error is required for dataframe_query".to_owned(),
13422                ),
13423            }
13424        }
13425        FixtureOperation::DataFrameMerge
13426        | FixtureOperation::DataFrameMergeIndex
13427        | FixtureOperation::DataFrameMergeAsof
13428        | FixtureOperation::DataFrameMergeOrdered
13429        | FixtureOperation::DataFrameConcat
13430        | FixtureOperation::DataFrameIsNa
13431        | FixtureOperation::DataFrameNotNa
13432        | FixtureOperation::DataFrameIsNull
13433        | FixtureOperation::DataFrameNotNull
13434        | FixtureOperation::DataFrameFillNa
13435        | FixtureOperation::DataFrameDropNa
13436        | FixtureOperation::DataFrameDropNaColumns
13437        | FixtureOperation::DataFrameSetIndex
13438        | FixtureOperation::DataFrameResetIndex
13439        | FixtureOperation::DataFrameInsert
13440        | FixtureOperation::DataFrameAssign
13441        | FixtureOperation::DataFrameRenameColumns
13442        | FixtureOperation::DataFrameReindex
13443        | FixtureOperation::DataFrameReindexColumns
13444        | FixtureOperation::DataFrameDropColumns
13445        | FixtureOperation::DataFrameReplace
13446        | FixtureOperation::DataFrameWhere
13447        | FixtureOperation::DataFrameWhereDf
13448        | FixtureOperation::DataFrameMask
13449        | FixtureOperation::DataFrameMaskDf
13450        | FixtureOperation::DataFrameDropDuplicates
13451        | FixtureOperation::DataFrameExplode
13452        | FixtureOperation::DataFrameSortIndex
13453        | FixtureOperation::DataFrameSortValues
13454        | FixtureOperation::DataFrameNlargest
13455        | FixtureOperation::DataFrameNsmallest
13456        | FixtureOperation::DataFrameDiff
13457        | FixtureOperation::DataFrameShift
13458        | FixtureOperation::DataFramePctChange
13459        | FixtureOperation::DataFrameMelt
13460        | FixtureOperation::DataFramePivot
13461        | FixtureOperation::DataFramePivotTable
13462        | FixtureOperation::DataFrameStack
13463        | FixtureOperation::DataFrameTranspose
13464        | FixtureOperation::DataFrameCrosstab
13465        | FixtureOperation::DataFrameCrosstabNormalize
13466        | FixtureOperation::DataFrameGetDummies
13467        | FixtureOperation::SeriesUnstack
13468        | FixtureOperation::SeriesStrGetDummies
13469        | FixtureOperation::DataFrameCombineFirst => {
13470            let actual = execute_dataframe_fixture_operation(fixture);
13471            match expected {
13472                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual?, &frame),
13473                ResolvedExpected::ErrorContains(substr) => match actual {
13474                    Err(message) if message.contains(&substr) => Ok(()),
13475                    Err(message) => Err(format!(
13476                        "expected {:?} error containing '{substr}', got '{message}'",
13477                        fixture.operation
13478                    )),
13479                    Ok(_) => Err(format!(
13480                        "expected {:?} to fail with error containing '{substr}'",
13481                        fixture.operation
13482                    )),
13483                },
13484                ResolvedExpected::ErrorAny => {
13485                    if actual.is_err() {
13486                        Ok(())
13487                    } else {
13488                        Err(format!(
13489                            "expected {:?} to fail but operation succeeded",
13490                            fixture.operation
13491                        ))
13492                    }
13493                }
13494                _ => Err(format!(
13495                    "expected_frame or expected_error is required for {:?}",
13496                    fixture.operation
13497                )),
13498            }
13499        }
13500        FixtureOperation::GroupByMean
13501        | FixtureOperation::GroupByCount
13502        | FixtureOperation::GroupByMin
13503        | FixtureOperation::GroupByMax
13504        | FixtureOperation::GroupByFirst
13505        | FixtureOperation::GroupByLast
13506        | FixtureOperation::GroupByStd
13507        | FixtureOperation::GroupByVar
13508        | FixtureOperation::GroupByMedian => {
13509            let actual =
13510                execute_groupby_fixture_operation(fixture, fixture.operation, policy, ledger)?;
13511            let op_name = format!("{:?}", fixture.operation).to_lowercase();
13512            let expected = match expected {
13513                ResolvedExpected::Series(series) => series,
13514                _ => return Err(format!("expected_series is required for {op_name}")),
13515            };
13516            compare_series_expected(&actual, &expected)
13517        }
13518        FixtureOperation::SeriesRollingMean
13519        | FixtureOperation::SeriesRollingSum
13520        | FixtureOperation::SeriesRollingStd
13521        | FixtureOperation::SeriesRollingMin
13522        | FixtureOperation::SeriesRollingMax
13523        | FixtureOperation::SeriesRollingVar
13524        | FixtureOperation::SeriesRollingCount
13525        | FixtureOperation::SeriesExpandingCount
13526        | FixtureOperation::SeriesExpandingQuantile
13527        | FixtureOperation::SeriesExpandingSum
13528        | FixtureOperation::SeriesExpandingMean
13529        | FixtureOperation::SeriesExpandingMin
13530        | FixtureOperation::SeriesExpandingMax
13531        | FixtureOperation::SeriesExpandingStd
13532        | FixtureOperation::SeriesExpandingVar
13533        | FixtureOperation::SeriesEwmMean
13534        | FixtureOperation::SeriesResampleSum
13535        | FixtureOperation::SeriesResampleMean
13536        | FixtureOperation::SeriesResampleCount
13537        | FixtureOperation::SeriesResampleAsfreq
13538        | FixtureOperation::SeriesResampleFfill
13539        | FixtureOperation::SeriesResampleBfill => {
13540            let actual = execute_series_window_fixture_operation(fixture, policy, ledger)?;
13541            match expected {
13542                ResolvedExpected::Series(series) => compare_series_expected(&actual, &series),
13543                _ => Err(format!(
13544                    "expected_series is required for {:?}",
13545                    fixture.operation
13546                )),
13547            }
13548        }
13549        FixtureOperation::DataFrameRollingMean
13550        | FixtureOperation::DataFrameResampleSum
13551        | FixtureOperation::DataFrameResampleMean => {
13552            let actual = execute_dataframe_window_fixture_operation(fixture, policy, ledger)?;
13553            match expected {
13554                ResolvedExpected::Frame(frame) => compare_dataframe_expected(&actual, &frame),
13555                _ => Err(format!(
13556                    "expected_frame is required for {:?}",
13557                    fixture.operation
13558                )),
13559            }
13560        }
13561    }
13562}
13563
13564fn resolve_expected(
13565    config: &HarnessConfig,
13566    fixture: &PacketFixture,
13567    default_mode: OracleMode,
13568) -> Result<ResolvedExpected, HarnessError> {
13569    let requested_mode = fixture
13570        .oracle_source
13571        .map(|source| match source {
13572            FixtureOracleSource::Fixture => OracleMode::FixtureExpected,
13573            FixtureOracleSource::LiveLegacyPandas => OracleMode::LiveLegacyPandas,
13574        })
13575        .unwrap_or(default_mode);
13576
13577    match requested_mode {
13578        OracleMode::FixtureExpected => fixture_expected(fixture),
13579        OracleMode::LiveLegacyPandas => match capture_live_oracle_expected(config, fixture) {
13580            Ok(expected) => Ok(expected),
13581            Err(error) if should_fallback_to_fixture(config, &error) => {
13582                // Environment guard: if neither legacy nor system pandas is usable,
13583                // fall back to fixture-backed expectations when explicitly allowed.
13584                fixture_expected(fixture)
13585            }
13586            Err(err) => Err(err),
13587        },
13588    }
13589}
13590
13591fn should_fallback_to_fixture(config: &HarnessConfig, error: &HarnessError) -> bool {
13592    matches!(error, HarnessError::OracleUnavailable(_)) && config.allow_fixture_fallback
13593}
13594
13595fn fixture_expected(fixture: &PacketFixture) -> Result<ResolvedExpected, HarnessError> {
13596    if let Some(expected_error_contains) = fixture.expected_error_contains.clone() {
13597        return Ok(ResolvedExpected::ErrorContains(expected_error_contains));
13598    }
13599
13600    match fixture.operation {
13601        FixtureOperation::SeriesAdd
13602        | FixtureOperation::SeriesSub
13603        | FixtureOperation::SeriesMul
13604        | FixtureOperation::SeriesDiv => fixture
13605            .expected_series
13606            .clone()
13607            .map(ResolvedExpected::Series)
13608            .ok_or_else(|| {
13609                HarnessError::FixtureFormat(format!(
13610                    "missing expected_series for case {}",
13611                    fixture.case_id
13612                ))
13613            }),
13614        FixtureOperation::SeriesJoin => fixture
13615            .expected_join
13616            .clone()
13617            .map(ResolvedExpected::Join)
13618            .ok_or_else(|| {
13619                HarnessError::FixtureFormat(format!(
13620                    "missing expected_join for case {}",
13621                    fixture.case_id
13622                ))
13623            }),
13624        FixtureOperation::GroupBySum => fixture
13625            .expected_series
13626            .clone()
13627            .map(ResolvedExpected::Series)
13628            .ok_or_else(|| {
13629                HarnessError::FixtureFormat(format!(
13630                    "missing expected_series for case {}",
13631                    fixture.case_id
13632                ))
13633            }),
13634        FixtureOperation::SeriesToArrowRoundTrip => fixture
13635            .expected_series
13636            .clone()
13637            .map(ResolvedExpected::Series)
13638            .ok_or_else(|| {
13639                HarnessError::FixtureFormat(format!(
13640                    "missing expected_series for case {}",
13641                    fixture.case_id
13642                ))
13643            }),
13644        FixtureOperation::IndexAlignUnion => fixture
13645            .expected_alignment
13646            .clone()
13647            .map(ResolvedExpected::Alignment)
13648            .ok_or_else(|| {
13649                HarnessError::FixtureFormat(format!(
13650                    "missing expected_alignment for case {}",
13651                    fixture.case_id
13652                ))
13653            }),
13654        FixtureOperation::IndexHasDuplicates => fixture
13655            .expected_bool
13656            .map(ResolvedExpected::Bool)
13657            .ok_or_else(|| {
13658                HarnessError::FixtureFormat(format!(
13659                    "missing expected_bool for case {}",
13660                    fixture.case_id
13661                ))
13662            }),
13663        FixtureOperation::IndexIsMonotonicIncreasing
13664        | FixtureOperation::IndexIsMonotonicDecreasing => fixture
13665            .expected_bool
13666            .map(ResolvedExpected::Bool)
13667            .ok_or_else(|| {
13668                HarnessError::FixtureFormat(format!(
13669                    "missing expected_bool for case {}",
13670                    fixture.case_id
13671                ))
13672            }),
13673        FixtureOperation::SeriesAny
13674        | FixtureOperation::SeriesAll
13675        | FixtureOperation::SeriesBool => fixture
13676            .expected_bool
13677            .map(ResolvedExpected::Bool)
13678            .ok_or_else(|| {
13679                HarnessError::FixtureFormat(format!(
13680                    "missing expected_bool for case {}",
13681                    fixture.case_id
13682                ))
13683            }),
13684        FixtureOperation::IndexFirstPositions => fixture
13685            .expected_positions
13686            .clone()
13687            .map(ResolvedExpected::Positions)
13688            .ok_or_else(|| {
13689                HarnessError::FixtureFormat(format!(
13690                    "missing expected_positions for case {}",
13691                    fixture.case_id
13692                ))
13693            }),
13694        FixtureOperation::SeriesConcat
13695        | FixtureOperation::SeriesConstructor
13696        | FixtureOperation::SeriesToDatetime
13697        | FixtureOperation::SeriesToTimedelta
13698        | FixtureOperation::SeriesTimedeltaTotalSeconds
13699        | FixtureOperation::FillNa
13700        | FixtureOperation::DropNa
13701        | FixtureOperation::SeriesFilter
13702        | FixtureOperation::SeriesHead
13703        | FixtureOperation::SeriesTail
13704        | FixtureOperation::SeriesValueCounts
13705        | FixtureOperation::SeriesSortIndex
13706        | FixtureOperation::SeriesSortValues
13707        | FixtureOperation::SeriesDiff
13708        | FixtureOperation::SeriesShift
13709        | FixtureOperation::SeriesPctChange
13710        | FixtureOperation::SeriesMode
13711        | FixtureOperation::SeriesRank
13712        | FixtureOperation::SeriesArgsort
13713        | FixtureOperation::SeriesDescribe
13714        | FixtureOperation::SeriesDuplicated
13715        | FixtureOperation::SeriesDropDuplicates
13716        | FixtureOperation::SeriesUnique
13717        | FixtureOperation::SeriesFactorize
13718        | FixtureOperation::SeriesWhere
13719        | FixtureOperation::SeriesMask
13720        | FixtureOperation::SeriesReplace
13721        | FixtureOperation::SeriesUpdate
13722        | FixtureOperation::SeriesMap
13723        | FixtureOperation::SeriesCategoricalFromCodes
13724        | FixtureOperation::SeriesXs
13725        | FixtureOperation::SeriesIsNa
13726        | FixtureOperation::SeriesNotNa
13727        | FixtureOperation::SeriesIsNull
13728        | FixtureOperation::SeriesNotNull
13729        | FixtureOperation::SeriesFillNa
13730        | FixtureOperation::SeriesDropNa
13731        | FixtureOperation::SeriesLoc
13732        | FixtureOperation::SeriesIloc
13733        | FixtureOperation::SeriesTake
13734        | FixtureOperation::SeriesRepeat
13735        | FixtureOperation::SeriesToNumeric
13736        | FixtureOperation::SeriesConvertDtypes
13737        | FixtureOperation::SeriesAstype
13738        | FixtureOperation::SeriesClip
13739        | FixtureOperation::SeriesAbs
13740        | FixtureOperation::SeriesRound
13741        | FixtureOperation::SeriesCumsum
13742        | FixtureOperation::SeriesCumprod
13743        | FixtureOperation::SeriesCummax
13744        | FixtureOperation::SeriesCummin
13745        | FixtureOperation::SeriesNlargest
13746        | FixtureOperation::SeriesNsmallest
13747        | FixtureOperation::SeriesBetween
13748        | FixtureOperation::SeriesCut
13749        | FixtureOperation::SeriesQcut
13750        | FixtureOperation::SeriesStrLower
13751        | FixtureOperation::SeriesStrUpper
13752        | FixtureOperation::SeriesStrCapitalize
13753        | FixtureOperation::SeriesStrStrip
13754        | FixtureOperation::SeriesStrLen
13755        | FixtureOperation::SeriesStrContains
13756        | FixtureOperation::SeriesStrStartswith
13757        | FixtureOperation::SeriesStrEndswith
13758        | FixtureOperation::SeriesStrReplace
13759        | FixtureOperation::SeriesStrLstrip
13760        | FixtureOperation::SeriesStrRstrip
13761        | FixtureOperation::SeriesStrTitle
13762        | FixtureOperation::SeriesStrSwapcase
13763        | FixtureOperation::SeriesStrZfill
13764        | FixtureOperation::SeriesStrCenter
13765        | FixtureOperation::SeriesStrLjust
13766        | FixtureOperation::SeriesStrRjust
13767        | FixtureOperation::SeriesStrPad
13768        | FixtureOperation::SeriesStrIsdigit
13769        | FixtureOperation::SeriesStrIsalpha
13770        | FixtureOperation::SeriesStrIsalnum
13771        | FixtureOperation::SeriesStrIsspace
13772        | FixtureOperation::SeriesStrIslower
13773        | FixtureOperation::SeriesStrIsupper
13774        | FixtureOperation::SeriesStrIsnumeric
13775        | FixtureOperation::SeriesStrFind
13776        | FixtureOperation::SeriesStrRfind
13777        | FixtureOperation::SeriesStrSlice
13778        | FixtureOperation::SeriesStrGet
13779        | FixtureOperation::SeriesStrRepeat
13780        | FixtureOperation::SeriesStrCount
13781        | FixtureOperation::SeriesStrWrap
13782        | FixtureOperation::SeriesStrNormalize
13783        | FixtureOperation::SeriesStrFullmatch
13784        | FixtureOperation::SeriesStrMatch
13785        | FixtureOperation::SeriesStrRemoveprefix
13786        | FixtureOperation::SeriesStrRemovesuffix
13787        | FixtureOperation::SeriesStrSplitGet
13788        | FixtureOperation::SeriesStrJoin
13789        | FixtureOperation::SeriesStrIsdecimal
13790        | FixtureOperation::SeriesStrIstitle
13791        | FixtureOperation::SeriesStrCasefold
13792        | FixtureOperation::SeriesStrEncode
13793        | FixtureOperation::SeriesStrDecode
13794        | FixtureOperation::SeriesStrTranslate
13795        | FixtureOperation::SeriesStrExpandtabs
13796        | FixtureOperation::SeriesStrIndexOf
13797        | FixtureOperation::SeriesStrRindexOf
13798        | FixtureOperation::SeriesStrSplitCount
13799        | FixtureOperation::SeriesStrRsplitGet
13800        | FixtureOperation::SeriesStrSplitRegexGet
13801        | FixtureOperation::SeriesStrCountMatches
13802        | FixtureOperation::SeriesStrCountLiteral
13803        | FixtureOperation::SeriesStrFindall
13804        | FixtureOperation::SeriesStrContainsAny
13805        | FixtureOperation::SeriesStrStartswithAny
13806        | FixtureOperation::SeriesStrEndswithAny
13807        | FixtureOperation::SeriesDtYear
13808        | FixtureOperation::SeriesDtMonth
13809        | FixtureOperation::SeriesDtDay
13810        | FixtureOperation::SeriesDtHour
13811        | FixtureOperation::SeriesDtMinute
13812        | FixtureOperation::SeriesDtSecond
13813        | FixtureOperation::SeriesDtMicrosecond
13814        | FixtureOperation::SeriesDtNanosecond
13815        | FixtureOperation::SeriesDtDayofweek
13816        | FixtureOperation::SeriesDtQuarter
13817        | FixtureOperation::SeriesDtDayofyear
13818        | FixtureOperation::SeriesDtWeekofyear
13819        | FixtureOperation::SeriesDtIsMonthStart
13820        | FixtureOperation::SeriesDtIsMonthEnd
13821        | FixtureOperation::SeriesDtIsYearStart
13822        | FixtureOperation::SeriesDtIsYearEnd
13823        | FixtureOperation::SeriesDtDate
13824        | FixtureOperation::SeriesDtDaysInMonth
13825        | FixtureOperation::SeriesDtIsLeapYear
13826        | FixtureOperation::SeriesDtIsQuarterStart
13827        | FixtureOperation::SeriesDtIsQuarterEnd
13828        | FixtureOperation::SeriesDtStrftime
13829        | FixtureOperation::SeriesDtTzConvert
13830        | FixtureOperation::SeriesDtTzLocalize
13831        | FixtureOperation::SeriesDtTimetz
13832        | FixtureOperation::SeriesDtToPeriod
13833        | FixtureOperation::SeriesDtFloor
13834        | FixtureOperation::SeriesDtCeil
13835        | FixtureOperation::SeriesDtRound
13836        | FixtureOperation::SeriesDtMonthName
13837        | FixtureOperation::SeriesDtDayName
13838        | FixtureOperation::SeriesDtTotalSeconds
13839        | FixtureOperation::SeriesDtDays
13840        | FixtureOperation::SeriesDtSeconds
13841        | FixtureOperation::SeriesDtMicroseconds
13842        | FixtureOperation::SeriesDtNanoseconds
13843        | FixtureOperation::SeriesDtToTimestamp
13844        | FixtureOperation::SeriesDtToPytimedelta
13845        | FixtureOperation::SeriesDtToPydatetime
13846        | FixtureOperation::SeriesAtTime
13847        | FixtureOperation::SeriesBetweenTime
13848        | FixtureOperation::DataFrameGroupByCumcount
13849        | FixtureOperation::DataFrameGroupByNgroup
13850        | FixtureOperation::DataFrameAsof
13851        | FixtureOperation::DataFrameEval
13852        | FixtureOperation::DataFrameCount
13853        | FixtureOperation::DataFrameIdxmin
13854        | FixtureOperation::DataFrameIdxmax
13855        | FixtureOperation::DataFrameSem
13856        | FixtureOperation::DataFrameApplySemAxis0
13857        | FixtureOperation::DataFrameSkew
13858        | FixtureOperation::DataFrameKurtosis
13859        | FixtureOperation::DataFrameProd
13860        | FixtureOperation::DataFrameApplyProdAxis1
13861        | FixtureOperation::DataFrameApplyProductAxis1
13862        | FixtureOperation::DataFrameSum
13863        | FixtureOperation::DataFrameMean
13864        | FixtureOperation::DataFrameStd
13865        | FixtureOperation::DataFrameVar
13866        | FixtureOperation::DataFrameMin
13867        | FixtureOperation::DataFrameMax
13868        | FixtureOperation::DataFrameMedian
13869        | FixtureOperation::DataFrameAny
13870        | FixtureOperation::DataFrameAll
13871        | FixtureOperation::DataFrameNunique
13872        | FixtureOperation::DataFrameApplyNuniqueAxis0
13873        | FixtureOperation::DataFrameQuantile
13874        | FixtureOperation::DataFrameValueCounts
13875        | FixtureOperation::DataFrameMemoryUsage
13876        | FixtureOperation::DataFrameDuplicated
13877        | FixtureOperation::GroupByMean
13878        | FixtureOperation::GroupByCount
13879        | FixtureOperation::GroupByMin
13880        | FixtureOperation::GroupByMax
13881        | FixtureOperation::GroupByFirst
13882        | FixtureOperation::GroupByLast
13883        | FixtureOperation::GroupByStd
13884        | FixtureOperation::GroupByVar
13885        | FixtureOperation::GroupByMedian
13886        | FixtureOperation::SeriesCombineFirst
13887        | FixtureOperation::SeriesRollingMean
13888        | FixtureOperation::SeriesRollingSum
13889        | FixtureOperation::SeriesRollingStd
13890        | FixtureOperation::SeriesRollingMin
13891        | FixtureOperation::SeriesRollingMax
13892        | FixtureOperation::SeriesRollingVar
13893        | FixtureOperation::SeriesRollingCount
13894        | FixtureOperation::SeriesExpandingCount
13895        | FixtureOperation::SeriesExpandingQuantile
13896        | FixtureOperation::SeriesExpandingSum
13897        | FixtureOperation::SeriesExpandingMean
13898        | FixtureOperation::SeriesExpandingMin
13899        | FixtureOperation::SeriesExpandingMax
13900        | FixtureOperation::SeriesExpandingStd
13901        | FixtureOperation::SeriesExpandingVar
13902        | FixtureOperation::SeriesEwmMean
13903        | FixtureOperation::SeriesResampleSum
13904        | FixtureOperation::SeriesResampleMean
13905        | FixtureOperation::SeriesResampleCount
13906        | FixtureOperation::SeriesResampleAsfreq
13907        | FixtureOperation::SeriesResampleFfill
13908        | FixtureOperation::SeriesResampleBfill => fixture
13909            .expected_series
13910            .clone()
13911            .map(ResolvedExpected::Series)
13912            .ok_or_else(|| {
13913                HarnessError::FixtureFormat(format!(
13914                    "missing expected_series for case {}",
13915                    fixture.case_id
13916                ))
13917            }),
13918        FixtureOperation::DataFrameLoc
13919        | FixtureOperation::DataFrameIdentity
13920        | FixtureOperation::SeriesExtractAll
13921        | FixtureOperation::SeriesToFrame
13922        | FixtureOperation::SeriesUnstack
13923        | FixtureOperation::SeriesStrGetDummies
13924        | FixtureOperation::DataFrameIloc
13925        | FixtureOperation::DataFrameTake
13926        | FixtureOperation::DataFrameFilter
13927        | FixtureOperation::DataFrameXs
13928        | FixtureOperation::DataFrameGroupBySum
13929        | FixtureOperation::DataFrameGroupByAggMulti
13930        | FixtureOperation::DataFrameGroupByIdxMin
13931        | FixtureOperation::DataFrameGroupByIdxMax
13932        | FixtureOperation::DataFrameGroupByAny
13933        | FixtureOperation::DataFrameGroupByAll
13934        | FixtureOperation::DataFrameGroupByGetGroup
13935        | FixtureOperation::DataFrameGroupByFfill
13936        | FixtureOperation::DataFrameGroupByBfill
13937        | FixtureOperation::DataFrameGroupBySem
13938        | FixtureOperation::DataFrameGroupBySkew
13939        | FixtureOperation::DataFrameGroupByKurtosis
13940        | FixtureOperation::DataFrameGroupByOhlc
13941        | FixtureOperation::DataFrameAtTime
13942        | FixtureOperation::DataFrameBetweenTime
13943        | FixtureOperation::DataFrameHead
13944        | FixtureOperation::DataFrameTail
13945        | FixtureOperation::DataFrameCompare
13946        | FixtureOperation::DataFrameQuery
13947        | FixtureOperation::DataFrameMode
13948        | FixtureOperation::DataFrameCumsum
13949        | FixtureOperation::DataFrameCumprod
13950        | FixtureOperation::DataFrameCummax
13951        | FixtureOperation::DataFrameCummin
13952        | FixtureOperation::DataFrameAstype
13953        | FixtureOperation::DataFrameClip
13954        | FixtureOperation::DataFrameAbs
13955        | FixtureOperation::DataFrameDescribe
13956        | FixtureOperation::DataFrameCorr
13957        | FixtureOperation::DataFrameCov
13958        | FixtureOperation::DataFrameRound
13959        | FixtureOperation::DataFrameBinaryAlias
13960        | FixtureOperation::DataFrameRank
13961        | FixtureOperation::DataFrameFromSeries
13962        | FixtureOperation::DataFrameFromDict
13963        | FixtureOperation::DataFrameFromRecords
13964        | FixtureOperation::DataFrameConstructorKwargs
13965        | FixtureOperation::DataFrameConstructorScalar
13966        | FixtureOperation::DataFrameConstructorDictOfSeries
13967        | FixtureOperation::DataFrameConstructorListLike
13968        | FixtureOperation::DataFrameIsNa
13969        | FixtureOperation::DataFrameNotNa
13970        | FixtureOperation::DataFrameIsNull
13971        | FixtureOperation::DataFrameNotNull
13972        | FixtureOperation::DataFrameFillNa
13973        | FixtureOperation::DataFrameDropNa
13974        | FixtureOperation::DataFrameDropNaColumns
13975        | FixtureOperation::DataFrameSetIndex
13976        | FixtureOperation::DataFrameResetIndex
13977        | FixtureOperation::DataFrameInsert
13978        | FixtureOperation::DataFrameAssign
13979        | FixtureOperation::DataFrameRenameColumns
13980        | FixtureOperation::DataFrameReindex
13981        | FixtureOperation::DataFrameReindexColumns
13982        | FixtureOperation::DataFrameDropColumns
13983        | FixtureOperation::DataFrameReplace
13984        | FixtureOperation::DataFrameWhere
13985        | FixtureOperation::DataFrameWhereDf
13986        | FixtureOperation::DataFrameMask
13987        | FixtureOperation::DataFrameMaskDf
13988        | FixtureOperation::DataFrameDropDuplicates
13989        | FixtureOperation::DataFrameExplode
13990        | FixtureOperation::DataFrameMerge
13991        | FixtureOperation::DataFrameMergeIndex
13992        | FixtureOperation::DataFrameMergeAsof
13993        | FixtureOperation::DataFrameMergeOrdered
13994        | FixtureOperation::DataFrameConcat
13995        | FixtureOperation::DataFrameSortIndex
13996        | FixtureOperation::DataFrameSortValues
13997        | FixtureOperation::DataFrameNlargest
13998        | FixtureOperation::DataFrameNsmallest
13999        | FixtureOperation::DataFrameDiff
14000        | FixtureOperation::DataFrameShift
14001        | FixtureOperation::DataFramePctChange
14002        | FixtureOperation::DataFrameMelt
14003        | FixtureOperation::DataFramePivot
14004        | FixtureOperation::DataFramePivotTable
14005        | FixtureOperation::DataFrameStack
14006        | FixtureOperation::DataFrameTranspose
14007        | FixtureOperation::DataFrameCrosstab
14008        | FixtureOperation::DataFrameCrosstabNormalize
14009        | FixtureOperation::DataFrameGetDummies
14010        | FixtureOperation::DataFrameCombineFirst
14011        | FixtureOperation::SeriesPartitionDf
14012        | FixtureOperation::SeriesRpartitionDf
14013        | FixtureOperation::SeriesSplitDf
14014        | FixtureOperation::SeriesExtractDf
14015        | FixtureOperation::CsvReadFrame
14016        | FixtureOperation::DataFrameRollingMean
14017        | FixtureOperation::DataFrameResampleSum
14018        | FixtureOperation::DataFrameResampleMean
14019        | FixtureOperation::DataFrameGroupByRollingMean
14020        | FixtureOperation::DataFrameGroupByRollingSum
14021        | FixtureOperation::DataFrameGroupByRollingMin
14022        | FixtureOperation::DataFrameGroupByRollingMax
14023        | FixtureOperation::DataFrameGroupByRollingCount
14024        | FixtureOperation::DataFrameGroupByRollingStd
14025        | FixtureOperation::DataFrameGroupByRollingVar
14026        | FixtureOperation::DataFrameGroupByResampleMin
14027        | FixtureOperation::DataFrameGroupByResampleMax
14028        | FixtureOperation::DataFrameGroupByResampleCount
14029        | FixtureOperation::DataFrameGroupByResampleFirst
14030        | FixtureOperation::DataFrameGroupByResampleLast => fixture
14031            .expected_frame
14032            .clone()
14033            .map(ResolvedExpected::Frame)
14034            .ok_or_else(|| {
14035                HarnessError::FixtureFormat(format!(
14036                    "missing expected_frame for case {}",
14037                    fixture.case_id
14038                ))
14039            }),
14040        FixtureOperation::NanSum
14041        | FixtureOperation::NanMean
14042        | FixtureOperation::NanMin
14043        | FixtureOperation::NanMax
14044        | FixtureOperation::NanStd
14045        | FixtureOperation::NanVar
14046        | FixtureOperation::NanCount
14047        | FixtureOperation::SeriesAsof
14048        | FixtureOperation::SeriesAutocorr
14049        | FixtureOperation::SeriesCount
14050        | FixtureOperation::SeriesNunique
14051        | FixtureOperation::SeriesFirstValidIndex
14052        | FixtureOperation::SeriesLastValidIndex
14053        | FixtureOperation::SeriesIdxmin
14054        | FixtureOperation::SeriesIdxmax
14055        | FixtureOperation::SeriesArgmin
14056        | FixtureOperation::SeriesArgmax
14057        | FixtureOperation::SeriesSearchsorted
14058        | FixtureOperation::SeriesDot
14059        | FixtureOperation::DataFrameToJsonRecords => fixture
14060            .expected_scalar
14061            .clone()
14062            .map(ResolvedExpected::Scalar)
14063            .ok_or_else(|| {
14064                HarnessError::FixtureFormat(format!(
14065                    "missing expected_scalar for case {}",
14066                    fixture.case_id
14067                ))
14068            }),
14069        FixtureOperation::DataFrameBool
14070        | FixtureOperation::CsvRoundTrip
14071        | FixtureOperation::JsonRoundTrip
14072        | FixtureOperation::JsonlRoundTrip
14073        | FixtureOperation::ParquetRoundTrip
14074        | FixtureOperation::FeatherRoundTrip
14075        | FixtureOperation::ExcelRoundTrip
14076        | FixtureOperation::IpcStreamRoundTrip => fixture
14077            .expected_bool
14078            .map(ResolvedExpected::Bool)
14079            .ok_or_else(|| {
14080                HarnessError::FixtureFormat(format!(
14081                    "missing expected_bool for case {}",
14082                    fixture.case_id
14083                ))
14084            }),
14085        FixtureOperation::ColumnDtypeCheck | FixtureOperation::SeriesDtypeCheck => fixture
14086            .expected_dtype
14087            .clone()
14088            .map(ResolvedExpected::Dtype)
14089            .ok_or_else(|| {
14090                HarnessError::FixtureFormat(format!(
14091                    "missing expected_dtype for case {}",
14092                    fixture.case_id
14093                ))
14094            }),
14095    }
14096}
14097
14098fn resolve_expected_oracle_error(
14099    fixture: &PacketFixture,
14100    oracle_error: String,
14101) -> Result<ResolvedExpected, HarnessError> {
14102    let expected = fixture.expected_error_contains.as_deref().ok_or_else(|| {
14103        HarnessError::FixtureFormat(format!(
14104            "oracle returned an error for non-error case {}: {oracle_error}",
14105            fixture.case_id
14106        ))
14107    })?;
14108
14109    if oracle_error.contains(expected) {
14110        Ok(ResolvedExpected::ErrorAny)
14111    } else {
14112        Err(HarnessError::FixtureFormat(format!(
14113            "oracle error for {} did not contain expected substring {expected:?}: {oracle_error}",
14114            fixture.case_id
14115        )))
14116    }
14117}
14118
14119/// Parse the pinned pandas version from the oracle requirements file
14120/// (`pandas==X.Y.Z`). Returns `None` when the file is absent or has no pin —
14121/// callers then degrade to the pre-guard behavior rather than inventing a pin.
14122fn pinned_pandas_version(config: &HarnessConfig) -> Option<String> {
14123    let path = config
14124        .repo_root
14125        .join("crates/fp-conformance/oracle/requirements.txt");
14126    let text = fs::read_to_string(path).ok()?;
14127    for line in text.lines() {
14128        let line = line.trim();
14129        if let Some(rest) = line.strip_prefix("pandas==") {
14130            return Some(rest.trim().to_owned());
14131        }
14132    }
14133    None
14134}
14135
14136/// Refuse to compare against an oracle that is not the PINNED pandas.
14137///
14138/// The oracle response self-reports its pandas version in
14139/// `fixture_provenance.pandas_version`; when it differs from
14140/// `oracle/requirements.txt`, the expected values describe a different library
14141/// than the fixtures pin (observed: rch-offloaded runs resolved
14142/// `.venv-oracle`'s symlinked interpreter to the worker's own newer pandas),
14143/// so the comparison would be a cross-version artifact, not parity evidence.
14144/// Fail closed into the honest-unavailable path (skip under normal policy,
14145/// hard error under `FP_REQUIRE_LIVE_ORACLE`). A missing provenance block is
14146/// not verified here — expected-error responses and legacy callers rely on
14147/// that shape.
14148fn verify_oracle_pandas_pin(
14149    config: &HarnessConfig,
14150    provenance: Option<&FixtureProvenance>,
14151) -> Result<(), HarnessError> {
14152    let Some(pin) = pinned_pandas_version(config) else {
14153        return Ok(());
14154    };
14155    let Some(provenance) = provenance else {
14156        return Ok(());
14157    };
14158    if provenance.pandas_version == pin {
14159        return Ok(());
14160    }
14161    let message = format!(
14162        "oracle pandas {} != pinned {pin}: refusing a cross-version comparison \
14163         (br-frankenpandas-rc-oracle-provenance-guard-d8wt4)",
14164        provenance.pandas_version
14165    );
14166    if config.require_live_oracle {
14167        Err(HarnessError::LiveOracleRequired(message))
14168    } else {
14169        Err(HarnessError::OracleUnavailable(message))
14170    }
14171}
14172
14173fn capture_live_oracle_expected(
14174    config: &HarnessConfig,
14175    fixture: &PacketFixture,
14176) -> Result<ResolvedExpected, HarnessError> {
14177    fn oracle_unavailable(config: &HarnessConfig, message: String) -> HarnessError {
14178        if config.require_live_oracle {
14179            HarnessError::LiveOracleRequired(message)
14180        } else {
14181            HarnessError::OracleUnavailable(message)
14182        }
14183    }
14184
14185    let expects_error = fixture.expected_error_contains.is_some();
14186    let allow_system_pandas_fallback = config.allows_system_pandas_fallback();
14187
14188    if !config.oracle_root.exists() && !allow_system_pandas_fallback {
14189        return Err(oracle_unavailable(
14190            config,
14191            format!(
14192                "legacy oracle root does not exist: {}",
14193                config.oracle_root.display()
14194            ),
14195        ));
14196    }
14197    let script = config.oracle_script_path();
14198    if !script.exists() {
14199        return Err(oracle_unavailable(
14200            config,
14201            format!("oracle script does not exist: {}", script.display()),
14202        ));
14203    }
14204
14205    let payload = OracleRequest {
14206        operation: fixture.operation,
14207        left: fixture.left.clone(),
14208        right: fixture.right.clone(),
14209        series: fixture.left.clone(),
14210        groupby_keys: fixture.groupby_keys.clone(),
14211        groupby_columns: fixture.groupby_columns.clone(),
14212        groupby_observed: fixture.groupby_observed,
14213        groupby_agg_multi: fixture.groupby_agg_multi.clone(),
14214        frame: fixture.frame.clone(),
14215        expr: fixture.expr.clone(),
14216        locals: fixture.locals.clone(),
14217        frame_right: fixture.frame_right.clone(),
14218        frame_other: fixture.frame_other.clone(),
14219        dict_columns: fixture.dict_columns.clone(),
14220        column_order: fixture.column_order.clone(),
14221        records: fixture.records.clone(),
14222        matrix_rows: fixture.matrix_rows.clone(),
14223        index: fixture.index.clone(),
14224        join_type: fixture.join_type,
14225        merge_on: fixture.merge_on.clone(),
14226        merge_on_keys: fixture.merge_on_keys.clone(),
14227        left_on_keys: fixture.left_on_keys.clone(),
14228        right_on_keys: fixture.right_on_keys.clone(),
14229        left_index: fixture.left_index,
14230        right_index: fixture.right_index,
14231        merge_indicator: fixture.merge_indicator,
14232        merge_indicator_name: fixture.merge_indicator_name.clone(),
14233        merge_validate: fixture.merge_validate.clone(),
14234        merge_suffixes: fixture.merge_suffixes.clone(),
14235        merge_sort: fixture.merge_sort,
14236        fill_value: fixture.fill_value.clone(),
14237        constructor_dtype: fixture.constructor_dtype.clone(),
14238        datetime_unit: fixture.datetime_unit.clone(),
14239        datetime_origin: fixture.datetime_origin.clone(),
14240        datetime_utc: fixture.datetime_utc,
14241        head_n: fixture.head_n,
14242        tail_n: fixture.tail_n,
14243        diff_periods: fixture.diff_periods,
14244        shift_periods: fixture.shift_periods,
14245        shift_axis: fixture.shift_axis,
14246        pct_change_periods: fixture.pct_change_periods,
14247        pct_change_axis: fixture.pct_change_axis,
14248        mode_dropna: fixture.mode_dropna,
14249        idxmin_skipna: fixture.idxmin_skipna,
14250        idxmax_skipna: fixture.idxmax_skipna,
14251        argmin_skipna: fixture.argmin_skipna,
14252        argmax_skipna: fixture.argmax_skipna,
14253        searchsorted_value: fixture.searchsorted_value.clone(),
14254        searchsorted_side: fixture.searchsorted_side.clone(),
14255        autocorr_lag: fixture.autocorr_lag,
14256        diff_axis: fixture.diff_axis,
14257        clip_lower: fixture.clip_lower,
14258        clip_upper: fixture.clip_upper,
14259        clip_lower_series: fixture.clip_lower_series.clone(),
14260        clip_upper_series: fixture.clip_upper_series.clone(),
14261        round_decimals: fixture.round_decimals,
14262        dataframe_binary_method: fixture.dataframe_binary_method.clone(),
14263        rank_method: fixture.rank_method.clone(),
14264        rank_na_option: fixture.rank_na_option.clone(),
14265        rank_axis: fixture.rank_axis,
14266        rank_pct: fixture.rank_pct,
14267        corr_method: fixture.corr_method.clone(),
14268        corr_min_periods: fixture.corr_min_periods,
14269        corr_numeric_only: fixture.corr_numeric_only,
14270        sum_numeric_only: fixture.sum_numeric_only,
14271        mean_numeric_only: fixture.mean_numeric_only,
14272        min_numeric_only: fixture.min_numeric_only,
14273        max_numeric_only: fixture.max_numeric_only,
14274        prod_numeric_only: fixture.prod_numeric_only,
14275        median_numeric_only: fixture.median_numeric_only,
14276        std_numeric_only: fixture.std_numeric_only,
14277        var_numeric_only: fixture.var_numeric_only,
14278        sem_numeric_only: fixture.sem_numeric_only,
14279        skew_numeric_only: fixture.skew_numeric_only,
14280        kurtosis_numeric_only: fixture.kurtosis_numeric_only,
14281        count_numeric_only: fixture.count_numeric_only,
14282        quantile_numeric_only: fixture.quantile_numeric_only,
14283        sort_column: fixture.sort_column.clone(),
14284        sort_ascending: fixture.sort_ascending,
14285        sort_na_position: fixture.sort_na_position.clone(),
14286        value_counts_normalize: fixture.value_counts_normalize,
14287        value_counts_dropna: fixture.value_counts_dropna,
14288        frame_name: fixture.frame_name.clone(),
14289        memory_usage_index: fixture.memory_usage_index,
14290        memory_usage_deep: fixture.memory_usage_deep,
14291        concat_axis: fixture.concat_axis,
14292        concat_join: fixture.concat_join.clone(),
14293        set_index_column: fixture.set_index_column.clone(),
14294        set_index_drop: fixture.set_index_drop,
14295        set_index_verify_integrity: fixture.set_index_verify_integrity,
14296        reset_index_drop: fixture.reset_index_drop,
14297        insert_loc: fixture.insert_loc,
14298        insert_column: fixture.insert_column.clone(),
14299        insert_values: fixture.insert_values.clone(),
14300        assignments: fixture.assignments.clone(),
14301        rename_columns: fixture.rename_columns.clone(),
14302        reindex_labels: fixture.reindex_labels.clone(),
14303        reindex_columns: fixture.reindex_columns.clone(),
14304        drop_columns: fixture.drop_columns.clone(),
14305        replace_to_find: fixture.replace_to_find.clone(),
14306        replace_to_value: fixture.replace_to_value.clone(),
14307        na_action_ignore: fixture.na_action_ignore,
14308        categorical_categories: fixture.categorical_categories.clone(),
14309        categorical_ordered: fixture.categorical_ordered,
14310        subset: fixture.subset.clone(),
14311        keep: fixture.keep.clone(),
14312        ignore_index: fixture.ignore_index,
14313        explode_column: fixture.explode_column.clone(),
14314        csv_input: fixture.csv_input.clone(),
14315        csv_decimal: fixture.csv_decimal.clone(),
14316        csv_on_bad_lines: fixture.csv_on_bad_lines.clone(),
14317        csv_parse_dates: fixture.csv_parse_dates.clone(),
14318        csv_parse_date_combinations: fixture.csv_parse_date_combinations.clone(),
14319        csv_true_values: fixture.csv_true_values.clone(),
14320        csv_false_values: fixture.csv_false_values.clone(),
14321        loc_labels: fixture.loc_labels.clone(),
14322        iloc_positions: fixture.iloc_positions.clone(),
14323        take_indices: fixture.take_indices.clone(),
14324        filter_items: fixture.filter_items.clone(),
14325        filter_like: fixture.filter_like.clone(),
14326        filter_regex: fixture.filter_regex.clone(),
14327        filter_axis: fixture.filter_axis,
14328        repeat_n: fixture.repeat_n,
14329        repeat_counts: fixture.repeat_counts.clone(),
14330        group_name: fixture.group_name.clone(),
14331        xs_key: fixture.xs_key.clone(),
14332        xs_level: fixture.xs_level,
14333        cut_bins: fixture.cut_bins,
14334        qcut_quantiles: fixture.qcut_quantiles,
14335        take_axis: fixture.take_axis,
14336        asof_label: fixture.asof_label.clone(),
14337        time_value: fixture.time_value.clone(),
14338        start_time: fixture.start_time.clone(),
14339        end_time: fixture.end_time.clone(),
14340        string_sep: fixture.string_sep.clone(),
14341        regex_pattern: fixture.regex_pattern.clone(),
14342        str_prefix: fixture.str_prefix.clone(),
14343        str_suffix: fixture.str_suffix.clone(),
14344        replace_value: fixture.replace_value.clone(),
14345        str_pad_side: fixture.str_pad_side.clone(),
14346        str_repeat_n: fixture.str_repeat_n,
14347        str_normalize_form: fixture.str_normalize_form.clone(),
14348        str_slice_start: fixture.str_slice_start,
14349        str_slice_end: fixture.str_slice_end,
14350        str_slice_step: fixture.str_slice_step,
14351        str_split_pat: fixture.str_split_pat.clone(),
14352        str_split_n: fixture.str_split_n,
14353        str_sub: fixture.str_sub.clone(),
14354        str_get_index: fixture.str_get_index,
14355        str_fillchar: fixture.str_fillchar,
14356        str_width: fixture.str_width,
14357        str_wrap_width: fixture.str_wrap_width,
14358        str_expandtabs_size: fixture.str_expandtabs_size,
14359        str_findall_sep: fixture.str_findall_sep.clone(),
14360        str_join_sep: fixture.str_join_sep.clone(),
14361        str_translate_from: fixture.str_translate_from.clone(),
14362        str_translate_to: fixture.str_translate_to.clone(),
14363        nlargest_n: fixture.nlargest_n,
14364        between_left: fixture.between_left.clone(),
14365        between_right: fixture.between_right.clone(),
14366        between_inclusive: fixture.between_inclusive.clone(),
14367        direction: fixture.direction.clone(),
14368        allow_exact_matches: fixture.allow_exact_matches,
14369        tolerance: fixture.tolerance,
14370        merge_asof_by: fixture.merge_asof_by.clone(),
14371        merge_fill_method: fixture.merge_fill_method.clone(),
14372        compare_result_names: fixture.compare_result_names.clone(),
14373        constructor_copy: fixture.constructor_copy,
14374        str_wrap_drop_whitespace: fixture.str_wrap_drop_whitespace,
14375        str_patterns: fixture.str_patterns.clone(),
14376        str_join_from: fixture.str_join_from.clone(),
14377        json_input: fixture.json_input.clone(),
14378        json_orient: fixture.json_orient.clone(),
14379        jsonl_input: fixture.jsonl_input.clone(),
14380        melt_id_vars: fixture.melt_id_vars.clone(),
14381        melt_value_vars: fixture.melt_value_vars.clone(),
14382        melt_var_name: fixture.melt_var_name.clone(),
14383        melt_value_name: fixture.melt_value_name.clone(),
14384        pivot_values: fixture.pivot_values.clone(),
14385        pivot_index: fixture.pivot_index.clone(),
14386        pivot_columns: fixture.pivot_columns.clone(),
14387        pivot_aggfunc: fixture.pivot_aggfunc.clone(),
14388        pivot_margins: fixture.pivot_margins,
14389        pivot_dropna: fixture.pivot_dropna,
14390        pivot_sort: fixture.pivot_sort,
14391        pivot_margins_name: fixture.pivot_margins_name.clone(),
14392        dummy_columns: fixture.dummy_columns.clone(),
14393        crosstab_normalize: fixture.crosstab_normalize.clone(),
14394        window_size: fixture.window_size,
14395        min_periods: fixture.min_periods,
14396        window_center: fixture.window_center,
14397        ewm_span: fixture.ewm_span,
14398        ewm_alpha: fixture.ewm_alpha,
14399        resample_freq: fixture.resample_freq.clone(),
14400        resample_limit: fixture.resample_limit,
14401        resample_closed: fixture.resample_closed.clone(),
14402        resample_label: fixture.resample_label.clone(),
14403        resample_origin: fixture.resample_origin.clone(),
14404        quantile_value: fixture.quantile_value,
14405        dt_freq: fixture.dt_freq.clone(),
14406        dt_tz: fixture.dt_tz.clone(),
14407        dt_strftime_format: fixture.dt_strftime_format.clone(),
14408        dt_how: fixture.dt_how.clone(),
14409        dt_warn: fixture.dt_warn,
14410    };
14411    let input = serde_json::to_vec(&payload)?;
14412
14413    // Per br-frankenpandas-92df89: spawn a thread to drain stdin so
14414    // wait_with_output can drain stdout/stderr concurrently. Synchronous
14415    // pre-wait write_all deadlocks if the JSON payload exceeds the OS
14416    // stdin pipe buffer (~64 KB) AND the child emits output that fills
14417    // its stdout pipe buffer before reading all input.
14418    let mut child = Command::new(&config.python_bin)
14419        .arg(&script)
14420        .arg("--legacy-root")
14421        .arg(&config.oracle_root)
14422        .arg("--strict-legacy")
14423        .args(allow_system_pandas_fallback.then_some("--allow-system-pandas-fallback"))
14424        .stdin(Stdio::piped())
14425        .stdout(Stdio::piped())
14426        .stderr(Stdio::piped())
14427        .spawn()?;
14428    let stdin_handle = child.stdin.take();
14429    let stdin_writer = std::thread::spawn(move || -> std::io::Result<()> {
14430        use std::io::Write;
14431        if let Some(mut stdin) = stdin_handle {
14432            stdin.write_all(&input)?;
14433        }
14434        Ok(())
14435    });
14436    let output = child.wait_with_output()?;
14437    stdin_writer
14438        .join()
14439        .map_err(|_| std::io::Error::other("oracle stdin writer thread panicked"))??;
14440
14441    if !output.status.success() {
14442        if let Ok(response) = serde_json::from_slice::<OracleResponse>(&output.stdout)
14443            && let Some(error) = response.error
14444        {
14445            let origin = response.error_origin.as_deref();
14446            // A pandas that never loaded is not the pandas answer to an
14447            // expected-error case either.
14448            if expects_error && origin != Some("oracle_unavailable") {
14449                return resolve_expected_oracle_error(fixture, error);
14450            }
14451            return Err(classify_oracle_error(
14452                error,
14453                origin,
14454                config.require_live_oracle,
14455            ));
14456        }
14457
14458        let code = output.status.code().unwrap_or(-1);
14459        let stderr = String::from_utf8_lossy(&output.stderr).to_string();
14460        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
14461        return Err(HarnessError::OracleCommandFailed {
14462            status: code,
14463            stderr: format!("{stderr}\nstdout={stdout}"),
14464        });
14465    }
14466
14467    let response: OracleResponse = serde_json::from_slice(&output.stdout)?;
14468    if let Some(error) = response.error {
14469        let origin = response.error_origin.as_deref();
14470        if expects_error && origin != Some("oracle_unavailable") {
14471            return resolve_expected_oracle_error(fixture, error);
14472        }
14473        return Err(classify_oracle_error(
14474            error,
14475            origin,
14476            config.require_live_oracle,
14477        ));
14478    }
14479    // br-frankenpandas-rc-oracle-provenance-guard-d8wt4: the oracle response
14480    // self-reports the pandas it ran. If that is not the PINNED version, the
14481    // "expected" values describe a DIFFERENT library than the fixtures pin and
14482    // any comparison is a cross-version artifact, not parity evidence
14483    // (observed: rch-offloaded runs resolved .venv-oracle's symlinked python
14484    // to the worker's own newer pandas). Fail closed into an HONEST skip.
14485    verify_oracle_pandas_pin(config, response.fixture_provenance.as_ref())?;
14486
14487    if expects_error {
14488        return Err(HarnessError::FixtureFormat(format!(
14489            "oracle unexpectedly succeeded for expected-error case {}",
14490            fixture.case_id
14491        )));
14492    }
14493
14494    match fixture.operation {
14495        FixtureOperation::SeriesAdd
14496        | FixtureOperation::SeriesSub
14497        | FixtureOperation::SeriesMul
14498        | FixtureOperation::SeriesDiv => response
14499            .expected_series
14500            .map(ResolvedExpected::Series)
14501            .ok_or_else(|| {
14502                HarnessError::FixtureFormat("oracle omitted expected_series".to_owned())
14503            }),
14504        FixtureOperation::SeriesJoin => response
14505            .expected_join
14506            .map(ResolvedExpected::Join)
14507            .ok_or_else(|| HarnessError::FixtureFormat("oracle omitted expected_join".to_owned())),
14508        FixtureOperation::GroupBySum => response
14509            .expected_series
14510            .map(ResolvedExpected::Series)
14511            .ok_or_else(|| {
14512                HarnessError::FixtureFormat("oracle omitted expected_series".to_owned())
14513            }),
14514        FixtureOperation::SeriesToArrowRoundTrip => response
14515            .expected_series
14516            .map(ResolvedExpected::Series)
14517            .ok_or_else(|| {
14518                HarnessError::FixtureFormat("oracle omitted expected_series".to_owned())
14519            }),
14520        FixtureOperation::IndexAlignUnion => response
14521            .expected_alignment
14522            .map(ResolvedExpected::Alignment)
14523            .ok_or_else(|| {
14524                HarnessError::FixtureFormat("oracle omitted expected_alignment".to_owned())
14525            }),
14526        FixtureOperation::IndexHasDuplicates
14527        | FixtureOperation::IndexIsMonotonicIncreasing
14528        | FixtureOperation::IndexIsMonotonicDecreasing => response
14529            .expected_bool
14530            .map(ResolvedExpected::Bool)
14531            .ok_or_else(|| HarnessError::FixtureFormat("oracle omitted expected_bool".to_owned())),
14532        FixtureOperation::SeriesAny
14533        | FixtureOperation::SeriesAll
14534        | FixtureOperation::SeriesBool => response
14535            .expected_bool
14536            .map(ResolvedExpected::Bool)
14537            .ok_or_else(|| HarnessError::FixtureFormat("oracle omitted expected_bool".to_owned())),
14538        FixtureOperation::IndexFirstPositions => response
14539            .expected_positions
14540            .map(ResolvedExpected::Positions)
14541            .ok_or_else(|| {
14542                HarnessError::FixtureFormat("oracle omitted expected_positions".to_owned())
14543            }),
14544        FixtureOperation::SeriesConcat
14545        | FixtureOperation::SeriesConstructor
14546        | FixtureOperation::SeriesToDatetime
14547        | FixtureOperation::SeriesToTimedelta
14548        | FixtureOperation::SeriesTimedeltaTotalSeconds
14549        | FixtureOperation::FillNa
14550        | FixtureOperation::DropNa
14551        | FixtureOperation::SeriesFilter
14552        | FixtureOperation::SeriesHead
14553        | FixtureOperation::SeriesTail
14554        | FixtureOperation::SeriesValueCounts
14555        | FixtureOperation::SeriesSortIndex
14556        | FixtureOperation::SeriesSortValues
14557        | FixtureOperation::SeriesDiff
14558        | FixtureOperation::SeriesShift
14559        | FixtureOperation::SeriesPctChange
14560        | FixtureOperation::SeriesMode
14561        | FixtureOperation::SeriesRank
14562        | FixtureOperation::SeriesArgsort
14563        | FixtureOperation::SeriesDescribe
14564        | FixtureOperation::SeriesDuplicated
14565        | FixtureOperation::SeriesDropDuplicates
14566        | FixtureOperation::SeriesUnique
14567        | FixtureOperation::SeriesFactorize
14568        | FixtureOperation::SeriesWhere
14569        | FixtureOperation::SeriesMask
14570        | FixtureOperation::SeriesReplace
14571        | FixtureOperation::SeriesUpdate
14572        | FixtureOperation::SeriesMap
14573        | FixtureOperation::SeriesCategoricalFromCodes
14574        | FixtureOperation::SeriesXs
14575        | FixtureOperation::SeriesIsNa
14576        | FixtureOperation::SeriesNotNa
14577        | FixtureOperation::SeriesIsNull
14578        | FixtureOperation::SeriesNotNull
14579        | FixtureOperation::SeriesFillNa
14580        | FixtureOperation::SeriesDropNa
14581        | FixtureOperation::SeriesLoc
14582        | FixtureOperation::SeriesIloc
14583        | FixtureOperation::SeriesTake
14584        | FixtureOperation::SeriesRepeat
14585        | FixtureOperation::SeriesToNumeric
14586        | FixtureOperation::SeriesConvertDtypes
14587        | FixtureOperation::SeriesAstype
14588        | FixtureOperation::SeriesClip
14589        | FixtureOperation::SeriesAbs
14590        | FixtureOperation::SeriesRound
14591        | FixtureOperation::SeriesCumsum
14592        | FixtureOperation::SeriesCumprod
14593        | FixtureOperation::SeriesCummax
14594        | FixtureOperation::SeriesCummin
14595        | FixtureOperation::SeriesNlargest
14596        | FixtureOperation::SeriesNsmallest
14597        | FixtureOperation::SeriesBetween
14598        | FixtureOperation::SeriesCut
14599        | FixtureOperation::SeriesQcut
14600        | FixtureOperation::SeriesStrLower
14601        | FixtureOperation::SeriesStrUpper
14602        | FixtureOperation::SeriesStrCapitalize
14603        | FixtureOperation::SeriesStrStrip
14604        | FixtureOperation::SeriesStrLen
14605        | FixtureOperation::SeriesStrContains
14606        | FixtureOperation::SeriesStrStartswith
14607        | FixtureOperation::SeriesStrEndswith
14608        | FixtureOperation::SeriesStrReplace
14609        | FixtureOperation::SeriesStrLstrip
14610        | FixtureOperation::SeriesStrRstrip
14611        | FixtureOperation::SeriesStrTitle
14612        | FixtureOperation::SeriesStrSwapcase
14613        | FixtureOperation::SeriesStrZfill
14614        | FixtureOperation::SeriesStrCenter
14615        | FixtureOperation::SeriesStrLjust
14616        | FixtureOperation::SeriesStrRjust
14617        | FixtureOperation::SeriesStrPad
14618        | FixtureOperation::SeriesStrIsdigit
14619        | FixtureOperation::SeriesStrIsalpha
14620        | FixtureOperation::SeriesStrIsalnum
14621        | FixtureOperation::SeriesStrIsspace
14622        | FixtureOperation::SeriesStrIslower
14623        | FixtureOperation::SeriesStrIsupper
14624        | FixtureOperation::SeriesStrIsnumeric
14625        | FixtureOperation::SeriesStrFind
14626        | FixtureOperation::SeriesStrRfind
14627        | FixtureOperation::SeriesStrSlice
14628        | FixtureOperation::SeriesStrGet
14629        | FixtureOperation::SeriesStrRepeat
14630        | FixtureOperation::SeriesStrCount
14631        | FixtureOperation::SeriesStrWrap
14632        | FixtureOperation::SeriesStrNormalize
14633        | FixtureOperation::SeriesStrFullmatch
14634        | FixtureOperation::SeriesStrMatch
14635        | FixtureOperation::SeriesStrRemoveprefix
14636        | FixtureOperation::SeriesStrRemovesuffix
14637        | FixtureOperation::SeriesStrSplitGet
14638        | FixtureOperation::SeriesStrJoin
14639        | FixtureOperation::SeriesStrIsdecimal
14640        | FixtureOperation::SeriesStrIstitle
14641        | FixtureOperation::SeriesStrCasefold
14642        | FixtureOperation::SeriesStrEncode
14643        | FixtureOperation::SeriesStrDecode
14644        | FixtureOperation::SeriesStrTranslate
14645        | FixtureOperation::SeriesStrExpandtabs
14646        | FixtureOperation::SeriesStrIndexOf
14647        | FixtureOperation::SeriesStrRindexOf
14648        | FixtureOperation::SeriesStrSplitCount
14649        | FixtureOperation::SeriesStrRsplitGet
14650        | FixtureOperation::SeriesStrSplitRegexGet
14651        | FixtureOperation::SeriesStrCountMatches
14652        | FixtureOperation::SeriesStrCountLiteral
14653        | FixtureOperation::SeriesStrFindall
14654        | FixtureOperation::SeriesStrContainsAny
14655        | FixtureOperation::SeriesStrStartswithAny
14656        | FixtureOperation::SeriesStrEndswithAny
14657        | FixtureOperation::SeriesDtYear
14658        | FixtureOperation::SeriesDtMonth
14659        | FixtureOperation::SeriesDtDay
14660        | FixtureOperation::SeriesDtHour
14661        | FixtureOperation::SeriesDtMinute
14662        | FixtureOperation::SeriesDtSecond
14663        | FixtureOperation::SeriesDtMicrosecond
14664        | FixtureOperation::SeriesDtNanosecond
14665        | FixtureOperation::SeriesDtDayofweek
14666        | FixtureOperation::SeriesDtQuarter
14667        | FixtureOperation::SeriesDtDayofyear
14668        | FixtureOperation::SeriesDtWeekofyear
14669        | FixtureOperation::SeriesDtIsMonthStart
14670        | FixtureOperation::SeriesDtIsMonthEnd
14671        | FixtureOperation::SeriesDtIsYearStart
14672        | FixtureOperation::SeriesDtIsYearEnd
14673        | FixtureOperation::SeriesDtDate
14674        | FixtureOperation::SeriesDtDaysInMonth
14675        | FixtureOperation::SeriesDtIsLeapYear
14676        | FixtureOperation::SeriesDtIsQuarterStart
14677        | FixtureOperation::SeriesDtIsQuarterEnd
14678        | FixtureOperation::SeriesDtStrftime
14679        | FixtureOperation::SeriesDtTzConvert
14680        | FixtureOperation::SeriesDtTzLocalize
14681        | FixtureOperation::SeriesDtTimetz
14682        | FixtureOperation::SeriesDtToPeriod
14683        | FixtureOperation::SeriesDtFloor
14684        | FixtureOperation::SeriesDtCeil
14685        | FixtureOperation::SeriesDtRound
14686        | FixtureOperation::SeriesDtMonthName
14687        | FixtureOperation::SeriesDtDayName
14688        | FixtureOperation::SeriesDtTotalSeconds
14689        | FixtureOperation::SeriesDtDays
14690        | FixtureOperation::SeriesDtSeconds
14691        | FixtureOperation::SeriesDtMicroseconds
14692        | FixtureOperation::SeriesDtNanoseconds
14693        | FixtureOperation::SeriesDtToTimestamp
14694        | FixtureOperation::SeriesDtToPytimedelta
14695        | FixtureOperation::SeriesDtToPydatetime
14696        | FixtureOperation::SeriesAtTime
14697        | FixtureOperation::SeriesBetweenTime
14698        | FixtureOperation::DataFrameGroupByCumcount
14699        | FixtureOperation::DataFrameGroupByNgroup
14700        | FixtureOperation::DataFrameAsof
14701        | FixtureOperation::DataFrameEval
14702        | FixtureOperation::DataFrameCount
14703        | FixtureOperation::DataFrameIdxmin
14704        | FixtureOperation::DataFrameIdxmax
14705        | FixtureOperation::DataFrameSem
14706        | FixtureOperation::DataFrameApplySemAxis0
14707        | FixtureOperation::DataFrameSkew
14708        | FixtureOperation::DataFrameKurtosis
14709        | FixtureOperation::DataFrameProd
14710        | FixtureOperation::DataFrameApplyProdAxis1
14711        | FixtureOperation::DataFrameApplyProductAxis1
14712        | FixtureOperation::DataFrameSum
14713        | FixtureOperation::DataFrameMean
14714        | FixtureOperation::DataFrameStd
14715        | FixtureOperation::DataFrameVar
14716        | FixtureOperation::DataFrameMin
14717        | FixtureOperation::DataFrameMax
14718        | FixtureOperation::DataFrameMedian
14719        | FixtureOperation::DataFrameAny
14720        | FixtureOperation::DataFrameAll
14721        | FixtureOperation::DataFrameNunique
14722        | FixtureOperation::DataFrameApplyNuniqueAxis0
14723        | FixtureOperation::DataFrameQuantile
14724        | FixtureOperation::DataFrameValueCounts
14725        | FixtureOperation::DataFrameMemoryUsage
14726        | FixtureOperation::DataFrameDuplicated
14727        | FixtureOperation::GroupByMean
14728        | FixtureOperation::GroupByCount
14729        | FixtureOperation::GroupByMin
14730        | FixtureOperation::GroupByMax
14731        | FixtureOperation::GroupByFirst
14732        | FixtureOperation::GroupByLast
14733        | FixtureOperation::GroupByStd
14734        | FixtureOperation::GroupByVar
14735        | FixtureOperation::GroupByMedian
14736        | FixtureOperation::SeriesCombineFirst
14737        | FixtureOperation::SeriesRollingMean
14738        | FixtureOperation::SeriesRollingSum
14739        | FixtureOperation::SeriesRollingStd
14740        | FixtureOperation::SeriesRollingMin
14741        | FixtureOperation::SeriesRollingMax
14742        | FixtureOperation::SeriesRollingVar
14743        | FixtureOperation::SeriesRollingCount
14744        | FixtureOperation::SeriesExpandingCount
14745        | FixtureOperation::SeriesExpandingQuantile
14746        | FixtureOperation::SeriesExpandingSum
14747        | FixtureOperation::SeriesExpandingMean
14748        | FixtureOperation::SeriesExpandingMin
14749        | FixtureOperation::SeriesExpandingMax
14750        | FixtureOperation::SeriesExpandingStd
14751        | FixtureOperation::SeriesExpandingVar
14752        | FixtureOperation::SeriesEwmMean
14753        | FixtureOperation::SeriesResampleSum
14754        | FixtureOperation::SeriesResampleMean
14755        | FixtureOperation::SeriesResampleCount
14756        | FixtureOperation::SeriesResampleAsfreq
14757        | FixtureOperation::SeriesResampleFfill
14758        | FixtureOperation::SeriesResampleBfill => response
14759            .expected_series
14760            .map(ResolvedExpected::Series)
14761            .ok_or_else(|| {
14762                HarnessError::FixtureFormat("oracle omitted expected_series".to_owned())
14763            }),
14764        FixtureOperation::DataFrameBool => response
14765            .expected_bool
14766            .map(ResolvedExpected::Bool)
14767            .ok_or_else(|| HarnessError::FixtureFormat("oracle omitted expected_bool".to_owned())),
14768        FixtureOperation::DataFrameLoc
14769        | FixtureOperation::DataFrameIdentity
14770        | FixtureOperation::SeriesExtractAll
14771        | FixtureOperation::SeriesToFrame
14772        | FixtureOperation::SeriesUnstack
14773        | FixtureOperation::SeriesStrGetDummies
14774        | FixtureOperation::DataFrameIloc
14775        | FixtureOperation::DataFrameTake
14776        | FixtureOperation::DataFrameFilter
14777        | FixtureOperation::DataFrameXs
14778        | FixtureOperation::DataFrameGroupBySum
14779        | FixtureOperation::DataFrameGroupByAggMulti
14780        | FixtureOperation::DataFrameGroupByIdxMin
14781        | FixtureOperation::DataFrameGroupByIdxMax
14782        | FixtureOperation::DataFrameGroupByAny
14783        | FixtureOperation::DataFrameGroupByAll
14784        | FixtureOperation::DataFrameGroupByGetGroup
14785        | FixtureOperation::DataFrameGroupByFfill
14786        | FixtureOperation::DataFrameGroupByBfill
14787        | FixtureOperation::DataFrameGroupBySem
14788        | FixtureOperation::DataFrameGroupBySkew
14789        | FixtureOperation::DataFrameGroupByKurtosis
14790        | FixtureOperation::DataFrameGroupByOhlc
14791        | FixtureOperation::DataFrameAtTime
14792        | FixtureOperation::DataFrameBetweenTime
14793        | FixtureOperation::DataFrameHead
14794        | FixtureOperation::DataFrameTail
14795        | FixtureOperation::DataFrameCompare
14796        | FixtureOperation::DataFrameQuery
14797        | FixtureOperation::DataFrameMode
14798        | FixtureOperation::DataFrameCumsum
14799        | FixtureOperation::DataFrameCumprod
14800        | FixtureOperation::DataFrameCummax
14801        | FixtureOperation::DataFrameCummin
14802        | FixtureOperation::DataFrameAstype
14803        | FixtureOperation::DataFrameClip
14804        | FixtureOperation::DataFrameAbs
14805        | FixtureOperation::DataFrameDescribe
14806        | FixtureOperation::DataFrameCorr
14807        | FixtureOperation::DataFrameCov
14808        | FixtureOperation::DataFrameRound
14809        | FixtureOperation::DataFrameBinaryAlias
14810        | FixtureOperation::DataFrameRank
14811        | FixtureOperation::DataFrameFromSeries
14812        | FixtureOperation::DataFrameFromDict
14813        | FixtureOperation::DataFrameFromRecords
14814        | FixtureOperation::DataFrameConstructorKwargs
14815        | FixtureOperation::DataFrameConstructorScalar
14816        | FixtureOperation::DataFrameConstructorDictOfSeries
14817        | FixtureOperation::DataFrameConstructorListLike
14818        | FixtureOperation::DataFrameIsNa
14819        | FixtureOperation::DataFrameNotNa
14820        | FixtureOperation::DataFrameIsNull
14821        | FixtureOperation::DataFrameNotNull
14822        | FixtureOperation::DataFrameFillNa
14823        | FixtureOperation::DataFrameDropNa
14824        | FixtureOperation::DataFrameDropNaColumns
14825        | FixtureOperation::DataFrameSetIndex
14826        | FixtureOperation::DataFrameResetIndex
14827        | FixtureOperation::DataFrameInsert
14828        | FixtureOperation::DataFrameAssign
14829        | FixtureOperation::DataFrameRenameColumns
14830        | FixtureOperation::DataFrameReindex
14831        | FixtureOperation::DataFrameReindexColumns
14832        | FixtureOperation::DataFrameDropColumns
14833        | FixtureOperation::DataFrameReplace
14834        | FixtureOperation::DataFrameWhere
14835        | FixtureOperation::DataFrameWhereDf
14836        | FixtureOperation::DataFrameMask
14837        | FixtureOperation::DataFrameMaskDf
14838        | FixtureOperation::DataFrameDropDuplicates
14839        | FixtureOperation::DataFrameExplode
14840        | FixtureOperation::DataFrameMerge
14841        | FixtureOperation::DataFrameMergeIndex
14842        | FixtureOperation::DataFrameMergeAsof
14843        | FixtureOperation::DataFrameMergeOrdered
14844        | FixtureOperation::DataFrameConcat
14845        | FixtureOperation::DataFrameSortIndex
14846        | FixtureOperation::DataFrameSortValues
14847        | FixtureOperation::DataFrameNlargest
14848        | FixtureOperation::DataFrameNsmallest
14849        | FixtureOperation::DataFrameDiff
14850        | FixtureOperation::DataFrameShift
14851        | FixtureOperation::DataFramePctChange
14852        | FixtureOperation::DataFrameMelt
14853        | FixtureOperation::DataFramePivot
14854        | FixtureOperation::DataFramePivotTable
14855        | FixtureOperation::DataFrameStack
14856        | FixtureOperation::DataFrameTranspose
14857        | FixtureOperation::DataFrameCrosstab
14858        | FixtureOperation::DataFrameCrosstabNormalize
14859        | FixtureOperation::DataFrameGetDummies
14860        | FixtureOperation::DataFrameCombineFirst
14861        | FixtureOperation::SeriesPartitionDf
14862        | FixtureOperation::SeriesRpartitionDf
14863        | FixtureOperation::SeriesSplitDf
14864        | FixtureOperation::SeriesExtractDf
14865        | FixtureOperation::CsvReadFrame
14866        | FixtureOperation::DataFrameRollingMean
14867        | FixtureOperation::DataFrameResampleSum
14868        | FixtureOperation::DataFrameResampleMean
14869        | FixtureOperation::DataFrameGroupByRollingMean
14870        | FixtureOperation::DataFrameGroupByRollingSum
14871        | FixtureOperation::DataFrameGroupByRollingMin
14872        | FixtureOperation::DataFrameGroupByRollingMax
14873        | FixtureOperation::DataFrameGroupByRollingCount
14874        | FixtureOperation::DataFrameGroupByRollingStd
14875        | FixtureOperation::DataFrameGroupByRollingVar
14876        | FixtureOperation::DataFrameGroupByResampleMin
14877        | FixtureOperation::DataFrameGroupByResampleMax
14878        | FixtureOperation::DataFrameGroupByResampleCount
14879        | FixtureOperation::DataFrameGroupByResampleFirst
14880        | FixtureOperation::DataFrameGroupByResampleLast => response
14881            .expected_frame
14882            .map(ResolvedExpected::Frame)
14883            .ok_or_else(|| HarnessError::FixtureFormat("oracle omitted expected_frame".to_owned())),
14884        FixtureOperation::NanSum
14885        | FixtureOperation::NanMean
14886        | FixtureOperation::NanMin
14887        | FixtureOperation::NanMax
14888        | FixtureOperation::NanStd
14889        | FixtureOperation::NanVar
14890        | FixtureOperation::NanCount
14891        | FixtureOperation::SeriesAsof
14892        | FixtureOperation::SeriesAutocorr
14893        | FixtureOperation::SeriesCount
14894        | FixtureOperation::SeriesNunique
14895        | FixtureOperation::SeriesFirstValidIndex
14896        | FixtureOperation::SeriesLastValidIndex
14897        | FixtureOperation::SeriesIdxmin
14898        | FixtureOperation::SeriesIdxmax
14899        | FixtureOperation::SeriesArgmin
14900        | FixtureOperation::SeriesArgmax
14901        | FixtureOperation::SeriesSearchsorted
14902        | FixtureOperation::SeriesDot
14903        | FixtureOperation::DataFrameToJsonRecords => response
14904            .expected_scalar
14905            .map(ResolvedExpected::Scalar)
14906            .ok_or_else(|| {
14907                HarnessError::FixtureFormat("oracle omitted expected_scalar".to_owned())
14908            }),
14909        FixtureOperation::CsvRoundTrip
14910        | FixtureOperation::JsonRoundTrip
14911        | FixtureOperation::JsonlRoundTrip
14912        | FixtureOperation::ParquetRoundTrip
14913        | FixtureOperation::FeatherRoundTrip
14914        | FixtureOperation::ExcelRoundTrip
14915        | FixtureOperation::IpcStreamRoundTrip => response
14916            .expected_bool
14917            .map(ResolvedExpected::Bool)
14918            .ok_or_else(|| HarnessError::FixtureFormat("oracle omitted expected_bool".to_owned())),
14919        FixtureOperation::ColumnDtypeCheck | FixtureOperation::SeriesDtypeCheck => response
14920            .expected_dtype
14921            .map(ResolvedExpected::Dtype)
14922            .ok_or_else(|| HarnessError::FixtureFormat("oracle omitted expected_dtype".to_owned())),
14923    }
14924}
14925
14926pub fn optional_index_label_to_scalar(label: Option<fp_index::IndexLabel>) -> Scalar {
14927    match label {
14928        None => Scalar::Null(NullKind::Null),
14929        Some(ref l) => index_label_to_scalar(l),
14930    }
14931}
14932
14933fn series_idx_skipna(fixture: &PacketFixture) -> bool {
14934    match fixture.operation {
14935        FixtureOperation::SeriesIdxmin => fixture.idxmin_skipna.unwrap_or(true),
14936        FixtureOperation::SeriesIdxmax => fixture.idxmax_skipna.unwrap_or(true),
14937        _ => true,
14938    }
14939}
14940
14941fn execute_series_idx_fixture_scalar(fixture: &PacketFixture) -> Result<Scalar, String> {
14942    let left = require_left_series(fixture)?;
14943    let series = build_series(left)?;
14944    let skipna = series_idx_skipna(fixture);
14945    if !skipna && series.values().iter().any(Scalar::is_missing) {
14946        return Ok(Scalar::Null(NullKind::NaN));
14947    }
14948
14949    let label = match fixture.operation {
14950        FixtureOperation::SeriesIdxmin => series.idxmin(),
14951        FixtureOperation::SeriesIdxmax => series.idxmax(),
14952        _ => return Err("series idx fixture scalar requires idxmin or idxmax".to_owned()),
14953    }
14954    .map_err(|err| err.to_string())?;
14955    Ok(index_label_to_scalar(&label))
14956}
14957
14958fn execute_series_arg_fixture_scalar(fixture: &PacketFixture) -> Result<Scalar, String> {
14959    let left = require_left_series(fixture)?;
14960    let series = build_series(left)?;
14961    let idx = match fixture.operation {
14962        FixtureOperation::SeriesArgmin => {
14963            series.argmin_skipna(fixture.argmin_skipna.unwrap_or(true))
14964        }
14965        FixtureOperation::SeriesArgmax => {
14966            series.argmax_skipna(fixture.argmax_skipna.unwrap_or(true))
14967        }
14968        _ => return Err("series arg fixture scalar requires argmin or argmax".to_owned()),
14969    }
14970    .map_err(|err| err.to_string())?;
14971    Ok(Scalar::Int64(idx))
14972}
14973
14974fn execute_series_searchsorted_fixture(fixture: &PacketFixture) -> Result<Scalar, String> {
14975    let left = require_left_series(fixture)?;
14976    let series = build_series(left)?;
14977    let needle = fixture
14978        .searchsorted_value
14979        .as_ref()
14980        .ok_or_else(|| "series_searchsorted requires searchsorted_value".to_owned())?;
14981    let side = fixture.searchsorted_side.as_deref().unwrap_or("left");
14982    let pos = series
14983        .searchsorted(needle, side)
14984        .map_err(|err| err.to_string())?;
14985    Ok(Scalar::Int64(pos as i64))
14986}
14987
14988fn execute_series_dot_fixture(fixture: &PacketFixture) -> Result<Scalar, String> {
14989    let left = require_left_series(fixture)?;
14990    let right = require_right_series(fixture)?;
14991    let left_series = build_series(left)?;
14992    let right_series = build_series(right)?;
14993    let result = left_series
14994        .dot(&right_series)
14995        .map_err(|err| err.to_string())?;
14996    Ok(Scalar::Float64(result))
14997}
14998
14999fn require_left_series(fixture: &PacketFixture) -> Result<&FixtureSeries, String> {
15000    fixture
15001        .left
15002        .as_ref()
15003        .ok_or_else(|| "missing left fixture series".to_owned())
15004}
15005
15006fn require_right_series(fixture: &PacketFixture) -> Result<&FixtureSeries, String> {
15007    fixture
15008        .right
15009        .as_ref()
15010        .ok_or_else(|| "missing right fixture series".to_owned())
15011}
15012
15013fn require_replacement_pairs(
15014    fixture: &PacketFixture,
15015    operation: &str,
15016) -> Result<Vec<(Scalar, Scalar)>, String> {
15017    let to_find = fixture
15018        .replace_to_find
15019        .as_ref()
15020        .ok_or_else(|| format!("replace_to_find required for {operation}"))?;
15021    let to_value = fixture
15022        .replace_to_value
15023        .as_ref()
15024        .ok_or_else(|| format!("replace_to_value required for {operation}"))?;
15025    if to_find.len() != to_value.len() {
15026        return Err(format!(
15027            "{operation} replacement lists must match in length: replace_to_find={}, replace_to_value={}",
15028            to_find.len(),
15029            to_value.len()
15030        ));
15031    }
15032    Ok(to_find
15033        .iter()
15034        .zip(to_value.iter())
15035        .map(|(from, to)| (from.clone(), to.clone()))
15036        .collect())
15037}
15038
15039fn require_frame(fixture: &PacketFixture) -> Result<&FixtureDataFrame, String> {
15040    fixture
15041        .frame
15042        .as_ref()
15043        .ok_or_else(|| "missing frame fixture payload".to_owned())
15044}
15045
15046fn require_expr<'a>(fixture: &'a PacketFixture, operation: &str) -> Result<&'a str, String> {
15047    let expr = fixture
15048        .expr
15049        .as_deref()
15050        .ok_or_else(|| format!("{operation} requires expr payload"))?;
15051    if expr.trim().is_empty() {
15052        return Err(format!("{operation} requires non-empty expr payload"));
15053    }
15054    Ok(expr)
15055}
15056
15057fn require_frame_right(fixture: &PacketFixture) -> Result<&FixtureDataFrame, String> {
15058    fixture
15059        .frame_right
15060        .as_ref()
15061        .ok_or_else(|| "missing frame_right fixture payload".to_owned())
15062}
15063
15064fn require_frame_other(fixture: &PacketFixture) -> Result<&FixtureDataFrame, String> {
15065    fixture
15066        .frame_other
15067        .as_ref()
15068        .ok_or_else(|| "missing frame_other fixture payload".to_owned())
15069}
15070
15071fn require_dict_columns(fixture: &PacketFixture) -> Result<&BTreeMap<String, Vec<Scalar>>, String> {
15072    fixture
15073        .dict_columns
15074        .as_ref()
15075        .ok_or_else(|| "missing dict_columns fixture payload".to_owned())
15076}
15077
15078fn require_matrix_rows(fixture: &PacketFixture) -> Result<&Vec<Vec<Scalar>>, String> {
15079    fixture
15080        .matrix_rows
15081        .as_ref()
15082        .ok_or_else(|| "missing matrix_rows fixture payload".to_owned())
15083}
15084
15085fn require_index(fixture: &PacketFixture) -> Result<&Vec<IndexLabel>, String> {
15086    fixture
15087        .index
15088        .as_ref()
15089        .ok_or_else(|| "missing index fixture vector".to_owned())
15090}
15091
15092fn require_join_type(fixture: &PacketFixture) -> Result<FixtureJoinType, String> {
15093    fixture
15094        .join_type
15095        .ok_or_else(|| "missing join_type for join fixture".to_owned())
15096}
15097
15098fn require_series_join_type(fixture: &PacketFixture) -> Result<JoinType, String> {
15099    let join_type = require_join_type(fixture)?;
15100    if matches!(join_type, FixtureJoinType::Cross) {
15101        return Err(
15102            "series_join requires join_type=inner|left|right|outer, got 'cross'".to_owned(),
15103        );
15104    }
15105    Ok(join_type.into_join_type())
15106}
15107
15108fn resolve_merge_on_keys(
15109    merge_on: Option<&str>,
15110    merge_on_keys: Option<&[String]>,
15111    operation_name: &str,
15112    default_key: Option<&str>,
15113) -> Result<Vec<String>, String> {
15114    if let Some(keys) = merge_on_keys {
15115        if keys.is_empty() {
15116            return Err(format!(
15117                "{operation_name} requires merge_on_keys with at least one key"
15118            ));
15119        }
15120        let mut resolved = Vec::with_capacity(keys.len());
15121        for (index, key) in keys.iter().enumerate() {
15122            let key = key.trim();
15123            if key.is_empty() {
15124                return Err(format!(
15125                    "{operation_name} merge_on_keys[{index}] must be a non-empty string"
15126                ));
15127            }
15128            resolved.push(key.to_owned());
15129        }
15130        return Ok(resolved);
15131    }
15132
15133    if let Some(key) = merge_on {
15134        let key = key.trim();
15135        if key.is_empty() {
15136            return Err(format!(
15137                "{operation_name} merge_on must be a non-empty string"
15138            ));
15139        }
15140        return Ok(vec![key.to_owned()]);
15141    }
15142
15143    if let Some(key) = default_key {
15144        return Ok(vec![key.to_owned()]);
15145    }
15146
15147    Err(format!(
15148        "{operation_name} requires merge_on string or merge_on_keys list payload"
15149    ))
15150}
15151
15152fn normalize_key_list(
15153    keys: &[String],
15154    operation_name: &str,
15155    field_name: &str,
15156) -> Result<Vec<String>, String> {
15157    if keys.is_empty() {
15158        return Err(format!(
15159            "{operation_name} requires {field_name} with at least one key"
15160        ));
15161    }
15162    let mut normalized = Vec::with_capacity(keys.len());
15163    for (index, key) in keys.iter().enumerate() {
15164        let key = key.trim();
15165        if key.is_empty() {
15166            return Err(format!(
15167                "{operation_name} {field_name}[{index}] must be a non-empty string"
15168            ));
15169        }
15170        normalized.push(key.to_owned());
15171    }
15172    Ok(normalized)
15173}
15174
15175fn resolve_merge_key_pairs(
15176    merge_on: Option<&str>,
15177    merge_on_keys: Option<&[String]>,
15178    left_on_keys: Option<&[String]>,
15179    right_on_keys: Option<&[String]>,
15180    operation_name: &str,
15181    default_key: Option<&str>,
15182) -> Result<(Vec<String>, Vec<String>), String> {
15183    if left_on_keys.is_some() || right_on_keys.is_some() {
15184        let left = left_on_keys.ok_or_else(|| {
15185            format!("{operation_name} requires right_on_keys when left_on_keys is provided")
15186        })?;
15187        let right = right_on_keys.ok_or_else(|| {
15188            format!("{operation_name} requires left_on_keys when right_on_keys is provided")
15189        })?;
15190        let left_keys = normalize_key_list(left, operation_name, "left_on_keys")?;
15191        let right_keys = normalize_key_list(right, operation_name, "right_on_keys")?;
15192        if left_keys.len() != right_keys.len() {
15193            return Err(format!(
15194                "{operation_name} left_on_keys and right_on_keys must have equal length"
15195            ));
15196        }
15197        return Ok((left_keys, right_keys));
15198    }
15199
15200    let keys = resolve_merge_on_keys(merge_on, merge_on_keys, operation_name, default_key)?;
15201    Ok((keys.clone(), keys))
15202}
15203
15204fn resolve_merge_indicator_name(
15205    merge_indicator: Option<bool>,
15206    merge_indicator_name: Option<&str>,
15207    operation_name: &str,
15208) -> Result<Option<String>, String> {
15209    if matches!(merge_indicator, Some(false)) && merge_indicator_name.is_some() {
15210        return Err(format!(
15211            "{operation_name} merge_indicator_name requires merge_indicator=true when explicitly provided"
15212        ));
15213    }
15214
15215    if let Some(name) = merge_indicator_name {
15216        if name.trim().is_empty() {
15217            return Err(format!(
15218                "{operation_name} merge_indicator_name must be a non-empty string"
15219            ));
15220        }
15221        return Ok(Some(name.to_owned()));
15222    }
15223
15224    if merge_indicator.unwrap_or(false) {
15225        return Ok(Some("_merge".to_owned()));
15226    }
15227
15228    Ok(None)
15229}
15230
15231fn resolve_merge_validate_mode(
15232    merge_validate: Option<&str>,
15233    operation_name: &str,
15234) -> Result<Option<MergeValidateMode>, String> {
15235    let Some(raw_mode) = merge_validate else {
15236        return Ok(None);
15237    };
15238    let normalized = raw_mode.trim().to_ascii_lowercase();
15239    let mode = match normalized.as_str() {
15240        "one_to_one" | "1:1" => MergeValidateMode::OneToOne,
15241        "one_to_many" | "1:m" => MergeValidateMode::OneToMany,
15242        "many_to_one" | "m:1" => MergeValidateMode::ManyToOne,
15243        "many_to_many" | "m:m" => MergeValidateMode::ManyToMany,
15244        _ => {
15245            return Err(format!(
15246                "{operation_name} merge_validate must be one_to_one, one_to_many, many_to_one, or many_to_many"
15247            ));
15248        }
15249    };
15250    Ok(Some(mode))
15251}
15252
15253fn resolve_merge_suffixes(
15254    merge_suffixes: Option<&[Option<String>; 2]>,
15255) -> Option<[Option<String>; 2]> {
15256    merge_suffixes.cloned()
15257}
15258
15259fn resolve_merge_sort(merge_sort: Option<bool>) -> bool {
15260    merge_sort.unwrap_or(false)
15261}
15262
15263fn execute_dataframe_merge_asof_fixture_operation(
15264    fixture: &PacketFixture,
15265) -> Result<DataFrame, String> {
15266    let left = build_dataframe(require_frame(fixture)?)
15267        .map_err(|err| format!("left frame build failed: {err}"))?;
15268    let right = build_dataframe(require_frame_right(fixture)?)
15269        .map_err(|err| format!("right frame build failed: {err}"))?;
15270
15271    let on = fixture
15272        .merge_on
15273        .as_deref()
15274        .ok_or_else(|| "merge_on field required for dataframe_merge_asof".to_owned())?;
15275
15276    let direction_str = fixture.direction.as_deref().unwrap_or("backward");
15277    let direction = match direction_str {
15278        "backward" => fp_join::AsofDirection::Backward,
15279        "forward" => fp_join::AsofDirection::Forward,
15280        "nearest" => fp_join::AsofDirection::Nearest,
15281        _ => return Err(format!("invalid merge_asof direction: {direction_str}")),
15282    };
15283
15284    // Build options from fixture fields
15285    let mut options = fp_join::MergeAsofOptions::new();
15286
15287    // allow_exact_matches defaults to true in both pandas and our impl
15288    if let Some(allow) = fixture.allow_exact_matches {
15289        options = options.allow_exact_matches(allow);
15290    }
15291
15292    // tolerance: maximum distance for a match
15293    if let Some(tol) = fixture.tolerance {
15294        options = options.tolerance(tol);
15295    }
15296
15297    // by: columns to match exactly before asof matching
15298    if let Some(ref by_cols) = fixture.merge_asof_by {
15299        options = options.by(by_cols.clone());
15300    }
15301
15302    let merged = fp_join::merge_asof_with_options(&left, &right, on, direction, options)
15303        .map_err(|err| err.to_string())?;
15304    DataFrame::new_with_column_order(merged.index, merged.columns, merged.column_order)
15305        .map_err(|err| err.to_string())
15306}
15307
15308fn execute_dataframe_merge_ordered_fixture_operation(
15309    fixture: &PacketFixture,
15310) -> Result<DataFrame, String> {
15311    let left = build_dataframe(require_frame(fixture)?)
15312        .map_err(|err| format!("left frame build failed: {err}"))?;
15313    let right = build_dataframe(require_frame_right(fixture)?)
15314        .map_err(|err| format!("right frame build failed: {err}"))?;
15315
15316    let on_keys = if let Some(keys) = fixture.merge_on_keys.as_ref() {
15317        keys.iter().map(String::as_str).collect::<Vec<_>>()
15318    } else if let Some(key) = fixture.merge_on.as_deref() {
15319        vec![key]
15320    } else {
15321        return Err("merge_on or merge_on_keys field required for dataframe_merge_ordered".into());
15322    };
15323
15324    let merged = merge_ordered(
15325        &left,
15326        &right,
15327        &on_keys,
15328        fixture.merge_fill_method.as_deref(),
15329    )
15330    .map_err(|err| err.to_string())?;
15331    DataFrame::new_with_column_order(merged.index, merged.columns, merged.column_order)
15332        .map_err(|err| err.to_string())
15333}
15334
15335fn validate_cross_merge_configuration(
15336    fixture: &PacketFixture,
15337    operation_name: &str,
15338    merge_on_index: bool,
15339) -> Result<(), String> {
15340    if merge_on_index {
15341        return Err(format!(
15342            "{operation_name} does not support join_type='cross'"
15343        ));
15344    }
15345
15346    if fixture.merge_on.is_some()
15347        || fixture.merge_on_keys.is_some()
15348        || fixture.left_on_keys.is_some()
15349        || fixture.right_on_keys.is_some()
15350    {
15351        return Err(format!(
15352            "{operation_name} join_type='cross' does not allow merge_on/merge_on_keys/left_on_keys/right_on_keys"
15353        ));
15354    }
15355
15356    if matches!(fixture.left_index, Some(true)) || matches!(fixture.right_index, Some(true)) {
15357        return Err(format!(
15358            "{operation_name} join_type='cross' does not allow left_index/right_index"
15359        ));
15360    }
15361
15362    Ok(())
15363}
15364
15365fn normalize_concat_axis(fixture: &PacketFixture) -> Result<i64, String> {
15366    let axis = fixture.concat_axis.unwrap_or(0);
15367    match axis {
15368        0 | 1 => Ok(axis),
15369        _ => Err(format!(
15370            "concat_axis must be 0 or 1 for dataframe_concat (got {axis})"
15371        )),
15372    }
15373}
15374
15375fn normalize_concat_join(fixture: &PacketFixture) -> Result<ConcatJoin, String> {
15376    let join = fixture.concat_join.as_deref().unwrap_or("outer");
15377    if join.eq_ignore_ascii_case("outer") {
15378        return Ok(ConcatJoin::Outer);
15379    }
15380    if join.eq_ignore_ascii_case("inner") {
15381        return Ok(ConcatJoin::Inner);
15382    }
15383    Err(format!(
15384        "concat_join must be 'outer' or 'inner' for dataframe_concat (got {join})"
15385    ))
15386}
15387
15388fn require_loc_labels(fixture: &PacketFixture) -> Result<&Vec<IndexLabel>, String> {
15389    fixture
15390        .loc_labels
15391        .as_ref()
15392        .ok_or_else(|| "loc_labels is required for loc operations".to_owned())
15393}
15394
15395fn require_iloc_positions(fixture: &PacketFixture) -> Result<&Vec<i64>, String> {
15396    fixture
15397        .iloc_positions
15398        .as_ref()
15399        .ok_or_else(|| "iloc_positions is required for iloc operations".to_owned())
15400}
15401
15402fn require_take_indices(fixture: &PacketFixture) -> Result<&Vec<i64>, String> {
15403    fixture
15404        .take_indices
15405        .as_ref()
15406        .ok_or_else(|| "take_indices is required for take operations".to_owned())
15407}
15408
15409fn require_cut_bins(fixture: &PacketFixture) -> Result<usize, String> {
15410    fixture
15411        .cut_bins
15412        .ok_or_else(|| "cut_bins is required for series_cut".to_owned())
15413}
15414
15415fn require_qcut_quantiles(fixture: &PacketFixture) -> Result<usize, String> {
15416    fixture
15417        .qcut_quantiles
15418        .ok_or_else(|| "qcut_quantiles is required for series_qcut".to_owned())
15419}
15420
15421fn require_xs_key<'a>(
15422    fixture: &'a PacketFixture,
15423    operation_name: &str,
15424) -> Result<&'a IndexLabel, String> {
15425    fixture
15426        .xs_key
15427        .as_ref()
15428        .ok_or_else(|| format!("xs_key is required for {operation_name}"))
15429}
15430
15431fn require_groupby_columns(
15432    fixture: &PacketFixture,
15433    operation_name: &str,
15434) -> Result<Vec<String>, String> {
15435    let columns =
15436        resolve_optional_string_list(fixture.groupby_columns.as_ref(), "groupby_columns")?;
15437    if columns.is_empty() {
15438        Err(format!("groupby_columns is required for {operation_name}"))
15439    } else {
15440        Ok(columns)
15441    }
15442}
15443
15444fn require_resample_freq<'a>(
15445    fixture: &'a PacketFixture,
15446    operation_name: &str,
15447) -> Result<&'a str, String> {
15448    fixture
15449        .resample_freq
15450        .as_deref()
15451        .ok_or_else(|| format!("resample_freq required for {operation_name}"))
15452}
15453
15454fn require_groupby_agg_multi(
15455    fixture: &PacketFixture,
15456    operation_name: &str,
15457) -> Result<OrderedFuncMap, String> {
15458    let Some(func_map) = fixture.groupby_agg_multi.as_ref() else {
15459        return Err(format!(
15460            "groupby_agg_multi is required for {operation_name}"
15461        ));
15462    };
15463
15464    Ok(func_map.clone())
15465}
15466
15467fn resolve_groupby_observed(fixture: &PacketFixture) -> bool {
15468    fixture.groupby_observed.unwrap_or(true)
15469}
15470
15471fn require_group_name<'a>(
15472    fixture: &'a PacketFixture,
15473    operation_name: &str,
15474) -> Result<&'a str, String> {
15475    fixture
15476        .group_name
15477        .as_deref()
15478        .ok_or_else(|| format!("group_name is required for {operation_name}"))
15479}
15480
15481fn require_asof_label(fixture: &PacketFixture) -> Result<&IndexLabel, String> {
15482    fixture.asof_label.as_ref().ok_or_else(|| {
15483        format!(
15484            "asof_label is required for {}",
15485            fixture.operation.operation_name()
15486        )
15487    })
15488}
15489
15490fn require_time_value(fixture: &PacketFixture) -> Result<&str, String> {
15491    fixture
15492        .time_value
15493        .as_deref()
15494        .ok_or_else(|| "time_value is required for at_time operations".to_owned())
15495}
15496
15497fn require_regex_pattern<'a>(
15498    fixture: &'a PacketFixture,
15499    operation_name: &str,
15500) -> Result<&'a str, String> {
15501    fixture
15502        .regex_pattern
15503        .as_deref()
15504        .ok_or_else(|| format!("regex_pattern is required for {operation_name}"))
15505}
15506
15507fn require_string_sep<'a>(
15508    fixture: &'a PacketFixture,
15509    operation_name: &str,
15510) -> Result<&'a str, String> {
15511    fixture
15512        .string_sep
15513        .as_deref()
15514        .ok_or_else(|| format!("string_sep is required for {operation_name}"))
15515}
15516
15517fn require_explode_column<'a>(
15518    fixture: &'a PacketFixture,
15519    operation_name: &str,
15520) -> Result<&'a str, String> {
15521    fixture
15522        .explode_column
15523        .as_deref()
15524        .ok_or_else(|| format!("explode_column is required for {operation_name}"))
15525}
15526
15527fn require_start_time(fixture: &PacketFixture) -> Result<&str, String> {
15528    fixture
15529        .start_time
15530        .as_deref()
15531        .ok_or_else(|| "start_time is required for between_time operations".to_owned())
15532}
15533
15534fn require_end_time(fixture: &PacketFixture) -> Result<&str, String> {
15535    fixture
15536        .end_time
15537        .as_deref()
15538        .ok_or_else(|| "end_time is required for between_time operations".to_owned())
15539}
15540
15541fn require_sort_column(fixture: &PacketFixture) -> Result<&str, String> {
15542    require_sort_column_for(fixture, "dataframe_sort_values")
15543}
15544
15545fn require_sort_column_for<'a>(
15546    fixture: &'a PacketFixture,
15547    operation_name: &str,
15548) -> Result<&'a str, String> {
15549    fixture
15550        .sort_column
15551        .as_deref()
15552        .ok_or_else(|| format!("sort_column is required for {operation_name}"))
15553}
15554
15555fn require_set_index_column(fixture: &PacketFixture) -> Result<&str, String> {
15556    fixture
15557        .set_index_column
15558        .as_deref()
15559        .ok_or_else(|| "set_index_column is required for dataframe_set_index".to_owned())
15560}
15561
15562fn require_set_index_drop(fixture: &PacketFixture) -> Result<bool, String> {
15563    fixture
15564        .set_index_drop
15565        .ok_or_else(|| "set_index_drop is required for dataframe_set_index".to_owned())
15566}
15567
15568fn resolve_set_index_verify_integrity(fixture: &PacketFixture) -> bool {
15569    fixture.set_index_verify_integrity.unwrap_or(false)
15570}
15571
15572fn require_reset_index_drop(fixture: &PacketFixture) -> Result<bool, String> {
15573    fixture
15574        .reset_index_drop
15575        .ok_or_else(|| "reset_index_drop is required for dataframe_reset_index".to_owned())
15576}
15577
15578fn resolve_duplicate_subset(fixture: &PacketFixture) -> Result<Option<Vec<String>>, String> {
15579    fixture
15580        .subset
15581        .as_ref()
15582        .map(|subset| {
15583            subset
15584                .iter()
15585                .map(|name| {
15586                    let trimmed = name.trim();
15587                    if trimmed.is_empty() {
15588                        Err("subset entries must be non-empty strings".to_owned())
15589                    } else {
15590                        Ok(trimmed.to_owned())
15591                    }
15592                })
15593                .collect::<Result<Vec<_>, _>>()
15594        })
15595        .transpose()
15596}
15597
15598fn resolve_optional_string_list(
15599    values: Option<&Vec<String>>,
15600    field_name: &str,
15601) -> Result<Vec<String>, String> {
15602    values
15603        .map(|items| {
15604            items
15605                .iter()
15606                .map(|item| {
15607                    let trimmed = item.trim();
15608                    if trimmed.is_empty() {
15609                        Err(format!("{field_name} entries must be non-empty strings"))
15610                    } else {
15611                        Ok(trimmed.to_owned())
15612                    }
15613                })
15614                .collect::<Result<Vec<_>, _>>()
15615        })
15616        .transpose()
15617        .map(|items| items.unwrap_or_default())
15618}
15619
15620fn require_pivot_value_names(fixture: &PacketFixture) -> Result<Vec<String>, String> {
15621    let values = resolve_optional_string_list(fixture.pivot_values.as_ref(), "pivot_values")?;
15622    if values.is_empty() {
15623        Err("pivot_values is required for dataframe_pivot_table".to_owned())
15624    } else {
15625        Ok(values)
15626    }
15627}
15628
15629fn require_pivot_index(fixture: &PacketFixture) -> Result<&str, String> {
15630    fixture
15631        .pivot_index
15632        .as_deref()
15633        .ok_or_else(|| "pivot_index is required for dataframe_pivot_table".to_owned())
15634}
15635
15636fn require_pivot_columns(fixture: &PacketFixture) -> Result<&str, String> {
15637    fixture
15638        .pivot_columns
15639        .as_deref()
15640        .ok_or_else(|| "pivot_columns is required for dataframe_pivot_table".to_owned())
15641}
15642
15643fn require_pivot_aggfunc(fixture: &PacketFixture) -> Result<&str, String> {
15644    fixture
15645        .pivot_aggfunc
15646        .as_deref()
15647        .ok_or_else(|| "pivot_aggfunc is required for dataframe_pivot_table".to_owned())
15648}
15649
15650fn require_crosstab_normalize(fixture: &PacketFixture) -> Result<&str, String> {
15651    fixture
15652        .crosstab_normalize
15653        .as_deref()
15654        .ok_or_else(|| "crosstab_normalize is required for dataframe_crosstab_normalize".to_owned())
15655}
15656
15657fn resolve_duplicate_keep(fixture: &PacketFixture) -> Result<DuplicateKeep, String> {
15658    let Some(keep) = fixture.keep.as_deref() else {
15659        return Ok(DuplicateKeep::First);
15660    };
15661    let keep = keep.trim();
15662    if keep.eq_ignore_ascii_case("first") {
15663        Ok(DuplicateKeep::First)
15664    } else if keep.eq_ignore_ascii_case("last") {
15665        Ok(DuplicateKeep::Last)
15666    } else if keep.eq_ignore_ascii_case("none") {
15667        Ok(DuplicateKeep::None)
15668    } else {
15669        Err(format!(
15670            "keep must be one of 'first', 'last', or 'none' (got '{keep}')"
15671        ))
15672    }
15673}
15674
15675fn resolve_drop_duplicates_ignore_index(fixture: &PacketFixture) -> bool {
15676    fixture.ignore_index.unwrap_or(false)
15677}
15678
15679fn resolve_sort_ascending(fixture: &PacketFixture) -> bool {
15680    fixture.sort_ascending.unwrap_or(true)
15681}
15682
15683fn resolve_value_counts_ascending(fixture: &PacketFixture) -> bool {
15684    fixture.sort_ascending.unwrap_or(false)
15685}
15686
15687fn resolve_value_counts_normalize(fixture: &PacketFixture) -> bool {
15688    fixture.value_counts_normalize.unwrap_or(false)
15689}
15690
15691fn resolve_memory_usage_index(fixture: &PacketFixture) -> bool {
15692    fixture.memory_usage_index.unwrap_or(true)
15693}
15694
15695fn resolve_memory_usage_deep(fixture: &PacketFixture) -> bool {
15696    fixture.memory_usage_deep.unwrap_or(false)
15697}
15698
15699fn resolve_rank_axis(fixture: &PacketFixture) -> Result<usize, String> {
15700    match fixture.rank_axis.unwrap_or(0) {
15701        axis @ (0 | 1) => Ok(axis),
15702        axis => Err(format!(
15703            "rank_axis must be 0 or 1 for dataframe_rank (got {axis})"
15704        )),
15705    }
15706}
15707
15708fn resolve_rank_pct(fixture: &PacketFixture) -> bool {
15709    fixture.rank_pct.unwrap_or(false)
15710}
15711
15712fn resolve_autocorr_lag(fixture: &PacketFixture) -> usize {
15713    fixture.autocorr_lag.unwrap_or(1)
15714}
15715
15716fn resolve_take_axis(fixture: &PacketFixture) -> Result<usize, String> {
15717    match fixture.take_axis.unwrap_or(0) {
15718        axis @ (0 | 1) => Ok(axis),
15719        axis => Err(format!(
15720            "take_axis must be 0 or 1 for dataframe_take (got {axis})"
15721        )),
15722    }
15723}
15724
15725fn resolve_filter_axis(fixture: &PacketFixture) -> Result<usize, String> {
15726    match fixture.filter_axis.unwrap_or(1) {
15727        axis @ (0 | 1) => Ok(axis),
15728        axis => Err(format!(
15729            "filter_axis must be 0 or 1 for dataframe_filter (got {axis})"
15730        )),
15731    }
15732}
15733
15734fn resolve_series_repeat_counts(fixture: &PacketFixture, len: usize) -> Result<Vec<usize>, String> {
15735    match (fixture.repeat_n, fixture.repeat_counts.as_ref()) {
15736        (Some(_), Some(_)) => {
15737            Err("series_repeat accepts either repeat_n or repeat_counts, but not both".to_owned())
15738        }
15739        (Some(repeat_n), None) => {
15740            let repeat_n = usize::try_from(repeat_n).map_err(|_| {
15741                format!("repeat_n must be non-negative for series_repeat (got {repeat_n})")
15742            })?;
15743            Ok(vec![repeat_n; len])
15744        }
15745        (None, Some(repeat_counts)) => {
15746            if repeat_counts.len() != len {
15747                return Err(format!(
15748                    "repeat_counts must contain {len} elements for series_repeat (got {})",
15749                    repeat_counts.len()
15750                ));
15751            }
15752            repeat_counts
15753                .iter()
15754                .map(|count| {
15755                    usize::try_from(*count).map_err(|_| {
15756                        format!(
15757                            "repeat_counts must be non-negative for series_repeat (got {count})"
15758                        )
15759                    })
15760                })
15761                .collect()
15762        }
15763        (None, None) => Err("series_repeat requires repeat_n or repeat_counts".to_owned()),
15764    }
15765}
15766
15767fn resolve_shift_axis(fixture: &PacketFixture) -> Result<usize, String> {
15768    match fixture.shift_axis.unwrap_or(0) {
15769        axis @ (0 | 1) => Ok(axis),
15770        axis => Err(format!(
15771            "shift_axis must be 0 or 1 for dataframe_shift (got {axis})"
15772        )),
15773    }
15774}
15775
15776fn normalize_head_take(n: i64, len: usize) -> usize {
15777    if n >= 0 {
15778        usize::try_from(n).unwrap_or(usize::MAX).min(len)
15779    } else {
15780        len.saturating_sub(usize::try_from(n.unsigned_abs()).unwrap_or(usize::MAX))
15781    }
15782}
15783
15784fn collect_constructor_series_payloads(
15785    fixture: &PacketFixture,
15786    op_name: &str,
15787) -> Result<Vec<FixtureSeries>, String> {
15788    let mut payloads = Vec::new();
15789    if let Some(left) = fixture.left.clone() {
15790        payloads.push(left);
15791    }
15792    if let Some(right) = fixture.right.clone() {
15793        payloads.push(right);
15794    }
15795    if let Some(extra) = fixture.groupby_keys.clone() {
15796        payloads.extend(extra);
15797    }
15798    if payloads.is_empty() {
15799        return Err(format!(
15800            "{op_name} requires at least one series payload (left/right/groupby_keys)"
15801        ));
15802    }
15803    Ok(payloads)
15804}
15805
15806fn parse_constructor_dtype_spec(dtype_spec: &str) -> Result<DType, String> {
15807    let trimmed = dtype_spec.trim();
15808
15809    // TIER 1 — EXACT, CASE-SENSITIVE. pandas' nullable extension dtypes differ
15810    // from the numpy ones BY CASE ALONE, and the difference is observable rather
15811    // than cosmetic (br-frankenpandas-jozfk). Live pandas 2.2.3:
15812    //
15813    //   pd.DataFrame([[True, None], [False, True]], dtype="Int64") -> Int64Dtype
15814    //   pd.DataFrame([[True, None], [False, True]], dtype="int64") -> TypeError
15815    //
15816    // `fp-types` encodes the same split on purpose — `Int64` vs `Int64Nullable`,
15817    // `Float64` vs `Float64Nullable`, with `#[serde(rename = "Int64")]` chosen so
15818    // the wire spelling IS pandas' spelling (br-frankenpandas-qkqfb). Lowercasing
15819    // first destroyed exactly that bit.
15820    //
15821    // WHY A TIER RATHER THAN JUST MAKING THE WHOLE MATCH CASE-SENSITIVE: the
15822    // corpus deliberately pins case-insensitive alias handling — `BOOLEAN`,
15823    // `STRING`, `Float`, and `"  INT64  "` with surrounding whitespace. Those are
15824    // ALIASES, not pandas dtypes (`INT64` is not a pandas dtype at all), so they
15825    // cannot collide with this tier, and ordering satisfies both intents at once.
15826    // The oracle's own docstring called the two intents "in genuine conflict";
15827    // they are only in conflict if the match is flat.
15828    match trimmed {
15829        "Int64" => return Ok(DType::Int64Nullable),
15830        "Float64" => return Ok(DType::Float64Nullable),
15831        _ => {}
15832    }
15833
15834    // TIER 2 — case-insensitive aliases, unchanged.
15835    let normalized = trimmed.to_ascii_lowercase();
15836    match normalized.as_str() {
15837        // numpy bool (nonzero-truthy) vs pandas nullable Boolean (strict 0/1).
15838        // (br-frankenpandas-tjomg)
15839        "bool" => Ok(DType::Bool),
15840        "boolean" => Ok(DType::BoolNullable),
15841        "int64" | "int" | "i64" => Ok(DType::Int64),
15842        "float64" | "float" | "f64" => Ok(DType::Float64),
15843        "utf8" | "string" | "str" => Ok(DType::Utf8),
15844        // `DType::Datetime64` already has a constructor path. Verified against
15845        // live pandas 2.2.3:
15846        //     pd.DataFrame([["2026-01-01"]], dtype="datetime64[ns]")
15847        //       -> dtype datetime64[ns], Timestamp('2026-01-01 00:00:00')
15848        // i.e. pandas SUCCEEDS where the corpus asserted it raises.
15849        "datetime64[ns]" | "datetime64" => Ok(DType::datetime64_naive()),
15850        // The conformance scalar wire format has no unsigned or Arrow-backed
15851        // storage tags. For values it can represent, constructor coercion uses
15852        // the corresponding scalar lane; the live differential locks below keep
15853        // the observable constructor results aligned with pandas.
15854        "uint64" => Ok(DType::Int64),
15855        "boolean[pyarrow]" => Ok(DType::Bool),
15856        // Object is deliberately a no-op in `apply_constructor_options`: mapping
15857        // it here keeps the accepted constructor vocabulary explicit, while the
15858        // no-op retains mixed Scalar values instead of stringifying them as Utf8.
15859        "object" => Ok(DType::Utf8),
15860        "category" | "categorical" => Ok(DType::Categorical),
15861        _ => Err(format!(
15862            "unsupported constructor dtype '{}'",
15863            dtype_spec.trim()
15864        )),
15865    }
15866}
15867
15868fn apply_constructor_options(
15869    fixture: &PacketFixture,
15870    operation_name: &str,
15871    frame: DataFrame,
15872) -> Result<DataFrame, String> {
15873    let _copy_requested = fixture.constructor_copy.unwrap_or(false);
15874    let Some(dtype_spec) = fixture.constructor_dtype.as_deref() else {
15875        return Ok(frame);
15876    };
15877    if dtype_spec.trim().eq_ignore_ascii_case("object") {
15878        // pandas' object constructor dtype preserves the supplied Python values.
15879        // FrankenPandas likewise already carries tagged Scalars for this frame;
15880        // casting to Utf8 would incorrectly turn an input integer into "1".
15881        return Ok(frame);
15882    }
15883    let target_dtype = parse_constructor_dtype_spec(dtype_spec)?;
15884    // DELEGATES to the real constructor-dtype operation rather than casting the
15885    // columns here. br-frankenpandas-oxodo: this helper used to loop over
15886    // Column::new + DataFrame::new_with_column_order itself, so every fixture
15887    // carrying `constructor_dtype` was green against a capability fp-frame did
15888    // not expose (there is no `dtype=` on any DataFrame constructor, and
15889    // `astype` is a DIFFERENT operation — it truncates a lossy float->int where
15890    // the constructor refuses it).
15891    frame
15892        .with_constructor_dtype(target_dtype)
15893        .map_err(|err| format!("{operation_name} dtype='{dtype_spec}' cast failed: {err}"))
15894}
15895
15896fn execute_nanop_fixture_operation(
15897    fixture: &PacketFixture,
15898    operation: FixtureOperation,
15899) -> Result<Scalar, String> {
15900    let left = require_left_series(fixture)?;
15901    Ok(match operation {
15902        FixtureOperation::NanSum => nansum(&left.values),
15903        FixtureOperation::NanMean => nanmean(&left.values),
15904        FixtureOperation::NanMin => nanmin(&left.values),
15905        FixtureOperation::NanMax => nanmax(&left.values),
15906        FixtureOperation::NanStd => nanstd(&left.values, 1),
15907        FixtureOperation::NanVar => nanvar(&left.values, 1),
15908        FixtureOperation::NanCount => nancount(&left.values),
15909        _ => {
15910            return Err(format!(
15911                "unsupported nanops operation for fixture execution: {operation:?}"
15912            ));
15913        }
15914    })
15915}
15916
15917fn execute_dataframe_from_series_fixture_operation(
15918    fixture: &PacketFixture,
15919) -> Result<DataFrame, String> {
15920    let payloads = collect_constructor_series_payloads(fixture, "dataframe_from_series")?;
15921    let mut series_list = Vec::with_capacity(payloads.len());
15922    for payload in payloads {
15923        series_list
15924            .push(build_series(&payload).map_err(|err| format!("series build failed: {err}"))?);
15925    }
15926    let frame = DataFrame::from_series(series_list).map_err(|err| err.to_string())?;
15927    apply_constructor_options(fixture, "dataframe_from_series", frame)
15928}
15929
15930fn execute_dataframe_from_dict_fixture_operation(
15931    fixture: &PacketFixture,
15932) -> Result<DataFrame, String> {
15933    let dict_columns = require_dict_columns(fixture)?;
15934    // DELEGATES the whole `columns=` contract to DataFrame::from_dict_with_columns.
15935    // br-frankenpandas-oxodo: `collect_dict_constructor_payloads` used to project
15936    // the payload here and raise "column 'z' not found in data" for a name the
15937    // dict does not carry — a rejection pandas does not make. MEASURED, live
15938    // pandas 2.2.3, d = {"a": [1, 2], "b": [3, 4]}:
15939    //   pd.DataFrame(d, columns=["a","z"])  -> a=[1,2], z=[nan,nan] object
15940    //   pd.DataFrame(d, columns=["b"])      -> ONLY b; 'a' is dropped
15941    //   pd.DataFrame(d, columns=["z","y"])  -> shape (0, 2)
15942    // The oracle carried the same invented rejection, so fixture, harness and
15943    // oracle all agreed on an error and nothing could go red. Note this shadow
15944    // was invisible to tests/harness_delegation_policy.rs: the helper builds
15945    // nothing, so none of the RAW_BUILDERS needles appear in it — it owned a
15946    // POLICY, not a constructor.
15947    let data: Vec<(&str, Vec<Scalar>)> = dict_columns
15948        .iter()
15949        .map(|(name, values)| (name.as_str(), values.clone()))
15950        .collect();
15951    let frame = DataFrame::from_dict_with_columns(
15952        data,
15953        fixture.column_order.as_deref(),
15954        fixture.index.clone(),
15955    )
15956    .map_err(|err| err.to_string())?;
15957    apply_constructor_options(fixture, "dataframe_from_dict", frame)
15958}
15959
15960fn execute_dataframe_from_records_fixture_operation(
15961    fixture: &PacketFixture,
15962) -> Result<DataFrame, String> {
15963    let frame = match (&fixture.records, &fixture.matrix_rows) {
15964        (Some(records), None) => DataFrame::from_record_maps(
15965            records.clone(),
15966            fixture.column_order.as_deref(),
15967            fixture.index.clone(),
15968        )
15969        .map_err(|err| err.to_string())?,
15970        (None, Some(matrix_rows)) => DataFrame::from_records(
15971            matrix_rows.clone(),
15972            fixture.column_order.as_deref(),
15973            fixture.index.clone(),
15974        )
15975        .map_err(|err| err.to_string())?,
15976        (Some(_), Some(_)) => {
15977            return Err(
15978                "dataframe_from_records fixture cannot define both records and matrix_rows"
15979                    .to_owned(),
15980            );
15981        }
15982        (None, None) => {
15983            return Err(
15984                "dataframe_from_records requires records or matrix_rows payload".to_owned(),
15985            );
15986        }
15987    };
15988
15989    apply_constructor_options(fixture, "dataframe_from_records", frame)
15990}
15991
15992fn execute_dataframe_constructor_kwargs_fixture_operation(
15993    fixture: &PacketFixture,
15994) -> Result<DataFrame, String> {
15995    let frame = build_dataframe(require_frame(fixture)?)
15996        .map_err(|err| format!("frame build failed: {err}"))?;
15997    let projected = materialize_dataframe_constructor_projection(
15998        &frame,
15999        fixture.index.clone(),
16000        fixture.column_order.clone(),
16001    )?;
16002    apply_constructor_options(fixture, "dataframe_constructor_kwargs", projected)
16003}
16004
16005fn materialize_dataframe_constructor_projection(
16006    frame: &DataFrame,
16007    index: Option<Vec<IndexLabel>>,
16008    column_order: Option<Vec<String>>,
16009) -> Result<DataFrame, String> {
16010    let target_index = index.unwrap_or_else(|| frame.index().labels().to_vec());
16011    let target_columns = column_order.unwrap_or_else(|| {
16012        frame
16013            .column_names()
16014            .iter()
16015            .map(|name| (*name).clone())
16016            .collect()
16017    });
16018
16019    // DELEGATES to DataFrame::reindex for the row projection instead of
16020    // reimplementing it. br-frankenpandas-oxodo: this helper used to build a
16021    // label -> first-position map and gather through it, which made it BOTH a
16022    // shadow of a tuned FP path AND the place that minted the missing cells —
16023    // so the eight constructor_kwargs / dict_of_series rows on
16024    // br-frankenpandas-nywa8 could not be fixed in FrankenPandas at all.
16025    //
16026    // Delegating also drops a permissiveness the shadow had: `first_position`
16027    // silently took the first of a duplicated source label, while both pandas
16028    // and DataFrame::reindex reject a duplicated axis ("cannot reindex on an
16029    // axis with duplicate labels"). No fixture exercised that, so the shadow's
16030    // extra tolerance was never observed — which is exactly how a harness ends
16031    // up certifying behaviour the library does not have.
16032    let projected = frame
16033        .reindex(target_index.clone())
16034        .map_err(|err| err.to_string())?;
16035
16036    // Column selection stays here: it must ADD a column the frame lacks (named
16037    // in `columns=` but absent from the data), which is the constructor's own
16038    // semantics rather than a reindex. pandas gives such a column all-NaN
16039    // float64 — measured, DataFrame({'a':[1,2]}).reindex(columns=['a','z'])
16040    // -> a int64, z float64 NaN (br-frankenpandas-nywa8).
16041    let mut columns = BTreeMap::new();
16042    for name in &target_columns {
16043        let column = match projected.column(name) {
16044            Some(existing) => existing.clone(),
16045            None => Column::new(
16046                DType::Float64,
16047                vec![Scalar::Null(NullKind::NaN); target_index.len()],
16048            )
16049            .map_err(|err| err.to_string())?,
16050        };
16051        columns.insert(name.clone(), column);
16052    }
16053
16054    DataFrame::new_with_column_order(Index::new(target_index), columns, target_columns)
16055        .map_err(|err| err.to_string())
16056}
16057
16058fn execute_dataframe_constructor_scalar_fixture_operation(
16059    fixture: &PacketFixture,
16060) -> Result<DataFrame, String> {
16061    let fill_value = fixture
16062        .fill_value
16063        .clone()
16064        .ok_or_else(|| "fill_value is required for dataframe_constructor_scalar".to_owned())?;
16065    let target_index = fixture
16066        .index
16067        .clone()
16068        .ok_or_else(|| "index is required for dataframe_constructor_scalar".to_owned())?;
16069    let target_columns = fixture
16070        .column_order
16071        .clone()
16072        .ok_or_else(|| "column_order is required for dataframe_constructor_scalar".to_owned())?;
16073
16074    // DELEGATES to the real constructor rather than broadcasting here.
16075    // br-frankenpandas-oxodo: this arm used to build the frame itself with
16076    // Column::from_values + DataFrame::new_with_column_order, so all eight
16077    // dataframe_constructor_scalar fixtures were green against an operation
16078    // FrankenPandas did not expose at all.
16079    // `column_order` was already required above, so Some(..) here is the
16080    // "columns were supplied" case — including an explicitly EMPTY list, which
16081    // pandas accepts as shape (n, 0).
16082    let frame = DataFrame::from_scalar(&fill_value, target_index, Some(&target_columns))
16083        .map_err(|err| err.to_string())?;
16084    apply_constructor_options(fixture, "dataframe_constructor_scalar", frame)
16085}
16086
16087fn execute_dataframe_constructor_dict_of_series_fixture_operation(
16088    fixture: &PacketFixture,
16089) -> Result<DataFrame, String> {
16090    let payloads =
16091        collect_constructor_series_payloads(fixture, "dataframe_constructor_dict_of_series")?;
16092    let mut series_list = Vec::with_capacity(payloads.len());
16093    for payload in payloads {
16094        series_list
16095            .push(build_series(&payload).map_err(|err| format!("series build failed: {err}"))?);
16096    }
16097    // Delegate the COLUMN selection to FrankenPandas rather than building the
16098    // full union here and projecting afterwards. pandas selects first and
16099    // aligns only the selected columns, so the two orders differ in ROW COUNT:
16100    // with a indexed [1,2] and b indexed [2,3], columns=['b'] gives index [2,3],
16101    // not the union [1,2,3]. Building-then-projecting produced three rows and
16102    // null-filled b. (br-frankenpandas-oxodo)
16103    let frame = DataFrame::from_series_with_columns(series_list, fixture.column_order.as_deref())
16104        .map_err(|err| err.to_string())?;
16105    // The explicit index= is still applied afterwards; that IS a reindex of the
16106    // constructed frame, which is what pandas does with it.
16107    let projected =
16108        materialize_dataframe_constructor_projection(&frame, fixture.index.clone(), None)?;
16109    apply_constructor_options(fixture, "dataframe_constructor_dict_of_series", projected)
16110}
16111
16112fn execute_dataframe_constructor_list_like_fixture_operation(
16113    fixture: &PacketFixture,
16114) -> Result<DataFrame, String> {
16115    let matrix_rows = require_matrix_rows(fixture)?;
16116    // The fixture arm must delegate every constructor semantic to fp-frame:
16117    // columns, index handling, padding, and one-row broadcasting all belong to
16118    // `DataFrame::from_list_like`, not to a second implementation here.
16119    let frame = DataFrame::from_list_like(
16120        matrix_rows.to_vec(),
16121        fixture.column_order.as_deref(),
16122        fixture.index.clone(),
16123    )
16124    .map_err(|err| err.to_string())?;
16125    apply_constructor_options(fixture, "dataframe_constructor_list_like", frame)
16126}
16127
16128fn execute_csv_round_trip_fixture_operation(fixture: &PacketFixture) -> Result<bool, String> {
16129    let csv_input = fixture
16130        .csv_input
16131        .as_ref()
16132        .ok_or_else(|| "csv_input is required for csv_round_trip".to_owned())?;
16133    let df = read_csv_str(csv_input).map_err(|err| format!("csv parse failed: {err}"))?;
16134    // The oracle's op_csv_round_trip is `to_csv(index=False)`; write_csv_string
16135    // now defaults to pandas' index=True (4qg5w.1), so say index=False here.
16136    let output = write_csv_string_with_options(&df, &csv_index_false())
16137        .map_err(|err| format!("csv write failed: {err}"))?;
16138    let reparsed = read_csv_str(&output).map_err(|err| format!("csv reparse failed: {err}"))?;
16139    Ok(dataframes_semantically_equal(&df, &reparsed))
16140}
16141
16142/// `to_csv(index=False)` options, for round trips of RangeIndex frames read
16143/// from CSV (the question the oracle's csv_round_trip asks).
16144fn csv_index_false() -> CsvWriteOptions {
16145    CsvWriteOptions {
16146        include_index: false,
16147        ..CsvWriteOptions::default()
16148    }
16149}
16150
16151fn execute_csv_read_frame_fixture_operation(fixture: &PacketFixture) -> Result<DataFrame, String> {
16152    let csv_input = fixture
16153        .csv_input
16154        .as_ref()
16155        .ok_or_else(|| "csv_input is required for csv_read_frame".to_owned())?;
16156    let on_bad_lines = match fixture.csv_on_bad_lines.as_deref().unwrap_or("error") {
16157        "error" => CsvOnBadLines::Error,
16158        "warn" => CsvOnBadLines::Warn,
16159        "skip" => CsvOnBadLines::Skip,
16160        other => {
16161            return Err(format!(
16162                "csv_on_bad_lines must be one of error|warn|skip, got '{other}'"
16163            ));
16164        }
16165    };
16166    let decimal = match fixture.csv_decimal.as_deref() {
16167        None => b'.',
16168        Some(value) if value.len() == 1 => value.as_bytes()[0],
16169        Some(other) => {
16170            return Err(format!(
16171                "csv_decimal must be a single-byte separator, got '{other}'"
16172            ));
16173        }
16174    };
16175
16176    let options = CsvReadOptions {
16177        decimal,
16178        on_bad_lines,
16179        parse_dates: fixture.csv_parse_dates.clone(),
16180        parse_date_combinations: fixture.csv_parse_date_combinations.clone(),
16181        true_values: fixture.csv_true_values.clone().unwrap_or_default(),
16182        false_values: fixture.csv_false_values.clone().unwrap_or_default(),
16183        ..CsvReadOptions::default()
16184    };
16185    read_csv_with_options(csv_input, &options).map_err(|err| format!("csv read failed: {err}"))
16186}
16187
16188fn execute_series_to_arrow_round_trip_fixture_operation(
16189    fixture: &PacketFixture,
16190) -> Result<Series, String> {
16191    let left = require_left_series(fixture)?;
16192    let series = build_series(left)?;
16193    let (dt, arr) = series_to_arrow_array(&series).map_err(|err| err.to_string())?;
16194    series_from_arrow_array(
16195        series.name(),
16196        series.index().labels().to_vec(),
16197        arr.as_ref(),
16198        &dt,
16199    )
16200    .map_err(|err| err.to_string())
16201}
16202
16203fn dataframes_semantically_equal(left: &DataFrame, right: &DataFrame) -> bool {
16204    if left.column_names() != right.column_names() || left.len() != right.len() {
16205        return false;
16206    }
16207    for name in left.columns().keys() {
16208        let Some(left_col) = left.column(name) else {
16209            return false;
16210        };
16211        let Some(right_col) = right.column(name) else {
16212            return false;
16213        };
16214        // For round-trip tests, allow numeric dtype coercion (Float64 <-> Int64)
16215        // since formats like Excel convert whole-number floats to integers.
16216        if !columns_semantically_equal_lenient(left_col, right_col) {
16217            return false;
16218        }
16219    }
16220    true
16221}
16222
16223fn columns_semantically_equal_lenient(left: &Column, right: &Column) -> bool {
16224    use fp_types::{DType, Scalar};
16225    if left.len() != right.len() {
16226        return false;
16227    }
16228    // Allow numeric coercion: Float64 <-> Int64 round-trips through formats
16229    // that don't preserve exact numeric dtype (Excel, CSV).
16230    let numeric_compat = matches!(
16231        (left.dtype(), right.dtype()),
16232        (DType::Float64 | DType::Int64, DType::Float64 | DType::Int64)
16233    );
16234    if !numeric_compat && left.dtype() != right.dtype() {
16235        return false;
16236    }
16237    left.values()
16238        .iter()
16239        .zip(right.values())
16240        .all(|(l, r)| match (l, r) {
16241            (Scalar::Float64(a), Scalar::Int64(b)) => *a == *b as f64,
16242            (Scalar::Int64(a), Scalar::Float64(b)) => *a as f64 == *b,
16243            _ => l.semantic_eq(r),
16244        })
16245}
16246
16247fn run_bool_round_trip_match(
16248    actual: Result<bool, String>,
16249    expected: ResolvedExpected,
16250    op_name: &str,
16251) -> Result<(), String> {
16252    match expected {
16253        ResolvedExpected::Bool(value) => {
16254            let round_trip_ok = actual?;
16255            if round_trip_ok != value {
16256                return Err(format!(
16257                    "{op_name} mismatch: actual={round_trip_ok}, expected={value}"
16258                ));
16259            }
16260            Ok(())
16261        }
16262        ResolvedExpected::ErrorContains(substr) => match actual {
16263            Err(message) if message.contains(&substr) => Ok(()),
16264            Err(message) => Err(format!(
16265                "expected {op_name} error containing '{substr}', got '{message}'"
16266            )),
16267            Ok(_) => Err(format!(
16268                "expected {op_name} to fail with error containing '{substr}'"
16269            )),
16270        },
16271        ResolvedExpected::ErrorAny => match actual {
16272            Err(_) => Ok(()),
16273            Ok(_) => Err(format!("expected {op_name} to fail")),
16274        },
16275        _ => Err(format!(
16276            "expected_bool or expected_error is required for {op_name}"
16277        )),
16278    }
16279}
16280
16281fn diff_bool_round_trip_result(
16282    actual: Result<bool, String>,
16283    expected: ResolvedExpected,
16284    op_name: &str,
16285) -> Result<Vec<DriftRecord>, String> {
16286    match expected {
16287        ResolvedExpected::Bool(value) => Ok(diff_bool(actual?, value, op_name)),
16288        ResolvedExpected::ErrorContains(substr) => Ok(match actual {
16289            Err(message) if message.contains(&substr) => Vec::new(),
16290            Err(message) => vec![make_drift_record(
16291                ComparisonCategory::Value,
16292                DriftLevel::Critical,
16293                format!("{op_name}.error"),
16294                format!("expected {op_name} error containing '{substr}', got '{message}'"),
16295            )],
16296            Ok(_) => vec![make_drift_record(
16297                ComparisonCategory::Value,
16298                DriftLevel::Critical,
16299                format!("{op_name}.error"),
16300                format!("expected {op_name} to fail but operation succeeded"),
16301            )],
16302        }),
16303        ResolvedExpected::ErrorAny => Ok(match actual {
16304            Err(_) => Vec::new(),
16305            Ok(_) => vec![make_drift_record(
16306                ComparisonCategory::Value,
16307                DriftLevel::Critical,
16308                format!("{op_name}.error"),
16309                format!("expected {op_name} to fail but operation succeeded"),
16310            )],
16311        }),
16312        _ => Err(format!(
16313            "expected_bool or expected_error required for {op_name}"
16314        )),
16315    }
16316}
16317
16318fn execute_dataframe_to_json_records_fixture_operation(
16319    fixture: &PacketFixture,
16320) -> Result<Scalar, String> {
16321    let frame = build_dataframe(require_frame(fixture)?)
16322        .map_err(|err| format!("frame build failed: {err}"))?;
16323    let json = frame.to_json("records").map_err(|err| err.to_string())?;
16324    Ok(Scalar::Utf8(json))
16325}
16326
16327fn execute_json_round_trip_fixture_operation(fixture: &PacketFixture) -> Result<bool, String> {
16328    let json_input = fixture
16329        .json_input
16330        .as_ref()
16331        .ok_or_else(|| "json_input is required for json_round_trip".to_owned())?;
16332    let orient = fixture
16333        .json_orient
16334        .as_deref()
16335        .map(parse_json_orient)
16336        .transpose()?
16337        .unwrap_or(JsonOrient::Records);
16338    let df =
16339        read_json_str(json_input, orient).map_err(|err| format!("json parse failed: {err}"))?;
16340    let output =
16341        write_json_string(&df, orient).map_err(|err| format!("json write failed: {err}"))?;
16342    let reparsed =
16343        read_json_str(&output, orient).map_err(|err| format!("json reparse failed: {err}"))?;
16344    Ok(dataframes_semantically_equal(&df, &reparsed))
16345}
16346
16347fn parse_json_orient(s: &str) -> Result<JsonOrient, String> {
16348    match s {
16349        "records" => Ok(JsonOrient::Records),
16350        "columns" => Ok(JsonOrient::Columns),
16351        "index" => Ok(JsonOrient::Index),
16352        "split" => Ok(JsonOrient::Split),
16353        "values" => Ok(JsonOrient::Values),
16354        _ => Err(format!("unknown json orient: {s}")),
16355    }
16356}
16357
16358fn execute_jsonl_round_trip_fixture_operation(fixture: &PacketFixture) -> Result<bool, String> {
16359    let jsonl_input = fixture
16360        .jsonl_input
16361        .as_ref()
16362        .ok_or_else(|| "jsonl_input is required for jsonl_round_trip".to_owned())?;
16363    let df = read_jsonl_str(jsonl_input).map_err(|err| format!("jsonl parse failed: {err}"))?;
16364    let output = write_jsonl_string(&df).map_err(|err| format!("jsonl write failed: {err}"))?;
16365    let reparsed = read_jsonl_str(&output).map_err(|err| format!("jsonl reparse failed: {err}"))?;
16366    Ok(dataframes_semantically_equal(&df, &reparsed))
16367}
16368
16369fn execute_parquet_round_trip_fixture_operation(fixture: &PacketFixture) -> Result<bool, String> {
16370    let frame = build_dataframe(require_frame(fixture)?)?;
16371    let bytes =
16372        write_parquet_bytes(&frame).map_err(|err| format!("parquet write failed: {err}"))?;
16373    let reparsed =
16374        read_parquet_bytes(&bytes).map_err(|err| format!("parquet read failed: {err}"))?;
16375    Ok(dataframes_semantically_equal(&frame, &reparsed))
16376}
16377
16378fn execute_feather_round_trip_fixture_operation(fixture: &PacketFixture) -> Result<bool, String> {
16379    let frame = build_dataframe(require_frame(fixture)?)?;
16380    let bytes =
16381        write_feather_bytes(&frame).map_err(|err| format!("feather write failed: {err}"))?;
16382    let reparsed =
16383        read_feather_bytes(&bytes).map_err(|err| format!("feather read failed: {err}"))?;
16384    Ok(dataframes_semantically_equal(&frame, &reparsed))
16385}
16386
16387fn execute_excel_round_trip_fixture_operation(fixture: &PacketFixture) -> Result<bool, String> {
16388    let frame = build_dataframe(require_frame(fixture)?)?;
16389    let bytes = write_excel_bytes(&frame).map_err(|err| format!("excel write failed: {err}"))?;
16390    let reparsed = read_excel_bytes(&bytes, &excel_round_trip_read_options(&frame))
16391        .map_err(|err| format!("excel read failed: {err}"))?;
16392    Ok(dataframes_semantically_equal(&frame, &reparsed))
16393}
16394
16395fn execute_ipc_stream_round_trip_fixture_operation(
16396    fixture: &PacketFixture,
16397) -> Result<bool, String> {
16398    let frame = build_dataframe(require_frame(fixture)?)?;
16399    let bytes =
16400        write_ipc_stream_bytes(&frame).map_err(|err| format!("ipc_stream write failed: {err}"))?;
16401    let reparsed =
16402        read_ipc_stream_bytes(&bytes).map_err(|err| format!("ipc_stream read failed: {err}"))?;
16403    Ok(dataframes_semantically_equal(&frame, &reparsed))
16404}
16405
16406const INDEX_MERGE_KEY_COLUMN: &str = "__index_key";
16407
16408fn execute_dataframe_eval_fixture_operation(
16409    fixture: &PacketFixture,
16410    policy: &RuntimePolicy,
16411    ledger: &mut EvidenceLedger,
16412) -> Result<Series, String> {
16413    let frame = build_dataframe(require_frame(fixture)?)
16414        .map_err(|err| format!("frame build failed: {err}"))?;
16415    let expr = require_expr(fixture, "dataframe_eval")?;
16416    let locals = fixture.locals.clone().unwrap_or_default();
16417    eval_str_with_locals(expr, &frame, &locals, policy, ledger).map_err(|err| err.to_string())
16418}
16419
16420fn execute_dataframe_query_fixture_operation(
16421    fixture: &PacketFixture,
16422    policy: &RuntimePolicy,
16423    ledger: &mut EvidenceLedger,
16424) -> Result<DataFrame, String> {
16425    let frame = build_dataframe(require_frame(fixture)?)
16426        .map_err(|err| format!("frame build failed: {err}"))?;
16427    let expr = require_expr(fixture, "dataframe_query")?;
16428    let locals = fixture.locals.clone().unwrap_or_default();
16429    query_str_with_locals(expr, &frame, &locals, policy, ledger).map_err(|err| err.to_string())
16430}
16431
16432fn execute_series_window_fixture_operation(
16433    fixture: &PacketFixture,
16434    _policy: &RuntimePolicy,
16435    _ledger: &mut EvidenceLedger,
16436) -> Result<Series, String> {
16437    let left = require_left_series(fixture)?;
16438    let series = build_series(left).map_err(|err| format!("series build failed: {err}"))?;
16439    let window_size = fixture.window_size.unwrap_or(3);
16440    let min_periods = fixture.min_periods;
16441    let center = fixture.window_center.unwrap_or(false);
16442
16443    match fixture.operation {
16444        FixtureOperation::SeriesRollingMean => {
16445            if center {
16446                series
16447                    .rolling_with_center(window_size, min_periods, true)
16448                    .mean()
16449                    .map_err(|err| err.to_string())
16450            } else {
16451                series
16452                    .rolling(window_size, min_periods)
16453                    .mean()
16454                    .map_err(|err| err.to_string())
16455            }
16456        }
16457        FixtureOperation::SeriesRollingSum => {
16458            if center {
16459                series
16460                    .rolling_with_center(window_size, min_periods, true)
16461                    .sum()
16462                    .map_err(|err| err.to_string())
16463            } else {
16464                series
16465                    .rolling(window_size, min_periods)
16466                    .sum()
16467                    .map_err(|err| err.to_string())
16468            }
16469        }
16470        FixtureOperation::SeriesRollingStd => {
16471            if center {
16472                series
16473                    .rolling_with_center(window_size, min_periods, true)
16474                    .std()
16475                    .map_err(|err| err.to_string())
16476            } else {
16477                series
16478                    .rolling(window_size, min_periods)
16479                    .std()
16480                    .map_err(|err| err.to_string())
16481            }
16482        }
16483        FixtureOperation::SeriesRollingMin => {
16484            if center {
16485                series
16486                    .rolling_with_center(window_size, min_periods, true)
16487                    .min()
16488                    .map_err(|err| err.to_string())
16489            } else {
16490                series
16491                    .rolling(window_size, min_periods)
16492                    .min()
16493                    .map_err(|err| err.to_string())
16494            }
16495        }
16496        FixtureOperation::SeriesRollingMax => {
16497            if center {
16498                series
16499                    .rolling_with_center(window_size, min_periods, true)
16500                    .max()
16501                    .map_err(|err| err.to_string())
16502            } else {
16503                series
16504                    .rolling(window_size, min_periods)
16505                    .max()
16506                    .map_err(|err| err.to_string())
16507            }
16508        }
16509        FixtureOperation::SeriesRollingVar => {
16510            if center {
16511                series
16512                    .rolling_with_center(window_size, min_periods, true)
16513                    .var()
16514                    .map_err(|err| err.to_string())
16515            } else {
16516                series
16517                    .rolling(window_size, min_periods)
16518                    .var()
16519                    .map_err(|err| err.to_string())
16520            }
16521        }
16522        FixtureOperation::SeriesRollingCount => {
16523            if center {
16524                series
16525                    .rolling_with_center(window_size, min_periods, true)
16526                    .count()
16527                    .map_err(|err| err.to_string())
16528            } else {
16529                series
16530                    .rolling(window_size, min_periods)
16531                    .count()
16532                    .map_err(|err| err.to_string())
16533            }
16534        }
16535        FixtureOperation::SeriesExpandingCount => series
16536            .expanding(min_periods)
16537            .count()
16538            .map_err(|err| err.to_string()),
16539        FixtureOperation::SeriesExpandingSum => series
16540            .expanding(min_periods)
16541            .sum()
16542            .map_err(|err| err.to_string()),
16543        FixtureOperation::SeriesExpandingMean => series
16544            .expanding(min_periods)
16545            .mean()
16546            .map_err(|err| err.to_string()),
16547        FixtureOperation::SeriesExpandingMin => series
16548            .expanding(min_periods)
16549            .min()
16550            .map_err(|err| err.to_string()),
16551        FixtureOperation::SeriesExpandingMax => series
16552            .expanding(min_periods)
16553            .max()
16554            .map_err(|err| err.to_string()),
16555        FixtureOperation::SeriesExpandingStd => series
16556            .expanding(min_periods)
16557            .std()
16558            .map_err(|err| err.to_string()),
16559        FixtureOperation::SeriesExpandingVar => series
16560            .expanding(min_periods)
16561            .var()
16562            .map_err(|err| err.to_string()),
16563        FixtureOperation::SeriesExpandingQuantile => {
16564            let q = fixture.quantile_value.unwrap_or(0.5);
16565            series
16566                .expanding(min_periods)
16567                .quantile(q)
16568                .map_err(|err| err.to_string())
16569        }
16570        FixtureOperation::SeriesEwmMean => {
16571            let span = fixture.ewm_span;
16572            let alpha = fixture.ewm_alpha;
16573            series
16574                .ewm(span, alpha)
16575                .mean()
16576                .map_err(|err| err.to_string())
16577        }
16578        FixtureOperation::SeriesResampleSum => {
16579            let freq = fixture
16580                .resample_freq
16581                .as_deref()
16582                .ok_or("resample_freq required for series_resample_sum")?;
16583            series
16584                .resample_ext(
16585                    freq,
16586                    fixture.resample_closed.as_deref(),
16587                    fixture.resample_label.as_deref(),
16588                    fixture.resample_origin.as_deref(),
16589                )
16590                .sum()
16591                .map_err(|err| err.to_string())
16592        }
16593        FixtureOperation::SeriesResampleMean => {
16594            let freq = fixture
16595                .resample_freq
16596                .as_deref()
16597                .ok_or("resample_freq required for series_resample_mean")?;
16598            series
16599                .resample_ext(
16600                    freq,
16601                    fixture.resample_closed.as_deref(),
16602                    fixture.resample_label.as_deref(),
16603                    fixture.resample_origin.as_deref(),
16604                )
16605                .mean()
16606                .map_err(|err| err.to_string())
16607        }
16608        FixtureOperation::SeriesResampleCount => {
16609            let freq = fixture
16610                .resample_freq
16611                .as_deref()
16612                .ok_or("resample_freq required for series_resample_count")?;
16613            series
16614                .resample_ext(
16615                    freq,
16616                    fixture.resample_closed.as_deref(),
16617                    fixture.resample_label.as_deref(),
16618                    fixture.resample_origin.as_deref(),
16619                )
16620                .count()
16621                .map_err(|err| err.to_string())
16622        }
16623        FixtureOperation::SeriesResampleAsfreq => {
16624            let freq = fixture
16625                .resample_freq
16626                .as_deref()
16627                .ok_or("resample_freq required for series_resample_asfreq")?;
16628            series
16629                .resample_ext(
16630                    freq,
16631                    fixture.resample_closed.as_deref(),
16632                    fixture.resample_label.as_deref(),
16633                    fixture.resample_origin.as_deref(),
16634                )
16635                .asfreq()
16636                .map_err(|err| err.to_string())
16637        }
16638        FixtureOperation::SeriesResampleFfill => {
16639            let freq = fixture
16640                .resample_freq
16641                .as_deref()
16642                .ok_or("resample_freq required for series_resample_ffill")?;
16643            series
16644                .resample_ext(
16645                    freq,
16646                    fixture.resample_closed.as_deref(),
16647                    fixture.resample_label.as_deref(),
16648                    fixture.resample_origin.as_deref(),
16649                )
16650                .ffill(fixture.resample_limit)
16651                .map_err(|err| err.to_string())
16652        }
16653        FixtureOperation::SeriesResampleBfill => {
16654            let freq = fixture
16655                .resample_freq
16656                .as_deref()
16657                .ok_or("resample_freq required for series_resample_bfill")?;
16658            series
16659                .resample_ext(
16660                    freq,
16661                    fixture.resample_closed.as_deref(),
16662                    fixture.resample_label.as_deref(),
16663                    fixture.resample_origin.as_deref(),
16664                )
16665                .bfill(fixture.resample_limit)
16666                .map_err(|err| err.to_string())
16667        }
16668        _ => Err(format!(
16669            "unsupported window operation: {:?}",
16670            fixture.operation
16671        )),
16672    }
16673}
16674
16675fn execute_dataframe_window_fixture_operation(
16676    fixture: &PacketFixture,
16677    _policy: &RuntimePolicy,
16678    _ledger: &mut EvidenceLedger,
16679) -> Result<DataFrame, String> {
16680    let frame = build_dataframe(require_frame(fixture)?)
16681        .map_err(|err| format!("frame build failed: {err}"))?;
16682    let window_size = fixture.window_size.unwrap_or(3);
16683    let min_periods = fixture.min_periods;
16684
16685    match fixture.operation {
16686        FixtureOperation::DataFrameRollingMean => frame
16687            .rolling(window_size, min_periods)
16688            .mean()
16689            .map_err(|err| err.to_string()),
16690        FixtureOperation::DataFrameResampleSum => {
16691            let freq = fixture
16692                .resample_freq
16693                .as_deref()
16694                .ok_or("resample_freq required for dataframe_resample_sum")?;
16695            frame
16696                .resample_ext(
16697                    freq,
16698                    fixture.resample_closed.as_deref(),
16699                    fixture.resample_label.as_deref(),
16700                    fixture.resample_origin.as_deref(),
16701                )
16702                .sum()
16703                .map_err(|err| err.to_string())
16704        }
16705        FixtureOperation::DataFrameResampleMean => {
16706            let freq = fixture
16707                .resample_freq
16708                .as_deref()
16709                .ok_or("resample_freq required for dataframe_resample_mean")?;
16710            frame
16711                .resample_ext(
16712                    freq,
16713                    fixture.resample_closed.as_deref(),
16714                    fixture.resample_label.as_deref(),
16715                    fixture.resample_origin.as_deref(),
16716                )
16717                .mean()
16718                .map_err(|err| err.to_string())
16719        }
16720        _ => Err(format!(
16721            "unsupported dataframe window operation: {:?}",
16722            fixture.operation
16723        )),
16724    }
16725}
16726
16727fn execute_dataframe_apply_alias_fixture_operation(
16728    fixture: &PacketFixture,
16729) -> Result<Series, String> {
16730    let frame = build_dataframe(require_frame(fixture)?)
16731        .map_err(|err| format!("frame build failed: {err}"))?;
16732
16733    match fixture.operation {
16734        FixtureOperation::DataFrameApplySemAxis0 => {
16735            frame.apply("sem", 0).map_err(|err| err.to_string())
16736        }
16737        FixtureOperation::DataFrameApplyNuniqueAxis0 => {
16738            frame.apply("nunique", 0).map_err(|err| err.to_string())
16739        }
16740        FixtureOperation::DataFrameApplyProdAxis1 => {
16741            frame.apply("prod", 1).map_err(|err| err.to_string())
16742        }
16743        FixtureOperation::DataFrameApplyProductAxis1 => {
16744            frame.apply("product", 1).map_err(|err| err.to_string())
16745        }
16746        other => Err(format!(
16747            "unsupported dataframe apply alias operation: {other:?}"
16748        )),
16749    }
16750}
16751
16752fn execute_dataframe_corr_fixture(
16753    frame: &DataFrame,
16754    fixture: &PacketFixture,
16755) -> Result<DataFrame, String> {
16756    let numeric_only = fixture.corr_numeric_only.unwrap_or(false);
16757    match (fixture.corr_method.as_deref(), fixture.corr_min_periods) {
16758        (None, None) => frame.corr_with_numeric_only(numeric_only),
16759        (None, Some(min_periods)) | (Some("pearson"), Some(min_periods)) => {
16760            frame.corr_min_periods_with_numeric_only(min_periods, numeric_only)
16761        }
16762        (Some(method), None) => frame.corr_method_with_numeric_only(method, numeric_only),
16763        (Some(method), Some(_)) => Err(FrameError::CompatibilityRejected(format!(
16764            "dataframe_corr min_periods with method '{method}' is not supported"
16765        ))),
16766    }
16767    .map_err(|err| err.to_string())
16768}
16769
16770fn execute_dataframe_binary_alias_fixture_operation(
16771    fixture: &PacketFixture,
16772) -> Result<DataFrame, String> {
16773    let frame = build_dataframe(require_frame(fixture)?)
16774        .map_err(|err| format!("frame build failed: {err}"))?;
16775    let other = build_dataframe(require_frame_other(fixture)?)
16776        .map_err(|err| format!("frame_other build failed: {err}"))?;
16777    let method = fixture
16778        .dataframe_binary_method
16779        .as_deref()
16780        .ok_or_else(|| "dataframe_binary_method required for dataframe_binary_alias".to_owned())?;
16781
16782    match method {
16783        "add" => frame.add(&other),
16784        "sub" => frame.sub(&other),
16785        "subtract" => frame.subtract(&other),
16786        "mul" => frame.mul(&other),
16787        "multiply" => frame.multiply(&other),
16788        "div" => frame.div(&other),
16789        "divide" => frame.divide(&other),
16790        "truediv" => frame.truediv(&other),
16791        "floordiv" => frame.floordiv(&other),
16792        "mod" => frame.r#mod(&other),
16793        "pow" => frame.pow(&other),
16794        "radd" => frame.radd(&other),
16795        "rsub" => frame.rsub(&other),
16796        "rmul" => frame.rmul(&other),
16797        "rdiv" => frame.rdiv(&other),
16798        "rtruediv" => frame.rtruediv(&other),
16799        "rfloordiv" => frame.rfloordiv(&other),
16800        "rmod" => frame.rmod(&other),
16801        "rpow" => frame.rpow(&other),
16802        "eq" => frame.eq(&other),
16803        "ne" => frame.ne(&other),
16804        "gt" => frame.gt(&other),
16805        "ge" => frame.ge(&other),
16806        "lt" => frame.lt(&other),
16807        "le" => frame.le(&other),
16808        other => {
16809            return Err(format!(
16810                "unsupported dataframe_binary_alias method: {other}"
16811            ));
16812        }
16813    }
16814    .map_err(|err| err.to_string())
16815}
16816
16817fn execute_dataframe_fixture_operation(fixture: &PacketFixture) -> Result<DataFrame, String> {
16818    match fixture.operation {
16819        FixtureOperation::SeriesPartitionDf => {
16820            let left = require_left_series(fixture)?;
16821            let sep = require_string_sep(fixture, "series_partition_df")?;
16822            let series = build_series(left).map_err(|err| format!("series build failed: {err}"))?;
16823            series
16824                .str()
16825                .partition_df(sep)
16826                .map_err(|err| err.to_string())
16827        }
16828        FixtureOperation::SeriesRpartitionDf => {
16829            let left = require_left_series(fixture)?;
16830            let sep = require_string_sep(fixture, "series_rpartition_df")?;
16831            let series = build_series(left).map_err(|err| format!("series build failed: {err}"))?;
16832            series
16833                .str()
16834                .rpartition_df(sep)
16835                .map_err(|err| err.to_string())
16836        }
16837        FixtureOperation::SeriesSplitDf => {
16838            let left = require_left_series(fixture)?;
16839            let pat = fixture
16840                .str_split_pat
16841                .as_deref()
16842                .ok_or_else(|| "str_split_pat is required for series_split_df".to_owned())?;
16843            let series = build_series(left).map_err(|err| format!("series build failed: {err}"))?;
16844            series
16845                .str()
16846                .split_expand_n(pat, fixture.str_split_n)
16847                .map_err(|err| err.to_string())
16848        }
16849        FixtureOperation::SeriesExtractDf => {
16850            let left = require_left_series(fixture)?;
16851            let pattern = require_regex_pattern(fixture, "series_extract_df")?;
16852            let series = build_series(left).map_err(|err| format!("series build failed: {err}"))?;
16853            series
16854                .str()
16855                .extract_df(pattern)
16856                .map_err(|err| err.to_string())
16857        }
16858        FixtureOperation::SeriesExtractAll => {
16859            let left = require_left_series(fixture)?;
16860            let pattern = require_regex_pattern(fixture, "series_extractall")?;
16861            let series = build_series(left).map_err(|err| format!("series build failed: {err}"))?;
16862            series
16863                .str()
16864                .extractall(pattern)
16865                .map_err(|err| err.to_string())
16866        }
16867        FixtureOperation::SeriesToFrame => {
16868            let left = require_left_series(fixture)?;
16869            let series = build_series(left).map_err(|err| format!("series build failed: {err}"))?;
16870            series.to_frame(None).map_err(|err| err.to_string())
16871        }
16872        FixtureOperation::SeriesUnstack => {
16873            let left = require_left_series(fixture)?;
16874            let series = build_series(left).map_err(|err| format!("series build failed: {err}"))?;
16875            series.unstack().map_err(|err| err.to_string())
16876        }
16877        FixtureOperation::SeriesStrGetDummies => {
16878            let left = require_left_series(fixture)?;
16879            let sep = require_string_sep(fixture, "series_str_get_dummies")?;
16880            let series = build_series(left).map_err(|err| format!("series build failed: {err}"))?;
16881            series.str().get_dummies(sep).map_err(|err| err.to_string())
16882        }
16883        FixtureOperation::DataFrameMerge => {
16884            execute_dataframe_merge_fixture_operation(fixture, false)
16885        }
16886        FixtureOperation::DataFrameMergeIndex => {
16887            execute_dataframe_merge_fixture_operation(fixture, true)
16888        }
16889        FixtureOperation::DataFrameMergeAsof => {
16890            execute_dataframe_merge_asof_fixture_operation(fixture)
16891        }
16892        FixtureOperation::DataFrameMergeOrdered => {
16893            execute_dataframe_merge_ordered_fixture_operation(fixture)
16894        }
16895        FixtureOperation::DataFrameConcat => {
16896            let left = build_dataframe(require_frame(fixture)?)
16897                .map_err(|err| format!("left frame build failed: {err}"))?;
16898            let right = build_dataframe(require_frame_right(fixture)?)
16899                .map_err(|err| format!("right frame build failed: {err}"))?;
16900            let axis = normalize_concat_axis(fixture)?;
16901            let join = normalize_concat_join(fixture)?;
16902            concat_dataframes_with_axis_join(&[&left, &right], axis, join)
16903                .map_err(|err| err.to_string())
16904        }
16905        FixtureOperation::DataFrameCombineFirst => {
16906            let left = build_dataframe(require_frame(fixture)?)
16907                .map_err(|err| format!("left frame build failed: {err}"))?;
16908            let right = build_dataframe(require_frame_right(fixture)?)
16909                .map_err(|err| format!("right frame build failed: {err}"))?;
16910            left.combine_first(&right).map_err(|err| err.to_string())
16911        }
16912        FixtureOperation::DataFrameSortIndex => {
16913            let frame = build_dataframe(require_frame(fixture)?)
16914                .map_err(|err| format!("frame build failed: {err}"))?;
16915            frame
16916                .sort_index(resolve_sort_ascending(fixture))
16917                .map_err(|err| err.to_string())
16918        }
16919        FixtureOperation::DataFrameSortValues => {
16920            let frame = build_dataframe(require_frame(fixture)?)
16921                .map_err(|err| format!("frame build failed: {err}"))?;
16922            frame
16923                .sort_values(
16924                    require_sort_column(fixture)?,
16925                    resolve_sort_ascending(fixture),
16926                )
16927                .map_err(|err| err.to_string())
16928        }
16929        FixtureOperation::DataFrameNlargest => {
16930            let frame = build_dataframe(require_frame(fixture)?)
16931                .map_err(|err| format!("frame build failed: {err}"))?;
16932            let n = fixture
16933                .nlargest_n
16934                .ok_or_else(|| "nlargest_n required for dataframe_nlargest".to_owned())?;
16935            let column = require_sort_column_for(fixture, "dataframe_nlargest")?;
16936            match fixture.keep.as_deref() {
16937                Some(keep) => frame.nlargest_keep(n, column, keep),
16938                None => frame.nlargest(n, column),
16939            }
16940            .map_err(|err| err.to_string())
16941        }
16942        FixtureOperation::DataFrameNsmallest => {
16943            let frame = build_dataframe(require_frame(fixture)?)
16944                .map_err(|err| format!("frame build failed: {err}"))?;
16945            let n = fixture
16946                .nlargest_n
16947                .ok_or_else(|| "nlargest_n required for dataframe_nsmallest".to_owned())?;
16948            let column = require_sort_column_for(fixture, "dataframe_nsmallest")?;
16949            match fixture.keep.as_deref() {
16950                Some(keep) => frame.nsmallest_keep(n, column, keep),
16951                None => frame.nsmallest(n, column),
16952            }
16953            .map_err(|err| err.to_string())
16954        }
16955        FixtureOperation::DataFrameDiff => {
16956            let frame = build_dataframe(require_frame(fixture)?)
16957                .map_err(|err| format!("frame build failed: {err}"))?;
16958            let periods = fixture.diff_periods.unwrap_or(1);
16959            let axis = fixture.diff_axis.unwrap_or(0);
16960            if axis == 1 {
16961                frame.diff_axis1(periods).map_err(|err| err.to_string())
16962            } else {
16963                frame.diff(periods).map_err(|err| err.to_string())
16964            }
16965        }
16966        FixtureOperation::DataFrameShift => {
16967            let frame = build_dataframe(require_frame(fixture)?)
16968                .map_err(|err| format!("frame build failed: {err}"))?;
16969            let periods = fixture.shift_periods.unwrap_or(1);
16970            let axis = resolve_shift_axis(fixture)?;
16971            if axis == 1 {
16972                frame.shift_axis1(periods).map_err(|err| err.to_string())
16973            } else {
16974                frame.shift(periods).map_err(|err| err.to_string())
16975            }
16976        }
16977        FixtureOperation::DataFramePctChange => {
16978            let frame = build_dataframe(require_frame(fixture)?)
16979                .map_err(|err| format!("frame build failed: {err}"))?;
16980            let periods = fixture
16981                .diff_periods
16982                .or(fixture.pct_change_periods)
16983                .unwrap_or(1);
16984            let axis = fixture.diff_axis.or(fixture.pct_change_axis).unwrap_or(0);
16985            if axis == 1 {
16986                frame
16987                    .pct_change_axis1(periods)
16988                    .map_err(|err| err.to_string())
16989            } else {
16990                frame.pct_change(periods).map_err(|err| err.to_string())
16991            }
16992        }
16993        FixtureOperation::DataFrameMelt => {
16994            let frame = build_dataframe(require_frame(fixture)?)
16995                .map_err(|err| format!("frame build failed: {err}"))?;
16996            let id_vars =
16997                resolve_optional_string_list(fixture.melt_id_vars.as_ref(), "melt_id_vars")?;
16998            let value_vars =
16999                resolve_optional_string_list(fixture.melt_value_vars.as_ref(), "melt_value_vars")?;
17000            let id_var_refs = id_vars.iter().map(String::as_str).collect::<Vec<_>>();
17001            let value_var_refs = value_vars.iter().map(String::as_str).collect::<Vec<_>>();
17002            frame
17003                .melt(
17004                    &id_var_refs,
17005                    &value_var_refs,
17006                    fixture.melt_var_name.as_deref(),
17007                    fixture.melt_value_name.as_deref(),
17008                )
17009                .map_err(|err| err.to_string())
17010        }
17011        FixtureOperation::DataFramePivot => {
17012            let frame = build_dataframe(require_frame(fixture)?)
17013                .map_err(|err| format!("frame build failed: {err}"))?;
17014            let values =
17015                resolve_optional_string_list(fixture.pivot_values.as_ref(), "pivot_values")?;
17016            let [value] = values.as_slice() else {
17017                return Err(
17018                    "pivot_values must contain exactly one value for dataframe_pivot".to_owned(),
17019                );
17020            };
17021            let index = fixture
17022                .pivot_index
17023                .as_deref()
17024                .ok_or_else(|| "pivot_index is required for dataframe_pivot".to_owned())?;
17025            let columns = fixture
17026                .pivot_columns
17027                .as_deref()
17028                .ok_or_else(|| "pivot_columns is required for dataframe_pivot".to_owned())?;
17029            frame
17030                .pivot(index, columns, value)
17031                .map_err(|err| err.to_string())
17032        }
17033        FixtureOperation::DataFramePivotTable => {
17034            let frame = build_dataframe(require_frame(fixture)?)
17035                .map_err(|err| format!("frame build failed: {err}"))?;
17036            let values = require_pivot_value_names(fixture)?;
17037            let index = require_pivot_index(fixture)?;
17038            let columns = require_pivot_columns(fixture)?;
17039            let aggfunc = require_pivot_aggfunc(fixture)?;
17040            let value_refs = values.iter().map(String::as_str).collect::<Vec<_>>();
17041
17042            if value_refs.len() > 1 {
17043                frame
17044                    .pivot_table_multi_values(&value_refs, index, columns, aggfunc)
17045                    .map_err(|err| err.to_string())
17046            } else if fixture.pivot_margins.unwrap_or(false) {
17047                if let Some(margins_name) = fixture.pivot_margins_name.as_deref() {
17048                    frame
17049                        .pivot_table_with_margins_name(
17050                            value_refs[0],
17051                            index,
17052                            columns,
17053                            aggfunc,
17054                            true,
17055                            margins_name,
17056                        )
17057                        .map_err(|err| err.to_string())
17058                } else {
17059                    frame
17060                        .pivot_table_with_margins(value_refs[0], index, columns, aggfunc, true)
17061                        .map_err(|err| err.to_string())
17062                }
17063            } else if let Some(fill_value) = fixture.fill_value.as_ref() {
17064                let fill = fill_value
17065                    .to_f64()
17066                    .map_err(|err| format!("pivot fill_value must be numeric: {err:?}"))?;
17067                frame
17068                    .pivot_table_fill(value_refs[0], index, columns, aggfunc, fill)
17069                    .map_err(|err| err.to_string())
17070            } else {
17071                frame
17072                    .pivot_table(value_refs[0], index, columns, aggfunc)
17073                    .map_err(|err| err.to_string())
17074            }
17075        }
17076        FixtureOperation::DataFrameCompare => {
17077            let frame = build_dataframe(require_frame(fixture)?)
17078                .map_err(|err| format!("left frame build failed: {err}"))?;
17079            let other = build_dataframe(require_frame_right(fixture)?)
17080                .map_err(|err| format!("right frame build failed: {err}"))?;
17081            let result_names = fixture
17082                .compare_result_names
17083                .as_ref()
17084                .map(|names| (names[0].as_str(), names[1].as_str()))
17085                .unwrap_or(("self", "other"));
17086            frame
17087                .compare_with_result_names(&other, result_names)
17088                .map_err(|err| err.to_string())
17089        }
17090        FixtureOperation::DataFrameStack => {
17091            let frame = build_dataframe(require_frame(fixture)?)
17092                .map_err(|err| format!("frame build failed: {err}"))?;
17093            frame.stack().map_err(|err| err.to_string())
17094        }
17095        FixtureOperation::DataFrameTranspose => {
17096            let frame = build_dataframe(require_frame(fixture)?)
17097                .map_err(|err| format!("frame build failed: {err}"))?;
17098            frame.transpose().map_err(|err| err.to_string())
17099        }
17100        FixtureOperation::DataFrameCrosstab => {
17101            let left = build_series(require_left_series(fixture)?)
17102                .map_err(|err| format!("left series build failed: {err}"))?;
17103            let right = build_series(require_right_series(fixture)?)
17104                .map_err(|err| format!("right series build failed: {err}"))?;
17105            DataFrame::crosstab(&left, &right).map_err(|err| err.to_string())
17106        }
17107        FixtureOperation::DataFrameCrosstabNormalize => {
17108            let left = build_series(require_left_series(fixture)?)
17109                .map_err(|err| format!("left series build failed: {err}"))?;
17110            let right = build_series(require_right_series(fixture)?)
17111                .map_err(|err| format!("right series build failed: {err}"))?;
17112            DataFrame::crosstab_normalize(&left, &right, require_crosstab_normalize(fixture)?)
17113                .map_err(|err| err.to_string())
17114        }
17115        FixtureOperation::DataFrameGetDummies => {
17116            let frame = build_dataframe(require_frame(fixture)?)
17117                .map_err(|err| format!("frame build failed: {err}"))?;
17118            let columns =
17119                resolve_optional_string_list(fixture.dummy_columns.as_ref(), "dummy_columns")?;
17120            let refs = columns.iter().map(String::as_str).collect::<Vec<_>>();
17121            frame.get_dummies(&refs).map_err(|err| err.to_string())
17122        }
17123        FixtureOperation::DataFrameIsNa => {
17124            let frame = build_dataframe(require_frame(fixture)?)
17125                .map_err(|err| format!("frame build failed: {err}"))?;
17126            frame.isna().map_err(|err| err.to_string())
17127        }
17128        FixtureOperation::DataFrameNotNa => {
17129            let frame = build_dataframe(require_frame(fixture)?)
17130                .map_err(|err| format!("frame build failed: {err}"))?;
17131            frame.notna().map_err(|err| err.to_string())
17132        }
17133        FixtureOperation::DataFrameIsNull => {
17134            let frame = build_dataframe(require_frame(fixture)?)
17135                .map_err(|err| format!("frame build failed: {err}"))?;
17136            frame.isnull().map_err(|err| err.to_string())
17137        }
17138        FixtureOperation::DataFrameNotNull => {
17139            let frame = build_dataframe(require_frame(fixture)?)
17140                .map_err(|err| format!("frame build failed: {err}"))?;
17141            frame.notnull().map_err(|err| err.to_string())
17142        }
17143        FixtureOperation::DataFrameMode => {
17144            let frame = build_dataframe(require_frame(fixture)?)
17145                .map_err(|err| format!("frame build failed: {err}"))?;
17146            frame.mode().map_err(|err| err.to_string())
17147        }
17148        FixtureOperation::DataFrameCumsum => {
17149            let frame = build_dataframe(require_frame(fixture)?)
17150                .map_err(|err| format!("frame build failed: {err}"))?;
17151            frame.cumsum().map_err(|err| err.to_string())
17152        }
17153        FixtureOperation::DataFrameCumprod => {
17154            let frame = build_dataframe(require_frame(fixture)?)
17155                .map_err(|err| format!("frame build failed: {err}"))?;
17156            frame.cumprod().map_err(|err| err.to_string())
17157        }
17158        FixtureOperation::DataFrameCummax => {
17159            let frame = build_dataframe(require_frame(fixture)?)
17160                .map_err(|err| format!("frame build failed: {err}"))?;
17161            frame.cummax().map_err(|err| err.to_string())
17162        }
17163        FixtureOperation::DataFrameCummin => {
17164            let frame = build_dataframe(require_frame(fixture)?)
17165                .map_err(|err| format!("frame build failed: {err}"))?;
17166            frame.cummin().map_err(|err| err.to_string())
17167        }
17168        FixtureOperation::DataFrameAstype => {
17169            let frame = build_dataframe(require_frame(fixture)?)
17170                .map_err(|err| format!("frame build failed: {err}"))?;
17171            let dtype_spec = fixture
17172                .constructor_dtype
17173                .as_deref()
17174                .ok_or_else(|| "constructor_dtype required for dataframe_astype".to_owned())?;
17175            let target_dtype = parse_constructor_dtype_spec(dtype_spec)?;
17176            frame.astype(target_dtype).map_err(|err| err.to_string())
17177        }
17178        FixtureOperation::DataFrameClip => {
17179            let frame = build_dataframe(require_frame(fixture)?)
17180                .map_err(|err| format!("frame build failed: {err}"))?;
17181            frame
17182                .clip(fixture.clip_lower, fixture.clip_upper)
17183                .map_err(|err| err.to_string())
17184        }
17185        FixtureOperation::DataFrameAbs => {
17186            let frame = build_dataframe(require_frame(fixture)?)
17187                .map_err(|err| format!("frame build failed: {err}"))?;
17188            frame.abs().map_err(|err| err.to_string())
17189        }
17190        FixtureOperation::DataFrameDescribe => {
17191            let frame = build_dataframe(require_frame(fixture)?)
17192                .map_err(|err| format!("frame build failed: {err}"))?;
17193            frame.describe().map_err(|err| err.to_string())
17194        }
17195        FixtureOperation::DataFrameCorr => {
17196            let frame = build_dataframe(require_frame(fixture)?)
17197                .map_err(|err| format!("frame build failed: {err}"))?;
17198            execute_dataframe_corr_fixture(&frame, fixture)
17199        }
17200        FixtureOperation::DataFrameCov => {
17201            let frame = build_dataframe(require_frame(fixture)?)
17202                .map_err(|err| format!("frame build failed: {err}"))?;
17203            frame.cov().map_err(|err| err.to_string())
17204        }
17205        FixtureOperation::DataFrameRound => {
17206            let frame = build_dataframe(require_frame(fixture)?)
17207                .map_err(|err| format!("frame build failed: {err}"))?;
17208            let decimals = fixture.round_decimals.unwrap_or(0);
17209            frame.round(decimals).map_err(|err| err.to_string())
17210        }
17211        FixtureOperation::DataFrameBinaryAlias => {
17212            execute_dataframe_binary_alias_fixture_operation(fixture)
17213        }
17214        FixtureOperation::DataFrameRank => {
17215            let frame = build_dataframe(require_frame(fixture)?)
17216                .map_err(|err| format!("frame build failed: {err}"))?;
17217            let method = fixture.rank_method.as_deref().unwrap_or("average");
17218            let na_option = fixture.rank_na_option.as_deref().unwrap_or("keep");
17219            let ascending = resolve_sort_ascending(fixture);
17220            let axis = resolve_rank_axis(fixture)?;
17221            let pct = resolve_rank_pct(fixture);
17222            if axis == 1 {
17223                frame
17224                    .rank_axis1_with_pct(method, ascending, na_option, pct)
17225                    .map_err(|err| err.to_string())
17226            } else {
17227                frame
17228                    .rank_with_pct(method, ascending, na_option, pct)
17229                    .map_err(|err| err.to_string())
17230            }
17231        }
17232        FixtureOperation::DataFrameFillNa => {
17233            let frame = build_dataframe(require_frame(fixture)?)
17234                .map_err(|err| format!("frame build failed: {err}"))?;
17235            let fill_value = fixture
17236                .fill_value
17237                .as_ref()
17238                .ok_or_else(|| "fill_value is required for dataframe_fillna".to_owned())?;
17239            frame.fillna(fill_value).map_err(|err| err.to_string())
17240        }
17241        FixtureOperation::DataFrameDropNa => {
17242            let frame = build_dataframe(require_frame(fixture)?)
17243                .map_err(|err| format!("frame build failed: {err}"))?;
17244            frame.dropna().map_err(|err| err.to_string())
17245        }
17246        FixtureOperation::DataFrameDropNaColumns => {
17247            let frame = build_dataframe(require_frame(fixture)?)
17248                .map_err(|err| format!("frame build failed: {err}"))?;
17249            frame.dropna_columns().map_err(|err| err.to_string())
17250        }
17251        FixtureOperation::DataFrameSetIndex => {
17252            let frame = build_dataframe(require_frame(fixture)?)
17253                .map_err(|err| format!("frame build failed: {err}"))?;
17254            frame
17255                .set_index_with_verify_integrity(
17256                    require_set_index_column(fixture)?,
17257                    require_set_index_drop(fixture)?,
17258                    resolve_set_index_verify_integrity(fixture),
17259                )
17260                .map_err(|err| err.to_string())
17261        }
17262        FixtureOperation::DataFrameResetIndex => {
17263            let frame = build_dataframe(require_frame(fixture)?)
17264                .map_err(|err| format!("frame build failed: {err}"))?;
17265            frame
17266                .reset_index(require_reset_index_drop(fixture)?)
17267                .map_err(|err| err.to_string())
17268        }
17269        FixtureOperation::DataFrameInsert => {
17270            let frame = build_dataframe(require_frame(fixture)?)
17271                .map_err(|err| format!("frame build failed: {err}"))?;
17272            let loc = fixture
17273                .insert_loc
17274                .ok_or_else(|| "insert_loc is required for dataframe_insert".to_owned())?;
17275            let column_name = fixture
17276                .insert_column
17277                .as_deref()
17278                .ok_or_else(|| "insert_column is required for dataframe_insert".to_owned())?;
17279            let values = fixture
17280                .insert_values
17281                .clone()
17282                .ok_or_else(|| "insert_values is required for dataframe_insert".to_owned())?;
17283            let column = Column::from_values(values)
17284                .map_err(|err| format!("insert column build failed: {err}"))?;
17285            frame
17286                .insert(loc, column_name, column)
17287                .map_err(|err| err.to_string())
17288        }
17289        FixtureOperation::DataFrameAssign => {
17290            let frame = build_dataframe(require_frame(fixture)?)
17291                .map_err(|err| format!("frame build failed: {err}"))?;
17292            let assignment_payloads = fixture
17293                .assignments
17294                .as_ref()
17295                .ok_or_else(|| "assignments are required for dataframe_assign".to_owned())?;
17296            let assignment_columns: Result<Vec<(String, Column)>, String> = assignment_payloads
17297                .iter()
17298                .map(|assignment| {
17299                    Column::from_values(assignment.values.clone())
17300                        .map(|column| (assignment.name.clone(), column))
17301                        .map_err(|err| format!("assign column build failed: {err}"))
17302                })
17303                .collect();
17304            let assignment_columns = assignment_columns?;
17305            let assignments = assignment_columns
17306                .iter()
17307                .map(|(name, column)| (name.as_str(), column.clone()))
17308                .collect();
17309            frame.assign(assignments).map_err(|err| err.to_string())
17310        }
17311        FixtureOperation::DataFrameRenameColumns => {
17312            let frame = build_dataframe(require_frame(fixture)?)
17313                .map_err(|err| format!("frame build failed: {err}"))?;
17314            let rename_payloads = fixture.rename_columns.as_ref().ok_or_else(|| {
17315                "rename_columns are required for dataframe_rename_columns".to_owned()
17316            })?;
17317            let rename_pairs: Vec<(&str, &str)> = rename_payloads
17318                .iter()
17319                .map(|rename| (rename.from.as_str(), rename.to.as_str()))
17320                .collect();
17321            frame
17322                .rename_columns(&rename_pairs)
17323                .map_err(|err| err.to_string())
17324        }
17325        FixtureOperation::DataFrameReindex => {
17326            let frame = build_dataframe(require_frame(fixture)?)
17327                .map_err(|err| format!("frame build failed: {err}"))?;
17328            let labels = fixture
17329                .reindex_labels
17330                .clone()
17331                .ok_or_else(|| "reindex_labels are required for dataframe_reindex".to_owned())?;
17332            frame.reindex(labels).map_err(|err| err.to_string())
17333        }
17334        FixtureOperation::DataFrameReindexColumns => {
17335            let frame = build_dataframe(require_frame(fixture)?)
17336                .map_err(|err| format!("frame build failed: {err}"))?;
17337            let columns = fixture.reindex_columns.as_ref().ok_or_else(|| {
17338                "reindex_columns are required for dataframe_reindex_columns".to_owned()
17339            })?;
17340            let column_refs: Vec<&str> = columns.iter().map(String::as_str).collect();
17341            frame
17342                .reindex_columns(&column_refs)
17343                .map_err(|err| err.to_string())
17344        }
17345        FixtureOperation::DataFrameDropColumns => {
17346            let frame = build_dataframe(require_frame(fixture)?)
17347                .map_err(|err| format!("frame build failed: {err}"))?;
17348            let columns = fixture
17349                .drop_columns
17350                .as_ref()
17351                .ok_or_else(|| "drop_columns are required for dataframe_drop_columns".to_owned())?;
17352            let column_refs: Vec<&str> = columns.iter().map(String::as_str).collect();
17353            frame
17354                .drop_columns(&column_refs)
17355                .map_err(|err| err.to_string())
17356        }
17357        FixtureOperation::DataFrameReplace => {
17358            let frame = build_dataframe(require_frame(fixture)?)
17359                .map_err(|err| format!("frame build failed: {err}"))?;
17360            let replacements = require_replacement_pairs(fixture, "dataframe_replace")?;
17361            frame.replace(&replacements).map_err(|err| err.to_string())
17362        }
17363        FixtureOperation::DataFrameWhere => {
17364            let frame = build_dataframe(require_frame(fixture)?)
17365                .map_err(|err| format!("frame build failed: {err}"))?;
17366            let cond = build_dataframe(require_frame_right(fixture)?)
17367                .map_err(|err| format!("condition frame build failed: {err}"))?;
17368            frame
17369                .where_cond(&cond, fixture.fill_value.as_ref())
17370                .map_err(|err| err.to_string())
17371        }
17372        FixtureOperation::DataFrameWhereDf => {
17373            let frame = build_dataframe(require_frame(fixture)?)
17374                .map_err(|err| format!("frame build failed: {err}"))?;
17375            let cond = build_dataframe(require_frame_right(fixture)?)
17376                .map_err(|err| format!("condition frame build failed: {err}"))?;
17377            let other = build_dataframe(require_frame_other(fixture)?)
17378                .map_err(|err| format!("other frame build failed: {err}"))?;
17379            frame
17380                .where_cond_df(&cond, &other)
17381                .map_err(|err| err.to_string())
17382        }
17383        FixtureOperation::DataFrameMask => {
17384            let frame = build_dataframe(require_frame(fixture)?)
17385                .map_err(|err| format!("frame build failed: {err}"))?;
17386            let cond = build_dataframe(require_frame_right(fixture)?)
17387                .map_err(|err| format!("condition frame build failed: {err}"))?;
17388            frame
17389                .mask(&cond, fixture.fill_value.as_ref())
17390                .map_err(|err| err.to_string())
17391        }
17392        FixtureOperation::DataFrameMaskDf => {
17393            let frame = build_dataframe(require_frame(fixture)?)
17394                .map_err(|err| format!("frame build failed: {err}"))?;
17395            let cond = build_dataframe(require_frame_right(fixture)?)
17396                .map_err(|err| format!("condition frame build failed: {err}"))?;
17397            let other = build_dataframe(require_frame_other(fixture)?)
17398                .map_err(|err| format!("other frame build failed: {err}"))?;
17399            frame
17400                .mask_df_other(&cond, &other)
17401                .map_err(|err| err.to_string())
17402        }
17403        FixtureOperation::DataFrameDropDuplicates => {
17404            let frame = build_dataframe(require_frame(fixture)?)
17405                .map_err(|err| format!("frame build failed: {err}"))?;
17406            let subset = resolve_duplicate_subset(fixture)?;
17407            let keep = resolve_duplicate_keep(fixture)?;
17408            frame
17409                .drop_duplicates(
17410                    subset.as_deref(),
17411                    keep,
17412                    resolve_drop_duplicates_ignore_index(fixture),
17413                )
17414                .map_err(|err| err.to_string())
17415        }
17416        FixtureOperation::DataFrameExplode => {
17417            let frame = build_dataframe(require_frame(fixture)?)
17418                .map_err(|err| format!("frame build failed: {err}"))?;
17419            frame
17420                .explode_with_ignore_index(
17421                    require_explode_column(fixture, "dataframe_explode")?,
17422                    require_string_sep(fixture, "dataframe_explode")?,
17423                    fixture.ignore_index.unwrap_or(false),
17424                )
17425                .map_err(|err| err.to_string())
17426        }
17427        FixtureOperation::DataFrameTake => {
17428            let frame = build_dataframe(require_frame(fixture)?)
17429                .map_err(|err| format!("frame build failed: {err}"))?;
17430            let indices = require_take_indices(fixture)?;
17431            let axis = resolve_take_axis(fixture)?;
17432            frame.take(indices, axis).map_err(|err| err.to_string())
17433        }
17434        FixtureOperation::DataFrameFilter => {
17435            let frame = build_dataframe(require_frame(fixture)?)
17436                .map_err(|err| format!("frame build failed: {err}"))?;
17437            let item_refs = fixture
17438                .filter_items
17439                .as_ref()
17440                .map(|items| items.iter().map(String::as_str).collect::<Vec<_>>());
17441            frame
17442                .filter_axis(
17443                    item_refs.as_deref(),
17444                    fixture.filter_like.as_deref(),
17445                    fixture.filter_regex.as_deref(),
17446                    resolve_filter_axis(fixture)?,
17447                )
17448                .map_err(|err| err.to_string())
17449        }
17450        FixtureOperation::DataFrameLoc => {
17451            let frame = build_dataframe(require_frame(fixture)?)
17452                .map_err(|err| format!("frame build failed: {err}"))?;
17453            let labels = require_loc_labels(fixture)?;
17454            if frame.row_multiindex().is_some() {
17455                frame
17456                    .loc_tuple_with_columns(labels, fixture.column_order.as_deref())
17457                    .map_err(|err| err.to_string())
17458            } else {
17459                frame
17460                    .loc_with_columns(labels, fixture.column_order.as_deref())
17461                    .map_err(|err| err.to_string())
17462            }
17463        }
17464        FixtureOperation::DataFrameIdentity => build_dataframe(require_frame(fixture)?)
17465            .map_err(|err| format!("frame build failed: {err}")),
17466        FixtureOperation::DataFrameGroupBySum => {
17467            execute_dataframe_groupby_frame_fixture_operation(fixture, "dataframe_groupby_sum")
17468        }
17469        FixtureOperation::DataFrameGroupByAggMulti => {
17470            execute_dataframe_groupby_frame_fixture_operation(
17471                fixture,
17472                "dataframe_groupby_agg_multi",
17473            )
17474        }
17475        FixtureOperation::DataFrameXs => {
17476            let frame = build_dataframe(require_frame(fixture)?)
17477                .map_err(|err| format!("frame build failed: {err}"))?;
17478            if let Some(level) = fixture.xs_level {
17479                frame
17480                    .xs_level(require_xs_key(fixture, "dataframe_xs")?, level)
17481                    .map_err(|err| err.to_string())
17482            } else {
17483                frame
17484                    .xs(require_xs_key(fixture, "dataframe_xs")?)
17485                    .map_err(|err| err.to_string())
17486            }
17487        }
17488        FixtureOperation::DataFrameGroupByIdxMin => {
17489            execute_dataframe_groupby_frame_fixture_operation(fixture, "dataframe_groupby_idxmin")
17490        }
17491        FixtureOperation::DataFrameGroupByIdxMax => {
17492            execute_dataframe_groupby_frame_fixture_operation(fixture, "dataframe_groupby_idxmax")
17493        }
17494        FixtureOperation::DataFrameGroupByAny => {
17495            execute_dataframe_groupby_frame_fixture_operation(fixture, "dataframe_groupby_any")
17496        }
17497        FixtureOperation::DataFrameGroupByAll => {
17498            execute_dataframe_groupby_frame_fixture_operation(fixture, "dataframe_groupby_all")
17499        }
17500        FixtureOperation::DataFrameGroupByGetGroup => {
17501            execute_dataframe_groupby_frame_fixture_operation(
17502                fixture,
17503                "dataframe_groupby_get_group",
17504            )
17505        }
17506        FixtureOperation::DataFrameGroupByFfill => {
17507            execute_dataframe_groupby_frame_fixture_operation(fixture, "dataframe_groupby_ffill")
17508        }
17509        FixtureOperation::DataFrameGroupByBfill => {
17510            execute_dataframe_groupby_frame_fixture_operation(fixture, "dataframe_groupby_bfill")
17511        }
17512        FixtureOperation::DataFrameGroupBySem => {
17513            execute_dataframe_groupby_frame_fixture_operation(fixture, "dataframe_groupby_sem")
17514        }
17515        FixtureOperation::DataFrameGroupBySkew => {
17516            execute_dataframe_groupby_frame_fixture_operation(fixture, "dataframe_groupby_skew")
17517        }
17518        FixtureOperation::DataFrameGroupByKurtosis => {
17519            execute_dataframe_groupby_frame_fixture_operation(fixture, "dataframe_groupby_kurtosis")
17520        }
17521        FixtureOperation::DataFrameGroupByOhlc => {
17522            execute_dataframe_groupby_frame_fixture_operation(fixture, "dataframe_groupby_ohlc")
17523        }
17524        FixtureOperation::DataFrameGroupByResampleMin
17525        | FixtureOperation::DataFrameGroupByResampleMax
17526        | FixtureOperation::DataFrameGroupByResampleCount => {
17527            execute_dataframe_groupby_resample_fixture_operation(fixture)
17528        }
17529        FixtureOperation::DataFrameGroupByRollingMean
17530        | FixtureOperation::DataFrameGroupByRollingSum
17531        | FixtureOperation::DataFrameGroupByRollingMin
17532        | FixtureOperation::DataFrameGroupByRollingMax
17533        | FixtureOperation::DataFrameGroupByRollingCount
17534        | FixtureOperation::DataFrameGroupByRollingStd
17535        | FixtureOperation::DataFrameGroupByRollingVar => {
17536            execute_dataframe_groupby_rolling_fixture_operation(fixture)
17537        }
17538        FixtureOperation::DataFrameAtTime => {
17539            let frame = build_dataframe(require_frame(fixture)?)
17540                .map_err(|err| format!("frame build failed: {err}"))?;
17541            frame
17542                .at_time(require_time_value(fixture)?)
17543                .map_err(|err| err.to_string())
17544        }
17545        FixtureOperation::DataFrameBetweenTime => {
17546            let frame = build_dataframe(require_frame(fixture)?)
17547                .map_err(|err| format!("frame build failed: {err}"))?;
17548            frame
17549                .between_time(require_start_time(fixture)?, require_end_time(fixture)?)
17550                .map_err(|err| err.to_string())
17551        }
17552        _ => Err(format!(
17553            "unsupported dataframe operation for fixture execution: {:?}",
17554            fixture.operation
17555        )),
17556    }
17557}
17558
17559fn execute_dataframe_groupby_frame_fixture_operation(
17560    fixture: &PacketFixture,
17561    operation_name: &str,
17562) -> Result<DataFrame, String> {
17563    let frame = build_dataframe(require_frame(fixture)?)
17564        .map_err(|err| format!("frame build failed: {err}"))?;
17565    let groupby_columns = require_groupby_columns(fixture, operation_name)?;
17566    let groupby_refs = groupby_columns
17567        .iter()
17568        .map(String::as_str)
17569        .collect::<Vec<_>>();
17570    let groupby = frame
17571        .groupby_full_options_with_observed(
17572            &groupby_refs,
17573            true,
17574            true,
17575            true,
17576            resolve_groupby_observed(fixture),
17577        )
17578        .map_err(|err| err.to_string())?;
17579    match operation_name {
17580        "dataframe_groupby_sum" => groupby.sum().map_err(|err| err.to_string()),
17581        "dataframe_groupby_agg_multi" => groupby
17582            .agg_multi(&require_groupby_agg_multi(fixture, operation_name)?)
17583            .map_err(|err| err.to_string()),
17584        "dataframe_groupby_idxmin" => groupby.idxmin().map_err(|err| err.to_string()),
17585        "dataframe_groupby_idxmax" => groupby.idxmax().map_err(|err| err.to_string()),
17586        "dataframe_groupby_any" => groupby.any().map_err(|err| err.to_string()),
17587        "dataframe_groupby_all" => groupby.all().map_err(|err| err.to_string()),
17588        "dataframe_groupby_get_group" => groupby
17589            .get_group(require_group_name(fixture, operation_name)?)
17590            .map_err(|err| err.to_string()),
17591        "dataframe_groupby_ffill" => groupby.ffill(None).map_err(|err| err.to_string()),
17592        "dataframe_groupby_bfill" => groupby.bfill(None).map_err(|err| err.to_string()),
17593        "dataframe_groupby_sem" => groupby.sem().map_err(|err| err.to_string()),
17594        "dataframe_groupby_skew" => groupby.skew().map_err(|err| err.to_string()),
17595        "dataframe_groupby_kurtosis" => groupby.kurtosis().map_err(|err| err.to_string()),
17596        "dataframe_groupby_ohlc" => groupby.ohlc().map_err(|err| err.to_string()),
17597        other => Err(format!(
17598            "unsupported dataframe groupby frame operation: {other}"
17599        )),
17600    }
17601}
17602
17603fn execute_dataframe_groupby_resample_fixture_operation(
17604    fixture: &PacketFixture,
17605) -> Result<DataFrame, String> {
17606    let frame = build_dataframe(require_frame(fixture)?)
17607        .map_err(|err| format!("frame build failed: {err}"))?;
17608    let op_name = fixture.operation.operation_name();
17609    let groupby_columns = require_groupby_columns(fixture, op_name)?;
17610    let groupby_refs = groupby_columns
17611        .iter()
17612        .map(String::as_str)
17613        .collect::<Vec<_>>();
17614    let freq = require_resample_freq(fixture, op_name)?;
17615    let groupby = frame
17616        .groupby(&groupby_refs)
17617        .map_err(|err| err.to_string())?;
17618
17619    match fixture.operation {
17620        FixtureOperation::DataFrameGroupByResampleMin => {
17621            groupby.resample(freq).min().map_err(|err| err.to_string())
17622        }
17623        FixtureOperation::DataFrameGroupByResampleMax => {
17624            groupby.resample(freq).max().map_err(|err| err.to_string())
17625        }
17626        FixtureOperation::DataFrameGroupByResampleCount => groupby
17627            .resample(freq)
17628            .count()
17629            .map_err(|err| err.to_string()),
17630        FixtureOperation::DataFrameGroupByResampleFirst => groupby
17631            .resample(freq)
17632            .first()
17633            .map_err(|err| err.to_string()),
17634        FixtureOperation::DataFrameGroupByResampleLast => {
17635            groupby.resample(freq).last().map_err(|err| err.to_string())
17636        }
17637        other => Err(format!(
17638            "unsupported dataframe groupby resample operation: {other:?}"
17639        )),
17640    }
17641}
17642
17643fn execute_dataframe_groupby_rolling_fixture_operation(
17644    fixture: &PacketFixture,
17645) -> Result<DataFrame, String> {
17646    let frame = build_dataframe(require_frame(fixture)?)
17647        .map_err(|err| format!("frame build failed: {err}"))?;
17648    let op_name = fixture.operation.operation_name();
17649    let groupby_columns = require_groupby_columns(fixture, op_name)?;
17650    let groupby_refs = groupby_columns
17651        .iter()
17652        .map(String::as_str)
17653        .collect::<Vec<_>>();
17654    let window_size = fixture.window_size.unwrap_or(3);
17655    let groupby = frame
17656        .groupby(&groupby_refs)
17657        .map_err(|err| err.to_string())?;
17658
17659    match fixture.operation {
17660        FixtureOperation::DataFrameGroupByRollingMean => groupby
17661            .rolling(window_size)
17662            .mean()
17663            .map_err(|err| err.to_string()),
17664        FixtureOperation::DataFrameGroupByRollingSum => groupby
17665            .rolling(window_size)
17666            .sum()
17667            .map_err(|err| err.to_string()),
17668        FixtureOperation::DataFrameGroupByRollingMin => groupby
17669            .rolling(window_size)
17670            .min()
17671            .map_err(|err| err.to_string()),
17672        FixtureOperation::DataFrameGroupByRollingMax => groupby
17673            .rolling(window_size)
17674            .max()
17675            .map_err(|err| err.to_string()),
17676        FixtureOperation::DataFrameGroupByRollingCount => groupby
17677            .rolling(window_size)
17678            .count()
17679            .map_err(|err| err.to_string()),
17680        FixtureOperation::DataFrameGroupByRollingStd => groupby
17681            .rolling(window_size)
17682            .std()
17683            .map_err(|err| err.to_string()),
17684        FixtureOperation::DataFrameGroupByRollingVar => groupby
17685            .rolling(window_size)
17686            .var()
17687            .map_err(|err| err.to_string()),
17688        other => Err(format!(
17689            "unsupported dataframe groupby rolling operation: {other:?}"
17690        )),
17691    }
17692}
17693
17694fn execute_dataframe_groupby_series_fixture_operation(
17695    fixture: &PacketFixture,
17696    use_ngroup: bool,
17697) -> Result<Series, String> {
17698    let frame = build_dataframe(require_frame(fixture)?)
17699        .map_err(|err| format!("frame build failed: {err}"))?;
17700    let operation_name = if use_ngroup {
17701        "dataframe_groupby_ngroup"
17702    } else {
17703        "dataframe_groupby_cumcount"
17704    };
17705    let groupby_columns = require_groupby_columns(fixture, operation_name)?;
17706    let groupby_refs = groupby_columns
17707        .iter()
17708        .map(String::as_str)
17709        .collect::<Vec<_>>();
17710    let groupby = frame
17711        .groupby(&groupby_refs)
17712        .map_err(|err| err.to_string())?;
17713    if use_ngroup {
17714        groupby
17715            .ngroup_with_ascending(resolve_sort_ascending(fixture))
17716            .map_err(|err| err.to_string())
17717    } else {
17718        groupby
17719            .cumcount_with_ascending(resolve_sort_ascending(fixture))
17720            .map_err(|err| err.to_string())
17721    }
17722}
17723
17724fn execute_dataframe_asof_fixture_operation(fixture: &PacketFixture) -> Result<Series, String> {
17725    let frame = build_dataframe(require_frame(fixture)?)
17726        .map_err(|err| format!("frame build failed: {err}"))?;
17727    let subset = resolve_duplicate_subset(fixture)?;
17728    let subset_refs = subset
17729        .as_ref()
17730        .map(|columns| columns.iter().map(String::as_str).collect::<Vec<_>>());
17731    frame
17732        .asof(require_asof_label(fixture)?, subset_refs.as_deref())
17733        .map_err(|err| err.to_string())
17734}
17735
17736fn execute_series_bool_fixture_operation(fixture: &PacketFixture) -> Result<bool, String> {
17737    let left = require_left_series(fixture)?;
17738    let series = build_series(left)?;
17739    series.bool_().map_err(|err| err.to_string())
17740}
17741
17742fn execute_series_repeat_fixture_operation(fixture: &PacketFixture) -> Result<Series, String> {
17743    let left = require_left_series(fixture)?;
17744    let series = build_series(left)?;
17745    let repeat_counts = resolve_series_repeat_counts(fixture, series.len())?;
17746    series
17747        .repeat_by(&repeat_counts)
17748        .map_err(|err| err.to_string())
17749}
17750
17751fn execute_series_combine_first_fixture_operation(
17752    fixture: &PacketFixture,
17753) -> Result<Series, String> {
17754    let left = require_left_series(fixture)?;
17755    let right = require_right_series(fixture)?;
17756    let left = build_series(left).map_err(|err| format!("left series build failed: {err}"))?;
17757    let right = build_series(right).map_err(|err| format!("right series build failed: {err}"))?;
17758    left.combine_first(&right).map_err(|err| err.to_string())
17759}
17760
17761fn execute_series_asof_fixture_operation(fixture: &PacketFixture) -> Result<Scalar, String> {
17762    let left = build_series(require_left_series(fixture)?)
17763        .map_err(|err| format!("series build failed: {err}"))?;
17764    let label = require_asof_label(fixture)?;
17765    // Delegates to FrankenPandas rather than deciding the missing marker here.
17766    // This helper used to map `None` itself, via a "does this Utf8 column look
17767    // datetime-like" heuristic that produced NaT — a marker pandas never
17768    // returns from `asof`, and a harness-side reimplementation of semantics FP
17769    // owns (br-frankenpandas-oxodo, br-frankenpandas-nywa8).
17770    left.asof_value(label).map_err(|err| err.to_string())
17771}
17772
17773fn execute_series_autocorr_fixture_operation(fixture: &PacketFixture) -> Result<Scalar, String> {
17774    let series = build_series(require_left_series(fixture)?)
17775        .map_err(|err| format!("series build failed: {err}"))?;
17776    let value = series
17777        .autocorr(resolve_autocorr_lag(fixture))
17778        .map_err(|err| err.to_string())?;
17779    Ok(float_result_scalar(value))
17780}
17781
17782fn float_result_scalar(value: f64) -> Scalar {
17783    if value.is_nan() {
17784        Scalar::Null(NullKind::NaN)
17785    } else {
17786        Scalar::Float64(value)
17787    }
17788}
17789
17790fn execute_series_clip_fixture_operation(
17791    series: &Series,
17792    fixture: &PacketFixture,
17793) -> Result<Series, String> {
17794    let lower = fixture
17795        .clip_lower_series
17796        .as_ref()
17797        .map(build_series)
17798        .transpose()
17799        .map_err(|err| format!("clip lower series build failed: {err}"))?;
17800    let upper = fixture
17801        .clip_upper_series
17802        .as_ref()
17803        .map(build_series)
17804        .transpose()
17805        .map_err(|err| format!("clip upper series build failed: {err}"))?;
17806
17807    if lower.is_some() || upper.is_some() {
17808        series
17809            .clip_with_series(lower.as_ref(), upper.as_ref())
17810            .map_err(|err| err.to_string())
17811    } else {
17812        series
17813            .clip(fixture.clip_lower, fixture.clip_upper)
17814            .map_err(|err| err.to_string())
17815    }
17816}
17817
17818fn execute_series_module_utility_fixture_operation(
17819    fixture: &PacketFixture,
17820) -> Result<Series, String> {
17821    let series = build_series(require_left_series(fixture)?)?;
17822    match fixture.operation {
17823        // The series_to_numeric oracle uses errors='coerce' (pandas_oracle.py),
17824        // so replay through the coerce policy — bare to_numeric now defaults to
17825        // raise (br-frankenpandas-mlaht).
17826        FixtureOperation::SeriesToNumeric => to_numeric_with_options(
17827            &series,
17828            ToNumericOptions {
17829                errors: ToNumericErrors::Coerce,
17830            },
17831        )
17832        .map_err(|err| err.to_string()),
17833        FixtureOperation::SeriesConvertDtypes => {
17834            series.convert_dtypes().map_err(|err| err.to_string())
17835        }
17836        FixtureOperation::SeriesAstype => {
17837            let dtype_spec = fixture
17838                .constructor_dtype
17839                .as_deref()
17840                .ok_or_else(|| "constructor_dtype required for series_astype".to_owned())?;
17841            let target_dtype = parse_constructor_dtype_spec(dtype_spec)?;
17842            series.astype(target_dtype).map_err(|err| err.to_string())
17843        }
17844        FixtureOperation::SeriesClip => execute_series_clip_fixture_operation(&series, fixture),
17845        FixtureOperation::SeriesAbs => series.abs().map_err(|err| err.to_string()),
17846        FixtureOperation::SeriesRound => {
17847            let decimals = fixture.round_decimals.unwrap_or(0);
17848            series.round(decimals).map_err(|err| err.to_string())
17849        }
17850        FixtureOperation::SeriesCumsum => series.cumsum().map_err(|err| err.to_string()),
17851        FixtureOperation::SeriesCumprod => series.cumprod().map_err(|err| err.to_string()),
17852        FixtureOperation::SeriesCummax => series.cummax().map_err(|err| err.to_string()),
17853        FixtureOperation::SeriesCummin => series.cummin().map_err(|err| err.to_string()),
17854        FixtureOperation::SeriesNlargest => {
17855            let n = fixture
17856                .nlargest_n
17857                .ok_or_else(|| "nlargest_n required for series_nlargest".to_owned())?;
17858            match fixture.keep.as_deref() {
17859                Some(keep) => series.nlargest_keep(n, keep).map_err(|err| err.to_string()),
17860                None => series.nlargest(n).map_err(|err| err.to_string()),
17861            }
17862        }
17863        FixtureOperation::SeriesNsmallest => {
17864            let n = fixture
17865                .nlargest_n
17866                .ok_or_else(|| "nlargest_n required for series_nsmallest".to_owned())?;
17867            match fixture.keep.as_deref() {
17868                Some(keep) => series
17869                    .nsmallest_keep(n, keep)
17870                    .map_err(|err| err.to_string()),
17871                None => series.nsmallest(n).map_err(|err| err.to_string()),
17872            }
17873        }
17874        FixtureOperation::SeriesBetween => {
17875            let left = fixture
17876                .between_left
17877                .as_ref()
17878                .ok_or_else(|| "between_left required for series_between".to_owned())?;
17879            let right = fixture
17880                .between_right
17881                .as_ref()
17882                .ok_or_else(|| "between_right required for series_between".to_owned())?;
17883            let inclusive = fixture.between_inclusive.as_deref().unwrap_or("both");
17884            series
17885                .between(left, right, inclusive)
17886                .map_err(|err| err.to_string())
17887        }
17888        FixtureOperation::SeriesCut => {
17889            cut(&series, require_cut_bins(fixture)?).map_err(|err| err.to_string())
17890        }
17891        FixtureOperation::SeriesQcut => {
17892            qcut(&series, require_qcut_quantiles(fixture)?).map_err(|err| err.to_string())
17893        }
17894        FixtureOperation::SeriesStrLower => series.str().lower().map_err(|err| err.to_string()),
17895        FixtureOperation::SeriesStrUpper => series.str().upper().map_err(|err| err.to_string()),
17896        FixtureOperation::SeriesStrCapitalize => {
17897            series.str().capitalize().map_err(|err| err.to_string())
17898        }
17899        FixtureOperation::SeriesStrStrip => series.str().strip().map_err(|err| err.to_string()),
17900        FixtureOperation::SeriesStrLen => series.str().len().map_err(|err| err.to_string()),
17901        FixtureOperation::SeriesStrContains => {
17902            let pattern = fixture
17903                .regex_pattern
17904                .as_deref()
17905                .ok_or_else(|| "regex_pattern required for series_str_contains".to_owned())?;
17906            series
17907                .str()
17908                .contains(pattern)
17909                .map_err(|err| err.to_string())
17910        }
17911        FixtureOperation::SeriesStrStartswith => {
17912            let pattern = fixture
17913                .regex_pattern
17914                .as_deref()
17915                .ok_or_else(|| "regex_pattern required for series_str_startswith".to_owned())?;
17916            series
17917                .str()
17918                .startswith(pattern)
17919                .map_err(|err| err.to_string())
17920        }
17921        FixtureOperation::SeriesStrEndswith => {
17922            let pattern = fixture
17923                .regex_pattern
17924                .as_deref()
17925                .ok_or_else(|| "regex_pattern required for series_str_endswith".to_owned())?;
17926            series
17927                .str()
17928                .endswith(pattern)
17929                .map_err(|err| err.to_string())
17930        }
17931        FixtureOperation::SeriesStrReplace => {
17932            let pattern = fixture
17933                .regex_pattern
17934                .as_deref()
17935                .ok_or_else(|| "regex_pattern required for series_str_replace".to_owned())?;
17936            let repl = fixture
17937                .replace_value
17938                .as_deref()
17939                .ok_or_else(|| "replace_value required for series_str_replace".to_owned())?;
17940            series
17941                .str()
17942                .replace(pattern, repl)
17943                .map_err(|err| err.to_string())
17944        }
17945        FixtureOperation::SeriesStrLstrip => series.str().lstrip().map_err(|err| err.to_string()),
17946        FixtureOperation::SeriesStrRstrip => series.str().rstrip().map_err(|err| err.to_string()),
17947        FixtureOperation::SeriesStrTitle => series.str().title().map_err(|err| err.to_string()),
17948        FixtureOperation::SeriesStrSwapcase => {
17949            series.str().swapcase().map_err(|err| err.to_string())
17950        }
17951        FixtureOperation::SeriesStrZfill => {
17952            let width = fixture
17953                .str_width
17954                .ok_or_else(|| "str_width required for series_str_zfill".to_owned())?;
17955            series.str().zfill(width).map_err(|err| err.to_string())
17956        }
17957        FixtureOperation::SeriesStrCenter => {
17958            let width = fixture
17959                .str_width
17960                .ok_or_else(|| "str_width required for series_str_center".to_owned())?;
17961            let fillchar = fixture.str_fillchar.unwrap_or(' ');
17962            series
17963                .str()
17964                .center(width, fillchar)
17965                .map_err(|err| err.to_string())
17966        }
17967        FixtureOperation::SeriesStrLjust => {
17968            let width = fixture
17969                .str_width
17970                .ok_or_else(|| "str_width required for series_str_ljust".to_owned())?;
17971            let fillchar = fixture.str_fillchar.unwrap_or(' ');
17972            series
17973                .str()
17974                .ljust(width, fillchar)
17975                .map_err(|err| err.to_string())
17976        }
17977        FixtureOperation::SeriesStrRjust => {
17978            let width = fixture
17979                .str_width
17980                .ok_or_else(|| "str_width required for series_str_rjust".to_owned())?;
17981            let fillchar = fixture.str_fillchar.unwrap_or(' ');
17982            series
17983                .str()
17984                .rjust(width, fillchar)
17985                .map_err(|err| err.to_string())
17986        }
17987        FixtureOperation::SeriesStrPad => {
17988            let width = fixture
17989                .str_width
17990                .ok_or_else(|| "str_width required for series_str_pad".to_owned())?;
17991            let side = fixture
17992                .str_pad_side
17993                .as_deref()
17994                .ok_or_else(|| "str_pad_side required for series_str_pad".to_owned())?;
17995            let fillchar = fixture.str_fillchar.unwrap_or(' ');
17996            series
17997                .str()
17998                .pad(width, side, fillchar)
17999                .map_err(|err| err.to_string())
18000        }
18001        FixtureOperation::SeriesStrIsdigit => series.str().isdigit().map_err(|err| err.to_string()),
18002        FixtureOperation::SeriesStrIsalpha => series.str().isalpha().map_err(|err| err.to_string()),
18003        FixtureOperation::SeriesStrIsalnum => series.str().isalnum().map_err(|err| err.to_string()),
18004        FixtureOperation::SeriesStrIsspace => series.str().isspace().map_err(|err| err.to_string()),
18005        FixtureOperation::SeriesStrIslower => series.str().islower().map_err(|err| err.to_string()),
18006        FixtureOperation::SeriesStrIsupper => series.str().isupper().map_err(|err| err.to_string()),
18007        FixtureOperation::SeriesStrIsnumeric => {
18008            series.str().isnumeric().map_err(|err| err.to_string())
18009        }
18010        FixtureOperation::SeriesStrFind => {
18011            let sub = fixture
18012                .str_sub
18013                .as_deref()
18014                .ok_or_else(|| "str_sub required for series_str_find".to_owned())?;
18015            series.str().find(sub).map_err(|err| err.to_string())
18016        }
18017        FixtureOperation::SeriesStrRfind => {
18018            let sub = fixture
18019                .str_sub
18020                .as_deref()
18021                .ok_or_else(|| "str_sub required for series_str_rfind".to_owned())?;
18022            series.str().rfind(sub).map_err(|err| err.to_string())
18023        }
18024        FixtureOperation::SeriesStrSlice => {
18025            // start/stop/step are all optional (Python slice semantics); a
18026            // missing start no longer errors — None means "from the beginning".
18027            series
18028                .str()
18029                .slice(
18030                    fixture.str_slice_start,
18031                    fixture.str_slice_end,
18032                    fixture.str_slice_step,
18033                )
18034                .map_err(|err| err.to_string())
18035        }
18036        FixtureOperation::SeriesStrGet => {
18037            let i = fixture
18038                .str_get_index
18039                .ok_or_else(|| "str_get_index required for series_str_get".to_owned())?;
18040            series.str().get(i).map_err(|err| err.to_string())
18041        }
18042        FixtureOperation::SeriesStrRepeat => {
18043            let n = fixture
18044                .str_repeat_n
18045                .ok_or_else(|| "str_repeat_n required for series_str_repeat".to_owned())?;
18046            series.str().repeat(n).map_err(|err| err.to_string())
18047        }
18048        FixtureOperation::SeriesStrCount => {
18049            let pat = fixture
18050                .regex_pattern
18051                .as_deref()
18052                .ok_or_else(|| "regex_pattern required for series_str_count".to_owned())?;
18053            series.str().count(pat).map_err(|err| err.to_string())
18054        }
18055        FixtureOperation::SeriesStrWrap => {
18056            let width = fixture
18057                .str_wrap_width
18058                .ok_or_else(|| "str_wrap_width required for series_str_wrap".to_owned())?;
18059            series
18060                .str()
18061                .wrap_with_drop_whitespace(width, fixture.str_wrap_drop_whitespace.unwrap_or(true))
18062                .map_err(|err| err.to_string())
18063        }
18064        FixtureOperation::SeriesStrNormalize => {
18065            let form = fixture
18066                .str_normalize_form
18067                .as_deref()
18068                .ok_or_else(|| "str_normalize_form required for series_str_normalize".to_owned())?;
18069            series.str().normalize(form).map_err(|err| err.to_string())
18070        }
18071        FixtureOperation::SeriesStrFullmatch => {
18072            let pat = fixture
18073                .regex_pattern
18074                .as_deref()
18075                .ok_or_else(|| "regex_pattern required for series_str_fullmatch".to_owned())?;
18076            series.str().fullmatch(pat).map_err(|err| err.to_string())
18077        }
18078        FixtureOperation::SeriesStrMatch => {
18079            let pat = fixture
18080                .regex_pattern
18081                .as_deref()
18082                .ok_or_else(|| "regex_pattern required for series_str_match".to_owned())?;
18083            series.str().match_regex(pat).map_err(|err| err.to_string())
18084        }
18085        FixtureOperation::SeriesStrRemoveprefix => {
18086            let prefix = fixture
18087                .str_prefix
18088                .as_deref()
18089                .ok_or_else(|| "str_prefix required for series_str_removeprefix".to_owned())?;
18090            series
18091                .str()
18092                .removeprefix(prefix)
18093                .map_err(|err| err.to_string())
18094        }
18095        FixtureOperation::SeriesStrRemovesuffix => {
18096            let suffix = fixture
18097                .str_suffix
18098                .as_deref()
18099                .ok_or_else(|| "str_suffix required for series_str_removesuffix".to_owned())?;
18100            series
18101                .str()
18102                .removesuffix(suffix)
18103                .map_err(|err| err.to_string())
18104        }
18105        FixtureOperation::SeriesStrSplitGet => {
18106            let pat = fixture
18107                .str_split_pat
18108                .as_deref()
18109                .ok_or_else(|| "str_split_pat required for series_str_split_get".to_owned())?;
18110            let n = fixture
18111                .str_split_n
18112                .ok_or_else(|| "str_split_n required for series_str_split_get".to_owned())?;
18113            series
18114                .str()
18115                .split_get(pat, n as i64)
18116                .map_err(|err| err.to_string())
18117        }
18118        FixtureOperation::SeriesStrJoin => {
18119            let from = fixture
18120                .str_join_from
18121                .as_deref()
18122                .ok_or_else(|| "str_join_from required for series_str_join".to_owned())?;
18123            let sep = fixture
18124                .str_join_sep
18125                .as_deref()
18126                .ok_or_else(|| "str_join_sep required for series_str_join".to_owned())?;
18127            series.str().join(from, sep).map_err(|err| err.to_string())
18128        }
18129        FixtureOperation::SeriesStrIsdecimal => {
18130            series.str().isdecimal().map_err(|err| err.to_string())
18131        }
18132        FixtureOperation::SeriesStrIstitle => series.str().istitle().map_err(|err| err.to_string()),
18133        FixtureOperation::SeriesStrCasefold => {
18134            series.str().casefold().map_err(|err| err.to_string())
18135        }
18136        FixtureOperation::SeriesStrEncode => {
18137            series.str().encode("utf-8").map_err(|err| err.to_string())
18138        }
18139        FixtureOperation::SeriesStrDecode => {
18140            series.str().decode("utf-8").map_err(|err| err.to_string())
18141        }
18142        FixtureOperation::SeriesStrTranslate => {
18143            let from = fixture.str_translate_from.as_deref().unwrap_or("");
18144            let to = fixture.str_translate_to.as_deref().unwrap_or("");
18145            series
18146                .str()
18147                .translate(from, to)
18148                .map_err(|err| err.to_string())
18149        }
18150        FixtureOperation::SeriesStrExpandtabs => {
18151            let tabsize = fixture.str_expandtabs_size.unwrap_or(8);
18152            series
18153                .str()
18154                .expandtabs(tabsize)
18155                .map_err(|err| err.to_string())
18156        }
18157        FixtureOperation::SeriesStrIndexOf => {
18158            let sub = fixture.str_sub.as_deref().unwrap_or("");
18159            series.str().index_of(sub).map_err(|err| err.to_string())
18160        }
18161        FixtureOperation::SeriesStrRindexOf => {
18162            let sub = fixture.str_sub.as_deref().unwrap_or("");
18163            series.str().rindex_of(sub).map_err(|err| err.to_string())
18164        }
18165        FixtureOperation::SeriesStrSplitCount => {
18166            let pat = fixture.str_split_pat.as_deref().unwrap_or("");
18167            series.str().split_count(pat).map_err(|err| err.to_string())
18168        }
18169        FixtureOperation::SeriesStrRsplitGet => {
18170            let pat = fixture.str_split_pat.as_deref().unwrap_or("");
18171            let n = fixture.str_split_n.unwrap_or(0);
18172            series
18173                .str()
18174                .rsplit_get(pat, n as i64)
18175                .map_err(|err| err.to_string())
18176        }
18177        FixtureOperation::SeriesStrSplitRegexGet => {
18178            let pat = fixture.regex_pattern.as_deref().unwrap_or("");
18179            let n = fixture.str_split_n.unwrap_or(0);
18180            series
18181                .str()
18182                .split_regex_get(pat, n as i64)
18183                .map_err(|err| err.to_string())
18184        }
18185        FixtureOperation::SeriesStrCountMatches => {
18186            let pat = fixture.regex_pattern.as_deref().unwrap_or("");
18187            series
18188                .str()
18189                .count_matches(pat)
18190                .map_err(|err| err.to_string())
18191        }
18192        FixtureOperation::SeriesStrCountLiteral => {
18193            let pat = fixture.str_sub.as_deref().unwrap_or("");
18194            series
18195                .str()
18196                .count_literal(pat)
18197                .map_err(|err| err.to_string())
18198        }
18199        FixtureOperation::SeriesStrFindall => {
18200            let pat = fixture.regex_pattern.as_deref().unwrap_or("");
18201            let sep = fixture.str_findall_sep.as_deref().unwrap_or(",");
18202            series
18203                .str()
18204                .findall(pat, sep)
18205                .map_err(|err| err.to_string())
18206        }
18207        FixtureOperation::SeriesStrContainsAny => {
18208            let pats: Vec<&str> = fixture
18209                .str_patterns
18210                .as_ref()
18211                .map(|v| v.iter().map(String::as_str).collect())
18212                .unwrap_or_default();
18213            series
18214                .str()
18215                .contains_any(&pats)
18216                .map_err(|err| err.to_string())
18217        }
18218        FixtureOperation::SeriesStrStartswithAny => {
18219            let pats: Vec<&str> = fixture
18220                .str_patterns
18221                .as_ref()
18222                .map(|v| v.iter().map(String::as_str).collect())
18223                .unwrap_or_default();
18224            series
18225                .str()
18226                .startswith_any(&pats)
18227                .map_err(|err| err.to_string())
18228        }
18229        FixtureOperation::SeriesStrEndswithAny => {
18230            let pats: Vec<&str> = fixture
18231                .str_patterns
18232                .as_ref()
18233                .map(|v| v.iter().map(String::as_str).collect())
18234                .unwrap_or_default();
18235            series
18236                .str()
18237                .endswith_any(&pats)
18238                .map_err(|err| err.to_string())
18239        }
18240        FixtureOperation::SeriesDtYear => series.dt().year().map_err(|err| err.to_string()),
18241        FixtureOperation::SeriesDtMonth => series.dt().month().map_err(|err| err.to_string()),
18242        FixtureOperation::SeriesDtDay => series.dt().day().map_err(|err| err.to_string()),
18243        FixtureOperation::SeriesDtHour => series.dt().hour().map_err(|err| err.to_string()),
18244        FixtureOperation::SeriesDtMinute => series.dt().minute().map_err(|err| err.to_string()),
18245        FixtureOperation::SeriesDtSecond => series.dt().second().map_err(|err| err.to_string()),
18246        FixtureOperation::SeriesDtMicrosecond => {
18247            series.dt().microsecond().map_err(|err| err.to_string())
18248        }
18249        FixtureOperation::SeriesDtNanosecond => {
18250            series.dt().nanosecond().map_err(|err| err.to_string())
18251        }
18252        FixtureOperation::SeriesDtDayofweek => {
18253            series.dt().dayofweek().map_err(|err| err.to_string())
18254        }
18255        FixtureOperation::SeriesDtQuarter => series.dt().quarter().map_err(|err| err.to_string()),
18256        FixtureOperation::SeriesDtDayofyear => {
18257            series.dt().dayofyear().map_err(|err| err.to_string())
18258        }
18259        FixtureOperation::SeriesDtWeekofyear => {
18260            series.dt().weekofyear().map_err(|err| err.to_string())
18261        }
18262        FixtureOperation::SeriesDtIsMonthStart => {
18263            series.dt().is_month_start().map_err(|err| err.to_string())
18264        }
18265        FixtureOperation::SeriesDtIsMonthEnd => {
18266            series.dt().is_month_end().map_err(|err| err.to_string())
18267        }
18268        FixtureOperation::SeriesDtIsYearStart => {
18269            series.dt().is_year_start().map_err(|err| err.to_string())
18270        }
18271        FixtureOperation::SeriesDtIsYearEnd => {
18272            series.dt().is_year_end().map_err(|err| err.to_string())
18273        }
18274        FixtureOperation::SeriesDtDate => series.dt().date().map_err(|err| err.to_string()),
18275        FixtureOperation::SeriesDtDaysInMonth => {
18276            series.dt().days_in_month().map_err(|err| err.to_string())
18277        }
18278        FixtureOperation::SeriesDtIsLeapYear => {
18279            series.dt().is_leap_year().map_err(|err| err.to_string())
18280        }
18281        FixtureOperation::SeriesDtIsQuarterStart => series
18282            .dt()
18283            .is_quarter_start()
18284            .map_err(|err| err.to_string()),
18285        FixtureOperation::SeriesDtIsQuarterEnd => {
18286            series.dt().is_quarter_end().map_err(|err| err.to_string())
18287        }
18288        FixtureOperation::SeriesDtStrftime => {
18289            let format = fixture
18290                .dt_strftime_format
18291                .as_deref()
18292                .unwrap_or("%Y-%m-%d %H:%M:%S");
18293            series.dt().strftime(format).map_err(|err| err.to_string())
18294        }
18295        // `dt_tz` ABSENT means None, which is meaningful rather than missing:
18296        // tz_convert(None) converts to UTC and drops the zone, tz_localize(None)
18297        // keeps wall-clock and drops it. So these use as_deref() with no
18298        // ok_or_else — unlike dt_freq, where absence really is an error.
18299        // The key is spelled EXACTLY as the oracle spells it; a key only one arm
18300        // understands is the hazard 4645db2b8 guards against.
18301        FixtureOperation::SeriesDtTzConvert => series
18302            .dt()
18303            .tz_convert(fixture.dt_tz.as_deref())
18304            .map_err(|err| err.to_string()),
18305        FixtureOperation::SeriesDtTzLocalize => series
18306            .dt()
18307            .tz_localize(fixture.dt_tz.as_deref())
18308            .map_err(|err| err.to_string()),
18309        FixtureOperation::SeriesDtTimetz => series.dt().timetz().map_err(|err| err.to_string()),
18310        FixtureOperation::SeriesDtFloor => {
18311            let freq = fixture
18312                .dt_freq
18313                .as_deref()
18314                .ok_or_else(|| "series_dt_floor requires dt_freq".to_string())?;
18315            series.dt().floor(freq).map_err(|err| err.to_string())
18316        }
18317        FixtureOperation::SeriesDtToPeriod => {
18318            let freq = fixture
18319                .dt_freq
18320                .as_deref()
18321                .ok_or_else(|| "series_dt_to_period requires dt_freq".to_string())?;
18322            series.dt().to_period(freq).map_err(|err| err.to_string())
18323        }
18324        FixtureOperation::SeriesDtCeil => {
18325            let freq = fixture
18326                .dt_freq
18327                .as_deref()
18328                .ok_or_else(|| "series_dt_ceil requires dt_freq".to_string())?;
18329            series.dt().ceil(freq).map_err(|err| err.to_string())
18330        }
18331        FixtureOperation::SeriesDtRound => {
18332            let freq = fixture
18333                .dt_freq
18334                .as_deref()
18335                .ok_or_else(|| "series_dt_round requires dt_freq".to_string())?;
18336            series.dt().round(freq).map_err(|err| err.to_string())
18337        }
18338        FixtureOperation::SeriesDtMonthName => {
18339            series.dt().month_name().map_err(|err| err.to_string())
18340        }
18341        FixtureOperation::SeriesDtDayName => series.dt().day_name().map_err(|err| err.to_string()),
18342        FixtureOperation::SeriesDtTotalSeconds => {
18343            series.dt().total_seconds().map_err(|err| err.to_string())
18344        }
18345        FixtureOperation::SeriesDtDays => series.dt().days().map_err(|err| err.to_string()),
18346        FixtureOperation::SeriesDtSeconds => series.dt().seconds().map_err(|err| err.to_string()),
18347        FixtureOperation::SeriesDtMicroseconds => {
18348            series.dt().microseconds().map_err(|err| err.to_string())
18349        }
18350        FixtureOperation::SeriesDtNanoseconds => {
18351            series.dt().nanoseconds().map_err(|err| err.to_string())
18352        }
18353        FixtureOperation::SeriesDtToTimestamp => {
18354            let how = fixture.dt_how.as_deref().unwrap_or("start");
18355            series
18356                .dt()
18357                .to_timestamp_with_how(how)
18358                .map_err(|err| err.to_string())
18359        }
18360        FixtureOperation::SeriesDtToPydatetime => {
18361            let warn = fixture.dt_warn.unwrap_or(true);
18362            series
18363                .dt()
18364                .to_pydatetime_with_warn(warn)
18365                .map_err(|err| err.to_string())
18366        }
18367        FixtureOperation::SeriesDtToPytimedelta => {
18368            series.dt().to_pytimedelta().map_err(|err| err.to_string())
18369        }
18370        other => Err(format!(
18371            "unsupported series module utility operation for fixture execution: {other:?}"
18372        )),
18373    }
18374}
18375
18376fn execute_series_xs_fixture_operation(fixture: &PacketFixture) -> Result<Series, String> {
18377    let series = build_series(require_left_series(fixture)?)?;
18378    series
18379        .xs(require_xs_key(fixture, "series_xs")?)
18380        .map_err(|err| err.to_string())
18381}
18382
18383fn execute_dataframe_bool_fixture_operation(fixture: &PacketFixture) -> Result<bool, String> {
18384    let frame = build_dataframe(require_frame(fixture)?)
18385        .map_err(|err| format!("frame build failed: {err}"))?;
18386    frame.bool_().map_err(|err| err.to_string())
18387}
18388
18389fn execute_dataframe_merge_fixture_operation(
18390    fixture: &PacketFixture,
18391    merge_on_index: bool,
18392) -> Result<DataFrame, String> {
18393    let left = build_dataframe(require_frame(fixture)?)
18394        .map_err(|err| format!("left frame build failed: {err}"))?;
18395    let right = build_dataframe(require_frame_right(fixture)?)
18396        .map_err(|err| format!("right frame build failed: {err}"))?;
18397    let join_type = require_join_type(fixture)?.into_join_type();
18398
18399    let (left_use_index, right_use_index, operation_name) = if merge_on_index {
18400        (true, true, "dataframe_merge_index")
18401    } else {
18402        (
18403            fixture.left_index.unwrap_or(false),
18404            fixture.right_index.unwrap_or(false),
18405            "dataframe_merge",
18406        )
18407    };
18408    if matches!(join_type, JoinType::Cross) {
18409        validate_cross_merge_configuration(fixture, operation_name, merge_on_index)?;
18410    }
18411
18412    let (left_merge_keys, right_merge_keys) = if matches!(join_type, JoinType::Cross) {
18413        (Vec::new(), Vec::new())
18414    } else {
18415        let default_index_key =
18416            (left_use_index && right_use_index).then_some(INDEX_MERGE_KEY_COLUMN);
18417        resolve_merge_key_pairs(
18418            fixture.merge_on.as_deref(),
18419            fixture.merge_on_keys.as_deref(),
18420            fixture.left_on_keys.as_deref(),
18421            fixture.right_on_keys.as_deref(),
18422            operation_name,
18423            default_index_key,
18424        )?
18425    };
18426    let indicator_name = resolve_merge_indicator_name(
18427        fixture.merge_indicator,
18428        fixture.merge_indicator_name.as_deref(),
18429        operation_name,
18430    )?;
18431    let validate_mode =
18432        resolve_merge_validate_mode(fixture.merge_validate.as_deref(), operation_name)?;
18433    let suffixes = resolve_merge_suffixes(fixture.merge_suffixes.as_ref());
18434    let sort = resolve_merge_sort(fixture.merge_sort);
18435
18436    let left_input = if left_use_index {
18437        dataframe_with_index_as_columns(&left, &left_merge_keys)?
18438    } else {
18439        left
18440    };
18441    let right_input = if right_use_index {
18442        dataframe_with_index_as_columns(&right, &right_merge_keys)?
18443    } else {
18444        right
18445    };
18446
18447    let left_merge_refs = left_merge_keys
18448        .iter()
18449        .map(String::as_str)
18450        .collect::<Vec<_>>();
18451    let right_merge_refs = right_merge_keys
18452        .iter()
18453        .map(String::as_str)
18454        .collect::<Vec<_>>();
18455    let merged = merge_dataframes_on_with_options(
18456        &left_input,
18457        &right_input,
18458        &left_merge_refs,
18459        &right_merge_refs,
18460        join_type,
18461        MergeExecutionOptions {
18462            indicator_name,
18463            validate_mode,
18464            suffixes,
18465            sort,
18466        },
18467    )
18468    .map_err(|err| err.to_string())?;
18469    DataFrame::new_with_column_order(merged.index, merged.columns, merged.column_order)
18470        .map_err(|err| err.to_string())
18471}
18472
18473/// Promote the row index into a merge-key column, DELEGATING the label-to-value
18474/// conversion to `DataFrame::reset_index` rather than keeping a private copy.
18475///
18476/// br-frankenpandas-oxodo, scope item 1: this helper (and the since-removed
18477/// `collect_dict_constructor_payloads`, whose `columns=` policy now lives in
18478/// `DataFrame::from_dict_with_columns`) were the two the `execute_*` sweep could
18479/// not see. It carried its OWN `index_label_to_scalar`, and that copy had drifted
18480/// from fp-frame's: it rendered a `Datetime64` label as
18481/// `Scalar::Utf8(format_datetime_ns(..))`, so merging on a DatetimeIndex joined
18482/// on STRINGS where FrankenPandas itself joins on `Datetime64`.
18483///
18484/// MEASURED, live pandas 2.2.3:
18485/// ```text
18486///   idx = pd.to_datetime(['2024-01-15','2024-01-16'])
18487///   pd.DataFrame({'v':[1,2]}, index=idx).reset_index().dtypes
18488///     -> index datetime64[ns], v int64      NOT a string column
18489///   df.merge(other, left_index=True, right_index=True, how='outer').index.dtype
18490///     -> datetime64[ns]
18491/// ```
18492/// fp-frame's own `index_label_to_scalar` already says exactly this at its
18493/// `Datetime64` arm; the harness copy contradicted it. This is the shape oxodo
18494/// warns about — a harness that models an operation differently from FP — and it
18495/// was latent only because no current fixture merges on a datetime index.
18496///
18497/// The conversion now comes from `reset_index(false)`, which is the FP API that
18498/// owns it (including the mixed int/utf8 label rule the private copy lacked
18499/// entirely). The promoted column is then attached under each requested key
18500/// name, leaving the original index in place — the one thing `reset_index` does
18501/// that this caller must NOT inherit.
18502fn dataframe_with_index_as_columns(
18503    frame: &DataFrame,
18504    key_names: &[String],
18505) -> Result<DataFrame, String> {
18506    let promoted = frame.reset_index(false).map_err(|err| err.to_string())?;
18507    let existing: Vec<&String> = frame.column_names();
18508    let added: Vec<&String> = promoted
18509        .column_names()
18510        .into_iter()
18511        .filter(|name| !existing.contains(name))
18512        .collect();
18513    let [index_column_name] = added.as_slice() else {
18514        return Err(format!(
18515            "merge on index expects a single-level index; reset_index promoted {} columns",
18516            added.len()
18517        ));
18518    };
18519    let key_column = promoted
18520        .column(index_column_name.as_str())
18521        .ok_or_else(|| format!("reset_index did not produce column '{index_column_name}'"))?
18522        .clone();
18523
18524    let mut out = frame.clone();
18525    for key_name in key_names {
18526        out = out
18527            .with_column(key_name.as_str(), key_column.clone())
18528            .map_err(|err| err.to_string())?;
18529    }
18530    Ok(out)
18531}
18532
18533/// Render a single index LABEL as the scalar the corpus compares against.
18534///
18535/// This is NOT the conversion `dataframe_with_index_as_columns` above needs, and
18536/// the difference is the reason that helper stopped calling it. Here the answer
18537/// is an `expected_scalar` for `idxmin`/`idxmax`, and the corpus's convention for
18538/// a datetime scalar is the STRING form — `scalar_to_json` in the oracle
18539/// deliberately does not intercept `Timestamp` and falls through to `str(value)`,
18540/// with a comment saying so. There the answer is a merge KEY COLUMN, where
18541/// pandas keeps `datetime64[ns]` (measured on `reset_index` and on an
18542/// index-merge) and FrankenPandas must join on the typed value, not on text.
18543///
18544/// So this stays a serialization convention for a scalar comparison, while the
18545/// column path delegates to `DataFrame::reset_index`. Keeping them separate is
18546/// deliberate; collapsing either into the other reintroduces
18547/// br-frankenpandas-oxodo's failure in one direction or the other.
18548fn index_label_to_scalar(label: &IndexLabel) -> Scalar {
18549    match label {
18550        IndexLabel::Int64(value) => Scalar::Int64(*value),
18551        IndexLabel::Float64(value) => Scalar::Float64(value.0),
18552        IndexLabel::Bool(value) => Scalar::Bool(*value),
18553        IndexLabel::Utf8(value) => Scalar::Utf8(value.clone()),
18554        IndexLabel::Timedelta64(value) => Scalar::Timedelta64(*value),
18555        IndexLabel::Datetime64(value) => Scalar::Utf8(format_datetime_ns(*value)),
18556        IndexLabel::Object(value) => Scalar::Object(value.clone()),
18557        IndexLabel::Period(value) => Scalar::Period(*value),
18558        IndexLabel::Interval(value) => Scalar::Interval(*value),
18559        // Typed-null label round-trips to the same-kind missing scalar.
18560        IndexLabel::Null(kind) => Scalar::Null(*kind),
18561    }
18562}
18563
18564fn execute_groupby_fixture_operation(
18565    fixture: &PacketFixture,
18566    operation: FixtureOperation,
18567    policy: &RuntimePolicy,
18568    ledger: &mut EvidenceLedger,
18569) -> Result<Series, String> {
18570    let key_series = build_groupby_key_series(fixture)?;
18571    let values = require_right_series(fixture)?;
18572    let value_series =
18573        build_series(values).map_err(|err| format!("values series build failed: {err}"))?;
18574    let options = GroupByOptions::default();
18575
18576    let result = match operation {
18577        FixtureOperation::GroupBySum => {
18578            groupby_sum(&key_series, &value_series, options, policy, ledger)
18579        }
18580        FixtureOperation::GroupByMean => {
18581            groupby_mean(&key_series, &value_series, options, policy, ledger)
18582        }
18583        FixtureOperation::GroupByCount => {
18584            groupby_count(&key_series, &value_series, options, policy, ledger)
18585        }
18586        FixtureOperation::GroupByMin => {
18587            groupby_min(&key_series, &value_series, options, policy, ledger)
18588        }
18589        FixtureOperation::GroupByMax => {
18590            groupby_max(&key_series, &value_series, options, policy, ledger)
18591        }
18592        FixtureOperation::GroupByFirst => {
18593            groupby_first(&key_series, &value_series, options, policy, ledger)
18594        }
18595        FixtureOperation::GroupByLast => {
18596            groupby_last(&key_series, &value_series, options, policy, ledger)
18597        }
18598        FixtureOperation::GroupByStd => {
18599            groupby_std(&key_series, &value_series, options, policy, ledger)
18600        }
18601        FixtureOperation::GroupByVar => {
18602            groupby_var(&key_series, &value_series, options, policy, ledger)
18603        }
18604        FixtureOperation::GroupByMedian => {
18605            groupby_median(&key_series, &value_series, options, policy, ledger)
18606        }
18607        _ => {
18608            return Err(format!(
18609                "unsupported groupby operation for fixture execution: {operation:?}"
18610            ));
18611        }
18612    };
18613
18614    result.map_err(|err| err.to_string())
18615}
18616
18617fn build_groupby_key_series(fixture: &PacketFixture) -> Result<Series, String> {
18618    if let Some(groupby_keys) = fixture.groupby_keys.as_ref() {
18619        if groupby_keys.is_empty() {
18620            return Err("groupby_keys must contain at least one key series".to_owned());
18621        }
18622        return build_composite_groupby_keys_series(groupby_keys);
18623    }
18624
18625    let keys = require_left_series(fixture)?;
18626    build_series(keys).map_err(|err| format!("keys series build failed: {err}"))
18627}
18628
18629fn build_composite_groupby_keys_series(groupby_keys: &[FixtureSeries]) -> Result<Series, String> {
18630    let mut union_index = Vec::new();
18631    let mut seen = BTreeSet::new();
18632    let mut key_maps = Vec::with_capacity(groupby_keys.len());
18633
18634    for key in groupby_keys {
18635        if key.index.len() != key.values.len() {
18636            return Err(format!(
18637                "groupby key series '{}' index/value length mismatch: {} vs {}",
18638                key.name,
18639                key.index.len(),
18640                key.values.len()
18641            ));
18642        }
18643
18644        for label in &key.index {
18645            if seen.insert(label.clone()) {
18646                union_index.push(label.clone());
18647            }
18648        }
18649
18650        let mut first_value_by_label: HashMap<IndexLabel, Scalar> = HashMap::new();
18651        for (label, value) in key.index.iter().cloned().zip(key.values.iter().cloned()) {
18652            first_value_by_label.entry(label).or_insert(value);
18653        }
18654        key_maps.push(first_value_by_label);
18655    }
18656
18657    let mut composite_values = Vec::with_capacity(union_index.len());
18658    for label in &union_index {
18659        let mut tuple_values = Vec::with_capacity(key_maps.len());
18660        let mut has_missing_component = false;
18661
18662        for key_map in &key_maps {
18663            match key_map.get(label) {
18664                Some(value) if !value.is_missing() => tuple_values.push(value.clone()),
18665                _ => {
18666                    has_missing_component = true;
18667                    break;
18668                }
18669            }
18670        }
18671
18672        if has_missing_component {
18673            composite_values.push(Scalar::Null(NullKind::Null));
18674        } else {
18675            let composite = encode_groupby_composite_key(&tuple_values)?;
18676            composite_values.push(Scalar::Utf8(composite));
18677        }
18678    }
18679
18680    Series::from_values(
18681        "groupby_composite_key".to_owned(),
18682        union_index,
18683        composite_values,
18684    )
18685    .map_err(|err| format!("groupby composite key series build failed: {err}"))
18686}
18687
18688fn encode_groupby_composite_key(values: &[Scalar]) -> Result<String, String> {
18689    let mut components = Vec::with_capacity(values.len());
18690    for value in values {
18691        let component = match value {
18692            Scalar::Bool(v) => format!("b:{v}"),
18693            Scalar::Int64(v) => format!("i:{v}"),
18694            Scalar::Float64(v) => {
18695                if v.is_nan() {
18696                    return Err("groupby composite key component cannot be NaN".to_owned());
18697                }
18698                format!("f_bits:{:016x}", v.to_bits())
18699            }
18700            Scalar::Utf8(v) => {
18701                let escaped = serde_json::to_string(v)
18702                    .map_err(|err| format!("groupby key encoding failed: {err}"))?;
18703                format!("s:{escaped}")
18704            }
18705            Scalar::Timedelta64(v) => {
18706                if *v == Timedelta::NAT {
18707                    return Err("groupby composite key component cannot be NaT".to_owned());
18708                }
18709                format!("td:{v}")
18710            }
18711            Scalar::Datetime64(v) => {
18712                if *v == Timestamp::NAT {
18713                    return Err("groupby composite key component cannot be NaT".to_owned());
18714                }
18715                format!("dt:{v}")
18716            }
18717            Scalar::Period(v) => {
18718                if v.ordinal == i64::MIN {
18719                    return Err("groupby composite key component cannot be NaT".to_owned());
18720                }
18721                format!("pd:{}:{}", v.freq, v.ordinal)
18722            }
18723            Scalar::Interval(iv) => format!("iv:{iv}"),
18724            Scalar::Object(object) => format!("obj:{}", object.repr()),
18725            Scalar::Null(_) => {
18726                return Err("groupby composite key component cannot be null".to_owned());
18727            }
18728        };
18729        components.push(component);
18730    }
18731
18732    Ok(components.join("|"))
18733}
18734
18735/// The dtype a fixture payload DECLARES, mirroring the oracle's chooser.
18736///
18737/// `pandas_oracle.py::series_dtype_for_payload_values` maps a payload whose
18738/// non-null kinds are exactly `{int64}` and which carries a null to the NULLABLE
18739/// `Int64`, and `{bool}` + null to `boolean`. The harness had no equivalent: it
18740/// went straight to `Column::from_values`, whose `infer_dtype` SKIPS nulls and
18741/// yields plain `DType::Int64`. So for the same payload the oracle built
18742/// `Int64Dtype()` while FrankenPandas built `dtype('int64')` — the two sides
18743/// were handed DIFFERENT columns, which is how FP-P2D-056 merged an asof key
18744/// that pandas rejects as `incompatible merge keys`.
18745///
18746/// FrankenPandas models the distinction already — `DType::Int64Nullable` and
18747/// `DType::BoolNullable`, whose `name()` is literally `"Int64"` and
18748/// `"boolean"` — and `fp-join` already implements the rejection
18749/// (br-frankenpandas-sopel, 870a1003c). Nothing was CHOOSING the nullable
18750/// dtype. This is the harness-input class of defect, the same shape as
18751/// br-frankenpandas-nv5ct and br-frankenpandas-i9mgp: no amount of re-banking
18752/// the EXPECTED side can fix it, and the failure points at the wrong crate.
18753///
18754/// Returning `None` means "let inference decide", so every payload shape other
18755/// than these two is untouched. (br-frankenpandas-vprpg)
18756fn declared_payload_dtype(values: &[Scalar]) -> Option<DType> {
18757    let mut has_null = false;
18758    let mut kinds = BTreeSet::new();
18759    for value in values {
18760        if value.is_missing() {
18761            has_null = true;
18762        } else {
18763            kinds.insert(value.dtype());
18764        }
18765    }
18766    // No null means no nullable-extension question to answer: an all-valid
18767    // int64 payload is plain `int64` in pandas too.
18768    if !has_null {
18769        return None;
18770    }
18771    match kinds.iter().next() {
18772        Some(DType::Int64) if kinds.len() == 1 => Some(DType::Int64Nullable),
18773        Some(DType::Bool) if kinds.len() == 1 => Some(DType::BoolNullable),
18774        _ => None,
18775    }
18776}
18777
18778fn column_from_fixture_values(values: Vec<Scalar>) -> Result<Column, String> {
18779    match declared_payload_dtype(&values) {
18780        Some(dtype) => Column::new(dtype, values).map_err(|err| err.to_string()),
18781        None => Column::from_values(values).map_err(|err| err.to_string()),
18782    }
18783}
18784
18785/// `DataFrame::from_dict_with_index`, but routing each lane through the payload
18786/// dtype chooser instead of `Column::from_values`.
18787///
18788/// The frame path matters more than the Series path here: `merge_asof` takes
18789/// FRAMES, so wiring the chooser into `build_series` alone would have left
18790/// FP-P2D-056 exactly as red as before.
18791fn dataframe_from_fixture_columns(
18792    columns: Vec<(String, Vec<Scalar>)>,
18793    index_labels: Vec<IndexLabel>,
18794) -> Result<DataFrame, String> {
18795    let n = index_labels.len();
18796    let mut pairs = Vec::with_capacity(columns.len());
18797    let mut order = Vec::with_capacity(columns.len());
18798    for (name, values) in columns {
18799        if values.len() != n {
18800            return Err(format!(
18801                "column '{name}' has {} values but the index has {n}",
18802                values.len()
18803            ));
18804        }
18805        order.push(name.clone());
18806        pairs.push((name, column_from_fixture_values(values)?));
18807    }
18808    DataFrame::new_with_column_order(
18809        Index::new(index_labels),
18810        fp_frame::ColumnStore::from_pairs(pairs),
18811        order,
18812    )
18813    .map_err(|err| err.to_string())
18814}
18815
18816fn build_series(series: &FixtureSeries) -> Result<Series, String> {
18817    let column = column_from_fixture_values(series.values.clone())?;
18818    Series::new(
18819        series.name.clone(),
18820        Index::new(series.index.clone()),
18821        column,
18822    )
18823    .map_err(|err| err.to_string())
18824}
18825
18826fn build_series_with_optional_categorical(
18827    fixture: &PacketFixture,
18828    series: &FixtureSeries,
18829) -> Result<Series, String> {
18830    if let Some(categories) = fixture.categorical_categories.as_ref() {
18831        let ordered = fixture.categorical_ordered.unwrap_or(false);
18832        let codes = series
18833            .values
18834            .iter()
18835            .enumerate()
18836            .map(|(idx, value)| match value {
18837                Scalar::Int64(code) => Ok(*code),
18838                other => Err(format!(
18839                    "categorical fixture requires int64 codes at idx={idx}, got {other:?}"
18840                )),
18841            })
18842            .collect::<Result<Vec<_>, _>>()?;
18843
18844        Series::from_categorical_codes(series.name.clone(), codes, categories.clone(), ordered)
18845            .map_err(|err| err.to_string())
18846    } else {
18847        build_series(series)
18848    }
18849}
18850
18851fn build_series_for_dtype_check(fixture: &PacketFixture) -> Result<Series, String> {
18852    let left = require_left_series(fixture)?;
18853    // ⚠ THIS BRANCH IS STEERED BY THE EXPECTED OUTPUT, WHICH IS BACKWARDS
18854    // (br-frankenpandas-3gxc6). It used to test `== Some("Sparse")` exactly, so
18855    // the fixture's EXPECTATION decided how its INPUT was built: repinning
18856    // `expected_dtype` to the pandas-correct `Sparse[int64, 0]` silently
18857    // stopped the harness building a sparse Series at all, and the case then
18858    // reported `actual=int64` — a failure that looked like an FP regression and
18859    // was really the harness constructing a different input.
18860    //
18861    // Widened to accept the parameterized name so the pin can be correct. The
18862    // CIRCULARITY IS NOT FIXED and should not be mistaken for fixed: this still
18863    // reads an expectation to choose an input, so a sparse case can only ever
18864    // assert a name beginning "Sparse". The real fix is to key the branch off an
18865    // INPUT declaration (`fill_value` / `constructor_dtype`), which is a wider
18866    // harness change and needs its own bead — a fixture asserting that a sparse
18867    // payload does NOT report a sparse dtype is currently unwritable.
18868    if fixture
18869        .expected_dtype
18870        .as_deref()
18871        .is_some_and(|dtype| dtype == "Sparse" || dtype.starts_with("Sparse["))
18872    {
18873        let dtype_spec = fixture
18874            .constructor_dtype
18875            .as_deref()
18876            .ok_or_else(|| "constructor_dtype required for sparse series_dtype_check".to_owned())?;
18877        let value_dtype = parse_constructor_dtype_spec(dtype_spec)?;
18878        let fill_value = fixture
18879            .fill_value
18880            .clone()
18881            .unwrap_or_else(|| Scalar::missing_for_dtype(value_dtype.clone()));
18882        return Series::from_sparse_dense(
18883            left.name.clone(),
18884            left.index.clone(),
18885            left.values.clone(),
18886            value_dtype,
18887            fill_value,
18888        )
18889        .map_err(|err| err.to_string());
18890    }
18891    build_series_with_optional_categorical(fixture, left)
18892}
18893
18894fn run_series_categorical_from_codes(fixture: &PacketFixture) -> Result<Series, String> {
18895    let left = require_left_series(fixture)?;
18896    let categories = fixture.categorical_categories.as_ref().ok_or_else(|| {
18897        "categorical_categories required for series_categorical_from_codes".to_owned()
18898    })?;
18899    let ordered = fixture.categorical_ordered.unwrap_or(false);
18900    let codes = left
18901        .values
18902        .iter()
18903        .enumerate()
18904        .map(|(idx, value)| match value {
18905            Scalar::Int64(code) => Ok(*code),
18906            other => Err(format!(
18907                "series_categorical_from_codes requires int64 codes at idx={idx}, got {other:?}"
18908            )),
18909        })
18910        .collect::<Result<Vec<_>, _>>()?;
18911
18912    let categorical =
18913        Series::from_categorical_codes(left.name.clone(), codes, categories.clone(), ordered)
18914            .map_err(|err| err.to_string())?;
18915
18916    categorical
18917        .cat()
18918        .ok_or_else(|| "series_categorical_from_codes produced non-categorical series".to_owned())?
18919        .to_values()
18920        .map_err(|err| err.to_string())
18921}
18922
18923fn resolve_datetime_origin_option(
18924    origin: Option<&serde_json::Value>,
18925) -> Result<Option<fp_frame::ToDatetimeOrigin<'_>>, String> {
18926    match origin {
18927        None | Some(serde_json::Value::Null) => Ok(None),
18928        Some(serde_json::Value::String(value)) => {
18929            let trimmed = value.trim();
18930            if trimmed.is_empty() {
18931                Err("series_to_datetime datetime_origin must be non-empty".to_owned())
18932            } else {
18933                Ok(Some(fp_frame::ToDatetimeOrigin::Str(trimmed)))
18934            }
18935        }
18936        Some(serde_json::Value::Number(value)) => {
18937            if let Some(int_value) = value.as_i64() {
18938                Ok(Some(fp_frame::ToDatetimeOrigin::Int(int_value)))
18939            } else if let Some(float_value) = value.as_f64() {
18940                Ok(Some(fp_frame::ToDatetimeOrigin::Float(float_value)))
18941            } else {
18942                Err("series_to_datetime datetime_origin number is out of range".to_owned())
18943            }
18944        }
18945        Some(_) => {
18946            Err("series_to_datetime datetime_origin must be a string, integer, or float".to_owned())
18947        }
18948    }
18949}
18950
18951fn resolve_frame_column_order(frame: &FixtureDataFrame) -> Result<Vec<String>, String> {
18952    let mut column_order = Vec::new();
18953    let mut seen = BTreeSet::new();
18954
18955    if let Some(requested_order) = frame.column_order.as_ref() {
18956        for name in requested_order {
18957            if !frame.columns.contains_key(name) {
18958                return Err(format!(
18959                    "frame column_order references missing column '{name}'"
18960                ));
18961            }
18962            // Positions in column_order are unique while column names need not be.
18963            // Record seen names to prevent appending already-requested columns.
18964            seen.insert(name.clone());
18965            column_order.push(name.clone());
18966        }
18967    }
18968
18969    // DOCUMENT order, not the map's sorted keys. An explicit `column_order`
18970    // still wins (handled above); this only decides the order of the columns it
18971    // did not name. (br-frankenpandas-i9mgp)
18972    for name in frame.columns.document_order() {
18973        if seen.insert(name.clone()) {
18974            column_order.push(name.clone());
18975        }
18976    }
18977
18978    Ok(column_order)
18979}
18980
18981fn build_fixture_categorical_series(
18982    name: &str,
18983    values: &[Scalar],
18984    spec: &FixtureCategoricalColumn,
18985) -> Result<Series, String> {
18986    let codes = values
18987        .iter()
18988        .enumerate()
18989        .map(|(idx, value)| {
18990            if value.is_missing() {
18991                return Ok(-1);
18992            }
18993            spec.categories
18994                .iter()
18995                .position(|category| category.semantic_eq(value))
18996                .map(|position| position as i64)
18997                .ok_or_else(|| {
18998                    format!(
18999                        "frame categorical column '{name}' value at idx={idx} is not present in categories"
19000                    )
19001                })
19002        })
19003        .collect::<Result<Vec<_>, _>>()?;
19004
19005    let categories = spec.categories.clone();
19006    let ordered = spec.ordered.unwrap_or(false);
19007    Series::from_categorical_codes(name.to_owned(), codes, categories, ordered)
19008        .map_err(|err| err.to_string())
19009}
19010
19011fn build_fixture_multiindex(spec: &FixtureMultiIndex) -> Result<fp_index::MultiIndex, String> {
19012    let mut multiindex = if spec.tuples.is_empty() && !spec.names.is_empty() {
19013        fp_index::MultiIndex::from_arrays(vec![Vec::new(); spec.names.len()])
19014            .map_err(|err| err.to_string())?
19015    } else {
19016        fp_index::MultiIndex::from_tuples(spec.tuples.clone()).map_err(|err| err.to_string())?
19017    };
19018    if !spec.names.is_empty() {
19019        multiindex = multiindex.set_names(
19020            spec.names
19021                .iter()
19022                .map(|name| name.clone().map(Into::into))
19023                .collect(),
19024        );
19025    }
19026    Ok(multiindex)
19027}
19028
19029fn multiindex_to_fixture(multiindex: &fp_index::MultiIndex) -> Result<FixtureMultiIndex, String> {
19030    let tuples = (0..multiindex.len())
19031        .map(|position| {
19032            multiindex
19033                .get_tuple(position)
19034                .ok_or_else(|| format!("row MultiIndex position {position} out of bounds"))
19035                .map(|tuple| tuple.into_iter().cloned().collect::<Vec<_>>())
19036        })
19037        .collect::<Result<Vec<_>, _>>()?;
19038    Ok(FixtureMultiIndex {
19039        tuples,
19040        names: multiindex
19041            .names()
19042            .iter()
19043            .map(|name| name.clone().map(String::from))
19044            .collect(),
19045    })
19046}
19047
19048fn attach_fixture_row_multiindex(
19049    frame: DataFrame,
19050    spec: Option<&FixtureMultiIndex>,
19051) -> Result<DataFrame, String> {
19052    let Some(spec) = spec else {
19053        return Ok(frame);
19054    };
19055
19056    let row_multiindex = build_fixture_multiindex(spec)?;
19057    // br-frankenpandas-wfkzm: `new_with_row_multiindex` takes a ColumnStore and
19058    // re-sorts its names alphabetically, so a previously-reordered
19059    // row-MultiIndex fixture reached FrankenPandas with its columns reordered
19060    // and seven live tests compared the wrong frame. Keep the order the
19061    // fixture declared.
19062    frame
19063        .with_row_multiindex(row_multiindex)
19064        .map_err(|err| err.to_string())
19065}
19066
19067fn build_dataframe(frame_spec: &FixtureDataFrame) -> Result<DataFrame, String> {
19068    let column_order = resolve_frame_column_order(frame_spec)?;
19069    if let Some(categorical_columns) = frame_spec.categorical_columns.as_ref() {
19070        let row_index = frame_spec.index.clone();
19071        let default_index = (0..row_index.len() as i64)
19072            .map(IndexLabel::from)
19073            .collect::<Vec<_>>();
19074        let mut series_list = Vec::with_capacity(column_order.len());
19075
19076        for name in &column_order {
19077            let values = frame_spec
19078                .columns
19079                .get(name)
19080                .ok_or_else(|| format!("frame is missing column '{name}'"))?;
19081            let series = if let Some(spec) = categorical_columns.get(name) {
19082                build_fixture_categorical_series(name, values, spec)?
19083            } else {
19084                Series::from_values(name.clone(), default_index.clone(), values.clone())
19085                    .map_err(|err| err.to_string())?
19086            };
19087            series_list.push(series);
19088        }
19089
19090        let materialized = DataFrame::from_series(series_list).map_err(|err| err.to_string())?;
19091        let rebuilt_columns = column_order
19092            .iter()
19093            .enumerate()
19094            .map(|(col_idx, name)| {
19095                let col = materialized.column_at(col_idx).ok_or_else(|| {
19096                    format!("materialized frame is missing column at idx={col_idx}")
19097                })?;
19098                Ok((name.clone(), col.values().to_vec()))
19099            })
19100            .collect::<Result<Vec<_>, String>>()?;
19101        let frame = dataframe_from_fixture_columns(rebuilt_columns, row_index)?;
19102        return attach_fixture_row_multiindex(frame, frame_spec.row_multiindex.as_ref());
19103    }
19104
19105    let columns = column_order
19106        .iter()
19107        .map(|name| {
19108            frame_spec
19109                .columns
19110                .get(name)
19111                .cloned()
19112                .map(|values| (name.clone(), values))
19113                .ok_or_else(|| format!("frame is missing column '{name}'"))
19114        })
19115        .collect::<Result<Vec<_>, String>>()?;
19116
19117    let frame = dataframe_from_fixture_columns(columns, frame_spec.index.clone())?;
19118    attach_fixture_row_multiindex(frame, frame_spec.row_multiindex.as_ref())
19119}
19120
19121fn compare_series_expected(
19122    actual: &Series,
19123    expected: &FixtureExpectedSeries,
19124) -> Result<(), String> {
19125    // br-frankenpandas-xi5li: compared ONLY when the fixture pins one, so the
19126    // ~569 fixtures that omit it keep meaning "not asserted".
19127    //
19128    // MEASURED before switching this on, live pandas 2.2.3 on a Series named
19129    // "values": mode / rank / duplicated / drop_duplicates / where / mask /
19130    // replace / map all return a result whose .name is "values", and update is
19131    // in-place and leaves it "values". So the pinned names are pandas' answer,
19132    // not an artifact of an older emitter.
19133    if let Some(expected_name) = expected.name.as_deref()
19134        && actual.name() != expected_name
19135    {
19136        return Err(format!(
19137            "series name mismatch: actual={:?}, expected={expected_name:?}",
19138            actual.name()
19139        ));
19140    }
19141
19142    if actual.index().labels() != expected.index {
19143        return Err(format!(
19144            "index mismatch: actual={:?}, expected={:?}",
19145            actual.index().labels(),
19146            expected.index
19147        ));
19148    }
19149
19150    if actual.values().len() != expected.values.len() {
19151        return Err(format!(
19152            "value length mismatch: actual={}, expected={}",
19153            actual.values().len(),
19154            expected.values.len()
19155        ));
19156    }
19157
19158    for (idx, (left, right)) in actual
19159        .values()
19160        .iter()
19161        .zip(expected.values.iter())
19162        .enumerate()
19163    {
19164        if !left.semantic_eq(right) {
19165            return Err(format!(
19166                "value mismatch at idx={idx}: actual={left:?}, expected={right:?}"
19167            ));
19168        }
19169    }
19170    Ok(())
19171}
19172
19173fn compare_dataframe_expected(
19174    actual: &DataFrame,
19175    expected: &FixtureExpectedDataFrame,
19176) -> Result<(), String> {
19177    if actual.index().labels() != expected.index {
19178        return Err(format!(
19179            "dataframe index mismatch: actual={:?}, expected={:?}",
19180            actual.index().labels(),
19181            expected.index
19182        ));
19183    }
19184
19185    let actual_names = actual
19186        .column_names()
19187        .into_iter()
19188        .map(ToOwned::to_owned)
19189        .collect::<Vec<_>>();
19190    if let Some(expected_order) = expected.column_order.clone() {
19191        if actual_names != expected_order {
19192            return Err(format!(
19193                "dataframe column mismatch: actual={actual_names:?}, expected={expected_order:?}"
19194            ));
19195        }
19196    } else {
19197        let mut expected_names = expected.columns.keys().cloned().collect::<Vec<_>>();
19198        expected_names.sort();
19199        let mut actual_sorted = actual_names.clone();
19200        actual_sorted.sort();
19201        if actual_sorted != expected_names {
19202            return Err(format!(
19203                "dataframe column set mismatch: actual={actual_names:?}, expected={expected_names:?}"
19204            ));
19205        }
19206    }
19207
19208    let actual_row_multiindex = actual
19209        .row_multiindex()
19210        .map(multiindex_to_fixture)
19211        .transpose()?;
19212    if actual_row_multiindex != expected.row_multiindex {
19213        return Err(format!(
19214            "dataframe row_multiindex mismatch: actual={actual_row_multiindex:?}, expected={:?}",
19215            expected.row_multiindex
19216        ));
19217    }
19218
19219    // Column axis, sibling of the row check above (br-frankenpandas-nv5ct).
19220    // Compared unconditionally in BOTH directions: a fixture pinning a
19221    // two-level axis must fail on a flat actual, AND a flat fixture must fail on
19222    // an actual that grew one, or the key would only ever be decorative.
19223    let actual_column_multiindex = actual
19224        .column_multiindex()
19225        .map(multiindex_to_fixture)
19226        .transpose()?;
19227    if actual_column_multiindex != expected.column_multiindex {
19228        return Err(format!(
19229            "dataframe column_multiindex mismatch: actual={actual_column_multiindex:?}, expected={:?}",
19230            expected.column_multiindex
19231        ));
19232    }
19233
19234    for (name, expected_values) in &expected.columns {
19235        let Some(column) = actual.column(name) else {
19236            return Err(format!("dataframe column missing in actual: {name}"));
19237        };
19238
19239        if column.values().len() != expected_values.len() {
19240            return Err(format!(
19241                "dataframe column '{name}' length mismatch: actual={}, expected={}",
19242                column.values().len(),
19243                expected_values.len()
19244            ));
19245        }
19246
19247        for (idx, (left, right)) in column
19248            .values()
19249            .iter()
19250            .zip(expected_values.iter())
19251            .enumerate()
19252        {
19253            if !left.semantic_eq(right) {
19254                return Err(format!(
19255                    "dataframe column '{name}' mismatch at idx={idx}: actual={left:?}, expected={right:?}"
19256                ));
19257            }
19258        }
19259    }
19260
19261    Ok(())
19262}
19263
19264fn compare_scalar(actual: &Scalar, expected: &Scalar, op_name: &str) -> Result<(), String> {
19265    if !actual.semantic_eq(expected) {
19266        return Err(format!(
19267            "{op_name} scalar mismatch: actual={actual:?}, expected={expected:?}"
19268        ));
19269    }
19270    Ok(())
19271}
19272
19273fn compare_join_expected(
19274    actual: &fp_join::JoinedSeries,
19275    expected: &FixtureExpectedJoin,
19276) -> Result<(), String> {
19277    if actual.index.labels() != expected.index {
19278        return Err(format!(
19279            "join index mismatch: actual={:?}, expected={:?}",
19280            actual.index.labels(),
19281            expected.index
19282        ));
19283    }
19284
19285    if actual.left_values.values().len() != expected.left_values.len() {
19286        return Err(format!(
19287            "join left length mismatch: actual={}, expected={}",
19288            actual.left_values.values().len(),
19289            expected.left_values.len()
19290        ));
19291    }
19292    if actual.right_values.values().len() != expected.right_values.len() {
19293        return Err(format!(
19294            "join right length mismatch: actual={}, expected={}",
19295            actual.right_values.values().len(),
19296            expected.right_values.len()
19297        ));
19298    }
19299
19300    for (idx, (left, right)) in actual
19301        .left_values
19302        .values()
19303        .iter()
19304        .zip(expected.left_values.iter())
19305        .enumerate()
19306    {
19307        let equal = left.semantic_eq(right) || (left.is_missing() && right.is_missing());
19308        if !equal {
19309            return Err(format!(
19310                "join left mismatch at idx={idx}: actual={left:?}, expected={right:?}"
19311            ));
19312        }
19313    }
19314    for (idx, (left, right)) in actual
19315        .right_values
19316        .values()
19317        .iter()
19318        .zip(expected.right_values.iter())
19319        .enumerate()
19320    {
19321        let equal = left.semantic_eq(right) || (left.is_missing() && right.is_missing());
19322        if !equal {
19323            return Err(format!(
19324                "join right mismatch at idx={idx}: actual={left:?}, expected={right:?}"
19325            ));
19326        }
19327    }
19328
19329    Ok(())
19330}
19331
19332fn compare_alignment_expected(
19333    actual: &AlignmentPlan,
19334    expected: &FixtureExpectedAlignment,
19335) -> Result<(), String> {
19336    if actual.union_index.labels() != expected.union_index {
19337        return Err(format!(
19338            "union_index mismatch: actual={:?}, expected={:?}",
19339            actual.union_index.labels(),
19340            expected.union_index
19341        ));
19342    }
19343    if actual.left_positions != expected.left_positions {
19344        return Err(format!(
19345            "left_positions mismatch: actual={:?}, expected={:?}",
19346            actual.left_positions, expected.left_positions
19347        ));
19348    }
19349    if actual.right_positions != expected.right_positions {
19350        return Err(format!(
19351            "right_positions mismatch: actual={:?}, expected={:?}",
19352            actual.right_positions, expected.right_positions
19353        ));
19354    }
19355    Ok(())
19356}
19357
19358// === Differential Harness: Internal Execution + Taxonomy Comparators ===
19359
19360fn build_differential_report_internal(
19361    config: &HarnessConfig,
19362    suite: String,
19363    packet_id: Option<String>,
19364    fixtures: &[PacketFixture],
19365    options: &SuiteOptions,
19366) -> Result<DifferentialReport, HarnessError> {
19367    let mut results = Vec::with_capacity(fixtures.len());
19368    for fixture in fixtures {
19369        results.push(run_differential_fixture(config, fixture, options)?);
19370    }
19371    Ok(build_differential_report(
19372        suite,
19373        packet_id,
19374        config.oracle_root.exists(),
19375        results,
19376    ))
19377}
19378
19379fn run_differential_fixture(
19380    config: &HarnessConfig,
19381    fixture: &PacketFixture,
19382    options: &SuiteOptions,
19383) -> Result<DifferentialResult, HarnessError> {
19384    // br-frankenpandas-fixture-corpus-stale-vs-oracle-p6srr: a RETIRED fixture
19385    // is not executed, and — critically — is not a pass. It keeps its place in
19386    // `fixture_count` and carries its reason, so the report can never present a
19387    // skipped case as a checked one.
19388    if let Some(retirement) = &fixture.retired {
19389        return Ok(DifferentialResult::retired(fixture, &retirement.reason));
19390    }
19391    let policy = match fixture.mode {
19392        RuntimeMode::Strict => RuntimePolicy::strict(),
19393        RuntimeMode::Hardened => RuntimePolicy::hardened(Some(100_000)),
19394    };
19395    let mut ledger = EvidenceLedger::new();
19396    let oracle_source = fixture.oracle_source.unwrap_or(match options.oracle_mode {
19397        OracleMode::FixtureExpected => FixtureOracleSource::Fixture,
19398        OracleMode::LiveLegacyPandas => FixtureOracleSource::LiveLegacyPandas,
19399    });
19400
19401    let drift_records = match execute_and_compare_differential(
19402        config,
19403        fixture,
19404        &policy,
19405        &mut ledger,
19406        options.oracle_mode,
19407    ) {
19408        Ok(drifts) => drifts,
19409        Err(err) => vec![make_drift_record(
19410            ComparisonCategory::Value,
19411            DriftLevel::Critical,
19412            "execution",
19413            err,
19414        )],
19415    };
19416
19417    let has_critical = drift_records
19418        .iter()
19419        .any(|d| matches!(d.level, DriftLevel::Critical));
19420
19421    Ok(DifferentialResult {
19422        case_id: fixture.case_id.clone(),
19423        packet_id: fixture.packet_id.clone(),
19424        operation: fixture.operation,
19425        mode: fixture.mode,
19426        replay_key: deterministic_replay_key(&fixture.packet_id, &fixture.case_id, fixture.mode),
19427        trace_id: deterministic_trace_id(&fixture.packet_id, &fixture.case_id, fixture.mode),
19428        oracle_source,
19429        // This path EXECUTED the fixture, so it is never a retirement.
19430        retired_reason: None,
19431        status: if has_critical {
19432            CaseStatus::Fail
19433        } else {
19434            CaseStatus::Pass
19435        },
19436        drift_records,
19437        evidence_records: ledger.records().len(),
19438    })
19439}
19440
19441fn execute_and_compare_differential(
19442    config: &HarnessConfig,
19443    fixture: &PacketFixture,
19444    policy: &RuntimePolicy,
19445    ledger: &mut EvidenceLedger,
19446    default_oracle_mode: OracleMode,
19447) -> Result<Vec<DriftRecord>, String> {
19448    let expected = resolve_expected(config, fixture, default_oracle_mode)
19449        .map_err(|err| format!("expected resolution failed: {err}"))?;
19450
19451    match fixture.operation {
19452        FixtureOperation::SeriesAdd
19453        | FixtureOperation::SeriesSub
19454        | FixtureOperation::SeriesMul
19455        | FixtureOperation::SeriesDiv => {
19456            let left = require_left_series(fixture)?;
19457            let right = require_right_series(fixture)?;
19458            let left_series = build_series(left)?;
19459            let right_series = build_series(right)?;
19460            let actual = match fixture.operation {
19461                FixtureOperation::SeriesAdd => {
19462                    left_series.add_with_policy(&right_series, policy, ledger)
19463                }
19464                FixtureOperation::SeriesSub => {
19465                    left_series.sub_with_policy(&right_series, policy, ledger)
19466                }
19467                FixtureOperation::SeriesMul => {
19468                    left_series.mul_with_policy(&right_series, policy, ledger)
19469                }
19470                FixtureOperation::SeriesDiv => {
19471                    left_series.div_with_policy(&right_series, policy, ledger)
19472                }
19473                _ => unreachable!("match arm constrained to series arithmetic operations"),
19474            }
19475            .map_err(|err| err.to_string())?;
19476            let expected = match expected {
19477                ResolvedExpected::Series(s) => s,
19478                _ => {
19479                    return Err(format!(
19480                        "expected_series required for {}",
19481                        fixture.operation.operation_name()
19482                    ));
19483                }
19484            };
19485            Ok(diff_series(&actual, &expected))
19486        }
19487        FixtureOperation::SeriesJoin => {
19488            let left = require_left_series(fixture)?;
19489            let right = require_right_series(fixture)?;
19490            let joined = (|| -> Result<fp_join::JoinedSeries, String> {
19491                let left_series = build_series(left).map_err(|err| format!("left build: {err}"))?;
19492                let right_series =
19493                    build_series(right).map_err(|err| format!("right build: {err}"))?;
19494                let join_type = require_series_join_type(fixture)?;
19495                join_series(&left_series, &right_series, join_type).map_err(|err| err.to_string())
19496            })();
19497            match expected {
19498                ResolvedExpected::Join(expected_join) => Ok(diff_join(&joined?, &expected_join)),
19499                ResolvedExpected::ErrorContains(substr) => Ok(match joined {
19500                    Err(message) if message.contains(&substr) => Vec::new(),
19501                    Err(message) => vec![make_drift_record(
19502                        ComparisonCategory::Value,
19503                        DriftLevel::Critical,
19504                        "series_join.error",
19505                        format!(
19506                            "expected series_join error containing '{substr}', got '{}'",
19507                            message
19508                        ),
19509                    )],
19510                    Ok(_) => vec![make_drift_record(
19511                        ComparisonCategory::Value,
19512                        DriftLevel::Critical,
19513                        "series_join.error",
19514                        format!("expected series_join to fail with error containing '{substr}'"),
19515                    )],
19516                }),
19517                ResolvedExpected::ErrorAny => Ok(match joined {
19518                    Err(_) => Vec::new(),
19519                    Ok(_) => vec![make_drift_record(
19520                        ComparisonCategory::Value,
19521                        DriftLevel::Critical,
19522                        "series_join.error",
19523                        "expected series_join to fail".to_owned(),
19524                    )],
19525                }),
19526                _ => Err("expected_join required for series_join".to_owned()),
19527            }
19528        }
19529        FixtureOperation::SeriesConstructor => {
19530            let left = require_left_series(fixture)?;
19531            let actual = build_series(left);
19532            match expected {
19533                ResolvedExpected::Series(series) => Ok(diff_series(&actual?, &series)),
19534                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
19535                    Err(message) if message.contains(&substr) => Vec::new(),
19536                    Err(message) => vec![make_drift_record(
19537                        ComparisonCategory::Value,
19538                        DriftLevel::Critical,
19539                        "series_constructor.error",
19540                        format!(
19541                            "expected series_constructor error containing '{substr}', got '{message}'"
19542                        ),
19543                    )],
19544                    Ok(_) => vec![make_drift_record(
19545                        ComparisonCategory::Value,
19546                        DriftLevel::Critical,
19547                        "series_constructor.error",
19548                        "expected series_constructor to fail but operation succeeded".to_owned(),
19549                    )],
19550                }),
19551                ResolvedExpected::ErrorAny => Ok(match actual {
19552                    Err(_) => Vec::new(),
19553                    Ok(_) => vec![make_drift_record(
19554                        ComparisonCategory::Value,
19555                        DriftLevel::Critical,
19556                        "series_constructor.error",
19557                        "expected series_constructor to fail but operation succeeded".to_owned(),
19558                    )],
19559                }),
19560                _ => Err(
19561                    "expected_series or expected_error required for series_constructor".to_owned(),
19562                ),
19563            }
19564        }
19565        FixtureOperation::SeriesToDatetime => {
19566            let left = require_left_series(fixture)?;
19567            let series = build_series(left)?;
19568            let actual = resolve_datetime_origin_option(fixture.datetime_origin.as_ref()).and_then(
19569                |origin| {
19570                    fp_frame::to_datetime_with_options(
19571                        &series,
19572                        fp_frame::ToDatetimeOptions {
19573                            format: None,
19574                            unit: fixture.datetime_unit.as_deref(),
19575                            utc: fixture.datetime_utc.unwrap_or(false),
19576                            origin,
19577                            infer_mixed_timezone: true,
19578                            mixed_tz_as_object: false,
19579                            errors: fp_frame::DatetimeErrors::Coerce,
19580                            dayfirst: false,
19581                            yearfirst: false,
19582                            list_input: false,
19583                        },
19584                    )
19585                    .map_err(|err| err.to_string())
19586                },
19587            );
19588            match expected {
19589                ResolvedExpected::Series(series) => Ok(diff_series(&actual?, &series)),
19590                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
19591                    Err(message) if message.contains(&substr) => Vec::new(),
19592                    Err(message) => vec![make_drift_record(
19593                        ComparisonCategory::Value,
19594                        DriftLevel::Critical,
19595                        "series_to_datetime.error",
19596                        format!(
19597                            "expected series_to_datetime error containing '{substr}', got '{message}'"
19598                        ),
19599                    )],
19600                    Ok(_) => vec![make_drift_record(
19601                        ComparisonCategory::Value,
19602                        DriftLevel::Critical,
19603                        "series_to_datetime.error",
19604                        "expected series_to_datetime to fail but operation succeeded".to_owned(),
19605                    )],
19606                }),
19607                ResolvedExpected::ErrorAny => Ok(match actual {
19608                    Err(_) => Vec::new(),
19609                    Ok(_) => vec![make_drift_record(
19610                        ComparisonCategory::Value,
19611                        DriftLevel::Critical,
19612                        "series_to_datetime.error",
19613                        "expected series_to_datetime to fail but operation succeeded".to_owned(),
19614                    )],
19615                }),
19616                _ => Err(
19617                    "expected_series or expected_error required for series_to_datetime".to_owned(),
19618                ),
19619            }
19620        }
19621        FixtureOperation::SeriesToTimedelta => {
19622            let left = require_left_series(fixture)?;
19623            let series = build_series(left)?;
19624            let actual = fp_frame::to_timedelta(&series).map_err(|err| err.to_string());
19625            match expected {
19626                ResolvedExpected::Series(series) => Ok(diff_series(&actual?, &series)),
19627                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
19628                    Err(message) if message.contains(&substr) => Vec::new(),
19629                    Err(message) => vec![make_drift_record(
19630                        ComparisonCategory::Value,
19631                        DriftLevel::Critical,
19632                        "series_to_timedelta.error",
19633                        format!(
19634                            "expected series_to_timedelta error containing '{substr}', got '{message}'"
19635                        ),
19636                    )],
19637                    Ok(_) => vec![make_drift_record(
19638                        ComparisonCategory::Value,
19639                        DriftLevel::Critical,
19640                        "series_to_timedelta.error",
19641                        "expected series_to_timedelta to fail but operation succeeded".to_owned(),
19642                    )],
19643                }),
19644                ResolvedExpected::ErrorAny => Ok(match actual {
19645                    Err(_) => Vec::new(),
19646                    Ok(_) => vec![make_drift_record(
19647                        ComparisonCategory::Value,
19648                        DriftLevel::Critical,
19649                        "series_to_timedelta.error",
19650                        "expected series_to_timedelta to fail but operation succeeded".to_owned(),
19651                    )],
19652                }),
19653                _ => Err(
19654                    "expected_series or expected_error required for series_to_timedelta".to_owned(),
19655                ),
19656            }
19657        }
19658        FixtureOperation::SeriesTimedeltaTotalSeconds => {
19659            let left = require_left_series(fixture)?;
19660            let series = build_series(left)?;
19661            let actual = fp_frame::timedelta_total_seconds(&series).map_err(|err| err.to_string());
19662            match expected {
19663                ResolvedExpected::Series(series) => Ok(diff_series(&actual?, &series)),
19664                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
19665                    Err(message) if message.contains(&substr) => Vec::new(),
19666                    Err(message) => vec![make_drift_record(
19667                        ComparisonCategory::Value,
19668                        DriftLevel::Critical,
19669                        "timedelta_total_seconds.error",
19670                        format!(
19671                            "expected timedelta_total_seconds error containing '{substr}', got '{message}'"
19672                        ),
19673                    )],
19674                    Ok(_) => vec![make_drift_record(
19675                        ComparisonCategory::Value,
19676                        DriftLevel::Critical,
19677                        "timedelta_total_seconds.error",
19678                        "expected timedelta_total_seconds to fail but operation succeeded"
19679                            .to_owned(),
19680                    )],
19681                }),
19682                ResolvedExpected::ErrorAny => Ok(match actual {
19683                    Err(_) => Vec::new(),
19684                    Ok(_) => vec![make_drift_record(
19685                        ComparisonCategory::Value,
19686                        DriftLevel::Critical,
19687                        "timedelta_total_seconds.error",
19688                        "expected timedelta_total_seconds to fail but operation succeeded"
19689                            .to_owned(),
19690                    )],
19691                }),
19692                _ => Err(
19693                    "expected_series or expected_error required for timedelta_total_seconds"
19694                        .to_owned(),
19695                ),
19696            }
19697        }
19698        FixtureOperation::DataFrameFromSeries => {
19699            let actual = execute_dataframe_from_series_fixture_operation(fixture);
19700            match expected {
19701                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
19702                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
19703                    Err(message) if message.contains(&substr) => Vec::new(),
19704                    Err(message) => vec![make_drift_record(
19705                        ComparisonCategory::Value,
19706                        DriftLevel::Critical,
19707                        "dataframe_from_series.error",
19708                        format!(
19709                            "expected dataframe_from_series error containing '{substr}', got '{message}'"
19710                        ),
19711                    )],
19712                    Ok(_) => vec![make_drift_record(
19713                        ComparisonCategory::Value,
19714                        DriftLevel::Critical,
19715                        "dataframe_from_series.error",
19716                        "expected dataframe_from_series to fail but operation succeeded".to_owned(),
19717                    )],
19718                }),
19719                ResolvedExpected::ErrorAny => Ok(match actual {
19720                    Err(_) => Vec::new(),
19721                    Ok(_) => vec![make_drift_record(
19722                        ComparisonCategory::Value,
19723                        DriftLevel::Critical,
19724                        "dataframe_from_series.error",
19725                        "expected dataframe_from_series to fail but operation succeeded".to_owned(),
19726                    )],
19727                }),
19728                _ => Err(
19729                    "expected_frame or expected_error required for dataframe_from_series"
19730                        .to_owned(),
19731                ),
19732            }
19733        }
19734        FixtureOperation::DataFrameFromDict => {
19735            let actual = execute_dataframe_from_dict_fixture_operation(fixture);
19736            match expected {
19737                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
19738                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
19739                    Err(message) if message.contains(&substr) => Vec::new(),
19740                    Err(message) => vec![make_drift_record(
19741                        ComparisonCategory::Value,
19742                        DriftLevel::Critical,
19743                        "dataframe_from_dict.error",
19744                        format!(
19745                            "expected dataframe_from_dict error containing '{substr}', got '{message}'"
19746                        ),
19747                    )],
19748                    Ok(_) => vec![make_drift_record(
19749                        ComparisonCategory::Value,
19750                        DriftLevel::Critical,
19751                        "dataframe_from_dict.error",
19752                        "expected dataframe_from_dict to fail but operation succeeded".to_owned(),
19753                    )],
19754                }),
19755                ResolvedExpected::ErrorAny => Ok(match actual {
19756                    Err(_) => Vec::new(),
19757                    Ok(_) => vec![make_drift_record(
19758                        ComparisonCategory::Value,
19759                        DriftLevel::Critical,
19760                        "dataframe_from_dict.error",
19761                        "expected dataframe_from_dict to fail but operation succeeded".to_owned(),
19762                    )],
19763                }),
19764                _ => Err(
19765                    "expected_frame or expected_error required for dataframe_from_dict".to_owned(),
19766                ),
19767            }
19768        }
19769        FixtureOperation::DataFrameFromRecords => {
19770            let actual = execute_dataframe_from_records_fixture_operation(fixture);
19771            match expected {
19772                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
19773                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
19774                    Err(message) if message.contains(&substr) => Vec::new(),
19775                    Err(message) => vec![make_drift_record(
19776                        ComparisonCategory::Value,
19777                        DriftLevel::Critical,
19778                        "dataframe_from_records.error",
19779                        format!(
19780                            "expected dataframe_from_records error containing '{substr}', got '{message}'"
19781                        ),
19782                    )],
19783                    Ok(_) => vec![make_drift_record(
19784                        ComparisonCategory::Value,
19785                        DriftLevel::Critical,
19786                        "dataframe_from_records.error",
19787                        "expected dataframe_from_records to fail but operation succeeded"
19788                            .to_owned(),
19789                    )],
19790                }),
19791                ResolvedExpected::ErrorAny => Ok(match actual {
19792                    Err(_) => Vec::new(),
19793                    Ok(_) => vec![make_drift_record(
19794                        ComparisonCategory::Value,
19795                        DriftLevel::Critical,
19796                        "dataframe_from_records.error",
19797                        "expected dataframe_from_records to fail but operation succeeded"
19798                            .to_owned(),
19799                    )],
19800                }),
19801                _ => Err(
19802                    "expected_frame or expected_error required for dataframe_from_records"
19803                        .to_owned(),
19804                ),
19805            }
19806        }
19807        FixtureOperation::DataFrameConstructorKwargs => {
19808            let actual = execute_dataframe_constructor_kwargs_fixture_operation(fixture);
19809            match expected {
19810                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
19811                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
19812                    Err(message) if message.contains(&substr) => Vec::new(),
19813                    Err(message) => vec![make_drift_record(
19814                        ComparisonCategory::Value,
19815                        DriftLevel::Critical,
19816                        "dataframe_constructor_kwargs.error",
19817                        format!(
19818                            "expected dataframe_constructor_kwargs error containing '{substr}', got '{message}'"
19819                        ),
19820                    )],
19821                    Ok(_) => vec![make_drift_record(
19822                        ComparisonCategory::Value,
19823                        DriftLevel::Critical,
19824                        "dataframe_constructor_kwargs.error",
19825                        "expected dataframe_constructor_kwargs to fail but operation succeeded"
19826                            .to_owned(),
19827                    )],
19828                }),
19829                ResolvedExpected::ErrorAny => Ok(match actual {
19830                    Err(_) => Vec::new(),
19831                    Ok(_) => vec![make_drift_record(
19832                        ComparisonCategory::Value,
19833                        DriftLevel::Critical,
19834                        "dataframe_constructor_kwargs.error",
19835                        "expected dataframe_constructor_kwargs to fail but operation succeeded"
19836                            .to_owned(),
19837                    )],
19838                }),
19839                _ => Err(
19840                    "expected_frame or expected_error required for dataframe_constructor_kwargs"
19841                        .to_owned(),
19842                ),
19843            }
19844        }
19845        FixtureOperation::DataFrameConstructorScalar => {
19846            let actual = execute_dataframe_constructor_scalar_fixture_operation(fixture);
19847            match expected {
19848                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
19849                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
19850                    Err(message) if message.contains(&substr) => Vec::new(),
19851                    Err(message) => vec![make_drift_record(
19852                        ComparisonCategory::Value,
19853                        DriftLevel::Critical,
19854                        "dataframe_constructor_scalar.error",
19855                        format!(
19856                            "expected dataframe_constructor_scalar error containing '{substr}', got '{message}'"
19857                        ),
19858                    )],
19859                    Ok(_) => vec![make_drift_record(
19860                        ComparisonCategory::Value,
19861                        DriftLevel::Critical,
19862                        "dataframe_constructor_scalar.error",
19863                        "expected dataframe_constructor_scalar to fail but operation succeeded"
19864                            .to_owned(),
19865                    )],
19866                }),
19867                ResolvedExpected::ErrorAny => Ok(match actual {
19868                    Err(_) => Vec::new(),
19869                    Ok(_) => vec![make_drift_record(
19870                        ComparisonCategory::Value,
19871                        DriftLevel::Critical,
19872                        "dataframe_constructor_scalar.error",
19873                        "expected dataframe_constructor_scalar to fail but operation succeeded"
19874                            .to_owned(),
19875                    )],
19876                }),
19877                _ => Err(
19878                    "expected_frame or expected_error required for dataframe_constructor_scalar"
19879                        .to_owned(),
19880                ),
19881            }
19882        }
19883        FixtureOperation::DataFrameConstructorDictOfSeries => {
19884            let actual = execute_dataframe_constructor_dict_of_series_fixture_operation(fixture);
19885            match expected {
19886                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
19887                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
19888                    Err(message) if message.contains(&substr) => Vec::new(),
19889                    Err(message) => vec![make_drift_record(
19890                        ComparisonCategory::Value,
19891                        DriftLevel::Critical,
19892                        "dataframe_constructor_dict_of_series.error",
19893                        format!(
19894                            "expected dataframe_constructor_dict_of_series error containing '{substr}', got '{message}'"
19895                        ),
19896                    )],
19897                    Ok(_) => vec![make_drift_record(
19898                        ComparisonCategory::Value,
19899                        DriftLevel::Critical,
19900                        "dataframe_constructor_dict_of_series.error",
19901                        "expected dataframe_constructor_dict_of_series to fail but operation succeeded"
19902                            .to_owned(),
19903                    )],
19904                }),
19905                ResolvedExpected::ErrorAny => Ok(match actual {
19906                    Err(_) => Vec::new(),
19907                    Ok(_) => vec![make_drift_record(
19908                        ComparisonCategory::Value,
19909                        DriftLevel::Critical,
19910                        "dataframe_constructor_dict_of_series.error",
19911                        "expected dataframe_constructor_dict_of_series to fail but operation succeeded"
19912                            .to_owned(),
19913                    )],
19914                }),
19915                _ => Err(
19916                    "expected_frame or expected_error required for dataframe_constructor_dict_of_series"
19917                        .to_owned(),
19918                ),
19919            }
19920        }
19921        FixtureOperation::DataFrameConstructorListLike => {
19922            let actual = execute_dataframe_constructor_list_like_fixture_operation(fixture);
19923            match expected {
19924                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
19925                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
19926                    Err(message) if message.contains(&substr) => Vec::new(),
19927                    Err(message) => vec![make_drift_record(
19928                        ComparisonCategory::Value,
19929                        DriftLevel::Critical,
19930                        "dataframe_constructor_list_like.error",
19931                        format!(
19932                            "expected dataframe_constructor_list_like error containing '{substr}', got '{message}'"
19933                        ),
19934                    )],
19935                    Ok(_) => vec![make_drift_record(
19936                        ComparisonCategory::Value,
19937                        DriftLevel::Critical,
19938                        "dataframe_constructor_list_like.error",
19939                        "expected dataframe_constructor_list_like to fail but operation succeeded"
19940                            .to_owned(),
19941                    )],
19942                }),
19943                ResolvedExpected::ErrorAny => Ok(match actual {
19944                    Err(_) => Vec::new(),
19945                    Ok(_) => vec![make_drift_record(
19946                        ComparisonCategory::Value,
19947                        DriftLevel::Critical,
19948                        "dataframe_constructor_list_like.error",
19949                        "expected dataframe_constructor_list_like to fail but operation succeeded"
19950                            .to_owned(),
19951                    )],
19952                }),
19953                _ => Err(
19954                    "expected_frame or expected_error required for dataframe_constructor_list_like"
19955                        .to_owned(),
19956                ),
19957            }
19958        }
19959        FixtureOperation::GroupBySum => {
19960            let actual =
19961                execute_groupby_fixture_operation(fixture, fixture.operation, policy, ledger)?;
19962            let expected = match expected {
19963                ResolvedExpected::Series(s) => s,
19964                _ => return Err("expected_series required for groupby_sum".to_owned()),
19965            };
19966            Ok(diff_series(&actual, &expected))
19967        }
19968        FixtureOperation::IndexAlignUnion => {
19969            let left = require_left_series(fixture)?;
19970            let right = require_right_series(fixture)?;
19971            let plan = align_union(
19972                &Index::new(left.index.clone()),
19973                &Index::new(right.index.clone()),
19974            );
19975            validate_alignment_plan(&plan).map_err(|err| err.to_string())?;
19976            let expected = match expected {
19977                ResolvedExpected::Alignment(a) => a,
19978                _ => return Err("expected_alignment required for index_align_union".to_owned()),
19979            };
19980            Ok(diff_alignment(&plan, &expected))
19981        }
19982        FixtureOperation::IndexHasDuplicates
19983        | FixtureOperation::IndexIsMonotonicIncreasing
19984        | FixtureOperation::IndexIsMonotonicDecreasing => {
19985            let index = require_index(fixture)?;
19986            let index = Index::new(index.clone());
19987            let actual = match fixture.operation {
19988                FixtureOperation::IndexHasDuplicates => index.has_duplicates(),
19989                FixtureOperation::IndexIsMonotonicIncreasing => index.is_monotonic_increasing(),
19990                FixtureOperation::IndexIsMonotonicDecreasing => index.is_monotonic_decreasing(),
19991                _ => unreachable!(),
19992            };
19993            let expected = match expected {
19994                ResolvedExpected::Bool(b) => b,
19995                _ => {
19996                    return Err(format!(
19997                        "expected_bool required for {}",
19998                        fixture.operation.operation_name()
19999                    ));
20000                }
20001            };
20002            Ok(diff_bool(
20003                actual,
20004                expected,
20005                fixture.operation.operation_name(),
20006            ))
20007        }
20008        FixtureOperation::IndexFirstPositions => {
20009            let index = require_index(fixture)?;
20010            let index = Index::new(index.clone());
20011            let positions = index.position_map_first();
20012            let actual: Vec<Option<usize>> = index
20013                .labels()
20014                .iter()
20015                .map(|label| positions.get(label).copied())
20016                .collect();
20017            let expected = match expected {
20018                ResolvedExpected::Positions(p) => p,
20019                _ => {
20020                    return Err("expected_positions required for index_first_positions".to_owned());
20021                }
20022            };
20023            Ok(diff_positions(&actual, &expected))
20024        }
20025        FixtureOperation::SeriesConcat => {
20026            let left = require_left_series(fixture)?;
20027            let right = require_right_series(fixture)?;
20028            let left_s = build_series(left).map_err(|err| format!("left build: {err}"))?;
20029            let right_s = build_series(right).map_err(|err| format!("right build: {err}"))?;
20030            let actual = concat_series(&[&left_s, &right_s]).map_err(|err| err.to_string())?;
20031            let expected = match expected {
20032                ResolvedExpected::Series(s) => s,
20033                _ => return Err("expected_series required for series_concat".to_owned()),
20034            };
20035            Ok(diff_series(&actual, &expected))
20036        }
20037        FixtureOperation::NanSum
20038        | FixtureOperation::NanMean
20039        | FixtureOperation::NanMin
20040        | FixtureOperation::NanMax
20041        | FixtureOperation::NanStd
20042        | FixtureOperation::NanVar
20043        | FixtureOperation::NanCount => {
20044            let actual = execute_nanop_fixture_operation(fixture, fixture.operation)?;
20045            let expected = match expected {
20046                ResolvedExpected::Scalar(scalar) => scalar,
20047                _ => {
20048                    return Err(format!(
20049                        "expected_scalar required for {}",
20050                        fixture.operation.operation_name()
20051                    ));
20052                }
20053            };
20054            Ok(diff_scalar(
20055                &actual,
20056                &expected,
20057                fixture.operation.operation_name(),
20058            ))
20059        }
20060        FixtureOperation::FillNa => {
20061            let left = require_left_series(fixture)?;
20062            let fill = fixture
20063                .fill_value
20064                .as_ref()
20065                .ok_or_else(|| "fill_value is required for fill_na".to_owned())?;
20066            let actual_values = fill_na(&left.values, fill);
20067            let expected = match expected {
20068                ResolvedExpected::Series(series) => series,
20069                _ => return Err("expected_series required for fill_na".to_owned()),
20070            };
20071            Ok(diff_values(&actual_values, &expected.values, "fill_na"))
20072        }
20073        FixtureOperation::DropNa => {
20074            let left = require_left_series(fixture)?;
20075            let actual_values = dropna(&left.values);
20076            let expected = match expected {
20077                ResolvedExpected::Series(series) => series,
20078                _ => return Err("expected_series required for drop_na".to_owned()),
20079            };
20080            Ok(diff_values(&actual_values, &expected.values, "drop_na"))
20081        }
20082        FixtureOperation::SeriesToArrowRoundTrip => {
20083            let actual = execute_series_to_arrow_round_trip_fixture_operation(fixture);
20084            match expected {
20085                ResolvedExpected::Series(series) => Ok(diff_series(&actual?, &series)),
20086                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20087                    Err(message) if message.contains(&substr) => Vec::new(),
20088                    Err(message) => vec![make_drift_record(
20089                        ComparisonCategory::Value,
20090                        DriftLevel::Critical,
20091                        "series_to_arrow_round_trip.error",
20092                        format!(
20093                            "expected series_to_arrow_round_trip error containing '{substr}', got '{message}'"
20094                        ),
20095                    )],
20096                    Ok(_) => vec![make_drift_record(
20097                        ComparisonCategory::Value,
20098                        DriftLevel::Critical,
20099                        "series_to_arrow_round_trip.error",
20100                        "expected series_to_arrow_round_trip to fail but operation succeeded"
20101                            .to_owned(),
20102                    )],
20103                }),
20104                ResolvedExpected::ErrorAny => Ok(match actual {
20105                    Err(_) => Vec::new(),
20106                    Ok(_) => vec![make_drift_record(
20107                        ComparisonCategory::Value,
20108                        DriftLevel::Critical,
20109                        "series_to_arrow_round_trip.error",
20110                        "expected series_to_arrow_round_trip to fail but operation succeeded"
20111                            .to_owned(),
20112                    )],
20113                }),
20114                _ => Err(
20115                    "expected_series or expected_error required for series_to_arrow_round_trip"
20116                        .to_owned(),
20117                ),
20118            }
20119        }
20120        FixtureOperation::CsvRoundTrip => {
20121            let actual = execute_csv_round_trip_fixture_operation(fixture);
20122            diff_bool_round_trip_result(actual, expected, "csv_round_trip")
20123        }
20124        FixtureOperation::CsvReadFrame => {
20125            let actual = execute_csv_read_frame_fixture_operation(fixture);
20126            match expected {
20127                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
20128                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20129                    Err(message) if message.contains(&substr) => Vec::new(),
20130                    Err(message) => vec![make_drift_record(
20131                        ComparisonCategory::Value,
20132                        DriftLevel::Critical,
20133                        "csv_read_frame.error",
20134                        format!(
20135                            "expected csv_read_frame error containing '{substr}', got '{message}'"
20136                        ),
20137                    )],
20138                    Ok(_) => vec![make_drift_record(
20139                        ComparisonCategory::Value,
20140                        DriftLevel::Critical,
20141                        "csv_read_frame.error",
20142                        "expected csv_read_frame to fail but operation succeeded".to_owned(),
20143                    )],
20144                }),
20145                ResolvedExpected::ErrorAny => Ok(match actual {
20146                    Err(_) => Vec::new(),
20147                    Ok(_) => vec![make_drift_record(
20148                        ComparisonCategory::Value,
20149                        DriftLevel::Critical,
20150                        "csv_read_frame.error",
20151                        "expected csv_read_frame to fail but operation succeeded".to_owned(),
20152                    )],
20153                }),
20154                _ => Err("expected_frame or expected_error required for csv_read_frame".to_owned()),
20155            }
20156        }
20157        FixtureOperation::DataFrameToJsonRecords => {
20158            let actual = execute_dataframe_to_json_records_fixture_operation(fixture);
20159            match expected {
20160                ResolvedExpected::Scalar(expected) => Ok(diff_scalar(
20161                    &actual?,
20162                    &expected,
20163                    fixture.operation.operation_name(),
20164                )),
20165                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20166                    Err(message) if message.contains(&substr) => Vec::new(),
20167                    Err(message) => vec![make_drift_record(
20168                        ComparisonCategory::Value,
20169                        DriftLevel::Critical,
20170                        "dataframe_to_json_records.error",
20171                        format!(
20172                            "expected dataframe_to_json_records error containing '{substr}', got '{message}'"
20173                        ),
20174                    )],
20175                    Ok(_) => vec![make_drift_record(
20176                        ComparisonCategory::Value,
20177                        DriftLevel::Critical,
20178                        "dataframe_to_json_records.error",
20179                        "expected dataframe_to_json_records to fail but operation succeeded"
20180                            .to_owned(),
20181                    )],
20182                }),
20183                ResolvedExpected::ErrorAny => Ok(match actual {
20184                    Err(_) => Vec::new(),
20185                    Ok(_) => vec![make_drift_record(
20186                        ComparisonCategory::Value,
20187                        DriftLevel::Critical,
20188                        "dataframe_to_json_records.error",
20189                        "expected dataframe_to_json_records to fail but operation succeeded"
20190                            .to_owned(),
20191                    )],
20192                }),
20193                _ => Err(
20194                    "expected_scalar or expected_error required for dataframe_to_json_records"
20195                        .to_owned(),
20196                ),
20197            }
20198        }
20199        FixtureOperation::JsonRoundTrip => {
20200            let actual = execute_json_round_trip_fixture_operation(fixture);
20201            diff_bool_round_trip_result(actual, expected, "json_round_trip")
20202        }
20203        FixtureOperation::JsonlRoundTrip => {
20204            let actual = execute_jsonl_round_trip_fixture_operation(fixture);
20205            diff_bool_round_trip_result(actual, expected, "jsonl_round_trip")
20206        }
20207        FixtureOperation::ParquetRoundTrip => {
20208            let actual = execute_parquet_round_trip_fixture_operation(fixture);
20209            diff_bool_round_trip_result(actual, expected, "parquet_round_trip")
20210        }
20211        FixtureOperation::FeatherRoundTrip => {
20212            let actual = execute_feather_round_trip_fixture_operation(fixture);
20213            diff_bool_round_trip_result(actual, expected, "feather_round_trip")
20214        }
20215        FixtureOperation::ExcelRoundTrip => {
20216            let actual = execute_excel_round_trip_fixture_operation(fixture);
20217            diff_bool_round_trip_result(actual, expected, "excel_round_trip")
20218        }
20219        FixtureOperation::IpcStreamRoundTrip => {
20220            let actual = execute_ipc_stream_round_trip_fixture_operation(fixture);
20221            diff_bool_round_trip_result(actual, expected, "ipc_stream_round_trip")
20222        }
20223        FixtureOperation::ColumnDtypeCheck => {
20224            let left = require_left_series(fixture)?;
20225            let series = build_series(left)?;
20226            // pandas SPELLING, not Rust `Debug`. `DType::name()` is documented
20227            // "Matches numpy dtype.name property" and yields int64/float64/
20228            // object/category/Int64/boolean; `{:?}` yields FrankenPandas
20229            // internals (Float64/Utf8/Categorical) that no oracle can produce,
20230            // which is why these fixtures were unverifiable.
20231            // (br-frankenpandas-62d1s)
20232            let actual_dtype = series.column().dtype().name().to_owned();
20233            let expected = match expected {
20234                ResolvedExpected::Dtype(dtype) => dtype,
20235                _ => return Err("expected_dtype required for column_dtype_check".to_owned()),
20236            };
20237            Ok(diff_string(&actual_dtype, &expected, "column_dtype"))
20238        }
20239        FixtureOperation::SeriesDtypeCheck => {
20240            let series = build_series_for_dtype_check(fixture)?;
20241            // See ColumnDtypeCheck above (br-frankenpandas-62d1s).
20242            //
20243            // `dtype_name()`, not `dtype().name()` (br-frankenpandas-3gxc6): a
20244            // sparse Series reports the parameterized `Sparse[int64, 0]` that
20245            // pandas spells, and `DType::name()` can only answer the bare
20246            // `"Sparse"` because `DType::Sparse` carries no subtype or fill.
20247            // Every other dtype is byte-identical through this call. Both the
20248            // strict and hardened arms route through it, so the two modes
20249            // cannot disagree about a dtype name.
20250            let actual_dtype = series.dtype_name();
20251            let expected = match expected {
20252                ResolvedExpected::Dtype(dtype) => dtype,
20253                _ => return Err("expected_dtype required for series_dtype_check".to_owned()),
20254            };
20255            Ok(diff_string(&actual_dtype, &expected, "series_dtype"))
20256        }
20257        FixtureOperation::SeriesFilter => {
20258            let left = require_left_series(fixture)?;
20259            let right = require_right_series(fixture)?;
20260            let data = build_series(left)?;
20261            let mask = build_series(right)?;
20262            let actual = data.filter(&mask).map_err(|err| err.to_string());
20263            match expected {
20264                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
20265                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20266                    Err(message) if message.contains(&substr) => Vec::new(),
20267                    Err(message) => vec![make_drift_record(
20268                        ComparisonCategory::Value,
20269                        DriftLevel::Critical,
20270                        "series_filter.error",
20271                        format!(
20272                            "expected series_filter error containing '{substr}', got '{message}'"
20273                        ),
20274                    )],
20275                    Ok(_) => vec![make_drift_record(
20276                        ComparisonCategory::Value,
20277                        DriftLevel::Critical,
20278                        "series_filter.error",
20279                        "expected series_filter to fail but operation succeeded".to_owned(),
20280                    )],
20281                }),
20282                ResolvedExpected::ErrorAny => Ok(match actual {
20283                    Err(_) => Vec::new(),
20284                    Ok(_) => vec![make_drift_record(
20285                        ComparisonCategory::Value,
20286                        DriftLevel::Critical,
20287                        "series_filter.error",
20288                        "expected series_filter to fail but operation succeeded".to_owned(),
20289                    )],
20290                }),
20291                _ => Err("expected_series or expected_error required for series_filter".to_owned()),
20292            }
20293        }
20294        FixtureOperation::SeriesHead => {
20295            let left = require_left_series(fixture)?;
20296            let n = fixture
20297                .head_n
20298                .ok_or_else(|| "head_n is required for series_head".to_owned())?;
20299            let series = build_series(left)?;
20300            let take = normalize_head_take(n, series.len());
20301            let labels = series.index().labels()[..take].to_vec();
20302            let values = series.values()[..take].to_vec();
20303            let actual =
20304                Series::from_values(series.name(), labels, values).map_err(|e| e.to_string())?;
20305            let expected = match expected {
20306                ResolvedExpected::Series(s) => s,
20307                _ => return Err("expected_series required for series_head".to_owned()),
20308            };
20309            Ok(diff_series(&actual, &expected))
20310        }
20311        FixtureOperation::SeriesTail => {
20312            let left = require_left_series(fixture)?;
20313            let n = fixture
20314                .tail_n
20315                .ok_or_else(|| "tail_n is required for series_tail".to_owned())?;
20316            let series = build_series(left)?;
20317            let actual = series.tail(n).map_err(|err| err.to_string());
20318            match expected {
20319                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
20320                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20321                    Err(message) if message.contains(&substr) => Vec::new(),
20322                    Err(message) => vec![make_drift_record(
20323                        ComparisonCategory::Value,
20324                        DriftLevel::Critical,
20325                        "series_tail.error",
20326                        format!(
20327                            "expected series_tail error containing '{substr}', got '{message}'"
20328                        ),
20329                    )],
20330                    Ok(_) => vec![make_drift_record(
20331                        ComparisonCategory::Value,
20332                        DriftLevel::Critical,
20333                        "series_tail.error",
20334                        "expected series_tail to fail but operation succeeded".to_owned(),
20335                    )],
20336                }),
20337                ResolvedExpected::ErrorAny => Ok(match actual {
20338                    Err(_) => Vec::new(),
20339                    Ok(_) => vec![make_drift_record(
20340                        ComparisonCategory::Value,
20341                        DriftLevel::Critical,
20342                        "series_tail.error",
20343                        "expected series_tail to fail but operation succeeded".to_owned(),
20344                    )],
20345                }),
20346                _ => Err("expected_series or expected_error required for series_tail".to_owned()),
20347            }
20348        }
20349        FixtureOperation::SeriesValueCounts => {
20350            let left = require_left_series(fixture)?;
20351            let series = build_series_with_optional_categorical(fixture, left)?;
20352            let actual = series
20353                .value_counts_with_options(
20354                    resolve_value_counts_normalize(fixture),
20355                    true,
20356                    resolve_value_counts_ascending(fixture),
20357                    true,
20358                )
20359                .map_err(|err| err.to_string());
20360            match expected {
20361                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
20362                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20363                    Err(message) if message.contains(&substr) => Vec::new(),
20364                    Err(message) => vec![make_drift_record(
20365                        ComparisonCategory::Value,
20366                        DriftLevel::Critical,
20367                        "series_value_counts.error",
20368                        format!(
20369                            "expected series_value_counts error containing '{substr}', got '{message}'"
20370                        ),
20371                    )],
20372                    Ok(_) => vec![make_drift_record(
20373                        ComparisonCategory::Value,
20374                        DriftLevel::Critical,
20375                        "series_value_counts.error",
20376                        "expected series_value_counts to fail but operation succeeded".to_owned(),
20377                    )],
20378                }),
20379                ResolvedExpected::ErrorAny => Ok(match actual {
20380                    Err(_) => Vec::new(),
20381                    Ok(_) => vec![make_drift_record(
20382                        ComparisonCategory::Value,
20383                        DriftLevel::Critical,
20384                        "series_value_counts.error",
20385                        "expected series_value_counts to fail but operation succeeded".to_owned(),
20386                    )],
20387                }),
20388                _ => Err(
20389                    "expected_series or expected_error required for series_value_counts".to_owned(),
20390                ),
20391            }
20392        }
20393        FixtureOperation::SeriesSortIndex => {
20394            let left = require_left_series(fixture)?;
20395            let series = build_series(left)?;
20396            let actual = series
20397                .sort_index(resolve_sort_ascending(fixture))
20398                .map_err(|err| err.to_string());
20399            match expected {
20400                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
20401                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20402                    Err(message) if message.contains(&substr) => Vec::new(),
20403                    Err(message) => vec![make_drift_record(
20404                        ComparisonCategory::Value,
20405                        DriftLevel::Critical,
20406                        "series_sort_index.error",
20407                        format!(
20408                            "expected series_sort_index error containing '{substr}', got '{message}'"
20409                        ),
20410                    )],
20411                    Ok(_) => vec![make_drift_record(
20412                        ComparisonCategory::Value,
20413                        DriftLevel::Critical,
20414                        "series_sort_index.error",
20415                        "expected series_sort_index to fail but operation succeeded".to_owned(),
20416                    )],
20417                }),
20418                ResolvedExpected::ErrorAny => Ok(match actual {
20419                    Err(_) => Vec::new(),
20420                    Ok(_) => vec![make_drift_record(
20421                        ComparisonCategory::Value,
20422                        DriftLevel::Critical,
20423                        "series_sort_index.error",
20424                        "expected series_sort_index to fail but operation succeeded".to_owned(),
20425                    )],
20426                }),
20427                _ => Err(
20428                    "expected_series or expected_error required for series_sort_index".to_owned(),
20429                ),
20430            }
20431        }
20432        FixtureOperation::SeriesSortValues => {
20433            let left = require_left_series(fixture)?;
20434            let series = build_series(left)?;
20435            let actual = series
20436                .sort_values(resolve_sort_ascending(fixture))
20437                .map_err(|err| err.to_string());
20438            match expected {
20439                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
20440                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20441                    Err(message) if message.contains(&substr) => Vec::new(),
20442                    Err(message) => vec![make_drift_record(
20443                        ComparisonCategory::Value,
20444                        DriftLevel::Critical,
20445                        "series_sort_values.error",
20446                        format!(
20447                            "expected series_sort_values error containing '{substr}', got '{message}'"
20448                        ),
20449                    )],
20450                    Ok(_) => vec![make_drift_record(
20451                        ComparisonCategory::Value,
20452                        DriftLevel::Critical,
20453                        "series_sort_values.error",
20454                        "expected series_sort_values to fail but operation succeeded".to_owned(),
20455                    )],
20456                }),
20457                ResolvedExpected::ErrorAny => Ok(match actual {
20458                    Err(_) => Vec::new(),
20459                    Ok(_) => vec![make_drift_record(
20460                        ComparisonCategory::Value,
20461                        DriftLevel::Critical,
20462                        "series_sort_values.error",
20463                        "expected series_sort_values to fail but operation succeeded".to_owned(),
20464                    )],
20465                }),
20466                _ => Err(
20467                    "expected_series or expected_error required for series_sort_values".to_owned(),
20468                ),
20469            }
20470        }
20471        FixtureOperation::SeriesDiff => {
20472            let left = require_left_series(fixture)?;
20473            let series = build_series(left)?;
20474            let periods = fixture.diff_periods.unwrap_or(1);
20475            let actual = series.diff(periods).map_err(|err| err.to_string());
20476            match expected {
20477                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
20478                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20479                    Err(message) if message.contains(&substr) => Vec::new(),
20480                    Err(message) => vec![make_drift_record(
20481                        ComparisonCategory::Value,
20482                        DriftLevel::Critical,
20483                        "series_diff.error",
20484                        format!(
20485                            "expected series_diff error containing '{substr}', got '{message}'"
20486                        ),
20487                    )],
20488                    Ok(_) => vec![make_drift_record(
20489                        ComparisonCategory::Value,
20490                        DriftLevel::Critical,
20491                        "series_diff.error",
20492                        "expected series_diff to fail but operation succeeded".to_owned(),
20493                    )],
20494                }),
20495                ResolvedExpected::ErrorAny => Ok(match actual {
20496                    Err(_) => Vec::new(),
20497                    Ok(_) => vec![make_drift_record(
20498                        ComparisonCategory::Value,
20499                        DriftLevel::Critical,
20500                        "series_diff.error",
20501                        "expected series_diff to fail but operation succeeded".to_owned(),
20502                    )],
20503                }),
20504                _ => Err("expected_series or expected_error required for series_diff".to_owned()),
20505            }
20506        }
20507        FixtureOperation::SeriesShift => {
20508            let left = require_left_series(fixture)?;
20509            let series = build_series(left)?;
20510            let periods = fixture.shift_periods.unwrap_or(1);
20511            let actual = series.shift(periods).map_err(|err| err.to_string());
20512            match expected {
20513                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
20514                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20515                    Err(message) if message.contains(&substr) => Vec::new(),
20516                    Err(message) => vec![make_drift_record(
20517                        ComparisonCategory::Value,
20518                        DriftLevel::Critical,
20519                        "series_shift.error",
20520                        format!(
20521                            "expected series_shift error containing '{substr}', got '{message}'"
20522                        ),
20523                    )],
20524                    Ok(_) => vec![make_drift_record(
20525                        ComparisonCategory::Value,
20526                        DriftLevel::Critical,
20527                        "series_shift.error",
20528                        "expected series_shift to fail but operation succeeded".to_owned(),
20529                    )],
20530                }),
20531                ResolvedExpected::ErrorAny => Ok(match actual {
20532                    Err(_) => Vec::new(),
20533                    Ok(_) => vec![make_drift_record(
20534                        ComparisonCategory::Value,
20535                        DriftLevel::Critical,
20536                        "series_shift.error",
20537                        "expected series_shift to fail but operation succeeded".to_owned(),
20538                    )],
20539                }),
20540                _ => Err("expected_series or expected_error required for series_shift".to_owned()),
20541            }
20542        }
20543        FixtureOperation::SeriesPctChange => {
20544            let left = require_left_series(fixture)?;
20545            let series = build_series(left)?;
20546            let periods = fixture.pct_change_periods.unwrap_or(1);
20547            let actual = series.pct_change(periods).map_err(|err| err.to_string());
20548            match expected {
20549                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
20550                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20551                    Err(message) if message.contains(&substr) => Vec::new(),
20552                    Err(message) => vec![make_drift_record(
20553                        ComparisonCategory::Value,
20554                        DriftLevel::Critical,
20555                        "series_pct_change.error",
20556                        format!(
20557                            "expected series_pct_change error containing '{substr}', got '{message}'"
20558                        ),
20559                    )],
20560                    Ok(_) => vec![make_drift_record(
20561                        ComparisonCategory::Value,
20562                        DriftLevel::Critical,
20563                        "series_pct_change.error",
20564                        "expected series_pct_change to fail but operation succeeded".to_owned(),
20565                    )],
20566                }),
20567                ResolvedExpected::ErrorAny => Ok(match actual {
20568                    Err(_) => Vec::new(),
20569                    Ok(_) => vec![make_drift_record(
20570                        ComparisonCategory::Value,
20571                        DriftLevel::Critical,
20572                        "series_pct_change.error",
20573                        "expected series_pct_change to fail but operation succeeded".to_owned(),
20574                    )],
20575                }),
20576                _ => Err(
20577                    "expected_series or expected_error required for series_pct_change".to_owned(),
20578                ),
20579            }
20580        }
20581        FixtureOperation::SeriesMode => {
20582            let left = require_left_series(fixture)?;
20583            let series = build_series(left)?;
20584            let actual = series
20585                .mode_with_dropna(fixture.mode_dropna.unwrap_or(true))
20586                .map_err(|err| err.to_string());
20587            match expected {
20588                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
20589                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20590                    Err(message) if message.contains(&substr) => Vec::new(),
20591                    Err(message) => vec![make_drift_record(
20592                        ComparisonCategory::Value,
20593                        DriftLevel::Critical,
20594                        "series_mode.error",
20595                        format!(
20596                            "expected series_mode error containing '{substr}', got '{message}'"
20597                        ),
20598                    )],
20599                    Ok(_) => vec![make_drift_record(
20600                        ComparisonCategory::Value,
20601                        DriftLevel::Critical,
20602                        "series_mode.error",
20603                        "expected series_mode to fail but operation succeeded".to_owned(),
20604                    )],
20605                }),
20606                ResolvedExpected::ErrorAny => Ok(match actual {
20607                    Err(_) => Vec::new(),
20608                    Ok(_) => vec![make_drift_record(
20609                        ComparisonCategory::Value,
20610                        DriftLevel::Critical,
20611                        "series_mode.error",
20612                        "expected series_mode to fail but operation succeeded".to_owned(),
20613                    )],
20614                }),
20615                _ => Err("expected_series or expected_error required for series_mode".to_owned()),
20616            }
20617        }
20618        FixtureOperation::SeriesRank => {
20619            let left = require_left_series(fixture)?;
20620            let series = build_series(left)?;
20621            let method = fixture.rank_method.as_deref().unwrap_or("average");
20622            let ascending = resolve_sort_ascending(fixture);
20623            let na_option = fixture.rank_na_option.as_deref().unwrap_or("keep");
20624            let pct = resolve_rank_pct(fixture);
20625            let actual = series
20626                .rank_with_pct(method, ascending, na_option, pct)
20627                .map_err(|err| err.to_string());
20628            match expected {
20629                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
20630                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20631                    Err(message) if message.contains(&substr) => Vec::new(),
20632                    Err(message) => vec![make_drift_record(
20633                        ComparisonCategory::Value,
20634                        DriftLevel::Critical,
20635                        "series_rank.error",
20636                        format!(
20637                            "expected series_rank error containing '{substr}', got '{message}'"
20638                        ),
20639                    )],
20640                    Ok(_) => vec![make_drift_record(
20641                        ComparisonCategory::Value,
20642                        DriftLevel::Critical,
20643                        "series_rank.error",
20644                        "expected series_rank to fail but operation succeeded".to_owned(),
20645                    )],
20646                }),
20647                ResolvedExpected::ErrorAny => Ok(match actual {
20648                    Err(_) => Vec::new(),
20649                    Ok(_) => vec![make_drift_record(
20650                        ComparisonCategory::Value,
20651                        DriftLevel::Critical,
20652                        "series_rank.error",
20653                        "expected series_rank to fail but operation succeeded".to_owned(),
20654                    )],
20655                }),
20656                _ => Err("expected_series or expected_error required for series_rank".to_owned()),
20657            }
20658        }
20659        FixtureOperation::SeriesArgsort => {
20660            let left = require_left_series(fixture)?;
20661            let series = build_series(left)?;
20662            let ascending = resolve_sort_ascending(fixture);
20663            let actual = series.argsort(ascending).map_err(|err| err.to_string());
20664            match expected {
20665                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
20666                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20667                    Err(message) if message.contains(&substr) => Vec::new(),
20668                    Err(message) => vec![make_drift_record(
20669                        ComparisonCategory::Value,
20670                        DriftLevel::Critical,
20671                        "series_argsort.error",
20672                        format!(
20673                            "expected series_argsort error containing '{substr}', got '{message}'"
20674                        ),
20675                    )],
20676                    Ok(_) => vec![make_drift_record(
20677                        ComparisonCategory::Value,
20678                        DriftLevel::Critical,
20679                        "series_argsort.error",
20680                        "expected series_argsort to fail but operation succeeded".to_owned(),
20681                    )],
20682                }),
20683                ResolvedExpected::ErrorAny => Ok(match actual {
20684                    Err(_) => Vec::new(),
20685                    Ok(_) => vec![make_drift_record(
20686                        ComparisonCategory::Value,
20687                        DriftLevel::Critical,
20688                        "series_argsort.error",
20689                        "expected series_argsort to fail but operation succeeded".to_owned(),
20690                    )],
20691                }),
20692                _ => {
20693                    Err("expected_series or expected_error required for series_argsort".to_owned())
20694                }
20695            }
20696        }
20697        FixtureOperation::SeriesDescribe => {
20698            let left = require_left_series(fixture)?;
20699            let series = build_series(left)?;
20700            let actual = series.describe().map_err(|err| err.to_string());
20701            match expected {
20702                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
20703                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20704                    Err(message) if message.contains(&substr) => Vec::new(),
20705                    Err(message) => vec![make_drift_record(
20706                        ComparisonCategory::Value,
20707                        DriftLevel::Critical,
20708                        "series_describe.error",
20709                        format!(
20710                            "expected series_describe error containing '{substr}', got '{message}'"
20711                        ),
20712                    )],
20713                    Ok(_) => vec![make_drift_record(
20714                        ComparisonCategory::Value,
20715                        DriftLevel::Critical,
20716                        "series_describe.error",
20717                        "expected series_describe to fail but operation succeeded".to_owned(),
20718                    )],
20719                }),
20720                ResolvedExpected::ErrorAny => Ok(match actual {
20721                    Err(_) => Vec::new(),
20722                    Ok(_) => vec![make_drift_record(
20723                        ComparisonCategory::Value,
20724                        DriftLevel::Critical,
20725                        "series_describe.error",
20726                        "expected series_describe to fail but operation succeeded".to_owned(),
20727                    )],
20728                }),
20729                _ => {
20730                    Err("expected_series or expected_error required for series_describe".to_owned())
20731                }
20732            }
20733        }
20734        FixtureOperation::SeriesDuplicated => {
20735            let left = require_left_series(fixture)?;
20736            let series = build_series(left)?;
20737            let keep = resolve_duplicate_keep(fixture)?;
20738            let actual = series.duplicated_keep(keep).map_err(|err| err.to_string());
20739            match expected {
20740                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
20741                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20742                    Err(message) if message.contains(&substr) => Vec::new(),
20743                    Err(message) => vec![make_drift_record(
20744                        ComparisonCategory::Value,
20745                        DriftLevel::Critical,
20746                        "series_duplicated.error",
20747                        format!(
20748                            "expected series_duplicated error containing '{substr}', got '{message}'"
20749                        ),
20750                    )],
20751                    Ok(_) => vec![make_drift_record(
20752                        ComparisonCategory::Value,
20753                        DriftLevel::Critical,
20754                        "series_duplicated.error",
20755                        "expected series_duplicated to fail but operation succeeded".to_owned(),
20756                    )],
20757                }),
20758                ResolvedExpected::ErrorAny => Ok(match actual {
20759                    Err(_) => Vec::new(),
20760                    Ok(_) => vec![make_drift_record(
20761                        ComparisonCategory::Value,
20762                        DriftLevel::Critical,
20763                        "series_duplicated.error",
20764                        "expected series_duplicated to fail but operation succeeded".to_owned(),
20765                    )],
20766                }),
20767                _ => Err(
20768                    "expected_series or expected_error required for series_duplicated".to_owned(),
20769                ),
20770            }
20771        }
20772        FixtureOperation::SeriesDropDuplicates => {
20773            let left = require_left_series(fixture)?;
20774            let series = build_series(left)?;
20775            let keep = resolve_duplicate_keep(fixture)?;
20776            let actual = series
20777                .drop_duplicates_keep(keep)
20778                .map_err(|err| err.to_string());
20779            match expected {
20780                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
20781                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20782                    Err(message) if message.contains(&substr) => Vec::new(),
20783                    Err(message) => vec![make_drift_record(
20784                        ComparisonCategory::Value,
20785                        DriftLevel::Critical,
20786                        "series_drop_duplicates.error",
20787                        format!(
20788                            "expected series_drop_duplicates error containing '{substr}', got '{message}'"
20789                        ),
20790                    )],
20791                    Ok(_) => vec![make_drift_record(
20792                        ComparisonCategory::Value,
20793                        DriftLevel::Critical,
20794                        "series_drop_duplicates.error",
20795                        "expected series_drop_duplicates to fail but operation succeeded"
20796                            .to_owned(),
20797                    )],
20798                }),
20799                ResolvedExpected::ErrorAny => Ok(match actual {
20800                    Err(_) => Vec::new(),
20801                    Ok(_) => vec![make_drift_record(
20802                        ComparisonCategory::Value,
20803                        DriftLevel::Critical,
20804                        "series_drop_duplicates.error",
20805                        "expected series_drop_duplicates to fail but operation succeeded"
20806                            .to_owned(),
20807                    )],
20808                }),
20809                _ => Err(
20810                    "expected_series or expected_error required for series_drop_duplicates"
20811                        .to_owned(),
20812                ),
20813            }
20814        }
20815        FixtureOperation::SeriesUnique => {
20816            let left = require_left_series(fixture)?;
20817            let series = build_series(left)?;
20818            let unique_values = series.unique();
20819            let labels: Vec<IndexLabel> = (0..unique_values.len())
20820                .map(|i| IndexLabel::Int64(i as i64))
20821                .collect();
20822            let actual = Series::from_values(series.name().to_owned(), labels, unique_values)
20823                .map_err(|err| err.to_string());
20824            match expected {
20825                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
20826                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20827                    Err(message) if message.contains(&substr) => Vec::new(),
20828                    Err(message) => vec![make_drift_record(
20829                        ComparisonCategory::Value,
20830                        DriftLevel::Critical,
20831                        "series_unique.error",
20832                        format!(
20833                            "expected series_unique error containing '{substr}', got '{message}'"
20834                        ),
20835                    )],
20836                    Ok(_) => vec![make_drift_record(
20837                        ComparisonCategory::Value,
20838                        DriftLevel::Critical,
20839                        "series_unique.error",
20840                        "expected series_unique to fail but operation succeeded".to_owned(),
20841                    )],
20842                }),
20843                ResolvedExpected::ErrorAny => Ok(match actual {
20844                    Err(_) => Vec::new(),
20845                    Ok(_) => vec![make_drift_record(
20846                        ComparisonCategory::Value,
20847                        DriftLevel::Critical,
20848                        "series_unique.error",
20849                        "expected series_unique to fail but operation succeeded".to_owned(),
20850                    )],
20851                }),
20852                _ => Err("expected_series or expected_error required for series_unique".to_owned()),
20853            }
20854        }
20855        FixtureOperation::SeriesFactorize => {
20856            let left = require_left_series(fixture)?;
20857            let series = build_series(left)?;
20858            let actual = series
20859                .factorize()
20860                .map(|(codes, _uniques)| codes)
20861                .map_err(|err| err.to_string());
20862            match expected {
20863                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
20864                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20865                    Err(message) if message.contains(&substr) => Vec::new(),
20866                    Err(message) => vec![make_drift_record(
20867                        ComparisonCategory::Value,
20868                        DriftLevel::Critical,
20869                        "series_factorize.error",
20870                        format!(
20871                            "expected series_factorize error containing '{substr}', got '{message}'"
20872                        ),
20873                    )],
20874                    Ok(_) => vec![make_drift_record(
20875                        ComparisonCategory::Value,
20876                        DriftLevel::Critical,
20877                        "series_factorize.error",
20878                        "expected series_factorize to fail but operation succeeded".to_owned(),
20879                    )],
20880                }),
20881                ResolvedExpected::ErrorAny => Ok(match actual {
20882                    Err(_) => Vec::new(),
20883                    Ok(_) => vec![make_drift_record(
20884                        ComparisonCategory::Value,
20885                        DriftLevel::Critical,
20886                        "series_factorize.error",
20887                        "expected series_factorize to fail but operation succeeded".to_owned(),
20888                    )],
20889                }),
20890                _ => Err(
20891                    "expected_series or expected_error required for series_factorize".to_owned(),
20892                ),
20893            }
20894        }
20895        FixtureOperation::SeriesWhere => {
20896            let left = require_left_series(fixture)?;
20897            let series = build_series(left)?;
20898            let cond = require_right_series(fixture)?;
20899            let cond_series = build_series(cond)?;
20900            let other = fixture.fill_value.as_ref();
20901            let actual = series
20902                .where_cond(&cond_series, other)
20903                .map_err(|err| err.to_string());
20904            match expected {
20905                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
20906                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20907                    Err(message) if message.contains(&substr) => Vec::new(),
20908                    Err(message) => vec![make_drift_record(
20909                        ComparisonCategory::Value,
20910                        DriftLevel::Critical,
20911                        "series_where.error",
20912                        format!(
20913                            "expected series_where error containing '{substr}', got '{message}'"
20914                        ),
20915                    )],
20916                    Ok(_) => vec![make_drift_record(
20917                        ComparisonCategory::Value,
20918                        DriftLevel::Critical,
20919                        "series_where.error",
20920                        "expected series_where to fail but operation succeeded".to_owned(),
20921                    )],
20922                }),
20923                ResolvedExpected::ErrorAny => Ok(match actual {
20924                    Err(_) => Vec::new(),
20925                    Ok(_) => vec![make_drift_record(
20926                        ComparisonCategory::Value,
20927                        DriftLevel::Critical,
20928                        "series_where.error",
20929                        "expected series_where to fail but operation succeeded".to_owned(),
20930                    )],
20931                }),
20932                _ => Err("expected_series or expected_error required for series_where".to_owned()),
20933            }
20934        }
20935        FixtureOperation::SeriesMask => {
20936            let left = require_left_series(fixture)?;
20937            let series = build_series(left)?;
20938            let cond = require_right_series(fixture)?;
20939            let cond_series = build_series(cond)?;
20940            let other = fixture.fill_value.as_ref();
20941            let actual = series
20942                .mask(&cond_series, other)
20943                .map_err(|err| err.to_string());
20944            match expected {
20945                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
20946                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20947                    Err(message) if message.contains(&substr) => Vec::new(),
20948                    Err(message) => vec![make_drift_record(
20949                        ComparisonCategory::Value,
20950                        DriftLevel::Critical,
20951                        "series_mask.error",
20952                        format!(
20953                            "expected series_mask error containing '{substr}', got '{message}'"
20954                        ),
20955                    )],
20956                    Ok(_) => vec![make_drift_record(
20957                        ComparisonCategory::Value,
20958                        DriftLevel::Critical,
20959                        "series_mask.error",
20960                        "expected series_mask to fail but operation succeeded".to_owned(),
20961                    )],
20962                }),
20963                ResolvedExpected::ErrorAny => Ok(match actual {
20964                    Err(_) => Vec::new(),
20965                    Ok(_) => vec![make_drift_record(
20966                        ComparisonCategory::Value,
20967                        DriftLevel::Critical,
20968                        "series_mask.error",
20969                        "expected series_mask to fail but operation succeeded".to_owned(),
20970                    )],
20971                }),
20972                _ => Err("expected_series or expected_error required for series_mask".to_owned()),
20973            }
20974        }
20975        FixtureOperation::SeriesReplace => {
20976            let left = require_left_series(fixture)?;
20977            let series = build_series(left)?;
20978            let actual =
20979                require_replacement_pairs(fixture, "series_replace").and_then(|replacements| {
20980                    series.replace(&replacements).map_err(|err| err.to_string())
20981                });
20982            match expected {
20983                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
20984                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
20985                    Err(message) if message.contains(&substr) => Vec::new(),
20986                    Err(message) => vec![make_drift_record(
20987                        ComparisonCategory::Value,
20988                        DriftLevel::Critical,
20989                        "series_replace.error",
20990                        format!(
20991                            "expected series_replace error containing '{substr}', got '{message}'"
20992                        ),
20993                    )],
20994                    Ok(_) => vec![make_drift_record(
20995                        ComparisonCategory::Value,
20996                        DriftLevel::Critical,
20997                        "series_replace.error",
20998                        "expected series_replace to fail but operation succeeded".to_owned(),
20999                    )],
21000                }),
21001                ResolvedExpected::ErrorAny => Ok(match actual {
21002                    Err(_) => Vec::new(),
21003                    Ok(_) => vec![make_drift_record(
21004                        ComparisonCategory::Value,
21005                        DriftLevel::Critical,
21006                        "series_replace.error",
21007                        "expected series_replace to fail but operation succeeded".to_owned(),
21008                    )],
21009                }),
21010                _ => {
21011                    Err("expected_series or expected_error required for series_replace".to_owned())
21012                }
21013            }
21014        }
21015        FixtureOperation::SeriesUpdate => {
21016            let left = require_left_series(fixture)?;
21017            let series = build_series(left)?;
21018            let other = require_right_series(fixture)?;
21019            let other_series = build_series(other)?;
21020            let actual = series.update(&other_series).map_err(|err| err.to_string());
21021            match expected {
21022                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
21023                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
21024                    Err(message) if message.contains(&substr) => Vec::new(),
21025                    Err(message) => vec![make_drift_record(
21026                        ComparisonCategory::Value,
21027                        DriftLevel::Critical,
21028                        "series_update.error",
21029                        format!(
21030                            "expected series_update error containing '{substr}', got '{message}'"
21031                        ),
21032                    )],
21033                    Ok(_) => vec![make_drift_record(
21034                        ComparisonCategory::Value,
21035                        DriftLevel::Critical,
21036                        "series_update.error",
21037                        "expected series_update to fail but operation succeeded".to_owned(),
21038                    )],
21039                }),
21040                ResolvedExpected::ErrorAny => Ok(match actual {
21041                    Err(_) => Vec::new(),
21042                    Ok(_) => vec![make_drift_record(
21043                        ComparisonCategory::Value,
21044                        DriftLevel::Critical,
21045                        "series_update.error",
21046                        "expected series_update to fail but operation succeeded".to_owned(),
21047                    )],
21048                }),
21049                _ => Err("expected_series or expected_error required for series_update".to_owned()),
21050            }
21051        }
21052        FixtureOperation::SeriesMap => {
21053            let left = require_left_series(fixture)?;
21054            let series = build_series(left)?;
21055            let to_find = fixture
21056                .replace_to_find
21057                .as_ref()
21058                .ok_or_else(|| "replace_to_find required for series_map".to_owned())?;
21059            let to_value = fixture
21060                .replace_to_value
21061                .as_ref()
21062                .ok_or_else(|| "replace_to_value required for series_map".to_owned())?;
21063            let mapping: Vec<(Scalar, Scalar)> = to_find
21064                .iter()
21065                .zip(to_value.iter())
21066                .map(|(f, v)| (f.clone(), v.clone()))
21067                .collect();
21068            let actual = if fixture.na_action_ignore.unwrap_or(false) {
21069                series
21070                    .map_with_na_action(&mapping, true)
21071                    .map_err(|err| err.to_string())
21072            } else {
21073                series.map(&mapping).map_err(|err| err.to_string())
21074            };
21075            match expected {
21076                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
21077                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
21078                    Err(message) if message.contains(&substr) => Vec::new(),
21079                    Err(message) => vec![make_drift_record(
21080                        ComparisonCategory::Value,
21081                        DriftLevel::Critical,
21082                        "series_map.error",
21083                        format!("expected series_map error containing '{substr}', got '{message}'"),
21084                    )],
21085                    Ok(_) => vec![make_drift_record(
21086                        ComparisonCategory::Value,
21087                        DriftLevel::Critical,
21088                        "series_map.error",
21089                        "expected series_map to fail but operation succeeded".to_owned(),
21090                    )],
21091                }),
21092                ResolvedExpected::ErrorAny => Ok(match actual {
21093                    Err(_) => Vec::new(),
21094                    Ok(_) => vec![make_drift_record(
21095                        ComparisonCategory::Value,
21096                        DriftLevel::Critical,
21097                        "series_map.error",
21098                        "expected series_map to fail but operation succeeded".to_owned(),
21099                    )],
21100                }),
21101                _ => Err("expected_series or expected_error required for series_map".to_owned()),
21102            }
21103        }
21104        FixtureOperation::SeriesCategoricalFromCodes => {
21105            let actual = run_series_categorical_from_codes(fixture);
21106            match expected {
21107                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
21108                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
21109                    Err(message) if message.contains(&substr) => Vec::new(),
21110                    Err(message) => vec![make_drift_record(
21111                        ComparisonCategory::Value,
21112                        DriftLevel::Critical,
21113                        "series_categorical_from_codes.error",
21114                        format!(
21115                            "expected series_categorical_from_codes error containing '{substr}', got '{message}'"
21116                        ),
21117                    )],
21118                    Ok(_) => vec![make_drift_record(
21119                        ComparisonCategory::Value,
21120                        DriftLevel::Critical,
21121                        "series_categorical_from_codes.error",
21122                        "expected series_categorical_from_codes to fail but operation succeeded"
21123                            .to_owned(),
21124                    )],
21125                }),
21126                ResolvedExpected::ErrorAny => Ok(match actual {
21127                    Err(_) => Vec::new(),
21128                    Ok(_) => vec![make_drift_record(
21129                        ComparisonCategory::Value,
21130                        DriftLevel::Critical,
21131                        "series_categorical_from_codes.error",
21132                        "expected series_categorical_from_codes to fail but operation succeeded"
21133                            .to_owned(),
21134                    )],
21135                }),
21136                _ => Err(
21137                    "expected_series or expected_error required for series_categorical_from_codes"
21138                        .to_owned(),
21139                ),
21140            }
21141        }
21142        FixtureOperation::SeriesIsNa => {
21143            let left = require_left_series(fixture)?;
21144            let series = build_series(left)?;
21145            let actual = series.isna().map_err(|err| err.to_string());
21146            match expected {
21147                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
21148                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
21149                    Err(message) if message.contains(&substr) => Vec::new(),
21150                    Err(message) => vec![make_drift_record(
21151                        ComparisonCategory::Value,
21152                        DriftLevel::Critical,
21153                        "series_isna.error",
21154                        format!(
21155                            "expected series_isna error containing '{substr}', got '{message}'"
21156                        ),
21157                    )],
21158                    Ok(_) => vec![make_drift_record(
21159                        ComparisonCategory::Value,
21160                        DriftLevel::Critical,
21161                        "series_isna.error",
21162                        "expected series_isna to fail but operation succeeded".to_owned(),
21163                    )],
21164                }),
21165                ResolvedExpected::ErrorAny => Ok(match actual {
21166                    Err(_) => Vec::new(),
21167                    Ok(_) => vec![make_drift_record(
21168                        ComparisonCategory::Value,
21169                        DriftLevel::Critical,
21170                        "series_isna.error",
21171                        "expected series_isna to fail but operation succeeded".to_owned(),
21172                    )],
21173                }),
21174                _ => Err("expected_series or expected_error required for series_isna".to_owned()),
21175            }
21176        }
21177        FixtureOperation::SeriesNotNa => {
21178            let left = require_left_series(fixture)?;
21179            let series = build_series(left)?;
21180            let actual = series.notna().map_err(|err| err.to_string());
21181            match expected {
21182                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
21183                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
21184                    Err(message) if message.contains(&substr) => Vec::new(),
21185                    Err(message) => vec![make_drift_record(
21186                        ComparisonCategory::Value,
21187                        DriftLevel::Critical,
21188                        "series_notna.error",
21189                        format!(
21190                            "expected series_notna error containing '{substr}', got '{message}'"
21191                        ),
21192                    )],
21193                    Ok(_) => vec![make_drift_record(
21194                        ComparisonCategory::Value,
21195                        DriftLevel::Critical,
21196                        "series_notna.error",
21197                        "expected series_notna to fail but operation succeeded".to_owned(),
21198                    )],
21199                }),
21200                ResolvedExpected::ErrorAny => Ok(match actual {
21201                    Err(_) => Vec::new(),
21202                    Ok(_) => vec![make_drift_record(
21203                        ComparisonCategory::Value,
21204                        DriftLevel::Critical,
21205                        "series_notna.error",
21206                        "expected series_notna to fail but operation succeeded".to_owned(),
21207                    )],
21208                }),
21209                _ => Err("expected_series or expected_error required for series_notna".to_owned()),
21210            }
21211        }
21212        FixtureOperation::SeriesIsNull => {
21213            let left = require_left_series(fixture)?;
21214            let series = build_series(left)?;
21215            let actual = series.isnull().map_err(|err| err.to_string());
21216            match expected {
21217                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
21218                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
21219                    Err(message) if message.contains(&substr) => Vec::new(),
21220                    Err(message) => vec![make_drift_record(
21221                        ComparisonCategory::Value,
21222                        DriftLevel::Critical,
21223                        "series_isnull.error",
21224                        format!(
21225                            "expected series_isnull error containing '{substr}', got '{message}'"
21226                        ),
21227                    )],
21228                    Ok(_) => vec![make_drift_record(
21229                        ComparisonCategory::Value,
21230                        DriftLevel::Critical,
21231                        "series_isnull.error",
21232                        "expected series_isnull to fail but operation succeeded".to_owned(),
21233                    )],
21234                }),
21235                ResolvedExpected::ErrorAny => Ok(match actual {
21236                    Err(_) => Vec::new(),
21237                    Ok(_) => vec![make_drift_record(
21238                        ComparisonCategory::Value,
21239                        DriftLevel::Critical,
21240                        "series_isnull.error",
21241                        "expected series_isnull to fail but operation succeeded".to_owned(),
21242                    )],
21243                }),
21244                _ => Err("expected_series or expected_error required for series_isnull".to_owned()),
21245            }
21246        }
21247        FixtureOperation::SeriesNotNull => {
21248            let left = require_left_series(fixture)?;
21249            let series = build_series(left)?;
21250            let actual = series.notnull().map_err(|err| err.to_string());
21251            match expected {
21252                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
21253                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
21254                    Err(message) if message.contains(&substr) => Vec::new(),
21255                    Err(message) => vec![make_drift_record(
21256                        ComparisonCategory::Value,
21257                        DriftLevel::Critical,
21258                        "series_notnull.error",
21259                        format!(
21260                            "expected series_notnull error containing '{substr}', got '{message}'"
21261                        ),
21262                    )],
21263                    Ok(_) => vec![make_drift_record(
21264                        ComparisonCategory::Value,
21265                        DriftLevel::Critical,
21266                        "series_notnull.error",
21267                        "expected series_notnull to fail but operation succeeded".to_owned(),
21268                    )],
21269                }),
21270                ResolvedExpected::ErrorAny => Ok(match actual {
21271                    Err(_) => Vec::new(),
21272                    Ok(_) => vec![make_drift_record(
21273                        ComparisonCategory::Value,
21274                        DriftLevel::Critical,
21275                        "series_notnull.error",
21276                        "expected series_notnull to fail but operation succeeded".to_owned(),
21277                    )],
21278                }),
21279                _ => {
21280                    Err("expected_series or expected_error required for series_notnull".to_owned())
21281                }
21282            }
21283        }
21284        FixtureOperation::SeriesFillNa => {
21285            let left = require_left_series(fixture)?;
21286            let series = build_series(left)?;
21287            let fill_value = fixture
21288                .fill_value
21289                .as_ref()
21290                .ok_or_else(|| "fill_value is required for series_fillna".to_owned())?;
21291            let actual = series.fillna(fill_value).map_err(|err| err.to_string());
21292            match expected {
21293                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
21294                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
21295                    Err(message) if message.contains(&substr) => Vec::new(),
21296                    Err(message) => vec![make_drift_record(
21297                        ComparisonCategory::Value,
21298                        DriftLevel::Critical,
21299                        "series_fillna.error",
21300                        format!(
21301                            "expected series_fillna error containing '{substr}', got '{message}'"
21302                        ),
21303                    )],
21304                    Ok(_) => vec![make_drift_record(
21305                        ComparisonCategory::Value,
21306                        DriftLevel::Critical,
21307                        "series_fillna.error",
21308                        "expected series_fillna to fail but operation succeeded".to_owned(),
21309                    )],
21310                }),
21311                ResolvedExpected::ErrorAny => Ok(match actual {
21312                    Err(_) => Vec::new(),
21313                    Ok(_) => vec![make_drift_record(
21314                        ComparisonCategory::Value,
21315                        DriftLevel::Critical,
21316                        "series_fillna.error",
21317                        "expected series_fillna to fail but operation succeeded".to_owned(),
21318                    )],
21319                }),
21320                _ => Err("expected_series or expected_error required for series_fillna".to_owned()),
21321            }
21322        }
21323        FixtureOperation::SeriesDropNa => {
21324            let left = require_left_series(fixture)?;
21325            let series = build_series(left)?;
21326            let actual = series.dropna().map_err(|err| err.to_string());
21327            match expected {
21328                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
21329                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
21330                    Err(message) if message.contains(&substr) => Vec::new(),
21331                    Err(message) => vec![make_drift_record(
21332                        ComparisonCategory::Value,
21333                        DriftLevel::Critical,
21334                        "series_dropna.error",
21335                        format!(
21336                            "expected series_dropna error containing '{substr}', got '{message}'"
21337                        ),
21338                    )],
21339                    Ok(_) => vec![make_drift_record(
21340                        ComparisonCategory::Value,
21341                        DriftLevel::Critical,
21342                        "series_dropna.error",
21343                        "expected series_dropna to fail but operation succeeded".to_owned(),
21344                    )],
21345                }),
21346                ResolvedExpected::ErrorAny => Ok(match actual {
21347                    Err(_) => Vec::new(),
21348                    Ok(_) => vec![make_drift_record(
21349                        ComparisonCategory::Value,
21350                        DriftLevel::Critical,
21351                        "series_dropna.error",
21352                        "expected series_dropna to fail but operation succeeded".to_owned(),
21353                    )],
21354                }),
21355                _ => Err("expected_series or expected_error required for series_dropna".to_owned()),
21356            }
21357        }
21358        FixtureOperation::SeriesCount | FixtureOperation::SeriesNunique => {
21359            let left = require_left_series(fixture)?;
21360            let series = build_series(left)?;
21361            let value = match fixture.operation {
21362                FixtureOperation::SeriesCount => series.count(),
21363                FixtureOperation::SeriesNunique => series.nunique(),
21364                _ => unreachable!(),
21365            };
21366            let actual = Scalar::Int64(value as i64);
21367            match expected {
21368                ResolvedExpected::Scalar(scalar) => Ok(diff_scalar(
21369                    &actual,
21370                    &scalar,
21371                    fixture.operation.operation_name(),
21372                )),
21373                _ => Err(format!(
21374                    "expected_scalar required for {}",
21375                    fixture.operation.operation_name()
21376                )),
21377            }
21378        }
21379        FixtureOperation::SeriesFirstValidIndex | FixtureOperation::SeriesLastValidIndex => {
21380            let left = require_left_series(fixture)?;
21381            let series = build_series(left)?;
21382            let label_opt = match fixture.operation {
21383                FixtureOperation::SeriesFirstValidIndex => series.first_valid_index(),
21384                FixtureOperation::SeriesLastValidIndex => series.last_valid_index(),
21385                _ => unreachable!(),
21386            };
21387            let actual = optional_index_label_to_scalar(label_opt);
21388            match expected {
21389                ResolvedExpected::Scalar(scalar) => Ok(diff_scalar(
21390                    &actual,
21391                    &scalar,
21392                    fixture.operation.operation_name(),
21393                )),
21394                _ => Err(format!(
21395                    "expected_scalar required for {}",
21396                    fixture.operation.operation_name()
21397                )),
21398            }
21399        }
21400        FixtureOperation::SeriesIdxmin | FixtureOperation::SeriesIdxmax => {
21401            let actual_result = execute_series_idx_fixture_scalar(fixture);
21402            match (actual_result, expected) {
21403                (Ok(actual), ResolvedExpected::Scalar(scalar)) => Ok(diff_scalar(
21404                    &actual,
21405                    &scalar,
21406                    fixture.operation.operation_name(),
21407                )),
21408                (Err(message), ResolvedExpected::ErrorContains(substr)) => {
21409                    if message.contains(&substr) {
21410                        Ok(Vec::new())
21411                    } else {
21412                        Ok(vec![make_drift_record(
21413                            ComparisonCategory::Value,
21414                            DriftLevel::Critical,
21415                            format!("{}.error", fixture.operation.operation_name()),
21416                            format!(
21417                                "expected {} error containing '{}', got '{}'",
21418                                fixture.operation.operation_name(),
21419                                substr,
21420                                message
21421                            ),
21422                        )])
21423                    }
21424                }
21425                (Ok(_), ResolvedExpected::ErrorContains(substr)) => Ok(vec![make_drift_record(
21426                    ComparisonCategory::Value,
21427                    DriftLevel::Critical,
21428                    format!("{}.error", fixture.operation.operation_name()),
21429                    format!(
21430                        "expected {} error containing '{}', but got Ok",
21431                        fixture.operation.operation_name(),
21432                        substr
21433                    ),
21434                )]),
21435                (Err(message), ResolvedExpected::Scalar(_)) => Ok(vec![make_drift_record(
21436                    ComparisonCategory::Value,
21437                    DriftLevel::Critical,
21438                    format!("{}.error", fixture.operation.operation_name()),
21439                    format!(
21440                        "expected {} scalar, got error: {}",
21441                        fixture.operation.operation_name(),
21442                        message
21443                    ),
21444                )]),
21445                (_, _) => Err(format!(
21446                    "expected_scalar or expected_error_contains required for {}",
21447                    fixture.operation.operation_name()
21448                )),
21449            }
21450        }
21451        FixtureOperation::SeriesArgmin | FixtureOperation::SeriesArgmax => {
21452            let actual_result = execute_series_arg_fixture_scalar(fixture);
21453            match (actual_result, expected) {
21454                (Ok(actual), ResolvedExpected::Scalar(scalar)) => Ok(diff_scalar(
21455                    &actual,
21456                    &scalar,
21457                    fixture.operation.operation_name(),
21458                )),
21459                (Err(message), ResolvedExpected::ErrorContains(substr)) => {
21460                    if message.contains(&substr) {
21461                        Ok(Vec::new())
21462                    } else {
21463                        Ok(vec![make_drift_record(
21464                            ComparisonCategory::Value,
21465                            DriftLevel::Critical,
21466                            format!("{}.error", fixture.operation.operation_name()),
21467                            format!(
21468                                "expected {} error containing '{}', got '{}'",
21469                                fixture.operation.operation_name(),
21470                                substr,
21471                                message
21472                            ),
21473                        )])
21474                    }
21475                }
21476                (Ok(_), ResolvedExpected::ErrorContains(substr)) => Ok(vec![make_drift_record(
21477                    ComparisonCategory::Value,
21478                    DriftLevel::Critical,
21479                    format!("{}.error", fixture.operation.operation_name()),
21480                    format!(
21481                        "expected {} error containing '{}', but got Ok",
21482                        fixture.operation.operation_name(),
21483                        substr
21484                    ),
21485                )]),
21486                (Err(message), ResolvedExpected::Scalar(_)) => Ok(vec![make_drift_record(
21487                    ComparisonCategory::Value,
21488                    DriftLevel::Critical,
21489                    format!("{}.error", fixture.operation.operation_name()),
21490                    format!(
21491                        "expected {} scalar, got error: {}",
21492                        fixture.operation.operation_name(),
21493                        message
21494                    ),
21495                )]),
21496                (_, _) => Err(format!(
21497                    "expected_scalar or expected_error_contains required for {}",
21498                    fixture.operation.operation_name()
21499                )),
21500            }
21501        }
21502        FixtureOperation::SeriesSearchsorted => {
21503            let actual_result = execute_series_searchsorted_fixture(fixture);
21504            match (actual_result, expected) {
21505                (Ok(actual), ResolvedExpected::Scalar(scalar)) => Ok(diff_scalar(
21506                    &actual,
21507                    &scalar,
21508                    fixture.operation.operation_name(),
21509                )),
21510                (Err(message), ResolvedExpected::ErrorContains(substr)) => {
21511                    if message.contains(&substr) {
21512                        Ok(Vec::new())
21513                    } else {
21514                        Ok(vec![make_drift_record(
21515                            ComparisonCategory::Value,
21516                            DriftLevel::Critical,
21517                            format!("{}.error", fixture.operation.operation_name()),
21518                            format!(
21519                                "expected {} error containing '{}', got '{}'",
21520                                fixture.operation.operation_name(),
21521                                substr,
21522                                message
21523                            ),
21524                        )])
21525                    }
21526                }
21527                (Ok(_), ResolvedExpected::ErrorContains(substr)) => Ok(vec![make_drift_record(
21528                    ComparisonCategory::Value,
21529                    DriftLevel::Critical,
21530                    format!("{}.error", fixture.operation.operation_name()),
21531                    format!(
21532                        "expected {} error containing '{}', but got Ok",
21533                        fixture.operation.operation_name(),
21534                        substr
21535                    ),
21536                )]),
21537                (Err(message), ResolvedExpected::Scalar(_)) => Ok(vec![make_drift_record(
21538                    ComparisonCategory::Value,
21539                    DriftLevel::Critical,
21540                    format!("{}.error", fixture.operation.operation_name()),
21541                    format!(
21542                        "expected {} scalar, got error: {}",
21543                        fixture.operation.operation_name(),
21544                        message
21545                    ),
21546                )]),
21547                (_, _) => Err(format!(
21548                    "expected_scalar or expected_error_contains required for {}",
21549                    fixture.operation.operation_name()
21550                )),
21551            }
21552        }
21553        FixtureOperation::SeriesDot => {
21554            let actual_result = execute_series_dot_fixture(fixture);
21555            match (actual_result, expected) {
21556                (Ok(actual), ResolvedExpected::Scalar(scalar)) => Ok(diff_scalar(
21557                    &actual,
21558                    &scalar,
21559                    fixture.operation.operation_name(),
21560                )),
21561                (Err(message), ResolvedExpected::ErrorContains(substr)) => {
21562                    if message.contains(&substr) {
21563                        Ok(Vec::new())
21564                    } else {
21565                        Ok(vec![make_drift_record(
21566                            ComparisonCategory::Value,
21567                            DriftLevel::Critical,
21568                            format!("{}.error", fixture.operation.operation_name()),
21569                            format!(
21570                                "expected {} error containing '{}', got '{}'",
21571                                fixture.operation.operation_name(),
21572                                substr,
21573                                message
21574                            ),
21575                        )])
21576                    }
21577                }
21578                (Ok(_), ResolvedExpected::ErrorContains(substr)) => Ok(vec![make_drift_record(
21579                    ComparisonCategory::Value,
21580                    DriftLevel::Critical,
21581                    format!("{}.error", fixture.operation.operation_name()),
21582                    format!(
21583                        "expected {} error containing '{}', but got Ok",
21584                        fixture.operation.operation_name(),
21585                        substr
21586                    ),
21587                )]),
21588                (Err(message), ResolvedExpected::Scalar(_)) => Ok(vec![make_drift_record(
21589                    ComparisonCategory::Value,
21590                    DriftLevel::Critical,
21591                    format!("{}.error", fixture.operation.operation_name()),
21592                    format!(
21593                        "expected {} scalar, got error: {}",
21594                        fixture.operation.operation_name(),
21595                        message
21596                    ),
21597                )]),
21598                (_, _) => Err(format!(
21599                    "expected_scalar or expected_error_contains required for {}",
21600                    fixture.operation.operation_name()
21601                )),
21602            }
21603        }
21604        FixtureOperation::DataFrameCount => {
21605            let frame = build_dataframe(require_frame(fixture)?)
21606                .map_err(|err| format!("frame build failed: {err}"))?;
21607            let actual = frame.count().map_err(|err| err.to_string());
21608            match expected {
21609                ResolvedExpected::Series(series) => Ok(diff_series(&actual?, &series)),
21610                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
21611                    Err(message) if message.contains(&substr) => Vec::new(),
21612                    Err(message) => vec![make_drift_record(
21613                        ComparisonCategory::Value,
21614                        DriftLevel::Critical,
21615                        "dataframe_count.error",
21616                        format!(
21617                            "expected dataframe_count error containing '{substr}', got '{message}'"
21618                        ),
21619                    )],
21620                    Ok(_) => vec![make_drift_record(
21621                        ComparisonCategory::Value,
21622                        DriftLevel::Critical,
21623                        "dataframe_count.error",
21624                        "expected dataframe_count to fail but operation succeeded".to_owned(),
21625                    )],
21626                }),
21627                ResolvedExpected::ErrorAny => Ok(match actual {
21628                    Err(_) => Vec::new(),
21629                    Ok(_) => vec![make_drift_record(
21630                        ComparisonCategory::Value,
21631                        DriftLevel::Critical,
21632                        "dataframe_count.error",
21633                        "expected dataframe_count to fail but operation succeeded".to_owned(),
21634                    )],
21635                }),
21636                _ => {
21637                    Err("expected_series or expected_error required for dataframe_count".to_owned())
21638                }
21639            }
21640        }
21641        FixtureOperation::DataFrameIdxmin
21642        | FixtureOperation::DataFrameIdxmax
21643        | FixtureOperation::DataFrameSem
21644        | FixtureOperation::DataFrameApplySemAxis0
21645        | FixtureOperation::DataFrameSkew
21646        | FixtureOperation::DataFrameKurtosis
21647        | FixtureOperation::DataFrameProd
21648        | FixtureOperation::DataFrameApplyProdAxis1
21649        | FixtureOperation::DataFrameApplyProductAxis1
21650        | FixtureOperation::DataFrameSum
21651        | FixtureOperation::DataFrameMean
21652        | FixtureOperation::DataFrameStd
21653        | FixtureOperation::DataFrameVar
21654        | FixtureOperation::DataFrameMin
21655        | FixtureOperation::DataFrameMax
21656        | FixtureOperation::DataFrameMedian
21657        | FixtureOperation::DataFrameAny
21658        | FixtureOperation::DataFrameAll
21659        | FixtureOperation::DataFrameNunique
21660        | FixtureOperation::DataFrameApplyNuniqueAxis0
21661        | FixtureOperation::DataFrameQuantile
21662        | FixtureOperation::DataFrameValueCounts
21663        | FixtureOperation::DataFrameMemoryUsage => {
21664            let frame = build_dataframe(require_frame(fixture)?)
21665                .map_err(|err| format!("frame build failed: {err}"))?;
21666            let op_name = fixture.operation.operation_name();
21667            let actual = match fixture.operation {
21668                FixtureOperation::DataFrameIdxmin => frame.idxmin().map_err(|err| err.to_string()),
21669                FixtureOperation::DataFrameIdxmax => frame.idxmax().map_err(|err| err.to_string()),
21670                FixtureOperation::DataFrameSem => match fixture.sem_numeric_only {
21671                    Some(numeric_only) => frame.sem_agg_with_numeric_only(numeric_only),
21672                    None => frame.sem_agg(),
21673                }
21674                .map_err(|err| err.to_string()),
21675                FixtureOperation::DataFrameApplySemAxis0 => {
21676                    execute_dataframe_apply_alias_fixture_operation(fixture)
21677                }
21678                FixtureOperation::DataFrameSkew => match fixture.skew_numeric_only {
21679                    Some(numeric_only) => frame.skew_agg_with_numeric_only(numeric_only),
21680                    None => frame.skew_agg(),
21681                }
21682                .map_err(|err| err.to_string()),
21683                FixtureOperation::DataFrameKurtosis => match fixture.kurtosis_numeric_only {
21684                    Some(numeric_only) => frame.kurtosis_agg_with_numeric_only(numeric_only),
21685                    None => frame.kurtosis_agg(),
21686                }
21687                .map_err(|err| err.to_string()),
21688                FixtureOperation::DataFrameProd => match fixture.prod_numeric_only {
21689                    Some(numeric_only) => frame.prod_with_numeric_only(numeric_only),
21690                    None => frame.prod_agg(),
21691                }
21692                .map_err(|err| err.to_string()),
21693                FixtureOperation::DataFrameApplyProdAxis1
21694                | FixtureOperation::DataFrameApplyProductAxis1 => {
21695                    execute_dataframe_apply_alias_fixture_operation(fixture)
21696                }
21697                FixtureOperation::DataFrameSum => match fixture.sum_numeric_only {
21698                    Some(numeric_only) => frame.sum_with_numeric_only(numeric_only),
21699                    None => frame.sum(),
21700                }
21701                .map_err(|err| err.to_string()),
21702                FixtureOperation::DataFrameMean => match fixture.mean_numeric_only {
21703                    Some(numeric_only) => frame.mean_with_numeric_only(numeric_only),
21704                    None => frame.mean(),
21705                }
21706                .map_err(|err| err.to_string()),
21707                FixtureOperation::DataFrameStd => match fixture.std_numeric_only {
21708                    Some(numeric_only) => frame.std_agg_with_numeric_only(numeric_only),
21709                    None => frame.std_agg(),
21710                }
21711                .map_err(|err| err.to_string()),
21712                FixtureOperation::DataFrameVar => match fixture.var_numeric_only {
21713                    Some(numeric_only) => frame.var_agg_with_numeric_only(numeric_only),
21714                    None => frame.var_agg(),
21715                }
21716                .map_err(|err| err.to_string()),
21717                FixtureOperation::DataFrameMin => match fixture.min_numeric_only {
21718                    Some(numeric_only) => frame.min_agg_with_numeric_only(numeric_only),
21719                    None => frame.min_agg(),
21720                }
21721                .map_err(|err| err.to_string()),
21722                FixtureOperation::DataFrameMax => match fixture.max_numeric_only {
21723                    Some(numeric_only) => frame.max_agg_with_numeric_only(numeric_only),
21724                    None => frame.max_agg(),
21725                }
21726                .map_err(|err| err.to_string()),
21727                FixtureOperation::DataFrameMedian => match fixture.median_numeric_only {
21728                    Some(numeric_only) => frame.median_with_numeric_only(numeric_only),
21729                    None => frame.median_agg(),
21730                }
21731                .map_err(|err| err.to_string()),
21732                FixtureOperation::DataFrameAny => frame.any().map_err(|err| err.to_string()),
21733                FixtureOperation::DataFrameAll => frame.all().map_err(|err| err.to_string()),
21734                FixtureOperation::DataFrameNunique => {
21735                    frame.nunique().map_err(|err| err.to_string())
21736                }
21737                FixtureOperation::DataFrameApplyNuniqueAxis0 => {
21738                    execute_dataframe_apply_alias_fixture_operation(fixture)
21739                }
21740                FixtureOperation::DataFrameQuantile => {
21741                    frame.quantile(0.5).map_err(|err| err.to_string())
21742                }
21743                FixtureOperation::DataFrameValueCounts => {
21744                    frame.value_counts().map_err(|err| err.to_string())
21745                }
21746                FixtureOperation::DataFrameMemoryUsage => frame
21747                    .memory_usage_with_options(
21748                        resolve_memory_usage_index(fixture),
21749                        resolve_memory_usage_deep(fixture),
21750                    )
21751                    .map_err(|err| err.to_string()),
21752                _ => unreachable!(),
21753            };
21754            match expected {
21755                ResolvedExpected::Series(series) => Ok(diff_series(&actual?, &series)),
21756                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
21757                    Err(message) if message.contains(&substr) => Vec::new(),
21758                    Err(message) => vec![make_drift_record(
21759                        ComparisonCategory::Value,
21760                        DriftLevel::Critical,
21761                        format!("{op_name}.error"),
21762                        format!("expected {op_name} error containing '{substr}', got '{message}'"),
21763                    )],
21764                    Ok(_) => vec![make_drift_record(
21765                        ComparisonCategory::Value,
21766                        DriftLevel::Critical,
21767                        format!("{op_name}.error"),
21768                        format!("expected {op_name} to fail but operation succeeded"),
21769                    )],
21770                }),
21771                ResolvedExpected::ErrorAny => Ok(match actual {
21772                    Err(_) => Vec::new(),
21773                    Ok(_) => vec![make_drift_record(
21774                        ComparisonCategory::Value,
21775                        DriftLevel::Critical,
21776                        format!("{op_name}.error"),
21777                        format!("expected {op_name} to fail but operation succeeded"),
21778                    )],
21779                }),
21780                _ => Err(format!(
21781                    "expected_series or expected_error required for {op_name}"
21782                )),
21783            }
21784        }
21785        FixtureOperation::DataFrameMode => {
21786            let frame = build_dataframe(require_frame(fixture)?)
21787                .map_err(|err| format!("frame build failed: {err}"))?;
21788            let actual = frame.mode().map_err(|err| err.to_string());
21789            match expected {
21790                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
21791                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
21792                    Err(message) if message.contains(&substr) => Vec::new(),
21793                    Err(message) => vec![make_drift_record(
21794                        ComparisonCategory::Value,
21795                        DriftLevel::Critical,
21796                        "dataframe_mode.error",
21797                        format!(
21798                            "expected dataframe_mode error containing '{substr}', got '{message}'"
21799                        ),
21800                    )],
21801                    Ok(_) => vec![make_drift_record(
21802                        ComparisonCategory::Value,
21803                        DriftLevel::Critical,
21804                        "dataframe_mode.error",
21805                        "expected dataframe_mode to fail but operation succeeded".to_owned(),
21806                    )],
21807                }),
21808                ResolvedExpected::ErrorAny => Ok(match actual {
21809                    Err(_) => Vec::new(),
21810                    Ok(_) => vec![make_drift_record(
21811                        ComparisonCategory::Value,
21812                        DriftLevel::Critical,
21813                        "dataframe_mode.error",
21814                        "expected dataframe_mode to fail but operation succeeded".to_owned(),
21815                    )],
21816                }),
21817                _ => Err("expected_frame or expected_error required for dataframe_mode".to_owned()),
21818            }
21819        }
21820        FixtureOperation::DataFrameRank => {
21821            let frame = build_dataframe(require_frame(fixture)?)
21822                .map_err(|err| format!("frame build failed: {err}"))?;
21823            let method = fixture.rank_method.as_deref().unwrap_or("average");
21824            let na_option = fixture.rank_na_option.as_deref().unwrap_or("keep");
21825            let ascending = resolve_sort_ascending(fixture);
21826            let axis = resolve_rank_axis(fixture)?;
21827            let pct = resolve_rank_pct(fixture);
21828            let actual = if axis == 1 {
21829                frame.rank_axis1_with_pct(method, ascending, na_option, pct)
21830            } else {
21831                frame.rank_with_pct(method, ascending, na_option, pct)
21832            }
21833            .map_err(|err| err.to_string());
21834            match expected {
21835                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
21836                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
21837                    Err(message) if message.contains(&substr) => Vec::new(),
21838                    Err(message) => vec![make_drift_record(
21839                        ComparisonCategory::Value,
21840                        DriftLevel::Critical,
21841                        "dataframe_rank.error",
21842                        format!(
21843                            "expected dataframe_rank error containing '{substr}', got '{message}'"
21844                        ),
21845                    )],
21846                    Ok(_) => vec![make_drift_record(
21847                        ComparisonCategory::Value,
21848                        DriftLevel::Critical,
21849                        "dataframe_rank.error",
21850                        "expected dataframe_rank to fail but operation succeeded".to_owned(),
21851                    )],
21852                }),
21853                ResolvedExpected::ErrorAny => Ok(match actual {
21854                    Err(_) => Vec::new(),
21855                    Ok(_) => vec![make_drift_record(
21856                        ComparisonCategory::Value,
21857                        DriftLevel::Critical,
21858                        "dataframe_rank.error",
21859                        "expected dataframe_rank to fail but operation succeeded".to_owned(),
21860                    )],
21861                }),
21862                _ => Err("expected_frame or expected_error required for dataframe_rank".to_owned()),
21863            }
21864        }
21865        FixtureOperation::DataFrameDuplicated => {
21866            let frame = build_dataframe(require_frame(fixture)?)
21867                .map_err(|err| format!("frame build failed: {err}"))?;
21868            let subset = resolve_duplicate_subset(fixture)?;
21869            let keep = resolve_duplicate_keep(fixture)?;
21870            let actual = frame
21871                .duplicated(subset.as_deref(), keep)
21872                .map_err(|err| err.to_string());
21873            match expected {
21874                ResolvedExpected::Series(series) => Ok(diff_series(&actual?, &series)),
21875                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
21876                    Err(message) if message.contains(&substr) => Vec::new(),
21877                    Err(message) => vec![make_drift_record(
21878                        ComparisonCategory::Value,
21879                        DriftLevel::Critical,
21880                        "dataframe_duplicated.error",
21881                        format!(
21882                            "expected dataframe_duplicated error containing '{substr}', got '{message}'"
21883                        ),
21884                    )],
21885                    Ok(_) => vec![make_drift_record(
21886                        ComparisonCategory::Value,
21887                        DriftLevel::Critical,
21888                        "dataframe_duplicated.error",
21889                        "expected dataframe_duplicated to fail but operation succeeded".to_owned(),
21890                    )],
21891                }),
21892                ResolvedExpected::ErrorAny => Ok(match actual {
21893                    Err(_) => Vec::new(),
21894                    Ok(_) => vec![make_drift_record(
21895                        ComparisonCategory::Value,
21896                        DriftLevel::Critical,
21897                        "dataframe_duplicated.error",
21898                        "expected dataframe_duplicated to fail but operation succeeded".to_owned(),
21899                    )],
21900                }),
21901                _ => Err(
21902                    "expected_series or expected_error required for dataframe_duplicated"
21903                        .to_owned(),
21904                ),
21905            }
21906        }
21907        FixtureOperation::SeriesAny => {
21908            let left = require_left_series(fixture)?;
21909            let series = build_series(left)?;
21910            let actual = series.any().map_err(|err| err.to_string());
21911            match expected {
21912                ResolvedExpected::Bool(value) => Ok(diff_bool(actual?, value, "series_any")),
21913                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
21914                    Err(message) if message.contains(&substr) => Vec::new(),
21915                    Err(message) => vec![make_drift_record(
21916                        ComparisonCategory::Value,
21917                        DriftLevel::Critical,
21918                        "series_any.error",
21919                        format!("expected series_any error containing '{substr}', got '{message}'"),
21920                    )],
21921                    Ok(_) => vec![make_drift_record(
21922                        ComparisonCategory::Value,
21923                        DriftLevel::Critical,
21924                        "series_any.error",
21925                        "expected series_any to fail but operation succeeded".to_owned(),
21926                    )],
21927                }),
21928                ResolvedExpected::ErrorAny => Ok(match actual {
21929                    Err(_) => Vec::new(),
21930                    Ok(_) => vec![make_drift_record(
21931                        ComparisonCategory::Value,
21932                        DriftLevel::Critical,
21933                        "series_any.error",
21934                        "expected series_any to fail but operation succeeded".to_owned(),
21935                    )],
21936                }),
21937                _ => Err("expected_bool or expected_error required for series_any".to_owned()),
21938            }
21939        }
21940        FixtureOperation::SeriesAll => {
21941            let left = require_left_series(fixture)?;
21942            let series = build_series(left)?;
21943            let actual = series.all().map_err(|err| err.to_string());
21944            match expected {
21945                ResolvedExpected::Bool(value) => Ok(diff_bool(actual?, value, "series_all")),
21946                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
21947                    Err(message) if message.contains(&substr) => Vec::new(),
21948                    Err(message) => vec![make_drift_record(
21949                        ComparisonCategory::Value,
21950                        DriftLevel::Critical,
21951                        "series_all.error",
21952                        format!("expected series_all error containing '{substr}', got '{message}'"),
21953                    )],
21954                    Ok(_) => vec![make_drift_record(
21955                        ComparisonCategory::Value,
21956                        DriftLevel::Critical,
21957                        "series_all.error",
21958                        "expected series_all to fail but operation succeeded".to_owned(),
21959                    )],
21960                }),
21961                ResolvedExpected::ErrorAny => Ok(match actual {
21962                    Err(_) => Vec::new(),
21963                    Ok(_) => vec![make_drift_record(
21964                        ComparisonCategory::Value,
21965                        DriftLevel::Critical,
21966                        "series_all.error",
21967                        "expected series_all to fail but operation succeeded".to_owned(),
21968                    )],
21969                }),
21970                _ => Err("expected_bool or expected_error required for series_all".to_owned()),
21971            }
21972        }
21973        FixtureOperation::SeriesBool => {
21974            let actual = execute_series_bool_fixture_operation(fixture);
21975            match expected {
21976                ResolvedExpected::Bool(value) => Ok(diff_bool(actual?, value, "series_bool")),
21977                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
21978                    Err(message) if message.contains(&substr) => Vec::new(),
21979                    Err(message) => vec![make_drift_record(
21980                        ComparisonCategory::Value,
21981                        DriftLevel::Critical,
21982                        "series_bool.error",
21983                        format!(
21984                            "expected series_bool error containing '{substr}', got '{message}'"
21985                        ),
21986                    )],
21987                    Ok(_) => vec![make_drift_record(
21988                        ComparisonCategory::Value,
21989                        DriftLevel::Critical,
21990                        "series_bool.error",
21991                        "expected series_bool to fail but operation succeeded".to_owned(),
21992                    )],
21993                }),
21994                ResolvedExpected::ErrorAny => Ok(match actual {
21995                    Err(_) => Vec::new(),
21996                    Ok(_) => vec![make_drift_record(
21997                        ComparisonCategory::Value,
21998                        DriftLevel::Critical,
21999                        "series_bool.error",
22000                        "expected series_bool to fail but operation succeeded".to_owned(),
22001                    )],
22002                }),
22003                _ => Err("expected_bool or expected_error required for series_bool".to_owned()),
22004            }
22005        }
22006        FixtureOperation::SeriesRepeat => {
22007            let actual = execute_series_repeat_fixture_operation(fixture);
22008            match expected {
22009                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
22010                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22011                    Err(message) if message.contains(&substr) => Vec::new(),
22012                    Err(message) => vec![make_drift_record(
22013                        ComparisonCategory::Value,
22014                        DriftLevel::Critical,
22015                        "series_repeat.error",
22016                        format!(
22017                            "expected series_repeat error containing '{substr}', got '{message}'"
22018                        ),
22019                    )],
22020                    Ok(_) => vec![make_drift_record(
22021                        ComparisonCategory::Value,
22022                        DriftLevel::Critical,
22023                        "series_repeat.error",
22024                        "expected series_repeat to fail but operation succeeded".to_owned(),
22025                    )],
22026                }),
22027                ResolvedExpected::ErrorAny => Ok(match actual {
22028                    Err(_) => Vec::new(),
22029                    Ok(_) => vec![make_drift_record(
22030                        ComparisonCategory::Value,
22031                        DriftLevel::Critical,
22032                        "series_repeat.error",
22033                        "expected series_repeat to fail but operation succeeded".to_owned(),
22034                    )],
22035                }),
22036                _ => Err("expected_series or expected_error required for series_repeat".to_owned()),
22037            }
22038        }
22039        FixtureOperation::SeriesCombineFirst => {
22040            let actual = execute_series_combine_first_fixture_operation(fixture);
22041            match expected {
22042                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
22043                _ => Err("expected_series required for series_combine_first".to_owned()),
22044            }
22045        }
22046        FixtureOperation::SeriesAsof => {
22047            let actual = execute_series_asof_fixture_operation(fixture);
22048            match expected {
22049                ResolvedExpected::Scalar(scalar) => {
22050                    Ok(diff_scalar(&actual?, &scalar, "series_asof"))
22051                }
22052                _ => Err("expected_scalar required for series_asof".to_owned()),
22053            }
22054        }
22055        FixtureOperation::SeriesAutocorr => {
22056            let actual = execute_series_autocorr_fixture_operation(fixture);
22057            match expected {
22058                ResolvedExpected::Scalar(scalar) => {
22059                    Ok(diff_scalar(&actual?, &scalar, "series_autocorr"))
22060                }
22061                _ => Err("expected_scalar required for series_autocorr".to_owned()),
22062            }
22063        }
22064        FixtureOperation::SeriesToNumeric
22065        | FixtureOperation::SeriesConvertDtypes
22066        | FixtureOperation::SeriesAstype
22067        | FixtureOperation::SeriesClip
22068        | FixtureOperation::SeriesAbs
22069        | FixtureOperation::SeriesRound
22070        | FixtureOperation::SeriesCumsum
22071        | FixtureOperation::SeriesCumprod
22072        | FixtureOperation::SeriesCummax
22073        | FixtureOperation::SeriesCummin
22074        | FixtureOperation::SeriesNlargest
22075        | FixtureOperation::SeriesNsmallest
22076        | FixtureOperation::SeriesBetween
22077        | FixtureOperation::SeriesCut
22078        | FixtureOperation::SeriesQcut
22079        | FixtureOperation::SeriesStrLower
22080        | FixtureOperation::SeriesStrUpper
22081        | FixtureOperation::SeriesStrCapitalize
22082        | FixtureOperation::SeriesStrStrip
22083        | FixtureOperation::SeriesStrLen
22084        | FixtureOperation::SeriesStrContains
22085        | FixtureOperation::SeriesStrStartswith
22086        | FixtureOperation::SeriesStrEndswith
22087        | FixtureOperation::SeriesStrReplace
22088        | FixtureOperation::SeriesStrLstrip
22089        | FixtureOperation::SeriesStrRstrip
22090        | FixtureOperation::SeriesStrTitle
22091        | FixtureOperation::SeriesStrSwapcase
22092        | FixtureOperation::SeriesStrZfill
22093        | FixtureOperation::SeriesStrCenter
22094        | FixtureOperation::SeriesStrLjust
22095        | FixtureOperation::SeriesStrRjust
22096        | FixtureOperation::SeriesStrPad
22097        | FixtureOperation::SeriesStrIsdigit
22098        | FixtureOperation::SeriesStrIsalpha
22099        | FixtureOperation::SeriesStrIsalnum
22100        | FixtureOperation::SeriesStrIsspace
22101        | FixtureOperation::SeriesStrIslower
22102        | FixtureOperation::SeriesStrIsupper
22103        | FixtureOperation::SeriesStrIsnumeric
22104        | FixtureOperation::SeriesStrFind
22105        | FixtureOperation::SeriesStrRfind
22106        | FixtureOperation::SeriesStrSlice
22107        | FixtureOperation::SeriesStrGet
22108        | FixtureOperation::SeriesStrRepeat
22109        | FixtureOperation::SeriesStrCount
22110        | FixtureOperation::SeriesStrWrap
22111        | FixtureOperation::SeriesStrNormalize
22112        | FixtureOperation::SeriesStrFullmatch
22113        | FixtureOperation::SeriesStrMatch
22114        | FixtureOperation::SeriesStrRemoveprefix
22115        | FixtureOperation::SeriesStrRemovesuffix
22116        | FixtureOperation::SeriesStrSplitGet
22117        | FixtureOperation::SeriesStrJoin
22118        | FixtureOperation::SeriesStrIsdecimal
22119        | FixtureOperation::SeriesStrIstitle
22120        | FixtureOperation::SeriesStrCasefold
22121        | FixtureOperation::SeriesStrEncode
22122        | FixtureOperation::SeriesStrDecode
22123        | FixtureOperation::SeriesStrTranslate
22124        | FixtureOperation::SeriesStrExpandtabs
22125        | FixtureOperation::SeriesStrIndexOf
22126        | FixtureOperation::SeriesStrRindexOf
22127        | FixtureOperation::SeriesStrSplitCount
22128        | FixtureOperation::SeriesStrRsplitGet
22129        | FixtureOperation::SeriesStrSplitRegexGet
22130        | FixtureOperation::SeriesStrCountMatches
22131        | FixtureOperation::SeriesStrCountLiteral
22132        | FixtureOperation::SeriesStrFindall
22133        | FixtureOperation::SeriesStrContainsAny
22134        | FixtureOperation::SeriesStrStartswithAny
22135        | FixtureOperation::SeriesStrEndswithAny
22136        | FixtureOperation::SeriesDtYear
22137        | FixtureOperation::SeriesDtMonth
22138        | FixtureOperation::SeriesDtDay
22139        | FixtureOperation::SeriesDtHour
22140        | FixtureOperation::SeriesDtMinute
22141        | FixtureOperation::SeriesDtSecond
22142        | FixtureOperation::SeriesDtMicrosecond
22143        | FixtureOperation::SeriesDtNanosecond
22144        | FixtureOperation::SeriesDtDayofweek
22145        | FixtureOperation::SeriesDtQuarter
22146        | FixtureOperation::SeriesDtDayofyear
22147        | FixtureOperation::SeriesDtWeekofyear
22148        | FixtureOperation::SeriesDtIsMonthStart
22149        | FixtureOperation::SeriesDtIsMonthEnd
22150        | FixtureOperation::SeriesDtIsYearStart
22151        | FixtureOperation::SeriesDtIsYearEnd
22152        | FixtureOperation::SeriesDtDate
22153        | FixtureOperation::SeriesDtDaysInMonth
22154        | FixtureOperation::SeriesDtIsLeapYear
22155        | FixtureOperation::SeriesDtIsQuarterStart
22156        | FixtureOperation::SeriesDtIsQuarterEnd
22157        | FixtureOperation::SeriesDtStrftime
22158        | FixtureOperation::SeriesDtTzConvert
22159        | FixtureOperation::SeriesDtTzLocalize
22160        | FixtureOperation::SeriesDtTimetz
22161        | FixtureOperation::SeriesDtToPeriod
22162        | FixtureOperation::SeriesDtFloor
22163        | FixtureOperation::SeriesDtCeil
22164        | FixtureOperation::SeriesDtRound
22165        | FixtureOperation::SeriesDtMonthName
22166        | FixtureOperation::SeriesDtDayName
22167        | FixtureOperation::SeriesDtTotalSeconds
22168        | FixtureOperation::SeriesDtDays
22169        | FixtureOperation::SeriesDtSeconds
22170        | FixtureOperation::SeriesDtMicroseconds
22171        | FixtureOperation::SeriesDtNanoseconds
22172        | FixtureOperation::SeriesDtToTimestamp
22173        | FixtureOperation::SeriesDtToPytimedelta
22174        | FixtureOperation::SeriesDtToPydatetime => {
22175            let actual = execute_series_module_utility_fixture_operation(fixture);
22176            let op_name = fixture.operation.operation_name();
22177            match expected {
22178                ResolvedExpected::Series(series) => Ok(diff_series(&actual?, &series)),
22179                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22180                    Err(message) if message.contains(&substr) => Vec::new(),
22181                    Err(message) => vec![make_drift_record(
22182                        ComparisonCategory::Value,
22183                        DriftLevel::Critical,
22184                        format!("{op_name}.error"),
22185                        format!("expected {op_name} error containing '{substr}', got '{message}'"),
22186                    )],
22187                    Ok(_) => vec![make_drift_record(
22188                        ComparisonCategory::Value,
22189                        DriftLevel::Critical,
22190                        format!("{op_name}.error"),
22191                        format!("expected {op_name} to fail but operation succeeded"),
22192                    )],
22193                }),
22194                ResolvedExpected::ErrorAny => Ok(match actual {
22195                    Err(_) => Vec::new(),
22196                    Ok(_) => vec![make_drift_record(
22197                        ComparisonCategory::Value,
22198                        DriftLevel::Critical,
22199                        format!("{op_name}.error"),
22200                        format!("expected {op_name} to fail but operation succeeded"),
22201                    )],
22202                }),
22203                _ => Err(format!(
22204                    "expected_series or expected_error required for {op_name}"
22205                )),
22206            }
22207        }
22208        FixtureOperation::SeriesXs => {
22209            let actual = execute_series_xs_fixture_operation(fixture);
22210            match expected {
22211                ResolvedExpected::Series(series) => Ok(diff_series(&actual?, &series)),
22212                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22213                    Err(message) if message.contains(&substr) => Vec::new(),
22214                    Err(message) => vec![make_drift_record(
22215                        ComparisonCategory::Value,
22216                        DriftLevel::Critical,
22217                        "series_xs.error",
22218                        format!("expected series_xs error containing '{substr}', got '{message}'"),
22219                    )],
22220                    Ok(_) => vec![make_drift_record(
22221                        ComparisonCategory::Value,
22222                        DriftLevel::Critical,
22223                        "series_xs.error",
22224                        "expected series_xs to fail but operation succeeded".to_owned(),
22225                    )],
22226                }),
22227                ResolvedExpected::ErrorAny => Ok(match actual {
22228                    Err(_) => Vec::new(),
22229                    Ok(_) => vec![make_drift_record(
22230                        ComparisonCategory::Value,
22231                        DriftLevel::Critical,
22232                        "series_xs.error",
22233                        "expected series_xs to fail but operation succeeded".to_owned(),
22234                    )],
22235                }),
22236                _ => Err("expected_series or expected_error required for series_xs".to_owned()),
22237            }
22238        }
22239        FixtureOperation::SeriesLoc => {
22240            let left = require_left_series(fixture)?;
22241            let labels = require_loc_labels(fixture)?;
22242            let series = build_series(left)?;
22243            let actual = series.loc(labels).map_err(|err| err.to_string());
22244            match expected {
22245                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
22246                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22247                    Err(message) if message.contains(&substr) => Vec::new(),
22248                    Err(message) => vec![make_drift_record(
22249                        ComparisonCategory::Value,
22250                        DriftLevel::Critical,
22251                        "series_loc.error",
22252                        format!("expected series_loc error containing '{substr}', got '{message}'"),
22253                    )],
22254                    Ok(_) => vec![make_drift_record(
22255                        ComparisonCategory::Value,
22256                        DriftLevel::Critical,
22257                        "series_loc.error",
22258                        "expected series_loc to fail but operation succeeded".to_owned(),
22259                    )],
22260                }),
22261                ResolvedExpected::ErrorAny => Ok(match actual {
22262                    Err(_) => Vec::new(),
22263                    Ok(_) => vec![make_drift_record(
22264                        ComparisonCategory::Value,
22265                        DriftLevel::Critical,
22266                        "series_loc.error",
22267                        "expected series_loc to fail but operation succeeded".to_owned(),
22268                    )],
22269                }),
22270                _ => Err("expected_series or expected_error required for series_loc".to_owned()),
22271            }
22272        }
22273        FixtureOperation::SeriesIloc => {
22274            let left = require_left_series(fixture)?;
22275            let positions = require_iloc_positions(fixture)?;
22276            let series = build_series(left)?;
22277            let actual = series.iloc(positions).map_err(|err| err.to_string());
22278            match expected {
22279                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
22280                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22281                    Err(message) if message.contains(&substr) => Vec::new(),
22282                    Err(message) => vec![make_drift_record(
22283                        ComparisonCategory::Value,
22284                        DriftLevel::Critical,
22285                        "series_iloc.error",
22286                        format!(
22287                            "expected series_iloc error containing '{substr}', got '{message}'"
22288                        ),
22289                    )],
22290                    Ok(_) => vec![make_drift_record(
22291                        ComparisonCategory::Value,
22292                        DriftLevel::Critical,
22293                        "series_iloc.error",
22294                        "expected series_iloc to fail but operation succeeded".to_owned(),
22295                    )],
22296                }),
22297                ResolvedExpected::ErrorAny => Ok(match actual {
22298                    Err(_) => Vec::new(),
22299                    Ok(_) => vec![make_drift_record(
22300                        ComparisonCategory::Value,
22301                        DriftLevel::Critical,
22302                        "series_iloc.error",
22303                        "expected series_iloc to fail but operation succeeded".to_owned(),
22304                    )],
22305                }),
22306                _ => Err("expected_series or expected_error required for series_iloc".to_owned()),
22307            }
22308        }
22309        FixtureOperation::SeriesTake => {
22310            let left = require_left_series(fixture)?;
22311            let indices = require_take_indices(fixture)?;
22312            let series = build_series(left)?;
22313            let actual = series.take(indices).map_err(|err| err.to_string());
22314            match expected {
22315                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
22316                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22317                    Err(message) if message.contains(&substr) => Vec::new(),
22318                    Err(message) => vec![make_drift_record(
22319                        ComparisonCategory::Value,
22320                        DriftLevel::Critical,
22321                        "series_take.error",
22322                        format!(
22323                            "expected series_take error containing '{substr}', got '{message}'"
22324                        ),
22325                    )],
22326                    Ok(_) => vec![make_drift_record(
22327                        ComparisonCategory::Value,
22328                        DriftLevel::Critical,
22329                        "series_take.error",
22330                        "expected series_take to fail but operation succeeded".to_owned(),
22331                    )],
22332                }),
22333                ResolvedExpected::ErrorAny => Ok(match actual {
22334                    Err(_) => Vec::new(),
22335                    Ok(_) => vec![make_drift_record(
22336                        ComparisonCategory::Value,
22337                        DriftLevel::Critical,
22338                        "series_take.error",
22339                        "expected series_take to fail but operation succeeded".to_owned(),
22340                    )],
22341                }),
22342                _ => Err("expected_series or expected_error required for series_take".to_owned()),
22343            }
22344        }
22345        FixtureOperation::SeriesAtTime => {
22346            let left = require_left_series(fixture)?;
22347            let time = require_time_value(fixture)?;
22348            let series = build_series(left)?;
22349            let actual = series.at_time(time).map_err(|err| err.to_string());
22350            match expected {
22351                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
22352                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22353                    Err(message) if message.contains(&substr) => Vec::new(),
22354                    Err(message) => vec![make_drift_record(
22355                        ComparisonCategory::Value,
22356                        DriftLevel::Critical,
22357                        "series_at_time.error",
22358                        format!(
22359                            "expected series_at_time error containing '{substr}', got '{message}'"
22360                        ),
22361                    )],
22362                    Ok(_) => vec![make_drift_record(
22363                        ComparisonCategory::Value,
22364                        DriftLevel::Critical,
22365                        "series_at_time.error",
22366                        "expected series_at_time to fail but operation succeeded".to_owned(),
22367                    )],
22368                }),
22369                ResolvedExpected::ErrorAny => Ok(match actual {
22370                    Err(_) => Vec::new(),
22371                    Ok(_) => vec![make_drift_record(
22372                        ComparisonCategory::Value,
22373                        DriftLevel::Critical,
22374                        "series_at_time.error",
22375                        "expected series_at_time to fail but operation succeeded".to_owned(),
22376                    )],
22377                }),
22378                _ => {
22379                    Err("expected_series or expected_error required for series_at_time".to_owned())
22380                }
22381            }
22382        }
22383        FixtureOperation::SeriesBetweenTime => {
22384            let left = require_left_series(fixture)?;
22385            let start = require_start_time(fixture)?;
22386            let end = require_end_time(fixture)?;
22387            let series = build_series(left)?;
22388            let actual = series
22389                .between_time(start, end)
22390                .map_err(|err| err.to_string());
22391            match expected {
22392                ResolvedExpected::Series(s) => Ok(diff_series(&actual?, &s)),
22393                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22394                    Err(message) if message.contains(&substr) => Vec::new(),
22395                    Err(message) => vec![make_drift_record(
22396                        ComparisonCategory::Value,
22397                        DriftLevel::Critical,
22398                        "series_between_time.error",
22399                        format!(
22400                            "expected series_between_time error containing '{substr}', got '{message}'"
22401                        ),
22402                    )],
22403                    Ok(_) => vec![make_drift_record(
22404                        ComparisonCategory::Value,
22405                        DriftLevel::Critical,
22406                        "series_between_time.error",
22407                        "expected series_between_time to fail but operation succeeded".to_owned(),
22408                    )],
22409                }),
22410                ResolvedExpected::ErrorAny => Ok(match actual {
22411                    Err(_) => Vec::new(),
22412                    Ok(_) => vec![make_drift_record(
22413                        ComparisonCategory::Value,
22414                        DriftLevel::Critical,
22415                        "series_between_time.error",
22416                        "expected series_between_time to fail but operation succeeded".to_owned(),
22417                    )],
22418                }),
22419                _ => Err(
22420                    "expected_series or expected_error required for series_between_time".to_owned(),
22421                ),
22422            }
22423        }
22424        FixtureOperation::SeriesPartitionDf => {
22425            let actual = execute_dataframe_fixture_operation(fixture);
22426            match expected {
22427                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
22428                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22429                    Err(message) if message.contains(&substr) => Vec::new(),
22430                    Err(message) => vec![make_drift_record(
22431                        ComparisonCategory::Value,
22432                        DriftLevel::Critical,
22433                        "series_partition_df.error",
22434                        format!(
22435                            "expected series_partition_df error containing '{substr}', got '{message}'"
22436                        ),
22437                    )],
22438                    Ok(_) => vec![make_drift_record(
22439                        ComparisonCategory::Value,
22440                        DriftLevel::Critical,
22441                        "series_partition_df.error",
22442                        "expected series_partition_df to fail but operation succeeded".to_owned(),
22443                    )],
22444                }),
22445                ResolvedExpected::ErrorAny => Ok(match actual {
22446                    Err(_) => Vec::new(),
22447                    Ok(_) => vec![make_drift_record(
22448                        ComparisonCategory::Value,
22449                        DriftLevel::Critical,
22450                        "series_partition_df.error",
22451                        "expected series_partition_df to fail but operation succeeded".to_owned(),
22452                    )],
22453                }),
22454                _ => Err(
22455                    "expected_frame or expected_error required for series_partition_df".to_owned(),
22456                ),
22457            }
22458        }
22459        FixtureOperation::SeriesRpartitionDf => {
22460            let actual = execute_dataframe_fixture_operation(fixture);
22461            match expected {
22462                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
22463                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22464                    Err(message) if message.contains(&substr) => Vec::new(),
22465                    Err(message) => vec![make_drift_record(
22466                        ComparisonCategory::Value,
22467                        DriftLevel::Critical,
22468                        "series_rpartition_df.error",
22469                        format!(
22470                            "expected series_rpartition_df error containing '{substr}', got '{message}'"
22471                        ),
22472                    )],
22473                    Ok(_) => vec![make_drift_record(
22474                        ComparisonCategory::Value,
22475                        DriftLevel::Critical,
22476                        "series_rpartition_df.error",
22477                        "expected series_rpartition_df to fail but operation succeeded".to_owned(),
22478                    )],
22479                }),
22480                ResolvedExpected::ErrorAny => Ok(match actual {
22481                    Err(_) => Vec::new(),
22482                    Ok(_) => vec![make_drift_record(
22483                        ComparisonCategory::Value,
22484                        DriftLevel::Critical,
22485                        "series_rpartition_df.error",
22486                        "expected series_rpartition_df to fail but operation succeeded".to_owned(),
22487                    )],
22488                }),
22489                _ => Err(
22490                    "expected_frame or expected_error required for series_rpartition_df".to_owned(),
22491                ),
22492            }
22493        }
22494        FixtureOperation::SeriesSplitDf => {
22495            let actual = execute_dataframe_fixture_operation(fixture);
22496            match expected {
22497                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
22498                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22499                    Err(message) if message.contains(&substr) => Vec::new(),
22500                    Err(message) => vec![make_drift_record(
22501                        ComparisonCategory::Value,
22502                        DriftLevel::Critical,
22503                        "series_split_df.error",
22504                        format!(
22505                            "expected series_split_df error containing '{substr}', got '{message}'"
22506                        ),
22507                    )],
22508                    Ok(_) => vec![make_drift_record(
22509                        ComparisonCategory::Value,
22510                        DriftLevel::Critical,
22511                        "series_split_df.error",
22512                        "expected series_split_df to fail but operation succeeded".to_owned(),
22513                    )],
22514                }),
22515                ResolvedExpected::ErrorAny => Ok(match actual {
22516                    Err(_) => Vec::new(),
22517                    Ok(_) => vec![make_drift_record(
22518                        ComparisonCategory::Value,
22519                        DriftLevel::Critical,
22520                        "series_split_df.error",
22521                        "expected series_split_df to fail but operation succeeded".to_owned(),
22522                    )],
22523                }),
22524                _ => {
22525                    Err("expected_frame or expected_error required for series_split_df".to_owned())
22526                }
22527            }
22528        }
22529        FixtureOperation::SeriesExtractAll => {
22530            let actual = execute_dataframe_fixture_operation(fixture);
22531            match expected {
22532                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
22533                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22534                    Err(message) if message.contains(&substr) => Vec::new(),
22535                    Err(message) => vec![make_drift_record(
22536                        ComparisonCategory::Value,
22537                        DriftLevel::Critical,
22538                        "series_extractall.error",
22539                        format!(
22540                            "expected series_extractall error containing '{substr}', got '{message}'"
22541                        ),
22542                    )],
22543                    Ok(_) => vec![make_drift_record(
22544                        ComparisonCategory::Value,
22545                        DriftLevel::Critical,
22546                        "series_extractall.error",
22547                        "expected series_extractall to fail but operation succeeded".to_owned(),
22548                    )],
22549                }),
22550                ResolvedExpected::ErrorAny => Ok(match actual {
22551                    Err(_) => Vec::new(),
22552                    Ok(_) => vec![make_drift_record(
22553                        ComparisonCategory::Value,
22554                        DriftLevel::Critical,
22555                        "series_extractall.error",
22556                        "expected series_extractall to fail but operation succeeded".to_owned(),
22557                    )],
22558                }),
22559                _ => Err(
22560                    "expected_frame or expected_error required for series_extractall".to_owned(),
22561                ),
22562            }
22563        }
22564        FixtureOperation::SeriesToFrame => {
22565            let actual = execute_dataframe_fixture_operation(fixture);
22566            match expected {
22567                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
22568                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22569                    Err(message) if message.contains(&substr) => Vec::new(),
22570                    Err(message) => vec![make_drift_record(
22571                        ComparisonCategory::Value,
22572                        DriftLevel::Critical,
22573                        "series_to_frame.error",
22574                        format!(
22575                            "expected series_to_frame error containing '{substr}', got '{message}'"
22576                        ),
22577                    )],
22578                    Ok(_) => vec![make_drift_record(
22579                        ComparisonCategory::Value,
22580                        DriftLevel::Critical,
22581                        "series_to_frame.error",
22582                        "expected series_to_frame to fail but operation succeeded".to_owned(),
22583                    )],
22584                }),
22585                ResolvedExpected::ErrorAny => Ok(match actual {
22586                    Err(_) => Vec::new(),
22587                    Ok(_) => vec![make_drift_record(
22588                        ComparisonCategory::Value,
22589                        DriftLevel::Critical,
22590                        "series_to_frame.error",
22591                        "expected series_to_frame to fail but operation succeeded".to_owned(),
22592                    )],
22593                }),
22594                _ => {
22595                    Err("expected_frame or expected_error required for series_to_frame".to_owned())
22596                }
22597            }
22598        }
22599        FixtureOperation::SeriesExtractDf => {
22600            let actual = execute_dataframe_fixture_operation(fixture);
22601            match expected {
22602                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
22603                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22604                    Err(message) if message.contains(&substr) => Vec::new(),
22605                    Err(message) => vec![make_drift_record(
22606                        ComparisonCategory::Value,
22607                        DriftLevel::Critical,
22608                        "series_extract_df.error",
22609                        format!(
22610                            "expected series_extract_df error containing '{substr}', got '{message}'"
22611                        ),
22612                    )],
22613                    Ok(_) => vec![make_drift_record(
22614                        ComparisonCategory::Value,
22615                        DriftLevel::Critical,
22616                        "series_extract_df.error",
22617                        "expected series_extract_df to fail but operation succeeded".to_owned(),
22618                    )],
22619                }),
22620                ResolvedExpected::ErrorAny => Ok(match actual {
22621                    Err(_) => Vec::new(),
22622                    Ok(_) => vec![make_drift_record(
22623                        ComparisonCategory::Value,
22624                        DriftLevel::Critical,
22625                        "series_extract_df.error",
22626                        "expected series_extract_df to fail but operation succeeded".to_owned(),
22627                    )],
22628                }),
22629                _ => Err(
22630                    "expected_frame or expected_error required for series_extract_df".to_owned(),
22631                ),
22632            }
22633        }
22634        FixtureOperation::DataFrameLoc => {
22635            let frame = require_frame(fixture)?;
22636            let labels = require_loc_labels(fixture)?;
22637            let frame = build_dataframe(frame)?;
22638            let actual = if frame.row_multiindex().is_some() {
22639                frame
22640                    .loc_tuple_with_columns(labels, fixture.column_order.as_deref())
22641                    .map_err(|err| err.to_string())
22642            } else {
22643                frame
22644                    .loc_with_columns(labels, fixture.column_order.as_deref())
22645                    .map_err(|err| err.to_string())
22646            };
22647            match expected {
22648                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
22649                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22650                    Err(message) if message.contains(&substr) => Vec::new(),
22651                    Err(message) => vec![make_drift_record(
22652                        ComparisonCategory::Value,
22653                        DriftLevel::Critical,
22654                        "dataframe_loc.error",
22655                        format!(
22656                            "expected dataframe_loc error containing '{substr}', got '{message}'"
22657                        ),
22658                    )],
22659                    Ok(_) => vec![make_drift_record(
22660                        ComparisonCategory::Value,
22661                        DriftLevel::Critical,
22662                        "dataframe_loc.error",
22663                        "expected dataframe_loc to fail but operation succeeded".to_owned(),
22664                    )],
22665                }),
22666                ResolvedExpected::ErrorAny => Ok(match actual {
22667                    Err(_) => Vec::new(),
22668                    Ok(_) => vec![make_drift_record(
22669                        ComparisonCategory::Value,
22670                        DriftLevel::Critical,
22671                        "dataframe_loc.error",
22672                        "expected dataframe_loc to fail but operation succeeded".to_owned(),
22673                    )],
22674                }),
22675                _ => Err("expected_frame or expected_error required for dataframe_loc".to_owned()),
22676            }
22677        }
22678        FixtureOperation::DataFrameIdentity => {
22679            let actual = build_dataframe(require_frame(fixture)?);
22680            match expected {
22681                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
22682                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22683                    Err(message) if message.contains(&substr) => Vec::new(),
22684                    Err(message) => vec![make_drift_record(
22685                        ComparisonCategory::Value,
22686                        DriftLevel::Critical,
22687                        "dataframe_identity.error",
22688                        format!(
22689                            "expected dataframe_identity error containing '{substr}', got '{message}'"
22690                        ),
22691                    )],
22692                    Ok(_) => vec![make_drift_record(
22693                        ComparisonCategory::Value,
22694                        DriftLevel::Critical,
22695                        "dataframe_identity.error",
22696                        "expected dataframe_identity to fail but operation succeeded".to_owned(),
22697                    )],
22698                }),
22699                ResolvedExpected::ErrorAny => Ok(match actual {
22700                    Err(_) => Vec::new(),
22701                    Ok(_) => vec![make_drift_record(
22702                        ComparisonCategory::Value,
22703                        DriftLevel::Critical,
22704                        "dataframe_identity.error",
22705                        "expected dataframe_identity to fail but operation succeeded".to_owned(),
22706                    )],
22707                }),
22708                _ => Err(
22709                    "expected_frame or expected_error required for dataframe_identity".to_owned(),
22710                ),
22711            }
22712        }
22713        FixtureOperation::DataFrameIloc => {
22714            let frame = require_frame(fixture)?;
22715            let positions = require_iloc_positions(fixture)?;
22716            let frame = build_dataframe(frame)?;
22717            let actual = frame
22718                .iloc_with_columns(positions, fixture.column_order.as_deref())
22719                .map_err(|err| err.to_string());
22720            match expected {
22721                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
22722                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22723                    Err(message) if message.contains(&substr) => Vec::new(),
22724                    Err(message) => vec![make_drift_record(
22725                        ComparisonCategory::Value,
22726                        DriftLevel::Critical,
22727                        "dataframe_iloc.error",
22728                        format!(
22729                            "expected dataframe_iloc error containing '{substr}', got '{message}'"
22730                        ),
22731                    )],
22732                    Ok(_) => vec![make_drift_record(
22733                        ComparisonCategory::Value,
22734                        DriftLevel::Critical,
22735                        "dataframe_iloc.error",
22736                        "expected dataframe_iloc to fail but operation succeeded".to_owned(),
22737                    )],
22738                }),
22739                ResolvedExpected::ErrorAny => Ok(match actual {
22740                    Err(_) => Vec::new(),
22741                    Ok(_) => vec![make_drift_record(
22742                        ComparisonCategory::Value,
22743                        DriftLevel::Critical,
22744                        "dataframe_iloc.error",
22745                        "expected dataframe_iloc to fail but operation succeeded".to_owned(),
22746                    )],
22747                }),
22748                _ => Err("expected_frame or expected_error required for dataframe_iloc".to_owned()),
22749            }
22750        }
22751        FixtureOperation::DataFrameTake => {
22752            let actual = execute_dataframe_fixture_operation(fixture);
22753            match expected {
22754                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
22755                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22756                    Err(message) if message.contains(&substr) => Vec::new(),
22757                    Err(message) => vec![make_drift_record(
22758                        ComparisonCategory::Value,
22759                        DriftLevel::Critical,
22760                        "dataframe_take.error",
22761                        format!(
22762                            "expected dataframe_take error containing '{substr}', got '{message}'"
22763                        ),
22764                    )],
22765                    Ok(_) => vec![make_drift_record(
22766                        ComparisonCategory::Value,
22767                        DriftLevel::Critical,
22768                        "dataframe_take.error",
22769                        "expected dataframe_take to fail but operation succeeded".to_owned(),
22770                    )],
22771                }),
22772                ResolvedExpected::ErrorAny => Ok(match actual {
22773                    Err(_) => Vec::new(),
22774                    Ok(_) => vec![make_drift_record(
22775                        ComparisonCategory::Value,
22776                        DriftLevel::Critical,
22777                        "dataframe_take.error",
22778                        "expected dataframe_take to fail but operation succeeded".to_owned(),
22779                    )],
22780                }),
22781                _ => Err("expected_frame or expected_error required for dataframe_take".to_owned()),
22782            }
22783        }
22784        FixtureOperation::DataFrameXs => {
22785            let actual = execute_dataframe_fixture_operation(fixture);
22786            match expected {
22787                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
22788                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22789                    Err(message) if message.contains(&substr) => Vec::new(),
22790                    Err(message) => vec![make_drift_record(
22791                        ComparisonCategory::Value,
22792                        DriftLevel::Critical,
22793                        "dataframe_xs.error",
22794                        format!(
22795                            "expected dataframe_xs error containing '{substr}', got '{message}'"
22796                        ),
22797                    )],
22798                    Ok(_) => vec![make_drift_record(
22799                        ComparisonCategory::Value,
22800                        DriftLevel::Critical,
22801                        "dataframe_xs.error",
22802                        "expected dataframe_xs to fail but operation succeeded".to_owned(),
22803                    )],
22804                }),
22805                ResolvedExpected::ErrorAny => Ok(match actual {
22806                    Err(_) => Vec::new(),
22807                    Ok(_) => vec![make_drift_record(
22808                        ComparisonCategory::Value,
22809                        DriftLevel::Critical,
22810                        "dataframe_xs.error",
22811                        "expected dataframe_xs to fail but operation succeeded".to_owned(),
22812                    )],
22813                }),
22814                _ => Err("expected_frame or expected_error required for dataframe_xs".to_owned()),
22815            }
22816        }
22817        FixtureOperation::DataFrameGroupByIdxMin => {
22818            let actual = execute_dataframe_fixture_operation(fixture);
22819            match expected {
22820                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
22821                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22822                    Err(message) if message.contains(&substr) => Vec::new(),
22823                    Err(message) => vec![make_drift_record(
22824                        ComparisonCategory::Value,
22825                        DriftLevel::Critical,
22826                        "dataframe_groupby_idxmin.error",
22827                        format!(
22828                            "expected dataframe_groupby_idxmin error containing '{substr}', got '{message}'"
22829                        ),
22830                    )],
22831                    Ok(_) => vec![make_drift_record(
22832                        ComparisonCategory::Value,
22833                        DriftLevel::Critical,
22834                        "dataframe_groupby_idxmin.error",
22835                        "expected dataframe_groupby_idxmin to fail but operation succeeded"
22836                            .to_owned(),
22837                    )],
22838                }),
22839                ResolvedExpected::ErrorAny => Ok(match actual {
22840                    Err(_) => Vec::new(),
22841                    Ok(_) => vec![make_drift_record(
22842                        ComparisonCategory::Value,
22843                        DriftLevel::Critical,
22844                        "dataframe_groupby_idxmin.error",
22845                        "expected dataframe_groupby_idxmin to fail but operation succeeded"
22846                            .to_owned(),
22847                    )],
22848                }),
22849                _ => Err(
22850                    "expected_frame or expected_error required for dataframe_groupby_idxmin"
22851                        .to_owned(),
22852                ),
22853            }
22854        }
22855        FixtureOperation::DataFrameGroupBySum => {
22856            let actual = execute_dataframe_fixture_operation(fixture);
22857            match expected {
22858                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
22859                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22860                    Err(message) if message.contains(&substr) => Vec::new(),
22861                    Err(message) => vec![make_drift_record(
22862                        ComparisonCategory::Value,
22863                        DriftLevel::Critical,
22864                        "dataframe_groupby_sum.error",
22865                        format!(
22866                            "expected dataframe_groupby_sum error containing '{substr}', got '{message}'"
22867                        ),
22868                    )],
22869                    Ok(_) => vec![make_drift_record(
22870                        ComparisonCategory::Value,
22871                        DriftLevel::Critical,
22872                        "dataframe_groupby_sum.error",
22873                        "expected dataframe_groupby_sum to fail but operation succeeded".to_owned(),
22874                    )],
22875                }),
22876                ResolvedExpected::ErrorAny => Ok(match actual {
22877                    Err(_) => Vec::new(),
22878                    Ok(_) => vec![make_drift_record(
22879                        ComparisonCategory::Value,
22880                        DriftLevel::Critical,
22881                        "dataframe_groupby_sum.error",
22882                        "expected dataframe_groupby_sum to fail but operation succeeded".to_owned(),
22883                    )],
22884                }),
22885                _ => Err(
22886                    "expected_frame or expected_error required for dataframe_groupby_sum"
22887                        .to_owned(),
22888                ),
22889            }
22890        }
22891        FixtureOperation::DataFrameGroupByAggMulti => {
22892            let actual = execute_dataframe_fixture_operation(fixture);
22893            match expected {
22894                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
22895                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22896                    Err(message) if message.contains(&substr) => Vec::new(),
22897                    Err(message) => vec![make_drift_record(
22898                        ComparisonCategory::Value,
22899                        DriftLevel::Critical,
22900                        "dataframe_groupby_agg_multi.error",
22901                        format!(
22902                            "expected dataframe_groupby_agg_multi error containing '{substr}', got '{message}'"
22903                        ),
22904                    )],
22905                    Ok(_) => vec![make_drift_record(
22906                        ComparisonCategory::Value,
22907                        DriftLevel::Critical,
22908                        "dataframe_groupby_agg_multi.error",
22909                        "expected dataframe_groupby_agg_multi to fail but operation succeeded"
22910                            .to_owned(),
22911                    )],
22912                }),
22913                ResolvedExpected::ErrorAny => Ok(match actual {
22914                    Err(_) => Vec::new(),
22915                    Ok(_) => vec![make_drift_record(
22916                        ComparisonCategory::Value,
22917                        DriftLevel::Critical,
22918                        "dataframe_groupby_agg_multi.error",
22919                        "expected dataframe_groupby_agg_multi to fail but operation succeeded"
22920                            .to_owned(),
22921                    )],
22922                }),
22923                _ => Err(
22924                    "expected_frame or expected_error required for dataframe_groupby_agg_multi"
22925                        .to_owned(),
22926                ),
22927            }
22928        }
22929        FixtureOperation::DataFrameGroupByIdxMax => {
22930            let actual = execute_dataframe_fixture_operation(fixture);
22931            match expected {
22932                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
22933                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22934                    Err(message) if message.contains(&substr) => Vec::new(),
22935                    Err(message) => vec![make_drift_record(
22936                        ComparisonCategory::Value,
22937                        DriftLevel::Critical,
22938                        "dataframe_groupby_idxmax.error",
22939                        format!(
22940                            "expected dataframe_groupby_idxmax error containing '{substr}', got '{message}'"
22941                        ),
22942                    )],
22943                    Ok(_) => vec![make_drift_record(
22944                        ComparisonCategory::Value,
22945                        DriftLevel::Critical,
22946                        "dataframe_groupby_idxmax.error",
22947                        "expected dataframe_groupby_idxmax to fail but operation succeeded"
22948                            .to_owned(),
22949                    )],
22950                }),
22951                ResolvedExpected::ErrorAny => Ok(match actual {
22952                    Err(_) => Vec::new(),
22953                    Ok(_) => vec![make_drift_record(
22954                        ComparisonCategory::Value,
22955                        DriftLevel::Critical,
22956                        "dataframe_groupby_idxmax.error",
22957                        "expected dataframe_groupby_idxmax to fail but operation succeeded"
22958                            .to_owned(),
22959                    )],
22960                }),
22961                _ => Err(
22962                    "expected_frame or expected_error required for dataframe_groupby_idxmax"
22963                        .to_owned(),
22964                ),
22965            }
22966        }
22967        FixtureOperation::DataFrameGroupByAny => {
22968            let actual = execute_dataframe_fixture_operation(fixture);
22969            match expected {
22970                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
22971                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
22972                    Err(message) if message.contains(&substr) => Vec::new(),
22973                    Err(message) => vec![make_drift_record(
22974                        ComparisonCategory::Value,
22975                        DriftLevel::Critical,
22976                        "dataframe_groupby_any.error",
22977                        format!(
22978                            "expected dataframe_groupby_any error containing '{substr}', got '{message}'"
22979                        ),
22980                    )],
22981                    Ok(_) => vec![make_drift_record(
22982                        ComparisonCategory::Value,
22983                        DriftLevel::Critical,
22984                        "dataframe_groupby_any.error",
22985                        "expected dataframe_groupby_any to fail but operation succeeded".to_owned(),
22986                    )],
22987                }),
22988                ResolvedExpected::ErrorAny => Ok(match actual {
22989                    Err(_) => Vec::new(),
22990                    Ok(_) => vec![make_drift_record(
22991                        ComparisonCategory::Value,
22992                        DriftLevel::Critical,
22993                        "dataframe_groupby_any.error",
22994                        "expected dataframe_groupby_any to fail but operation succeeded".to_owned(),
22995                    )],
22996                }),
22997                _ => Err(
22998                    "expected_frame or expected_error required for dataframe_groupby_any"
22999                        .to_owned(),
23000                ),
23001            }
23002        }
23003        FixtureOperation::DataFrameGroupByAll => {
23004            let actual = execute_dataframe_fixture_operation(fixture);
23005            match expected {
23006                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
23007                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
23008                    Err(message) if message.contains(&substr) => Vec::new(),
23009                    Err(message) => vec![make_drift_record(
23010                        ComparisonCategory::Value,
23011                        DriftLevel::Critical,
23012                        "dataframe_groupby_all.error",
23013                        format!(
23014                            "expected dataframe_groupby_all error containing '{substr}', got '{message}'"
23015                        ),
23016                    )],
23017                    Ok(_) => vec![make_drift_record(
23018                        ComparisonCategory::Value,
23019                        DriftLevel::Critical,
23020                        "dataframe_groupby_all.error",
23021                        "expected dataframe_groupby_all to fail but operation succeeded".to_owned(),
23022                    )],
23023                }),
23024                ResolvedExpected::ErrorAny => Ok(match actual {
23025                    Err(_) => Vec::new(),
23026                    Ok(_) => vec![make_drift_record(
23027                        ComparisonCategory::Value,
23028                        DriftLevel::Critical,
23029                        "dataframe_groupby_all.error",
23030                        "expected dataframe_groupby_all to fail but operation succeeded".to_owned(),
23031                    )],
23032                }),
23033                _ => Err(
23034                    "expected_frame or expected_error required for dataframe_groupby_all"
23035                        .to_owned(),
23036                ),
23037            }
23038        }
23039        FixtureOperation::DataFrameGroupByGetGroup => {
23040            let actual = execute_dataframe_fixture_operation(fixture);
23041            match expected {
23042                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
23043                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
23044                    Err(message) if message.contains(&substr) => Vec::new(),
23045                    Err(message) => vec![make_drift_record(
23046                        ComparisonCategory::Value,
23047                        DriftLevel::Critical,
23048                        "dataframe_groupby_get_group.error",
23049                        format!(
23050                            "expected dataframe_groupby_get_group error containing '{substr}', got '{message}'"
23051                        ),
23052                    )],
23053                    Ok(_) => vec![make_drift_record(
23054                        ComparisonCategory::Value,
23055                        DriftLevel::Critical,
23056                        "dataframe_groupby_get_group.error",
23057                        "expected dataframe_groupby_get_group to fail but operation succeeded"
23058                            .to_owned(),
23059                    )],
23060                }),
23061                ResolvedExpected::ErrorAny => Ok(match actual {
23062                    Err(_) => Vec::new(),
23063                    Ok(_) => vec![make_drift_record(
23064                        ComparisonCategory::Value,
23065                        DriftLevel::Critical,
23066                        "dataframe_groupby_get_group.error",
23067                        "expected dataframe_groupby_get_group to fail but operation succeeded"
23068                            .to_owned(),
23069                    )],
23070                }),
23071                _ => Err(
23072                    "expected_frame or expected_error required for dataframe_groupby_get_group"
23073                        .to_owned(),
23074                ),
23075            }
23076        }
23077        FixtureOperation::DataFrameGroupByFfill => {
23078            let actual = execute_dataframe_fixture_operation(fixture);
23079            match expected {
23080                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
23081                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
23082                    Err(message) if message.contains(&substr) => Vec::new(),
23083                    Err(message) => vec![make_drift_record(
23084                        ComparisonCategory::Value,
23085                        DriftLevel::Critical,
23086                        "dataframe_groupby_ffill.error",
23087                        format!(
23088                            "expected dataframe_groupby_ffill error containing '{substr}', got '{message}'"
23089                        ),
23090                    )],
23091                    Ok(_) => vec![make_drift_record(
23092                        ComparisonCategory::Value,
23093                        DriftLevel::Critical,
23094                        "dataframe_groupby_ffill.error",
23095                        "expected dataframe_groupby_ffill to fail but operation succeeded"
23096                            .to_owned(),
23097                    )],
23098                }),
23099                ResolvedExpected::ErrorAny => Ok(match actual {
23100                    Err(_) => Vec::new(),
23101                    Ok(_) => vec![make_drift_record(
23102                        ComparisonCategory::Value,
23103                        DriftLevel::Critical,
23104                        "dataframe_groupby_ffill.error",
23105                        "expected dataframe_groupby_ffill to fail but operation succeeded"
23106                            .to_owned(),
23107                    )],
23108                }),
23109                _ => Err(
23110                    "expected_frame or expected_error required for dataframe_groupby_ffill"
23111                        .to_owned(),
23112                ),
23113            }
23114        }
23115        FixtureOperation::DataFrameGroupByBfill => {
23116            let actual = execute_dataframe_fixture_operation(fixture);
23117            match expected {
23118                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
23119                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
23120                    Err(message) if message.contains(&substr) => Vec::new(),
23121                    Err(message) => vec![make_drift_record(
23122                        ComparisonCategory::Value,
23123                        DriftLevel::Critical,
23124                        "dataframe_groupby_bfill.error",
23125                        format!(
23126                            "expected dataframe_groupby_bfill error containing '{substr}', got '{message}'"
23127                        ),
23128                    )],
23129                    Ok(_) => vec![make_drift_record(
23130                        ComparisonCategory::Value,
23131                        DriftLevel::Critical,
23132                        "dataframe_groupby_bfill.error",
23133                        "expected dataframe_groupby_bfill to fail but operation succeeded"
23134                            .to_owned(),
23135                    )],
23136                }),
23137                ResolvedExpected::ErrorAny => Ok(match actual {
23138                    Err(_) => Vec::new(),
23139                    Ok(_) => vec![make_drift_record(
23140                        ComparisonCategory::Value,
23141                        DriftLevel::Critical,
23142                        "dataframe_groupby_bfill.error",
23143                        "expected dataframe_groupby_bfill to fail but operation succeeded"
23144                            .to_owned(),
23145                    )],
23146                }),
23147                _ => Err(
23148                    "expected_frame or expected_error required for dataframe_groupby_bfill"
23149                        .to_owned(),
23150                ),
23151            }
23152        }
23153        FixtureOperation::DataFrameGroupBySem => {
23154            let actual = execute_dataframe_fixture_operation(fixture);
23155            match expected {
23156                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
23157                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
23158                    Err(message) if message.contains(&substr) => Vec::new(),
23159                    Err(message) => vec![make_drift_record(
23160                        ComparisonCategory::Value,
23161                        DriftLevel::Critical,
23162                        "dataframe_groupby_sem.error",
23163                        format!(
23164                            "expected dataframe_groupby_sem error containing '{substr}', got '{message}'"
23165                        ),
23166                    )],
23167                    Ok(_) => vec![make_drift_record(
23168                        ComparisonCategory::Value,
23169                        DriftLevel::Critical,
23170                        "dataframe_groupby_sem.error",
23171                        "expected dataframe_groupby_sem to fail but operation succeeded".to_owned(),
23172                    )],
23173                }),
23174                ResolvedExpected::ErrorAny => Ok(match actual {
23175                    Err(_) => Vec::new(),
23176                    Ok(_) => vec![make_drift_record(
23177                        ComparisonCategory::Value,
23178                        DriftLevel::Critical,
23179                        "dataframe_groupby_sem.error",
23180                        "expected dataframe_groupby_sem to fail but operation succeeded".to_owned(),
23181                    )],
23182                }),
23183                _ => Err(
23184                    "expected_frame or expected_error required for dataframe_groupby_sem"
23185                        .to_owned(),
23186                ),
23187            }
23188        }
23189        FixtureOperation::DataFrameGroupBySkew => {
23190            let actual = execute_dataframe_fixture_operation(fixture);
23191            match expected {
23192                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
23193                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
23194                    Err(message) if message.contains(&substr) => Vec::new(),
23195                    Err(message) => vec![make_drift_record(
23196                        ComparisonCategory::Value,
23197                        DriftLevel::Critical,
23198                        "dataframe_groupby_skew.error",
23199                        format!(
23200                            "expected dataframe_groupby_skew error containing '{substr}', got '{message}'"
23201                        ),
23202                    )],
23203                    Ok(_) => vec![make_drift_record(
23204                        ComparisonCategory::Value,
23205                        DriftLevel::Critical,
23206                        "dataframe_groupby_skew.error",
23207                        "expected dataframe_groupby_skew to fail but operation succeeded"
23208                            .to_owned(),
23209                    )],
23210                }),
23211                ResolvedExpected::ErrorAny => Ok(match actual {
23212                    Err(_) => Vec::new(),
23213                    Ok(_) => vec![make_drift_record(
23214                        ComparisonCategory::Value,
23215                        DriftLevel::Critical,
23216                        "dataframe_groupby_skew.error",
23217                        "expected dataframe_groupby_skew to fail but operation succeeded"
23218                            .to_owned(),
23219                    )],
23220                }),
23221                _ => Err(
23222                    "expected_frame or expected_error required for dataframe_groupby_skew"
23223                        .to_owned(),
23224                ),
23225            }
23226        }
23227        FixtureOperation::DataFrameGroupByKurtosis => {
23228            let actual = execute_dataframe_fixture_operation(fixture);
23229            match expected {
23230                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
23231                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
23232                    Err(message) if message.contains(&substr) => Vec::new(),
23233                    Err(message) => vec![make_drift_record(
23234                        ComparisonCategory::Value,
23235                        DriftLevel::Critical,
23236                        "dataframe_groupby_kurtosis.error",
23237                        format!(
23238                            "expected dataframe_groupby_kurtosis error containing '{substr}', got '{message}'"
23239                        ),
23240                    )],
23241                    Ok(_) => vec![make_drift_record(
23242                        ComparisonCategory::Value,
23243                        DriftLevel::Critical,
23244                        "dataframe_groupby_kurtosis.error",
23245                        "expected dataframe_groupby_kurtosis to fail but operation succeeded"
23246                            .to_owned(),
23247                    )],
23248                }),
23249                ResolvedExpected::ErrorAny => Ok(match actual {
23250                    Err(_) => Vec::new(),
23251                    Ok(_) => vec![make_drift_record(
23252                        ComparisonCategory::Value,
23253                        DriftLevel::Critical,
23254                        "dataframe_groupby_kurtosis.error",
23255                        "expected dataframe_groupby_kurtosis to fail but operation succeeded"
23256                            .to_owned(),
23257                    )],
23258                }),
23259                _ => Err(
23260                    "expected_frame or expected_error required for dataframe_groupby_kurtosis"
23261                        .to_owned(),
23262                ),
23263            }
23264        }
23265        FixtureOperation::DataFrameGroupByOhlc => {
23266            let actual = execute_dataframe_fixture_operation(fixture);
23267            match expected {
23268                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
23269                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
23270                    Err(message) if message.contains(&substr) => Vec::new(),
23271                    Err(message) => vec![make_drift_record(
23272                        ComparisonCategory::Value,
23273                        DriftLevel::Critical,
23274                        "dataframe_groupby_ohlc.error",
23275                        format!(
23276                            "expected dataframe_groupby_ohlc error containing '{substr}', got '{message}'"
23277                        ),
23278                    )],
23279                    Ok(_) => vec![make_drift_record(
23280                        ComparisonCategory::Value,
23281                        DriftLevel::Critical,
23282                        "dataframe_groupby_ohlc.error",
23283                        "expected dataframe_groupby_ohlc to fail but operation succeeded"
23284                            .to_owned(),
23285                    )],
23286                }),
23287                ResolvedExpected::ErrorAny => Ok(match actual {
23288                    Err(_) => Vec::new(),
23289                    Ok(_) => vec![make_drift_record(
23290                        ComparisonCategory::Value,
23291                        DriftLevel::Critical,
23292                        "dataframe_groupby_ohlc.error",
23293                        "expected dataframe_groupby_ohlc to fail but operation succeeded"
23294                            .to_owned(),
23295                    )],
23296                }),
23297                _ => Err(
23298                    "expected_frame or expected_error required for dataframe_groupby_ohlc"
23299                        .to_owned(),
23300                ),
23301            }
23302        }
23303        FixtureOperation::DataFrameGroupByCumcount => {
23304            let actual = execute_dataframe_groupby_series_fixture_operation(fixture, false);
23305            match expected {
23306                ResolvedExpected::Series(series) => Ok(diff_series(&actual?, &series)),
23307                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
23308                    Err(message) if message.contains(&substr) => Vec::new(),
23309                    Err(message) => vec![make_drift_record(
23310                        ComparisonCategory::Value,
23311                        DriftLevel::Critical,
23312                        "dataframe_groupby_cumcount.error",
23313                        format!(
23314                            "expected dataframe_groupby_cumcount error containing '{substr}', got '{message}'"
23315                        ),
23316                    )],
23317                    Ok(_) => vec![make_drift_record(
23318                        ComparisonCategory::Value,
23319                        DriftLevel::Critical,
23320                        "dataframe_groupby_cumcount.error",
23321                        "expected dataframe_groupby_cumcount to fail but operation succeeded"
23322                            .to_owned(),
23323                    )],
23324                }),
23325                ResolvedExpected::ErrorAny => Ok(match actual {
23326                    Err(_) => Vec::new(),
23327                    Ok(_) => vec![make_drift_record(
23328                        ComparisonCategory::Value,
23329                        DriftLevel::Critical,
23330                        "dataframe_groupby_cumcount.error",
23331                        "expected dataframe_groupby_cumcount to fail but operation succeeded"
23332                            .to_owned(),
23333                    )],
23334                }),
23335                _ => Err(
23336                    "expected_series or expected_error required for dataframe_groupby_cumcount"
23337                        .to_owned(),
23338                ),
23339            }
23340        }
23341        FixtureOperation::DataFrameGroupByNgroup => {
23342            let actual = execute_dataframe_groupby_series_fixture_operation(fixture, true);
23343            match expected {
23344                ResolvedExpected::Series(series) => Ok(diff_series(&actual?, &series)),
23345                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
23346                    Err(message) if message.contains(&substr) => Vec::new(),
23347                    Err(message) => vec![make_drift_record(
23348                        ComparisonCategory::Value,
23349                        DriftLevel::Critical,
23350                        "dataframe_groupby_ngroup.error",
23351                        format!(
23352                            "expected dataframe_groupby_ngroup error containing '{substr}', got '{message}'"
23353                        ),
23354                    )],
23355                    Ok(_) => vec![make_drift_record(
23356                        ComparisonCategory::Value,
23357                        DriftLevel::Critical,
23358                        "dataframe_groupby_ngroup.error",
23359                        "expected dataframe_groupby_ngroup to fail but operation succeeded"
23360                            .to_owned(),
23361                    )],
23362                }),
23363                ResolvedExpected::ErrorAny => Ok(match actual {
23364                    Err(_) => Vec::new(),
23365                    Ok(_) => vec![make_drift_record(
23366                        ComparisonCategory::Value,
23367                        DriftLevel::Critical,
23368                        "dataframe_groupby_ngroup.error",
23369                        "expected dataframe_groupby_ngroup to fail but operation succeeded"
23370                            .to_owned(),
23371                    )],
23372                }),
23373                _ => Err(
23374                    "expected_series or expected_error required for dataframe_groupby_ngroup"
23375                        .to_owned(),
23376                ),
23377            }
23378        }
23379        FixtureOperation::DataFrameAsof => {
23380            let actual = execute_dataframe_asof_fixture_operation(fixture);
23381            match expected {
23382                ResolvedExpected::Series(series) => Ok(diff_series(&actual?, &series)),
23383                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
23384                    Err(message) if message.contains(&substr) => Vec::new(),
23385                    Err(message) => vec![make_drift_record(
23386                        ComparisonCategory::Value,
23387                        DriftLevel::Critical,
23388                        "dataframe_asof.error",
23389                        format!(
23390                            "expected dataframe_asof error containing '{substr}', got '{message}'"
23391                        ),
23392                    )],
23393                    Ok(_) => vec![make_drift_record(
23394                        ComparisonCategory::Value,
23395                        DriftLevel::Critical,
23396                        "dataframe_asof.error",
23397                        "expected dataframe_asof to fail but operation succeeded".to_owned(),
23398                    )],
23399                }),
23400                ResolvedExpected::ErrorAny => Ok(match actual {
23401                    Err(_) => Vec::new(),
23402                    Ok(_) => vec![make_drift_record(
23403                        ComparisonCategory::Value,
23404                        DriftLevel::Critical,
23405                        "dataframe_asof.error",
23406                        "expected dataframe_asof to fail but operation succeeded".to_owned(),
23407                    )],
23408                }),
23409                _ => {
23410                    Err("expected_series or expected_error required for dataframe_asof".to_owned())
23411                }
23412            }
23413        }
23414        FixtureOperation::DataFrameAtTime => {
23415            let actual = execute_dataframe_fixture_operation(fixture);
23416            match expected {
23417                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
23418                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
23419                    Err(message) if message.contains(&substr) => Vec::new(),
23420                    Err(message) => vec![make_drift_record(
23421                        ComparisonCategory::Value,
23422                        DriftLevel::Critical,
23423                        "dataframe_at_time.error",
23424                        format!(
23425                            "expected dataframe_at_time error containing '{substr}', got '{message}'"
23426                        ),
23427                    )],
23428                    Ok(_) => vec![make_drift_record(
23429                        ComparisonCategory::Value,
23430                        DriftLevel::Critical,
23431                        "dataframe_at_time.error",
23432                        "expected dataframe_at_time to fail but operation succeeded".to_owned(),
23433                    )],
23434                }),
23435                ResolvedExpected::ErrorAny => Ok(match actual {
23436                    Err(_) => Vec::new(),
23437                    Ok(_) => vec![make_drift_record(
23438                        ComparisonCategory::Value,
23439                        DriftLevel::Critical,
23440                        "dataframe_at_time.error",
23441                        "expected dataframe_at_time to fail but operation succeeded".to_owned(),
23442                    )],
23443                }),
23444                _ => Err(
23445                    "expected_frame or expected_error required for dataframe_at_time".to_owned(),
23446                ),
23447            }
23448        }
23449        FixtureOperation::DataFrameBetweenTime => {
23450            let actual = execute_dataframe_fixture_operation(fixture);
23451            match expected {
23452                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
23453                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
23454                    Err(message) if message.contains(&substr) => Vec::new(),
23455                    Err(message) => vec![make_drift_record(
23456                        ComparisonCategory::Value,
23457                        DriftLevel::Critical,
23458                        "dataframe_between_time.error",
23459                        format!(
23460                            "expected dataframe_between_time error containing '{substr}', got '{message}'"
23461                        ),
23462                    )],
23463                    Ok(_) => vec![make_drift_record(
23464                        ComparisonCategory::Value,
23465                        DriftLevel::Critical,
23466                        "dataframe_between_time.error",
23467                        "expected dataframe_between_time to fail but operation succeeded"
23468                            .to_owned(),
23469                    )],
23470                }),
23471                ResolvedExpected::ErrorAny => Ok(match actual {
23472                    Err(_) => Vec::new(),
23473                    Ok(_) => vec![make_drift_record(
23474                        ComparisonCategory::Value,
23475                        DriftLevel::Critical,
23476                        "dataframe_between_time.error",
23477                        "expected dataframe_between_time to fail but operation succeeded"
23478                            .to_owned(),
23479                    )],
23480                }),
23481                _ => Err(
23482                    "expected_frame or expected_error required for dataframe_between_time"
23483                        .to_owned(),
23484                ),
23485            }
23486        }
23487        FixtureOperation::DataFrameBool => {
23488            let actual = execute_dataframe_bool_fixture_operation(fixture);
23489            match expected {
23490                ResolvedExpected::Bool(value) => Ok(diff_bool(actual?, value, "dataframe_bool")),
23491                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
23492                    Err(message) if message.contains(&substr) => Vec::new(),
23493                    Err(message) => vec![make_drift_record(
23494                        ComparisonCategory::Value,
23495                        DriftLevel::Critical,
23496                        "dataframe_bool.error",
23497                        format!(
23498                            "expected dataframe_bool error containing '{substr}', got '{message}'"
23499                        ),
23500                    )],
23501                    Ok(_) => vec![make_drift_record(
23502                        ComparisonCategory::Value,
23503                        DriftLevel::Critical,
23504                        "dataframe_bool.error",
23505                        "expected dataframe_bool to fail but operation succeeded".to_owned(),
23506                    )],
23507                }),
23508                ResolvedExpected::ErrorAny => Ok(match actual {
23509                    Err(_) => Vec::new(),
23510                    Ok(_) => vec![make_drift_record(
23511                        ComparisonCategory::Value,
23512                        DriftLevel::Critical,
23513                        "dataframe_bool.error",
23514                        "expected dataframe_bool to fail but operation succeeded".to_owned(),
23515                    )],
23516                }),
23517                _ => Err("expected_bool or expected_error required for dataframe_bool".to_owned()),
23518            }
23519        }
23520        FixtureOperation::DataFrameHead => {
23521            let frame = require_frame(fixture)?;
23522            let n = fixture
23523                .head_n
23524                .ok_or_else(|| "head_n is required for dataframe_head".to_owned())?;
23525            let frame = build_dataframe(frame)?;
23526            let actual = frame.head(n).map_err(|err| err.to_string());
23527            match expected {
23528                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
23529                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
23530                    Err(message) if message.contains(&substr) => Vec::new(),
23531                    Err(message) => vec![make_drift_record(
23532                        ComparisonCategory::Value,
23533                        DriftLevel::Critical,
23534                        "dataframe_head.error",
23535                        format!(
23536                            "expected dataframe_head error containing '{substr}', got '{message}'"
23537                        ),
23538                    )],
23539                    Ok(_) => vec![make_drift_record(
23540                        ComparisonCategory::Value,
23541                        DriftLevel::Critical,
23542                        "dataframe_head.error",
23543                        "expected dataframe_head to fail but operation succeeded".to_owned(),
23544                    )],
23545                }),
23546                ResolvedExpected::ErrorAny => Ok(match actual {
23547                    Err(_) => Vec::new(),
23548                    Ok(_) => vec![make_drift_record(
23549                        ComparisonCategory::Value,
23550                        DriftLevel::Critical,
23551                        "dataframe_head.error",
23552                        "expected dataframe_head to fail but operation succeeded".to_owned(),
23553                    )],
23554                }),
23555                _ => Err("expected_frame or expected_error required for dataframe_head".to_owned()),
23556            }
23557        }
23558        FixtureOperation::DataFrameTail => {
23559            let frame = require_frame(fixture)?;
23560            let n = fixture
23561                .tail_n
23562                .ok_or_else(|| "tail_n is required for dataframe_tail".to_owned())?;
23563            let frame = build_dataframe(frame)?;
23564            let actual = frame.tail(n).map_err(|err| err.to_string());
23565            match expected {
23566                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
23567                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
23568                    Err(message) if message.contains(&substr) => Vec::new(),
23569                    Err(message) => vec![make_drift_record(
23570                        ComparisonCategory::Value,
23571                        DriftLevel::Critical,
23572                        "dataframe_tail.error",
23573                        format!(
23574                            "expected dataframe_tail error containing '{substr}', got '{message}'"
23575                        ),
23576                    )],
23577                    Ok(_) => vec![make_drift_record(
23578                        ComparisonCategory::Value,
23579                        DriftLevel::Critical,
23580                        "dataframe_tail.error",
23581                        "expected dataframe_tail to fail but operation succeeded".to_owned(),
23582                    )],
23583                }),
23584                ResolvedExpected::ErrorAny => Ok(match actual {
23585                    Err(_) => Vec::new(),
23586                    Ok(_) => vec![make_drift_record(
23587                        ComparisonCategory::Value,
23588                        DriftLevel::Critical,
23589                        "dataframe_tail.error",
23590                        "expected dataframe_tail to fail but operation succeeded".to_owned(),
23591                    )],
23592                }),
23593                _ => Err("expected_frame or expected_error required for dataframe_tail".to_owned()),
23594            }
23595        }
23596        FixtureOperation::DataFrameEval => {
23597            let actual = execute_dataframe_eval_fixture_operation(fixture, policy, ledger);
23598            match expected {
23599                ResolvedExpected::Series(series) => Ok(diff_series(&actual?, &series)),
23600                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
23601                    Err(message) if message.contains(&substr) => Vec::new(),
23602                    Err(message) => vec![make_drift_record(
23603                        ComparisonCategory::Value,
23604                        DriftLevel::Critical,
23605                        "dataframe_eval.error",
23606                        format!(
23607                            "expected dataframe_eval error containing '{substr}', got '{message}'"
23608                        ),
23609                    )],
23610                    Ok(_) => vec![make_drift_record(
23611                        ComparisonCategory::Value,
23612                        DriftLevel::Critical,
23613                        "dataframe_eval.error",
23614                        "expected dataframe_eval to fail but operation succeeded".to_owned(),
23615                    )],
23616                }),
23617                ResolvedExpected::ErrorAny => Ok(match actual {
23618                    Err(_) => Vec::new(),
23619                    Ok(_) => vec![make_drift_record(
23620                        ComparisonCategory::Value,
23621                        DriftLevel::Critical,
23622                        "dataframe_eval.error",
23623                        "expected dataframe_eval to fail but operation succeeded".to_owned(),
23624                    )],
23625                }),
23626                _ => {
23627                    Err("expected_series or expected_error required for dataframe_eval".to_owned())
23628                }
23629            }
23630        }
23631        FixtureOperation::DataFrameQuery => {
23632            let actual = execute_dataframe_query_fixture_operation(fixture, policy, ledger);
23633            match expected {
23634                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
23635                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
23636                    Err(message) if message.contains(&substr) => Vec::new(),
23637                    Err(message) => vec![make_drift_record(
23638                        ComparisonCategory::Value,
23639                        DriftLevel::Critical,
23640                        "dataframe_query.error",
23641                        format!(
23642                            "expected dataframe_query error containing '{substr}', got '{message}'"
23643                        ),
23644                    )],
23645                    Ok(_) => vec![make_drift_record(
23646                        ComparisonCategory::Value,
23647                        DriftLevel::Critical,
23648                        "dataframe_query.error",
23649                        "expected dataframe_query to fail but operation succeeded".to_owned(),
23650                    )],
23651                }),
23652                ResolvedExpected::ErrorAny => Ok(match actual {
23653                    Err(_) => Vec::new(),
23654                    Ok(_) => vec![make_drift_record(
23655                        ComparisonCategory::Value,
23656                        DriftLevel::Critical,
23657                        "dataframe_query.error",
23658                        "expected dataframe_query to fail but operation succeeded".to_owned(),
23659                    )],
23660                }),
23661                _ => {
23662                    Err("expected_frame or expected_error required for dataframe_query".to_owned())
23663                }
23664            }
23665        }
23666        FixtureOperation::DataFrameMerge
23667        | FixtureOperation::DataFrameMergeIndex
23668        | FixtureOperation::DataFrameMergeAsof
23669        | FixtureOperation::DataFrameMergeOrdered
23670        | FixtureOperation::DataFrameConcat
23671        | FixtureOperation::DataFrameIsNa
23672        | FixtureOperation::DataFrameNotNa
23673        | FixtureOperation::DataFrameIsNull
23674        | FixtureOperation::DataFrameNotNull
23675        | FixtureOperation::DataFrameFillNa
23676        | FixtureOperation::DataFrameDropNa
23677        | FixtureOperation::DataFrameDropNaColumns
23678        | FixtureOperation::DataFrameSetIndex
23679        | FixtureOperation::DataFrameResetIndex
23680        | FixtureOperation::DataFrameInsert
23681        | FixtureOperation::DataFrameAssign
23682        | FixtureOperation::DataFrameRenameColumns
23683        | FixtureOperation::DataFrameReindex
23684        | FixtureOperation::DataFrameReindexColumns
23685        | FixtureOperation::DataFrameDropColumns
23686        | FixtureOperation::DataFrameReplace
23687        | FixtureOperation::DataFrameWhere
23688        | FixtureOperation::DataFrameWhereDf
23689        | FixtureOperation::DataFrameMask
23690        | FixtureOperation::DataFrameMaskDf
23691        | FixtureOperation::DataFrameDropDuplicates
23692        | FixtureOperation::DataFrameExplode
23693        | FixtureOperation::DataFrameSortIndex
23694        | FixtureOperation::DataFrameSortValues
23695        | FixtureOperation::DataFrameNlargest
23696        | FixtureOperation::DataFrameNsmallest
23697        | FixtureOperation::DataFrameDiff
23698        | FixtureOperation::DataFrameShift
23699        | FixtureOperation::DataFramePctChange
23700        | FixtureOperation::DataFrameCumsum
23701        | FixtureOperation::DataFrameCumprod
23702        | FixtureOperation::DataFrameCummax
23703        | FixtureOperation::DataFrameCummin
23704        | FixtureOperation::DataFrameAstype
23705        | FixtureOperation::DataFrameClip
23706        | FixtureOperation::DataFrameAbs
23707        | FixtureOperation::DataFrameDescribe
23708        | FixtureOperation::DataFrameCorr
23709        | FixtureOperation::DataFrameCov
23710        | FixtureOperation::DataFrameRound
23711        | FixtureOperation::DataFrameBinaryAlias
23712        | FixtureOperation::DataFrameCompare
23713        | FixtureOperation::DataFrameMelt
23714        | FixtureOperation::DataFramePivot
23715        | FixtureOperation::DataFramePivotTable
23716        | FixtureOperation::DataFrameStack
23717        | FixtureOperation::DataFrameTranspose
23718        | FixtureOperation::DataFrameCrosstab
23719        | FixtureOperation::DataFrameCrosstabNormalize
23720        | FixtureOperation::DataFrameGetDummies
23721        | FixtureOperation::SeriesUnstack
23722        | FixtureOperation::SeriesStrGetDummies
23723        | FixtureOperation::DataFrameGroupByRollingMean
23724        | FixtureOperation::DataFrameGroupByRollingSum
23725        | FixtureOperation::DataFrameGroupByRollingMin
23726        | FixtureOperation::DataFrameGroupByRollingMax
23727        | FixtureOperation::DataFrameGroupByRollingCount
23728        | FixtureOperation::DataFrameGroupByRollingStd
23729        | FixtureOperation::DataFrameGroupByRollingVar
23730        | FixtureOperation::DataFrameGroupByResampleMin
23731        | FixtureOperation::DataFrameGroupByResampleMax
23732        | FixtureOperation::DataFrameGroupByResampleCount
23733        | FixtureOperation::DataFrameGroupByResampleFirst
23734        | FixtureOperation::DataFrameGroupByResampleLast
23735        | FixtureOperation::DataFrameFilter
23736        | FixtureOperation::DataFrameCombineFirst => {
23737            let actual = match fixture.operation {
23738                FixtureOperation::DataFrameGroupByRollingMean
23739                | FixtureOperation::DataFrameGroupByRollingSum
23740                | FixtureOperation::DataFrameGroupByRollingMin
23741                | FixtureOperation::DataFrameGroupByRollingMax
23742                | FixtureOperation::DataFrameGroupByRollingCount => {
23743                    execute_dataframe_groupby_rolling_fixture_operation(fixture)
23744                }
23745                FixtureOperation::DataFrameGroupByResampleMin
23746                | FixtureOperation::DataFrameGroupByResampleMax
23747                | FixtureOperation::DataFrameGroupByResampleCount
23748                | FixtureOperation::DataFrameGroupByResampleFirst
23749                | FixtureOperation::DataFrameGroupByResampleLast => {
23750                    execute_dataframe_groupby_resample_fixture_operation(fixture)
23751                }
23752                _ => execute_dataframe_fixture_operation(fixture),
23753            };
23754            match expected {
23755                ResolvedExpected::Frame(frame) => Ok(diff_dataframe(&actual?, &frame)),
23756                ResolvedExpected::ErrorContains(substr) => Ok(match actual {
23757                    Err(message) if message.contains(&substr) => Vec::new(),
23758                    Err(message) => vec![make_drift_record(
23759                        ComparisonCategory::Value,
23760                        DriftLevel::Critical,
23761                        format!("{:?}.error", fixture.operation),
23762                        format!(
23763                            "expected {:?} error containing '{substr}', got '{message}'",
23764                            fixture.operation
23765                        ),
23766                    )],
23767                    Ok(_) => vec![make_drift_record(
23768                        ComparisonCategory::Value,
23769                        DriftLevel::Critical,
23770                        format!("{:?}.error", fixture.operation),
23771                        format!(
23772                            "expected {:?} to fail but operation succeeded",
23773                            fixture.operation
23774                        ),
23775                    )],
23776                }),
23777                ResolvedExpected::ErrorAny => Ok(match actual {
23778                    Err(_) => Vec::new(),
23779                    Ok(_) => vec![make_drift_record(
23780                        ComparisonCategory::Value,
23781                        DriftLevel::Critical,
23782                        format!("{:?}.error", fixture.operation),
23783                        format!(
23784                            "expected {:?} to fail but operation succeeded",
23785                            fixture.operation
23786                        ),
23787                    )],
23788                }),
23789                _ => Err(format!(
23790                    "expected_frame or expected_error required for {:?}",
23791                    fixture.operation
23792                )),
23793            }
23794        }
23795        FixtureOperation::GroupByMean
23796        | FixtureOperation::GroupByCount
23797        | FixtureOperation::GroupByMin
23798        | FixtureOperation::GroupByMax
23799        | FixtureOperation::GroupByFirst
23800        | FixtureOperation::GroupByLast
23801        | FixtureOperation::GroupByStd
23802        | FixtureOperation::GroupByVar
23803        | FixtureOperation::GroupByMedian => {
23804            let actual =
23805                execute_groupby_fixture_operation(fixture, fixture.operation, policy, ledger)?;
23806            let op_name = format!("{:?}", fixture.operation).to_lowercase();
23807            let expected = match expected {
23808                ResolvedExpected::Series(s) => s,
23809                _ => return Err(format!("expected_series required for {op_name}")),
23810            };
23811            Ok(diff_series(&actual, &expected))
23812        }
23813        FixtureOperation::SeriesRollingMean
23814        | FixtureOperation::SeriesRollingSum
23815        | FixtureOperation::SeriesRollingStd
23816        | FixtureOperation::SeriesRollingMin
23817        | FixtureOperation::SeriesRollingMax
23818        | FixtureOperation::SeriesRollingVar
23819        | FixtureOperation::SeriesRollingCount
23820        | FixtureOperation::SeriesExpandingCount
23821        | FixtureOperation::SeriesExpandingQuantile
23822        | FixtureOperation::SeriesExpandingSum
23823        | FixtureOperation::SeriesExpandingMean
23824        | FixtureOperation::SeriesExpandingMin
23825        | FixtureOperation::SeriesExpandingMax
23826        | FixtureOperation::SeriesExpandingStd
23827        | FixtureOperation::SeriesExpandingVar
23828        | FixtureOperation::SeriesEwmMean
23829        | FixtureOperation::SeriesResampleSum
23830        | FixtureOperation::SeriesResampleMean
23831        | FixtureOperation::SeriesResampleCount
23832        | FixtureOperation::SeriesResampleAsfreq
23833        | FixtureOperation::SeriesResampleFfill
23834        | FixtureOperation::SeriesResampleBfill => {
23835            let actual = execute_series_window_fixture_operation(fixture, policy, ledger)?;
23836            let expected = match expected {
23837                ResolvedExpected::Series(s) => s,
23838                _ => {
23839                    return Err(format!(
23840                        "expected_series required for {:?}",
23841                        fixture.operation
23842                    ));
23843                }
23844            };
23845            Ok(diff_series(&actual, &expected))
23846        }
23847        FixtureOperation::DataFrameRollingMean
23848        | FixtureOperation::DataFrameResampleSum
23849        | FixtureOperation::DataFrameResampleMean => {
23850            let actual = execute_dataframe_window_fixture_operation(fixture, policy, ledger)?;
23851            let expected = match expected {
23852                ResolvedExpected::Frame(f) => f,
23853                _ => {
23854                    return Err(format!(
23855                        "expected_frame required for {:?}",
23856                        fixture.operation
23857                    ));
23858                }
23859            };
23860            Ok(diff_dataframe(&actual, &expected))
23861        }
23862    }
23863}
23864
23865fn diff_scalar(actual: &Scalar, expected: &Scalar, name: &str) -> Vec<DriftRecord> {
23866    if actual.semantic_eq(expected) {
23867        Vec::new()
23868    } else {
23869        vec![make_drift_record(
23870            ComparisonCategory::Value,
23871            DriftLevel::Critical,
23872            format!("{name}.scalar"),
23873            format!("scalar mismatch: actual={actual:?}, expected={expected:?}"),
23874        )]
23875    }
23876}
23877
23878fn diff_values(actual: &[Scalar], expected: &[Scalar], name: &str) -> Vec<DriftRecord> {
23879    let mut drifts = Vec::new();
23880    if actual.len() != expected.len() {
23881        drifts.push(make_drift_record(
23882            ComparisonCategory::Shape,
23883            DriftLevel::Critical,
23884            format!("{name}.len"),
23885            format!(
23886                "length mismatch: actual={}, expected={}",
23887                actual.len(),
23888                expected.len()
23889            ),
23890        ));
23891        return drifts;
23892    }
23893    for (i, (a, e)) in actual.iter().zip(expected.iter()).enumerate() {
23894        if !a.semantic_eq(e) {
23895            drifts.push(make_drift_record(
23896                ComparisonCategory::Value,
23897                DriftLevel::Critical,
23898                format!("{name}[{i}]"),
23899                format!("value mismatch: actual={a:?}, expected={e:?}"),
23900            ));
23901        }
23902    }
23903    drifts
23904}
23905
23906fn diff_string(actual: &str, expected: &str, name: &str) -> Vec<DriftRecord> {
23907    if actual == expected {
23908        Vec::new()
23909    } else {
23910        vec![make_drift_record(
23911            ComparisonCategory::Type,
23912            DriftLevel::Critical,
23913            format!("{name}.value"),
23914            format!("string mismatch: actual={actual:?}, expected={expected:?}"),
23915        )]
23916    }
23917}
23918
23919fn diff_series(actual: &Series, expected: &FixtureExpectedSeries) -> Vec<DriftRecord> {
23920    let mut drifts = Vec::new();
23921
23922    if actual.index().labels() != expected.index {
23923        drifts.push(make_drift_record(
23924            ComparisonCategory::Index,
23925            DriftLevel::Critical,
23926            "series.index",
23927            format!(
23928                "index mismatch: actual={:?}, expected={:?}",
23929                actual.index().labels(),
23930                expected.index
23931            ),
23932        ));
23933    }
23934
23935    if actual.values().len() != expected.values.len() {
23936        drifts.push(make_drift_record(
23937            ComparisonCategory::Shape,
23938            DriftLevel::Critical,
23939            "series.values.len",
23940            format!(
23941                "length mismatch: actual={}, expected={}",
23942                actual.values().len(),
23943                expected.values.len()
23944            ),
23945        ));
23946        return drifts;
23947    }
23948
23949    diff_value_vectors(
23950        actual.values(),
23951        &expected.values,
23952        "series.values",
23953        &mut drifts,
23954    );
23955    drifts
23956}
23957
23958fn diff_dataframe(actual: &DataFrame, expected: &FixtureExpectedDataFrame) -> Vec<DriftRecord> {
23959    let mut drifts = Vec::new();
23960
23961    if actual.index().labels() != expected.index {
23962        drifts.push(make_drift_record(
23963            ComparisonCategory::Index,
23964            DriftLevel::Critical,
23965            "dataframe.index",
23966            format!(
23967                "index mismatch: actual={:?}, expected={:?}",
23968                actual.index().labels(),
23969                expected.index
23970            ),
23971        ));
23972    }
23973
23974    let actual_row_multiindex = actual
23975        .row_multiindex()
23976        .map(multiindex_to_fixture)
23977        .transpose();
23978    match actual_row_multiindex {
23979        Ok(actual_row_multiindex) => {
23980            if actual_row_multiindex != expected.row_multiindex {
23981                drifts.push(make_drift_record(
23982                    ComparisonCategory::Index,
23983                    DriftLevel::Critical,
23984                    "dataframe.row_multiindex",
23985                    format!(
23986                        "row_multiindex mismatch: actual={actual_row_multiindex:?}, expected={:?}",
23987                        expected.row_multiindex
23988                    ),
23989                ));
23990            }
23991        }
23992        Err(message) => drifts.push(make_drift_record(
23993            ComparisonCategory::Index,
23994            DriftLevel::Critical,
23995            "dataframe.row_multiindex",
23996            format!("failed to serialize actual row_multiindex: {message}"),
23997        )),
23998    }
23999
24000    let actual_names = actual
24001        .column_names()
24002        .into_iter()
24003        .map(ToOwned::to_owned)
24004        .collect::<Vec<_>>();
24005    if let Some(expected_order) = expected.column_order.as_ref() {
24006        if &actual_names != expected_order {
24007            drifts.push(make_drift_record(
24008                ComparisonCategory::Shape,
24009                DriftLevel::Critical,
24010                "dataframe.columns",
24011                format!("column mismatch: actual={actual_names:?}, expected={expected_order:?}"),
24012            ));
24013        }
24014    } else {
24015        let mut expected_names = expected.columns.keys().cloned().collect::<Vec<_>>();
24016        expected_names.sort();
24017        let mut actual_sorted = actual_names.clone();
24018        actual_sorted.sort();
24019        if actual_sorted != expected_names {
24020            drifts.push(make_drift_record(
24021                ComparisonCategory::Shape,
24022                DriftLevel::Critical,
24023                "dataframe.columns",
24024                format!(
24025                    "column set mismatch: actual={actual_names:?}, expected={expected_names:?}"
24026                ),
24027            ));
24028        }
24029    }
24030
24031    for (name, expected_values) in &expected.columns {
24032        let Some(column) = actual.column(name) else {
24033            drifts.push(make_drift_record(
24034                ComparisonCategory::Shape,
24035                DriftLevel::Critical,
24036                format!("dataframe.columns.{name}"),
24037                "column missing in actual result".to_owned(),
24038            ));
24039            continue;
24040        };
24041
24042        let actual_values = column.values();
24043        if actual_values.len() != expected_values.len() {
24044            drifts.push(make_drift_record(
24045                ComparisonCategory::Shape,
24046                DriftLevel::Critical,
24047                format!("dataframe.columns.{name}.len"),
24048                format!(
24049                    "length mismatch: actual={}, expected={}",
24050                    actual_values.len(),
24051                    expected_values.len()
24052                ),
24053            ));
24054            continue;
24055        }
24056
24057        diff_value_vectors(
24058            actual_values,
24059            expected_values,
24060            &format!("dataframe.columns.{name}.values"),
24061            &mut drifts,
24062        );
24063    }
24064
24065    drifts
24066}
24067
24068fn diff_join(actual: &fp_join::JoinedSeries, expected: &FixtureExpectedJoin) -> Vec<DriftRecord> {
24069    let mut drifts = Vec::new();
24070
24071    if actual.index.labels() != expected.index {
24072        drifts.push(make_drift_record(
24073            ComparisonCategory::Index,
24074            DriftLevel::Critical,
24075            "join.index",
24076            format!(
24077                "index mismatch: actual={:?}, expected={:?}",
24078                actual.index.labels(),
24079                expected.index
24080            ),
24081        ));
24082    }
24083
24084    if actual.left_values.values().len() != expected.left_values.len() {
24085        drifts.push(make_drift_record(
24086            ComparisonCategory::Shape,
24087            DriftLevel::Critical,
24088            "join.left_values.len",
24089            format!(
24090                "left length mismatch: actual={}, expected={}",
24091                actual.left_values.values().len(),
24092                expected.left_values.len()
24093            ),
24094        ));
24095    } else {
24096        diff_value_vectors(
24097            actual.left_values.values(),
24098            &expected.left_values,
24099            "join.left_values",
24100            &mut drifts,
24101        );
24102    }
24103
24104    if actual.right_values.values().len() != expected.right_values.len() {
24105        drifts.push(make_drift_record(
24106            ComparisonCategory::Shape,
24107            DriftLevel::Critical,
24108            "join.right_values.len",
24109            format!(
24110                "right length mismatch: actual={}, expected={}",
24111                actual.right_values.values().len(),
24112                expected.right_values.len()
24113            ),
24114        ));
24115    } else {
24116        diff_value_vectors(
24117            actual.right_values.values(),
24118            &expected.right_values,
24119            "join.right_values",
24120            &mut drifts,
24121        );
24122    }
24123
24124    drifts
24125}
24126
24127fn diff_alignment(actual: &AlignmentPlan, expected: &FixtureExpectedAlignment) -> Vec<DriftRecord> {
24128    let mut drifts = Vec::new();
24129
24130    if actual.union_index.labels() != expected.union_index {
24131        drifts.push(make_drift_record(
24132            ComparisonCategory::Index,
24133            DriftLevel::Critical,
24134            "alignment.union_index",
24135            format!(
24136                "union_index mismatch: actual={:?}, expected={:?}",
24137                actual.union_index.labels(),
24138                expected.union_index
24139            ),
24140        ));
24141    }
24142
24143    if actual.left_positions != expected.left_positions {
24144        drifts.push(make_drift_record(
24145            ComparisonCategory::Value,
24146            DriftLevel::Critical,
24147            "alignment.left_positions",
24148            format!(
24149                "left_positions mismatch: actual={:?}, expected={:?}",
24150                actual.left_positions, expected.left_positions
24151            ),
24152        ));
24153    }
24154
24155    if actual.right_positions != expected.right_positions {
24156        drifts.push(make_drift_record(
24157            ComparisonCategory::Value,
24158            DriftLevel::Critical,
24159            "alignment.right_positions",
24160            format!(
24161                "right_positions mismatch: actual={:?}, expected={:?}",
24162                actual.right_positions, expected.right_positions
24163            ),
24164        ));
24165    }
24166
24167    drifts
24168}
24169
24170fn diff_bool(actual: bool, expected: bool, name: &str) -> Vec<DriftRecord> {
24171    if actual == expected {
24172        Vec::new()
24173    } else {
24174        vec![make_drift_record(
24175            ComparisonCategory::Value,
24176            DriftLevel::Critical,
24177            name,
24178            format!("boolean mismatch: actual={actual}, expected={expected}"),
24179        )]
24180    }
24181}
24182
24183fn diff_positions(actual: &[Option<usize>], expected: &[Option<usize>]) -> Vec<DriftRecord> {
24184    if actual == expected {
24185        Vec::new()
24186    } else {
24187        vec![make_drift_record(
24188            ComparisonCategory::Value,
24189            DriftLevel::Critical,
24190            "first_positions",
24191            format!("positions mismatch: actual={actual:?}, expected={expected:?}"),
24192        )]
24193    }
24194}
24195
24196fn diff_value_vectors(
24197    actual: &[Scalar],
24198    expected: &[Scalar],
24199    prefix: &str,
24200    drifts: &mut Vec<DriftRecord>,
24201) {
24202    for (idx, (a, e)) in actual.iter().zip(expected.iter()).enumerate() {
24203        let equal = a.semantic_eq(e) || (a.is_missing() && e.is_missing());
24204        if !equal {
24205            let location = format!("{prefix}[{idx}]");
24206            if a.is_missing() != e.is_missing() {
24207                drifts.push(make_drift_record(
24208                    ComparisonCategory::Nullness,
24209                    DriftLevel::Critical,
24210                    location,
24211                    format!("nullness mismatch: actual={a:?}, expected={e:?}"),
24212                ));
24213            } else {
24214                let level = classify_value_drift(a, e);
24215                drifts.push(make_drift_record(
24216                    ComparisonCategory::Value,
24217                    level,
24218                    location,
24219                    format!("value mismatch: actual={a:?}, expected={e:?}"),
24220                ));
24221            }
24222        }
24223    }
24224}
24225
24226fn classify_value_drift(actual: &Scalar, expected: &Scalar) -> DriftLevel {
24227    match (actual, expected) {
24228        (Scalar::Float64(a), Scalar::Float64(e)) => {
24229            let max_abs = a.abs().max(e.abs()).max(1.0);
24230            let rel_diff = (a - e).abs() / max_abs;
24231            if rel_diff < 1e-10 {
24232                DriftLevel::NonCritical
24233            } else {
24234                DriftLevel::Critical
24235            }
24236        }
24237        _ => DriftLevel::Critical,
24238    }
24239}
24240
24241fn summarize_drift(results: &[DifferentialResult]) -> DriftSummary {
24242    let mut total = 0usize;
24243    let mut critical = 0usize;
24244    let mut non_critical = 0usize;
24245    let mut informational = 0usize;
24246    let mut cat_counts = BTreeMap::<ComparisonCategory, usize>::new();
24247
24248    for result in results {
24249        for drift in &result.drift_records {
24250            total += 1;
24251            match drift.level {
24252                DriftLevel::Critical => critical += 1,
24253                DriftLevel::NonCritical => non_critical += 1,
24254                DriftLevel::Informational => informational += 1,
24255            }
24256            *cat_counts.entry(drift.category).or_default() += 1;
24257        }
24258    }
24259
24260    let categories = cat_counts
24261        .into_iter()
24262        .map(|(category, count)| CategoryCount { category, count })
24263        .collect();
24264
24265    DriftSummary {
24266        total_drift_records: total,
24267        critical_count: critical,
24268        non_critical_count: non_critical,
24269        informational_count: informational,
24270        categories,
24271    }
24272}
24273
24274fn percent(failed: usize, total: usize) -> f64 {
24275    if total == 0 {
24276        0.0
24277    } else {
24278        (failed as f64 / total as f64) * 100.0
24279    }
24280}
24281
24282fn hash_bytes(bytes: &[u8]) -> String {
24283    hex_encode(Sha256::digest(bytes).as_slice())
24284}
24285
24286fn hex_encode(bytes: &[u8]) -> String {
24287    let mut out = String::with_capacity(bytes.len() * 2);
24288    for byte in bytes {
24289        out.push(hex_digit(byte >> 4));
24290        out.push(hex_digit(byte & 0x0f));
24291    }
24292    out
24293}
24294
24295fn hex_decode(value: &str) -> Result<Vec<u8>, HarnessError> {
24296    if !value.len().is_multiple_of(2) {
24297        return Err(HarnessError::RaptorQ(format!(
24298            "invalid hex length {}",
24299            value.len()
24300        )));
24301    }
24302    let bytes = value.as_bytes();
24303    let mut out = Vec::with_capacity(value.len() / 2);
24304    for idx in (0..bytes.len()).step_by(2) {
24305        let high = hex_value(bytes[idx])?;
24306        let low = hex_value(bytes[idx + 1])?;
24307        out.push((high << 4) | low);
24308    }
24309    Ok(out)
24310}
24311
24312fn hex_digit(value: u8) -> char {
24313    match value {
24314        0..=9 => (b'0' + value) as char,
24315        10..=15 => (b'a' + (value - 10)) as char,
24316        _ => unreachable!("nibble out of range"),
24317    }
24318}
24319
24320fn hex_value(byte: u8) -> Result<u8, HarnessError> {
24321    match byte {
24322        b'0'..=b'9' => Ok(byte - b'0'),
24323        b'a'..=b'f' => Ok(byte - b'a' + 10),
24324        b'A'..=b'F' => Ok(byte - b'A' + 10),
24325        _ => Err(HarnessError::RaptorQ(format!(
24326            "invalid hex character: {}",
24327            byte as char
24328        ))),
24329    }
24330}
24331
24332fn now_unix_ms() -> u64 {
24333    SystemTime::now()
24334        .duration_since(UNIX_EPOCH)
24335        .map(|duration| duration.as_millis() as u64)
24336        .unwrap_or(0)
24337}
24338
24339// === E2E Orchestrator + Replay/Forensics Logging (bd-2gi.6) ===
24340
24341/// Forensic event kinds emitted during E2E orchestration.
24342#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24343#[serde(rename_all = "snake_case", tag = "kind")]
24344pub enum ForensicEventKind {
24345    SuiteStart {
24346        suite: String,
24347        packet_filter: Option<String>,
24348    },
24349    SuiteEnd {
24350        suite: String,
24351        total_fixtures: usize,
24352        passed: usize,
24353        failed: usize,
24354    },
24355    PacketStart {
24356        packet_id: String,
24357    },
24358    PacketEnd {
24359        packet_id: String,
24360        fixtures: usize,
24361        passed: usize,
24362        failed: usize,
24363        gate_pass: bool,
24364    },
24365    CaseStart {
24366        scenario_id: String,
24367        packet_id: String,
24368        case_id: String,
24369        trace_id: String,
24370        step_id: String,
24371        seed: u64,
24372        assertion_path: String,
24373        replay_cmd: String,
24374        operation: FixtureOperation,
24375        mode: RuntimeMode,
24376    },
24377    CaseEnd {
24378        scenario_id: String,
24379        packet_id: String,
24380        case_id: String,
24381        trace_id: String,
24382        step_id: String,
24383        seed: u64,
24384        assertion_path: String,
24385        result: String,
24386        replay_cmd: String,
24387        decision_action: String,
24388        replay_key: String,
24389        mismatch_class: Option<String>,
24390        status: CaseStatus,
24391        evidence_records: usize,
24392        elapsed_us: u64,
24393    },
24394    CompatClosureCase {
24395        ts_utc: u64,
24396        suite_id: String,
24397        test_id: String,
24398        api_surface_id: String,
24399        packet_id: String,
24400        mode: RuntimeMode,
24401        seed: u64,
24402        input_digest: String,
24403        output_digest: String,
24404        env_fingerprint: String,
24405        artifact_refs: Vec<String>,
24406        duration_ms: u64,
24407        outcome: String,
24408        reason_code: String,
24409    },
24410    ArtifactWritten {
24411        packet_id: String,
24412        artifact_kind: String,
24413        path: String,
24414    },
24415    GateEvaluated {
24416        packet_id: String,
24417        pass: bool,
24418        reasons: Vec<String>,
24419    },
24420    DriftHistoryAppended {
24421        path: String,
24422        entries: usize,
24423    },
24424    Error {
24425        phase: String,
24426        message: String,
24427    },
24428}
24429
24430/// A single forensic log entry with timestamp.
24431#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
24432pub struct ForensicEvent {
24433    pub ts_unix_ms: u64,
24434    pub event: ForensicEventKind,
24435}
24436
24437/// Accumulator for forensic events during an E2E run.
24438#[derive(Debug, Clone, Default, Serialize, Deserialize)]
24439pub struct ForensicLog {
24440    pub events: Vec<ForensicEvent>,
24441}
24442
24443impl ForensicLog {
24444    #[must_use]
24445    pub fn new() -> Self {
24446        Self { events: Vec::new() }
24447    }
24448
24449    pub fn record(&mut self, event: ForensicEventKind) {
24450        self.events.push(ForensicEvent {
24451            ts_unix_ms: now_unix_ms(),
24452            event,
24453        });
24454    }
24455
24456    /// Write the forensic log as JSONL to the given path.
24457    pub fn write_jsonl(&self, path: &Path) -> Result<(), HarnessError> {
24458        let mut file = fs::File::create(path).map_err(HarnessError::Io)?;
24459        for entry in &self.events {
24460            let line = serde_json::to_string(entry).map_err(HarnessError::Json)?;
24461            writeln!(file, "{line}").map_err(HarnessError::Io)?;
24462        }
24463        Ok(())
24464    }
24465
24466    #[must_use]
24467    pub fn len(&self) -> usize {
24468        self.events.len()
24469    }
24470
24471    #[must_use]
24472    pub fn is_empty(&self) -> bool {
24473        self.events.is_empty()
24474    }
24475}
24476
24477/// Lifecycle hooks for E2E orchestration. Default implementations are no-ops.
24478pub trait LifecycleHooks {
24479    fn before_suite(&mut self, _suite: &str, _packet_filter: &Option<String>) {}
24480    fn after_suite(&mut self, _report: &[PacketParityReport]) {}
24481    fn before_packet(&mut self, _packet_id: &str) {}
24482    fn after_packet(&mut self, _report: &PacketParityReport, _gate_pass: bool) {}
24483    fn before_case(&mut self, _fixture: &PacketFixture) {}
24484    fn after_case(&mut self, _result: &CaseResult) {}
24485}
24486
24487/// Default no-op hooks.
24488pub struct NoopHooks;
24489impl LifecycleHooks for NoopHooks {}
24490
24491/// Configuration for the E2E orchestrator.
24492#[derive(Debug, Clone)]
24493pub struct E2eConfig {
24494    pub harness: HarnessConfig,
24495    pub options: SuiteOptions,
24496    pub write_artifacts: bool,
24497    pub enforce_gates: bool,
24498    pub append_drift_history: bool,
24499    pub forensic_log_path: Option<PathBuf>,
24500}
24501
24502impl E2eConfig {
24503    #[must_use]
24504    pub fn default_all_phases() -> Self {
24505        Self {
24506            harness: HarnessConfig::default_paths(),
24507            options: SuiteOptions::default(),
24508            write_artifacts: true,
24509            enforce_gates: true,
24510            append_drift_history: true,
24511            forensic_log_path: None,
24512        }
24513    }
24514}
24515
24516/// Final result of an E2E orchestration run.
24517#[derive(Debug, Clone, Serialize, Deserialize)]
24518pub struct E2eReport {
24519    pub suite: String,
24520    pub packet_reports: Vec<PacketParityReport>,
24521    pub artifacts_written: Vec<WrittenPacketArtifacts>,
24522    pub gate_results: Vec<PacketGateResult>,
24523    pub gates_pass: bool,
24524    pub drift_history_path: Option<String>,
24525    pub forensic_log: ForensicLog,
24526    pub total_fixtures: usize,
24527    pub total_passed: usize,
24528    pub total_failed: usize,
24529}
24530
24531impl E2eReport {
24532    #[must_use]
24533    pub fn is_green(&self) -> bool {
24534        self.total_failed == 0 && self.total_fixtures > 0 && self.gates_pass
24535    }
24536}
24537
24538#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
24539#[serde(rename_all = "snake_case")]
24540pub enum CompatClosureScenarioKind {
24541    GoldenJourney,
24542    Regression,
24543    FailureInjection,
24544}
24545
24546#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24547pub struct CompatClosureE2eScenarioStep {
24548    pub scenario_id: String,
24549    pub packet_id: String,
24550    pub mode: RuntimeMode,
24551    pub trace_id: String,
24552    pub step_id: String,
24553    pub kind: CompatClosureScenarioKind,
24554    pub command_or_api: String,
24555    pub input_ref: String,
24556    pub output_ref: String,
24557    pub duration_ms: u64,
24558    pub retry_count: u32,
24559    pub outcome: String,
24560    pub reason_code: String,
24561    pub replay_cmd: String,
24562}
24563
24564#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24565pub struct CompatClosureE2eScenarioReport {
24566    pub suite_id: String,
24567    pub scenario_count: usize,
24568    pub pass_count: usize,
24569    pub fail_count: usize,
24570    pub steps: Vec<CompatClosureE2eScenarioStep>,
24571}
24572
24573#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
24574struct CompatClosureScenarioBuildStats {
24575    trace_metadata_index_nodes: usize,
24576    trace_metadata_lookup_steps: usize,
24577}
24578
24579#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24580struct CompatClosureTraceMetadata {
24581    operation: FixtureOperation,
24582    mode: RuntimeMode,
24583}
24584
24585fn append_fault_injection_steps(
24586    steps: &mut Vec<CompatClosureE2eScenarioStep>,
24587    fault_reports: &[FaultInjectionValidationReport],
24588) {
24589    for report in fault_reports {
24590        for entry in &report.entries {
24591            let scenario_id = format!(
24592                "fault-injection:{}:{}:{}",
24593                entry.packet_id,
24594                entry.case_id,
24595                runtime_mode_slug(entry.mode)
24596            );
24597            let outcome = match entry.classification {
24598                FaultInjectionClassification::StrictViolation => "fail",
24599                FaultInjectionClassification::HardenedAllowlisted => "allowlisted",
24600            };
24601            steps.push(CompatClosureE2eScenarioStep {
24602                scenario_id,
24603                packet_id: entry.packet_id.clone(),
24604                mode: entry.mode,
24605                trace_id: entry.trace_id.clone(),
24606                step_id: "fault-injected".to_owned(),
24607                kind: CompatClosureScenarioKind::FailureInjection,
24608                command_or_api: "fault_injection".to_owned(),
24609                input_ref: format!("fixture://{}/{}", entry.packet_id, entry.case_id),
24610                output_ref: format!(
24611                    "artifact://{}/fault_injection_validation.json#{}",
24612                    entry.packet_id, entry.replay_key
24613                ),
24614                duration_ms: 1,
24615                retry_count: 0,
24616                outcome: outcome.to_owned(),
24617                reason_code: entry.mismatch_class.clone(),
24618                replay_cmd: "cargo test -p fp-conformance --lib fault_injection_validation_classifies_strict_vs_hardened -- --nocapture".to_owned(),
24619            });
24620        }
24621    }
24622}
24623
24624fn finalize_compat_closure_e2e_scenario_report(
24625    mut steps: Vec<CompatClosureE2eScenarioStep>,
24626) -> CompatClosureE2eScenarioReport {
24627    steps.sort_by(|a, b| {
24628        (
24629            a.scenario_id.as_str(),
24630            a.step_id.as_str(),
24631            runtime_mode_slug(a.mode),
24632        )
24633            .cmp(&(
24634                b.scenario_id.as_str(),
24635                b.step_id.as_str(),
24636                runtime_mode_slug(b.mode),
24637            ))
24638    });
24639
24640    let pass_count = steps
24641        .iter()
24642        .filter(|step| step.outcome == "pass" || step.outcome == "allowlisted")
24643        .count();
24644    let fail_count = steps.len().saturating_sub(pass_count);
24645    let scenario_count = steps
24646        .iter()
24647        .map(|step| step.scenario_id.as_str())
24648        .collect::<BTreeSet<_>>()
24649        .len();
24650
24651    CompatClosureE2eScenarioReport {
24652        suite_id: "COMPAT-CLOSURE-G".to_owned(),
24653        scenario_count,
24654        pass_count,
24655        fail_count,
24656        steps,
24657    }
24658}
24659
24660#[cfg(test)]
24661fn build_compat_closure_e2e_scenario_report_baseline_with_stats(
24662    e2e: &E2eReport,
24663    fault_reports: &[FaultInjectionValidationReport],
24664) -> (
24665    CompatClosureE2eScenarioReport,
24666    CompatClosureScenarioBuildStats,
24667) {
24668    let mut operation_by_trace = BTreeMap::<String, FixtureOperation>::new();
24669    let mut mode_by_trace = BTreeMap::<String, RuntimeMode>::new();
24670    let mut trace_metadata_index_nodes = 0_usize;
24671
24672    for event in &e2e.forensic_log.events {
24673        if let ForensicEventKind::CaseStart {
24674            trace_id,
24675            operation,
24676            mode,
24677            ..
24678        } = &event.event
24679        {
24680            operation_by_trace.insert(trace_id.clone(), *operation);
24681            mode_by_trace.insert(trace_id.clone(), *mode);
24682            trace_metadata_index_nodes += 2;
24683        }
24684    }
24685
24686    let mut steps = Vec::new();
24687    let mut trace_metadata_lookup_steps = 0_usize;
24688    for event in &e2e.forensic_log.events {
24689        if let ForensicEventKind::CaseEnd {
24690            scenario_id,
24691            packet_id,
24692            trace_id,
24693            step_id,
24694            result,
24695            replay_cmd,
24696            replay_key,
24697            mismatch_class,
24698            elapsed_us,
24699            ..
24700        } = &event.event
24701        {
24702            trace_metadata_lookup_steps += 2;
24703            let mode = mode_by_trace
24704                .get(trace_id)
24705                .copied()
24706                .unwrap_or(RuntimeMode::Strict);
24707            let kind = if result == "pass" {
24708                CompatClosureScenarioKind::GoldenJourney
24709            } else {
24710                CompatClosureScenarioKind::Regression
24711            };
24712            let command_or_api = operation_by_trace
24713                .get(trace_id)
24714                .map(|operation| format!("{operation:?}"))
24715                .unwrap_or_else(|| "unknown_operation".to_owned());
24716            steps.push(CompatClosureE2eScenarioStep {
24717                scenario_id: scenario_id.clone(),
24718                packet_id: packet_id.clone(),
24719                mode,
24720                trace_id: trace_id.clone(),
24721                step_id: step_id.clone(),
24722                kind,
24723                command_or_api,
24724                input_ref: format!(
24725                    "fixture://{packet_id}/{}",
24726                    step_id.trim_start_matches("case:")
24727                ),
24728                output_ref: format!(
24729                    "artifact://{packet_id}/parity_mismatch_corpus.json#{replay_key}"
24730                ),
24731                duration_ms: elapsed_us.saturating_add(999) / 1000,
24732                retry_count: 0,
24733                outcome: result.clone(),
24734                reason_code: mismatch_class.clone().unwrap_or_else(|| "ok".to_owned()),
24735                replay_cmd: replay_cmd.clone(),
24736            });
24737        }
24738    }
24739    append_fault_injection_steps(&mut steps, fault_reports);
24740
24741    let report = finalize_compat_closure_e2e_scenario_report(steps);
24742    let stats = CompatClosureScenarioBuildStats {
24743        trace_metadata_index_nodes,
24744        trace_metadata_lookup_steps,
24745    };
24746    (report, stats)
24747}
24748
24749fn build_compat_closure_e2e_scenario_report_optimized_with_stats(
24750    e2e: &E2eReport,
24751    fault_reports: &[FaultInjectionValidationReport],
24752) -> (
24753    CompatClosureE2eScenarioReport,
24754    CompatClosureScenarioBuildStats,
24755) {
24756    let mut trace_metadata_by_id = HashMap::<String, CompatClosureTraceMetadata>::new();
24757    for event in &e2e.forensic_log.events {
24758        if let ForensicEventKind::CaseStart {
24759            trace_id,
24760            operation,
24761            mode,
24762            ..
24763        } = &event.event
24764        {
24765            trace_metadata_by_id.insert(
24766                trace_id.clone(),
24767                CompatClosureTraceMetadata {
24768                    operation: *operation,
24769                    mode: *mode,
24770                },
24771            );
24772        }
24773    }
24774
24775    let mut steps = Vec::new();
24776    let mut trace_metadata_lookup_steps = 0_usize;
24777    for event in &e2e.forensic_log.events {
24778        if let ForensicEventKind::CaseEnd {
24779            scenario_id,
24780            packet_id,
24781            trace_id,
24782            step_id,
24783            result,
24784            replay_cmd,
24785            replay_key,
24786            mismatch_class,
24787            elapsed_us,
24788            ..
24789        } = &event.event
24790        {
24791            trace_metadata_lookup_steps += 1;
24792            let metadata = trace_metadata_by_id.get(trace_id);
24793            let mode = metadata
24794                .map(|entry| entry.mode)
24795                .unwrap_or(RuntimeMode::Strict);
24796            let kind = if result == "pass" {
24797                CompatClosureScenarioKind::GoldenJourney
24798            } else {
24799                CompatClosureScenarioKind::Regression
24800            };
24801            let command_or_api = metadata
24802                .map(|entry| format!("{:?}", entry.operation))
24803                .unwrap_or_else(|| "unknown_operation".to_owned());
24804            steps.push(CompatClosureE2eScenarioStep {
24805                scenario_id: scenario_id.clone(),
24806                packet_id: packet_id.clone(),
24807                mode,
24808                trace_id: trace_id.clone(),
24809                step_id: step_id.clone(),
24810                kind,
24811                command_or_api,
24812                input_ref: format!(
24813                    "fixture://{packet_id}/{}",
24814                    step_id.trim_start_matches("case:")
24815                ),
24816                output_ref: format!(
24817                    "artifact://{packet_id}/parity_mismatch_corpus.json#{replay_key}"
24818                ),
24819                duration_ms: elapsed_us.saturating_add(999) / 1000,
24820                retry_count: 0,
24821                outcome: result.clone(),
24822                reason_code: mismatch_class.clone().unwrap_or_else(|| "ok".to_owned()),
24823                replay_cmd: replay_cmd.clone(),
24824            });
24825        }
24826    }
24827
24828    append_fault_injection_steps(&mut steps, fault_reports);
24829
24830    let report = finalize_compat_closure_e2e_scenario_report(steps);
24831    let stats = CompatClosureScenarioBuildStats {
24832        trace_metadata_index_nodes: trace_metadata_by_id.len(),
24833        trace_metadata_lookup_steps,
24834    };
24835    (report, stats)
24836}
24837
24838#[must_use]
24839pub fn build_compat_closure_e2e_scenario_report(
24840    e2e: &E2eReport,
24841    fault_reports: &[FaultInjectionValidationReport],
24842) -> CompatClosureE2eScenarioReport {
24843    let (report, _) =
24844        build_compat_closure_e2e_scenario_report_optimized_with_stats(e2e, fault_reports);
24845    report
24846}
24847
24848pub fn write_compat_closure_e2e_scenario_report(
24849    repo_root: &Path,
24850    report: &CompatClosureE2eScenarioReport,
24851) -> Result<PathBuf, HarnessError> {
24852    let packet_id = report
24853        .steps
24854        .iter()
24855        .map(|step| step.packet_id.as_str())
24856        .collect::<BTreeSet<_>>();
24857    let path = if packet_id.len() == 1 {
24858        let only = packet_id
24859            .iter()
24860            .next()
24861            .copied()
24862            .ok_or_else(|| HarnessError::FixtureFormat("missing packet id".to_owned()))?;
24863        repo_root.join(format!(
24864            "artifacts/phase2c/{only}/compat_closure_e2e_scenarios.json"
24865        ))
24866    } else {
24867        repo_root.join("artifacts/phase2c/compat_closure_e2e_scenarios.json")
24868    };
24869
24870    if let Some(parent) = path.parent() {
24871        fs::create_dir_all(parent)?;
24872    }
24873    fs::write(&path, serde_json::to_string_pretty(report)?)?;
24874    Ok(path)
24875}
24876
24877#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24878pub struct CompatClosureMigrationManifest {
24879    pub manifest_version: String,
24880    pub packet_ids: Vec<String>,
24881    pub compatibility_guarantees: Vec<String>,
24882    pub known_deltas: Vec<String>,
24883    pub rollback_paths: Vec<String>,
24884    pub operational_guardrails: Vec<String>,
24885}
24886
24887#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24888pub struct CompatClosureReproducibilityLedger {
24889    pub env_fingerprint: String,
24890    pub lockfile_path: String,
24891    pub replay_commands: Vec<String>,
24892    pub artifact_hashes: BTreeMap<String, String>,
24893}
24894
24895#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24896pub struct CompatClosureFinalEvidencePacket {
24897    pub packet_id: String,
24898    pub parity_green: bool,
24899    pub gate_pass: bool,
24900    pub strict_critical_drift_count: usize,
24901    pub strict_zero_drift: bool,
24902    pub hardened_allowlisted_count: usize,
24903    pub sidecar_integrity_ok: bool,
24904    pub decode_proof_recovered: bool,
24905    pub risk_notes: Vec<String>,
24906}
24907
24908impl CompatClosureFinalEvidencePacket {
24909    #[must_use]
24910    pub fn is_green(&self) -> bool {
24911        self.parity_green
24912            && self.gate_pass
24913            && self.strict_zero_drift
24914            && self.sidecar_integrity_ok
24915            && self.decode_proof_recovered
24916    }
24917}
24918
24919#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24920pub struct CompatClosureFinalEvidencePack {
24921    pub generated_unix_ms: u128,
24922    pub suite_id: String,
24923    pub coverage_report: CompatClosureCoverageReport,
24924    pub strict_zero_drift: bool,
24925    pub hardened_allowlisted_total: usize,
24926    pub packets: Vec<CompatClosureFinalEvidencePacket>,
24927    pub migration_manifest: CompatClosureMigrationManifest,
24928    pub reproducibility_ledger: CompatClosureReproducibilityLedger,
24929    pub benchmark_delta_report_ref: String,
24930    pub invariant_checklist_delta: Vec<String>,
24931    pub risk_note_update: Vec<String>,
24932    pub all_checks_passed: bool,
24933    pub attestation_signature: String,
24934}
24935
24936#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24937pub struct CompatClosureAttestationSummary {
24938    pub claim_id: String,
24939    pub generated_unix_ms: u128,
24940    pub all_checks_passed: bool,
24941    pub coverage_percent: usize,
24942    pub strict_zero_drift: bool,
24943    pub hardened_allowlisted_total: usize,
24944    pub packet_count: usize,
24945    pub attestation_signature: String,
24946    pub evidence_pack_path: String,
24947    pub migration_manifest_path: String,
24948}
24949
24950#[derive(Debug, Clone, PartialEq, Eq)]
24951pub struct CompatClosureFinalEvidencePaths {
24952    pub evidence_pack_path: PathBuf,
24953    pub migration_manifest_path: PathBuf,
24954    pub attestation_summary_path: PathBuf,
24955}
24956
24957fn summarize_strict_and_hardened_drift(report: &DifferentialReport) -> (usize, usize) {
24958    let mut strict_critical_drift_count = 0_usize;
24959    let mut hardened_allowlisted_count = 0_usize;
24960    for result in &report.differential_results {
24961        let has_critical = result
24962            .drift_records
24963            .iter()
24964            .any(|record| matches!(record.level, DriftLevel::Critical));
24965        let has_non_critical_or_info = result.drift_records.iter().any(|record| {
24966            matches!(
24967                record.level,
24968                DriftLevel::NonCritical | DriftLevel::Informational
24969            )
24970        });
24971
24972        match result.mode {
24973            RuntimeMode::Strict => {
24974                if has_critical || matches!(result.status, CaseStatus::Fail) {
24975                    strict_critical_drift_count += 1;
24976                }
24977            }
24978            RuntimeMode::Hardened => {
24979                if !has_critical && has_non_critical_or_info {
24980                    hardened_allowlisted_count += 1;
24981                }
24982            }
24983        }
24984    }
24985    (strict_critical_drift_count, hardened_allowlisted_count)
24986}
24987
24988fn collect_compat_closure_artifact_hashes(
24989    config: &HarnessConfig,
24990    packet_ids: &[String],
24991) -> BTreeMap<String, String> {
24992    let mut hashes = BTreeMap::new();
24993    for packet_id in packet_ids {
24994        let packet_root = config.packet_artifact_root(packet_id);
24995        for file_name in [
24996            "parity_report.json",
24997            "parity_report.raptorq.json",
24998            "parity_report.decode_proof.json",
24999            "parity_gate_result.json",
25000            "parity_mismatch_corpus.json",
25001            "differential_validation_log.jsonl",
25002            "fault_injection_validation.json",
25003            "compat_closure_e2e_scenarios.json",
25004        ] {
25005            let path = packet_root.join(file_name);
25006            if let Ok(bytes) = fs::read(&path) {
25007                hashes.insert(
25008                    relative_to_repo(config, &path),
25009                    format!("sha256:{}", hash_bytes(&bytes)),
25010                );
25011            }
25012        }
25013    }
25014
25015    for shared in [
25016        "artifacts/phase2c/PERFORMANCE_BASELINES.md",
25017        "artifacts/phase2c/COMPAT_CLOSURE_FINAL_EVIDENCE_PACK.md",
25018        "artifacts/phase2c/COMPAT_CLOSURE_TEST_LOGGING_EVIDENCE.md",
25019        "artifacts/phase2c/COMPAT_CLOSURE_DIFFERENTIAL_FAULT_INJECTION_EVIDENCE.md",
25020        "artifacts/phase2c/COMPAT_CLOSURE_E2E_SCENARIO_EVIDENCE.md",
25021        "artifacts/phase2c/COMPAT_CLOSURE_OPTIMIZATION_ISOMORPHISM_EVIDENCE.md",
25022    ] {
25023        let path = config.repo_root.join(shared);
25024        if let Ok(bytes) = fs::read(&path) {
25025            hashes.insert(shared.to_owned(), format!("sha256:{}", hash_bytes(&bytes)));
25026        }
25027    }
25028    hashes
25029}
25030
25031fn build_compat_closure_migration_manifest(
25032    packet_ids: &[String],
25033) -> CompatClosureMigrationManifest {
25034    CompatClosureMigrationManifest {
25035        manifest_version: "1.0.0".to_owned(),
25036        packet_ids: packet_ids.to_vec(),
25037        compatibility_guarantees: vec![
25038            "strict mode enforces fail-closed compatibility boundaries".to_owned(),
25039            "hardened mode divergences remain explicit and bounded via allowlist policy".to_owned(),
25040            "alignment and null/NaN semantics are preserved as pandas-observable contracts"
25041                .to_owned(),
25042        ],
25043        known_deltas: vec![
25044            "live-oracle fallback remains opt-in via --allow-system-pandas-fallback".to_owned(),
25045            "full pandas API closure beyond scoped packets remains tracked in remaining Phase-2C program beads".to_owned(),
25046        ],
25047        rollback_paths: vec![
25048            "re-run packet parity gates with fixture oracle to validate rollback candidate".to_owned(),
25049            "use parity_mismatch_corpus replay keys for one-command reproduction of regressions"
25050                .to_owned(),
25051        ],
25052        operational_guardrails: vec![
25053            "require --require-green for release-path conformance execution".to_owned(),
25054            "block release when sidecar/decode integrity checks fail".to_owned(),
25055            "treat unresolved critical strict-mode drift as release blocker".to_owned(),
25056        ],
25057    }
25058}
25059
25060pub fn build_compat_closure_final_evidence_pack(
25061    config: &HarnessConfig,
25062    packet_reports: &[PacketParityReport],
25063    differential_reports: &[DifferentialReport],
25064    fault_reports: &[FaultInjectionValidationReport],
25065) -> Result<CompatClosureFinalEvidencePack, HarnessError> {
25066    let coverage_report = build_compat_closure_coverage_report(config)?;
25067
25068    let differential_by_packet = differential_reports
25069        .iter()
25070        .filter_map(|report| {
25071            report
25072                .report
25073                .packet_id
25074                .as_ref()
25075                .map(|packet_id| (packet_id.clone(), report))
25076        })
25077        .collect::<BTreeMap<_, _>>();
25078    let fault_by_packet = fault_reports
25079        .iter()
25080        .map(|report| (report.packet_id.clone(), report))
25081        .collect::<BTreeMap<_, _>>();
25082
25083    let mut packet_ids = packet_reports
25084        .iter()
25085        .filter_map(|report| report.packet_id.clone())
25086        .collect::<Vec<_>>();
25087    packet_ids.sort();
25088    packet_ids.dedup();
25089
25090    let mut packets = Vec::new();
25091    let mut strict_zero_drift = true;
25092    let mut hardened_allowlisted_total = 0_usize;
25093    let mut risk_note_update = Vec::new();
25094
25095    for report in packet_reports {
25096        let Some(packet_id) = report.packet_id.as_deref() else {
25097            continue;
25098        };
25099        let gate = evaluate_parity_gate(config, report)?;
25100        let sidecar =
25101            verify_packet_sidecar_integrity(&config.packet_artifact_root(packet_id), packet_id);
25102        let (strict_critical_drift_count, differential_hardened_allowlisted_count) =
25103            differential_by_packet
25104                .get(packet_id)
25105                .map_or((0, 0), |diff| summarize_strict_and_hardened_drift(diff));
25106        let hardened_allowlisted_count = fault_by_packet
25107            .get(packet_id)
25108            .map_or(differential_hardened_allowlisted_count, |fault| {
25109                fault.hardened_allowlisted_count
25110            });
25111
25112        strict_zero_drift &= strict_critical_drift_count == 0;
25113        hardened_allowlisted_total += hardened_allowlisted_count;
25114
25115        let mut risk_notes = Vec::new();
25116        if !report.is_green() {
25117            risk_notes.push(format!(
25118                "parity report not green (passed={} failed={})",
25119                report.passed, report.failed
25120            ));
25121        }
25122        if !gate.pass {
25123            if gate.reasons.is_empty() {
25124                risk_notes.push("parity gate failed without explicit reasons".to_owned());
25125            } else {
25126                risk_notes.push(format!("parity gate failed: {}", gate.reasons.join("; ")));
25127            }
25128        }
25129        if strict_critical_drift_count > 0 {
25130            risk_notes.push(format!(
25131                "strict-mode critical drift count={strict_critical_drift_count}"
25132            ));
25133        }
25134        if hardened_allowlisted_count > 0 {
25135            risk_notes.push(format!(
25136                "hardened allowlisted divergence count={hardened_allowlisted_count}"
25137            ));
25138        }
25139        if !sidecar.is_ok() {
25140            risk_notes.extend(sidecar.errors.clone());
25141        }
25142        risk_notes.sort();
25143        risk_notes.dedup();
25144        risk_note_update.extend(risk_notes.iter().cloned());
25145
25146        packets.push(CompatClosureFinalEvidencePacket {
25147            packet_id: packet_id.to_owned(),
25148            parity_green: report.is_green(),
25149            gate_pass: gate.pass,
25150            strict_critical_drift_count,
25151            strict_zero_drift: strict_critical_drift_count == 0,
25152            hardened_allowlisted_count,
25153            sidecar_integrity_ok: sidecar.is_ok(),
25154            decode_proof_recovered: sidecar.decode_proof_valid,
25155            risk_notes,
25156        });
25157    }
25158
25159    packets.sort_by(|left, right| left.packet_id.cmp(&right.packet_id));
25160    risk_note_update.sort();
25161    risk_note_update.dedup();
25162
25163    let migration_manifest = build_compat_closure_migration_manifest(&packet_ids);
25164    let reproducibility_ledger = CompatClosureReproducibilityLedger {
25165        env_fingerprint: compat_closure_env_fingerprint(config),
25166        lockfile_path: "Cargo.lock".to_owned(),
25167        replay_commands: vec![
25168            "rch exec -- cargo run -p fp-conformance --bin fp-conformance-cli -- --packet-id FP-P2C-001 --write-artifacts --require-green --write-drift-history --write-differential-validation --write-fault-injection --write-e2e-scenarios --write-final-evidence-pack".to_owned(),
25169            "rch exec -- cargo test -p fp-conformance --lib compat_closure_e2e_scenario -- --nocapture".to_owned(),
25170            "rch exec -- cargo check --workspace --all-targets".to_owned(),
25171            "rch exec -- cargo clippy --workspace --all-targets -- -D warnings".to_owned(),
25172        ],
25173        artifact_hashes: collect_compat_closure_artifact_hashes(config, &packet_ids),
25174    };
25175
25176    let generated_unix_ms = SystemTime::now()
25177        .duration_since(UNIX_EPOCH)
25178        .map_or(0, |duration| duration.as_millis());
25179    let all_checks_passed = coverage_report.is_complete()
25180        && strict_zero_drift
25181        && packets
25182            .iter()
25183            .all(CompatClosureFinalEvidencePacket::is_green);
25184
25185    let mut pack = CompatClosureFinalEvidencePack {
25186        generated_unix_ms,
25187        suite_id: "COMPAT-CLOSURE-I".to_owned(),
25188        coverage_report,
25189        strict_zero_drift,
25190        hardened_allowlisted_total,
25191        packets,
25192        migration_manifest,
25193        reproducibility_ledger,
25194        benchmark_delta_report_ref: "artifacts/phase2c/PERFORMANCE_BASELINES.md".to_owned(),
25195        invariant_checklist_delta: vec![
25196            "CC-001..CC-009 closure coverage preserved at 100%".to_owned(),
25197            "strict-mode differential drift budget remains zero".to_owned(),
25198            "RaptorQ sidecar + decode-proof integrity checks remain enforced".to_owned(),
25199        ],
25200        risk_note_update,
25201        all_checks_passed,
25202        attestation_signature: String::new(),
25203    };
25204
25205    let unsigned = serde_json::to_vec(&pack).map_err(HarnessError::Json)?;
25206    pack.attestation_signature = format!("sha256:{}", hash_bytes(&unsigned));
25207    Ok(pack)
25208}
25209
25210pub fn write_compat_closure_final_evidence_pack(
25211    config: &HarnessConfig,
25212    pack: &CompatClosureFinalEvidencePack,
25213) -> Result<CompatClosureFinalEvidencePaths, HarnessError> {
25214    let phase2c_root = config.repo_root.join("artifacts/phase2c");
25215    fs::create_dir_all(&phase2c_root)?;
25216
25217    let evidence_pack_path = phase2c_root.join("compat_closure_final_evidence_pack.json");
25218    let migration_manifest_path = phase2c_root.join("compat_closure_migration_manifest.json");
25219    let attestation_summary_path = phase2c_root.join("compat_closure_attestation_summary.json");
25220
25221    fs::write(&evidence_pack_path, serde_json::to_string_pretty(pack)?)?;
25222    fs::write(
25223        &migration_manifest_path,
25224        serde_json::to_string_pretty(&pack.migration_manifest)?,
25225    )?;
25226
25227    let summary = CompatClosureAttestationSummary {
25228        claim_id: "COMPAT-CLOSURE-I/attestation".to_owned(),
25229        generated_unix_ms: pack.generated_unix_ms,
25230        all_checks_passed: pack.all_checks_passed,
25231        coverage_percent: pack.coverage_report.achieved_percent,
25232        strict_zero_drift: pack.strict_zero_drift,
25233        hardened_allowlisted_total: pack.hardened_allowlisted_total,
25234        packet_count: pack.packets.len(),
25235        attestation_signature: pack.attestation_signature.clone(),
25236        evidence_pack_path: relative_to_repo(config, &evidence_pack_path),
25237        migration_manifest_path: relative_to_repo(config, &migration_manifest_path),
25238    };
25239    fs::write(
25240        &attestation_summary_path,
25241        serde_json::to_string_pretty(&summary)?,
25242    )?;
25243
25244    Ok(CompatClosureFinalEvidencePaths {
25245        evidence_pack_path,
25246        migration_manifest_path,
25247        attestation_summary_path,
25248    })
25249}
25250
25251/// Run the full E2E orchestration pipeline with lifecycle hooks and forensic logging.
25252///
25253/// Phases:
25254/// 1. **Run**: Execute all packet fixtures grouped by packet ID
25255/// 2. **Write**: Persist parity reports, RaptorQ sidecars, decode proofs, gate results, mismatch corpora
25256/// 3. **Enforce**: Validate all reports against parity gate configs
25257/// 4. **History**: Append JSONL rows to drift history ledger
25258///
25259/// Returns `E2eReport` with all phase results and forensic log.
25260pub fn run_e2e_suite(
25261    config: &E2eConfig,
25262    hooks: &mut dyn LifecycleHooks,
25263) -> Result<E2eReport, HarnessError> {
25264    let mut forensic = ForensicLog::new();
25265    let suite_name = config
25266        .options
25267        .packet_filter
25268        .clone()
25269        .unwrap_or("full".to_owned());
25270
25271    // Phase 1: Suite Start
25272    forensic.record(ForensicEventKind::SuiteStart {
25273        suite: suite_name.clone(),
25274        packet_filter: config.options.packet_filter.clone(),
25275    });
25276    hooks.before_suite(&suite_name, &config.options.packet_filter);
25277
25278    // Phase 2: Run fixtures grouped by packet
25279    let grouped_reports = run_packets_grouped(&config.harness, &config.options)?;
25280
25281    // Emit per-packet forensic events
25282    for report in &grouped_reports {
25283        let packet_id = report
25284            .packet_id
25285            .clone()
25286            .unwrap_or_else(|| "unknown".to_owned());
25287        let scenario_id = deterministic_scenario_id(&suite_name, &packet_id);
25288
25289        forensic.record(ForensicEventKind::PacketStart {
25290            packet_id: packet_id.clone(),
25291        });
25292        hooks.before_packet(&packet_id);
25293
25294        // Emit per-case events from the report results
25295        for case_result in &report.results {
25296            let trace_id = if case_result.trace_id.is_empty() {
25297                deterministic_trace_id(
25298                    &case_result.packet_id,
25299                    &case_result.case_id,
25300                    case_result.mode,
25301                )
25302            } else {
25303                case_result.trace_id.clone()
25304            };
25305            let replay_key = if case_result.replay_key.is_empty() {
25306                deterministic_replay_key(
25307                    &case_result.packet_id,
25308                    &case_result.case_id,
25309                    case_result.mode,
25310                )
25311            } else {
25312                case_result.replay_key.clone()
25313            };
25314            let step_id = deterministic_step_id(&case_result.case_id);
25315            let seed = deterministic_seed(
25316                &case_result.packet_id,
25317                &case_result.case_id,
25318                case_result.mode,
25319            );
25320            let assertion_path =
25321                assertion_path_for_case(&case_result.packet_id, &case_result.case_id);
25322            let replay_cmd = replay_cmd_for_case(&case_result.case_id);
25323            forensic.record(ForensicEventKind::CaseStart {
25324                scenario_id: scenario_id.clone(),
25325                packet_id: case_result.packet_id.clone(),
25326                case_id: case_result.case_id.clone(),
25327                trace_id: trace_id.clone(),
25328                step_id: step_id.clone(),
25329                seed,
25330                assertion_path: assertion_path.clone(),
25331                replay_cmd: replay_cmd.clone(),
25332                operation: case_result.operation,
25333                mode: case_result.mode,
25334            });
25335            forensic.record(ForensicEventKind::CaseEnd {
25336                scenario_id: scenario_id.clone(),
25337                packet_id: case_result.packet_id.clone(),
25338                case_id: case_result.case_id.clone(),
25339                trace_id,
25340                step_id,
25341                seed,
25342                assertion_path,
25343                result: result_label_for_status(&case_result.status).to_owned(),
25344                replay_cmd,
25345                decision_action: decision_action_for(&case_result.status).to_owned(),
25346                replay_key,
25347                mismatch_class: case_result.mismatch_class.clone(),
25348                status: case_result.status.clone(),
25349                evidence_records: case_result.evidence_records,
25350                elapsed_us: case_result.elapsed_us.max(1),
25351            });
25352            let compat_case_log = build_compat_closure_case_log(
25353                &config.harness,
25354                COMPAT_CLOSURE_SUITE_ID,
25355                case_result,
25356                now_unix_ms(),
25357            );
25358            forensic.record(ForensicEventKind::CompatClosureCase {
25359                ts_utc: compat_case_log.ts_utc,
25360                suite_id: compat_case_log.suite_id,
25361                test_id: compat_case_log.test_id,
25362                api_surface_id: compat_case_log.api_surface_id,
25363                packet_id: compat_case_log.packet_id,
25364                mode: compat_case_log.mode,
25365                seed: compat_case_log.seed,
25366                input_digest: compat_case_log.input_digest,
25367                output_digest: compat_case_log.output_digest,
25368                env_fingerprint: compat_case_log.env_fingerprint,
25369                artifact_refs: compat_case_log.artifact_refs,
25370                duration_ms: compat_case_log.duration_ms,
25371                outcome: compat_case_log.outcome,
25372                reason_code: compat_case_log.reason_code,
25373            });
25374            hooks.after_case(case_result);
25375        }
25376
25377        // Evaluate gate for this packet
25378        let gate_result = evaluate_parity_gate(&config.harness, report)?;
25379
25380        forensic.record(ForensicEventKind::GateEvaluated {
25381            packet_id: packet_id.clone(),
25382            pass: gate_result.pass,
25383            reasons: gate_result.reasons.clone(),
25384        });
25385
25386        forensic.record(ForensicEventKind::PacketEnd {
25387            packet_id: packet_id.clone(),
25388            fixtures: report.fixture_count,
25389            passed: report.passed,
25390            failed: report.failed,
25391            gate_pass: gate_result.pass,
25392        });
25393        hooks.after_packet(report, gate_result.pass);
25394    }
25395
25396    // Phase 3: Write artifacts
25397    let mut artifacts_written = Vec::new();
25398    if config.write_artifacts {
25399        let written = write_grouped_artifacts(&config.harness, &grouped_reports)?;
25400        for w in &written {
25401            for (kind, path) in [
25402                ("parity_report", &w.parity_report_path),
25403                ("raptorq_sidecar", &w.raptorq_sidecar_path),
25404                ("decode_proof", &w.decode_proof_path),
25405                ("gate_result", &w.gate_result_path),
25406                ("mismatch_corpus", &w.mismatch_corpus_path),
25407            ] {
25408                forensic.record(ForensicEventKind::ArtifactWritten {
25409                    packet_id: w.packet_id.clone(),
25410                    artifact_kind: kind.to_owned(),
25411                    path: path.display().to_string(),
25412                });
25413            }
25414        }
25415        artifacts_written = written;
25416    }
25417
25418    // Phase 4: Evaluate gates
25419    let mut gate_results = Vec::new();
25420    let mut gates_pass = true;
25421    for report in &grouped_reports {
25422        let gate = evaluate_parity_gate(&config.harness, report)?;
25423        if !gate.pass {
25424            gates_pass = false;
25425        }
25426        gate_results.push(gate);
25427    }
25428
25429    // Phase 5: Enforce gates (if configured)
25430    if config.enforce_gates
25431        && let Err(e) = enforce_packet_gates(&config.harness, &grouped_reports)
25432    {
25433        forensic.record(ForensicEventKind::Error {
25434            phase: "gate_enforcement".to_owned(),
25435            message: e.to_string(),
25436        });
25437        // Record but don't fail: the E2eReport captures gates_pass=false
25438    }
25439
25440    // Phase 6: Append drift history
25441    let mut drift_history_path = None;
25442    if config.append_drift_history {
25443        match append_phase2c_drift_history(&config.harness, &grouped_reports) {
25444            Ok(path) => {
25445                forensic.record(ForensicEventKind::DriftHistoryAppended {
25446                    path: path.display().to_string(),
25447                    entries: grouped_reports.len(),
25448                });
25449                drift_history_path = Some(path.display().to_string());
25450            }
25451            Err(e) => {
25452                forensic.record(ForensicEventKind::Error {
25453                    phase: "drift_history".to_owned(),
25454                    message: e.to_string(),
25455                });
25456            }
25457        }
25458    }
25459
25460    // Aggregate totals
25461    let total_fixtures: usize = grouped_reports.iter().map(|r| r.fixture_count).sum();
25462    let total_passed: usize = grouped_reports.iter().map(|r| r.passed).sum();
25463    let total_failed: usize = grouped_reports.iter().map(|r| r.failed).sum();
25464
25465    // Suite End
25466    forensic.record(ForensicEventKind::SuiteEnd {
25467        suite: suite_name.clone(),
25468        total_fixtures,
25469        passed: total_passed,
25470        failed: total_failed,
25471    });
25472    hooks.after_suite(&grouped_reports);
25473
25474    // Write forensic log if configured
25475    if let Some(ref log_path) = config.forensic_log_path {
25476        forensic.write_jsonl(log_path)?;
25477    }
25478
25479    Ok(E2eReport {
25480        suite: suite_name,
25481        packet_reports: grouped_reports,
25482        artifacts_written,
25483        gate_results,
25484        gates_pass,
25485        drift_history_path,
25486        forensic_log: forensic,
25487        total_fixtures,
25488        total_passed,
25489        total_failed,
25490    })
25491}
25492
25493// === Failure Forensics UX + Artifact Index (bd-2gi.21) ===
25494
25495/// Deterministic artifact identifier for cross-referencing forensic artifacts.
25496#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
25497pub struct ArtifactId {
25498    pub packet_id: String,
25499    pub artifact_kind: String,
25500    pub run_ts_unix_ms: u64,
25501}
25502
25503impl ArtifactId {
25504    /// Generate a short deterministic hash for display.
25505    #[must_use]
25506    pub fn short_hash(&self) -> String {
25507        let input = format!(
25508            "{}:{}:{}",
25509            self.packet_id, self.artifact_kind, self.run_ts_unix_ms
25510        );
25511        let hash = Sha256::digest(input.as_bytes());
25512        hex_encode(hash.as_slice())[..8].to_owned()
25513    }
25514}
25515
25516impl std::fmt::Display for ArtifactId {
25517    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25518        write!(
25519            f,
25520            "{}:{}@{}",
25521            self.packet_id,
25522            self.artifact_kind,
25523            self.short_hash()
25524        )
25525    }
25526}
25527
25528/// A concise failure summary for a single test case.
25529#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
25530pub struct FailureDigest {
25531    pub packet_id: String,
25532    pub case_id: String,
25533    pub operation: FixtureOperation,
25534    pub mode: RuntimeMode,
25535    pub mismatch_class: Option<String>,
25536    pub mismatch_summary: String,
25537    pub replay_key: String,
25538    pub trace_id: String,
25539    pub replay_command: String,
25540    pub artifact_path: Option<String>,
25541}
25542
25543impl std::fmt::Display for FailureDigest {
25544    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25545        writeln!(
25546            f,
25547            "FAIL {packet}::{case} [{op:?}/{mode:?}]",
25548            packet = self.packet_id,
25549            case = self.case_id,
25550            op = self.operation,
25551            mode = self.mode,
25552        )?;
25553        if let Some(ref mismatch_class) = self.mismatch_class {
25554            writeln!(f, "  Class:    {mismatch_class}")?;
25555        }
25556        writeln!(f, "  ReplayKey: {}", self.replay_key)?;
25557        writeln!(f, "  Trace:    {}", self.trace_id)?;
25558        writeln!(f, "  Mismatch: {}", self.mismatch_summary)?;
25559        writeln!(f, "  Replay:   {}", self.replay_command)?;
25560        if let Some(ref path) = self.artifact_path {
25561            writeln!(f, "  Artifact: {path}")?;
25562        }
25563        Ok(())
25564    }
25565}
25566
25567/// Human-readable failure report for an E2E run.
25568#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
25569pub struct FailureForensicsReport {
25570    pub run_ts_unix_ms: u64,
25571    pub total_fixtures: usize,
25572    pub total_passed: usize,
25573    pub total_failed: usize,
25574    pub failures: Vec<FailureDigest>,
25575    pub gate_failures: Vec<String>,
25576}
25577
25578impl FailureForensicsReport {
25579    #[must_use]
25580    pub fn is_clean(&self) -> bool {
25581        self.failures.is_empty() && self.gate_failures.is_empty()
25582    }
25583}
25584
25585impl std::fmt::Display for FailureForensicsReport {
25586    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25587        if self.is_clean() {
25588            writeln!(
25589                f,
25590                "ALL GREEN: {}/{} fixtures passed",
25591                self.total_passed, self.total_fixtures
25592            )?;
25593            return Ok(());
25594        }
25595
25596        writeln!(
25597            f,
25598            "FAILURES: {failed}/{total} fixtures failed",
25599            failed = self.total_failed,
25600            total = self.total_fixtures,
25601        )?;
25602        writeln!(f)?;
25603
25604        for (i, failure) in self.failures.iter().enumerate() {
25605            write!(f, "  {idx}. {failure}", idx = i + 1)?;
25606        }
25607
25608        if !self.gate_failures.is_empty() {
25609            writeln!(f)?;
25610            writeln!(f, "GATE FAILURES:")?;
25611            for reason in &self.gate_failures {
25612                writeln!(f, "  - {reason}")?;
25613            }
25614        }
25615
25616        Ok(())
25617    }
25618}
25619
25620/// Build a failure forensics report from an E2E report.
25621#[must_use]
25622pub fn build_failure_forensics(e2e: &E2eReport) -> FailureForensicsReport {
25623    let mut failures = Vec::new();
25624
25625    for report in &e2e.packet_reports {
25626        let packet_id = report
25627            .packet_id
25628            .clone()
25629            .unwrap_or_else(|| "unknown".to_owned());
25630
25631        for result in &report.results {
25632            if matches!(result.status, CaseStatus::Fail) {
25633                let mismatch_summary = result
25634                    .mismatch
25635                    .as_deref()
25636                    .unwrap_or("(no details)")
25637                    .chars()
25638                    .take(200)
25639                    .collect();
25640
25641                let replay_command = replay_cmd_for_case(&result.case_id);
25642
25643                let artifact_path = e2e
25644                    .artifacts_written
25645                    .iter()
25646                    .find(|a| a.packet_id == packet_id)
25647                    .map(|a| a.mismatch_corpus_path.display().to_string());
25648
25649                failures.push(FailureDigest {
25650                    packet_id: packet_id.clone(),
25651                    case_id: result.case_id.clone(),
25652                    operation: result.operation,
25653                    mode: result.mode,
25654                    mismatch_class: result.mismatch_class.clone(),
25655                    mismatch_summary,
25656                    replay_key: if result.replay_key.is_empty() {
25657                        deterministic_replay_key(&result.packet_id, &result.case_id, result.mode)
25658                    } else {
25659                        result.replay_key.clone()
25660                    },
25661                    trace_id: if result.trace_id.is_empty() {
25662                        deterministic_trace_id(&result.packet_id, &result.case_id, result.mode)
25663                    } else {
25664                        result.trace_id.clone()
25665                    },
25666                    replay_command,
25667                    artifact_path,
25668                });
25669            }
25670        }
25671    }
25672
25673    let gate_failures: Vec<String> = e2e
25674        .gate_results
25675        .iter()
25676        .filter(|g| !g.pass)
25677        .flat_map(|g| {
25678            g.reasons
25679                .iter()
25680                .map(|r| format!("{}: {}", g.packet_id, r))
25681                .collect::<Vec<_>>()
25682        })
25683        .collect();
25684
25685    FailureForensicsReport {
25686        run_ts_unix_ms: now_unix_ms(),
25687        total_fixtures: e2e.total_fixtures,
25688        total_passed: e2e.total_passed,
25689        total_failed: e2e.total_failed,
25690        failures,
25691        gate_failures,
25692    }
25693}
25694
25695/// Machine-readable per-case failure surface for packet/e2e assertion output.
25696#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25697pub struct FailureSurfaceEntry {
25698    pub suite: String,
25699    pub packet_id: String,
25700    pub case_id: String,
25701    pub operation: FixtureOperation,
25702    pub mode: RuntimeMode,
25703    pub mismatch_class: String,
25704    pub mismatch: String,
25705    pub replay_key: String,
25706    pub trace_id: String,
25707    pub evidence_records: usize,
25708}
25709
25710#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25711pub struct CaseEvidenceEntry {
25712    pub suite: String,
25713    pub packet_id: String,
25714    pub case_id: String,
25715    pub operation: FixtureOperation,
25716    pub mode: RuntimeMode,
25717    pub mismatch_class: String,
25718    pub mismatch: String,
25719    pub replay_key: String,
25720    pub trace_id: String,
25721    pub evidence_records: usize,
25722    pub ledger_id: String,
25723    #[serde(default)]
25724    pub expected_dtype: Option<String>,
25725    #[serde(default)]
25726    pub actual_dtype: Option<String>,
25727    #[serde(default)]
25728    pub first_mismatch_idx: Option<usize>,
25729    #[serde(default)]
25730    pub first_mismatch_actual: Option<String>,
25731    #[serde(default)]
25732    pub first_mismatch_expected: Option<String>,
25733}
25734
25735#[derive(Debug, Default, Clone, PartialEq, Eq)]
25736struct ExtractedMismatchDetails {
25737    expected_dtype: Option<String>,
25738    actual_dtype: Option<String>,
25739    first_mismatch_idx: Option<usize>,
25740    first_mismatch_actual: Option<String>,
25741    first_mismatch_expected: Option<String>,
25742}
25743
25744fn extract_segment_value(segment: &str, prefix: &str, terminators: &[&str]) -> Option<String> {
25745    let start = segment.find(prefix)? + prefix.len();
25746    let tail = &segment[start..];
25747    let end = terminators
25748        .iter()
25749        .filter_map(|needle| tail.find(needle))
25750        .min()
25751        .unwrap_or(tail.len());
25752    let value = tail[..end].trim();
25753    if value.is_empty() {
25754        None
25755    } else {
25756        Some(value.to_owned())
25757    }
25758}
25759
25760fn extract_first_mismatch_details(mismatch: &str) -> ExtractedMismatchDetails {
25761    let mut details = ExtractedMismatchDetails::default();
25762
25763    for segment in mismatch.split("; ") {
25764        if (details.actual_dtype.is_none() || details.expected_dtype.is_none())
25765            && let Some(actual_dtype) =
25766                extract_segment_value(segment, "dtype mismatch: actual=", &[", expected="])
25767        {
25768            details.actual_dtype = Some(actual_dtype);
25769            details.expected_dtype =
25770                extract_segment_value(segment, ", expected=", &["; ", "] ", "\n"]);
25771        }
25772
25773        if details.first_mismatch_idx.is_none()
25774            && let Some(idx_tail) = segment.split("idx=").nth(1)
25775        {
25776            let digits: String = idx_tail
25777                .chars()
25778                .take_while(|ch| ch.is_ascii_digit())
25779                .collect();
25780            if !digits.is_empty() {
25781                details.first_mismatch_idx = digits.parse::<usize>().ok();
25782            }
25783        }
25784
25785        if (details.first_mismatch_actual.is_none() || details.first_mismatch_expected.is_none())
25786            && segment.contains("idx=")
25787            && let Some(actual_value) = extract_segment_value(segment, "actual=", &[", expected="])
25788        {
25789            details.first_mismatch_actual = Some(actual_value);
25790            details.first_mismatch_expected =
25791                extract_segment_value(segment, ", expected=", &["; ", "] ", "\n"]);
25792        }
25793    }
25794
25795    details
25796}
25797
25798fn failure_evidence_ledger_id(packet_id: &str, case_id: &str, mode: RuntimeMode) -> String {
25799    format!(
25800        "evidence:{}",
25801        stable_json_digest(&serde_json::json!({
25802            "packet_id": packet_id,
25803            "case_id": case_id,
25804            "mode": runtime_mode_slug(mode),
25805        }))
25806    )
25807}
25808
25809#[must_use]
25810pub fn build_failure_surface_entries_for_report(
25811    report: &PacketParityReport,
25812) -> Vec<FailureSurfaceEntry> {
25813    build_failure_surface_entries(std::slice::from_ref(report))
25814}
25815
25816#[must_use]
25817pub fn build_failure_surface_entries(reports: &[PacketParityReport]) -> Vec<FailureSurfaceEntry> {
25818    let mut entries: Vec<_> = reports
25819        .iter()
25820        .flat_map(|report| {
25821            // Fallback must be a legal path component on every platform:
25822            // this value becomes a directory name under artifacts/conformance/
25823            // and Windows (NTFS) rejects angle brackets, aborting `git
25824            // checkout` (issue #9). Use a plain ASCII token here, with
25825            // sanitize_artifact_path_component as a second line of defense.
25826            let packet_id = report
25827                .packet_id
25828                .clone()
25829                .unwrap_or_else(|| "unknown".to_owned());
25830            report
25831                .results
25832                .iter()
25833                .filter(|result| matches!(result.status, CaseStatus::Fail))
25834                .map(move |result| FailureSurfaceEntry {
25835                    suite: report.suite.clone(),
25836                    packet_id: packet_id.clone(),
25837                    case_id: result.case_id.clone(),
25838                    operation: result.operation,
25839                    mode: result.mode,
25840                    mismatch_class: result
25841                        .mismatch_class
25842                        .clone()
25843                        .unwrap_or_else(|| "unknown".to_owned()),
25844                    mismatch: result
25845                        .mismatch
25846                        .clone()
25847                        .unwrap_or_else(|| "(no details)".to_owned()),
25848                    replay_key: if result.replay_key.is_empty() {
25849                        deterministic_replay_key(&result.packet_id, &result.case_id, result.mode)
25850                    } else {
25851                        result.replay_key.clone()
25852                    },
25853                    trace_id: if result.trace_id.is_empty() {
25854                        deterministic_trace_id(&result.packet_id, &result.case_id, result.mode)
25855                    } else {
25856                        result.trace_id.clone()
25857                    },
25858                    evidence_records: result.evidence_records,
25859                })
25860        })
25861        .collect();
25862
25863    entries.sort_by(|a, b| {
25864        (
25865            a.suite.as_str(),
25866            a.packet_id.as_str(),
25867            a.case_id.as_str(),
25868            runtime_mode_slug(a.mode),
25869            a.mismatch_class.as_str(),
25870        )
25871            .cmp(&(
25872                b.suite.as_str(),
25873                b.packet_id.as_str(),
25874                b.case_id.as_str(),
25875                runtime_mode_slug(b.mode),
25876                b.mismatch_class.as_str(),
25877            ))
25878    });
25879    entries
25880}
25881
25882#[must_use]
25883pub fn build_case_evidence_entries_for_report(
25884    report: &PacketParityReport,
25885) -> Vec<CaseEvidenceEntry> {
25886    build_case_evidence_entries(std::slice::from_ref(report))
25887}
25888
25889#[must_use]
25890pub fn build_case_evidence_entries(reports: &[PacketParityReport]) -> Vec<CaseEvidenceEntry> {
25891    let mut entries: Vec<_> = reports
25892        .iter()
25893        .flat_map(|report| {
25894            // Fallback must be a legal path component on every platform:
25895            // this value becomes a directory name under artifacts/conformance/
25896            // and Windows (NTFS) rejects angle brackets, aborting `git
25897            // checkout` (issue #9). Use a plain ASCII token here, with
25898            // sanitize_artifact_path_component as a second line of defense.
25899            let packet_id = report
25900                .packet_id
25901                .clone()
25902                .unwrap_or_else(|| "unknown".to_owned());
25903            report
25904                .results
25905                .iter()
25906                .filter(|result| matches!(result.status, CaseStatus::Fail))
25907                .map(move |result| {
25908                    let mismatch = result
25909                        .mismatch
25910                        .clone()
25911                        .unwrap_or_else(|| "(no details)".to_owned());
25912                    let details = extract_first_mismatch_details(&mismatch);
25913                    CaseEvidenceEntry {
25914                        suite: report.suite.clone(),
25915                        packet_id: packet_id.clone(),
25916                        case_id: result.case_id.clone(),
25917                        operation: result.operation,
25918                        mode: result.mode,
25919                        mismatch_class: result
25920                            .mismatch_class
25921                            .clone()
25922                            .unwrap_or_else(|| "unknown".to_owned()),
25923                        mismatch,
25924                        replay_key: if result.replay_key.is_empty() {
25925                            deterministic_replay_key(
25926                                &result.packet_id,
25927                                &result.case_id,
25928                                result.mode,
25929                            )
25930                        } else {
25931                            result.replay_key.clone()
25932                        },
25933                        trace_id: if result.trace_id.is_empty() {
25934                            deterministic_trace_id(&result.packet_id, &result.case_id, result.mode)
25935                        } else {
25936                            result.trace_id.clone()
25937                        },
25938                        evidence_records: result.evidence_records,
25939                        ledger_id: failure_evidence_ledger_id(
25940                            &result.packet_id,
25941                            &result.case_id,
25942                            result.mode,
25943                        ),
25944                        expected_dtype: details.expected_dtype,
25945                        actual_dtype: details.actual_dtype,
25946                        first_mismatch_idx: details.first_mismatch_idx,
25947                        first_mismatch_actual: details.first_mismatch_actual,
25948                        first_mismatch_expected: details.first_mismatch_expected,
25949                    }
25950                })
25951        })
25952        .collect();
25953
25954    entries.sort_by(|a, b| {
25955        (
25956            a.suite.as_str(),
25957            a.packet_id.as_str(),
25958            a.case_id.as_str(),
25959            runtime_mode_slug(a.mode),
25960        )
25961            .cmp(&(
25962                b.suite.as_str(),
25963                b.packet_id.as_str(),
25964                b.case_id.as_str(),
25965                runtime_mode_slug(b.mode),
25966            ))
25967    });
25968    entries
25969}
25970
25971fn sanitize_failure_surface_artifact_name(label: &str) -> String {
25972    let sanitized: String = label
25973        .chars()
25974        .map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '_' })
25975        .collect();
25976    let trimmed = sanitized.trim_matches('_');
25977    if trimmed.is_empty() {
25978        "failure_surface".to_owned()
25979    } else {
25980        trimmed.to_owned()
25981    }
25982}
25983
25984/// Sanitize a single path component (a packet id or case id) so it is a legal
25985/// file/directory name on every supported platform — most importantly Windows
25986/// (NTFS), which rejects the characters `< > : " / \ | ? *` and trailing dots
25987/// or spaces. A committed `artifacts/conformance/<unknown>/...` path (emitted
25988/// when a report carried no `packet_id`) made `git checkout` abort with
25989/// "invalid path" on `windows-latest` (issue #9), so every component that
25990/// feeds an on-disk artifact path is routed through this.
25991fn sanitize_artifact_path_component(component: &str) -> String {
25992    let sanitized: String = component
25993        .chars()
25994        .map(|ch| match ch {
25995            '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*' => '_',
25996            c if (c as u32) < 0x20 => '_',
25997            c => c,
25998        })
25999        .collect();
26000    // NTFS also forbids names ending in '.' or ' '.
26001    let trimmed = sanitized.trim_end_matches(['.', ' ']);
26002    if trimmed.is_empty() {
26003        "unknown".to_owned()
26004    } else {
26005        trimmed.to_owned()
26006    }
26007}
26008
26009pub fn write_failure_surface_jsonl(
26010    config: &HarnessConfig,
26011    artifact_name: &str,
26012    entries: &[FailureSurfaceEntry],
26013) -> Result<Option<PathBuf>, HarnessError> {
26014    if entries.is_empty() {
26015        return Ok(None);
26016    }
26017
26018    let output_path = config
26019        .repo_root
26020        .join("artifacts/phase2c/test_failure_surfaces")
26021        .join(format!(
26022            "{}.jsonl",
26023            sanitize_failure_surface_artifact_name(artifact_name)
26024        ));
26025    if let Some(parent) = output_path.parent() {
26026        fs::create_dir_all(parent)?;
26027    }
26028
26029    let mut file = fs::File::create(&output_path)?;
26030    for entry in entries {
26031        writeln!(file, "{}", serde_json::to_string(entry)?)?;
26032    }
26033    Ok(Some(output_path))
26034}
26035
26036pub fn write_case_evidence_jsonl(
26037    config: &HarnessConfig,
26038    reports: &[PacketParityReport],
26039) -> Result<Vec<PathBuf>, HarnessError> {
26040    let mut entries_by_case: BTreeMap<(String, String), Vec<CaseEvidenceEntry>> = BTreeMap::new();
26041    for entry in build_case_evidence_entries(reports) {
26042        entries_by_case
26043            .entry((entry.packet_id.clone(), entry.case_id.clone()))
26044            .or_default()
26045            .push(entry);
26046    }
26047
26048    let mut paths = Vec::with_capacity(entries_by_case.len());
26049    for ((packet_id, case_id), mut entries) in entries_by_case {
26050        entries.sort_by(|a, b| runtime_mode_slug(a.mode).cmp(runtime_mode_slug(b.mode)));
26051        let output_path = config
26052            .repo_root
26053            .join("artifacts/conformance")
26054            .join(sanitize_artifact_path_component(&packet_id))
26055            .join(format!(
26056                "{}.jsonl",
26057                sanitize_artifact_path_component(&case_id)
26058            ));
26059        if let Some(parent) = output_path.parent() {
26060            fs::create_dir_all(parent)?;
26061        }
26062
26063        let mut file = fs::File::create(&output_path)?;
26064        for entry in &entries {
26065            writeln!(file, "{}", serde_json::to_string(entry)?)?;
26066        }
26067        paths.push(output_path);
26068    }
26069
26070    paths.sort();
26071    Ok(paths)
26072}
26073
26074#[cfg(test)]
26075#[path = "tests/harness_delegation_policy.rs"]
26076mod harness_delegation_policy;
26077
26078#[cfg(test)]
26079#[path = "tests/fixture_payload_order.rs"]
26080mod fixture_payload_order;
26081
26082#[cfg(test)]
26083#[path = "tests/live_oracle_dataframe_apply_alias.rs"]
26084mod live_oracle_dataframe_apply_alias;
26085
26086#[cfg(test)]
26087#[path = "tests/live_oracle_dataframe_groupby_resample.rs"]
26088mod live_oracle_dataframe_groupby_resample;
26089
26090#[cfg(test)]
26091#[path = "tests/live_oracle_dataframe_groupby_rolling.rs"]
26092mod live_oracle_dataframe_groupby_rolling;
26093
26094#[cfg(test)]
26095#[path = "tests/live_oracle_dataframe_groupby_misc.rs"]
26096mod live_oracle_dataframe_groupby_misc;
26097
26098#[cfg(test)]
26099#[path = "tests/live_oracle_dataframe_row_multiindex.rs"]
26100mod live_oracle_dataframe_row_multiindex;
26101
26102#[cfg(test)]
26103#[path = "tests/live_oracle_dataframe_merge.rs"]
26104mod live_oracle_dataframe_merge;
26105
26106#[cfg(test)]
26107#[path = "tests/live_oracle_dataframe_series_selection.rs"]
26108mod live_oracle_dataframe_series_selection;
26109
26110#[cfg(test)]
26111#[path = "tests/live_oracle_dataframe_series_core.rs"]
26112mod live_oracle_dataframe_series_core;
26113
26114#[cfg(test)]
26115#[path = "tests/live_oracle_series_to_datetime_variants.rs"]
26116mod live_oracle_series_to_datetime_variants;
26117
26118#[cfg(test)]
26119#[path = "tests/live_oracle_series_misc.rs"]
26120mod live_oracle_series_misc;
26121
26122#[cfg(test)]
26123#[path = "tests/live_oracle_harness_availability.rs"]
26124mod live_oracle_harness_availability;
26125
26126#[cfg(test)]
26127#[path = "tests/live_oracle_report.rs"]
26128mod live_oracle_report;
26129
26130#[cfg(test)]
26131#[path = "tests/ci_supply_chain_policy.rs"]
26132mod ci_supply_chain_policy;
26133
26134#[cfg(test)]
26135#[path = "tests/fuzz_seed_fixtures.rs"]
26136mod fuzz_seed_fixtures;
26137
26138#[cfg(test)]
26139#[path = "tests/packet_filter_runs.rs"]
26140mod packet_filter_runs;
26141
26142#[cfg(test)]
26143#[path = "tests/conformance_series.rs"]
26144mod conformance_series;
26145
26146#[cfg(test)]
26147#[path = "tests/conformance_index.rs"]
26148mod conformance_index;
26149
26150#[cfg(test)]
26151#[path = "tests/conformance_dataframe.rs"]
26152mod conformance_dataframe;
26153
26154#[cfg(test)]
26155#[path = "tests/conformance_categorical.rs"]
26156mod conformance_categorical;
26157
26158#[cfg(test)]
26159#[path = "tests/conformance_datetime.rs"]
26160mod conformance_datetime;
26161
26162#[cfg(test)]
26163#[path = "tests/conformance_tseries.rs"]
26164mod conformance_tseries;
26165
26166#[cfg(test)]
26167#[path = "tests/conformance_groupby.rs"]
26168mod conformance_groupby;
26169
26170#[cfg(test)]
26171#[path = "tests/conformance_groupby_apply.rs"]
26172mod conformance_groupby_apply;
26173
26174#[cfg(test)]
26175#[path = "tests/conformance_io.rs"]
26176mod conformance_io;
26177
26178#[cfg(test)]
26179#[path = "tests/conformance_io_formats.rs"]
26180mod conformance_io_formats;
26181
26182#[cfg(test)]
26183#[path = "tests/conformance_merge_join_concat.rs"]
26184mod conformance_merge_join_concat;
26185
26186#[cfg(test)]
26187#[path = "tests/conformance_multiindex.rs"]
26188mod conformance_multiindex;
26189
26190#[cfg(test)]
26191#[path = "tests/conformance_reshape.rs"]
26192mod conformance_reshape;
26193
26194#[cfg(test)]
26195#[path = "tests/conformance_window.rs"]
26196mod conformance_window;
26197
26198#[cfg(test)]
26199mod tests {
26200    use std::{
26201        collections::BTreeSet,
26202        fs,
26203        path::PathBuf,
26204        sync::{Mutex, OnceLock},
26205    };
26206
26207    use fp_runtime::RuntimeMode;
26208
26209    use super::{
26210        ArtifactId, CaseEvidenceEntry, CaseResult, CaseStatus, CiGate, CiGateResult,
26211        CiPipelineConfig, CiPipelineResult, ComparisonCategory, DecodeProofArtifact,
26212        DecodeProofStatus, DifferentialResult, DriftLevel, DriftRecord, E2eConfig, FailureDigest,
26213        FailureForensicsReport, FailureSurfaceEntry, FaultInjectionClassification,
26214        FixtureExpectedAlignment, FixtureOperation, FixtureOracleSource, ForensicEventKind,
26215        ForensicLog, HarnessConfig, LifecycleHooks, NoopHooks, OracleMode, PacketParityReport,
26216        RaptorQSidecarArtifact, SuiteOptions, append_phase2c_drift_history,
26217        build_case_evidence_entries, build_case_evidence_entries_for_report,
26218        build_ci_forensics_report, build_compat_closure_e2e_scenario_report,
26219        build_compat_closure_final_evidence_pack, build_differential_report,
26220        build_differential_validation_log, build_failure_forensics, build_failure_surface_entries,
26221        build_failure_surface_entries_for_report, build_g6_conformance_errors,
26222        enforce_packet_gates, evaluate_ci_gate, evaluate_parity_gate, generate_raptorq_sidecar,
26223        run_ci_pipeline, run_differential_by_id, run_differential_suite, run_e2e_suite,
26224        run_fault_injection_validation_by_id, run_packet_by_id, run_packet_suite,
26225        run_packets_grouped, run_raptorq_decode_recovery_drill, run_smoke,
26226        sanitize_artifact_path_component, verify_all_sidecars_ci, verify_packet_sidecar_integrity,
26227        write_case_evidence_jsonl, write_compat_closure_e2e_scenario_report,
26228        write_compat_closure_final_evidence_pack, write_differential_validation_log,
26229        write_failure_surface_jsonl, write_fault_injection_validation_report,
26230        write_packet_artifacts,
26231    };
26232
26233    fn phase2c_artifact_test_lock() -> std::sync::MutexGuard<'static, ()> {
26234        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
26235        // The lock guards only side-effect sequencing for artifact-writing
26236        // tests; the inner tuple is (), so recovering a poisoned guard via
26237        // `into_inner()` is safe and prevents a single panicking test from
26238        // cascading 18 downstream tests into `PoisonError` failures.
26239        match LOCK.get_or_init(|| Mutex::new(())).lock() {
26240            Ok(guard) => guard,
26241            Err(poisoned) => poisoned.into_inner(),
26242        }
26243    }
26244
26245    fn assert_text_golden(golden_name: &str, actual: &str) {
26246        let golden_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
26247            .join("tests")
26248            .join("goldens")
26249            .join(golden_name);
26250
26251        if std::env::var_os("UPDATE_GOLDENS").is_some() {
26252            let parent = golden_path
26253                .parent()
26254                .expect("golden files should always have a parent directory");
26255            std::fs::create_dir_all(parent).expect("golden directory should be creatable");
26256            std::fs::write(&golden_path, actual).expect("golden file should be writable");
26257            return;
26258        }
26259
26260        let expected =
26261            std::fs::read_to_string(&golden_path).expect("golden file should be readable");
26262        assert_eq!(
26263            actual,
26264            expected,
26265            "golden mismatch for {}",
26266            golden_path.display()
26267        );
26268    }
26269
26270    fn render_failure_surface_entries(entries: &[FailureSurfaceEntry]) -> String {
26271        if entries.is_empty() {
26272            return "  (no failed case entries captured)".to_owned();
26273        }
26274
26275        entries
26276            .iter()
26277            .map(|entry| {
26278                format!(
26279                    "  - suite={} packet_id={} case_id={} mode={} mismatch_class={} mismatch={} replay_key={} trace_id={}",
26280                    entry.suite,
26281                    entry.packet_id,
26282                    entry.case_id,
26283                    super::runtime_mode_slug(entry.mode),
26284                    entry.mismatch_class,
26285                    entry.mismatch,
26286                    entry.replay_key,
26287                    entry.trace_id,
26288                )
26289            })
26290            .collect::<Vec<_>>()
26291            .join("\n")
26292    }
26293
26294    fn write_failure_surface_artifact(label: &str, entries: &[FailureSurfaceEntry]) -> String {
26295        let cfg = HarnessConfig::default_paths();
26296        match write_failure_surface_jsonl(&cfg, label, entries) {
26297            Ok(Some(path)) => format!("artifact: {}", path.display()),
26298            Ok(None) => "artifact: <none>".to_owned(),
26299            Err(err) => format!("artifact write failed: {err}"),
26300        }
26301    }
26302
26303    fn assert_failure_surface_is_actionable(
26304        label: &str,
26305        artifact: &str,
26306        entries: &[FailureSurfaceEntry],
26307    ) {
26308        assert!(
26309            !entries.is_empty(),
26310            "{label} expected actionable failure surface\n{artifact}"
26311        );
26312        for entry in entries {
26313            assert!(
26314                !entry.packet_id.is_empty()
26315                    && !entry.case_id.is_empty()
26316                    && !entry.mismatch_class.is_empty()
26317                    && !entry.mismatch.is_empty()
26318                    && !entry.replay_key.is_empty()
26319                    && !entry.trace_id.is_empty(),
26320                "{label} emitted incomplete failure surface entry\n{artifact}\n{surface}",
26321                artifact = artifact,
26322                surface = render_failure_surface_entries(entries),
26323            );
26324        }
26325    }
26326
26327    fn assert_green_after_failure_surface(
26328        label: &str,
26329        is_green: bool,
26330        entries: &[FailureSurfaceEntry],
26331        artifact_writer: impl FnOnce(&[FailureSurfaceEntry]) -> String,
26332    ) {
26333        if is_green {
26334            return;
26335        }
26336
26337        let artifact = artifact_writer(entries);
26338        assert_failure_surface_is_actionable(label, &artifact, entries);
26339        panic!(
26340            "{label} conformance mismatch\n{artifact}\n{surface}",
26341            surface = render_failure_surface_entries(entries),
26342        );
26343    }
26344
26345    fn assert_packet_report_green_after_writing_failure_surface(
26346        label: &str,
26347        report: &PacketParityReport,
26348    ) {
26349        if report.is_green() {
26350            return;
26351        }
26352        let entries = build_failure_surface_entries_for_report(report);
26353        assert_green_after_failure_surface(label, false, &entries, |entries| {
26354            write_failure_surface_artifact(label, entries)
26355        });
26356    }
26357
26358    fn assert_grouped_reports_green_after_writing_failure_surface(
26359        label: &str,
26360        reports: &[PacketParityReport],
26361    ) {
26362        if reports.iter().all(PacketParityReport::is_green) {
26363            return;
26364        }
26365        let entries = build_failure_surface_entries(reports);
26366        assert_green_after_failure_surface(label, false, &entries, |entries| {
26367            write_failure_surface_artifact(label, entries)
26368        });
26369    }
26370
26371    #[test]
26372    #[should_panic(expected = "synthetic packet mismatch conformance mismatch")]
26373    fn non_green_packet_surface_fails_the_gate_gxe5s() {
26374        let entries = [FailureSurfaceEntry {
26375            suite: "synthetic".to_owned(),
26376            packet_id: "FP-TEST-001".to_owned(),
26377            case_id: "fixture_mismatch".to_owned(),
26378            operation: FixtureOperation::SeriesAdd,
26379            mode: RuntimeMode::Strict,
26380            mismatch_class: "value_critical".to_owned(),
26381            mismatch: "actual=Int64(1), expected=Int64(2)".to_owned(),
26382            replay_key: "FP-TEST-001/fixture_mismatch/strict".to_owned(),
26383            trace_id: "FP-TEST-001:fixture_mismatch:strict".to_owned(),
26384            evidence_records: 1,
26385        }];
26386
26387        assert_green_after_failure_surface("synthetic packet mismatch", false, &entries, |_| {
26388            "artifact: <test-only>".to_owned()
26389        });
26390    }
26391
26392    fn assert_ci_gate_green_after_validating_failure_surface(label: &str, result: &CiGateResult) {
26393        if result.passed {
26394            return;
26395        }
26396
26397        assert!(
26398            !result.errors.is_empty(),
26399            "{label} expected actionable ci gate errors\n{result:#?}"
26400        );
26401        let mut saw_structured_failure = false;
26402        for error in &result.errors {
26403            if error.contains("packet_id=")
26404                && error.contains("case_id=")
26405                && error.contains("mismatch_class=")
26406                && error.contains("mismatch=")
26407            {
26408                saw_structured_failure = true;
26409                continue;
26410            }
26411            assert!(
26412                error.starts_with("case_evidence_artifact=")
26413                    || error.starts_with("case_evidence_artifact_write_failed="),
26414                "{label} expected structured ci gate error rows\n{result:#?}",
26415            );
26416        }
26417        assert!(
26418            saw_structured_failure,
26419            "{label} expected at least one structured failure row\n{result:#?}"
26420        );
26421        panic!("{label} conformance gate failed\n{result:#?}");
26422    }
26423
26424    fn sample_failure_digest() -> FailureDigest {
26425        FailureDigest {
26426            packet_id: "FP-P2C-001".to_owned(),
26427            case_id: "series_add_strict".to_owned(),
26428            operation: FixtureOperation::SeriesAdd,
26429            mode: RuntimeMode::Strict,
26430            mismatch_class: Some("value_critical".to_owned()),
26431            mismatch_summary: "expected Int64(10), got Float64(10.0)".to_owned(),
26432            replay_key: "FP-P2C-001/series_add_strict/strict".to_owned(),
26433            trace_id: "FP-P2C-001:series_add_strict:strict".to_owned(),
26434            replay_command: "cargo test -p fp-conformance -- series_add_strict --nocapture"
26435                .to_owned(),
26436            artifact_path: Some("artifacts/phase2c/FP-P2C-001/mismatch.json".to_owned()),
26437        }
26438    }
26439
26440    fn sample_failure_forensics_report() -> FailureForensicsReport {
26441        FailureForensicsReport {
26442            run_ts_unix_ms: 1000,
26443            total_fixtures: 5,
26444            total_passed: 3,
26445            total_failed: 2,
26446            failures: vec![
26447                FailureDigest {
26448                    packet_id: "FP-P2C-001".to_owned(),
26449                    case_id: "case_a".to_owned(),
26450                    operation: FixtureOperation::SeriesAdd,
26451                    mode: RuntimeMode::Strict,
26452                    mismatch_class: Some("value_critical".to_owned()),
26453                    mismatch_summary: "value drift".to_owned(),
26454                    replay_key: "FP-P2C-001/case_a/strict".to_owned(),
26455                    trace_id: "FP-P2C-001:case_a:strict".to_owned(),
26456                    replay_command: "cargo test -- case_a".to_owned(),
26457                    artifact_path: None,
26458                },
26459                FailureDigest {
26460                    packet_id: "FP-P2C-002".to_owned(),
26461                    case_id: "case_b".to_owned(),
26462                    operation: FixtureOperation::IndexAlignUnion,
26463                    mode: RuntimeMode::Hardened,
26464                    mismatch_class: Some("shape_critical".to_owned()),
26465                    mismatch_summary: "shape mismatch".to_owned(),
26466                    replay_key: "FP-P2C-002/case_b/hardened".to_owned(),
26467                    trace_id: "FP-P2C-002:case_b:hardened".to_owned(),
26468                    replay_command: "cargo test -- case_b".to_owned(),
26469                    artifact_path: Some("path/to/corpus.json".to_owned()),
26470                },
26471            ],
26472            gate_failures: vec!["FP-P2C-001: strict_failed > 0".to_owned()],
26473        }
26474    }
26475
26476    fn sample_ci_pipeline_result() -> CiPipelineResult {
26477        CiPipelineResult {
26478            gates: vec![
26479                CiGateResult {
26480                    gate: CiGate::G3Unit,
26481                    passed: true,
26482                    elapsed_ms: 100,
26483                    summary: "10 tests passed".to_owned(),
26484                    errors: vec![],
26485                },
26486                CiGateResult {
26487                    gate: CiGate::G6Conformance,
26488                    passed: false,
26489                    elapsed_ms: 200,
26490                    summary: "2 fixtures failed".to_owned(),
26491                    errors: vec!["case_a: value drift".to_owned()],
26492                },
26493            ],
26494            all_passed: false,
26495            first_failure: Some(CiGate::G6Conformance),
26496            elapsed_ms: 300,
26497        }
26498    }
26499
26500    #[test]
26501    fn smoke_harness_finds_oracle_and_fixtures() {
26502        let cfg = HarnessConfig::default_paths();
26503        if !cfg.oracle_reachable() {
26504            eprintln!(
26505                "no pandas oracle reachable (legacy root {} absent, interpreter {} has no pandas); \
26506                 skipping smoke oracle check",
26507                cfg.oracle_root.display(),
26508                cfg.python_bin
26509            );
26510            return;
26511        }
26512        let report = run_smoke(&cfg);
26513        assert!(
26514            report.oracle_present,
26515            "a reachable oracle must be reported present"
26516        );
26517        assert!(report.fixture_count >= 1, "expected at least one fixture");
26518        assert!(report.strict_mode);
26519    }
26520
26521    #[test]
26522    fn packet_suite_is_green_for_bootstrap_cases() {
26523        let cfg = HarnessConfig::default_paths();
26524        let report = run_packet_suite(&cfg).expect("suite should run");
26525        assert!(report.fixture_count >= 1, "expected packet fixtures");
26526        assert_packet_report_green_after_writing_failure_surface(
26527            "packet_suite_is_green_for_bootstrap_cases",
26528            &report,
26529        );
26530    }
26531
26532    #[test]
26533    fn grouped_reports_are_partitioned_per_packet() {
26534        let _artifact_guard = phase2c_artifact_test_lock();
26535        let cfg = HarnessConfig::default_paths();
26536        let reports = run_packets_grouped(&cfg, &SuiteOptions::default()).expect("grouped");
26537        let packet_ids: Vec<String> = reports
26538            .iter()
26539            .map(|report| {
26540                report
26541                    .packet_id
26542                    .clone()
26543                    .expect("grouped report should have packet_id")
26544            })
26545            .collect();
26546        assert!(
26547            !packet_ids.is_empty(),
26548            "expected grouped packet reports to include packet ids"
26549        );
26550        let unique_packet_count = packet_ids.iter().collect::<BTreeSet<_>>().len();
26551        assert!(
26552            unique_packet_count == reports.len(),
26553            "expected exactly one grouped report per packet: unique={unique_packet_count} reports={}",
26554            reports.len()
26555        );
26556        assert_grouped_reports_green_after_writing_failure_surface(
26557            "grouped_reports_are_partitioned_per_packet",
26558            &reports,
26559        );
26560        if reports.iter().all(PacketParityReport::is_green) {
26561            enforce_packet_gates(&cfg, &reports).expect("enforcement should pass");
26562        }
26563    }
26564
26565    #[test]
26566    fn packet_gate_enforcement_fails_when_report_is_not_green() {
26567        let _artifact_guard = phase2c_artifact_test_lock();
26568        let cfg = HarnessConfig::default_paths();
26569        let mut reports = run_packets_grouped(&cfg, &SuiteOptions::default()).expect("grouped");
26570        let report = reports.first_mut().expect("at least one packet");
26571        let first_case = report.results.first_mut().expect("at least one case");
26572        first_case.status = CaseStatus::Fail;
26573        first_case.mismatch = Some("synthetic non-green check".to_owned());
26574        report.failed = 1;
26575        report.passed = report.fixture_count.saturating_sub(1);
26576
26577        let err = enforce_packet_gates(&cfg, &reports).expect_err("should fail");
26578        let message = err.to_string();
26579        assert!(
26580            message.contains("enforcement failed"),
26581            "unexpected error message: {message}"
26582        );
26583    }
26584
26585    #[test]
26586    fn drift_history_append_emits_jsonl_rows() {
26587        let _artifact_guard = phase2c_artifact_test_lock();
26588        let cfg = HarnessConfig::default_paths();
26589        let reports = run_packets_grouped(&cfg, &SuiteOptions::default()).expect("grouped");
26590        let history_path = append_phase2c_drift_history(&cfg, &reports).expect("history");
26591        let contents = fs::read_to_string(&history_path).expect("history content");
26592        let latest = contents.lines().last().expect("at least one row");
26593        let row: serde_json::Value = serde_json::from_str(latest).expect("json row");
26594        assert!(
26595            row.get("packet_id").is_some(),
26596            "history row should include packet_id"
26597        );
26598        assert!(
26599            row.get("gate_pass").is_some(),
26600            "history row should include gate pass status"
26601        );
26602    }
26603
26604    #[test]
26605    fn parity_gate_evaluation_passes_for_packet_001() {
26606        let _artifact_guard = phase2c_artifact_test_lock();
26607        let cfg = HarnessConfig::default_paths();
26608        let report =
26609            run_packet_by_id(&cfg, "FP-P2C-001", OracleMode::FixtureExpected).expect("report");
26610        let result = evaluate_parity_gate(&cfg, &report).expect("gate");
26611        assert!(result.pass, "gate should pass: {result:?}");
26612    }
26613
26614    #[test]
26615    fn parity_gate_evaluation_fails_for_injected_drift() {
26616        let _artifact_guard = phase2c_artifact_test_lock();
26617        let cfg = HarnessConfig::default_paths();
26618        let mut report =
26619            run_packet_by_id(&cfg, "FP-P2C-001", OracleMode::FixtureExpected).expect("report");
26620        let first = report.results.first_mut().expect("at least one result");
26621        first.status = CaseStatus::Fail;
26622        first.mismatch = Some("synthetic drift injection".to_owned());
26623        report.failed = 1;
26624        report.passed = report.fixture_count.saturating_sub(1);
26625
26626        let result = evaluate_parity_gate(&cfg, &report).expect("gate");
26627        assert!(!result.pass, "gate should fail for injected drift");
26628        assert!(
26629            result
26630                .reasons
26631                .iter()
26632                .any(|reason| reason.contains("failed="))
26633        );
26634    }
26635
26636    #[test]
26637    fn raptorq_sidecar_round_trip_recovery_drill_passes() {
26638        let payload = br#"{\"suite\":\"phase2c_packets\",\"passed\":4,\"failed\":0}"#;
26639        let sidecar = generate_raptorq_sidecar("test/parity_report", "conformance", payload, 8)
26640            .expect("sidecar generation");
26641        let proof = run_raptorq_decode_recovery_drill(&sidecar, payload).expect("decode drill");
26642        assert!(proof.recovered_blocks >= 1);
26643    }
26644
26645    #[test]
26646    fn index_alignment_expected_type_serialization_is_stable() {
26647        let expected = FixtureExpectedAlignment {
26648            union_index: vec![1_i64.into(), 2_i64.into()],
26649            left_positions: vec![Some(0), None],
26650            right_positions: vec![None, Some(0)],
26651        };
26652        let json = serde_json::to_string(&expected).expect("serialize");
26653        let back: FixtureExpectedAlignment = serde_json::from_str(&json).expect("deserialize");
26654        assert_eq!(back, expected);
26655    }
26656
26657    #[test]
26658    fn sidecar_verification_runs_on_generated_artifact() {
26659        let payload = br#"{\"suite\":\"phase2c_packets\",\"passed\":2,\"failed\":0}"#;
26660        let sidecar: RaptorQSidecarArtifact =
26661            generate_raptorq_sidecar("test/artifact", "conformance", payload, 8).expect("sidecar");
26662        let scrub = super::verify_raptorq_sidecar(&sidecar, payload).expect("scrub");
26663        assert_eq!(scrub.status, "ok");
26664    }
26665
26666    #[cfg(not(feature = "asupersync"))]
26667    #[test]
26668    fn sidecar_verification_rejects_asupersync_evidence_without_feature_y13st() {
26669        let payload = br#"{\"suite\":\"phase2c_packets\",\"passed\":2,\"failed\":0}"#;
26670        let mut sidecar: RaptorQSidecarArtifact =
26671            generate_raptorq_sidecar("test/artifact", "conformance", payload, 8).expect("sidecar");
26672        sidecar.asupersync_codec = Some(super::AsupersyncCodecEvidence {
26673            codec: "passthrough".to_owned(),
26674            verifier: "fnv1a64".to_owned(),
26675            encoded_bytes: payload.len(),
26676            repair_symbols: 0,
26677            integrity_verified: true,
26678        });
26679
26680        let err = super::verify_raptorq_sidecar(&sidecar, payload)
26681            .expect_err("no-feature build must not accept unchecked asupersync evidence");
26682        let message = err.to_string();
26683        assert!(
26684            message.contains("asupersync codec evidence is present")
26685                && message.contains("without the asupersync feature"),
26686            "unexpected error: {message}"
26687        );
26688    }
26689
26690    // === Differential Harness Tests ===
26691
26692    #[test]
26693    fn differential_suite_produces_structured_drift() {
26694        let cfg = HarnessConfig::default_paths();
26695        let diff_report =
26696            run_differential_suite(&cfg, &SuiteOptions::default()).expect("differential suite");
26697        assert!(diff_report.report.fixture_count >= 1);
26698        assert_packet_report_green_after_writing_failure_surface(
26699            "differential_suite_produces_structured_drift",
26700            &diff_report.report,
26701        );
26702        if diff_report.report.is_green() {
26703            assert_eq!(diff_report.drift_summary.critical_count, 0);
26704        }
26705    }
26706
26707    #[test]
26708    fn differential_by_id_matches_legacy_report() {
26709        let cfg = HarnessConfig::default_paths();
26710        let legacy_report =
26711            run_packet_by_id(&cfg, "FP-P2C-001", OracleMode::FixtureExpected).expect("legacy");
26712        let diff_report = run_differential_by_id(&cfg, "FP-P2C-001", OracleMode::FixtureExpected)
26713            .expect("differential");
26714        assert_eq!(
26715            diff_report.report.fixture_count,
26716            legacy_report.fixture_count
26717        );
26718        assert_eq!(diff_report.report.passed, legacy_report.passed);
26719        assert_eq!(diff_report.report.failed, legacy_report.failed);
26720    }
26721
26722    /// br-frankenpandas-fixture-corpus-stale-vs-oracle-p6srr: a RETIRED fixture
26723    /// must never read as a pass, must stay in the denominator, and must carry
26724    /// its reason.
26725    ///
26726    /// The negative control is the arithmetic itself: under the previous
26727    /// `passed = len - failed` inference, the retired case below would have
26728    /// been counted as PASSED — a fixture that was never executed presented as
26729    /// one that was checked. That is the pass-by-skip hazard, and this test
26730    /// fails if anyone reintroduces the inference.
26731    #[test]
26732    fn retired_fixture_is_not_a_pass_and_stays_in_the_denominator_p6srr() {
26733        let make = |case_id: &str, status: CaseStatus, reason: Option<&str>| DifferentialResult {
26734            case_id: case_id.to_owned(),
26735            packet_id: "FP-P2C-001".to_owned(),
26736            operation: FixtureOperation::SeriesAdd,
26737            mode: RuntimeMode::Strict,
26738            replay_key: String::new(),
26739            trace_id: String::new(),
26740            oracle_source: FixtureOracleSource::Fixture,
26741            status,
26742            drift_records: Vec::new(),
26743            evidence_records: 0,
26744            retired_reason: reason.map(str::to_owned),
26745        };
26746
26747        let results = vec![
26748            make("passing", CaseStatus::Pass, None),
26749            make(
26750                "retired",
26751                CaseStatus::Retired,
26752                Some("oracle no longer supports operation 'column_dtype_check'"),
26753            ),
26754        ];
26755        let report = build_differential_report("suite".to_owned(), None, false, results).report;
26756
26757        // In the denominator, but NOT in passed.
26758        assert_eq!(report.fixture_count, 2, "retired stays in the denominator");
26759        assert_eq!(report.passed, 1, "retired must NOT be counted as a pass");
26760        assert_eq!(report.failed, 0);
26761        assert_eq!(report.retired, 1);
26762        assert_eq!(
26763            report.passed + report.failed + report.retired,
26764            report.fixture_count,
26765            "the three buckets must account for every fixture"
26766        );
26767        // Executed coverage is smaller than the fixture count, and visibly so.
26768        assert_eq!(report.executed(), 1);
26769
26770        // The reason survives to the report, named per case.
26771        let retirement = report.retirement_report();
26772        assert_eq!(retirement.len(), 1);
26773        assert!(
26774            retirement[0].contains("column_dtype_check"),
26775            "retirement must carry its reason, got {:?}",
26776            retirement[0]
26777        );
26778        assert!(retirement[0].contains("RETIRED"));
26779
26780        // A retired case is not silently green: its status is distinguishable.
26781        let retired_case = report
26782            .results
26783            .iter()
26784            .find(|r| r.case_id == "retired")
26785            .expect("retired case present");
26786        assert_eq!(retired_case.status, CaseStatus::Retired);
26787        assert_ne!(retired_case.status, CaseStatus::Pass);
26788        assert!(retired_case.mismatch.is_some(), "reason lands in mismatch");
26789    }
26790
26791    #[test]
26792    fn differential_result_converts_to_case_result() {
26793        let diff = DifferentialResult {
26794            case_id: "test".to_owned(),
26795            packet_id: "FP-P2C-001".to_owned(),
26796            operation: FixtureOperation::SeriesAdd,
26797            mode: RuntimeMode::Strict,
26798            replay_key: "FP-P2C-001/test/strict".to_owned(),
26799            trace_id: "FP-P2C-001:test:strict".to_owned(),
26800            oracle_source: FixtureOracleSource::Fixture,
26801            status: CaseStatus::Pass,
26802            drift_records: Vec::new(),
26803            evidence_records: 0,
26804            retired_reason: None,
26805        };
26806        let case = diff.to_case_result();
26807        assert_eq!(case.status, CaseStatus::Pass);
26808        assert!(case.mismatch.is_none());
26809        assert_eq!(case.replay_key, "FP-P2C-001/test/strict");
26810        assert_eq!(case.trace_id, "FP-P2C-001:test:strict");
26811    }
26812
26813    #[test]
26814    fn differential_result_with_drift_converts_mismatch_string() {
26815        let diff = DifferentialResult {
26816            case_id: "test".to_owned(),
26817            packet_id: "FP-P2C-001".to_owned(),
26818            operation: FixtureOperation::SeriesAdd,
26819            mode: RuntimeMode::Strict,
26820            replay_key: "FP-P2C-001/test/strict".to_owned(),
26821            trace_id: "FP-P2C-001:test:strict".to_owned(),
26822            oracle_source: FixtureOracleSource::Fixture,
26823            status: CaseStatus::Fail,
26824            drift_records: vec![
26825                DriftRecord {
26826                    category: ComparisonCategory::Value,
26827                    level: DriftLevel::Critical,
26828                    mismatch_class: "value_critical".to_owned(),
26829                    location: "series.values[0]".to_owned(),
26830                    message: "value mismatch".to_owned(),
26831                },
26832                DriftRecord {
26833                    category: ComparisonCategory::Index,
26834                    level: DriftLevel::NonCritical,
26835                    mismatch_class: "index_non_critical".to_owned(),
26836                    location: "series.index".to_owned(),
26837                    message: "order divergence".to_owned(),
26838                },
26839            ],
26840            evidence_records: 0,
26841            retired_reason: None,
26842        };
26843        let case = diff.to_case_result();
26844        assert_eq!(case.status, CaseStatus::Fail);
26845        let mismatch = case.mismatch.expect("should have mismatch");
26846        assert!(mismatch.contains("Value"));
26847        assert!(mismatch.contains("Index"));
26848        assert!(mismatch.contains("Critical"));
26849        assert!(mismatch.contains("NonCritical"));
26850    }
26851
26852    #[test]
26853    fn drift_summary_counts_categories() {
26854        let results = vec![DifferentialResult {
26855            case_id: "test".to_owned(),
26856            packet_id: "FP-P2C-001".to_owned(),
26857            operation: FixtureOperation::SeriesAdd,
26858            mode: RuntimeMode::Strict,
26859            replay_key: "FP-P2C-001/test/strict".to_owned(),
26860            trace_id: "FP-P2C-001:test:strict".to_owned(),
26861            oracle_source: FixtureOracleSource::Fixture,
26862            status: CaseStatus::Fail,
26863            drift_records: vec![
26864                DriftRecord {
26865                    category: ComparisonCategory::Value,
26866                    level: DriftLevel::Critical,
26867                    mismatch_class: "value_critical".to_owned(),
26868                    location: "test[0]".to_owned(),
26869                    message: "mismatch".to_owned(),
26870                },
26871                DriftRecord {
26872                    category: ComparisonCategory::Index,
26873                    level: DriftLevel::NonCritical,
26874                    mismatch_class: "index_non_critical".to_owned(),
26875                    location: "test.index".to_owned(),
26876                    message: "order".to_owned(),
26877                },
26878                DriftRecord {
26879                    category: ComparisonCategory::Nullness,
26880                    level: DriftLevel::Informational,
26881                    mismatch_class: "nullness_informational".to_owned(),
26882                    location: "test[1]".to_owned(),
26883                    message: "nan handling".to_owned(),
26884                },
26885            ],
26886            evidence_records: 0,
26887            retired_reason: None,
26888        }];
26889        let summary = super::summarize_drift(&results);
26890        assert_eq!(summary.total_drift_records, 3);
26891        assert_eq!(summary.critical_count, 1);
26892        assert_eq!(summary.non_critical_count, 1);
26893        assert_eq!(summary.informational_count, 1);
26894        assert_eq!(summary.categories.len(), 3);
26895    }
26896
26897    #[test]
26898    fn build_differential_report_aggregates_correctly() {
26899        let results = vec![
26900            DifferentialResult {
26901                case_id: "pass_case".to_owned(),
26902                packet_id: "FP-P2C-001".to_owned(),
26903                operation: FixtureOperation::SeriesAdd,
26904                mode: RuntimeMode::Strict,
26905                replay_key: "FP-P2C-001/pass_case/strict".to_owned(),
26906                trace_id: "FP-P2C-001:pass_case:strict".to_owned(),
26907                oracle_source: FixtureOracleSource::Fixture,
26908                status: CaseStatus::Pass,
26909                drift_records: Vec::new(),
26910                evidence_records: 0,
26911                retired_reason: None,
26912            },
26913            DifferentialResult {
26914                case_id: "fail_case".to_owned(),
26915                packet_id: "FP-P2C-001".to_owned(),
26916                operation: FixtureOperation::SeriesAdd,
26917                mode: RuntimeMode::Strict,
26918                replay_key: "FP-P2C-001/fail_case/strict".to_owned(),
26919                trace_id: "FP-P2C-001:fail_case:strict".to_owned(),
26920                oracle_source: FixtureOracleSource::Fixture,
26921                status: CaseStatus::Fail,
26922                drift_records: vec![DriftRecord {
26923                    category: ComparisonCategory::Value,
26924                    level: DriftLevel::Critical,
26925                    mismatch_class: "value_critical".to_owned(),
26926                    location: "v[0]".to_owned(),
26927                    message: "bad".to_owned(),
26928                }],
26929                evidence_records: 1,
26930                retired_reason: None,
26931            },
26932        ];
26933        let report = build_differential_report(
26934            "test_suite".to_owned(),
26935            Some("FP-P2C-001".to_owned()),
26936            true,
26937            results,
26938        );
26939        assert_eq!(report.report.fixture_count, 2);
26940        assert_eq!(report.report.passed, 1);
26941        assert_eq!(report.report.failed, 1);
26942        assert_eq!(report.differential_results.len(), 2);
26943        assert_eq!(report.drift_summary.total_drift_records, 1);
26944        assert_eq!(report.drift_summary.critical_count, 1);
26945    }
26946
26947    #[test]
26948    fn differential_report_serializes_to_json() {
26949        let cfg = HarnessConfig::default_paths();
26950        let diff_report = run_differential_by_id(&cfg, "FP-P2C-001", OracleMode::FixtureExpected)
26951            .expect("differential");
26952        let json = serde_json::to_string_pretty(&diff_report).expect("serialize");
26953        assert!(json.contains("differential_results"));
26954        assert!(json.contains("drift_summary"));
26955    }
26956
26957    #[test]
26958    fn differential_all_packets_green() {
26959        let cfg = HarnessConfig::default_paths();
26960        let mut packet_ids: Vec<String> = run_packets_grouped(&cfg, &SuiteOptions::default())
26961            .expect("grouped")
26962            .into_iter()
26963            .map(|report| {
26964                report
26965                    .packet_id
26966                    .expect("grouped report should have packet_id")
26967            })
26968            .collect();
26969        packet_ids.sort();
26970        packet_ids.dedup();
26971        assert!(
26972            !packet_ids.is_empty(),
26973            "expected at least one packet id from grouped reports"
26974        );
26975        for packet_id in packet_ids {
26976            let diff_report = run_differential_by_id(&cfg, &packet_id, OracleMode::FixtureExpected)
26977                .expect("differential report for discovered packet should run");
26978            assert_packet_report_green_after_writing_failure_surface(
26979                &format!("differential_all_packets_green_{packet_id}"),
26980                &diff_report.report,
26981            );
26982        }
26983    }
26984
26985    #[test]
26986    fn differential_validation_log_contains_required_fields() {
26987        let cfg = HarnessConfig::default_paths();
26988        let report =
26989            run_differential_by_id(&cfg, "FP-P2C-001", OracleMode::FixtureExpected).expect("diff");
26990        let entries = build_differential_validation_log(&report);
26991        assert!(
26992            !entries.is_empty(),
26993            "expected differential validation entries"
26994        );
26995
26996        for entry in entries {
26997            assert_eq!(entry.packet_id, "FP-P2C-001");
26998            assert!(!entry.case_id.is_empty());
26999            assert!(!entry.trace_id.is_empty());
27000            assert!(!entry.replay_key.is_empty());
27001            assert!(!entry.mismatch_class.is_empty());
27002        }
27003    }
27004
27005    #[test]
27006    fn differential_validation_log_writes_jsonl() {
27007        let tmp = tempfile::tempdir().expect("tmp");
27008        let mut cfg = HarnessConfig::default_paths();
27009        cfg.repo_root = tmp.path().to_path_buf();
27010
27011        let report =
27012            run_differential_by_id(&cfg, "FP-P2C-001", OracleMode::FixtureExpected).expect("diff");
27013        let path = write_differential_validation_log(&cfg, &report).expect("write log");
27014        assert!(path.exists(), "differential validation log should exist");
27015        let content = fs::read_to_string(path).expect("read");
27016        let lines: Vec<&str> = content.lines().collect();
27017        assert!(!lines.is_empty(), "expected at least one jsonl row");
27018        for line in lines {
27019            let row: serde_json::Value = serde_json::from_str(line).expect("json row");
27020            for required in [
27021                "packet_id",
27022                "case_id",
27023                "mode",
27024                "trace_id",
27025                "oracle_source",
27026                "mismatch_class",
27027                "replay_key",
27028            ] {
27029                assert!(row.get(required).is_some(), "missing field: {required}");
27030            }
27031        }
27032    }
27033
27034    #[test]
27035    fn fault_injection_validation_classifies_strict_vs_hardened() {
27036        let cfg = HarnessConfig::default_paths();
27037        let report =
27038            run_fault_injection_validation_by_id(&cfg, "FP-P2C-001", OracleMode::FixtureExpected)
27039                .expect("fault report");
27040        assert_eq!(report.packet_id, "FP-P2C-001");
27041        assert!(report.entry_count > 0);
27042        assert!(report.strict_violation_count > 0);
27043        assert!(report.hardened_allowlisted_count > 0);
27044        assert_eq!(
27045            report.entry_count,
27046            report.strict_violation_count + report.hardened_allowlisted_count
27047        );
27048
27049        for entry in &report.entries {
27050            assert!(!entry.case_id.is_empty());
27051            assert!(!entry.trace_id.is_empty());
27052            assert!(!entry.replay_key.is_empty());
27053            assert!(!entry.mismatch_class.is_empty());
27054            match entry.classification {
27055                FaultInjectionClassification::StrictViolation => {
27056                    assert_eq!(entry.mode, RuntimeMode::Strict);
27057                }
27058                FaultInjectionClassification::HardenedAllowlisted => {
27059                    assert_eq!(entry.mode, RuntimeMode::Hardened);
27060                }
27061            }
27062        }
27063    }
27064
27065    #[test]
27066    fn fault_injection_validation_report_writes_json() {
27067        let tmp = tempfile::tempdir().expect("tmp");
27068        let mut cfg = HarnessConfig::default_paths();
27069        cfg.repo_root = tmp.path().to_path_buf();
27070
27071        let report =
27072            run_fault_injection_validation_by_id(&cfg, "FP-P2C-001", OracleMode::FixtureExpected)
27073                .expect("fault report");
27074        let path = write_fault_injection_validation_report(&cfg, &report).expect("write report");
27075        assert!(path.exists(), "fault injection report should exist");
27076        let row: serde_json::Value =
27077            serde_json::from_str(&fs::read_to_string(path).expect("read")).expect("json");
27078        assert_eq!(row["packet_id"], "FP-P2C-001");
27079        assert!(row.get("strict_violation_count").is_some());
27080        assert!(row.get("hardened_allowlisted_count").is_some());
27081        assert!(row.get("entries").is_some());
27082    }
27083
27084    fn amplify_compat_closure_scenario_builder_workload(
27085        report: &mut super::E2eReport,
27086        repeats: usize,
27087    ) {
27088        let base_case_events: Vec<_> = report
27089            .forensic_log
27090            .events
27091            .iter()
27092            .filter(|event| {
27093                matches!(
27094                    event.event,
27095                    ForensicEventKind::CaseStart { .. } | ForensicEventKind::CaseEnd { .. }
27096                )
27097            })
27098            .cloned()
27099            .collect();
27100
27101        for repeat in 0..repeats {
27102            for template in &base_case_events {
27103                let mut event = template.clone();
27104                match &mut event.event {
27105                    ForensicEventKind::CaseStart {
27106                        case_id,
27107                        trace_id,
27108                        step_id,
27109                        assertion_path,
27110                        replay_cmd,
27111                        seed,
27112                        ..
27113                    } => {
27114                        *case_id = format!("{case_id}::amp{repeat}");
27115                        *trace_id = format!("{trace_id}::amp{repeat}");
27116                        *step_id = format!("{step_id}::amp{repeat}");
27117                        *assertion_path = format!("{assertion_path}::amp{repeat}");
27118                        *replay_cmd = format!("{replay_cmd} -- --amplify-seed={repeat}");
27119                        *seed = seed.saturating_add(repeat as u64 + 1);
27120                    }
27121                    ForensicEventKind::CaseEnd {
27122                        case_id,
27123                        trace_id,
27124                        step_id,
27125                        assertion_path,
27126                        replay_cmd,
27127                        replay_key,
27128                        seed,
27129                        ..
27130                    } => {
27131                        *case_id = format!("{case_id}::amp{repeat}");
27132                        *trace_id = format!("{trace_id}::amp{repeat}");
27133                        *step_id = format!("{step_id}::amp{repeat}");
27134                        *assertion_path = format!("{assertion_path}::amp{repeat}");
27135                        *replay_cmd = format!("{replay_cmd} -- --amplify-seed={repeat}");
27136                        *replay_key = format!("{replay_key}::amp{repeat}");
27137                        *seed = seed.saturating_add(repeat as u64 + 1);
27138                    }
27139                    _ => {}
27140                }
27141                report.forensic_log.events.push(event);
27142            }
27143        }
27144    }
27145
27146    fn quantile_from_sorted(samples: &[u128], pct: usize) -> u128 {
27147        let len = samples.len();
27148        assert!(len > 0);
27149        let idx = (len.saturating_sub(1) * pct) / 100;
27150        samples[idx]
27151    }
27152
27153    fn latency_quantiles(mut samples_ns: Vec<u128>) -> (u128, u128, u128) {
27154        samples_ns.sort_unstable();
27155        (
27156            quantile_from_sorted(&samples_ns, 50),
27157            quantile_from_sorted(&samples_ns, 95),
27158            quantile_from_sorted(&samples_ns, 99),
27159        )
27160    }
27161
27162    #[test]
27163    fn compat_closure_e2e_scenario_report_contains_required_step_fields() {
27164        let config = E2eConfig {
27165            harness: HarnessConfig::default_paths(),
27166            options: SuiteOptions {
27167                packet_filter: Some("FP-P2C-001".to_owned()),
27168                oracle_mode: OracleMode::FixtureExpected,
27169            },
27170            write_artifacts: false,
27171            enforce_gates: false,
27172            append_drift_history: false,
27173            forensic_log_path: None,
27174        };
27175
27176        let mut hooks = NoopHooks;
27177        let e2e = run_e2e_suite(&config, &mut hooks).expect("e2e");
27178        let report = build_compat_closure_e2e_scenario_report(&e2e, &[]);
27179        assert!(report.scenario_count >= 1);
27180        assert!(!report.steps.is_empty());
27181
27182        for step in report.steps {
27183            assert!(!step.scenario_id.is_empty());
27184            assert!(!step.packet_id.is_empty());
27185            assert!(!step.trace_id.is_empty());
27186            assert!(!step.step_id.is_empty());
27187            assert!(!step.command_or_api.is_empty());
27188            assert!(!step.input_ref.is_empty());
27189            assert!(!step.output_ref.is_empty());
27190            assert!(step.duration_ms >= 1);
27191            assert!(!step.outcome.is_empty());
27192            assert!(!step.reason_code.is_empty());
27193            assert!(!step.replay_cmd.is_empty());
27194        }
27195    }
27196
27197    #[test]
27198    fn compat_closure_e2e_scenario_report_includes_failure_injection_steps() {
27199        let e2e_config = E2eConfig {
27200            harness: HarnessConfig::default_paths(),
27201            options: SuiteOptions {
27202                packet_filter: Some("FP-P2C-001".to_owned()),
27203                oracle_mode: OracleMode::FixtureExpected,
27204            },
27205            write_artifacts: false,
27206            enforce_gates: false,
27207            append_drift_history: false,
27208            forensic_log_path: None,
27209        };
27210
27211        let mut hooks = NoopHooks;
27212        let e2e = run_e2e_suite(&e2e_config, &mut hooks).expect("e2e");
27213        let fault = run_fault_injection_validation_by_id(
27214            &e2e_config.harness,
27215            "FP-P2C-001",
27216            OracleMode::FixtureExpected,
27217        )
27218        .expect("fault");
27219        let report = build_compat_closure_e2e_scenario_report(&e2e, &[fault]);
27220
27221        assert!(
27222            report.steps.iter().any(|step| {
27223                step.kind == super::CompatClosureScenarioKind::FailureInjection
27224                    && step.command_or_api == "fault_injection"
27225            }),
27226            "expected failure-injection steps in scenario report"
27227        );
27228    }
27229
27230    #[test]
27231    fn compat_closure_e2e_scenario_optimized_path_is_isomorphic_to_baseline() {
27232        let e2e_config = E2eConfig {
27233            harness: HarnessConfig::default_paths(),
27234            options: SuiteOptions {
27235                packet_filter: Some("FP-P2C-001".to_owned()),
27236                oracle_mode: OracleMode::FixtureExpected,
27237            },
27238            write_artifacts: false,
27239            enforce_gates: false,
27240            append_drift_history: false,
27241            forensic_log_path: None,
27242        };
27243
27244        let mut hooks = NoopHooks;
27245        let mut e2e = run_e2e_suite(&e2e_config, &mut hooks).expect("e2e");
27246        amplify_compat_closure_scenario_builder_workload(&mut e2e, 256);
27247        let fault = run_fault_injection_validation_by_id(
27248            &e2e_config.harness,
27249            "FP-P2C-001",
27250            OracleMode::FixtureExpected,
27251        )
27252        .expect("fault");
27253
27254        let (baseline, baseline_stats) =
27255            super::build_compat_closure_e2e_scenario_report_baseline_with_stats(
27256                &e2e,
27257                std::slice::from_ref(&fault),
27258            );
27259        let (optimized, optimized_stats) =
27260            super::build_compat_closure_e2e_scenario_report_optimized_with_stats(
27261                &e2e,
27262                std::slice::from_ref(&fault),
27263            );
27264        assert_eq!(optimized, baseline);
27265        assert!(
27266            baseline_stats.trace_metadata_index_nodes > optimized_stats.trace_metadata_index_nodes
27267        );
27268        assert!(
27269            baseline_stats.trace_metadata_lookup_steps
27270                > optimized_stats.trace_metadata_lookup_steps
27271        );
27272    }
27273
27274    #[test]
27275    fn compat_closure_e2e_scenario_profile_snapshot_reports_index_delta() {
27276        const ITERATIONS: usize = 64;
27277        let e2e_config = E2eConfig {
27278            harness: HarnessConfig::default_paths(),
27279            options: SuiteOptions {
27280                packet_filter: Some("FP-P2C-001".to_owned()),
27281                oracle_mode: OracleMode::FixtureExpected,
27282            },
27283            write_artifacts: false,
27284            enforce_gates: false,
27285            append_drift_history: false,
27286            forensic_log_path: None,
27287        };
27288
27289        let mut hooks = NoopHooks;
27290        let mut e2e = run_e2e_suite(&e2e_config, &mut hooks).expect("e2e");
27291        amplify_compat_closure_scenario_builder_workload(&mut e2e, 256);
27292        let fault = run_fault_injection_validation_by_id(
27293            &e2e_config.harness,
27294            "FP-P2C-001",
27295            OracleMode::FixtureExpected,
27296        )
27297        .expect("fault");
27298
27299        let mut baseline_ns = Vec::with_capacity(ITERATIONS);
27300        let mut optimized_ns = Vec::with_capacity(ITERATIONS);
27301        let mut baseline_index_nodes_total = 0_usize;
27302        let mut optimized_index_nodes_total = 0_usize;
27303        let mut baseline_lookup_steps_total = 0_usize;
27304        let mut optimized_lookup_steps_total = 0_usize;
27305
27306        for _ in 0..ITERATIONS {
27307            let baseline_start = std::time::Instant::now();
27308            let (baseline, baseline_stats) =
27309                super::build_compat_closure_e2e_scenario_report_baseline_with_stats(
27310                    &e2e,
27311                    std::slice::from_ref(&fault),
27312                );
27313            baseline_ns.push(baseline_start.elapsed().as_nanos());
27314            baseline_index_nodes_total += baseline_stats.trace_metadata_index_nodes;
27315            baseline_lookup_steps_total += baseline_stats.trace_metadata_lookup_steps;
27316
27317            let optimized_start = std::time::Instant::now();
27318            let (optimized, optimized_stats) =
27319                super::build_compat_closure_e2e_scenario_report_optimized_with_stats(
27320                    &e2e,
27321                    std::slice::from_ref(&fault),
27322                );
27323            optimized_ns.push(optimized_start.elapsed().as_nanos());
27324            optimized_index_nodes_total += optimized_stats.trace_metadata_index_nodes;
27325            optimized_lookup_steps_total += optimized_stats.trace_metadata_lookup_steps;
27326
27327            assert_eq!(optimized, baseline);
27328            std::hint::black_box(optimized.steps.len());
27329        }
27330
27331        let (baseline_p50_ns, baseline_p95_ns, baseline_p99_ns) = latency_quantiles(baseline_ns);
27332        let (optimized_p50_ns, optimized_p95_ns, optimized_p99_ns) =
27333            latency_quantiles(optimized_ns);
27334        assert!(baseline_index_nodes_total > optimized_index_nodes_total);
27335        assert!(baseline_lookup_steps_total > optimized_lookup_steps_total);
27336
27337        println!(
27338            "compat_closure_e2e_scenario_profile_snapshot baseline_ns[p50={baseline_p50_ns},p95={baseline_p95_ns},p99={baseline_p99_ns}] optimized_ns[p50={optimized_p50_ns},p95={optimized_p95_ns},p99={optimized_p99_ns}] trace_metadata_index_nodes_baseline={baseline_index_nodes_total} trace_metadata_index_nodes_optimized={optimized_index_nodes_total} trace_metadata_lookup_steps_baseline={baseline_lookup_steps_total} trace_metadata_lookup_steps_optimized={optimized_lookup_steps_total}"
27339        );
27340    }
27341
27342    #[test]
27343    fn compat_closure_e2e_scenario_report_writes_json() {
27344        let tmp = tempfile::tempdir().expect("tmp");
27345        let config = E2eConfig {
27346            harness: HarnessConfig::default_paths(),
27347            options: SuiteOptions {
27348                packet_filter: Some("FP-P2C-001".to_owned()),
27349                oracle_mode: OracleMode::FixtureExpected,
27350            },
27351            write_artifacts: false,
27352            enforce_gates: false,
27353            append_drift_history: false,
27354            forensic_log_path: None,
27355        };
27356        let mut hooks = NoopHooks;
27357        let e2e = run_e2e_suite(&config, &mut hooks).expect("e2e");
27358        let report = build_compat_closure_e2e_scenario_report(&e2e, &[]);
27359        let path = write_compat_closure_e2e_scenario_report(tmp.path(), &report).expect("write");
27360        assert!(path.exists());
27361        let json: serde_json::Value =
27362            serde_json::from_str(&fs::read_to_string(path).expect("read")).expect("json");
27363        assert_eq!(json["suite_id"], "COMPAT-CLOSURE-G");
27364        assert!(json.get("steps").is_some());
27365    }
27366
27367    #[test]
27368    fn compat_closure_final_evidence_pack_contains_required_fields() {
27369        let _artifact_guard = phase2c_artifact_test_lock();
27370        let cfg = HarnessConfig::default_paths();
27371        let options = SuiteOptions {
27372            packet_filter: Some("FP-P2C-001".to_owned()),
27373            oracle_mode: OracleMode::FixtureExpected,
27374        };
27375        let reports = run_packets_grouped(&cfg, &options).expect("reports");
27376        let _ = super::write_grouped_artifacts(&cfg, &reports).expect("write artifacts");
27377        let differential = run_differential_by_id(&cfg, "FP-P2C-001", OracleMode::FixtureExpected)
27378            .expect("differential");
27379        let fault =
27380            run_fault_injection_validation_by_id(&cfg, "FP-P2C-001", OracleMode::FixtureExpected)
27381                .expect("fault");
27382
27383        let pack =
27384            build_compat_closure_final_evidence_pack(&cfg, &reports, &[differential], &[fault])
27385                .expect("build final evidence");
27386        let payload = serde_json::to_value(&pack).expect("serialize");
27387        for required in [
27388            "generated_unix_ms",
27389            "suite_id",
27390            "coverage_report",
27391            "strict_zero_drift",
27392            "hardened_allowlisted_total",
27393            "packets",
27394            "migration_manifest",
27395            "reproducibility_ledger",
27396            "benchmark_delta_report_ref",
27397            "invariant_checklist_delta",
27398            "risk_note_update",
27399            "all_checks_passed",
27400            "attestation_signature",
27401        ] {
27402            assert!(payload.get(required).is_some(), "missing field: {required}");
27403        }
27404        assert!(pack.coverage_report.is_complete());
27405        assert!(pack.attestation_signature.starts_with("sha256:"));
27406        assert!(
27407            pack.all_checks_passed,
27408            "expected all checks to pass for fixture-backed green packet"
27409        );
27410        assert!(
27411            pack.packets
27412                .iter()
27413                .any(|packet| packet.packet_id == "FP-P2C-001"),
27414            "expected packet snapshot for FP-P2C-001"
27415        );
27416    }
27417
27418    #[test]
27419    fn compat_closure_final_evidence_pack_writes_json_artifacts() {
27420        let _artifact_guard = phase2c_artifact_test_lock();
27421        let cfg = HarnessConfig::default_paths();
27422        let options = SuiteOptions {
27423            packet_filter: Some("FP-P2C-001".to_owned()),
27424            oracle_mode: OracleMode::FixtureExpected,
27425        };
27426        let reports = run_packets_grouped(&cfg, &options).expect("reports");
27427        let _ = super::write_grouped_artifacts(&cfg, &reports).expect("write artifacts");
27428        let differential = run_differential_by_id(&cfg, "FP-P2C-001", OracleMode::FixtureExpected)
27429            .expect("differential");
27430        let fault =
27431            run_fault_injection_validation_by_id(&cfg, "FP-P2C-001", OracleMode::FixtureExpected)
27432                .expect("fault");
27433
27434        let pack =
27435            build_compat_closure_final_evidence_pack(&cfg, &reports, &[differential], &[fault])
27436                .expect("build final evidence");
27437        // Write under a temp root, not the checkout: the pack carries a fresh
27438        // timestamp and signature on every run, so writing the tracked
27439        // artifacts/phase2c/compat_closure_* files dirtied the shared checkout on
27440        // every `cargo test -p fp-conformance` (and peers then committed the churn,
27441        // e.g. 3ab22efec). br-frankenpandas-rc0923-epic-first-green-ci-kyvo0.5.
27442        let out = tempfile::tempdir().expect("tmp");
27443        let mut out_cfg = cfg.clone();
27444        out_cfg.repo_root = out.path().to_path_buf();
27445        let paths = write_compat_closure_final_evidence_pack(&out_cfg, &pack).expect("write final");
27446        assert!(paths.evidence_pack_path.starts_with(out.path()));
27447
27448        assert!(paths.evidence_pack_path.exists());
27449        assert!(paths.migration_manifest_path.exists());
27450        assert!(paths.attestation_summary_path.exists());
27451
27452        let summary: super::CompatClosureAttestationSummary = serde_json::from_str(
27453            &fs::read_to_string(&paths.attestation_summary_path).expect("read"),
27454        )
27455        .expect("summary json");
27456        assert_eq!(summary.attestation_signature, pack.attestation_signature);
27457        assert_eq!(
27458            summary.coverage_percent,
27459            pack.coverage_report.achieved_percent
27460        );
27461        assert_eq!(summary.packet_count, pack.packets.len());
27462    }
27463
27464    // === E2E Orchestrator + Forensic Logging Tests (bd-2gi.6) ===
27465
27466    #[test]
27467    fn forensic_log_records_events_with_timestamps() {
27468        let mut log = ForensicLog::new();
27469        assert!(log.is_empty());
27470
27471        log.record(ForensicEventKind::SuiteStart {
27472            suite: "test".to_owned(),
27473            packet_filter: None,
27474        });
27475        log.record(ForensicEventKind::SuiteEnd {
27476            suite: "test".to_owned(),
27477            total_fixtures: 5,
27478            passed: 5,
27479            failed: 0,
27480        });
27481
27482        assert_eq!(log.len(), 2);
27483        assert!(log.events[0].ts_unix_ms > 0);
27484        assert!(log.events[1].ts_unix_ms >= log.events[0].ts_unix_ms);
27485    }
27486
27487    #[test]
27488    fn forensic_log_serializes_to_jsonl() {
27489        let mut log = ForensicLog::new();
27490        log.record(ForensicEventKind::PacketStart {
27491            packet_id: "FP-P2C-001".to_owned(),
27492        });
27493        log.record(ForensicEventKind::CaseEnd {
27494            scenario_id: "test:FP-P2C-001".to_owned(),
27495            packet_id: "FP-P2C-001".to_owned(),
27496            case_id: "test_case".to_owned(),
27497            trace_id: "FP-P2C-001:test_case:strict".to_owned(),
27498            step_id: "case:test_case".to_owned(),
27499            seed: 42,
27500            assertion_path: "ASUPERSYNC-G/FP-P2C-001/test_case".to_owned(),
27501            result: "pass".to_owned(),
27502            replay_cmd: "cargo test -p fp-conformance -- test_case --nocapture".to_owned(),
27503            decision_action: "allow".to_owned(),
27504            replay_key: "FP-P2C-001/test_case/strict".to_owned(),
27505            mismatch_class: None,
27506            status: CaseStatus::Pass,
27507            evidence_records: 2,
27508            elapsed_us: 1234,
27509        });
27510
27511        let dir = tempfile::tempdir().expect("tempdir");
27512        let path = dir.path().join("forensic.jsonl");
27513        log.write_jsonl(&path).expect("write");
27514
27515        let content = fs::read_to_string(&path).expect("read");
27516        let lines: Vec<&str> = content.lines().collect();
27517        assert_eq!(lines.len(), 2);
27518
27519        // Each line is valid JSON
27520        for line in &lines {
27521            let _: serde_json::Value = serde_json::from_str(line).expect("valid JSON");
27522        }
27523        assert!(lines[0].contains("packet_start"));
27524        assert!(lines[1].contains("case_end"));
27525        assert!(lines[1].contains("test_case"));
27526        assert!(lines[1].contains("assertion_path"));
27527        assert!(lines[1].contains("replay_cmd"));
27528    }
27529
27530    #[test]
27531    fn forensic_event_kind_serde_round_trip() {
27532        let events = vec![
27533            ForensicEventKind::SuiteStart {
27534                suite: "smoke".to_owned(),
27535                packet_filter: Some("FP-P2C-001".to_owned()),
27536            },
27537            ForensicEventKind::ArtifactWritten {
27538                packet_id: "FP-P2C-001".to_owned(),
27539                artifact_kind: "parity_report".to_owned(),
27540                path: "artifacts/phase2c/FP-P2C-001/parity_report.json".to_owned(),
27541            },
27542            ForensicEventKind::GateEvaluated {
27543                packet_id: "FP-P2C-002".to_owned(),
27544                pass: true,
27545                reasons: Vec::new(),
27546            },
27547            ForensicEventKind::Error {
27548                phase: "gate_enforcement".to_owned(),
27549                message: "gate failed".to_owned(),
27550            },
27551        ];
27552
27553        for event in &events {
27554            let json = serde_json::to_string(event).expect("serialize");
27555            let back: ForensicEventKind = serde_json::from_str(&json).expect("deserialize");
27556            assert_eq!(*event, back);
27557        }
27558    }
27559
27560    #[test]
27561    fn e2e_suite_runs_full_pipeline() {
27562        let config = E2eConfig {
27563            harness: HarnessConfig::default_paths(),
27564            options: SuiteOptions::default(),
27565            write_artifacts: false,      // skip artifact writes in test
27566            enforce_gates: false,        // skip enforcement in test
27567            append_drift_history: false, // skip drift history in test
27568            forensic_log_path: None,
27569        };
27570
27571        let mut hooks = NoopHooks;
27572        let report = run_e2e_suite(&config, &mut hooks).expect("e2e");
27573        let expected_packet_count = run_packets_grouped(&config.harness, &config.options)
27574            .expect("grouped")
27575            .len();
27576
27577        assert!(
27578            report.packet_reports.len() == expected_packet_count,
27579            "expected packet report count to match grouped packets: expected={expected_packet_count} actual={}",
27580            report.packet_reports.len()
27581        );
27582        assert!(report.total_fixtures > 0, "should have fixtures");
27583        assert_grouped_reports_green_after_writing_failure_surface(
27584            "e2e_suite_runs_full_pipeline",
27585            &report.packet_reports,
27586        );
27587        if report.is_green() {
27588            assert_eq!(report.total_failed, 0, "no failures expected");
27589        } else {
27590            assert!(
27591                report.total_failed > 0,
27592                "red e2e report should record failures"
27593            );
27594            assert!(
27595                !build_failure_forensics(&report).is_clean(),
27596                "red e2e report should produce forensic failures"
27597            );
27598        }
27599
27600        // Forensic log should have events
27601        assert!(!report.forensic_log.is_empty());
27602
27603        // Should have suite_start and suite_end
27604        let first = &report.forensic_log.events[0].event;
27605        assert!(
27606            matches!(first, ForensicEventKind::SuiteStart { .. }),
27607            "first event should be SuiteStart"
27608        );
27609        let last = &report.forensic_log.events[report.forensic_log.len() - 1].event;
27610        assert!(
27611            matches!(last, ForensicEventKind::SuiteEnd { .. }),
27612            "last event should be SuiteEnd"
27613        );
27614    }
27615
27616    #[test]
27617    fn e2e_suite_with_packet_filter() {
27618        let config = E2eConfig {
27619            harness: HarnessConfig::default_paths(),
27620            options: SuiteOptions {
27621                packet_filter: Some("FP-P2C-001".to_owned()),
27622                oracle_mode: OracleMode::FixtureExpected,
27623            },
27624            write_artifacts: false,
27625            enforce_gates: false,
27626            append_drift_history: false,
27627            forensic_log_path: None,
27628        };
27629
27630        let mut hooks = NoopHooks;
27631        let report = run_e2e_suite(&config, &mut hooks).expect("e2e");
27632
27633        assert_eq!(report.packet_reports.len(), 1);
27634        assert_eq!(
27635            report.packet_reports[0].packet_id.as_deref(),
27636            Some("FP-P2C-001")
27637        );
27638        assert!(report.is_green());
27639    }
27640
27641    #[test]
27642    fn e2e_lifecycle_hooks_called() {
27643        use std::sync::{Arc, Mutex};
27644
27645        #[derive(Default)]
27646        struct TrackingHooks {
27647            calls: Arc<Mutex<Vec<String>>>,
27648        }
27649
27650        impl LifecycleHooks for TrackingHooks {
27651            fn before_suite(&mut self, suite: &str, _filter: &Option<String>) {
27652                self.calls
27653                    .lock()
27654                    .unwrap()
27655                    .push(format!("before_suite:{suite}"));
27656            }
27657            fn after_suite(&mut self, _reports: &[PacketParityReport]) {
27658                self.calls.lock().unwrap().push("after_suite".to_owned());
27659            }
27660            fn before_packet(&mut self, packet_id: &str) {
27661                self.calls
27662                    .lock()
27663                    .unwrap()
27664                    .push(format!("before_packet:{packet_id}"));
27665            }
27666            fn after_packet(&mut self, _report: &PacketParityReport, gate_pass: bool) {
27667                self.calls
27668                    .lock()
27669                    .unwrap()
27670                    .push(format!("after_packet:gate={gate_pass}"));
27671            }
27672            fn after_case(&mut self, result: &CaseResult) {
27673                self.calls
27674                    .lock()
27675                    .unwrap()
27676                    .push(format!("after_case:{}", result.case_id));
27677            }
27678        }
27679
27680        let config = E2eConfig {
27681            harness: HarnessConfig::default_paths(),
27682            options: SuiteOptions {
27683                packet_filter: Some("FP-P2C-001".to_owned()),
27684                oracle_mode: OracleMode::FixtureExpected,
27685            },
27686            write_artifacts: false,
27687            enforce_gates: false,
27688            append_drift_history: false,
27689            forensic_log_path: None,
27690        };
27691
27692        let calls = Arc::new(Mutex::new(Vec::new()));
27693        let mut hooks = TrackingHooks {
27694            calls: calls.clone(),
27695        };
27696        let _report = run_e2e_suite(&config, &mut hooks).expect("e2e");
27697
27698        let logged = calls.lock().unwrap();
27699        assert!(logged[0].starts_with("before_suite:"));
27700        assert!(logged.iter().any(|c| c.starts_with("before_packet:")));
27701        assert!(logged.iter().any(|c| c.starts_with("after_packet:")));
27702        assert!(logged.iter().any(|c| c.starts_with("after_case:")));
27703        assert_eq!(*logged.last().unwrap(), "after_suite");
27704    }
27705
27706    #[test]
27707    fn e2e_forensic_log_writes_to_file() {
27708        let dir = tempfile::tempdir().expect("tempdir");
27709        let log_path = dir.path().join("forensic.jsonl");
27710
27711        let config = E2eConfig {
27712            harness: HarnessConfig::default_paths(),
27713            options: SuiteOptions {
27714                packet_filter: Some("FP-P2C-001".to_owned()),
27715                oracle_mode: OracleMode::FixtureExpected,
27716            },
27717            write_artifacts: false,
27718            enforce_gates: false,
27719            append_drift_history: false,
27720            forensic_log_path: Some(log_path.clone()),
27721        };
27722
27723        let mut hooks = NoopHooks;
27724        let _report = run_e2e_suite(&config, &mut hooks).expect("e2e");
27725
27726        assert!(log_path.exists(), "forensic log file should exist");
27727        let content = fs::read_to_string(&log_path).expect("read");
27728        assert!(content.lines().count() >= 4, "should have multiple events");
27729
27730        // Verify every line is valid JSON
27731        for line in content.lines() {
27732            let parsed: serde_json::Value = serde_json::from_str(line).expect("valid JSON line");
27733            assert!(parsed.get("ts_unix_ms").is_some());
27734            assert!(parsed.get("event").is_some());
27735        }
27736    }
27737
27738    #[test]
27739    fn e2e_case_events_include_replay_bundle_fields() {
27740        let config = E2eConfig {
27741            harness: HarnessConfig::default_paths(),
27742            options: SuiteOptions {
27743                packet_filter: Some("FP-P2C-001".to_owned()),
27744                oracle_mode: OracleMode::FixtureExpected,
27745            },
27746            write_artifacts: false,
27747            enforce_gates: false,
27748            append_drift_history: false,
27749            forensic_log_path: None,
27750        };
27751
27752        let mut hooks = NoopHooks;
27753        let report = run_e2e_suite(&config, &mut hooks).expect("e2e");
27754
27755        let mut saw_case_start = false;
27756        let mut saw_case_end = false;
27757
27758        for event in report.forensic_log.events {
27759            match event.event {
27760                ForensicEventKind::CaseStart {
27761                    seed,
27762                    assertion_path,
27763                    replay_cmd,
27764                    ..
27765                } => {
27766                    saw_case_start = true;
27767                    assert!(seed > 0, "seed should be deterministic non-zero");
27768                    assert!(
27769                        assertion_path.starts_with("ASUPERSYNC-G/"),
27770                        "assertion_path should be namespaced"
27771                    );
27772                    assert!(
27773                        replay_cmd.contains("cargo test -p fp-conformance --"),
27774                        "replay command should target fp-conformance test replay"
27775                    );
27776                }
27777                ForensicEventKind::CaseEnd {
27778                    seed,
27779                    assertion_path,
27780                    result,
27781                    replay_cmd,
27782                    ..
27783                } => {
27784                    saw_case_end = true;
27785                    assert!(seed > 0, "seed should be deterministic non-zero");
27786                    assert!(
27787                        assertion_path.starts_with("ASUPERSYNC-G/"),
27788                        "assertion_path should be namespaced"
27789                    );
27790                    assert!(result == "pass" || result == "fail");
27791                    assert!(
27792                        replay_cmd.contains("cargo test -p fp-conformance --"),
27793                        "replay command should target fp-conformance test replay"
27794                    );
27795                }
27796                _ => {}
27797            }
27798        }
27799
27800        assert!(saw_case_start, "expected at least one case_start event");
27801        assert!(saw_case_end, "expected at least one case_end event");
27802    }
27803
27804    #[test]
27805    fn compat_closure_case_log_contains_required_fields() {
27806        let config = HarnessConfig::default_paths();
27807        let case = CaseResult {
27808            packet_id: "FP-P2C-001".to_owned(),
27809            case_id: "series_add_strict".to_owned(),
27810            mode: RuntimeMode::Strict,
27811            operation: FixtureOperation::SeriesAdd,
27812            status: CaseStatus::Pass,
27813            mismatch: None,
27814            mismatch_class: None,
27815            replay_key: "FP-P2C-001/series_add_strict/strict".to_owned(),
27816            trace_id: "FP-P2C-001:series_add_strict:strict".to_owned(),
27817            elapsed_us: 5_000,
27818            evidence_records: 2,
27819        };
27820
27821        let log = super::build_compat_closure_case_log(
27822            &config,
27823            super::COMPAT_CLOSURE_SUITE_ID,
27824            &case,
27825            1_700_000_000_000,
27826        );
27827        let payload = serde_json::to_value(&log).expect("serialize");
27828
27829        for field in [
27830            "ts_utc",
27831            "suite_id",
27832            "test_id",
27833            "api_surface_id",
27834            "packet_id",
27835            "mode",
27836            "seed",
27837            "input_digest",
27838            "output_digest",
27839            "env_fingerprint",
27840            "artifact_refs",
27841            "duration_ms",
27842            "outcome",
27843            "reason_code",
27844        ] {
27845            assert!(
27846                payload.get(field).is_some(),
27847                "structured compat-closure log missing field: {field}"
27848            );
27849        }
27850
27851        assert_eq!(log.suite_id, super::COMPAT_CLOSURE_SUITE_ID);
27852        assert_eq!(log.api_surface_id, "CC-004");
27853        assert_eq!(log.outcome, "pass");
27854        assert_eq!(log.reason_code, "ok");
27855    }
27856
27857    #[test]
27858    fn compat_closure_case_log_is_deterministic_for_same_inputs() {
27859        let config = HarnessConfig::default_paths();
27860        let case = CaseResult {
27861            packet_id: "FP-P2C-002".to_owned(),
27862            case_id: "index_align_union".to_owned(),
27863            mode: RuntimeMode::Hardened,
27864            operation: FixtureOperation::IndexAlignUnion,
27865            status: CaseStatus::Fail,
27866            mismatch: Some("synthetic mismatch".to_owned()),
27867            mismatch_class: Some("index_critical".to_owned()),
27868            replay_key: "FP-P2C-002/index_align_union/hardened".to_owned(),
27869            trace_id: "FP-P2C-002:index_align_union:hardened".to_owned(),
27870            elapsed_us: 8_000,
27871            evidence_records: 1,
27872        };
27873
27874        let first = super::build_compat_closure_case_log(
27875            &config,
27876            super::COMPAT_CLOSURE_SUITE_ID,
27877            &case,
27878            1_700_000_000_001,
27879        );
27880        let second = super::build_compat_closure_case_log(
27881            &config,
27882            super::COMPAT_CLOSURE_SUITE_ID,
27883            &case,
27884            1_700_000_000_001,
27885        );
27886
27887        let first_json = serde_json::to_vec(&first).expect("serialize");
27888        let second_json = serde_json::to_vec(&second).expect("serialize");
27889        assert_eq!(
27890            first_json, second_json,
27891            "compat-closure logs should be byte-identical for same inputs"
27892        );
27893        assert_eq!(first.reason_code, "index_critical");
27894    }
27895
27896    #[test]
27897    fn compat_closure_mode_split_contracts_hold_across_seed_span() {
27898        for seed in 0_u64..128 {
27899            let mut strict_ledger = fp_runtime::EvidenceLedger::new();
27900            let strict = fp_runtime::RuntimePolicy::strict();
27901            let strict_action = strict.decide_unknown_feature(
27902                "compat-closure",
27903                format!("seed={seed}"),
27904                &mut strict_ledger,
27905            );
27906            assert_eq!(
27907                strict_action,
27908                fp_runtime::DecisionAction::Reject,
27909                "strict mode should fail closed (CC-008)"
27910            );
27911
27912            let cap = 32 + (seed as usize % 64);
27913            let mut hardened_ledger = fp_runtime::EvidenceLedger::new();
27914            let hardened = fp_runtime::RuntimePolicy::hardened(Some(cap));
27915            let hardened_action = hardened.decide_join_admission(cap + 1, &mut hardened_ledger);
27916            assert_eq!(
27917                hardened_action,
27918                fp_runtime::DecisionAction::Repair,
27919                "hardened mode should enforce bounded repair over cap (CC-009)"
27920            );
27921        }
27922    }
27923
27924    #[test]
27925    fn compat_closure_coverage_report_is_complete() {
27926        let config = HarnessConfig::default_paths();
27927        let report = super::build_compat_closure_coverage_report(&config).expect("coverage report");
27928        assert_eq!(report.suite_id, super::COMPAT_CLOSURE_SUITE_ID);
27929        assert!(
27930            report.is_complete(),
27931            "compat-closure matrix has uncovered rows: {:?}",
27932            report.uncovered_rows
27933        );
27934        assert_eq!(report.achieved_percent, 100);
27935        assert_eq!(report.coverage_floor_percent, 100);
27936    }
27937
27938    #[test]
27939    fn e2e_emits_compat_closure_case_events() {
27940        let config = E2eConfig {
27941            harness: HarnessConfig::default_paths(),
27942            options: SuiteOptions {
27943                packet_filter: Some("FP-P2C-001".to_owned()),
27944                oracle_mode: OracleMode::FixtureExpected,
27945            },
27946            write_artifacts: false,
27947            enforce_gates: false,
27948            append_drift_history: false,
27949            forensic_log_path: None,
27950        };
27951
27952        let mut hooks = NoopHooks;
27953        let report = run_e2e_suite(&config, &mut hooks).expect("e2e");
27954
27955        let compat_events: Vec<_> = report
27956            .forensic_log
27957            .events
27958            .iter()
27959            .filter_map(|entry| match &entry.event {
27960                ForensicEventKind::CompatClosureCase {
27961                    suite_id,
27962                    api_surface_id,
27963                    seed,
27964                    input_digest,
27965                    output_digest,
27966                    env_fingerprint,
27967                    artifact_refs,
27968                    duration_ms,
27969                    outcome,
27970                    reason_code,
27971                    ..
27972                } => Some((
27973                    suite_id,
27974                    api_surface_id,
27975                    seed,
27976                    input_digest,
27977                    output_digest,
27978                    env_fingerprint,
27979                    artifact_refs,
27980                    duration_ms,
27981                    outcome,
27982                    reason_code,
27983                )),
27984                _ => None,
27985            })
27986            .collect();
27987
27988        assert!(
27989            !compat_events.is_empty(),
27990            "expected compat-closure case logs in forensic output"
27991        );
27992
27993        for (
27994            suite_id,
27995            api_surface_id,
27996            seed,
27997            input_digest,
27998            output_digest,
27999            env_fingerprint,
28000            artifact_refs,
28001            duration_ms,
28002            outcome,
28003            reason_code,
28004        ) in compat_events
28005        {
28006            assert_eq!(suite_id.as_str(), super::COMPAT_CLOSURE_SUITE_ID);
28007            assert!(api_surface_id.starts_with("CC-"));
28008            assert!(*seed > 0);
28009            assert_eq!(input_digest.len(), 64);
28010            assert_eq!(output_digest.len(), 64);
28011            assert_eq!(env_fingerprint.len(), 64);
28012            assert!(
28013                artifact_refs.len() >= 5,
28014                "expected closure artifact references"
28015            );
28016            assert!(*duration_ms >= 1);
28017            assert!(outcome == "pass" || outcome == "fail");
28018            assert!(!reason_code.is_empty());
28019        }
28020    }
28021
28022    // === Failure Forensics UX Tests (bd-2gi.21) ===
28023
28024    #[test]
28025    fn artifact_id_short_hash_is_deterministic() {
28026        let id = ArtifactId {
28027            packet_id: "FP-P2C-001".to_owned(),
28028            artifact_kind: "parity_report".to_owned(),
28029            run_ts_unix_ms: 1000,
28030        };
28031        let h1 = id.short_hash();
28032        let h2 = id.short_hash();
28033        assert_eq!(h1, h2);
28034        assert_eq!(h1.len(), 8);
28035        // Display format
28036        let display = format!("{id}");
28037        assert!(display.starts_with("FP-P2C-001:parity_report@"));
28038    }
28039
28040    #[test]
28041    fn failure_digest_display_format() {
28042        let digest = sample_failure_digest();
28043
28044        let output = format!("{digest}");
28045        assert_text_golden("failure_digest_display.txt", &output);
28046    }
28047
28048    #[test]
28049    fn failure_forensics_report_clean_when_all_pass() {
28050        let forensics = FailureForensicsReport {
28051            run_ts_unix_ms: 1000,
28052            total_fixtures: 5,
28053            total_passed: 5,
28054            total_failed: 0,
28055            failures: Vec::new(),
28056            gate_failures: Vec::new(),
28057        };
28058        assert!(forensics.is_clean());
28059        let output = format!("{forensics}");
28060        assert!(output.contains("ALL GREEN"));
28061    }
28062
28063    #[test]
28064    fn failure_forensics_report_shows_failures() {
28065        let report = sample_failure_forensics_report();
28066
28067        assert!(!report.is_clean());
28068        let output = format!("{report}");
28069        assert_text_golden("failure_forensics_report.txt", &output);
28070    }
28071
28072    #[test]
28073    fn failure_forensics_clean_display_matches_golden() {
28074        let report = FailureForensicsReport {
28075            run_ts_unix_ms: 1000,
28076            total_fixtures: 5,
28077            total_passed: 5,
28078            total_failed: 0,
28079            failures: Vec::new(),
28080            gate_failures: Vec::new(),
28081        };
28082
28083        let output = format!("{report}");
28084        assert_text_golden("failure_forensics_all_green.txt", &output);
28085    }
28086
28087    #[test]
28088    fn failure_forensics_serializes_to_json() {
28089        let report = FailureForensicsReport {
28090            run_ts_unix_ms: 1000,
28091            total_fixtures: 1,
28092            total_passed: 1,
28093            total_failed: 0,
28094            failures: Vec::new(),
28095            gate_failures: Vec::new(),
28096        };
28097        let json = serde_json::to_string(&report).expect("serialize");
28098        let back: FailureForensicsReport = serde_json::from_str(&json).expect("deserialize");
28099        assert_eq!(report, back);
28100    }
28101
28102    // === RaptorQ CI Enforcement Tests (bd-2gi.9) ===
28103
28104    #[test]
28105    fn decode_proof_artifact_round_trip_serialization() {
28106        let artifact = DecodeProofArtifact {
28107            packet_id: "FP-P2C-001".to_owned(),
28108            decode_proofs: vec![fp_runtime::DecodeProof {
28109                ts_unix_ms: 1000,
28110                reason: "test drill".to_owned(),
28111                recovered_blocks: 2,
28112                proof_hash: "sha256:abcdef".to_owned(),
28113            }],
28114            status: DecodeProofStatus::Recovered,
28115        };
28116        let json = serde_json::to_string_pretty(&artifact).expect("serialize");
28117        let back: DecodeProofArtifact = serde_json::from_str(&json).expect("deserialize");
28118        assert_eq!(artifact, back);
28119        assert!(json.contains("\"recovered\""));
28120    }
28121
28122    #[test]
28123    fn decode_proof_status_variants_serialize_correctly() {
28124        for (status, expected) in [
28125            (DecodeProofStatus::Recovered, "\"recovered\""),
28126            (DecodeProofStatus::Failed, "\"failed\""),
28127            (DecodeProofStatus::NotAttempted, "\"not_attempted\""),
28128        ] {
28129            let json = serde_json::to_string(&status).expect("serialize");
28130            assert_eq!(json, expected);
28131        }
28132    }
28133
28134    #[test]
28135    fn sidecar_integrity_check_passes_for_valid_packet_dir() {
28136        let dir = tempfile::tempdir().expect("tempdir");
28137        let packet_id = "FP-P2C-099";
28138
28139        // Write parity report
28140        let report_bytes = br#"{"suite":"test","passed":1,"failed":0}"#;
28141        fs::write(dir.path().join("parity_report.json"), report_bytes).unwrap();
28142
28143        // Generate sidecar
28144        let mut sidecar =
28145            generate_raptorq_sidecar("FP-P2C-099/parity_report", "conformance", report_bytes, 8)
28146                .expect("sidecar");
28147        let proof =
28148            run_raptorq_decode_recovery_drill(&sidecar, report_bytes).expect("decode drill");
28149        sidecar.envelope.push_decode_proof_capped(proof.clone());
28150        sidecar.envelope.scrub.status = "ok".to_owned();
28151        fs::write(
28152            dir.path().join("parity_report.raptorq.json"),
28153            serde_json::to_string_pretty(&sidecar).unwrap(),
28154        )
28155        .unwrap();
28156
28157        // Write decode proof artifact
28158        let decode_artifact = DecodeProofArtifact {
28159            packet_id: packet_id.to_owned(),
28160            decode_proofs: vec![proof],
28161            status: DecodeProofStatus::Recovered,
28162        };
28163        fs::write(
28164            dir.path().join("parity_report.decode_proof.json"),
28165            serde_json::to_string_pretty(&decode_artifact).unwrap(),
28166        )
28167        .unwrap();
28168
28169        let result = verify_packet_sidecar_integrity(dir.path(), packet_id);
28170        assert!(
28171            result.is_ok(),
28172            "expected ok, got errors: {:?}",
28173            result.errors
28174        );
28175        assert!(result.source_hash_matches);
28176        assert!(result.scrub_ok);
28177        assert!(result.decode_proof_valid);
28178    }
28179
28180    #[test]
28181    fn sidecar_integrity_fails_when_sidecar_missing() {
28182        let dir = tempfile::tempdir().expect("tempdir");
28183        let report_bytes = br#"{"suite":"test"}"#;
28184        fs::write(dir.path().join("parity_report.json"), report_bytes).unwrap();
28185
28186        let result = verify_packet_sidecar_integrity(dir.path(), "FP-P2C-099");
28187        assert!(!result.is_ok());
28188        assert!(result.parity_report_exists);
28189        assert!(!result.sidecar_exists);
28190        assert!(result.errors.iter().any(|e| e.contains("Rule T5")));
28191    }
28192
28193    #[test]
28194    fn write_packet_artifacts_synthesizes_missing_parity_gate() {
28195        let dir = tempfile::tempdir().expect("tempdir");
28196        let packet_id = "FP-P2D-999";
28197        let config = HarnessConfig {
28198            repo_root: dir.path().to_path_buf(),
28199            oracle_root: dir.path().join("legacy_pandas_code/pandas"),
28200            fixture_root: dir.path().join("fixtures"),
28201            strict_mode: true,
28202            python_bin: "python3".to_owned(),
28203            allow_system_pandas_fallback: false,
28204            allow_fixture_fallback: false,
28205            require_live_oracle: false,
28206        };
28207        let report = PacketParityReport {
28208            suite: format!("phase2c_packets:{packet_id}"),
28209            packet_id: Some(packet_id.to_owned()),
28210            oracle_present: false,
28211            fixture_count: 2,
28212            passed: 2,
28213            failed: 0,
28214            retired: 0,
28215            results: vec![
28216                CaseResult {
28217                    packet_id: packet_id.to_owned(),
28218                    case_id: "strict_case".to_owned(),
28219                    mode: RuntimeMode::Strict,
28220                    operation: FixtureOperation::SeriesCombineFirst,
28221                    status: CaseStatus::Pass,
28222                    mismatch: None,
28223                    mismatch_class: None,
28224                    replay_key: format!("{packet_id}/strict_case/strict"),
28225                    trace_id: format!("{packet_id}:strict_case:strict"),
28226                    elapsed_us: 1,
28227                    evidence_records: 1,
28228                },
28229                CaseResult {
28230                    packet_id: packet_id.to_owned(),
28231                    case_id: "hardened_case".to_owned(),
28232                    mode: RuntimeMode::Hardened,
28233                    operation: FixtureOperation::SeriesCombineFirst,
28234                    status: CaseStatus::Pass,
28235                    mismatch: None,
28236                    mismatch_class: None,
28237                    replay_key: format!("{packet_id}/hardened_case/hardened"),
28238                    trace_id: format!("{packet_id}:hardened_case:hardened"),
28239                    elapsed_us: 1,
28240                    evidence_records: 1,
28241                },
28242            ],
28243        };
28244
28245        let written = write_packet_artifacts(&config, &report).expect("write artifacts");
28246        let gate_path = config.parity_gate_path(packet_id);
28247        let gate_yaml = fs::read_to_string(&gate_path).expect("read synthesized gate");
28248
28249        assert!(gate_path.exists(), "missing synthesized parity gate");
28250        assert!(
28251            gate_yaml.contains(&format!("packet_id: {packet_id}")),
28252            "unexpected gate payload: {gate_yaml}"
28253        );
28254        assert!(
28255            gate_yaml.contains("require_fixture_count_at_least: 2"),
28256            "unexpected gate payload: {gate_yaml}"
28257        );
28258        assert!(
28259            written.gate_result_path.exists(),
28260            "missing gate result artifact"
28261        );
28262    }
28263
28264    #[test]
28265    fn drift_reconciliation_fixes_disagreeing_gate_and_spares_agreeing_one() {
28266        use super::{
28267            GateReconciliation, PacketDriftHistoryEntry, reconcile_packet_gate_with_drift,
28268        };
28269
28270        let dir = tempfile::tempdir().expect("tempdir");
28271        let packet_id = "FP-P2D-998";
28272        let config = HarnessConfig {
28273            repo_root: dir.path().to_path_buf(),
28274            oracle_root: dir.path().join("legacy_pandas_code/pandas"),
28275            fixture_root: dir.path().join("fixtures"),
28276            strict_mode: true,
28277            python_bin: "python3".to_owned(),
28278            allow_system_pandas_fallback: false,
28279            allow_fixture_fallback: false,
28280            require_live_oracle: false,
28281        };
28282        let entry = PacketDriftHistoryEntry {
28283            ts_unix_ms: 1_788_412_811_653,
28284            packet_id: packet_id.to_owned(),
28285            suite: format!("phase2c_packets:{packet_id}"),
28286            fixture_count: 2,
28287            passed: 2,
28288            failed: 0,
28289            strict_failed: 0,
28290            hardened_failed: 0,
28291            gate_pass: true,
28292            report_hash: "sha256:abc".to_owned(),
28293        };
28294        let packet_dir = dir.path().join("artifacts/phase2c").join(packet_id);
28295        fs::create_dir_all(&packet_dir).expect("packet dir");
28296        let gate_path = packet_dir.join("parity_gate_result.json");
28297
28298        // Stale/synthetic RED gate vs a newer GREEN drift row -> reconciled.
28299        fs::write(
28300            &gate_path,
28301            r#"{"packet_id":"FP-P2D-998","pass":false,"fixture_count":2,"reasons":["failed=2 but gate requires 0"]}"#,
28302        )
28303        .expect("seed red gate");
28304        let outcome =
28305            reconcile_packet_gate_with_drift(&config, packet_id, &entry).expect("reconcile red");
28306        assert_eq!(outcome, GateReconciliation::Reconciled);
28307        let body = fs::read_to_string(&gate_path).expect("read reconciled gate");
28308        let gate: serde_json::Value = serde_json::from_str(&body).expect("parse gate");
28309        assert_eq!(
28310            gate["pass"],
28311            serde_json::json!(true),
28312            "gate must match the drift verdict"
28313        );
28314        assert_eq!(
28315            gate["source"],
28316            serde_json::json!("drift_history_reconciliation")
28317        );
28318        assert_eq!(
28319            gate["drift_ts_unix_ms"],
28320            serde_json::json!(entry.ts_unix_ms)
28321        );
28322        assert_eq!(gate["reasons"], serde_json::json!([]));
28323
28324        // Idempotent: second call with the stamped, agreeing gate is a no-op.
28325        let before = fs::read_to_string(&gate_path).expect("read gate");
28326        let outcome =
28327            reconcile_packet_gate_with_drift(&config, packet_id, &entry).expect("reconcile noop");
28328        assert_eq!(outcome, GateReconciliation::UpToDate);
28329        assert_eq!(fs::read_to_string(&gate_path).expect("reread"), before);
28330
28331        // NEGATIVE CASE: an AGREEING gate without a stamp must be spared —
28332        // real run artifacts carry per-fixture detail that reconciliation is
28333        // not allowed to clobber. Verify the file is byte-identical after.
28334        let agree_body = r#"{"packet_id":"FP-P2D-998","pass":true,"fixture_count":2,"strict_total":1,"strict_failed":0,"hardened_total":1,"hardened_failed":0,"reasons":[]}"#;
28335        fs::write(&gate_path, agree_body).expect("seed agreeing gate");
28336        let outcome =
28337            reconcile_packet_gate_with_drift(&config, packet_id, &entry).expect("spare agree");
28338        assert_eq!(outcome, GateReconciliation::UpToDate);
28339        assert_eq!(
28340            fs::read_to_string(&gate_path).expect("reread agree"),
28341            agree_body,
28342            "an agreeing real-run gate must never be rewritten"
28343        );
28344
28345        // And the reverse divergence: green gate vs newer RED drift row loses
28346        // (the drift row is the later measurement — reporting a loss is fine,
28347        // hiding one is not).
28348        let mut red = entry.clone();
28349        red.gate_pass = false;
28350        red.passed = 1;
28351        red.failed = 1;
28352        red.ts_unix_ms += 1_000;
28353        let outcome = reconcile_packet_gate_with_drift(&config, packet_id, &red).expect("to red");
28354        assert_eq!(outcome, GateReconciliation::Reconciled);
28355        let gate: serde_json::Value =
28356            serde_json::from_str(&fs::read_to_string(&gate_path).expect("read")).unwrap();
28357        assert_eq!(gate["pass"], serde_json::json!(false));
28358    }
28359
28360    #[test]
28361    fn oracle_pandas_pin_guard_fails_closed_on_cross_version_d8wt4() {
28362        use super::{FixtureProvenance, verify_oracle_pandas_pin};
28363
28364        let dir = tempfile::tempdir().expect("tempdir");
28365        let oracle_dir = dir.path().join("crates/fp-conformance/oracle");
28366        fs::create_dir_all(&oracle_dir).expect("oracle dir");
28367        fs::write(oracle_dir.join("requirements.txt"), "pandas==2.2.3\n").expect("pin");
28368        let config = HarnessConfig {
28369            repo_root: dir.path().to_path_buf(),
28370            oracle_root: dir.path().join("legacy_pandas_code/pandas"),
28371            fixture_root: dir.path().join("fixtures"),
28372            strict_mode: true,
28373            python_bin: "python3".to_owned(),
28374            allow_system_pandas_fallback: false,
28375            allow_fixture_fallback: false,
28376            require_live_oracle: false,
28377        };
28378        let provenance = |version: &str| FixtureProvenance {
28379            pandas_version: version.to_owned(),
28380            oracle_script_sha256: "sha256:abc".to_owned(),
28381            generated_at: "2026-09-04T00:00:00Z".to_owned(),
28382            generation_command: None,
28383            input_matrix: Vec::new(),
28384            intentional_divergence_notes: Vec::new(),
28385            oracle_attestation: None,
28386        };
28387
28388        // Matching version: the comparison is legal.
28389        assert!(verify_oracle_pandas_pin(&config, Some(&provenance("2.2.3"))).is_ok());
28390
28391        // NEGATIVE CASE — the whole point: an unpinned worker pandas must
28392        // produce an honest UNAVAILABLE (skip), never a comparison result.
28393        let err = verify_oracle_pandas_pin(&config, Some(&provenance("3.1.0")))
28394            .expect_err("cross-version comparison must be refused");
28395        assert!(
28396            err.to_string().contains("3.1.0") && err.to_string().contains("2.2.3"),
28397            "error must name both versions: {err}"
28398        );
28399
28400        // Under require_live_oracle the same drift is a HARD error, not a skip.
28401        let mut strict = config.clone();
28402        strict.require_live_oracle = true;
28403        assert!(matches!(
28404            verify_oracle_pandas_pin(&strict, Some(&provenance("3.1.0"))),
28405            Err(super::HarnessError::LiveOracleRequired(_))
28406        ));
28407
28408        // Degrade paths: no pin file -> old behavior; no provenance -> unchecked.
28409        fs::remove_file(oracle_dir.join("requirements.txt")).expect("remove pin");
28410        assert!(verify_oracle_pandas_pin(&config, Some(&provenance("9.9.9"))).is_ok());
28411    }
28412
28413    #[test]
28414    fn parse_live_oracle_report_output_counts_marker_skips_atag8() {
28415        // Per br-frankenpandas-atag8: legacy marker-based skip detection
28416        // must still work — tests that report "passed" but printed the
28417        // LIVE_ORACLE_SKIP_MARKER are counted as skipped.
28418        let output = "\
28419running 3 tests\n\
28420test live_oracle_pct_change ... ok\n\
28421live pandas unavailable; skipping\n\
28422test live_oracle_diff ... ok\n\
28423live pandas unavailable; skipping\n\
28424test live_oracle_cumsum ... ok\n\
28425\n\
28426test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.10s\n\
28427";
28428        let report = super::parse_live_oracle_report_output(output, 3, true, Some(0));
28429        assert_eq!(report.total_tests, 3);
28430        assert_eq!(report.passed, 3);
28431        assert_eq!(report.failed, 0);
28432        assert_eq!(
28433            report.skipped, 2,
28434            "marker hits should be counted as skipped"
28435        );
28436        assert_eq!(report.ran, 1);
28437    }
28438
28439    #[test]
28440    fn parse_live_oracle_report_output_counts_ignored_as_skipped_atag8() {
28441        // Per br-frankenpandas-atag8: cargo's structured `ignored` count is
28442        // also harvested. Previously only the LIVE_ORACLE_SKIP_MARKER
28443        // substring was scanned, so #[ignore]'d tests went undetected.
28444        let output = "\
28445running 4 tests\n\
28446test live_oracle_pct_change ... ok\n\
28447test live_oracle_diff ... ignored\n\
28448test live_oracle_cumsum ... ignored\n\
28449test live_oracle_mean ... ok\n\
28450\n\
28451test result: ok. 2 passed; 0 failed; 2 ignored; 0 measured; 0 filtered out; finished in 0.10s\n\
28452";
28453        let report = super::parse_live_oracle_report_output(output, 4, true, Some(0));
28454        assert_eq!(report.total_tests, 4);
28455        assert_eq!(report.passed, 2);
28456        assert_eq!(report.skipped, 2, "cargo ignored should count as skipped");
28457        assert_eq!(report.failed, 0);
28458    }
28459
28460    #[test]
28461    fn live_oracle_requirement_escalates_missing_script() {
28462        let dir = tempfile::tempdir().expect("tempdir");
28463        let config = HarnessConfig {
28464            repo_root: dir.path().to_path_buf(),
28465            oracle_root: dir.path().join("legacy_pandas_code/pandas"),
28466            fixture_root: dir.path().join("fixtures"),
28467            strict_mode: true,
28468            python_bin: "python3".to_owned(),
28469            allow_system_pandas_fallback: false,
28470            allow_fixture_fallback: false,
28471            require_live_oracle: true,
28472        };
28473        let fixture: super::PacketFixture = serde_json::from_value(serde_json::json!({
28474            "packet_id": "FP-P2D-REQ",
28475            "case_id": "live_oracle_required_missing_script",
28476            "mode": "strict",
28477            "operation": "series_constructor",
28478            "oracle_source": "live_legacy_pandas",
28479            "left": {
28480                "name": "nums",
28481                "index": [{ "kind": "int64", "value": 0 }],
28482                "values": [{ "kind": "int64", "value": 1 }]
28483            }
28484        }))
28485        .expect("fixture");
28486
28487        let result = super::capture_live_oracle_expected(&config, &fixture);
28488        assert!(
28489            matches!(
28490                result,
28491                Err(super::HarnessError::LiveOracleRequired(ref message))
28492                    if message.contains("oracle script does not exist")
28493            ),
28494            "expected required live oracle failure, got {result:?}"
28495        );
28496    }
28497
28498    #[test]
28499    fn live_oracle_expected_error_requires_the_fixture_substring_t2n6i() {
28500        let fixture: super::PacketFixture = serde_json::from_value(serde_json::json!({
28501            "packet_id": "FP-P2D-240",
28502            "case_id": "series_dt_tz_convert_naive_rejected_strict",
28503            "mode": "strict",
28504            "operation": "series_dt_tz_convert",
28505            "expected_error_contains": "tz-naive timestamps"
28506        }))
28507        .expect("fixture");
28508
28509        assert!(matches!(
28510            super::resolve_expected_oracle_error(
28511                &fixture,
28512                "series_dt_tz_convert failed: Cannot convert tz-naive timestamps, use tz_localize to localize".to_owned(),
28513            ),
28514            Ok(super::ResolvedExpected::ErrorAny)
28515        ));
28516
28517        let error = super::resolve_expected_oracle_error(
28518            &fixture,
28519            "series_dt_tz_convert failed: invalid timezone specifier".to_owned(),
28520        )
28521        .expect_err("a different pandas failure must not satisfy the fixture");
28522        assert!(
28523            matches!(error, super::HarnessError::FixtureFormat(ref message) if message.contains("tz-naive timestamps")),
28524            "unexpected error: {error:?}"
28525        );
28526    }
28527
28528    #[test]
28529    fn sidecar_integrity_fails_when_decode_proof_hash_mismatches_sidecar() {
28530        let dir = tempfile::tempdir().expect("tempdir");
28531        let packet_id = "FP-P2C-099";
28532
28533        let report_bytes = br#"{"suite":"test","passed":1,"failed":0}"#;
28534        fs::write(dir.path().join("parity_report.json"), report_bytes).expect("write report");
28535
28536        let mut sidecar =
28537            generate_raptorq_sidecar("FP-P2C-099/parity_report", "conformance", report_bytes, 8)
28538                .expect("sidecar");
28539        let proof =
28540            run_raptorq_decode_recovery_drill(&sidecar, report_bytes).expect("decode drill");
28541        sidecar.envelope.push_decode_proof_capped(proof.clone());
28542        sidecar.envelope.scrub.status = "ok".to_owned();
28543        fs::write(
28544            dir.path().join("parity_report.raptorq.json"),
28545            serde_json::to_string_pretty(&sidecar).expect("serialize sidecar"),
28546        )
28547        .expect("write sidecar");
28548
28549        let mut mismatched_proof = proof;
28550        mismatched_proof.proof_hash = "sha256:deadbeef".to_owned();
28551        let decode_artifact = DecodeProofArtifact {
28552            packet_id: packet_id.to_owned(),
28553            decode_proofs: vec![mismatched_proof],
28554            status: DecodeProofStatus::Recovered,
28555        };
28556        fs::write(
28557            dir.path().join("parity_report.decode_proof.json"),
28558            serde_json::to_string_pretty(&decode_artifact).expect("serialize decode artifact"),
28559        )
28560        .expect("write decode artifact");
28561
28562        let result = verify_packet_sidecar_integrity(dir.path(), packet_id);
28563        assert!(!result.is_ok());
28564        assert!(!result.decode_proof_valid);
28565        assert!(
28566            result
28567                .errors
28568                .iter()
28569                .any(|entry| entry.contains("proof hash mismatch")),
28570            "expected proof hash mismatch error, got {:?}",
28571            result.errors
28572        );
28573    }
28574
28575    #[test]
28576    fn sidecar_integrity_fails_when_decode_proof_count_exceeds_cap() {
28577        let dir = tempfile::tempdir().expect("tempdir");
28578        let packet_id = "FP-P2C-099";
28579
28580        let report_bytes = br#"{"suite":"test","passed":1,"failed":0}"#;
28581        fs::write(dir.path().join("parity_report.json"), report_bytes).expect("write report");
28582
28583        let mut sidecar =
28584            generate_raptorq_sidecar("FP-P2C-099/parity_report", "conformance", report_bytes, 8)
28585                .expect("sidecar");
28586        sidecar.envelope.decode_proofs = (0..=fp_runtime::MAX_DECODE_PROOFS)
28587            .map(|idx| fp_runtime::DecodeProof {
28588                ts_unix_ms: u64::try_from(idx).expect("idx fits in u64"),
28589                reason: format!("overflow-{idx}"),
28590                recovered_blocks: u32::try_from(idx).expect("idx fits in u32"),
28591                proof_hash: format!("sha256:{idx:08x}"),
28592            })
28593            .collect();
28594        sidecar.envelope.scrub.status = "ok".to_owned();
28595        fs::write(
28596            dir.path().join("parity_report.raptorq.json"),
28597            serde_json::to_string_pretty(&sidecar).expect("serialize sidecar"),
28598        )
28599        .expect("write sidecar");
28600
28601        let decode_artifact = DecodeProofArtifact {
28602            packet_id: packet_id.to_owned(),
28603            decode_proofs: vec![fp_runtime::DecodeProof {
28604                ts_unix_ms: 1,
28605                reason: "single-proof".to_owned(),
28606                recovered_blocks: 1,
28607                proof_hash: "sha256:00000001".to_owned(),
28608            }],
28609            status: DecodeProofStatus::Recovered,
28610        };
28611        fs::write(
28612            dir.path().join("parity_report.decode_proof.json"),
28613            serde_json::to_string_pretty(&decode_artifact).expect("serialize decode artifact"),
28614        )
28615        .expect("write decode artifact");
28616
28617        let result = verify_packet_sidecar_integrity(dir.path(), packet_id);
28618        assert!(!result.is_ok());
28619        assert!(!result.decode_proof_valid);
28620        assert!(
28621            result
28622                .errors
28623                .iter()
28624                .any(|entry| entry.contains("decode_proofs exceeds cap")),
28625            "expected decode proof cap error, got {:?}",
28626            result.errors
28627        );
28628    }
28629
28630    #[test]
28631    fn sidecar_integrity_fails_when_sidecar_artifact_id_mismatches_packet() {
28632        let dir = tempfile::tempdir().expect("tempdir");
28633        let packet_id = "FP-P2C-099";
28634
28635        let report_bytes = br#"{"suite":"test","passed":1,"failed":0}"#;
28636        fs::write(dir.path().join("parity_report.json"), report_bytes).expect("write report");
28637
28638        let mut sidecar =
28639            generate_raptorq_sidecar("FP-P2C-007/parity_report", "conformance", report_bytes, 8)
28640                .expect("sidecar");
28641        let proof =
28642            run_raptorq_decode_recovery_drill(&sidecar, report_bytes).expect("decode drill");
28643        sidecar.envelope.push_decode_proof_capped(proof.clone());
28644        sidecar.envelope.scrub.status = "ok".to_owned();
28645        fs::write(
28646            dir.path().join("parity_report.raptorq.json"),
28647            serde_json::to_string_pretty(&sidecar).expect("serialize sidecar"),
28648        )
28649        .expect("write sidecar");
28650
28651        let decode_artifact = DecodeProofArtifact {
28652            packet_id: packet_id.to_owned(),
28653            decode_proofs: vec![proof],
28654            status: DecodeProofStatus::Recovered,
28655        };
28656        fs::write(
28657            dir.path().join("parity_report.decode_proof.json"),
28658            serde_json::to_string_pretty(&decode_artifact).expect("serialize decode artifact"),
28659        )
28660        .expect("write decode artifact");
28661
28662        let result = verify_packet_sidecar_integrity(dir.path(), packet_id);
28663        assert!(!result.is_ok());
28664        assert!(!result.decode_proof_valid);
28665        assert!(
28666            result
28667                .errors
28668                .iter()
28669                .any(|entry| entry.contains("artifact_id mismatch")),
28670            "expected artifact_id mismatch error, got {:?}",
28671            result.errors
28672        );
28673    }
28674
28675    #[test]
28676    fn sidecar_integrity_fails_when_envelope_k_mismatches_source_packets() {
28677        let dir = tempfile::tempdir().expect("tempdir");
28678        let packet_id = "FP-P2C-099";
28679
28680        let report_bytes = br#"{"suite":"test","passed":1,"failed":0}"#;
28681        fs::write(dir.path().join("parity_report.json"), report_bytes).expect("write report");
28682
28683        let mut sidecar =
28684            generate_raptorq_sidecar("FP-P2C-099/parity_report", "conformance", report_bytes, 8)
28685                .expect("sidecar");
28686        let proof =
28687            run_raptorq_decode_recovery_drill(&sidecar, report_bytes).expect("decode drill");
28688        sidecar.envelope.push_decode_proof_capped(proof.clone());
28689        sidecar.envelope.scrub.status = "ok".to_owned();
28690        sidecar.envelope.raptorq.k = sidecar.envelope.raptorq.k.saturating_add(1);
28691        fs::write(
28692            dir.path().join("parity_report.raptorq.json"),
28693            serde_json::to_string_pretty(&sidecar).expect("serialize sidecar"),
28694        )
28695        .expect("write sidecar");
28696
28697        let decode_artifact = DecodeProofArtifact {
28698            packet_id: packet_id.to_owned(),
28699            decode_proofs: vec![proof],
28700            status: DecodeProofStatus::Recovered,
28701        };
28702        fs::write(
28703            dir.path().join("parity_report.decode_proof.json"),
28704            serde_json::to_string_pretty(&decode_artifact).expect("serialize decode artifact"),
28705        )
28706        .expect("write decode artifact");
28707
28708        let result = verify_packet_sidecar_integrity(dir.path(), packet_id);
28709        assert!(!result.is_ok());
28710        assert!(!result.decode_proof_valid);
28711        assert!(
28712            result
28713                .errors
28714                .iter()
28715                .any(|entry| entry.contains("does not match source_packets")),
28716            "expected source packet count mismatch error, got {:?}",
28717            result.errors
28718        );
28719    }
28720
28721    #[test]
28722    fn sidecar_integrity_fails_when_envelope_repair_symbols_mismatch_repair_packets() {
28723        let dir = tempfile::tempdir().expect("tempdir");
28724        let packet_id = "FP-P2C-099";
28725
28726        let report_bytes = br#"{"suite":"test","passed":1,"failed":0}"#;
28727        fs::write(dir.path().join("parity_report.json"), report_bytes).expect("write report");
28728
28729        let mut sidecar =
28730            generate_raptorq_sidecar("FP-P2C-099/parity_report", "conformance", report_bytes, 8)
28731                .expect("sidecar");
28732        let proof =
28733            run_raptorq_decode_recovery_drill(&sidecar, report_bytes).expect("decode drill");
28734        sidecar.envelope.push_decode_proof_capped(proof.clone());
28735        sidecar.envelope.scrub.status = "ok".to_owned();
28736        sidecar.envelope.raptorq.repair_symbols =
28737            sidecar.envelope.raptorq.repair_symbols.saturating_add(1);
28738        fs::write(
28739            dir.path().join("parity_report.raptorq.json"),
28740            serde_json::to_string_pretty(&sidecar).expect("serialize sidecar"),
28741        )
28742        .expect("write sidecar");
28743
28744        let decode_artifact = DecodeProofArtifact {
28745            packet_id: packet_id.to_owned(),
28746            decode_proofs: vec![proof],
28747            status: DecodeProofStatus::Recovered,
28748        };
28749        fs::write(
28750            dir.path().join("parity_report.decode_proof.json"),
28751            serde_json::to_string_pretty(&decode_artifact).expect("serialize decode artifact"),
28752        )
28753        .expect("write decode artifact");
28754
28755        let result = verify_packet_sidecar_integrity(dir.path(), packet_id);
28756        assert!(!result.is_ok());
28757        assert!(!result.decode_proof_valid);
28758        assert!(
28759            result
28760                .errors
28761                .iter()
28762                .any(|entry| entry.contains("does not match repair_packets")),
28763            "expected repair packet count mismatch error, got {:?}",
28764            result.errors
28765        );
28766    }
28767
28768    #[test]
28769    fn verify_all_sidecars_ci_on_empty_dir_returns_ok() {
28770        let dir = tempfile::tempdir().expect("tempdir");
28771        let result = verify_all_sidecars_ci(dir.path());
28772        assert!(result.is_ok());
28773        assert!(result.unwrap().is_empty());
28774    }
28775
28776    #[test]
28777    fn verify_all_sidecars_ci_on_existing_packets() {
28778        let _artifact_guard = phase2c_artifact_test_lock();
28779        let cfg = HarnessConfig::default_paths();
28780        let artifact_root = cfg.repo_root.join("artifacts");
28781        if !artifact_root.join("phase2c").exists() {
28782            return; // skip if no artifacts
28783        }
28784        let result = verify_all_sidecars_ci(&artifact_root);
28785        match result {
28786            Ok(results) => {
28787                for r in &results {
28788                    assert!(r.is_ok(), "{}: {:?}", r.packet_id, r.errors);
28789                }
28790            }
28791            Err(failures) => {
28792                for f in &failures {
28793                    eprintln!("SIDECAR INTEGRITY FAILURE: {}: {:?}", f.packet_id, f.errors);
28794                }
28795                // Don't assert here - existing artifacts may not all have sidecars yet
28796            }
28797        }
28798    }
28799
28800    // === CI Gate Topology Tests (bd-2gi.10) ===
28801
28802    #[test]
28803    fn ci_gate_pipeline_order_is_monotonic() {
28804        let pipeline = CiGate::pipeline();
28805        for window in pipeline.windows(2) {
28806            assert!(
28807                window[0].order() < window[1].order(),
28808                "{:?} should come before {:?}",
28809                window[0],
28810                window[1]
28811            );
28812        }
28813    }
28814
28815    #[test]
28816    fn ci_gate_commit_pipeline_is_subset_of_full() {
28817        let full = CiGate::pipeline();
28818        let commit = CiGate::commit_pipeline();
28819        for gate in &commit {
28820            assert!(
28821                full.contains(gate),
28822                "{gate:?} in commit but not full pipeline"
28823            );
28824        }
28825    }
28826
28827    #[test]
28828    fn ci_gate_labels_are_nonempty() {
28829        for gate in CiGate::pipeline() {
28830            assert!(!gate.label().is_empty());
28831            assert!(gate.to_string().contains("G"));
28832        }
28833    }
28834
28835    #[test]
28836    fn ci_gate_failure_output_keeps_the_tail() {
28837        let log = "   Compiling a\n   Compiling b\nfailures:\n    my_test\ntest result: FAILED";
28838        assert_eq!(super::output_tail(log, 19), "test result: FAILED");
28839        assert_eq!(
28840            super::output_tail(log, 41),
28841            "failures:\n    my_test\ntest result: FAILED"
28842        );
28843        // NEGATIVE: the head of the same length - what was kept before -
28844        // names no failing test.
28845        assert!(!log.chars().take(41).collect::<String>().contains("my_test"));
28846        // Shorter output is kept whole; the cut lands on a char boundary
28847        // (a byte slice would panic inside 'é').
28848        assert_eq!(super::output_tail("abc", 10), "abc");
28849        assert_eq!(super::output_tail("", 10), "");
28850        assert_eq!(super::output_tail("ééé", 2), "éé");
28851        assert_eq!(super::output_tail("abc", 0), "");
28852    }
28853
28854    #[test]
28855    fn ci_gate_serialization_round_trip() {
28856        for gate in CiGate::pipeline() {
28857            let json = serde_json::to_string(&gate).expect("serialize");
28858            let back: CiGate = serde_json::from_str(&json).expect("deserialize");
28859            assert_eq!(gate, back);
28860        }
28861    }
28862
28863    #[test]
28864    fn ci_gate_g6_conformance_evaluates() {
28865        let config = CiPipelineConfig::default();
28866        let result = evaluate_ci_gate(CiGate::G6Conformance, &config);
28867        assert_ci_gate_green_after_validating_failure_surface(
28868            "ci_gate_g6_conformance_evaluates",
28869            &result,
28870        );
28871        assert!(result.elapsed_ms > 0 || result.passed);
28872    }
28873
28874    #[test]
28875    fn ci_pipeline_result_display_format() {
28876        let result = sample_ci_pipeline_result();
28877        let output = format!("{result}");
28878        assert_text_golden("ci_pipeline_result_display.txt", &output);
28879    }
28880
28881    #[test]
28882    fn ci_pipeline_conformance_only_runs_and_reports() {
28883        let config = CiPipelineConfig {
28884            gates: vec![CiGate::G6Conformance],
28885            fail_fast: true,
28886            harness_config: HarnessConfig::default_paths(),
28887            verify_sidecars: false,
28888        };
28889        let result = run_ci_pipeline(&config);
28890        assert_eq!(result.gates.len(), 1);
28891        if result.all_passed {
28892            assert!(
28893                result.gates[0].passed,
28894                "green pipeline should have green gate"
28895            );
28896        } else {
28897            assert_ci_gate_green_after_validating_failure_surface(
28898                "ci_pipeline_conformance_only_runs_and_reports",
28899                &result.gates[0],
28900            );
28901        }
28902    }
28903
28904    #[test]
28905    fn failure_surface_jsonl_writes_required_fields() {
28906        let tmp = tempfile::tempdir().expect("tmp");
28907        let mut cfg = HarnessConfig::default_paths();
28908        cfg.repo_root = tmp.path().to_path_buf();
28909
28910        let mut report =
28911            run_packet_by_id(&cfg, "FP-P2C-001", OracleMode::FixtureExpected).expect("report");
28912        let first = report.results.first_mut().expect("at least one case");
28913        first.status = CaseStatus::Fail;
28914        first.mismatch = Some("synthetic failure surface".to_owned());
28915        first.mismatch_class = Some("value_critical".to_owned());
28916        report.failed = 1;
28917        report.passed = report.fixture_count.saturating_sub(1);
28918
28919        let entries = build_failure_surface_entries_for_report(&report);
28920        let path = write_failure_surface_jsonl(&cfg, "synthetic_failure_surface", &entries)
28921            .expect("write surface")
28922            .expect("surface path");
28923        let content = fs::read_to_string(path).expect("read");
28924        let lines: Vec<&str> = content.lines().collect();
28925        assert_eq!(lines.len(), 1);
28926
28927        let row: serde_json::Value = serde_json::from_str(lines[0]).expect("json row");
28928        for required in [
28929            "suite",
28930            "packet_id",
28931            "case_id",
28932            "operation",
28933            "mode",
28934            "mismatch_class",
28935            "mismatch",
28936            "replay_key",
28937            "trace_id",
28938            "evidence_records",
28939        ] {
28940            assert!(row.get(required).is_some(), "missing field: {required}");
28941        }
28942    }
28943
28944    #[test]
28945    fn case_evidence_entries_extract_machine_readable_mismatch_fields() {
28946        let report = PacketParityReport {
28947            suite: "phase2c_packets:FP-P2C-001".to_owned(),
28948            packet_id: Some("FP-P2C-001".to_owned()),
28949            oracle_present: true,
28950            fixture_count: 1,
28951            passed: 0,
28952            failed: 1,
28953            retired: 0,
28954            results: vec![CaseResult {
28955                packet_id: "FP-P2C-001".to_owned(),
28956                case_id: "case_a".to_owned(),
28957                mode: RuntimeMode::Strict,
28958                operation: FixtureOperation::SeriesAdd,
28959                status: CaseStatus::Fail,
28960                mismatch: Some(
28961                    "[Type/Critical] dtype mismatch: actual=Float64, expected=Int64; \
28962                     [Value/Critical] value mismatch at idx=2: actual=Float64(1.5), expected=Int64(1)"
28963                        .to_owned(),
28964                ),
28965                mismatch_class: Some("type_critical".to_owned()),
28966                replay_key: "FP-P2C-001/case_a/strict".to_owned(),
28967                trace_id: "FP-P2C-001:case_a:strict".to_owned(),
28968                elapsed_us: 11,
28969                evidence_records: 3,
28970            }],
28971        };
28972
28973        let entries = build_case_evidence_entries_for_report(&report);
28974        assert_eq!(entries.len(), 1);
28975        let entry = &entries[0];
28976        assert_eq!(entry.packet_id, "FP-P2C-001");
28977        assert_eq!(entry.case_id, "case_a");
28978        assert_eq!(entry.actual_dtype.as_deref(), Some("Float64"));
28979        assert_eq!(entry.expected_dtype.as_deref(), Some("Int64"));
28980        assert_eq!(entry.first_mismatch_idx, Some(2));
28981        assert_eq!(entry.first_mismatch_actual.as_deref(), Some("Float64(1.5)"));
28982        assert_eq!(entry.first_mismatch_expected.as_deref(), Some("Int64(1)"));
28983        assert!(entry.ledger_id.starts_with("evidence:"));
28984    }
28985
28986    #[test]
28987    fn case_evidence_jsonl_writes_per_case_artifacts() {
28988        let tmp = tempfile::tempdir().expect("tmp");
28989        let mut cfg = HarnessConfig::default_paths();
28990        cfg.repo_root = tmp.path().to_path_buf();
28991
28992        let report = PacketParityReport {
28993            suite: "phase2c_packets:FP-P2C-001".to_owned(),
28994            packet_id: Some("FP-P2C-001".to_owned()),
28995            oracle_present: true,
28996            fixture_count: 2,
28997            passed: 0,
28998            failed: 2,
28999            retired: 0,
29000            results: vec![
29001                CaseResult {
29002                    packet_id: "FP-P2C-001".to_owned(),
29003                    case_id: "case_a".to_owned(),
29004                    mode: RuntimeMode::Strict,
29005                    operation: FixtureOperation::SeriesAdd,
29006                    status: CaseStatus::Fail,
29007                    mismatch: Some(
29008                        "[Value/Critical] value mismatch at idx=1: actual=Int64(2), expected=Int64(3)"
29009                            .to_owned(),
29010                    ),
29011                    mismatch_class: Some("value_critical".to_owned()),
29012                    replay_key: "FP-P2C-001/case_a/strict".to_owned(),
29013                    trace_id: "FP-P2C-001:case_a:strict".to_owned(),
29014                    elapsed_us: 7,
29015                    evidence_records: 1,
29016                },
29017                CaseResult {
29018                    packet_id: "FP-P2C-001".to_owned(),
29019                    case_id: "case_a".to_owned(),
29020                    mode: RuntimeMode::Hardened,
29021                    operation: FixtureOperation::SeriesAdd,
29022                    status: CaseStatus::Fail,
29023                    mismatch: Some(
29024                        "[Type/Critical] dtype mismatch: actual=Float64, expected=Int64"
29025                            .to_owned(),
29026                    ),
29027                    mismatch_class: Some("type_critical".to_owned()),
29028                    replay_key: "FP-P2C-001/case_a/hardened".to_owned(),
29029                    trace_id: "FP-P2C-001:case_a:hardened".to_owned(),
29030                    elapsed_us: 9,
29031                    evidence_records: 2,
29032                },
29033            ],
29034        };
29035
29036        let paths = write_case_evidence_jsonl(&cfg, std::slice::from_ref(&report)).expect("write");
29037        assert_eq!(paths.len(), 1);
29038        let path = &paths[0];
29039        assert!(
29040            path.ends_with("artifacts/conformance/FP-P2C-001/case_a.jsonl"),
29041            "unexpected path: {}",
29042            path.display()
29043        );
29044
29045        let content = fs::read_to_string(path).expect("read");
29046        let rows: Vec<CaseEvidenceEntry> = content
29047            .lines()
29048            .map(|line| serde_json::from_str(line).expect("json row"))
29049            .collect();
29050        assert_eq!(rows.len(), 2);
29051        assert_eq!(rows[0].mode, RuntimeMode::Hardened);
29052        assert_eq!(rows[1].mode, RuntimeMode::Strict);
29053        assert_eq!(rows[0].actual_dtype.as_deref(), Some("Float64"));
29054        assert_eq!(rows[1].first_mismatch_idx, Some(1));
29055
29056        let aggregated = build_case_evidence_entries(&[report]);
29057        assert_eq!(aggregated.len(), 2);
29058    }
29059
29060    #[test]
29061    fn sanitize_artifact_path_component_rejects_windows_illegal_chars() {
29062        // Every character NTFS forbids in a name must be scrubbed so a
29063        // committed artifact path can never abort `git checkout` on Windows
29064        // (issue #9). Legal alphanumeric/dash/underscore tokens pass through.
29065        assert_eq!(sanitize_artifact_path_component("FP-P2C-001"), "FP-P2C-001");
29066        assert_eq!(sanitize_artifact_path_component("<unknown>"), "_unknown_");
29067        assert_eq!(
29068            sanitize_artifact_path_component("a:b\"c/d\\e|f?g*h<i>j"),
29069            "a_b_c_d_e_f_g_h_i_j"
29070        );
29071        // Empty / fully-illegal / trailing-dot inputs collapse to a safe token.
29072        assert_eq!(sanitize_artifact_path_component(""), "unknown");
29073        assert_eq!(sanitize_artifact_path_component("trailing."), "trailing");
29074        for component in ["FP-P2C-001", "<unknown>", "a:b", "name."] {
29075            let out = sanitize_artifact_path_component(component);
29076            assert!(
29077                !out.chars()
29078                    .any(|c| matches!(c, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*')),
29079                "sanitized component still contains an NTFS-illegal char: {out}"
29080            );
29081        }
29082    }
29083
29084    #[test]
29085    fn case_evidence_jsonl_uses_windows_legal_path_when_packet_id_missing() {
29086        // A report with no packet_id previously serialized to
29087        // artifacts/conformance/<unknown>/..., whose angle brackets are
29088        // illegal on NTFS and break `git checkout` (issue #9). The path must
29089        // now be Windows-legal.
29090        let tmp = tempfile::tempdir().expect("tmp");
29091        let mut cfg = HarnessConfig::default_paths();
29092        cfg.repo_root = tmp.path().to_path_buf();
29093
29094        let report = PacketParityReport {
29095            suite: "phase2c_packets:orphan".to_owned(),
29096            packet_id: None,
29097            oracle_present: true,
29098            fixture_count: 1,
29099            passed: 0,
29100            failed: 1,
29101            retired: 0,
29102            results: vec![CaseResult {
29103                packet_id: String::new(),
29104                case_id: "case_a".to_owned(),
29105                mode: RuntimeMode::Strict,
29106                operation: FixtureOperation::SeriesAdd,
29107                status: CaseStatus::Fail,
29108                mismatch: Some(
29109                    "[Value/Critical] value mismatch at idx=1: actual=Int64(2), expected=Int64(3)"
29110                        .to_owned(),
29111                ),
29112                mismatch_class: Some("value_critical".to_owned()),
29113                replay_key: "orphan/case_a/strict".to_owned(),
29114                trace_id: "orphan:case_a:strict".to_owned(),
29115                elapsed_us: 7,
29116                evidence_records: 1,
29117            }],
29118        };
29119
29120        let paths = write_case_evidence_jsonl(&cfg, std::slice::from_ref(&report)).expect("write");
29121        assert_eq!(paths.len(), 1);
29122        let path = &paths[0];
29123        assert!(
29124            path.ends_with("artifacts/conformance/unknown/case_a.jsonl"),
29125            "unexpected path: {}",
29126            path.display()
29127        );
29128        assert!(
29129            !path.to_string_lossy().contains('<') && !path.to_string_lossy().contains('>'),
29130            "artifact path contains NTFS-illegal angle brackets: {}",
29131            path.display()
29132        );
29133    }
29134
29135    #[test]
29136    fn g6_conformance_errors_include_case_evidence_artifacts() {
29137        let tmp = tempfile::tempdir().expect("tmp");
29138        let mut cfg = HarnessConfig::default_paths();
29139        cfg.repo_root = tmp.path().to_path_buf();
29140
29141        let report = PacketParityReport {
29142            suite: "phase2c_packets:FP-P2C-001".to_owned(),
29143            packet_id: Some("FP-P2C-001".to_owned()),
29144            oracle_present: true,
29145            fixture_count: 1,
29146            passed: 0,
29147            failed: 1,
29148            retired: 0,
29149            results: vec![CaseResult {
29150                packet_id: "FP-P2C-001".to_owned(),
29151                case_id: "case_a".to_owned(),
29152                mode: RuntimeMode::Strict,
29153                operation: FixtureOperation::SeriesAdd,
29154                status: CaseStatus::Fail,
29155                mismatch: Some(
29156                    "[Value/Critical] value mismatch at idx=1: actual=Int64(2), expected=Int64(3)"
29157                        .to_owned(),
29158                ),
29159                mismatch_class: Some("value_critical".to_owned()),
29160                replay_key: "FP-P2C-001/case_a/strict".to_owned(),
29161                trace_id: "FP-P2C-001:case_a:strict".to_owned(),
29162                elapsed_us: 7,
29163                evidence_records: 1,
29164            }],
29165        };
29166
29167        let errors = build_g6_conformance_errors(&cfg, &report);
29168        assert!(
29169            errors.iter().any(|error| {
29170                error.contains("packet_id=FP-P2C-001")
29171                    && error.contains("case_id=case_a")
29172                    && error.contains("mismatch_class=value_critical")
29173            }),
29174            "expected structured failure row: {errors:#?}"
29175        );
29176
29177        let artifact_line = errors
29178            .iter()
29179            .find(|error| error.starts_with("case_evidence_artifact="))
29180            .expect("expected case evidence artifact");
29181        let artifact_path = artifact_line
29182            .strip_prefix("case_evidence_artifact=")
29183            .expect("artifact prefix");
29184        let content = fs::read_to_string(artifact_path).expect("read case evidence artifact");
29185        assert!(
29186            content.contains("\"ledger_id\""),
29187            "expected machine-readable ledger id in artifact: {content}"
29188        );
29189    }
29190
29191    fn repo_root() -> PathBuf {
29192        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..")
29193    }
29194
29195    #[test]
29196    fn fp_frame_first_wave_public_panics_are_documented() {
29197        let root = repo_root();
29198        let source =
29199            fs::read_to_string(root.join("crates/fp-frame/src/lib.rs")).expect("read fp-frame");
29200        assert!(
29201            source.contains("#![warn(rustdoc::broken_intra_doc_links)]"),
29202            "expected fp-frame to opt into rustdoc broken link warnings"
29203        );
29204        // Per br-frankenpandas-a79h9: Series::last_offset and
29205        // DataFrame::last_offset no longer panic on inconsistent
29206        // non-empty/labels state — they return CompatibilityRejected
29207        // instead. The two corresponding panic-contract snippets are
29208        // removed from this list. The remaining functions still document
29209        // their panic contracts.
29210        for snippet in [
29211            "/// # Panics\n    ///\n    /// Panics if `self.column_order` references a column that is absent from\n    /// `self.columns`, which indicates internal DataFrame metadata corruption.\n    pub fn items(&self) -> Result<Vec<(String, Series)>, FrameError> {",
29212            "/// # Panics\n    ///\n    /// Panics if any column length no longer matches the DataFrame index\n    /// length, which indicates internal DataFrame corruption.\n    pub fn to_series_dict(&self) -> BTreeMap<String, Series> {",
29213            "/// # Panics\n    ///\n    /// Panics if the squeezed output cannot be represented as a valid Series\n    /// because the DataFrame's internal index or column metadata has already\n    /// diverged from its column storage.\n    #[allow(clippy::result_large_err)]\n    pub fn squeeze_to_series(&self, axis: usize) -> Result<Series, Self> {",
29214        ] {
29215            assert!(
29216                source.contains(snippet),
29217                "expected panic-contract snippet to exist in fp-frame source: {snippet}"
29218            );
29219        }
29220    }
29221
29222    #[test]
29223    fn ci_gate_rule_ids_are_stable_and_nonempty() {
29224        let expected = vec![
29225            (CiGate::G1Compile, "G1"),
29226            (CiGate::G2Lint, "G2"),
29227            (CiGate::G3Unit, "G3"),
29228            (CiGate::G4Property, "G4"),
29229            (CiGate::G4_5Fuzz, "G4.5"),
29230            (CiGate::G5Integration, "G5"),
29231            (CiGate::G6Conformance, "G6"),
29232            (CiGate::G7Coverage, "G7"),
29233            (CiGate::G8E2e, "G8"),
29234        ];
29235        for (gate, rule_id) in expected {
29236            assert_eq!(gate.rule_id(), rule_id);
29237            assert!(!gate.repro_command().is_empty());
29238        }
29239    }
29240
29241    #[test]
29242    fn ci_forensics_report_collects_violations_with_replay_commands() {
29243        let pipeline = CiPipelineResult {
29244            gates: vec![
29245                CiGateResult {
29246                    gate: CiGate::G1Compile,
29247                    passed: true,
29248                    elapsed_ms: 10,
29249                    summary: "ok".to_owned(),
29250                    errors: vec![],
29251                },
29252                CiGateResult {
29253                    gate: CiGate::G2Lint,
29254                    passed: false,
29255                    elapsed_ms: 20,
29256                    summary: "lint failed".to_owned(),
29257                    errors: vec!["clippy warning".to_owned()],
29258                },
29259            ],
29260            all_passed: false,
29261            first_failure: Some(CiGate::G2Lint),
29262            elapsed_ms: 30,
29263        };
29264
29265        let report = build_ci_forensics_report(&pipeline);
29266        assert_eq!(report.passed_count, 1);
29267        assert_eq!(report.total_count, 2);
29268        assert_eq!(report.violations.len(), 1);
29269        assert_eq!(report.violations[0].rule_id, "G2");
29270        assert!(report.violations[0].repro_cmd.contains("cargo clippy"));
29271        assert_eq!(report.violations[0].errors.len(), 1);
29272    }
29273
29274    #[test]
29275    fn to_timedelta_int64_seconds_converts() {
29276        use fp_frame::{Series, to_timedelta_with_unit};
29277        use fp_index::IndexLabel;
29278        use fp_types::{NullKind, Scalar};
29279
29280        let input = Series::from_values(
29281            "duration_s".to_owned(),
29282            vec![
29283                IndexLabel::Int64(0),
29284                IndexLabel::Int64(1),
29285                IndexLabel::Int64(2),
29286            ],
29287            vec![
29288                Scalar::Int64(3661),
29289                Scalar::Int64(90061),
29290                Scalar::Null(NullKind::Null),
29291            ],
29292        )
29293        .unwrap();
29294
29295        // Explicit unit='s' (pandas default is nanoseconds — br-0caxj).
29296        let result = to_timedelta_with_unit(&input, "s").expect("to_timedelta should succeed");
29297        assert_eq!(result.len(), 3);
29298
29299        let values = result.values();
29300        // 3661 seconds = 3661 * 1_000_000_000 nanoseconds
29301        assert_eq!(values[0], Scalar::Timedelta64(3_661_000_000_000));
29302        // 90061 seconds = 90061 * 1_000_000_000 nanoseconds
29303        assert_eq!(values[1], Scalar::Timedelta64(90_061_000_000_000));
29304        assert!(values[2].is_missing(), "null input should produce NaT");
29305    }
29306
29307    #[test]
29308    fn to_timedelta_string_hms_parses() {
29309        use fp_frame::{Series, to_timedelta};
29310        use fp_index::IndexLabel;
29311        use fp_types::Scalar;
29312
29313        let input = Series::from_values(
29314            "td_str".to_owned(),
29315            vec![
29316                IndexLabel::Int64(0),
29317                IndexLabel::Int64(1),
29318                IndexLabel::Int64(2),
29319            ],
29320            vec![
29321                Scalar::Utf8("02:30:45".to_owned()),
29322                Scalar::Utf8("3d 4h 15m 30s".to_owned()),
29323                Scalar::Utf8("5hours".to_owned()),
29324            ],
29325        )
29326        .unwrap();
29327
29328        let result = to_timedelta(&input).expect("to_timedelta should succeed");
29329        assert_eq!(result.len(), 3);
29330
29331        let values = result.values();
29332        // 02:30:45 = 2*3600 + 30*60 + 45 = 9045 seconds
29333        assert_eq!(values[0], Scalar::Timedelta64(9_045_000_000_000));
29334        // 3d 4h 15m 30s = 3*86400 + 4*3600 + 15*60 + 30 = 274530 seconds
29335        assert_eq!(values[1], Scalar::Timedelta64(274_530_000_000_000));
29336        // 5hours = 5*3600 = 18000 seconds
29337        assert_eq!(values[2], Scalar::Timedelta64(18_000_000_000_000));
29338    }
29339
29340    #[test]
29341    fn to_timedelta_invalid_string_returns_nat() {
29342        use fp_frame::{Series, ToTimedeltaErrors, ToTimedeltaOptions, to_timedelta_with_options};
29343        use fp_index::IndexLabel;
29344        use fp_types::Scalar;
29345
29346        let input = Series::from_values(
29347            "bad_td".to_owned(),
29348            vec![IndexLabel::Int64(0), IndexLabel::Int64(1)],
29349            vec![
29350                Scalar::Utf8("not a duration".to_owned()),
29351                Scalar::Utf8("xyz abc".to_owned()),
29352            ],
29353        )
29354        .unwrap();
29355
29356        let result = to_timedelta_with_options(
29357            &input,
29358            ToTimedeltaOptions {
29359                errors: ToTimedeltaErrors::Coerce,
29360                ..Default::default()
29361            },
29362        )
29363        .expect("to_timedelta should succeed with coerce");
29364        assert_eq!(result.len(), 2);
29365
29366        let values = result.values();
29367        assert!(values[0].is_missing(), "invalid string should produce NaT");
29368        assert!(
29369            values[1].is_missing(),
29370            "malformed string should produce NaT"
29371        );
29372    }
29373
29374    #[test]
29375    fn packet_fixture_deserializes_without_fixture_provenance() {
29376        let fixture: super::PacketFixture = serde_json::from_value(serde_json::json!({
29377            "packet_id": "FP-P2C-LEGACY",
29378            "case_id": "legacy_fixture_without_provenance",
29379            "mode": "strict",
29380            "operation": "series_add",
29381            "left": {
29382                "name": "left",
29383                "index": [{ "kind": "int64", "value": 0 }],
29384                "values": [{ "kind": "int64", "value": 1 }]
29385            },
29386            "right": {
29387                "name": "right",
29388                "index": [{ "kind": "int64", "value": 0 }],
29389                "values": [{ "kind": "int64", "value": 2 }]
29390            },
29391            "expected_series": {
29392                "index": [{ "kind": "int64", "value": 0 }],
29393                "values": [{ "kind": "int64", "value": 3 }]
29394            }
29395        }))
29396        .expect("legacy packet fixture should deserialize");
29397
29398        assert!(fixture.fixture_provenance.is_none());
29399    }
29400
29401    #[test]
29402    fn fixture_input_structs_reject_unknown_fields_vxbuf() {
29403        fn assert_rejects_unknown_field<T>(value: serde_json::Value, field: &str)
29404        where
29405            T: serde::de::DeserializeOwned,
29406        {
29407            let error = match serde_json::from_value::<T>(value) {
29408                Ok(_) => panic!("fixture schema must reject undeclared fields"),
29409                Err(error) => error.to_string(),
29410            };
29411            assert!(
29412                error.contains(&format!("unknown field `{field}`")),
29413                "expected unknown-field error for {field}, got: {error}"
29414            );
29415        }
29416
29417        assert_rejects_unknown_field::<super::PacketFixture>(
29418            serde_json::json!({
29419                "packet_id": "FP-VXBUF-001",
29420                "case_id": "reject_unknown_top_level",
29421                "mode": "strict",
29422                "operation": "series_add",
29423                "typoed_packet_field": true
29424            }),
29425            "typoed_packet_field",
29426        );
29427        assert_rejects_unknown_field::<super::FixtureSeries>(
29428            serde_json::json!({
29429                "name": "input",
29430                "index": [],
29431                "values": [],
29432                "typoed_series_field": true
29433            }),
29434            "typoed_series_field",
29435        );
29436        assert_rejects_unknown_field::<super::FixtureDataFrame>(
29437            serde_json::json!({
29438                "index": [],
29439                "columns": {},
29440                "typoed_frame_field": true
29441            }),
29442            "typoed_frame_field",
29443        );
29444        assert_rejects_unknown_field::<super::FixtureCategoricalColumn>(
29445            serde_json::json!({
29446                "categories": [],
29447                "typoed_categorical_field": true
29448            }),
29449            "typoed_categorical_field",
29450        );
29451        assert_rejects_unknown_field::<super::FixtureColumnAssignment>(
29452            serde_json::json!({
29453                "name": "a",
29454                "values": [],
29455                "typoed_assignment_field": true
29456            }),
29457            "typoed_assignment_field",
29458        );
29459        assert_rejects_unknown_field::<super::FixtureColumnRename>(
29460            serde_json::json!({
29461                "from": "a",
29462                "to": "b",
29463                "typoed_rename_field": true
29464            }),
29465            "typoed_rename_field",
29466        );
29467        assert_rejects_unknown_field::<super::FixtureProvenance>(
29468            serde_json::json!({
29469                "pandas_version": "2.2.3",
29470                "oracle_script_sha256": "sha",
29471                "generated_at": "2026-08-24T00:00:00Z",
29472                "typoed_provenance_field": true
29473            }),
29474            "typoed_provenance_field",
29475        );
29476        assert_rejects_unknown_field::<super::FixtureRetirement>(
29477            serde_json::json!({
29478                "reason": "test",
29479                "typoed_retirement_field": true
29480            }),
29481            "typoed_retirement_field",
29482        );
29483    }
29484
29485    #[test]
29486    fn fixture_corpus_loads_with_strict_input_schema_vxbuf() {
29487        let fixtures = super::load_fixtures(&super::HarnessConfig::default_paths(), None)
29488            .expect("all checked-in fixtures must satisfy the strict schema");
29489        assert!(
29490            !fixtures.is_empty(),
29491            "the checked-in fixture corpus must not be empty"
29492        );
29493    }
29494
29495    #[test]
29496    fn fixture_generation_template_enriches_expected_series_tn6qb2() -> Result<(), String> {
29497        let mut fixture = super::fixture_generation_template(
29498            "series_add",
29499            "FP-GEN-TN6QB2-001",
29500            "series_add_generated_alignment_strict_tn6qb2",
29501        )
29502        .map_err(|err| format!("template should build: {err}"))?;
29503        let response: super::OracleResponse = serde_json::from_value(serde_json::json!({
29504            "expected_series": {
29505                "index": [
29506                    { "kind": "int64", "value": 0 },
29507                    { "kind": "int64", "value": 1 },
29508                    { "kind": "int64", "value": 2 },
29509                    { "kind": "int64", "value": 3 }
29510                ],
29511                "values": [
29512                    { "kind": "null", "value": "na_n" },
29513                    { "kind": "float64", "value": 12.0 },
29514                    { "kind": "float64", "value": 23.0 },
29515                    { "kind": "null", "value": "na_n" }
29516                ]
29517            },
29518            "fixture_provenance": {
29519                "pandas_version": "2.2.3",
29520                "oracle_script_sha256": "abc123",
29521                "generated_at": "2026-05-08T12:00:00Z"
29522            }
29523        }))
29524        .map_err(|err| format!("oracle response should deserialize: {err}"))?;
29525        let input_matrix = vec!["operation=series_add".to_owned()];
29526        let divergence_notes = vec!["none".to_owned()];
29527
29528        super::apply_oracle_response_to_generated_fixture(
29529            &mut fixture,
29530            response,
29531            "fp-conformance-cli --generate-fixture-pilot series_add",
29532            &input_matrix,
29533            &divergence_notes,
29534        )
29535        .map_err(|err| format!("oracle response should enrich fixture: {err}"))?;
29536
29537        let provenance = fixture
29538            .fixture_provenance
29539            .as_ref()
29540            .ok_or_else(|| "missing fixture provenance".to_owned())?;
29541        assert_eq!(
29542            fixture.oracle_source,
29543            Some(super::FixtureOracleSource::Fixture)
29544        );
29545        assert!(fixture.expected_series.is_some());
29546        assert_eq!(
29547            provenance.generation_command.as_deref(),
29548            Some("fp-conformance-cli --generate-fixture-pilot series_add")
29549        );
29550        assert_eq!(provenance.input_matrix, input_matrix);
29551        assert_eq!(provenance.intentional_divergence_notes, divergence_notes);
29552        Ok(())
29553    }
29554
29555    #[test]
29556    fn generated_fixture_pilot_series_add_packet_passes_tn6qb2() -> Result<(), String> {
29557        let report = super::run_differential_by_id(
29558            &super::HarnessConfig::default_paths(),
29559            "FP-GEN-TN6QB2-001",
29560            super::OracleMode::FixtureExpected,
29561        )
29562        .map_err(|err| format!("generated packet should run: {err}"))?;
29563
29564        assert_eq!(report.report.fixture_count, 1);
29565        assert_eq!(
29566            report.report.failed, 0,
29567            "generated fixture should match fixture expectations: {:?}",
29568            report.differential_results
29569        );
29570        Ok(())
29571    }
29572
29573    #[test]
29574    fn series_replace_replacement_length_mismatch_matches_expected_error() {
29575        let fixture: super::PacketFixture = serde_json::from_value(serde_json::json!({
29576            "packet_id": "FP-TEST",
29577            "case_id": "series_replace_mismatched_replacements",
29578            "mode": "strict",
29579            "operation": "series_replace",
29580            "left": {
29581                "name": "left",
29582                "index": [
29583                    { "kind": "int64", "value": 0 },
29584                    { "kind": "int64", "value": 1 }
29585                ],
29586                "values": [
29587                    { "kind": "int64", "value": 1 },
29588                    { "kind": "int64", "value": 2 }
29589                ]
29590            },
29591            "replace_to_find": [
29592                { "kind": "int64", "value": 1 },
29593                { "kind": "int64", "value": 2 }
29594            ],
29595            "replace_to_value": [
29596                { "kind": "int64", "value": 10 }
29597            ],
29598            "expected_error_contains": "replacement lists must match in length"
29599        }))
29600        .expect("series_replace fixture should deserialize");
29601
29602        let mut ledger = super::EvidenceLedger::new();
29603        super::run_fixture_operation(
29604            &super::HarnessConfig::default_paths(),
29605            &fixture,
29606            &super::RuntimePolicy::strict(),
29607            &mut ledger,
29608            super::OracleMode::FixtureExpected,
29609        )
29610        .expect("mismatched replacement lists should satisfy expected_error_contains");
29611    }
29612
29613    #[test]
29614    fn dataframe_pivot_duplicate_keys_expected_error_contains_tn6qb7() -> Result<(), String> {
29615        let fixture: super::PacketFixture = serde_json::from_value(serde_json::json!({
29616            "packet_id": "FP-ERR-CATALOG-001",
29617            "case_id": "dataframe_pivot_duplicate_keys_expected_error_contains_tn6qb7",
29618            "mode": "strict",
29619            "operation": "dataframe_pivot",
29620            "pivot_values": ["val"],
29621            "pivot_index": "row",
29622            "pivot_columns": "col",
29623            "frame": {
29624                "index": [
29625                    { "kind": "int64", "value": 0 },
29626                    { "kind": "int64", "value": 1 }
29627                ],
29628                "columns": {
29629                    "row": [
29630                        { "kind": "utf8", "value": "A" },
29631                        { "kind": "utf8", "value": "A" }
29632                    ],
29633                    "col": [
29634                        { "kind": "utf8", "value": "x" },
29635                        { "kind": "utf8", "value": "x" }
29636                    ],
29637                    "val": [
29638                        { "kind": "float64", "value": 1.0 },
29639                        { "kind": "float64", "value": 2.0 }
29640                    ]
29641                },
29642                "column_order": ["row", "col", "val"]
29643            },
29644            "expected_error_contains": "duplicate entries"
29645        }))
29646        .map_err(|err| format!("dataframe_pivot duplicate fixture should deserialize: {err}"))?;
29647
29648        let report = super::run_differential_fixture(
29649            &super::HarnessConfig::default_paths(),
29650            &fixture,
29651            &super::SuiteOptions::default(),
29652        )
29653        .map_err(|err| {
29654            format!("dataframe_pivot duplicate expected-error fixture should run: {err}")
29655        })?;
29656
29657        assert_eq!(report.status, super::CaseStatus::Pass, "{report:?}");
29658        assert!(
29659            report.drift_records.is_empty(),
29660            "unexpected drift records: {:?}",
29661            report.drift_records
29662        );
29663
29664        Ok(())
29665    }
29666
29667    #[test]
29668    fn dataframe_pivot_missing_value_column_expected_error_contains_tn6qb7() -> Result<(), String> {
29669        let fixture: super::PacketFixture = serde_json::from_value(serde_json::json!({
29670            "packet_id": "FP-ERR-CATALOG-002",
29671            "case_id": "dataframe_pivot_missing_value_column_expected_error_contains_tn6qb7",
29672            "mode": "strict",
29673            "operation": "dataframe_pivot",
29674            "pivot_values": ["missing"],
29675            "pivot_index": "row",
29676            "pivot_columns": "col",
29677            "frame": {
29678                "index": [
29679                    { "kind": "int64", "value": 0 },
29680                    { "kind": "int64", "value": 1 }
29681                ],
29682                "columns": {
29683                    "row": [
29684                        { "kind": "utf8", "value": "A" },
29685                        { "kind": "utf8", "value": "B" }
29686                    ],
29687                    "col": [
29688                        { "kind": "utf8", "value": "x" },
29689                        { "kind": "utf8", "value": "y" }
29690                    ],
29691                    "val": [
29692                        { "kind": "float64", "value": 1.0 },
29693                        { "kind": "float64", "value": 2.0 }
29694                    ]
29695                },
29696                "column_order": ["row", "col", "val"]
29697            },
29698            "expected_error_contains": "column 'missing' not found"
29699        }))
29700        .map_err(|err| {
29701            format!("dataframe_pivot missing column fixture should deserialize: {err}")
29702        })?;
29703
29704        let report = super::run_differential_fixture(
29705            &super::HarnessConfig::default_paths(),
29706            &fixture,
29707            &super::SuiteOptions::default(),
29708        )
29709        .map_err(|err| {
29710            format!("dataframe_pivot missing-column expected-error fixture should run: {err}")
29711        })?;
29712
29713        assert_eq!(report.status, super::CaseStatus::Pass, "{report:?}");
29714        assert!(
29715            report.drift_records.is_empty(),
29716            "unexpected drift records: {:?}",
29717            report.drift_records
29718        );
29719
29720        Ok(())
29721    }
29722
29723    #[test]
29724    fn oracle_response_deserializes_with_fixture_provenance() {
29725        let response: super::OracleResponse = serde_json::from_value(serde_json::json!({
29726            "expected_series": null,
29727            "expected_join": null,
29728            "expected_frame": null,
29729            "expected_alignment": null,
29730            "expected_bool": true,
29731            "expected_positions": null,
29732            "expected_scalar": null,
29733            "expected_dtype": null,
29734            "fixture_provenance": {
29735                "pandas_version": "2.2.3",
29736                "oracle_script_sha256": "abc123",
29737                "generated_at": "2026-04-22T21:00:00Z"
29738            },
29739            "error": null
29740        }))
29741        .expect("oracle response should deserialize");
29742
29743        let provenance = response
29744            .fixture_provenance
29745            .expect("expected fixture provenance");
29746        assert_eq!(provenance.pandas_version, "2.2.3");
29747        assert_eq!(provenance.oracle_script_sha256, "abc123");
29748        assert_eq!(provenance.generated_at, "2026-04-22T21:00:00Z");
29749    }
29750}
29751
29752/// REGRESSION LOCK for the tiered constructor-dtype match (br-frankenpandas-jozfk).
29753///
29754/// The corpus CANNOT defend this. Confirmed by running it: after the fix, all 1259
29755/// packet fixtures still pass, because the one fixture that passes a cased spelling
29756/// pins only VALUES and asserts no `expected_dtype`. So changing which dtype a spec
29757/// resolves to is invisible to the entire packet suite, and a revert would be
29758/// invisible too. These unit locks are the only thing standing between the fix and
29759/// a silent regression.
29760#[cfg(test)]
29761mod constructor_dtype_tier_locks_jozfk {
29762    use fp_types::DType;
29763
29764    use super::parse_constructor_dtype_spec;
29765
29766    /// TIER 1. pandas' nullable extension dtypes differ from the numpy ones BY CASE
29767    /// ALONE, and the difference is observable: live pandas 2.2.3 constructs
29768    /// `dtype='Int64'` over data containing a missing entry and RAISES TypeError for
29769    /// `dtype='int64'` over the same data.
29770    #[test]
29771    fn cased_pandas_spellings_must_resolve_to_the_nullable_extension_dtypes_jozfk() {
29772        assert_eq!(
29773            parse_constructor_dtype_spec("Int64"),
29774            Ok(DType::Int64Nullable),
29775            "'Int64' is pandas' NULLABLE extension spelling; resolving it to the numpy \
29776             DType::Int64 is the bug this lock exists for"
29777        );
29778        assert_eq!(
29779            parse_constructor_dtype_spec("Float64"),
29780            Ok(DType::Float64Nullable),
29781            "'Float64' is the extension dtype; 'float64' is numpy's"
29782        );
29783    }
29784
29785    /// TIER 2, and the half a naive fix breaks. Four fixtures deliberately pin
29786    /// case-insensitive alias handling, so "just make the match case-sensitive"
29787    /// is NOT the fix — these spellings must keep resolving to the numpy dtypes.
29788    #[test]
29789    fn corpus_pinned_aliases_must_still_resolve_case_insensitively_jozfk() {
29790        for spec in ["int64", "INT64", "  INT64  ", "int", "i64"] {
29791            assert_eq!(
29792                parse_constructor_dtype_spec(spec),
29793                Ok(DType::Int64),
29794                "{spec:?} is an ALIAS, not a pandas dtype, and must stay on numpy Int64"
29795            );
29796        }
29797        for spec in ["float64", "Float", "FLOAT64", "f64"] {
29798            assert_eq!(
29799                parse_constructor_dtype_spec(spec),
29800                Ok(DType::Float64),
29801                "{spec:?} must stay on numpy Float64"
29802            );
29803        }
29804        for spec in ["BOOLEAN", "boolean"] {
29805            assert_eq!(parse_constructor_dtype_spec(spec), Ok(DType::BoolNullable));
29806        }
29807        for spec in ["STRING", "string", "str", "utf8"] {
29808            assert_eq!(parse_constructor_dtype_spec(spec), Ok(DType::Utf8));
29809        }
29810    }
29811
29812    /// THE NEGATIVE CASE, which is the whole point of the pair above.
29813    ///
29814    /// Re-adding a leading `.to_ascii_lowercase()` — the exact shape of the code this
29815    /// replaced, and the obvious "simplification" — makes `Int64` and `int64`
29816    /// indistinguishable. That change passes every packet fixture (verified: 1259 of
29817    /// 1259 pass either way) and would silently un-fix this. It cannot pass BOTH
29818    /// assertions here, because they demand different answers for two specs that
29819    /// differ only in case.
29820    #[test]
29821    fn the_two_tiers_must_disagree_on_specs_differing_only_in_case_jozfk() {
29822        let cased = parse_constructor_dtype_spec("Int64");
29823        let lower = parse_constructor_dtype_spec("int64");
29824        assert_ne!(
29825            cased, lower,
29826            "'Int64' and 'int64' must NOT resolve to the same dtype; if they do, the \
29827             match has been flattened back to a single case-insensitive tier and the \
29828             nullable constructor path is unreachable again"
29829        );
29830        let cased_f = parse_constructor_dtype_spec("Float64");
29831        let lower_f = parse_constructor_dtype_spec("float64");
29832        assert_ne!(
29833            cased_f, lower_f,
29834            "'Float64' and 'float64' must not collapse either"
29835        );
29836    }
29837
29838    /// Constructor dtype spellings are an observable boundary. Keep every accepted
29839    /// spelling explicit so the adapter, fixture corpus, and constructor cannot
29840    /// silently turn a FrankenPandas limitation into a claimed pandas error.
29841    ///
29842    /// `datetime64[ns]` LEFT this set on purpose (br-frankenpandas-jozfk scope item
29843    /// 2). This lock previously demanded it be refused, and that demand was correct
29844    /// until someone asked the incumbent. Live pandas 2.2.3:
29845    ///
29846    ///     pd.DataFrame([["2026-01-01"]], dtype="datetime64[ns]")
29847    ///       -> dtype datetime64[ns], Timestamp('2026-01-01 00:00:00')
29848    ///
29849    /// pandas SUCCEEDS, `DType::Datetime64` exists, and `with_constructor_dtype`
29850    /// already handles temporal targets — so the refusal was a harness gap, and the
29851    /// corpus fixture asserting `expected_error_contains: "unsupported constructor
29852    /// dtype 'datetime64[ns]'"` was pinning FrankenPandas' own error message as the
29853    /// incumbent's behaviour, attested `error_agreement`. That fixture now carries
29854    /// the measured value instead.
29855    ///
29856    #[test]
29857    fn constructor_dtype_supported_set_is_explicit_bhyqp() {
29858        assert_eq!(
29859            parse_constructor_dtype_spec("datetime64[ns]"),
29860            Ok(DType::datetime64_naive()),
29861            "datetime64[ns] was deliberately admitted against live pandas 2.2.3; \
29862             re-refusing it would restore a fixture that asserts FrankenPandas' own \
29863             error text as pandas' behaviour"
29864        );
29865        assert_eq!(parse_constructor_dtype_spec("object"), Ok(DType::Utf8));
29866        assert_eq!(parse_constructor_dtype_spec("uint64"), Ok(DType::Int64));
29867        assert_eq!(
29868            parse_constructor_dtype_spec("boolean[pyarrow]"),
29869            Ok(DType::Bool)
29870        );
29871        assert_eq!(
29872            parse_constructor_dtype_spec("category"),
29873            Ok(DType::Categorical)
29874        );
29875        assert_eq!(
29876            parse_constructor_dtype_spec("categorical"),
29877            Ok(DType::Categorical)
29878        );
29879    }
29880
29881    #[test]
29882    fn test_conformance_duplicate_column_support_8b4d4() {
29883        use std::collections::BTreeMap;
29884
29885        use fp_frame::ColumnSelection;
29886        use fp_types::Scalar;
29887
29888        use super::{
29889            FixtureDataFrame, OrderedColumnData, dataframe_from_fixture_columns,
29890            resolve_frame_column_order,
29891        };
29892
29893        // 1. resolve_frame_column_order accepts duplicate column names
29894        let mut col_data = BTreeMap::new();
29895        col_data.insert("a".to_string(), vec![Scalar::Int64(1)]);
29896        let fixture_frame = FixtureDataFrame {
29897            index: vec![0_i64.into()],
29898            columns: OrderedColumnData::from(col_data),
29899            column_order: Some(vec!["a".to_string(), "a".to_string()]),
29900            categorical_columns: None,
29901            row_multiindex: None,
29902        };
29903        let resolved = resolve_frame_column_order(&fixture_frame).expect("order resolution");
29904        assert_eq!(resolved, vec!["a", "a"]);
29905
29906        // 2. dataframe_from_fixture_columns preserves duplicate columns and distinct values
29907        let cols = vec![
29908            ("a".to_string(), vec![Scalar::Int64(10)]),
29909            ("a".to_string(), vec![Scalar::Int64(20)]),
29910        ];
29911        let df = dataframe_from_fixture_columns(cols, vec![0_i64.into()])
29912            .expect("dataframe_from_fixture_columns");
29913        assert_eq!(df.column_names(), vec!["a", "a"]);
29914        assert_eq!(df.column_at(0).unwrap().values(), &[Scalar::Int64(10)]);
29915        assert_eq!(df.column_at(1).unwrap().values(), &[Scalar::Int64(20)]);
29916
29917        // 3. Negative case: df['a'] on duplicate column must NOT return just a Series
29918        let selection = df.get_column_selection("a").expect("selection");
29919        assert!(
29920            matches!(selection, ColumnSelection::DataFrame(_)),
29921            "df['a'] with duplicate 'a' columns must return a DataFrame, not a Series"
29922        );
29923        if let ColumnSelection::DataFrame(selected) = selection {
29924            assert_eq!(selected.shape(), (1, 2));
29925            assert_eq!(selected.column_names(), vec!["a", "a"]);
29926            assert_eq!(
29927                selected.column_at(0).unwrap().values(),
29928                &[Scalar::Int64(10)]
29929            );
29930            assert_eq!(
29931                selected.column_at(1).unwrap().values(),
29932                &[Scalar::Int64(20)]
29933            );
29934        }
29935    }
29936}