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-52-dynamic-parameter-tables.changed.md
Original file line number Diff line number Diff line change
@@ -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`.
6 changes: 4 additions & 2 deletions docs/engineering/skills/database-access.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
10 changes: 7 additions & 3 deletions libs/policyengine-simulation-persistence/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion libs/policyengine-simulation-persistence/public-api-commit
Original file line number Diff line number Diff line change
@@ -1 +1 @@
825a9b3c927b7cb06303179efdb38ab596f94d6e
806b1ec9a5a2474e4ed55e50b32f26fdf37ba818
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,8 @@
from policyengine_simulation_persistence.input_tables import (
Dataset,
Dynamic,
DynamicParameter,
DynamicParameterValue,
Household,
Parameter,
ParameterValue,
Expand Down Expand Up @@ -247,6 +249,8 @@
"DecileImpact",
"DecileType",
"Dynamic",
"DynamicParameter",
"DynamicParameterValue",
"DynamicWithoutValuesError",
"EconomyCatalogRows",
"EconomyPopulation",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand All @@ -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"
Expand All @@ -141,15 +145,15 @@ 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):
"""Parameter values a simulation applies beside its policy.

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"
Expand All @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -42,14 +45,16 @@

from policyengine_simulation_persistence.input_tables import (
Dynamic,
DynamicParameter,
DynamicParameterValue,
Parameter,
ParameterValue,
Policy,
)
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

Expand All @@ -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."""

Expand Down Expand Up @@ -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",
)


Expand All @@ -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(
Expand All @@ -195,15 +234,15 @@ 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 "
"the service can read"
)
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
)


Expand Down Expand Up @@ -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.
Expand Down
Loading