Skip to content

Run Module

The xpyrment.run module contains submodules and components for run.

run

Live experiment runtime execution, data ingestion, monitoring, and sequential stopping.

This package manages the execution phase of xpyrment. It provides the operational scaffolding for ingesting raw telemetry datasets, logging and deduplicating variant exposures, monitoring cumulative allocations in real-time, and evaluating continuous early-stopping rules.

Submodules: - ingestion: Connectors and schema gates to import SQL datasets or pandas DataFrames. - assignment: Records variant exposures, enforcing first-touch attribution for causal safety. - monitor: Aggregates active traffic into binned time-series metrics for real-time dashboards and audits. - stopping: Implements mixture Sequential Probability Ratio Tests (mSPRTs) for continuous peeking and safe early-stopping.

MODULE DESCRIPTION
assignment

Live experiment assignment tracking and first-touch deduplication.

hub
ingestion

Data ingestion adapters, validation gates, and normalization utilities.

monitor

Live telemetry monitoring, cumulative traffic accumulation, and telemetry audit feeds.

stopping

Mixture Sequential Probability Ratio Test (mSPRT) sequential stopping rules.

webui

Standalone HTTP Web-UI dashboard server for real-time digital experiment monitoring.

CLASS DESCRIPTION
AssignmentLogger

Manages tracking live assignment exposures and deduplicating multiple logs.

LiveMonitor

Provides active monitoring of experimental groups to build diagnostics dashboards.

StoppingRules

Implements early-stopping rules like mixture sequential probability ratio tests (mSPRT).

ExperimentDashboardServer

Hosts an interactive Web-UI dashboard to monitor running experiments.

FUNCTION DESCRIPTION
ingest_dataframe

Ingests, validates, and copies an in-memory pandas DataFrame into the xpyrment lifecycle.

load_from_sql

Loads experimental telemetry and assignment logs from an external relational SQL database.

AssignmentLogger

AssignmentLogger()

Manages tracking live assignment exposures and deduplicating multiple logs.

In live online systems, users can trigger assignment events repeatedly (e.g., refreshing a page or navigating back to a screen). For rigorous statistical evaluation, we must identify and lock the exact moment of initial exposure for each unit.

First-Touch Attribution and Causal Ordering

To establish a valid causal relationship, any metric event \(Y\) must occur after the initial exposure to the treatment \(T\): $$ t_{\text{metric}} \ge t_{\text{initial_exposure}} $$ If we attribute a user's metric events to their assignment using a later exposure timestamp, we violate this temporal sequence, potentially including pre-treatment behavior in our post-treatment metric calculations, introducing severe selection bias.

The AssignmentLogger records all exposure events and deduplicates them by sorting chronologically and retaining only the earliest occurrence per unit.

Pseudocode for first-touch deduplication
function get_deduplicated_exposures(exposures_list):
    1. Convert exposures_list to DataFrame.
    2. Sort DataFrame by "timestamp" in ascending order.
    3. Drop duplicate rows where "unit_id" is identical, keeping the first occurrence.
    4. Return the cleaned DataFrame.
METHOD DESCRIPTION
log_assignment

Logs an assignment exposure event.

get_deduplicated_exposures

Deduplicates multiple logs of the same unit_id, keeping only the earliest exposure.

Source code in src\xpyrment\run\assignment.py
def __init__(self):
    """Initializes an empty AssignmentLogger."""
    self._exposures = []

log_assignment

log_assignment(unit_id: str, variant: str, timestamp: str)

Logs an assignment exposure event.

PARAMETER DESCRIPTION
unit_id

Unique identifier of the experimental unit (e.g. user_id, cookie_id).

TYPE: str

variant

The assigned variant label (e.g. "control", "treatment_a").

TYPE: str

timestamp

ISO-8601 or epoch timestamp when the exposure occurred.

TYPE: str

Source code in src\xpyrment\run\assignment.py
def log_assignment(self, unit_id: str, variant: str, timestamp: str):
    """Logs an assignment exposure event.

    Args:
        unit_id (str): Unique identifier of the experimental unit (e.g. user_id, cookie_id).
        variant (str): The assigned variant label (e.g. "control", "treatment_a").
        timestamp (str): ISO-8601 or epoch timestamp when the exposure occurred.
    """
    self._exposures.append({
        "unit_id": unit_id,
        "variant": variant,
        "timestamp": timestamp
    })

get_deduplicated_exposures

get_deduplicated_exposures() -> DataFrame

Deduplicates multiple logs of the same unit_id, keeping only the earliest exposure.

This enforces the first-touch exposure model, establishing a robust temporal baseline for subsequent metric windowing and causal analysis.

RETURNS DESCRIPTION
DataFrame

pd.DataFrame: A pandas DataFrame containing unique unit_id rows, with their original earliest variant and timestamp.

Source code in src\xpyrment\run\assignment.py
def get_deduplicated_exposures(self) -> pd.DataFrame:
    """Deduplicates multiple logs of the same unit_id, keeping only the earliest exposure.

    This enforces the first-touch exposure model, establishing a robust temporal baseline for
    subsequent metric windowing and causal analysis.

    Returns:
        pd.DataFrame: A pandas DataFrame containing unique `unit_id` rows, with their original
            earliest `variant` and `timestamp`.
    """
    df = pd.DataFrame(self._exposures)
    if df.empty:
        return df
    return df.sort_values("timestamp").drop_duplicates(subset=["unit_id"], keep="first")

LiveMonitor

LiveMonitor(
    df: DataFrame,
    time_col: str,
    dispatcher: Optional[WebhookAlertDispatcher] = None,
)

Provides active monitoring of experimental groups to build diagnostics dashboards.

Accumulates exposure logs chronologically to generate time-series metrics. By evaluating traffic trends in real time, experimenters can verify that the randomization splits remain stable and that no asymmetric telemetry dropouts or scheduling anomalies occur.

Temporal Binning and Accumulation Theory

Let there be \(k\) variants. Let the experimental logs be grouped into sequential, non-overlapping temporal intervals (bins) \(t \in \{1, 2, \dots, H\}\) (such as hours or days). - Let \(n_v(t)\) be the number of unique units newly exposed to variant \(v\) during time bin \(t\). - The cumulative traffic \(C_v(t)\) for variant \(v\) up to time bin \(t\) is calculated as: $$ C_v(t) = \sum_{\tau=1}^{t} n_v(\tau) $$ The ratio of cumulative traffic across variants should remain statistically stable and proportional to the designed allocation ratios. A sudden shift or step-function deviation in: $$ R(t) = \frac{C_{\text{treatment}}(t)}{C_{\text{control}}(t)} $$ indicates a critical operational failure (e.g., treatment servers crashing, CDN configuration issues, or regional tracking bugs).

Pseudocode for Binning and Accumulation
function get_cumulative_traffic(df, time_col, variant_col, bin_frequency):
    1. Truncate timestamps in time_col to the specified bin_frequency (e.g., 'H' for Hour, 'D' for Day).
    2. Group by binned time and variant_col, calculating count of unique units.
    3. Pivot the grouped DataFrame to have binned time as index and variant names as columns.
    4. Fill missing values with 0.
    5. Compute cumulative sums along the rows (axis=0) for each column.
    6. Return the resulting cumulative DataFrame.
ATTRIBUTE DESCRIPTION
df

Raw log DataFrame containing exposure details.

TYPE: DataFrame

time_col

Name of the column containing assignment timestamps.

TYPE: str

dispatcher

Alert dispatcher.

TYPE: Optional[WebhookAlertDispatcher]

shutoff_triggered

Status flag indicating whether an active SRM or critical alert has suspended assignment.

TYPE: bool

PARAMETER DESCRIPTION
df

The experimental dataset.

TYPE: DataFrame

time_col

The column representing assignment timestamps.

TYPE: str

dispatcher

Alert dispatcher. Defaults to None.

TYPE: Optional[WebhookAlertDispatcher] DEFAULT: None

METHOD DESCRIPTION
get_cumulative_traffic

Calculates cumulative traffic counts over time for each variant.

get_binned_traffic

Calculates binned (non-cumulative) traffic counts over time for each variant.

check_traffic_anomaly

Performs a Z-score anomaly test on non-cumulative temporal traffic volumes.

check_live_srm

Calculates cumulative chi-square p-value and SRM flagging on the latest cumulative traffic.

check_sequential_srm

Runs Wald's SPRT on the assignment series.

run_telemetry_checks

Runs traffic anomaly, cumulative SRM, and sequential SRM checks, dispatching alerts if needed.

Source code in src\xpyrment\run\monitor.py
def __init__(self, df: pd.DataFrame, time_col: str, dispatcher: Optional[WebhookAlertDispatcher] = None):
    """Initializes a LiveMonitor.

    Args:
        df (pd.DataFrame): The experimental dataset.
        time_col (str): The column representing assignment timestamps.
        dispatcher (Optional[WebhookAlertDispatcher]): Alert dispatcher. Defaults to None.
    """
    self.df = df
    self.time_col = time_col
    self.dispatcher = dispatcher
    self.shutoff_triggered = False

get_cumulative_traffic

get_cumulative_traffic(
    variant_col: str = "variant", freq: str = "D"
) -> DataFrame

Calculates cumulative traffic counts over time for each variant.

Processes and groups timestamps, returning a cumulative summation matrix suitable for charting and structural allocation audits.

PARAMETER DESCRIPTION
variant_col

Column representing treatment assignment groups. Defaults to "variant".

TYPE: str DEFAULT: 'variant'

freq

Binning frequency (e.g., "h" for Hour, "D" for Day). Defaults to "D".

TYPE: str DEFAULT: 'D'

RETURNS DESCRIPTION
DataFrame

pd.DataFrame: A pandas DataFrame indexed by time bins, with columns representing variants and cells containing cumulative exposure counts.

Source code in src\xpyrment\run\monitor.py
def get_cumulative_traffic(self, variant_col: str = "variant", freq: str = "D") -> pd.DataFrame:
    """Calculates cumulative traffic counts over time for each variant.

    Processes and groups timestamps, returning a cumulative summation matrix suitable
    for charting and structural allocation audits.

    Args:
        variant_col (str): Column representing treatment assignment groups. Defaults to "variant".
        freq (str): Binning frequency (e.g., "h" for Hour, "D" for Day). Defaults to "D".

    Returns:
        pd.DataFrame: A pandas DataFrame indexed by time bins, with columns representing
            variants and cells containing cumulative exposure counts.
    """
    binned = self.get_binned_traffic(variant_col=variant_col, freq=freq)
    cumulative = binned.cumsum(axis=0)
    return cumulative

get_binned_traffic

get_binned_traffic(
    variant_col: str = "variant", freq: str = "D"
) -> DataFrame

Calculates binned (non-cumulative) traffic counts over time for each variant.

Processes and groups timestamps, returning a non-cumulative summation matrix indexed by time bins with variants as columns.

PARAMETER DESCRIPTION
variant_col

Column representing treatment assignment groups. Defaults to "variant".

TYPE: str DEFAULT: 'variant'

freq

Binning frequency (e.g., "h" for Hour, "D" for Day). Defaults to "D".

TYPE: str DEFAULT: 'D'

RETURNS DESCRIPTION
DataFrame

pd.DataFrame: A pandas DataFrame indexed by time bins, with columns representing variants and cells containing binned exposure counts.

Source code in src\xpyrment\run\monitor.py
def get_binned_traffic(self, variant_col: str = "variant", freq: str = "D") -> pd.DataFrame:
    """Calculates binned (non-cumulative) traffic counts over time for each variant.

    Processes and groups timestamps, returning a non-cumulative summation matrix
    indexed by time bins with variants as columns.

    Args:
        variant_col (str): Column representing treatment assignment groups. Defaults to "variant".
        freq (str): Binning frequency (e.g., "h" for Hour, "D" for Day). Defaults to "D".

    Returns:
        pd.DataFrame: A pandas DataFrame indexed by time bins, with columns representing
            variants and cells containing binned exposure counts.
    """
    binned_df = self.df.copy()
    binned_df["binned_time"] = pd.to_datetime(binned_df[self.time_col]).dt.floor(freq)

    # Group by binned time and variant, counting unique units
    unit_col = "unit_id" if "unit_id" in binned_df.columns else binned_df.columns[0]
    grouped = binned_df.groupby(["binned_time", variant_col])[unit_col].nunique().reset_index()

    # Pivot to place variants as columns
    pivoted = grouped.pivot(index="binned_time", columns=variant_col, values=unit_col)

    # Fill missing time slots with 0
    binned = pivoted.fillna(0.0)
    return binned

check_traffic_anomaly

check_traffic_anomaly(
    variant_col: str = "variant",
    freq: str = "D",
    window: int = 7,
    z_threshold: float = 3.0,
    drop_threshold: float = 0.5,
) -> Dict[str, Any]

Performs a Z-score anomaly test on non-cumulative temporal traffic volumes.

Calculates the unique units per time bin, and checks if the latest bin represents a significant traffic drop compared to the simple moving average and standard deviation of the preceding window.

Z-Score Traffic Drop Check Theory

Let \(x_t\) be the total unique units exposed across all variants in time bin \(t\). For a history window of size \(W\), the baseline mean \(\mu_T\) and sample standard deviation \(\sigma_T\) of the preceding window are computed as: $$ \mu_T = \frac{1}{K} \sum_{\tau=1}^{K} x_{T-\tau} $$ $$ \sigma_T = \sqrt{\frac{1}{K-1} \sum_{\tau=1}^{K} (x_{T-\tau} - \mu_T)^2} $$ where \(K = \min(T-1, W)\). The Z-score for the latest bin \(x_T\) is defined as: $$ Z = \frac{x_T - \mu_T}{\sigma_T} $$ If \(\sigma_T > 0\) and \(Z < -z_{\text{threshold}}\), a sudden traffic drop anomaly is flagged. If \(\sigma_T = 0\), a fallback check flags an anomaly if: $$ x_T < \mu_T \cdot (1 - \text{drop_threshold}) $$

PARAMETER DESCRIPTION
variant_col

Column representing treatment groups.

TYPE: str DEFAULT: 'variant'

freq

Binning frequency.

TYPE: str DEFAULT: 'D'

window

Moving window size for baseline computation.

TYPE: int DEFAULT: 7

z_threshold

Z-score threshold for drop detection (must be positive).

TYPE: float DEFAULT: 3.0

drop_threshold

Percentage threshold drop fallback if variance is 0.

TYPE: float DEFAULT: 0.5

RETURNS DESCRIPTION
Dict[str, Any]

Dict[str, Any]: Dict containing keys: - anomaly_detected (bool) - latest_volume (float) - historical_mean (float) - historical_std (float) - z_score (float) - message (str)

Source code in src\xpyrment\run\monitor.py
def check_traffic_anomaly(
    self,
    variant_col: str = "variant",
    freq: str = "D",
    window: int = 7,
    z_threshold: float = 3.0,
    drop_threshold: float = 0.5
) -> Dict[str, Any]:
    r"""Performs a Z-score anomaly test on non-cumulative temporal traffic volumes.

    Calculates the unique units per time bin, and checks if the latest bin represents
    a significant traffic drop compared to the simple moving average and standard deviation
    of the preceding window.

    ??? mathbox "Z-Score Traffic Drop Check Theory"

        Let $x_t$ be the total unique units exposed across all variants in time bin $t$.
        For a history window of size $W$, the baseline mean $\mu_T$ and sample standard deviation $\sigma_T$
        of the preceding window are computed as:
        $$
        \mu_T = \frac{1}{K} \sum_{\tau=1}^{K} x_{T-\tau}
        $$
        $$
        \sigma_T = \sqrt{\frac{1}{K-1} \sum_{\tau=1}^{K} (x_{T-\tau} - \mu_T)^2}
        $$
        where $K = \min(T-1, W)$.
        The Z-score for the latest bin $x_T$ is defined as:
        $$
        Z = \frac{x_T - \mu_T}{\sigma_T}
        $$
        If $\sigma_T > 0$ and $Z < -z_{\text{threshold}}$, a sudden traffic drop anomaly is flagged.
        If $\sigma_T = 0$, a fallback check flags an anomaly if:
        $$
        x_T < \mu_T \cdot (1 - \text{drop\_threshold})
        $$

    Args:
        variant_col (str): Column representing treatment groups.
        freq (str): Binning frequency.
        window (int): Moving window size for baseline computation.
        z_threshold (float): Z-score threshold for drop detection (must be positive).
        drop_threshold (float): Percentage threshold drop fallback if variance is 0.

    Returns:
        Dict[str, Any]: Dict containing keys:
            - anomaly_detected (bool)
            - latest_volume (float)
            - historical_mean (float)
            - historical_std (float)
            - z_score (float)
            - message (str)
    """
    binned = self.get_binned_traffic(variant_col=variant_col, freq=freq)
    if binned.empty:
        return {
            "anomaly_detected": False,
            "latest_volume": 0.0,
            "historical_mean": 0.0,
            "historical_std": 0.0,
            "z_score": 0.0,
            "message": "Traffic DataFrame is empty."
        }

    # Sum unique units across all variants per time bin
    volumes = binned.sum(axis=1).values
    n_bins = len(volumes)

    if n_bins < 3:
        return {
            "anomaly_detected": False,
            "latest_volume": float(volumes[-1]),
            "historical_mean": float(np.mean(volumes[:-1])) if n_bins > 1 else 0.0,
            "historical_std": 0.0,
            "z_score": 0.0,
            "message": "Insufficient history to stably calculate baseline standard deviation (need at least 3 bins)."
        }

    latest_volume = float(volumes[-1])
    # Historical baseline: preceding window excluding the latest bin
    k = min(n_bins - 1, window)
    baseline = volumes[-(k+1):-1]

    mean = float(np.mean(baseline))
    std = float(np.std(baseline, ddof=1))

    if std == 0.0:
        anomaly = latest_volume < mean * (1.0 - drop_threshold)
        return {
            "anomaly_detected": anomaly,
            "latest_volume": latest_volume,
            "historical_mean": mean,
            "historical_std": std,
            "z_score": 0.0,
            "message": f"Degenerate variance (std=0). Drop check fallback applied: {anomaly}."
        }

    z_score = (latest_volume - mean) / std
    anomaly = z_score < -z_threshold

    return {
        "anomaly_detected": anomaly,
        "latest_volume": latest_volume,
        "historical_mean": mean,
        "historical_std": std,
        "z_score": z_score,
        "message": f"Z-score = {z_score:.4f}. Anomaly detected: {anomaly}."
    }

check_live_srm

check_live_srm(
    expected_ratios: List[float],
    variant_col: str = "variant",
) -> Dict[str, Any]

Calculates cumulative chi-square p-value and SRM flagging on the latest cumulative traffic.

PARAMETER DESCRIPTION
expected_ratios

Target allocation proportions/ratios.

TYPE: List[float]

variant_col

Column representing treatment assignment groups.

TYPE: str DEFAULT: 'variant'

RETURNS DESCRIPTION
Dict[str, Any]

Dict[str, Any]: Dict containing keys: - srm_detected (bool) - p_value (float) - observed_counts (List[int]) - expected_ratios (List[float]) - message (str)

Source code in src\xpyrment\run\monitor.py
def check_live_srm(self, expected_ratios: List[float], variant_col: str = "variant") -> Dict[str, Any]:
    """Calculates cumulative chi-square p-value and SRM flagging on the latest cumulative traffic.

    Args:
        expected_ratios (List[float]): Target allocation proportions/ratios.
        variant_col (str): Column representing treatment assignment groups.

    Returns:
        Dict[str, Any]: Dict containing keys:
            - srm_detected (bool)
            - p_value (float)
            - observed_counts (List[int])
            - expected_ratios (List[float])
            - message (str)
    """
    cumulative = self.get_cumulative_traffic(variant_col=variant_col)
    if cumulative.empty:
        return {
            "srm_detected": False,
            "p_value": 1.0,
            "observed_counts": [],
            "expected_ratios": expected_ratios,
            "message": "Cumulative traffic DataFrame is empty."
        }

    cumulative = cumulative.reindex(columns=sorted(cumulative.columns))
    observed_counts = [int(x) for x in cumulative.iloc[-1].values]

    if len(observed_counts) != len(expected_ratios):
        raise ValueError(
            f"Number of observed variants ({len(observed_counts)}) does not match "
            f"number of expected ratios ({len(expected_ratios)})."
        )

    from xpyrment.validate.srm import check_srm
    from xpyrment.core.exceptions import SRMError
    from scipy import stats

    total_observed = sum(observed_counts)
    sum_ratios = sum(expected_ratios)
    expected_counts = [ratio * total_observed / sum_ratios for ratio in expected_ratios]
    if total_observed > 0:
        _, p_val = stats.chisquare(f_obs=observed_counts, f_exp=expected_counts)
    else:
        p_val = 1.0

    try:
        check_srm(observed_counts, expected_ratios)
        srm_detected = False
        message = f"No SRM detected. p-value = {p_val:.4f}"
    except SRMError as e:
        srm_detected = True
        message = str(e)

    return {
        "srm_detected": srm_detected,
        "p_value": float(p_val),
        "observed_counts": observed_counts,
        "expected_ratios": expected_ratios,
        "message": message
    }

check_sequential_srm

check_sequential_srm(
    variant_col: str = "variant",
    target_treatment_ratio: float = 0.5,
    delta: float = 0.02,
    alpha: float = 0.01,
) -> Dict[str, Any]

Runs Wald's SPRT on the assignment series.

Sequential Sample Ratio Mismatch SPRT Theory

Wald's Sequential Probability Ratio Test (SPRT) is applied to the assignment sequence \(y_1, y_2, \dots, y_N\) where \(y_i \in \{0, 1\}\) (0 = control, 1 = treatment). The likelihood ratio \(LR_N\) at step \(N\) is calculated under a mixture of alternative hypotheses: $$ LR_N = 0.5 \cdot \prod_{i=1}^N \frac{f(y_i \mid p_0 + \delta)}{f(y_i \mid p_0)} + 0.5 \cdot \prod_{i=1}^N \frac{f(y_i \mid p_0 - \delta)}{f(y_i \mid p_0)} $$ where \(p_0\) is the target treatment allocation ratio. If \(LR_N \ge \frac{1}{\alpha}\), the null hypothesis of balanced allocation is rejected, indicating a sample ratio mismatch.

PARAMETER DESCRIPTION
variant_col

Column representing treatment assignment groups.

TYPE: str DEFAULT: 'variant'

target_treatment_ratio

Target allocation ratio for the treatment group.

TYPE: float DEFAULT: 0.5

delta

SPRT mismatch shift boundary.

TYPE: float DEFAULT: 0.02

alpha

SPRT Type I error threshold boundary.

TYPE: float DEFAULT: 0.01

RETURNS DESCRIPTION
Dict[str, Any]

Dict[str, Any]: Dict containing keys: - srm_detected (bool) - running_likelihood_ratios (np.ndarray) - stopped_index (int) - message (str)

Source code in src\xpyrment\run\monitor.py
def check_sequential_srm(
    self,
    variant_col: str = "variant",
    target_treatment_ratio: float = 0.5,
    delta: float = 0.02,
    alpha: float = 0.01
) -> Dict[str, Any]:
    r"""Runs Wald's SPRT on the assignment series.

    ??? mathbox "Sequential Sample Ratio Mismatch SPRT Theory"

        Wald's Sequential Probability Ratio Test (SPRT) is applied to the assignment sequence $y_1, y_2, \dots, y_N$
        where $y_i \in \{0, 1\}$ (0 = control, 1 = treatment).
        The likelihood ratio $LR_N$ at step $N$ is calculated under a mixture of alternative hypotheses:
        $$
        LR_N = 0.5 \cdot \prod_{i=1}^N \frac{f(y_i \mid p_0 + \delta)}{f(y_i \mid p_0)} + 0.5 \cdot \prod_{i=1}^N \frac{f(y_i \mid p_0 - \delta)}{f(y_i \mid p_0)}
        $$
        where $p_0$ is the target treatment allocation ratio.
        If $LR_N \ge \frac{1}{\alpha}$, the null hypothesis of balanced allocation is rejected, indicating a sample ratio mismatch.

    Args:
        variant_col (str): Column representing treatment assignment groups.
        target_treatment_ratio (float): Target allocation ratio for the treatment group.
        delta (float): SPRT mismatch shift boundary.
        alpha (float): SPRT Type I error threshold boundary.

    Returns:
        Dict[str, Any]: Dict containing keys:
            - srm_detected (bool)
            - running_likelihood_ratios (np.ndarray)
            - stopped_index (int)
            - message (str)
    """
    unique_variants = sorted(self.df[variant_col].dropna().unique())
    if len(unique_variants) != 2:
        logger.warning("Sequential SRM (SPRT) is only supported for two-arm (binary) experiments.")
        return {
            "srm_detected": False,
            "message": "Sequential SRM SPRT is only supported for exactly two variants."
        }

    control_val = unique_variants[0]
    treatment_val = unique_variants[1]
    for v in unique_variants:
        if "ctrl" in str(v).lower() or "control" in str(v).lower():
            control_val = v
            treatment_val = [x for x in unique_variants if x != v][0]
            break

    sorted_df = self.df.dropna(subset=[self.time_col, variant_col]).sort_values(by=self.time_col)
    if sorted_df.empty:
        return {
            "srm_detected": False,
            "message": "No assignment data available."
        }

    assignments = np.where(sorted_df[variant_col] == treatment_val, 1, 0)

    from xpyrment.analyze.srm import SampleRatioMismatchDetector
    detector = SampleRatioMismatchDetector(target_treatment_ratio=target_treatment_ratio)
    res = detector.test_sequential(assignments, delta=delta, alpha=alpha)

    return {
        "srm_detected": bool(res["srm_detected"]),
        "running_likelihood_ratios": res["running_likelihood_ratios"],
        "stopped_index": int(res["stopped_index"]),
        "message": f"Sequential SPRT finished. SRM detected: {res['srm_detected']} at index {res['stopped_index']}."
    }

run_telemetry_checks

run_telemetry_checks(
    expected_ratios: List[float],
    variant_col: str = "variant",
    freq: str = "D",
    window: int = 7,
    z_threshold: float = 3.0,
) -> Dict[str, Any]

Runs traffic anomaly, cumulative SRM, and sequential SRM checks, dispatching alerts if needed.

PARAMETER DESCRIPTION
expected_ratios

Target allocation proportions/ratios.

TYPE: List[float]

variant_col

Column representing treatment assignment groups.

TYPE: str DEFAULT: 'variant'

freq

Binning frequency.

TYPE: str DEFAULT: 'D'

window

Moving window size for traffic anomaly check.

TYPE: int DEFAULT: 7

z_threshold

Z-score threshold for drop detection.

TYPE: float DEFAULT: 3.0

RETURNS DESCRIPTION
Dict[str, Any]

Dict[str, Any]: Combined results of all checks.

Source code in src\xpyrment\run\monitor.py
def run_telemetry_checks(
    self,
    expected_ratios: List[float],
    variant_col: str = "variant",
    freq: str = "D",
    window: int = 7,
    z_threshold: float = 3.0
) -> Dict[str, Any]:
    """Runs traffic anomaly, cumulative SRM, and sequential SRM checks, dispatching alerts if needed.

    Args:
        expected_ratios (List[float]): Target allocation proportions/ratios.
        variant_col (str): Column representing treatment assignment groups.
        freq (str): Binning frequency.
        window (int): Moving window size for traffic anomaly check.
        z_threshold (float): Z-score threshold for drop detection.

    Returns:
        Dict[str, Any]: Combined results of all checks.
    """
    anomaly_res = self.check_traffic_anomaly(
        variant_col=variant_col, freq=freq, window=window, z_threshold=z_threshold
    )

    live_srm_res = self.check_live_srm(expected_ratios=expected_ratios, variant_col=variant_col)

    seq_srm_res = {"srm_detected": False, "message": "SPRT bypassed (unsupported multi-arm)."}
    unique_variants = sorted(self.df[variant_col].dropna().unique())
    if len(unique_variants) == 2:
        target_treatment_ratio = expected_ratios[1] / sum(expected_ratios)
        seq_srm_res = self.check_sequential_srm(
            variant_col=variant_col,
            target_treatment_ratio=target_treatment_ratio
        )

    alerts_triggered = []

    if anomaly_res["anomaly_detected"]:
        alerts_triggered.append("TRAFFIC_DROP_ANOMALY")
        if self.dispatcher:
            self.dispatcher.dispatch(
                alert_type="TRAFFIC_DROP_ANOMALY",
                message=f"Traffic dropout anomaly detected in the latest bin! {anomaly_res['message']}",
                payload=anomaly_res
            )

    if live_srm_res["srm_detected"]:
        alerts_triggered.append("SRM_SHUTOFF_TRIGGERED")
        self.shutoff_triggered = True
        if self.dispatcher:
            self.dispatcher.dispatch(
                alert_type="SRM_SHUTOFF_TRIGGERED",
                message=f"Critical Sample Ratio Mismatch (SRM) detected! Shutoff triggered. {live_srm_res['message']}",
                payload=live_srm_res
            )

    if seq_srm_res.get("srm_detected", False):
        alerts_triggered.append("SEQUENTIAL_SRM_TRIGGERED")
        self.shutoff_triggered = True
        if self.dispatcher:
            self.dispatcher.dispatch(
                alert_type="SEQUENTIAL_SRM_TRIGGERED",
                message=f"Sequential SPRT Sample Ratio Mismatch detected! Shutoff triggered. {seq_srm_res['message']}",
                payload=seq_srm_res
            )

    return {
        "shutoff_triggered": self.shutoff_triggered,
        "alerts_triggered": alerts_triggered,
        "traffic_anomaly": anomaly_res,
        "cumulative_srm": live_srm_res,
        "sequential_srm": seq_srm_res
    }

StoppingRules

StoppingRules(alpha: float = 0.05)

Implements early-stopping rules like mixture sequential probability ratio tests (mSPRT).

In traditional fixed-sample A/B testing, peeking at the results before the planned sample size is reached and stopping the test early if the p-value is significant severely inflates the Type I error rate (the peeking problem). mSPRT solves this by constructing a sequence of likelihood ratios that form a non-negative martingale.

Mathematical Theory and Martingale Boundaries

Under the null hypothesis \(H_0\) (no effect), the mixture likelihood ratio sequence \(\Lambda_n\) is a martingale with expected value \(E[\Lambda_n] = 1\). By Doob's Martingale Inequality, the probability that the likelihood ratio ever exceeds a critical threshold \(1/\alpha\) at any point in the infinite sequence is strictly bounded by \(\alpha\): $$ P\left( \sup_{n \ge 1} \Lambda_n \ge \frac{1}{\alpha} \right) \le \alpha $$ This properties allows experimenters to continuously monitor ("peek at") the data in real-time. If the likelihood ratio crosses the boundary, they can stop the experiment immediately with a mathematically guaranteed Type I error rate controlled at \(\alpha\).

Likelihood Ratio Formulation (\(\Lambda_n\))

For a continuous metric with cumulative sample variance \(\sigma^2\) and a normal mixing distribution \(H(\theta) = \mathcal{N}(0, \tau^2)\) over the expected effect size \(\theta\), the mixture likelihood ratio at accumulated sample size \(n\) is calculated as: $$ \Lambda_n = \sqrt{\frac{\sigma^2}{\sigma^2 + n\tau^2}} \exp \left( \frac{n^2 \bar{Y}_n^2 \tau^2}{2\sigma^2(\sigma^2 + n\tau^2)} \right) $$ where: - \(\bar{Y}_n\): The observed sample mean difference between treatment and control at step \(n\). - \(\sigma^2\): The estimated daily/unit baseline variance of the metric. - \(\tau^2\): The mixing parameter (tuning parameter) representing the prior variance of the expected effect size (usually selected to match the Minimum Detectable Effect, MDE).

ATTRIBUTE DESCRIPTION
alpha

The target Type I error rate (e.g., 0.05).

TYPE: float

Examples:

Example
>>> # Monitoring a live test with alpha = 0.05
>>> rules = StoppingRules(alpha=0.05)
>>> # If the calculated likelihood ratio lambda_value crosses 1/alpha = 20.0, we stop early.
>>> rules.check_msprt_stop(lambda_value=25.4)
True
PARAMETER DESCRIPTION
alpha

The desired false-positive probability bound (Type I error rate). Defaults to 0.05.

TYPE: float DEFAULT: 0.05

METHOD DESCRIPTION
check_msprt_stop

Determines if the mSPRT likelihood ratio exceeds the safety stopping bounds.

calculate_msprt_lambda

Calculates the mixture Sequential Probability Ratio Test (mSPRT) likelihood ratio (Lambda_n).

Source code in src\xpyrment\run\stopping.py
def __init__(self, alpha: float = 0.05):
    """Initializes StoppingRules.

    Args:
        alpha (float): The desired false-positive probability bound (Type I error rate). Defaults to 0.05.
    """
    self.alpha = alpha

check_msprt_stop

check_msprt_stop(lambda_value: float) -> bool

Determines if the mSPRT likelihood ratio exceeds the safety stopping bounds.

PARAMETER DESCRIPTION
lambda_value

The calculated mixture likelihood ratio (\(\Lambda_n\)) for the active metric.

TYPE: float

RETURNS DESCRIPTION
bool

True if the likelihood ratio exceeds the martingale boundary (\(1/\alpha\)), indicating that the null hypothesis can be rejected and the experiment can be stopped immediately.

TYPE: bool

Source code in src\xpyrment\run\stopping.py
def check_msprt_stop(self, lambda_value: float) -> bool:
    r"""Determines if the mSPRT likelihood ratio exceeds the safety stopping bounds.

    Args:
        lambda_value (float): The calculated mixture likelihood ratio ($\Lambda_n$) for the active metric.

    Returns:
        bool: True if the likelihood ratio exceeds the martingale boundary ($1/\alpha$), indicating
            that the null hypothesis can be rejected and the experiment can be stopped immediately.
    """
    # Boundaries typically equal 1 / alpha
    boundary = 1.0 / self.alpha
    return lambda_value > boundary

calculate_msprt_lambda

calculate_msprt_lambda(
    n: int, mean_diff: float, variance: float, tau: float
) -> float

Calculates the mixture Sequential Probability Ratio Test (mSPRT) likelihood ratio (Lambda_n).

Mathematical Formulation
\[ \Lambda_n = \sqrt{\frac{\sigma^2}{\sigma^2 + n\tau^2}} \exp \left( \frac{n^2 \bar{Y}_n^2 \tau^2}{2\sigma^2(\sigma^2 + n\tau^2)} \right) \]

Args: n (int): Sample size at the current peeking interval. mean_diff (float): The observed sample mean difference between treatment and control (Y_bar_n). variance (float): The baseline variance of the metric (sigma^2). tau (float): The standard deviation of the mixing distribution (prior expected effect size).

RETURNS DESCRIPTION
float

The calculated mixture likelihood ratio (Lambda_n).

TYPE: float

Source code in src\xpyrment\run\stopping.py
def calculate_msprt_lambda(
    self,
    n: int,
    mean_diff: float,
    variance: float,
    tau: float
) -> float:
    r"""Calculates the mixture Sequential Probability Ratio Test (mSPRT) likelihood ratio (Lambda_n).

    ??? mathbox "Mathematical Formulation"

        $$
        \Lambda_n = \sqrt{\frac{\sigma^2}{\sigma^2 + n\tau^2}} \exp \left( \frac{n^2 \bar{Y}_n^2 \tau^2}{2\sigma^2(\sigma^2 + n\tau^2)} \right)
        $$
    Args:
        n (int): Sample size at the current peeking interval.
        mean_diff (float): The observed sample mean difference between treatment and control (Y_bar_n).
        variance (float): The baseline variance of the metric (sigma^2).
        tau (float): The standard deviation of the mixing distribution (prior expected effect size).

    Returns:
        float: The calculated mixture likelihood ratio (Lambda_n).
    """
    import numpy as np

    if variance <= 0.0 or n <= 0:
        return 1.0

    tau_sq = tau ** 2
    if tau_sq == 0.0:
        return 1.0

    term1 = np.sqrt(variance / (variance + n * tau_sq))
    exponent = (n ** 2 * (mean_diff ** 2) * tau_sq) / (2.0 * variance * (variance + n * tau_sq))
    lambda_val = term1 * np.exp(exponent)

    return float(lambda_val)

ExperimentDashboardServer

ExperimentDashboardServer(
    monitor: LiveMonitor,
    expected_ratios: List[float],
    host: str = "127.0.0.1",
    port: int = 0,
    variant_col: str = "variant",
    freq: str = "D",
    metrics: Optional[List[BaseMetric]] = None,
)

Hosts an interactive Web-UI dashboard to monitor running experiments.

Spawns a thread-safe background server. Supports port 0 binding to avoid testing EADDRINUSE conflicts and provides clean stop/join teardown lifecycle hook.

PARAMETER DESCRIPTION
monitor

The active LiveMonitor containing exposure logs.

TYPE: LiveMonitor

expected_ratios

Expected target allocation ratios (e.g. [0.5, 0.5]).

TYPE: List[float]

host

Host binding address. Defaults to "127.0.0.1".

TYPE: str DEFAULT: '127.0.0.1'

port

Port to bind to. Set to 0 to dynamically allocate a free port.

TYPE: int DEFAULT: 0

variant_col

Variant column name. Defaults to "variant".

TYPE: str DEFAULT: 'variant'

freq

Binning frequency. Defaults to "D".

TYPE: str DEFAULT: 'D'

metrics

Pluggable analytical metrics to monitor.

TYPE: Optional[List[BaseMetric]] DEFAULT: None

METHOD DESCRIPTION
start

Binds the HTTP socket and starts the dashboard server loop in a background thread.

stop

Gracefully halts the server, closes sockets, and joins the background thread.

start_simulation

Starts the background thread-safe traffic simulator.

stop_simulation

Halts the background traffic simulator thread.

update_simulation_config

Updates live simulation configurations thread-safely.

reset_simulation_data

Clears all historical logs in the monitor dataset to begin a fresh run.

get_api_payload

Runs diagnostics checks and serializes stats safely to JSON-compatible data structures.

get_html_content

Returns the self-contained premium glassmorphic HTML structure for the client dashboard.

Source code in src\xpyrment\run\webui.py
def __init__(
    self,
    monitor: LiveMonitor,
    expected_ratios: List[float],
    host: str = "127.0.0.1",
    port: int = 0,
    variant_col: str = "variant",
    freq: str = "D",
    metrics: Optional[List[BaseMetric]] = None
) -> None:
    """Initializes the ExperimentDashboardServer.

    Args:
        monitor (LiveMonitor): The active LiveMonitor containing exposure logs.
        expected_ratios (List[float]): Expected target allocation ratios (e.g. [0.5, 0.5]).
        host (str): Host binding address. Defaults to "127.0.0.1".
        port (int): Port to bind to. Set to 0 to dynamically allocate a free port.
        variant_col (str): Variant column name. Defaults to "variant".
        freq (str): Binning frequency. Defaults to "D".
        metrics (Optional[List[BaseMetric]]): Pluggable analytical metrics to monitor.
    """
    self.monitor = monitor
    self.expected_ratios = expected_ratios
    self.host = host
    self.port_requested = port
    self.variant_col = variant_col
    self.freq = freq
    self.server: Optional[HTTPServer] = None
    self.thread: Optional[threading.Thread] = None
    self.port: int = port
    self._is_running = False

    # Pluggable Metrics Registry and CUPED state
    self.metrics = metrics if metrics is not None else [
        MeanMetric("Conversion Revenue", value_col="metric_value", pre_period_col="pre_value")
    ]
    self.cuped_active = False

    # Simulation configurations
    self._lock = threading.Lock()
    self.sim_active = False
    self.sim_thread: Optional[threading.Thread] = None
    self.sim_rate = 10.0
    self.sim_srm_bias = False
    self.sim_traffic_drop = False
    self.sim_counter = 0

start

start() -> None

Binds the HTTP socket and starts the dashboard server loop in a background thread.

Source code in src\xpyrment\run\webui.py
def start(self) -> None:
    """Binds the HTTP socket and starts the dashboard server loop in a background thread."""
    if self._is_running:
        return

    server_instance = self

    class DashboardHTTPRequestHandler(BaseHTTPRequestHandler):
        def log_message(self, format: str, *args: Any) -> None:
            # Direct server logs to python logging debug level to keep tests silent
            logger.debug(format, *args)

        def do_GET(self) -> None:
            if self.path == "/" or self.path == "/index.html":
                self.send_response(200)
                self.send_header("Content-Type", "text/html; charset=utf-8")
                self.end_headers()
                self.wfile.write(server_instance.get_html_content().encode("utf-8"))
            elif self.path == "/api/data":
                self.send_response(200)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                payload = server_instance.get_api_payload()
                self.wfile.write(json.dumps(payload).encode("utf-8"))
            elif self.path == "/favicon.ico":
                self.send_response(204)
                self.end_headers()
            else:
                self.send_response(404)
                self.send_header("Content-Type", "text/plain")
                self.end_headers()
                self.wfile.write(b"Not Found")

        def do_POST(self) -> None:
            content_length = int(self.headers.get("Content-Length", 0))
            post_data = self.rfile.read(content_length).decode("utf-8") if content_length > 0 else ""
            try:
                params = json.loads(post_data) if post_data else {}
            except Exception:
                params = {}

            if self.path == "/api/simulate/toggle":
                active = params.get("active", False)
                if active:
                    server_instance.start_simulation()
                else:
                    server_instance.stop_simulation()
                self.send_response(200)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps({
                    "status": "success",
                    "sim_active": server_instance.sim_active
                }).encode("utf-8"))

            elif self.path == "/api/simulate/config":
                rate = params.get("rate", server_instance.sim_rate)
                srm_bias = params.get("srm_bias", server_instance.sim_srm_bias)
                traffic_drop = params.get("traffic_drop", server_instance.sim_traffic_drop)

                server_instance.update_simulation_config(rate, srm_bias, traffic_drop)
                self.send_response(200)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps({
                    "status": "success", 
                    "rate": server_instance.sim_rate,
                    "srm_bias": server_instance.sim_srm_bias,
                    "traffic_drop": server_instance.sim_traffic_drop
                }).encode("utf-8"))

            elif self.path == "/api/simulate/reset":
                server_instance.reset_simulation_data()
                self.send_response(200)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps({"status": "success"}).encode("utf-8"))

            elif self.path == "/api/cuped/toggle":
                with server_instance._lock:
                    if "active" in params:
                        server_instance.cuped_active = bool(params["active"])
                    else:
                        server_instance.cuped_active = not server_instance.cuped_active
                    current_cuped = server_instance.cuped_active

                self.send_response(200)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps({
                    "status": "success",
                    "cuped_active": current_cuped
                }).encode("utf-8"))

            else:
                self.send_response(404)
                self.send_header("Content-Type", "text/plain")
                self.end_headers()
                self.wfile.write(b"Not Found")

    # Bind immediately on the parent thread to capture port or EADDRINUSE exceptions
    self.server = HTTPServer((self.host, self.port_requested), DashboardHTTPRequestHandler)
    self.port = self.server.server_address[1]

    self._is_running = True
    self.thread = threading.Thread(target=self._run_server, daemon=True)
    self.thread.start()
    logger.info(f"xpyrment Live Dashboard started at http://{self.host}:{self.port}")

stop

stop() -> None

Gracefully halts the server, closes sockets, and joins the background thread.

Source code in src\xpyrment\run\webui.py
def stop(self) -> None:
    """Gracefully halts the server, closes sockets, and joins the background thread."""
    if not self._is_running or not self.server:
        return

    self.stop_simulation()

    self.server.shutdown()
    self.server.server_close()

    if self.thread:
        self.thread.join(timeout=5.0)

    self._is_running = False
    self.server = None
    self.thread = None
    logger.info("xpyrment Live Dashboard server stopped cleanly.")

start_simulation

start_simulation() -> None

Starts the background thread-safe traffic simulator.

Source code in src\xpyrment\run\webui.py
def start_simulation(self) -> None:
    """Starts the background thread-safe traffic simulator."""
    with self._lock:
        if self.sim_active:
            return
        self.sim_active = True
        self.sim_thread = threading.Thread(target=self._run_simulation_loop, daemon=True)
        self.sim_thread.start()
        logger.info("Simulation engine activated.")

stop_simulation

stop_simulation() -> None

Halts the background traffic simulator thread.

Source code in src\xpyrment\run\webui.py
def stop_simulation(self) -> None:
    """Halts the background traffic simulator thread."""
    with self._lock:
        if not self.sim_active:
            return
        self.sim_active = False
    if self.sim_thread:
        self.sim_thread.join(timeout=2.0)
        self.sim_thread = None
    logger.info("Simulation engine deactivated.")

update_simulation_config

update_simulation_config(
    rate: float, srm_bias: bool, traffic_drop: bool
) -> None

Updates live simulation configurations thread-safely.

Source code in src\xpyrment\run\webui.py
def update_simulation_config(self, rate: float, srm_bias: bool, traffic_drop: bool) -> None:
    """Updates live simulation configurations thread-safely."""
    with self._lock:
        self.sim_rate = max(1.0, float(rate))
        self.sim_srm_bias = bool(srm_bias)
        self.sim_traffic_drop = bool(traffic_drop)
        logger.info(f"Simulation config updated: rate={self.sim_rate}, srm_bias={self.sim_srm_bias}, traffic_drop={self.sim_traffic_drop}")

reset_simulation_data

reset_simulation_data() -> None

Clears all historical logs in the monitor dataset to begin a fresh run.

Source code in src\xpyrment\run\webui.py
def reset_simulation_data(self) -> None:
    """Clears all historical logs in the monitor dataset to begin a fresh run."""
    with self._lock:
        empty_df = pd.DataFrame(columns=self.monitor.df.columns)
        self.monitor.df = empty_df
        self.monitor.shutoff_triggered = False
        self.sim_counter = 0
        logger.info("Simulation dataset has been cleared and reset.")

get_api_payload

get_api_payload() -> Dict[str, Any]

Runs diagnostics checks and serializes stats safely to JSON-compatible data structures.

Source code in src\xpyrment\run\webui.py
def get_api_payload(self) -> Dict[str, Any]:
    """Runs diagnostics checks and serializes stats safely to JSON-compatible data structures."""
    with self._lock:
        checks = self.monitor.run_telemetry_checks(
            expected_ratios=self.expected_ratios,
            variant_col=self.variant_col,
            freq=self.freq
        )

        cumulative = self.monitor.get_cumulative_traffic(variant_col=self.variant_col, freq=self.freq)

        labels = []
        columns = {}
        ratios = []

        if not cumulative.empty:
            cumulative = cumulative.reindex(columns=sorted(cumulative.columns))

            if self.freq in ["s", "S"]:
                labels = [idx.strftime("%H:%M:%S") for idx in cumulative.index]
            elif self.freq in ["min", "T"]:
                labels = [idx.strftime("%H:%M") for idx in cumulative.index]
            else:
                labels = [str(idx.date()) for idx in cumulative.index]

            for col in cumulative.columns:
                columns[str(col)] = cumulative[col].tolist()

            # Ratio tracking if exactly two arms exist
            if len(cumulative.columns) == 2:
                col1, col2 = cumulative.columns[0], cumulative.columns[1]
                for val1, val2 in zip(cumulative[col1], cumulative[col2]):
                    total = val1 + val2
                    ratios.append(float(val2 / total) if total > 0 else 0.0)

        observed_counts = []
        variants = sorted(list(cumulative.columns)) if not cumulative.empty else []
        if not cumulative.empty:
            observed_counts = [int(x) for x in cumulative.iloc[-1].values]

        # Dynamic Real-Time Causal Metrics Welch / CUPED Calculations
        metrics_results = []
        if len(variants) == 2 and not self.monitor.df.empty:
            ctrl_arm = variants[0]
            treat_arm = variants[1]
            for v in variants:
                if "ctrl" in str(v).lower() or "control" in str(v).lower():
                    ctrl_arm = v
                    treat_arm = [x for x in variants if x != v][0]
                    break

            for m in self.metrics:
                orig_pre_period_col = getattr(m, "pre_period_col", None)
                orig_pre_numerator_col = getattr(m, "pre_numerator_col", None)
                orig_pre_denominator_col = getattr(m, "pre_denominator_col", None)

                if not self.cuped_active:
                    if hasattr(m, "pre_period_col"):
                        m.pre_period_col = None
                    if hasattr(m, "pre_numerator_col"):
                        m.pre_numerator_col = None
                    if hasattr(m, "pre_denominator_col"):
                        m.pre_denominator_col = None

                try:
                    res = m.calculate(
                        df=self.monitor.df,
                        treatment_col=self.variant_col,
                        control=ctrl_arm,
                        treatment=treat_arm
                    )
                    metrics_results.append(res)
                except Exception as me:
                    logger.warning(f"Error calculating metric {m.name}: {me}", exc_info=True)
                finally:
                    if hasattr(m, "pre_period_col"):
                        m.pre_period_col = orig_pre_period_col
                    if hasattr(m, "pre_numerator_col"):
                        m.pre_numerator_col = orig_pre_numerator_col
                    if hasattr(m, "pre_denominator_col"):
                        m.pre_denominator_col = orig_pre_denominator_col

        payload = {
            "status": "success",
            "data": {
                "shutoff_triggered": checks.get("shutoff_triggered", False),
                "alerts_triggered": checks.get("alerts_triggered", []),
                "expected_ratios": self.expected_ratios,
                "variants": variants,
                "observed_counts": observed_counts,
                "traffic_anomaly": checks.get("traffic_anomaly", {}),
                "cumulative_srm": checks.get("cumulative_srm", {}),
                "sequential_srm": checks.get("sequential_srm", {}),
                "trends": {
                    "labels": labels,
                    "columns": columns,
                    "ratios": ratios
                },
                "metrics_analysis": metrics_results,
                "cuped_active": self.cuped_active,
                "simulation": {
                    "active": self.sim_active,
                    "rate": self.sim_rate,
                    "srm_bias": self.sim_srm_bias,
                    "traffic_drop": self.sim_traffic_drop
                }
            }
        }
        return numpy_to_python(payload)

get_html_content

get_html_content() -> str

Returns the self-contained premium glassmorphic HTML structure for the client dashboard.

Source code in src\xpyrment\run\webui.py
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
    def get_html_content(self) -> str:
        """Returns the self-contained premium glassmorphic HTML structure for the client dashboard."""
        return """<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>xpyrment Live Experiment Dashboard</title>
    <!-- Premium Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;800&family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet">
    <!-- Chart.js CDN for live rendering -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        :root {
            --bg-dark: #09090e;
            --panel-bg: rgba(18, 18, 28, 0.45);
            --border-glass: rgba(255, 255, 255, 0.07);
            --text-primary: #f8fafc;
            --text-secondary: #94a3b8;
            --color-control: #0ea5e9;    /* Glowing Electric Blue */
            --color-treatment: #a855f7;  /* Glowing Vibrant Violet */
            --color-healthy: #10b981;    /* Deep Emerald Green */
            --color-alert: #ef4444;      /* Glowing Crimson Red */
            --color-warn: #f59e0b;       /* Glowing Amber Gold */
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            background-color: var(--bg-dark);
            background-image: 
                radial-gradient(at 0% 0%, rgba(14, 165, 233, 0.06) 0, transparent 50%),
                radial-gradient(at 100% 100%, rgba(168, 85, 247, 0.06) 0, transparent 50%);
            font-family: 'Outfit', 'Inter', sans-serif;
            color: var(--text-primary);
            min-height: 100vh;
            padding: 32px 24px;
        }

        .dashboard-container {
            max-width: 1440px;
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            gap: 28px;
        }

        /* Glassmorphic Panel Base styling */
        .glass-panel {
            background: var(--panel-bg);
            border: 1px solid var(--border-glass);
            border-radius: 18px;
            box-shadow: 0 12px 40px 0 rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(14px);
            -webkit-backdrop-filter: blur(14px);
            padding: 26px;
            transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), border-color 0.3s ease;
        }

        .glass-panel:hover {
            transform: translateY(-4px);
            border-color: rgba(255, 255, 255, 0.15);
        }

        /* Header Layout */
        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-bottom: 8px;
        }

        .brand-title {
            display: flex;
            flex-direction: column;
        }

        .brand-title h1 {
            font-size: 2rem;
            font-weight: 800;
            letter-spacing: -0.5px;
            background: linear-gradient(135deg, #f8fafc 30%, #a855f7 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .brand-title span {
            font-size: 0.85rem;
            color: var(--text-secondary);
            font-family: 'Inter', sans-serif;
            text-transform: uppercase;
            letter-spacing: 2px;
            margin-top: 4px;
        }

        /* Pulsing Status indicator Badge */
        .status-badge {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 8px 16px;
            border-radius: 9999px;
            background: rgba(16, 185, 129, 0.1);
            border: 1px solid rgba(16, 185, 129, 0.2);
            color: var(--color-healthy);
            font-weight: 600;
            font-size: 0.85rem;
            font-family: 'Inter', sans-serif;
            letter-spacing: 0.5px;
            transition: all 0.3s ease;
        }

        .status-badge.alert-active {
            background: rgba(239, 68, 68, 0.1);
            border: 1px solid rgba(239, 68, 68, 0.2);
            color: var(--color-alert);
            animation: pulse-glow 2s infinite;
        }

        .status-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: var(--color-healthy);
            box-shadow: 0 0 8px var(--color-healthy);
        }

        .status-badge.alert-active .status-dot {
            background-color: var(--color-alert);
            box-shadow: 0 0 8px var(--color-alert);
        }

        /* KPI Responsive Grid */
        .kpi-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
            gap: 20px;
        }

        .kpi-card {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            min-height: 140px;
        }

        .kpi-card .kpi-label {
            font-size: 0.8rem;
            text-transform: uppercase;
            letter-spacing: 1.5px;
            color: var(--text-secondary);
            font-family: 'Inter', sans-serif;
            font-weight: 500;
        }

        .kpi-card .kpi-value {
            font-size: 2.2rem;
            font-weight: 800;
            margin-top: 12px;
            letter-spacing: -1px;
        }

        .kpi-card .kpi-delta {
            font-size: 0.85rem;
            margin-top: 8px;
            color: var(--text-secondary);
        }

        /* KPI Custom Border highlights */
        .kpi-total { border-left: 4px solid var(--color-control); }
        .kpi-srm { border-left: 4px solid var(--color-healthy); }
        .kpi-sprt { border-left: 4px solid var(--color-treatment); }
        .kpi-volatility { border-left: 4px solid var(--color-warn); }

        .kpi-card.anomaly-highlight {
            border: 1px solid var(--color-alert);
            box-shadow: 0 0 15px rgba(239, 68, 68, 0.15);
        }

        /* Charts Responsive Grid */
        .charts-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(580px, 1fr));
            gap: 24px;
        }

        .chart-panel {
            display: flex;
            flex-direction: column;
            gap: 16px;
        }

        .chart-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .chart-header h3 {
            font-size: 1.15rem;
            font-weight: 600;
            color: var(--text-primary);
        }

        .chart-container {
            position: relative;
            height: 280px;
            width: 100%;
        }

        /* SVG Offline Fallback Styling */
        .chart-fallback {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .no-data {
            font-size: 0.9rem;
            color: var(--text-secondary);
            font-family: 'Inter', sans-serif;
        }

        /* Alert and Diagnostics Panel */
        .alert-panel {
            display: flex;
            flex-direction: column;
            gap: 16px;
        }

        .alert-feed {
            max-height: 200px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            gap: 12px;
            padding-right: 6px;
        }

        .alert-item {
            display: flex;
            align-items: flex-start;
            gap: 16px;
            padding: 14px 18px;
            border-radius: 12px;
            background: rgba(255, 255, 255, 0.02);
            border: 1px solid rgba(255, 255, 255, 0.05);
            font-family: 'Inter', sans-serif;
            font-size: 0.9rem;
            animation: fadeIn 0.4s ease-out;
        }

        .alert-item.alert-danger {
            background: rgba(239, 68, 68, 0.06);
            border-color: rgba(239, 68, 68, 0.15);
        }

        .alert-item.alert-warn {
            background: rgba(245, 158, 11, 0.06);
            border-color: rgba(245, 158, 11, 0.15);
        }

        .alert-icon {
            font-size: 1.2rem;
            line-height: 1;
        }

        .alert-info {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .alert-title {
            font-weight: 600;
            color: var(--text-primary);
        }

        .alert-msg {
            color: var(--text-secondary);
            font-size: 0.85rem;
        }

        .alert-time {
            font-size: 0.75rem;
            color: rgba(255, 255, 255, 0.25);
            margin-top: 2px;
        }

        /* Controls / Footer */
        footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 0.8rem;
            color: var(--text-secondary);
            font-family: 'Inter', sans-serif;
            padding-top: 8px;
        }

        .refresh-btn {
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid var(--border-glass);
            border-radius: 8px;
            color: var(--text-primary);
            padding: 8px 16px;
            font-size: 0.8rem;
            font-family: 'Inter', sans-serif;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .refresh-btn:hover {
            background: rgba(255, 255, 255, 0.15);
            border-color: rgba(255, 255, 255, 0.3);
        }

        /* Alert flashing Animation */
        @keyframes pulse-glow {
            0% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.4); }
            70% { box-shadow: 0 0 0 12px rgba(239, 68, 68, 0); }
            100% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0); }
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(6px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* Custom Scrollbar for Alert Feed */
        .alert-feed::-webkit-scrollbar {
            width: 6px;
        }
        .alert-feed::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.02);
            border-radius: 99px;
        }
        .alert-feed::-webkit-scrollbar-thumb {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 99px;
        }
        .alert-feed::-webkit-scrollbar-thumb:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        /* Floating Settings/Simulator Button */
        .settings-toggle-btn {
            position: fixed;
            bottom: 24px;
            right: 24px;
            background: linear-gradient(135deg, var(--color-control) 0%, var(--color-treatment) 100%);
            border: none;
            border-radius: 9999px;
            color: white;
            padding: 12px 24px;
            font-size: 0.95rem;
            font-weight: 600;
            cursor: pointer;
            box-shadow: 0 4px 20px rgba(14, 165, 233, 0.4);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            z-index: 1000;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .settings-toggle-btn:hover {
            transform: scale(1.05) translateY(-2px);
            box-shadow: 0 6px 24px rgba(14, 165, 233, 0.6);
        }

        /* Simulator Drawer panel */
        .drawer {
            position: fixed;
            top: 0;
            right: -380px;
            width: 360px;
            height: 100vh;
            background: rgba(10, 10, 18, 0.9);
            border-left: 1px solid var(--border-glass);
            box-shadow: -10px 0 40px rgba(0, 0, 0, 0.6);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            transition: right 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            z-index: 999;
            padding: 24px;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .drawer.open {
            right: 0;
        }

        .drawer-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-bottom: 16px;
            border-bottom: 1px solid var(--border-glass);
        }

        .drawer-header h3 {
            font-size: 1.25rem;
            font-weight: 700;
            letter-spacing: -0.5px;
            background: linear-gradient(135deg, var(--text-primary) 30%, var(--color-treatment) 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .close-btn {
            background: none;
            border: none;
            color: var(--text-secondary);
            font-size: 1.5rem;
            cursor: pointer;
            transition: color 0.2s;
        }

        .close-btn:hover {
            color: var(--text-primary);
        }

        /* Drawer sections */
        .drawer-body {
            display: flex;
            flex-direction: column;
            gap: 24px;
            overflow-y: auto;
            flex-grow: 1;
        }

        .sim-section {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }

        .sim-section.border-top {
            border-top: 1px solid var(--border-glass);
            padding-top: 20px;
            margin-top: 10px;
        }

        .section-title {
            font-size: 0.8rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 1px;
            color: var(--text-secondary);
            font-family: 'Inter', sans-serif;
        }

        .text-danger {
            color: var(--color-alert) !important;
        }

        .sim-status-container {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
        }

        .sim-status-badge {
            font-size: 0.75rem;
            font-weight: 700;
            padding: 6px 12px;
            border-radius: 6px;
            letter-spacing: 0.5px;
            font-family: 'Inter', sans-serif;
        }

        .sim-status-badge.offline {
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(255, 255, 255, 0.1);
            color: var(--text-secondary);
        }

        .sim-status-badge.active {
            background: rgba(16, 185, 129, 0.15);
            border: 1px solid rgba(16, 185, 129, 0.3);
            color: var(--color-healthy);
            animation: pulse-glow 2s infinite;
        }

        .sim-action-btn {
            background: rgba(255, 255, 255, 0.08);
            border: 1px solid var(--border-glass);
            border-radius: 8px;
            color: var(--text-primary);
            padding: 8px 16px;
            font-size: 0.85rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            font-family: 'Inter', sans-serif;
        }

        .sim-action-btn:hover {
            background: rgba(255, 255, 255, 0.15);
            border-color: rgba(255, 255, 255, 0.3);
        }

        .sim-action-btn.start {
            background: rgba(14, 165, 233, 0.15);
            border-color: rgba(14, 165, 233, 0.3);
            color: var(--color-control);
        }

        .sim-action-btn.stop {
            background: rgba(239, 68, 68, 0.15);
            border-color: rgba(239, 68, 68, 0.3);
            color: var(--color-alert);
        }

        /* Sliders */
        .slider-container {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .slider-label {
            font-size: 0.85rem;
            color: var(--text-secondary);
            font-family: 'Inter', sans-serif;
        }

        input[type="range"] {
            -webkit-appearance: none;
            width: 100%;
            height: 6px;
            border-radius: 3px;
            background: rgba(255, 255, 255, 0.1);
            outline: none;
            transition: background 0.2s;
        }

        input[type="range"]::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 16px;
            height: 16px;
            border-radius: 50%;
            background: var(--color-control);
            cursor: pointer;
            box-shadow: 0 0 8px var(--color-control);
            transition: transform 0.1s;
        }

        input[type="range"]::-webkit-slider-thumb:hover {
            transform: scale(1.2);
        }

        /* Switches */
        .toggle-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: rgba(255, 255, 255, 0.02);
            border: 1px solid rgba(255, 255, 255, 0.04);
            border-radius: 10px;
            padding: 10px 14px;
        }

        .toggle-label {
            font-size: 0.85rem;
            color: var(--text-primary);
            font-family: 'Inter', sans-serif;
        }

        .switch {
            position: relative;
            display: inline-block;
            width: 44px;
            height: 22px;
        }

        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .slider-switch {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(255, 255, 255, 0.1);
            transition: .3s;
            border-radius: 34px;
        }

        .slider-switch:before {
            position: absolute;
            content: "";
            height: 16px;
            width: 16px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: .3s;
            border-radius: 50%;
        }

        input:checked + .slider-switch {
            background-color: var(--color-treatment);
        }

        input:focus + .slider-switch {
            box-shadow: 0 0 1px var(--color-treatment);
        }

        input:checked + .slider-switch:before {
            transform: translateX(22px);
        }

        /* Reset button */
        .reset-btn {
            background: rgba(239, 68, 68, 0.08);
            border: 1px solid rgba(239, 68, 68, 0.2);
            border-radius: 8px;
            color: var(--color-alert);
            padding: 10px;
            font-size: 0.85rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            font-family: 'Inter', sans-serif;
            text-align: center;
        }

        .reset-btn:hover {
            background: rgba(239, 68, 68, 0.18);
            border-color: rgba(239, 68, 68, 0.4);
        }

        /* Real-Time Inference Styles */
        .metric-card {
            background: rgba(255, 255, 255, 0.015);
            border: 1px solid rgba(255, 255, 255, 0.05);
            border-radius: 14px;
            padding: 20px;
            display: flex;
            flex-direction: column;
            gap: 16px;
            transition: all 0.3s ease;
        }

        .metric-card:hover {
            background: rgba(255, 255, 255, 0.03);
            border-color: rgba(255, 255, 255, 0.1);
        }

        .metric-card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .metric-card-title {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .metric-card-title h4 {
            font-size: 1.1rem;
            font-weight: 700;
            color: var(--text-primary);
        }

        .metric-card-title span {
            font-size: 0.75rem;
            color: var(--text-secondary);
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .metric-stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
            gap: 16px;
            background: rgba(255, 255, 255, 0.01);
            border: 1px solid rgba(255, 255, 255, 0.03);
            border-radius: 10px;
            padding: 14px;
        }

        .metric-stat-item {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .metric-stat-label {
            font-size: 0.75rem;
            color: var(--text-secondary);
            text-transform: uppercase;
            font-weight: 500;
            font-family: 'Inter', sans-serif;
        }

        .metric-stat-value {
            font-size: 1.25rem;
            font-weight: 700;
            color: var(--text-primary);
        }

        .metric-stat-value.lift-positive {
            color: var(--color-healthy);
            text-shadow: 0 0 10px rgba(16, 185, 129, 0.3);
        }

        .metric-stat-value.lift-negative {
            color: var(--color-alert);
            text-shadow: 0 0 10px rgba(239, 68, 68, 0.3);
        }

        .sig-badge {
            font-size: 0.75rem;
            font-weight: 700;
            padding: 4px 10px;
            border-radius: 6px;
            letter-spacing: 0.5px;
            font-family: 'Inter', sans-serif;
            text-transform: uppercase;
        }

        .sig-badge.significant {
            background: rgba(16, 185, 129, 0.15);
            border: 1px solid rgba(16, 185, 129, 0.3);
            color: var(--color-healthy);
        }

        .sig-badge.not-significant {
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(255, 255, 255, 0.1);
            color: var(--text-secondary);
        }

        .vr-badge {
            font-size: 0.7rem;
            font-weight: 700;
            background: rgba(168, 85, 247, 0.15);
            border: 1px solid rgba(168, 85, 247, 0.3);
            color: var(--color-treatment);
            padding: 3px 8px;
            border-radius: 4px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-left: 8px;
        }

        /* CI Visual Container */
        .ci-visual-container {
            display: flex;
            flex-direction: column;
            gap: 8px;
            padding: 10px 0;
        }

        .ci-track {
            position: relative;
            height: 12px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 6px;
            border: 1px solid rgba(255, 255, 255, 0.03);
            width: 100%;
            overflow: visible;
        }

        .ci-zero-line {
            position: absolute;
            top: 0;
            bottom: 0;
            width: 1px;
            border-left: 1px dashed rgba(255, 255, 255, 0.25);
            left: 50%;
            z-index: 1;
        }

        .ci-range-bar {
            position: absolute;
            top: 3px;
            height: 6px;
            border-radius: 3px;
            z-index: 2;
            box-shadow: 0 0 10px rgba(255, 255, 255, 0.1);
            transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .ci-range-bar.significant-pos {
            background: linear-gradient(90deg, rgba(16, 185, 129, 0.5), rgba(16, 185, 129, 0.8));
            box-shadow: 0 0 10px rgba(16, 185, 129, 0.3);
        }

        .ci-range-bar.significant-neg {
            background: linear-gradient(90deg, rgba(239, 68, 68, 0.5), rgba(239, 68, 68, 0.8));
            box-shadow: 0 0 10px rgba(239, 68, 68, 0.3);
        }

        .ci-range-bar.non-significant {
            background: linear-gradient(90deg, rgba(148, 163, 184, 0.3), rgba(148, 163, 184, 0.6));
            box-shadow: none;
        }

        .ci-estimate-dot {
            position: absolute;
            top: -3px;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #ffffff;
            border: 2px solid var(--bg-dark);
            z-index: 3;
            transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .ci-labels-row {
            display: flex;
            justify-content: space-between;
            font-size: 0.75rem;
            color: var(--text-secondary);
            font-family: 'Inter', sans-serif;
        }
    </style>
</head>
<body>
    <div class="dashboard-container">
        <!-- Top Header Panel -->
        <header class="glass-panel">
            <div class="brand-title">
                <h1>xpyrment Live Monitor</h1>
                <span>Real-Time Telemetry & Safe Shutoff Panel</span>
            </div>
            <div class="status-badge" id="system-badge">
                <div class="status-dot"></div>
                <span id="badge-text">SYSTEM ACTIVE</span>
            </div>
        </header>

        <!-- KPI Grid -->
        <section class="kpi-grid">
            <!-- KPI: Total Volume -->
            <div class="glass-panel kpi-card kpi-total">
                <div class="kpi-label">Exposed Units</div>
                <div class="kpi-value" id="kpi-total-val">0</div>
                <div class="kpi-delta" id="kpi-total-breakdown">Control: 0 | Treatment: 0</div>
            </div>
            <!-- KPI: Chi-Square SRM -->
            <div class="glass-panel kpi-card kpi-srm" id="card-srm">
                <div class="kpi-label">Cumulative SRM P-Value</div>
                <div class="kpi-value" id="kpi-srm-val">1.0000</div>
                <div class="kpi-delta" id="kpi-srm-status">SRM: HEALTHY</div>
            </div>
            <!-- KPI: SPRT likelihood -->
            <div class="glass-panel kpi-card kpi-sprt" id="card-sprt">
                <div class="kpi-label">SPRT Likelihood Ratio</div>
                <div class="kpi-value" id="kpi-sprt-val">1.00</div>
                <div class="kpi-delta" id="kpi-sprt-status">Boundary: 100.00 (Healthy)</div>
            </div>
            <!-- KPI: Volatility Z-Score -->
            <div class="glass-panel kpi-card kpi-volatility" id="card-anomaly">
                <div class="kpi-label">Latest Traffic Z-Score</div>
                <div class="kpi-value" id="kpi-anomaly-val">0.00</div>
                <div class="kpi-delta" id="kpi-anomaly-status">Traffic stable</div>
            </div>
        </section>

        <!-- Charts Section -->
        <section class="charts-grid">
            <!-- Chart 1: Allocation Splits -->
            <div class="glass-panel chart-panel">
                <div class="chart-header">
                    <h3>Cumulative Assignment Split</h3>
                </div>
                <div class="chart-container" id="chart1-container">
                    <canvas id="assignmentChart"></canvas>
                    <div id="chart1-fallback" class="chart-fallback" style="display: none;"></div>
                </div>
            </div>
            <!-- Chart 2: Martingale Likelihood Ratio -->
            <div class="glass-panel chart-panel">
                <div class="chart-header">
                    <h3>Sequential SPRT Martingale Path</h3>
                </div>
                <div class="chart-container" id="chart2-container">
                    <canvas id="sprtChart"></canvas>
                    <div id="chart2-fallback" class="chart-fallback" style="display: none;"></div>
                </div>
            </div>
        </section>

        <!-- Causal Inference Panel -->
        <section class="glass-panel" id="causal-inference-panel" style="display: none;">
            <div class="chart-header" style="margin-bottom: 20px;">
                <h3>Live Causal Inference & Lift Analysis</h3>
            </div>
            <div id="metrics-container" style="display: flex; flex-direction: column; gap: 20px;">
                <!-- Dynamic causal metric cards will render here -->
            </div>
        </section>

        <!-- Alerts Panel -->
        <section class="glass-panel alert-panel">
            <h3>Diagnostic Activity Feed & Alerts</h3>
            <div class="alert-feed" id="alert-feed">
                <!-- Dynamic alerts populated here -->
            </div>
        </section>

        <!-- Footer section -->
        <footer>
            <span>Status: Polling Active (Every 3s)</span>
            <button class="refresh-btn" onclick="fetchUpdate()">Refresh Now</button>
        </footer>
    </div>

    <!-- Floating Settings Toggle Button -->
    <button class="settings-toggle-btn" onclick="toggleDrawer()">⚙️ Simulator Panel</button>

    <!-- Floating Drawer Panel -->
    <div class="drawer" id="simulator-drawer">
        <div class="drawer-header">
            <h3>Experiment Simulator</h3>
            <button class="close-btn" onclick="toggleDrawer()">&times;</button>
        </div>
        <div class="drawer-body">
            <!-- Simulator Status -->
            <div class="sim-section">
                <label class="section-title">Simulator Status</label>
                <div class="sim-status-container">
                    <span class="sim-status-badge offline" id="sim-status-badge">SIMULATION OFFLINE</span>
                    <button class="sim-action-btn start" id="sim-toggle-btn" onclick="toggleSimulation()">Start Simulator</button>
                </div>
            </div>

            <!-- Rate Slider -->
            <div class="sim-section">
                <label class="section-title">Traffic Generation Rate</label>
                <div class="slider-container">
                    <input type="range" id="sim-rate-range" min="1" max="100" value="10" oninput="updateRateLabel(this.value)" onchange="sendConfig()">
                    <span class="slider-label"><span id="sim-rate-val">10</span> req/sec</span>
                </div>
            </div>

            <!-- Variance Reduction Settings -->
            <div class="sim-section">
                <label class="section-title">Variance Reduction</label>
                <div class="toggle-container">
                    <span class="toggle-label" style="display: flex; flex-direction: column; gap: 4px;">
                        <span>Apply CUPED</span>
                        <span style="font-size: 0.72rem; color: var(--text-secondary);">Using pre-period covariate</span>
                    </span>
                    <label class="switch">
                        <input type="checkbox" id="sim-cuped-checkbox" onchange="toggleCuped()">
                        <span class="slider-switch"></span>
                    </label>
                </div>
            </div>

            <!-- Toggles -->
            <div class="sim-section">
                <label class="section-title">Inject Anomalies</label>

                <div class="toggle-container">
                    <span class="toggle-label">Inject SRM Bias (70/30)</span>
                    <label class="switch">
                        <input type="checkbox" id="sim-srm-checkbox" onchange="sendConfig()">
                        <span class="slider-switch"></span>
                    </label>
                </div>

                <div class="toggle-container">
                    <span class="toggle-label">Inject Traffic Dropout</span>
                    <label class="switch">
                        <input type="checkbox" id="sim-drop-checkbox" onchange="sendConfig()">
                        <span class="slider-switch"></span>
                    </label>
                </div>
            </div>

            <!-- Danger Zone Actions -->
            <div class="sim-section border-top">
                <label class="section-title text-danger">Reset Controls</label>
                <button class="reset-btn" onclick="resetSimulationData()">Clear Dashboard Logs</button>
            </div>
        </div>
    </div>

    <!-- Live Polling & Drawing Script -->
    <script>
        let assignmentChart = null;
        let sprtChart = null;
        let isChartJsLoaded = typeof Chart !== 'undefined';
        let isSimulating = false;

        // Custom responsive SVG generators if Chart.js fails
        function generateAssignmentSvg(trends) {
            if (!trends || !trends.labels || trends.labels.length === 0) {
                return '<div class="no-data">No cumulative trends data</div>';
            }
            const labels = trends.labels;
            const keys = Object.keys(trends.columns || {});
            if (keys.length === 0) return '<div class="no-data">No trend variables</div>';

            const width = 600;
            const height = 280;
            const pad = 50;

            const allVals = keys.flatMap(k => trends.columns[k]);
            const maxVal = Math.max(...allVals, 100) * 1.1;
            const minVal = 0;

            const getX = (idx) => pad + (idx / Math.max(1, labels.length - 1)) * (width - 2 * pad);
            const getY = (val) => height - pad - ((val - minVal) / (maxVal - minVal)) * (height - 2 * pad);

            let svg = `<svg viewBox="0 0 ${width} ${height}" style="width: 100%; height: 100%;">`;

            // Neon glow Filters & gradients
            svg += `
              <defs>
                <linearGradient id="svg-grad-ctrl" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stop-color="#0ea5e9" stop-opacity="0.25"/>
                  <stop offset="100%" stop-color="#0ea5e9" stop-opacity="0"/>
                </linearGradient>
                <linearGradient id="svg-grad-treat" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stop-color="#a855f7" stop-opacity="0.25"/>
                  <stop offset="100%" stop-color="#a855f7" stop-opacity="0"/>
                </linearGradient>
              </defs>
            `;

            // Grid Lines
            for (let i = 0; i <= 4; i++) {
                const y = pad + (i / 4) * (height - 2 * pad);
                const val = maxVal - (i / 4) * (maxVal - minVal);
                svg += `
                  <line x1="${pad}" y1="${y}" x2="${width - pad}" y2="${y}" stroke="rgba(255,255,255,0.04)" stroke-width="1" />
                  <text x="${pad - 10}" y="${y + 4}" fill="#64748b" font-size="9" text-anchor="end">${Math.round(val)}</text>
                `;
            }

            const colors = ["#0ea5e9", "#a855f7", "#10b981", "#ef4444"];
            const grads = ["#svg-grad-ctrl", "#svg-grad-treat"];

            keys.forEach((key, kIdx) => {
                const vals = trends.columns[key];
                const color = colors[kIdx % colors.length];
                const grad = grads[kIdx % grads.length] || "none";

                let pathStr = "";
                let areaStr = `M ${getX(0)} ${height - pad} `;

                vals.forEach((v, idx) => {
                    const x = getX(idx);
                    const y = getY(v);
                    if (idx === 0) {
                        pathStr += `M ${x} ${y} `;
                    } else {
                        pathStr += `L ${x} ${y} `;
                    }
                    areaStr += `L ${x} ${y} `;
                });
                areaStr += `L ${getX(vals.length - 1)} ${height - pad} Z`;

                svg += `<path d="${areaStr}" fill="url(${grad})" />`;
                svg += `<path d="${pathStr}" fill="none" stroke="${color}" stroke-width="3" stroke-linecap="round" />`;

                // Dots
                vals.forEach((v, idx) => {
                    svg += `<circle cx="${getX(idx)}" cy="${getY(v)}" r="4" fill="#ffffff" stroke="${color}" stroke-width="2" />`;
                });
            });

            // X Labels
            labels.forEach((lbl, idx) => {
                svg += `<text x="${getX(idx)}" y="${height - pad + 18}" fill="#64748b" font-size="9" text-anchor="middle">${lbl}</text>`;
            });

            svg += "</svg>";
            return svg;
        }

        function generateSprtSvg(seqData, alpha) {
            const ratios = (seqData && seqData.running_likelihood_ratios) || [1.0];
            const targetAlpha = alpha || 0.01;
            const threshold = 1.0 / targetAlpha;

            const width = 600;
            const height = 280;
            const pad = 50;

            const maxVal = Math.max(threshold * 1.2, ...ratios) || 120;
            const minVal = 0;

            const getX = (idx) => pad + (idx / Math.max(1, ratios.length - 1)) * (width - 2 * pad);
            const getY = (val) => height - pad - ((val - minVal) / (maxVal - minVal)) * (height - 2 * pad);

            let svg = `<svg viewBox="0 0 ${width} ${height}" style="width: 100%; height: 100%;">`;

            // Grid Lines
            for (let i = 0; i <= 4; i++) {
                const y = pad + (i / 4) * (height - 2 * pad);
                const val = maxVal - (i / 4) * (maxVal - minVal);
                svg += `
                  <line x1="${pad}" y1="${y}" x2="${width - pad}" y2="${y}" stroke="rgba(255,255,255,0.04)" stroke-width="1" />
                  <text x="${pad - 10}" y="${y + 4}" fill="#64748b" font-size="9" text-anchor="end">${Math.round(val)}</text>
                `;
            }

            // Target Threshold Rejection Line
            const threshY = getY(threshold);
            svg += `
              <line x1="${pad}" y1="${threshY}" x2="${width - pad}" y2="${threshY}" stroke="#ef4444" stroke-width="2" stroke-dasharray="6,4" />
              <text x="${width - pad - 10}" y="${threshY - 6}" fill="#ef4444" font-size="9" text-anchor="end" font-weight="bold">Rejection Boundary (1/α = ${Math.round(threshold)})</text>
            `;

            // Martingale path
            let pathStr = "";
            ratios.forEach((r, idx) => {
                const x = getX(idx);
                const y = getY(r);
                if (idx === 0) {
                    pathStr += `M ${x} ${y} `;
                } else {
                    pathStr += `L ${x} ${y} `;
                }
            });

            svg += `<path d="${pathStr}" fill="none" stroke="#a855f7" stroke-width="3" stroke-linecap="round" />`;

            // Dots
            ratios.forEach((r, idx) => {
                svg += `<circle cx="${getX(idx)}" cy="${getY(r)}" r="3.5" fill="#ffffff" stroke="#a855f7" stroke-width="1.5" />`;
            });

            svg += "</svg>";
            return svg;
        }

        // Live stats parser and card updates
        function updateCards(data) {
            const totalVal = (data.observed_counts || []).reduce((a, b) => a + b, 0);
            document.getElementById('kpi-total-val').innerText = totalVal.toLocaleString();

            const variants = data.variants || [];
            const counts = data.observed_counts || [];
            if (variants.length > 0) {
                const parts = variants.map((v, i) => `${v}: ${counts[i].toLocaleString()}`);
                document.getElementById('kpi-total-breakdown').innerText = parts.join(' | ');
            }

            // SRM Chi-Square
            const srmVal = data.cumulative_srm ? data.cumulative_srm.p_value : 1.0;
            const srmCard = document.getElementById('card-srm');
            document.getElementById('kpi-srm-val').innerText = srmVal.toFixed(4);

            if (data.cumulative_srm && data.cumulative_srm.srm_detected) {
                srmCard.classList.add('anomaly-highlight');
                document.getElementById('kpi-srm-status').innerText = 'SRM DETECTED (SHUTOFF)';
                document.getElementById('kpi-srm-status').style.color = 'var(--color-alert)';
            } else {
                srmCard.classList.remove('anomaly-highlight');
                document.getElementById('kpi-srm-status').innerText = 'SRM: HEALTHY';
                document.getElementById('kpi-srm-status').style.color = 'var(--text-secondary)';
            }

            // Sequential SPRT
            const sprtRatio = (data.sequential_srm && data.sequential_srm.running_likelihood_ratios) 
                ? data.sequential_srm.running_likelihood_ratios[data.sequential_srm.running_likelihood_ratios.length - 1] 
                : 1.0;
            const sprtCard = document.getElementById('card-sprt');
            document.getElementById('kpi-sprt-val').innerText = sprtRatio.toFixed(2);

            if (data.sequential_srm && data.sequential_srm.srm_detected) {
                sprtCard.classList.add('anomaly-highlight');
                document.getElementById('kpi-sprt-status').innerText = `SRM DETECTED at index ${data.sequential_srm.stopped_index}`;
                document.getElementById('kpi-sprt-status').style.color = 'var(--color-alert)';
            } else {
                sprtCard.classList.remove('anomaly-highlight');
                document.getElementById('kpi-sprt-status').innerText = 'Boundary: 100.00 (Healthy)';
                document.getElementById('kpi-sprt-status').style.color = 'var(--text-secondary)';
            }

            // Volatility / Traffic drop anomaly
            const anomalyData = data.traffic_anomaly || {};
            const zScore = anomalyData.z_score || 0.0;
            const anomalyCard = document.getElementById('card-anomaly');
            document.getElementById('kpi-anomaly-val').innerText = zScore.toFixed(2);

            if (anomalyData.anomaly_detected) {
                anomalyCard.classList.add('anomaly-highlight');
                document.getElementById('kpi-anomaly-status').innerText = 'TRAFFIC DROP ANOMALY';
                document.getElementById('kpi-anomaly-status').style.color = 'var(--color-alert)';
            } else {
                anomalyCard.classList.remove('anomaly-highlight');
                document.getElementById('kpi-anomaly-status').innerText = 'Traffic stable';
                document.getElementById('kpi-anomaly-status').style.color = 'var(--text-secondary)';
            }

            // System Active Pulsing Badge
            const badge = document.getElementById('system-badge');
            const badgeText = document.getElementById('badge-text');
            if (data.shutoff_triggered) {
                badge.classList.add('alert-active');
                badgeText.innerText = 'SHUTOFF TRIGGERED';
            } else {
                badge.classList.remove('alert-active');
                badgeText.innerText = 'SYSTEM ACTIVE';
            }
        }

        // Live alert feed updates
        function updateAlertFeed(data) {
            const feed = document.getElementById('alert-feed');
            feed.innerHTML = '';

            const alarms = data.alerts_triggered || [];

            // Include baseline logs if no active alerts
            if (alarms.length === 0) {
                feed.innerHTML = `
                    <div class="alert-item">
                        <span class="alert-icon">⚡</span>
                        <div class="alert-info">
                            <span class="alert-title">Diagnostic Feed Initialized</span>
                            <span class="alert-msg">Running diagnostics. Standard traffic ratio balanced. No structural anomalies detected in active partitions.</span>
                            <span class="alert-time">${new Date().toLocaleTimeString()}</span>
                        </div>
                    </div>
                `;
                return;
            }

            alarms.forEach(type => {
                let cl = 'alert-danger';
                let icon = '🚨';
                let title = type;
                let desc = '';

                if (type === 'TRAFFIC_DROP_ANOMALY') {
                    cl = 'alert-warn';
                    icon = '⚠️';
                    title = 'Traffic Dropout Alert';
                    desc = data.traffic_anomaly.message || 'Latest binned exposure volume indicates severe traffic drop.';
                } else if (type === 'SRM_SHUTOFF_TRIGGERED') {
                    title = 'SRM Shutoff Safety Triggered';
                    desc = data.cumulative_srm.message || 'Sample ratios mismatched beyond Wald Chi-Square bounds. Assignment halt recommended.';
                } else if (type === 'SEQUENTIAL_SRM_TRIGGERED') {
                    title = 'Sequential SPRT SRM Boundary Crossed';
                    desc = data.sequential_srm.message || 'Sequential likelihood ratio crossed type-I error martingale boundary.';
                }

                feed.innerHTML += `
                    <div class="alert-item ${cl}">
                        <span class="alert-icon">${icon}</span>
                        <div class="alert-info">
                            <span class="alert-title">${title}</span>
                            <span class="alert-msg">${desc}</span>
                            <span class="alert-time">${new Date().toLocaleTimeString()}</span>
                        </div>
                    </div>
                `;
            });
        }

        // Draw dynamic ChartJS or trigger SVG fallback
        function drawCharts(data) {
            const trends = data.trends || {};
            const labels = trends.labels || [];
            const cols = trends.columns || {};
            const keys = Object.keys(cols);

            if (!isChartJsLoaded) {
                // Trigger dynamic premium SVG rendering offline fallbacks
                document.getElementById('chart1-fallback').innerHTML = generateAssignmentSvg(trends);
                document.getElementById('chart2-fallback').innerHTML = generateSprtSvg(data.sequential_srm, 0.01);
                document.getElementById('chart1-fallback').style.display = 'block';
                document.getElementById('chart2-fallback').style.display = 'block';
                document.getElementById('assignmentChart').style.display = 'none';
                document.getElementById('sprtChart').style.display = 'none';
                return;
            }

            // Chart 1: Cumulative Assignment Split
            const datasetList = [];
            const colors = ['#0ea5e9', '#a855f7', '#10b981', '#f59e0b'];

            keys.forEach((key, idx) => {
                const color = colors[idx % colors.length];
                datasetList.push({
                    label: `Cumulative ${key}`,
                    data: cols[key],
                    borderColor: color,
                    backgroundColor: `${color}15`,
                    borderWidth: 3,
                    fill: true,
                    tension: 0.35,
                    pointBackgroundColor: '#ffffff',
                    pointBorderColor: color,
                    pointBorderWidth: 2,
                    pointRadius: 4,
                    pointHoverRadius: 6
                });
            });

            if (assignmentChart) {
                assignmentChart.data.labels = labels;
                assignmentChart.data.datasets = datasetList;
                assignmentChart.update();
            } else {
                const ctx = document.getElementById('assignmentChart').getContext('2d');
                assignmentChart = new Chart(ctx, {
                    type: 'line',
                    data: { labels, datasets: datasetList },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                labels: { color: '#94a3b8', font: { family: 'Inter', size: 11 } }
                            }
                        },
                        scales: {
                            x: { grid: { color: 'rgba(255, 255, 255, 0.04)' }, ticks: { color: '#94a3b8', font: { family: 'Inter' } } },
                            y: { grid: { color: 'rgba(255, 255, 255, 0.04)' }, ticks: { color: '#94a3b8', font: { family: 'Inter' } } }
                        }
                    }
                });
            }

            // Chart 2: SPRT Martingale path
            const sprtRatios = (data.sequential_srm && data.sequential_srm.running_likelihood_ratios) || [];
            const boundaryVal = 100.0;
            const thresholdArray = new Array(sprtRatios.length).fill(boundaryVal);

            if (sprtChart) {
                sprtChart.data.labels = sprtRatios.map((_, i) => `Step ${i}`);
                sprtChart.data.datasets[0].data = sprtRatios;
                sprtChart.data.datasets[1].data = thresholdArray;
                sprtChart.update();
            } else {
                const ctx = document.getElementById('sprtChart').getContext('2d');
                sprtChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: sprtRatios.map((_, i) => `Step ${i}`),
                        datasets: [
                            {
                                label: 'Likelihood Ratio (LR)',
                                data: sprtRatios,
                                borderColor: '#a855f7',
                                backgroundColor: 'rgba(168, 85, 247, 0.05)',
                                borderWidth: 3,
                                fill: true,
                                tension: 0.2,
                                pointBackgroundColor: '#ffffff',
                                pointBorderColor: '#a855f7',
                                pointBorderWidth: 1.5,
                                pointRadius: 3
                            },
                            {
                                label: 'Rejection Boundary (1/α)',
                                data: thresholdArray,
                                borderColor: '#ef4444',
                                borderWidth: 2,
                                borderDash: [6, 4],
                                fill: false,
                                pointRadius: 0
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                labels: { color: '#94a3b8', font: { family: 'Inter', size: 11 } }
                            }
                        },
                        scales: {
                            x: { grid: { color: 'rgba(255, 255, 255, 0.04)' }, ticks: { color: '#94a3b8', font: { family: 'Inter' } } },
                            y: { grid: { color: 'rgba(255, 255, 255, 0.04)' }, ticks: { color: '#94a3b8', font: { family: 'Inter' } } }
                        }
                    }
                });
            }
        }

        // Drawer management & Simulator commands
        function toggleDrawer() {
            const drawer = document.getElementById('simulator-drawer');
            drawer.classList.toggle('open');
        }

        function updateRateLabel(val) {
            document.getElementById('sim-rate-val').innerText = val;
        }

        function toggleSimulation() {
            const targetState = !isSimulating;
            fetch('/api/simulate/toggle', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ active: targetState })
            })
            .then(res => res.json())
            .then(res => {
                if (res.status === 'success') {
                    isSimulating = res.sim_active;
                    updateSimBadgeAndButton();
                }
            })
            .catch(err => console.error('Error toggling simulation:', err));
        }

        function updateSimBadgeAndButton() {
            const badge = document.getElementById('sim-status-badge');
            const btn = document.getElementById('sim-toggle-btn');

            if (isSimulating) {
                badge.className = 'sim-status-badge active';
                badge.innerText = 'SIMULATION ACTIVE';
                btn.className = 'sim-action-btn stop';
                btn.innerText = 'Stop Simulator';
            } else {
                badge.className = 'sim-status-badge offline';
                badge.innerText = 'SIMULATION OFFLINE';
                btn.className = 'sim-action-btn start';
                btn.innerText = 'Start Simulator';
            }
        }

        function sendConfig() {
            const rate = parseInt(document.getElementById('sim-rate-range').value);
            const srm_bias = document.getElementById('sim-srm-checkbox').checked;
            const traffic_drop = document.getElementById('sim-drop-checkbox').checked;

            fetch('/api/simulate/config', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ rate, srm_bias, traffic_drop })
            })
            .then(res => res.json())
            .then(res => {
                if (res.status === 'success') {
                    console.log('Simulation config updated:', res);
                }
            })
            .catch(err => console.error('Error updating config:', err));
        }

        function resetSimulationData() {
            if (confirm('Are you sure you want to clear all telemetry data on the dashboard? This will reset active trend charts.')) {
                fetch('/api/simulate/reset', { method: 'POST' })
                .then(res => res.json())
                .then(res => {
                    if (res.status === 'success') {
                        console.log('Simulation logs cleared.');
                        fetchUpdate();
                    }
                })
                .catch(err => console.error('Error resetting data:', err));
            }
        }

        // Periodic API polling function
        function fetchUpdate() {
            fetch('/api/data')
                .then(res => res.json())
                .then(res => {
                    if (res.status === 'success') {
                        updateCards(res.data);
                        updateAlertFeed(res.data);
                        drawCharts(res.data);
                        updateMetricsPanel(res.data);

                        // Synchronize simulator drawer controls with server state
                        document.getElementById('sim-cuped-checkbox').checked = res.data.cuped_active;

                        if (res.data.simulation) {
                            const sim = res.data.simulation;
                            isSimulating = sim.active;
                            updateSimBadgeAndButton();

                            document.getElementById('sim-rate-range').value = sim.rate;
                            document.getElementById('sim-rate-val').innerText = sim.rate;
                            document.getElementById('sim-srm-checkbox').checked = sim.srm_bias;
                            document.getElementById('sim-drop-checkbox').checked = sim.traffic_drop;
                        }
                    }
                })
                .catch(err => {
                    console.error('Failed to poll dashboard update:', err);
                });
        }

        // Run immediate check and schedule loop
        fetchUpdate();
        setInterval(fetchUpdate, 3000);
    </script>
</body>
</html>
"""

ingest_dataframe

ingest_dataframe(
    df: DataFrame,
    unit_id_col: Optional[str] = None,
    time_col: Optional[str] = None,
    metric_cols: Optional[List[str]] = None,
    categorical_cols: Optional[List[str]] = None,
    schema=None,
) -> DataFrame

Ingests, validates, and copies an in-memory pandas DataFrame into the xpyrment lifecycle.

Performs localized validation checks on the pandas DataFrame, ensuring all required column signatures are mapped correctly.

PARAMETER DESCRIPTION
df

The raw source DataFrame.

TYPE: DataFrame

unit_id_col

Column representing unit identifiers (nulls will be dropped).

TYPE: str DEFAULT: None

time_col

Column representing event timestamps (will be parsed to datetime).

TYPE: str DEFAULT: None

metric_cols

Continuous metric columns (nulls will be imputed to 0.0).

TYPE: list DEFAULT: None

categorical_cols

Categorical covariate columns (nulls will be imputed to "UNKNOWN").

TYPE: list DEFAULT: None

schema

A user-provided Pandera schema to validate against. If None, a schema is built dynamically based on the provided columns.

TYPE: DataFrameSchema DEFAULT: None

RETURNS DESCRIPTION
DataFrame

pd.DataFrame: An audited, isolated copy of the DataFrame ready for downstream operations.

Source code in src\xpyrment\run\ingestion.py
def ingest_dataframe(
    df: pd.DataFrame,
    unit_id_col: Optional[str] = None,
    time_col: Optional[str] = None,
    metric_cols: Optional[List[str]] = None,
    categorical_cols: Optional[List[str]] = None,
    schema=None,
) -> pd.DataFrame:
    """Ingests, validates, and copies an in-memory pandas DataFrame into the xpyrment lifecycle.

    Performs localized validation checks on the pandas DataFrame, ensuring all required column signatures
    are mapped correctly.

    Args:
        df (pd.DataFrame): The raw source DataFrame.
        unit_id_col (str): Column representing unit identifiers (nulls will be dropped).
        time_col (str): Column representing event timestamps (will be parsed to datetime).
        metric_cols (list): Continuous metric columns (nulls will be imputed to 0.0).
        categorical_cols (list): Categorical covariate columns (nulls will be imputed to "UNKNOWN").
        schema (pandera.DataFrameSchema, optional): A user-provided Pandera schema to validate against.
            If None, a schema is built dynamically based on the provided columns.

    Returns:
        pd.DataFrame: An audited, isolated copy of the DataFrame ready for downstream operations.
    """
    return _clean_dataframe_like(
        df=df,
        unit_id_col=unit_id_col,
        time_col=time_col,
        metric_cols=metric_cols,
        categorical_cols=categorical_cols,
        to_datetime=pd.to_datetime,
        frame_label="DataFrame",
        copy_frame=True,
        schema=schema,
    )

load_from_sql

load_from_sql(
    query: str, connection_string: str
) -> DataFrame

Loads experimental telemetry and assignment logs from an external relational SQL database.

Fetches exposure matrices, pre-period metrics, and covariate vectors using high-performance database adapters.

PARAMETER DESCRIPTION
query

The SQL retrieval query (e.g., "SELECT user_id, variant, revenue FROM experimental_ledger").

TYPE: str

connection_string

The database connection URI.

TYPE: str

RETURNS DESCRIPTION
DataFrame

pd.DataFrame: A cleaned pandas DataFrame containing the queried records.

Source code in src\xpyrment\run\ingestion.py
def load_from_sql(query: str, connection_string: str) -> pd.DataFrame:
    r"""Loads experimental telemetry and assignment logs from an external relational SQL database.

    Fetches exposure matrices, pre-period metrics, and covariate vectors using high-performance
    database adapters.

    Args:
        query (str): The SQL retrieval query (e.g., `"SELECT user_id, variant, revenue FROM experimental_ledger"`).
        connection_string (str): The database connection URI.

    Returns:
        pd.DataFrame: A cleaned pandas DataFrame containing the queried records.
    """
    import sqlite3

    if (
        ":memory:" in connection_string
        or "sqlite" in connection_string
        or connection_string == ""
    ):
        db_path = (
            ":memory:"
            if (connection_string == "" or ":memory:" in connection_string)
            else connection_string.replace("sqlite:///", "")
        )
        conn = sqlite3.connect(db_path)
        try:
            df = pd.read_sql_query(query, conn)
            conn.close()
            return df
        except Exception as e:
            conn.close()
            raise e
    else:
        raise ValueError(
            "Non-SQLite databases are not supported because sqlalchemy has been removed from the project."
        )