Skip to content

StatsPAI 1.17.0 — correctness fixes + agent-UX hardening

Choose a tag to compare

@brycewang-stanford brycewang-stanford released this 06 Jun 08:30
· 2939 commits to main since this release

Added

  • Registry-example bind guard (tests/test_registry_examples_bind.py).
    A parametrized test now statically parses every registered example string
    and binds the keyword arguments of its sp.<name>(...) call against the real
    signature, failing if an example references a keyword the function does not
    accept or does not parse. This locks down the agent copy-paste path — an
    agent reads sp.describe_function(name) and runs the example verbatim — so
    the registry/example drift fixed below cannot silently return. 373 examples
    bind green.

  • parity optional extra — opt-in DoubleML reference pin for sp.dml.
    pip install -e ".[dev,parity]" now installs doubleml-for-py (the Python
    DoubleML reference of Bach, Chernozhukov, Kurz & Spindler, JMLR 23(53),
    2022), so tests/external_parity/test_dml_python_parity.py runs instead
    of silently skipping. Under identical scikit-learn learners and folds,
    sp.dml(model='plr') reproduces doubleml-for-py to machine precision on
    the seed-42 fixture — |Δ coefficient| = 1.1e-16 and |Δ standard error| = 1.4e-17, i.e. one float64 unit in the last place. doubleml remains not
    a runtime dependency. The measured numbers, software versions, and the
    divergence discussion are recorded in a new Double Machine Learning Parity
    section of docs/joss_validation_dossier.md, with a one-command reproduce
    path added to docs/joss_reviewer_guide.md. Verified by installing the
    extra and running both tests/external_parity/test_dml_python_parity.py and
    tests/reference_parity/test_dml_parity.py (55 DML tests green).

Fixed

  • ⚠️ Correctness: sp.drdid(method='trad') returned ~half the true ATT.
    The traditional doubly-robust DiD branch of sp.drdid (Sant'Anna & Zhao
    2020) normalised each of its four cell terms (treated/control × post/pre) by
    the full sample size n instead of by that cell's weight mass. This
    multiplied every term by the cell's sample share (~0.25 each on a balanced
    2×2), biasing the ATT toward zero by ~50%: on a 2×2 with a true ATT of 2.0
    (raw DiD 1.96) the traditional estimator returned ≈1.04. Each term is now
    normalised by its own weight total, so method='trad' reduces exactly to the
    raw 2×2 DiD when no covariates are supplied and recovers the true ATT with
    covariates. The improved (locally efficient) method='imp' — the default
    — already normalised correctly and is unchanged, so no default-path or
    parity/dossier numbers move. sp.drdid now also raises ValueError on an
    unknown method instead of silently treating it as traditional (previously
    e.g. method='ipw' ran the traditional branch). See MIGRATION.md.

  • ⚠️ Correctness: sp.multiway_cluster_vcov undercounted intersection
    clusters, biasing multiway-cluster-robust standard errors.
    The
    Cameron-Gelbach-Miller inclusion-exclusion builds an intersection cluster
    (the unique combinations of the clustering dimensions); its key was formed by
    joining the dimensions into a single string with a "\0" separator, but
    NumPy fixed-width unicode strips the embedded NUL, so e.g. (1, 23) and
    (12, 3) both collapsed to "123". On a 40×50 crossed-cluster DGP this
    merged 1733 true intersection clusters into 1639, biasing the two-way SE by
    ~0.2% (~0.5% at three-way) versus the canonical estimator. The intersection
    key is now built collision-free via np.unique(axis=0) on per-dimension
    integer codes. sp.multiway_cluster_vcov now reproduces sandwich::vcovCL
    and sp.twoway_cluster to machine precision (two-way exact; three-way rel
    ~4e-7), pinned by the new tests/r_parity module 56 and a direct
    twoway-vs-multiway regression test. Propagates to did.harvest and
    panel.feols multiway-clustered SEs. sp.twoway_cluster itself was already
    correct (distinct collision-free key) and is unchanged. See MIGRATION.md.

  • .glance() crashed (OverflowError: cannot convert float infinity to integer) on Cox and parametric-survival (survreg) results. Those
    estimators deliberately store df_resid = inf to signal a large-sample
    (normal) reference distribution, but glance() cast the residual degrees of
    freedom with int() unconditionally. The cast now passes non-finite degrees
    of freedom through unchanged; finite results keep an integer df_resid
    (no change). A crash-hunt across ~48 fitted results confirmed the rest of
    the §3 unified-result export surface (summary/to_latex/to_markdown/
    to_word/to_excel/cite/tidy/for_agent/plot) is otherwise clean
    across 20+ estimator families. Covered by tests/test_glance_survival.py.

  • sp.event_study results crashed the library's own exporters, plotters and
    pre-trend tools (canonical-column mismatch).
    sp.event_study emitted its
    coefficient table under the column name estimate, but the rest of the DID
    family — and every downstream consumer — keys on the canonical att column
    (did._core.EVENT_STUDY_COLUMNS). So the canonical event-study estimator
    was incompatible with its own tooling: .tidy() (and the .to_markdown() /
    .to_excel() / .to_word() exporters that delegate to it) raised
    TypeError: unsupported operand type(s) for /: 'NoneType' and 'float';
    .plot() / .event_study_plot() / sp.enhanced_event_study_plot raised
    KeyError: 'att'; and sp.honest_did / sp.breakdown_m raised
    ValueError: missing {'att'}. The event-study table now carries the
    canonical att column (with estimate retained as a backward-compatible
    alias), fixing every consumer at the source. No numerical change.

  • sp.pretrends_test / sp.pretrends_summary crashed (LinAlgError: Singular matrix) on every standard sp.event_study result — the same
    reference-period defect already fixed in pretrends_power: the SE = 0
    omitted period made the diagonal VCV singular. It is now dropped before
    inversion, with a clear ValueError on a genuinely collinear pre-period set.

  • sp.diagnose_result crashed (TypeError: bad operand type for abs(): 'str') on sp.synth results. The donor-pool check iterated the synthetic
    weights, but sp.synth stores them as a ['unit', 'weight'] DataFrame, so
    iteration yielded column-name strings. The weights are now coerced to their
    numeric values regardless of container (DataFrame / Series / dict / array).

  • sp.pretrends_power crashed (LinAlgError: Singular matrix) on every
    standard sp.event_study result.
    Roth's (2022) pre-trend power calculation
    inverts the pre-period variance–covariance matrix, but the omitted reference
    period (relative time −1) is reported with a standard error of exactly zero,
    so the diagonal VCV was singular and np.linalg.inv raised on the exact
    workflow shown in the function's own docstring. The reference period (and any
    other mechanically-normalised, zero-SE period) is now dropped before
    inversion — it is the baseline, not an estimated coefficient — so the joint
    pre-trend test runs on the estimated pre-periods only. A full-rank
    model_info['vcv_pre'] and a full-length delta are aligned to the retained
    periods, and a still-singular VCV now raises a clear ValueError (collinear
    pre-periods) instead of an opaque NumPy error. No output changes for any call
    that previously succeeded. Covered by tests/test_pretrends_power.py.

  • ⚠️ Correctness — sp.structural_break sup-F p-value used the wrong null
    distribution.
    The Chow/sup-F statistic is a supremum of the F statistic
    over candidate break points, so under H0 it follows the Andrews (1993)
    sup-F law — not F(k, n-2k). The previous code referred the maximised
    statistic to the ordinary F CDF, which ignored the maximisation and
    massively over-rejected: on pure Gaussian white noise at the 5% level the
    test flagged a spurious structural break in 33–37% of series (measured,
    n ∈ {100, 200, 400}). The p-value is now computed from the Andrews (1993)
    limiting null — a q-vector Brownian-bridge functional sampled by a
    deterministic, cached simulation on a grid tied to the sample size —
    restoring nominal size (~0.05) while retaining power (1.00 / 0.88 to
    detect a one-/half-σ mean shift at n=200). The same correct threshold now
    drives the Bai-Perron sequential supF(l+1|l) stopping rule (previously the
    same naive-F over-detection), so method='bai-perron' no longer
    over-segments noise. As a side benefit the Bai-Perron result now populates
    f_stats / p_values (one sup-F statistic and Andrews p-value per detected
    break, chronologically aligned) instead of returning None. Reference
    verified via Crossref / Econometric Society / RePEc: Andrews, D.W.K. (1993),
    Econometrica 61(4), 821-856, doi:10.2307/2951764. See MIGRATION.md.

  • 33 registered example strings were statically broken (agent-UX). Six
    failed to parse (stray/unmatched parens, a positional-after-keyword
    ... placeholder, an unclosed call) and 27 passed a keyword the function
    does not accept — a deterministic TypeError/SyntaxError on the exact
    agent copy-paste path. Root causes were two long-standing parameter-name
    drifts: the Mendelian-randomization family (mr_egger/mr_ivw/mr_raps/
    mr_presso) used the short b_exp/b_out/se_exp/se_out names instead
    of the implemented beta_exposure/beta_outcome/se_exposure/se_outcome,
    and the Bayesian family (bayes_rd/bayes_fuzzy_rd/bayes_mte/bayes_did/
    bayes_iv) plus metalearner/tmle/causal_impact/sensemakr/
    spec_curve/qreg/tobit/heckman/cluster_cross_interference/
    causal_dqn/pci_mtp/bartik/ffl_decompose drifted from their
    signatures. qreg/tobit/heckman/spec_curve additionally had wrong
    call shapes (formula passed positionally into data; flat controls
    where a list-of-lists was required) and were rebuilt to runnable form and
    executed to confirm. Fixed across registry.py and _baseline_cards.py;
    the regenerated schemas/ bundle stays in sync. Guarded by the new
    bind test above.

  • sp.heckman / sp.tobit MCP tool schemas advertised parameters the
    functions reject (agent-native path).
    The prior example-string fix above
    repaired the copy-paste path, but the other drifted field — the
    FunctionSpec.params that generate each tool's MCP input_schema — was left
    pointing at a never-implemented formula API: heckman exposed required
    formula/select_formula and tobit exposed formula/lower/upper,
    while the implementations take data, y, x, select, z and data, y, x, ll, ul. An agent calling either tool exactly as the manifest instructed hit a
    deterministic TypeError: ... got an unexpected keyword argument 'formula'.
    The example-bind guard above does not cover this because it validates the
    example field, not params. Re-pointed both params blocks at the real
    signatures in registry.py; the regenerated schemas/ bundle is back in
    sync and both tools now dispatch (sp.heckman recovers the known-truth
    β=2.05 fixture through the MCP dispatch layer). The estimator numerics were
    never affected — Python-direct sp.heckman(...) / sp.tobit(...) always
    worked; only the MCP schema was wrong.

  • ⚠️ Correctness — sp.stabilized_weights / sp.msm silently dropped all
    IPTW adjustment on single-period panels.
    On a single-period (point-
    treatment) panel the within-unit lagged-treatment column is all-zero, which
    made the logistic treatment-model design singular. The internal
    _logit_proba helper swallowed the resulting LinAlgError and silently
    returned the marginal mean for both the numerator and denominator models,
    so every stabilized weight collapsed to exactly 1.0 — turning the marginal
    structural model into an unweighted, confounded regression with no
    warning (a CLAUDE.md §7 silent-degradation violation). _logit_proba now
    drops zero-variance columns before fitting (the numerically correct move:
    such columns only duplicate the intercept that add_constant adds) and,
    if the treatment model still fails to converge (e.g. perfect separation),
    emits a RuntimeWarning instead of silently degrading. On the regression
    fixture the fixed path reproduces a textbook stabilized-IPTW computation to
    machine precision (max|Δw| = 1.8e-15); the already-correct multi-period
    path is unchanged. Verified by tests/test_msm_singleperiod_iptw_regression.py
    (3 new tests) plus the existing tests/test_msm.py (8 green total). See
    MIGRATION.md.

  • CI: scikit-learn 1.9 compatibility — LassoCV(n_alphas=...) removal.
    scikit-learn 1.7 deprecated the n_alphas argument of the coordinate-descent
    CV estimators (LassoCV/ElasticNetCV/…) in favour of passing an integer to
    alphas, and 1.9 removed it outright — constructing LassoCV(n_alphas=20)
    now raises TypeError: LassoCV.__init__() got an unexpected keyword argument 'n_alphas'. The CI/CD Pipeline matrix resolves to scikit-learn 1.9.0, so
    sp.tmle(method='hal') (HALRegressor) and sp.rd_flex(learner='lasso')
    both failed at construction (tests/test_hal_tmle.py,
    tests/test_estimator_provenance_round5.py::TestHalTmleProvenance,
    tests/test_low_cov_battery.py::test_hal_regressor_predicts_finite). A new
    version-robust shim statspai.compat.sklearn.lasso_cv_alphas_kwargs(n) emits
    {"alphas": n} on scikit-learn >= 1.7 and {"n_alphas": n} on older
    releases; both call sites now route through it. The number of path alphas
    (20 for HAL, 50 for rd_flex) is unchanged — no numerical effect. Verified
    on the local scikit-learn 1.6.1 pin (8 HAL tests + 6 rd_flex tests green)
    and by version-logic assertion across 1.6/1.7/1.8/1.9.

  • CI: schemas/functions.json no longer drifts by pandas version. The
    auto-registered schema export stringified parameter annotations via
    str(typing.Optional[pandas.DataFrame]), which pandas 3.0 renders as
    pandas.DataFrame while pandas < 3.0 renders as the internal
    pandas.core.frame.DataFrame. Because pandas 3.0 requires Python >= 3.11,
    the committed bundle matched the CI ubuntu x 3.10 shard but was flagged
    stale on every 3.11/3.12/3.13 shard, failing CI/CD Pipeline
    (tests/test_schema_export.py::test_committed_schemas_dir_is_in_sync).
    _stringify_annotation now canonicalises pandas internal module paths to
    their public form, so the exported bundle is byte-identical across pandas
    versions. Verified by regenerating under both pandas 2.x and pandas 3.0 and
    confirming identical output. Agent-facing schema metadata only — no
    numerical effect.

  • CI: Windows shards no longer fail on validation-evidence path separators.
    _scan_reference_tests recorded each parity test as a validation-evidence
    note via str(path.relative_to(root)), which emits OS-native separators —
    so Windows runners wrote tests\reference_parity\... backslash notes. That
    (a) failed tests/test_jss_validation_api.py::test_certified_validated_symbols_have_attached_evidence_notes
    because the JSS evidence-grade markers are forward-slash, and (b) drifted
    agent_cards.json away from the POSIX-generated committed bundle, failing
    the schema-sync guard on every Windows shard. Notes are now built with
    Path.as_posix() and the test files are iterated in a POSIX-keyed sort, so
    the evidence notes — and the exported bundle — are byte-identical on Windows
    and POSIX. Agent-facing metadata only — no numerical effect.

  • CI hardening: swept the same OS-portability class across the codebase. A
    multi-agent audit surfaced the remaining latent siblings of the two bugs
    above (none yet red, but each a Windows landmine of the identical class):
    validation._rel (artifact paths in sp.validation_report()) and
    scripts/stability_audit.py now build paths with Path.as_posix();
    tests/test_causal_workflow.py and tests/test_paper_tables.py now read the
    UTF-8 HTML/LaTeX/markdown reports they generate with encoding="utf-8"
    (cp1252 default would mojibake on Windows — CLAUDE.md §5). Two POSIX-runnable
    schema-bundle invariants were added (no backslash separators; no internal
    pandas.core. paths) so both classes are caught on any shard, not only the
    one whose regeneration diverges.

  • Docs: docs/reference/dml.md documented four sp.dml patterns that
    raised on copy-paste.
    r.coef → r.estimate; r.ci(alpha=0.05) →
    r.ci (a (lower, upper) tuple — the level is set via
    sp.dml(..., alpha=)); r.influence_function (never exposed on
    CausalResult) → r.diagnostics / r.pvalue; and an IRM example passing a
    non-existent trim= keyword (propensity clipping is automatic at
    [0.01, 0.99], with the clip counts reported in r.diagnostics). Every
    documented result attribute and all four model= types now run on the
    bundled fixture. Docs only — no API or numerical change.

  • Docs: corrected an unverified claim in
    docs/guides/sp_dml_vs_doubleml.md.
    The guide asserted that matching
    propensity-trimming thresholds eliminates the small sp.dml-vs-
    doubleml-for-py IRM gap; the gap (0.0076 absolute, ≈ 0.10 SE) is verified
    not to move with trimming nor with normalize_ipw, and stems from
    internal AIPW score construction. PLR agreement is now stated as the
    measured machine-precision figure (1.1e-16 / 1.4e-17) rather than "four
    decimal places", and an over-broad "PLR / PLIV / IIVM agree to machine
    precision" line was narrowed to the PLR case that is actually pinned.

  • Docs: refreshed live registry-stats drift. docs/stats.md (per-module
    table + the measured source/test LOC rows), README.md, and README_CN.md
    now match python scripts/registry_stats.py (269,043 core LOC / 96,514 test
    LOC; 1,020 functions across 81 submodules). This restores
    tests/test_jss_release_manifest.py::test_registry_stats_docs_are_live
    (scripts/registry_stats.py --check exits 0). Docs only — no API change.