Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions integration/drift/canaries.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
21 changes: 20 additions & 1 deletion integration/src/policyengine_macro/capabilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from __future__ import annotations

import warnings
from copy import deepcopy


Expand Down Expand Up @@ -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",
Expand All @@ -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()
Expand Down Expand Up @@ -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,
Expand All @@ -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
63 changes: 62 additions & 1 deletion integration/src/policyengine_macro/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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 "
Expand Down Expand Up @@ -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.
Expand Down
16 changes: 12 additions & 4 deletions integration/src/policyengine_macro/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand All @@ -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
Expand Down
40 changes: 40 additions & 0 deletions integration/tests/test_capabilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
45 changes: 45 additions & 0 deletions integration/tests/test_define.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
19 changes: 19 additions & 0 deletions integration/tests/test_hank.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading