From 91fb2892014644519faed2c21c959bcae530fcca Mon Sep 17 00:00:00 2001 From: igerber Date: Wed, 25 Nov 2026 12:28:11 -0500 Subject: [PATCH 1/3] docs(tutorials): tutorial conventions and a CI guard for them CONTRIBUTING.md gains a 'Tutorial conventions' section: what every notebook states and how (estimand and assumptions, truth check on simulated data, clustered inference and which p-values are count-based, one event-study idiom, warnings, committed outputs, a drift test per notebook, reader voice), plus the recipe for re-executing a notebook. tests/test_tutorial_conventions.py enforces the mechanical rules over every notebook by parsing the notebook JSON: execution counts, no committed error output (never allowlistable), no removed 4.0 names or aliases, no internal jargon, no unqualified warning suppression, no em dashes, no HAS_MATPLOTLIB guard, a drift test per notebook. A ratchet allowlist records today's violations; repair PRs must shrink it. It runs in docs-tests.yml, and the workflow wiring is self-pinned. notebooks.yml now runs every tutorial drift test, so a notebook-only diff cannot leave its pinned numbers unchecked. docs/tutorials/README.md is reduced to a pointer to the tutorial index and the conventions. --- .github/workflows/docs-tests.yml | 14 + .github/workflows/notebooks.yml | 35 +- CONTRIBUTING.md | 137 ++++ changelog.d/20261125-tutorial-conventions.md | 11 + docs/tutorials/README.md | 238 +------ tests/test_tutorial_conventions.py | 692 +++++++++++++++++++ 6 files changed, 897 insertions(+), 230 deletions(-) create mode 100644 changelog.d/20261125-tutorial-conventions.md create mode 100644 tests/test_tutorial_conventions.py diff --git a/.github/workflows/docs-tests.yml b/.github/workflows/docs-tests.yml index a24f79c2a..ea7b10dcc 100644 --- a/.github/workflows/docs-tests.yml +++ b/.github/workflows/docs-tests.yml @@ -9,6 +9,9 @@ on: - 'tests/test_doc_snippets.py' - 'tests/test_doc_deps_integrity.py' - 'tests/test_docs_ia.py' + # Tutorial conventions guard: notebook diffs already trigger via + # docs/**; this entry covers a diff that touches only the guard. + - 'tests/test_tutorial_conventions.py' - 'tests/test_v4_matrix.py' - 'tests/test_naming_guard.py' # Diagnostic-family roster guard (M-090): README-only diffs otherwise @@ -51,6 +54,9 @@ on: - 'tests/test_doc_snippets.py' - 'tests/test_doc_deps_integrity.py' - 'tests/test_docs_ia.py' + # Tutorial conventions guard: notebook diffs already trigger via + # docs/**; this entry covers a diff that touches only the guard. + - 'tests/test_tutorial_conventions.py' - 'tests/test_v4_matrix.py' - 'tests/test_naming_guard.py' # Diagnostic-family roster guard (M-090): README-only diffs otherwise @@ -132,6 +138,14 @@ jobs: # All four are valid-Sphinx states the -W build cannot catch. run: PYTHONPATH=. DIFF_DIFF_BACKEND=python pytest tests/test_docs_ia.py -v + - name: Run tutorial conventions guard + # Static checks over every docs/tutorials/*.ipynb (CONTRIBUTING.md, + # "Tutorial conventions"): committed outputs, no removed 4.0 names or + # internal jargon, no blanket warning filters, a drift test per + # notebook. Parses the notebook JSON - nothing is executed. Runs here + # because the main test matrix does not trigger on docs-only diffs. + run: PYTHONPATH=. DIFF_DIFF_BACKEND=python pytest tests/test_tutorial_conventions.py -v + - name: Run v4 deprecation-matrix enforcement # Asserts every docs/v4-deprecations.yaml row's status against reality # at HEAD (schema: docs/v4-design.md section 11). Runs here so diff --git a/.github/workflows/notebooks.yml b/.github/workflows/notebooks.yml index 770d96bf6..7bd4599ea 100644 --- a/.github/workflows/notebooks.yml +++ b/.github/workflows/notebooks.yml @@ -10,9 +10,12 @@ on: - '.github/workflows/notebooks.yml' # the interop drift guard runs only in this workflow (balance installed) - 'tests/test_t26_composition_drift_calibration_drift.py' - # the MMM tutorial drift guards run as a step in execute-notebooks - - 'tests/test_t29_mmm_calibration_pymc_drift.py' - - 'tests/test_t30_mmm_calibration_meridian_drift.py' + # every tutorial drift guard runs as a step in execute-notebooks, so a + # notebook-only diff (docs/tutorials/**) cannot leave its pinned numbers + # unchecked - rust-test.yml, the lane that runs tests/, does not fire on + # docs/** + - 'tests/test_t*_drift.py' + - 'tests/_tutorial_drift.py' pull_request: branches: [main] types: [opened, synchronize, reopened, labeled, unlabeled] @@ -23,9 +26,12 @@ on: - '.github/workflows/notebooks.yml' # the interop drift guard runs only in this workflow (balance installed) - 'tests/test_t26_composition_drift_calibration_drift.py' - # the MMM tutorial drift guards run as a step in execute-notebooks - - 'tests/test_t29_mmm_calibration_pymc_drift.py' - - 'tests/test_t30_mmm_calibration_meridian_drift.py' + # every tutorial drift guard runs as a step in execute-notebooks, so a + # notebook-only diff (docs/tutorials/**) cannot leave its pinned numbers + # unchecked - rust-test.yml, the lane that runs tests/, does not fire on + # docs/** + - 'tests/test_t*_drift.py' + - 'tests/_tutorial_drift.py' schedule: # Weekly Sunday 6am UTC — smoke test that notebooks still execute cleanly - cron: '0 6 * * 0' @@ -86,15 +92,20 @@ jobs: # drift guards run in the next step, and the mmm-interop.yml workflow # smoke-tests the exporters against the real frameworks (no sampling). - - name: Run MMM tutorial drift guards - # The MMM notebooks are excluded from execution above, so their committed - # surface is protected here: DGP/sampler/integration needles + diff-diff - # recomputation of the DiD-side numbers (no MMM frameworks needed). + - name: Run tutorial drift guards + # Every notebook's drift test: re-derives the numbers its prose quotes + # and checks them against the committed notebook. nbmake above only + # proves cells execute; RTD renders the COMMITTED outputs. This is the + # only lane that runs these tests on a notebook-only diff. It also + # protects the MMM notebooks (excluded from execution above) through + # their DGP/sampler/integration needles and the diff-diff recomputation + # of the DiD-side numbers (no MMM frameworks needed). Slow-marked + # re-derivations stay out via the default addopts; the balance-interop + # test (t26) importorskips here and runs in interop-notebooks below. env: DIFF_DIFF_BACKEND: python run: | - pytest tests/test_t29_mmm_calibration_pymc_drift.py \ - tests/test_t30_mmm_calibration_meridian_drift.py -v --tb=short + pytest tests/test_t*_drift.py -v --tb=short - name: Upload failed notebook outputs if: failure() diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 683229cd5..b3d44c9a9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -67,6 +67,8 @@ If you find yourself adding a usage example, a parameter table, or a multi-parag 3. **`docs/tutorials/*.ipynb`** - Update relevant tutorial or create new one: - Working code examples - Explanation of when/why to use the feature + - Follow the "Tutorial conventions" section below (CI-enforced by + `tests/test_tutorial_conventions.py`), including a drift test for a new notebook - New notebooks are registered in `docs/tutorials/index.rst` (NOT `docs/index.rst`): add a toctree entry with a short display label to the matching group (Business Applications / Fundamentals / Advanced Methods / Study Design) @@ -152,6 +154,141 @@ Example format (RST): - **Sun, L., & Abraham, S. (2021).** "Estimating Dynamic Treatment Effects in Event Studies with Heterogeneous Treatment Effects." *Journal of Econometrics*, 225(2), 175-199. https://doi.org/10.1016/j.jeconom.2020.09.006 ``` +## Tutorial conventions + +The notebooks in `docs/tutorials/` are teaching material: a reader should meet +the same idea the same way wherever it comes up. These conventions apply to +every new notebook and to any notebook you edit. The mechanical ones are +CI-enforced by `tests/test_tutorial_conventions.py`; that guard carries a +shrinking allowlist of pre-existing violations (`KNOWN_VIOLATIONS`) - when you +repair a notebook, delete its entries; never add one. + +### Teaching + +1. **Opening.** An H1 that matches the notebook's card label in + `docs/tutorials/index.rst`; one paragraph stating the question the notebook + answers; a short "What you'll learn" list; a prerequisites line linking the + tutorials it builds on. +2. **Estimand and assumptions before the first fit.** Name the target + parameter, state the identifying assumptions in plain words, and say what + would violate them. +3. **Check against the truth on synthetic data.** State the true effect as a + named constant where the data is built, and pass every generator argument + that determines the truth explicitly, even at its default value + (`generate_staggered_data` defaults to `dynamic_effects=True`, so the true + average effect is not `treatment_effect`). Compare the estimate and its + interval to the truth in the output; if the interval misses, say why. Real + data comes from a `load_*` loader where one exists. No data files are added + under `docs/tutorials/`. +4. **Inference.** Cluster panel fits at the unit. `DifferenceInDifferences` + does not auto-cluster, so pass `cluster=`; the estimators that cluster at + the unit by default need nothing extra. Tutorial 01 explains why; elsewhere + one line is enough, and any other choice is justified in prose. Bootstraps + use `n_bootstrap=999` and a fixed seed (fewer only for runtime, and say so). + When prose discusses a p-value, name the inference that produced it and + check it against the estimator's REGISTRY section, because the count-based + p-values differ. With `B` valid draws of which `c` are at least as extreme + as the estimate: the permutation test reports `(c + 1) / (B + 1)` (steps of + `1/(B+1)`, smallest value `1/(B+1)`); the SyntheticDiD placebo reports + `max(c / B, 1/(B+1))` (steps of `1/B`, same floor). A p-value computed + analytically from a resampled standard error (SyntheticDiD bootstrap and + jackknife, ChangesInChanges) is not count-based and has no floor. +5. **Pre-trend tests are not pass/fail.** A non-rejection is not evidence that + parallel trends holds. Say so, and link the sensitivity tutorial + (`05_honest_did`) and the pre-test power tutorial (`07_pretrends_power`). +6. **Control groups.** Never-treated and not-yet-treated comparisons rest on + different identifying assumptions; neither is uniformly weaker. Do not + describe one as "the stronger assumption". +7. **Event studies: one idiom.** + + ```python + es = results.aggregate("event_study") # if the results class has aggregate() + es = results # otherwise (SunAbraham, a TWFE event_study=True fit) + plot_event_study(es) + ``` + + Read the table with `es.to_dataframe()` when `es` is an `EventStudyResults` + container, and with `results.to_dataframe(level="event_study")` otherwise + (SunAbraham, WooldridgeDiD). Do not read raw `event_study_effects` dicts, + rename the unified columns, or hand-draw a single estimator's event study in + matplotlib; build multi-estimator overlays from the unified frames. Event + time 0 is the first treated period - an estimator with a different native + index states the mapping. The idiom is pinned on every event-study producer + by `tests/test_visualization.py::TestEventStudyIdiomContract`. +8. **Warnings.** No unqualified `warnings.filterwarnings("ignore")` or + `simplefilter("ignore")`. A warning that appears in committed output is + either removed by fixing the call or explained in the next markdown cell. + Two narrow exceptions: a scoped `warnings.catch_warnings()` with `category=` + and `message=` for documented platform noise, and a category-qualified + filter with a comment for a third-party framework's deprecation noise. +9. **Closing.** "Summary" (three to five bullets), "When to use it and when not + to", "Next steps" linking other tutorials, and references. Business-track + notebooks also keep their stakeholder-summary section. + +### Mechanics + +10. **Code style.** Import from top-level `diff_diff` (a submodule import only + for a symbol that is not exported there). Use full class names, not the + short aliases. Import matplotlib plainly - no `HAS_MATPLOTLIB` guard. Print + results with `print(results.summary())` and read them as `results.att`, + `.se`, `.conf_int`, `.p_value`. +11. **Reader voice.** No version or migration narration, deprecation-ledger + ids, PR numbers, internal phase or wave names, internal paths, or + `file:line` references - the migration guide and the changelog own that + history. Hyphens, not em dashes, in cell sources. Sentence-case, + unnumbered section headings. +12. **Committed outputs.** Every notebook is committed executed: all code + cells run top to bottom in one pass (execution counts `1..n`), no error + outputs, no stray empty figures. `nbsphinx_execute = "never"`, so the + committed outputs are what Read the Docs shows. +13. **Drift test.** Every notebook has a `tests/test_t__drift.py` + that re-derives the numbers its prose quotes and asserts they appear in the + rendered notebook (helpers in `tests/_tutorial_drift.py`). Prose that would + need an unpinned number should point at the output instead. +14. **Numbering.** The number in a filename is a stable id, not a reading + order (two notebooks are numbered 16). Reading order is the group order in + `docs/tutorials/index.rst`. + +Three notebooks keep documented exceptions: `16_survey_did` reads NHANES from +the tracked benchmark CSV (there is no loader for it), with a CDC download +only as the fallback; `29_mmm_calibration_pymc` and +`30_mmm_calibration_meridian` have frozen code cells, because their committed +outputs come from long MCMC runs in framework-specific environments. + +### Re-executing a notebook + +Committed outputs come from the Rust backend. Kernels are bound to a virtual +environment, so register one for the checkout you are working in: + +```bash +python -m ipykernel install --user --name my-diffdiff-kernel +``` + +Execute into a scratch directory, compare with what is committed, then copy +the executed file back (never execute in place, and never pipe the run through +`tail`): + +```bash +DIFF_DIFF_BACKEND=rust python - <<'PY' +from pathlib import Path + +import nbformat +from nbclient import NotebookClient + +out = Path("/tmp/executed") +out.mkdir(parents=True, exist_ok=True) # before the (possibly long) run +nb = nbformat.read("docs/tutorials/01_basic_did.ipynb", as_version=4) +NotebookClient(nb, timeout=3000, kernel_name="my-diffdiff-kernel", + resources={"metadata": {"path": "docs/tutorials"}}).execute() +nbformat.write(nb, out / "01_basic_did.ipynb") +PY +``` + +Read every changed output against the prose around it, then update the +notebook's drift test (and, for `31`-`33`, its code-cell hash pins). Before +opening the PR, mirror CI with +`DIFF_DIFF_BACKEND=python pytest --nbmake docs/tutorials/.ipynb`. + ## Test Writing Guidelines ### For Fallback/Error Handling Paths diff --git a/changelog.d/20261125-tutorial-conventions.md b/changelog.d/20261125-tutorial-conventions.md new file mode 100644 index 000000000..e55830501 --- /dev/null +++ b/changelog.d/20261125-tutorial-conventions.md @@ -0,0 +1,11 @@ +### Internal +- **Tutorial conventions and a CI guard for them**: `CONTRIBUTING.md` gains a + "Tutorial conventions" section (what every notebook states and how: estimand + and assumptions, the truth check on simulated data, clustered inference, one + event-study idiom, warnings, committed outputs, a drift test per notebook). + `tests/test_tutorial_conventions.py` enforces the mechanical rules over every + notebook by parsing the notebook JSON, with a shrinking allowlist of the + violations that exist today; it runs in the docs-tests workflow. The notebooks + workflow now runs every tutorial drift test, so a notebook-only change can no + longer leave its pinned numbers unchecked. `docs/tutorials/README.md` is + reduced to a pointer to the tutorial index and the conventions. diff --git a/docs/tutorials/README.md b/docs/tutorials/README.md index bae23bf63..3e559e62d 100644 --- a/docs/tutorials/README.md +++ b/docs/tutorials/README.md @@ -1,226 +1,28 @@ -# diff-diff Tutorials +# diff-diff tutorials -This directory contains Jupyter notebook tutorials demonstrating the features of the `diff-diff` library. +Jupyter notebooks that teach the library hands-on. The rendered versions, with +their outputs, are on Read the Docs: +. -## Notebooks +- **What is here and in what order:** [`index.rst`](index.rst) lists every + notebook with a one-line description, grouped into Business Applications, + Fundamentals, Advanced Methods and Study Design. The number in a filename is + a stable id, not a reading order. +- **Writing or editing a notebook:** follow "Tutorial conventions" in + [`CONTRIBUTING.md`](../../CONTRIBUTING.md), which also covers how to + re-execute a notebook and update its drift test. The mechanical rules are + enforced by `tests/test_tutorial_conventions.py`. -### 1. Basic DiD (`01_basic_did.ipynb`) -Introduction to Difference-in-Differences with `diff-diff`: -- Basic 2x2 DiD estimation -- Column-name and formula interfaces -- Adding covariates -- Fixed effects (dummy and absorbed) -- Two-Way Fixed Effects (TWFE) -- Cluster-robust standard errors -- Wild cluster bootstrap +## Running the notebooks -### 2. Staggered DiD (`02_staggered_did.ipynb`) -Handling staggered treatment adoption with the Callaway-Sant'Anna estimator: -- Understanding staggered adoption -- Problems with TWFE in staggered settings -- **Goodman-Bacon decomposition**: Diagnosing *why* TWFE fails -- Group-time effects ATT(g,t) -- Aggregation methods (simple, group, event-study) -- Control group specifications -- Visualization - -### 3. Synthetic DiD (`03_synthetic_did.ipynb`) -Synthetic Difference-in-Differences for few treated units: -- When to use Synthetic DiD -- Understanding unit and time weights -- Pre-treatment fit diagnostics -- Inference methods (bootstrap, placebo) -- Regularization tuning -- Comparison with standard DiD - -### 4. Parallel Trends (`04_parallel_trends.ipynb`) -Testing assumptions and diagnostics: -- Visual inspection of trends -- Simple parallel trends tests -- Robust Wasserstein-based tests -- Equivalence testing (TOST) -- Placebo tests (timing, group, permutation) -- Event study as a diagnostic -- What to do if parallel trends fails - -### 15. Efficient DiD (`15_efficient_did.ipynb`) -Efficient Difference-in-Differences (Chen, Sant'Anna & Xie 2025): -- Optimal weighting across comparison groups and baselines -- PT-All vs PT-Post assumptions -- Efficiency gains vs Callaway-Sant'Anna -- Event study and group-level aggregation -- Bootstrap inference and diagnostics - -### 16. Wooldridge ETWFE (`16_wooldridge_etwfe.ipynb`) -Wooldridge Extended Two-Way Fixed Effects (ETWFE) for staggered DiD: -- Basic OLS estimation with cohort x time ATT cells -- Aggregation methods: event-study, group, calendar, simple -- Poisson QMLE for count / non-negative outcomes -- Logit for binary outcomes -- Comparison with Callaway-Sant'Anna -- Delta-method standard errors - -### Survey-Aware DiD (`16_survey_did.ipynb`) -Survey-aware DiD with complex sampling designs (strata, PSU, FPC, weights): -- Why survey design matters for DiD inference -- Setting up `SurveyDesign` (weights, strata, PSU, FPC) -- Basic DiD and staggered DiD with survey design -- Replicate weights (JK1, BRR, Fay, JKn) -- Subpopulation analysis -- DEFF diagnostics -- Repeated cross-sections with survey design - -### 17. Brand Awareness Survey (`17_brand_awareness_survey.ipynb`) -Practitioner walkthrough for measuring brand-campaign lift on survey data with complex sampling: -- The brand-tracker problem framed for marketing analytics -- Naive vs survey-aware DiD comparison (overconfidence under naive) -- `SurveyDesign` setup (strata, PSU, FPC, weights) wired into the fit -- Funnel-metric extension across awareness / consideration / purchase intent -- Diagnostics (parallel trends, placebo, automated `practitioner_next_steps()`) -- Stakeholder communication template - -### 18. Geo-Experiment Analysis with SyntheticDiD (`18_geo_experiments.ipynb`) -Practitioner walkthrough for marketing analytics teams measuring geo-experiment lift: -- The geo-experiment problem framed for marketing analytics -- Synthetic panel of 80 markets with simulated campaign launch -- `SyntheticDiD` fit, diagnostics, and inference (placebo + bootstrap) -- Unit weights and time weights interpretation -- Stakeholder communication template (Tutorial 17 leadership-communication pattern) - -### 19. dCDH Marketing Pulse Campaigns (`19_dcdh_marketing_pulse.ipynb`) -Practitioner walkthrough for measuring lift from on/off promotional pulses across markets, where treatment can switch in both directions: -- The marketing-pulse problem framed for reversible (non-absorbing) treatment -- TWFE decomposition diagnostic (`twowayfeweights`) showing why standard regression misleads on reversible panels (de Chaisemartin & D'Haultfoeuille 2020 Theorem 1) -- `DCDH` Phase 1: DID_M, joiners-vs-leavers decomposition, single-lag placebo -- Multi-horizon event study with `L_max` + multiplier bootstrap -- Stakeholder communication template + drift guards - -### 20. HAD for National Brand Campaign with Regional Spend Intensity (`20_had_brand_campaign.ipynb`) -Practitioner walkthrough for measuring per-dollar lift when every market is treated at a different dose level and no never-treated unit exists (comparison comes from the dose variation across markets): -- The measurement problem framed for heterogeneous-adoption (no-untreated-control) panels -- `HAD` overall fit on a 2-period collapse, with `design="auto"` resolving to `continuous_near_d_lower` (Design 1) and target `WAS_d_lower` (per-$1K marginal effect above the lightest-touch DMA's spend) -- Multi-week event study showing per-week dynamics with pre-launch placebos -- Stakeholder communication template flagging the Assumption 5/6 identification caveat -- Companion drift-test file (`tests/test_t20_had_brand_campaign_drift.py`) - -### 21. HAD Pre-test Workflow (`21_had_pretest_workflow.ipynb`) -Composite pre-test walkthrough for `HeterogeneousAdoptionDiD`, building on Tutorial 20's brand-campaign framing on a panel where the dose distribution has a strictly positive but very near-zero lower bound (so the QUG step fails-to-reject `H0: d_lower = 0`): -- Paper Section 4.2 step taxonomy (QUG support-infimum, parallel pre-trends, linearity) -- `did_had_pretest_workflow` on a two-period collapse (the overall battery, selected from the panel shape): Step 1 + Step 3 only, verdict explicitly flags Step 2 as deferred -- Upgrade to the multi-week panel (the event-study battery): adds the joint pre-trends Stute and joint homogeneity Stute diagnostics (none of the three testable steps reject) -- Side panel comparing `yatchew_hr_test` `null="linearity"` (default, paper Theorem 7) vs `null="mean_independence"` (Phase 4 R-parity with R `YatchewTest::yatchew_test(order=0)`) -- Companion drift-test file (`tests/test_t21_had_pretest_workflow_drift.py`) - -### 22. HAD Survey-Weighted Workflow (`22_had_survey_design.ipynb`) -End-to-end HAD walkthrough on a BRFSS-shape stratified survey design (5 strata x 6 PSUs/stratum x 2 states/PSU = 60 states; post-stratification raking weights with CV ~ 0.30; FPC = 30 PSUs/stratum). Demonstrates the `SurveyDesign(strata=...)` path through the Stute pretest family that PR #432 (2026-05-14) unblocked: -- Naive vs survey-aware HAD headline fit on a two-period collapse, with side-by-side ATT / SE / CI table -- Why the SE inflation is modest for HAD (local-linear at d_lower IF concentration vs full-panel regression coefficients) -- Event-study fit with sup-t cband under the survey design -- `did_had_pretest_workflow` on both overall and event-study paths under `survey_design=`, walking the Phase 4.5 C0 QUG-deferred verdict suffix and the stratified-clustered Stute multiplier bootstrap -- Companion drift-test file (`tests/test_t22_had_survey_design_drift.py`) - -### 23. SpilloverDiD on a TVA-style Spillover Panel (`23_spillover_tva.ipynb`) -Practitioner workflow for `SpilloverDiD` (Butts 2021 ring-indicator estimator + Gardner 2022 two-stage residualize-then-fit) on a synthetic TVA-style panel (4 periods, 200 units = 25 treated + 120 near-control + 55 far-control) reproducing the Butts §4 Table 1 Panel A ~40% understatement direction: -- When place-based interventions cause geographic spillovers, naive multi-period TWFE on the full sample understates the direct effect because near-controls absorb the spillover (here: ATT recovers as -4.29 vs true `tau_total = -7.4`, a 42% understatement) -- `SpilloverDiD(rings=[0.0, 100.0], conley_coords=("lat", "lon"))` cleanly recovers both `tau_total` (-7.34) and the near-band spillover coefficient `delta_1` (-4.53) -- Choosing the spillover bandwidth via a `rings` sensitivity grid at outer edges 50 / 100 / 150 / 200 km, with the documented "undershooting `d_bar`" failure mode at 50 km -- Conley spatial-HAC variance under `vcov_type="conley", conley_cutoff_km=100, conley_lag_cutoff in {0, 1}` — the cutoff = `d_bar` choice follows Butts §3.1, while the `conley_lag_cutoff` serial extension is the library's documented Wave E.2 follow-up synthesis with Newey-West-style serial Bartlett HAC (per REGISTRY "Variance (Wave E.2 follow-up)") -- Companion drift-test file (`tests/test_t23_spillover_tva_drift.py`) - -### 24. Staggered Rollout vs a Collapsed 2×2 (`24_staggered_vs_collapsed_power.ipynb`) -Power-analysis decision guide for geo experiments (framed on a 50-state staggered rollout) on when to use Callaway-Sant'Anna vs collapsing to a familiar pre/post 2×2: -- Why the collapsed 2×2 silently targets a *diluted* estimand (and how often its CI misses the true effect-on-treated) -- The CS event study vs the 2×2's single diluted number -- How the minimum detectable lift (MDE) changes for each estimator as the rollout gets more staggered — the power gap is a *fast-rollout* phenomenon that closes to near parity as staggering increases -- When a clean-tail 2×2 is unbiased, the small-holdout and few-clusters caveats, and a CS-vs-2×2 decision guide -- Fully self-contained: runs live (no committed data files) - -### 25. Synthetic Control for a Policy Evaluation: Two Routes to Inference (`25_synthetic_control_policy.ipynb`) -A single state adopts a clean-energy standard and no other state is a clean control - `SyntheticControl` builds a weighted donor-blend counterfactual, and with one treated unit the analytical inference fields are NaN by design, so the tutorial walks both genuine inference routes: -- Philosophy A - compare across regions: the ADH (2010) in-space placebo permutation (`in_space_placebo()`, RMSPE-ratio rank p-value) and the Firpo-Possebom (2018) confidence set -- Philosophy B - compare across time: Chernozhukov-Wuthrich-Zhu (2021) conformal inference, inverting a permutation-over-time test into a p-value for a hypothesized effect path and per-post-period confidence intervals -- The two philosophies side by side: what each does and does not protect against, and how to report them together -- Fully self-contained: runs live (no committed data files) - -### 26. Composition Drift & Survey Calibration with balance (`26_composition_drift_calibration.ipynb`) -The failure-mode companion to Meta balance's `balance_diff_diff_brfss` tutorial: when non-response drift correlates with treatment timing, the design-weight DiD itself is biased and calibration becomes essential for the *causal* estimand: -- BRFSS-style smoking-ban DGP with no systematic arm-specific trends (parallel trends hold in expectation; planted ATT -3.0pp, realized -2.98pp) and treatment-correlated non-response drift -- Design-weight Callaway-Sant'Anna overstates the ATT ~35% with *clean pre-trends* (pre-trend tests are not a safety net) -- A per-wave national rake fails (margins satisfied in aggregate, arm-level composition untouched); per-state raking - BRFSS's own granularity - recovers the truth -- The seam both ways: native `SurveyDesign` + `aggregate_survey` 3-liner vs the `balance.interop.diff_diff` adapter (`to_panel_for_did` / `fit_did`), with an exact-parity assert -- Estimator sweep (CS / SunAbraham / ImputationDiD), `survey_metadata` DEFF diagnostics, and `as_balance_diagnostic` cross-package diagnostics -- Requires `pip install "balance>=0.21"` (this tutorial only); fully self-contained data - -### 27. When the Average Hides the Action: Distributional DiD with Changes-in-Changes (`27_cic_distributional_effects.ipynb`) -A loyalty program looks dead on mean DiD ($0.22, p = 0.90) but in truth lifted the bottom half of the spend distribution - `ChangesInChanges` (Athey & Imbens 2006) recovers the full quantile-treatment-effect profile: -- Reading a QTE profile, and making joint "which quantiles moved" claims with sup-t uniform bands (they exclude zero for exactly tau = 0.05-0.50 here) -- The interior-range guardrail live: a short-support control sample triggers loud warnings and NaN tail inference instead of silent extrapolation -- The scale-equivariance centerpiece: levels-vs-logs flips mean DiD's verdict and shifts QDiD's profile by dollars, while CiC's counterfactual quantiles agree to floating-point precision (unconditional fits) -- Covariate-composition confounding fixed with `covariates=` (quantile-regression conditioning, qte `xformla` parity), and the `practitioner_next_steps()` close -- Companion drift-test file (`tests/test_t27_cic_distributional_effects_drift.py`); fully self-contained (runs live, no committed data files) - -### 29. MMM Calibration with PyMC-Marketing Lift Tests (`29_mmm_calibration_pymc.ipynb`) -Executed end-to-end against the real framework: a staggered geo spend-boost experiment measured with `CallawaySantAnna`, exported via `to_pymc_marketing_lift_test`, and fed to `MMM.add_lift_test_measurements` - the demand-chasing-biased MMM's search-ROI posterior moves to the simulated truth and tightens: -- Grain reconciliation for a national-weekly lift row (`aggregate('simple')` + `scale=G_treated`), the `aggregate('total')` campaign headline, and the double-count guardrail -- With/without-calibration money plot plus in-notebook sampler-health and posterior acceptance asserts -- Requires `pip install "pymc-marketing==1.0.0"` on Python 3.12 (this tutorial only); cannot share an environment with the Meridian tutorial (conflicting `arviz` pins); fully self-contained data -- Companion drift-test file (`tests/test_t29_mmm_calibration_pymc_drift.py`) - -### 30. MMM Calibration with Meridian ROI Priors (`30_mmm_calibration_meridian.ipynb`) -Executed end-to-end against the real framework: a geo-holdout launch experiment (the `roi_m` estimand exactly), exported via `to_meridian_roi_prior` from the `aggregate('total')` container, with `meridian_calibration_mask` and the generated `to_code()` snippet run verbatim: -- A national Meridian model that cannot see the geo holdout overcredits the launch; the experiment prior centers its ROI posterior on the truth and tightens it -- Window/spend/mass alignment asserts, default-vs-calibrated money plot, and sampler-health checks -- Requires `pip install "google-meridian==1.8.0"` on Python 3.12 (this tutorial only); cannot share an environment with the PyMC-Marketing tutorial (conflicting `arviz` pins); fully self-contained data -- Companion drift-test file (`tests/test_t30_mmm_calibration_meridian_drift.py`) - -### 31. LWDiD Rolling Transformations (`31_lwdid.ipynb`) -Lee & Wooldridge (2026) rolling-transformation DiD: demeaning (Procedure 2.1) and detrending (Procedure 3.1) turn the panel into a cross-section with exact small-sample t inference: -- Prop 99 (common timing, one treated unit) and Walmart entry (staggered) replications -- Cluster-robust and wild-bootstrap inference, randomization tests, transformation diagnostics -- Companion drift-test file (`tests/test_t31_lwdid_drift.py`) - -### 32. Double ML DiD (`32_dml_did.ipynb`) -Chang (2020) double/debiased machine learning DiD: cross-fitted ML nuisances on a staggered panel with engineered nonlinear confounding: -- The bias demo: a misspecified linear outcome learner misses by almost five standard errors while the adaptive sieve and a hand-rolled duck-typed `PolynomialRidge` learner recover the truth (double robustness in action) -- Cross-fitting diagnostics, event-study/group aggregation, HonestDiD sensitivity, bootstrap sup-t bands -- The repeated-cross-section lane (`panel=False`) with a `SurveyDesign` (PSU-cohesive folds, design-df t inference) -- Companion drift-test file (`tests/test_t32_dml_did_drift.py`) - -### 33. Bad Controls (`33_bad_controls.ipynb`) -Caetano, Callaway, Payne & Sant'Anna (2026) "bad controls" - covariates that treatment can change - on a staggered version of the paper's DGP 1: -- The naive TWFE regression with the bad control at `t` misses by the full treatment effect on the covariate (the paper's `tau^use` bias) -- Approach 1 (the pre-treatment bad control as a base-period covariate) with and without the confounders `W` -- The `DMLDiD` bad-control lane (`fit(bad_control=, bad_control_covariates=)`), the choice of `W` (Remark 5's lagged outcome), reading `bad_control_summary()` (pre rows pre-test MP-5/MP-8, post rows check that treatment moves the covariate), a ridge refit through the split-half nested stage, and the lane's restrictions -- Companion drift-test file (`tests/test_t33_bad_controls_drift.py`) - -### 34. Design Diagnosis and the Design Lock (`34_design_diagnosis.ipynb`) -The design-stage workflow on one simulated retail panel (untreated history first, the rollout afterwards): -- `diagnose_design` on four candidate estimators with placebo treatments assigned to the history: the size check (classical standard errors over-reject under serial correlation), power and the minimum detectable effect -- `lock()` with its rerun of the chosen estimator, the lock as a JSON file, and why the file has to be registered outside the library -- `DesignLock.fit` after the rollout (`match` / `deviates`), `BusinessReport(design_reconciliation=...)`, and two deviations: a shorter follow-up window and a by-hand fit with another comparison group -- What the workflow does not establish (parallel trends, when the lock was made, a verdict near the size threshold) -- Companion drift-test file (`tests/test_t34_design_diagnosis_drift.py`) - -## Running the Notebooks - -1. Install diff-diff with dependencies: -```bash -pip install diff-diff -pip install matplotlib # for visualizations -pip install jupyter # to run notebooks -``` - -2. Start Jupyter: ```bash +pip install diff-diff matplotlib jupyter jupyter notebook ``` -3. Open any notebook and run the cells. - -## Requirements - -- Python 3.8+ -- diff-diff -- numpy -- pandas -- matplotlib (optional, for visualizations) +Every notebook is self-contained (data is simulated or loaded by the library) +and runs on Python 3.9+. Three need an extra package that is not a diff-diff +dependency: `26_composition_drift_calibration` (`balance`), +`29_mmm_calibration_pymc` (`pymc-marketing`) and `30_mmm_calibration_meridian` +(`google-meridian`); each notebook states its exact install line, and the two +MMM notebooks need Python 3.12 and separate environments. diff --git a/tests/test_tutorial_conventions.py b/tests/test_tutorial_conventions.py new file mode 100644 index 000000000..6a4a59159 --- /dev/null +++ b/tests/test_tutorial_conventions.py @@ -0,0 +1,692 @@ +"""Static guard for the tutorial conventions. + +The conventions are written down in CONTRIBUTING.md ("Tutorial conventions"). +This file enforces the mechanical ones over every notebook in +``docs/tutorials/`` by parsing the ``.ipynb`` JSON directly: nothing is +executed, so it is cheap and runs on notebook-only diffs (docs-tests.yml). + +Ratchet: ``KNOWN_VIOLATIONS`` lists, per notebook, the rules it violated when +the guard was introduced. The guard fails on any violation that is NOT listed +and ALSO fails when a listed violation has been fixed, so a PR that repairs a +notebook must delete its entries. The dict is meant to end empty; never add to +it to get a new or edited notebook past the guard - fix the notebook. + +Rules scan cell SOURCES only. Committed outputs are not scanned: library +output legitimately contains characters and names the rules ban in prose. +""" + +from __future__ import annotations + +import ast +import io +import json +import re +import tokenize +from pathlib import Path +from typing import Dict, FrozenSet, List, Tuple + +import pytest + +REPO_ROOT = Path(__file__).resolve().parents[1] +TUTORIALS_DIR = REPO_ROOT / "docs" / "tutorials" +TESTS_DIR = REPO_ROOT / "tests" + +if not TUTORIALS_DIR.is_dir(): + # The isolated-install CI jobs copy only tests/ and run without docs/. + pytest.skip("docs/tutorials not present in this environment", allow_module_level=True) + +# -------------------------------------------------------------------------- +# Rule ids +# -------------------------------------------------------------------------- +EXECUTED = "executed" +ERROR_OUTPUT = "error-output" +REMOVED_NAME = "removed-name" +REMOVED_IDENTIFIER = "removed-identifier" +JARGON = "jargon" +BLANKET_WARNING_FILTER = "blanket-warning-filter" +EM_DASH = "em-dash" +MATPLOTLIB_GUARD = "matplotlib-guard" +DRIFT_TEST = "drift-test" + +ALL_RULES = ( + EXECUTED, + ERROR_OUTPUT, + REMOVED_NAME, + REMOVED_IDENTIFIER, + JARGON, + BLANKET_WARNING_FILTER, + EM_DASH, + MATPLOTLIB_GUARD, + DRIFT_TEST, +) + +# -------------------------------------------------------------------------- +# Configuration +# -------------------------------------------------------------------------- + +# Notebooks exempt from every rule: tutorials that are in flight on other +# branches and were written before this guard existed. An entry is inert +# while its file does not exist. Conform the notebook, then remove it here. +PENDING: FrozenSet[str] = frozenset( + { + "34_chained_did", + "34_did_ovb", + } +) + +# Explicit notebook -> drift-test file. REQUIRED for every notebook whose +# number is shared with another notebook (the NN glob is ambiguous there); +# optional otherwise. +DRIFT_TEST_FILES: Dict[str, str] = { + "16_survey_did": "test_t16_survey_did_drift.py", + "16_wooldridge_etwfe": "test_t16_wooldridge_etwfe_drift.py", + "34_design_diagnosis": "test_t34_design_diagnosis_drift.py", +} + +# Names removed at 4.0 that must not appear anywhere in a cell source. +# ``overall_att`` is matched as an exact name, because the bootstrap containers +# legitimately keep ``overall_att_se`` / ``overall_att_ci`` / ... +_REMOVED_NAME_PATTERNS: Tuple[Tuple[str, "re.Pattern[str]"], ...] = ( + ("overall_att", re.compile(r"(? List[str]: + return sorted(p.stem for p in TUTORIALS_DIR.glob("*.ipynb")) + + +def _load(stem: str) -> dict: + return json.loads((TUTORIALS_DIR / f"{stem}.ipynb").read_text(encoding="utf-8")) + + +def _source(cell: dict) -> str: + src = cell.get("source", "") + return "".join(src) if isinstance(src, list) else src + + +def _number(stem: str) -> str: + return stem.split("_", 1)[0] + + +# -------------------------------------------------------------------------- +# Rule implementations. Each returns a list of human-readable findings +# (empty = the rule holds). +# -------------------------------------------------------------------------- +def check_executed(nb: dict) -> List[str]: + """Code cells were executed top to bottom in one pass. + + Counts must be exactly 1..n over the non-empty code cells in cell order + (a cell that produced no output is fine). + """ + findings: List[str] = [] + counts = [ + cell.get("execution_count") + for cell in nb["cells"] + if cell["cell_type"] == "code" and _source(cell).strip() + ] + if counts != list(range(1, len(counts) + 1)): + n_missing = sum(c is None for c in counts) + if n_missing == len(counts): + findings.append("no code cell has been executed (no committed outputs)") + elif n_missing: + findings.append(f"{n_missing} of {len(counts)} code cells have no execution_count") + else: + findings.append(f"execution counts are not 1..{len(counts)} in cell order") + return findings + + +def check_error_output(nb: dict) -> List[str]: + """No committed traceback. Separate from ``check_executed`` so that a + notebook allowlisted for missing outputs still fails on a new error.""" + return [ + f"cell {idx}: error output ({out.get('ename')})" + for idx, cell in enumerate(nb["cells"]) + if cell["cell_type"] == "code" + for out in cell.get("outputs", []) + if out.get("output_type") == "error" + ] + + +def check_removed_names(nb: dict) -> List[str]: + findings = [] + for idx, cell in enumerate(nb["cells"]): + text = _source(cell) + for label, pattern in _REMOVED_NAME_PATTERNS: + if pattern.search(text): + findings.append(f"cell {idx}: removed 4.0 name {label!r}") + return findings + + +def _strip_magics(code: str) -> str: + """Drop IPython magics / shell escapes so the cell is plain Python.""" + lines = [ln for ln in code.splitlines() if not ln.lstrip().startswith(("%", "!"))] + return "\n".join(lines) + "\n" + + +def _identifier_tokens(code: str) -> FrozenSet[str]: + """Python NAME tokens in a code cell (strings and comments excluded). + + IPython magics / shell escapes are dropped first. If the cell still does + not tokenize, fall back to a word scan of the lines with string literals + crudely stripped - conservative, so a broken cell cannot hide a name. + """ + cleaned = _strip_magics(code) + try: + return frozenset( + tok.string + for tok in tokenize.generate_tokens(io.StringIO(cleaned).readline) + if tok.type == tokenize.NAME + ) + except (tokenize.TokenError, IndentationError, SyntaxError): + no_strings = re.sub(r"(\"[^\"\n]*\"|'[^'\n]*')", "", cleaned) + no_comments = re.sub(r"#.*", "", no_strings) + return frozenset(re.findall(r"[A-Za-z_]\w*", no_comments)) + + +def check_removed_identifiers(nb: dict) -> List[str]: + findings = [] + for idx, cell in enumerate(nb["cells"]): + if cell["cell_type"] != "code": + continue + hits = sorted(_identifier_tokens(_source(cell)) & _REMOVED_IDENTIFIERS) + if hits: + findings.append(f"cell {idx}: removed class/alias used in code: {hits}") + return findings + + +def check_jargon(nb: dict) -> List[str]: + findings = [] + for idx, cell in enumerate(nb["cells"]): + text = _source(cell) + for label, pattern in _JARGON_PATTERNS: + m = pattern.search(text) + if m: + findings.append(f"cell {idx}: {label} ({m.group(0)!r})") + return findings + + +def _is_str(node, value=None) -> bool: + ok = isinstance(node, ast.Constant) and isinstance(node.value, str) + return ok and (value is None or node.value == value) + + +# Literal ``message=`` / ``module=`` regexes that match every warning. The +# warnings module applies both anchored at the START of the text +# (``re.match``), so each of these is equivalent to passing no pattern. +_BLANKET_PATTERNS: FrozenSet[str] = frozenset({"", ".*", "^", "^.*", ".*$", "^.*$", ".*?", "(.*)"}) + + +def _narrows(node) -> bool: + """Does this ``message=`` / ``module=`` argument restrict the filter? + + Deliberately conservative: only the known blanket literals in + ``_BLANKET_PATTERNS`` count as "restricts nothing". Whether an arbitrary + regex matches every possible warning cannot be established statically, so + any other pattern - and any non-literal argument - is taken as narrowing. + The rule exists to stop "ignore everything" filters, not to grade regexes. + """ + return not (_is_str(node) and node.value in _BLANKET_PATTERNS) + + +def _unqualified_ignore_calls(code: str) -> List[str]: + """``filterwarnings`` / ``simplefilter`` calls that ignore EVERY warning. + + A call is qualified - and allowed - only if it narrows what it ignores: + a ``message`` / ``module`` pattern that does not match everything + (filterwarnings; see ``_narrows``), or a ``category`` other than the base + ``Warning``. Extra arguments that do not narrow it + (``append=``, ``lineno=``) do not count, and neither does spelling the + action as a keyword. + """ + try: + tree = ast.parse(_strip_magics(code)) + except SyntaxError: + # Cannot inspect arguments: be conservative and flag any ignore filter. + return [m.group(0) for m in _IGNORE_FILTER_TEXT.finditer(code)] + hits = [] + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + func = node.func + name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", None) + if name not in ("filterwarnings", "simplefilter"): + continue + # signatures: filterwarnings(action, message, category, module, lineno, append) + # simplefilter(action, category, lineno, append) + order = ( + ("action", "message", "category", "module") + if name == "filterwarnings" + else ("action", "category") + ) + args = dict(zip(order, node.args)) + args.update({kw.arg: kw.value for kw in node.keywords if kw.arg in order}) + if not _is_str(args.get("action"), "ignore"): + continue + narrowed = False + for key in ("message", "module"): + value = args.get(key) + if value is not None and _narrows(value): + narrowed = True + category = args.get("category") + if category is not None: + base = category.attr if isinstance(category, ast.Attribute) else None + base = category.id if isinstance(category, ast.Name) else base + if base != "Warning": + narrowed = True + if not narrowed: + hits.append(ast.unparse(node) if hasattr(ast, "unparse") else f"{name}('ignore', ...)") + return hits + + +def check_blanket_warning_filter(nb: dict) -> List[str]: + findings = [] + for idx, cell in enumerate(nb["cells"]): + if cell["cell_type"] != "code": + continue + for call in _unqualified_ignore_calls(_source(cell)): + findings.append(f"cell {idx}: unqualified warning suppression ({call})") + return findings + + +def check_em_dash(nb: dict) -> List[str]: + cells = [idx for idx, cell in enumerate(nb["cells"]) if _EM_DASH in _source(cell)] + return [f"em dash in cell sources: cells {cells}"] if cells else [] + + +def check_matplotlib_guard(nb: dict) -> List[str]: + cells = [idx for idx, cell in enumerate(nb["cells"]) if "HAS_MATPLOTLIB" in _source(cell)] + return [f"HAS_MATPLOTLIB guard: cells {cells}"] if cells else [] + + +def check_drift_test(stem: str, all_stems: List[str]) -> List[str]: + """The notebook has exactly one drift test. + + ``tests/test_t_*_drift.py`` must match exactly one file, unless the + notebook has an explicit ``DRIFT_TEST_FILES`` entry - which is mandatory + when another notebook shares its number. + """ + explicit = DRIFT_TEST_FILES.get(stem) + if explicit is not None: + if (TESTS_DIR / explicit).is_file(): + return [] + return [f"drift test tests/{explicit} does not exist"] + number = _number(stem) + if sum(_number(s) == number for s in all_stems) > 1: + return [f"number {number} is shared with another notebook: add a DRIFT_TEST_FILES entry"] + matches = sorted(p.name for p in TESTS_DIR.glob(f"test_t{number}_*_drift.py")) + if len(matches) == 1: + return [] + if not matches: + return [f"no drift test matches tests/test_t{number}_*_drift.py"] + return [f"several drift tests match tests/test_t{number}_*_drift.py: {matches}"] + + +def violations(stem: str, all_stems: List[str]) -> Dict[str, List[str]]: + """Every rule the notebook violates, with its findings.""" + nb = _load(stem) + results = { + EXECUTED: check_executed(nb), + ERROR_OUTPUT: check_error_output(nb), + REMOVED_NAME: check_removed_names(nb), + REMOVED_IDENTIFIER: check_removed_identifiers(nb), + JARGON: check_jargon(nb), + BLANKET_WARNING_FILTER: check_blanket_warning_filter(nb), + EM_DASH: check_em_dash(nb), + MATPLOTLIB_GUARD: check_matplotlib_guard(nb), + DRIFT_TEST: check_drift_test(stem, all_stems), + } + return {rule: found for rule, found in results.items() if found} + + +# -------------------------------------------------------------------------- +# The guard +# -------------------------------------------------------------------------- +_ALL_STEMS = _stems() +_GUARDED_STEMS = [s for s in _ALL_STEMS if s not in PENDING] + + +@pytest.mark.parametrize("stem", _GUARDED_STEMS) +def test_notebook_follows_conventions(stem): + found = violations(stem, _ALL_STEMS) + allowed = KNOWN_VIOLATIONS.get(stem, frozenset()) + + new = {rule: detail for rule, detail in found.items() if rule not in allowed} + assert not new, ( + f"docs/tutorials/{stem}.ipynb breaks the tutorial conventions " + f"(CONTRIBUTING.md, 'Tutorial conventions'). Fix the notebook; do not " + f"add to KNOWN_VIOLATIONS.\n" + + "\n".join(f" [{rule}] {line}" for rule, lines in new.items() for line in lines) + ) + + fixed = sorted(allowed - set(found)) + assert not fixed, ( + f"docs/tutorials/{stem}.ipynb no longer violates {fixed}: delete those " + f"entries from KNOWN_VIOLATIONS in tests/test_tutorial_conventions.py " + f"so the fix cannot regress." + ) + + +def test_configuration_is_consistent(): + stems = set(_ALL_STEMS) + unknown_rules = { + stem: sorted(set(rules) - set(ALL_RULES)) + for stem, rules in KNOWN_VIOLATIONS.items() + if set(rules) - set(ALL_RULES) + } + assert not unknown_rules, f"KNOWN_VIOLATIONS names unknown rules: {unknown_rules}" + forbidden = { + stem: sorted(set(rules) & NEVER_ALLOWED) + for stem, rules in KNOWN_VIOLATIONS.items() + if set(rules) & NEVER_ALLOWED + } + assert not forbidden, f"these rules can never be allowlisted: {forbidden}" + assert not [ + s for s, rules in KNOWN_VIOLATIONS.items() if not rules + ], "KNOWN_VIOLATIONS has an empty entry: delete the notebook's line instead" + stale = sorted(set(KNOWN_VIOLATIONS) - stems) + assert not stale, f"KNOWN_VIOLATIONS lists notebooks that do not exist: {stale}" + assert not ( + PENDING & set(KNOWN_VIOLATIONS) + ), "a notebook is in both PENDING and KNOWN_VIOLATIONS" + stale_map = sorted(set(DRIFT_TEST_FILES) - stems - PENDING) + assert not stale_map, f"DRIFT_TEST_FILES lists notebooks that do not exist: {stale_map}" + + +# -------------------------------------------------------------------------- +# The rules themselves: each fires on a violating fixture and stays quiet on +# a conforming one (so an edit cannot silently turn a rule into a no-op). +# -------------------------------------------------------------------------- +def _nb(*cells) -> dict: + return {"cells": list(cells)} + + +def _code(src, count=None, outputs=()): + return { + "cell_type": "code", + "source": src, + "execution_count": count, + "outputs": list(outputs), + } + + +def _md(src): + return {"cell_type": "markdown", "source": src} + + +class TestRules: + def test_executed_accepts_sequential_counts_and_empty_outputs(self): + nb = _nb(_md("# t"), _code("import x", 1), _code("", None), _code("print(1)", 2)) + assert check_executed(nb) == [] + + @pytest.mark.parametrize( + "cells, needle", + [ + ([_code("a", None), _code("b", None)], "no code cell has been executed"), + ([_code("a", 1), _code("b", None)], "1 of 2 code cells"), + ([_code("a", 2), _code("b", 1)], "not 1..2 in cell order"), + ([_code("a", 1), _code("b", 3)], "not 1..2 in cell order"), + ], + ) + def test_executed_rejects(self, cells, needle): + found = check_executed(_nb(*cells)) + assert any(needle in f for f in found), found + + def test_error_output_is_its_own_rule(self): + err = {"output_type": "error", "ename": "ValueError", "evalue": "x"} + # an executed notebook with a traceback: only the error rule fires + executed = _nb(_code("boom()", 1, [err])) + assert check_executed(executed) == [] + assert check_error_output(executed) == ["cell 0: error output (ValueError)"] + # a notebook allowlisted for missing execution counts still fails on it + partial = _nb(_code("a", None), _code("boom()", 1, [err])) + assert check_executed(partial) + assert check_error_output(partial) == ["cell 1: error output (ValueError)"] + assert check_error_output(_nb(_code("a", 1, [{"output_type": "stream"}]))) == [] + assert ERROR_OUTPUT in NEVER_ALLOWED + + def test_removed_names(self): + assert check_removed_names(_nb(_md("see `results.att`"), _code("r.att", 1))) == [] + # live bootstrap-container fields are not the removed attribute + ok = _nb(_code("b.overall_att_se; b.overall_att_ci; b.overall_se", 1)) + assert check_removed_names(ok) == [] + assert check_removed_names(_nb(_md("reported as `overall_att`."))) + assert check_removed_names(_nb(_code("# results.overall_att", 1))) + assert check_removed_names(_nb(_md("the former MultiPeriodDiD class"))) + assert check_removed_names(_nb(_code("StaggeredTripleDifference()", 1))) + + def test_removed_identifiers_only_match_code_identifiers(self): + quiet = _nb( + _md("QDiD and Stacked DiD are methods; Gardner (2022)."), + _code('print("Stacked data shape") # Gardner two-stage\nStackedDiD()', 1), + _code("%matplotlib inline\n!pip list\nChangesInChanges(method='qdid')", 2), + ) + assert check_removed_identifiers(quiet) == [] + assert check_removed_identifiers(_nb(_code("from diff_diff import Stacked", 1))) + assert check_removed_identifiers(_nb(_code("est = QDiD()", 1))) + assert check_removed_identifiers(_nb(_code("x: QDiDResults = fit()", 1))) + # a cell that does not tokenize still cannot hide a removed name + assert check_removed_identifiers(_nb(_code("est = Gardner(\n", 1))) + + @pytest.mark.parametrize( + "text", + [ + "(3.9, row M-021)", + "shipped in PR #397", + "the Phase 1 placebo", + "added in Wave C", + "see _scratch/dcdh_tutorial/", + "documented at had.py:1450", + ], + ) + def test_jargon_fires(self, text): + assert check_jargon(_nb(_md(text))) + + @pytest.mark.parametrize( + "text", + [ + "the M-estimator and ATT-012 are fine", + "a two-phase rollout; a wave of adoption", + "run `python script.py` and read model.py for details", + "PR is short for parallel trends here", + ], + ) + def test_jargon_quiet(self, text): + assert check_jargon(_nb(_md(text))) == [] + + @pytest.mark.parametrize( + "call", + [ + "warnings.filterwarnings('ignore')", + 'warnings.simplefilter("ignore")', + "warnings.filterwarnings('ignore', append=True)", + "warnings.simplefilter(action='ignore')", + "warnings.filterwarnings('ignore', category=Warning)", + "warnings.simplefilter('ignore', Warning)", + "warnings.filterwarnings('ignore', message='')", + "warnings.filterwarnings('ignore', message='.*')", + "warnings.filterwarnings('ignore', module='.*')", + "warnings.filterwarnings('ignore', '^')", + "warnings.filterwarnings('ignore', message='^.*$')", + "warnings.filterwarnings('ignore', message='.*', category=Warning, module='')", + "filterwarnings('ignore')", + "with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n fit()", + # a cell that does not parse cannot hide one + "warnings.simplefilter('ignore')\nest = fit(", + ], + ) + def test_blanket_warning_filter_fires(self, call): + assert check_blanket_warning_filter(_nb(_code(call, 1))) + + @pytest.mark.parametrize( + "call", + [ + "warnings.filterwarnings('ignore', category=FutureWarning)", + "warnings.simplefilter('ignore', DeprecationWarning)", + "warnings.simplefilter('ignore', category=np.exceptions.RankWarning)", + 'warnings.filterwarnings("ignore", message=".*matmul")', + "warnings.filterwarnings('ignore', '.*matmul', RuntimeWarning)", + "warnings.filterwarnings('ignore', module='pymc')", + "warnings.filterwarnings('ignore', message=r'^$|.*matmul')", + "warnings.filterwarnings('ignore', module=r'^$|pymc')", + "warnings.filterwarnings('ignore', message=r'^$|^[a-z]')", + "warnings.filterwarnings('ignore', message='.*', category=FutureWarning)", + "warnings.filterwarnings('ignore', message=PATTERN)", + "warnings.filterwarnings('error')", + "warnings.simplefilter('always')", + "%matplotlib inline\nwarnings.filterwarnings('ignore', category=UserWarning)", + ], + ) + def test_blanket_warning_filter_quiet(self, call): + assert check_blanket_warning_filter(_nb(_code(call, 1))) == [] + + def test_blanket_warning_filter_ignores_prose(self): + prose = _nb(_md("never call `warnings.filterwarnings('ignore')` globally")) + assert check_blanket_warning_filter(prose) == [] + + def test_em_dash_and_matplotlib_guard(self): + assert check_em_dash(_nb(_md("a — b"))) + assert check_em_dash(_nb(_code("# a — b", 1))) + assert check_em_dash(_nb(_md("a - b, 2019–2021"))) == [] # en dash is fine + assert check_matplotlib_guard(_nb(_code("if HAS_MATPLOTLIB:\n plot()", 1))) + assert check_matplotlib_guard(_nb(_code("import matplotlib.pyplot as plt", 1))) == [] + + def test_drift_test_resolution(self): + # explicit entry + assert check_drift_test("34_design_diagnosis", ["34_design_diagnosis"]) == [] + # unique number, glob matches exactly one existing file + assert check_drift_test("19_dcdh_marketing_pulse", ["19_dcdh_marketing_pulse"]) == [] + # shared number without an explicit entry + shared = check_drift_test("19_dcdh_marketing_pulse", ["19_dcdh_marketing_pulse", "19_x"]) + assert shared and "shared" in shared[0] + # no drift test at all + missing = check_drift_test("99_nothing", ["99_nothing"]) + assert missing and "no drift test" in missing[0] + + +class TestWorkflowPins: + """Notebook-only diffs must run this guard and the drift tests, and + neither lane fires on ``docs/**`` by accident: pin the wiring so a + workflow edit cannot silently de-wire it (the tracking-file guard's + TestWorkflowPins precedent).""" + + @staticmethod + def _text(name): + path = REPO_ROOT / ".github" / "workflows" / name + if not path.exists(): + pytest.skip(f"{name} not present") + return path.read_text(encoding="utf-8") + + @staticmethod + def _trigger_block(text, trigger): + on_block = text[: text.index("\njobs:")] + start = on_block.index(trigger) + later = [ + on_block.index(t) + for t in ("push:", "pull_request:", "schedule:", "workflow_dispatch:") + if t != trigger and t in on_block and on_block.index(t) > start + ] + return on_block[start : min(later)] if later else on_block[start:] + + @pytest.mark.parametrize("trigger", ["push:", "pull_request:"]) + def test_docs_tests_triggers_on_notebooks_and_this_file(self, trigger): + block = self._trigger_block(self._text("docs-tests.yml"), trigger) + for entry in ("docs/**", "tests/test_tutorial_conventions.py"): + assert f"'{entry}'" in block, ( + f"docs-tests.yml {trigger} paths filter is missing {entry!r} - " + "a diff touching only it would not run the tutorial conventions guard" + ) + + def test_docs_tests_runs_this_guard(self): + text = self._text("docs-tests.yml") + jobs = text[text.index("\njobs:") :] + assert ( + "pytest tests/test_tutorial_conventions.py" in jobs + ), "docs-tests.yml no longer runs the tutorial conventions guard" + + @pytest.mark.parametrize("trigger", ["push:", "pull_request:"]) + def test_notebooks_workflow_triggers_on_drift_tests(self, trigger): + block = self._trigger_block(self._text("notebooks.yml"), trigger) + for entry in ("docs/tutorials/**", "tests/test_t*_drift.py", "tests/_tutorial_drift.py"): + assert f"'{entry}'" in block, ( + f"notebooks.yml {trigger} paths filter is missing {entry!r} - " + "a notebook-only or drift-test-only diff would not run the drift tests" + ) + + def test_notebooks_workflow_runs_every_drift_test(self): + text = self._text("notebooks.yml") + jobs = text[text.index("\njobs:") :] + assert ( + "pytest tests/test_t*_drift.py" in jobs + ), "notebooks.yml no longer runs the tutorial drift tests on notebook diffs" From 01453a5f9a844dd56cae3cbc8d961b91890cac7f Mon Sep 17 00:00:00 2001 From: igerber Date: Wed, 25 Nov 2026 12:39:53 -0500 Subject: [PATCH 2/3] test(tutorials): resolve aliased warning-filter imports in the conventions guard from warnings import simplefilter as sf; sf('ignore') - or an assignment alias, possibly created in an earlier cell - no longer bypasses the blanket-warning-filter rule. --- tests/test_tutorial_conventions.py | 80 ++++++++++++++++++++++++++++-- 1 file changed, 76 insertions(+), 4 deletions(-) diff --git a/tests/test_tutorial_conventions.py b/tests/test_tutorial_conventions.py index 6a4a59159..14d70ed83 100644 --- a/tests/test_tutorial_conventions.py +++ b/tests/test_tutorial_conventions.py @@ -300,9 +300,46 @@ def _narrows(node) -> bool: return not (_is_str(node) and node.value in _BLANKET_PATTERNS) -def _unqualified_ignore_calls(code: str) -> List[str]: +_FILTER_FUNCTIONS = ("filterwarnings", "simplefilter") + + +def _filter_aliases(nb: dict) -> Dict[str, str]: + """Local names bound to ``warnings.filterwarnings`` / ``simplefilter`` + anywhere in the notebook: ``from warnings import simplefilter as sf`` or + ``sf = warnings.simplefilter`` (possibly in an earlier cell than the call). + Maps the local name to the canonical function name. + """ + aliases: Dict[str, str] = {} + for cell in nb["cells"]: + if cell["cell_type"] != "code": + continue + try: + tree = ast.parse(_strip_magics(_source(cell))) + except SyntaxError: + continue + for node in ast.walk(tree): + if isinstance(node, ast.ImportFrom) and node.module == "warnings": + for alias in node.names: + if alias.name in _FILTER_FUNCTIONS: + aliases[alias.asname or alias.name] = alias.name + elif isinstance(node, ast.Assign): + value = node.value + target = value.attr if isinstance(value, ast.Attribute) else None + target = aliases.get(value.id) if isinstance(value, ast.Name) else target + if target in _FILTER_FUNCTIONS: + for tgt in node.targets: + if isinstance(tgt, ast.Name): + aliases[tgt.id] = target + return aliases + + +def _unqualified_ignore_calls(code: str, aliases: Dict[str, str]) -> List[str]: """``filterwarnings`` / ``simplefilter`` calls that ignore EVERY warning. + ``aliases`` (from ``_filter_aliases``) resolves renamed imports and + assignments, so ``from warnings import simplefilter as sf; sf("ignore")`` + is recognized. + A call is qualified - and allowed - only if it narrows what it ignores: a ``message`` / ``module`` pattern that does not match everything (filterwarnings; see ``_narrows``), or a ``category`` other than the base @@ -320,8 +357,12 @@ def _unqualified_ignore_calls(code: str) -> List[str]: if not isinstance(node, ast.Call): continue func = node.func - name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", None) - if name not in ("filterwarnings", "simplefilter"): + if isinstance(func, ast.Attribute): + name = func.attr + else: + bare = getattr(func, "id", None) + name = aliases.get(bare, bare) + if name not in _FILTER_FUNCTIONS: continue # signatures: filterwarnings(action, message, category, module, lineno, append) # simplefilter(action, category, lineno, append) @@ -352,10 +393,11 @@ def _unqualified_ignore_calls(code: str) -> List[str]: def check_blanket_warning_filter(nb: dict) -> List[str]: findings = [] + aliases = _filter_aliases(nb) for idx, cell in enumerate(nb["cells"]): if cell["cell_type"] != "code": continue - for call in _unqualified_ignore_calls(_source(cell)): + for call in _unqualified_ignore_calls(_source(cell), aliases): findings.append(f"cell {idx}: unqualified warning suppression ({call})") return findings @@ -611,6 +653,36 @@ def test_blanket_warning_filter_fires(self, call): def test_blanket_warning_filter_quiet(self, call): assert check_blanket_warning_filter(_nb(_code(call, 1))) == [] + def test_blanket_warning_filter_resolves_aliases(self): + """A renamed import or assignment cannot hide a blanket filter - also + when the alias is created in an earlier cell than the call.""" + blanket = [ + _nb(_code("from warnings import simplefilter as sf\nsf('ignore')", 1)), + _nb(_code("from warnings import filterwarnings as fw\nfw('ignore')", 1)), + _nb( + _code("from warnings import filterwarnings as fw", 1), + _code("fw('ignore', append=True)", 2), + ), + _nb( + _code("import warnings\nquiet = warnings.simplefilter", 1), + _code("quiet('ignore')", 2), + ), + _nb(_code("from warnings import simplefilter\nmute = simplefilter\nmute('ignore')", 1)), + ] + for nb in blanket: + assert check_blanket_warning_filter(nb), nb + qualified = [ + _nb(_code("from warnings import simplefilter as sf\nsf('ignore', FutureWarning)", 1)), + _nb( + _code("from warnings import filterwarnings as fw", 1), + _code("fw('ignore', message='.*matmul', category=RuntimeWarning)", 2), + ), + # an unrelated function that happens to share the alias name pattern + _nb(_code("def sf(mode):\n return mode\nsf('ignore')", 1)), + ] + for nb in qualified: + assert check_blanket_warning_filter(nb) == [], nb + def test_blanket_warning_filter_ignores_prose(self): prose = _nb(_md("never call `warnings.filterwarnings('ignore')` globally")) assert check_blanket_warning_filter(prose) == [] From 45fa609a3672f136d154db223fdbafcd26b5bcd7 Mon Sep 17 00:00:00 2001 From: igerber Date: Wed, 25 Nov 2026 13:32:05 -0500 Subject: [PATCH 3/3] docs(contributing): describe the comparison-group assumptions as the paper does Tutorial convention 6 said neither the never-treated nor the not-yet-treated assumption is uniformly weaker. Callaway and Sant'Anna (2021) do not rank them; they say the not-yet-treated version additionally restricts pre-treatment trends across cohorts, and suggest never-treated when that group is sizeable. The convention now says that. --- CONTRIBUTING.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b3d44c9a9..736e6070b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -197,8 +197,13 @@ repair a notebook, delete its entries; never add one. parallel trends holds. Say so, and link the sensitivity tutorial (`05_honest_did`) and the pre-test power tutorial (`07_pretrends_power`). 6. **Control groups.** Never-treated and not-yet-treated comparisons rest on - different identifying assumptions; neither is uniformly weaker. Do not - describe one as "the stronger assumption". + different identifying assumptions. Say what each restricts, as Callaway and + Sant'Anna (2021, Assumptions 4 and 5) do: the not-yet-treated version also + restricts pre-treatment trends across cohorts (later cohorts' untreated + trends must match too), in exchange for a larger comparison group; the + never-treated version does not. They suggest never-treated when that group + is sizeable and not-yet-treated when it is missing or too small. Do not + rank the two as "weaker" and "stronger": the paper does not. 7. **Event studies: one idiom.** ```python