Skip to content

fix(stacked_did): complete event windows and equal cohort shares on both arms (all weightings, survey weights) - #914

Merged
igerber merged 3 commits into
mainfrom
stacked-complete-windows
Nov 26, 2026
Merged

igerber merged 3 commits into
mainfrom
stacked-complete-windows

Conversation

@igerber

@igerber igerber commented Nov 26, 2026

Copy link
Copy Markdown
Owner

Summary

Closes the TODO.md row "StackedDiD returns shifted estimates with NO warning on ragged event windows", and fixes two weighting defects found while working on it.

The stacked regression (Wing, Freedman & Hollingsworth 2024, Eq. 3) contrasts (treated x event-time) and (control x event-time) cell means. Two conditions make those contrasts the trimmed aggregate ATT, and the library broke both.

1. Complete event windows

The contrasts are within-unit changes only when the same units sit in every cell of a sub-experiment, which is how the paper builds its stack (Section 5.1). fit() kept every row of an eligible unit inside the window, so on a panel with missing observations level differences between units leaked into the estimates, with no warning.

  • Complete-window rule. A unit enters a sub-experiment only if it has a row at every integer event time of [-kappa_pre - anticipation, kappa_post]. Excluded units are reported in one warning with per-event "kept of eligible" counts; the estimand is the trimmed aggregate ATT over the units observed across their whole window.
  • Events without complete units are dropped with a warning and move from groups to trimmed_groups (including a window that contains a period no unit observes). With none left fit() raises ValueError, naming gaps in the time grid.
  • Under survey_design= both exclusions are refused (NotImplementedError): they would remove PSUs and strata from the variance. Tracked in TODO.md.
  • balance="entropy" trims the same way instead of raising.
  • Input validation. Duplicate (unit, time) rows, a missing or non-integer time and a non-integer first_treat raise ValueError; each was silently mis-assigned before.

Noiseless panel, 90 units, 10 periods, cohorts 4 and 6 plus never-treated, kappa_pre = kappa_post = 2, true ATT 2.5:

Panel Before After
balanced 2.5000 2.5000 (exactly unchanged)
one never-treated observation missing 2.4978 2.5000
5% of rows missing at random 2.6020 2.5000
half of cohort 6 missing its e = -1 row 2.2965 2.5000
all of cohort 6 missing e = -1, or no pre-treatment rows 1.9500 2.5000 on cohort 4; cohort 6 dropped
never-treated units missing periods 7-8 2.7000 2.5000 on cohort 4; cohort 6 dropped
period 7 absent for every unit 2.6833 2.5000 on cohort 4; cohort 6 dropped
period 5 absent for every unit 1.7667 ValueError naming the gap
never-treated units missing periods 4-8 NaN + rank warning ValueError
duplicated (unit, time) rows 2.5411 ValueError
rows at a fractional time 1.3833 ValueError

None of the "before" rows warned, apart from the NaN case.

2. Equal cohort shares on both arms

Section 5.3 of the paper: the untreated trends cancel only if the treated arm and the control arm aggregate the sub-experiments with the same shares.

  • weighting="population" / "sample_share" set the treated weight to 1, where Table 1 gives the treated rows a weight as well. The arms were aggregated with different shares.
  • survey_design= formed the corrective weights from raw unit counts and then multiplied by the survey weight, with the same consequence.

One formula on unit masses now gives both arms the target share pi_a, from survey-weighted masses under a survey design, recomputed in each replicate refit. Survey columns must be constant within a unit; the treated units' population is validated; a sub-experiment with no mass carries zero weight and is named in a warning.

Configuration (noiseless) Before After
weighting="population", balanced: largest event-study row error 0.0023 exact
weighting="sample_share", balanced: largest event-study row error 0.10 exact
survey weights 1.5 / 0.5 / 1 by cohort (true ATT 2.50) 2.46 2.50
half of a cohort at survey weight 0 (true ATT 2.50) 2.4733 2.50
survey weights changing within a unit (true ATT 2.5) 2.6174 ValueError

weighting="aggregate" without survey weights is bit-identical: 36 default-weighting configurations, an entropy-balanced fit and a wider-window fit compare exactly equal to the pre-change values on both backends.

Methodology references (required if estimator / math changes)

  • Method name(s): Stacked Difference-in-Differences (weighted stacked event study); covariate-balanced weighted stacked DiD for the balance="entropy" path
  • Paper / source link(s): Wing, C., Freedman, S. M. and Hollingsworth, A. (2024), "Stacked Difference-in-Differences", NBER Working Paper 32054, https://www.nber.org/papers/w32054 (Section 5.1 stack construction, Section 5.3 and Table 1 weights). Ustyuzhanin, V. (2026), arXiv:2604.02293.
  • Any intentional deviations from the source (and why):
    • Deviation from R (REGISTRY **Deviation from R:**): the authors' reference code (hollina/stacked-did-weights) keeps incomplete units and returns the shifted numbers on ragged panels; the library before this change matched it to 12 digits. On a stack trimmed by hand the reference code and the library agree to 1e-10 in coefficients and cluster-robust SEs. Balanced panels are unaffected.
    • The paper prescribes nothing for missing rows; the complete-window rule restores the data structure its proof assumes (REGISTRY **Note:**).
    • Survey-weighted corrective weights are a library extension, since the paper has no survey weights (REGISTRY **Note:**): the target is the design-weighted aggregate, the Taylor-linearized variance conditions on the realized shares, and replicate refits recompute them.
    • R cbwsdid already builds its stack from complete units, so balance="entropy" on a ragged panel now matches it (1,185 stacked rows in both, dynamic ATTs within 9e-8).

Validation

  • Tests added/updated:
    • tests/test_stacked_did.py: new classes TestStackedDiDCompleteWindows, TestStackedDiDCompleteWindowsSurvey and TestStackedDiDCohortShares. They cover exact recovery on noiseless ragged panels, 30 random-missingness panels, an independent oracle (cohort DID contrasts from plain or survey-weighted cell means, aggregated with shares computed from the input panel), the Table 1 weight formulas, zero-mass sub-experiments, and replicate variance against per-replicate weighted cell means. On main, 47 of the 51 new or changed complete-window tests fail, as do 31 of the 35 cohort-share and estimand-prose tests; the rest are unchanged-behavior checks.
    • tests/test_methodology_stacked_did.py: new test_ragged_panel_matches_r_cbwsdid.
    • tests/test_target_parameter.py: the estimand prose names each scheme's share.
    • Existing tests that changed:
      • TestEdgeCases::test_unbalanced_panel now asserts the trim.
      • TestStackedDiDCovariateBalance: three tests that expected a ValueError on ragged windows now expect the trim (test_ragged_event_window_trims, test_zero_row_eligible_control_is_trimmed) or the duplicate-row error (test_duplicate_unit_time_rows_raise).
      • TestReferenceSupportGuard and TestReferenceSupportGuardEffectiveWeights: the gapped and ragged panels now end in the "no sub-experiment" ValueError or a dropped event; the guard keeps one test per remaining cause.
      • TestStackedDiDVcovType::test_replicate_refit_coef_bit_equal_vs_bake_w_baseline: the pinned replicate SE moves from 0.14697 to 0.14471 because each refit now recomputes the corrective weights; its pinned ATT is unchanged.
      • The four population / sample-share R parity tests and tests/test_survey_estimator_validation.py::test_s2_stacked_did keep their assertions against regenerated goldens.
  • R goldens:
    • benchmarks/data/stacked_did_golden.json: only the population and sample_share blocks changed. New helper benchmarks/python_helpers/dump_stacked_did_panel.py (the R script referenced it, but it was not in the repo) regenerates the pre-stacked CSVs; the default and anticipation CSVs come out byte-identical.
    • benchmarks/data/synthetic/survey_estimator_validation_golden.json: only the S2 block changed. The R benchmark implements the corrected formula independently before survey::svyglm; its ATT matches the library to 8e-12 (5.0396 before, 5.0838 now) and the SE gap is 0.79%, inside the test's 1.5%.
    • benchmarks/data/cbwsdid_golden.json: new dynamic_ragged block; existing numbers byte-identical.
  • Backtest / simulation / notebook evidence (if applicable): tutorial 13 executes under --nbmake (two markdown bullets and one printed note reworded; it stores no outputs).
  • Sibling audit (report only): CallawaySantAnna, SunAbraham, ImputationDiD, TwoStageDiD, WooldridgeDiD and the TWFE event study recover the truth on the same ragged and gapped panels; LPDiD raises on gapped time grids.

Security / privacy

  • Confirm no secrets/PII in this PR: Yes

Changelog

  • changelog.d/ fragment added (or N/A - no user-visible change): Yes (changelog.d/20261126-stacked-complete-windows.md, Fixed + Behavioral Changes)

…both arms under every weighting and under survey weights

The stacked regression (Wing, Freedman & Hollingsworth 2024, Eq. 3) contrasts
(treated x event-time) and (control x event-time) cell means. Two conditions
make those contrasts the trimmed aggregate ATT, and the library broke both.

1. The same units must sit in every cell of a sub-experiment (Section 5.1).
   fit() kept every row of an eligible unit inside the window, so on a panel
   with missing observations level differences between units leaked into the
   estimates with no warning (noiseless panel, true ATT 2.5: 2.4978 with one
   observation missing, 2.6020 with 5% missing at random, 1.7667 with a
   calendar period absent for every unit).

   - Complete-window rule: a unit enters a sub-experiment only if it has a row
     at every integer event time of [-kappa_pre - anticipation, kappa_post].
     Excluded units are reported in one warning with per-event "kept of
     eligible" counts; the estimand is the trimmed aggregate ATT over the units
     observed across their whole window.
   - An event left without a complete treated unit or clean control (including
     a window containing a period no unit observes) is dropped with a warning
     and moves from groups to trimmed_groups; with none left fit() raises
     ValueError, naming gaps in the time grid.
   - Under survey_design= both exclusions are refused (NotImplementedError):
     they would remove PSUs and strata from the variance.
   - balance="entropy" trims the same way instead of raising, matching R
     cbwsdid (new dynamic_ragged golden block).
   - Duplicate (unit, time) rows, a missing or non-integer time and a
     non-integer first_treat raise ValueError; each was silently mis-assigned.

2. Both arms must aggregate the sub-experiments with the same shares
   (Section 5.3), or the untreated trends do not cancel.

   - weighting="population" / "sample_share" set the treated weight to 1 where
     Table 1 gives a treatment weight (largest event-study row error on
     balanced noiseless panels: 0.0023 and 0.10).
   - Under survey_design= the corrective weights used raw unit counts (2.46 for
     a true 2.50 with weights 1.5 / 0.5 / 1 by cohort).

   One formula on unit masses now gives both arms the target share, from
   survey-weighted masses under a survey design, recomputed in each replicate
   refit. Survey columns must be constant within a unit; the treated units'
   population is validated; a sub-experiment with no mass carries zero weight
   and is named in a warning. weighting="aggregate" without survey weights is
   bit-identical.

The authors' reference R code returns the same shifted numbers on ragged
panels; the complete-window rule is a documented deviation from it. R goldens
for the population, sample-share and survey (S2) variants are regenerated; an
independent R implementation of the survey formula matches to 1e-11.
@github-actions

Copy link
Copy Markdown

Overall assessment: ✅ Looks good

No unmitigated P0/P1 findings. One P2 test-coverage issue.

Executive summary

  • Reviewed StackedDiD’s window construction, three weighting schemes, survey refits, and entropy-balancing path.
  • The implementation agrees with the Registry’s documented formulas and deviations.
  • Independent calculations reproduce four fixtures’ Q weights, coefficients, and CR1S standard errors within (1.4\times10^{-14}).
  • The new replicate oracle does not actually vary cohort shares.
  • Python syntax and changelog checks pass. Pytest could not run because dependencies are absent; network restrictions prevented direct paper retrieval.

Methodology

P3 — Informational: documented methodology choices. Complete-window trimming, the departure from the R stack construction, and survey variance conditional on realized shares are explicitly documented in docs/methodology/REGISTRY.md:L2632-L2637.

Impact: These choices define the retained population and inference convention. They are not defects under the review rules.
Concrete fix: None required.

Source comparison used the Registry, docstrings, and checked-in Ustyuzhanin paper review. Direct primary-paper verification remains limited by network availability.

Code Quality

No actionable findings. The changed helper’s caller is updated, and affected inference paths retain safe_inference().

Performance

No actionable findings.

Maintainability

No actionable findings. The shared weighting helper keeps full-sample and replicate calculations consistent.

Tech Debt

No new untracked finding. Survey domain-estimation limitations and remaining balancing extensions are recorded in TODO.md and DEFERRED.md.

Security

No findings in the reviewed changes.

Documentation/Tests

P2 — The replicate oracle does not exercise changing cohort shares.
Location: tests/test_stacked_did.py:L3113-L3139.

Each replicate deletes exactly three units from each cohort. Because weights are constant by cohort, multiplying survivors by 10/9 restores the original cohort masses. Consequently, every replicate has the same corrective Q weights as the full sample.

Impact: This oracle would also pass if replicate refits reused the full-sample Q weights, leaving the central recomputation behavior unverified independently.

Concrete fix: Use unit-varying weights, such as _cw_weighted(..., "random"); assert that at least one replicate changes cohort shares, then retain the independent cell-mean variance comparisons for both mse settings.

…rt shares move across replicates

With weights constant within a cohort, the JK1 columns removed the same mass
from every cohort, so each replicate had the full-sample cohort shares and the
oracle would also have passed if the refits reused the full-sample corrective
weights (verified: that mutant matched to 1.5e-14). With unit-varying weights
the cohort-4 share ranges 0.486 to 0.541 across replicates (0.509 full sample)
and the same mutant is off by 11% in the SE under both mse settings. The test
now asserts that the shares move.
@github-actions

Copy link
Copy Markdown

🔁 AI review rerun (requested by @igerber)

Head SHA: 3ff0b437b763c50db04a6645b64388697b1d76ef


Overall assessment: ✅ Looks good

No unmitigated P0/P1 findings. The previous P2 replicate-oracle finding is resolved.

Executive summary

  • The revised oracle uses unit-varying weights, asserts changing replicate shares, and retains independent variance comparisons for both mse settings.
  • StackedDiD’s weighting and complete-window changes agree with the Methodology Registry.
  • Independent calculations reproduced four fixtures’ weights, coefficients, and CR1S standard errors within (1.6\times10^{-14}).
  • Python syntax and changelog checks passed. Pytest could not run because dependencies are absent; DNS failure prevented direct paper retrieval.

Methodology

P3 — Informational: documented methodological choices.
Location: docs/methodology/REGISTRY.md:L2632-L2637.

Affected methods are Wing–Freedman–Hollingsworth weighted stacked DiD and Ustyuzhanin’s covariate-balanced extension. Complete-window trimming, departure from the R stacking behavior, survey-weighted shares, and variance conditional on realized shares are explicitly documented.

Impact: These choices define the retained population and inference convention; they are not defects under the review rules.
Concrete fix: None required.

Source checks used the Registry, docstrings, checked-in Ustyuzhanin paper review, and numerical fixtures. Direct primary-paper verification remains unavailable.

Code Quality

No actionable findings. The changed helper’s caller is updated, and affected inference paths retain all-or-nothing NaN handling through safe_inference().

Performance

No actionable findings in the reviewed changes.

Maintainability

No actionable findings. Full-sample and replicate calculations share the same corrective-weight helper.

Tech Debt

No new untracked findings. Existing survey-domain work and deferred balancing extensions remain recorded in TODO.md and DEFERRED.md.

Security

No findings in the reviewed changes.

Documentation/Tests

Previous P2 finding resolved.
Location: tests/test_stacked_did.py:L3113-L3146.

The oracle now uses random unit-level weights and asserts that at least one replicate’s cohort share differs from the full-sample share by more than 0.01. Independent weighted-cell-mean variance comparisons remain for both mse=False and mse=True.

Impact: The test now exercises the share-recomputation behavior previously left unverified.
Concrete fix: None required.

The required changelog fragment is present and passes validation. Runtime test results were not independently verified in this environment.

@igerber igerber added the ready-for-ci Triggers CI test workflows label Nov 26, 2026
…e class docstring

The list had a wrapped item and no blank line before or after it, so docutils
read it as a paragraph with an unexpectedly indented line and the Sphinx -W
build failed (one ERROR, two WARNINGs on the StackedDiD docstring). Rendering
the changed modules' docstrings through napoleon and docutils reproduces the
three messages before this change and none after.
@github-actions

Copy link
Copy Markdown

🔁 AI review rerun (requested by @igerber)

Head SHA: 55e31e53312a8bbfdf44f3fcc03f57a805b4e1b4


Overall assessment: ✅ Looks good

No unmitigated P0/P1 findings. The previous replicate-oracle finding remains resolved.

Executive summary

  • The replicate oracle checks changing cohort shares and independently calculates variance for both mse settings.
  • Complete-window trimming and weighting changes match the Methodology Registry.
  • Independent calculations verified four fixtures’ Q-weights, coefficients, and CR1S standard errors within (1.6\times10^{-14}).
  • Python syntax and changelog validation passed. Runtime tests remain unverified because dependencies are absent; DNS failure prevented direct paper retrieval.

Methodology

P3 — Informational: documented methodological choices.
Location: docs/methodology/REGISTRY.md:L2632-L2637.

Affected methods are Wing–Freedman–Hollingsworth weighted stacked DiD and Ustyuzhanin’s covariate-balanced extension. Cross-checks against the Registry, docstrings, and checked-in paper review support the equal-share formulas and complete-window construction. Trimming, departure from the R stacking behavior, survey-weighted shares, and conditional analytical variance are explicitly documented.

Impact: These choices define the retained population and inference convention; they are informational under the review rules.
Concrete fix: None required.

Direct primary-paper verification was unavailable.

Code Quality

No actionable findings. The changed helper’s caller is updated, empty stacks receive explicit errors, and affected inference paths retain consistent NaN handling through safe_inference().

Performance

No actionable findings in the reviewed changes.

Maintainability

No actionable findings. Full-sample and replicate calculations share the corrective-weight helper.

Tech Debt

No new untracked findings. Survey-domain support and deferred balancing extensions remain recorded in TODO.md and DEFERRED.md.

Security

No findings in the reviewed changes.

Documentation/Tests

Previous P2 finding resolved.
Location: tests/test_stacked_did.py:L3113-L3146.

The oracle uses unit-varying weights, requires a replicate cohort-share change greater than 0.01, and compares reported standard errors with independent weighted-cell-mean calculations for both centering conventions.

Impact: The test exercises the share-recomputation behavior previously left unverified.
Concrete fix: None required.

The required changelog fragment is present and passes validation. Runtime pytest results were not independently verified.

@igerber
igerber merged commit aecaac0 into main Nov 26, 2026
35 checks passed
@igerber
igerber deleted the stacked-complete-windows branch November 26, 2026 19:58
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