Skip to content

feat(staggered): cluster jackknife inference for CallawaySantAnna (vcov_type="jackknife") - #907

Merged
igerber merged 10 commits into
mainfrom
feat/cs-jackknife
Nov 25, 2026
Merged

igerber merged 10 commits into
mainfrom
feat/cs-jackknife

Conversation

@igerber

@igerber igerber commented Nov 25, 2026

Copy link
Copy Markdown
Owner

Summary

Cluster jackknife inference for CallawaySantAnna, for designs with few clusters. Implements Karim, Nielsen, MacKinnon & Webb (2026), whose paper review landed in #892.

  • CallawaySantAnna(vcov_type="jackknife"): each cluster (the cluster= column, or the unit when none is given) is deleted in turn, the estimator is re-run on the remaining data, and the variance is ((H - 1) / H) * sum_h (theta_h - theta)^2 around the full-sample estimate, with a t(H - 1) reference. No influence function is involved.
  • Coverage: the overall ATT (the paper's case), and by the same formula element-wise every ATT(g,t), each event-study horizon and each cohort of the group aggregation; the event-study container carries the jackknife covariance. The element-wise extension is a library choice, documented and backed by a size simulation (below).
  • results.get_loo_effects_df(): the delete-one overall ATTs, most influential cluster first (the name and layout SyntheticDiDResults already uses).
  • Rules where the paper gives none: H counts the clusters whose omission moves an estimate. A cluster counts when it holds a unit that enters a cell or a unit of a cohort whose whole-cohort mass is an aggregation weight; every other cluster label in the data is refitted without and counted if that changes any point input, so the rule is checked on every fit. Labels are read from the caller's data, never from the fit's recoded working copy. A deletion that leaves no estimate makes every jackknife standard error NaN; a cell, horizon or cohort not estimable in every delete-one sample gets NaN; a delete-one overall ATT built from the surviving cohorts enters the sum, with a warning (the paper's second caveat).
  • Warning for few treated clusters: a fit warns when the overall ATT or ATT(g,t) cells rest on fewer than three treated clusters, and aggregate() warns for the horizons and cohorts that do. The threshold comes from the simulation, not the paper.
  • Refused: with n_bootstrap > 0, survey_design=, allow_unbalanced_panel=True, and panel=False without cluster=.
  • Reports: DiagnosticReport gives a jackknife fit the existing hc2_bm parallel-trends policy (Bonferroni over the per-row p-values, no covariance-based joint Wald) and skips its pre-trends power section.
  • Tutorial 2: no longer says the multiplier bootstrap gives valid inference with few clusters.

New public surface: one new value of an existing argument (vcov_type="jackknife") and one method (CallawaySantAnnaResults.get_loo_effects_df). No new argument, no renamed or removed name. cluster_name stays None when no cluster column is given (M-080 unchanged). The results object keeps a cluster's label only for clusters coarser than the unit; unit-level deletions carry position codes, so no raw unit identifier is retained.

Methodology references (required if estimator / math changes)

  • Method name(s): CallawaySantAnna, cluster jackknife (CV3). docs/methodology/REGISTRY.md ## CallawaySantAnna, "Cluster jackknife"; docs/methodology/REPORTING.md, "Cluster-jackknife parallel-trends policy".
  • Paper / source link(s): Karim, S. R., Nielsen, M. Ø., MacKinnon, J. G., & Webb, M. D. (2026), "Improved Inference for CSDID Using the Cluster Jackknife", arXiv:2602.12043, Section 4, equation (20). https://arxiv.org/abs/2602.12043
  • Any intentional deviations from the source (and why), each labelled in the registry:
    • Deviation from R: didjack skips the treated cluster when there is exactly one and scales by the replicates run; the library returns NaN.
    • Notes (library choices where the paper is silent): the t(H - 1) reference; H as the clusters whose omission moves an estimate, with the per-fit check; refits keep cluster= so that every replicate uses the full-sample weighting route; the element-wise extension and the event-study covariance; the deleted-cell rules; the few-treated-clusters warning; the refused combinations; retained labels; the report policy.

Validation

  • Tests added/updated: tests/test_staggered_jackknife.py (new, 102 tests), tests/test_staggered.py (the vcov_type contract class), tests/test_aggregate_contract.py (df relay on a jackknife fit).

    • Every quantity equals a by-hand delete-one loop (same estimator, vcov_type="hc1", same cluster=, refitted on each delete-one frame) at 1e-12: overall, every cell, event study with and without balance_e, group, the full event-study covariance including off-diagonals; clustered, unit-level, repeated cross-sections, covariates with all three estimation methods, both comparison groups, both base periods, anticipation.
    • A panel with missing treated outcomes separates the two aggregation-weight routes, so the test fails if a refit ever drops cluster=.
    • Which clusters count: a cluster that only carries cohort mass, a missing-unit-ID cluster that moves a base period, an always-treated cluster (not counted), a cluster column that the fit recodes (cluster= on the first-treatment column), categorical units with an unused category, and datetime / period / categorical / tuple / float / string labels for clusters and units. The file passes on pandas 3.1, 2.2 and 1.5.
    • R parity: benchmarks/R/generate_cs_jackknife_golden.R runs did::att_gt + aggte (did 2.5.1) on each delete-one-cluster sample for four configurations; overall, event-study and group jackknife standard errors, p-values and intervals match to 1e-8.
  • Backtest / simulation / notebook evidence (if applicable): benchmarks/python/cs_jackknife_size.py (results committed as benchmarks/data/cs_jackknife_size.json; the registry's numbers are pinned to that file by TestSizeEvidence). No effect, nominal 5%, the grid of the paper's Table 1 (8 to 32 clusters) with 1 and 5 units per cluster, 1,000 replications per design point. Rejection rates by treated clusters per cohort J:

    J Overall ATT: default (cluster=) multiplier bootstrap jackknife Single-cohort horizon: default jackknife
    1 15-35% 26-39% 8-18% 42-72% NaN
    2 5-15% 14-19% 3-10% 14-29% 6-18%
    3 7-11% 12-21% 5-8% 12-19% 6-12%
    4 6-9% 9-12% 4-7% 7-14% 4-9%
    6 to 12 4-7% 7-10% 3-6% 6-10% 4-7%

    The jackknife rejects less than the default at every design point and is close to nominal from three treated clusters per cohort. It still over-rejects with very few treated clusters, as the paper reports. Horizons identified by a single cohort rest on J treated clusters and reject more; at an equal number of treated clusters they match the overall ATT. This is one simulated design.

  • mypy diff_diff at the pinned versions reports no errors; the Sphinx -W build passes.

Tracked for later (TODO.md): the jackknife for the other staggered estimators; the jackknife with allow_unbalanced_panel=True; and a finding from the same simulation about existing behaviour, not changed here: the report's chi-square joint pre-trend test on default clustered fits rejects 13-22% with six or more treated clusters per cohort and 62-78% with two.

Security / privacy

  • Confirm no secrets/PII in this PR: Yes

Changelog

  • changelog.d/ fragment added (or N/A - no user-visible change): Yes

…ov_type="jackknife")

Implements the delete-one-cluster jackknife (CV3) of Karim, Nielsen, MacKinnon
& Webb (2026, arXiv:2602.12043), equation (20): each cluster is deleted in
turn, the estimator is re-run on the remaining data, and the variance is
((H - 1) / H) * sum_h (theta^(h) - theta)^2 around the full-sample estimate,
with a t(H - 1) reference.

- CallawaySantAnna accepts vcov_type="jackknife". Clusters come from cluster=,
  or the unit when none is given. Refits keep every parameter, cluster
  included, so they take the full-sample fit's routing and weights.
- Applies to the overall ATT, every ATT(g,t), and the event-study and group
  aggregations (element-wise; outer-product form for the event-study
  covariance). The replicates ride the aggregation kit as point estimates.
- H counts the clusters that enter the estimation. A deletion that leaves no
  estimate makes every standard error NaN; a cell or aggregate missing in some
  delete-one sample gets NaN; the overall ATT follows the paper (surviving
  cohorts enter) with a warning.
- results.get_loo_effects_df() returns the delete-one overall ATTs. Labels are
  kept only for clusters coarser than the unit; unit-level deletions carry
  position codes, so no raw unit identifier is retained.
- Refused with n_bootstrap > 0, survey_design=, allow_unbalanced_panel=True,
  and panel=False without cluster=.
- DiagnosticReport: a jackknife fit takes the hc2_bm parallel-trends policy
  (Bonferroni over the per-row p-values, no covariance-based joint Wald) and
  its pre-trends power section is skipped.

Validated against R did 2.5.1 on delete-one samples
(benchmarks/R/generate_cs_jackknife_golden.R) and against a by-hand loop.
…clusters; size simulation

- A cluster-jackknife fit warns when the overall ATT or ATT(g,t) cells rest on
  fewer than three treated clusters, and aggregate() warns for the event-study
  horizons and cohorts that do. The threshold is a library choice backed by
  the size simulation, not by the paper.
- benchmarks/data/cs_jackknife_size.json: rejection rates of hc1, the
  multiplier bootstrap and the jackknife over the paper's Table 1 grid
  (42 design points, 1,000 replications each) for the overall ATT,
  event-study coefficients and the pre-trend tests.
- Results docstrings: vcov_type, n_clusters and df_inference describe the
  jackknife lane.
- REGISTRY CallawaySantAnna: "Cluster jackknife" section (equation, the
  paper's caveats, and labelled notes for the reference distribution, H, the
  refit route, the element-wise extension, measured size, the few-treated
  warning, deleted cells, the deviation from the R package, refused
  combinations, retained labels and reports); taxonomy and roster updated.
- REPORTING: cluster-jackknife parallel-trends policy with its measured size.
- v4-design section 7: why the jackknife sits on vcov_type.
- API page, autosummary stubs, references, estimator guide, AI guides,
  doc-deps, methodology review entry, changelog fragment.
- Tutorial 2: the multiplier bootstrap is not presented as a few-cluster fix.
- TODO: the jackknife for the other staggered estimators and for
  allow_unbalanced_panel; the chi-square joint pre-trend test on clustered
  default fits.
- tests: TestSizeEvidence pins the documented ranges to the simulation file.
One line per design point with derived ratios rounded to 6 decimals and the
rejection counts stored exactly. A rerun reproduces the first run's rates.
…ference-only replicate horizons

- Cluster labels are resolved from the caller's frame, not from the fit's
  working copy, which recodes the first-treatment and time columns. A
  deletion that removes no row now raises instead of contributing a no-op
  replicate.
- A horizon estimated in the full sample that is reference-only in a
  delete-one sample takes that sample's value (0) instead of being treated as
  missing.
- llms-practitioner: the few-clusters message no longer nests double quotes
  inside an f-string (invalid before Python 3.12).
- REGISTRY: notes for both rules; the cost statement counts the baseline
  estimation.
…an estimate

- A cluster is a deletion unit when it holds a unit of a cohort whose
  whole-cohort mass is an aggregation weight (cluster-route cohort masses,
  universal-base reference cells), even if the unit enters no cell: deleting
  it shifts the weights. Such clusters were left out before.
- The rule is now checked on every fit: clusters it excludes are refitted too
  and promoted to deletion units if their omission changes any point input.
- REGISTRY: the H note states both.
…epeated cross-sections; cost count

- The refit-cost warning counts the refits actually run (audited spare
  clusters and the baseline estimation), not the H the variance is built on.
- Equality with the by-hand loop for estimation_method='ipw' with covariates
  on the panel route, and for reg / ipw / dr with covariates on repeated
  cross-sections (overall, cells, event study, group).
…r's data

A cluster made only of rows with a missing unit ID holds no unit of the
estimation index, yet such a row can add a period to the calendar grid and
move a cohort's base period. Those labels are now audited like the other
excluded clusters: refitted without, and deleted for real when that changes
any point input. REGISTRY and the accessor docstring say so.
…udit

The minimum was checked on the structurally resolved clusters, before the
audit could promote one, so a design with one ordinary cluster and one
audited cluster was refused instead of getting NaN inference with the
undefined-deletion warning. The early check now only rejects designs whose
whole candidate set is below two; the binding check is on the audited
replicates.
…etime IDs

- Only index entries with rows in the caller's data are deletion candidates:
  an unused category of a categorical unit column (listed by the fit's
  groupby before pandas 3.0) is neither deleted nor audited.
- Labels are taken as pandas Index elements, not ndarray.tolist(), which
  turned datetime64 unit IDs into integers that matched no row.
- Tests: categorical units with an unused category, a hand-built index entry
  without rows, and datetime / period / categorical / tuple / float / string
  labels for both clusters and units.
@github-actions

Copy link
Copy Markdown

Overall assessment

✅ Looks good — no unmitigated P0 or P1 findings identified in the reviewed changes.

Executive summary

  • The CV3 formula uses full-sample centering, the correct (H−1)/H factor, and full delete-one re-estimation.
  • Refits retain cluster=, preserving the full-sample aggregation weighting route.
  • Undefined deletions and missing replicate estimates propagate NaNs through inference using shared helpers.
  • Extensions beyond the paper are explicitly documented; deferred feature coverage is tracked.
  • Static checks passed. Runtime tests and independent PDF verification were unavailable in this environment.

Methodology

P3 — Informational: documented extensions and deviations.
Location: docs/methodology/REGISTRY.md:L1058-L1082.

Impact: The t(H−1) reference, element-wise inference, event-study covariance, contributing-cluster definition, and deleted-cell rules extend the paper’s scalar formula. These choices are explicitly labeled and therefore are not defects.

Concrete fix: None required.

The implementation in diff_diff/staggered_jackknife.py:L103-L124 matches equation (20) reproduced in the committed paper audit. Inference replacement consistently uses safe_inference() and safe_inference_batch() at diff_diff/staggered_jackknife.py:L616-L641.

Source verification relied on the Registry and committed paper audit; the original PDF could not be retrieved.

Code Quality

No actionable findings. Reviewed empty-result handling, deletion-label alignment, parameter propagation, and NaN guards without identifying a new correctness defect.

Performance

No actionable findings. Full re-estimation and the additional baseline/audit fits impose an expected cost that is documented in docs/methodology/REGISTRY.md:L1054-L1060.

Maintainability

No actionable findings. Replicate aggregation reuses the existing point-estimation aggregation code, reducing the risk of divergent weighting logic.

Tech Debt

P3 — Informational: deferred feature coverage is tracked.
Location: TODO.md:L41-L42.

Impact: Other staggered estimators and unbalanced-panel jackknife inference remain unsupported. The unsupported Callaway–Sant’Anna combination raises explicitly.

Concrete fix: None required for this PR; follow the tracked work.

Security

No findings identified in the changed code or committed artifacts.

Documentation/Tests

No actionable findings. The required release fragment is present at changelog.d/20261125-cs-jackknife.md:L1-L32, and the added tests cover substantive configuration, weighting, deletion, and inference cases.

Validation completed: all nine changed Python files parsed; both new JSON fixtures and the tutorial notebook parsed; all four R golden configurations had internally consistent overall CV3 variance, degrees of freedom, and CI centering.

Validation limitation: NumPy, pandas, SciPy, and pytest are absent, so the runtime suite could not be executed.

@igerber igerber added the ready-for-ci Triggers CI test workflows label Nov 25, 2026
@igerber
igerber merged commit 3718f2b into main Nov 25, 2026
47 of 48 checks passed
@igerber
igerber deleted the feat/cs-jackknife branch November 25, 2026 20:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ci Triggers CI test workflows

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant