breakitdown 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.
@@ -0,0 +1,22 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ build/
6
+ dist/
7
+ .venv/
8
+ venv/
9
+ .pytest_cache/
10
+ .coverage
11
+ htmlcov/
12
+ .ipynb_checkpoints/
13
+
14
+ # Spark local runs
15
+ spark-warehouse/
16
+ metastore_db/
17
+ derby.log
18
+
19
+ # Editors and OS
20
+ .idea/
21
+ .vscode/
22
+ .DS_Store
@@ -0,0 +1,18 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-11-06)
4
+
5
+ First release.
6
+
7
+ - `Experiment` and `MetricTable`: A/B analysis on Spark.
8
+ - Tables that carry the flight on every row work out of the box.
9
+ - Joining one `FlightMapping` to many metric tables is opt-in.
10
+ - Metrics: `Count`, `Binary`, `Ratio` and `Quantile`. Quantiles have `regular` and `density` methods.
11
+ - User segments and metric segments, in any combination, with cumulative and daily results.
12
+ - Inference:
13
+ - Welch t-tests.
14
+ - Delta-method ratio and relative-difference intervals.
15
+ - Unit-clustered quantile variance.
16
+ - Benjamini–Hochberg adjustment.
17
+ - Pairwise sample-ratio-mismatch tests.
18
+ - Cochran's Q test for heterogeneous effects.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,375 @@
1
+ Metadata-Version: 2.5
2
+ Name: breakitdown
3
+ Version: 0.1.0
4
+ Summary: A/B test analysis on Spark, broken down by any user or metric segment.
5
+ Project-URL: Homepage, https://github.com/lukewarm/breakitdown
6
+ Project-URL: Issues, https://github.com/lukewarm/breakitdown/issues
7
+ Project-URL: Changelog, https://github.com/lukewarm/breakitdown/blob/main/CHANGELOG.md
8
+ Author: Max He
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: a/b testing,delta method,experimentation,pyspark,spark,statistics
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.9
20
+ Requires-Dist: numpy>=1.22
21
+ Requires-Dist: pandas>=1.4
22
+ Requires-Dist: scipy>=1.7
23
+ Provides-Extra: spark
24
+ Requires-Dist: pyspark>=3.3; extra == 'spark'
25
+ Provides-Extra: test
26
+ Requires-Dist: pyspark>=3.3; extra == 'test'
27
+ Requires-Dist: pytest-timeout>=2; extra == 'test'
28
+ Requires-Dist: pytest>=7; extra == 'test'
29
+ Requires-Dist: scipy>=1.11; extra == 'test'
30
+ Description-Content-Type: text/markdown
31
+
32
+ # breakitdown
33
+
34
+ **Break it down: A/B tests on Spark, sliced any way you like.**
35
+
36
+ breakitdown compares the flights (variants) of an A/B test on data in Spark. It breaks every result
37
+ down by user segment (os, country, or any combination), by metric segment (say, clicks on photos vs
38
+ clicks on videos) and by day, all through one small Python API. It works on the tables you already
39
+ have: if they carry the flight on every row, nothing needs to be joined.
40
+
41
+ * **Any breakdown, no SQL.** Name user segments on the experiment and metric segments on a table.
42
+ Every combination is computed and tested, each with the right denominator.
43
+ * **Four metric kinds.** Per-user counts, binary rates, ratios and quantiles, all with unit-level
44
+ (clustered) variances.
45
+ * **Tidy output.** One pandas DataFrame with one row per comparison, ready for notebooks and dashboards.
46
+ * **Built for Spark.** Each table is reduced to sufficient statistics in Spark. Only those reach the
47
+ driver.
48
+
49
+ ## Install
50
+
51
+ ```bash
52
+ pip install breakitdown # on a Spark cluster: uses the cluster's PySpark
53
+ pip install "breakitdown[spark]" # anywhere else: installs PySpark too
54
+ ```
55
+
56
+ Requires Python 3.9+ and PySpark 3.3+, and is tested with PySpark 3.5 and 4.3. Running Spark locally
57
+ needs Java 17.
58
+
59
+ ## Quick start
60
+
61
+ `analytics.app_events` carries the flight on every row. This table has one row per user, day and
62
+ media type; any grain at or below user × day works.
63
+
64
+ | ruid | flight | event_time | os | country | media_type | clicks | sessions |
65
+ |------|---------|------------|---------|---------|------------|-------:|---------:|
66
+ | u1 | control | 2024-03-01 | ios | US | photo | 3 | 2 |
67
+ | u1 | control | 2024-03-01 | ios | US | video | 1 | 0 |
68
+ | u2 | t1 | 2024-03-02 | android | GB | photo | 0 | 1 |
69
+
70
+ ```python
71
+ from breakitdown import Binary, Count, Experiment, MetricTable, Ratio
72
+
73
+ exp = Experiment(control="control", treatments=["t1", "t2"], start="2024-03-01", end="2024-03-14")
74
+
75
+ events = MetricTable("analytics.app_events", [
76
+ Count("clicks"), # mean clicks per user
77
+ Binary("clicks", name="clickers"), # share of users with any click
78
+ Ratio("clicks", "sessions", name="clicks_per_session"), # sum of clicks / sum of sessions
79
+ ])
80
+
81
+ results = exp.analyze(events)
82
+ results.overall()
83
+ ```
84
+
85
+ ```text
86
+ metric treatment n_control n_treatment value_control value_treatment pct_diff pct_diff_ci_lower pct_diff_ci_upper p_value outcome
87
+ clicks t1 1003 1020 1.299 1.523 +17.20 +6.15 +28.25 0.0010 better
88
+ clicks t2 1003 977 1.299 1.294 -0.41 -10.05 +9.23 0.9334 flat
89
+ clickers t1 1003 1020 0.6271 0.6696 +6.78 -0.10 +13.65 0.0454 better
90
+ clickers t2 1003 977 0.6271 0.6469 +3.15 -3.72 +10.02 0.3609 flat
91
+ clicks_per_session t1 1003 1020 0.1493 0.1822 +22.02 +12.90 +31.14 <0.0001 better
92
+ clicks_per_session t2 1003 977 0.1493 0.1524 +2.08 -5.91 +10.08 0.6059 flat
93
+ ```
94
+
95
+ * **Rows:** each row compares one treatment with control. CIs are 95% (`analyze(alpha=...)`).
96
+ The [Methods](#methods) section explains the `clickers` t1 row, whose relative CI just includes 0
97
+ while p < 0.05.
98
+ * **Everything else:** `results.table` holds every comparison, including segments and days. In a
99
+ notebook, `results` renders as a colour-coded scorecard.
100
+ * **Column names:** the defaults are `ruid` (randomization unit), `flight` and `event_time`; see
101
+ [Input contract](#input-contract).
102
+
103
+ ## Examples
104
+
105
+ Each example adds one idea to the quick start.
106
+
107
+ ### Break it down: user segments and metric segments
108
+
109
+ ```python
110
+ exp = Experiment("control", ["t1", "t2"], "2024-03-01", "2024-03-14",
111
+ user_segments=["os", ("os", "country")])
112
+ events = MetricTable("analytics.app_events", [Count("clicks")], metric_segments=["media_type"])
113
+ results = exp.analyze(events)
114
+
115
+ results.by_user_segment("os") # one row per os value and treatment
116
+ results.by_metric_segment("media_type") # clicks on photos and on videos, per user in the flight
117
+ results.hte() # does the effect differ across os values?
118
+ results.daily("clicks") # each day on its own
119
+ ```
120
+
121
+ * **User segments** split *users*: each user has one `os`.
122
+ * **Metric segments** split a metric's *rows*: one user can click both photos and videos. The
123
+ denominator stays every user in the flight, so the segment values of a Count add up to its overall
124
+ value.
125
+ * **Combinations:** every user segment is crossed with every metric segment.
126
+ * **Daily results:** each day's denominator is the users exposed by that day.
127
+
128
+ ### Quantiles, labels and the desired direction
129
+
130
+ ```python
131
+ from breakitdown import Quantile
132
+
133
+ latency = MetricTable(
134
+ "analytics.request_latency", # one row per request
135
+ [Quantile("latency_ms", [0.5, 0.9], method="density", label="Latency", direction="down")],
136
+ )
137
+ results = exp.analyze([events, latency])
138
+ ```
139
+
140
+ * `direction` (`"up"`, `"down"` or `"neutral"`) decides whether a significant change is `better` or
141
+ `worse` in `outcome`.
142
+ * Every metric has a `name` (a unique id, defaulting to the column) and a `label` (display text).
143
+ * Quantiles pool all rows of a flight, with users as clusters. `method="density"` suits
144
+ integer-valued metrics; see [Methods](#methods).
145
+
146
+ ### Joining a flight mapping (opt-in)
147
+
148
+ Use this when metric tables don't carry the flight, or when users without rows must count as zeros:
149
+
150
+ ```python
151
+ from breakitdown import Columns, FlightMapping
152
+
153
+ exp = Experiment(
154
+ "control", ["t1", "t2"], "2024-03-01", "2024-03-14",
155
+ mapping=FlightMapping("analytics.flight_assignment", Columns(exposure="exposure_time")),
156
+ )
157
+ purchases = MetricTable("analytics.purchases", [Count("revenue"), Binary("revenue", name="buyers")])
158
+ results = exp.analyze(purchases)
159
+ ```
160
+
161
+ `analytics.purchases` needs only `ruid`, `event_time` and `revenue`. Every mapped user counts:
162
+ mapped users with no purchases count as zero revenue. Rows before a user's `exposure_time` are dropped.
163
+
164
+ ### Other column names and date formats
165
+
166
+ ```python
167
+ exp = Experiment(
168
+ "control", ["t1"], "2024-03-01", "2024-03-14",
169
+ columns=Columns(unit="user_id", flight="variant", time="ds", time_format="yyyyMMdd"),
170
+ )
171
+ results = exp.analyze(MetricTable("analytics.daily_user_stats", [Count("clicks")]))
172
+ ```
173
+
174
+ ### SQL sources, data checks and sample ratio mismatch
175
+
176
+ ```python
177
+ exp = Experiment("control", ["t1", "t2"], "2024-03-01", "2024-03-14",
178
+ expected_traffic={"control": 1, "t1": 1, "t2": 1})
179
+ ios = MetricTable("SELECT * FROM analytics.app_events WHERE os = 'ios'", [Count("clicks")], name="ios_events")
180
+
181
+ exp.validate(ios) # users in two flights, segment values that change, flights without users
182
+ results = exp.analyze(ios)
183
+ results.srm() # one test per control/treatment pair
184
+ ```
185
+
186
+ A source can be a table name, a SQL query or a Spark DataFrame. Don't pre-filter dates: breakitdown
187
+ filters the time column itself, and Spark prunes partitions on it.
188
+
189
+ ## API at a glance
190
+
191
+ ```text
192
+ Experiment(control, treatments, start, end, *, user_segments=None, mapping=None, columns=None,
193
+ expected_traffic=None, spark=None)
194
+ .analyze(metric_tables, *, daily=True, alpha=0.05, enforce_min_sample=True,
195
+ hte_alpha=0.001, hte_min_units=10_000, hte_scale="absolute", cache=True) -> ExperimentResults
196
+ .validate(metric_table) -> pandas.DataFrame
197
+
198
+ MetricTable(source, metrics, name="", metric_segments=None, columns=None, inner_join=False, daily=True)
199
+ FlightMapping(source, columns=None)
200
+ Columns(unit="ruid", flight="flight", time="event_time", exposure=None, time_format=None)
201
+
202
+ Count(col, name="", label="", direction="up")
203
+ Binary(col, name="", label="", direction="up")
204
+ Ratio(numerator, denominator, name="", label="", direction="up") # numerator/denominator: column, Count or Binary
205
+ Quantile(col, quantiles=(0.5, 0.9), method="regular", bandwidth=0.001, lower=None, upper=None,
206
+ resolution=1.0, accuracy=10_000, name="", label="", direction="up")
207
+ ```
208
+
209
+ `ExperimentResults` views. Those with a `granularity` argument accept `"cumulative"` (the default)
210
+ or `"daily"`.
211
+
212
+ | Call | Returns |
213
+ |------|---------|
214
+ | `overall()` | Comparisons without a breakdown |
215
+ | `by_user_segment(segment)` | User-segment rows; with a segment such as `"os"` or `("os", "country")`, adds those columns back |
216
+ | `by_metric_segment(segment)` | Metric-segment rows, with `segment_share_control` and `segment_contribution` |
217
+ | `daily(metric)` | Daily rows; filter with `user_segment=`, `user_segment_value=`, `metric_segment=`, `metric_segment_value=` |
218
+ | `hte()` | One row per heterogeneity test, most significant first |
219
+ | `srm()` | One row per control/treatment pair and segment value (needs `expected_traffic`) |
220
+ | `table` | Every comparison |
221
+ | `population` | Denominators: users per table, flight and segment value (and day) |
222
+ | `sufficient_stats` | Raw per-flight sums collected from Spark, per table |
223
+
224
+ ## Methods
225
+
226
+ The randomization unit (`ruid`) is the independent observation. Each metric is first reduced to one
227
+ value per unit: its total over the date range for cumulative results, and over the day for daily
228
+ results. Units in the population without rows contribute zeros. Sample variances divide by n − 1.
229
+
230
+ | Metric | Estimate per flight | Variance V of the estimate | Test and CI quantile c |
231
+ |--------|---------------------|----------------------------|------------------------|
232
+ | `Count(y)` | ȳ = Σ y_u / n | s²_y / n | Welch t; c = t(1 − α/2, ν) |
233
+ | `Binary(y)` | p̂ = #{u : y_u > 0} / n | p̂ (1 − p̂) / (n − 1) | Welch t; c = t(1 − α/2, ν) |
234
+ | `Ratio(y, x)` | R = Σ y_u / Σ x_u | (s²_y − 2R s_xy + R² s²_x) / (n x̄²), the delta method | z; c = z(1 − α/2) |
235
+ | `Quantile(v, p)` | Q = p-quantile of v over all rows | Σ_u (a_u − r m_u)² / (Σ_u m_u)² / f̂(Q)² | z; c = z(1 − α/2) |
236
+
237
+ For treatment T and control C, with estimates θ and variances V:
238
+
239
+ * **Absolute difference:** Δ = θ_T − θ_C, with CI Δ ± c √(V_T + V_C). `p_value` is the two-sided test
240
+ of Δ = 0 on the same statistic, so this CI excludes 0 exactly when p < α. The Welch degrees of
241
+ freedom are ν = (V_T + V_C)² / (V_T² / (n_T − 1) + V_C² / (n_C − 1)).
242
+ * **Relative difference:** `pct_diff` = 100 (θ_T / θ_C − 1), with a delta-method CI
243
+ 100 [(θ_T / θ_C − 1) ± c √(V_T / θ_C² + θ_T² V_C / θ_C⁴)], which includes the control's uncertainty.
244
+ `p_value` tests the absolute difference, so near α the two can disagree. In the quick start,
245
+ `clickers` for t1 has p = 0.045 and a relative CI of [−0.10%, +13.65%].
246
+ * **Quantiles:**
247
+ * m_u is unit u's number of rows, a_u its rows above Q, and r = Σa / Σm.
248
+ * The density is f̂(Q) = 2h / (Q_{p+h} − Q_{p−h}) with `bandwidth` h = 0.001.
249
+ * `method="regular"` reads Q and Q_{p±h} from `percentile_approx` (`accuracy` 10,000).
250
+ * `method="density"` reads them from an exact histogram whose CDF is interpolated linearly within
251
+ ±`resolution`/2 of each distinct value. That keeps f̂ finite for integer-valued metrics. Its cost
252
+ grows with the number of distinct values, so round or clip (`lower`/`upper`) high-cardinality
253
+ metrics.
254
+ * **Minimum samples, per flight:**
255
+ * Count: n ≥ 200.
256
+ * Binary: at least 10 units with a hit and 10 without.
257
+ * Ratio: n ≥ 100.
258
+ * Quantile: n ≥ 1,000 and at least 2,000 rows.
259
+
260
+ Below these, `sufficient_sample` is False, and the CIs and p-value are left empty unless you pass
261
+ `enforce_min_sample=False`.
262
+ * **Multiple testing:** `p_value_bh` is Benjamini–Hochberg across all metrics and quantiles of one
263
+ comparison cell, meaning the same treatment, day and segment values.
264
+ * **Sample ratio mismatch:** `srm_p_value` tests each control/treatment pair on its own, as a
265
+ chi-square goodness of fit (1 dof) of the pair's unit counts against `expected_traffic`.
266
+ * **Heterogeneous effects:** a Cochran's Q test that Δ is equal across the values of a user segment
267
+ (χ² with k − 1 dof, using V_T + V_C).
268
+ * A value takes part when both flights have at least `hte_min_units` units. `(null)` never takes
269
+ part.
270
+ * HTE is flagged when p < `hte_alpha`.
271
+ * `hte_scale="relative"` tests `pct_diff` instead of Δ.
272
+ * `hte_pattern` summarises which tested values are significant on their own at 0.01.
273
+ * **Metric segments** (Count and Binary metrics only):
274
+ * `segment_share_control` is the segment's control value over the sum across segment values.
275
+ * `segment_contribution` is the segment's Δ over the sum of Δ.
276
+
277
+ ## Input contract
278
+
279
+ ### Columns
280
+
281
+ | `Columns` field | Default | Meaning |
282
+ |-----------------|---------|---------|
283
+ | `unit` | `ruid` | Randomization unit id |
284
+ | `flight` | `flight` | The unit's flight, compared as a string |
285
+ | `time` | `event_time` | DATE, TIMESTAMP, string or `yyyyMMdd` integer. Filtered to `start..end` and bucketed by calendar day in the Spark session time zone. |
286
+ | `exposure` | `None` | Optional first-exposure time, with the same types as `time` |
287
+ | `time_format` | `None` | Spark datetime pattern for string or integer times; strings default to `yyyy-MM-dd` |
288
+
289
+ Set the columns once on the `Experiment`. A table with a different schema passes its own
290
+ `MetricTable(columns=...)` or `FlightMapping(source, columns)`.
291
+
292
+ ### Pre-joined tables vs a flight mapping
293
+
294
+ | | Pre-joined (default) | `FlightMapping` (opt-in) |
295
+ |------------------------------|----------------------|--------------------------|
296
+ | Metric table columns | unit, flight, time, user segment columns, metric columns | unit, time, metric columns |
297
+ | Population (the denominator) | units with rows in this table | mapped units exposed by `end`. With `MetricTable(inner_join=True)`: only those with rows in this table. |
298
+ | Rows before exposure | dropped when `exposure` is set | dropped when the mapping has `exposure` |
299
+ | Daily denominator on day d | units whose exposure (or else first row) is on or before d | units exposed on or before d; all units if there is no `exposure` |
300
+
301
+ * **Exposure cut-off:** exact when both `time` and `exposure` are timestamps, by day otherwise.
302
+ * **Several mapping rows per unit:** reduced to one row per unit and flight, keeping the earliest
303
+ exposure and the largest non-null segment value.
304
+ * **Unit in two flights:** counted in both. `exp.validate(table)` reports it.
305
+
306
+ ### Grain and segments
307
+
308
+ * **Grain:** Count and Ratio sum rows per unit, and Binary takes "any row > 0". So a table can be at
309
+ any grain at or below unit × day. Quantile treats every row as one observation.
310
+ * **Segment syntax:** both kinds of segment accept `"os"`, `("os", "country")`, `"os|country"`, or
311
+ a list of these. Multi-column values read like `ios|US`.
312
+ * **NULL values:** these form their own `(null)` segment.
313
+ * **User segments:** columns must be constant per unit; `exp.validate(table)` reports units where
314
+ they change.
315
+
316
+ ## Roadmap
317
+
318
+ Planned. The code already leaves a place for each:
319
+
320
+ | Feature | Where it plugs in |
321
+ |---------|-------------------|
322
+ | Retro A/A | `Period` (`_common.py`): run the same pipeline over the pre-experiment range as period `"aa"`. Results already carry a `period` column. |
323
+ | CUPED | Join each unit's pre-period value in the unit rollup (`aggregate.unit_metric_stats`). Add Σx, Σx², Σxy to the metric's `group_aggregations`. Add an estimator in `stats.py` that adjusts θ and V before `compare`. |
324
+ | Capping / winsorization | `Count(cap=...)`: wrap the expression in `Count.unit_aggregations` with `least(..., cap)`. Per-day caps become a `when` on the day. |
325
+ | Plots (forest, daily trend) | A `plots.py` over the tidy `results.table`. |
326
+ | Ordinal HTE "trend" pattern | Mark a user segment as ordinal, then extend `compare._hte_pattern`. |
327
+ | Sequential testing | Another inference function next to `stats.compare`. |
328
+ | Very wide breakdowns | Replace the per-grouping aggregations plus union in `aggregate.py` with `GROUPING SETS`. |
329
+
330
+ ## Design
331
+
332
+ ```text
333
+ source ─► rows (unit, flight, day, segments, metric inputs) pre-joined: rows and population from the table
334
+ └► population (one row per unit and flight) mapping: rows ⋈ mapping, population from the mapping
335
+
336
+ rows ─► unit rollup (unit [× day] [× metric segment]) ─► sufficient statistics per flight × segment [× day]
337
+ rows ─► quantiles per group ─► per-unit row and above-quantile counts ─► sufficient statistics
338
+ population ─► units per flight × user segment [× exposure day] (denominators; units without rows count as zeros)
339
+ │
340
+ pandas/numpy: estimates ─► compare ─► BH, HTE, contributions ─► ExperimentResults
341
+ ```
342
+
343
+ * **Spark:** all groupings of a table are unioned and collected once. The unit-level shuffle is
344
+ reused across user-segment groupings.
345
+ * **Statistics:** `stats.py` is plain numpy, vectorised over all groups.
346
+ * **Modules** (in `src/breakitdown/`):
347
+ * `experiment.py`: `Experiment`
348
+ * `tables.py`: `MetricTable`, `FlightMapping`
349
+ * `metrics.py`: the metric classes
350
+ * `columns.py`: `Columns`
351
+ * `aggregate.py`: Spark
352
+ * `compare.py`: pandas
353
+ * `stats.py`: numpy/scipy
354
+ * `results.py`: `ExperimentResults`
355
+
356
+ ## Development
357
+
358
+ From a clone of the repository:
359
+
360
+ ```bash
361
+ pip install -e ".[test]"
362
+ python -m pytest
363
+ ```
364
+
365
+ The tests need Java 17 for local Spark.
366
+
367
+ * `tests/test_stats.py` checks every estimator against an independent computation on raw unit-level
368
+ data: SciPy's Welch test, the linearised ratio variance and the Wald contrast test.
369
+ * The Spark tests run end to end on local Spark and compare every number with an independent
370
+ pandas/SciPy implementation (`tests/reference.py`).
371
+ * `tests/test_readme.py` runs every Python block of this README against synthetic tables.
372
+
373
+ ## License
374
+
375
+ Apache License 2.0; see [LICENSE](LICENSE).