flagsmith-second-opinion 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. flagsmith_second_opinion-0.1.0/LICENSE +11 -0
  2. flagsmith_second_opinion-0.1.0/PKG-INFO +262 -0
  3. flagsmith_second_opinion-0.1.0/README.md +227 -0
  4. flagsmith_second_opinion-0.1.0/flagsmith_second_opinion.egg-info/PKG-INFO +262 -0
  5. flagsmith_second_opinion-0.1.0/flagsmith_second_opinion.egg-info/SOURCES.txt +50 -0
  6. flagsmith_second_opinion-0.1.0/flagsmith_second_opinion.egg-info/dependency_links.txt +1 -0
  7. flagsmith_second_opinion-0.1.0/flagsmith_second_opinion.egg-info/entry_points.txt +2 -0
  8. flagsmith_second_opinion-0.1.0/flagsmith_second_opinion.egg-info/requires.txt +18 -0
  9. flagsmith_second_opinion-0.1.0/flagsmith_second_opinion.egg-info/top_level.txt +1 -0
  10. flagsmith_second_opinion-0.1.0/pyproject.toml +65 -0
  11. flagsmith_second_opinion-0.1.0/second_opinion/__init__.py +5 -0
  12. flagsmith_second_opinion-0.1.0/second_opinion/checks/__init__.py +23 -0
  13. flagsmith_second_opinion-0.1.0/second_opinion/checks/base.py +22 -0
  14. flagsmith_second_opinion-0.1.0/second_opinion/checks/c1_srm.py +43 -0
  15. flagsmith_second_opinion-0.1.0/second_opinion/checks/c2_primary.py +166 -0
  16. flagsmith_second_opinion-0.1.0/second_opinion/checks/c3_guardrails.py +127 -0
  17. flagsmith_second_opinion-0.1.0/second_opinion/checks/c4_segments.py +186 -0
  18. flagsmith_second_opinion-0.1.0/second_opinion/checks/c5_novelty.py +147 -0
  19. flagsmith_second_opinion-0.1.0/second_opinion/checks/c6_sequential.py +101 -0
  20. flagsmith_second_opinion-0.1.0/second_opinion/checks/c7_event_quality.py +156 -0
  21. flagsmith_second_opinion-0.1.0/second_opinion/cli.py +544 -0
  22. flagsmith_second_opinion-0.1.0/second_opinion/config.py +134 -0
  23. flagsmith_second_opinion-0.1.0/second_opinion/flagsmith_api.py +68 -0
  24. flagsmith_second_opinion-0.1.0/second_opinion/report/__init__.py +17 -0
  25. flagsmith_second_opinion-0.1.0/second_opinion/report/html_reporter.py +257 -0
  26. flagsmith_second_opinion-0.1.0/second_opinion/report/json_reporter.py +14 -0
  27. flagsmith_second_opinion-0.1.0/second_opinion/report/markdown_reporter.py +104 -0
  28. flagsmith_second_opinion-0.1.0/second_opinion/sim/__init__.py +8 -0
  29. flagsmith_second_opinion-0.1.0/second_opinion/sim/generator.py +231 -0
  30. flagsmith_second_opinion-0.1.0/second_opinion/sim/proxy.py +135 -0
  31. flagsmith_second_opinion-0.1.0/second_opinion/sim/scenarios.py +78 -0
  32. flagsmith_second_opinion-0.1.0/second_opinion/sources/__init__.py +42 -0
  33. flagsmith_second_opinion-0.1.0/second_opinion/sources/base.py +92 -0
  34. flagsmith_second_opinion-0.1.0/second_opinion/sources/clickhouse.py +68 -0
  35. flagsmith_second_opinion-0.1.0/second_opinion/sources/csv_source.py +310 -0
  36. flagsmith_second_opinion-0.1.0/second_opinion/sources/postgres.py +180 -0
  37. flagsmith_second_opinion-0.1.0/second_opinion/stats/__init__.py +41 -0
  38. flagsmith_second_opinion-0.1.0/second_opinion/stats/bayes.py +188 -0
  39. flagsmith_second_opinion-0.1.0/second_opinion/stats/flagsmith_replica.py +65 -0
  40. flagsmith_second_opinion-0.1.0/second_opinion/stats/freq.py +142 -0
  41. flagsmith_second_opinion-0.1.0/second_opinion/stats/math_utils.py +236 -0
  42. flagsmith_second_opinion-0.1.0/second_opinion/stats/sequential.py +124 -0
  43. flagsmith_second_opinion-0.1.0/second_opinion/stats/srm.py +137 -0
  44. flagsmith_second_opinion-0.1.0/second_opinion/verdict.py +254 -0
  45. flagsmith_second_opinion-0.1.0/setup.cfg +4 -0
  46. flagsmith_second_opinion-0.1.0/tests/test_calibration_validation.py +73 -0
  47. flagsmith_second_opinion-0.1.0/tests/test_checks.py +70 -0
  48. flagsmith_second_opinion-0.1.0/tests/test_cli.py +70 -0
  49. flagsmith_second_opinion-0.1.0/tests/test_math_vs_scipy.py +140 -0
  50. flagsmith_second_opinion-0.1.0/tests/test_numbers_consistency.py +82 -0
  51. flagsmith_second_opinion-0.1.0/tests/test_scenarios_golden.py +75 -0
  52. flagsmith_second_opinion-0.1.0/tests/test_stats.py +85 -0
@@ -0,0 +1,11 @@
1
+ Copyright 2026 Ankit Kumar Tiwari
2
+
3
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
4
+
5
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
6
+
7
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
8
+
9
+ 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
10
+
11
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,262 @@
1
+ Metadata-Version: 2.4
2
+ Name: flagsmith-second-opinion
3
+ Version: 0.1.0
4
+ Summary: A read-only trust layer and deploy gate for Flagsmith experimentation
5
+ Author: Toggle Wars Track 03 Team
6
+ License: BSD-3-Clause
7
+ Classifier: Development Status :: 4 - Beta
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: License :: OSI Approved :: BSD License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: pyyaml>=6.0
19
+ Provides-Extra: full
20
+ Requires-Dist: numpy>=1.26.0; extra == "full"
21
+ Requires-Dist: scipy>=1.12.0; extra == "full"
22
+ Requires-Dist: typer>=0.12.0; extra == "full"
23
+ Requires-Dist: rich>=13.7.0; extra == "full"
24
+ Requires-Dist: jinja2>=3.1.0; extra == "full"
25
+ Requires-Dist: httpx>=0.27.0; extra == "full"
26
+ Requires-Dist: duckdb>=0.10.0; extra == "full"
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
29
+ Requires-Dist: hypothesis>=6.100.0; extra == "dev"
30
+ Requires-Dist: ruff>=0.4.0; extra == "dev"
31
+ Requires-Dist: mypy>=1.10.0; extra == "dev"
32
+ Requires-Dist: numpy>=1.26.0; extra == "dev"
33
+ Requires-Dist: scipy>=1.12.0; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ <p align="center">
37
+ <picture>
38
+ <source media="(prefers-color-scheme: dark)" srcset="docs/wemakedevs_flagsmith_logo.svg">
39
+ <source media="(prefers-color-scheme: light)" srcset="docs/wemakedevs_flagsmith_logo_light.svg">
40
+ <img src="docs/wemakedevs_flagsmith_logo.png" alt="WeMakeDevs x Flagsmith Experimentation" width="480"/>
41
+ </picture>
42
+ </p>
43
+
44
+ # Second Opinion
45
+
46
+ > **A read-only trust layer and automated deploy gate for self-hosted Flagsmith Experimentation.**
47
+ > *Toggle Wars Track 03: Build on Open Source Flagsmith*
48
+
49
+ [![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)
50
+ [![License](https://img.shields.io/badge/license-BSD--3--Clause-blue.svg)](LICENSE)
51
+ [![Python](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue)](pyproject.toml)
52
+
53
+ ---
54
+
55
+ ## What is Second Opinion?
56
+
57
+ Flagsmith makes it easy to run feature-flag experiments. But in production, shipping code whenever a dashboard card turns green can be dangerous:
58
+
59
+ - **Simpson's Paradox:** Overall conversion looks positive (+13.3%), but mobile users suffer a severe -16.2% drop.
60
+ - **Guardrail Regressions:** Purchases increase, but refund requests quietly spike by +81.8%.
61
+ - **Peeking Bias:** Checking daily and stopping early inflates false positive rates up to about 19-20% (varies slightly with Python version).
62
+
63
+ **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.
64
+
65
+ ---
66
+
67
+ ## System Architecture
68
+
69
+ ```mermaid
70
+ flowchart TD
71
+ subgraph Flagsmith["Self-Hosted Flagsmith"]
72
+ Flags["Multivariate Flags (Control vs Treatment)"]
73
+ SDK["Flagsmith SDKs (Client & Server)"]
74
+ Flags --> SDK
75
+ SDK -->|"Emits exposures & events"| PG[("PostgreSQL\n(experimentation_sdkexperimentationevent)")]
76
+ end
77
+
78
+ subgraph SecondOpinion["Second Opinion Trust Layer (Read-Only)"]
79
+ API_Client["Flagsmith API Client\n(Reads configs & baselines)"]
80
+ PG_Reader["PostgreSQL Reader\n(Direct read-only event stream)"]
81
+
82
+ Engine{"Statistical Engine\n(7 Verification Checks)"}
83
+
84
+ API_Client --> Engine
85
+ PG_Reader --> Engine
86
+
87
+ C1["C1: Sample Ratio (Chi-Square)"]
88
+ C2["C2: Primary Effect (Delta Method & Bayes)"]
89
+ C3["C3: Guardrails (Tolerance Loss)"]
90
+ C4["C4: Subgroups (Simpson's Paradox)"]
91
+ C5["C5: Novelty Effect (Decay Tracking)"]
92
+ C6["C6: Peeking (mSPRT Always-Valid)"]
93
+ C7["C7: Data Hygiene (Event Linter)"]
94
+
95
+ Engine --- C1
96
+ Engine --- C2
97
+ Engine --- C3
98
+ Engine --- C4
99
+ Engine --- C5
100
+ Engine --- C6
101
+ Engine --- C7
102
+ end
103
+
104
+ subgraph CICD["Deployment Pipeline (CI/CD)"]
105
+ Engine -->|"Exit 0"| SHIP["🟢 SHIP: Merge PR / Rollout Winner"]
106
+ Engine -->|"Exit 10"| HOLD["🟡 HOLD: Continue Experimentation"]
107
+ Engine -->|"Exit 20"| VETO["🔴 DON'T SHIP: Block Deploy & Alert"]
108
+ end
109
+ ```
110
+
111
+ ---
112
+
113
+ ## How Flagsmith Experimentation Works with Second Opinion
114
+
115
+ 1. **Round 01 (Create Flag):** Discovers multivariate flags and baseline controls via Flagsmith's API.
116
+ 2. **Round 02 (Pick Metric):** Ingests conversion and guardrail events from the PostgreSQL event table.
117
+ 3. **Round 03 (Split Traffic):** Audits `$flag_exposure` events to verify traffic ratios without tracking bias.
118
+ 4. **Round 04 (Ship Winner):** Evaluates 7 statistical checks to return a binary CI exit code before rollout.
119
+
120
+ ---
121
+
122
+ ## The Verdict Card
123
+
124
+ Here is what happens when Second Opinion evaluates an experiment where aggregate conversions look positive, but mobile users are being harmed:
125
+
126
+ ```text
127
+ checkout_button environment: Development 24,000 identities
128
+ Flagsmith: Winning, 99.7% chance to win, +13.3% lift
129
+ Second Opinion: DON'T SHIP (Exit 20)
130
+
131
+ VETO VETO: Credible harm detected in subgroup: Segment 'platform=mobile': lift -16.2%, 95% interval (-26.4%, -4.5%), 6000 identities/arm
132
+ info Variant 'treatment' not safe to stop (mSPRT p=0.0716 > 0.05).
133
+ ok Sample ratio matches expected split (chi2=0.00, df=1, p=1.0000).
134
+ ok Second Opinion's Bayesian estimate: chance to win 99.8%, frequentist p=0.0030, lift +13.3%.
135
+ ok No guardrail metrics configured.
136
+ ok Event data quality verified: clean schemas, zero naming anomalies, high integrity.
137
+ ```
138
+
139
+ ---
140
+
141
+ ## 30-Second Quickstart (Zero Setup Needed)
142
+
143
+ Second Opinion includes 7 built-in test fixtures with planted traps so you can test it immediately without needing a database:
144
+
145
+ ```bash
146
+ # 1. Clone the repository
147
+ git clone https://github.com/ankit-cybertron/Second_Opinion.git
148
+ cd Second_Opinion
149
+
150
+ # 2. Install
151
+ pip install -e .
152
+
153
+ # 3. Catch Simpson's Paradox / Mobile harm (exits with code 20)
154
+ so analyze --demo hidden-harm
155
+
156
+ # 4. Generate an interactive visual HTML report
157
+ so analyze --demo hidden-harm --format html -o report.html
158
+ open report.html
159
+ ```
160
+
161
+ ---
162
+
163
+ ## The Three Real Traps Caught
164
+
165
+ | Experiment Trap | Flagsmith Dashboard Alone | Second Opinion Trust Layer | Verdict & Action |
166
+ | :--- | :--- | :--- | :--- |
167
+ | **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. |
168
+ | **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. |
169
+ | **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. |
170
+
171
+ ---
172
+
173
+ ## The Seven Planted-Trap Scenarios
174
+
175
+ Every claim is backed by reproducible test runs on golden fixtures:
176
+
177
+ | Scenario | Planted Trap | Flagsmith View | Second Opinion Verdict | Exit Code |
178
+ | :--- | :--- | :--- | :---: | :---: |
179
+ | `honest-win` | Authentic lift (8% $\to$ 10%, 16k users) | Winning (+29.9% lift) | 🟢 **SHIP** | `0` |
180
+ | `srm` | Assignment bug (70/30 split on 50/50 flag) | Unreliable split ($p < 10^{-15}$) | 🔴 **DON'T SHIP** (C1) | `20` |
181
+ | `hidden-harm` | Simpson's Paradox: mobile harmed (-16.2%) | Winning (99.7% win prob, +13.3% lift) | 🔴 **DON'T SHIP** (C4) | `20` |
182
+ | `novelty` | Day 1 surge (+82.7%) collapses by Days 2–3 | Winning overall from Day 1 spike | 🔴 **DON'T SHIP** (C5) | `20` |
183
+ | `guardrail` | Purchases up (+26.0%), but refunds spike +81.8% | Winning on purchase metric (99.5% win) | 🔴 **DON'T SHIP** (C3) | `20` |
184
+ | `dirty-events` | 15% conversions sent as `Signup_Completed` | Instrumentation case defect | 🟡 **HOLD** (C7) | `10` |
185
+ | `peeking-aa` | True A/A test under daily peeking | False win spikes at early looks | 🟡 **HOLD** (C6) | `10` |
186
+
187
+ ---
188
+
189
+ ## Empirical Statistical Validation
190
+
191
+ From `scripts/validate.py` (2,000 A/A Monte Carlo simulations with an 8% base rate):
192
+
193
+ ```text
194
+ Results across 2,000 A/A replicates:
195
+ Naive peeking false win rate (14 daily looks): 19.60% (about 19-20% (varies slightly with Python version))
196
+ Second Opinion mSPRT false alarm rate (20 looks): 1.80% (about 1-2%)
197
+ Full Engine false SHIP rate (completed tests): 0.15% (Strictly <= 5.0%)
198
+ ```
199
+
200
+ ---
201
+
202
+ ## The Seven Checks
203
+
204
+ Second Opinion evaluates seven safety checks before clearing an experiment:
205
+
206
+ - **C1: Sample Ratio (SRM):** Verifies traffic split matches configuration ($p < 0.001$ = Blocker).
207
+ - **C2: Primary Effect:** Computes delta-method lift & Bayesian win probability (matches Flagsmith $< 10^{-6}$).
208
+ - **C3: Guardrail Protection:** Ensures secondary metrics (e.g. refunds, latency) do not exceed tolerance.
209
+ - **C4: Subgroup Harm:** Checks segments for Simpson's paradox with Benjamini-Hochberg FDR control.
210
+ - **C5: Novelty Decay:** Compares Day 1 lift against Days 2–3 to catch early novelty surges that fade.
211
+ - **C6: Sequential Stopping:** mSPRT always-valid $p$-value prevents false wins from daily peeking.
212
+ - **C7: Data Hygiene:** Lints for casing mismatches (e.g. `Signup_Completed` vs `signup_completed`) and dropped events.
213
+
214
+ ---
215
+
216
+ ## CI/CD Deploy Gate
217
+
218
+ Add Second Opinion directly to your deployment pipeline to fail pull requests on `Exit 20`:
219
+
220
+ ```yaml
221
+ name: experiment-gate
222
+ on: pull_request
223
+
224
+ jobs:
225
+ gate:
226
+ runs-on: ubuntu-latest
227
+ steps:
228
+ - uses: actions/checkout@v4
229
+ - uses: ./
230
+ with:
231
+ experiment: checkout_button
232
+ fail-on: dont-ship
233
+ env:
234
+ SO_DATABASE_URL: ${{ secrets.SO_DATABASE_URL }}
235
+ ```
236
+
237
+ | Verdict | Exit Code | Action in CI |
238
+ | :--- | :---: | :--- |
239
+ | `SHIP` | `0` | 🟢 Automatically merge or deploy winner |
240
+ | `HOLD` | `10` | 🟡 Keep experiment running; data not ready |
241
+ | `DON'T SHIP` | `20` | 🔴 Block rollout; notify engineering team |
242
+
243
+ ---
244
+
245
+ ## Track 03: Build on Open Source Flagsmith
246
+
247
+ <p align="center">
248
+ <img src="docs/wemakedevs_flagsmith_logo.png" alt="WeMakeDevs x Flagsmith Experiment" width="360"/>
249
+ </p>
250
+
251
+ Second Opinion is designed specifically for **Track 03** of the WeMakeDevs Flagsmith Hackathon:
252
+
253
+ - **Self-Hosted First:** Connects directly to self-hosted Flagsmith API and PostgreSQL event stream.
254
+ - **Zero-Dependency Quickstart:** Evaluates offline in 15 seconds with 7 frozen golden fixtures.
255
+ - **Non-Invasive:** 100% read-only. Zero database migrations, zero schema changes.
256
+ - **Mathematical Parity:** Verified to match Flagsmith's server-side delta-method calculations within $|\Delta| < 10^{-6}$.
257
+
258
+ ---
259
+
260
+ ## License
261
+
262
+ BSD-3-Clause License. Open source and free for enterprise or community use.
@@ -0,0 +1,227 @@
1
+ <p align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="docs/wemakedevs_flagsmith_logo.svg">
4
+ <source media="(prefers-color-scheme: light)" srcset="docs/wemakedevs_flagsmith_logo_light.svg">
5
+ <img src="docs/wemakedevs_flagsmith_logo.png" alt="WeMakeDevs x Flagsmith Experimentation" width="480"/>
6
+ </picture>
7
+ </p>
8
+
9
+ # Second Opinion
10
+
11
+ > **A read-only trust layer and automated deploy gate for self-hosted Flagsmith Experimentation.**
12
+ > *Toggle Wars Track 03: Build on Open Source Flagsmith*
13
+
14
+ [![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)
15
+ [![License](https://img.shields.io/badge/license-BSD--3--Clause-blue.svg)](LICENSE)
16
+ [![Python](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue)](pyproject.toml)
17
+
18
+ ---
19
+
20
+ ## What is Second Opinion?
21
+
22
+ Flagsmith makes it easy to run feature-flag experiments. But in production, shipping code whenever a dashboard card turns green can be dangerous:
23
+
24
+ - **Simpson's Paradox:** Overall conversion looks positive (+13.3%), but mobile users suffer a severe -16.2% drop.
25
+ - **Guardrail Regressions:** Purchases increase, but refund requests quietly spike by +81.8%.
26
+ - **Peeking Bias:** Checking daily and stopping early inflates false positive rates up to about 19-20% (varies slightly with Python version).
27
+
28
+ **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.
29
+
30
+ ---
31
+
32
+ ## System Architecture
33
+
34
+ ```mermaid
35
+ flowchart TD
36
+ subgraph Flagsmith["Self-Hosted Flagsmith"]
37
+ Flags["Multivariate Flags (Control vs Treatment)"]
38
+ SDK["Flagsmith SDKs (Client & Server)"]
39
+ Flags --> SDK
40
+ SDK -->|"Emits exposures & events"| PG[("PostgreSQL\n(experimentation_sdkexperimentationevent)")]
41
+ end
42
+
43
+ subgraph SecondOpinion["Second Opinion Trust Layer (Read-Only)"]
44
+ API_Client["Flagsmith API Client\n(Reads configs & baselines)"]
45
+ PG_Reader["PostgreSQL Reader\n(Direct read-only event stream)"]
46
+
47
+ Engine{"Statistical Engine\n(7 Verification Checks)"}
48
+
49
+ API_Client --> Engine
50
+ PG_Reader --> Engine
51
+
52
+ C1["C1: Sample Ratio (Chi-Square)"]
53
+ C2["C2: Primary Effect (Delta Method & Bayes)"]
54
+ C3["C3: Guardrails (Tolerance Loss)"]
55
+ C4["C4: Subgroups (Simpson's Paradox)"]
56
+ C5["C5: Novelty Effect (Decay Tracking)"]
57
+ C6["C6: Peeking (mSPRT Always-Valid)"]
58
+ C7["C7: Data Hygiene (Event Linter)"]
59
+
60
+ Engine --- C1
61
+ Engine --- C2
62
+ Engine --- C3
63
+ Engine --- C4
64
+ Engine --- C5
65
+ Engine --- C6
66
+ Engine --- C7
67
+ end
68
+
69
+ subgraph CICD["Deployment Pipeline (CI/CD)"]
70
+ Engine -->|"Exit 0"| SHIP["🟢 SHIP: Merge PR / Rollout Winner"]
71
+ Engine -->|"Exit 10"| HOLD["🟡 HOLD: Continue Experimentation"]
72
+ Engine -->|"Exit 20"| VETO["🔴 DON'T SHIP: Block Deploy & Alert"]
73
+ end
74
+ ```
75
+
76
+ ---
77
+
78
+ ## How Flagsmith Experimentation Works with Second Opinion
79
+
80
+ 1. **Round 01 (Create Flag):** Discovers multivariate flags and baseline controls via Flagsmith's API.
81
+ 2. **Round 02 (Pick Metric):** Ingests conversion and guardrail events from the PostgreSQL event table.
82
+ 3. **Round 03 (Split Traffic):** Audits `$flag_exposure` events to verify traffic ratios without tracking bias.
83
+ 4. **Round 04 (Ship Winner):** Evaluates 7 statistical checks to return a binary CI exit code before rollout.
84
+
85
+ ---
86
+
87
+ ## The Verdict Card
88
+
89
+ Here is what happens when Second Opinion evaluates an experiment where aggregate conversions look positive, but mobile users are being harmed:
90
+
91
+ ```text
92
+ checkout_button environment: Development 24,000 identities
93
+ Flagsmith: Winning, 99.7% chance to win, +13.3% lift
94
+ Second Opinion: DON'T SHIP (Exit 20)
95
+
96
+ VETO VETO: Credible harm detected in subgroup: Segment 'platform=mobile': lift -16.2%, 95% interval (-26.4%, -4.5%), 6000 identities/arm
97
+ info Variant 'treatment' not safe to stop (mSPRT p=0.0716 > 0.05).
98
+ ok Sample ratio matches expected split (chi2=0.00, df=1, p=1.0000).
99
+ ok Second Opinion's Bayesian estimate: chance to win 99.8%, frequentist p=0.0030, lift +13.3%.
100
+ ok No guardrail metrics configured.
101
+ ok Event data quality verified: clean schemas, zero naming anomalies, high integrity.
102
+ ```
103
+
104
+ ---
105
+
106
+ ## 30-Second Quickstart (Zero Setup Needed)
107
+
108
+ Second Opinion includes 7 built-in test fixtures with planted traps so you can test it immediately without needing a database:
109
+
110
+ ```bash
111
+ # 1. Clone the repository
112
+ git clone https://github.com/ankit-cybertron/Second_Opinion.git
113
+ cd Second_Opinion
114
+
115
+ # 2. Install
116
+ pip install -e .
117
+
118
+ # 3. Catch Simpson's Paradox / Mobile harm (exits with code 20)
119
+ so analyze --demo hidden-harm
120
+
121
+ # 4. Generate an interactive visual HTML report
122
+ so analyze --demo hidden-harm --format html -o report.html
123
+ open report.html
124
+ ```
125
+
126
+ ---
127
+
128
+ ## The Three Real Traps Caught
129
+
130
+ | Experiment Trap | Flagsmith Dashboard Alone | Second Opinion Trust Layer | Verdict & Action |
131
+ | :--- | :--- | :--- | :--- |
132
+ | **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. |
133
+ | **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. |
134
+ | **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. |
135
+
136
+ ---
137
+
138
+ ## The Seven Planted-Trap Scenarios
139
+
140
+ Every claim is backed by reproducible test runs on golden fixtures:
141
+
142
+ | Scenario | Planted Trap | Flagsmith View | Second Opinion Verdict | Exit Code |
143
+ | :--- | :--- | :--- | :---: | :---: |
144
+ | `honest-win` | Authentic lift (8% $\to$ 10%, 16k users) | Winning (+29.9% lift) | 🟢 **SHIP** | `0` |
145
+ | `srm` | Assignment bug (70/30 split on 50/50 flag) | Unreliable split ($p < 10^{-15}$) | 🔴 **DON'T SHIP** (C1) | `20` |
146
+ | `hidden-harm` | Simpson's Paradox: mobile harmed (-16.2%) | Winning (99.7% win prob, +13.3% lift) | 🔴 **DON'T SHIP** (C4) | `20` |
147
+ | `novelty` | Day 1 surge (+82.7%) collapses by Days 2–3 | Winning overall from Day 1 spike | 🔴 **DON'T SHIP** (C5) | `20` |
148
+ | `guardrail` | Purchases up (+26.0%), but refunds spike +81.8% | Winning on purchase metric (99.5% win) | 🔴 **DON'T SHIP** (C3) | `20` |
149
+ | `dirty-events` | 15% conversions sent as `Signup_Completed` | Instrumentation case defect | 🟡 **HOLD** (C7) | `10` |
150
+ | `peeking-aa` | True A/A test under daily peeking | False win spikes at early looks | 🟡 **HOLD** (C6) | `10` |
151
+
152
+ ---
153
+
154
+ ## Empirical Statistical Validation
155
+
156
+ From `scripts/validate.py` (2,000 A/A Monte Carlo simulations with an 8% base rate):
157
+
158
+ ```text
159
+ Results across 2,000 A/A replicates:
160
+ Naive peeking false win rate (14 daily looks): 19.60% (about 19-20% (varies slightly with Python version))
161
+ Second Opinion mSPRT false alarm rate (20 looks): 1.80% (about 1-2%)
162
+ Full Engine false SHIP rate (completed tests): 0.15% (Strictly <= 5.0%)
163
+ ```
164
+
165
+ ---
166
+
167
+ ## The Seven Checks
168
+
169
+ Second Opinion evaluates seven safety checks before clearing an experiment:
170
+
171
+ - **C1: Sample Ratio (SRM):** Verifies traffic split matches configuration ($p < 0.001$ = Blocker).
172
+ - **C2: Primary Effect:** Computes delta-method lift & Bayesian win probability (matches Flagsmith $< 10^{-6}$).
173
+ - **C3: Guardrail Protection:** Ensures secondary metrics (e.g. refunds, latency) do not exceed tolerance.
174
+ - **C4: Subgroup Harm:** Checks segments for Simpson's paradox with Benjamini-Hochberg FDR control.
175
+ - **C5: Novelty Decay:** Compares Day 1 lift against Days 2–3 to catch early novelty surges that fade.
176
+ - **C6: Sequential Stopping:** mSPRT always-valid $p$-value prevents false wins from daily peeking.
177
+ - **C7: Data Hygiene:** Lints for casing mismatches (e.g. `Signup_Completed` vs `signup_completed`) and dropped events.
178
+
179
+ ---
180
+
181
+ ## CI/CD Deploy Gate
182
+
183
+ Add Second Opinion directly to your deployment pipeline to fail pull requests on `Exit 20`:
184
+
185
+ ```yaml
186
+ name: experiment-gate
187
+ on: pull_request
188
+
189
+ jobs:
190
+ gate:
191
+ runs-on: ubuntu-latest
192
+ steps:
193
+ - uses: actions/checkout@v4
194
+ - uses: ./
195
+ with:
196
+ experiment: checkout_button
197
+ fail-on: dont-ship
198
+ env:
199
+ SO_DATABASE_URL: ${{ secrets.SO_DATABASE_URL }}
200
+ ```
201
+
202
+ | Verdict | Exit Code | Action in CI |
203
+ | :--- | :---: | :--- |
204
+ | `SHIP` | `0` | 🟢 Automatically merge or deploy winner |
205
+ | `HOLD` | `10` | 🟡 Keep experiment running; data not ready |
206
+ | `DON'T SHIP` | `20` | 🔴 Block rollout; notify engineering team |
207
+
208
+ ---
209
+
210
+ ## Track 03: Build on Open Source Flagsmith
211
+
212
+ <p align="center">
213
+ <img src="docs/wemakedevs_flagsmith_logo.png" alt="WeMakeDevs x Flagsmith Experiment" width="360"/>
214
+ </p>
215
+
216
+ Second Opinion is designed specifically for **Track 03** of the WeMakeDevs Flagsmith Hackathon:
217
+
218
+ - **Self-Hosted First:** Connects directly to self-hosted Flagsmith API and PostgreSQL event stream.
219
+ - **Zero-Dependency Quickstart:** Evaluates offline in 15 seconds with 7 frozen golden fixtures.
220
+ - **Non-Invasive:** 100% read-only. Zero database migrations, zero schema changes.
221
+ - **Mathematical Parity:** Verified to match Flagsmith's server-side delta-method calculations within $|\Delta| < 10^{-6}$.
222
+
223
+ ---
224
+
225
+ ## License
226
+
227
+ BSD-3-Clause License. Open source and free for enterprise or community use.