Metadata-Version: 2.4
Name: flagsmith-second-opinion
Version: 0.1.0
Summary: A read-only trust layer and deploy gate for Flagsmith experimentation
Author: Toggle Wars Track 03 Team
License: BSD-3-Clause
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: BSD License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pyyaml>=6.0
Provides-Extra: full
Requires-Dist: numpy>=1.26.0; extra == "full"
Requires-Dist: scipy>=1.12.0; extra == "full"
Requires-Dist: typer>=0.12.0; extra == "full"
Requires-Dist: rich>=13.7.0; extra == "full"
Requires-Dist: jinja2>=3.1.0; extra == "full"
Requires-Dist: httpx>=0.27.0; extra == "full"
Requires-Dist: duckdb>=0.10.0; extra == "full"
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: hypothesis>=6.100.0; extra == "dev"
Requires-Dist: ruff>=0.4.0; extra == "dev"
Requires-Dist: mypy>=1.10.0; extra == "dev"
Requires-Dist: numpy>=1.26.0; extra == "dev"
Requires-Dist: scipy>=1.12.0; extra == "dev"
Dynamic: license-file

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="docs/wemakedevs_flagsmith_logo.svg">
    <source media="(prefers-color-scheme: light)" srcset="docs/wemakedevs_flagsmith_logo_light.svg">
    <img src="docs/wemakedevs_flagsmith_logo.png" alt="WeMakeDevs x Flagsmith Experimentation" width="480"/>
  </picture>
</p>

# Second Opinion

> **A read-only trust layer and automated deploy gate for self-hosted Flagsmith Experimentation.**  
> *Toggle Wars Track 03: Build on Open Source Flagsmith*

[![CI](https://github.com/ankit-cybertron/Second_Opinion/actions/workflows/ci.yml/badge.svg)](https://github.com/ankit-cybertron/Second_Opinion/actions/workflows/ci.yml)
[![License](https://img.shields.io/badge/license-BSD--3--Clause-blue.svg)](LICENSE)
[![Python](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue)](pyproject.toml)

---

## What is Second Opinion?

Flagsmith makes it easy to run feature-flag experiments. But in production, shipping code whenever a dashboard card turns green can be dangerous:

- **Simpson's Paradox:** Overall conversion looks positive (+13.3%), but mobile users suffer a severe -16.2% drop.
- **Guardrail Regressions:** Purchases increase, but refund requests quietly spike by +81.8%.
- **Peeking Bias:** Checking daily and stopping early inflates false positive rates up to about 19-20% (varies slightly with Python version).

**Second Opinion connects to your self-hosted Flagsmith stack as a read-only companion.** It runs 7 automated integrity checks on your event stream and outputs a clean CI exit code (`Exit 20 VETO` or `Exit 0 SHIP`) to protect your releases.

---

## System Architecture

```mermaid
flowchart TD
    subgraph Flagsmith["Self-Hosted Flagsmith"]
        Flags["Multivariate Flags (Control vs Treatment)"]
        SDK["Flagsmith SDKs (Client & Server)"]
        Flags --> SDK
        SDK -->|"Emits exposures & events"| PG[("PostgreSQL\n(experimentation_sdkexperimentationevent)")]
    end

    subgraph SecondOpinion["Second Opinion Trust Layer (Read-Only)"]
        API_Client["Flagsmith API Client\n(Reads configs & baselines)"]
        PG_Reader["PostgreSQL Reader\n(Direct read-only event stream)"]
        
        Engine{"Statistical Engine\n(7 Verification Checks)"}
        
        API_Client --> Engine
        PG_Reader --> Engine
        
        C1["C1: Sample Ratio (Chi-Square)"]
        C2["C2: Primary Effect (Delta Method & Bayes)"]
        C3["C3: Guardrails (Tolerance Loss)"]
        C4["C4: Subgroups (Simpson's Paradox)"]
        C5["C5: Novelty Effect (Decay Tracking)"]
        C6["C6: Peeking (mSPRT Always-Valid)"]
        C7["C7: Data Hygiene (Event Linter)"]
        
        Engine --- C1
        Engine --- C2
        Engine --- C3
        Engine --- C4
        Engine --- C5
        Engine --- C6
        Engine --- C7
    end

    subgraph CICD["Deployment Pipeline (CI/CD)"]
        Engine -->|"Exit 0"| SHIP["🟢 SHIP: Merge PR / Rollout Winner"]
        Engine -->|"Exit 10"| HOLD["🟡 HOLD: Continue Experimentation"]
        Engine -->|"Exit 20"| VETO["🔴 DON'T SHIP: Block Deploy & Alert"]
    end
```

---

## How Flagsmith Experimentation Works with Second Opinion

1. **Round 01 (Create Flag):** Discovers multivariate flags and baseline controls via Flagsmith's API.
2. **Round 02 (Pick Metric):** Ingests conversion and guardrail events from the PostgreSQL event table.
3. **Round 03 (Split Traffic):** Audits `$flag_exposure` events to verify traffic ratios without tracking bias.
4. **Round 04 (Ship Winner):** Evaluates 7 statistical checks to return a binary CI exit code before rollout.

---

## The Verdict Card

Here is what happens when Second Opinion evaluates an experiment where aggregate conversions look positive, but mobile users are being harmed:

```text
checkout_button   environment: Development   24,000 identities
Flagsmith:        Winning, 99.7% chance to win, +13.3% lift
Second Opinion:   DON'T SHIP (Exit 20)

  VETO  VETO: Credible harm detected in subgroup: Segment 'platform=mobile': lift -16.2%, 95% interval (-26.4%, -4.5%), 6000 identities/arm
  info  Variant 'treatment' not safe to stop (mSPRT p=0.0716 > 0.05).
  ok    Sample ratio matches expected split (chi2=0.00, df=1, p=1.0000).
  ok    Second Opinion's Bayesian estimate: chance to win 99.8%, frequentist p=0.0030, lift +13.3%.
  ok    No guardrail metrics configured.
  ok    Event data quality verified: clean schemas, zero naming anomalies, high integrity.
```

---

## 30-Second Quickstart (Zero Setup Needed)

Second Opinion includes 7 built-in test fixtures with planted traps so you can test it immediately without needing a database:

```bash
# 1. Clone the repository
git clone https://github.com/ankit-cybertron/Second_Opinion.git
cd Second_Opinion

# 2. Install
pip install -e .

# 3. Catch Simpson's Paradox / Mobile harm (exits with code 20)
so analyze --demo hidden-harm

# 4. Generate an interactive visual HTML report
so analyze --demo hidden-harm --format html -o report.html
open report.html
```

---

## The Three Real Traps Caught

| Experiment Trap | Flagsmith Dashboard Alone | Second Opinion Trust Layer | Verdict & Action |
| :--- | :--- | :--- | :--- |
| **1. Mobile Harm**<br>*Simpson's Paradox* | **Winning, 99.7% chance to win, +13.3% lift**<br>Looks green and invites rollout. | **VETO (C4)**: Slices traits and catches a credible **-16.2%** drop on mobile. | 🔴 **`DON'T SHIP` (Exit 20)**<br>Protects mobile revenue. |
| **2. Refund Spike**<br>*Guardrail metric* | **Winning (+26.0% lift)**<br>High purchase conversion. | **VETO (C3)**: Catches a **+81.8%** spike in refund requests exceeding tolerance. | 🔴 **`DON'T SHIP` (Exit 20)**<br>Halts costly rollouts. |
| **3. Peeking Inflation**<br>*A/A test false wins* | **Claims 95%+ win**<br>Early random noise looks real. | **HOLD (C6)**: Always-valid mSPRT sequential test prevents premature stopping. | 🟡 **`HOLD` (Exit 10)**<br>Suppresses the about 19-20% (varies slightly with Python version) naive false win rate. |

---

## The Seven Planted-Trap Scenarios

Every claim is backed by reproducible test runs on golden fixtures:

| Scenario | Planted Trap | Flagsmith View | Second Opinion Verdict | Exit Code |
| :--- | :--- | :--- | :---: | :---: |
| `honest-win` | Authentic lift (8% $\to$ 10%, 16k users) | Winning (+29.9% lift) | 🟢 **SHIP** | `0` |
| `srm` | Assignment bug (70/30 split on 50/50 flag) | Unreliable split ($p < 10^{-15}$) | 🔴 **DON'T SHIP** (C1) | `20` |
| `hidden-harm` | Simpson's Paradox: mobile harmed (-16.2%) | Winning (99.7% win prob, +13.3% lift) | 🔴 **DON'T SHIP** (C4) | `20` |
| `novelty` | Day 1 surge (+82.7%) collapses by Days 2–3 | Winning overall from Day 1 spike | 🔴 **DON'T SHIP** (C5) | `20` |
| `guardrail` | Purchases up (+26.0%), but refunds spike +81.8% | Winning on purchase metric (99.5% win) | 🔴 **DON'T SHIP** (C3) | `20` |
| `dirty-events` | 15% conversions sent as `Signup_Completed` | Instrumentation case defect | 🟡 **HOLD** (C7) | `10` |
| `peeking-aa` | True A/A test under daily peeking | False win spikes at early looks | 🟡 **HOLD** (C6) | `10` |

---

## Empirical Statistical Validation

From `scripts/validate.py` (2,000 A/A Monte Carlo simulations with an 8% base rate):

```text
Results across 2,000 A/A replicates:
  Naive peeking false win rate (14 daily looks):  19.60% (about 19-20% (varies slightly with Python version))
  Second Opinion mSPRT false alarm rate (20 looks): 1.80% (about 1-2%)
  Full Engine false SHIP rate (completed tests):    0.15% (Strictly <= 5.0%)
```

---

## The Seven Checks

Second Opinion evaluates seven safety checks before clearing an experiment:

- **C1: Sample Ratio (SRM):** Verifies traffic split matches configuration ($p < 0.001$ = Blocker).
- **C2: Primary Effect:** Computes delta-method lift & Bayesian win probability (matches Flagsmith $< 10^{-6}$).
- **C3: Guardrail Protection:** Ensures secondary metrics (e.g. refunds, latency) do not exceed tolerance.
- **C4: Subgroup Harm:** Checks segments for Simpson's paradox with Benjamini-Hochberg FDR control.
- **C5: Novelty Decay:** Compares Day 1 lift against Days 2–3 to catch early novelty surges that fade.
- **C6: Sequential Stopping:** mSPRT always-valid $p$-value prevents false wins from daily peeking.
- **C7: Data Hygiene:** Lints for casing mismatches (e.g. `Signup_Completed` vs `signup_completed`) and dropped events.

---

## CI/CD Deploy Gate

Add Second Opinion directly to your deployment pipeline to fail pull requests on `Exit 20`:

```yaml
name: experiment-gate
on: pull_request

jobs:
  gate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: ./
        with:
          experiment: checkout_button
          fail-on: dont-ship
        env:
          SO_DATABASE_URL: ${{ secrets.SO_DATABASE_URL }}
```

| Verdict | Exit Code | Action in CI |
| :--- | :---: | :--- |
| `SHIP` | `0` | 🟢 Automatically merge or deploy winner |
| `HOLD` | `10` | 🟡 Keep experiment running; data not ready |
| `DON'T SHIP` | `20` | 🔴 Block rollout; notify engineering team |

---

## Track 03: Build on Open Source Flagsmith

<p align="center">
  <img src="docs/wemakedevs_flagsmith_logo.png" alt="WeMakeDevs x Flagsmith Experiment" width="360"/>
</p>

Second Opinion is designed specifically for **Track 03** of the WeMakeDevs Flagsmith Hackathon:

- **Self-Hosted First:** Connects directly to self-hosted Flagsmith API and PostgreSQL event stream.
- **Zero-Dependency Quickstart:** Evaluates offline in 15 seconds with 7 frozen golden fixtures.
- **Non-Invasive:** 100% read-only. Zero database migrations, zero schema changes.
- **Mathematical Parity:** Verified to match Flagsmith's server-side delta-method calculations within $|\Delta| < 10^{-6}$.

---

## License

BSD-3-Clause License. Open source and free for enterprise or community use.
