diff --git a/changelog.d/stop-mapping-report-per-user-columns.removed.md b/changelog.d/stop-mapping-report-per-user-columns.removed.md new file mode 100644 index 000000000..579927b93 --- /dev/null +++ b/changelog.d/stop-mapping-report-per-user-columns.removed.md @@ -0,0 +1 @@ +`/v2/reports` run items and budget-window run items no longer have a `trigger` field: a run is shared between requests, and each user's trigger is on their record of it. API v1 no longer selects or writes the per-user columns of reports, report runs and budget-window runs, which a later database revision drops. diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 6e4e8fc24..e305f1486 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -309,13 +309,17 @@ and `refused(session, ...)`. `add_row(session, Model, **values)`, given a mapped class. A JSON column takes the Python value, such as `[2026]`, not its JSON text. - **Columns a mapper leaves out**: a column kept in its table but left out of - the model's mapper (`exclude_properties`), such as a report run's four older - cliff columns until a revision drops them, has no statement through the - model: `update(Model).values(column=...)` raises `AttributeError`. A test - that sets one maps it on a class of a registry of its own, as - `tests.integration.privilege_statements.ReportRunColumns` does, and reads it - from SQLite's copy of the schema (`StoredTable.columns` in - `tests.unit.v2.v2_schema_reading`) or from the database's `Inspector`. + the model's mapper (`exclude_properties`), such as a report's `label`, + `description` and `user_id`, a report run's `trigger` and four older cliff + columns, and a budget-window run's `trigger` until a revision drops them, + has no statement through the model: `update(Model).values(column=...)` + raises `AttributeError`, a constructor value is never stored, and + `Model.column` is the table's Core column, which the rule rules out even + in a `select`. A test that sets or selects one maps it on a class of a + registry of its own, as `tests.integration.privilege_statements`' + `ReportColumns`, `ReportRunColumns` and `BudgetWindowRunColumns` do, and + reads its declaration from SQLite's copy of the schema (`StoredTable.columns` + in `tests.unit.v2.v2_schema_reading`) or from the database's `Inspector`. - **Postgres functions**: `func`, as in `session.execute(select(func.current_database(), func.current_user()))`, `func.pg_backend_pid()` and `func.has_table_privilege(...)`. @@ -1221,10 +1225,9 @@ from there gives the same operations. - The per-user columns of shared rows become nullable, with no default: `reports.label`, `report_runs.trigger` and `budget_window_runs.trigger` (`reports.description` and `user_id` already were). A shared row describes - no one caller, so the simulation service stops writing them, and a later - revision drops them; until then the report read and run lists answer a - missing label or trigger as null. A user's trigger is on their - `user_report_run_associations` row. + no one caller, so the simulation service stops writing them, API v1's models + leave them out, and a later revision drops them. A user's trigger is on + their `user_report_run_associations` row. - `user_report_run_associations` records each user's request for a report run: the user (`CASCADE`), the run (`RESTRICT`, so a run a user asked for can't be deleted), `requested_at` (required, with no default: the writer diff --git a/policyengine_api/data/v2/models/reports.py b/policyengine_api/data/v2/models/reports.py index f167e198a..6bf2e64c3 100644 --- a/policyengine_api/data/v2/models/reports.py +++ b/policyengine_api/data/v2/models/reports.py @@ -28,7 +28,6 @@ ) from policyengine_api.data.v2.models.policies import Policy from policyengine_api.data.v2.models.simulations import Simulation -from policyengine_api.data.v2.models.users import User if TYPE_CHECKING: from policyengine_api.data.v2.models.run_results import ( @@ -61,7 +60,10 @@ class ReportRunStatus(StrEnum): class ReportRunTrigger(StrEnum): - """Why a report run started: the report's first run, a manual or a system rerun.""" + """Why a user asked for a report run: the report's creation or a re-run. + + ``system`` remains in the database type; no user's record may hold it. + """ INITIAL = "initial" MANUAL = "manual" @@ -71,13 +73,21 @@ class ReportRunTrigger(StrEnum): class Report(TimestampedModel, table=True): """Stable report definition; execution state belongs to ReportRun. - The simulation service writes reports, and the Public API the user, model, - policy, household, dataset and region a report names; each service writes - only its own tables, and the foreign keys between them stay. Deleting the - user, policy, dataset or region clears the reference, which for the user - is found through ``user_id``'s index; the model and household can't be + The simulation service writes reports, and API v1 the model, policy, + household, dataset and region a report names; each service writes only its + own tables, and the foreign keys between them stay. Deleting the policy, + dataset or region clears the reference; the model and household can't be deleted while a report names them. + A report is shared by everyone who asks for it, so it describes no one + caller: a report's name and description are on each user's saved report. + The table's ``label``, ``description`` and ``user_id`` stay SQLModel + fields, as rule ``api.data.orm-only`` requires of every column, and + ``exclude_properties`` leaves them out of the mapper, so API v1 neither + loads nor writes them: a value given to the constructor is never stored, + and the class attributes are the table's columns, not values to read. A + release keeps working while a later revision drops them. + The simulation service finds a report by ``definition_key``, the SHA-256 of what it compares (its country, type, each side's policy and dynamic, the dataset name, region code, year and SPM selection both sides share, @@ -89,6 +99,9 @@ class Report(TimestampedModel, table=True): """ __tablename__ = "reports" + __mapper_args__: ClassVar[dict[str, Any]] = { + "exclude_properties": ("label", "description", "user_id") + } __table_args__ = ( sa.CheckConstraint( "year IS NULL OR year BETWEEN 1900 AND 2200", @@ -117,12 +130,13 @@ class Report(TimestampedModel, table=True): sa.Index("ix_reports_dataset_independent_key", "dataset_independent_key"), ) - # Per-user: nullable until a later revision drops it, since a shared report - # describes no one caller. + # In the table but left out of the mapper (``exclude_properties``) until a + # revision drops them. label: str | None = Field(default=None, max_length=255) description: str | None = None country: str = Field(max_length=16) type: str | None = Field(default=None, max_length=128) + # In the table but left out of the mapper, like ``label``. user_id: UUID | None = Field( default=None, foreign_key="users.id", @@ -171,7 +185,6 @@ class Report(TimestampedModel, table=True): definition_key: str | None = Field(default=None, max_length=64) dataset_independent_key: str | None = Field(default=None, max_length=64) - user: User | None = Relationship(back_populates="reports") tax_benefit_model: TaxBenefitModel = Relationship(back_populates="reports") policy: Policy | None = Relationship(back_populates="reports") baseline_simulation: Simulation | None = Relationship( @@ -217,6 +230,7 @@ class BudgetWindowRun(TimestampedModel, table=True): """ __tablename__ = "budget_window_runs" + __mapper_args__: ClassVar[dict[str, Any]] = {"exclude_properties": ("trigger",)} __table_args__ = ( sa.UniqueConstraint("id", "report_id", name="uq_budget_window_runs_id_report"), sa.CheckConstraint( @@ -247,8 +261,9 @@ class BudgetWindowRun(TimestampedModel, table=True): index=True, ) policyengine_version: str | None = Field(default=None, max_length=128) - # Per-user: nullable until a later revision drops it, since a shared run - # answers more than one request; each user's trigger is on their record. + # In the table but left out of the mapper (``exclude_properties``) until a + # revision drops it: a shared run answers more than one request, and each + # user's trigger is on their record of it. trigger: ReportRunTrigger | None = Field( default=None, sa_type=enum_type(ReportRunTrigger, "v2_report_run_trigger"), @@ -280,13 +295,13 @@ class ReportRun(TimestampedModel, table=True): and ``year``, at most one report run per year of a window run. ``spm_provenance`` is the SPM receipt and ``data_version`` the data release it used. Its labour supply response has its own two tables. Its cliff impact - is its two simulation runs' (``CliffImpact``). The table's four older cliff - columns stay SQLModel fields, as rule ``api.data.orm-only`` requires of every - column, and ``exclude_properties`` leaves them out of the mapper, so API v1 - neither loads nor writes them: a value given to the constructor is never - stored, and the class attributes are the table's columns, not values to - read. This covers only those four: ``trigger`` is still mapped, so it must - stop being mapped in an earlier release before a revision drops it. + is its two simulation runs' (``CliffImpact``), and each user's trigger is on + their record of the run. The table's four older cliff columns and + ``trigger`` stay SQLModel fields, as rule ``api.data.orm-only`` requires of + every column, and ``exclude_properties`` leaves them out of the mapper, so + API v1 neither loads nor writes them: a value given to the constructor is + never stored, and the class attributes are the table's columns, not values + to read. A release keeps working while a later revision drops them. Outside budget windows, a report has at most one run that hasn't failed for each pair of package versions, which identical requests join; a @@ -297,6 +312,7 @@ class ReportRun(TimestampedModel, table=True): __tablename__ = "report_runs" __mapper_args__: ClassVar[dict[str, Any]] = { "exclude_properties": ( + "trigger", "baseline_cliff_gap", "baseline_cliff_share", "reform_cliff_gap", @@ -388,8 +404,9 @@ class ReportRun(TimestampedModel, table=True): default=ReportRunStatus.PENDING, sa_type=enum_type(ReportRunStatus, "v2_report_run_status"), ) - # Per-user: nullable until a later revision drops it, since a shared run - # answers more than one request; each user's trigger is on their record. + # In the table but left out of the mapper (``exclude_properties``) until a + # revision drops it: a shared run answers more than one request, and each + # user's trigger is on their record of it. trigger: ReportRunTrigger | None = Field( default=None, sa_type=enum_type(ReportRunTrigger, "v2_report_run_trigger"), diff --git a/policyengine_api/data/v2/models/users.py b/policyengine_api/data/v2/models/users.py index 0a4d55018..ee923cb08 100644 --- a/policyengine_api/data/v2/models/users.py +++ b/policyengine_api/data/v2/models/users.py @@ -27,7 +27,6 @@ UserReportRunAssociation, UserSimulationAssociation, ) - from policyengine_api.data.v2.models.reports import Report class UserType(StrEnum): @@ -79,8 +78,8 @@ class User(IdentifiedModel, table=True): A signed-in user, of any type but ``unauthenticated``, always has a primary country. Deleting a user deletes their sign-in identities, saved - associations and records of the report runs they asked for; reports they - own are kept without an owner. + associations and records of the report runs they asked for; the reports + and runs themselves are shared and stay. """ __tablename__ = "users" @@ -115,7 +114,6 @@ class User(IdentifiedModel, table=True): sa_column_kwargs={"server_default": UserType.STANDARD.value}, ) - reports: list["Report"] = Relationship(back_populates="user") identities: list["UserIdentity"] = Relationship( back_populates="user", cascade_delete=True, diff --git a/policyengine_api/data/v2/report_runs.py b/policyengine_api/data/v2/report_runs.py index f1980aadd..61c14fc07 100644 --- a/policyengine_api/data/v2/report_runs.py +++ b/policyengine_api/data/v2/report_runs.py @@ -20,7 +20,6 @@ Report, ReportRun, ReportRunStatus, - ReportRunTrigger, ) from policyengine_api.data.v2.models.base import utc_now @@ -113,7 +112,6 @@ def create_report_run( *, report_id: UUID, inputs: ReportRunInputs, - trigger: ReportRunTrigger, idempotency_key: UUID | None = None, ) -> ReportRun: """Create one run, or return the run for a retried idempotent request. @@ -122,9 +120,6 @@ def create_report_run( simulation runs that attempt named. """ _locked_report(session, report_id) - if trigger is ReportRunTrigger.MANUAL and idempotency_key is None: - msg = "manual report reruns require an idempotency key" - raise ValueError(msg) versions = inputs.versions if not versions.country_package_version or not versions.policyengine_version: msg = "report run package versions must be non-empty" @@ -136,7 +131,6 @@ def create_report_run( reform_simulation_run_id=inputs.simulation_runs.reform_simulation_run_id, country_package_version=versions.country_package_version, policyengine_version=versions.policyengine_version, - trigger=trigger, idempotency_key=idempotency_key, ) if idempotency_key is None: diff --git a/policyengine_api/fastapi_routes/v2/reports/response_models.py b/policyengine_api/fastapi_routes/v2/reports/response_models.py index 600213ccf..4b1ea4958 100644 --- a/policyengine_api/fastapi_routes/v2/reports/response_models.py +++ b/policyengine_api/fastapi_routes/v2/reports/response_models.py @@ -56,15 +56,11 @@ class ReportRunItem(StrictReportAPIModel): """One calculation of a report, on one country package and .py version. ``status`` is ``pending``, ``running``, ``succeeded`` or ``failed``, and - ``error_message`` says why a failed run failed. ``trigger`` is - ``initial`` for the run the report's creation started, and null for a run - the simulation service shares between requests, which records no one - request's trigger. + ``error_message`` says why a failed run failed. """ id: UUID status: Literal["pending", "running", "succeeded", "failed"] - trigger: Literal["initial", "manual", "system"] | None country_package_version: str policyengine_version: str baseline_simulation_run_id: UUID @@ -299,9 +295,7 @@ class BudgetWindowRunItem(StrictReportAPIModel): ``status`` is ``pending`` until a year starts running, ``running`` while its years run, ``failed`` once a year has failed, with ``error_message`` - saying which, and ``succeeded`` once every year has. ``trigger`` is - ``initial`` for the run the report's creation started (null for a shared - run, which records no one request's trigger), and ``recalculate`` says + saying which, and ``succeeded`` once every year has. ``recalculate`` says whether its years calculate their simulations again rather than reusing successful runs. ``country_package_version`` and ``policyengine_version`` are the versions @@ -310,7 +304,6 @@ class BudgetWindowRunItem(StrictReportAPIModel): id: UUID status: Literal["pending", "running", "succeeded", "failed"] - trigger: Literal["initial", "manual", "system"] | None recalculate: bool country_package_version: str | None policyengine_version: str | None diff --git a/policyengine_api/services/v2/stored_reports/transformations.py b/policyengine_api/services/v2/stored_reports/transformations.py index 36c9f0033..e67e76911 100644 --- a/policyengine_api/services/v2/stored_reports/transformations.py +++ b/policyengine_api/services/v2/stored_reports/transformations.py @@ -68,11 +68,10 @@ def report_kind(report: Report) -> ReportKind: def report_run_read(run: ReportRun) -> ReportRunRead: - """Return the run's status, trigger, versions and times.""" + """Return the run's status, versions and times.""" return ReportRunRead( id=run.id, status=run.status.value, - trigger=None if run.trigger is None else run.trigger.value, country_package_version=run.country_package_version, policyengine_version=run.policyengine_version, baseline_simulation_run_id=run.baseline_simulation_run_id, @@ -236,7 +235,7 @@ def household_report_read( def budget_window_run_read( window_run: BudgetWindowRun, years: Sequence[ReportRun] ) -> BudgetWindowRunRead: - """Return the window run's status, trigger and times, with its years. + """Return the window run's status and times, with its years. Its versions are its first year's, since the simulation service creates every year on one version; a run with no year has none. @@ -250,7 +249,6 @@ def budget_window_run_read( return BudgetWindowRunRead( id=window_run.id, status=window_run.status.value, - trigger=None if window_run.trigger is None else window_run.trigger.value, recalculate=window_run.recalculate, country_package_version=( None if first_year is None else first_year.country_package_version diff --git a/policyengine_api/services/v2/stored_reports/types.py b/policyengine_api/services/v2/stored_reports/types.py index 96f8f6cea..30765f965 100644 --- a/policyengine_api/services/v2/stored_reports/types.py +++ b/policyengine_api/services/v2/stored_reports/types.py @@ -52,7 +52,6 @@ # The kinds whose runs are their report runs; a budget window's are its # budget-window runs. ReportRunsKind = Literal["economy", "household"] -ReportRunTriggerName = Literal["initial", "manual", "system"] # How far a side's cliff calculation has got: not_calculated while its # simulation run has none, else its calculation's status (failed once its # newest calculation failed and none is pending, running or succeeded). @@ -65,15 +64,12 @@ class ReportRunRead: """One calculation of a report, and the package versions it ran on. - ``trigger`` is ``initial`` for the run the report's creation started, and - null for a run the simulation service shares between requests. A user's - trigger is on their record of the run. ``error_message`` says why a failed - run failed. + ``error_message`` says why a failed run failed. A run is shared between + requests, so each user's trigger is on their record of the run. """ id: UUID status: Literal["pending", "running", "succeeded", "failed"] - trigger: ReportRunTriggerName | None country_package_version: str policyengine_version: str baseline_simulation_run_id: UUID @@ -237,7 +233,6 @@ class BudgetWindowRunRead: id: UUID status: Literal["pending", "running", "succeeded", "failed"] - trigger: ReportRunTriggerName | None recalculate: bool country_package_version: str | None policyengine_version: str | None diff --git a/tests/integration/privilege_statements.py b/tests/integration/privilege_statements.py index adab29edc..ec22fbf02 100644 --- a/tests/integration/privilege_statements.py +++ b/tests/integration/privilege_statements.py @@ -14,9 +14,11 @@ refuses a statement on it; a statement sends only the columns it sets. No code creates tables from these classes: Alembic creates them from the models. -``ReportRunColumns`` also maps the four older cliff columns ``ReportRun``'s -mapper leaves out until a revision drops them. No model maps them, so every -test that writes them, or is refused them, sends its statement through it. +``ReportColumns`` also maps ``label``, ``ReportRunColumns`` ``trigger`` and the +four older cliff columns, and ``BudgetWindowRunColumns`` its ``trigger``: the +models' mappers leave them out until a revision drops them. No model maps +them, so every test that reads or writes them, or is refused them, sends its +statement through these classes. """ # No ``from __future__ import annotations``: SQLAlchemy reads the classes' @@ -35,6 +37,7 @@ CliffImpact, ReportRun, Simulation, + UserReportRunAssociation, WithheldAreaCode, ) @@ -65,12 +68,13 @@ class SimulationColumns: @named_column_tables.mapped class ReportColumns: - """A report's key version.""" + """A report's key version, and its label, which its mapper leaves out.""" __tablename__ = "reports" id: Mapped[UUID] = mapped_column(primary_key=True) key_version: Mapped[int | None] + label: Mapped[str | None] @named_column_tables.mapped @@ -130,24 +134,26 @@ class LaborSupplyDecileResponseColumns: @named_column_tables.mapped class BudgetWindowRunColumns: - """A new budget-window run's columns.""" + """A new budget-window run's columns, and ``trigger``, which its mapper omits.""" __tablename__ = "budget_window_runs" id: Mapped[UUID] = mapped_column(primary_key=True) report_id: Mapped[UUID] tax_benefit_model_version_id: Mapped[UUID] - trigger: Mapped[str | None] = mapped_column(_type_of(BudgetWindowRun, "trigger")) + trigger: Mapped[str | None] = mapped_column( + _type_of(UserReportRunAssociation, "trigger") + ) recalculate: Mapped[bool] status: Mapped[str] = mapped_column(_type_of(BudgetWindowRun, "status")) @named_column_tables.mapped class ReportRunColumns: - """A new report run's columns, and the four older cliff columns. + """A new report run's columns, ``trigger`` and the four older cliff columns. - ``ReportRun``'s mapper leaves the cliff columns out until a revision drops - them, so statements that set them go through this class. + ``ReportRun``'s mapper leaves ``trigger`` and the cliff columns out until a + revision drops them, so statements that set them go through this class. """ __tablename__ = "report_runs" @@ -158,14 +164,16 @@ class ReportRunColumns: country_package_version: Mapped[str] policyengine_version: Mapped[str] status: Mapped[str] = mapped_column(_type_of(ReportRun, "status")) - trigger: Mapped[str | None] = mapped_column(_type_of(ReportRun, "trigger")) + trigger: Mapped[str | None] = mapped_column( + _type_of(UserReportRunAssociation, "trigger") + ) baseline_cliff_gap: Mapped[float | None] baseline_cliff_share: Mapped[float | None] reform_cliff_gap: Mapped[float | None] reform_cliff_share: Mapped[float | None] -# The report run columns ``ReportRun``'s mapper leaves out, which only +# The four older cliff columns ``ReportRun``'s mapper leaves out, which only # ``ReportRunColumns`` maps. REPORT_RUN_CLIFF_COLUMNS = ( "baseline_cliff_gap", diff --git a/tests/integration/stored_report_rows.py b/tests/integration/stored_report_rows.py index f0f0cc9bd..495d9cde2 100644 --- a/tests/integration/stored_report_rows.py +++ b/tests/integration/stored_report_rows.py @@ -349,8 +349,6 @@ def store_report( # noqa: PLR0913 # the session and catalog, then each column session, Report, id=report.report_id, - label=f"{catalog.country} reform", - description="A stored report", country=catalog.country, type="economy", tax_benefit_model_id=catalog.model_id, @@ -430,7 +428,6 @@ def store_report_run( ), year=None if budget_window_year is None else budget_window_year.year, status=settings.status, - trigger="initial", started_at=created_at, completed_at=created_at + timedelta(minutes=10) if settings.finished else None, error_message=settings.error_message, @@ -501,7 +498,6 @@ def store_budget_window_run( created_at=created_at, report_id=report.report_id, tax_benefit_model_version_id=catalog.version_id, - trigger="initial", recalculate=False, status=settings.status, error_message=settings.error_message, diff --git a/tests/integration/test_alembic_v2_lifecycle.py b/tests/integration/test_alembic_v2_lifecycle.py index 494c4a170..e8152daa6 100644 --- a/tests/integration/test_alembic_v2_lifecycle.py +++ b/tests/integration/test_alembic_v2_lifecycle.py @@ -841,7 +841,6 @@ def report_run_checks() -> set[str | None]: session, Report, id=report_id, - label="UUID cast report", country="us", tax_benefit_model_id=public_api_rows.model_id, inputs={}, @@ -855,7 +854,6 @@ def report_run_checks() -> set[str | None]: country_package_version="1.0", policyengine_version="1.0", status="pending", - trigger="manual", # The key as text, which PostgreSQL stores as a native UUID. idempotency_key=str(request_key), ) diff --git a/tests/integration/test_alembic_v2_saved_item_keys.py b/tests/integration/test_alembic_v2_saved_item_keys.py index b46cda09e..6cf14e7b0 100644 --- a/tests/integration/test_alembic_v2_saved_item_keys.py +++ b/tests/integration/test_alembic_v2_saved_item_keys.py @@ -131,7 +131,6 @@ def _insert_report(session: Session, rows: PublicApiRows) -> UUID: session, Report, id=report_id, - label="Saved report", country="us", tax_benefit_model_id=rows.model_id, inputs={}, diff --git a/tests/integration/test_alembic_v2_simulation_runs.py b/tests/integration/test_alembic_v2_simulation_runs.py index 2906c46e4..3d6ca4e34 100644 --- a/tests/integration/test_alembic_v2_simulation_runs.py +++ b/tests/integration/test_alembic_v2_simulation_runs.py @@ -345,7 +345,6 @@ def _insert_report_run( session, Report, id=report_id, - label="Report", country="us", tax_benefit_model_id=public_api_rows.model_id, inputs={}, @@ -358,7 +357,6 @@ def _insert_report_run( baseline_simulation_run_id=baseline_run_id, reform_simulation_run_id=reform_run_id, status="running", - trigger="initial", **RUN_VERSIONS, ) return report_run_id @@ -691,7 +689,6 @@ def _insert_report( session, Report, id=report_id, - label="Budget window", country="us", tax_benefit_model_id=public_api_rows.model_id, inputs={}, @@ -710,7 +707,6 @@ def _insert_budget_window_run( id=window_run_id, report_id=report_id, tax_benefit_model_version_id=public_api_rows.version_id, - trigger="initial", recalculate=False, status="running", ) @@ -755,7 +751,6 @@ def insert_year(year: int | None, *, of_report: UUID = report_id) -> None: year=year or 2026, ), status="pending", - trigger="initial", **RUN_VERSIONS, ) diff --git a/tests/integration/test_alembic_v2_withheld_area_codes.py b/tests/integration/test_alembic_v2_withheld_area_codes.py index 6e6f48b24..554d2f9c0 100644 --- a/tests/integration/test_alembic_v2_withheld_area_codes.py +++ b/tests/integration/test_alembic_v2_withheld_area_codes.py @@ -209,7 +209,6 @@ def _insert_report_run(session: Session) -> dict[str, UUID]: session, Report, id=ids["report"], - label="Local areas", country="uk", tax_benefit_model_id=public_api_rows.model_id, year=2026, @@ -223,7 +222,6 @@ def _insert_report_run(session: Session) -> dict[str, UUID]: baseline_simulation_run_id=ids["baseline_run"], reform_simulation_run_id=ids["reform_run"], status="pending", - trigger="initial", **RUN_VERSIONS, ) return ids diff --git a/tests/integration/test_v2_budget_window_report_creation.py b/tests/integration/test_v2_budget_window_report_creation.py index b359c92b7..bbb3f398e 100644 --- a/tests/integration/test_v2_budget_window_report_creation.py +++ b/tests/integration/test_v2_budget_window_report_creation.py @@ -216,7 +216,7 @@ def test_a_created_budget_window_is_answered_as_the_tables_hold_it( assert (item["id"], item["kind"]) == (str(catalog.report_ids[0]), "budget_window") assert (item["year"], item["budget_window_size"]) == (2026, 3) assert item["status"] == "pending" - assert item["run"]["trigger"] == "initial" + assert "trigger" not in item["run"] assert item["run"]["policyengine_version"] == "4.2.0" assert [(year["year"], year["status"]) for year in item["run"]["years"]] == [ (2026, "pending"), diff --git a/tests/integration/test_v2_budget_window_report_reads.py b/tests/integration/test_v2_budget_window_report_reads.py index 3f3ed6b01..5178f0b30 100644 --- a/tests/integration/test_v2_budget_window_report_reads.py +++ b/tests/integration/test_v2_budget_window_report_reads.py @@ -220,11 +220,8 @@ def test_a_budget_window_reads_its_newest_run_years_and_result( assert item["status"] == "succeeded" run = item["run"] assert run["id"] == str(window_run_id) - assert (run["status"], run["trigger"], run["recalculate"]) == ( - "succeeded", - "initial", - False, - ) + assert (run["status"], run["recalculate"]) == ("succeeded", False) + assert "trigger" not in run assert (run["country_package_version"], run["policyengine_version"]) == ( "1.4.0", "4.1.0", diff --git a/tests/integration/test_v2_catalog_publication.py b/tests/integration/test_v2_catalog_publication.py index bd424c34f..55be28327 100644 --- a/tests/integration/test_v2_catalog_publication.py +++ b/tests/integration/test_v2_catalog_publication.py @@ -502,7 +502,6 @@ def test_republish_preserves_existing_run_and_dataset_version_records( region_id=region.id, ) report = Report( - label="Existing report", country="us", tax_benefit_model_id=model.id, dataset_id=input_dataset.id, diff --git a/tests/integration/test_v2_household_reports.py b/tests/integration/test_v2_household_reports.py index 76dd5320f..116245249 100644 --- a/tests/integration/test_v2_household_reports.py +++ b/tests/integration/test_v2_household_reports.py @@ -265,7 +265,6 @@ def store_household_report( session, Report, id=report_id, - label="My household under the reform", country=catalog.country, tax_benefit_model_id=catalog.model_id, policy_id=catalog.policy_id if with_reform else None, @@ -285,7 +284,6 @@ def store_household_report( baseline_simulation_run_id=baseline_run_id, reform_simulation_run_id=reform_run_id, status=status, - trigger="initial", started_at=STARTED_AT, completed_at=( STARTED_AT + timedelta(minutes=1) diff --git a/tests/integration/test_v2_report_creation.py b/tests/integration/test_v2_report_creation.py index 947996fc3..7c1afbff8 100644 --- a/tests/integration/test_v2_report_creation.py +++ b/tests/integration/test_v2_report_creation.py @@ -254,7 +254,7 @@ def test_a_created_report_is_answered_as_the_tables_hold_it( item = response.json()["result"]["item"] assert item["id"] == str(catalog.report_ids[0]) assert item["status"] == "pending" - assert item["run"]["trigger"] == "initial" + assert "trigger" not in item["run"] assert item["run"]["policyengine_version"] == "4.2.0" assert item["result"] is None assert item["current_versions"] == CURRENT_VERSIONS diff --git a/tests/integration/test_v2_report_runs.py b/tests/integration/test_v2_report_runs.py index 099ebbbb4..6ca2213f8 100644 --- a/tests/integration/test_v2_report_runs.py +++ b/tests/integration/test_v2_report_runs.py @@ -109,21 +109,14 @@ def current_versions(country_id: str) -> PackageVersions: return PackageVersions(**CURRENT_VERSIONS) -def mark_manual(session: Session, run_id: UUID) -> None: - """Record the report run as a re-run, as the simulation service creates one.""" - session.execute( - update(ReportRun).where(col(ReportRun.id) == run_id).values(trigger="manual") - ) - - -def mark_window_manual( +def set_window_recalculate( session: Session, window_run_id: UUID, *, recalculate: bool ) -> None: - """Record the window run as a re-run, as the simulation service creates one.""" + """Record whether the window run is forced, as the simulation service does.""" session.execute( update(BudgetWindowRun) .where(col(BudgetWindowRun.id) == window_run_id) - .values(trigger="manual", recalculate=recalculate) + .values(recalculate=recalculate) ) @@ -203,7 +196,7 @@ def rerun_report(self, rerun: ReportRerunInput) -> StartedReportRun: window_run_id = store_window_run( session, self.catalog, report, settings, self.window_years ) - mark_window_manual(session, window_run_id, recalculate=rerun.force) + set_window_recalculate(session, window_run_id, recalculate=rerun.force) self.new_run_ids.append(window_run_id) started = StartedReportRun( report_run_id=session.execute( @@ -216,7 +209,6 @@ def rerun_report(self, rerun: ReportRerunInput) -> StartedReportRun: ) else: run_ids = store_report_run(session, self.catalog, report, settings) - mark_manual(session, run_ids.report_run_id) if rerun.include_cliffs: for simulation_run_id in ( run_ids.baseline_simulation_run_id, @@ -358,7 +350,6 @@ def test_a_reports_runs_are_listed_newest_first_with_their_versions( error_message="The reform simulation failed", ), ) - mark_manual(session, failed.report_run_id) newest = store_report_run( session, catalog, @@ -369,7 +360,6 @@ def test_a_reports_runs_are_listed_newest_first_with_their_versions( created_at=STARTED_AT + timedelta(days=2), ), ) - mark_manual(session, newest.report_run_id) other_report = store_report(session, catalog) store_report_run( session, @@ -394,11 +384,8 @@ def test_a_reports_runs_are_listed_newest_first_with_their_versions( str(failed.report_run_id), str(first.report_run_id), ] - assert [(item["status"], item["trigger"]) for item in items] == [ - ("running", "manual"), - ("failed", "manual"), - ("succeeded", "initial"), - ] + assert [item["status"] for item in items] == ["running", "failed", "succeeded"] + assert all("trigger" not in item for item in items) assert [item["policyengine_version"] for item in items] == [ "4.2.0", "4.2.0", @@ -498,7 +485,6 @@ def test_a_household_reports_runs_are_listed_newest_first_with_their_versions( created_at=STARTED_AT + timedelta(days=1), ), ) - mark_manual(session, newest.report_run_id) client = client_for( runtime_sessions, RerunningSimulationService(owner_sessions, catalog) ) @@ -515,10 +501,8 @@ def test_a_household_reports_runs_are_listed_newest_first_with_their_versions( str(newest.report_run_id), str(first.report_run_id), ] - assert [(item["status"], item["trigger"]) for item in items] == [ - ("pending", "manual"), - ("succeeded", "initial"), - ] + assert [item["status"] for item in items] == ["pending", "succeeded"] + assert all("trigger" not in item for item in items) assert [item["policyengine_version"] for item in items] == ["4.2.0", "4.1.0"] @@ -559,7 +543,7 @@ def test_a_household_report_runs_again_where_households_are_calculated( assert item["kind"] == "household" assert item["status"] == "pending" assert item["run"]["id"] == str(new_run_id) - assert item["run"]["trigger"] == "manual" + assert "trigger" not in item["run"] assert item["run"]["policyengine_version"] == "4.2.0" assert item["result"] is None runs = client.get(f"/v2/reports/{report.report_id}/runs?country_id=uk").json() @@ -607,7 +591,7 @@ def test_running_a_report_again_answers_it_with_its_new_run( assert item["id"] == str(report.report_id) assert item["status"] == "pending" assert item["run"]["id"] == str(new_run_id) - assert item["run"]["trigger"] == "manual" + assert "trigger" not in item["run"] assert item["run"]["policyengine_version"] == "4.2.0" assert item["current_versions"] == CURRENT_VERSIONS assert item["result"] is None @@ -824,7 +808,7 @@ def test_a_budget_windows_runs_are_listed_newest_first_with_their_years( ), (2026, 2027), ) - mark_window_manual(session, newest_run_id, recalculate=True) + set_window_recalculate(session, newest_run_id, recalculate=True) client = client_for( runtime_sessions, RerunningSimulationService(owner_sessions, catalog) ) @@ -838,9 +822,11 @@ def test_a_budget_windows_runs_are_listed_newest_first_with_their_years( assert result["current_versions"] == CURRENT_VERSIONS items = result["items"] assert [item["id"] for item in items] == [str(newest_run_id), str(first_run_id)] - assert [ - (item["status"], item["trigger"], item["recalculate"]) for item in items - ] == [("running", "manual", True), ("succeeded", "initial", False)] + assert [(item["status"], item["recalculate"]) for item in items] == [ + ("running", True), + ("succeeded", False), + ] + assert all("trigger" not in item for item in items) assert [item["policyengine_version"] for item in items] == ["4.2.0", "4.1.0"] assert [[year["year"] for year in item["years"]] for item in items] == [ [2026, 2027], @@ -892,7 +878,7 @@ def test_running_a_budget_window_again_answers_it_with_its_new_run( assert item["kind"] == "budget_window" assert item["status"] == "pending" assert item["run"]["id"] == str(new_run_id) - assert item["run"]["trigger"] == "manual" + assert "trigger" not in item["run"] assert item["run"]["recalculate"] is force assert item["run"]["policyengine_version"] == "4.2.0" assert item["result"] is None diff --git a/tests/integration/test_v2_shared_report_rows.py b/tests/integration/test_v2_shared_report_rows.py index 5c309f116..480e58834 100644 --- a/tests/integration/test_v2_shared_report_rows.py +++ b/tests/integration/test_v2_shared_report_rows.py @@ -50,7 +50,9 @@ ) from tests.fixtures.database_sessions import act_as, act_as_owner, query_plan from tests.integration.privilege_statements import ( + BudgetWindowRunColumns, ReportColumns, + ReportRunColumns, SimulationColumns, unfailed, update_row, @@ -110,7 +112,6 @@ def _find_or_create_report(public_api_rows: PublicApiRows, key: str) -> Executab postgresql.insert(Report) .values( id=uuid4(), - label="Report", country="us", tax_benefit_model_id=public_api_rows.model_id, year=2026, @@ -176,7 +177,6 @@ def _find_or_create_report_run( report_id=report_id, baseline_simulation_run_id=baseline_run_id, status="pending", - trigger="initial", forced=forced, **versions, ) @@ -210,7 +210,6 @@ def _find_or_create_window_run( report_id=report_id, tax_benefit_model_version_id=public_api_rows.version_id, policyengine_version=policyengine_version, - trigger="initial", recalculate=recalculate, status="pending", ) @@ -327,7 +326,6 @@ def _report(session: Session, public_api_rows: PublicApiRows) -> UUID: session, Report, id=report_id, - label="Report", country="us", tax_benefit_model_id=public_api_rows.model_id, year=2026, @@ -508,7 +506,6 @@ def test_a_malformed_or_incomplete_key_is_refused( } if table == "simulations" else { - "label": "Report", "country": "us", "tax_benefit_model_id": public_api_rows.model_id, "inputs": {}, @@ -593,7 +590,6 @@ def test_a_report_has_one_unfailed_unforced_run_per_version_set_outside_windows( id=window_run_id, report_id=report_id, tax_benefit_model_version_id=public_api_rows.version_id, - trigger="initial", recalculate=False, status="pending", ) @@ -606,7 +602,6 @@ def test_a_report_has_one_unfailed_unforced_run_per_version_set_outside_windows( year=2026, baseline_simulation_run_id=baseline_run_id, status="pending", - trigger="initial", **RUN_VERSIONS, ) @@ -701,11 +696,18 @@ def test_the_simulation_service_writes_shared_rows_without_per_user_columns( act_as(session, managed_v2_roles.runtime) stored = session.execute( - select(col(Report.label), col(ReportRun.trigger), col(BudgetWindowRun.trigger)) - .select_from(Report) - .join(ReportRun, col(ReportRun.report_id) == col(Report.id)) - .join(BudgetWindowRun, col(BudgetWindowRun.report_id) == col(Report.id)) - .where(col(Report.id) == report_id) + select( + ReportColumns.label, + ReportRunColumns.trigger, + BudgetWindowRunColumns.trigger, + ) + .select_from(ReportColumns) + .join(ReportRunColumns, ReportRunColumns.report_id == ReportColumns.id) + .join( + BudgetWindowRunColumns, + BudgetWindowRunColumns.report_id == ReportColumns.id, + ) + .where(ReportColumns.id == report_id) ).one() assert tuple(stored) == (None, None, None) diff --git a/tests/integration/test_v2_simulation_role_privileges.py b/tests/integration/test_v2_simulation_role_privileges.py index 91a56cbed..78f6458d7 100644 --- a/tests/integration/test_v2_simulation_role_privileges.py +++ b/tests/integration/test_v2_simulation_role_privileges.py @@ -18,9 +18,10 @@ models: both simulation roles may update ``updated_at`` on the run, budget-window run and cliff calculation tables, and ``poverty`` and ``withheld_area_codes`` have no ``updated_at``. A column a model's mapper leaves out, such as a report -run's four older cliff columns until a revision drops them, has no statement -through the model, so its writes and refusals go through the class that maps -it, ``ReportRunColumns``. +run's ``trigger`` and four older cliff columns, or a budget-window run's +``trigger``, until a revision drops them, has no statement through the model, +so its writes and refusals go through the class that maps it, +``ReportRunColumns`` or ``BudgetWindowRunColumns``. """ from __future__ import annotations @@ -182,7 +183,6 @@ def _create_simulation_rows( session, Report, id=ids["report"], - label="Report", country="us", tax_benefit_model_id=public_api_rows.model_id, year=2026, @@ -195,7 +195,6 @@ def _create_simulation_rows( id=ids["budget_window_run"], report_id=ids["report"], tax_benefit_model_version_id=public_api_rows.version_id, - trigger="initial", recalculate=False, status="pending", ) @@ -208,7 +207,6 @@ def _create_simulation_rows( year=2026, baseline_simulation_run_id=ids["run"], status="pending", - trigger="initial", **RUN_VERSIONS, ) add_row( @@ -512,7 +510,6 @@ def test_modal_workers_start_finish_and_fail_budget_windows( id=failing_window_id, report_id=ids["report"], tax_benefit_model_version_id=public_api_rows.version_id, - trigger="manual", recalculate=True, status="pending", ) @@ -553,7 +550,7 @@ def test_modal_workers_start_finish_and_fail_budget_windows( assert started_windows == [window_id, failing_window_id] assert (succeeded_window, failed_window) == (window_id, failing_window_id) for statement in ( - update_row(BudgetWindowRun, window_id, trigger="manual"), + update_row(BudgetWindowRunColumns, window_id, trigger="manual"), update_row(BudgetWindowRun, window_id, recalculate=False), update_row( BudgetWindowRun, @@ -629,7 +626,10 @@ def test_the_public_api_reads_runs_and_results_but_writes_neither( # The class that maps the columns each model's mapper leaves out. -UNMAPPED_COLUMN_CLASSES: dict[type[Any], type[Any]] = {ReportRun: ReportRunColumns} +UNMAPPED_COLUMN_CLASSES: dict[type[Any], type[Any]] = { + BudgetWindowRun: BudgetWindowRunColumns, + ReportRun: ReportRunColumns, +} @pytest.mark.parametrize("role_kind", ["simulation_service", "modal_worker"]) diff --git a/tests/unit/v2/budget_window_report_support.py b/tests/unit/v2/budget_window_report_support.py index b364168c4..4817290b1 100644 --- a/tests/unit/v2/budget_window_report_support.py +++ b/tests/unit/v2/budget_window_report_support.py @@ -62,7 +62,6 @@ def budget_window_year_read(year: int, **changes: Any) -> BudgetWindowYearRead: "year": year, "id": YEAR_RUN_IDS[year], "status": "succeeded", - "trigger": "initial", "country_package_version": "1.4.0", "policyengine_version": "4.1.0", "baseline_simulation_run_id": UUID(int=year * 2), @@ -79,7 +78,6 @@ def budget_window_run_read(**changes: Any) -> BudgetWindowRunRead: values: dict[str, Any] = { "id": BUDGET_WINDOW_RUN_ID, "status": "succeeded", - "trigger": "initial", "recalculate": False, "country_package_version": "1.4.0", "policyengine_version": "4.1.0", diff --git a/tests/unit/v2/report_run_support.py b/tests/unit/v2/report_run_support.py index 83c4317e0..efe1beee3 100644 --- a/tests/unit/v2/report_run_support.py +++ b/tests/unit/v2/report_run_support.py @@ -44,7 +44,6 @@ def report_runs_read() -> ReportRunsRead: report_run_read( id=NEW_RUN_ID, status="pending", - trigger="manual", country_package_version=CURRENT_VERSIONS.country_package_version, policyengine_version=CURRENT_VERSIONS.policyengine_version, created_at=CREATED_AT + timedelta(days=3), @@ -75,7 +74,6 @@ def budget_window_runs_read() -> BudgetWindowRunsRead: budget_window_run_read( id=NEW_WINDOW_RUN_ID, status="pending", - trigger="manual", recalculate=True, created_at=rerun_at, started_at=None, @@ -87,7 +85,6 @@ def budget_window_runs_read() -> BudgetWindowRunsRead: baseline_simulation_run_id=UUID(int=year * 2 + 10_000), reform_simulation_run_id=UUID(int=year * 2 + 10_001), status="pending", - trigger="manual", created_at=rerun_at, started_at=None, completed_at=None, diff --git a/tests/unit/v2/sqlite_report_rows.py b/tests/unit/v2/sqlite_report_rows.py index 1aa3bac9a..32de7ef13 100644 --- a/tests/unit/v2/sqlite_report_rows.py +++ b/tests/unit/v2/sqlite_report_rows.py @@ -102,7 +102,6 @@ def store_economy_report( ) stored = Report( id=uuid4() if report.report_id is None else report.report_id, - label="A stored report", country=place.country, tax_benefit_model_id=place.model_id, baseline_simulation_id=simulations[0].id, diff --git a/tests/unit/v2/stored_report_support.py b/tests/unit/v2/stored_report_support.py index bb3c89757..8f191bfdd 100644 --- a/tests/unit/v2/stored_report_support.py +++ b/tests/unit/v2/stored_report_support.py @@ -65,7 +65,6 @@ def report_run_read(**changes: Any) -> ReportRunRead: values: dict[str, Any] = { "id": REPORT_RUN_ID, "status": "succeeded", - "trigger": "initial", "country_package_version": "1.4.0", "policyengine_version": "4.1.0", "baseline_simulation_run_id": BASELINE_RUN_ID, diff --git a/tests/unit/v2/test_budget_window_report_read_routes.py b/tests/unit/v2/test_budget_window_report_read_routes.py index e27cc49ba..6d237ffa3 100644 --- a/tests/unit/v2/test_budget_window_report_read_routes.py +++ b/tests/unit/v2/test_budget_window_report_read_routes.py @@ -15,7 +15,6 @@ budget_window_report_read, budget_window_run_read, budget_window_summary_read, - budget_window_year_read, ) from tests.unit.v2.stored_report_support import ( REPORT_ID, @@ -42,11 +41,8 @@ def test_a_budget_window_answers_its_window_newest_run_years_and_result() -> Non assert (item["year"], item["budget_window_size"]) == (2026, 2) run = item["run"] assert run["id"] == str(BUDGET_WINDOW_RUN_ID) - assert (run["status"], run["trigger"], run["recalculate"]) == ( - "succeeded", - "initial", - False, - ) + assert (run["status"], run["recalculate"]) == ("succeeded", False) + assert "trigger" not in run assert (run["country_package_version"], run["policyengine_version"]) == ( "1.4.0", "4.1.0", @@ -58,7 +54,6 @@ def test_a_budget_window_answers_its_window_newest_run_years_and_result() -> Non "year", "id", "status", - "trigger", "country_package_version", "policyengine_version", "baseline_simulation_run_id", @@ -81,20 +76,14 @@ def test_a_budget_window_answers_its_window_newest_run_years_and_result() -> Non ] -def test_a_window_run_and_its_years_without_a_trigger_answer_it_as_null() -> None: - run = budget_window_run_read( - trigger=None, - years=tuple( - budget_window_year_read(year, trigger=None) for year in YEAR_RUN_IDS - ), - ) - service = FakeReportService(report=budget_window_report_read(run=run, label=None)) +def test_a_window_run_and_its_years_answer_no_trigger() -> None: + service = FakeReportService(report=budget_window_report_read(label=None)) item = read_item(service) assert item["label"] is None - assert item["run"]["trigger"] is None - assert {year["trigger"] for year in item["run"]["years"]} == {None} + assert "trigger" not in item["run"] + assert all("trigger" not in year for year in item["run"]["years"]) def test_a_budget_window_without_a_run_answers_no_run_and_no_result() -> None: diff --git a/tests/unit/v2/test_household_report_reads.py b/tests/unit/v2/test_household_report_reads.py index 0c078ec3c..2ff124c87 100644 --- a/tests/unit/v2/test_household_report_reads.py +++ b/tests/unit/v2/test_household_report_reads.py @@ -21,7 +21,6 @@ Report, ReportRun, ReportRunStatus, - ReportRunTrigger, Simulation, SimulationRun, SimulationStatus, @@ -212,8 +211,6 @@ def simulation(policy_id: UUID | None) -> Simulation: session.add_all([side for side in (baseline, reform) if side is not None]) session.flush() report = Report( - label="My household under the reform", - description="Doubles the credit", country=country, tax_benefit_model_id=model.id, baseline_simulation_id=baseline.id, @@ -262,7 +259,6 @@ def simulation_run( baseline_simulation_run_id=baseline_run.id, reform_simulation_run_id=None if reform_run is None else reform_run.id, status=run.status, - trigger=ReportRunTrigger.INITIAL, created_at=STORED_AT, started_at=STORED_AT, completed_at=completed_at, @@ -522,7 +518,6 @@ def store_economy_report(session: Session) -> UUID: session.add(model) session.flush() report = Report( - label="Economy", country="us", tax_benefit_model_id=model.id, year=2026, diff --git a/tests/unit/v2/test_models.py b/tests/unit/v2/test_models.py index d3d9c7c59..a77821c59 100644 --- a/tests/unit/v2/test_models.py +++ b/tests/unit/v2/test_models.py @@ -317,7 +317,6 @@ def test_report_definition_and_run_columns_are_separated() -> None: "country_package_version", "policyengine_version", "status", - "trigger", "idempotency_key", "started_at", "completed_at", diff --git a/tests/unit/v2/test_report_column_mapping.py b/tests/unit/v2/test_report_column_mapping.py new file mode 100644 index 000000000..3c3f7ee24 --- /dev/null +++ b/tests/unit/v2/test_report_column_mapping.py @@ -0,0 +1,90 @@ +"""API v1's models leave out the report columns a later revision drops. + +The deploy upgrades the database before new code takes traffic, so the release +serving during that upgrade must not name a column it removes. The tables keep +the columns until then: each stays a SQLModel field, as rule +``api.data.orm-only`` requires of every column, and ``exclude_properties`` +leaves it out of the mapper, so the models neither select nor write it. +""" + +import pytest +import sqlalchemy as sa +from pydantic_core import PydanticUndefined +from sqlmodel import select + +from policyengine_api.data.v2.models import ( + BudgetWindowRun, + Report, + ReportRun, + User, +) +from tests.unit.v2.v2_schema_reading import model_columns, stored_v2_table + +UNMAPPED_COLUMNS = [ + (Report, "label"), + (Report, "description"), + (Report, "user_id"), + (ReportRun, "trigger"), + (BudgetWindowRun, "trigger"), +] + + +@pytest.mark.parametrize(("model", "column_name"), UNMAPPED_COLUMNS) +def test_a_whole_row_read_names_no_unmapped_column( + model: type, column_name: str +) -> None: + selected_names = {column.name for column in select(model).selected_columns} + + assert column_name not in selected_names + + +@pytest.mark.parametrize(("model", "column_name"), UNMAPPED_COLUMNS) +def test_the_mapper_leaves_out_an_unmapped_column( + model: type, column_name: str +) -> None: + mapper = sa.inspect(model) + + assert column_name in mapper.exclude_properties + assert column_name not in mapper.column_attrs + + +@pytest.mark.parametrize(("model", "column_name"), UNMAPPED_COLUMNS) +def test_the_table_keeps_an_unmapped_column_until_a_revision_drops_it( + model: type, column_name: str +) -> None: + stored_column = stored_v2_table(model.__tablename__).columns[column_name] + field = model.model_fields[column_name] + column_arguments = getattr(field, "sa_column_kwargs", None) + + assert stored_column.nullable + assert field.default is None + assert column_arguments in (None, PydanticUndefined) + + +@pytest.mark.parametrize("model", [ReportRun, BudgetWindowRun]) +def test_a_runs_trigger_keeps_the_type_users_run_records_share(model: type) -> None: + trigger_type = model.model_fields["trigger"].sa_type + record_trigger_type = model_columns("user_report_run_associations").trigger.type + + assert isinstance(trigger_type, sa.Enum) + assert isinstance(record_trigger_type, sa.Enum) + assert trigger_type.name == record_trigger_type.name == "v2_report_run_trigger" + assert trigger_type.enums == record_trigger_type.enums + + +def test_the_reports_user_key_and_index_stay_with_the_column() -> None: + reports = stored_v2_table("reports") + + (user_key,) = ( + foreign_key + for foreign_key in reports.foreign_keys + if foreign_key.columns == ("user_id",) + ) + assert user_key.targets == ("users.id",) + assert user_key.ondelete == "SET NULL" + assert reports.index_columns["ix_reports_user_id"] == ("user_id",) + + +def test_reports_and_users_have_no_relationship() -> None: + assert "user" not in Report.__sqlmodel_relationships__ + assert "reports" not in User.__sqlmodel_relationships__ diff --git a/tests/unit/v2/test_report_dataset_independent_keys.py b/tests/unit/v2/test_report_dataset_independent_keys.py index 9cac9c32b..5f49158b7 100644 --- a/tests/unit/v2/test_report_dataset_independent_keys.py +++ b/tests/unit/v2/test_report_dataset_independent_keys.py @@ -121,7 +121,6 @@ def store_household_report( session.add_all(simulations) session.flush() report = Report( - label="My household", country=catalog.country, tax_benefit_model_id=catalog.model_id, baseline_simulation_id=simulations[0].id, diff --git a/tests/unit/v2/test_report_read_routes.py b/tests/unit/v2/test_report_read_routes.py index 7513986be..7270c4acc 100644 --- a/tests/unit/v2/test_report_read_routes.py +++ b/tests/unit/v2/test_report_read_routes.py @@ -73,12 +73,10 @@ def test_a_reports_spm_receipts_are_answered_with_package_names_as_keys() -> Non } -def test_a_report_without_a_label_or_run_trigger_answers_them_as_null() -> None: +def test_a_report_without_a_label_answers_null_and_its_run_no_trigger() -> None: """A shared report holds no caller's label, and its runs no request's trigger.""" service = FakeReportService() - service.report = replace( - service.report, label=None, run=report_run_read(trigger=None) - ) + service.report = replace(service.report, label=None, run=report_run_read()) client = report_route_client(reports=service) response = client.get(f"/v2/reports/{REPORT_ID}?country_id=us") @@ -86,7 +84,7 @@ def test_a_report_without_a_label_or_run_trigger_answers_them_as_null() -> None: assert response.status_code == 200, response.text item = response.json()["result"]["item"] assert item["label"] is None - assert item["run"]["trigger"] is None + assert "trigger" not in item["run"] def test_a_report_without_a_run_answers_with_no_run_and_no_result() -> None: diff --git a/tests/unit/v2/test_report_rerun_service.py b/tests/unit/v2/test_report_rerun_service.py index bd948a040..34a58fd5d 100644 --- a/tests/unit/v2/test_report_rerun_service.py +++ b/tests/unit/v2/test_report_rerun_service.py @@ -14,7 +14,6 @@ BudgetWindowRun, Report, ReportRunStatus, - ReportRunTrigger, ) from policyengine_api.services.v2.simulation_service.types import ( PackageVersions, @@ -74,7 +73,6 @@ def rerun_report(self, rerun: ReportRerunInput) -> StartedReportRun: def stored_rows(**report_columns: object) -> StoredReportRows: report = Report( id=REPORT_ID, - label="Reform", country="us", tax_benefit_model_id=uuid4(), year=2026, @@ -147,7 +145,6 @@ def test_a_window_run_with_no_year_lists_no_years_and_no_versions() -> None: updated_at=STORED_AT, report_id=REPORT_ID, tax_benefit_model_version_id=uuid4(), - trigger=ReportRunTrigger.MANUAL, recalculate=True, status=ReportRunStatus.PENDING, ) @@ -162,7 +159,7 @@ def test_a_window_run_with_no_year_lists_no_years_and_no_versions() -> None: assert runs.kind == "budget_window" (run,) = runs.runs assert run.id == window_run.id - assert (run.trigger, run.recalculate, run.status) == ("manual", True, "pending") + assert (run.recalculate, run.status) == (True, "pending") assert run.years == () assert run.country_package_version is None assert run.policyengine_version is None diff --git a/tests/unit/v2/test_report_run_creation.py b/tests/unit/v2/test_report_run_creation.py index 9b62e08cf..36d450d36 100644 --- a/tests/unit/v2/test_report_run_creation.py +++ b/tests/unit/v2/test_report_run_creation.py @@ -14,7 +14,6 @@ Report, ReportRun, ReportRunStatus, - ReportRunTrigger, TaxBenefitModel, ) from policyengine_api.data.v2.report_runs import ( @@ -49,7 +48,6 @@ def _create_report(session: Session) -> Report: session.add(model) session.flush() report = Report( - label="Distributional report", country="us", tax_benefit_model_id=model.id, inputs={}, @@ -74,31 +72,9 @@ def test_unknown_report_is_rejected_before_any_validation(sessions) -> None: ), simulation_runs=SIMULATION_RUNS, ), - trigger=ReportRunTrigger.MANUAL, ) -def test_manual_run_without_a_key_is_rejected_before_version_checks(sessions) -> None: - with sessions(expire_on_commit=True) as session: - report = _create_report(session) - - with pytest.raises( - ValueError, match=r"^manual report reruns require an idempotency key$" - ): - create_report_run( - session, - report_id=report.id, - inputs=ReportRunInputs( - versions=ReportRunPackageVersions( - country_package_version="", - policyengine_version="", - ), - simulation_runs=SIMULATION_RUNS, - ), - trigger=ReportRunTrigger.MANUAL, - ) - - @pytest.mark.parametrize( ("country_package_version", "policyengine_version"), [("", "4.5.6"), ("1.2.3", "")], @@ -124,7 +100,6 @@ def test_empty_package_versions_are_rejected( ), simulation_runs=SIMULATION_RUNS, ), - trigger=ReportRunTrigger.SYSTEM, ) @@ -142,7 +117,6 @@ def test_run_without_a_key_is_inserted_without_a_savepoint(sessions) -> None: ), simulation_runs=SIMULATION_RUNS, ), - trigger=ReportRunTrigger.INITIAL, ) stored = session.exec(select(ReportRun)).one() @@ -150,7 +124,6 @@ def test_run_without_a_key_is_inserted_without_a_savepoint(sessions) -> None: assert run.report_id == report.id assert run.country_package_version == "1.2.3" assert run.policyengine_version == "4.5.6" - assert run.trigger is ReportRunTrigger.INITIAL assert run.idempotency_key is None assert run.status is ReportRunStatus.PENDING assert run.baseline_simulation_run_id == UUID(int=101) @@ -183,7 +156,6 @@ def failing_savepoint(): ), simulation_runs=SIMULATION_RUNS, ), - trigger=ReportRunTrigger.MANUAL, idempotency_key=uuid4(), ) diff --git a/tests/unit/v2/test_report_run_routes.py b/tests/unit/v2/test_report_run_routes.py index 9ce831810..0760fa244 100644 --- a/tests/unit/v2/test_report_run_routes.py +++ b/tests/unit/v2/test_report_run_routes.py @@ -73,7 +73,7 @@ def test_a_reports_runs_are_answered_newest_first_with_versions_and_current_ones str(NEW_RUN_ID), str(REPORT_RUN_ID), ] - assert [run["trigger"] for run in result["items"]] == ["manual", "initial"] + assert all("trigger" not in run for run in result["items"]) assert [ (run["country_package_version"], run["policyengine_version"]) for run in result["items"] @@ -134,7 +134,8 @@ def test_a_budget_windows_runs_are_answered_with_their_years() -> None: assert result["kind"] == "budget_window" newest, first = result["items"] assert newest["id"] == str(NEW_WINDOW_RUN_ID) - assert (newest["trigger"], newest["recalculate"]) == ("manual", True) + assert newest["recalculate"] is True + assert "trigger" not in newest assert newest["policyengine_version"] == "4.2.0" assert [year["year"] for year in first["years"]] == [2026, 2027] assert first["years"][0]["country_package_version"] == "1.4.0" @@ -225,7 +226,7 @@ def test_running_a_report_again_answers_the_report_with_its_new_run( service.report = replace( service.report, status="pending", - run=report_run_read(id=NEW_RUN_ID, status="pending", trigger="manual"), + run=report_run_read(id=NEW_RUN_ID, status="pending"), result=None, ) @@ -236,7 +237,7 @@ def test_running_a_report_again_answers_the_report_with_its_new_run( assert item["id"] == str(REPORT_ID) assert item["status"] == "pending" assert item["run"]["id"] == str(NEW_RUN_ID) - assert item["run"]["trigger"] == "manual" + assert "trigger" not in item["run"] assert item["result"] is None assert item["current_versions"]["policyengine_version"] == "4.2.0" assert service.calls == [ diff --git a/tests/unit/v2/test_report_runs.py b/tests/unit/v2/test_report_runs.py index 0073e420d..e2ffeae55 100644 --- a/tests/unit/v2/test_report_runs.py +++ b/tests/unit/v2/test_report_runs.py @@ -19,7 +19,6 @@ Report, ReportRun, ReportRunStatus, - ReportRunTrigger, Simulation, SimulationType, TaxBenefitModel, @@ -65,7 +64,6 @@ def _create_report(session: Session, *, report_type: str | None = None) -> Repor session.add(model) session.flush() report = Report( - label="Distributional report", country="us", type=report_type, tax_benefit_model_id=model.id, @@ -94,7 +92,6 @@ def _create_run( ), simulation_runs=SIMULATION_RUNS, ), - trigger=ReportRunTrigger.MANUAL, idempotency_key=key if key is not None else uuid4(), ) @@ -111,7 +108,6 @@ def _create_forced_run(session: Session, report: Report) -> ReportRun: reform_simulation_run_id=SIMULATION_RUNS.reform_simulation_run_id, country_package_version="1.2.3", policyengine_version=DEPLOYED_POLICYENGINE_VERSION, - trigger=ReportRunTrigger.MANUAL, idempotency_key=uuid4(), forced=True, ) @@ -157,7 +153,7 @@ def test_report_type_can_change_before_first_run_but_not_after(sessions) -> None ) -def test_new_manual_keys_create_a_same_version_run_once_the_last_one_failed( +def test_new_keys_create_a_same_version_run_once_the_last_one_failed( sessions, ) -> None: with sessions(expire_on_commit=True) as session: @@ -177,25 +173,6 @@ def test_new_manual_keys_create_a_same_version_run_once_the_last_one_failed( assert len(session.exec(select(ReportRun)).all()) == 2 -def test_manual_rerun_requires_an_idempotency_key(sessions) -> None: - with sessions(expire_on_commit=True) as session: - report = _create_report(session) - - with pytest.raises(ValueError, match="require an idempotency key"): - create_report_run( - session, - report_id=report.id, - inputs=ReportRunInputs( - versions=ReportRunPackageVersions( - country_package_version="1.2.3", - policyengine_version=DEPLOYED_POLICYENGINE_VERSION, - ), - simulation_runs=SIMULATION_RUNS, - ), - trigger=ReportRunTrigger.MANUAL, - ) - - def test_idempotency_key_round_trips_as_a_python_uuid(sessions) -> None: with sessions(expire_on_commit=True) as session: report = _create_report(session) @@ -251,7 +228,6 @@ def request_rerun() -> UUID: ), simulation_runs=SIMULATION_RUNS, ), - trigger=ReportRunTrigger.MANUAL, idempotency_key=request_key, ) run_id = run.id diff --git a/tests/unit/v2/test_shared_report_models.py b/tests/unit/v2/test_shared_report_models.py index 367c777cd..4d27c03cb 100644 --- a/tests/unit/v2/test_shared_report_models.py +++ b/tests/unit/v2/test_shared_report_models.py @@ -228,13 +228,10 @@ def test_per_user_columns_of_shared_rows_need_no_value( ) -> None: """A shared row describes no one caller, so the simulation service may omit them. - They go in a later revision; until then they are nullable, with no default, - so a row written without one holds none. + They go in a later revision; until then the table keeps them nullable, so + a row written without them is stored. """ - column = model_columns(table_name)[column_name] - - assert column.nullable - assert column.server_default is None + assert stored_v2_table(table_name).columns[column_name].nullable def test_user_report_run_associations_record_each_users_request_for_a_run() -> None: @@ -403,8 +400,8 @@ def report_run(*, window_year: int | None) -> ReportRun: sqlite_session.commit() -def test_stored_runs_without_a_trigger_read_as_null() -> None: - """The run lists pass on a missing trigger as null (the route tests a label).""" +def test_stored_runs_are_read_without_a_trigger() -> None: + """A shared run has no one trigger: each user's is on their record of it.""" window_run_id = uuid4() run = ReportRun( report_id=uuid4(), @@ -412,7 +409,6 @@ def test_stored_runs_without_a_trigger_read_as_null() -> None: country_package_version="1.5.0", policyengine_version="4.2.0", status=ReportRunStatus.PENDING, - trigger=None, ) year_run = ReportRun( report_id=run.report_id, @@ -422,19 +418,17 @@ def test_stored_runs_without_a_trigger_read_as_null() -> None: country_package_version="1.5.0", policyengine_version="4.2.0", status=ReportRunStatus.PENDING, - trigger=None, ) window_run = BudgetWindowRun( id=window_run_id, report_id=run.report_id, tax_benefit_model_version_id=uuid4(), status=ReportRunStatus.PENDING, - trigger=None, ) - assert stored_report_transformations.report_run_read(run).trigger is None + assert not hasattr(stored_report_transformations.report_run_read(run), "trigger") window_read = stored_report_transformations.budget_window_run_read( window_run, [year_run] ) - assert window_read.trigger is None - assert [year.trigger for year in window_read.years] == [None] + assert not hasattr(window_read, "trigger") + assert not any(hasattr(year, "trigger") for year in window_read.years) diff --git a/tests/unit/v2/test_simulation_run_models.py b/tests/unit/v2/test_simulation_run_models.py index 3a17d6059..228d4b43e 100644 --- a/tests/unit/v2/test_simulation_run_models.py +++ b/tests/unit/v2/test_simulation_run_models.py @@ -519,14 +519,12 @@ def test_budget_window_runs_record_each_calculation_of_a_window() -> None: "started_at", "completed_at", "policyengine_version", - "trigger", } assert set(windows.keys()) == {"id"} | required | optional assert all(not windows[name].nullable for name in required) assert all(windows[name].nullable for name in optional) - # A window run has a report run's states and starts for a report run's reasons. + # A window run has a report run's states. assert windows.status.type.name == "v2_report_run_status" - assert windows.trigger.type.name == "v2_report_run_trigger" report_key = _foreign_key("budget_window_runs", "report_id") assert report_key.target == "reports.id" assert report_key.ondelete == "CASCADE"