Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .github/workflows/docs-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
35 changes: 23 additions & 12 deletions .github/workflows/notebooks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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'
Expand Down Expand Up @@ -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()
Expand Down
142 changes: 142 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -152,6 +154,146 @@ 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. 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
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<NN>_<slug>_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/<notebook>.ipynb`.

## Test Writing Guidelines

### For Fallback/Error Handling Paths
Expand Down
11 changes: 11 additions & 0 deletions changelog.d/20261125-tutorial-conventions.md
Original file line number Diff line number Diff line change
@@ -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.
Loading
Loading