Skip to content
Merged
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
1 change: 1 addition & 0 deletions changelog.d/c1-47-empty-dynamic.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A simulation naming a stored dynamic with no parameter values, economy or household alike and their re-runs included, is refused with 400 `dynamic_without_values` instead of being calculated and stored as current law. API v1 stores no dynamic without values, so such a dynamic's values are stored where this release doesn't read them.
11 changes: 8 additions & 3 deletions libs/policyengine-simulation-persistence/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -277,8 +277,9 @@ their own, opened by `from_session_factory` with `bounded_session`:
model, the stored household and each side's policy and dynamic values,
combined (`read_simulation_reform`), together, raising
`UnknownCatalogVersionError`, `UnknownHouseholdError` or `ReportSideError`
for the side whose policy or dynamic is missing in the country, sets
parameters the catalog version lacks, or sets one the other also sets;
for the side whose policy or dynamic is missing in the country, is a
dynamic with no values stored, sets parameters the catalog version lacks, or
sets one the other also sets;
`find_or_create_report` raises `EconomyRecordOutcomeUnknownError` when the
commit fails after the rows were inserted; and `record_report_call` and `fail_unstarted_report` use the
economy report run writes.
Expand Down Expand Up @@ -358,7 +359,11 @@ version lacks raises `MissingPolicyParametersError`, naming each one, and a
policy the country doesn't have raises `UnknownPolicyError`.
`read_dynamic_reform` reads a stored dynamic the same way: a dynamic, like a
policy, belongs to one country, and one the country doesn't have, another
country's included, raises `UnknownDynamicError`. `combine_reforms` joins a
country's included, raises `UnknownDynamicError`. A dynamic with no
parameter values stored raises `DynamicWithoutValuesError` rather than being
applied as current law: API v1 stores no dynamic without values, so its
values are where this release doesn't read them, and a current-law result
would be stored under a key naming the dynamic. `combine_reforms` joins a
simulation's policy and dynamic values, refusing a parameter both set
(`OverlappingReformError`), and `read_simulation_reform` reads both and
joins them, as every simulation does: economy (`read_simulation_values`),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@
ServiceBase,
)
from policyengine_simulation_persistence.policy_reform import (
DynamicWithoutValuesError,
MissingPolicyParametersError,
OverlappingReformError,
PolicyReform,
Expand Down Expand Up @@ -246,6 +247,7 @@
"DecileImpact",
"DecileType",
"Dynamic",
"DynamicWithoutValuesError",
"EconomyCatalogRows",
"EconomyPopulation",
"EconomyRecordOutcomeUnknownError",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
UnknownCatalogVersionError,
)
from policyengine_simulation_persistence.policy_reform import (
DynamicWithoutValuesError,
MissingPolicyParametersError,
OverlappingReformError,
UnknownDynamicError,
Expand All @@ -52,6 +53,7 @@
type SideRefusal = (
UnknownPolicyError
| UnknownDynamicError
| DynamicWithoutValuesError
| MissingPolicyParametersError
| OverlappingReformError
)
Expand Down Expand Up @@ -88,8 +90,8 @@ class ReportSideError(Exception):
"""A report side's policy or dynamic is refused.

``side`` names the side, and ``error`` is the policy reader's refusal:
UnknownPolicyError, UnknownDynamicError, MissingPolicyParametersError or
OverlappingReformError.
UnknownPolicyError, UnknownDynamicError, DynamicWithoutValuesError,
MissingPolicyParametersError or OverlappingReformError.
"""

def __init__(self, side: ReportSide, error: SideRefusal) -> None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,8 @@ def read_simulation_inputs(

Raise UnknownCatalogVersionError, UnknownRegionError or
UnknownDatasetError, or the policy reader's UnknownPolicyError,
UnknownDynamicError or MissingPolicyParametersError, or
OverlappingReformError.
UnknownDynamicError, DynamicWithoutValuesError or
MissingPolicyParametersError, or OverlappingReformError.
"""
with self._transaction() as session:
catalog = read_catalog_rows(session, request)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,8 @@ def read_inputs(
simulation's are (``read_simulation_reform``). Raise
UnknownCatalogVersionError, UnknownHouseholdError, or the readers'
UnknownPolicyError, UnknownDynamicError (a dynamic of another
country included), MissingPolicyParametersError or
OverlappingReformError.
country included), DynamicWithoutValuesError,
MissingPolicyParametersError or OverlappingReformError.
"""
with self._transaction() as session:
catalog_version_id = read_catalog_version_id(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,8 @@ def read_inputs(
(``read_simulation_reform``). Raise UnknownCatalogVersionError or
UnknownHouseholdError, or ReportSideError naming the side whose
policy or dynamic is missing in the country (UnknownPolicyError,
UnknownDynamicError), sets parameters the catalog version lacks
UnknownDynamicError), is a dynamic with no values stored
(DynamicWithoutValuesError), sets parameters the catalog version lacks
(MissingPolicyParametersError) or sets one the other also sets
(OverlappingReformError).
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
way, and a dynamic, like a policy, belongs to one country. A simulation,
economy or household, applies its policy's and its dynamic's values together
(``read_simulation_reform``), and is refused when both set the same parameter
(``combine_reforms``).
(``combine_reforms``). API v1 stores no dynamic without values, so a dynamic
the reader finds no values for is refused rather than applied as current
law: its values are stored where this release doesn't read them.

Each period is a range, ``YYYY-MM-DD.YYYY-MM-DD``, with the dates read in
UTC. A value with no end date follows .py's own rule
Expand Down Expand Up @@ -51,7 +53,7 @@
from datetime import datetime
from uuid import UUID

from sqlalchemy import ColumnElement
from sqlalchemy import ColumnElement, Row
from sqlalchemy.orm import Session

# The last day a value without an end date is applied.
Expand All @@ -71,6 +73,16 @@ class UnknownDynamicError(LookupError):
"""API v1 has no such dynamic in the country."""


class DynamicWithoutValuesError(LookupError):
"""API v1 has the dynamic, but no parameter values are stored for it here.

API v1 refuses to store a dynamic without values, so its values are
stored where this release does not read them. Applying it as current law
would store a result under a key naming the dynamic, which later
requests would reuse.
"""


class MissingPolicyParametersError(ValueError):
"""The policy, or dynamic, sets parameters the calculation's catalog version lacks.

Expand Down Expand Up @@ -150,9 +162,9 @@ def read_policy_reform(
if found is None:
msg = f"{country} has no policy {policy_id}"
raise UnknownPolicyError(msg)
return _read_reform(
return _reform_from_values(
session,
owner=ParameterValue.policy_id == policy_id,
_read_values(session, owner=ParameterValue.policy_id == policy_id),
catalog_version_id=catalog_version_id,
source="policy",
)
Expand All @@ -169,9 +181,11 @@ def read_dynamic_reform(

The periods follow the same rule as a policy's. Raise
UnknownDynamicError when the country has no such dynamic, a dynamic
stored for another country included, and MissingPolicyParametersError,
stored for another country included; DynamicWithoutValuesError when no
parameter value is stored for it; and MissingPolicyParametersError,
naming the dynamic as its source, when ``catalog_version_id`` lacks a
parameter it sets.
parameter it sets. A dynamic whose values are read but whose periods
hold no day, as for values starting after 2200, is read as no change.
"""
found = session.execute(
select(Dynamic.id).where(
Expand All @@ -181,11 +195,15 @@ def read_dynamic_reform(
if found is None:
msg = f"{country} has no dynamic {dynamic_id}"
raise UnknownDynamicError(msg)
return _read_reform(
session,
owner=ParameterValue.dynamic_id == dynamic_id,
catalog_version_id=catalog_version_id,
source="dynamic",
values = _read_values(session, owner=ParameterValue.dynamic_id == dynamic_id)
if not values:
msg = (
f"{country}'s dynamic {dynamic_id} has no parameter values "
"the service can read"
)
raise DynamicWithoutValuesError(msg)
return _reform_from_values(
session, values, catalog_version_id=catalog_version_id, source="dynamic"
)


Expand Down Expand Up @@ -214,6 +232,7 @@ def read_simulation_reform(

None for either reads nothing for it. Raise UnknownPolicyError or
UnknownDynamicError for one the country doesn't have,
DynamicWithoutValuesError for a dynamic with no values stored,
MissingPolicyParametersError for one setting a parameter
``catalog_version_id`` lacks, and OverlappingReformError when both set a
parameter.
Expand Down Expand Up @@ -254,19 +273,11 @@ def combine_reforms(policy: PolicyReform, dynamic: PolicyReform) -> PolicyReform
return {**policy, **dynamic}


def _read_reform(
session: Session,
*,
owner: ColumnElement[bool],
catalog_version_id: UUID,
source: ReformSource,
) -> PolicyReform:
"""Return the values ``owner`` selects, by parameter name and .py's periods.

Raise MissingPolicyParametersError, naming ``source``, when
``catalog_version_id`` lacks a parameter they set.
"""
values = session.execute(
def _read_values(
session: Session, *, owner: ColumnElement[bool]
) -> Sequence[Row[tuple[str, object, datetime, datetime | None]]]:
"""Return the values ``owner`` selects, by parameter name, then start date."""
return session.execute(
select(
Parameter.name,
ParameterValue.value_json,
Expand All @@ -278,6 +289,20 @@ def _read_reform(
.where(owner)
.order_by(Parameter.name, ParameterValue.start_date)
).all()


def _reform_from_values(
session: Session,
values: Sequence[Row[tuple[str, object, datetime, datetime | None]]],
*,
catalog_version_id: UUID,
source: ReformSource,
) -> PolicyReform:
"""Return ``values`` by parameter name and .py's periods (``_read_values``).

Raise MissingPolicyParametersError, naming ``source``, when
``catalog_version_id`` lacks a parameter they set.
"""
names = sorted({row.name for row in values})
available = set(
session.execute(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import pytest
from conftest import act_as_the_service, in_session, rolled_back_transaction
from policyengine_simulation_persistence import (
DynamicWithoutValuesError,
MissingPolicyParametersError,
OverlappingReformError,
SimulationReform,
Expand Down Expand Up @@ -144,6 +145,91 @@ def test_a_dynamic_of_another_country_is_refused(public_api_database_url) -> Non
assert uk_reform == {ELASTICITY: {"2026-01-01.2200-12-31": -0.05}}


@pytest.mark.public_api_schema
def test_a_dynamic_without_values_is_refused_instead_of_read_as_current_law(
public_api_database_url,
) -> None:
"""API v1 stores no dynamic without values, so none read means values sim can't see.

Applying such a dynamic as current law would store that result under a
key naming the dynamic, so the read refuses it, alone or with a policy.
"""
with rolled_back_transaction(public_api_database_url) as connection:
catalog = insert_catalog_version(
connection,
country="us",
model_id=insert_model(connection, "us"),
policyengine_version="6.17.1",
parameter_names=[ELASTICITY, CTC_AMOUNT],
)
policy_id = insert_policy(
connection, catalog, [StoredValue(CTC_AMOUNT, 3_000, START)]
)
dynamic_without_values_id = insert_dynamic(connection, catalog)
act_as_the_service(connection)

with pytest.raises(DynamicWithoutValuesError) as alone:
in_session(
connection,
read_dynamic_reform,
country="us",
dynamic_id=dynamic_without_values_id,
catalog_version_id=catalog.version_id,
)
with pytest.raises(DynamicWithoutValuesError) as with_policy:
in_session(
connection,
read_simulation_reform,
country="us",
policy_id=policy_id,
dynamic_id=dynamic_without_values_id,
catalog_version_id=catalog.version_id,
)

assert str(alone.value) == (
f"us's dynamic {dynamic_without_values_id} has no parameter values "
"the service can read"
)
assert str(with_policy.value) == str(alone.value)
# It is not a missing dynamic: the dynamic exists.
assert not isinstance(alone.value, UnknownDynamicError)


@pytest.mark.public_api_schema
def test_a_dynamic_whose_values_all_start_after_2200_is_read_and_applies_nothing(
public_api_database_url,
) -> None:
"""Its values are read, but no year a calculation can be for is in their periods.

Only a dynamic with no stored values is refused: this one's current-law
result is its own correct result.
"""
with rolled_back_transaction(public_api_database_url) as connection:
catalog = insert_catalog_version(
connection,
country="us",
model_id=insert_model(connection, "us"),
policyengine_version="6.17.1",
parameter_names=[ELASTICITY],
)
dynamic_id = insert_dynamic(
connection,
catalog,
[StoredValue(ELASTICITY, -0.05, datetime(2201, 1, 1, tzinfo=UTC))],
)
act_as_the_service(connection)

reform = in_session(
connection,
read_dynamic_reform,
country="us",
dynamic_id=dynamic_id,
catalog_version_id=catalog.version_id,
)

assert reform == {}


@pytest.mark.public_api_schema
def test_a_dynamic_changing_parameters_the_run_lacks_names_each_of_them(
public_api_database_url,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from policyengine_simulation_persistence import (
CatalogDataset,
CatalogRegion,
DynamicWithoutValuesError,
EconomyCatalogRows,
EconomyPopulation,
EconomyRecordOutcomeUnknownError,
Expand Down Expand Up @@ -419,6 +420,7 @@ def test_a_report_and_a_simulation_are_read_as_they_stand(
("reform", UnknownPolicyError),
("reform", MissingPolicyParametersError),
("baseline", OverlappingReformError),
("reform", DynamicWithoutValuesError),
],
)
def test_a_reports_refused_values_name_the_side_they_belong_to(
Expand All @@ -440,12 +442,16 @@ def test_a_reports_refused_values_name_the_side_they_belong_to(
dynamic_id = insert_dynamic(
connection, economy.catalog, [StoredValue(ELASTICITY, -0.05, START)]
)
dynamic_without_values_id = insert_dynamic(connection, economy.catalog)
act_as_the_service(connection)
refused = {
UnknownDynamicError: SimulationChoice(None, uuid4()),
UnknownPolicyError: SimulationChoice(uuid4(), None),
MissingPolicyParametersError: SimulationChoice(lacking_policy_id, None),
OverlappingReformError: SimulationChoice(overlapping_policy_id, dynamic_id),
DynamicWithoutValuesError: SimulationChoice(
None, dynamic_without_values_id
),
}[error_type]
choices = {"baseline": CURRENT_LAW, "reform": CURRENT_LAW, side: refused}

Expand Down Expand Up @@ -525,6 +531,7 @@ def test_every_side_refusal_is_raised_with_its_side(monkeypatch) -> None:
UnknownDynamicError: UnknownDynamicError("no dynamic"),
MissingPolicyParametersError: MissingPolicyParametersError(["gov.a"]),
OverlappingReformError: OverlappingReformError(["gov.a"]),
DynamicWithoutValuesError: DynamicWithoutValuesError("no values"),
}
assert set(get_args(SideRefusal.__value__)) == set(refusals)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,8 @@
(rerun_definitions, "read_simulation_definition"),
(policy_reform, "read_policy_reform"),
(policy_reform, "read_dynamic_reform"),
(policy_reform, "_read_reform"),
(policy_reform, "_read_values"),
(policy_reform, "_reform_from_values"),
)


Expand Down
Loading
Loading