/*
 * eproc_single.h — Single-header C11/C++17 distribution of eproc
 * Generated by scripts/make_single_header.py
 * License: Apache-2.0
 *
 * In exactly ONE C/C++ translation unit, define:
 *   #define EPROC_IMPLEMENTATION
 *   #include "eproc_single.h"
 * Compile with: -std=c11 -O3 -ffp-contract=off -lm (runtime AVX2 auto-dispatched on x86_64)
 */

#ifndef EPROC_H
#define EPROC_H

/*
 * eproc — Sub-microsecond anytime-valid online statistical inference,
 * multi-rate conformal calibration, Byzantine-safe multi-agent evidence fusion,
 * and causal Horvitz-Thompson subsampling.
 *
 * Portable C11 ABI (zero runtime dependencies, zero hot-path malloc,
 * IEEE-754 binary64 deterministic with -ffp-contract=off).
 *
 * License: Apache-2.0
 */

#include <stddef.h>
#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif

#define EPROC_ABI_VERSION 1U

/* Status codes */
#define EPROC_OK            0
#define EPROC_ERR_INVALID  -1
#define EPROC_ERR_CAPACITY -2
#define EPROC_ERR_EMPTY    -3
#define EPROC_ERR_MISMATCH -4

/* Verdict codes */
#define EPROC_VERDICT_CONTINUE 0
#define EPROC_VERDICT_REJECT   1
#define EPROC_VERDICT_PROMOTE  1
#define EPROC_VERDICT_ROLLBACK -1

/* Test sides */
#define EPROC_SIDE_UPPER     0  /* H0: E[X] <= mu0, H1: E[X] > mu0 */
#define EPROC_SIDE_LOWER     1  /* H0: E[X] >= mu0, H1: E[X] < mu0 */
#define EPROC_SIDE_TWO_SIDED 2  /* H0: E[X] == mu0, H1: E[X] != mu0 */

/* Hard capacity bounds for zero-allocation hot paths */
#define EPROC_MAX_ARMS            64
#define EPROC_MAX_RATES           5
#define EPROC_AGACI_EXPERTS       4
#define EPROC_CONFORMAL_MAX_WIN   256
#define EPROC_CMONOID_BINS        64
#define EPROC_DELAY_MAX_PENDING   4096
#define EPROC_BOA_MAX_EXPERTS     64
#define EPROC_ECHO_MAX_SOURCES    256
#define EPROC_ECHO_MAX_CLAIMS     256
#define EPROC_ECHO_TABLE_CAP      4096   /* must be power of 2 */
#define EPROC_VAROPT_MAX_K        4096
#define EPROC_RLS_MAX_D           32
#define EPROC_SIFT_MAX_SITES      1024
#define EPROC_SIFT_MAX_PER_SITE   16

/* ============================================================================
 * 1. ANYTIME-VALID BETTING E-PROCESSES, CONFIDENCE SEQUENCES & AGENT RACING
 * ============================================================================ */

/*
 * ONS Betting Supermartingale E-Process for bounded streams X_t in [lower, upper].
 * Exact Ville inequality: P_{H0}(exists t >= 1: e_value_t >= 1/alpha) <= alpha.
 */
typedef struct {
    double lower;
    double upper;
    double inv_span;
    double mu0_norm;      /* normalized null mean in (0, 1) */
    double alpha;
    double log_thresh;    /* log(1 / alpha) */
    double c_max;         /* bet cap fraction in (0, 0.95], default 0.75 */
    int32_t side;         /* EPROC_SIDE_* */
    uint32_t _pad0;

    /* Upper-tail betting state (lambda_pos in [0, c_max / mu0_norm]) */
    double lam_pos;
    double a_pos;
    double log_e_pos;

    /* Lower-tail betting state (lambda_neg in [-c_max / (1 - mu0_norm), 0]) */
    double lam_neg;
    double a_neg;
    double log_e_neg;

    /* Running summaries (Kahan compensated) */
    double log_e;         /* current log E_t */
    double max_log_e;     /* running max log E_s for anytime-valid p-value */
    double sum_x;
    double sum_x_comp;
    double sum_sq;
    uint64_t n;
    uint64_t rejected_at; /* 0 if not yet rejected, else first tick t */
    uint64_t n_invalid;   /* count of sanitized NaN/Inf inputs */
} eproc_bet_t;

typedef struct {
    uint64_t n;
    double e_value;       /* exp(min(log_e, 700)) */
    double log_e;
    double max_log_e;
    double p_value;       /* min(1.0, exp(-max_log_e)) — anytime-valid */
    double mean;
    int32_t rejected;     /* 1 if max_log_e >= log(1/alpha) */
    uint32_t _pad0;
} eproc_bet_result_t;

int eproc_bet_init(eproc_bet_t *ep,
                   double mu0,
                   double alpha,
                   double lower,
                   double upper,
                   int32_t side);

int eproc_bet_update(eproc_bet_t *ep, double x, eproc_bet_result_t *out);

int eproc_bet_update_batch(eproc_bet_t *ep,
                           const double *xs,
                           size_t n,
                           eproc_bet_result_t *out);

void eproc_bet_query(const eproc_bet_t *ep, eproc_bet_result_t *out);

/* Combine two independent e-processes: log E_prod = log E_a + log E_b */
double eproc_combine_independent_log(double log_e_a, double log_e_b);

/* Combine K arbitrarily dependent e-processes: E_avg = (1/K) sum_k E_k (Vovk & Wang 2021) */
double eproc_combine_dependent_log(const double *log_es, size_t k);

/*
 * Exact Closed-Form Empirical-Bernstein Confidence Sequence (Waudby-Smith & Ramdas 2024)
 * for bounded streams X_t in [lower, upper], plus sub-Gaussian Normal-Mixture CS
 * (Howard et al. 2021) when mode == 1.
 *
 * Runs in O(1) time and O(1) memory (~25 ns/update) with running-intersection tightening.
 */
#define EPROC_CS_EMPIRICAL_BERNSTEIN 0
#define EPROC_CS_NORMAL_MIXTURE      1

typedef struct {
    double lower;
    double upper;
    double span;
    double inv_span;
    double alpha;
    double log_2_over_alpha;
    double sigma;         /* sub-Gaussian proxy for NORMAL_MIXTURE */
    double rho;           /* mixture prior variance for NORMAL_MIXTURE */
    int32_t mode;
    uint32_t _pad0;

    /* Empirical-Bernstein predictable accumulators (normalized to [0, 1]) */
    double sum_y;
    double sum_y_comp;
    double sum_sq_dev;    /* sum (y_s - mu_hat_{s-1})^2 */
    double sum_lam;       /* sum lambda_s */
    double sum_lam_y;     /* sum lambda_s * y_s */
    double sum_psi_v;     /* sum psi_E(lambda_s) * (y_s - mu_hat_{s-1})^2 */

    /* Running intersection bounds in original [lower, upper] scale */
    double cs_low;
    double cs_high;
    double sum_x;
    double sum_x_comp;
    uint64_t n;
    uint64_t n_invalid;
} eproc_cs_t;

typedef struct {
    uint64_t n;
    double mean;
    double low;
    double high;
    double width;
} eproc_cs_result_t;

int eproc_cs_init_eb(eproc_cs_t *cs, double alpha, double lower, double upper);
int eproc_cs_init_normal(eproc_cs_t *cs, double alpha, double sigma, double v_opt);
int eproc_cs_update(eproc_cs_t *cs, double x, eproc_cs_result_t *out);
int eproc_cs_update_batch(eproc_cs_t *cs,
                          const double *xs,
                          size_t n,
                          eproc_cs_result_t *out);
void eproc_cs_query(const eproc_cs_t *cs, eproc_cs_result_t *out);

/*
 * Anytime-Valid E-Detector (Page / Shiryaev-Roberts resettable e-process)
 * for streaming drift / silent regression detection.
 * Alarms when R_t = max(1, R_{t-1}) * e_t >= 1/alpha (ARL >= 1/alpha under H0).
 */
typedef struct {
    eproc_bet_t inner;
    double log_cusum;     /* Page-CUSUM resettable e-detector log R_t */
    double max_log_cusum;
    double log_thresh;
    uint64_t alarm_at;
    uint64_t n_alarms;
    uint64_t n;
} eproc_edetect_t;

typedef struct {
    uint64_t n;
    double log_stat;
    double stat;
    int32_t alarm;
    uint32_t _pad0;
} eproc_edetect_result_t;

int eproc_edetect_init(eproc_edetect_t *ed,
                       double mu0,
                       double alpha,
                       double lower,
                       double upper,
                       int32_t side);
int eproc_edetect_update(eproc_edetect_t *ed, double x, eproc_edetect_result_t *out);
void eproc_edetect_reset_alarm(eproc_edetect_t *ed);

/*
 * Anytime-Valid Multi-Arm Agent/Model Racer (Best-Arm Identification with
 * Automatic Early Elimination & Exact FWER Control).
 *
 * Each of K arms maintains an Empirical-Bernstein Confidence Sequence at
 * Bonferroni-adjusted alpha / K. Arm j is eliminated the instant
 *   cs_high[j] < max_i cs_low[i] - margin.
 * Winner is certified when only 1 active arm remains.
 */
typedef struct {
    uint32_t n_arms;
    uint32_t n_active;
    double alpha;
    double lower;
    double upper;
    double margin;        /* indifference / practical significance margin >= 0 */
    int32_t winner;       /* -1 until certified, else winning arm index */
    uint32_t _pad0;
    uint64_t total_obs;
    uint8_t active[EPROC_MAX_ARMS];
    uint64_t eliminated_at[EPROC_MAX_ARMS];
    eproc_cs_t arms[EPROC_MAX_ARMS];
} eproc_race_t;

typedef struct {
    uint32_t n_arms;
    uint32_t n_active;
    int32_t winner;
    int32_t leader;
    uint64_t total_obs;
    double leader_low;
    double leader_high;
    double runner_up_high;
} eproc_race_status_t;

int eproc_race_init(eproc_race_t *race,
                    uint32_t n_arms,
                    double alpha,
                    double lower,
                    double upper,
                    double margin);

int eproc_race_update(eproc_race_t *race,
                      uint32_t arm,
                      double reward,
                      eproc_race_status_t *out);

int eproc_race_update_batch(eproc_race_t *race,
                            const uint32_t *arms,
                            const double *rewards,
                            size_t n,
                            eproc_race_status_t *out);

void eproc_race_status(const eproc_race_t *race, eproc_race_status_t *out);
int eproc_race_arm_state(const eproc_race_t *race,
                         uint32_t arm,
                         eproc_cs_result_t *out,
                         int32_t *is_active);
/* Recommend next arm to sample (LCB/UCB active gap-maximizing scheduler) */
int32_t eproc_race_suggest_arm(const eproc_race_t *race);


/* ============================================================================
 * 2. MULTI-RATE ONLINE CONFORMAL, DELAYED FEEDBACK, BUDGET BOUNDS & MONOID
 * ============================================================================ */

/*
 * Multi-Rate Crossing-Free AgACI + Conformal PID Calibrator.
 * Simultaneously calibrates up to 5 coverage levels (e.g. 50/80/90/95/99%)
 * with zero quantile crossing (PAVA isotonic projection), O(W) L1-resident
 * sorted score ring, and 4-rate online BOA/Hedge expert aggregation per rate.
 */
typedef struct {
    uint32_t n_rates;
    uint32_t win_cap;
    uint32_t win_len;
    uint32_t ring_pos;
    double pid_ki;        /* integral saturation gain (0 = pure AgACI) */
    double pid_csat;      /* saturation scale */
    uint64_t n_updates;

    double target_alphas[EPROC_MAX_RATES]; /* descending alpha = ascending coverage */
    double gammas[EPROC_AGACI_EXPERTS];    /* {0.005, 0.02, 0.08, 0.20} */

    /* Per-rate, per-expert adaptive alpha_t & BOA weights */
    double alpha_t[EPROC_MAX_RATES][EPROC_AGACI_EXPERTS];
    double exp_log_w[EPROC_MAX_RATES][EPROC_AGACI_EXPERTS];
    double exp_var[EPROC_MAX_RATES][EPROC_AGACI_EXPERTS];
    double pid_err_sum[EPROC_MAX_RATES];
    double eff_alpha[EPROC_MAX_RATES];
    double current_q[EPROC_MAX_RATES];     /* guaranteed non-decreasing */
    double emp_cov_ema[EPROC_MAX_RATES];
    uint64_t hit_counts[EPROC_MAX_RATES];

    /* Circular raw buffer + incrementally maintained sorted buffer */
    double ring[EPROC_CONFORMAL_MAX_WIN];
    double sorted[EPROC_CONFORMAL_MAX_WIN];
} eproc_conformal_t;

typedef struct {
    uint32_t n_rates;
    uint32_t _pad0;
    double quantiles[EPROC_MAX_RATES];     /* monotone non-decreasing radii */
    double eff_alphas[EPROC_MAX_RATES];
    double emp_coverage[EPROC_MAX_RATES];
} eproc_conformal_out_t;

int eproc_conformal_init(eproc_conformal_t *cp,
                         const double *alphas,
                         uint32_t n_rates,
                         uint32_t window_size,
                         double pid_ki);

void eproc_conformal_predict(const eproc_conformal_t *cp,
                             double point_pred,
                             double scale,
                             double *lows_out,
                             double *highs_out,
                             eproc_conformal_out_t *meta_out);

int eproc_conformal_update(eproc_conformal_t *cp,
                           double nonconformity_score,
                           eproc_conformal_out_t *meta_out);

int eproc_conformal_update_batch(eproc_conformal_t *cp,
                                 const double *scores,
                                 size_t n,
                                 eproc_conformal_out_t *meta_out);

/*
 * Strictly Causal Delayed-Feedback Conformal Wrapper.
 * Issue predictions at t_issue; reveal ground truth y at arbitrary later t_reveal.
 * Predictions depend ONLY on labels revealed <= t_issue (assert_causal exact).
 */
typedef struct {
    uint64_t ticket_id;
    double pred;
    double scale;
    uint8_t occupied;
    uint8_t _pad[7];
} eproc_delay_slot_t;

typedef struct {
    eproc_conformal_t core;
    uint32_t pending_count;
    uint32_t _pad0;
    uint64_t next_ticket;
    eproc_delay_slot_t slots[EPROC_DELAY_MAX_PENDING];
} eproc_delayed_conformal_t;

int eproc_delayed_conformal_init(eproc_delayed_conformal_t *dc,
                                 const double *alphas,
                                 uint32_t n_rates,
                                 uint32_t window_size,
                                 double pid_ki);

int eproc_delayed_conformal_issue(eproc_delayed_conformal_t *dc,
                                  double pred,
                                  double scale,
                                  uint64_t *ticket_out,
                                  double *lows_out,
                                  double *highs_out);

int eproc_delayed_conformal_reveal(eproc_delayed_conformal_t *dc,
                                   uint64_t ticket_id,
                                   double y_true,
                                   eproc_conformal_out_t *meta_out);

/*
 * Right-Censored Agent Budget Conformal Calibrator (PROBE-style UPB).
 * Calibrates upper predictive bounds on agent latency/tokens/steps when
 * timed-out trajectories are right-censored at budget B_t.
 */
typedef struct {
    eproc_conformal_t core;
    double censor_penalty; /* conservative inflation factor >= 1.0 on censored runs */
    uint64_t n_completed;
    uint64_t n_censored;
} eproc_budget_conformal_t;

int eproc_budget_conformal_init(eproc_budget_conformal_t *bc,
                                double alpha,
                                uint32_t window_size,
                                double censor_penalty);

double eproc_budget_conformal_bound(const eproc_budget_conformal_t *bc,
                                    double base_estimate);

int eproc_budget_conformal_update(eproc_budget_conformal_t *bc,
                                  double base_estimate,
                                  double observed_cost,
                                  int32_t censored);

/*
 * Exact Associative & Commutative Distributed Conformal Monoid (640 bytes fixed!).
 *
 * Uses uint64_t exact bin counts over 64 signed log-spaced buckets spanning
 * [-16, +32] (with 2 tail overflow buckets), making merge(A, B) and
 * leave-one-out subtract(global, local) BIT-EXACT abelian group operations
 * (0.0 associativity drift across arbitrary tree-reduction orders!).
 */
typedef struct {
    uint64_t count;
    uint64_t bin_counts[EPROC_CMONOID_BINS];
    double sum;
    double sum_comp;
    double sum_sq;
    double sum_sq_comp;
    double min_val;
    double max_val;
    double log_wealth;
    double scale_hint;    /* optional reference scale (>0, default 1.0) */
    uint64_t flags;
    uint64_t _reserved[6];
} eproc_cmonoid_t;

void eproc_cmonoid_init(eproc_cmonoid_t *m, double scale_hint);
void eproc_cmonoid_add(eproc_cmonoid_t *m, double score);
void eproc_cmonoid_add_batch(eproc_cmonoid_t *m, const double *scores, size_t n);
void eproc_cmonoid_merge(const eproc_cmonoid_t *a,
                         const eproc_cmonoid_t *b,
                         eproc_cmonoid_t *out);
int  eproc_cmonoid_subtract(const eproc_cmonoid_t *global_m,
                            const eproc_cmonoid_t *local_m,
                            eproc_cmonoid_t *loo_out);
double eproc_cmonoid_quantile(const eproc_cmonoid_t *m, double q);
size_t eproc_cmonoid_wire_size(void);
int  eproc_cmonoid_serialize(const eproc_cmonoid_t *m, uint8_t *buf, size_t cap);
int  eproc_cmonoid_deserialize(eproc_cmonoid_t *m, const uint8_t *buf, size_t len);


/* ============================================================================
 * 3. BYZANTINE-SAFE MULTI-AGENT EVIDENCE & PREDICTION FUSION
 * ============================================================================ */

/*
 * Scale-Free Bernstein Online Aggregation (BOA, Wintenberger 2017) with
 * 3-Gate Ville E-Process Non-Inferiority Fallback & Poisoning Isolation.
 *
 * Also exposes a Boehm-2012 lock-free seqlocked snapshot of active weights
 * so concurrent inference threads read weights with 0 locks and 0 torn reads.
 */
typedef struct {
    uint32_t n_experts;
    uint32_t anchor_idx;      /* fallback baseline expert index */
    int32_t fallback_active;  /* 1 if deg_e tripped and BOA is quarantined */
    uint32_t _pad0;
    double scale_ema;         /* F_{t-1}-predictable loss scale */
    double clip_mult;         /* poisoning cap multiplier (default 25.0) */
    uint64_t n_updates;
    uint64_t n_poison_clipped;
    uint64_t n_fallback_trips;

    double weights[EPROC_BOA_MAX_EXPERTS];
    double log_w[EPROC_BOA_MAX_EXPERTS];
    double grad_sq_sum[EPROC_BOA_MAX_EXPERTS];
    double cum_loss[EPROC_BOA_MAX_EXPERTS];
    uint8_t quarantined[EPROC_BOA_MAX_EXPERTS];
    uint32_t poison_strikes[EPROC_BOA_MAX_EXPERTS];

    /* 3 Ville E-processes gating non-inferiority vs anchor */
    eproc_bet_t sup_e;        /* superiority vs anchor */
    eproc_bet_t deg_e;        /* degradation vs anchor -> trips fallback */
    eproc_bet_t rec_e;        /* recovery after fallback -> re-enables BOA */

    /* Lock-free Boehm-2012 seqlocked snapshot of published weights */
    uint64_t seqlock_seq;     /* accessed atomically in C implementation */
    uint64_t seqlock_words[EPROC_BOA_MAX_EXPERTS + 2]; /* weights + meta */
} eproc_boa_t;

typedef struct {
    double fused_pred;
    double anchor_pred;
    int32_t fallback_active;
    uint32_t n_quarantined;
    double sup_log_e;
    double deg_log_e;
    uint64_t n_updates;
} eproc_boa_step_t;

int eproc_boa_init(eproc_boa_t *boa,
                   uint32_t n_experts,
                   uint32_t anchor_idx,
                   double alpha_deg);

double eproc_boa_predict(const eproc_boa_t *boa, const double *expert_preds);

int eproc_boa_update(eproc_boa_t *boa,
                     const double *expert_preds,
                     double y_true,
                     eproc_boa_step_t *out);

int eproc_boa_snapshot_weights(const eproc_boa_t *boa,
                               double *weights_out,
                               uint32_t max_experts,
                               int32_t *fallback_out);

/*
 * Provenance-Deduplicated Multi-Agent Evidence Pool (EchoPool) + Online
 * Beta-Bernoulli Peer Reliability Tracker.
 *
 * Solves:
 *  - Echo double-counting: each unique (claim_id, evidence_id) counted ONCE.
 *  - Overwrite churn (84% at W=8 -> 0%): commutative log-odds accumulation.
 *  - Uncalibrated / sycophantic / Byzantine peers: Beta-Bernoulli reliability
 *    weighting shrinks noisy/adversarial agents toward 0 weight.
 */
typedef struct {
    uint64_t key_hash;
    uint64_t evidence_id;
    uint32_t claim_id;
    uint32_t source_id;
    double weighted_llr;
    uint8_t used;
    uint8_t _pad[7];
} eproc_echo_slot_t;

typedef struct {
    uint32_t n_sources;
    uint32_t n_claims;
    uint64_t n_accepted;
    uint64_t n_echo_dropped;
    uint64_t n_table_full;

    /* Per-source Beta-Bernoulli accuracy / reliability state */
    double src_alpha[EPROC_ECHO_MAX_SOURCES];
    double src_beta[EPROC_ECHO_MAX_SOURCES];
    double src_reliability[EPROC_ECHO_MAX_SOURCES]; /* in [0, 1] */

    /* Per-claim accumulated log-odds & unique evidence count */
    double claim_prior_lo[EPROC_ECHO_MAX_CLAIMS];
    double claim_lo[EPROC_ECHO_MAX_CLAIMS];
    double claim_lo_comp[EPROC_ECHO_MAX_CLAIMS];
    uint64_t claim_unique[EPROC_ECHO_MAX_CLAIMS];

    /* Open-addressing deduplication table */
    eproc_echo_slot_t table[EPROC_ECHO_TABLE_CAP];
} eproc_echopool_t;

typedef struct {
    int32_t accepted;       /* 1 if novel evidence, 0 if duplicate echo dropped */
    uint32_t _pad0;
    double posterior_prob;
    double log_odds;
    double source_reliability;
    uint64_t unique_count;
} eproc_echo_out_t;

int eproc_echopool_init(eproc_echopool_t *pool,
                        uint32_t n_sources,
                        uint32_t n_claims,
                        double prior_prob);

int eproc_echopool_submit(eproc_echopool_t *pool,
                          uint32_t source_id,
                          uint32_t claim_id,
                          uint64_t evidence_id,
                          double llr,
                          eproc_echo_out_t *out);

int eproc_echopool_resolve(eproc_echopool_t *pool,
                           uint32_t claim_id,
                           int32_t outcome_positive);

double eproc_echopool_posterior(const eproc_echopool_t *pool, uint32_t claim_id);
double eproc_echopool_source_reliability(const eproc_echopool_t *pool, uint32_t source_id);


/* ============================================================================
 * 4. CAUSAL ONLINE SUBSAMPLING & MULTI-RESOLUTION VALUE-OF-INFORMATION (VOI)
 * ============================================================================ */

/*
 * Variance-Optimal Weighted Reservoir Sampler (Cohen et al. 2011)
 * with exact unbiased Horvitz-Thompson adjusted weights.
 */
typedef struct {
    uint64_t item_id;
    double orig_weight;
    double adj_weight;    /* Horvitz-Thompson unbiased weight */
    double value;
    double rand_u;
} eproc_varopt_item_t;

typedef struct {
    uint32_t k;           /* reservoir capacity <= EPROC_VAROPT_MAX_K */
    uint32_t count;       /* current items in reservoir */
    uint32_t n_heavy;     /* count of heavy items (w >= tau) */
    uint32_t _pad0;
    double tau;           /* inclusion threshold */
    double total_weight;
    double total_weight_comp;
    uint64_t n_seen;
    uint64_t rng_state[2]; /* xoshiro128++ deterministic PRNG */
    eproc_varopt_item_t items[EPROC_VAROPT_MAX_K];
} eproc_varopt_t;

int eproc_varopt_init(eproc_varopt_t *vo, uint32_t k, uint64_t seed);
int eproc_varopt_push(eproc_varopt_t *vo, uint64_t item_id, double weight, double value);
double eproc_varopt_estimate_sum(const eproc_varopt_t *vo);
double eproc_varopt_estimate_mean(const eproc_varopt_t *vo);

/*
 * Online Ridge Leverage Score (RLS) Causal Subsampler
 * (Cohen-Musco-Pachocki, Sherman-Morrison rank-1 inverse updates).
 */
typedef struct {
    uint32_t d;           /* feature dimension <= EPROC_RLS_MAX_D */
    uint32_t _pad0;
    double lambda;        /* ridge regularization > 0 */
    double oversample;    /* multiplier c >= 1.0 */
    double min_prob;      /* heartbeat floor p_min in (0, 1] */
    uint64_t n_seen;
    uint64_t n_kept;
    uint64_t rng_state[2];
    double inv_a[EPROC_RLS_MAX_D * EPROC_RLS_MAX_D];
} eproc_rls_t;

typedef struct {
    int32_t keep;
    uint32_t _pad0;
    double leverage;
    double prob;
    double ht_weight;     /* 1.0 / prob if kept, else 0.0 */
} eproc_rls_out_t;

int eproc_rls_init(eproc_rls_t *rls,
                   uint32_t d,
                   double lambda,
                   double oversample,
                   double min_prob,
                   uint64_t seed);

int eproc_rls_step(eproc_rls_t *rls, const double *x, eproc_rls_out_t *out);

/*
 * Hierarchical Multi-Resolution Bayes Value-of-Information (VOI) Selector
 * (for massive sparse anomaly detection across S sites x M channels under
 * tight attention/tool-call budgets).
 */
typedef struct {
    uint32_t n_sites;
    uint32_t per_site;
    double prior_hot_site;
    double prior_active_cold;
    double prior_active_hot;
    double signal_mean;
    double noise_sd;
    /* Per-site log posterior of hot site, per-channel log odds of active */
    double site_log_prob[EPROC_SIFT_MAX_SITES];
    double chan_prob[EPROC_SIFT_MAX_SITES * EPROC_SIFT_MAX_PER_SITE];
    double chan_noise_scale[EPROC_SIFT_MAX_SITES * EPROC_SIFT_MAX_PER_SITE];
} eproc_sift_t;

typedef struct {
    int32_t action_type;  /* 0 = read site mean, 1 = read channel mean, 2 = read raw ticks */
    uint32_t target_idx;  /* site_id if type==0, else flat channel index */
    double evoi_per_cost;
} eproc_sift_action_t;

int eproc_sift_init(eproc_sift_t *sf,
                    uint32_t n_sites,
                    uint32_t per_site,
                    double signal_mean,
                    double noise_sd);

int eproc_sift_set_noise_scale(eproc_sift_t *sf,
                               uint32_t channel_idx,
                               double noise_scale);

int eproc_sift_observe_channel(eproc_sift_t *sf,
                               uint32_t channel_idx,
                               double obs_mean,
                               uint32_t n_ticks);

int eproc_sift_observe_site(eproc_sift_t *sf,
                            uint32_t site_idx,
                            double site_mean);

int eproc_sift_select_next(const eproc_sift_t *sf,
                           double cost_site,
                           double cost_channel,
                           double cost_ticks,
                           uint32_t ticks_per_read,
                           eproc_sift_action_t *out);

/* Runtime capability query (e.g., returns 1 if compiled with AVX2/FMA) */
uint32_t eproc_abi_version(void);
uint32_t eproc_simd_flags(void); /* bit 0: AVX2, bit 1: FMA, bit 2: NEON */

#ifdef __cplusplus
}
#endif

#endif /* EPROC_H */

#ifdef EPROC_IMPLEMENTATION

#ifndef EPROC_IMPLEMENTATION_INCLUDED

#define EPROC_IMPLEMENTATION_INCLUDED


#ifndef EPROC_SEQLOCK_H
#define EPROC_SEQLOCK_H

/*
 * Lock-free Boehm-2012 atomic seqlock for zero-torn-read concurrent
 * snapshots of online inference state (portable C11 & C++17).
 *
 * Writer protocol (single-writer or CAS-serialized multi-writer):
 *   1. CAS seq even -> odd (acq_rel)
 *   2. release fence
 *   3. Write payload words as relaxed atomic uint64_t stores
 *   4. Store seq = odd + 1 (release)
 *
 * Reader protocol (wait-free fast path, zero locks):
 *   1. Load s1 = seq (acquire); if odd, spin with CPU pause
 *   2. Read payload words as relaxed atomic uint64_t loads
 *   3. acquire fence
 *   4. Load s2 = seq (relaxed); retry if s1 != s2
 *
 * Verified under TSan with atomic payload words (zero C11/C++17 data-race UB).
 */

#ifdef __cplusplus
#include <atomic>
#else
#include <stdatomic.h>
#endif

#include <stddef.h>
#include <stdint.h>
#include <string.h>

#if defined(__x86_64__) || defined(_M_X64) || defined(__i386__)
#define EPROC_CPU_PAUSE() __asm__ __volatile__("pause" ::: "memory")
#elif defined(__aarch64__) || defined(__arm__)
#define EPROC_CPU_PAUSE() __asm__ __volatile__("yield" ::: "memory")
#else
#define EPROC_CPU_PAUSE() ((void)0)
#endif

/* ============================================================================
 * 1. Typed atomic seqlock API (C11 _Atomic uint64_t / C++17 std::atomic<uint64_t>)
 * ============================================================================ */
#ifdef __cplusplus

static inline uint64_t eproc_seqlock_write_begin(std::atomic<uint64_t> *seq) {
    uint64_t s = seq->load(std::memory_order_relaxed);
    for (;;) {
        if ((s & 1ULL) != 0ULL) {
            EPROC_CPU_PAUSE();
            s = seq->load(std::memory_order_relaxed);
            continue;
        }
        if (seq->compare_exchange_weak(
                s, s + 1ULL, std::memory_order_acq_rel, std::memory_order_relaxed)) {
            std::atomic_thread_fence(std::memory_order_release);
            return s + 1ULL;
        }
        EPROC_CPU_PAUSE();
    }
}

static inline void eproc_seqlock_write_end(std::atomic<uint64_t> *seq, uint64_t odd_seq) {
    seq->store(odd_seq + 1ULL, std::memory_order_release);
}

static inline void eproc_seqlock_store_words(std::atomic<uint64_t> *dst,
                                             const void *src,
                                             size_t n_words) {
    const uint8_t *p = (const uint8_t *)src;
    for (size_t i = 0; i < n_words; ++i) {
        uint64_t w;
        memcpy(&w, p + i * sizeof(uint64_t), sizeof(uint64_t));
        dst[i].store(w, std::memory_order_relaxed);
    }
}

static inline uint64_t eproc_seqlock_read_words(const std::atomic<uint64_t> *seq,
                                                const std::atomic<uint64_t> *src,
                                                void *dst,
                                                size_t n_words) {
    uint8_t *p = (uint8_t *)dst;
    for (;;) {
        uint64_t s1 = seq->load(std::memory_order_acquire);
        if ((s1 & 1ULL) != 0ULL) {
            EPROC_CPU_PAUSE();
            continue;
        }
        for (size_t i = 0; i < n_words; ++i) {
            uint64_t w = src[i].load(std::memory_order_relaxed);
            memcpy(p + i * sizeof(uint64_t), &w, sizeof(uint64_t));
        }
        std::atomic_thread_fence(std::memory_order_acquire);
        uint64_t s2 = seq->load(std::memory_order_relaxed);
        if (s1 == s2) {
            return s1;
        }
        EPROC_CPU_PAUSE();
    }
}

#else /* C11 */

static inline uint64_t eproc_seqlock_write_begin(_Atomic uint64_t *seq) {
    uint64_t s = atomic_load_explicit(seq, memory_order_relaxed);
    for (;;) {
        if ((s & 1ULL) != 0ULL) {
            EPROC_CPU_PAUSE();
            s = atomic_load_explicit(seq, memory_order_relaxed);
            continue;
        }
        if (atomic_compare_exchange_weak_explicit(
                seq, &s, s + 1ULL, memory_order_acq_rel, memory_order_relaxed)) {
            atomic_thread_fence(memory_order_release);
            return s + 1ULL;
        }
        EPROC_CPU_PAUSE();
    }
}

static inline void eproc_seqlock_write_end(_Atomic uint64_t *seq, uint64_t odd_seq) {
    atomic_store_explicit(seq, odd_seq + 1ULL, memory_order_release);
}

static inline void eproc_seqlock_store_words(_Atomic uint64_t *dst,
                                             const void *src,
                                             size_t n_words) {
    const uint8_t *p = (const uint8_t *)src;
    for (size_t i = 0; i < n_words; ++i) {
        uint64_t w;
        memcpy(&w, p + i * sizeof(uint64_t), sizeof(uint64_t));
        atomic_store_explicit(&dst[i], w, memory_order_relaxed);
    }
}

static inline uint64_t eproc_seqlock_read_words(const _Atomic uint64_t *seq,
                                                const _Atomic uint64_t *src,
                                                void *dst,
                                                size_t n_words) {
    uint8_t *p = (uint8_t *)dst;
    for (;;) {
        uint64_t s1 = atomic_load_explicit(seq, memory_order_acquire);
        if ((s1 & 1ULL) != 0ULL) {
            EPROC_CPU_PAUSE();
            continue;
        }
        for (size_t i = 0; i < n_words; ++i) {
            uint64_t w = atomic_load_explicit(&src[i], memory_order_relaxed);
            memcpy(p + i * sizeof(uint64_t), &w, sizeof(uint64_t));
        }
        atomic_thread_fence(memory_order_acquire);
        uint64_t s2 = atomic_load_explicit(seq, memory_order_relaxed);
        if (s1 == s2) {
            return s1;
        }
        EPROC_CPU_PAUSE();
    }
}

#endif /* __cplusplus */

/* ============================================================================
 * 2. Zero-UB plain uint64_t ABI seqlock API (for C-ABI structs like eproc_boa_t
 *    that store uint64_t fields in public headers for C/C++/FFI compatibility).
 *    Uses GCC/Clang __atomic_* builtins directly on uint64_t* (zero type-punning
 *    UB, full TSan visibility, works identically in C11 and C++17).
 * ============================================================================ */
#if defined(__GNUC__) || defined(__clang__)

static inline void eproc_seqlock_init_u64(uint64_t *seq, uint64_t *words, size_t n_words) {
    __atomic_store_n(seq, 0ULL, __ATOMIC_RELAXED);
    for (size_t i = 0; i < n_words; ++i) {
        __atomic_store_n(&words[i], 0ULL, __ATOMIC_RELAXED);
    }
}

static inline uint64_t eproc_seqlock_write_begin_u64(uint64_t *seq) {
    uint64_t s = __atomic_load_n(seq, __ATOMIC_RELAXED);
    for (;;) {
        if ((s & 1ULL) != 0ULL) {
            EPROC_CPU_PAUSE();
            s = __atomic_load_n(seq, __ATOMIC_RELAXED);
            continue;
        }
        if (__atomic_compare_exchange_n(
                seq, &s, s + 1ULL, 1, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)) {
            __atomic_thread_fence(__ATOMIC_RELEASE);
            return s + 1ULL;
        }
        EPROC_CPU_PAUSE();
    }
}

static inline void eproc_seqlock_write_end_u64(uint64_t *seq, uint64_t odd_seq) {
    __atomic_store_n(seq, odd_seq + 1ULL, __ATOMIC_RELEASE);
}

static inline void eproc_seqlock_store_words_u64(uint64_t *dst,
                                                 const void *src,
                                                 size_t n_words) {
    const uint8_t *p = (const uint8_t *)src;
    for (size_t i = 0; i < n_words; ++i) {
        uint64_t w;
        memcpy(&w, p + i * sizeof(uint64_t), sizeof(uint64_t));
        __atomic_store_n(&dst[i], w, __ATOMIC_RELAXED);
    }
}

static inline uint64_t eproc_seqlock_read_words_u64(const uint64_t *seq,
                                                    const uint64_t *src,
                                                    void *dst,
                                                    size_t n_words) {
    uint8_t *p = (uint8_t *)dst;
    for (;;) {
        uint64_t s1 = __atomic_load_n(seq, __ATOMIC_ACQUIRE);
        if ((s1 & 1ULL) != 0ULL) {
            EPROC_CPU_PAUSE();
            continue;
        }
        for (size_t i = 0; i < n_words; ++i) {
            uint64_t w = __atomic_load_n(&src[i], __ATOMIC_RELAXED);
            memcpy(p + i * sizeof(uint64_t), &w, sizeof(uint64_t));
        }
        __atomic_thread_fence(__ATOMIC_ACQUIRE);
        uint64_t s2 = __atomic_load_n(seq, __ATOMIC_RELAXED);
        if (s1 == s2) {
            return s1;
        }
        EPROC_CPU_PAUSE();
    }
}

static inline uint64_t eproc_seqlock_read_meta_words_u64(const uint64_t *seq,
                                                         const uint64_t *src,
                                                         size_t meta_idx,
                                                         uint64_t *meta_out,
                                                         uint64_t *dst,
                                                         size_t max_words) {
    for (;;) {
        uint64_t s1 = __atomic_load_n(seq, __ATOMIC_ACQUIRE);
        if ((s1 & 1ULL) != 0ULL) {
            EPROC_CPU_PAUSE();
            continue;
        }
        uint64_t meta = __atomic_load_n(&src[meta_idx], __ATOMIC_RELAXED);
        size_t n_words = (size_t)(meta >> 32);
        if (n_words > max_words) {
            n_words = max_words;
        }
        for (size_t i = 0; i < n_words; ++i) {
            dst[i] = __atomic_load_n(&src[i], __ATOMIC_RELAXED);
        }
        __atomic_thread_fence(__ATOMIC_ACQUIRE);
        uint64_t s2 = __atomic_load_n(seq, __ATOMIC_RELAXED);
        if (s1 == s2) {
            *meta_out = meta;
            return s1;
        }
        EPROC_CPU_PAUSE();
    }
}

#else

/* Fallback for non-GCC/Clang toolchains */
#ifdef __cplusplus
typedef std::atomic<uint64_t> eproc_seqlock_u64_atom_t;
#else
typedef _Atomic uint64_t eproc_seqlock_u64_atom_t;
#endif

static inline void eproc_seqlock_init_u64(uint64_t *seq, uint64_t *words, size_t n_words) {
    *seq = 0ULL;
    for (size_t i = 0; i < n_words; ++i) {
        words[i] = 0ULL;
    }
}

static inline uint64_t eproc_seqlock_write_begin_u64(uint64_t *seq) {
    return eproc_seqlock_write_begin((eproc_seqlock_u64_atom_t *)(void *)seq);
}

static inline void eproc_seqlock_write_end_u64(uint64_t *seq, uint64_t odd_seq) {
    eproc_seqlock_write_end((eproc_seqlock_u64_atom_t *)(void *)seq, odd_seq);
}

static inline void eproc_seqlock_store_words_u64(uint64_t *dst,
                                                 const void *src,
                                                 size_t n_words) {
    eproc_seqlock_store_words((eproc_seqlock_u64_atom_t *)(void *)dst, src, n_words);
}

static inline uint64_t eproc_seqlock_read_words_u64(const uint64_t *seq,
                                                    const uint64_t *src,
                                                    void *dst,
                                                    size_t n_words) {
    return eproc_seqlock_read_words((const eproc_seqlock_u64_atom_t *)(const void *)seq,
                                    (const eproc_seqlock_u64_atom_t *)(const void *)src,
                                    dst, n_words);
}

static inline uint64_t eproc_seqlock_read_meta_words_u64(const uint64_t *seq,
                                                         const uint64_t *src,
                                                         size_t meta_idx,
                                                         uint64_t *meta_out,
                                                         uint64_t *dst,
                                                         size_t max_words) {
    uint64_t full[66];
    const size_t total = (meta_idx + 1U <= 66U) ? (meta_idx + 1U) : 66U;
    uint64_t s = eproc_seqlock_read_words_u64(seq, src, full, total);
    uint64_t meta = full[meta_idx];
    size_t n_words = (size_t)(meta >> 32);
    if (n_words > max_words) {
        n_words = max_words;
    }
    for (size_t i = 0; i < n_words; ++i) {
        dst[i] = full[i];
    }
    *meta_out = meta;
    return s;
}

#endif /* __GNUC__ || __clang__ */

#endif /* EPROC_SEQLOCK_H */


#ifndef EPROC_INTERNAL_H
#define EPROC_INTERNAL_H

/*
 * Internal numerical primitives, compensated summation, log-domain math,
 * and deterministic PRNG shared across eproc C11/C++17 translation units.
 */

#include <math.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>

#ifdef __cplusplus
#define EPROC_STATIC_ASSERT(cond, msg) static_assert((cond), msg)
#else
#define EPROC_STATIC_ASSERT(cond, msg) _Static_assert((cond), msg)
#endif

#define EPROC_LN2       0.693147180559945309417232121458176568
#define EPROC_LN3       1.098612288668109691395245236922525705
#define EPROC_INV_SQRT2 0.707106781186547524400844362104849039
/* ONS step size: 2 / (2 - log(3)) */
#define EPROC_ONS_ETA   (2.0 / (2.0 - EPROC_LN3))

/* NaN-safe clamp: NaN maps deterministically to lo */
static inline double eproc_clamp(double x, double lo, double hi) {
    if (isnan(x)) return lo;
    if (x < lo) return lo;
    if (x > hi) return hi;
    return x;
}

static inline uint64_t eproc_f64_to_u64(double x) {
    uint64_t u;
    memcpy(&u, &x, sizeof(u));
    return u;
}

static inline double eproc_u64_to_f64(uint64_t u) {
    double x;
    memcpy(&x, &u, sizeof(x));
    return x;
}

/* Overflow-safe Neumaier improved Kahan-Babuska compensated summation.
 * Exact even when |x| > |sum|, and never generates (+Inf) + (-Inf) = NaN on overflow. */
static inline void eproc_kahan_add(double *sum, double *comp, double x) {
    if (!isfinite(x)) {
        return;
    }
    const double s = *sum;
    const double t = s + x;
    if (!isfinite(t)) {
        *sum = t;
        *comp = 0.0;
        return;
    }
    double c;
    if (fabs(s) >= fabs(x)) {
        c = (s - t) + x;
    } else {
        c = (x - t) + s;
    }
    if (isfinite(c)) {
        const double nc = *comp + c;
        *comp = isfinite(nc) ? nc : 0.0;
    }
    *sum = t;
}

static inline double eproc_kahan_total(double sum, double comp) {
    if (!isfinite(sum)) return sum;
    if (!isfinite(comp)) return sum;
    const double tot = sum + comp;
    return isnan(tot) ? sum : tot;
}

/* Total order on IEEE-754 doubles for bit-exact canonical operand ordering */
static inline int eproc_f64_less_total(double a, double b) {
    if (a < b) return 1;
    if (a > b) return 0;
    return eproc_f64_to_u64(a) < eproc_f64_to_u64(b);
}

/* Bit-exact commutative compensated merge of two (sum, comp) pairs */
static inline void eproc_kahan_merge_sym(double s1, double c1,
                                         double s2, double c2,
                                         double *s_out, double *c_out) {
    if (eproc_f64_less_total(s2, s1) ||
        (eproc_f64_to_u64(s1) == eproc_f64_to_u64(s2) && eproc_f64_less_total(c2, c1))) {
        double ts = s1; s1 = s2; s2 = ts;
        double tc = c1; c1 = c2; c2 = tc;
    }
    double s = s1;
    double c = c1;
    if (!isfinite(s) || !isfinite(s2)) {
        double tot = s + s2;
        if (isnan(tot)) {
            tot = 0.0;
        }
        *s_out = (tot == 0.0) ? 0.0 : tot;
        *c_out = 0.0;
        return;
    }
    eproc_kahan_add(&s, &c, s2);
    if (isfinite(c2)) {
        eproc_kahan_add(&s, &c, c2);
    }
    /* Canonicalize -0.0 -> +0.0 for deterministic wire bytes */
    if (s == 0.0) s = 0.0;
    if (c == 0.0) c = 0.0;
    *s_out = s;
    *c_out = c;
}

/* Overflow/underflow-safe exp capped at exp(700) to avoid +Inf */
static inline double eproc_safe_exp(double x) {
    if (isnan(x)) return 1.0;
    if (x > 700.0) return exp(700.0);
    if (x < -745.0) return 0.0;
    return exp(x);
}

/* Numerically stable log(exp(a) + exp(b)) */
static inline double eproc_logaddexp(double a, double b) {
    if (isnan(a) || isnan(b)) {
        if (!isnan(a)) return a;
        if (!isnan(b)) return b;
        return 0.0;
    }
    if (a == -INFINITY) return b;
    if (b == -INFINITY) return a;
    if (isinf(a) || isinf(b)) {
        return (a > b) ? a : b;
    }
    double hi = (a >= b) ? a : b;
    double lo = (a >= b) ? b : a;
    double diff = lo - hi;
    if (diff < -745.0) return hi;
    return hi + log1p(exp(diff));
}

/* Overflow-safe logistic sigmoid */
static inline double eproc_sigmoid(double x) {
    if (isnan(x)) return 0.5;
    if (x >= 0.0) {
        if (x > 700.0) return 1.0;
        double z = exp(-x);
        return 1.0 / (1.0 + z);
    } else {
        if (x < -700.0) return 0.0;
        double z = exp(x);
        return z / (1.0 + z);
    }
}

/* Safe logit for p in (0, 1) */
static inline double eproc_logit(double p) {
    double pc = eproc_clamp(p, 1e-12, 1.0 - 1e-12);
    return log(pc / (1.0 - pc));
}

/* Standard normal CDF Phi(z) = 0.5 * erfc(-z / sqrt(2)) */
static inline double eproc_norm_cdf(double z) {
    if (isnan(z)) return 0.5;
    if (z > 38.0) return 1.0;
    if (z < -38.0) return 0.0;
    return 0.5 * erfc(-z * EPROC_INV_SQRT2);
}

/* Deterministic splitmix64 + xoroshiro128++ PRNG */
static inline uint64_t eproc_splitmix64(uint64_t *state) {
    uint64_t z = (*state += 0x9e3779b97f4a7c15ULL);
    z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;
    z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;
    return z ^ (z >> 31);
}

static inline uint64_t eproc_rotl64(uint64_t x, int k) {
    return (x << k) | (x >> (64 - k));
}

static inline void eproc_rng_seed(uint64_t s[2], uint64_t seed) {
    uint64_t sm = seed;
    s[0] = eproc_splitmix64(&sm);
    s[1] = eproc_splitmix64(&sm);
    if (s[0] == 0ULL && s[1] == 0ULL) {
        s[0] = 0x9e3779b97f4a7c15ULL;
        s[1] = 0xbf58476d1ce4e5b9ULL;
    }
}

static inline uint64_t eproc_rng_next_u64(uint64_t s[2]) {
    const uint64_t s0 = s[0];
    uint64_t s1 = s[1];
    const uint64_t result = eproc_rotl64(s0 + s1, 17) + s0;
    s1 ^= s0;
    s[0] = eproc_rotl64(s0, 49) ^ s1 ^ (s1 << 21);
    s[1] = eproc_rotl64(s1, 28);
    return result;
}

static inline double eproc_rng_uniform01(uint64_t s[2]) {
    return (double)(eproc_rng_next_u64(s) >> 11) * (1.0 / 9007199254740992.0);
}

/* Endian-safe little-endian wire encoding helpers */
static inline void eproc_put_le64(uint8_t *p, uint64_t v) {
    p[0] = (uint8_t)(v & 0xFFU);
    p[1] = (uint8_t)((v >> 8) & 0xFFU);
    p[2] = (uint8_t)((v >> 16) & 0xFFU);
    p[3] = (uint8_t)((v >> 24) & 0xFFU);
    p[4] = (uint8_t)((v >> 32) & 0xFFU);
    p[5] = (uint8_t)((v >> 40) & 0xFFU);
    p[6] = (uint8_t)((v >> 48) & 0xFFU);
    p[7] = (uint8_t)((v >> 56) & 0xFFU);
}

static inline uint64_t eproc_get_le64(const uint8_t *p) {
    return ((uint64_t)p[0])
         | ((uint64_t)p[1] << 8)
         | ((uint64_t)p[2] << 16)
         | ((uint64_t)p[3] << 24)
         | ((uint64_t)p[4] << 32)
         | ((uint64_t)p[5] << 40)
         | ((uint64_t)p[6] << 48)
         | ((uint64_t)p[7] << 56);
}

#endif /* EPROC_INTERNAL_H */


#ifndef EPROC_SIMD_H
#define EPROC_SIMD_H

/*
 * Portable compile-time + runtime CPUID AVX2 dispatch for eproc.
 *
 * - Native builds (-mavx2 / -march=native): zero-branch static AVX2.
 * - Portable x86_64 builds (PyPI wheels without -mavx2): one-time atomic-cached
 *   __builtin_cpu_supports("avx2") check dispatching into target("avx2") kernels
 *   (100% SIGILL-safe on SSE2-only CPUs, 0-ULP bit-identical to pure scalar).
 * - ARM64 / WASM / -DEPROC_FORCE_SCALAR: pure portable scalar path.
 */

#include <stdint.h>

#if defined(__AVX2__) && !defined(EPROC_FORCE_SCALAR) && !defined(__wasm__)
#  define EPROC_BUILD_AVX2   1
#  define EPROC_STATIC_AVX2  1
#  define EPROC_RUNTIME_AVX2 0
#  define EPROC_TARGET_AVX2
#  if defined(__GNUC__) || defined(__clang__)
#    define EPROC_AVX2_INLINE static inline __attribute__((always_inline))
#  else
#    define EPROC_AVX2_INLINE static inline
#  endif
#elif (defined(__GNUC__) || defined(__clang__)) \
      && (defined(__x86_64__) || defined(_M_X64)) \
      && !defined(__wasm__) && !defined(EPROC_FORCE_SCALAR)
#  define EPROC_BUILD_AVX2   1
#  define EPROC_STATIC_AVX2  0
#  define EPROC_RUNTIME_AVX2 1
#  define EPROC_TARGET_AVX2  __attribute__((target("avx2")))
#  define EPROC_AVX2_INLINE  static inline __attribute__((always_inline, target("avx2")))
#else
#  define EPROC_BUILD_AVX2   0
#  define EPROC_STATIC_AVX2  0
#  define EPROC_RUNTIME_AVX2 0
#  define EPROC_TARGET_AVX2
#  define EPROC_AVX2_INLINE  static inline
#endif

#if EPROC_BUILD_AVX2
#  include <immintrin.h>
#endif

static inline int eproc_use_avx2(void) {
#if EPROC_STATIC_AVX2
    return 1;
#elif EPROC_RUNTIME_AVX2
    static int g_eproc_avx2_state = -1;
    int s = __atomic_load_n(&g_eproc_avx2_state, __ATOMIC_RELAXED);
    if (__builtin_expect(s < 0, 0)) {
        __builtin_cpu_init();
        s = __builtin_cpu_supports("avx2") ? 1 : 0;
        __atomic_store_n(&g_eproc_avx2_state, s, __ATOMIC_RELAXED);
    }
    return s;
#else
    return 0;
#endif
}

#endif /* EPROC_SIMD_H */



/* ==================== eproc_eprocess.c ==================== */

#if !defined(__GNUC__) || defined(__clang__)
#pragma STDC FP_CONTRACT OFF
#endif


#include <math.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>

/* ============================================================================
 * 1A. ONS BETTING SUPERMARTINGALE E-PROCESS (Waudby-Smith & Ramdas 2024)
 * ============================================================================ */

static inline double eproc_bet_lam_pos_max(const eproc_bet_t *ep) {
    double denom = (ep->mu0_norm > 1e-9) ? ep->mu0_norm : 1e-9;
    return ep->c_max / denom;
}

static inline double eproc_bet_lam_neg_min(const eproc_bet_t *ep) {
    double one_minus = 1.0 - ep->mu0_norm;
    double denom = (one_minus > 1e-9) ? one_minus : 1e-9;
    return -ep->c_max / denom;
}

int eproc_bet_init(eproc_bet_t *ep,
                   double mu0,
                   double alpha,
                   double lower,
                   double upper,
                   int32_t side) {
    if (ep == NULL) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(mu0) || !isfinite(alpha) || !isfinite(lower) || !isfinite(upper)) {
        return EPROC_ERR_INVALID;
    }
    double span = upper - lower;
    if (!(span > 0.0) || !isfinite(span)) {
        return EPROC_ERR_INVALID;
    }
    if (!(alpha > 0.0 && alpha < 1.0)) {
        return EPROC_ERR_INVALID;
    }
    if (mu0 < lower || mu0 > upper) {
        return EPROC_ERR_INVALID;
    }
    if (side != EPROC_SIDE_UPPER &&
        side != EPROC_SIDE_LOWER &&
        side != EPROC_SIDE_TWO_SIDED) {
        return EPROC_ERR_INVALID;
    }

    memset(ep, 0, sizeof(*ep));
    ep->lower = lower;
    ep->upper = upper;
    ep->inv_span = 1.0 / span;
    ep->mu0_norm = eproc_clamp((mu0 - lower) * ep->inv_span, 0.0, 1.0);
    ep->alpha = alpha;
    ep->log_thresh = -log(alpha);
    ep->c_max = 0.75;
    ep->side = side;

    ep->lam_pos = 0.0;
    ep->a_pos = 1.0;
    ep->log_e_pos = 0.0;

    ep->lam_neg = 0.0;
    ep->a_neg = 1.0;
    ep->log_e_neg = 0.0;

    ep->log_e = 0.0;
    ep->max_log_e = 0.0;
    ep->sum_x = 0.0;
    ep->sum_x_comp = 0.0;
    ep->sum_sq = 0.0;
    ep->n = 0;
    ep->rejected_at = 0;
    ep->n_invalid = 0;

    return EPROC_OK;
}

void eproc_bet_query(const eproc_bet_t *ep, eproc_bet_result_t *out) {
    if (ep == NULL || out == NULL) {
        return;
    }
    out->n = ep->n;
    out->log_e = ep->log_e;
    out->max_log_e = ep->max_log_e;
    out->e_value = eproc_safe_exp(ep->log_e);
    if (ep->max_log_e <= 0.0) {
        out->p_value = 1.0;
    } else if (ep->max_log_e >= 745.0) {
        out->p_value = 0.0;
    } else {
        out->p_value = exp(-ep->max_log_e);
    }
    if (ep->n > 0) {
        out->mean = eproc_kahan_total(ep->sum_x, ep->sum_x_comp) / (double)ep->n;
    } else {
        out->mean = 0.0;
    }
    out->rejected = (ep->max_log_e >= ep->log_thresh) ? 1 : 0;
    out->_pad0 = 0;
}

int eproc_bet_update(eproc_bet_t *ep, double x, eproc_bet_result_t *out) {
    if (ep == NULL) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(x)) {
        ep->n_invalid++;
        if (out != NULL) {
            eproc_bet_query(ep, out);
        }
        return EPROC_OK;
    }

    const double x_eff = eproc_clamp(x, ep->lower, ep->upper);
    const double y = eproc_clamp((x_eff - ep->lower) * ep->inv_span, 0.0, 1.0);
    const double d = y - ep->mu0_norm;
    const int32_t side = ep->side;

    if (side == EPROC_SIDE_UPPER || side == EPROC_SIDE_TWO_SIDED) {
        const double lam_max = eproc_bet_lam_pos_max(ep);
        double step = ep->lam_pos * d;
        if (step < -0.999999999999) {
            step = -0.999999999999;
        }
        ep->log_e_pos += log1p(step);
        const double z = d / (1.0 + step);
        ep->a_pos += z * z;
        const double next_lam = ep->lam_pos + EPROC_ONS_ETA * (z / ep->a_pos);
        ep->lam_pos = eproc_clamp(next_lam, 0.0, lam_max);
    }

    if (side == EPROC_SIDE_LOWER || side == EPROC_SIDE_TWO_SIDED) {
        const double lam_min = eproc_bet_lam_neg_min(ep);
        double step = ep->lam_neg * d;
        if (step < -0.999999999999) {
            step = -0.999999999999;
        }
        ep->log_e_neg += log1p(step);
        const double z = d / (1.0 + step);
        ep->a_neg += z * z;
        const double next_lam = ep->lam_neg + EPROC_ONS_ETA * (z / ep->a_neg);
        ep->lam_neg = eproc_clamp(next_lam, lam_min, 0.0);
    }

    if (side == EPROC_SIDE_UPPER) {
        ep->log_e = ep->log_e_pos;
    } else if (side == EPROC_SIDE_LOWER) {
        ep->log_e = ep->log_e_neg;
    } else {
        ep->log_e = eproc_logaddexp(ep->log_e_pos, ep->log_e_neg) - EPROC_LN2;
    }

    if (ep->log_e > ep->max_log_e) {
        ep->max_log_e = ep->log_e;
    }

    eproc_kahan_add(&ep->sum_x, &ep->sum_x_comp, x_eff);
    ep->sum_sq += x_eff * x_eff;
    ep->n++;

    if (ep->rejected_at == 0 && ep->max_log_e >= ep->log_thresh) {
        ep->rejected_at = ep->n;
    }

    if (out != NULL) {
        eproc_bet_query(ep, out);
    }
    return EPROC_OK;
}

int eproc_bet_update_batch(eproc_bet_t *ep,
                           const double *xs,
                           size_t n,
                           eproc_bet_result_t *out) {
    if (ep == NULL || (n > 0 && xs == NULL)) {
        return EPROC_ERR_INVALID;
    }

    const double lower = ep->lower;
    const double upper = ep->upper;
    const double inv_span = ep->inv_span;
    const double mu0_norm = ep->mu0_norm;
    const double log_thresh = ep->log_thresh;
    const int32_t side = ep->side;
    const double lam_pos_max = eproc_bet_lam_pos_max(ep);
    const double lam_neg_min = eproc_bet_lam_neg_min(ep);

    double lam_pos = ep->lam_pos;
    double a_pos = ep->a_pos;
    double log_e_pos = ep->log_e_pos;
    double lam_neg = ep->lam_neg;
    double a_neg = ep->a_neg;
    double log_e_neg = ep->log_e_neg;
    double log_e = ep->log_e;
    double max_log_e = ep->max_log_e;
    double sum_x = ep->sum_x;
    double sum_x_comp = ep->sum_x_comp;
    double sum_sq = ep->sum_sq;
    uint64_t count = ep->n;
    uint64_t rejected_at = ep->rejected_at;
    uint64_t n_invalid = ep->n_invalid;

    if (side == EPROC_SIDE_UPPER) {
        for (size_t i = 0; i < n; ++i) {
            const double x = xs[i];
            if (!isfinite(x)) {
                n_invalid++;
                continue;
            }
            const double x_eff = eproc_clamp(x, lower, upper);
            const double y = eproc_clamp((x_eff - lower) * inv_span, 0.0, 1.0);
            const double d = y - mu0_norm;
            double step = lam_pos * d;
            if (step < -0.999999999999) {
                step = -0.999999999999;
            }
            log_e_pos += log1p(step);
            const double z = d / (1.0 + step);
            a_pos += z * z;
            lam_pos = eproc_clamp(lam_pos + EPROC_ONS_ETA * (z / a_pos), 0.0, lam_pos_max);

            log_e = log_e_pos;
            if (log_e > max_log_e) {
                max_log_e = log_e;
            }
            eproc_kahan_add(&sum_x, &sum_x_comp, x_eff);
            sum_sq += x_eff * x_eff;
            count++;
            if (rejected_at == 0 && max_log_e >= log_thresh) {
                rejected_at = count;
            }
        }
    } else if (side == EPROC_SIDE_LOWER) {
        for (size_t i = 0; i < n; ++i) {
            const double x = xs[i];
            if (!isfinite(x)) {
                n_invalid++;
                continue;
            }
            const double x_eff = eproc_clamp(x, lower, upper);
            const double y = eproc_clamp((x_eff - lower) * inv_span, 0.0, 1.0);
            const double d = y - mu0_norm;
            double step = lam_neg * d;
            if (step < -0.999999999999) {
                step = -0.999999999999;
            }
            log_e_neg += log1p(step);
            const double z = d / (1.0 + step);
            a_neg += z * z;
            lam_neg = eproc_clamp(lam_neg + EPROC_ONS_ETA * (z / a_neg), lam_neg_min, 0.0);

            log_e = log_e_neg;
            if (log_e > max_log_e) {
                max_log_e = log_e;
            }
            eproc_kahan_add(&sum_x, &sum_x_comp, x_eff);
            sum_sq += x_eff * x_eff;
            count++;
            if (rejected_at == 0 && max_log_e >= log_thresh) {
                rejected_at = count;
            }
        }
    } else {
        for (size_t i = 0; i < n; ++i) {
            const double x = xs[i];
            if (!isfinite(x)) {
                n_invalid++;
                continue;
            }
            const double x_eff = eproc_clamp(x, lower, upper);
            const double y = eproc_clamp((x_eff - lower) * inv_span, 0.0, 1.0);
            const double d = y - mu0_norm;

            double step_p = lam_pos * d;
            if (step_p < -0.999999999999) {
                step_p = -0.999999999999;
            }
            log_e_pos += log1p(step_p);
            const double zp = d / (1.0 + step_p);
            a_pos += zp * zp;
            lam_pos = eproc_clamp(lam_pos + EPROC_ONS_ETA * (zp / a_pos), 0.0, lam_pos_max);

            double step_n = lam_neg * d;
            if (step_n < -0.999999999999) {
                step_n = -0.999999999999;
            }
            log_e_neg += log1p(step_n);
            const double zn = d / (1.0 + step_n);
            a_neg += zn * zn;
            lam_neg = eproc_clamp(lam_neg + EPROC_ONS_ETA * (zn / a_neg), lam_neg_min, 0.0);

            log_e = eproc_logaddexp(log_e_pos, log_e_neg) - EPROC_LN2;
            if (log_e > max_log_e) {
                max_log_e = log_e;
            }
            eproc_kahan_add(&sum_x, &sum_x_comp, x_eff);
            sum_sq += x_eff * x_eff;
            count++;
            if (rejected_at == 0 && max_log_e >= log_thresh) {
                rejected_at = count;
            }
        }
    }

    ep->lam_pos = lam_pos;
    ep->a_pos = a_pos;
    ep->log_e_pos = log_e_pos;
    ep->lam_neg = lam_neg;
    ep->a_neg = a_neg;
    ep->log_e_neg = log_e_neg;
    ep->log_e = log_e;
    ep->max_log_e = max_log_e;
    ep->sum_x = sum_x;
    ep->sum_x_comp = sum_x_comp;
    ep->sum_sq = sum_sq;
    ep->n = count;
    ep->rejected_at = rejected_at;
    ep->n_invalid = n_invalid;

    if (out != NULL) {
        eproc_bet_query(ep, out);
    }
    return EPROC_OK;
}

double eproc_combine_independent_log(double log_e_a, double log_e_b) {
    if (isnan(log_e_a)) {
        log_e_a = 0.0;
    }
    if (isnan(log_e_b)) {
        log_e_b = 0.0;
    }
    if ((log_e_a == INFINITY && log_e_b == -INFINITY) ||
        (log_e_a == -INFINITY && log_e_b == INFINITY)) {
        return 0.0;
    }
    return log_e_a + log_e_b;
}

double eproc_combine_dependent_log(const double *log_es, size_t k) {
    if (log_es == NULL || k == 0) {
        return 0.0;
    }

    double max_v = -INFINITY;
    int has_finite = 0;
    int has_neg_inf = 0;

    for (size_t i = 0; i < k; ++i) {
        const double v = log_es[i];
        if (isnan(v)) {
            continue;
        }
        if (v == INFINITY) {
            return INFINITY;
        }
        if (v == -INFINITY) {
            has_neg_inf = 1;
            continue;
        }
        if (!has_finite || v > max_v) {
            max_v = v;
            has_finite = 1;
        }
    }

    if (!has_finite) {
        return has_neg_inf ? -INFINITY : 0.0;
    }

    double sum_exp = 0.0;
    double sum_exp_comp = 0.0;
    for (size_t i = 0; i < k; ++i) {
        const double v = log_es[i];
        if (!isfinite(v)) {
            continue;
        }
        const double diff = v - max_v;
        if (diff >= -745.0) {
            eproc_kahan_add(&sum_exp, &sum_exp_comp, exp(diff));
        }
    }

    const double total = eproc_kahan_total(sum_exp, sum_exp_comp);
    if (!(total > 0.0)) {
        return -INFINITY;
    }
    return max_v + log(total) - log((double)k);
}

/* ============================================================================
 * 1B. CONFIDENCE SEQUENCES: EMPIRICAL-BERNSTEIN & NORMAL-MIXTURE
 * ============================================================================ */

static inline double eproc_psi_e(double lam) {
    if (lam < 1e-4) {
        const double l2 = lam * lam;
        return l2 * (0.5 + lam * ((1.0 / 3.0) + lam * (0.25 + lam * (0.2 + lam * (1.0 / 6.0)))));
    }
    return -log1p(-lam) - lam;
}

int eproc_cs_init_eb(eproc_cs_t *cs, double alpha, double lower, double upper) {
    if (cs == NULL) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(alpha) || !(alpha > 0.0 && alpha < 1.0)) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(lower) || !isfinite(upper)) {
        return EPROC_ERR_INVALID;
    }
    double span = upper - lower;
    if (!(span > 0.0) || !isfinite(span)) {
        return EPROC_ERR_INVALID;
    }

    memset(cs, 0, sizeof(*cs));
    cs->lower = lower;
    cs->upper = upper;
    cs->span = span;
    cs->inv_span = 1.0 / span;
    cs->alpha = alpha;
    cs->log_2_over_alpha = log(2.0 / alpha);
    cs->sigma = 0.0;
    cs->rho = 0.0;
    cs->mode = EPROC_CS_EMPIRICAL_BERNSTEIN;
    cs->cs_low = lower;
    cs->cs_high = upper;

    return EPROC_OK;
}

int eproc_cs_init_normal(eproc_cs_t *cs, double alpha, double sigma, double v_opt) {
    if (cs == NULL) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(alpha) || !(alpha > 0.0 && alpha < 1.0)) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(sigma) || !(sigma > 0.0)) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(v_opt) || !(v_opt > 0.0)) {
        return EPROC_ERR_INVALID;
    }

    memset(cs, 0, sizeof(*cs));
    cs->lower = -INFINITY;
    cs->upper = INFINITY;
    cs->span = INFINITY;
    cs->inv_span = 0.0;
    cs->alpha = alpha;
    cs->log_2_over_alpha = log(2.0 / alpha);
    cs->sigma = sigma;

    /* Optimal mixture prior parameter rho for target intrinsic time v_opt (Howard et al. 2021) */
    const double two_log_inv_alpha = -2.0 * log(alpha);
    const double opt_denom = two_log_inv_alpha + log(two_log_inv_alpha + 1.0);
    cs->rho = v_opt / ((opt_denom > 1.0) ? opt_denom : 1.0);
    if (!(cs->rho > 0.0) || !isfinite(cs->rho)) {
        cs->rho = 1.0;
    }

    cs->mode = EPROC_CS_NORMAL_MIXTURE;
    cs->cs_low = -INFINITY;
    cs->cs_high = INFINITY;

    return EPROC_OK;
}

void eproc_cs_query(const eproc_cs_t *cs, eproc_cs_result_t *out) {
    if (cs == NULL || out == NULL) {
        return;
    }
    out->n = cs->n;
    if (cs->n > 0) {
        out->mean = eproc_kahan_total(cs->sum_x, cs->sum_x_comp) / (double)cs->n;
    } else {
        out->mean = 0.0;
    }
    out->low = cs->cs_low;
    out->high = cs->cs_high;
    if (isfinite(cs->cs_low) && isfinite(cs->cs_high)) {
        double w = cs->cs_high - cs->cs_low;
        out->width = (w > 0.0) ? w : 0.0;
    } else {
        out->width = INFINITY;
    }
}

static inline void eproc_cs_step_eb(eproc_cs_t *cs, double x) {
    const double x_eff = eproc_clamp(x, cs->lower, cs->upper);
    const double y = eproc_clamp((x_eff - cs->lower) * cs->inv_span, 0.0, 1.0);

    /* Strictly F_{t-1}-predictable mean, variance, and betting parameter lambda_t */
    const double n_prev = (double)cs->n;
    const double sum_y_prev = eproc_kahan_total(cs->sum_y, cs->sum_y_comp);
    const double mu_hat = (0.5 + sum_y_prev) / (n_prev + 1.0);
    const double var_hat = (0.25 + cs->sum_sq_dev) / (n_prev + 1.0);

    const double denom = var_hat * (n_prev + 1.0) * log(2.0 + n_prev);
    double lam = 0.5;
    if (denom > 0.0) {
        const double raw_lam = sqrt((2.0 * cs->log_2_over_alpha) / denom);
        if (isfinite(raw_lam) && raw_lam < lam) {
            lam = raw_lam;
        }
    }
    if (lam < 0.0) {
        lam = 0.0;
    }

    const double psi_e = eproc_psi_e(lam);
    const double dev = y - mu_hat;
    const double dev_sq = dev * dev;

    /* Update accumulators strictly AFTER using old mu_hat */
    cs->sum_sq_dev += dev_sq;
    cs->sum_lam += lam;
    cs->sum_lam_y += lam * y;
    cs->sum_psi_v += psi_e * dev_sq;
    eproc_kahan_add(&cs->sum_y, &cs->sum_y_comp, y);
    eproc_kahan_add(&cs->sum_x, &cs->sum_x_comp, x_eff);
    cs->n++;

    if (cs->sum_lam > 0.0) {
        const double center = cs->sum_lam_y / cs->sum_lam;
        const double radius = (cs->log_2_over_alpha + cs->sum_psi_v) / cs->sum_lam;
        const double lo_y = eproc_clamp(center - radius, 0.0, 1.0);
        const double hi_y = eproc_clamp(center + radius, 0.0, 1.0);
        const double new_low = cs->lower + cs->span * lo_y;
        const double new_high = cs->lower + cs->span * hi_y;

        if (new_low > cs->cs_low) {
            cs->cs_low = new_low;
        }
        if (new_high < cs->cs_high) {
            cs->cs_high = new_high;
        }
        if (cs->cs_low > cs->cs_high) {
            const double mid = 0.5 * cs->cs_low + 0.5 * cs->cs_high;
            cs->cs_low = mid;
            cs->cs_high = mid;
        }
    }
}

static inline void eproc_cs_step_normal(eproc_cs_t *cs, double x) {
    eproc_kahan_add(&cs->sum_x, &cs->sum_x_comp, x);
    cs->n++;

    const double nd = (double)cs->n;
    const double mean = eproc_kahan_total(cs->sum_x, cs->sum_x_comp) / nd;
    if (!isfinite(mean)) {
        return;
    }
    const double log_inv_alpha = cs->log_2_over_alpha - EPROC_LN2;
    const double rho_plus_n = cs->rho + nd;
    const double inner = rho_plus_n * (2.0 * log_inv_alpha + log(rho_plus_n / cs->rho));
    const double radius = (inner > 0.0) ? (cs->sigma * sqrt(inner) / nd) : 0.0;

    const double new_low = mean - radius;
    const double new_high = mean + radius;
    if (isfinite(new_low) && new_low > cs->cs_low) {
        cs->cs_low = new_low;
    }
    if (isfinite(new_high) && new_high < cs->cs_high) {
        cs->cs_high = new_high;
    }
    if (cs->cs_low > cs->cs_high) {
        const double mid = 0.5 * cs->cs_low + 0.5 * cs->cs_high;
        if (isfinite(mid)) {
            cs->cs_low = mid;
            cs->cs_high = mid;
        }
    }
}

int eproc_cs_update(eproc_cs_t *cs, double x, eproc_cs_result_t *out) {
    if (cs == NULL) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(x)) {
        cs->n_invalid++;
        if (out != NULL) {
            eproc_cs_query(cs, out);
        }
        return EPROC_OK;
    }

    if (cs->mode == EPROC_CS_EMPIRICAL_BERNSTEIN) {
        eproc_cs_step_eb(cs, x);
    } else if (cs->mode == EPROC_CS_NORMAL_MIXTURE) {
        eproc_cs_step_normal(cs, x);
    } else {
        return EPROC_ERR_INVALID;
    }

    if (out != NULL) {
        eproc_cs_query(cs, out);
    }
    return EPROC_OK;
}

int eproc_cs_update_batch(eproc_cs_t *cs,
                          const double *xs,
                          size_t n,
                          eproc_cs_result_t *out) {
    if (cs == NULL || (n > 0 && xs == NULL)) {
        return EPROC_ERR_INVALID;
    }

    if (cs->mode == EPROC_CS_EMPIRICAL_BERNSTEIN) {
        for (size_t i = 0; i < n; ++i) {
            const double x = xs[i];
            if (!isfinite(x)) {
                cs->n_invalid++;
                continue;
            }
            eproc_cs_step_eb(cs, x);
        }
    } else if (cs->mode == EPROC_CS_NORMAL_MIXTURE) {
        for (size_t i = 0; i < n; ++i) {
            const double x = xs[i];
            if (!isfinite(x)) {
                cs->n_invalid++;
                continue;
            }
            eproc_cs_step_normal(cs, x);
        }
    } else {
        return EPROC_ERR_INVALID;
    }

    if (out != NULL) {
        eproc_cs_query(cs, out);
    }
    return EPROC_OK;
}

/* ============================================================================
 * 1C. PAGE-CUSUM RESETTABLE E-DETECTOR
 * ============================================================================ */

static inline void eproc_edetect_reset_inner(eproc_bet_t *inner) {
    inner->lam_pos = 0.0;
    inner->a_pos = 1.0;
    inner->log_e_pos = 0.0;
    inner->lam_neg = 0.0;
    inner->a_neg = 1.0;
    inner->log_e_neg = 0.0;
    inner->log_e = 0.0;
}

int eproc_edetect_init(eproc_edetect_t *ed,
                       double mu0,
                       double alpha,
                       double lower,
                       double upper,
                       int32_t side) {
    if (ed == NULL) {
        return EPROC_ERR_INVALID;
    }
    memset(ed, 0, sizeof(*ed));
    int rc = eproc_bet_init(&ed->inner, mu0, alpha, lower, upper, side);
    if (rc != EPROC_OK) {
        return rc;
    }
    ed->log_cusum = 0.0;
    ed->max_log_cusum = 0.0;
    ed->log_thresh = -log(alpha);
    ed->alarm_at = 0;
    ed->n_alarms = 0;
    ed->n = 0;
    return EPROC_OK;
}

int eproc_edetect_update(eproc_edetect_t *ed, double x, eproc_edetect_result_t *out) {
    if (ed == NULL) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(x)) {
        ed->inner.n_invalid++;
        if (out != NULL) {
            out->n = ed->n;
            out->log_stat = ed->log_cusum;
            out->stat = eproc_safe_exp(ed->log_cusum);
            out->alarm = (ed->log_cusum >= ed->log_thresh) ? 1 : 0;
            out->_pad0 = 0;
        }
        return EPROC_OK;
    }

    const double log_e_before = ed->inner.log_e;
    eproc_bet_update(&ed->inner, x, NULL);
    const double dl = ed->inner.log_e - log_e_before;

    const double base = (ed->log_cusum > 0.0) ? ed->log_cusum : 0.0;
    ed->log_cusum = base + dl;

    /* Page-CUSUM reset: when cumulative log e-statistic drops below 0,
     * restart at 0 and reset inner ONS bettor so post-reset steps form a
     * fresh valid supermartingale increment. */
    if (ed->log_cusum < 0.0) {
        ed->log_cusum = 0.0;
        eproc_edetect_reset_inner(&ed->inner);
    } else if (ed->log_cusum == 0.0 &&
               ed->inner.lam_pos == 0.0 &&
               ed->inner.lam_neg == 0.0) {
        eproc_edetect_reset_inner(&ed->inner);
    }

    ed->n++;
    if (ed->log_cusum > ed->max_log_cusum) {
        ed->max_log_cusum = ed->log_cusum;
    }

    const int32_t alarm = (ed->log_cusum >= ed->log_thresh) ? 1 : 0;
    if (alarm) {
        if (ed->alarm_at == 0) {
            ed->alarm_at = ed->n;
        }
        ed->n_alarms++;
    }

    if (out != NULL) {
        out->n = ed->n;
        out->log_stat = ed->log_cusum;
        out->stat = eproc_safe_exp(ed->log_cusum);
        out->alarm = alarm;
        out->_pad0 = 0;
    }
    return EPROC_OK;
}

void eproc_edetect_reset_alarm(eproc_edetect_t *ed) {
    if (ed == NULL) {
        return;
    }
    ed->log_cusum = 0.0;
    ed->alarm_at = 0;
    eproc_edetect_reset_inner(&ed->inner);
}

/* ============================================================================
 * 1D. ANYTIME-VALID MULTI-ARM RACER (BONFERRONI EB-CS + LUCB1 SAMPLING)
 * ============================================================================ */

int eproc_race_init(eproc_race_t *race,
                    uint32_t n_arms,
                    double alpha,
                    double lower,
                    double upper,
                    double margin) {
    if (race == NULL) {
        return EPROC_ERR_INVALID;
    }
    if (n_arms == 0 || n_arms > EPROC_MAX_ARMS) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(alpha) || !(alpha > 0.0 && alpha < 1.0)) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(lower) || !isfinite(upper) || !(upper > lower) || !isfinite(upper - lower)) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(margin) || margin < 0.0) {
        return EPROC_ERR_INVALID;
    }

    memset(race, 0, sizeof(*race));
    race->n_arms = n_arms;
    race->n_active = n_arms;
    race->alpha = alpha;
    race->lower = lower;
    race->upper = upper;
    race->margin = margin;
    race->winner = (n_arms == 1) ? 0 : -1;
    race->total_obs = 0;

    const double arm_alpha = alpha / (double)n_arms;
    for (uint32_t i = 0; i < n_arms; ++i) {
        race->active[i] = 1;
        race->eliminated_at[i] = 0;
        int rc = eproc_cs_init_eb(&race->arms[i], arm_alpha, lower, upper);
        if (rc != EPROC_OK) {
            return rc;
        }
    }
    return EPROC_OK;
}

static inline void eproc_race_eliminate(eproc_race_t *race) {
    if (race->n_active <= 1) {
        return;
    }
    double max_active_low = -INFINITY;
    for (uint32_t i = 0; i < race->n_arms; ++i) {
        if (race->active[i] && race->arms[i].cs_low > max_active_low) {
            max_active_low = race->arms[i].cs_low;
        }
    }
    const double cutoff = max_active_low - race->margin;
    for (uint32_t j = 0; j < race->n_arms; ++j) {
        if (race->active[j] && race->n_active > 1 && race->arms[j].cs_high < cutoff) {
            race->active[j] = 0;
            race->eliminated_at[j] = race->total_obs;
            race->n_active--;
        }
    }
    if (race->n_active == 1 && race->winner < 0) {
        for (uint32_t k = 0; k < race->n_arms; ++k) {
            if (race->active[k]) {
                race->winner = (int32_t)k;
                break;
            }
        }
    }
}

void eproc_race_status(const eproc_race_t *race, eproc_race_status_t *out) {
    if (race == NULL || out == NULL) {
        return;
    }
    out->n_arms = race->n_arms;
    out->n_active = race->n_active;
    out->winner = race->winner;
    out->total_obs = race->total_obs;

    int32_t leader = 0;
    double best_low = -INFINITY;
    double best_mean = -INFINITY;
    for (uint32_t i = 0; i < race->n_arms; ++i) {
        if (!race->active[i]) {
            continue;
        }
        const double lo = race->arms[i].cs_low;
        const double mean = (race->arms[i].n > 0)
            ? (eproc_kahan_total(race->arms[i].sum_x, race->arms[i].sum_x_comp) / (double)race->arms[i].n)
            : 0.5 * (race->lower + race->upper);
        if (lo > best_low || (lo == best_low && mean > best_mean)) {
            best_low = lo;
            best_mean = mean;
            leader = (int32_t)i;
        }
    }

    double runner_up_high = race->lower;
    int found_other = 0;
    for (uint32_t j = 0; j < race->n_arms; ++j) {
        if ((int32_t)j == leader) {
            continue;
        }
        if (race->n_active > 1 && !race->active[j]) {
            continue;
        }
        if (!found_other || race->arms[j].cs_high > runner_up_high) {
            runner_up_high = race->arms[j].cs_high;
            found_other = 1;
        }
    }

    out->leader = leader;
    out->leader_low = race->arms[leader].cs_low;
    out->leader_high = race->arms[leader].cs_high;
    out->runner_up_high = runner_up_high;
}

int eproc_race_update(eproc_race_t *race,
                      uint32_t arm,
                      double reward,
                      eproc_race_status_t *out) {
    if (race == NULL || arm >= race->n_arms) {
        return EPROC_ERR_INVALID;
    }
    eproc_cs_update(&race->arms[arm], reward, NULL);
    if (isfinite(reward)) {
        race->total_obs++;
        eproc_race_eliminate(race);
    }
    if (out != NULL) {
        eproc_race_status(race, out);
    }
    return EPROC_OK;
}

int eproc_race_update_batch(eproc_race_t *race,
                            const uint32_t *arms,
                            const double *rewards,
                            size_t n,
                            eproc_race_status_t *out) {
    if (race == NULL || (n > 0 && (arms == NULL || rewards == NULL))) {
        return EPROC_ERR_INVALID;
    }
    for (size_t i = 0; i < n; ++i) {
        const uint32_t arm = arms[i];
        if (arm >= race->n_arms) {
            return EPROC_ERR_INVALID;
        }
        const double r = rewards[i];
        eproc_cs_update(&race->arms[arm], r, NULL);
        if (isfinite(r)) {
            race->total_obs++;
            eproc_race_eliminate(race);
        }
    }
    if (out != NULL) {
        eproc_race_status(race, out);
    }
    return EPROC_OK;
}

int eproc_race_arm_state(const eproc_race_t *race,
                         uint32_t arm,
                         eproc_cs_result_t *out,
                         int32_t *is_active) {
    if (race == NULL || arm >= race->n_arms) {
        return EPROC_ERR_INVALID;
    }
    if (out != NULL) {
        eproc_cs_query(&race->arms[arm], out);
    }
    if (is_active != NULL) {
        *is_active = (int32_t)race->active[arm];
    }
    return EPROC_OK;
}

int32_t eproc_race_suggest_arm(const eproc_race_t *race) {
    if (race == NULL || race->n_arms == 0) {
        return -1;
    }
    if (race->winner >= 0) {
        return race->winner;
    }

    /* Warm-start any unsampled active arm first */
    for (uint32_t i = 0; i < race->n_arms; ++i) {
        if (race->active[i] && race->arms[i].n == 0) {
            return (int32_t)i;
        }
    }

    /* LUCB1 active scheduler: identify empirical leader h_t and highest-UCB challenger l_t */
    int32_t leader = -1;
    double best_mean = -INFINITY;
    double best_low = -INFINITY;
    for (uint32_t i = 0; i < race->n_arms; ++i) {
        if (!race->active[i]) {
            continue;
        }
        const double mean = eproc_kahan_total(race->arms[i].sum_x, race->arms[i].sum_x_comp)
                            / (double)race->arms[i].n;
        const double lo = race->arms[i].cs_low;
        if (leader < 0 || mean > best_mean || (mean == best_mean && lo > best_low)) {
            leader = (int32_t)i;
            best_mean = mean;
            best_low = lo;
        }
    }

    if (leader < 0) {
        return 0;
    }

    int32_t challenger = -1;
    double best_challenger_high = -INFINITY;
    uint64_t best_challenger_n = UINT64_MAX;
    for (uint32_t j = 0; j < race->n_arms; ++j) {
        if (!race->active[j] || (int32_t)j == leader) {
            continue;
        }
        const double hi = race->arms[j].cs_high;
        if (challenger < 0 || hi > best_challenger_high ||
            (hi == best_challenger_high && race->arms[j].n < best_challenger_n)) {
            challenger = (int32_t)j;
            best_challenger_high = hi;
            best_challenger_n = race->arms[j].n;
        }
    }

    if (challenger < 0) {
        return leader;
    }

    /* Sample whichever of {leader, challenger} has wider confidence interval
     * (alternating on ties so leader LCB and challenger UCB tighten in lockstep) */
    const double w_leader = race->arms[leader].cs_high - race->arms[leader].cs_low;
    const double w_chall = race->arms[challenger].cs_high - race->arms[challenger].cs_low;
    if (w_leader > w_chall) {
        return leader;
    }
    if (w_chall > w_leader) {
        return challenger;
    }
    return (race->arms[leader].n <= race->arms[challenger].n) ? leader : challenger;
}



/* ==================== eproc_conformal.c ==================== */

#if !defined(__GNUC__) || defined(__clang__)
#pragma STDC FP_CONTRACT OFF
#endif


#include <math.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>

EPROC_STATIC_ASSERT(sizeof(eproc_cmonoid_t) == 640, "eproc_cmonoid_t must be exactly 640 bytes");

/* ============================================================================
 * 2A. MULTI-RATE CROSSING-FREE AgACI + CONFORMAL PID CALIBRATOR
 * ============================================================================ */

#if defined(__GNUC__) || defined(__clang__)
#define EPROC_ALWAYS_INLINE static inline __attribute__((always_inline))
#else
#define EPROC_ALWAYS_INLINE static inline
#endif

EPROC_ALWAYS_INLINE double eproc_sorted_quantile(const double *sorted, uint32_t len, double alpha) {
    if (len == 0U) {
        return 0.0;
    }
    if (!isfinite(alpha) || alpha <= 0.0) {
        return sorted[len - 1U];
    }
    if (alpha >= 1.0) {
        return sorted[0];
    }
    const double pos = (1.0 - alpha) * (double)(len + 1U);
    if (!isfinite(pos) || pos >= (double)len) {
        return sorted[len - 1U];
    }
    if (pos <= 1.0) {
        return sorted[0];
    }
    /* Exact ceil(pos) - 1 without calling libm ceil() and safe against float-cast-overflow */
    const uint32_t ipos = (uint32_t)pos;
    uint32_t idx = (pos > (double)ipos) ? ipos : (ipos - 1U);
    if (idx >= len) {
        idx = len - 1U;
    }
    return sorted[idx];
}

/* 4-wide bit-exact 1/sqrt(x) for x >= 1.0 using 64-bit IEEE magic + 2 Newton-Raphson steps
 * (error < 1e-7, ZERO vdivpd, ZERO vsqrtpd, 0-ULP AVX2/scalar identical). */
#if EPROC_BUILD_AVX2
EPROC_AVX2_INLINE __m256d eproc_rsqrt4_avx2(__m256d vx) {
    const __m256d half_x = _mm256_mul_pd(_mm256_set1_pd(0.5), vx);
    const __m256d three_half = _mm256_set1_pd(1.5);
    const __m256i magic = _mm256_set1_epi64x(0x5fe6eb50c7b537a9LL);
    __m256i ix = _mm256_castpd_si256(vx);
    ix = _mm256_sub_epi64(magic, _mm256_srli_epi64(ix, 1));
    __m256d y = _mm256_castsi256_pd(ix);
    y = _mm256_mul_pd(y, _mm256_sub_pd(three_half, _mm256_mul_pd(half_x, _mm256_mul_pd(y, y))));
    y = _mm256_mul_pd(y, _mm256_sub_pd(three_half, _mm256_mul_pd(half_x, _mm256_mul_pd(y, y))));
    return y;
}

/* 4-wide bit-exact exp(x) for pre-clamped x in [-50.0, 0.0] (degree-5 Estrin, 0-ULP identical) */
EPROC_AVX2_INLINE __m256d eproc_exp4_neg50_clamped_avx2(__m256d vx) {
    static const double INV_LN2 = 1.44269504088896340736;
    static const double LN2_VAL = 0.69314718055994530942;
    static const double C5      = 1.0 / 120.0;
    static const double C4      = 1.0 / 24.0;
    static const double C3      = 1.0 / 6.0;
    static const double C2      = 0.5;

    const __m256d kf = _mm256_floor_pd(
        _mm256_add_pd(_mm256_mul_pd(vx, _mm256_set1_pd(INV_LN2)), _mm256_set1_pd(0.5)));
    const __m256d r = _mm256_sub_pd(vx, _mm256_mul_pd(kf, _mm256_set1_pd(LN2_VAL)));

    const __m256d r2 = _mm256_mul_pd(r, r);
    const __m256d r4 = _mm256_mul_pd(r2, r2);

    const __m256d q0 = _mm256_add_pd(_mm256_set1_pd(1.0), r);
    const __m256d q1 = _mm256_add_pd(_mm256_set1_pd(C2), _mm256_mul_pd(_mm256_set1_pd(C3), r));
    const __m256d q2 = _mm256_add_pd(_mm256_set1_pd(C4), _mm256_mul_pd(_mm256_set1_pd(C5), r));

    const __m256d poly = _mm256_add_pd(_mm256_add_pd(q0, _mm256_mul_pd(q1, r2)),
                                       _mm256_mul_pd(q2, r4));

    const __m128i ki32 = _mm256_cvttpd_epi32(kf);
    const __m256i ki64 = _mm256_cvtepi32_epi64(ki32);
    const __m256i exp_bits = _mm256_slli_epi64(
        _mm256_add_epi64(ki64, _mm256_set1_epi64x(1023LL)), 52);
    return _mm256_mul_pd(poly, _mm256_castsi256_pd(exp_bits));
}

EPROC_AVX2_INLINE __m256d eproc_exp4_neg50_avx2(__m256d vx) {
    vx = _mm256_max_pd(vx, _mm256_set1_pd(-50.0));
    vx = _mm256_min_pd(vx, _mm256_setzero_pd());
    return eproc_exp4_neg50_clamped_avx2(vx);
}

EPROC_AVX2_INLINE double eproc_hsum4_avx2(__m256d v) {
    /* Deterministic pairwise sum: (v[0] + v[1]) + (v[2] + v[3]) matching scalar */
    const __m128d lo = _mm256_castpd256_pd128(v);
    const __m128d hi = _mm256_extractf128_pd(v, 1);
    const __m128d s_lo = _mm_add_sd(lo, _mm_unpackhi_pd(lo, lo));
    const __m128d s_hi = _mm_add_sd(hi, _mm_unpackhi_pd(hi, hi));
    return _mm_cvtsd_f64(_mm_add_sd(s_lo, s_hi));
}

/* Fast L1 scalar-indexed 4-expert sorted quantile load for pre-clamped alpha in [0, 1]. */
EPROC_AVX2_INLINE __m256d eproc_sorted_quantile4_avx2(const double *sorted,
                                                      __m256d v_len_p1,
                                                      __m256d v_len_m1,
                                                      __m256d valpha) {
    const __m256d v_zero = _mm256_setzero_pd();
    const __m256d v_one = _mm256_set1_pd(1.0);
    const __m256d vpos = _mm256_mul_pd(_mm256_sub_pd(v_one, valpha), v_len_p1);
    const __m256d vc = _mm256_sub_pd(_mm256_ceil_pd(vpos), v_one);
    const __m256d vclamped = _mm256_min_pd(_mm256_max_pd(vc, v_zero), v_len_m1);
    const __m128i vidx = _mm256_cvttpd_epi32(vclamped);
    const uint64_t lo2 = (uint64_t)_mm_cvtsi128_si64(vidx);
    const uint64_t hi2 = (uint64_t)_mm_extract_epi64(vidx, 1);
    const uint32_t i0 = (uint32_t)(lo2 & 0xFFFFFFFFULL);
    const uint32_t i1 = (uint32_t)(lo2 >> 32);
    const uint32_t i2 = (uint32_t)(hi2 & 0xFFFFFFFFULL);
    const uint32_t i3 = (uint32_t)(hi2 >> 32);
    return _mm256_set_pd(sorted[i3], sorted[i2], sorted[i1], sorted[i0]);
}
#endif

EPROC_ALWAYS_INLINE double eproc_rsqrt_scalar(double x) {
    const double half_x = 0.5 * x;
    uint64_t u = eproc_f64_to_u64(x);
    u = 0x5fe6eb50c7b537a9ULL - (u >> 1);
    double y = eproc_u64_to_f64(u);
    y = y * (1.5 - half_x * (y * y));
    y = y * (1.5 - half_x * (y * y));
    return y;
}

EPROC_ALWAYS_INLINE double eproc_exp_neg50_scalar(double x) {
    static const double INV_LN2 = 1.44269504088896340736;
    static const double LN2_VAL = 0.69314718055994530942;
    static const double C5      = 1.0 / 120.0;
    static const double C4      = 1.0 / 24.0;
    static const double C3      = 1.0 / 6.0;
    static const double C2      = 0.5;

    x = eproc_clamp(x, -50.0, 0.0);
    const double kf = floor(x * INV_LN2 + 0.5);
    const double r = x - kf * LN2_VAL;
    const double r2 = r * r;
    const double r4 = r2 * r2;
    const double q0 = 1.0 + r;
    const double q1 = C2 + C3 * r;
    const double q2 = C4 + C5 * r;
    const double poly = (q0 + q1 * r2) + q2 * r4;
    const int64_t ki = (int64_t)kf;
    const uint64_t exp_bits = (uint64_t)(ki + 1023LL) << 52;
    return poly * eproc_u64_to_f64(exp_bits);
}

/* Fast bit-exact tanh(z) for z in [-10.0, +10.0] using exp_neg50(-2|z|) */
EPROC_ALWAYS_INLINE double eproc_tanh_fast_scalar(double z) {
    const double az = fabs(z);
    if (az >= 20.0) {
        return (z >= 0.0) ? 1.0 : -1.0;
    }
    const double e = eproc_exp_neg50_scalar(-2.0 * az);
    const double mag = (1.0 - e) / (1.0 + e);
    return (z >= 0.0) ? mag : -mag;
}

#if EPROC_BUILD_AVX2
EPROC_AVX2_INLINE void eproc_tanh_rates_avx2(const double *z, double *out, uint32_t n) {
    if (n >= 4U) {
        const __m256d vz = _mm256_loadu_pd(z);
        const __m256d sign_mask = _mm256_set1_pd(-0.0);
        const __m256d vaz = _mm256_andnot_pd(sign_mask, vz);
        const __m256d ve = eproc_exp4_neg50_avx2(_mm256_mul_pd(_mm256_set1_pd(-2.0), vaz));
        const __m256d one = _mm256_set1_pd(1.0);
        const __m256d vmag = _mm256_div_pd(_mm256_sub_pd(one, ve), _mm256_add_pd(one, ve));
        const __m256d vres = _mm256_or_pd(vmag, _mm256_and_pd(vz, sign_mask));
        _mm256_storeu_pd(out, vres);
        for (uint32_t i = 4U; i < n; ++i) {
            out[i] = eproc_tanh_fast_scalar(z[i]);
        }
        return;
    }
    for (uint32_t i = 0; i < n; ++i) {
        out[i] = eproc_tanh_fast_scalar(z[i]);
    }
}
#endif

#if !EPROC_STATIC_AVX2
EPROC_ALWAYS_INLINE void eproc_tanh_rates_scalar(const double *z, double *out, uint32_t n) {
    for (uint32_t i = 0; i < n; ++i) {
        out[i] = eproc_tanh_fast_scalar(z[i]);
    }
}
#endif

/* Exact overflow-safe L2-optimal PAVA isotonic projection for non-decreasing q[0..n-1] */
EPROC_ALWAYS_INLINE void eproc_pava_nondecreasing(double *q, uint32_t n) {
    if (n <= 1U) {
        return;
    }
    int ordered = 1;
    for (uint32_t i = 1U; i < n; ++i) {
        if (q[i] < q[i - 1U]) {
            ordered = 0;
            break;
        }
    }
    if (ordered) {
        return;
    }

    double blk_val[EPROC_MAX_RATES];
    uint32_t blk_cnt[EPROC_MAX_RATES];
    uint32_t nb = 0;

    for (uint32_t i = 0; i < n; ++i) {
        blk_val[nb] = q[i];
        blk_cnt[nb] = 1U;
        nb++;
        while (nb >= 2U && blk_val[nb - 2U] > blk_val[nb - 1U]) {
            const uint32_t c_tot = blk_cnt[nb - 2U] + blk_cnt[nb - 1U];
            const double w2 = (double)blk_cnt[nb - 1U] / (double)c_tot;
            const double w1 = 1.0 - w2;
            blk_val[nb - 2U] = blk_val[nb - 2U] * w1 + blk_val[nb - 1U] * w2;
            blk_cnt[nb - 2U] = c_tot;
            nb--;
        }
    }

    uint32_t pos = 0;
    for (uint32_t b = 0; b < nb; ++b) {
        for (uint32_t c = 0; c < blk_cnt[b]; ++c) {
            q[pos++] = blk_val[b];
        }
    }
    for (uint32_t i = 1; i < n; ++i) {
        if (q[i] < q[i - 1]) {
            q[i] = q[i - 1];
        }
    }
}

/* Branchless lower-bound binary search in sorted[0..len-1] (0 branch mispredictions) */
EPROC_ALWAYS_INLINE uint32_t eproc_lower_bound(const double *sorted, uint32_t len, double val) {
    uint32_t base = 0U;
    uint32_t n = len;
    while (n > 1U) {
        const uint32_t half = n >> 1;
        base += (sorted[base + half] < val) ? half : 0U;
        n -= half;
    }
    base += (n > 0U && sorted[base] < val) ? 1U : 0U;
    return base;
}

/* Inline 8-double AVX2 shift helpers (prevents GCC memmove@plt + vzeroupper substitution) */
#if EPROC_BUILD_AVX2
EPROC_AVX2_INLINE void eproc_shift_right1_avx2(double *arr, uint32_t start, uint32_t count) {
    uint32_t rem = count;
    while (rem >= 8U) {
        rem -= 8U;
        __m256d vhi = _mm256_loadu_pd(arr + start + rem + 4U);
        __m256d vlo = _mm256_loadu_pd(arr + start + rem);
        _mm256_storeu_pd(arr + start + rem + 5U, vhi);
        _mm256_storeu_pd(arr + start + rem + 1U, vlo);
    }
    if (rem >= 4U) {
        rem -= 4U;
        __m256d v = _mm256_loadu_pd(arr + start + rem);
        _mm256_storeu_pd(arr + start + rem + 1U, v);
    }
    if (rem == 3U) {
        arr[start + 3U] = arr[start + 2U];
        arr[start + 2U] = arr[start + 1U];
        arr[start + 1U] = arr[start];
    } else if (rem == 2U) {
        arr[start + 2U] = arr[start + 1U];
        arr[start + 1U] = arr[start];
    } else if (rem == 1U) {
        arr[start + 1U] = arr[start];
    }
}

EPROC_AVX2_INLINE void eproc_shift_left1_avx2(double *arr, uint32_t dst_start, uint32_t count) {
    uint32_t i = 0U;
    for (; i + 8U <= count; i += 8U) {
        __m256d vlo = _mm256_loadu_pd(arr + dst_start + i + 1U);
        __m256d vhi = _mm256_loadu_pd(arr + dst_start + i + 5U);
        _mm256_storeu_pd(arr + dst_start + i, vlo);
        _mm256_storeu_pd(arr + dst_start + i + 4U, vhi);
    }
    if (i + 4U <= count) {
        __m256d v = _mm256_loadu_pd(arr + dst_start + i + 1U);
        _mm256_storeu_pd(arr + dst_start + i, v);
        i += 4U;
    }
    const uint32_t rem = count - i;
    if (rem == 3U) {
        arr[dst_start + i]      = arr[dst_start + i + 1U];
        arr[dst_start + i + 1U] = arr[dst_start + i + 2U];
        arr[dst_start + i + 2U] = arr[dst_start + i + 3U];
    } else if (rem == 2U) {
        arr[dst_start + i]      = arr[dst_start + i + 1U];
        arr[dst_start + i + 1U] = arr[dst_start + i + 2U];
    } else if (rem == 1U) {
        arr[dst_start + i]      = arr[dst_start + i + 1U];
    }
}

/* Single-pass O(W/3) L1-resident sorted ring maintenance with interleaved dual binary search */
EPROC_AVX2_INLINE void eproc_conformal_push_score_avx2(eproc_conformal_t *cp, double score) {
    if (cp->win_len == cp->win_cap) {
        const double old_val = cp->ring[cp->ring_pos];
        cp->ring[cp->ring_pos] = score;
        cp->ring_pos++;
        if (cp->ring_pos >= cp->win_cap) {
            cp->ring_pos = 0U;
        }
        if (old_val == score) {
            return;
        }
        const uint32_t len = cp->win_len;
        uint32_t rm_idx = 0U;
        uint32_t ins_idx = 0U;
        uint32_t n = len;
        while (n > 1U) {
            const uint32_t half = n >> 1;
            rm_idx  += (cp->sorted[rm_idx  + half] < old_val) ? half : 0U;
            ins_idx += (cp->sorted[ins_idx + half] < score)   ? half : 0U;
            n -= half;
        }
        rm_idx  += (cp->sorted[rm_idx]  < old_val) ? 1U : 0U;
        ins_idx += (cp->sorted[ins_idx] < score)   ? 1U : 0U;
        if (rm_idx >= len) {
            rm_idx = len - 1U;
        }
        if (ins_idx <= rm_idx) {
            eproc_shift_right1_avx2(cp->sorted, ins_idx, rm_idx - ins_idx);
            cp->sorted[ins_idx] = score;
        } else {
            const uint32_t dst = ins_idx - 1U;
            eproc_shift_left1_avx2(cp->sorted, rm_idx, dst - rm_idx);
            cp->sorted[dst] = score;
        }
        return;
    }

    cp->ring[cp->ring_pos] = score;
    cp->ring_pos++;
    if (cp->ring_pos >= cp->win_cap) {
        cp->ring_pos = 0U;
    }

    const uint32_t ins_idx = eproc_lower_bound(cp->sorted, cp->win_len, score);
    eproc_shift_right1_avx2(cp->sorted, ins_idx, cp->win_len - ins_idx);
    cp->sorted[ins_idx] = score;
    cp->win_len++;
}
#endif

#if !EPROC_STATIC_AVX2
EPROC_ALWAYS_INLINE void eproc_conformal_push_score_scalar(eproc_conformal_t *cp, double score) {
    if (cp->win_len == cp->win_cap) {
        const double old_val = cp->ring[cp->ring_pos];
        cp->ring[cp->ring_pos] = score;
        cp->ring_pos++;
        if (cp->ring_pos >= cp->win_cap) {
            cp->ring_pos = 0U;
        }
        if (old_val == score) {
            return;
        }
        const uint32_t len = cp->win_len;
        uint32_t rm_idx = 0U;
        uint32_t ins_idx = 0U;
        uint32_t n = len;
        while (n > 1U) {
            const uint32_t half = n >> 1;
            rm_idx  += (cp->sorted[rm_idx  + half] < old_val) ? half : 0U;
            ins_idx += (cp->sorted[ins_idx + half] < score)   ? half : 0U;
            n -= half;
        }
        rm_idx  += (cp->sorted[rm_idx]  < old_val) ? 1U : 0U;
        ins_idx += (cp->sorted[ins_idx] < score)   ? 1U : 0U;
        if (rm_idx >= len) {
            rm_idx = len - 1U;
        }
        if (ins_idx <= rm_idx) {
            const uint32_t cnt = rm_idx - ins_idx;
            if (cnt > 0U) {
                memmove(&cp->sorted[ins_idx + 1U], &cp->sorted[ins_idx], cnt * sizeof(double));
            }
            cp->sorted[ins_idx] = score;
        } else {
            const uint32_t dst = ins_idx - 1U;
            const uint32_t cnt = dst - rm_idx;
            if (cnt > 0U) {
                memmove(&cp->sorted[rm_idx], &cp->sorted[rm_idx + 1U], cnt * sizeof(double));
            }
            cp->sorted[dst] = score;
        }
        return;
    }

    cp->ring[cp->ring_pos] = score;
    cp->ring_pos++;
    if (cp->ring_pos >= cp->win_cap) {
        cp->ring_pos = 0U;
    }

    const uint32_t ins_idx = eproc_lower_bound(cp->sorted, cp->win_len, score);
    const uint32_t cnt = cp->win_len - ins_idx;
    if (cnt > 0U) {
        memmove(&cp->sorted[ins_idx + 1U], &cp->sorted[ins_idx], cnt * sizeof(double));
    }
    cp->sorted[ins_idx] = score;
    cp->win_len++;
}
#endif

static inline void eproc_conformal_fill_meta(const eproc_conformal_t *cp,
                                             eproc_conformal_out_t *meta_out) {
    if (meta_out == NULL) {
        return;
    }
    memset(meta_out, 0, sizeof(*meta_out));
    meta_out->n_rates = cp->n_rates;
    for (uint32_t r = 0; r < cp->n_rates; ++r) {
        meta_out->quantiles[r] = cp->current_q[r];
        meta_out->eff_alphas[r] = cp->eff_alpha[r];
        if (cp->n_updates > 0) {
            meta_out->emp_coverage[r] = (double)cp->hit_counts[r] / (double)cp->n_updates;
        } else {
            meta_out->emp_coverage[r] = 1.0 - cp->target_alphas[r];
        }
    }
}

int eproc_conformal_init(eproc_conformal_t *cp,
                         const double *alphas,
                         uint32_t n_rates,
                         uint32_t window_size,
                         double pid_ki) {
    if (cp == NULL || alphas == NULL) {
        return EPROC_ERR_INVALID;
    }
    if (n_rates == 0 || n_rates > EPROC_MAX_RATES) {
        return EPROC_ERR_INVALID;
    }
    if (window_size == 0 || window_size > EPROC_CONFORMAL_MAX_WIN) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(pid_ki) || pid_ki < 0.0) {
        return EPROC_ERR_INVALID;
    }
    for (uint32_t r = 0; r < n_rates; ++r) {
        if (!isfinite(alphas[r]) || !(alphas[r] > 0.0 && alphas[r] < 1.0)) {
            return EPROC_ERR_INVALID;
        }
    }

    memset(cp, 0, sizeof(*cp));
    cp->n_rates = n_rates;
    cp->win_cap = window_size;
    cp->win_len = 0;
    cp->ring_pos = 0;
    cp->pid_ki = pid_ki;
    cp->pid_csat = 10.0;
    cp->n_updates = 0;

    /* Copy and sort target_alphas descending (ascending coverage 1 - alpha) */
    for (uint32_t r = 0; r < n_rates; ++r) {
        cp->target_alphas[r] = alphas[r];
    }
    for (uint32_t i = 0; i < n_rates; ++i) {
        for (uint32_t j = i + 1U; j < n_rates; ++j) {
            if (cp->target_alphas[j] > cp->target_alphas[i]) {
                double tmp = cp->target_alphas[i];
                cp->target_alphas[i] = cp->target_alphas[j];
                cp->target_alphas[j] = tmp;
            }
        }
    }

    cp->gammas[0] = 0.005;
    cp->gammas[1] = 0.02;
    cp->gammas[2] = 0.08;
    cp->gammas[3] = 0.20;

    for (uint32_t r = 0; r < n_rates; ++r) {
        cp->eff_alpha[r] = cp->target_alphas[r];
        cp->current_q[r] = 0.0;
        cp->emp_cov_ema[r] = 1.0 - cp->target_alphas[r];
        cp->pid_err_sum[r] = 0.0;
        cp->hit_counts[r] = 0;
        for (uint32_t k = 0; k < EPROC_AGACI_EXPERTS; ++k) {
            cp->alpha_t[r][k] = cp->target_alphas[r];
            cp->exp_log_w[r][k] = 0.0;
            cp->exp_var[r][k] = 0.0;
        }
    }

    return EPROC_OK;
}

void eproc_conformal_predict(const eproc_conformal_t *cp,
                             double point_pred,
                             double scale,
                             double *lows_out,
                             double *highs_out,
                             eproc_conformal_out_t *meta_out) {
    if (cp == NULL) {
        return;
    }
    const double pred = isfinite(point_pred) ? point_pred : 0.0;
    const double sc = (isfinite(scale) && scale > 0.0) ? scale : 1.0;

    for (uint32_t r = 0; r < cp->n_rates; ++r) {
        const double rad = cp->current_q[r] * sc;
        const double lo = pred - rad;
        const double hi = pred + rad;
        if (lows_out != NULL) {
            lows_out[r] = isfinite(lo) ? lo : pred;
        }
        if (highs_out != NULL) {
            highs_out[r] = isfinite(hi) ? hi : pred;
        }
    }
    eproc_conformal_fill_meta(cp, meta_out);
}

/* Compute exact normalized weights from exp_log_w using the SAME exp4_neg50
 * kernel as the inner step -> guarantees 0.0-ULP scalar vs batch identity! */
#if EPROC_BUILD_AVX2
EPROC_AVX2_INLINE void eproc_conformal_load_weights_avx2(
    const eproc_conformal_t *cp,
    double w_cache[EPROC_MAX_RATES][EPROC_AGACI_EXPERTS]) {
    for (uint32_t r = 0; r < cp->n_rates; ++r) {
        const __m256d vlw = _mm256_loadu_pd(cp->exp_log_w[r]);
        const __m256d vw = eproc_exp4_neg50_avx2(vlw);
        const double w_sum = eproc_hsum4_avx2(vw);
        const __m256d vnorm = (w_sum > 0.0)
            ? _mm256_mul_pd(vw, _mm256_set1_pd(1.0 / w_sum))
            : _mm256_set1_pd(0.25);
        _mm256_storeu_pd(w_cache[r], vnorm);
    }
}

/* 3-pass ROB-overlapping, zero-spill AVX2 4-expert AgACI BOA + PID step */
EPROC_AVX2_INLINE void eproc_conformal_step_cached_avx2(
    eproc_conformal_t *cp,
    double score,
    double w_cache[EPROC_MAX_RATES][EPROC_AGACI_EXPERTS],
    double inv_csat,
    double max_pid_sum,
    uint32_t n_rates) {
    static const double SQRT_LOG4 = 1.17741002251547469101;
    const uint32_t prev_len = cp->win_len;

    const double ema_beta = (cp->n_updates < 50ULL)
        ? (1.0 / (double)(cp->n_updates + 1ULL))
        : 0.02;

    if (prev_len == 0U) {
        for (uint32_t r = 0; r < n_rates; ++r) {
            cp->emp_cov_ema[r] = (1.0 - ema_beta) * cp->emp_cov_ema[r];
            cp->eff_alpha[r] = cp->target_alphas[r];
        }
        eproc_conformal_push_score_avx2(cp, score);
        cp->n_updates++;
        for (uint32_t r = 0; r < n_rates; ++r) {
            cp->current_q[r] = score;
        }
        return;
    }

    /* Overflow-safe F_{t-1}-predictable half-range (guaranteed finite for all finite doubles!) */
    double half_scale;
    if (prev_len >= 2U) {
        const double half_rng = 0.5 * cp->sorted[prev_len - 1U] - 0.5 * cp->sorted[0];
        half_scale = (half_rng > 0.5e-6) ? half_rng : 0.5e-6;
    } else {
        const double half_ab = 0.5 * fabs(score);
        half_scale = (half_ab > 0.5) ? half_ab : 0.5;
    }
    const double inv_half_scale = 1.0 / half_scale;
    const double half_score = 0.5 * score;

    double a_agg_arr[EPROC_MAX_RATES] = {0.0};
    double pid_z[EPROC_MAX_RATES] = {0.0};
    double w_sum_arr[EPROC_MAX_RATES] = {1.0, 1.0, 1.0, 1.0, 1.0};
    double wa_sum_arr[EPROC_MAX_RATES] = {0.0};
    const double pid_ki = cp->pid_ki;

    double reg_buf[EPROC_MAX_RATES][4];
    double reg2_buf[EPROC_MAX_RATES][4];

    /* Vectorized per-rate coverage, EMA, and PID integral across rates 0..3 (+ rate 4) */
    {
        const __m256d v_one = _mm256_set1_pd(1.0);
        const __m256d v_score = _mm256_set1_pd(score);
        if (n_rates >= 4U) {
            const __m256d v_cq = _mm256_loadu_pd(cp->current_q);
            const __m256d v_ta = _mm256_loadu_pd(cp->target_alphas);
            const __m256d v_hit = _mm256_cmp_pd(v_score, v_cq, _CMP_LE_OQ);
            const __m256d v_cov = _mm256_and_pd(v_hit, v_one);
            const __m256d v_err = _mm256_andnot_pd(v_hit, v_one);
            const int hmask = _mm256_movemask_pd(v_hit);
            cp->hit_counts[0] += (uint64_t)((hmask >> 0) & 1);
            cp->hit_counts[1] += (uint64_t)((hmask >> 1) & 1);
            cp->hit_counts[2] += (uint64_t)((hmask >> 2) & 1);
            cp->hit_counts[3] += (uint64_t)((hmask >> 3) & 1);

            const __m256d v_ema = _mm256_add_pd(
                _mm256_mul_pd(_mm256_set1_pd(1.0 - ema_beta), _mm256_loadu_pd(cp->emp_cov_ema)),
                _mm256_mul_pd(_mm256_set1_pd(ema_beta), v_cov));
            _mm256_storeu_pd(cp->emp_cov_ema, v_ema);

            __m256d v_pid = _mm256_add_pd(_mm256_loadu_pd(cp->pid_err_sum),
                                          _mm256_sub_pd(v_err, v_ta));
            v_pid = _mm256_min_pd(_mm256_max_pd(v_pid, _mm256_set1_pd(-max_pid_sum)),
                                  _mm256_set1_pd(max_pid_sum));
            _mm256_storeu_pd(cp->pid_err_sum, v_pid);
            _mm256_storeu_pd(pid_z, _mm256_mul_pd(v_pid, _mm256_set1_pd(inv_csat)));

            for (uint32_t r = 4U; r < n_rates; ++r) {
                const double target_a = cp->target_alphas[r];
                const int covered = (score <= cp->current_q[r]);
                const double err = (double)(1 - covered);
                cp->hit_counts[r] += (uint64_t)covered;
                cp->emp_cov_ema[r] = (1.0 - ema_beta) * cp->emp_cov_ema[r] + ema_beta * (double)covered;
                cp->pid_err_sum[r] = eproc_clamp(
                    cp->pid_err_sum[r] + (err - target_a), -max_pid_sum, max_pid_sum);
                pid_z[r] = cp->pid_err_sum[r] * inv_csat;
            }
        } else {
            for (uint32_t r = 0; r < n_rates; ++r) {
                const double target_a = cp->target_alphas[r];
                const int covered = (score <= cp->current_q[r]);
                const double err = (double)(1 - covered);
                cp->hit_counts[r] += (uint64_t)covered;
                cp->emp_cov_ema[r] = (1.0 - ema_beta) * cp->emp_cov_ema[r] + ema_beta * (double)covered;
                cp->pid_err_sum[r] = eproc_clamp(
                    cp->pid_err_sum[r] + (err - target_a), -max_pid_sum, max_pid_sum);
                pid_z[r] = cp->pid_err_sum[r] * inv_csat;
            }
        }
    }

    /* Micro-pass 1: Quantile load, pinball regret, variance, ACI alpha_t */
    {
        const __m256d v_gam = _mm256_loadu_pd(cp->gammas);
        const __m256d v_half = _mm256_set1_pd(0.5);
        const __m256d v_one = _mm256_set1_pd(1.0);
        const __m256d v_neg1 = _mm256_set1_pd(-1.0);
        const __m256d v_zero = _mm256_setzero_pd();
        const __m256d v_lim100 = _mm256_set1_pd(1e100);
        const __m256d v_nlim100 = _mm256_set1_pd(-1e100);
        const __m256d v_score = _mm256_set1_pd(score);
        const __m256d v_hscore = _mm256_set1_pd(half_score);
        const __m256d v_ihs = _mm256_set1_pd(inv_half_scale);
        const __m256d v_len_p1 = _mm256_set1_pd((double)(prev_len + 1U));
        const __m256d v_len_m1 = _mm256_set1_pd((double)(prev_len - 1U));

        for (uint32_t r = 0; r < n_rates; ++r) {
            const double target_a = cp->target_alphas[r];
            const double tau = 1.0 - target_a;
            const __m256d valpha = _mm256_loadu_pd(cp->alpha_t[r]);
            const __m256d vq = eproc_sorted_quantile4_avx2(cp->sorted, v_len_p1, v_len_m1, valpha);
            const __m256d vwr = _mm256_loadu_pd(w_cache[r]);

            __m256d vsd = _mm256_mul_pd(_mm256_sub_pd(v_hscore, _mm256_mul_pd(v_half, vq)), v_ihs);
            vsd = _mm256_min_pd(_mm256_max_pd(vsd, v_nlim100), v_lim100);
            const __m256d v_ge0 = _mm256_cmp_pd(vsd, v_zero, _CMP_GE_OQ);
            const __m256d v_slope = _mm256_blendv_pd(_mm256_set1_pd(tau - 1.0),
                                                     _mm256_set1_pd(tau), v_ge0);
            const __m256d vloss = _mm256_mul_pd(v_slope, vsd);
            const double l_bar = eproc_hsum4_avx2(_mm256_mul_pd(vwr, vloss));

            __m256d vreg = _mm256_sub_pd(_mm256_set1_pd(l_bar), vloss);
            vreg = _mm256_min_pd(_mm256_max_pd(vreg, v_neg1), v_one);
            const __m256d vreg2 = _mm256_mul_pd(vreg, vreg);
            _mm256_storeu_pd(reg_buf[r], vreg);
            _mm256_storeu_pd(reg2_buf[r], vreg2);
            _mm256_storeu_pd(cp->exp_var[r], _mm256_add_pd(_mm256_loadu_pd(cp->exp_var[r]), vreg2));

            const __m256d v_hit = _mm256_cmp_pd(v_score, vq, _CMP_LE_OQ);
            const __m256d v_errk = _mm256_andnot_pd(v_hit, v_one);
            __m256d valpha_new = _mm256_add_pd(
                valpha, _mm256_mul_pd(v_gam, _mm256_sub_pd(_mm256_set1_pd(target_a), v_errk)));
            valpha_new = _mm256_min_pd(_mm256_max_pd(valpha_new, v_zero), v_one);
            _mm256_storeu_pd(cp->alpha_t[r], valpha_new);
        }
    }

    /* Micro-pass 2: Bit-exact rsqrt4 BOA learning rate + log-weight shift */
    {
        const __m256d v_one = _mm256_set1_pd(1.0);
        const __m256d v_half = _mm256_set1_pd(0.5);
        const __m256d v_sqlog4 = _mm256_set1_pd(SQRT_LOG4);
        const __m256d v_neg50 = _mm256_set1_pd(-50.0);

#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC unroll 5
#endif
        for (uint32_t r = 0; r < n_rates; ++r) {
            const __m256d vreg = _mm256_loadu_pd(reg_buf[r]);
            const __m256d vreg2 = _mm256_loadu_pd(reg2_buf[r]);
            const __m256d vdenom = _mm256_max_pd(_mm256_loadu_pd(cp->exp_var[r]), v_one);
            const __m256d veta = _mm256_min_pd(_mm256_mul_pd(v_sqlog4, eproc_rsqrt4_avx2(vdenom)), v_half);
            const __m256d vdelta = _mm256_sub_pd(_mm256_mul_pd(veta, vreg),
                                                 _mm256_mul_pd(_mm256_mul_pd(veta, veta), vreg2));
            __m256d vlw = _mm256_add_pd(_mm256_loadu_pd(cp->exp_log_w[r]), vdelta);
            const __m256d vmax1 = _mm256_max_pd(vlw, _mm256_permute_pd(vlw, 0x5));
            const __m256d vmax2 = _mm256_permute2f128_pd(vmax1, vmax1, 0x1);
            const __m256d vmax_all = _mm256_max_pd(vmax1, vmax2);
            vlw = _mm256_max_pd(_mm256_sub_pd(vlw, vmax_all), v_neg50);
            _mm256_storeu_pd(cp->exp_log_w[r], vlw);
        }
    }

    /* Micro-pass 3: Compact degree-5 exp4_neg50 (pre-clamped) + sums */
    {
#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC unroll 5
#endif
        for (uint32_t r = 0; r < n_rates; ++r) {
            const __m256d vw_raw = eproc_exp4_neg50_clamped_avx2(_mm256_loadu_pd(cp->exp_log_w[r]));
            _mm256_storeu_pd(w_cache[r], vw_raw);
            w_sum_arr[r] = eproc_hsum4_avx2(vw_raw);
            wa_sum_arr[r] = eproc_hsum4_avx2(_mm256_mul_pd(vw_raw, _mm256_loadu_pd(cp->alpha_t[r])));
        }
    }

    /* Micro-pass 4: Vectorized 1/w_sum normalization */
    {
        double inv_w_arr[EPROC_MAX_RATES];
        const __m256d v_one = _mm256_set1_pd(1.0);
        if (n_rates >= 4U) {
            _mm256_storeu_pd(inv_w_arr, _mm256_div_pd(v_one, _mm256_loadu_pd(w_sum_arr)));
            for (uint32_t r = 4U; r < n_rates; ++r) {
                inv_w_arr[r] = 1.0 / w_sum_arr[r];
            }
        } else {
            for (uint32_t r = 0; r < n_rates; ++r) {
                inv_w_arr[r] = 1.0 / w_sum_arr[r];
            }
        }
#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC unroll 5
#endif
        for (uint32_t r = 0; r < n_rates; ++r) {
            const double inv_s = inv_w_arr[r];
            _mm256_storeu_pd(w_cache[r],
                             _mm256_mul_pd(_mm256_loadu_pd(w_cache[r]), _mm256_set1_pd(inv_s)));
            a_agg_arr[r] = wa_sum_arr[r] * inv_s;
        }
    }

    if (pid_ki > 0.0) {
        double th[EPROC_MAX_RATES];
        eproc_tanh_rates_avx2(pid_z, th, n_rates);
        for (uint32_t r = 0; r < n_rates; ++r) {
            a_agg_arr[r] -= pid_ki * th[r];
        }
    }

    eproc_conformal_push_score_avx2(cp, score);
    cp->n_updates++;

    if (n_rates >= 4U) {
        const __m256d v_zero = _mm256_setzero_pd();
        const __m256d v_one = _mm256_set1_pd(1.0);
        const __m256d v_new_lp1 = _mm256_set1_pd((double)(cp->win_len + 1U));
        const __m256d v_new_lm1 = _mm256_set1_pd((double)(cp->win_len - 1U));
        __m256d vea = _mm256_min_pd(_mm256_max_pd(_mm256_loadu_pd(a_agg_arr), v_zero), v_one);
        _mm256_storeu_pd(cp->eff_alpha, vea);
        __m256d vcq = eproc_sorted_quantile4_avx2(cp->sorted, v_new_lp1, v_new_lm1, vea);
        _mm256_storeu_pd(cp->current_q, vcq);
        for (uint32_t r = 4U; r < n_rates; ++r) {
            const double ea = eproc_clamp(a_agg_arr[r], 0.0, 1.0);
            cp->eff_alpha[r] = ea;
            cp->current_q[r] = eproc_sorted_quantile(cp->sorted, cp->win_len, ea);
        }
    } else {
        for (uint32_t r = 0; r < n_rates; ++r) {
            const double ea = eproc_clamp(a_agg_arr[r], 0.0, 1.0);
            cp->eff_alpha[r] = ea;
            cp->current_q[r] = eproc_sorted_quantile(cp->sorted, cp->win_len, ea);
        }
    }

    eproc_pava_nondecreasing(cp->current_q, n_rates);
}

EPROC_TARGET_AVX2
static void eproc_conformal_run_single_avx2(eproc_conformal_t *cp, double score) {
    const double inv_csat = (cp->pid_csat > 0.0) ? (1.0 / cp->pid_csat) : 0.0;
    const double max_pid_sum = 10.0 * cp->pid_csat;
    double w_cache[EPROC_MAX_RATES][EPROC_AGACI_EXPERTS];
    eproc_conformal_load_weights_avx2(cp, w_cache);
    eproc_conformal_step_cached_avx2(cp, score, w_cache, inv_csat, max_pid_sum, cp->n_rates);
}

EPROC_TARGET_AVX2
static void eproc_conformal_run_batch_avx2(eproc_conformal_t *cp, const double *scores, size_t n) {
    const double inv_csat = (cp->pid_csat > 0.0) ? (1.0 / cp->pid_csat) : 0.0;
    const double max_pid_sum = 10.0 * cp->pid_csat;
    double w_cache[EPROC_MAX_RATES][EPROC_AGACI_EXPERTS];
    eproc_conformal_load_weights_avx2(cp, w_cache);
    const uint32_t nr = cp->n_rates;
    if (nr == 5U) {
        for (size_t i = 0; i < n; ++i) {
            const double s = scores[i];
            if (!isfinite(s)) {
                continue;
            }
            eproc_conformal_step_cached_avx2(cp, s, w_cache, inv_csat, max_pid_sum, 5U);
        }
    } else {
        for (size_t i = 0; i < n; ++i) {
            const double s = scores[i];
            if (!isfinite(s)) {
                continue;
            }
            eproc_conformal_step_cached_avx2(cp, s, w_cache, inv_csat, max_pid_sum, nr);
        }
    }
}
#endif

#if !EPROC_STATIC_AVX2
EPROC_ALWAYS_INLINE void eproc_conformal_load_weights_scalar(
    const eproc_conformal_t *cp,
    double w_cache[EPROC_MAX_RATES][EPROC_AGACI_EXPERTS]) {
    for (uint32_t r = 0; r < cp->n_rates; ++r) {
        double w[4];
        for (int k = 0; k < 4; ++k) {
            w[k] = eproc_exp_neg50_scalar(cp->exp_log_w[r][k]);
        }
        const double w_sum = (w[0] + w[1]) + (w[2] + w[3]);
        const double inv_s = (w_sum > 0.0) ? (1.0 / w_sum) : 0.25;
        for (int k = 0; k < 4; ++k) {
            w_cache[r][k] = w[k] * inv_s;
        }
    }
}

EPROC_ALWAYS_INLINE void eproc_conformal_step_cached_scalar(
    eproc_conformal_t *cp,
    double score,
    double w_cache[EPROC_MAX_RATES][EPROC_AGACI_EXPERTS],
    double inv_csat,
    double max_pid_sum,
    uint32_t n_rates) {
    static const double SQRT_LOG4 = 1.17741002251547469101;
    const uint32_t prev_len = cp->win_len;

    const double ema_beta = (cp->n_updates < 50ULL)
        ? (1.0 / (double)(cp->n_updates + 1ULL))
        : 0.02;

    if (prev_len == 0U) {
        for (uint32_t r = 0; r < n_rates; ++r) {
            cp->emp_cov_ema[r] = (1.0 - ema_beta) * cp->emp_cov_ema[r];
            cp->eff_alpha[r] = cp->target_alphas[r];
        }
        eproc_conformal_push_score_scalar(cp, score);
        cp->n_updates++;
        for (uint32_t r = 0; r < n_rates; ++r) {
            cp->current_q[r] = score;
        }
        return;
    }

    double half_scale;
    if (prev_len >= 2U) {
        const double half_rng = 0.5 * cp->sorted[prev_len - 1U] - 0.5 * cp->sorted[0];
        half_scale = (half_rng > 0.5e-6) ? half_rng : 0.5e-6;
    } else {
        const double half_ab = 0.5 * fabs(score);
        half_scale = (half_ab > 0.5) ? half_ab : 0.5;
    }
    const double inv_half_scale = 1.0 / half_scale;
    const double half_score = 0.5 * score;

    double a_agg_arr[EPROC_MAX_RATES] = {0.0};
    double pid_z[EPROC_MAX_RATES] = {0.0};
    double w_sum_arr[EPROC_MAX_RATES] = {1.0, 1.0, 1.0, 1.0, 1.0};
    double wa_sum_arr[EPROC_MAX_RATES] = {0.0};
    const double pid_ki = cp->pid_ki;

    double w_raw_arr[EPROC_MAX_RATES][4];
    for (uint32_t r = 0; r < n_rates; ++r) {
        const double target_a = cp->target_alphas[r];
        const double tau = 1.0 - target_a;
        const int covered = (score <= cp->current_q[r]);
        const double err = (double)(1 - covered);

        cp->hit_counts[r] += (uint64_t)covered;
        cp->emp_cov_ema[r] = (1.0 - ema_beta) * cp->emp_cov_ema[r] + ema_beta * (double)covered;
        cp->pid_err_sum[r] = eproc_clamp(
            cp->pid_err_sum[r] + (err - target_a), -max_pid_sum, max_pid_sum);
        pid_z[r] = cp->pid_err_sum[r] * inv_csat;

        const double *at = cp->alpha_t[r];
        double q_exp[4];
        q_exp[0] = eproc_sorted_quantile(cp->sorted, prev_len, at[0]);
        q_exp[1] = eproc_sorted_quantile(cp->sorted, prev_len, at[1]);
        q_exp[2] = eproc_sorted_quantile(cp->sorted, prev_len, at[2]);
        q_exp[3] = eproc_sorted_quantile(cp->sorted, prev_len, at[3]);

        const double *wr = w_cache[r];
        double loss_exp[4];
        for (int k = 0; k < 4; ++k) {
            double sd = (half_score - 0.5 * q_exp[k]) * inv_half_scale;
            sd = eproc_clamp(sd, -1e100, 1e100);
            loss_exp[k] = (sd >= 0.0) ? (tau * sd) : ((tau - 1.0) * sd);
        }
        const double l_bar = (wr[0] * loss_exp[0] + wr[1] * loss_exp[1])
                           + (wr[2] * loss_exp[2] + wr[3] * loss_exp[3]);

        double lw_new[4];
        double alpha_new[4];
        for (int k = 0; k < 4; ++k) {
            const double rk = eproc_clamp(l_bar - loss_exp[k], -1.0, 1.0);
            const double rk2 = rk * rk;
            const double v_new = cp->exp_var[r][k] + rk2;
            cp->exp_var[r][k] = v_new;
            const double denom = (v_new > 1.0) ? v_new : 1.0;
            const double e_raw = SQRT_LOG4 * eproc_rsqrt_scalar(denom);
            const double ek = (e_raw < 0.5) ? e_raw : 0.5;
            const double dk = ek * rk - (ek * ek) * rk2;
            lw_new[k] = cp->exp_log_w[r][k] + dk;

            const double err_k = (score <= q_exp[k]) ? 0.0 : 1.0;
            alpha_new[k] = eproc_clamp(at[k] + cp->gammas[k] * (target_a - err_k), 0.0, 1.0);
            cp->alpha_t[r][k] = alpha_new[k];
        }

        const double m01 = (lw_new[0] > lw_new[1]) ? lw_new[0] : lw_new[1];
        const double m23 = (lw_new[2] > lw_new[3]) ? lw_new[2] : lw_new[3];
        const double max_lw = (m01 > m23) ? m01 : m23;

        for (int k = 0; k < 4; ++k) {
            double s_lw = lw_new[k] - max_lw;
            if (s_lw < -50.0) s_lw = -50.0;
            cp->exp_log_w[r][k] = s_lw;
            w_raw_arr[r][k] = eproc_exp_neg50_scalar(s_lw);
        }
        w_sum_arr[r] = (w_raw_arr[r][0] + w_raw_arr[r][1]) + (w_raw_arr[r][2] + w_raw_arr[r][3]);
        wa_sum_arr[r] = (w_raw_arr[r][0] * alpha_new[0] + w_raw_arr[r][1] * alpha_new[1])
                      + (w_raw_arr[r][2] * alpha_new[2] + w_raw_arr[r][3] * alpha_new[3]);
    }
    for (uint32_t r = 0; r < n_rates; ++r) {
        const double inv_s = 1.0 / w_sum_arr[r];
        for (int k = 0; k < 4; ++k) {
            w_cache[r][k] = w_raw_arr[r][k] * inv_s;
        }
        a_agg_arr[r] = wa_sum_arr[r] * inv_s;
    }

    if (pid_ki > 0.0) {
        double th[EPROC_MAX_RATES];
        eproc_tanh_rates_scalar(pid_z, th, n_rates);
        for (uint32_t r = 0; r < n_rates; ++r) {
            a_agg_arr[r] -= pid_ki * th[r];
        }
    }

    eproc_conformal_push_score_scalar(cp, score);
    cp->n_updates++;

    for (uint32_t r = 0; r < n_rates; ++r) {
        const double ea = eproc_clamp(a_agg_arr[r], 0.0, 1.0);
        cp->eff_alpha[r] = ea;
        cp->current_q[r] = eproc_sorted_quantile(cp->sorted, cp->win_len, ea);
    }

    eproc_pava_nondecreasing(cp->current_q, n_rates);
}

static void eproc_conformal_run_single_scalar(eproc_conformal_t *cp, double score) {
    const double inv_csat = (cp->pid_csat > 0.0) ? (1.0 / cp->pid_csat) : 0.0;
    const double max_pid_sum = 10.0 * cp->pid_csat;
    double w_cache[EPROC_MAX_RATES][EPROC_AGACI_EXPERTS];
    eproc_conformal_load_weights_scalar(cp, w_cache);
    eproc_conformal_step_cached_scalar(cp, score, w_cache, inv_csat, max_pid_sum, cp->n_rates);
}

static void eproc_conformal_run_batch_scalar(eproc_conformal_t *cp, const double *scores, size_t n) {
    const double inv_csat = (cp->pid_csat > 0.0) ? (1.0 / cp->pid_csat) : 0.0;
    const double max_pid_sum = 10.0 * cp->pid_csat;
    double w_cache[EPROC_MAX_RATES][EPROC_AGACI_EXPERTS];
    eproc_conformal_load_weights_scalar(cp, w_cache);
    const uint32_t nr = cp->n_rates;
    if (nr == 5U) {
        for (size_t i = 0; i < n; ++i) {
            const double s = scores[i];
            if (!isfinite(s)) {
                continue;
            }
            eproc_conformal_step_cached_scalar(cp, s, w_cache, inv_csat, max_pid_sum, 5U);
        }
    } else {
        for (size_t i = 0; i < n; ++i) {
            const double s = scores[i];
            if (!isfinite(s)) {
                continue;
            }
            eproc_conformal_step_cached_scalar(cp, s, w_cache, inv_csat, max_pid_sum, nr);
        }
    }
}
#endif

int eproc_conformal_update(eproc_conformal_t *cp,
                           double nonconformity_score,
                           eproc_conformal_out_t *meta_out) {
    if (cp == NULL) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(nonconformity_score)) {
        eproc_conformal_fill_meta(cp, meta_out);
        return EPROC_OK;
    }
#if EPROC_BUILD_AVX2
    if (eproc_use_avx2()) {
        eproc_conformal_run_single_avx2(cp, nonconformity_score);
        eproc_conformal_fill_meta(cp, meta_out);
        return EPROC_OK;
    }
#endif
#if !EPROC_STATIC_AVX2
    eproc_conformal_run_single_scalar(cp, nonconformity_score);
#endif
    eproc_conformal_fill_meta(cp, meta_out);
    return EPROC_OK;
}

int eproc_conformal_update_batch(eproc_conformal_t *cp,
                                 const double *scores,
                                 size_t n,
                                 eproc_conformal_out_t *meta_out) {
    if (cp == NULL || (n > 0 && scores == NULL)) {
        return EPROC_ERR_INVALID;
    }
#if EPROC_BUILD_AVX2
    if (eproc_use_avx2()) {
        eproc_conformal_run_batch_avx2(cp, scores, n);
        eproc_conformal_fill_meta(cp, meta_out);
        return EPROC_OK;
    }
#endif
#if !EPROC_STATIC_AVX2
    eproc_conformal_run_batch_scalar(cp, scores, n);
#endif
    eproc_conformal_fill_meta(cp, meta_out);
    return EPROC_OK;
}

/* ============================================================================
 * 2B. STRICTLY CAUSAL DELAYED-FEEDBACK CONFORMAL WRAPPER
 * ============================================================================ */

int eproc_delayed_conformal_init(eproc_delayed_conformal_t *dc,
                                 const double *alphas,
                                 uint32_t n_rates,
                                 uint32_t window_size,
                                 double pid_ki) {
    if (dc == NULL) {
        return EPROC_ERR_INVALID;
    }
    memset(dc, 0, sizeof(*dc));
    int rc = eproc_conformal_init(&dc->core, alphas, n_rates, window_size, pid_ki);
    if (rc != EPROC_OK) {
        return rc;
    }
    dc->pending_count = 0;
    dc->next_ticket = 1ULL;
    return EPROC_OK;
}

int eproc_delayed_conformal_issue(eproc_delayed_conformal_t *dc,
                                  double pred,
                                  double scale,
                                  uint64_t *ticket_out,
                                  double *lows_out,
                                  double *highs_out) {
    if (dc == NULL) {
        return EPROC_ERR_INVALID;
    }
    if (dc->pending_count >= EPROC_DELAY_MAX_PENDING) {
        return EPROC_ERR_CAPACITY;
    }

    /* Issue predictions using ONLY labels revealed <= t_issue */
    eproc_conformal_predict(&dc->core, pred, scale, lows_out, highs_out, NULL);

    const uint64_t tid = dc->next_ticket++;
    const uint32_t mask = EPROC_DELAY_MAX_PENDING - 1U;
    uint32_t idx = (uint32_t)(tid & mask);
    for (uint32_t probe = 0; probe < EPROC_DELAY_MAX_PENDING; ++probe) {
        if (!dc->slots[idx].occupied) {
            dc->slots[idx].ticket_id = tid;
            dc->slots[idx].pred = pred;
            dc->slots[idx].scale = (isfinite(scale) && scale > 0.0) ? scale : 1.0;
            dc->slots[idx].occupied = 1U;
            dc->pending_count++;
            if (ticket_out != NULL) {
                *ticket_out = tid;
            }
            return EPROC_OK;
        }
        idx = (idx + 1U) & mask;
    }
    return EPROC_ERR_CAPACITY;
}

int eproc_delayed_conformal_reveal(eproc_delayed_conformal_t *dc,
                                   uint64_t ticket_id,
                                   double y_true,
                                   eproc_conformal_out_t *meta_out) {
    if (dc == NULL || ticket_id == 0ULL) {
        return EPROC_ERR_INVALID;
    }
    const uint32_t mask = EPROC_DELAY_MAX_PENDING - 1U;
    uint32_t idx = (uint32_t)(ticket_id & mask);
    uint32_t found = EPROC_DELAY_MAX_PENDING;

    for (uint32_t probe = 0; probe < EPROC_DELAY_MAX_PENDING; ++probe) {
        if (!dc->slots[idx].occupied) {
            break;
        }
        if (dc->slots[idx].ticket_id == ticket_id) {
            found = idx;
            break;
        }
        idx = (idx + 1U) & mask;
    }

    if (found == EPROC_DELAY_MAX_PENDING) {
        return EPROC_ERR_INVALID;
    }

    const double pred = dc->slots[found].pred;
    const double scale = dc->slots[found].scale;

    /* Knuth Algorithm R backward-shift deletion (O(1), zero tombstones) */
    dc->slots[found].occupied = 0U;
    uint32_t hole = found;
    uint32_t cur = (found + 1U) & mask;
    while (dc->slots[cur].occupied) {
        const uint32_t home = (uint32_t)(dc->slots[cur].ticket_id & mask);
        const uint32_t d_hole = (hole - home) & mask;
        const uint32_t d_cur = (cur - home) & mask;
        if (d_hole < d_cur) {
            dc->slots[hole] = dc->slots[cur];
            dc->slots[cur].occupied = 0U;
            hole = cur;
        }
        cur = (cur + 1U) & mask;
    }
    dc->pending_count--;

    if (!isfinite(y_true) || !isfinite(pred)) {
        eproc_conformal_fill_meta(&dc->core, meta_out);
        return EPROC_OK;
    }

    const double denom = (scale > 1e-12) ? scale : 1e-12;
    const double score = fabs(y_true - pred) / denom;
    return eproc_conformal_update(&dc->core, score, meta_out);
}

/* ============================================================================
 * 2C. RIGHT-CENSORED AGENT BUDGET CONFORMAL CALIBRATOR (PROBE-STYLE UPB)
 * ============================================================================ */

int eproc_budget_conformal_init(eproc_budget_conformal_t *bc,
                                double alpha,
                                uint32_t window_size,
                                double censor_penalty) {
    if (bc == NULL) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(censor_penalty) || censor_penalty < 1.0) {
        return EPROC_ERR_INVALID;
    }
    memset(bc, 0, sizeof(*bc));
    int rc = eproc_conformal_init(&bc->core, &alpha, 1U, window_size, 0.0);
    if (rc != EPROC_OK) {
        return rc;
    }
    bc->censor_penalty = censor_penalty;
    bc->n_completed = 0;
    bc->n_censored = 0;
    return EPROC_OK;
}

double eproc_budget_conformal_bound(const eproc_budget_conformal_t *bc,
                                    double base_estimate) {
    if (bc == NULL) {
        return 0.0;
    }
    const double base = (isfinite(base_estimate) && base_estimate > 0.0) ? base_estimate : 0.0;
    const double q = bc->core.current_q[0];
    const double raw = base + q;
    if (!isfinite(raw)) {
        return base;
    }
    if (base > 0.0) {
        return (raw > 1e-12) ? raw : 1e-12;
    }
    return (raw > 0.0) ? raw : 0.0;
}

int eproc_budget_conformal_update(eproc_budget_conformal_t *bc,
                                  double base_estimate,
                                  double observed_cost,
                                  int32_t censored) {
    if (bc == NULL) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(base_estimate) || !isfinite(observed_cost)) {
        return EPROC_OK;
    }
    if (observed_cost < 0.0) {
        return EPROC_ERR_INVALID;
    }

    double score;
    if (censored != 0) {
        score = (observed_cost * bc->censor_penalty) - base_estimate;
        bc->n_censored++;
    } else {
        score = observed_cost - base_estimate;
        bc->n_completed++;
    }
    return eproc_conformal_update(&bc->core, score, NULL);
}

/* ============================================================================
 * 2D. EXACT ASSOCIATIVE & COMMUTATIVE DISTRIBUTED CONFORMAL MONOID (640 B)
 * ============================================================================ */

#define EPROC_CMONOID_WIRE_MAGIC 0x455052434D4F4E01ULL /* "EPRCMON\x01" */
#define EPROC_CMONOID_FLAG_SCALE_MISMATCH 1ULL

/* 63 exact interior edges spanning [-16, +32] with signed log spacing:
 *   bin  0: (-inf, -16)
 *   bin  1..15: [-16, 0) via -(17^u - 1)
 *   bin 16..62: [0, 32)  via +(33^u - 1) (~7.7% uniform relative resolution)
 *   bin 63: [32, +inf)
 */
static const double EPROC_CMONOID_EDGES[EPROC_CMONOID_BINS - 1] = {
    -16.0,
    -13.074046879278832,
    -10.651693856478721,
    -8.6462638564168639,
    -6.9859982191237586,
    -5.6114890184579442,
    -4.4735533169184887,
    -3.531473292855468,
    -2.7515392679910513,
    -2.1058435015977324,
    -1.5712815906582351,
    -1.1287257439265086,
    -0.76234034783231697,
    -0.45901533368450531,
    -0.20789707081543396,
    0.0,
    0.077230911718957573,
    0.16042643716285654,
    0.25004722888772535,
    0.34658951606648092,
    0.45058785210348495,
    0.56261807444988143,
    0.68330049300816764,
    0.8133033247801591,
    0.95334639377594788,
    1.1042051166702023,
    1.2667147962743375,
    1.4417752465974552,
    1.6303557751049591,
    1.8335005497615402,
    2.0523343805757919,
    2.2880689476587794,
    2.5420095102812605,
    2.8155621340775001,
    3.1102414764126367,
    3.4276791730210592,
    3.7696328723525152,
    4.1379959676490108,
    4.5348080806388706,
    4.9622663548960633,
    5.4227376213959522,
    5.9187715036280117,
    6.4531145348283463,
    7.0287253654989517,
    7.6487911454175563,
    8.3167451708450031,
    9.0362858946425533,
    9.8113974045579138,
    10.646371483067893,
    11.545831370922896,
    12.514757365971565,
    13.558514399006048,
    14.682881739314858,
    15.89408499442273,
    17.198830581199559,
    18.604342859204451,
    20.118404131871845,
    21.749397737025703,
    23.50635446531339,
    25.39900256357749,
    27.437821600033679,
    29.634100489505336,
    32.0
};

static inline uint32_t eproc_cmonoid_bin(double z) {
    uint32_t lo = 0U;
    uint32_t hi = EPROC_CMONOID_BINS - 1U;
    while (lo < hi) {
        const uint32_t mid = (lo + hi) >> 1;
        if (z < EPROC_CMONOID_EDGES[mid]) {
            hi = mid;
        } else {
            lo = mid + 1U;
        }
    }
    return lo;
}

static inline uint64_t eproc_fnv1a64(const uint8_t *data, size_t len) {
    uint64_t h = 14695981039346656037ULL;
    for (size_t i = 0; i < len; ++i) {
        h ^= (uint64_t)data[i];
        h *= 1099511628211ULL;
    }
    return h;
}

void eproc_cmonoid_init(eproc_cmonoid_t *m, double scale_hint) {
    if (m == NULL) {
        return;
    }
    memset(m, 0, sizeof(*m));
    m->scale_hint = (isfinite(scale_hint) && scale_hint > 0.0) ? scale_hint : 1.0;
    m->min_val = INFINITY;
    m->max_val = -INFINITY;
}

/* Identical scaling (score * (1.0 / scale)) in BOTH scalar add and add_batch (fixes W07) */
void eproc_cmonoid_add(eproc_cmonoid_t *m, double score) {
    if (m == NULL || !isfinite(score)) {
        return;
    }
    const double scale = (isfinite(m->scale_hint) && m->scale_hint > 0.0) ? m->scale_hint : 1.0;
    const double inv_scale = 1.0 / scale;
    const uint32_t bin = eproc_cmonoid_bin(score * inv_scale);
    m->bin_counts[bin]++;
    m->count++;
    eproc_kahan_add(&m->sum, &m->sum_comp, score);
    const double sq = score * score;
    if (isfinite(sq)) {
        eproc_kahan_add(&m->sum_sq, &m->sum_sq_comp, sq);
    }
    if (score < m->min_val) {
        m->min_val = score;
    }
    if (score > m->max_val) {
        m->max_val = score;
    }
}

void eproc_cmonoid_add_batch(eproc_cmonoid_t *m, const double *scores, size_t n) {
    if (m == NULL || (n > 0 && scores == NULL)) {
        return;
    }
    const double scale = (isfinite(m->scale_hint) && m->scale_hint > 0.0) ? m->scale_hint : 1.0;
    const double inv_scale = 1.0 / scale;
    uint64_t count = m->count;
    double sum = m->sum;
    double sum_comp = m->sum_comp;
    double sum_sq = m->sum_sq;
    double sum_sq_comp = m->sum_sq_comp;
    double min_val = m->min_val;
    double max_val = m->max_val;

    for (size_t i = 0; i < n; ++i) {
        const double s = scores[i];
        if (!isfinite(s)) {
            continue;
        }
        const uint32_t bin = eproc_cmonoid_bin(s * inv_scale);
        m->bin_counts[bin]++;
        count++;
        eproc_kahan_add(&sum, &sum_comp, s);
        const double sq = s * s;
        if (isfinite(sq)) {
            eproc_kahan_add(&sum_sq, &sum_sq_comp, sq);
        }
        if (s < min_val) {
            min_val = s;
        }
        if (s > max_val) {
            max_val = s;
        }
    }

    m->count = count;
    m->sum = sum;
    m->sum_comp = sum_comp;
    m->sum_sq = sum_sq;
    m->sum_sq_comp = sum_sq_comp;
    m->min_val = min_val;
    m->max_val = max_val;
}

#if EPROC_BUILD_AVX2
EPROC_TARGET_AVX2
static void eproc_cmonoid_add_bins_avx2(uint64_t *dst, const uint64_t *a, const uint64_t *b) {
    for (size_t i = 0; i < EPROC_CMONOID_BINS; i += 4) {
        __m256i va = _mm256_loadu_si256((const __m256i *)(const void *)(a + i));
        __m256i vb = _mm256_loadu_si256((const __m256i *)(const void *)(b + i));
        __m256i vs = _mm256_add_epi64(va, vb);
        _mm256_storeu_si256((__m256i *)(void *)(dst + i), vs);
    }
}

EPROC_TARGET_AVX2
static void eproc_cmonoid_sub_bins_avx2(uint64_t *dst, const uint64_t *g, const uint64_t *l) {
    for (size_t i = 0; i < EPROC_CMONOID_BINS; i += 4) {
        __m256i vg = _mm256_loadu_si256((const __m256i *)(const void *)(g + i));
        __m256i vl = _mm256_loadu_si256((const __m256i *)(const void *)(l + i));
        __m256i vd = _mm256_sub_epi64(vg, vl);
        _mm256_storeu_si256((__m256i *)(void *)(dst + i), vd);
    }
}
#endif

void eproc_cmonoid_merge(const eproc_cmonoid_t *a,
                         const eproc_cmonoid_t *b,
                         eproc_cmonoid_t *out) {
    if (a == NULL || b == NULL || out == NULL) {
        return;
    }
    if (a->count == 0ULL) {
        if (out != b) {
            *out = *b;
        }
        return;
    }
    if (b->count == 0ULL) {
        if (out != a) {
            *out = *a;
        }
        return;
    }

    /* Capture scalar fields first so out == a or out == b aliasing is 100% safe */
    const uint64_t new_count = a->count + b->count;
    double sum = 0.0, sum_comp = 0.0;
    eproc_kahan_merge_sym(a->sum, a->sum_comp, b->sum, b->sum_comp, &sum, &sum_comp);

    double sum_sq = 0.0, sum_sq_comp = 0.0;
    eproc_kahan_merge_sym(a->sum_sq, a->sum_sq_comp, b->sum_sq, b->sum_sq_comp, &sum_sq, &sum_sq_comp);

    const double min_val = (a->min_val < b->min_val) ? a->min_val : b->min_val;
    const double max_val = (a->max_val > b->max_val) ? a->max_val : b->max_val;
    const double log_wealth = a->log_wealth + b->log_wealth;

    const double scale_ref = fmax(1.0, fmax(fabs(a->scale_hint), fabs(b->scale_hint)));
    const int scale_mismatch = (fabs(a->scale_hint - b->scale_hint) > 1e-12 * scale_ref) ? 1 : 0;
    const double scale_hint = scale_mismatch
        ? ((a->scale_hint < b->scale_hint) ? a->scale_hint : b->scale_hint)
        : a->scale_hint;
    const uint64_t flags = a->flags | b->flags | (scale_mismatch ? EPROC_CMONOID_FLAG_SCALE_MISMATCH : 0ULL);

#if EPROC_BUILD_AVX2
    if (eproc_use_avx2()) {
        eproc_cmonoid_add_bins_avx2(out->bin_counts, a->bin_counts, b->bin_counts);
    } else
#endif
    {
#if !EPROC_STATIC_AVX2
        for (size_t i = 0; i < EPROC_CMONOID_BINS; ++i) {
            out->bin_counts[i] = a->bin_counts[i] + b->bin_counts[i];
        }
#endif
    }

    out->count = new_count;
    out->sum = sum;
    out->sum_comp = sum_comp;
    out->sum_sq = sum_sq;
    out->sum_sq_comp = sum_sq_comp;
    out->min_val = min_val;
    out->max_val = max_val;
    out->log_wealth = log_wealth;
    out->scale_hint = scale_hint;
    out->flags = flags;
    memset(out->_reserved, 0, sizeof(out->_reserved));
}

int eproc_cmonoid_subtract(const eproc_cmonoid_t *global_m,
                           const eproc_cmonoid_t *local_m,
                           eproc_cmonoid_t *loo_out) {
    if (global_m == NULL || local_m == NULL || loo_out == NULL) {
        return EPROC_ERR_INVALID;
    }
    if (local_m->count > global_m->count) {
        return EPROC_ERR_INVALID;
    }
    if (local_m->count > 0ULL && global_m->count > 0ULL) {
        const double ref = fmax(1.0, fabs(global_m->scale_hint));
        if (fabs(local_m->scale_hint - global_m->scale_hint) > 1e-12 * ref) {
            return EPROC_ERR_MISMATCH;
        }
    }
    /* Strict underflow guard BEFORE mutating loo_out */
    for (size_t i = 0; i < EPROC_CMONOID_BINS; ++i) {
        if (local_m->bin_counts[i] > global_m->bin_counts[i]) {
            return EPROC_ERR_INVALID;
        }
    }

    const uint64_t new_count = global_m->count - local_m->count;
    double sum = global_m->sum;
    double sum_comp = global_m->sum_comp;
    eproc_kahan_add(&sum, &sum_comp, -local_m->sum);
    eproc_kahan_add(&sum, &sum_comp, -local_m->sum_comp);

    double sum_sq = global_m->sum_sq;
    double sum_sq_comp = global_m->sum_sq_comp;
    eproc_kahan_add(&sum_sq, &sum_sq_comp, -local_m->sum_sq);
    eproc_kahan_add(&sum_sq, &sum_sq_comp, -local_m->sum_sq_comp);

    const double log_wealth = global_m->log_wealth - local_m->log_wealth;
    const double scale_hint = global_m->scale_hint;
    const uint64_t flags = global_m->flags;
    const double g_min = global_m->min_val;
    const double g_max = global_m->max_val;
    const double l_min = local_m->min_val;
    const double l_max = local_m->max_val;

#if EPROC_BUILD_AVX2
    if (eproc_use_avx2()) {
        eproc_cmonoid_sub_bins_avx2(loo_out->bin_counts, global_m->bin_counts, local_m->bin_counts);
    } else
#endif
    {
#if !EPROC_STATIC_AVX2
        for (size_t i = 0; i < EPROC_CMONOID_BINS; ++i) {
            loo_out->bin_counts[i] = global_m->bin_counts[i] - local_m->bin_counts[i];
        }
#endif
    }

    loo_out->count = new_count;
    loo_out->scale_hint = scale_hint;
    loo_out->flags = flags;
    loo_out->log_wealth = log_wealth;
    memset(loo_out->_reserved, 0, sizeof(loo_out->_reserved));

    if (new_count == 0ULL) {
        loo_out->sum = 0.0;
        loo_out->sum_comp = 0.0;
        loo_out->sum_sq = 0.0;
        loo_out->sum_sq_comp = 0.0;
        loo_out->min_val = INFINITY;
        loo_out->max_val = -INFINITY;
    } else {
        loo_out->sum = sum;
        loo_out->sum_comp = sum_comp;
        loo_out->sum_sq = sum_sq;
        loo_out->sum_sq_comp = sum_sq_comp;

        /* W04 fix: tighten min_val/max_val against occupied LOO bins so removed
         * outlier shards NEVER leak stale extreme values into loo_out. */
        uint32_t first_bin = 0U;
        while (first_bin < EPROC_CMONOID_BINS - 1U && loo_out->bin_counts[first_bin] == 0ULL) {
            first_bin++;
        }
        uint32_t last_bin = EPROC_CMONOID_BINS - 1U;
        while (last_bin > 0U && loo_out->bin_counts[last_bin] == 0ULL) {
            last_bin--;
        }
        const double sc = (isfinite(scale_hint) && scale_hint > 0.0) ? scale_hint : 1.0;

        double new_min = g_min;
        if (first_bin > 0U) {
            const double bin_lo = EPROC_CMONOID_EDGES[first_bin - 1U] * sc;
            if (!isfinite(new_min) || new_min < bin_lo || l_min <= g_min) {
                new_min = bin_lo;
            }
        }
        double new_max = g_max;
        if (last_bin < EPROC_CMONOID_BINS - 1U) {
            const double bin_hi = EPROC_CMONOID_EDGES[last_bin] * sc;
            if (!isfinite(new_max) || new_max > bin_hi || l_max >= g_max) {
                new_max = bin_hi;
            }
        }
        if (isfinite(new_min) && isfinite(new_max) && new_min > new_max) {
            new_min = new_max;
        }
        loo_out->min_val = new_min;
        loo_out->max_val = new_max;
    }

    return EPROC_OK;
}

double eproc_cmonoid_quantile(const eproc_cmonoid_t *m, double q) {
    if (m == NULL || m->count == 0ULL || !isfinite(q)) {
        return 0.0;
    }
    const double qc = eproc_clamp(q, 0.0, 1.0);
    const double scale = (isfinite(m->scale_hint) && m->scale_hint > 0.0) ? m->scale_hint : 1.0;

    /* Exact abelian histogram quantile: for all interior bins 1..62, depends strictly
     * on exact uint64 bin_counts (guaranteeing 0.0 LOO drift: subtract(merge(A,B),A) == B).
     * Tail overflow bins (0 and 63) use min_val / max_val. */
    if (qc == 0.0) {
        uint32_t first_bin = 0U;
        while (first_bin < EPROC_CMONOID_BINS - 1U && m->bin_counts[first_bin] == 0ULL) {
            first_bin++;
        }
        if (first_bin == 0U) {
            const double hi0 = EPROC_CMONOID_EDGES[0] * scale;
            return (isfinite(m->min_val) && m->min_val < hi0) ? m->min_val : hi0;
        }
        return EPROC_CMONOID_EDGES[first_bin - 1U] * scale;
    }
    if (qc == 1.0) {
        uint32_t last_bin = EPROC_CMONOID_BINS - 1U;
        while (last_bin > 0U && m->bin_counts[last_bin] == 0ULL) {
            last_bin--;
        }
        if (last_bin == EPROC_CMONOID_BINS - 1U) {
            const double lo63 = EPROC_CMONOID_EDGES[EPROC_CMONOID_BINS - 2U] * scale;
            return (isfinite(m->max_val) && m->max_val > lo63) ? m->max_val : lo63;
        }
        return EPROC_CMONOID_EDGES[last_bin] * scale;
    }

    const double target = qc * (double)m->count;
    uint64_t cum = 0ULL;
    uint32_t hit = EPROC_CMONOID_BINS - 1U;
    uint64_t prev_cum = 0ULL;

    for (uint32_t b = 0; b < EPROC_CMONOID_BINS; ++b) {
        const uint64_t c = m->bin_counts[b];
        if (c == 0ULL) {
            continue;
        }
        prev_cum = cum;
        cum += c;
        hit = b;
        if ((double)cum >= target) {
            break;
        }
    }

    const uint64_t bin_c = m->bin_counts[hit];
    double frac = 0.5;
    if (bin_c > 0ULL) {
        frac = eproc_clamp((target - (double)prev_cum) / (double)bin_c, 0.0, 1.0);
    }

    double lo, hi;
    if (hit == 0U) {
        hi = EPROC_CMONOID_EDGES[0] * scale;
        lo = (isfinite(m->min_val) && m->min_val < hi) ? m->min_val : hi;
    } else if (hit == EPROC_CMONOID_BINS - 1U) {
        lo = EPROC_CMONOID_EDGES[EPROC_CMONOID_BINS - 2U] * scale;
        hi = (isfinite(m->max_val) && m->max_val > lo) ? m->max_val : lo;
    } else {
        lo = EPROC_CMONOID_EDGES[hit - 1U] * scale;
        hi = EPROC_CMONOID_EDGES[hit] * scale;
    }

    return lo + frac * (hi - lo);
}

size_t eproc_cmonoid_wire_size(void) {
    return 640U;
}

int eproc_cmonoid_serialize(const eproc_cmonoid_t *m, uint8_t *buf, size_t cap) {
    if (m == NULL || buf == NULL) {
        return EPROC_ERR_INVALID;
    }
    if (cap < 640U) {
        return EPROC_ERR_CAPACITY;
    }

    size_t off = 0;
    eproc_put_le64(buf + off, m->count);
    off += 8;
    for (size_t i = 0; i < EPROC_CMONOID_BINS; ++i) {
        eproc_put_le64(buf + off, m->bin_counts[i]);
        off += 8;
    }
    eproc_put_le64(buf + off, eproc_f64_to_u64(m->sum)); off += 8;
    eproc_put_le64(buf + off, eproc_f64_to_u64(m->sum_comp)); off += 8;
    eproc_put_le64(buf + off, eproc_f64_to_u64(m->sum_sq)); off += 8;
    eproc_put_le64(buf + off, eproc_f64_to_u64(m->sum_sq_comp)); off += 8;
    eproc_put_le64(buf + off, eproc_f64_to_u64(m->min_val)); off += 8;
    eproc_put_le64(buf + off, eproc_f64_to_u64(m->max_val)); off += 8;
    eproc_put_le64(buf + off, eproc_f64_to_u64(m->log_wealth)); off += 8;
    eproc_put_le64(buf + off, eproc_f64_to_u64(m->scale_hint)); off += 8;
    eproc_put_le64(buf + off, m->flags); off += 8;

    /* Reserved header: magic+version in slot 0, zeros in 1..4, FNV-1a checksum in slot 5 */
    eproc_put_le64(buf + off, EPROC_CMONOID_WIRE_MAGIC); off += 8;
    eproc_put_le64(buf + off, 0ULL); off += 8;
    eproc_put_le64(buf + off, 0ULL); off += 8;
    eproc_put_le64(buf + off, 0ULL); off += 8;
    eproc_put_le64(buf + off, 0ULL); off += 8;
    const uint64_t csum = eproc_fnv1a64(buf, off);
    eproc_put_le64(buf + off, csum); off += 8;
    (void)off;

    return EPROC_OK;
}

int eproc_cmonoid_deserialize(eproc_cmonoid_t *m, const uint8_t *buf, size_t len) {
    if (m == NULL || buf == NULL) {
        return EPROC_ERR_INVALID;
    }
    /* W11 fix: require exact 640-byte wire payload (reject both truncated & trailing garbage) */
    if (len != 640U) {
        return EPROC_ERR_INVALID;
    }

    const uint64_t magic = eproc_get_le64(buf + 592);
    if (magic != EPROC_CMONOID_WIRE_MAGIC) {
        return EPROC_ERR_MISMATCH;
    }
    const uint64_t stored_csum = eproc_get_le64(buf + 632);
    const uint64_t calc_csum = eproc_fnv1a64(buf, 632);
    if (stored_csum != calc_csum) {
        return EPROC_ERR_MISMATCH;
    }

    eproc_cmonoid_t tmp;
    memset(&tmp, 0, sizeof(tmp));

    size_t off = 0;
    tmp.count = eproc_get_le64(buf + off); off += 8;
    uint64_t bin_sum = 0ULL;
    for (size_t i = 0; i < EPROC_CMONOID_BINS; ++i) {
        tmp.bin_counts[i] = eproc_get_le64(buf + off);
        off += 8;
        if (UINT64_MAX - bin_sum < tmp.bin_counts[i]) {
            return EPROC_ERR_INVALID;
        }
        bin_sum += tmp.bin_counts[i];
    }
    if (bin_sum != tmp.count) {
        return EPROC_ERR_INVALID;
    }

    tmp.sum = eproc_u64_to_f64(eproc_get_le64(buf + off)); off += 8;
    tmp.sum_comp = eproc_u64_to_f64(eproc_get_le64(buf + off)); off += 8;
    tmp.sum_sq = eproc_u64_to_f64(eproc_get_le64(buf + off)); off += 8;
    tmp.sum_sq_comp = eproc_u64_to_f64(eproc_get_le64(buf + off)); off += 8;
    tmp.min_val = eproc_u64_to_f64(eproc_get_le64(buf + off)); off += 8;
    tmp.max_val = eproc_u64_to_f64(eproc_get_le64(buf + off)); off += 8;
    tmp.log_wealth = eproc_u64_to_f64(eproc_get_le64(buf + off)); off += 8;
    tmp.scale_hint = eproc_u64_to_f64(eproc_get_le64(buf + off)); off += 8;
    tmp.flags = eproc_get_le64(buf + off); off += 8;

    if (!isfinite(tmp.scale_hint) || !(tmp.scale_hint > 0.0)) {
        return EPROC_ERR_INVALID;
    }
    if (tmp.count > 0ULL) {
        if (!isfinite(tmp.min_val) || !isfinite(tmp.max_val) || tmp.min_val > tmp.max_val) {
            return EPROC_ERR_INVALID;
        }
    }

    *m = tmp;
    return EPROC_OK;
}



/* ==================== eproc_fusion.c ==================== */

#if !defined(__GNUC__) || defined(__clang__)
#pragma STDC FP_CONTRACT OFF
#endif


#include <math.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>

EPROC_STATIC_ASSERT((EPROC_ECHO_TABLE_CAP & (EPROC_ECHO_TABLE_CAP - 1U)) == 0U,
                    "EPROC_ECHO_TABLE_CAP must be a power of 2");

/* ============================================================================
 * 3A. SCALE-FREE BOA + FIXED-SHARE + 3-GATE VILLE E-PROCESS + BOEHM-2012 SEQLOCK
 * ============================================================================ */

static void eproc_boa_publish_seqlock(eproc_boa_t *boa) {
    const uint32_t k = boa->n_experts;
    uint64_t snap[EPROC_BOA_MAX_EXPERTS];

    if (boa->fallback_active) {
        for (uint32_t i = 0; i < k; ++i) {
            const double w = (i == boa->anchor_idx) ? 1.0 : 0.0;
            snap[i] = eproc_f64_to_u64(w);
        }
    } else {
        for (uint32_t i = 0; i < k; ++i) {
            snap[i] = eproc_f64_to_u64(boa->weights[i]);
        }
    }
    const uint64_t meta =
        ((uint64_t)k << 32) | (uint64_t)(uint32_t)boa->fallback_active;
    const uint64_t n_upd = boa->n_updates;

    const uint64_t odd = eproc_seqlock_write_begin_u64(&boa->seqlock_seq);
    eproc_seqlock_store_words_u64(boa->seqlock_words, snap, k);
    eproc_seqlock_store_words_u64(&boa->seqlock_words[EPROC_BOA_MAX_EXPERTS], &meta, 1U);
    eproc_seqlock_store_words_u64(&boa->seqlock_words[EPROC_BOA_MAX_EXPERTS + 1U], &n_upd, 1U);
    eproc_seqlock_write_end_u64(&boa->seqlock_seq, odd);
}

static void eproc_sort_small(double *arr, uint32_t n) {
    for (uint32_t i = 1; i < n; ++i) {
        double key = arr[i];
        uint32_t j = i;
        while (j > 0 && arr[j - 1] > key) {
            arr[j] = arr[j - 1];
            j--;
        }
        arr[j] = key;
    }
}

/* Compute robust shadow BOA prediction (immune to tick-0 and steady-state Byzantine spikes) */
static double eproc_boa_shadow_predict(const eproc_boa_t *boa,
                                       const double *expert_preds,
                                       double *anchor_out) {
    const uint32_t k = boa->n_experts;
    double anc = expert_preds[boa->anchor_idx];

    if (!isfinite(anc)) {
        /* Anchor itself is non-finite: fall back to median of finite non-quarantined experts */
        double finite_vals[EPROC_BOA_MAX_EXPERTS];
        uint32_t n_fin = 0;
        for (uint32_t i = 0; i < k; ++i) {
            if (!boa->quarantined[i] && isfinite(expert_preds[i])) {
                finite_vals[n_fin++] = expert_preds[i];
            }
        }
        if (n_fin == 0U) {
            if (anchor_out != NULL) {
                *anchor_out = 0.0;
            }
            return 0.0;
        }
        eproc_sort_small(finite_vals, n_fin);
        anc = (n_fin & 1U)
            ? finite_vals[n_fin >> 1]
            : (0.5 * finite_vals[(n_fin >> 1) - 1U] + 0.5 * finite_vals[n_fin >> 1]);
    }

    if (anchor_out != NULL) {
        *anchor_out = anc;
    }

    /* Reference and strictly F_{t-1}-predictable poisoning gate anchored on trusted anchor_pred.
     * On tick 0 (n_updates == 0), NEVER allow unauthenticated non-anchor experts to inflate
     * pred_scale via MAD (prevents tick-0 Byzantine spread attacks like [1e12, 2e12, 3e12, 4e12]). */
    const double ref = anc;
    double pred_scale;
    if (boa->n_updates == 0ULL) {
        pred_scale = fmax(1.0, fabs(ref) * 0.1);
    } else {
        pred_scale = fmax(boa->scale_ema, 1e-6);
    }
    const double max_dev = boa->clip_mult * pred_scale;

    double w_sum = 0.0;
    double pred_sum = 0.0;
    double pred_comp = 0.0;

    for (uint32_t i = 0; i < k; ++i) {
        if (boa->quarantined[i]) {
            continue;
        }
        const double p = expert_preds[i];
        if (!isfinite(p)) {
            continue;
        }
        const double dev = fabs(p - ref);
        if (i != boa->anchor_idx && (!isfinite(dev) || dev > max_dev)) {
            /* Single-tick Byzantine spike suppression -> 0.00% blast radius */
            continue;
        }
        const double w = boa->weights[i];
        if (w > 0.0) {
            w_sum += w;
            eproc_kahan_add(&pred_sum, &pred_comp, w * p);
        }
    }

    if (w_sum > 0.0) {
        const double res = eproc_kahan_total(pred_sum, pred_comp) / w_sum;
        if (isfinite(res)) {
            return res;
        }
    }
    return anc;
}

int eproc_boa_init(eproc_boa_t *boa,
                   uint32_t n_experts,
                   uint32_t anchor_idx,
                   double alpha_deg) {
    if (boa == NULL) {
        return EPROC_ERR_INVALID;
    }
    if (n_experts == 0 || n_experts > EPROC_BOA_MAX_EXPERTS) {
        return EPROC_ERR_INVALID;
    }
    if (anchor_idx >= n_experts) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(alpha_deg) || !(alpha_deg > 0.0 && alpha_deg < 1.0)) {
        return EPROC_ERR_INVALID;
    }

    memset(boa, 0, sizeof(*boa));
    boa->n_experts = n_experts;
    boa->anchor_idx = anchor_idx;
    boa->fallback_active = 0;
    boa->scale_ema = 1.0;
    boa->clip_mult = 25.0;
    boa->n_updates = 0;
    boa->n_poison_clipped = 0;
    boa->n_fallback_trips = 0;

    const double w0 = 1.0 / (double)n_experts;
    for (uint32_t i = 0; i < n_experts; ++i) {
        boa->weights[i] = w0;
        boa->log_w[i] = 0.0;
        boa->grad_sq_sum[i] = 0.0;
        boa->cum_loss[i] = 0.0;
        boa->quarantined[i] = 0;
        boa->poison_strikes[i] = 0;
    }

    int rc = eproc_bet_init(&boa->sup_e, 0.5, alpha_deg, 0.0, 1.0, EPROC_SIDE_UPPER);
    if (rc != EPROC_OK) return rc;
    rc = eproc_bet_init(&boa->deg_e, 0.5, alpha_deg, 0.0, 1.0, EPROC_SIDE_LOWER);
    if (rc != EPROC_OK) return rc;
    rc = eproc_bet_init(&boa->rec_e, 0.5, alpha_deg, 0.0, 1.0, EPROC_SIDE_UPPER);
    if (rc != EPROC_OK) return rc;

    /* Initialize atomic seqlock fields cleanly before publishing */
    eproc_seqlock_init_u64(&boa->seqlock_seq, boa->seqlock_words, EPROC_BOA_MAX_EXPERTS + 2U);
    eproc_boa_publish_seqlock(boa);
    return EPROC_OK;
}

double eproc_boa_predict(const eproc_boa_t *boa, const double *expert_preds) {
    if (boa == NULL || expert_preds == NULL || boa->n_experts == 0) {
        return 0.0;
    }
    double anc = 0.0;
    const double shadow = eproc_boa_shadow_predict(boa, expert_preds, &anc);
    return boa->fallback_active ? anc : shadow;
}

int eproc_boa_update(eproc_boa_t *boa,
                     const double *expert_preds,
                     double y_true,
                     eproc_boa_step_t *out) {
    if (boa == NULL || expert_preds == NULL || boa->n_experts == 0) {
        return EPROC_ERR_INVALID;
    }

    const uint32_t k = boa->n_experts;
    double anc_pred = 0.0;
    const double boa_pred = eproc_boa_shadow_predict(boa, expert_preds, &anc_pred);
    const double fused_pred = boa->fallback_active ? anc_pred : boa_pred;

    if (!isfinite(y_true)) {
        if (out != NULL) {
            uint32_t nq = 0;
            for (uint32_t i = 0; i < k; ++i) {
                nq += boa->quarantined[i] ? 1U : 0U;
            }
            out->fused_pred = fused_pred;
            out->anchor_pred = anc_pred;
            out->fallback_active = boa->fallback_active;
            out->n_quarantined = nq;
            out->sup_log_e = boa->sup_e.log_e;
            out->deg_log_e = boa->deg_e.log_e;
            out->n_updates = boa->n_updates;
        }
        return EPROC_OK;
    }

    /* Strictly F_{t-1}-predictable scale for Huber clipping & BOA normalization */
    const double anc_diff = fabs(y_true - anc_pred);
    const double prev_scale = (boa->n_updates == 0ULL)
        ? fmax(1.0, fmax(isfinite(anc_diff) ? anc_diff : 1.0, fabs(y_true) * 0.05))
        : fmax(boa->scale_ema, 1e-6);
    const double clip_cap = boa->clip_mult * prev_scale;
    const double extreme_cap = 1e4 * prev_scale;
    const double strike_cap = 15.0 * prev_scale;

    const double anc_loss = isfinite(anc_diff) ? anc_diff : clip_cap;
    const double boa_diff = fabs(y_true - boa_pred);
    const double boa_loss = isfinite(boa_diff) ? boa_diff : clip_cap;

    double eff_loss[EPROC_BOA_MAX_EXPERTS];
    double l_mix = 0.0;
    double w_active_sum = 0.0;

    for (uint32_t i = 0; i < k; ++i) {
        if (boa->quarantined[i]) {
            eff_loss[i] = clip_cap;
            continue;
        }

        const double p = expert_preds[i];
        if (!isfinite(p)) {
            boa->n_poison_clipped++;
            if (i != boa->anchor_idx) {
                boa->quarantined[i] = 1U;
            }
            eff_loss[i] = clip_cap;
            boa->cum_loss[i] += eff_loss[i];
            continue;
        }

        const double raw_err = fabs(y_true - p);
        if (i != boa->anchor_idx && (!isfinite(raw_err) || raw_err > extreme_cap)) {
            /* Immediate quarantine on extreme Byzantine spike (> 1e4 * scale_ema) */
            boa->quarantined[i] = 1U;
            boa->n_poison_clipped++;
            eff_loss[i] = clip_cap;
        } else if (i != boa->anchor_idx && boa->n_updates >= 3ULL && raw_err > strike_cap) {
            boa->poison_strikes[i]++;
            boa->n_poison_clipped++;
            if (boa->poison_strikes[i] >= 3U) {
                boa->quarantined[i] = 1U;
            }
            eff_loss[i] = (raw_err > clip_cap) ? clip_cap : raw_err;
        } else {
            boa->poison_strikes[i] = 0U;
            if (raw_err > clip_cap) {
                boa->n_poison_clipped++;
                eff_loss[i] = clip_cap;
            } else {
                eff_loss[i] = raw_err;
            }
        }

        boa->cum_loss[i] += eff_loss[i];
        if (!boa->quarantined[i]) {
            l_mix += boa->weights[i] * eff_loss[i];
            w_active_sum += boa->weights[i];
        }
    }

    if (w_active_sum > 0.0) {
        l_mix /= w_active_sum;
    } else {
        l_mix = (anc_loss > clip_cap) ? clip_cap : anc_loss;
    }

    /* Scale-free Wintenberger-2017 BOA second-order update with mild variance
     * forgetting + Fixed-Share exploration floor for fast post-shift recovery. */
    const double log_k = log((k > 2U) ? (double)k : 2.0);
    const double inv_scale = 1.0 / prev_scale;
    double max_lw = -INFINITY;
    uint32_t n_active = 0;

    for (uint32_t i = 0; i < k; ++i) {
        if (boa->quarantined[i]) {
            boa->weights[i] = 0.0;
            continue;
        }
        n_active++;
        const double reg = eproc_clamp((l_mix - eff_loss[i]) * inv_scale, -1.0, 1.0);
        boa->grad_sq_sum[i] = 0.98 * boa->grad_sq_sum[i] + reg * reg;
        const double denom_v = (boa->grad_sq_sum[i] > 1.0) ? boa->grad_sq_sum[i] : 1.0;
        double eta = sqrt(log_k / denom_v);
        if (eta > 0.5) {
            eta = 0.5;
        }
        boa->log_w[i] += eta * reg - (eta * eta) * (reg * reg);
        if (boa->log_w[i] > max_lw) {
            max_lw = boa->log_w[i];
        }
    }

    if (n_active == 0) {
        boa->quarantined[boa->anchor_idx] = 0U;
        for (uint32_t i = 0; i < k; ++i) {
            boa->weights[i] = (i == boa->anchor_idx) ? 1.0 : 0.0;
            boa->log_w[i] = (i == boa->anchor_idx) ? 0.0 : -50.0;
        }
    } else {
        double w_norm = 0.0;
        for (uint32_t i = 0; i < k; ++i) {
            if (boa->quarantined[i]) {
                boa->weights[i] = 0.0;
                continue;
            }
            boa->log_w[i] -= max_lw;
            if (boa->log_w[i] < -50.0) {
                boa->log_w[i] = -50.0;
            }
            boa->weights[i] = exp(boa->log_w[i]);
            w_norm += boa->weights[i];
        }
        if (w_norm > 0.0) {
            const double inv_norm = 1.0 / w_norm;
            for (uint32_t i = 0; i < k; ++i) {
                boa->weights[i] *= inv_norm;
            }
            /* Fixed-Share projection onto non-quarantined simplex (eps = 0.01) */
            if (n_active > 1U) {
                const double share_eps = 0.01;
                const double keep_scale = 1.0 - share_eps;
                const double floor_w = share_eps / (double)n_active;
                for (uint32_t i = 0; i < k; ++i) {
                    if (!boa->quarantined[i]) {
                        boa->weights[i] = keep_scale * boa->weights[i] + floor_w;
                        boa->log_w[i] = log(boa->weights[i]);
                    }
                }
            }
        } else {
            for (uint32_t i = 0; i < k; ++i) {
                boa->weights[i] = (i == boa->anchor_idx) ? 1.0 : 0.0;
                boa->log_w[i] = (i == boa->anchor_idx) ? 0.0 : -50.0;
            }
        }
    }

    /* 3-Gate Ville E-processes comparing shadow BOA vs anchor on bounded [0, 1].
     * deg_e and rec_e use Page-CUSUM resetting at 0.0 so sustained pre-shift
     * outperformance never sinks deg_e to -50 and delays post-shift protection. */
    const double c_boa = (boa_loss > clip_cap) ? clip_cap : boa_loss;
    const double c_anc = (anc_loss > clip_cap) ? clip_cap : anc_loss;
    const double norm_denom = fmax(2.0 * prev_scale, 1e-6);
    const double u_t = 0.5 + 0.5 * eproc_clamp((c_anc - c_boa) / norm_denom, -1.0, 1.0);

    eproc_bet_update(&boa->sup_e, u_t, NULL);
    if (!boa->fallback_active) {
        eproc_bet_update(&boa->deg_e, u_t, NULL);
        if (boa->deg_e.log_e_neg < 0.0) {
            boa->deg_e.log_e_neg = 0.0;
            boa->deg_e.log_e = 0.0;
            boa->deg_e.lam_neg = 0.0;
            boa->deg_e.a_neg = 1.0;
        } else if (boa->deg_e.log_e_neg == 0.0 && boa->deg_e.lam_neg == 0.0) {
            boa->deg_e.a_neg = 1.0;
        }
        if (boa->deg_e.log_e >= boa->deg_e.log_thresh) {
            boa->fallback_active = 1;
            boa->n_fallback_trips++;
            eproc_bet_init(&boa->rec_e, 0.5, boa->deg_e.alpha, 0.0, 1.0, EPROC_SIDE_UPPER);
        }
    } else {
        eproc_bet_update(&boa->rec_e, u_t, NULL);
        if (boa->rec_e.log_e_pos < 0.0) {
            boa->rec_e.log_e_pos = 0.0;
            boa->rec_e.log_e = 0.0;
            boa->rec_e.lam_pos = 0.0;
            boa->rec_e.a_pos = 1.0;
        } else if (boa->rec_e.log_e_pos == 0.0 && boa->rec_e.lam_pos == 0.0) {
            boa->rec_e.a_pos = 1.0;
        }
        if (boa->rec_e.log_e >= boa->rec_e.log_thresh) {
            boa->fallback_active = 0;
            eproc_bet_init(&boa->deg_e, 0.5, boa->deg_e.alpha, 0.0, 1.0, EPROC_SIDE_LOWER);
        }
    }

    /* Update F_t scale_ema strictly AFTER using prev_scale */
    const double obs_scale = fmax(fmin(fmax(anc_loss, boa_loss), clip_cap),
                                  fmax(1e-6 * fabs(y_true), 1e-6));
    if (boa->n_updates == 0ULL) {
        boa->scale_ema = obs_scale;
    } else {
        boa->scale_ema = 0.9 * boa->scale_ema + 0.1 * obs_scale;
    }

    boa->n_updates++;

    /* Publish lock-free snapshot for concurrent readers */
    eproc_boa_publish_seqlock(boa);

    if (out != NULL) {
        uint32_t nq = 0;
        for (uint32_t i = 0; i < k; ++i) {
            nq += boa->quarantined[i] ? 1U : 0U;
        }
        out->fused_pred = fused_pred;
        out->anchor_pred = anc_pred;
        out->fallback_active = boa->fallback_active;
        out->n_quarantined = nq;
        out->sup_log_e = boa->sup_e.log_e;
        out->deg_log_e = boa->deg_e.log_e;
        out->n_updates = boa->n_updates;
    }

    return EPROC_OK;
}

int eproc_boa_snapshot_weights(const eproc_boa_t *boa,
                               double *weights_out,
                               uint32_t max_experts,
                               int32_t *fallback_out) {
    if (boa == NULL || (max_experts > 0U && weights_out == NULL)) {
        return EPROC_ERR_INVALID;
    }

    uint64_t snap[EPROC_BOA_MAX_EXPERTS];
    uint64_t meta = 0ULL;
    const uint32_t lim = (max_experts < EPROC_BOA_MAX_EXPERTS) ? max_experts : EPROC_BOA_MAX_EXPERTS;
    eproc_seqlock_read_meta_words_u64(&boa->seqlock_seq,
                                      boa->seqlock_words,
                                      EPROC_BOA_MAX_EXPERTS,
                                      &meta,
                                      snap,
                                      lim);

    uint32_t n_exp = (uint32_t)(meta >> 32);
    if (n_exp > EPROC_BOA_MAX_EXPERTS) {
        n_exp = EPROC_BOA_MAX_EXPERTS;
    }
    const int32_t fb = (int32_t)(uint32_t)(meta & 0xFFFFFFFFULL);

    const uint32_t copy_n = (n_exp < lim) ? n_exp : lim;
    for (uint32_t i = 0; i < copy_n; ++i) {
        weights_out[i] = eproc_u64_to_f64(snap[i]);
    }
    if (fallback_out != NULL) {
        *fallback_out = fb;
    }
    return EPROC_OK;
}

/* ============================================================================
 * 3B. PROVENANCE-DEDUPLICATED MULTI-AGENT EVIDENCE POOL (ECHOPOOL)
 * ============================================================================ */

static inline uint64_t eproc_echo_hash(uint32_t claim_id, uint64_t evidence_id) {
    uint64_t h = evidence_id ^ ((uint64_t)claim_id * 0x9e3779b97f4a7c15ULL);
    h = (h ^ (h >> 30)) * 0xbf58476d1ce4e5b9ULL;
    h = (h ^ (h >> 27)) * 0x94d049bb133111ebULL;
    h ^= (h >> 31);
    return (h == 0ULL) ? 1ULL : h;
}

static inline double eproc_echo_calc_rel(double alpha, double beta) {
    const double tot = alpha + beta;
    if (!(tot > 0.0)) {
        return 0.0;
    }
    const double acc = alpha / tot;
    return eproc_clamp(2.0 * acc - 1.0, 0.0, 1.0);
}

int eproc_echopool_init(eproc_echopool_t *pool,
                        uint32_t n_sources,
                        uint32_t n_claims,
                        double prior_prob) {
    if (pool == NULL) {
        return EPROC_ERR_INVALID;
    }
    if (n_sources == 0 || n_sources > EPROC_ECHO_MAX_SOURCES) {
        return EPROC_ERR_INVALID;
    }
    if (n_claims == 0 || n_claims > EPROC_ECHO_MAX_CLAIMS) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(prior_prob) || !(prior_prob > 0.0 && prior_prob < 1.0)) {
        return EPROC_ERR_INVALID;
    }

    memset(pool, 0, sizeof(*pool));
    pool->n_sources = n_sources;
    pool->n_claims = n_claims;

    /* Optimistic Beta(2, 0) prior: fresh sources start at reliability = 1.0
     * and shrink smoothly toward 0 upon inaccurate claim resolutions. */
    for (uint32_t s = 0; s < n_sources; ++s) {
        pool->src_alpha[s] = 2.0;
        pool->src_beta[s] = 0.0;
        pool->src_reliability[s] = 1.0;
    }

    const double prior_lo = log(prior_prob / (1.0 - prior_prob));
    for (uint32_t c = 0; c < n_claims; ++c) {
        pool->claim_prior_lo[c] = prior_lo;
        pool->claim_lo[c] = prior_lo;
        pool->claim_lo_comp[c] = 0.0;
        pool->claim_unique[c] = 0;
    }

    return EPROC_OK;
}

int eproc_echopool_submit(eproc_echopool_t *pool,
                          uint32_t source_id,
                          uint32_t claim_id,
                          uint64_t evidence_id,
                          double llr,
                          eproc_echo_out_t *out) {
    if (pool == NULL || source_id >= pool->n_sources || claim_id >= pool->n_claims) {
        return EPROC_ERR_INVALID;
    }

    if (!isfinite(llr)) {
        if (out != NULL) {
            const double lo = eproc_kahan_total(pool->claim_lo[claim_id],
                                                pool->claim_lo_comp[claim_id]);
            out->accepted = 0;
            out->_pad0 = 0;
            out->log_odds = lo;
            out->posterior_prob = eproc_sigmoid(lo);
            out->source_reliability = pool->src_reliability[source_id];
            out->unique_count = pool->claim_unique[claim_id];
        }
        return EPROC_OK;
    }

    const double clamped_llr = eproc_clamp(llr, -50.0, 50.0);
    const uint64_t h = eproc_echo_hash(claim_id, evidence_id);
    const uint32_t mask = EPROC_ECHO_TABLE_CAP - 1U;
    uint32_t idx = (uint32_t)(h & mask);
    uint32_t free_idx = EPROC_ECHO_TABLE_CAP;

    for (uint32_t probe = 0; probe < EPROC_ECHO_TABLE_CAP; ++probe) {
        const eproc_echo_slot_t *slot = &pool->table[idx];
        if (slot->used == 0U) {
            free_idx = idx;
            break;
        }
        if (slot->key_hash == h &&
            slot->claim_id == claim_id &&
            slot->evidence_id == evidence_id) {
            /* Duplicate echo dropped! */
            pool->n_echo_dropped++;
            if (out != NULL) {
                const double lo = eproc_kahan_total(pool->claim_lo[claim_id],
                                                    pool->claim_lo_comp[claim_id]);
                out->accepted = 0;
                out->_pad0 = 0;
                out->log_odds = lo;
                out->posterior_prob = eproc_sigmoid(lo);
                out->source_reliability = pool->src_reliability[source_id];
                out->unique_count = pool->claim_unique[claim_id];
            }
            return EPROC_OK;
        }
        idx = (idx + 1U) & mask;
    }

    if (free_idx == EPROC_ECHO_TABLE_CAP) {
        pool->n_table_full++;
        if (out != NULL) {
            const double lo = eproc_kahan_total(pool->claim_lo[claim_id],
                                                pool->claim_lo_comp[claim_id]);
            out->accepted = 0;
            out->_pad0 = 0;
            out->log_odds = lo;
            out->posterior_prob = eproc_sigmoid(lo);
            out->source_reliability = pool->src_reliability[source_id];
            out->unique_count = pool->claim_unique[claim_id];
        }
        return EPROC_ERR_CAPACITY;
    }

    const double rel = pool->src_reliability[source_id];
    const double added = rel * clamped_llr;

    /* Preserve directional sign in slot even when rel == 0 so resolve can
     * still score a silenced peer for potential recovery. */
    eproc_echo_slot_t *dst = &pool->table[free_idx];
    dst->key_hash = h;
    dst->evidence_id = evidence_id;
    dst->claim_id = claim_id;
    dst->source_id = source_id;
    if (rel > 0.0 || clamped_llr == 0.0) {
        dst->weighted_llr = added;
    } else {
        dst->weighted_llr = copysign(1e-300, clamped_llr);
    }
    dst->used = 1U;

    eproc_kahan_add(&pool->claim_lo[claim_id], &pool->claim_lo_comp[claim_id], added);
    pool->claim_unique[claim_id]++;
    pool->n_accepted++;

    if (out != NULL) {
        const double lo = eproc_kahan_total(pool->claim_lo[claim_id],
                                            pool->claim_lo_comp[claim_id]);
        out->accepted = 1;
        out->_pad0 = 0;
        out->log_odds = lo;
        out->posterior_prob = eproc_sigmoid(lo);
        out->source_reliability = rel;
        out->unique_count = pool->claim_unique[claim_id];
    }
    return EPROC_OK;
}

int eproc_echopool_resolve(eproc_echopool_t *pool,
                           uint32_t claim_id,
                           int32_t outcome_positive) {
    if (pool == NULL || claim_id >= pool->n_claims) {
        return EPROC_ERR_INVALID;
    }

    const int truth_pos = (outcome_positive != 0) ? 1 : 0;
    for (uint32_t i = 0; i < EPROC_ECHO_TABLE_CAP; ++i) {
        eproc_echo_slot_t *slot = &pool->table[i];
        if (slot->used != 1U || slot->claim_id != claim_id) {
            continue;
        }
        slot->used = 2U; /* mark resolved while keeping echo deduplication active */
        if (slot->weighted_llr == 0.0) {
            continue;
        }
        const int pred_pos = (slot->weighted_llr > 0.0) ? 1 : 0;
        const uint32_t s = slot->source_id;
        if (s < pool->n_sources) {
            if (pred_pos == truth_pos) {
                pool->src_alpha[s] += 1.0;
            } else {
                pool->src_beta[s] += 1.0;
            }
            pool->src_reliability[s] = eproc_echo_calc_rel(pool->src_alpha[s],
                                                           pool->src_beta[s]);
        }
    }

    return EPROC_OK;
}

double eproc_echopool_posterior(const eproc_echopool_t *pool, uint32_t claim_id) {
    if (pool == NULL || claim_id >= pool->n_claims) {
        return 0.5;
    }
    return eproc_sigmoid(eproc_kahan_total(pool->claim_lo[claim_id],
                                           pool->claim_lo_comp[claim_id]));
}

double eproc_echopool_source_reliability(const eproc_echopool_t *pool, uint32_t source_id) {
    if (pool == NULL || source_id >= pool->n_sources) {
        return 0.0;
    }
    return pool->src_reliability[source_id];
}



/* ==================== eproc_subsample.c ==================== */

#if !defined(__GNUC__) || defined(__clang__)
#pragma STDC FP_CONTRACT OFF
#endif


#include <float.h>
#include <math.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>

/* ============================================================================
 * 4A. COHEN-2011 VARIANCE-OPTIMAL WEIGHTED RESERVOIR SAMPLER (VAROPT)
 * ============================================================================ */

static inline void eproc_varopt_sift_up(eproc_varopt_item_t *heap, uint32_t idx) {
    while (idx > 0U) {
        const uint32_t parent = (idx - 1U) >> 1;
        if (heap[idx].orig_weight < heap[parent].orig_weight) {
            eproc_varopt_item_t tmp = heap[idx];
            heap[idx] = heap[parent];
            heap[parent] = tmp;
            idx = parent;
        } else {
            break;
        }
    }
}

static inline void eproc_varopt_sift_down(eproc_varopt_item_t *heap,
                                          uint32_t n,
                                          uint32_t idx) {
    for (;;) {
        const uint32_t left = (idx << 1) + 1U;
        const uint32_t right = left + 1U;
        uint32_t smallest = idx;
        if (left < n && heap[left].orig_weight < heap[smallest].orig_weight) {
            smallest = left;
        }
        if (right < n && heap[right].orig_weight < heap[smallest].orig_weight) {
            smallest = right;
        }
        if (smallest != idx) {
            eproc_varopt_item_t tmp = heap[idx];
            heap[idx] = heap[smallest];
            heap[smallest] = tmp;
            idx = smallest;
        } else {
            break;
        }
    }
}

int eproc_varopt_init(eproc_varopt_t *vo, uint32_t k, uint64_t seed) {
    if (vo == NULL || k == 0U || k > EPROC_VAROPT_MAX_K) {
        return EPROC_ERR_INVALID;
    }
    memset(vo, 0, sizeof(*vo));
    vo->k = k;
    vo->count = 0U;
    vo->n_heavy = 0U;
    vo->tau = 0.0;
    vo->total_weight = 0.0;
    vo->total_weight_comp = 0.0;
    vo->n_seen = 0ULL;
    eproc_rng_seed(vo->rng_state, seed);
    return EPROC_OK;
}

int eproc_varopt_push(eproc_varopt_t *vo,
                      uint64_t item_id,
                      double weight,
                      double value) {
    if (vo == NULL || !isfinite(weight) || !isfinite(value) || weight < 0.0) {
        return EPROC_ERR_INVALID;
    }
    vo->n_seen++;
    if (weight == 0.0) {
        return EPROC_OK;
    }

    eproc_kahan_add(&vo->total_weight, &vo->total_weight_comp, weight);

    eproc_varopt_item_t incoming;
    incoming.item_id = item_id;
    incoming.orig_weight = weight;
    incoming.adj_weight = weight;
    incoming.value = value;
    incoming.rand_u = 0.0;

    /* Phase 1: Reservoir not yet full -> keep deterministically in heavy min-heap */
    if (vo->count < vo->k) {
        const uint32_t pos = vo->count;
        vo->items[pos] = incoming;
        vo->count++;
        vo->n_heavy = vo->count;
        eproc_varopt_sift_up(vo->items, pos);
        return EPROC_OK;
    }

    /* Phase 2: Reservoir full (k items) -> exact Cohen-2011 VarOpt threshold tau'.
     * W06 fix: scale threshold arithmetic by 1e-150 when total_weight > 1e200 so
     * extreme 1e308 weights never overflow sum_light/tau_new to +Inf. */
    const uint32_t k = vo->k;
    uint32_t n_heavy = vo->n_heavy;
    const uint32_t prev_n_light = k - n_heavy;
    const double old_tau = vo->tau;

    const int use_scale = (!isfinite(vo->total_weight) || vo->total_weight > 1e200 ||
                           weight > 1e200 || old_tau > 1e200);
    const double sc = use_scale ? 1e-150 : 1.0;
    const double inv_sc = use_scale ? 1e150 : 1.0;

    const double w_s = weight * sc;
    const double old_tau_s = old_tau * sc;

    double sum_light_s = (double)prev_n_light * old_tau_s;
    uint32_t cnt_light = prev_n_light;
    int new_in_light = 0;

    if (prev_n_light > 0U && w_s < old_tau_s) {
        new_in_light = 1;
        sum_light_s += w_s;
        cnt_light++;
    }

    double tau_new_s = old_tau_s;
    for (;;) {
        const double cand_tau_s = (cnt_light >= 2U)
            ? (sum_light_s / (double)(cnt_light - 1U))
            : INFINITY;

        double min_h_s = INFINITY;
        int from_new = 0;
        if (n_heavy > 0U) {
            const double hs = vo->items[0].orig_weight * sc;
            if (hs < min_h_s) {
                min_h_s = hs;
                from_new = 0;
            }
        }
        if (!new_in_light && w_s < min_h_s) {
            min_h_s = w_s;
            from_new = 1;
        }

        if (cnt_light >= 2U && min_h_s >= cand_tau_s) {
            tau_new_s = cand_tau_s;
            break;
        }

        if (from_new) {
            new_in_light = 1;
            sum_light_s += w_s;
            cnt_light++;
        } else {
            /* Demote smallest heavy item into items[n_heavy - 1] (light partition) */
            eproc_varopt_item_t popped = vo->items[0];
            n_heavy--;
            if (n_heavy > 0U) {
                vo->items[0] = vo->items[n_heavy];
                eproc_varopt_sift_down(vo->items, n_heavy, 0U);
            }
            vo->items[n_heavy] = popped;
            sum_light_s += popped.orig_weight * sc;
            cnt_light++;
        }
    }

    if (tau_new_s < old_tau_s) {
        tau_new_s = old_tau_s;
    }

    /* Draw one item from L' to drop with exact probability q_i = 1 - c_i / tau_new */
    const double u = eproc_rng_uniform01(vo->rng_state);
    incoming.rand_u = u;

    int drop_new = 0;
    uint32_t drop_idx = k; /* sentinel */
    double rem_u = u;

    const uint32_t old_light_start = k - prev_n_light;
    if (prev_n_light > 0U && tau_new_s > 0.0) {
        double p_each = 1.0 - (old_tau_s / tau_new_s);
        if (p_each < 0.0) {
            p_each = 0.0;
        }
        const double p_old_block = (double)prev_n_light * p_each;
        if (rem_u < p_old_block && p_old_block > 0.0) {
            uint32_t offset = (uint32_t)floor((rem_u / p_old_block) * (double)prev_n_light);
            if (offset >= prev_n_light) {
                offset = prev_n_light - 1U;
            }
            drop_idx = old_light_start + offset;
        } else {
            rem_u -= p_old_block;
        }
    }

    if (drop_idx == k && tau_new_s > 0.0) {
        /* Check newly demoted heavy items at [n_heavy .. old_light_start - 1] */
        for (uint32_t j = n_heavy; j < old_light_start; ++j) {
            double q_j = 1.0 - ((vo->items[j].orig_weight * sc) / tau_new_s);
            if (q_j < 0.0) {
                q_j = 0.0;
            }
            if (rem_u < q_j) {
                drop_idx = j;
                break;
            }
            rem_u -= q_j;
        }
    }

    if (drop_idx == k) {
        if (new_in_light) {
            drop_new = 1;
        } else {
            /* FP rounding residual: drop last valid light element in [n_heavy .. k-1] */
            drop_idx = k - 1U;
        }
    }

    if (new_in_light) {
        if (!drop_new && drop_idx < k) {
            vo->items[drop_idx] = incoming;
        }
    } else {
        /* incoming is heavy -> move items[n_heavy] into dropped light slot and push to heap */
        if (drop_idx != n_heavy) {
            vo->items[drop_idx] = vo->items[n_heavy];
        }
        vo->items[n_heavy] = incoming;
        vo->items[n_heavy].adj_weight = weight;
        n_heavy++;
        eproc_varopt_sift_up(vo->items, n_heavy - 1U);
    }

    double tau_new = use_scale ? (tau_new_s * inv_sc) : tau_new_s;
    if (!isfinite(tau_new)) {
        tau_new = DBL_MAX;
    }

    vo->n_heavy = n_heavy;
    vo->tau = tau_new;

    /* Maintain exact Horvitz-Thompson adjusted weight = max(orig_weight, tau) on all light items */
    for (uint32_t i = n_heavy; i < k; ++i) {
        vo->items[i].adj_weight = tau_new;
    }

    return EPROC_OK;
}

double eproc_varopt_estimate_sum(const eproc_varopt_t *vo) {
    if (vo == NULL || vo->count == 0U) {
        return 0.0;
    }
    double sum = 0.0;
    double comp = 0.0;
    for (uint32_t i = 0; i < vo->count; ++i) {
        const double v = vo->items[i].value;
        if (v == 0.0) {
            continue; /* never evaluate (+Inf) * 0.0 = NaN */
        }
        const double prod = vo->items[i].adj_weight * v;
        if (isfinite(prod)) {
            eproc_kahan_add(&sum, &comp, prod);
        } else if (!isnan(prod)) {
            sum = prod;
            comp = 0.0;
        }
    }
    return eproc_kahan_total(sum, comp);
}

double eproc_varopt_estimate_mean(const eproc_varopt_t *vo) {
    if (vo == NULL || vo->count == 0U) {
        return 0.0;
    }
    const double tot_w = eproc_kahan_total(vo->total_weight, vo->total_weight_comp);
    const double est_s = eproc_varopt_estimate_sum(vo);
    if (isfinite(tot_w) && tot_w > 0.0 && isfinite(est_s)) {
        return est_s / tot_w;
    }
    /* Overflow-safe rescaled weighted mean when total_weight or sum exceeded DBL_MAX */
    double max_w = 0.0;
    for (uint32_t i = 0; i < vo->count; ++i) {
        const double w = isfinite(vo->items[i].adj_weight) ? vo->items[i].adj_weight : 0.0;
        if (w > max_w) {
            max_w = w;
        }
    }
    if (!(max_w > 0.0)) {
        return 0.0;
    }
    double num = 0.0, num_c = 0.0, den = 0.0, den_c = 0.0;
    for (uint32_t i = 0; i < vo->count; ++i) {
        const double w = isfinite(vo->items[i].adj_weight) ? (vo->items[i].adj_weight / max_w) : 0.0;
        eproc_kahan_add(&den, &den_c, w);
        if (vo->items[i].value != 0.0) {
            eproc_kahan_add(&num, &num_c, w * vo->items[i].value);
        }
    }
    const double den_tot = eproc_kahan_total(den, den_c);
    return (den_tot > 0.0) ? (eproc_kahan_total(num, num_c) / den_tot) : 0.0;
}

/* ============================================================================
 * 4B. ONLINE RIDGE LEVERAGE SCORE (RLS) CAUSAL SUBSAMPLER (AVX2 BIT-EXACT)
 * ============================================================================ */

#if !EPROC_STATIC_AVX2
static inline double eproc_dot_4lane_scalar(const double *a, const double *b, uint32_t n) {
    double lane[4] = {0.0, 0.0, 0.0, 0.0};
    uint32_t j = 0;
    for (; j + 4U <= n; j += 4U) {
        lane[0] += a[j + 0U] * b[j + 0U];
        lane[1] += a[j + 1U] * b[j + 1U];
        lane[2] += a[j + 2U] * b[j + 2U];
        lane[3] += a[j + 3U] * b[j + 3U];
    }
    double sum = (lane[0] + lane[1]) + (lane[2] + lane[3]);
    for (; j < n; ++j) {
        sum += a[j] * b[j];
    }
    return sum;
}

static double eproc_rls_matvec_scalar(const double *inv_a,
                                      const double *x,
                                      double *v,
                                      uint32_t d) {
    for (uint32_t i = 0; i < d; ++i) {
        v[i] = eproc_dot_4lane_scalar(inv_a + (size_t)i * d, x, d);
    }
    return eproc_dot_4lane_scalar(x, v, d);
}

static void eproc_rls_rank1_sub_scalar(double *inv_a, const double *wv, uint32_t d) {
    for (uint32_t i = 0; i < d; ++i) {
        double *row = inv_a + (size_t)i * d;
        const double wi = wv[i];
        for (uint32_t j = 0; j < d; ++j) {
            row[j] -= wi * wv[j];
        }
        if (row[i] < 0.0) {
            row[i] = 0.0;
        }
    }
}
#endif

#if EPROC_BUILD_AVX2
EPROC_AVX2_INLINE double eproc_dot_4lane_avx2(const double *a, const double *b, uint32_t n) {
    __m256d vacc = _mm256_setzero_pd();
    uint32_t j = 0;
    for (; j + 4U <= n; j += 4U) {
        __m256d va = _mm256_loadu_pd(a + j);
        __m256d vb = _mm256_loadu_pd(b + j);
        vacc = _mm256_add_pd(vacc, _mm256_mul_pd(va, vb));
    }
    double lane[4];
    _mm256_storeu_pd(lane, vacc);
    double sum = (lane[0] + lane[1]) + (lane[2] + lane[3]);
    for (; j < n; ++j) {
        sum += a[j] * b[j];
    }
    return sum;
}

EPROC_TARGET_AVX2
static double eproc_rls_matvec_avx2(const double *inv_a,
                                    const double *x,
                                    double *v,
                                    uint32_t d) {
    for (uint32_t i = 0; i < d; ++i) {
        v[i] = eproc_dot_4lane_avx2(inv_a + (size_t)i * d, x, d);
    }
    return eproc_dot_4lane_avx2(x, v, d);
}

EPROC_TARGET_AVX2
static void eproc_rls_rank1_sub_avx2(double *inv_a, const double *wv, uint32_t d) {
    for (uint32_t i = 0; i < d; ++i) {
        double *row = inv_a + (size_t)i * d;
        const double wi = wv[i];
        uint32_t j = 0;
        const __m256d vwi = _mm256_set1_pd(wi);
        for (; j + 4U <= d; j += 4U) {
            __m256d vr = _mm256_loadu_pd(row + j);
            __m256d vw = _mm256_loadu_pd(wv + j);
            vr = _mm256_sub_pd(vr, _mm256_mul_pd(vwi, vw));
            _mm256_storeu_pd(row + j, vr);
        }
        for (; j < d; ++j) {
            row[j] -= wi * wv[j];
        }
        if (row[i] < 0.0) {
            row[i] = 0.0;
        }
    }
}
#endif

static inline void eproc_rls_rank1_sub(double *inv_a, const double *wv, uint32_t d) {
#if EPROC_BUILD_AVX2
    if (eproc_use_avx2()) {
        eproc_rls_rank1_sub_avx2(inv_a, wv, d);
        return;
    }
#endif
#if !EPROC_STATIC_AVX2
    eproc_rls_rank1_sub_scalar(inv_a, wv, d);
#endif
}

int eproc_rls_init(eproc_rls_t *rls,
                   uint32_t d,
                   double lambda,
                   double oversample,
                   double min_prob,
                   uint64_t seed) {
    if (rls == NULL || d == 0U || d > EPROC_RLS_MAX_D) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(lambda) || !(lambda > 0.0)) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(oversample) || !(oversample > 0.0)) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(min_prob) || !(min_prob > 0.0 && min_prob <= 1.0)) {
        return EPROC_ERR_INVALID;
    }

    memset(rls, 0, sizeof(*rls));
    rls->d = d;
    rls->lambda = lambda;
    rls->oversample = oversample;
    rls->min_prob = min_prob;
    rls->n_seen = 0;
    rls->n_kept = 0;
    eproc_rng_seed(rls->rng_state, seed);

    const double inv_lam = 1.0 / lambda;
    for (uint32_t i = 0; i < d; ++i) {
        rls->inv_a[(size_t)i * d + i] = inv_lam;
    }
    return EPROC_OK;
}

int eproc_rls_step(eproc_rls_t *rls, const double *x, eproc_rls_out_t *out) {
    if (rls == NULL || x == NULL || rls->d == 0U || rls->d > EPROC_RLS_MAX_D) {
        return EPROC_ERR_INVALID;
    }

    const uint32_t d = rls->d;
    double max_abs = 0.0;
    for (uint32_t i = 0; i < d; ++i) {
        if (!isfinite(x[i])) {
            if (out != NULL) {
                memset(out, 0, sizeof(*out));
            }
            return EPROC_OK;
        }
        const double a = fabs(x[i]);
        if (a > max_abs) {
            max_abs = a;
        }
    }

    double x_scaled[EPROC_RLS_MAX_D];
    double v[EPROC_RLS_MAX_D];
    int scaled = 0;
    double scale = 1.0;
    double lev_base = 0.0;

    /* W05 fix: treat subnormal / ultra-tiny vectors (< 1e-150) as exact zero leverage
     * so 1.0 / max_abs NEVER overflows to +Inf and produces 0 * +Inf = NaN. */
    if (max_abs < 1e-150) {
        max_abs = 0.0;
        for (uint32_t i = 0; i < d; ++i) {
            v[i] = 0.0;
        }
    } else {
        const double *x_use = x;
        if (max_abs > 1e100 || max_abs < 1e-100) {
            scaled = 1;
            scale = max_abs;
            for (uint32_t i = 0; i < d; ++i) {
                x_scaled[i] = x[i] / scale;
            }
            x_use = x_scaled;
        }
#if EPROC_BUILD_AVX2
        if (eproc_use_avx2()) {
            lev_base = eproc_rls_matvec_avx2(rls->inv_a, x_use, v, d);
        } else
#endif
        {
#if !EPROC_STATIC_AVX2
            lev_base = eproc_rls_matvec_scalar(rls->inv_a, x_use, v, d);
#endif
        }
        if (!isfinite(lev_base) || lev_base < 0.0) {
            lev_base = 0.0;
        }
    }

    double leverage = scaled ? ((lev_base * scale) * scale) : lev_base;
    if (isnan(leverage) || leverage < 0.0) {
        leverage = 0.0;
    } else if (!isfinite(leverage)) {
        leverage = INFINITY;
    }

    double prob = isfinite(leverage) ? (rls->oversample * leverage) : 1.0;
    prob = eproc_clamp(prob, rls->min_prob, 1.0);

    const double u = eproc_rng_uniform01(rls->rng_state);
    const int32_t keep = (u < prob) ? 1 : 0;
    const double ht_weight = keep ? (1.0 / prob) : 0.0;

    rls->n_seen++;
    if (keep) {
        rls->n_kept++;
        if (max_abs > 0.0 && lev_base > 0.0) {
            double denom;
            if (scaled) {
                const double inv_s = 1.0 / scale;
                const double inv_s2 = inv_s * inv_s;
                denom = inv_s2 + ht_weight * lev_base;
            } else {
                denom = 1.0 + ht_weight * lev_base;
            }
            if (isfinite(denom) && denom > 0.0) {
                const double coeff = ht_weight / denom;
                if (isfinite(coeff) && coeff > 0.0) {
                    const double root_c = sqrt(coeff);
                    double wv[EPROC_RLS_MAX_D];
                    for (uint32_t i = 0; i < d; ++i) {
                        wv[i] = root_c * v[i];
                    }
                    eproc_rls_rank1_sub(rls->inv_a, wv, d);
                }
            }
        }
    }

    if (out != NULL) {
        out->keep = keep;
        out->_pad0 = 0;
        out->leverage = isfinite(leverage) ? leverage : 1e300;
        out->prob = prob;
        out->ht_weight = ht_weight;
    }
    return EPROC_OK;
}

/* ============================================================================
 * 4C. HIERARCHICAL MULTI-RESOLUTION BAYES VOI SELECTOR (SIFT)
 *     WITH EXACT GAUSSIAN MAXIMUM-ENTROPY BRANCH-AND-BOUND (30x-100x FASTER)
 * ============================================================================ */

/* Exact binary entropy H_2(p) in nats */
static inline double eproc_bin_entropy(double p) {
    const double pc = eproc_clamp(p, 1e-15, 1.0 - 1e-15);
    return -(pc * log(pc) + (1.0 - pc) * log(1.0 - pc));
}

/* Exact Mutual Information I(Z; Y) in nats for Z ~ Bern(p), Y | Z ~ N(Z*d, 1)
 * via 5-point Gauss-Hermite quadrature, tightly bounded by the exact Shannon
 * Gaussian channel capacity 0.5 * log1p(p*(1-p)*d^2) to guarantee exact
 * branch-and-bound soundness. */
static double eproc_gauss_mi(double p, double d) {
    if (!(d > 1e-12) || !(p > 1e-12 && p < 1.0 - 1e-12)) {
        return 0.0;
    }
    static const double GH_X[5] = {
        -2.8569700138728056,
        -1.3556261799742659,
         0.0,
         1.3556261799742659,
         2.8569700138728056
    };
    static const double GH_W[5] = {
        0.011257411327720689,
        0.22207592200561264,
        0.53333333333333333,
        0.22207592200561264,
        0.011257411327720689
    };

    const double h_prior = eproc_bin_entropy(p);
    const double lo = log(p / (1.0 - p));
    const double half_d = 0.5 * d;
    double eh_post = 0.0;

    for (int i = 0; i < 5; ++i) {
        const double x = GH_X[i];
        const double p1 = eproc_sigmoid(lo + d * (x + half_d));
        const double p0 = eproc_sigmoid(lo + d * (x - half_d));
        eh_post += GH_W[i] * (p * eproc_bin_entropy(p1) + (1.0 - p) * eproc_bin_entropy(p0));
    }
    double mi = h_prior - eh_post;
    if (mi <= 0.0) {
        return 0.0;
    }
    const double cap = 0.5 * log1p(p * (1.0 - p) * d * d);
    return (mi < cap) ? mi : cap;
}

static inline double eproc_sift_site_sum_var(const eproc_sift_t *sf, uint32_t site_idx) {
    const uint32_t m = sf->per_site;
    const uint32_t base = site_idx * m;
    double sum_ns2 = 0.0;
    for (uint32_t j = 0; j < m; ++j) {
        const double sc = sf->chan_noise_scale[base + j];
        sum_ns2 += sc * sc;
    }
    return sum_ns2 * (sf->noise_sd * sf->noise_sd);
}

static void eproc_sift_site_params_from_sumvar(const eproc_sift_t *sf,
                                               double sum_var,
                                               double *mu0_out,
                                               double *var0_out,
                                               double *mu1_out,
                                               double *var1_out) {
    const double inv_m = 1.0 / (double)sf->per_site;
    const double noise_var_mean = sum_var * inv_m * inv_m;
    const double mu = sf->signal_mean;
    const double mu2 = mu * mu;

    const double pc = sf->prior_active_cold;
    const double ph = sf->prior_active_hot;

    *mu0_out = pc * mu;
    *mu1_out = ph * mu;
    *var0_out = fmax(noise_var_mean + pc * (1.0 - pc) * mu2 * inv_m, 1e-12);
    *var1_out = fmax(noise_var_mean + ph * (1.0 - ph) * mu2 * inv_m, 1e-12);
}

int eproc_sift_init(eproc_sift_t *sf,
                    uint32_t n_sites,
                    uint32_t per_site,
                    double signal_mean,
                    double noise_sd) {
    if (sf == NULL) {
        return EPROC_ERR_INVALID;
    }
    if (n_sites == 0U || n_sites > EPROC_SIFT_MAX_SITES) {
        return EPROC_ERR_INVALID;
    }
    if (per_site == 0U || per_site > EPROC_SIFT_MAX_PER_SITE) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(signal_mean) || fabs(signal_mean) <= 0.0) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(noise_sd) || !(noise_sd > 0.0)) {
        return EPROC_ERR_INVALID;
    }

    memset(sf, 0, sizeof(*sf));
    sf->n_sites = n_sites;
    sf->per_site = per_site;
    sf->prior_hot_site = 0.05;
    sf->prior_active_cold = 0.005;
    sf->prior_active_hot = 0.30;
    sf->signal_mean = signal_mean;
    sf->noise_sd = noise_sd;

    const double log_p_hot = log(sf->prior_hot_site);
    const double p_chan_0 = sf->prior_hot_site * sf->prior_active_hot
                          + (1.0 - sf->prior_hot_site) * sf->prior_active_cold;

    for (uint32_t s = 0; s < n_sites; ++s) {
        sf->site_log_prob[s] = log_p_hot;
    }
    const uint32_t total_ch = n_sites * per_site;
    for (uint32_t c = 0; c < total_ch; ++c) {
        sf->chan_prob[c] = p_chan_0;
        sf->chan_noise_scale[c] = 1.0;
    }
    return EPROC_OK;
}

int eproc_sift_set_noise_scale(eproc_sift_t *sf,
                               uint32_t channel_idx,
                               double noise_scale) {
    if (sf == NULL || channel_idx >= sf->n_sites * sf->per_site) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(noise_scale) || !(noise_scale > 0.0)) {
        return EPROC_ERR_INVALID;
    }
    sf->chan_noise_scale[channel_idx] = noise_scale;
    return EPROC_OK;
}

int eproc_sift_observe_channel(eproc_sift_t *sf,
                               uint32_t channel_idx,
                               double obs_mean,
                               uint32_t n_ticks) {
    if (sf == NULL || channel_idx >= sf->n_sites * sf->per_site || n_ticks == 0U) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(obs_mean)) {
        return EPROC_OK;
    }

    const double sd = sf->noise_sd * sf->chan_noise_scale[channel_idx];
    const double var_obs = fmax((sd * sd) / (double)n_ticks, 1e-18);
    const double mu = sf->signal_mean;

    /* Exact Gaussian LLR = log(p(obs | Z=1) / p(obs | Z=0)) */
    const double llr = eproc_clamp((mu * (obs_mean - 0.5 * mu)) / var_obs, -500.0, 500.0);

    const double lo_new = eproc_logit(sf->chan_prob[channel_idx]) + llr;
    sf->chan_prob[channel_idx] = eproc_clamp(eproc_sigmoid(lo_new), 1e-9, 1.0 - 1e-9);

    /* Propagate channel evidence upward to parent site posterior */
    const uint32_t site_idx = channel_idx / sf->per_site;
    const double lp_hot_act = eproc_logaddexp(log(sf->prior_active_hot) + llr,
                                              log(1.0 - sf->prior_active_hot));
    const double lp_cold_act = eproc_logaddexp(log(sf->prior_active_cold) + llr,
                                               log(1.0 - sf->prior_active_cold));
    const double site_llr = lp_hot_act - lp_cold_act;

    const double old_p_hot = eproc_clamp(exp(sf->site_log_prob[site_idx]), 1e-9, 1.0 - 1e-9);
    const double new_p_hot = eproc_clamp(eproc_sigmoid(eproc_logit(old_p_hot) + site_llr),
                                         1e-9, 1.0 - 1e-9);
    sf->site_log_prob[site_idx] = log(new_p_hot);

    return EPROC_OK;
}

int eproc_sift_observe_site(eproc_sift_t *sf,
                            uint32_t site_idx,
                            double site_mean) {
    if (sf == NULL || site_idx >= sf->n_sites) {
        return EPROC_ERR_INVALID;
    }
    if (!isfinite(site_mean)) {
        return EPROC_OK;
    }

    double mu0, var0, mu1, var1;
    const double sum_var = eproc_sift_site_sum_var(sf, site_idx);
    eproc_sift_site_params_from_sumvar(sf, sum_var, &mu0, &var0, &mu1, &var1);

    const double d0 = site_mean - mu0;
    const double d1 = site_mean - mu1;
    const double ll0 = -0.5 * log(var0) - 0.5 * (d0 * d0) / var0;
    const double ll1 = -0.5 * log(var1) - 0.5 * (d1 * d1) / var1;
    const double llr = eproc_clamp(ll1 - ll0, -500.0, 500.0);

    const double old_p_hot = eproc_clamp(exp(sf->site_log_prob[site_idx]), 1e-9, 1.0 - 1e-9);
    const double new_p_hot = eproc_clamp(eproc_sigmoid(eproc_logit(old_p_hot) + llr),
                                         1e-9, 1.0 - 1e-9);
    sf->site_log_prob[site_idx] = log(new_p_hot);

    /* Coherently propagate site posterior shift down to child channel priors */
    const double p_prior_old = old_p_hot * sf->prior_active_hot
                             + (1.0 - old_p_hot) * sf->prior_active_cold;
    const double p_prior_new = new_p_hot * sf->prior_active_hot
                             + (1.0 - new_p_hot) * sf->prior_active_cold;
    const double delta_lo = eproc_logit(p_prior_new) - eproc_logit(p_prior_old);

    const uint32_t base = site_idx * sf->per_site;
    for (uint32_t j = 0; j < sf->per_site; ++j) {
        const double lo = eproc_logit(sf->chan_prob[base + j]) + delta_lo;
        sf->chan_prob[base + j] = eproc_clamp(eproc_sigmoid(lo), 1e-9, 1.0 - 1e-9);
    }

    return EPROC_OK;
}

static inline void eproc_sift_eval_channel(uint32_t c,
                                           double p_c,
                                           double sd_c,
                                           double abs_mu,
                                           double mu2,
                                           double sqrt_ticks,
                                           double ticks_d,
                                           int ok_chan,
                                           double inv_c_chan,
                                           int ok_tick,
                                           double inv_c_tick,
                                           double *best_score,
                                           int32_t *best_type,
                                           uint32_t *best_target) {
    const double pq = p_c * (1.0 - p_c);
    const double sd_safe = (sd_c > 1e-12) ? sd_c : 1e-12;
    const double snr1_sq = mu2 / (sd_safe * sd_safe);

    if (ok_chan) {
        const double v1 = pq * snr1_sq;
        const double ub1 = 0.5 * v1 * inv_c_chan;
        if (ub1 * (1.0 + 1e-12) > *best_score) {
            const double ub1_log = 0.5 * log1p(v1) * inv_c_chan;
            if (ub1_log * (1.0 + 1e-12) > *best_score) {
                const double snr1 = abs_mu / sd_safe;
                const double score = eproc_gauss_mi(p_c, snr1) * inv_c_chan;
                if (score > *best_score) {
                    *best_score = score;
                    *best_type = 1;
                    *best_target = c;
                }
            }
        }
    }
    if (ok_tick) {
        const double v2 = pq * (snr1_sq * ticks_d);
        const double ub2 = 0.5 * v2 * inv_c_tick;
        if (ub2 * (1.0 + 1e-12) > *best_score) {
            const double ub2_log = 0.5 * log1p(v2) * inv_c_tick;
            if (ub2_log * (1.0 + 1e-12) > *best_score) {
                const double h_ub = eproc_bin_entropy(p_c) * inv_c_tick;
                if (h_ub * (1.0 + 1e-12) > *best_score) {
                    const double snr2 = (abs_mu / sd_safe) * sqrt_ticks;
                    const double score = eproc_gauss_mi(p_c, snr2) * inv_c_tick;
                    if (score > *best_score) {
                        *best_score = score;
                        *best_type = 2;
                        *best_target = c;
                    }
                }
            }
        }
    }
}

#if EPROC_BUILD_AVX2
EPROC_TARGET_AVX2
static void eproc_sift_scan_channels_avx2(const eproc_sift_t *sf,
                                          uint32_t total_ch,
                                          double noise_sd,
                                          double coeff_ub,
                                          double abs_mu,
                                          double mu2,
                                          double sqrt_ticks,
                                          double ticks_d,
                                          int ok_chan,
                                          double inv_c_chan,
                                          int ok_tick,
                                          double inv_c_tick,
                                          double *best_score,
                                          int32_t *best_type,
                                          uint32_t *best_target) {
    const __m256d v_one = _mm256_set1_pd(1.0);
    const __m256d v_coeff = _mm256_set1_pd(coeff_ub);
    const __m256d v_min_ns2 = _mm256_set1_pd(1e-24);
    __m256d v_best = _mm256_set1_pd(*best_score);

    uint32_t c = 0U;
    for (; c + 4U <= total_ch; c += 4U) {
        const __m256d vp = _mm256_loadu_pd(sf->chan_prob + c);
        const __m256d vns = _mm256_loadu_pd(sf->chan_noise_scale + c);
        const __m256d vpq = _mm256_mul_pd(vp, _mm256_sub_pd(v_one, vp));
        const __m256d vns2 = _mm256_max_pd(_mm256_mul_pd(vns, vns), v_min_ns2);
        /* Division-free sound B&B check: coeff_ub * p*(1-p) > best_score * ns^2 */
        const __m256d vlhs = _mm256_mul_pd(v_coeff, vpq);
        const __m256d vrhs = _mm256_mul_pd(v_best, vns2);
        const int mask = _mm256_movemask_pd(_mm256_cmp_pd(vlhs, vrhs, _CMP_GT_OQ));
        if (mask == 0) {
            continue;
        }
        for (uint32_t lane = 0U; lane < 4U; ++lane) {
            if ((mask & (1 << lane)) == 0) {
                continue;
            }
            const uint32_t idx = c + lane;
            const double prev_b = *best_score;
            eproc_sift_eval_channel(idx, sf->chan_prob[idx],
                                    noise_sd * sf->chan_noise_scale[idx],
                                    abs_mu, mu2, sqrt_ticks, ticks_d,
                                    ok_chan, inv_c_chan, ok_tick, inv_c_tick,
                                    best_score, best_type, best_target);
            if (*best_score > prev_b) {
                v_best = _mm256_set1_pd(*best_score);
            }
        }
    }
    for (; c < total_ch; ++c) {
        const double p_c = sf->chan_prob[c];
        const double ns = sf->chan_noise_scale[c];
        const double ns2 = fmax(ns * ns, 1e-24);
        if (coeff_ub * (p_c * (1.0 - p_c)) <= (*best_score) * ns2) {
            continue;
        }
        eproc_sift_eval_channel(c, p_c, noise_sd * ns,
                                abs_mu, mu2, sqrt_ticks, ticks_d,
                                ok_chan, inv_c_chan, ok_tick, inv_c_tick,
                                best_score, best_type, best_target);
    }
}
#endif

int eproc_sift_select_next(const eproc_sift_t *sf,
                           double cost_site,
                           double cost_channel,
                           double cost_ticks,
                           uint32_t ticks_per_read,
                           eproc_sift_action_t *out) {
    if (sf == NULL || out == NULL || ticks_per_read == 0U) {
        return EPROC_ERR_INVALID;
    }
    const int ok_site = isfinite(cost_site) && cost_site > 0.0;
    const int ok_chan = isfinite(cost_channel) && cost_channel > 0.0;
    const int ok_tick = isfinite(cost_ticks) && cost_ticks > 0.0;
    if (!ok_site && !ok_chan && !ok_tick) {
        return EPROC_ERR_INVALID;
    }

    int32_t best_type = ok_site ? 0 : (ok_chan ? 1 : 2);
    uint32_t best_target = 0U;
    double best_score = -1.0;

    const double abs_mu = fabs(sf->signal_mean);
    const double mu2 = abs_mu * abs_mu;
    const double ticks_d = (double)ticks_per_read;
    const double sqrt_ticks = sqrt(ticks_d);
    const double h_act_hot = eproc_bin_entropy(sf->prior_active_hot);
    const double h_act_cold = eproc_bin_entropy(sf->prior_active_cold);

    /* Action type 0: coarse site-mean reads with exact cache + Gaussian capacity B&B */
    if (ok_site) {
        const double inv_cost = 1.0 / cost_site;
        const double m = (double)sf->per_site;
        const double d_mu_sq = (sf->prior_active_hot - sf->prior_active_cold)
                             * (sf->prior_active_hot - sf->prior_active_cold) * mu2;

        /* Remember first/prior evaluated site state to skip identical cold sites in O(1) */
        int has_cache = 0;
        double cache_lp = 0.0;
        double cache_sumvar = 0.0;

        for (uint32_t s = 0; s < sf->n_sites; ++s) {
            const double lp = sf->site_log_prob[s];
            const double sum_var = eproc_sift_site_sum_var(sf, s);
            if (has_cache && lp == cache_lp && sum_var == cache_sumvar) {
                /* Identical (lp, sum_var) has exact same score <= best_score (ties keep lower index) */
                continue;
            }

            const double p_hot = eproc_clamp(exp(lp), 1e-9, 1.0 - 1e-9);
            double mu0, var0, mu1, var1;
            eproc_sift_site_params_from_sumvar(sf, sum_var, &mu0, &var0, &mu1, &var1);
            const double var_eff = fmax(0.5 * (var0 + var1), 1e-24);
            const double d_site_sq = d_mu_sq / var_eff;

            /* Exact upper bound: M * (I(Z_c; H_s) / H_2(H_s)) * I(H_s; Y_s)
             * <= M * I(H_s; Y_s) <= M * 0.5 * p_hot * (1 - p_hot) * d_site^2 */
            const double ub_site = m * 0.5 * p_hot * (1.0 - p_hot) * d_site_sq * inv_cost;
            if (ub_site * (1.0 + 1e-12) <= best_score) {
                continue;
            }

            const double h_site = eproc_bin_entropy(p_hot);
            if (!(h_site > 1e-12)) {
                continue;
            }

            const double p_ch_site = p_hot * sf->prior_active_hot
                                   + (1.0 - p_hot) * sf->prior_active_cold;
            const double h_ch_cond = p_hot * h_act_hot + (1.0 - p_hot) * h_act_cold;
            double mi_ch_given_h = eproc_bin_entropy(p_ch_site) - h_ch_cond;
            if (mi_ch_given_h <= 0.0) {
                continue;
            }

            const double ub_tight = m * mi_ch_given_h
                                  * fmin(1.0, 0.5 * log1p(p_hot * (1.0 - p_hot) * d_site_sq) / h_site)
                                  * inv_cost;
            if (ub_tight * (1.0 + 1e-12) <= best_score) {
                continue;
            }

            const double d_site = sqrt(d_site_sq);
            const double mi_site = eproc_gauss_mi(p_hot, d_site);
            const double evoi = m * mi_ch_given_h * (mi_site / h_site);
            const double score = evoi * inv_cost;
            if (!has_cache) {
                has_cache = 1;
                cache_lp = lp;
                cache_sumvar = sum_var;
            }
            if (score > best_score) {
                best_score = score;
                best_type = 0;
                best_target = s;
                cache_lp = lp;
                cache_sumvar = sum_var;
            }
        }
    }

    /* Action types 1 & 2: Exact Gaussian Max-Entropy Branch-and-Bound with AVX2 4-wide pre-filter */
    if (ok_chan || ok_tick) {
        const uint32_t total_ch = sf->n_sites * sf->per_site;
        const double inv_c_chan = ok_chan ? (1.0 / cost_channel) : 0.0;
        const double inv_c_tick = ok_tick ? (1.0 / cost_ticks) : 0.0;
        const double eff_inv = (ticks_d * inv_c_tick > inv_c_chan)
            ? (ticks_d * inv_c_tick)
            : inv_c_chan;
        const double noise_sd = sf->noise_sd;
        const double ns_var = fmax(noise_sd * noise_sd, 1e-24);
        /* Unified sound upper bound for both 1-tick & T-tick:
         * max(ub1, ub2) <= (0.5 * mu^2 * eff_inv / noise_sd^2) * p*(1-p) / chan_noise_scale^2 */
        const double coeff_ub = 0.5 * (mu2 / ns_var) * eff_inv * (1.0 + 1e-12);

#if EPROC_BUILD_AVX2
        if (eproc_use_avx2()) {
            eproc_sift_scan_channels_avx2(sf, total_ch, noise_sd, coeff_ub,
                                          abs_mu, mu2, sqrt_ticks, ticks_d,
                                          ok_chan, inv_c_chan, ok_tick, inv_c_tick,
                                          &best_score, &best_type, &best_target);
        } else
#endif
        {
#if !EPROC_STATIC_AVX2
            for (uint32_t c = 0U; c < total_ch; ++c) {
                const double p_c = sf->chan_prob[c];
                const double ns = sf->chan_noise_scale[c];
                const double ns2 = fmax(ns * ns, 1e-24);
                if (coeff_ub * (p_c * (1.0 - p_c)) <= best_score * ns2) {
                    continue;
                }
                eproc_sift_eval_channel(c, p_c, noise_sd * ns,
                                        abs_mu, mu2, sqrt_ticks, ticks_d,
                                        ok_chan, inv_c_chan, ok_tick, inv_c_tick,
                                        &best_score, &best_type, &best_target);
            }
#endif
        }
    }

    out->action_type = best_type;
    out->target_idx = best_target;
    out->evoi_per_cost = (best_score > 0.0) ? best_score : 0.0;
    return EPROC_OK;
}

/* ============================================================================
 * 4D. ABI VERSION & RUNTIME SIMD CAPABILITY FLAGS
 * ============================================================================ */

uint32_t eproc_abi_version(void) {
    return EPROC_ABI_VERSION;
}

uint32_t eproc_simd_flags(void) {
    uint32_t flags = 0U;
    if (eproc_use_avx2()) {
        flags |= 1U;
    }
#if defined(__FMA__)
    flags |= 2U;
#endif
#if defined(__ARM_NEON) || defined(__aarch64__)
    flags |= 4U;
#endif
    return flags;
}



#endif /* EPROC_IMPLEMENTATION_INCLUDED */

#endif /* EPROC_IMPLEMENTATION */
