Repository navigation
StatsPAI 1.17.0 — correctness fixes + agent-UX hardening
Added
-
Registry-example bind guard (
tests/test_registry_examples_bind.py).
A parametrized test now statically parses every registeredexamplestring
and binds the keyword arguments of itssp.<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 readssp.describe_function(name)and runs the example verbatim — so
the registry/example drift fixed below cannot silently return. 373 examples
bind green. -
parityoptional extra — opt-in DoubleML reference pin forsp.dml.
pip install -e ".[dev,parity]"now installsdoubleml-for-py(the Python
DoubleML reference of Bach, Chernozhukov, Kurz & Spindler, JMLR 23(53),
2022), sotests/external_parity/test_dml_python_parity.pyruns instead
of silently skipping. Under identical scikit-learn learners and folds,
sp.dml(model='plr')reproducesdoubleml-for-pyto machine precision on
the seed-42 fixture —|Δ coefficient| = 1.1e-16and|Δ standard error| = 1.4e-17, i.e. one float64 unit in the last place.doublemlremains not
a runtime dependency. The measured numbers, software versions, and the
divergence discussion are recorded in a new Double Machine Learning Parity
section ofdocs/joss_validation_dossier.md, with a one-command reproduce
path added todocs/joss_reviewer_guide.md. Verified by installing the
extra and running bothtests/external_parity/test_dml_python_parity.pyand
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 ofsp.drdid(Sant'Anna & Zhao
2020) normalised each of its four cell terms (treated/control × post/pre) by
the full sample sizeninstead 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, somethod='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.drdidnow also raisesValueErroron an
unknownmethodinstead of silently treating it as traditional (previously
e.g.method='ipw'ran the traditional branch). See MIGRATION.md. -
⚠️ Correctness:sp.multiway_cluster_vcovundercounted 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 vianp.unique(axis=0)on per-dimension
integer codes.sp.multiway_cluster_vcovnow reproducessandwich::vcovCL
andsp.twoway_clusterto machine precision (two-way exact; three-way rel
~4e-7), pinned by the newtests/r_paritymodule 56 and a direct
twoway-vs-multiway regression test. Propagates todid.harvestand
panel.feolsmultiway-clustered SEs.sp.twoway_clusteritself 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 storedf_resid = infto signal a large-sample
(normal) reference distribution, butglance()cast the residual degrees of
freedom withint()unconditionally. The cast now passes non-finite degrees
of freedom through unchanged; finite results keep an integerdf_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 bytests/test_glance_survival.py. -
sp.event_studyresults crashed the library's own exporters, plotters and
pre-trend tools (canonical-column mismatch).sp.event_studyemitted its
coefficient table under the column nameestimate, but the rest of the DID
family — and every downstream consumer — keys on the canonicalattcolumn
(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_plotraised
KeyError: 'att'; andsp.honest_did/sp.breakdown_mraised
ValueError: missing {'att'}. The event-study table now carries the
canonicalattcolumn (withestimateretained as a backward-compatible
alias), fixing every consumer at the source. No numerical change. -
sp.pretrends_test/sp.pretrends_summarycrashed (LinAlgError: Singular matrix) on every standardsp.event_studyresult — the same
reference-period defect already fixed inpretrends_power: the SE = 0
omitted period made the diagonal VCV singular. It is now dropped before
inversion, with a clearValueErroron a genuinely collinear pre-period set. -
sp.diagnose_resultcrashed (TypeError: bad operand type for abs(): 'str') onsp.synthresults. The donor-pool check iterated the synthetic
weights, butsp.synthstores 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_powercrashed (LinAlgError: Singular matrix) on every
standardsp.event_studyresult. 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 andnp.linalg.invraised 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-lengthdeltaare aligned to the retained
periods, and a still-singular VCV now raises a clearValueError(collinear
pre-periods) instead of an opaque NumPy error. No output changes for any call
that previously succeeded. Covered bytests/test_pretrends_power.py. -
⚠️ Correctness —sp.structural_breaksup-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 — notF(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 sequentialsupF(l+1|l)stopping rule (previously the
same naive-F over-detection), somethod='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 returningNone. Reference
verified via Crossref / Econometric Society / RePEc: Andrews, D.W.K. (1993),
Econometrica 61(4), 821-856, doi:10.2307/2951764. SeeMIGRATION.md. -
33 registered
examplestrings were statically broken (agent-UX). Six
failed to parse (stray/unmatchedparens, a positional-after-keyword
...placeholder, an unclosed call) and 27 passed a keyword the function
does not accept — a deterministicTypeError/SyntaxErroron 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 shortb_exp/b_out/se_exp/se_outnames instead
of the implementedbeta_exposure/beta_outcome/se_exposure/se_outcome,
and the Bayesian family (bayes_rd/bayes_fuzzy_rd/bayes_mte/bayes_did/
bayes_iv) plusmetalearner/tmle/causal_impact/sensemakr/
spec_curve/qreg/tobit/heckman/cluster_cross_interference/
causal_dqn/pci_mtp/bartik/ffl_decomposedrifted from their
signatures.qreg/tobit/heckman/spec_curveadditionally had wrong
call shapes (formula passed positionally intodata; flatcontrols
where a list-of-lists was required) and were rebuilt to runnable form and
executed to confirm. Fixed acrossregistry.pyand_baseline_cards.py;
the regeneratedschemas/bundle stays in sync. Guarded by the new
bind test above. -
sp.heckman/sp.tobitMCP tool schemas advertised parameters the
functions reject (agent-native path). The priorexample-string fix above
repaired the copy-paste path, but the other drifted field — the
FunctionSpec.paramsthat generate each tool's MCPinput_schema— was left
pointing at a never-implemented formula API:heckmanexposed required
formula/select_formulaandtobitexposedformula/lower/upper,
while the implementations takedata, y, x, select, zanddata, y, x, ll, ul. An agent calling either tool exactly as the manifest instructed hit a
deterministicTypeError: ... got an unexpected keyword argument 'formula'.
Theexample-bind guard above does not cover this because it validates the
examplefield, notparams. Re-pointed bothparamsblocks at the real
signatures inregistry.py; the regeneratedschemas/bundle is back in
sync and both tools now dispatch (sp.heckmanrecovers the known-truth
β=2.05 fixture through the MCP dispatch layer). The estimator numerics were
never affected — Python-directsp.heckman(...)/sp.tobit(...)always
worked; only the MCP schema was wrong. -
⚠️ Correctness —sp.stabilized_weights/sp.msmsilently 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_probahelper swallowed the resultingLinAlgErrorand silently
returned the marginal mean for both the numerator and denominator models,
so every stabilized weight collapsed to exactly1.0— turning the marginal
structural model into an unweighted, confounded regression with no
warning (a CLAUDE.md §7 silent-degradation violation)._logit_probanow
drops zero-variance columns before fitting (the numerically correct move:
such columns only duplicate the intercept thatadd_constantadds) and,
if the treatment model still fails to converge (e.g. perfect separation),
emits aRuntimeWarninginstead 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 bytests/test_msm_singleperiod_iptw_regression.py
(3 new tests) plus the existingtests/test_msm.py(8 green total). See
MIGRATION.md. -
CI: scikit-learn 1.9 compatibility —
LassoCV(n_alphas=...)removal.
scikit-learn 1.7 deprecated then_alphasargument of the coordinate-descent
CV estimators (LassoCV/ElasticNetCV/…) in favour of passing an integer to
alphas, and 1.9 removed it outright — constructingLassoCV(n_alphas=20)
now raisesTypeError: LassoCV.__init__() got an unexpected keyword argument 'n_alphas'. TheCI/CD Pipelinematrix resolves to scikit-learn 1.9.0, so
sp.tmle(method='hal')(HALRegressor) andsp.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 shimstatspai.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 forrd_flex) is unchanged — no numerical effect. Verified
on the local scikit-learn 1.6.1 pin (8 HAL tests + 6rd_flextests green)
and by version-logic assertion across 1.6/1.7/1.8/1.9. -
CI:
schemas/functions.jsonno 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.DataFramewhile pandas < 3.0 renders as the internal
pandas.core.frame.DataFrame. Because pandas 3.0 requires Python >= 3.11,
the committed bundle matched the CIubuntu x 3.10shard but was flagged
stale on every 3.11/3.12/3.13 shard, failingCI/CD Pipeline
(tests/test_schema_export.py::test_committed_schemas_dir_is_in_sync).
_stringify_annotationnow 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_testsrecorded each parity test as a validation-evidence
note viastr(path.relative_to(root)), which emits OS-native separators —
so Windows runners wrotetests\reference_parity\...backslash notes. That
(a) failedtests/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.jsonaway 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 insp.validation_report()) and
scripts/stability_audit.pynow build paths withPath.as_posix();
tests/test_causal_workflow.pyandtests/test_paper_tables.pynow read the
UTF-8 HTML/LaTeX/markdown reports they generate withencoding="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.mddocumented foursp.dmlpatterns 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-existenttrim=keyword (propensity clipping is automatic at
[0.01, 0.99], with the clip counts reported inr.diagnostics). Every
documented result attribute and all fourmodel=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 smallsp.dml-vs-
doubleml-for-pyIRM gap; the gap (0.0076 absolute, ≈ 0.10 SE) is verified
not to move with trimming nor withnormalize_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, andREADME_CN.md
now matchpython 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 --checkexits 0). Docs only — no API change.