diff --git a/.zenodo.json b/.zenodo.json index cd49b99..ae110ea 100644 --- a/.zenodo.json +++ b/.zenodo.json @@ -1,7 +1,7 @@ { "title": "hank-limits: analytic-limit and aggregate-identity tests for HANK codes", "upload_type": "software", - "version": "0.2.1", + "version": "0.3.0", "license": "MIT", "creators": [ { @@ -10,7 +10,7 @@ "affiliation": "Risk & Return Co., Ltd." } ], - "description": "

Tests that a HANK code must pass at limits with known answers, reported as errors and observed convergence orders. Reference implementation on sequence-jacobian 1.0.0, with minimal reproductions of two observations about that library (F1, F2). Not peer reviewed.

AI use: Developed with extensive assistance from Claude Opus 5.5 (Anthropic) and reviewed with GPT 6.1 Sol (OpenAI); the author directed and reviewed the work and is responsible for the content.

", + "description": "

Tests that a HANK code must pass at limits with known answers, reported as errors and observed convergence orders. Version 0.3.0 adds checks V1-V6 computed from primitive quantities the code reports: the GE target residual of the vanishing-liquidity solve, steady-state market-clearing and budget residuals, income normalisation, the documented specification along equilibrium paths, and the solved exogenous paths against the requested ones, with a verdict that missing or non-finite values cannot hide. Mutation tests of the suite on hand-made and independently generated errors, with pre-registered predictions, are documented in docs/MUTATION_v0_1.md, docs/MUTATION_v0_2.md and docs/CHECKS_v0_3_0_AMENDMENT.md. Reference implementation on sequence-jacobian 1.0.0, with minimal reproductions of three observations about that library: F1, F2 and F3 (hetinputs and hetoutputs differentiated one-sided, reported as shade-econ/sequence-jacobian#41). Not peer reviewed.

AI use: Developed with extensive assistance from Claude Opus 5.5 (Anthropic) and reviewed with GPT 6.1 Sol (OpenAI); the author directed and reviewed the work and is responsible for the content.

", "keywords": [ "HANK", "heterogeneous agents", diff --git a/CITATION.cff b/CITATION.cff index bc6763e..7a84272 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -1,17 +1,14 @@ cff-version: 1.2.0 message: "If you use this software, please cite it as below." title: "hank-limits: analytic-limit and aggregate-identity tests for HANK codes" -version: 0.2.1 -date-released: "2026-10-20" +version: 0.3.0 +date-released: "2026-10-24" license: MIT doi: 10.5281/zenodo.23489176 identifiers: - type: doi value: 10.5281/zenodo.23489176 description: "Concept DOI (all versions)" - - type: doi - value: 10.5281/zenodo.23489177 - description: "Version 0.2.1" type: software authors: - family-names: "Han" @@ -23,8 +20,13 @@ abstract: >- Tests that a HANK code must pass at limits with known answers or at exact identities (permanent-income household-block limit, TANK benchmark with imposed incidence, Werning (2015) vanishing liquidity, Aiyagari no-idiosyncratic-risk limit, intertemporal Keynesian cross consistency, HANK - RANK differencing - identity), reported as errors and observed convergence orders rather than single pass/fail checks. Reference implementation on sequence-jacobian 1.0.0, with minimal - reproductions of two observations about that library (F1, F2). Developed with extensive assistance + identity), reported as errors and observed convergence orders rather than single pass/fail checks. Version 0.3.0 + adds checks V1-V6 computed from primitive quantities the code reports (GE target residual of the vanishing-liquidity + solve, steady-state market-clearing and budget residuals, income normalisation, the documented specification along + equilibrium paths, and the solved exogenous paths against the requested ones), with a verdict that missing or + non-finite values cannot hide, and mutation tests of the suite on hand-made and independently generated errors. + Reference implementation on sequence-jacobian 1.0.0, with minimal reproductions of three observations about that + library (F1, F2, F3). Developed with extensive assistance from Claude Opus 5.5 (Anthropic) and reviewed with GPT 6.1 Sol (OpenAI); the author directed and reviewed the work and is responsible for the content. See the AI usage disclosure in the README. keywords: diff --git a/README.md b/README.md index f7bd7e0..71f3125 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,8 @@ -# hank-limits v0.2.1: analytic-limit and aggregate-identity tests for HANK codes - -**This branch: v0.3 (unreleased)** on top of release v0.2.1; see "v0.3 (unreleased)" below. +# hank-limits v0.3.0: analytic-limit and aggregate-identity tests for HANK codes [![DOI](https://zenodo.org/badge/1426447298.svg)](https://doi.org/10.5281/zenodo.23489176) -Cite all versions with the concept DOI [10.5281/zenodo.23489176](https://doi.org/10.5281/zenodo.23489176); this release (v0.2.1) is [10.5281/zenodo.23489177](https://doi.org/10.5281/zenodo.23489177). GitHub's "Cite this repository" button uses `CITATION.cff`. +Cite all versions with the concept DOI [10.5281/zenodo.23489176](https://doi.org/10.5281/zenodo.23489176). The DOI of this release (v0.3.0) will be added here and in `CITATION.cff` after it is archived on Zenodo. The previous release, v0.2.1, is [10.5281/zenodo.23489177](https://doi.org/10.5281/zenodo.23489177). GitHub's "Cite this repository" button uses `CITATION.cff`. This repository collects tests that a heterogeneous-agent New Keynesian (HANK) code should pass at limits with known answers and at exact aggregate identities. It is implemented on the public package `sequence-jacobian` (SSJ) 1.0.0. Each test reports not only pass/fail at one point but **the error as the limit parameter goes to its limit and the observed order of convergence**. @@ -28,25 +26,31 @@ This repository collects tests that a heterogeneous-agent New Keynesian (HANK) c **v0.2 → v0.2.1 (R4 follow-up review, same reviewer):** (1) removed the diagnostic field `normalisation_err_last_sweep`, which was always zero by construction; (2) the second Aiyagari cell is now reported as "not reproduced, cause unresolved", with a comparison against the level CV and autocorrelation of the original Table I and a grid audit; (3) the practical impact of F2 is limited to this example; (4) horizon independence in T1 is limited to the linear household Jacobian at a fixed steady state; (5) revised wording of the SSJ issue drafts. Test results are unchanged. -### v0.3 (unreleased): steady-state, normalisation and specification checks +### Changes v0.2.1 → v0.3.0: steady-state, normalisation and specification checks -Not released: the version in `pyproject.toml`, the tags and the citation metadata are still those of v0.2.1. Plan and pre-registration: `docs/CHECKS_PLAN_v0_3.md`; mutation tests: `docs/MUTATION_v0_1.md` (v0.2.1 suite) and `docs/MUTATION_v0_2.md` (v0.2.1 against v0.3 on independently generated mutants). +Plan and pre-registration: `docs/CHECKS_PLAN_v0_3.md`. Changes after the pre-release review, and their re-run: `docs/CHECKS_v0_3_0_AMENDMENT.md`. Mutation tests: `docs/MUTATION_v0_1.md` (v0.2.1 suite) and `docs/MUTATION_v0_2.md` (v0.2.1 against v0.3 on independently generated mutants). -| Item | v0.3 change | +| Item | v0.3.0 change | |---|---| -| V1 | T3 records and tests the GE target (asset-market) residual, both as reported by the solver and computed directly from the reported Jacobians. V1 assumes that T3 is solved on the asset-market target: its threshold (2e-12, on the residual divided by b) comes from the asset-market solve's own residual. A solve on the goods-market target, equivalent in exact arithmetic, leaves an asset-market residual far above it: up to 3.0e-6·b with proportional income, where F3 plays no role, and up to 2.4e-3·b with countercyclical income, where F3 adds an O(h) error. V1 therefore alarms on such a solve (control C03; `docs/MUTATION_v0_2.md`, section 8). | +| V1 | T3 records and tests the residual of the GE target that the provider reports in `ge_target` (`'asset_mkt'` or `'goods_mkt'`; if absent, `'asset_mkt'` is assumed and recorded as assumed), divided by b: as reported by the solver, and computed directly from the reported Jacobians and the rate path the check passed (asset market J^{A,Y} dY + J^{A,r} dr from `J_A`; goods market dY − J^{C,Y} dY − J^{C,r} dr from `J_C`). Thresholds: 2e-12 for the asset market, from the asset-market solve's own residual (unchanged); 9e-12 (proportional income) and 2e-11 (countercyclical income) for the goods market, from the reference provider solved on the goods market (v0.3.0). The other market's residual is recorded without a threshold. Scope: V1 applies to a T3 solve on one of these two markets; for any other reported target it is skipped as not applicable. Until v0.3.0, V1 assumed the asset-market target and alarmed on an equivalent goods-market solve (control C03): its asset-market residual is up to 3.0e-6·b with proportional income, where F3 plays no role, and up to 2.4e-3·b with countercyclical income, where F3 adds an O(h) error (`docs/MUTATION_v0_2.md`, section 8; `docs/CHECKS_v0_3_0_AMENDMENT.md`). | | V2 | Steady-state residuals computed in the checks from reported primitive quantities: government budget, goods and asset markets (fiscal HANK, TANK, Huggett), capital market, firm first-order conditions and goods market (Aiyagari), and the aggregate household budget in every model. | -| V3 | Income normalisation: Π row-stochastic, E[e] = 1 under the stationary distribution of the reported Π, aggregate income = Y (Y − Tax in the fiscal model), and Σ π e ζ = 0 for the countercyclical incidence. | -| V4 | Specification pins against the documented values in `hank_limits/spec.py` (not read from `models.py`): reported parameters, the Aiyagari Euler equation at the documented β and EIS, and the fiscal rule, government budget, real-rate rule and goods market along the T5 paths. | +| V3 | Income normalisation: Π row-stochastic, E[e] = 1 under the stationary distribution of the reported Π, and aggregate income Σ π y equal to the model's reference: Y (T1, T3); the type's income Y_H or Y_S, with the weighted sum λ Y_H + (1 − λ) Y_S = Y (T2); w L with the documented labour L = 1 (T4); Y − Tax (T5). Countercyclical incidence (T3): Σ π e ζ = 0. | +| V4 | Specification pins against the documented values in `hank_limits/spec.py` (not read from `models.py`): reported parameters, the Aiyagari Euler equation at the documented β and EIS, and the fiscal rule, government budget, real-rate rule and goods market along the T5 paths. v0.3.0: the solved exogenous paths are compared with the requested ones (`exog_G`, `exog_r`, `exog_rshock`), and the real-rate rule uses the requested rate shock. | | V5 | `test_rank_benchmark_is_ricardian` now holds only the closed-form RA assertion; the HA assertion is `test_ha_multiplier_exceeds_one`. | -| V6 | F3 pin (strict xfail, SSJ code only), in the same form as the F1 and F2 pins. | -| Providers | New **optional** fields `ss_detail`, `J_A`, `policy` and `irfs[...]['drshock']` (`hank_limits/interface.py`); checks whose fields are missing are skipped, with the reason recorded. No computation in `models.py` or `core.py` changed: the summaries of the existing checks are bit-identical to v0.2.1. | +| V6 | F3 pins (strict xfail, SSJ code only), in the same form as the F1 and F2 pins. v0.3.0: two tests, V6a (hetinputs differentiated one-sided) and V6b (hetoutputs one-sided even with `twosided=True`), so that an upstream fix of one part shows as XPASS of that test only. | +| Providers | New **optional** fields `ss_detail`, `J_A`, `J_C`, `ge_target`, `policy` and `irfs[...]` `dC`, `dB`, `drshock`; `hank_limits/interface.py` lists, per provider, every field the checks read and whether it is required or optional. Each V quantity is computed from the fields of its own equation; a missing field leaves that quantity missing, with the reason recorded. No computation in `models.py` or `core.py` changed; the Werning provider gained an optional argument `ge_target` whose default is the previous behaviour. In the baseline runs of the mutation reports (four in v0.2, two in the v0.3.0 re-run), the 276 summary numbers of the existing checks were exactly equal to those of v0.1 run B0. | +| Verdict | v0.3.0. A V test fails if any value is non-finite, negative or not below its threshold, whatever else is missing. Without a failure, it is skipped as **incomplete** (never passed) if expected values are missing, and skipped with the reason if the provider reports none of its quantities. The check declares the expected values per setting, income type and requested shock (`res['v0_3']` → `status`; `checks.v03_verdict`). | +| Review | Pre-release review of 2026-10-22 (no P0 or P1 findings): the verdict above (R1); one field convention in documentation and code, with fields per equation and T3 β read from `ss_detail` (R2); solved against requested exogenous paths (R3); V1 judged on the reported GE target (R4); V6 split. Regression tests of the checker with fake providers: `tests/test_v0_3_0_checker.py`. Design, predictions, thresholds and re-run: `docs/CHECKS_v0_3_0_AMENDMENT.md`. Pre-merge check of 2026-10-23: each check now keeps its own copy of what it requests and gives the provider another, so a provider that changes its arguments in place cannot change the comparison (amendment, section 11). | | T4, T6 | Two clarifications from mutation testing v0.1: T4's error-detection value lies in its diagnostics (sections 7 and 9); the T6 matrix identity is a linear-algebra check. | -Full pytest run with v0.3: **74 passed, 3 xfailed** (F1, F2, F3). +Full pytest run with v0.3.0: **114 passed, 4 xfailed** (F1, F2, V6a, V6b). The 114 passed are 77 tests of groups T1–T6, D and V and the 37 checker regression tests. Output: `out/pytest_output_v0_3_0.txt`. Mutation testing v0.2 (`docs/MUTATION_v0_2.md`): on 20 mutants generated by a separate agent without knowledge of the new checks, the v0.2.1 suite caught 14 and the v0.3 suite 19; neither suite alarmed on the 3 controls. Both missed N20, an error in a diagnostic that no test asserts tightly. On the 25 v0.1 mutants the v0.3 suite catches all 25, but those checks were designed after the v0.1 results, so that is not an independent result. +Re-run after the pre-release review (`docs/CHECKS_v0_3_0_AMENDMENT.md`, section 10): the suite as revised for v0.3.0 was run again on the same mutants, designs (ii) and (iii). In (ii) no result changed: 19 of 20 caught, N20 missed, no alarm on the controls. In (iii) the only change is control C03, which no longer alarms because V1 now judges the GE target that the provider reports. That holds by construction and is not independent evidence. The v0.2 results above remain the record for the checks as they were. + +Where to start reading the mutation tests: the reports `docs/MUTATION_v0_1.md`, `docs/MUTATION_v0_2.md` and `docs/CHECKS_v0_3_0_AMENDMENT.md`, and the CSV files with one row per design × mutant × test group (`out/mutation_v0_1.csv`, `out/mutation_v0_2.csv`, `out/mutation_v0_3_0_rerun.csv`). The JSON files `out/mutation_v0_*.json` keep every run's test outcomes and check summaries. + --- ## 1. Summary @@ -66,7 +70,7 @@ The error metric is the **relative max-entry error** `max|x − ref| / max|ref|` **Status of the tolerances.** Test tolerances are **regression-check thresholds for this calibration**. They are not a conformance specification requiring other implementations to show the same slopes or the same 1e-10 threshold. -Full pytest run: **41 passed, 2 xfailed, about 65–75 s** (section 11). Report script about 110 s, diagnostics script about 80 s. +Full pytest run of v0.2.1, for which this summary was written: **41 passed, 2 xfailed, about 65–75 s** (section 11). The T1–T6 results above are unchanged in v0.3.0, whose full run gives 114 passed, 4 xfailed, about 75 s (`out/pytest_output_v0_3_0.txt`). Report script about 110 s, diagnostics script about 80 s. ### Key findings @@ -85,7 +89,7 @@ Full pytest run: **41 passed, 2 xfailed, about 65–75 s** (section 11). Report ```bash pip install sequence-jacobian==1.0.0 pytest matplotlib # needs numpy, scipy, numba cd hank-limits -python3 -m pytest # about 74 s; summary output with python3 -m pytest -s +python3 -m pytest # about 75 s; summary output with python3 -m pytest -s python3 scripts/convergence_report.py # about 110 s: out/convergence_v0_2.json, 6 PNGs, out/tables_v0_2/*.csv python3 scripts/diagnostics_v0_2.py # about 80 s: out/diagnostics_v0_2.json (section 12) python3 scripts/aiyagari_table2_v0_2.py # about 20 s: out/aiyagari_table2_v0_2.json (section 7) @@ -93,6 +97,7 @@ python3 scripts/repro_F1_v0_2.py # SSJ code only: out/repro_F1_v0_2.js python3 scripts/repro_F2_v0_2.py # SSJ code only: out/repro_F2_v0_2.json, out/F2_HU_T300_v0_2.npz python3 scripts/repro_F3_v0_1.py # v0.3, SSJ code only: hetinput derivative (section 14) python3 scripts/repro_F3_hetblock_v0_1.py # v0.3, SSJ code only: HetBlock.jacobian, hetinput and hetoutput +python3 scripts/mutation_v0_3_0.py --v03-ref --design ii iii # about 18 min: mutation re-run (v0.3.0) ``` - Every entry point limits threads to one (`OMP_NUM_THREADS=1` etc.). @@ -112,9 +117,12 @@ hank_limits/ metrics.py error metrics, convergence orders, mixed absolute/relative tolerance suite.py standard settings (shared by tests and scripts) spec.py v0.3: documented specification values for the V checks -tests/ test_t1 ... test_t6, test_diagnostics_v0_2, test_v0_3_checks (v0.3) +tests/ test_t1 ... test_t6, test_diagnostics_v0_2, test_v0_3_checks (v0.3), + test_v0_3_0_checker (v0.3.0: the checker on fake providers) scripts/ convergence_report.py, diagnostics_v0_2.py, aiyagari_table2_v0_2.py, - repro_F1_v0_2.py, repro_F2_v0_2.py, a1_markov_checks_v0_2.py (for the design note, section 13) + repro_F1_v0_2.py, repro_F2_v0_2.py, repro_F3_*.py, a1_markov_checks_v0_2.py (for the design note, section 13), + mutation_v0_1.py, mutation_v0_2.py, mutation_v0_3_0.py (mutation runners), thresholds_v0_3_0.py, + rerun_v0_3_0_compare.py out/ JSON, PNG, tables_v0_2/*.csv, pytest output ``` @@ -361,7 +369,7 @@ The check functions (`hank_limits/checks.py`) do not depend on SSJ; they take pr | `check_aiyagari` | `f(sd, rho)` | `r, rho_disc`, optional `diag` (residuals) | | `check_ikc`, `check_differencing` | `f(T, shocks)` | `J`, `ss`, `irfs` | -v0.3: providers may also report the optional fields `ss_detail`, `J_A`, `policy` and `irfs[label]['drshock']` (`hank_limits/interface.py`). The V checks compute steady-state residuals, income normalisation and specification pins from them, against the values passed as `spec=` (the suite passes `hank_limits/spec.py`; pass your own calibration's values). If a field is missing, the checks that need it are skipped and the reason is recorded under `v0_3` → `skipped`. +v0.3.0: providers may also report the optional fields `ss_detail`, `J_A`, `J_C`, `ge_target`, `policy` and `irfs[label]` `dC`, `dB`, `drshock`. `hank_limits/interface.py` lists, per provider, every field the checks read and the V quantities each optional field feeds. The V checks compute steady-state residuals, income normalisation and specification pins from them, against the values passed as `spec=` (the suite passes `hank_limits/spec.py`; pass your own calibration's values), and compare the solved exogenous paths with those your code was asked to solve. Each V quantity is computed from the fields of its own equation; if a field is missing, that quantity is missing and the reason is recorded under `v0_3` → `skipped`. A V test fails on any non-finite, negative or too large value; it is skipped as incomplete if values are missing without a failure, and skipped with the reason if your provider reports none of its quantities (`checks.v03_verdict`). For T3, report in `ge_target` the market whose clearing your solve imposes (`'asset_mkt'` or `'goods_mkt'`). Each check passes your provider its own copy of the requested paths and experiments, and compares with a copy of its own. Recommendations: use T1 and T4 as single-type household-block unit tests, T2 in a form generalised to any number of types, and T5 and T6 as regression tests of your own GE solver. The numerical tolerances are values for this calibration, so reset them for your own calibration. Differences in timing convention or units usually show up at once in the eps = 0 exactness test (T1, at the 1e-9 level). @@ -369,7 +377,7 @@ Recommendations: use T1 and T4 as single-type household-block unit tests, T2 in ## 11. pytest output (actual) -The full output is in `out/pytest_output_v0_2_1.txt`. +The output below is that of v0.2.1 (41 passed, 2 xfailed), kept as recorded; its full output is in `out/pytest_output_v0_2_1.txt`. The T1–T6 and D tests and their results are unchanged since. The current output, v0.3.0 (114 passed, 4 xfailed: these tests, the V checks and the checker regression tests), is in `out/pytest_output_v0_3_0.txt`. ``` tests/test_t5_ikc.py::test_ikc_identity_ssj_solver_rule_long_horizon XFAIL diff --git a/README_ko.md b/README_ko.md index 8f82c29..f3c994e 100644 --- a/README_ko.md +++ b/README_ko.md @@ -1,10 +1,8 @@ -# HANK 해석적 극한·집계 항등식 검증 세트 v0.2.1 (analytic-limit and aggregate-identity test suite) - -**이 브랜치: v0.3 (unreleased)**, 릴리스 v0.2.1 위의 변경입니다. 아래 "v0.3 (unreleased)" 를 보십시오. +# HANK 해석적 극한·집계 항등식 검증 세트 v0.3.0 (analytic-limit and aggregate-identity test suite) [![DOI](https://zenodo.org/badge/1426447298.svg)](https://doi.org/10.5281/zenodo.23489176) -모든 판을 인용할 때는 concept DOI [10.5281/zenodo.23489176](https://doi.org/10.5281/zenodo.23489176), 이 판(v0.2.1)은 [10.5281/zenodo.23489177](https://doi.org/10.5281/zenodo.23489177) 입니다. GitHub 의 "Cite this repository" 버튼은 `CITATION.cff` 를 씁니다. +모든 판을 인용할 때는 concept DOI [10.5281/zenodo.23489176](https://doi.org/10.5281/zenodo.23489176) 를 씁니다. 이 릴리스(v0.3.0)의 DOI 는 Zenodo 보관 뒤 여기와 `CITATION.cff` 에 추가합니다. 이전 릴리스 v0.2.1 은 [10.5281/zenodo.23489177](https://doi.org/10.5281/zenodo.23489177) 입니다. GitHub 의 "Cite this repository" 버튼은 `CITATION.cff` 를 씁니다. 이 저장소는 이질적 경제주체 뉴케인지언 모형(heterogeneous-agent New Keynesian, HANK) 코드가 답이 알려진 극한(limit)과 집계 항등식(aggregate identity)에서 통과해야 하는 시험 모음입니다. 공개 패키지 `sequence-jacobian`(이하 SSJ) 1.0.0 위에서 구현했고, 각 시험은 한 지점의 통과/실패(pass/fail)만이 아니라 **극한 모수가 극한으로 갈 때의 오차와 관찰된 수렴 차수(observed order of convergence)** 를 함께 보고합니다. @@ -27,25 +25,31 @@ **v0.2 → v0.2.1 (R4 후속 검토 반영):** ① 구성상 항상 0 이던 진단 필드 `normalisation_err_last_sweep` 삭제, ② Aiyagari 둘째 셀을 "미재현·원인 미해결"로 고치고 원문 Table I 의 수준 CV·자기상관 대조와 격자 감사를 추가, ③ F2 의 실무 영향 서술을 이 예제로 한정, ④ T1 계산 시계 무관성을 고정 정상상태의 선형 가계 야코비안으로 한정, ⑤ SSJ 이슈 초안 문구 수정. 시험 결과는 같습니다. -### v0.3 (unreleased): 정상상태·소득 정규화·명세 검사 +### v0.2.1 → v0.3.0 변경: 정상상태·소득 정규화·명세 검사 -릴리스하지 않은 판입니다. `pyproject.toml` 의 버전, 태그, 인용 메타데이터는 v0.2.1 그대로입니다. 계획과 사전 등록은 `docs/CHECKS_PLAN_v0_3.md`, 오류 주입 시험(mutation testing)은 `docs/MUTATION_v0_1.md`(v0.2.1 묶음)와 `docs/MUTATION_v0_2.md`(독립 생성 변형으로 v0.2.1 과 v0.3 비교)에 있습니다. +계획과 사전 등록은 `docs/CHECKS_PLAN_v0_3.md`, 릴리스 전 검토 뒤의 수정과 그 재실행은 `docs/CHECKS_v0_3_0_AMENDMENT.md`, 오류 주입 시험(mutation testing)은 `docs/MUTATION_v0_1.md`(v0.2.1 묶음)와 `docs/MUTATION_v0_2.md`(독립 생성 변형으로 v0.2.1 과 v0.3 비교)에 있습니다. -| 항목 | v0.3 변경 | +| 항목 | v0.3.0 변경 | |---|---| -| V1 | T3 의 일반균형 목표(자산시장) 잔차를 기록하고 시험합니다. 풀이기가 보고한 값과, 보고된 야코비안으로 직접 계산한 값을 모두 봅니다. V1 은 T3 를 자산시장 목표로 푼다고 전제합니다. 임계값(잔차를 b 로 나눈 값에 대해 2e-12)은 자산시장 풀이 자신의 잔차에서 나왔습니다. 정확한 산술에서는 같은 해를 주는 재화시장 목표로 풀면, 자산시장 잔차가 이보다 훨씬 큽니다. 비례 소득에서는 F3 와 무관하게 최대 3.0e-6·b, 경기역행 소득에서는 F3 의 O(h) 오차가 더해져 최대 2.4e-3·b 입니다. 따라서 V1 은 그런 풀이에 경보를 냅니다(대조군 C03; `docs/MUTATION_v0_2.md` 8절). | +| V1 | 공급자가 `ge_target` 으로 보고한 T3 일반균형 목표(`'asset_mkt'` 또는 `'goods_mkt'`; 없으면 `'asset_mkt'` 로 보고 "assumed" 로 기록)의 잔차를 b 로 나눠 기록하고 시험합니다. 풀이기가 보고한 값과, 보고된 야코비안과 검사가 넘긴 금리 경로로 직접 계산한 값을 모두 봅니다(자산시장은 `J_A` 로 J^{A,Y} dY + J^{A,r} dr, 재화시장은 `J_C` 로 dY − J^{C,Y} dY − J^{C,r} dr). 임계값: 자산시장은 자산시장 풀이 자신의 잔차에서 나온 2e-12(그대로), 재화시장은 참조 공급자를 재화시장 목표로 푼 실행에서 나온 9e-12(비례 소득)와 2e-11(경기역행 소득)입니다(v0.3.0). 다른 시장의 잔차는 임계값 없이 기록만 합니다. 적용 범위: 두 시장 가운데 하나로 푼 T3 에만 적용하고, 다른 목표가 보고되면 적용 조건 미충족으로 skip 합니다. v0.3.0 전에는 V1 이 자산시장 목표를 전제했으므로, 정확한 산술에서는 같은 해를 주는 재화시장 풀이(대조군 C03)에 경보를 냈습니다. 그 풀이의 자산시장 잔차는 비례 소득에서 F3 와 무관하게 최대 3.0e-6·b, 경기역행 소득에서 F3 의 O(h) 오차가 더해져 최대 2.4e-3·b 입니다(`docs/MUTATION_v0_2.md` 8절, `docs/CHECKS_v0_3_0_AMENDMENT.md`). | | V2 | 공급자(provider)가 보고한 기본 수량으로 검사 쪽에서 직접 계산하는 정상상태 잔차: 정부 예산, 재화·자산시장(재정 HANK, TANK, Huggett), 자본시장·기업 1계 조건·재화시장(Aiyagari), 모든 모형의 집계 가계 예산. | -| V3 | 소득 정규화: Π 의 행 합이 1, 보고된 Π 의 정상분포에서 E[e] = 1, 총소득 = Y(재정 모형은 Y − Tax), 경기역행 귀착에서 Σ π e ζ = 0. | -| V4 | `hank_limits/spec.py` 의 문서화된 값으로 명세 고정(specification pins). `models.py` 에서 읽지 않습니다. 보고된 모수, 문서화된 β·EIS 에서의 Aiyagari 오일러 식, T5 경로에서의 재정 준칙·정부 예산·실질금리 준칙·재화시장을 확인합니다. | +| V3 | 소득 정규화: Π 의 행 합이 1, 보고된 Π 의 정상분포에서 E[e] = 1, 총소득 Σ π y 가 모형별 기준과 같음. 기준은 Y(T1, T3), 유형별 소득 Y_H·Y_S 와 그 가중 합 λ Y_H + (1 − λ) Y_S = Y(T2), 문서화된 노동 L = 1 에서의 w L(T4), Y − Tax(T5)입니다. 경기역행 귀착(T3)에서는 Σ π e ζ = 0. | +| V4 | `hank_limits/spec.py` 의 문서화된 값으로 명세 고정(specification pins). `models.py` 에서 읽지 않습니다. 보고된 모수, 문서화된 β·EIS 에서의 Aiyagari 오일러 식, T5 경로에서의 재정 준칙·정부 예산·실질금리 준칙·재화시장을 확인합니다. v0.3.0: 공급자가 실제로 푼 외생 경로를 요청한 경로와 대조하고(`exog_G`, `exog_r`, `exog_rshock`), 실질금리 준칙 잔차에는 요청한 금리 충격을 씁니다. | | V5 | `test_rank_benchmark_is_ricardian` 에는 RA 닫힌 해 assert 만 남기고, HA 조건은 `test_ha_multiplier_exceeds_one` 으로 나눴습니다. | -| V6 | F3 고정 시험(strict xfail, SSJ 코드만). F1·F2 고정과 같은 형식입니다. | -| 공급자 | **선택** 필드 `ss_detail`, `J_A`, `policy`, `irfs[...]['drshock']` 추가(`hank_limits/interface.py`). 필드가 없으면 해당 검사를 skip 하고 이유를 결과에 남깁니다. `models.py`·`core.py` 의 계산은 바꾸지 않았으므로 기존 검사의 요약 수치는 v0.2.1 과 비트 단위로 같습니다. | +| V6 | F3 고정 시험(strict xfail, SSJ 코드만). F1·F2 고정과 같은 형식입니다. v0.3.0: V6a(hetinput 이 항상 한쪽 차분)와 V6b(`twosided=True` 를 요청해도 hetoutput 이 한쪽 차분)로 나눠, 상류에서 한쪽만 고쳐져도 그 시험만 XPASS 로 알립니다. | +| 공급자 | **선택** 필드 `ss_detail`, `J_A`, `J_C`, `ge_target`, `policy`, `irfs[...]` 의 `dC`·`dB`·`drshock` 추가. `hank_limits/interface.py` 에 공급자별로 검사가 읽는 모든 필드와 필수·선택 구분을 적었습니다. V 수량은 각자 자기 식에 필요한 필드로만 계산하고, 필드가 없으면 그 수량만 빠진 것으로 두고 이유를 남깁니다. `models.py`·`core.py` 의 계산은 바꾸지 않았고, Werning 공급자에 기본값이 기존 동작과 같은 선택 인자 `ge_target` 만 더했습니다. 오류 주입 보고서의 기준 실행(v0.2 의 4회, v0.3.0 재실행의 2회)에서 기존 검사의 요약값 276개가 v0.1 실행 B0 과 정확히 같았습니다. | +| 판정 | v0.3.0. V 시험은 값 하나라도 유한하지 않거나 음수이거나 임계값 이상이면, 다른 값이 빠져 있어도 실패합니다. 실패가 없는데 기대한 값이 빠져 있으면 **incomplete** 로 skip 하고(통과로 보지 않음), 공급자가 그 시험의 수량을 하나도 보고하지 않으면 이유와 함께 skip 합니다. 기대하는 값은 검사가 설정·소득 유형·요청한 충격별로 미리 정해 둡니다(`res['v0_3']` → `status`, `checks.v03_verdict`). | +| 검토 | 2026-10-22 릴리스 전 검토(P0·P1 결함 없음)를 반영했습니다. 위의 판정(R1), 문서와 코드의 필드 규약 일치(식 단위 필드, T3 β 는 `ss_detail` 에서 읽음; R2), 실제로 푼 외생 경로와 요청 경로의 대조(R3), 보고된 일반균형 목표로 V1 판정(R4), V6 나누기. 가짜 공급자(fake provider)로 검사기 자체를 시험하는 회귀 시험은 `tests/test_v0_3_0_checker.py` 에 있습니다. 설계·예측·임계값·재실행은 `docs/CHECKS_v0_3_0_AMENDMENT.md` 에 있습니다. 2026-10-23 병합 전 확인 뒤에는, 검사가 요청한 객체의 사본을 따로 보존하고 공급자에게는 다른 사본을 넘기도록 고쳤습니다. 그래서 공급자가 받은 인수를 직접 바꿔도 비교 기준은 바뀌지 않습니다(같은 문서 11절). | | T4·T6 | 오류 주입 시험 v0.1 에서 나온 두 가지 설명: T4 의 오류 검출력은 진단에서 나오고(7·9절), T6 행렬 항등식은 선형대수 검사입니다. | -v0.3 의 pytest 전체: **74 passed, 3 xfailed** (F1, F2, F3). +v0.3.0 의 pytest 전체: **114 passed, 4 xfailed** (F1, F2, V6a, V6b). 통과한 114개는 T1–T6, D, V 묶음의 시험 77개와 검사기 회귀 시험 37개입니다. 출력은 `out/pytest_output_v0_3_0.txt` 에 있습니다. 오류 주입 시험 v0.2(`docs/MUTATION_v0_2.md`): 새 검사를 모르는 별도 에이전트가 만든 변형 20개 가운데 v0.2.1 묶음은 14개, v0.3 묶음은 19개를 잡았습니다. 대조군 3개에서는 두 묶음 모두 경보를 내지 않았습니다. 두 묶음 모두 놓친 N20 은 어떤 시험도 엄격히 확인하지 않는 진단 값의 오류입니다. v0.1 변형 25개는 v0.3 묶음이 모두 잡지만, 그 검사들은 v0.1 결과를 본 뒤 설계했으므로 독립 결과가 아닙니다. +릴리스 전 검토 뒤의 재실행(`docs/CHECKS_v0_3_0_AMENDMENT.md` 10절): v0.3.0 으로 수정한 묶음을 같은 변형으로 설계 (ii)·(iii)에서 다시 돌렸습니다. (ii)는 결과가 바뀌지 않았습니다(20개 가운데 19개를 잡고 N20 을 놓침, 대조군 경보 없음). (iii)에서는 대조군 C03 만 바뀌어 더는 경보를 내지 않습니다. V1 이 이제 공급자가 보고한 일반균형 목표로 판정하기 때문이며, 설계상 그렇게 되는 결과이므로 독립 증거가 아닙니다. 위의 v0.2 결과는 당시 검사에 대한 기록으로 그대로 둡니다. + +오류 주입 시험은 보고서(`docs/MUTATION_v0_1.md`, `docs/MUTATION_v0_2.md`, `docs/CHECKS_v0_3_0_AMENDMENT.md`)와, 설계 × 변형 × 시험 묶음마다 한 행인 CSV(`out/mutation_v0_1.csv`, `out/mutation_v0_2.csv`, `out/mutation_v0_3_0_rerun.csv`)부터 읽기를 권합니다. JSON 파일 `out/mutation_v0_*.json` 에는 모든 실행의 시험 결과와 검사 요약이 들어 있습니다. + --- ## 1. 결과 요약 (summary) @@ -65,7 +69,7 @@ v0.3 의 pytest 전체: **74 passed, 3 xfailed** (F1, F2, F3). **허용치의 지위.** 시험 허용치는 이 보정의 **회귀 검사(regression check) 기준**입니다. 다른 구현에 같은 수렴 기울기나 같은 1e-10 기준을 요구하는 규격(conformance specification)이 아닙니다. -pytest 전체: **41 passed, 2 xfailed, 약 65 ~ 75초** (11절). 보고서 스크립트 약 110초, 진단 스크립트 약 80초. +이 요약을 쓴 v0.2.1 의 pytest 전체: **41 passed, 2 xfailed, 약 65 ~ 75초** (11절). 위 T1–T6 결과는 v0.3.0 에서도 같고, v0.3.0 의 pytest 전체는 114 passed, 4 xfailed, 약 75초입니다(`out/pytest_output_v0_3_0.txt`). 보고서 스크립트 약 110초, 진단 스크립트 약 80초. ### 주요 발견 (key findings) @@ -83,8 +87,8 @@ pytest 전체: **41 passed, 2 xfailed, 약 65 ~ 75초** (11절). 보고서 스 ```bash pip install --break-system-packages sequence-jacobian==1.0.0 pytest matplotlib # numpy, scipy, numba 필요 -cd hank_tests -python3 -m pytest # 약 74초; 요약 출력은 python3 -m pytest -s +cd hank-limits +python3 -m pytest # 약 75초; 요약 출력은 python3 -m pytest -s python3 scripts/convergence_report.py # 약 110초: out/convergence_v0_2.json, PNG 6장, out/tables_v0_2/*.csv python3 scripts/diagnostics_v0_2.py # 약 80초: out/diagnostics_v0_2.json (12절) python3 scripts/aiyagari_table2_v0_2.py # 약 20초: out/aiyagari_table2_v0_2.json (7절) @@ -92,6 +96,7 @@ python3 scripts/repro_F1_v0_2.py # SSJ 코드만 사용: out/repro_F1_ python3 scripts/repro_F2_v0_2.py # SSJ 코드만 사용: out/repro_F2_v0_2.json, out/F2_HU_T300_v0_2.npz python3 scripts/repro_F3_v0_1.py # v0.3, SSJ 코드만 사용: hetinput 미분 (14절) python3 scripts/repro_F3_hetblock_v0_1.py # v0.3, SSJ 코드만 사용: HetBlock.jacobian 의 hetinput·hetoutput +python3 scripts/mutation_v0_3_0.py --v03-ref <커밋> --design ii iii # 약 18분: 오류 주입 재실행 (v0.3.0) ``` - 모든 진입점에서 스레드를 1개로 제한합니다(`OMP_NUM_THREADS=1` 등). @@ -111,9 +116,12 @@ hank_limits/ metrics.py 오차 척도, 수렴 차수, 절대·상대 혼합 허용치 suite.py 표준 설정 (tests 와 스크립트가 공유) spec.py v0.3: V 검사에 쓰는 문서화된 명세 값 -tests/ test_t1 ... test_t6, test_diagnostics_v0_2, test_v0_3_checks (v0.3) +tests/ test_t1 ... test_t6, test_diagnostics_v0_2, test_v0_3_checks (v0.3), + test_v0_3_0_checker (v0.3.0: 가짜 공급자로 검사기 시험) scripts/ convergence_report.py, diagnostics_v0_2.py, aiyagari_table2_v0_2.py, - repro_F1_v0_2.py, repro_F2_v0_2.py, a1_markov_checks_v0_2.py (설계 노트용, 13절) + repro_F1_v0_2.py, repro_F2_v0_2.py, repro_F3_*.py, a1_markov_checks_v0_2.py (설계 노트용, 13절), + mutation_v0_1.py, mutation_v0_2.py, mutation_v0_3_0.py (오류 주입 실행기), thresholds_v0_3_0.py, + rerun_v0_3_0_compare.py out/ JSON, PNG, tables_v0_2/*.csv, pytest 출력 ``` @@ -360,7 +368,7 @@ Euler 오차는 단위 없는(unit-free) c_impl/c − 1 이고, c(e', ·) 는 | `check_aiyagari` | `f(sd, rho)` | `r, rho_disc`, 선택 `diag` (잔차) | | `check_ikc`, `check_differencing` | `f(T, shocks)` | `J`, `ss`, `irfs` | -v0.3: 공급자는 선택 필드 `ss_detail`, `J_A`, `policy`, `irfs[label]['drshock']` 도 보고할 수 있습니다(`hank_limits/interface.py`). V 검사는 이 값들로 정상상태 잔차, 소득 정규화, 명세 고정을 계산하고 `spec=` 로 받은 값과 비교합니다(이 세트는 `hank_limits/spec.py` 를 넘깁니다. 다른 보정이면 그 보정의 값을 넘기십시오). 필드가 없으면 해당 검사를 skip 하고, 이유를 `v0_3` → `skipped` 에 남깁니다. +v0.3.0: 공급자는 선택 필드 `ss_detail`, `J_A`, `J_C`, `ge_target`, `policy`, `irfs[label]` 의 `dC`·`dB`·`drshock` 도 보고할 수 있습니다. `hank_limits/interface.py` 에 공급자별로 검사가 읽는 모든 필드와, 선택 필드마다 쓰이는 V 수량을 적었습니다. V 검사는 이 값들로 정상상태 잔차, 소득 정규화, 명세 고정을 계산해 `spec=` 로 받은 값과 비교하고(이 세트는 `hank_limits/spec.py` 를 넘깁니다. 다른 보정이면 그 보정의 값을 넘기십시오), 공급자가 실제로 푼 외생 경로를 요청한 경로와 대조합니다. V 수량은 자기 식에 필요한 필드로만 계산하므로, 필드가 없으면 그 수량만 빠지고 이유는 `v0_3` → `skipped` 에 남습니다. V 시험은 유한하지 않거나 음수이거나 임계값을 넘는 값이 하나라도 있으면 실패하고, 실패 없이 값이 빠져 있으면 incomplete 로 skip 하며, 공급자가 그 시험의 수량을 하나도 보고하지 않으면 이유와 함께 skip 합니다(`checks.v03_verdict`). T3 에서는 풀이가 청산을 부과한 시장을 `ge_target` 으로 보고하십시오(`'asset_mkt'` 또는 `'goods_mkt'`). 각 검사는 요청한 경로와 실험의 사본을 공급자에게 넘기고, 비교는 따로 보존한 자기 사본으로 합니다. 권장 사항: T1·T4 는 단일 유형 가계 블록 단위 시험으로, T2 는 유형 수를 일반화한 형태로, T5·T6 은 자신의 일반균형 풀이기의 회귀 시험으로 쓰십시오. 숫자 허용치는 이 보정의 값이므로 자신의 보정에 맞춰 다시 정하십시오. 시점 규약이나 단위가 다르면 대부분 eps = 0 정확도 시험(T1, 1e-9 수준)에서 바로 드러납니다. @@ -368,7 +376,7 @@ v0.3: 공급자는 선택 필드 `ss_detail`, `J_A`, `policy`, `irfs[label]['drs ## 11. pytest 출력 요약 (actual pytest output) -전체 출력은 `out/pytest_output_v0_2_1.txt` 에 있습니다. +아래는 기록한 그대로 둔 v0.2.1 의 출력(41 passed, 2 xfailed)이고, 전체 출력은 `out/pytest_output_v0_2_1.txt` 에 있습니다. T1–T6, D 시험과 그 결과는 그 뒤로 같습니다. 현재 판 v0.3.0 의 출력(114 passed, 4 xfailed: 이 시험들, V 검사, 검사기 회귀 시험)은 `out/pytest_output_v0_3_0.txt` 에 있습니다. ``` tests/test_t5_ikc.py::test_ikc_identity_ssj_solver_rule_long_horizon XFAIL diff --git a/docs/CHECKS_PLAN_v0_3.md b/docs/CHECKS_PLAN_v0_3.md index fb71138..27e5680 100644 --- a/docs/CHECKS_PLAN_v0_3.md +++ b/docs/CHECKS_PLAN_v0_3.md @@ -332,6 +332,8 @@ Summary: V is predicted to catch 18 of the 25 v0.1 mutants (M17 unsure), to miss None at the time of the pre-registration commit. None after it either: the mutants, patches, predictions, detection rule and runner were used as committed in P, and the thresholds as committed in T (the implementation notes in section 4 do not change the registered design). Results: `docs/MUTATION_v0_2.md`. +2026-10-22, after results: the review-driven changes for release v0.3.0 (R1–R4, V6 split) and their re-run are registered separately in `docs/CHECKS_v0_3_0_AMENDMENT.md`; nothing above is changed. + ## Appendix A. Mutant generation: prompt, inputs and complete output ### A.1 Inputs given to the agent diff --git a/docs/CHECKS_v0_3_0_AMENDMENT.md b/docs/CHECKS_v0_3_0_AMENDMENT.md new file mode 100644 index 0000000..d50dcfc --- /dev/null +++ b/docs/CHECKS_v0_3_0_AMENDMENT.md @@ -0,0 +1,527 @@ +# v0.3.0 release candidate: review-driven changes to the v0.3 checks, and their re-run + +Status: **design and predictions** committed as A (`471fc47`) on branch `v0_3_0-rc`, before any code of this amendment and before any re-run (sections 1–9 as committed then). The thresholds of the new quantities (section 5) were filled in by commit B (`a290c75`, code, tests and thresholds), before any mutant was run. The re-run outputs are commit C (`ad1857d`), the results (section 10) commit D. Release metadata (version 0.3.0) is commit E (`ee16305`). Section 11 records the changes after the pre-merge check of 2026-10-23, made after these results were seen. + +Starting point: `main` at `281de19` (v0.3, unreleased; the last release is v0.2.1, concept DOI 10.5281/zenodo.23489176). Pre-registration of v0.3: `docs/CHECKS_PLAN_v0_3.md` ("the plan"); its results: `docs/MUTATION_v0_2.md`. + +## 1. Why + +A pre-release review of v0.3 (GPT, 2026-10-22) found no P0 or P1 defect. It reproduced **74 passed, 3 xfailed** in a separate Windows environment, confirmed that the 88 thresholds follow the rule of the plan (section 4), and that the pre-registration order and the reported numbers (14/20, 19/20, 25/25) agree with the record. It raised four P2 items, fixed here before the release, and P3 documentation items (section 8): + +- **R1. Missing, non-finite and skipped values can hide a verdict** (`tests/test_v0_3_checks.py`). + - `_assert_below({'hh_budget': [0.0, NaN]}, ...)` passes: `max` keeps the leading 0.0. With the order reversed it fails. + - `[0.0, None]` passes: None is dropped. + - If one quantity of a test has no value, the whole test is skipped, even when another quantity of the same test is above its threshold. Example: V1 direct with the proportional-income value absent and 10.0 for the countercyclical one gives a skip. + - `_assert_paths` uses the same `max`, and `_paths` collects only the paths the provider returned, so a missing part of a path set is not visible. +- **R2. The optional-field convention of `hank_limits/interface.py` and the code disagree.** + - The T5 path checks read `dB` and `dC` without checking that they exist (`checks.py`, lines 252 and 257). A provider without them gets a `KeyError` under `v0_3` → `errors`, which fails every V test on T5. + - T3: `interface.py` puts `beta` in `ss_detail`; the code reads `out['beta']`. +- **R3. The checks do not compare the shock the provider solved with the shock the caller requested.** A linear provider that applies twice the requested `G`, `r` and `rshock`, and returns paths consistent with that, passes the IKC test and every path check (largest residual 6.07e-16). +- **R4. V1 assumes that T3 is solved on the asset-market target.** An external code solved on the goods-market target, equivalent in exact arithmetic, alarms (C03). + +The V6 pin of F3 is also split in two (section 3.5). + +## 2. Rules + +1. **Scope.** Branch `v0_3_0-rc` from `main` `281de19`. A pull request to `main` is opened and not merged here. No tag and no GitHub Release: the user creates them, and Zenodo then mints the version DOI. +2. **Historical material is not changed:** `docs/CHECKS_PLAN_v0_3.md`, `docs/MUTATION_PLAN_v0_1.md`, `docs/MUTATION_v0_1.md`, `scripts/mutation_v0_1.py`, `scripts/mutation_v0_2.py`, `out/mutation_v0_1.*`, `out/mutation_v0_2.*`. Exceptions: two dated corrections in `docs/MUTATION_v0_2.md` in the form of its existing "Correction, 2026-10-22" paragraph (section 8), and one line in section 10 (Amendments) of the plan that points to this file. +3. **Model side** (`models.py`, `core.py`). No computation is changed. Allowed: new fields in the dicts the providers return, optional arguments whose default is the current behaviour, docstrings. The 276 numbers of the v0.1 check summaries must equal run B0 of `out/mutation_v0_1.json` bit for bit in the re-run baselines. +4. **Thresholds.** The 88 existing thresholds are not changed. The new quantities get thresholds by the rule of the plan, section 4, `roundup_1sig(max(100 × b_max, 10 × τ))`, with b_max from two unmodified runs of the code of commit B. They are committed in B, before any mutant is run, in a table of the plan's form (section 5). +5. **Checker principles, as in v0.3.** `checks.py` does not depend on SSJ. A new check computes its quantity directly from reported primitive quantities and from **the inputs the caller passed**. Documented values are read from `spec.py`. +6. **Order.** A (this file) → B (code, tests, thresholds) → C (re-run outputs) → D (results) → E (release metadata). Each commit is pushed on its own. + +## 3. Design + +### 3.1 R1: a verdict that missing or non-finite values cannot hide + +**Coverage is declared by the check, not inferred from what the provider returned.** In each check function, at each setting, the quantities that are expected there are declared first, with a placeholder `None` that is replaced when the quantity is computed. + +| Model | Settings | Quantities expected at each setting | +|---|---|---| +| T1 | each eps | V2, V3, V4(a) of T1 | +| T2 | each eps | per income type H and S, and the aggregates | +| T3 | each b | per incidence (acyclical, countercyclical); V1 by the reported GE target (section 3.4) | +| T4 | each eps | V2, V3, V4(a), V4(b) Euler | +| T5 | each T | steady-state quantities; path quantities **for every shock label the caller passed** (rate rule only in rule-based experiments, `exog_r` only in fixed-rate experiments) | + +Records in `res['v0_3']` (new keys; the value lists keep their v0.3 form, one entry per setting): + +- `settings`: the setting labels in order (e.g. `eps=0.2`, `b=0.001`, `T=200`); +- `at[q]`: the setting of each value in `res['v0_3'][q]` (paths: `paths[label]['at'][q]`); +- `status[q]`: coverage per quantity: number expected, number reported, the settings with a missing value, those with a non-finite value, and a state `complete`, `incomplete`, `not_reported` or `nonfinite`. Thresholds are applied by the tests, not here. + +**Verdict of one V test** (`checks.v03_verdict(v, quantities, thresholds)`, numpy only; every V test uses it through `_assert_below` and `_assert_paths`): + +1. **failed** if a v0.3 computation raised an exception (as in v0.3), or if any recorded value of any of the test's quantities is non-finite (NaN, ±inf), negative, or not below its threshold. This holds whatever else is missing. Every V quantity is an absolute value or a maximum of absolute values, so a negative number can only be a malformed report (V1(a) is a value the provider reports); +2. otherwise **skipped** ("not reported", with the reasons recorded under `skipped`) if none of the test's quantities has a value at any setting: the provider does not support the check, as in v0.3; +3. otherwise **incomplete** if any expected value is missing: pytest skip with a message that starts with "incomplete" and lists the missing settings. It is never a pass; +4. otherwise **passed**. + +A quantity that the check declared at no setting does not apply and is ignored, e.g. the goods-market V1 quantities when every T3 solve is on the asset market. For a hand-made `v0_3` dict without coverage records (as in the regression tests), every listed quantity is expected and each list entry is one setting. + +**Regression tests** use the real helpers `_assert_below` and `_assert_paths` of `tests/test_v0_3_checks.py` and `checks.v03_verdict`: + +- `{'hh_budget': [0.0, NaN]}` → failed (also with the order reversed); `[0.0, inf]` → failed; +- `{'hh_budget': [0.0, None]}` → incomplete; +- V1 direct with the proportional-income quantity absent and `[10.0]` for the countercyclical one → failed; +- T5 paths: `[0.0, NaN]` → failed; a declared path value that is missing, and a shock label the provider did not return (through `check_ikc` and a fake provider) → incomplete. + +They are in a new file `tests/test_v0_3_0_checker.py`. It uses no model code, so no mutant can change it; the mutation runner maps it to no group. + +### 3.2 R2: one field convention, in the documentation and in the code + +- **T5 paths: fields per equation.** Fiscal rule (dB, dTax); government budget (dB, dTax, dr, dG); goods market (dY, dC, dG); rate rule (dr, dY, and the caller's rshock, section 3.3). A missing field skips only that equation, recorded under `skipped` with the path label and the missing field. It is no longer an error that fails every V test. +- **Steady-state quantities: fields per equation as well.** A missing income vector y no longer skips the market-clearing residuals that do not use it, and so on. +- **T3 `beta`** is read from `ss_detail['beta']`, as documented. The SSJ provider already reports it there; the top-level `beta` it also returns stays, so existing callers do not break. +- **`interface.py` lists every field that the checks read**, v0.1 part and V part, as required or optional, per provider, with the V quantities each optional field feeds. The code reads no other field (enforced by the fake providers below). +- **Two fake providers per check** in the regression tests: + - one that returns exactly the documented required and optional fields: every V test reaches a verdict (passed or failed) and no error is recorded; + - one that returns only the required fields: no error is recorded. Every V test that needs an optional field is skipped or incomplete, and `skipped` lists the reasons. The checks that need only required fields and the caller's inputs (the T5 rate rule, `exog_G`, `exog_r`; section 3.3) reach a verdict. + +### 3.3 R3: the solved shock against the requested shock + +- **New path quantities** in `_v03_fiscal`, normalised by s (the largest absolute requested input) like the other path checks: + - `exog_G` = max_t |dG_t − G_t| / s, with G the path the caller requested, or zero when the experiment has no G shock; + - `exog_r` = max_t |dr_t − r_t| / s in the fixed-rate experiments (requested r, or zero). In rule-based experiments dr is endogenous and the rate rule checks it; + - `exog_rshock` = max_t |drshock_t − rshock_t| / s (requested rshock, or zero; `drshock` stays an optional field). +- **The rate-rule residual uses the requested rshock**, not the reported drshock: max_t |dr_t − φ_y dY_t − rshock_t| / s. +- **The fiscal rule, the government budget and the goods market keep using the reported dG and dr.** The exog quantities compare those with the request. So a wrong exogenous path is attributed to `exog_*`, and a violated equation to that equation; together they are equivalent to evaluating the equations at the requested paths. +- **Tests** (group V): `test_v4_exogenous_G_as_requested`, `test_v4_exogenous_r_as_requested`, `test_v4_exogenous_rshock_as_requested`. +- **Regression test:** a small linear fake fiscal provider that applies twice the requested G, r and rshock, and returns paths consistent with that. It passes the IKC check (v0.1 part) and the fiscal-rule, budget and goods-market path checks, and fails the three exog tests and the rate rule. +- **Threshold** by the rule of section 2. The SSJ provider takes the exogenous paths from the inputs (`get` in `ssj_fiscal_provider`), so b_max is expected to be exactly 0, and τ = 1e-14 ("exact up to rounding", plan section 4) gives 1e-13. + +### 3.4 R4: the GE target of T3 in the provider convention + +**Provider.** + +- `WerningProvider` reports `ge_target` ∈ {`'asset_mkt'`, `'goods_mkt'`}: the market whose clearing the solve imposed. + - Absent: `'asset_mkt'` is assumed and recorded as assumed (backward compatible). + - Any other value: V1 is skipped at that setting as "applicability condition not met". The placeholder stays missing, so a mix with settings whose target is known is incomplete, not passed. +- New optional field `J_C` = {'Y': J^{C,Y}, 'r': J^{C,r}} (T × T) for the goods-market residual. `J_A` stays as it is. +- SSJ reference provider: optional argument `ge_target='asset_mkt'` (the default is the current behaviour). `targets = [ge_target]` is passed to the solve, and **the same variable** gives the reported `ge_target` and `diag['ge_target_resid']`, the residual of the solved target. A change of the solve's target, like C03, therefore shows in what is reported. + +**Checker.** V1 computes the residual of the reported target directly and divides it by b. dr is the rate path the check passed, as before. + +| Quantity | Target | Definition | Threshold | +|---|---|---|---| +| `ge_target_resid_direct_{acyc,cyc}` | asset market | max \|J_A['Y'] dY + J_A['r'] dr\| / b | 2e-12 (unchanged) | +| `ge_target_resid_direct_goods_{acyc,cyc}` | goods market | max \|dY − J_C['Y'] dY − J_C['r'] dr\| / b | new (section 5) | +| `ge_target_resid_reported_{acyc,cyc}` | asset market | V1(a): `diag['ge_target_resid']` / b, must be finite and non-negative | 2e-12 (unchanged) | +| `ge_target_resid_reported_goods_{acyc,cyc}` | goods market | V1(a) as above | new (section 5) | + +- **The other market's residual** is recorded without a threshold, where its Jacobians are reported: `v0_3['diagnostics']`, `goods_mkt_resid_direct_*` for an asset-market solve, `asset_mkt_resid_direct_*` for a goods-market solve. The target of each setting is recorded in `v0_3['ge_target']`. +- **Thresholds of the goods-market quantities:** two unmodified runs of the reference provider with `ge_target='goods_mkt'`, both incidences and all seven b, by the rule of section 2, τ = 1e-14 (linear solve). +- **Documentation:** `interface.py` and the V1 rows of both READMEs: the target convention, and that V1 applies to a T3 solve on one of the two markets. + +### 3.5 V6 split + +`test_v6_f3_hetinput_hetoutput_two_sided` becomes two strict xfails, each with SSJ code only: + +- `test_v6a_f3_hetinput_two_sided`: the hetinput derivative that `HetBlock` uses equals the central difference (fails: always one-sided); +- `test_v6b_f3_hetoutput_two_sided`: the hetoutput Jacobian with `twosided=True` equals the one obtained when the stored default is honoured (fails: one-sided even when two-sided differences are requested). + +If only one part is fixed upstream, only that test turns XPASS. + +### 3.6 Model side, in full, and patch anchors + +Only `ssj_werning_provider` changes: + +- signature (`ge_target='asset_mkt'`); +- a new line `targets = [ge_target]`, and the solve line passes `targets`; +- new return fields `ge_target` and `J_C`; +- `diag['ge_target_resid']` reads `irf[targets[0]]`; +- the docstring: it said "(goods market)" while the target is the asset market (P3). + +No other line of `models.py` or `core.py` changes. + +Patch anchors (checked against the plan's patch lists): + +- **M04 and C03** (v0.1) anchor on the T3 solve line, which now passes `targets`. They are re-anchored, the same change at the new location: + - M04: the same one-period shift of the rate path, on the new solve line; + - C03: `targets = [ge_target]` → `targets = ['goods_mkt']`. The target the solve imposes changes, as in the original patch; by design (R4) the reported target follows it. +- **M12** anchors on the `options=` line, which does not change. +- **No v0.2 patch** anchors on a changed line. + +`scripts/mutation_v0_2.py` has an empty `REANCHOR` and is not changed (rule 2). The re-run therefore uses a copy, `scripts/mutation_v0_3_0.py`, with only these changes: the two `REANCHOR` entries, its own module name as the pytest plugin and in the environment record, the default output path, and the docstring. + +## 4. New quantities and tests + +| Test (group V) | Quantity | Model | Fields used | +|---|---|---|---| +| `test_v1_werning_ge_target_resid_reported` | `ge_target_resid_reported_goods_{acyc,cyc}` (new), besides the asset-market ones | T3 | `ge_target`, `diag['ge_target_resid']` | +| `test_v1_werning_ge_target_resid_direct` | `ge_target_resid_direct_goods_{acyc,cyc}` (new), besides the asset-market ones | T3 | `ge_target`, dY, *`J_C`* (new, optional); dr from the caller | +| `test_v4_exogenous_G_as_requested` | `exog_G` | T5 paths | irfs dG; G from the caller | +| `test_v4_exogenous_r_as_requested` | `exog_r` (fixed-rate experiments) | T5 paths | irfs dr; r from the caller | +| `test_v4_exogenous_rshock_as_requested` | `exog_rshock` | T5 paths | irfs drshock; rshock from the caller | +| `test_v6a_f3_hetinput_two_sided` | as V6 (i) | – | SSJ only | +| `test_v6b_f3_hetoutput_two_sided` | as V6 (ii) | – | SSJ only | + +- **Changed meaning:** `rate_rule` uses the requested rshock (section 3.3). +- **Diagnostics without threshold:** `goods_mkt_resid_direct_*`, `asset_mkt_resid_direct_*` (section 3.4). +- **Group V** after B has 37 tests: 33, minus the V6 test, plus V6a, V6b and the three exog tests. Every other test name is unchanged. +- **The checker regression tests** are in `tests/test_v0_3_0_checker.py`, outside group V. + +## 5. Thresholds of the new quantities + +Rule and τ classes: plan, section 4. The table is filled in by commit B from two unmodified runs of the B candidate: the full suite for the T5 quantities, and `suite.run_t3(ge_target='goods_mkt')` for the goods-market quantities. + +**Filled in by commit B.** b_max from two runs of `scripts/thresholds_v0_3_0.py` on the B candidate (2026-10-22, 14:46 and 14:47 UTC). The candidate is a local commit, `e9fd7e1`, with the same `hank_limits/`, `tests/` and `pytest.ini` trees as B; B adds this table and the two run files `out/thresholds_v0_3_0_run{1,2}.json`. The script calls the check functions exactly as the pytest fixtures do. Environment as in v0.2: Python 3.13.16, sequence-jacobian 1.0.0, numpy 2.5.3 (scipy-openblas 0.3.34), scipy 1.18.1, numba 0.68.0. The two runs gave identical numbers. Path quantities are the largest over the four shocks and three horizons; T3 quantities the largest over the seven b. + +| Model | Quantity | b_max (run 1, run 2) | τ (source) | Threshold | +|---|---|---|---|---| +| T3, goods-market target | `ge_target_resid_reported_goods_acyc` | 8.67e-14, 8.67e-14 | 1e-14 (exact up to rounding (linear solve)) | 9e-12 | +| T3, goods-market target | `ge_target_resid_reported_goods_cyc` | 1.39e-13, 1.39e-13 | 1e-14 (exact up to rounding (linear solve)) | 2e-11 | +| T3, goods-market target | `ge_target_resid_direct_goods_acyc` | 8.75e-14, 8.75e-14 | 1e-14 (exact up to rounding (linear solve)) | 9e-12 | +| T3, goods-market target | `ge_target_resid_direct_goods_cyc` | 1.27e-13, 1.27e-13 | 1e-14 (exact up to rounding (linear solve)) | 2e-11 | +| T5 | `exog_G` (path, max over labels) | 0, 0 | 1e-14 (exact up to rounding) | 1e-13 | +| T5 | `exog_r` (path, fixed-rate labels) | 0, 0 | 1e-14 (exact up to rounding) | 1e-13 | +| T5 | `exog_rshock` (path, max over labels) | 0, 0 | 1e-14 (exact up to rounding) | 1e-13 | + +**Notes on the table** + +- **The goods-market quantities are about ten times the asset-market ones** (b_max 1.1e-14 to 1.5e-14 there). Both are rounding-level residuals of a linear solve. Both are largest at b = 1e-4, where the division by b is largest. Before the division, the goods-market residual is about 1e-17 and the asset-market one about 1e-18. +- **Residuals of the other market,** recorded without threshold. Divided by b and maximised over the seven b: + - the asset-market solve of the reference provider leaves a goods-market residual of 1.36e-7 (proportional income) and 2.52e-6 (countercyclical income); + - the goods-market solve leaves an asset-market residual of 2.96e-6 and 2.44e-3. These equal, bit for bit, the V1 values with which C03 alarmed in v0.2. +- **The 88 existing quantities** have, in both runs, the b_max of the plan's table to three significant digits; the T5 path `goods_market` has b_max 3.115563e-13 (3.12e-13, as in the plan). Their thresholds are unchanged. (Corrected 2026-10-23, section 11: this said "3.11e-13 here". That value, 3.113829e-13, is the same path quantity, `G_debt_r_rule` at T = 300, in an earlier trial run of the script that was not kept, not the maximum of the two runs in the table. It is the run-to-run rounding variation described below.) + +**Observations at B, before any mutant was run** + +- **Full pytest on the candidate:** 107 passed, 4 xfailed. That is 77 tests in the suite's groups and the 30 checker tests of `tests/test_v0_3_0_checker.py`; the xfails are F1, F2, V6a and V6b. +- **The 276 v0.1 numbers.** Two baseline runs of the re-run runner (`scripts/mutation_v0_3_0.py --baseline-only v0.3`; output not kept) gave, in both runs, all 276 v0.1 summary numbers equal to v0.1 run B0. Against v0.1 run B1 only the known two-valued number differs. Test outcomes were identical. +- **Rounding-level differences between B0 and B1.** The two baselines differed in five T5 goods-market path residuals (dY − dC − dG; values between 1e-15 and 4e-6): + - one is in the refined setting that the V tests use: `G_debt_r_rule` at T = 300, 3.11556e-13 in one run and 3.11383e-13 in the other, against a threshold of 4e-11; + - the other four are in the two settings that no V test uses; two of them are the quantities that the plan (section 4) already saw vary between runs. + - The refined-setting quantity took the value 3.11556e-13 (the v0.2 value) in the two threshold runs and in a pytest run in the repository, and 3.11383e-13 in a trial run of the threshold script that was not kept. (Corrected 2026-10-23, section 11: this said that the threshold runs gave 3.11383e-13.) This is the run-to-run rounding variation of dC that the plan describes. No number of the v0.1 summaries and no test outcome is affected. +- **Effect on the predictions.** Prediction P1 ("B0 and B1 identical in every summarised number") and prediction P4 ("equal to the v0.2 value", where the refined setting is not exempted) are therefore expected to fail at rounding level for these quantities. The predictions stay as registered, and the outcome is reported in section 10. + +## 6. Re-run design + +- **Suite.** The v0.3.0 candidate is the tree of commit B (`hank_limits/`, `tests/`, `pytest.ini`, extracted with `git archive` as before). +- **Designs.** + - (ii) the 20 v0.2 mutants and 3 controls × the candidate (23 runs); + - (iii) the 28 v0.1 mutants and controls × the candidate (28 runs); + - two unmutated baselines (B0, B1): 53 runs in all. + - Design (i), the v0.2.1 suite, does not change and is not re-run; comparisons with it use its v0.2 results. +- **Runner.** `python3 scripts/mutation_v0_3_0.py --v03-ref --design ii iii --out out/mutation_v0_3_0_rerun` (the copy of section 3.6). Detection rule, time limits, parallelism (4 runs, one BLAS thread each) and summaries are those of v0.2. The patches are those of the plan and of v0.1, re-anchored only as in section 3.6, and recorded in the output. +- **Outputs.** `out/mutation_v0_3_0_rerun.{json,csv}`. +- **Comparison with v0.2,** per run and group: verdicts, the tests that changed outcome, and the values of the v0.3 quantities. +- **The original results stay as the record of the checks as they were** (19/20, 25/25, the C03 alarm). This is a re-run of the suite as revised after review. + +## 7. Predictions + +**Basis.** The code changes above. For R1, a scan of `out/mutation_v0_2.json` made while writing this section: in the 53 runs of the v0.3 suite (both baselines, designs (ii) and (iii)), no v0.3 quantity is None, NaN or ±inf, no v0.3 computation recorded an error or a skip reason, and no V test was skipped. The one fixture error is t3 under N19 (root bracket, ValueError). For R3: the SSJ provider returns the requested exogenous paths because it takes them from the inputs, and no v0.1 or v0.2 patch touches `ssj_fiscal_provider` or the inputs. For the same reason the reported `drshock` equals the requested rshock in every run. + +**P1. Baselines.** +- All tests pass except four strict xfails (F1, F2, V6a, V6b). +- B0 and B1 are identical in every outcome and every summarised number. +- All 276 numbers of the v0.1 summaries equal v0.1 run B0. Against v0.1 run B1 only the known two-valued number differs (plan, section 8). + +**P2. Groups T1–T6 and D.** In all 51 runs, the same verdict and the same changed tests as in the v0.2 runs. + +**P3. Existing V tests.** Every test of v0.2's group V except the V6 test has the same outcome as in v0.2, in every run, **except C03** (P6). + +**P4. Values.** Every v0.3 quantity that exists in the v0.2 data equals its v0.2 value in the same run, except: +- C03's V1 quantities, now goods-market ones; +- possibly rounding-level differences in the two T5 settings that no V test uses (as seen between threshold runs in the plan, section 4). + +**P5. New tests.** +- `exog_G`, `exog_r` and `exog_rshock` are exactly 0 in every run, and the three exog tests pass in every run: they catch nothing. +- V6a and V6b xfail in every run. + +**P6. C03** (GE target goods market). +- The provider reports `goods_mkt`, and V1 is judged on the goods-market residual. Its values equal those of the goods-market threshold runs, so V1 passes, and C03 no longer alarms. +- **This is not independent evidence.** Its thresholds come from unmodified runs with the same setting as C03. +- The asset-market residual is now a diagnostic without threshold, and equals the values that alarmed in v0.2. Divided by b, the maximum over the seven b is 2.96e-6 with proportional income and 2.44e-3 with countercyclical income. + +**P7. Suite level.** +- (ii): 19 of 20 mutants caught, N20 missed, no alarm on K01–K03. +- (iii): 25 of 25 caught, no alarm on C01–C03. +- Against the original pre-registered predictions: (ii) unchanged (167 of 168 firm cells held). (iii): the C03/V cell now differs from the pre-registered "catch (false alarm)", by design of R4. + +**P8. Checker self-tests** (`tests/test_v0_3_0_checker.py`) pass in every run. + +**Cells expected to differ from v0.2** (cells as in `docs/MUTATION_v0_2.md`, sections 3 and 9): + +| Design | ID | Group | v0.2 | Predicted in the re-run | Why | +|---|---|---|---|---|---| +| (iii) | C03 | V | **2/33** (alarm: V1 reported and direct) | · (no alarm) | R4: judged on the reported goods-market target, with thresholds from the same setting | +| (ii), (iii) | every run | V | n/33 | the same n, out of 37 | V6 split, three exog tests; none expected to change outcome | + +No other cell is expected to change. R1 to R3 change how missing, non-finite and wrongly sized exogenous values are judged. No run of the v0.2 data produced such values, so their evidence is the regression tests with fake providers (sections 3.1–3.3), not this re-run. + +## 8. Documentation (P3) + +| Item | Where | Commit | +|---|---|---| +| `docs/MUTATION_v0_2.md` line 17: "Every V catch … factor of 1e4 or more" is wrong. N18's largest margin is about 7,577 (asset market) and 9,742 (goods market). By failing test, N12's TANK goods-market test is about 526. Recompute from the data, separating the largest margin per mutant from the smallest margin per failing test. Dated correction; no effect on 19/20 | `docs/MUTATION_v0_2.md` | D | +| Same file, line 242: "any goods-market solve" → what was observed with this reference provider, calibration and solver setting. Dated correction | `docs/MUTATION_v0_2.md` | D | +| `models.py` (~line 310): the `ssj_werning_provider` docstring says "(goods market)"; the target is `asset_mkt` | `models.py` | B | +| V1 rows: target convention and scope (R4) | both READMEs | B | +| V3 rows: aggregate income = Y, with the reference per model: T2 income per type and the weighted sum, T4 w L, T5 Y − Tax | both READMEs | E | +| "bit-identical": limited to "in the report's baseline runs, the 276 existing summary numbers were exactly equal" | both READMEs | E | +| "41 passed, 2 xfailed" (README.md ~line 69, README_ko.md ~line 68) and section 11: marked as the v0.2.1 result, with a link to the current result | both READMEs | E | + +## 9. What can and cannot be claimed + +- The re-run shows whether the revision changed detection on the same two samples (20 + 3 v0.2 runs, 28 v0.1 runs). It is not new independent evidence beyond v0.2. +- If C03 no longer alarms, that holds by construction (section 3.4); it shows only that the target convention works as built. +- R1–R3 address failure modes (missing, non-finite and wrongly sized exogenous values) that neither the reference provider nor the mutants produced. Their evidence is the regression tests with fake providers. +- The thresholds of the new quantities are regression thresholds for this calibration, like the others. + +## 10. Results (commit D) + +Data: `out/mutation_v0_3_0_rerun.json` (every run's outcomes and check summaries) and `out/mutation_v0_3_0_rerun.csv` (one row per design × mutant × group). Comparison with v0.2: `python3 scripts/rerun_v0_3_0_compare.py --json out/rerun_v0_3_0_compare.json`. + +**These are results of a re-run of the suite as revised after the review.** The v0.2 results in `docs/MUTATION_v0_2.md` (19 of 20, 25 of 25, the C03 alarm) remain the record for the checks as they were then. + +### 10.1 Execution record (2026-10-22, UTC) + +| Step | Commit | Time | Content | +|---|---|---|---| +| Design and predictions A | `471fc47` | 14:28:46 | this file, sections 1–9; one line in the plan, section 10 | +| Threshold runs | (candidate `e9fd7e1`) | 14:46, 14:47 | `scripts/thresholds_v0_3_0.py` twice; one baseline-only run of the runner (section 5) | +| Code, tests, thresholds B | `a290c75` | 14:51:57 | R1–R4, V6 split, thresholds, runner copy | +| Re-run | – | 14:52:08 start, 1071 s | 53 runs, 4 in parallel, 68–152 s each | +| Outputs C | `ad1857d` | 15:10:12 | `out/mutation_v0_3_0_rerun.{json,csv}` | +| Results D | this commit | | this section; corrections in `docs/MUTATION_v0_2.md` | + +- The runner record shows HEAD `a290c75` with a clean worktree, and `runner_committed = true` (the copy committed in B). +- The environment is that of v0.2 (section 5). +- Re-anchored patches, as registered in section 3.6: M04 and C03, recorded under `reanchored` in the JSON. No other patch changed. Before B, the unmodified v0.2 runner failed on exactly these two patches, and on no other (`--check`). +- No mutant was run before B was pushed. + +### 10.2 Baselines + +- Both baselines: 107 passed, 4 xfailed (F1, F2, V6a, V6b). +- B0 and B1 are identical in every outcome and every summarised number; the runner reports `deterministic = true`. +- **All 276 numbers of the v0.1 summaries equal v0.1 run B0 bit for bit, in both baselines.** Against v0.1 run B1 only the known two-valued number differs (`t5.ssj_inconsistent_options.walras_max.rshock_r_rule`, relative 1.4e-11). + +### 10.3 Changes against v0.2 + +Cells as in `docs/MUTATION_v0_2.md`, sections 3 and 9: per group, whether the mutant was caught and which tests changed outcome. + +| Design | Runs | Cells that differ from v0.2 (detection or the set of changed tests) | +|---|---|---| +| (ii) | 23 | **none**. Every mutant and control has the same verdict in every group, and the same changed tests, as in v0.2. | +| (iii) | 28 | **one**: C03, group V. v0.2: 2/33 (`test_v1_werning_ge_target_resid_reported`, `..._direct`); re-run: 0/37. | + +**Suite level.** + +- (ii): 19 of 20 mutants caught, N20 missed. Five of them are caught only by V (N04, N05, N07, N10, N18). No control alarms (K01–K03). +- (iii): 25 of 25 caught, four only by V (M12, M21, M23, M24). No control alarms (C01, C02, C03). +- Group-V counts are those of v0.2 with 37 in the denominator. For example, in (ii): N02 11/37, N06 9/37, N12 9/37, N19 8/37 (N19: the t3 fixture error, as before), N17 4/37. In (iii): M13 14/37, M08 13/37. + +**Per V test** (the table of `docs/MUTATION_v0_2.md`, section 5): + +- Each existing V test catches the same mutants as in v0.2, except that C03 no longer appears under the two V1 tests in (iii). +- The new tests caught nothing: `test_v4_exogenous_G_as_requested`, `..._r_...`, `..._rshock_...` passed and `test_v6a_...`, `test_v6b_...` xfailed in all 53 runs. + +**Pre-registered predictions of v0.2, scored by the runner.** + +- (ii): 167 of 168 firm cells held. The one miss is N13/T2, as in v0.2. +- (iii): 222 of 223 held. The one miss is C03/V, predicted "catch (false alarm)" in v0.2, which R4 was designed to change. + +### 10.4 Predictions of this amendment (section 7) + +| Prediction | Result | Detail | +|---|---|---| +| P1 baselines | **held** | 107 passed, 4 xfailed; B0 = B1 in every outcome and summarised number; 276 = v0.1 B0 in both. (The two baselines of the runner check at B differed at rounding level, section 5; these two did not.) | +| P2 T1–T6, D | **held** | same verdict and same changed tests as v0.2 in all 51 runs | +| P3 existing V tests | **held** | same outcomes as v0.2 in every run except C03 | +| P4 values | **failed at rounding level** | see below | +| P5 new tests | **held** | `exog_G`, `exog_r`, `exog_rshock` exactly 0 in every run; the three tests pass, V6a and V6b xfail, in every run | +| P6 C03 | **held** | the provider reports `goods_mkt` for both incidences; V1 passes. The four goods-market values equal the threshold runs' b_max bit for bit (8.67e-14, 1.39e-13, 8.75e-14, 1.27e-13 against 9e-12 and 2e-11). The asset-market diagnostic equals the values that alarmed in v0.2 (2.96e-6 and 2.44e-3, divided by b) | +| P7 suite level | **held** | (ii) 19/20, N20 missed, no alarm on K01–K03; (iii) 25/25, no alarm on C01–C03; original predictions 167/168 and 222/223 (C03/V) | +| P8 checker self-tests | **held** | the 30 tests of `tests/test_v0_3_0_checker.py` passed in all 53 runs | + +**P4 in detail.** Every v0.3 quantity in the v0.2 data was compared with the same run's value in the re-run. Only one kind of quantity differs, the T5 goods-market path residual max_t |dY_t − dC_t − dG_t| / s; there are no differences in any other quantity, and none in the v0.1 summaries apart from the known two-valued number. + +- **Runs affected:** 31 of the 53. The baselines differ from v0.2's in five such values, which are the ones seen in section 5. +- **Settings affected:** all three T5 settings. + - In the refined setting that the V tests use: 27 runs, 43 values, absolute differences at most 2.8e-15. The threshold is 4e-11, and the baseline values are near 3e-13. + - In the two settings that no V test uses: up to 5.8e-9 in absolute terms, but at most 4.5e-12 relative (M08, whose residuals there are of order 1e3). +- **Cause.** This is the run-to-run rounding of dC described in the plan (section 4), which also shows in the v0.1 two-valued number. The prediction exempted only the two unused settings, and was wrong for the refined one. +- **No test outcome changed because of it.** Section 5 had flagged this risk before any mutant was run. +- *(2026-10-23: the clause "none in the v0.1 summaries apart from the known two-valued number" above holds for the baselines only; see the correction in section 11.7.)* + +**C03 is not independent evidence.** Its V1 thresholds come from unmodified runs of the same setting (section 3.4), so its pass holds by construction. It shows that the target convention works as built: a goods-market solve is judged on the goods market, and its asset-market residual is kept as a diagnostic. + +### 10.5 Contribution of the new quantities + +| Quantity | (ii) | (iii) | Note | +|---|---|---|---| +| `exog_G`, `exog_r`, `exog_rshock` | 0 catches; value 0 in every run | 0 catches; value 0 in every run | the reference provider takes the exogenous paths from the inputs, and no mutant changes that; the evidence for R3 is the doubled-shock regression test | +| `ge_target_resid_*_goods_*` | not applicable (asset-market target in every run) | C03 only: passes | the four values equal the threshold runs' | +| `rate_rule` with the requested rshock | same catches as v0.2 (N04, N16) | same as v0.2 (M05, M20, M25) | the reported drshock equals the requested rshock in every run | +| R1 verdict (non-finite, missing, incomplete) | no run had a missing or non-finite V value | as (ii) | evidence: regression tests (section 3.1) | +| R2 per-equation fields | every field reported in every run | as (ii) | evidence: fake providers (section 3.2) | +| V6a, V6b | xfail in every run | xfail in every run | SSJ code only; no model-side mutant reaches them | + +### 10.6 Controls + +- No control changed any test outcome in the re-run: K01–K03 in (ii), C01–C03 in (iii). +- C03 no longer alarms, for the reason in section 10.4. Six controls do not make a false-alarm rate. + +### 10.7 Margins + +- The margins of the V catches are the same as in v0.2. The values are bit-identical, apart from the rounding-level goods-market path residuals of section 10.4, none of which is a catching value. +- In (ii), every mutant caught by V (13 of the 19 caught) has a failing V test above its threshold by a factor of 9.7e3 or more (N18). (Wording corrected 2026-10-23, section 11: this said "every caught mutant".) By individual failing test, the smallest factor is 526 (N12, TANK goods market). +- In (iii), the smallest of the largest factors per mutant is 274 (M16). By individual failing test, the smallest factor is 1.3 (M15, V1). +- These figures correct a statement in `docs/MUTATION_v0_2.md`, section 1; its dated correction is part of this commit. + +### 10.8 What this shows + +- The revision changed one detection outcome on the two samples, the one it was designed to change (C03). The 19 of 20 and 25 of 25 of v0.2 hold for the revised suite as well. +- The evidence for R1–R3 is in the regression tests with fake providers: missing, non-finite and wrongly sized exogenous values. Neither the reference provider nor any mutant produced such a case. +- The statements of `docs/CHECKS_PLAN_v0_3.md`, section 9, and of `docs/MUTATION_v0_2.md`, section 10, hold unchanged: two hand-picked samples, design (iii) not independent, one environment. + +## 11. Changes after the pre-merge check (2026-10-23) + +**These changes were made after the results of sections 5 and 10 were seen**, in response to a pre-merge check of the release candidate `ee16305` (GPT, 2026-10-23). Section 10 stays as the record of the re-run at `a290c75`; only its wording in 10.7 was narrowed (P3 below), and no result in it changed. + +### 11.1 What the check found + +The check confirmed that the six reproductions of the first review are handled as intended, and reproduced 107 passed, 4 xfailed. It also confirmed that the seven new thresholds follow the rule, the 88 old ones are unchanged, the 276 summary numbers are bit-identical, and the counts and metadata of the 53 re-run runs agree. It found one P2 defect, two P3 wording errors and one follow-up item. + +**P2: the provider and the checker shared the request objects.** The checks read the objects they had passed to the provider again after the call: + +- `check_ikc` (T5) took the expected experiments and the requested exogenous paths from the `shocks` dict it had given the provider; +- `check_werning` (T3) gave both incidences the caller's `dr` array, and used it for the reference paths and the V1 residual; +- `check_tank_limit` (T2) did the same with `dr`, and with `chis`. + +A provider that changed those objects therefore changed what it was compared with. The check reproduced three cases: + +| What the provider did | Result at `ee16305` | +|---|---| +| `shocks.pop('rshock_r_rule')`, then solved the rest | the dropped experiment also left the expected coverage; all 13 fiscal V tests passed, with no skip reason | +| `path *= 2` on every path it was given, then solved | the reference paths doubled as well; all 13 passed, `exog_*` and the rate rule included | +| T3 proportional-income provider: `dr *= 2` | all 7 T3 V tests passed, and the caller's array was four times its value after two b | + +So the claim of section 3.1, that coverage "is declared by the check, not inferred from what the provider returned", did not hold when a provider changed its arguments in place. The same channel let the doubled shock of R3 pass again. Neither the reference provider nor any mutant changes its arguments, so no result of sections 5 and 10 is affected; the prediction in 11.5 tests this. + +### 11.2 Fix + +`checks._request` makes a deep copy, arrays included; a shallow copy of a dict would still share its arrays. + +| Check | Before | After | +|---|---|---| +| `check_ikc` (T5) | `shocks = shocks_fn(T)`, `provider(T, shocks)`, then coverage, exogenous paths and residuals from the same `shocks` | the check's own copy of `shocks_fn(T)`; expected coverage declared from it **before** the provider is called; the provider gets a separate copy; residuals, `exog_*` and the rate rule from the check's copy | +| `check_werning` (T3) | the caller's `dr` passed to both incidences and reused | the check keeps its own copy; each of the two calls per b gets a fresh copy; reference paths and V1 residuals from the check's copy | +| `check_tank_limit` (T2) | the caller's `dr` and `chis` passed and reused | the check keeps copies; each eps gets fresh copies; reference paths and the chi loop from the check's copies | + +The other checks were searched for objects that a provider receives and the check reads again; none was found. + +- `check_rank_limit` (T1) and `check_aiyagari` (T4) pass only numbers (eps, T, sd, ρ). The lists `eps_list`, `sd_list` and `rho_list` are not passed to the provider. +- `check_differencing` (T6) calls no provider; it reads provider output only. +- `suite.run_t6` builds its `shocks` inline and does not read them after the call. +- Keyword arguments (`**kw`) are passed through to the provider and never read by the checks. +- The checks change no provider output in place. + +No computation of the reference provider changed. For it the copies hold the same values as before, so its results are the same; the outputs are listed in 11.6. + +### 11.3 `ge_target` outside the convention (follow-up item) + +A reported `ge_target` that is not a string (a number, a list, bytes) used to raise: a `TypeError` under `v0_3` → `errors`, or, for a list, outside the guard, which stopped the whole check. It is now treated like an unknown string: V1 does not apply at that setting, the reason is recorded, and the value is recorded as `repr(...) (not a string)` under `v0_3` → `ge_target`. `interface.py` says so ("any other value, another string or a value that is not a string"). + +### 11.4 New tests + +Seven tests in `tests/test_v0_3_0_checker.py`. All of them failed on `ee16305` (before the fix), as shown in the third column, and pass after it. + +| Test | What it checks | At `ee16305` | +|---|---|---| +| `test_request_t5_provider_drops_an_experiment` | the six path quantities of the dropped experiment are incomplete; the caller's stored `shocks` are unchanged | did not skip (all passed); the caller's dict lost the experiment | +| `test_request_t5_provider_doubles_paths_in_place` | IKC still holds, but `exog_G`, `exog_r`, `exog_rshock` and the rate rule fail; the caller's arrays are unchanged | did not fail | +| `test_request_t3_provider_doubles_dr_in_place` | V1 direct fails; the reference uses the requested path; the countercyclical call gets its own copy; the caller's `dr` is unchanged | the caller's `dr` was four times its value | +| `test_request_t2_provider_changes_dr_and_chis` | the caller's `dr` and `chis` are unchanged; the reference uses the requested path | `KeyError` (the provider appended to `chis`) | +| `test_r4_non_string_target_not_applicable[3, ['asset_mkt'], b'asset_mkt']` | no error; V1 skipped as not applicable, with the reason | `TypeError` (recorded, or raised outside the guard for the list) | + +Full pytest after the fix: **114 passed, 4 xfailed** (F1, F2, V6a, V6b). That is 77 tests of groups T1–T6, D and V, unchanged, and 37 checker tests (30 + 7). + +### 11.5 Wording (P3) + +- Section 5, notes on the table: the T5 path `goods_market` b_max is 3.115563e-13 in both threshold runs (3.12e-13, as in the plan). The "3.11e-13" written there came from a trial run that was not kept. The same mix-up is corrected in the observations of section 5; it was not named in the check but has the same cause. No threshold changes. +- Section 10.7: "every caught mutant" is narrowed to "every mutant caught by V". In (ii) V catches 13 of the 19 caught mutants. + +### 11.6 Re-run of designs (ii) and (iii) at the fix commit + +**Registered before the run.** This subsection up to "Results" was committed and pushed with the fix, before the re-run was started. + +- **Design.** Designs (ii) and (iii) and two baselines (53 runs) on the commit of the fix, with `scripts/mutation_v0_3_0.py` unchanged (`--v03-ref --design ii iii`). The output goes to a scratch directory. It is compared with commit C (`out/mutation_v0_3_0_rerun.json`) run by run, on: + - every test outcome; + - every group verdict and set of changed tests; + - every summarised number, the v0.1 part and the v0.3 quantities. + + The comparison script, `scripts/rerun_v0_3_0_F_compare.py`, is committed with the fix, before the run. +- **Prediction.** The reference provider and the mutants do not change the objects they are given, so everything is predicted to be as at commit C: + - every test outcome and every group cell is the same in all 53 runs. The 7 new checker tests are new; they belong to no group and pass in every run; + - in both baselines, all 276 v0.1 numbers equal v0.1 run B0; + - every summarised number equals its commit-C value in the same run, except T5 goods-market path residuals that vary at rounding level from run to run (sections 5 and 10.4), and the known two-valued v0.1 number. +- **Rule for the outputs, fixed now.** + - "Same" means: identical test outcomes and group cells, and identical summaries apart from the two exceptions just named. + - If so, the raw outputs (about 6 MB) are not committed. `out/rerun_v0_3_0_F_compare.json` holds the comparison: every differing number with both values, and the execution record (commit, time, runner blob, environment, SHA-256 of the raw files). + - If any test outcome, group cell or other summarised number differs, the raw outputs are committed as `out/mutation_v0_3_0_rerun_F.{json,csv}`, and every differing cell is reported here. + - `out/mutation_v0_3_0_rerun.*` (commit C) are not overwritten in either case. + +**Results** (added after the run, commit F2). + +**Execution record.** + +- Commit `361143c` (the fix, pushed 2026-10-22 23:21:05 UTC, which is 2026-10-23 in Korea). +- Run started 23:21:14 UTC: 53 runs, 4 in parallel, 1,007 s, 64–139 s per run. +- Runner `scripts/mutation_v0_3_0.py`, blob `67dea61` (unchanged since B; `runner_committed = true`), clean worktree, same environment as before. +- Comparison: `out/rerun_v0_3_0_F_compare.json`, which holds every differing number with both values and the execution record. + +**The registered rule applied.** Some summarised numbers differ outside the two exempted kinds (see below), so the raw outputs are committed as `out/mutation_v0_3_0_rerun_F.json` and `out/mutation_v0_3_0_rerun_F.csv`. Their SHA-256, also in the comparison file: + +- `mutation_v0_3_0_rerun_F.json`: `3d97e3a8034dc32e7cd23bcf8bca463190430f165109f4d8157cda1cb297af33`; +- `mutation_v0_3_0_rerun_F.csv`: `a8f15a4562dd18ebb9b61869e481cda3973b88353a57efbbd8503d091c272b41`. + +Commit C's `out/mutation_v0_3_0_rerun.*` are unchanged. + +**Test outcomes and cells: the same as commit C in every run.** + +- All 111 tests that exist in both runs have the same outcome in all 53 runs. +- The 7 new checker tests passed in all 53 runs. +- Every group cell (detected, and the set of changed tests) is the same in all 51 mutant and control runs. +- Suite level, as at commit C: (ii) 19 of 20 caught, N20 missed, no alarm on K01–K03; (iii) 25 of 25 caught, no alarm on C01–C03. + +**Baselines.** + +- Both baselines: 114 passed, 4 xfailed. +- In B1, all 276 v0.1 numbers equal v0.1 run B0 bit for bit. +- In B0, 275 equal v0.1 run B0. The known two-valued number (`t5.ssj_inconsistent_options.walras_max.rshock_r_rule`) took its other value, that of v0.1 run B1 (relative 1.4e-11). +- So every number equals its value in v0.1 B0 or B1, the plan's rule 2. The prediction "in both baselines all 276 equal v0.1 B0" failed in this one number. +- The two baselines differ from each other only in that number and in rounding-level goods-market path residuals; the runner reports `deterministic = false`. + +**Summarised numbers.** 182 numbers in 31 runs differ from commit C: + +| Kind | Count | Size | Registered as | +|---|---|---|---| +| T5 goods-market path residuals | 138 | refined setting: 35 values in 23 runs, at most 5.7e-12 absolute (M05, values of order 4); all settings: at most 1.3e-7 relative among values above 1e-10 | exempted | +| the known two-valued v0.1 number | 20 | 1.4e-11 relative | exempted | +| T5 `walras_max` (v0.1 summary, max \|asset_mkt\| on the path), all three settings | 24, in 9 mutant runs (K03, M01, M02, M09, M16, M21, M25, N12, N19) | at most 3.4e-11 relative; none in a baseline | **not exempted** | + +The third kind is the same run-to-run rounding as the other two: the asset-market path depends on the same propagated household paths as dC. It was already present between v0.2 and commit C (11.7). It changed no test outcome. The prediction did not exempt it, so for these 24 numbers it failed. + +**Predictions of 11.6, scored.** + +| Prediction | Result | +|---|---| +| every test outcome and group cell as at commit C; new tests pass in every run | **held** | +| 276 v0.1 numbers equal v0.1 B0 in both baselines | **failed in one number in B0**: the known two-valued number took its v0.1-B1 value; B1 held in all 276 | +| summarised numbers as at commit C, apart from goods-market path residuals and the two-valued number | **failed for 24 numbers**: T5 `walras_max` in 9 mutant runs, at most 3.4e-11 relative | + +**What this shows.** The fix changed no test outcome and no detection result on either sample, as predicted: neither the reference provider nor any mutant changes the objects it is given. Its evidence is the seven regression tests (11.4). The differing numbers are run-to-run rounding of the same kind that sections 5 and 10.4 describe, in one more quantity than was predicted. + +### 11.7 Correction to section 10.4 + +Section 10.4, "P4 in detail", says that comparing the v0.2 data with commit C there are "no differences in any other quantity, and none in the v0.1 summaries apart from the known two-valued number". The comparison behind it (`scripts/rerun_v0_3_0_compare.py`, `value_diffs`) covered the v0.3 quantities of every run, but the v0.1 summaries only through the 276 numbers of the baselines. For the baselines the statement holds. + +In the mutant runs, the v0.1 summaries differ between v0.2 and commit C in 34 numbers in 21 runs: + +- 16 are the known two-valued number; +- 18 are other T5 `walras_max` values, in 9 runs, at most 3.4e-11 relative. This is the same kind as in 11.6. + +No test outcome changed. Section 10 is left as it was, apart from a pointer to this correction. + diff --git a/docs/MUTATION_v0_2.md b/docs/MUTATION_v0_2.md index 516bbb0..d3dc625 100644 --- a/docs/MUTATION_v0_2.md +++ b/docs/MUTATION_v0_2.md @@ -6,6 +6,16 @@ Measured on branch `v0_3` (no tag, no release; the version, tags and citation me **Correction, 2026-10-22.** Sections 1 and 8 first attributed the C03 alarm in V1 to F3 alone and said that fixing F3 upstream, or differentiating the income in the provider, would remove it. That was wrong. With proportional income, where F3 plays no role, the goods-market solve already leaves an asset-market residual of up to 3.0e-6·b, far above the threshold. V1 alarms because it assumes the asset-market target; F3 only makes the residual larger with countercyclical income. Sections 1 and 8 are corrected. No data, code or threshold changed. +**Correction, 2026-10-22 (pre-release review of v0.3).** Two statements are corrected, from the data in `out/mutation_v0_2.json` (recomputed with `scripts/rerun_v0_3_0_compare.py`). + +1. Section 1, "Margins", said: "Every V catch in (ii) exceeds its threshold by a factor of 1e4 or more; in (iii) the smallest factor is 274 (M16, Euler errors at the documented β)." + - The first half is wrong. In (ii), the largest factor per mutant is at least 9.7e3, for N18 (9.7e3 in the TANK goods market, 7.6e3 in the TANK asset market). By individual failing test, the smallest factor is 526 (N12, TANK goods market). + - The second half holds only per mutant: 274 (M16) is the smallest of the largest factors. By individual failing test, the smallest factor in (iii) is 1.3 (M15, V1). + - Section 1 now separates the two. +2. Section 8 said that V1 alarms on "any goods-market solve of T3". What was observed is a solve with this reference provider, calibration and solver setting. The sentence is narrowed. + +Neither correction changes a result (19 of 20, 25 of 25), the data, the code or a threshold. From v0.3.0, V1 judges the GE target that the provider reports (`docs/CHECKS_v0_3_0_AMENDMENT.md`). + ## 1. Summary - **Setup.** Two suites: v0.2.1 (the released tests, tag `v0.2.1`) and v0.3 (the same tests plus the new checks V1–V6, commit T). 20 new mutants and 3 controls, generated by a separate agent that saw the model code and the v0.1 mutant list but not the tests, the v0.1 report or the new checks (plan, section 6 and appendix A). Each mutant was applied to a copy of the model side (`models.py`, `core.py`) of each suite, and that suite's full pytest run was compared with its own unmutated baseline. 78 runs in all: (i) v0.2 mutants × v0.2.1, (ii) v0.2 mutants × v0.3, (iii) the 28 v0.1 runs × v0.3, plus two baselines per suite. @@ -14,7 +24,9 @@ Measured on branch `v0_3` (no tag, no release; the version, tags and citation me - **Controls:** no false alarm in either suite (K01–K03). Among the v0.1 controls, C03 (T3 goods-market target) alarms in V1 in the v0.3 suite, as pre-registered. V1 assumes that T3 is solved on the asset-market target, and the goods-market solve leaves an asset-market residual far above the threshold: up to 3.0e-6·b with proportional income, where F3 plays no role, and up to 2.4e-3·b with countercyclical income, where F3 adds to it. The threshold was not adjusted. - **Pre-registered predictions:** in (i), 145 firm group-level predictions, 144 held; in (ii), 168, 167 held. The one failure is the same cell in both: N13 was predicted to pass T2 and failed it (section 7). Suite level: 12 caught predicted for v0.2.1 (14 observed: N13, and N01 via an "unsure" T4 cell); 18 for v0.3 (19 observed: N01). All 23 group-V predictions (20 mutants, 3 controls) held. - **v0.1 mutants (iii):** the v0.3 suite catches all 25, including the four that v0.2.1 missed (M12, M21, M23, M24), each by the check built for it, and M07 now directly (firm first-order condition at the documented δ). This is **not** an independent result: the checks were designed after seeing those misses. -- **Margins.** Every V catch in (ii) exceeds its threshold by a factor of 1e4 or more; in (iii) the smallest factor is 274 (M16, Euler errors at the documented β). The conclusions do not depend on the factor 100 in the threshold rule. +- **Margins** (corrected 2026-10-22, see the second correction above). In (ii), every mutant that V catches has a failing V test above its threshold by a factor of 9.7e3 or more. The smallest such factor is N18's: 9.7e3 in the TANK goods market, and 7.6e3 in its other failing test, the TANK asset market. By individual failing test, the smallest factor is 526 (N12, TANK goods market), then 529 (N02) and 577 (N06) in the same test. + In (iii), every mutant that V catches has a failing V test above its threshold by a factor of 274 or more (M16, Euler errors at the documented β, its only V catch). By individual failing test, the smallest factors are 1.3 (M15, both V1 tests), 1.6 (M20 and M25, rate rule on the path) and 1.6 (M08, fiscal asset market); each of these mutants is caught by another V test by a factor of 1e8 or more. + So the suite-level results (19 of 20, 25 of 25) do not depend on the factor 100 in the threshold rule: they would hold with any factor below about 9.7e5 in (ii) and 2.7e4 in (iii) (100 times the smallest of these per-mutant factors, rounding of the thresholds aside). Individual test catches with factors near 1 would not. This is a measurement on a second hand-picked sample of 20 errors. It describes this sample only; it is not an estimate of how often either suite catches HANK implementation errors in general (section 10). @@ -239,7 +251,7 @@ No control changed any test outcome in either suite: K01 (zero-profit wage), K02 - **Proportional income:** residual / b between 8.2e-10 and 3.0e-6 across the seven b, largest at b = 1e-4. The income hetinput is linear here, so F3 plays no role. - **Countercyclical income:** residual / b between 5.4e-5 and 2.4e-3, largest at b = 0.03. Here F3 adds an O(h) error: SSJ differentiates the nonlinear income hetinput one-sided, so the household Jacobians satisfy the aggregate budget identity only to O(h) (v0.1 report, section 8). -So V1 alarms on any goods-market solve of T3, with or without F3. The alarm is a true statement about the numerical solution, but it is a false alarm about C03, which is Walras-equivalent in exact arithmetic. The threshold was not adjusted. +So, with this reference provider, calibration and solver setting (the seven b, both incidences), V1 alarmed on the goods-market solve, with or without F3 (corrected 2026-10-22: this said "any goods-market solve of T3"; other goods-market solves were not examined). The alarm is a true statement about the numerical solution, but it is a false alarm about C03, which is Walras-equivalent in exact arithmetic. The threshold was not adjusted. **Prediction right, part of its reason wrong.** The pre-registered prediction (plan, section 7) was that C03 alarms in V1, and it did. The reason given there named F3 only ("1.1e-4 at b = 0.1 because of F3"). That number is the countercyclical residual at b = 0.1 (1.1e-3·b, measured). But the proportional-income case alarms as well, without F3, so F3 is not the cause of the alarm; it only makes the countercyclical residual larger. The plan is a pre-registration document and is left unchanged. diff --git a/hank_limits/__init__.py b/hank_limits/__init__.py index 07a17f2..0d82faa 100644 --- a/hank_limits/__init__.py +++ b/hank_limits/__init__.py @@ -11,4 +11,4 @@ "NUMBA_NUM_THREADS", "VECLIB_MAXIMUM_THREADS"): _os.environ.setdefault(_v, "1") -__version__ = "0.2.1" +__version__ = "0.3.0" diff --git a/hank_limits/checks.py b/hank_limits/checks.py index 4e472b3..ca862fc 100644 --- a/hank_limits/checks.py +++ b/hank_limits/checks.py @@ -7,6 +7,7 @@ """ from __future__ import annotations +import copy import time import numpy as np @@ -19,13 +20,32 @@ def _tolist(x): return [float(v) for v in np.asarray(x).ravel()] +def _request(x): + """An independent deep copy of what a check asks a provider for (requested experiments, rate + paths, chi values). Pre-merge check of v0.3.0 (docs/CHECKS_v0_3_0_AMENDMENT.md, section 11): + each check keeps its own copy, declares the expected coverage and computes the reference + paths and residuals from it, and gives every provider call a fresh copy. A provider that + changes the objects it is given (drops an experiment, scales a path in place) then changes + neither what the check compares with nor the caller's objects.""" + return copy.deepcopy(x) + + # --------------------------------------------------------------------------- -# v0.3 checks (docs/CHECKS_PLAN_v0_3.md): steady-state residuals (V2), income normalisation -# (V3) and specification pins (V4), computed here from primitive quantities the provider -# reports in the optional fields `ss_detail`, `J_A`, `policy` and the paths. They are stored -# under res['v0_3'] (one list entry per setting of the check), so the v0.1 part of every -# result is unchanged. A missing field skips the quantities that need it; the reason is -# recorded in res['v0_3']['skipped']. +# v0.3 checks (docs/CHECKS_PLAN_v0_3.md; revised for v0.3.0, docs/CHECKS_v0_3_0_AMENDMENT.md): +# GE target residual of T3 (V1), steady-state residuals (V2), income normalisation (V3) and +# specification pins (V4), computed here from primitive quantities the provider reports in the +# optional fields (`hank_limits.interface`) and from the inputs the caller passed. They are +# stored under res['v0_3'] (one list entry per setting of the check), so the v0.1 part of every +# result is unchanged. +# +# v0.3.0: coverage is declared by the check, not inferred from what the provider returned. At +# each setting the expected quantities get a placeholder None, replaced when the quantity is +# computed; res['v0_3']['at'][q] holds the setting of each value of q and +# res['v0_3']['status'][q] the coverage of q. Each quantity is computed from the fields its own +# equation needs; if one is missing, the placeholder stays and the reason is recorded in +# res['v0_3']['skipped']. `v03_verdict` turns the values into the verdict of a test: a +# non-finite, negative or too large value fails whatever else is missing, and a missing value +# without failure is "incomplete", never a pass. # --------------------------------------------------------------------------- def stationary_marginal(Pi): @@ -39,15 +59,30 @@ def stationary_marginal(Pi): return np.linalg.solve(A, b) +def _pi_row_sum_err(Pi): + return float(np.max(np.abs(Pi.sum(1) - 1))) + + +def _pi_negative(Pi): + return float(max(0.0, -Pi.min())) + + +def _mean_e_err(pi, e): + return float(abs(pi @ np.asarray(e, float) - 1)) + + +def _agg_income_err(pi, y, Y_ref): + return float(abs(pi @ np.asarray(y, float) - Y_ref) / abs(Y_ref)) + + def income_report(e, Pi, y=None, Y_ref=None): """V3: Pi row-stochastic, E_pi[e] = 1 and, if y is given, sum_e pi_e y_e = Y_ref.""" Pi = np.asarray(Pi, float) pi = stationary_marginal(Pi) - out = dict(pi_row_sum_err=float(np.max(np.abs(Pi.sum(1) - 1))), - pi_negative=float(max(0.0, -Pi.min())), - mean_e_err=float(abs(pi @ np.asarray(e, float) - 1))) + out = dict(pi_row_sum_err=_pi_row_sum_err(Pi), pi_negative=_pi_negative(Pi), + mean_e_err=_mean_e_err(pi, e)) if y is not None and Y_ref is not None: - out['agg_income_err'] = float(abs(pi @ np.asarray(y, float) - Y_ref) / abs(Y_ref)) + out['agg_income_err'] = _agg_income_err(pi, y, Y_ref) return out, pi @@ -83,8 +118,30 @@ def euler_errors(Pi, a_grid, a_pol, c_pol, D, r, beta, eis, bind_tol=1e-10, mass if np.any(binding & has_mass) else 0.0) +# --- records: settings, placeholders, values, skips ------------------------------------------ + def _new_v03(): - return dict(skipped=[]) + return dict(skipped=[], settings=[], at={}) + + +def _expect(v, keys, where): + """Declare that each quantity in `keys` is expected at setting `where` (placeholder None).""" + at = v.setdefault('at', {}) + for k in keys: + v.setdefault(k, []).append(None) + at.setdefault(k, []).append(where) + + +def _put(v, key, value, where): + """Record a value at setting `where`: it replaces the placeholder of a quantity declared + there, and is appended with its setting otherwise.""" + x = None if value is None else float(value) + vals, at = v.setdefault(key, []), v.setdefault('at', {}).setdefault(key, []) + if at and at[-1] == where and vals[-1] is None: + vals[-1] = x + else: + vals.append(x) + at.append(where) def _guard(v, fn, *args): @@ -96,171 +153,401 @@ def _guard(v, fn, *args): v.setdefault('errors', []).append(f'{fn.__name__}: {type(exc).__name__}: {exc}'[:300]) -def _put(v, key, value): - v.setdefault(key, []).append(None if value is None else float(value)) - - def _skip(v, what, missing): msg = f"{what}: provider does not report {', '.join(missing)}" if msg not in v['skipped']: v['skipped'].append(msg) -def _need(d, keys): - return [k for k in keys if d is None or k not in d] +class _Fields: + """The fields of one provider result that the V checks read: `f[name]` is the value, + `f.missing(names)` names the fields not reported (e.g. "ss_detail['y']"). `top` are + top-level fields; keyword arguments name a nested field and its keys + (`ss_detail=('Y', 'C')`, `policy=('a', 'c')`).""" + + def __init__(self, out, top=(), **nested): + self.val, self.lab = {}, {} + for k in top: + self.lab[k] = k + if k in out: + self.val[k] = out[k] + for field, keys in nested.items(): + d = out.get(field) + for k in keys: + self.lab[k] = f"{field}['{k}']" if isinstance(d, dict) else field + if isinstance(d, dict) and k in d: + self.val[k] = d[k] + + def __getitem__(self, k): + return self.val[k] + + def missing(self, names): + return list(dict.fromkeys(self.lab[n] for n in names if n not in self.val)) + + +def _eq(v, key, where, tag, f, names, fn): + """Compute one quantity if the provider reports every field its equation needs (R2: fields + per equation); otherwise keep the placeholder and record the missing fields.""" + miss = f.missing(names) + if miss: + return _skip(v, f'{key} ({tag})', miss) + _put(v, key, fn(), where) + + +def _dev(x, ref, rel=False): + return abs(x - ref) / (abs(ref) if rel else 1.0) -def _pin(v, key, value, ref, rel=False): - _put(v, key, abs(value - ref) / (abs(ref) if rel else 1.0)) +def _pin(v, key, where, tag, f, name, ref, rel=False): + _eq(v, key, where, tag, f, [name], lambda: _dev(f[name], ref, rel)) -def _income(v, suffix, e, Pi, y, Y_ref): - inc, pi = income_report(e, Pi, y, Y_ref) - for k, x in inc.items(): - _put(v, k + suffix, x) +def _income(v, sfx, where, tag, f, e, Pi, y, ref_names, ref): + """V3 for one income chain (field names e, Pi, y in f; the aggregate-income reference ref() + needs the fields ref_names). Returns the stationary distribution of Pi, or None.""" + pi = None if f.missing([Pi]) else stationary_marginal(f[Pi]) + _eq(v, 'pi_row_sum_err' + sfx, where, tag, f, [Pi], + lambda: _pi_row_sum_err(np.asarray(f[Pi], float))) + _eq(v, 'pi_negative' + sfx, where, tag, f, [Pi], lambda: _pi_negative(np.asarray(f[Pi], float))) + _eq(v, 'mean_e_err' + sfx, where, tag, f, [e, Pi], lambda: _mean_e_err(pi, f[e])) + _eq(v, 'agg_income_err' + sfx, where, tag, f, [y, Pi, *ref_names], + lambda: _agg_income_err(pi, f[y], ref())) return pi -def _v03_rank(v, out, spec): - d = out.get('ss_detail') - miss = _need(d, ('Y', 'C', 'A', 'r', 'eis', 'a_min', 'e_grid', 'Pi', 'y')) - if miss: - return _skip(v, 'V2/V3/V4 (T1)', miss) - pi = _income(v, '', d['e_grid'], d['Pi'], d['y'], d['Y']) - _put(v, 'hh_budget', household_budget_resid(d['C'], d['A'], d['r'], d['y'], pi)) +def _coverage(at, vals): + missing = [w for w, x in zip(at, vals) if x is None] + nonfinite = [w for w, x in zip(at, vals) if x is not None and not np.isfinite(x)] + n = len(vals) - len(missing) + state = ('nonfinite' if nonfinite else 'not_reported' if n == 0 else + 'incomplete' if missing else 'complete') + return dict(state=state, n_expected=len(vals), n_reported=n, missing=missing, + nonfinite=nonfinite) + + +def _finish(v): + """Coverage summary per quantity, res['v0_3']['status'] (T5 paths: 'paths.