diff --git a/changelog.d/c1-52-dynamic-parameter-tables.changed.md b/changelog.d/c1-52-dynamic-parameter-tables.changed.md new file mode 100644 index 000000000..b59f96e4f --- /dev/null +++ b/changelog.d/c1-52-dynamic-parameter-tables.changed.md @@ -0,0 +1 @@ +The simulation service reads a stored dynamic's values from API v1's `dynamic_parameter_values` and their names from `dynamic_parameters`, where API v1 keeps dynamic parameters apart from policy parameters, and its readiness check requires `SELECT` on both tables. It no longer reads `parameter_values.dynamic_id`. diff --git a/docs/engineering/skills/database-access.md b/docs/engineering/skills/database-access.md index 978ba9a4d..fc8c5e123 100644 --- a/docs/engineering/skills/database-access.md +++ b/docs/engineering/skills/database-access.md @@ -175,8 +175,10 @@ and this repository has no migration chain of its own The service connects as its own role, which policyengine-api's privilege manifest grants. - the policyengine-api tables a calculation is read from (`households`, - `policies`, `parameters`, `parameter_values`, `tax_benefit_models` and - `tax_benefit_model_versions`), which the simulation service only reads. + `policies`, `dynamics`, `parameters`, `parameter_values`, + `dynamic_parameters`, `dynamic_parameter_values`, `regions`, `datasets`, + `tax_benefit_models` and `tax_benefit_model_versions`), which the + simulation service only reads. Their read-only models in that library's `input_tables.py` name only the columns the service reads and each table's primary key, apart from the models of the tables it writes. diff --git a/libs/policyengine-simulation-persistence/README.md b/libs/policyengine-simulation-persistence/README.md index da11a05aa..bb837edf2 100644 --- a/libs/policyengine-simulation-persistence/README.md +++ b/libs/policyengine-simulation-persistence/README.md @@ -106,9 +106,10 @@ run's economy output. ## Input tables -`input_tables.py` holds read-only models of the Public API's tables a +`input_tables.py` holds read-only models of API v1's tables a calculation is read from: `households`, `policies`, `dynamics`, `parameters`, -`parameter_values`, `regions`, `datasets`, `tax_benefit_models` and +`parameter_values`, `dynamic_parameters`, `dynamic_parameter_values`, +`regions`, `datasets`, `tax_benefit_models` and `tax_benefit_model_versions`, in `input_metadata`. The service only reads them, with `SELECT`. Each names only the columns the service reads and its primary key, `id`, which a mapped class needs, so they are not models of the whole tables, @@ -357,7 +358,10 @@ the parameters of the catalog version it was saved on, so a calculation on any catalog version applies them by name; a parameter the calculation's 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 +`read_dynamic_reform` reads a stored dynamic the same way, from the tables +API v1 keeps a dynamic's parameters and values in, apart from a policy's +(`dynamic_parameters` and `dynamic_parameter_values`, whose rows with no +dynamic are current law, which the service doesn't read). A dynamic, like a policy, belongs to one country, and one the country doesn't have, another country's included, raises `UnknownDynamicError`. A dynamic with no parameter values stored raises `DynamicWithoutValuesError` rather than being diff --git a/libs/policyengine-simulation-persistence/public-api-commit b/libs/policyengine-simulation-persistence/public-api-commit index efff5b312..62cc37d01 100644 --- a/libs/policyengine-simulation-persistence/public-api-commit +++ b/libs/policyengine-simulation-persistence/public-api-commit @@ -1 +1 @@ -825a9b3c927b7cb06303179efdb38ab596f94d6e +806b1ec9a5a2474e4ed55e50b32f26fdf37ba818 diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/__init__.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/__init__.py index 33a5d9725..fea15cdbc 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/__init__.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/__init__.py @@ -123,6 +123,8 @@ from policyengine_simulation_persistence.input_tables import ( Dataset, Dynamic, + DynamicParameter, + DynamicParameterValue, Household, Parameter, ParameterValue, @@ -247,6 +249,8 @@ "DecileImpact", "DecileType", "Dynamic", + "DynamicParameter", + "DynamicParameterValue", "DynamicWithoutValuesError", "EconomyCatalogRows", "EconomyPopulation", diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/access.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/access.py index c310d27e9..42075f2fd 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/access.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/access.py @@ -55,6 +55,8 @@ "parameters": _READ, "parameter_values": _READ, "dynamics": _READ, + "dynamic_parameters": _READ, + "dynamic_parameter_values": _READ, } ) # The run state the service records for a run whose Modal call it starts: the diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/input_tables.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/input_tables.py index 4c7a2c630..1ccf6ed8d 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/input_tables.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/input_tables.py @@ -117,7 +117,10 @@ class Policy(InputBase): class Parameter(InputBase): - """A catalog version's parameter, named once within it.""" + """A catalog version's policy parameter, named once within it. + + API v1 keeps the parameters a dynamic sets apart, as ``DynamicParameter``. + """ __tablename__ = "parameters" @@ -127,10 +130,11 @@ class Parameter(InputBase): class ParameterValue(InputBase): - """A parameter's value from ``start_date`` until ``end_date``. + """A policy parameter's value from ``start_date`` until ``end_date``. With no end date it applies indefinitely. A policy's own values name it in - ``policy_id``, and a dynamic's in ``dynamic_id``. + ``policy_id``; a value with none is current law, which the service doesn't + read. A dynamic's values are ``DynamicParameterValue`` rows. """ __tablename__ = "parameter_values" @@ -141,7 +145,6 @@ class ParameterValue(InputBase): start_date: Mapped[datetime] = mapped_column(DateTime(timezone=True)) end_date: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) policy_id: Mapped[UUID | None] = mapped_column(Uuid) - dynamic_id: Mapped[UUID | None] = mapped_column(Uuid) class Dynamic(InputBase): @@ -149,7 +152,8 @@ class Dynamic(InputBase): Behavioural responses are an example. API v1 saves a dynamic as it saves a policy, on a country's catalog version; sim reads its ID and its country, - so a simulation refuses another country's dynamic. + so a simulation refuses another country's dynamic. Its values are + ``DynamicParameterValue`` rows. """ __tablename__ = "dynamics" @@ -158,4 +162,37 @@ class Dynamic(InputBase): country_id: Mapped[str] = mapped_column(String(2)) +class DynamicParameter(InputBase): + """A catalog version's dynamic parameter, named once within it. + + API v1 keeps the parameters a dynamic sets, the model's assumptions such + as behavioural responses, apart from the ones a policy sets + (``Parameter``). + """ + + __tablename__ = "dynamic_parameters" + + id: Mapped[UUID] = mapped_column(Uuid, primary_key=True) + name: Mapped[str] = mapped_column(String(512)) + tax_benefit_model_version_id: Mapped[UUID] = mapped_column(Uuid) + + +class DynamicParameterValue(InputBase): + """A dynamic parameter's value from ``start_date`` until ``end_date``. + + With no end date it applies indefinitely. A dynamic's own values name it + in ``dynamic_id``; a value with none is current law, which the service + doesn't read. + """ + + __tablename__ = "dynamic_parameter_values" + + id: Mapped[UUID] = mapped_column(Uuid, primary_key=True) + dynamic_parameter_id: Mapped[UUID] = mapped_column(Uuid) + value_json: Mapped[Any] = mapped_column(JSONB, nullable=False) + start_date: Mapped[datetime] = mapped_column(DateTime(timezone=True)) + end_date: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + dynamic_id: Mapped[UUID | None] = mapped_column(Uuid) + + input_metadata = InputBase.metadata diff --git a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/policy_reform.py b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/policy_reform.py index edfc76b35..f1374277d 100644 --- a/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/policy_reform.py +++ b/libs/policyengine-simulation-persistence/src/policyengine_simulation_persistence/policy_reform.py @@ -6,12 +6,15 @@ applies them by parameter name, as ``{parameter name: {period: value}}``, the shape of API v1's policy JSON that the household functions' contract and the economy requests take. A dynamic's values are stored and read the same -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``). 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. +way, against the catalog version's dynamic parameters, which API v1 keeps +apart from its policy parameters (``dynamic_parameters`` and +``dynamic_parameter_values``), 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``). 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 @@ -42,6 +45,8 @@ from policyengine_simulation_persistence.input_tables import ( Dynamic, + DynamicParameter, + DynamicParameterValue, Parameter, ParameterValue, Policy, @@ -49,7 +54,7 @@ from policyengine_simulation_persistence.tables import LATEST_YEAR if TYPE_CHECKING: - from collections.abc import Sequence + from collections.abc import Callable, Sequence from datetime import datetime from uuid import UUID @@ -65,6 +70,39 @@ type ReformSource = Literal["policy", "dynamic"] +@dataclass(frozen=True) +class _ReformModels: + """The mapped classes one kind of reform's values are read through. + + API v1 keeps a policy's parameters and values apart from a dynamic's. + ``value_of_parameter`` joins a value to its parameter, and ``owned_by`` + selects the values one policy or dynamic sets, by its ID. + """ + + source: ReformSource + parameter_model: type[Parameter | DynamicParameter] + value_model: type[ParameterValue | DynamicParameterValue] + value_of_parameter: ColumnElement[bool] + owned_by: Callable[[UUID], ColumnElement[bool]] + + +_POLICY_MODELS: Final = _ReformModels( + source="policy", + parameter_model=Parameter, + value_model=ParameterValue, + value_of_parameter=Parameter.id == ParameterValue.parameter_id, + owned_by=lambda policy_id: ParameterValue.policy_id == policy_id, +) +_DYNAMIC_MODELS: Final = _ReformModels( + source="dynamic", + parameter_model=DynamicParameter, + value_model=DynamicParameterValue, + value_of_parameter=DynamicParameter.id + == DynamicParameterValue.dynamic_parameter_id, + owned_by=lambda dynamic_id: DynamicParameterValue.dynamic_id == dynamic_id, +) + + class UnknownPolicyError(LookupError): """API v1 has no such policy in the country.""" @@ -164,9 +202,9 @@ def read_policy_reform( raise UnknownPolicyError(msg) return _reform_from_values( session, - _read_values(session, owner=ParameterValue.policy_id == policy_id), + _read_values(session, _POLICY_MODELS, owner_id=policy_id), + _POLICY_MODELS, catalog_version_id=catalog_version_id, - source="policy", ) @@ -184,8 +222,9 @@ def read_dynamic_reform( 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. A dynamic whose values are read but whose periods - hold no day, as for values starting after 2200, is read as no change. + dynamic 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( @@ -195,7 +234,7 @@ def read_dynamic_reform( if found is None: msg = f"{country} has no dynamic {dynamic_id}" raise UnknownDynamicError(msg) - values = _read_values(session, owner=ParameterValue.dynamic_id == dynamic_id) + values = _read_values(session, _DYNAMIC_MODELS, owner_id=dynamic_id) if not values: msg = ( f"{country}'s dynamic {dynamic_id} has no parameter values " @@ -203,7 +242,7 @@ def read_dynamic_reform( ) raise DynamicWithoutValuesError(msg) return _reform_from_values( - session, values, catalog_version_id=catalog_version_id, source="dynamic" + session, values, _DYNAMIC_MODELS, catalog_version_id=catalog_version_id ) @@ -274,47 +313,49 @@ def combine_reforms(policy: PolicyReform, dynamic: PolicyReform) -> PolicyReform def _read_values( - session: Session, *, owner: ColumnElement[bool] + session: Session, models: _ReformModels, *, owner_id: UUID ) -> Sequence[Row[tuple[str, object, datetime, datetime | None]]]: - """Return the values ``owner`` selects, by parameter name, then start date.""" + """Return the values that policy or dynamic sets, by parameter name, then start. + + Only its own values are read, never current law's. + """ + parameter = models.parameter_model + value = models.value_model return session.execute( - select( - Parameter.name, - ParameterValue.value_json, - ParameterValue.start_date, - ParameterValue.end_date, - ) - .select_from(ParameterValue) - .join(Parameter, Parameter.id == ParameterValue.parameter_id) - .where(owner) - .order_by(Parameter.name, ParameterValue.start_date) + select(parameter.name, value.value_json, value.start_date, value.end_date) + .select_from(value) + .join(parameter, models.value_of_parameter) + .where(models.owned_by(owner_id)) + .order_by(parameter.name, value.start_date) ).all() def _reform_from_values( session: Session, values: Sequence[Row[tuple[str, object, datetime, datetime | None]]], + models: _ReformModels, *, 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. + Raise MissingPolicyParametersError, naming the reform's source, when + ``catalog_version_id`` lacks a parameter they set among its parameters of + that kind. """ + parameter = models.parameter_model names = sorted({row.name for row in values}) available = set( session.execute( - select(Parameter.name).where( - Parameter.tax_benefit_model_version_id == catalog_version_id, - Parameter.name.in_(names), + select(parameter.name).where( + parameter.tax_benefit_model_version_id == catalog_version_id, + parameter.name.in_(names), ) ).scalars() ) missing = [name for name in names if name not in available] if missing: - raise MissingPolicyParametersError(missing, source=source) + raise MissingPolicyParametersError(missing, source=models.source) reform: PolicyReform = {} # The rows are ordered by parameter name, then start date, the order # .py takes them in; each value's periods are .py's. diff --git a/libs/policyengine-simulation-persistence/tests/public_api_rows.py b/libs/policyengine-simulation-persistence/tests/public_api_rows.py index e500f7194..efb7f4075 100644 --- a/libs/policyengine-simulation-persistence/tests/public_api_rows.py +++ b/libs/policyengine-simulation-persistence/tests/public_api_rows.py @@ -3,13 +3,18 @@ API v1 writes households, policies, dynamics, their parameter values and its model catalog; the tests insert them as the superuser, in a transaction they roll back, before acting as the simulation service's role. + +API v1 keeps two kinds of parameter apart (C1 · 50): a dynamic's parameters +(``dynamic_parameters``), with their current-law values and every dynamic's +values in ``dynamic_parameter_values``, and a policy's (``parameters``), with +their current-law values and every policy's values in ``parameter_values``. """ from __future__ import annotations from dataclasses import dataclass from hashlib import sha256 -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Final, Literal from uuid import UUID, uuid4 from sqlalchemy import text @@ -22,6 +27,16 @@ from sqlalchemy import Connection, TextClause +# Which of API v1's tables a parameter is stored in. +type ParameterKind = Literal["policy", "dynamic"] + +# API v1's ``DYNAMIC_PARAMETER_PREFIXES``: a name under one of its country's +# prefixes is a dynamic parameter, and any other a policy parameter. +DYNAMIC_PARAMETER_PREFIXES: Final[Mapping[str, tuple[str, ...]]] = { + "uk": ("gov.simulation.", "gov.dynamic."), + "us": ("gov.simulation.", "simulation."), +} + @dataclass(frozen=True) class CatalogVersion: @@ -62,6 +77,73 @@ def insert_model(connection: Connection, country: str) -> UUID: return model_id +def parameter_kind(country: str, parameter_name: str) -> ParameterKind: + """Return the kind of the country's parameter, by API v1's prefixes.""" + if parameter_name.startswith(DYNAMIC_PARAMETER_PREFIXES[country]): + return "dynamic" + return "policy" + + +@dataclass(frozen=True) +class _ParameterStatements: + """The statements that store one kind of parameter and its values. + + ``owned_value`` stores a value a policy or dynamic sets, binding its ID as + ``owner_id``; ``current_law_value`` stores one with no owner. + """ + + parameter: TextClause + parameter_ids: TextClause + current_law_value: TextClause + owned_value: TextClause + + +_PARAMETER_STATEMENTS: Final[Mapping[ParameterKind, _ParameterStatements]] = { + "policy": _ParameterStatements( + parameter=text( + "INSERT INTO public.parameters (id, name, tax_benefit_model_version_id) " + "VALUES (:id, :name, :version_id)" + ), + parameter_ids=text( + "SELECT name, id FROM public.parameters " + "WHERE tax_benefit_model_version_id = :version_id" + ), + current_law_value=text( + "INSERT INTO public.parameter_values " + "(id, parameter_id, value_json, start_date, end_date) " + "VALUES (:id, :parameter_id, :value, :start_date, :end_date)" + ).bindparams(bindparam("value", type_=JSONB)), + owned_value=text( + "INSERT INTO public.parameter_values " + "(id, parameter_id, value_json, start_date, end_date, policy_id) " + "VALUES (:id, :parameter_id, :value, :start_date, :end_date, :owner_id)" + ).bindparams(bindparam("value", type_=JSONB)), + ), + "dynamic": _ParameterStatements( + parameter=text( + "INSERT INTO public.dynamic_parameters " + "(id, name, tax_benefit_model_version_id) " + "VALUES (:id, :name, :version_id)" + ), + parameter_ids=text( + "SELECT name, id FROM public.dynamic_parameters " + "WHERE tax_benefit_model_version_id = :version_id" + ), + current_law_value=text( + "INSERT INTO public.dynamic_parameter_values " + "(id, dynamic_parameter_id, value_json, start_date, end_date) " + "VALUES (:id, :parameter_id, :value, :start_date, :end_date)" + ).bindparams(bindparam("value", type_=JSONB)), + owned_value=text( + "INSERT INTO public.dynamic_parameter_values " + "(id, dynamic_parameter_id, value_json, start_date, end_date, " + "dynamic_id) " + "VALUES (:id, :parameter_id, :value, :start_date, :end_date, :owner_id)" + ).bindparams(bindparam("value", type_=JSONB)), + ), +} + + def insert_catalog_version( connection: Connection, *, @@ -70,7 +152,11 @@ def insert_catalog_version( policyengine_version: str, parameter_names: Iterable[str] = (), ) -> CatalogVersion: - """Insert a catalog version of the model and its named parameters.""" + """Insert a catalog version of the model and its named parameters. + + As API v1's publication does, each name is stored in the table of its + kind (``parameter_kind``). + """ version_id = uuid4() connection.execute( text( @@ -80,68 +166,107 @@ def insert_catalog_version( ), {"id": version_id, "model_id": model_id, "version": policyengine_version}, ) - for name in parameter_names: - connection.execute( - text( - "INSERT INTO public.parameters " - "(id, name, tax_benefit_model_version_id) " - "VALUES (:id, :name, :version_id)" - ), - {"id": uuid4(), "name": name, "version_id": version_id}, - ) - return CatalogVersion( + catalog = CatalogVersion( country=country, model_id=model_id, version_id=version_id, policyengine_version=policyengine_version, ) + for name in parameter_names: + insert_parameter(connection, catalog, name, kind=parameter_kind(country, name)) + return catalog + + +def insert_current_law_values( + connection: Connection, catalog: CatalogVersion, values: Iterable[StoredValue] +) -> None: + """Insert current-law values of ``catalog``'s parameters, as its publication does. + + Each value names a parameter of the catalog version and is stored with no + owner, beside the other values of its parameter's kind. + """ + for stored in values: + kind = parameter_kind(catalog.country, stored.parameter_name) + _insert_value( + connection, + _PARAMETER_STATEMENTS[kind].current_law_value, + stored, + parameter_id=_parameter_ids(connection, catalog.version_id, kind)[ + stored.parameter_name + ], + ) + + +def insert_parameter( + connection: Connection, catalog: CatalogVersion, name: str, *, kind: ParameterKind +) -> UUID: + """Insert a parameter of ``catalog`` named ``name`` in the table of ``kind``. + + ``insert_catalog_version`` stores each name in the table of its own kind, + as API v1 does. A test of a policy and a dynamic that set one parameter + adds the name to the other table with this, a state API v1 never stores. + """ + parameter_id = uuid4() + connection.execute( + _PARAMETER_STATEMENTS[kind].parameter, + {"id": parameter_id, "name": name, "version_id": catalog.version_id}, + ) + return parameter_id -def _parameter_ids(connection: Connection, version_id: UUID) -> dict[str, UUID]: +def _parameter_ids( + connection: Connection, version_id: UUID, kind: ParameterKind +) -> dict[str, UUID]: rows = connection.execute( - text( - "SELECT name, id FROM public.parameters " - "WHERE tax_benefit_model_version_id = :version_id" - ), - {"version_id": version_id}, + _PARAMETER_STATEMENTS[kind].parameter_ids, {"version_id": version_id} ) return {row.name: row.id for row in rows} -@dataclass(frozen=True) -class _SavedReformStatements: - """The two inserts that save a policy or a dynamic and the values it sets. +def _insert_value( + connection: Connection, + statement: TextClause, + stored: StoredValue, + *, + parameter_id: UUID, + owner_id: UUID | None = None, +) -> None: + connection.execute( + statement, + { + "id": uuid4(), + "parameter_id": parameter_id, + "value": stored.value, + "start_date": stored.start_date, + "end_date": stored.end_date, + **({} if owner_id is None else {"owner_id": owner_id}), + }, + ) - ``values`` binds the saved row's ID as ``saved_id``. - """ + +@dataclass(frozen=True) +class _SavedReform: + """How a policy or dynamic is saved: its row and the kind of parameter it sets.""" row: TextClause - values: TextClause + parameter_kind: ParameterKind -_POLICY_STATEMENTS = _SavedReformStatements( +_POLICY = _SavedReform( row=text( "INSERT INTO public.policies (id, country_id, tax_benefit_model_id, " "tax_benefit_model_version_id, canonicalization_version, content_hash) " "VALUES (:id, :country, :model_id, :version_id, 1, :content_hash)" ), - values=text( - "INSERT INTO public.parameter_values " - "(id, parameter_id, value_json, start_date, end_date, policy_id) " - "VALUES (:id, :parameter_id, :value, :start_date, :end_date, :saved_id)" - ).bindparams(bindparam("value", type_=JSONB)), + parameter_kind="policy", ) -_DYNAMIC_STATEMENTS = _SavedReformStatements( +_DYNAMIC = _SavedReform( row=text( "INSERT INTO public.dynamics (id, country_id, tax_benefit_model_id, " "tax_benefit_model_version_id, canonicalization_version, content_hash) " "VALUES (:id, :country, :model_id, :version_id, 1, :content_hash)" ), - values=text( - "INSERT INTO public.parameter_values " - "(id, parameter_id, value_json, start_date, end_date, dynamic_id) " - "VALUES (:id, :parameter_id, :value, :start_date, :end_date, :saved_id)" - ).bindparams(bindparam("value", type_=JSONB)), + parameter_kind="dynamic", ) @@ -149,17 +274,18 @@ def _insert_saved_reform( connection: Connection, catalog: CatalogVersion, values: Iterable[StoredValue], - statements: _SavedReformStatements, + saved: _SavedReform, ) -> UUID: """Insert a policy or dynamic saved on ``catalog`` and the values it sets. API v1 stores both alike: on the catalog's country, model and version, with a canonicalization version and a content hash. Each value names a - parameter of that catalog version by name. + parameter of that catalog version by name, among the parameters of the + kind the policy or dynamic sets. """ saved_id = uuid4() connection.execute( - statements.row, + saved.row, { "id": saved_id, "country": catalog.country, @@ -168,18 +294,15 @@ def _insert_saved_reform( "content_hash": _stand_in_content_hash(saved_id), }, ) - parameter_ids = _parameter_ids(connection, catalog.version_id) + statements = _PARAMETER_STATEMENTS[saved.parameter_kind] + parameter_ids = _parameter_ids(connection, catalog.version_id, saved.parameter_kind) for stored in values: - connection.execute( - statements.values, - { - "id": uuid4(), - "parameter_id": parameter_ids[stored.parameter_name], - "value": stored.value, - "start_date": stored.start_date, - "end_date": stored.end_date, - "saved_id": saved_id, - }, + _insert_value( + connection, + statements.owned_value, + stored, + parameter_id=parameter_ids[stored.parameter_name], + owner_id=saved_id, ) return saved_id @@ -189,8 +312,11 @@ def insert_policy( catalog: CatalogVersion, values: Iterable[StoredValue] = (), ) -> UUID: - """Insert a policy saved on ``catalog`` and the values it sets.""" - return _insert_saved_reform(connection, catalog, values, _POLICY_STATEMENTS) + """Insert a policy saved on ``catalog`` and the values it sets. + + Each value names a policy parameter of ``catalog``. + """ + return _insert_saved_reform(connection, catalog, values, _POLICY) def insert_dynamic( @@ -198,8 +324,11 @@ def insert_dynamic( catalog: CatalogVersion, values: Iterable[StoredValue] = (), ) -> UUID: - """Insert a dynamic saved on ``catalog`` and the values it sets.""" - return _insert_saved_reform(connection, catalog, values, _DYNAMIC_STATEMENTS) + """Insert a dynamic saved on ``catalog`` and the values it sets. + + Each value names a dynamic parameter of ``catalog``. + """ + return _insert_saved_reform(connection, catalog, values, _DYNAMIC) def insert_dataset( diff --git a/libs/policyengine-simulation-persistence/tests/test_access.py b/libs/policyengine-simulation-persistence/tests/test_access.py index 197c6c9c3..bdd4b4311 100644 --- a/libs/policyengine-simulation-persistence/tests/test_access.py +++ b/libs/policyengine-simulation-persistence/tests/test_access.py @@ -54,6 +54,8 @@ "parameters", "parameter_values", "dynamics", + "dynamic_parameters", + "dynamic_parameter_values", ) # The run state the service records for a run whose Modal call it starts. CALL_START_COLUMNS = frozenset( diff --git a/libs/policyengine-simulation-persistence/tests/test_dynamic_reform.py b/libs/policyengine-simulation-persistence/tests/test_dynamic_reform.py index 309bb38da..2fc935866 100644 --- a/libs/policyengine-simulation-persistence/tests/test_dynamic_reform.py +++ b/libs/policyengine-simulation-persistence/tests/test_dynamic_reform.py @@ -21,13 +21,16 @@ UnknownDynamicError, combine_reforms, read_dynamic_reform, + read_policy_reform, read_simulation_reform, ) from public_api_rows import ( StoredValue, insert_catalog_version, + insert_current_law_values, insert_dynamic, insert_model, + insert_parameter, insert_policy, ) @@ -195,6 +198,56 @@ def test_a_dynamic_without_values_is_refused_instead_of_read_as_current_law( assert not isinstance(alone.value, UnknownDynamicError) +@pytest.mark.public_api_schema +def test_a_dynamics_parameters_current_law_values_are_never_read_as_its_own( + public_api_database_url, +) -> None: + """Current law is a dynamic parameter's value with no dynamic (C1 · 50). + + A dynamic is read as the values it sets alone, and one setting none is + refused although its catalog version's dynamic parameters have values. + """ + 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, SUBSTITUTION], + ) + insert_current_law_values( + connection, + catalog, + [ + StoredValue(ELASTICITY, 0, datetime(2015, 1, 1, tzinfo=UTC)), + StoredValue(SUBSTITUTION, 0, datetime(2015, 1, 1, tzinfo=UTC)), + ], + ) + dynamic_id = insert_dynamic( + connection, catalog, [StoredValue(ELASTICITY, -0.05, START, END)] + ) + dynamic_without_values_id = insert_dynamic(connection, catalog) + act_as_the_service(connection) + + reform = in_session( + connection, + read_dynamic_reform, + country="us", + dynamic_id=dynamic_id, + catalog_version_id=catalog.version_id, + ) + with pytest.raises(DynamicWithoutValuesError): + in_session( + connection, + read_dynamic_reform, + country="us", + dynamic_id=dynamic_without_values_id, + catalog_version_id=catalog.version_id, + ) + + assert reform == {ELASTICITY: {"2026-01-01.2027-12-31": -0.05}} + + @pytest.mark.public_api_schema def test_a_dynamic_whose_values_all_start_after_2200_is_read_and_applies_nothing( public_api_database_url, @@ -274,6 +327,64 @@ def test_a_dynamic_changing_parameters_the_run_lacks_names_each_of_them( assert str(refusal.value).startswith("the dynamic sets parameters") +@pytest.mark.public_api_schema +def test_each_reforms_parameters_are_found_among_its_own_kind_alone( + public_api_database_url, +) -> None: + """A version that has a name only as the other kind of parameter lacks it. + + API v1 keeps a dynamic's parameters apart from a policy's (C1 · 50), so + the running version's dynamic parameters are the ones a dynamic may set, + and its policy parameters the ones a policy may set. + """ + with rolled_back_transaction(public_api_database_url) as connection: + model_id = insert_model(connection, "us") + saved_on = insert_catalog_version( + connection, + country="us", + model_id=model_id, + policyengine_version="6.16.0", + parameter_names=[ELASTICITY, CTC_AMOUNT], + ) + running = insert_catalog_version( + connection, + country="us", + model_id=model_id, + policyengine_version="6.17.1", + ) + insert_parameter(connection, running, ELASTICITY, kind="policy") + insert_parameter(connection, running, CTC_AMOUNT, kind="dynamic") + dynamic_id = insert_dynamic( + connection, saved_on, [StoredValue(ELASTICITY, -0.05, START)] + ) + policy_id = insert_policy( + connection, saved_on, [StoredValue(CTC_AMOUNT, 3_000, START)] + ) + act_as_the_service(connection) + + with pytest.raises(MissingPolicyParametersError) as dynamic_refusal: + in_session( + connection, + read_dynamic_reform, + country="us", + dynamic_id=dynamic_id, + catalog_version_id=running.version_id, + ) + with pytest.raises(MissingPolicyParametersError) as policy_refusal: + in_session( + connection, + read_policy_reform, + country="us", + policy_id=policy_id, + catalog_version_id=running.version_id, + ) + + assert dynamic_refusal.value.parameter_names == (ELASTICITY,) + assert dynamic_refusal.value.source == "dynamic" + assert policy_refusal.value.parameter_names == (CTC_AMOUNT,) + assert policy_refusal.value.source == "policy" + + @pytest.mark.public_api_schema def test_a_simulations_policy_and_dynamic_are_read_as_one_reform( public_api_database_url, @@ -292,6 +403,9 @@ def test_a_simulations_policy_and_dynamic_are_read_as_one_reform( dynamic_id = insert_dynamic( connection, catalog, [StoredValue(ELASTICITY, -0.05, START, END)] ) + # API v1 stores each name in one kind's table; a dynamic setting the + # policy's parameter needs the name in both. + insert_parameter(connection, catalog, CTC_AMOUNT, kind="dynamic") overlapping_dynamic_id = insert_dynamic( connection, catalog, [StoredValue(CTC_AMOUNT, 2_000, START)] ) diff --git a/libs/policyengine-simulation-persistence/tests/test_economy_run_store.py b/libs/policyengine-simulation-persistence/tests/test_economy_run_store.py index 2e0d9cd0c..ece2bfd75 100644 --- a/libs/policyengine-simulation-persistence/tests/test_economy_run_store.py +++ b/libs/policyengine-simulation-persistence/tests/test_economy_run_store.py @@ -54,7 +54,13 @@ economy_run_store, ) from policyengine_simulation_persistence.economy_inputs import read_catalog_rows -from public_api_rows import StoredValue, insert_dataset, insert_dynamic, insert_policy +from public_api_rows import ( + StoredValue, + insert_dataset, + insert_dynamic, + insert_parameter, + insert_policy, +) from sqlalchemy import text from sqlalchemy.exc import OperationalError from transaction_fakes import CommitFailingTransaction, RecordingSession @@ -299,6 +305,9 @@ def test_values_the_running_version_lacks_or_both_set_are_refused( replace(saved_on.catalog, country="us"), [StoredValue(CTC_AMOUNT, 3_000, START)], ) + # API v1 stores each name in one kind's table; a policy setting the + # dynamic's parameter needs the name in both. + insert_parameter(connection, economy.catalog, ELASTICITY, kind="policy") overlapping_policy_id = insert_policy( connection, economy.catalog, [StoredValue(ELASTICITY, -0.1, START)] ) @@ -436,6 +445,9 @@ def test_a_reports_refused_values_name_the_side_they_belong_to( replace(saved_on.catalog, country="us"), [StoredValue(CTC_AMOUNT, 3_000, START)], ) + # API v1 stores each name in one kind's table; a policy setting the + # dynamic's parameter needs the name in both. + insert_parameter(connection, economy.catalog, ELASTICITY, kind="policy") overlapping_policy_id = insert_policy( connection, economy.catalog, [StoredValue(ELASTICITY, -0.1, START)] ) diff --git a/libs/policyengine-simulation-persistence/tests/test_household_job_store.py b/libs/policyengine-simulation-persistence/tests/test_household_job_store.py index 29a132c3a..e79f85e9d 100644 --- a/libs/policyengine-simulation-persistence/tests/test_household_job_store.py +++ b/libs/policyengine-simulation-persistence/tests/test_household_job_store.py @@ -42,6 +42,7 @@ insert_dynamic, insert_household, insert_model, + insert_parameter, insert_policy, ) from sqlalchemy import text @@ -211,6 +212,9 @@ def test_a_dynamic_that_cannot_be_applied_is_refused(public_api_database_url) -> policy_id = insert_policy( connection, catalog, [StoredValue(CTC_AMOUNT, 3_000, START)] ) + # API v1 stores each name in one kind's table; a dynamic setting the + # policy's parameter needs the name in both. + insert_parameter(connection, catalog, CTC_AMOUNT, kind="dynamic") overlapping_dynamic_id = insert_dynamic( connection, catalog, [StoredValue(CTC_AMOUNT, 2_000, START)] ) diff --git a/libs/policyengine-simulation-persistence/tests/test_household_report_store.py b/libs/policyengine-simulation-persistence/tests/test_household_report_store.py index 68b2a2049..44642df24 100644 --- a/libs/policyengine-simulation-persistence/tests/test_household_report_store.py +++ b/libs/policyengine-simulation-persistence/tests/test_household_report_store.py @@ -37,6 +37,7 @@ insert_dynamic, insert_household, insert_model, + insert_parameter, insert_policy, ) from sqlalchemy import text @@ -194,6 +195,9 @@ def test_a_sides_dynamic_of_another_country_overlapping_or_without_values_is_ref uk_dynamic_id = insert_dynamic( connection, uk_catalog, [StoredValue(ELASTICITY, -0.05, START)] ) + # API v1 stores each name in one kind's table; a policy setting the + # dynamic's parameter needs the name in both. + insert_parameter(connection, catalog, ELASTICITY, kind="policy") policy_id = insert_policy( connection, catalog, [StoredValue(ELASTICITY, -0.1, START)] ) diff --git a/libs/policyengine-simulation-persistence/tests/test_mapped_classes.py b/libs/policyengine-simulation-persistence/tests/test_mapped_classes.py index 00733235e..27cf3fa85 100644 --- a/libs/policyengine-simulation-persistence/tests/test_mapped_classes.py +++ b/libs/policyengine-simulation-persistence/tests/test_mapped_classes.py @@ -22,6 +22,8 @@ Dataset, DecileImpact, Dynamic, + DynamicParameter, + DynamicParameterValue, Household, HouseholdJob, HouseholdJobStatus, @@ -93,6 +95,8 @@ "parameters": Parameter, "parameter_values": ParameterValue, "dynamics": Dynamic, + "dynamic_parameters": DynamicParameter, + "dynamic_parameter_values": DynamicParameterValue, } RESULT_CLASSES = { "labor_supply_responses": LaborSupplyResponse, @@ -209,6 +213,38 @@ def test_the_keys_to_api_v1s_tables_name_the_referenced_classes() -> None: assert named_tables == referenced +def test_policy_values_and_dynamic_values_are_mapped_apart() -> None: + """API v1 keeps a dynamic's parameters and values in their own tables (C1 · 50). + + So ``ParameterValue`` maps no ``dynamic_id``, which C1 · 53 drops from + API v1's table, and a dynamic's values name its own parameters. + """ + column_names = { + mapped_class: [column.name for column in mapped_class.__table__.columns] + for mapped_class in (ParameterValue, DynamicParameter, DynamicParameterValue) + } + + assert column_names == { + ParameterValue: [ + "id", + "parameter_id", + "value_json", + "start_date", + "end_date", + "policy_id", + ], + DynamicParameter: ["id", "name", "tax_benefit_model_version_id"], + DynamicParameterValue: [ + "id", + "dynamic_parameter_id", + "value_json", + "start_date", + "end_date", + "dynamic_id", + ], + } + + def test_every_mapper_configures() -> None: configure_mappers() diff --git a/libs/policyengine-simulation-persistence/tests/test_tables.py b/libs/policyengine-simulation-persistence/tests/test_tables.py index 06adea473..c5b9b38ff 100644 --- a/libs/policyengine-simulation-persistence/tests/test_tables.py +++ b/libs/policyengine-simulation-persistence/tests/test_tables.py @@ -268,6 +268,8 @@ def test_the_input_models_are_tables_the_service_reads() -> None: "dynamics", "parameters", "parameter_values", + "dynamic_parameters", + "dynamic_parameter_values", "regions", "datasets", "tax_benefit_models", diff --git a/rules/fixtures/sim.persistence.missing-privileges-reported/bad_grants.txt b/rules/fixtures/sim.persistence.missing-privileges-reported/bad_grants.txt index a735a5ac7..fbf6fa48d 100644 --- a/rules/fixtures/sim.persistence.missing-privileges-reported/bad_grants.txt +++ b/rules/fixtures/sim.persistence.missing-privileges-reported/bad_grants.txt @@ -23,6 +23,8 @@ SELECT datasets SELECT parameters SELECT parameter_values SELECT dynamics +SELECT dynamic_parameters +SELECT dynamic_parameter_values UPDATE simulation_runs completed_at UPDATE simulation_runs error_message UPDATE simulation_runs modal_call_id diff --git a/rules/fixtures/sim.persistence.missing-privileges-reported/good_grants.txt b/rules/fixtures/sim.persistence.missing-privileges-reported/good_grants.txt index afbe388ba..fe1869957 100644 --- a/rules/fixtures/sim.persistence.missing-privileges-reported/good_grants.txt +++ b/rules/fixtures/sim.persistence.missing-privileges-reported/good_grants.txt @@ -22,6 +22,8 @@ SELECT datasets SELECT parameters SELECT parameter_values SELECT dynamics +SELECT dynamic_parameters +SELECT dynamic_parameter_values UPDATE simulation_runs completed_at UPDATE simulation_runs error_message UPDATE simulation_runs modal_call_id