diff --git a/CHANGELOG.md b/CHANGELOG.md index b2d6829aa..d8247a26f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,14 @@ heading here; `tests/test_repo_hygiene.py` asserts that they do. ## [Unreleased] +### Adapters: labels from two open model PRs, `horizon` deprecated + +- **`obr_shock`** forwards three more of the model's labels when the model sets them: `subsidy_residual_warning`, `procurement_residual_warning` and `nominal_consistent_legs` (obr-macroeconomic-model #90). The first two say that the listing's subsidy or procurement residual absorbed the shock, so the borrowing figures are not the effect of the spending change. The current pin sets `nominal_consistent_legs` only, for `CGG`; the warnings arrive with a re-pin. It also forwards obr-macroeconomic-model #95's labels saying which borrowing total a shock moved: `la_borrowing_identity`, `la_borrowing_note`, `investment_total_warning`, `procurement_offset_note` and `procurement_offset_m`. +- **`hank_shock` text** now says that at the default persistence of 0.9, above the two-asset sign change at about 0.75, an easing raises the policy rate on impact while the ex-ante real rate falls and output rises. Use about 0.61 for a falling policy rate (us-hank-model #22). The default is unchanged. +- **`define_scenario`** reports a `BaselineParameterMismatch` (define-uk-model #36) as its own refusal, `"refused": "baseline parameter mismatch"`, like the stock-flow one. It fell into the generic branch, whose hint is about a cached run that does not depart from baseline. The class is matched by name, so the adapter works before and after the DEFINE re-pin. +- **`recommend_model`**: `horizon` is deprecated (#210). It never changed the routing. It stays in the tool schema and is echoed back, so no caller breaks; a caller who passes it now gets `horizon_note` (and Python callers a `DeprecationWarning`) saying it was ignored and pointing at each candidate's own `horizon` under `details`. +- **Drift canary `hank_25bp_easing`** gains a `description`: the 25bp is per quarter, a shift in the Taylor-rule intercept of about 100bp annualised. The id is unchanged, so drift reports and #264 still refer to it. + ### BoE SVAR re-pin to `17f5d82` - **Pin.** BoE SVAR `c827ab86` → `17f5d824` (boe-var-model #34, world CPI seasonal adjustment; #35, November 2026 MPR comparator and 2026Q3 scoring). After a redeploy the hosted `forecast_uk` and `latest_shocks` run this pin. diff --git a/integration/drift/canaries.json b/integration/drift/canaries.json index c8fa2995d..7293da401 100644 --- a/integration/drift/canaries.json +++ b/integration/drift/canaries.json @@ -151,6 +151,7 @@ }, { "id": "hank_25bp_easing", + "description": "The 25bp in the id is per quarter: size -0.0025 shifts the intercept of the model's quarterly Taylor rule by 25bp, about 100bp annualised. It is a shift in the rule, not a 25bp cut in the policy rate. The id is kept so that drift reports and issue #264 still refer to the same canary.", "model_id": "us-hank", "source_url": "https://github.com/PolicyEngine/us-hank-model", "tool": "hank_shock", diff --git a/integration/src/policyengine_macro/capabilities.py b/integration/src/policyengine_macro/capabilities.py index 83cd7314c..ea63d294d 100644 --- a/integration/src/policyengine_macro/capabilities.py +++ b/integration/src/policyengine_macro/capabilities.py @@ -6,6 +6,7 @@ from __future__ import annotations +import warnings from copy import deepcopy @@ -775,6 +776,13 @@ def _no_model_warning(question_type: str, country: str, needs_distribution: bool } +HORIZON_DEPRECATION_NOTE = ( + "`horizon` is deprecated and ignored: it does not change which model is " + "recommended, and it will be removed in a later release. Read each " + "candidate's own `horizon` under `details` and choose on that." +) + + def recommend( question_type: str, country: str = "uk", @@ -787,6 +795,11 @@ def recommend( combination, so it raises with the valid types listed; before 6 Nov 2026 a typo such as 'shock' came back as "no registered model supports this request", which reads as a capability gap. + + ``horizon`` is deprecated (macro #210). It never changed the routing, and + it still does not: it is accepted, echoed back, and answered with + ``horizon_note`` and a ``DeprecationWarning`` so no caller thinks it + filtered anything. Each candidate's own horizon is in ``details``. """ valid_types = question_types() question_type = str(question_type).strip().lower() @@ -821,7 +834,7 @@ def recommend( f" Experimental, not a recommendation: {', '.join(tools)} feed " "this model's macro path into the microsimulation." ) - return { + out = { "question_type": question_type, "country": country, "needs_distribution": needs_distribution, @@ -831,3 +844,9 @@ def recommend( "warning": warning, "details": [get_status(model_id) for model_id in candidates], } + if horizon is not None: + # Its own key, not `warning`: `warning` is None whenever a model is + # recommended, and callers read a non-None value as "no model". + out["horizon_note"] = HORIZON_DEPRECATION_NOTE + warnings.warn(HORIZON_DEPRECATION_NOTE, DeprecationWarning, stacklevel=2) + return out diff --git a/integration/src/policyengine_macro/core.py b/integration/src/policyengine_macro/core.py index c8aa3809c..4281c8ec2 100644 --- a/integration/src/policyengine_macro/core.py +++ b/integration/src/policyengine_macro/core.py @@ -477,6 +477,38 @@ def obr_shock( # channel, set for most levers. if attrs.get("mechanical_passthrough"): result["mechanical_passthrough"] = True + # obr #90: a shock to a line of public sector current expenditure whose + # imposed total was held is absorbed by the listing's subsidy (or + # procurement) residual, so the borrowing figures are not the effect of + # the spending change. nominal_consistent_legs names the nominal totals + # that moved with the shock instead. Absent on older pins, hence .get. + for key in ("subsidy_residual_warning", "procurement_residual_warning"): + if attrs.get(key): + result[key] = str(attrs[key]) + if attrs.get("nominal_consistent_legs"): + result["nominal_consistent_legs"] = [ + str(v) for v in attrs["nominal_consistent_legs"] + ] + # obr #95: which borrowing aggregate a shock moved. la_borrowing_identity + # is a bool and False is the informative value (local authority net + # borrowing was held on its data path, so LANB and GGNB did not respond), + # so it is forwarded whenever the model sets it. investment_total_warning + # says a public investment shock ran with the investment total PSNI held; + # procurement_offset_* that central government procurement moved to + # offset a change in government pay, so the central/local split of + # borrowing is the listing's. Absent on older pins, hence .get. + if attrs.get("la_borrowing_identity") is not None: + result["la_borrowing_identity"] = bool(attrs["la_borrowing_identity"]) + for key in ("la_borrowing_note", "investment_total_warning", + "procurement_offset_note"): + if attrs.get(key): + result[key] = str(attrs[key]) + offset = attrs.get("procurement_offset_m") + if isinstance(offset, dict) and offset: + result["procurement_offset_m"] = { + str(name): [round(float(v), 1) for v in list(values)[: len(rows)]] + for name, values in offset.items() + } # Not on an overlay run: the model's VAT note describes the default # ("no price channel"), which the overlay's own note supersedes. if attrs.get("transmission_note") and not price_passthrough: @@ -1161,7 +1193,14 @@ def frbus_summary() -> dict: "Taylor rule; the policy rate itself is returned as the " "series i and does not move one for one: about -13bp on " "impact for -0.0025 at persistence 0.61 (pinned in " - "us-hank-model #18), and it depends on the persistence. -0.0025 is a " + "us-hank-model #18), and it depends on the persistence. At the " + "default persistence of 0.9, above the two_asset sign " + "change at about 0.75, a negative size (an easing) RAISES " + "the policy rate on impact (about +25bp a quarter for " + "-0.0025) while the ex-ante real rate falls and output " + "rises; pass persistence of about 0.61 for a falling " + "policy rate in two_asset (us-hank-model #22; one_asset " + "changes sign lower, between 0.55 and 0.6). -0.0025 is a " "25bp-per-quarter intercept shift, about 100bp annualised; " "for a 25bp annualised intercept shift use -0.000625. " "The r and pi responses are quarterly rates too: multiply " @@ -4873,6 +4912,28 @@ def define_scenario( "pick another scenario from define_list_scenarios." ), } + # define-uk-model#36: BaselineParameterMismatch, also a ValueError. + # Matched by class name over the MRO, so it needs no adapter that + # has the class and still catches a subclass. + if any( + c.__name__ == "BaselineParameterMismatch" for c in type(e).__mro__ + ): + return { + "model": "define-uk", + "available": False, + "refused": "baseline parameter mismatch", + "scenario": name, + "error": str(e), + "how_to_run": ( + f"{name!r} is a listed scenario, but its cached DEFINE-UK " + "parameters differ from the Baseline's outside the policy " + "levers, so its deltas would carry that difference as " + "well as the policy and are not served as results. The " + "cached run has to be redone upstream with a matched " + "Baseline; meanwhile pick another scenario from " + "define_list_scenarios." + ), + } if isinstance(e, KeyError): # Unknown scenario name: the adapter IS installed, so install # instructions would mislead — point at the listing tool. diff --git a/integration/src/policyengine_macro/mcp_server.py b/integration/src/policyengine_macro/mcp_server.py index 4c275a9f7..847a5dd00 100644 --- a/integration/src/policyengine_macro/mcp_server.py +++ b/integration/src/policyengine_macro/mcp_server.py @@ -98,8 +98,12 @@ def recommend_model( dynamic_scoring, economic_shock, translated_policy_scenario, forecast, economic_diagnosis, structural_change, or climate_policy_scenario; any other value is an error. Unsupported combinations return no model rather - than an invented mapping. ``horizon`` is echoed back but does not yet - change the routing. + than an invented mapping. + + ``horizon`` is deprecated: it is accepted for backward compatibility and + echoed back, but it has never changed the routing. When it is passed the + result carries ``horizon_note`` saying so. Each recommended model's own + horizon is in ``details``; choose on that. """ return capabilities.recommend( question_type=question_type, @@ -418,8 +422,8 @@ def hank_shock( QUARTERLY nominal Taylor rule, not in the policy rate: the rule also responds to the inflation the shock causes, so the quarterly policy rate falls only about 13bp on impact for -0.0025 at - persistence 0.61 (us-hank-model #18; not pinned at other - persistences, including the default 0.9). -0.0025 is + persistence 0.61 (us-hank-model #18) and RISES about 25bp at + the default 0.9 (us-hank-model #22; see persistence). -0.0025 is a 25bp-per-quarter intercept shift, about 100bp annualised; for a 25bp annualised intercept shift use -0.000625. fiscal_spending is a level change in G (steady-state Y = 1, so 0.01 = 1% of GDP); @@ -432,6 +436,10 @@ def hank_shock( default because the spending multiplier depends on it (impact multiplier 0.175 at 0.8, 0.075 at 0.9); quote it with any multiplier. Defaults to 0.9 for monetary and productivity. + At 0.9, above the two_asset sign change at about 0.75, a + negative monetary size (an easing) raises the policy rate i on + impact while the ex-ante real rate falls and output rises; use + about 0.61 for a falling policy rate (us-hank-model #22). horizon: Quarters reported (default 20 = 5 years; max 300). variant: 'two_asset' (default — the paper model) or 'one_asset' (fast no-capital variant: monetary/productivity only, no investment diff --git a/integration/tests/test_capabilities.py b/integration/tests/test_capabilities.py index c0ea32526..5410ea462 100644 --- a/integration/tests/test_capabilities.py +++ b/integration/tests/test_capabilities.py @@ -194,3 +194,43 @@ def test_experimental_incidence_tools_are_published_tools_of_registered_models() spec.loader.exec_module(surface) assert set(EXPERIMENTAL_INCIDENCE_TOOLS.values()) <= surface.GOLDEN_TOOLS assert set(EXPERIMENTAL_INCIDENCE_TOOLS) <= set(MODELS) + + +def test_horizon_is_deprecated_and_never_routes(): + """macro #210: the argument stays in the schema so no caller breaks, but + a caller who passes it is told it did nothing.""" + import pytest + + plain = capabilities.recommend("economic_shock", country="us") + assert "horizon_note" not in plain + assert plain["horizon"] is None + for value in ("long run", "next four quarters", "short_run"): + with pytest.warns(DeprecationWarning, match="deprecated and ignored"): + got = capabilities.recommend( + "economic_shock", country="us", horizon=value + ) + assert got["horizon"] == value + assert got["horizon_note"] == capabilities.HORIZON_DEPRECATION_NOTE + # The note is not a "no model" warning, and the routing is unchanged. + assert got["warning"] is None + assert got["candidate_models"] == plain["candidate_models"] + assert all(d["horizon"] for d in got["details"]) + + +def test_recommend_model_tool_keeps_horizon_in_its_schema(): + import asyncio + import pytest + from policyengine_macro import mcp_server + + tools = {t.name: t for t in asyncio.run(mcp_server.mcp.list_tools())} + props = tools["recommend_model"].inputSchema["properties"] + assert "horizon" in props + assert "horizon" not in tools["recommend_model"].inputSchema.get("required", []) + assert "deprecated" in tools["recommend_model"].description + with pytest.warns(DeprecationWarning): + out = mcp_server.recommend_model("forecast", country="uk", horizon="long_run") + assert out["primary_model"] and "horizon_note" in out + import warnings + with warnings.catch_warnings(): + warnings.simplefilter("error") + assert "horizon_note" not in mcp_server.recommend_model("forecast", country="uk") diff --git a/integration/tests/test_define.py b/integration/tests/test_define.py index 537566953..39cdb7633 100644 --- a/integration/tests/test_define.py +++ b/integration/tests/test_define.py @@ -243,3 +243,48 @@ def run(sc, name, **kw): assert out.exit_code == 0, out.output assert "units: MtCO2e per QUARTER" in out.output assert "n/a" in out.output + + +def test_baseline_parameter_mismatch_is_a_labelled_refusal(monkeypatch): + """define-uk-model#36. The class is matched by name, so the fake adapter + deliberately does not export it (an adapter pinned before #36 has no such + attribute), and a subclass must match as well.""" + class BaselineParameterMismatch(ValueError): + pass + + class Narrower(BaselineParameterMismatch): + pass + + for exc in (BaselineParameterMismatch, Narrower): + def run(sc, name, exc=exc, **kw): + raise exc( + f"scenario {name!r}: its cached parameters differ from the " + "Baseline's outside the policy levers: alpha_X" + ) + + sc = _fake_define(monkeypatch, run) + assert not hasattr(sc, "BaselineParameterMismatch") + res = core.define_scenario("fossil_fuel_ban__no_forward_guidance") + assert res["available"] is False + assert res["refused"] == "baseline parameter mismatch" + assert res["scenario"] == "fossil_fuel_ban__no_forward_guidance" + assert "alpha_X" in res["error"] + assert "matched Baseline" in res["how_to_run"] + # Not the generic branch, whose hint is about a run with no departure. + assert "adapter refused" not in res["error"] + assert "define_uk.runner.run()" not in res["how_to_run"] + inc = core.define_scenario_incidence( + "fossil_fuel_ban__no_forward_guidance" + ) + assert inc["refused"] == "baseline parameter mismatch" + assert "define_payload" not in inc["how_to_run"] + + +def test_other_value_errors_keep_the_generic_refusal(monkeypatch): + def run(sc, name, **kw): + raise ValueError("no departure from baseline") + + _fake_define(monkeypatch, run) + res = core.define_scenario("fossil_fuel_ban__no_forward_guidance") + assert "refused" not in res + assert res["error"].startswith("DEFINE-UK adapter refused") diff --git a/integration/tests/test_hank.py b/integration/tests/test_hank.py index 04074e290..85e1c8970 100644 --- a/integration/tests/test_hank.py +++ b/integration/tests/test_hank.py @@ -330,6 +330,25 @@ def test_monetary_and_tfp_units_are_stated_per_quarter_and_in_tfp_terms(): assert "annualised" in doc +def test_monetary_text_says_the_policy_rate_rises_at_the_default_persistence(): + """us-hank-model #22: above a persistence of about 0.75 a two_asset + easing raises the policy rate on impact. The default is 0.9, so the + catalogue and the tool docstring must say so, and must not still call + the response at 0.9 unpinned.""" + from policyengine_macro import mcp_server + + assert core.HANK_DEFAULT_PERSISTENCE == 0.9 + units = " ".join(core._HANK_KIND_INDEX["monetary"]["units"].split()) + doc = " ".join(mcp_server.hank_shock.__doc__.split()) + for text in (units, doc): + assert "us-hank-model #22" in text + assert "0.75" in text and "0.61" in text + assert "ex-ante real rate falls" in text + assert "RAISES the policy rate" in units + assert "raises the policy rate" in doc + assert "not pinned at other" not in doc + + def test_tfp_units_are_scoped_to_the_variant(): """Z_ss is 0.468 in two_asset but 1 in one_asset (sequence_jacobian's one-asset example calibrates Z = 1), so "0.01 ~ 2.1% TFP" must not be diff --git a/integration/tests/test_wiring.py b/integration/tests/test_wiring.py index ef8a8daf4..59a059828 100644 --- a/integration/tests/test_wiring.py +++ b/integration/tests/test_wiring.py @@ -638,3 +638,87 @@ def test_cli_help_header_names_every_subcommand(): header = main.help or "" missing = [name for name in main.commands if name not in header] assert not missing, f"pe-macro --help header omits {missing}" + + +def test_obr_shock_forwards_the_residual_warnings_and_spending_legs(monkeypatch): + """obr #90 sets three more attrs. An MCP caller never sees the frame, so + a borrowing figure that is not the effect of the spending change must + say so in the payload.""" + from policyengine_macro import core + + frames = iter([ + _obr_frame({"nominal_consistent_legs": ["PSCE"]}), + _obr_frame({"subsidy_residual_warning": "LASBHH: subsidies absorb it (#88)"}), + _obr_frame({"procurement_residual_warning": "LAPR: procurement absorbs it (l.377)"}), + ]) + monkeypatch.setattr(core, "_import_obr", lambda: lambda **kw: next(frames)) + monkeypatch.setattr(core, "_obr_window_end", lambda periods: "2025Q2") + + legs = core.obr_shock("CGSB", 1000.0, periods=2) + assert legs["nominal_consistent_legs"] == ["PSCE"] + assert "subsidy_residual_warning" not in legs + assert "procurement_residual_warning" not in legs + + subsidy = core.obr_shock("LASBHH", 1000.0, periods=2) + assert subsidy["subsidy_residual_warning"].startswith("LASBHH") + assert "procurement_residual_warning" not in subsidy + assert "nominal_consistent_legs" not in subsidy + + procurement = core.obr_shock("LAPR", 1000.0, periods=2) + assert "l.377" in procurement["procurement_residual_warning"] + assert "subsidy_residual_warning" not in procurement + + +def test_obr_shock_without_the_new_attrs_adds_no_keys(monkeypatch): + """Before the re-pin the model sets none of the obr #90 warnings; the + adapter must not invent them or fail on their absence.""" + from policyengine_macro import core + + monkeypatch.setattr(core, "_import_obr", lambda: lambda **kw: _obr_frame()) + monkeypatch.setattr(core, "_obr_window_end", lambda periods: "2025Q2") + out = core.obr_shock("CGG", 1000.0, periods=2) + for key in ("subsidy_residual_warning", "procurement_residual_warning", + "nominal_consistent_legs", "la_borrowing_identity", + "la_borrowing_note", "investment_total_warning", + "procurement_offset_note", "procurement_offset_m"): + assert key not in out + + +def test_obr_shock_forwards_the_borrowing_aggregate_labels(monkeypatch): + """obr #95 sets five more attrs saying which borrowing aggregate a shock + moved. la_borrowing_identity is a bool whose False is the informative + value, so it must travel when the model sets it either way.""" + from policyengine_macro import core + + frames = iter([ + _obr_frame({ + "la_borrowing_identity": True, + "la_borrowing_note": "LANB solved from l.526 without KGLAPC", + "procurement_offset_note": "CGP offsets pay (l.377)", + "procurement_offset_m": {"CGP": [-250.0, -251.04, -252.0], + "LAWS": [71.0, 71.0, 71.0]}, + }), + _obr_frame({ + "la_borrowing_identity": False, + "la_borrowing_note": "LANB held on its data path", + "investment_total_warning": "CGIPS: PSNI held (l.520)", + }), + ]) + monkeypatch.setattr(core, "_import_obr", lambda: lambda **kw: next(frames)) + monkeypatch.setattr(core, "_obr_window_end", lambda periods: "2025Q2") + + nics = core.obr_shock("EMPNIC", 1000.0, periods=2) + assert nics["la_borrowing_identity"] is True + assert "KGLAPC" in nics["la_borrowing_note"] + assert "l.377" in nics["procurement_offset_note"] + # Trimmed to the reported rows, like the other per-quarter lists. + assert nics["procurement_offset_m"] == {"CGP": [-250.0, -251.0], + "LAWS": [71.0, 71.0]} + assert "investment_total_warning" not in nics + + invest = core.obr_shock("CGIPS", 1000.0, periods=2) + assert invest["la_borrowing_identity"] is False + assert "data path" in invest["la_borrowing_note"] + assert "PSNI" in invest["investment_total_warning"] + assert "procurement_offset_note" not in invest + assert "procurement_offset_m" not in invest