Skip to main content

WeMakeDevs x Flagsmith

Second Opinion

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

PyPI version PyPI Downloads CI License Python


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

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:

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 is published on PyPI and includes 7 built-in test fixtures with planted traps so you can test it immediately:

# 1. Install directly via pip (available globally)
pip install flagsmith-second-opinion

# Optional: install with rich terminal UI, DuckDB, and HTML report generator
pip install "flagsmith-second-opinion[full]"

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

# 3. 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
Simpson's Paradox
Winning, 99.7% chance to win, +13.3% lift
Looks green and invites rollout.
VETO (C4): Slices traits and catches a credible -16.2% drop on mobile. 🔴 DON'T SHIP (Exit 20)
Protects mobile revenue.
2. Refund Spike
Guardrail metric
Winning (+26.0% lift)
High purchase conversion.
VETO (C3): Catches a +81.8% spike in refund requests exceeding tolerance. 🔴 DON'T SHIP (Exit 20)
Halts costly rollouts.
3. Peeking Inflation
A/A test false wins
Claims 95%+ win
Early random noise looks real.
HOLD (C6): Always-valid mSPRT sequential test prevents premature stopping. 🟡 HOLD (Exit 10)
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):

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:

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

WeMakeDevs x Flagsmith Experiment

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.

Metadata

Release files for flagsmith-second-opinion 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for flagsmith-second-opinion 0.1.1
File Size Uploaded Provenance Actions
flagsmith_second_opinion-0.1.1.tar.gz 53.0 kB Without provenance Details for flagsmith_second_opinion-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for flagsmith-second-opinion 0.1.1
File Interpreter ABI Platform Actions
flagsmith_second_opinion-0.1.1-py3-none-any.whl Python 3 none any Details for flagsmith_second_opinion-0.1.1-py3-none-any.whl

Total release size: 114.0 kB

Release files / flagsmith_second_opinion-0.1.1.tar.gz

Download URL flagsmith_second_opinion-0.1.1.tar.gz
Size 53.0 kB
Tags Source
SHA-256 checksum
How to use checksums
c5f53a91fa1ac89664f84752c6d96a4e0ca0107a8edc3fad501ace44749362a7
BLAKE2b-256 checksum
How to use checksums
13f333b1491904089131b88c51e3937982bae7984419c1ecfd7056fff5fef820
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.15

Release files / flagsmith_second_opinion-0.1.1-py3-none-any.whl

Download URL flagsmith_second_opinion-0.1.1-py3-none-any.whl
Size 60.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a7bf737d22573482ff8f819efd4df3b834ab893a1028e3554beaa7de8a5e1e8e
BLAKE2b-256 checksum
How to use checksums
83fcca61badfb26203687031ba6f2756223eaa809445967e8ca3426f0e9df2ce
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.15

Security for flagsmith-second-opinion 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page