From 0d635a20b40da28e18608aabacc0b58d74f32f83 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:36:45 +0400 Subject: [PATCH 01/20] Test a cliff result per simulation run and its grants (failing) Each simulation run can have one cliff calculation that hasn't failed, holding its state and, once it succeeds, the run's cliff gap and cliff share. The tests cover the model, its checks and partial unique index, the revision that adds the table, and the grants: the simulation service starts calculations, the Modal workers finish them, the Public API reads them, and the catalog writer and the Stage 12 role can do neither. Co-Authored-By: Claude Opus 5.5 --- .../test_alembic_v2_cliff_impacts.py | 369 ++++++++++++++++++ .../test_v2_simulation_role_privileges.py | 159 +++++++- tests/unit/test_alembic_workflows.py | 1 + tests/unit/v2/test_alembic_v2_revisions.py | 62 ++- tests/unit/v2/test_cliff_impact_models.py | 224 +++++++++++ tests/unit/v2/test_privilege_manifest.py | 33 +- tests/unit/v2/test_simulation_run_models.py | 3 +- 7 files changed, 844 insertions(+), 7 deletions(-) create mode 100644 tests/integration/test_alembic_v2_cliff_impacts.py create mode 100644 tests/unit/v2/test_cliff_impact_models.py diff --git a/tests/integration/test_alembic_v2_cliff_impacts.py b/tests/integration/test_alembic_v2_cliff_impacts.py new file mode 100644 index 000000000..56f9b3013 --- /dev/null +++ b/tests/integration/test_alembic_v2_cliff_impacts.py @@ -0,0 +1,369 @@ +"""Check the cliff impacts revision against disposable Postgres. + +Revision bc334f9877b7, on the user invitations revision f519a77ba122, adds +``cliff_impacts``: one row per cliff calculation of a simulation run, with its +state and, once it succeeds, the run's cliff gap and cliff share. Its status +reuses the ``v2_simulation_status`` type, and it changes no other table. The +downgrade drops the table with its rows and leaves the type, which +``simulation_runs`` still uses. +""" + +from collections.abc import Iterator +from typing import Any +from uuid import UUID, uuid4 + +import pytest +from alembic import command +from sqlalchemy import Connection, Engine, create_engine, inspect, text +from sqlalchemy.exc import IntegrityError +from sqlalchemy.pool import NullPool + +from tests.fixtures.integration.alembic_v2 import ( + alembic_v2_config, + disposable_v2_url, +) +from tests.integration.simulation_rows import ( + RUN_VERSIONS, + insert_public_api_rows, + insert_row, + refused, +) + +USER_INVITATIONS_REVISION = "f519a77ba122" +CLIFF_IMPACTS_REVISION = "bc334f9877b7" +# What a request starting a run's cliff calculation inserts: the conflict +# target names the partial unique index's whole condition. +START_CLIFF_CALCULATION = ( + "INSERT INTO cliff_impacts (id, simulation_run_id, status) " + "VALUES (:id, :simulation_run_id, 'pending') " + "ON CONFLICT (simulation_run_id) WHERE status <> 'failed' DO NOTHING " + "RETURNING id" +) + + +def _schema_shape(engine: Engine) -> dict[str, dict[str, Any]]: + """Reflect every table's columns, keys, indexes and checks.""" + inspector = inspect(engine) + return { + table_name: { + "columns": [ + ( + column["name"], + str(column["type"]), + column["nullable"], + column.get("default"), + ) + for column in inspector.get_columns(table_name) + ], + "primary_key": inspector.get_pk_constraint(table_name), + "foreign_keys": sorted( + ( + key["name"], + key["constrained_columns"], + key["referred_table"], + key["options"].get("ondelete"), + ) + for key in inspector.get_foreign_keys(table_name) + ), + "unique_constraints": sorted( + (unique["name"], unique["column_names"]) + for unique in inspector.get_unique_constraints(table_name) + ), + "indexes": sorted( + ( + index["name"], + index["column_names"], + index["unique"], + index.get("dialect_options", {}).get("postgresql_where"), + ) + for index in inspector.get_indexes(table_name) + ), + "checks": { + check["name"]: check["sqltext"] + for check in inspector.get_check_constraints(table_name) + }, + } + for table_name in inspector.get_table_names(schema="public") + if table_name != "alembic_version" + } + + +def _enum_labels(engine: Engine) -> dict[str, list[str]]: + """Return each enum type in the public schema with its labels in order.""" + with engine.connect() as connection: + rows = connection.execute( + text( + "SELECT type.typname, enum.enumlabel FROM pg_type AS type " + "JOIN pg_enum AS enum ON enum.enumtypid = type.oid " + "JOIN pg_namespace AS namespace ON namespace.oid = type.typnamespace " + "WHERE namespace.nspname = 'public' " + "ORDER BY type.typname, enum.enumsortorder" + ) + ).all() + labels: dict[str, list[str]] = {} + for type_name, label in rows: + labels.setdefault(type_name, []).append(label) + return labels + + +@pytest.fixture +def engine() -> Iterator[Engine]: + """Yield an engine on the disposable database, left at the v2 head.""" + database_engine = create_engine(disposable_v2_url(), poolclass=NullPool) + try: + yield database_engine + finally: + command.upgrade(alembic_v2_config(), "head") + database_engine.dispose() + + +def test_cliff_impacts_revision_adds_only_its_table(engine: Engine) -> None: + """The revision adds one table, with no new enum type, and changes nothing else.""" + config = alembic_v2_config() + + command.upgrade(config, "head") + command.downgrade(config, USER_INVITATIONS_REVISION) + parent_shape = _schema_shape(engine) + parent_enums = _enum_labels(engine) + command.upgrade(config, CLIFF_IMPACTS_REVISION) + revision_shape = _schema_shape(engine) + + assert set(revision_shape) - set(parent_shape) == {"cliff_impacts"} + assert { + table_name: shape + for table_name, shape in revision_shape.items() + if table_name != "cliff_impacts" + } == parent_shape + assert _enum_labels(engine) == parent_enums + cliff_impacts = revision_shape["cliff_impacts"] + assert cliff_impacts["primary_key"]["constrained_columns"] == ["id"] + assert [ + (columns, referred_table, ondelete) + for _name, columns, referred_table, ondelete in cliff_impacts["foreign_keys"] + ] == [(["simulation_run_id"], "simulation_runs", "CASCADE")] + assert cliff_impacts["unique_constraints"] == [] + assert cliff_impacts["indexes"] == [ + ("ix_cliff_impacts_simulation_run_id", ["simulation_run_id"], False, None), + ("ix_cliff_impacts_status_started_at", ["status", "started_at"], False, None), + ( + "uq_cliff_impacts_unfailed", + ["simulation_run_id"], + True, + "(status <> 'failed'::v2_simulation_status)", + ), + ] + assert set(cliff_impacts["checks"]) == { + "ck_cliff_impacts_finished_completion", + "ck_cliff_impacts_result_when_succeeded", + } + with engine.connect() as connection: + column_types = dict( + connection.execute( + text( + "SELECT column_name, udt_name || ':' || is_nullable " + "FROM information_schema.columns " + "WHERE table_schema = 'public' AND table_name = 'cliff_impacts'" + ) + ).all() + ) + assert column_types == { + "id": "uuid:NO", + "created_at": "timestamptz:NO", + "updated_at": "timestamptz:NO", + "simulation_run_id": "uuid:NO", + "status": "v2_simulation_status:NO", + "modal_call_id": "varchar:YES", + "error_message": "varchar:YES", + "started_at": "timestamptz:YES", + "completed_at": "timestamptz:YES", + "cliff_gap": "float8:YES", + "cliff_share": "float8:YES", + } + + +def test_cliff_impacts_downgrade_drops_the_table_and_keeps_the_status_type( + engine: Engine, +) -> None: + """Downgrading drops only the table, so upgrading again works.""" + config = alembic_v2_config() + + command.upgrade(config, "head") + command.downgrade(config, USER_INVITATIONS_REVISION) + + assert "cliff_impacts" not in inspect(engine).get_table_names() + # ``simulation_runs.status`` still uses the type. + assert _enum_labels(engine)["v2_simulation_status"] == [ + "pending", + "running", + "succeeded", + "failed", + ] + + command.upgrade(config, CLIFF_IMPACTS_REVISION) + + assert "cliff_impacts" in inspect(engine).get_table_names() + + +def _insert_simulation_run(connection: Connection) -> UUID: + """Store an economy simulation and one pending run of it.""" + public_api_rows = insert_public_api_rows(connection) + simulation_id = uuid4() + run_id = uuid4() + insert_row( + connection, + "simulations", + id=simulation_id, + simulation_type="economy", + dataset_id=public_api_rows.dataset_id, + tax_benefit_model_version_id=public_api_rows.version_id, + year=2026, + ) + insert_row( + connection, + "simulation_runs", + id=run_id, + simulation_id=simulation_id, + tax_benefit_model_version_id=public_api_rows.version_id, + year=2026, + status="pending", + **RUN_VERSIONS, + ) + return run_id + + +def _start_cliff_calculation(connection: Connection, run_id: UUID) -> UUID | None: + """Insert a pending calculation unless one that hasn't failed exists.""" + return connection.execute( + text(START_CLIFF_CALCULATION), {"id": uuid4(), "simulation_run_id": run_id} + ).scalar_one_or_none() + + +def _fail_cliff_calculation(connection: Connection, calculation_id: UUID) -> None: + connection.execute( + text( + "UPDATE cliff_impacts SET status = 'failed', " + "error_message = 'modal_call_ended: the call ended', " + "completed_at = now() WHERE id = :id" + ), + {"id": calculation_id}, + ) + + +def _cliff_statuses(connection: Connection, run_id: UUID) -> list[str]: + return list( + connection.execute( + text( + "SELECT status::text FROM cliff_impacts " + "WHERE simulation_run_id = :run_id ORDER BY created_at, status" + ), + {"run_id": run_id}, + ).scalars() + ) + + +def test_a_run_starts_one_cliff_calculation_until_it_fails(engine: Engine) -> None: + """Two requests at once start one calculation; a failed one never counts.""" + command.upgrade(alembic_v2_config(), "head") + + with engine.connect() as connection: + transaction = connection.begin() + try: + run_id = _insert_simulation_run(connection) + first_calculation = _start_cliff_calculation(connection, run_id) + joined_calculation = _start_cliff_calculation(connection, run_id) + + assert first_calculation is not None + # The second request joins the pending calculation. + assert joined_calculation is None + with refused(connection, IntegrityError, match="uq_cliff_impacts_unfailed"): + insert_row( + connection, + "cliff_impacts", + id=uuid4(), + simulation_run_id=run_id, + status="running", + ) + + _fail_cliff_calculation(connection, first_calculation) + retried_calculation = _start_cliff_calculation(connection, run_id) + + assert retried_calculation is not None + connection.execute( + text( + "UPDATE cliff_impacts SET status = 'succeeded', " + "cliff_gap = 1.5e9, cliff_share = 0.04, completed_at = now() " + "WHERE id = :id" + ), + {"id": retried_calculation}, + ) + assert _start_cliff_calculation(connection, run_id) is None + assert sorted(_cliff_statuses(connection, run_id)) == [ + "failed", + "succeeded", + ] + finally: + transaction.rollback() + + +@pytest.mark.parametrize( + ("assignments", "check_name"), + [ + ("status = 'succeeded', completed_at = now()", "result_when_succeeded"), + ( + "status = 'succeeded', cliff_gap = 1.0, completed_at = now()", + "result_when_succeeded", + ), + ("cliff_gap = 1.0, cliff_share = 0.1", "result_when_succeeded"), + ( + "status = 'failed', cliff_gap = 1.0, cliff_share = 0.1, " + "completed_at = now()", + "result_when_succeeded", + ), + ("status = 'failed'", "finished_completion"), + ( + "status = 'succeeded', cliff_gap = 1.0, cliff_share = 0.1", + "finished_completion", + ), + ], +) +def test_only_a_finished_calculation_ends_and_only_a_succeeded_one_has_numbers( + engine: Engine, assignments: str, check_name: str +) -> None: + command.upgrade(alembic_v2_config(), "head") + + with engine.connect() as connection: + transaction = connection.begin() + try: + run_id = _insert_simulation_run(connection) + calculation_id = _start_cliff_calculation(connection, run_id) + + with refused( + connection, IntegrityError, match=f"ck_cliff_impacts_{check_name}" + ): + connection.execute( + text(f"UPDATE cliff_impacts SET {assignments} WHERE id = :id"), + {"id": calculation_id}, + ) + finally: + transaction.rollback() + + +def test_a_runs_cliff_calculations_are_deleted_with_it(engine: Engine) -> None: + command.upgrade(alembic_v2_config(), "head") + + with engine.connect() as connection: + transaction = connection.begin() + try: + run_id = _insert_simulation_run(connection) + failed_calculation = _start_cliff_calculation(connection, run_id) + assert failed_calculation is not None + _fail_cliff_calculation(connection, failed_calculation) + _start_cliff_calculation(connection, run_id) + + connection.execute( + text("DELETE FROM simulation_runs WHERE id = :id"), {"id": run_id} + ) + + assert _cliff_statuses(connection, run_id) == [] + finally: + transaction.rollback() diff --git a/tests/integration/test_v2_simulation_role_privileges.py b/tests/integration/test_v2_simulation_role_privileges.py index 2bc48db88..944aeeb9e 100644 --- a/tests/integration/test_v2_simulation_role_privileges.py +++ b/tests/integration/test_v2_simulation_role_privileges.py @@ -1,8 +1,9 @@ """Run the simulation tables' writes as the roles that do them in production. The simulation service creates simulations, reports, their runs, budget-window -runs and household jobs; its Modal workers write their runs' status and -results and their budget-window runs' status; the Public API reads them. Each +runs, household jobs and simulation runs' cliff calculations; its Modal +workers write their runs' and cliff calculations' status and results and +their budget-window runs' status; the Public API reads them. Each role holds only its declared privileges (``policyengine_api/data/v2/privileges.py``), so a statement outside them fails here as it would in staging and production. @@ -561,6 +562,7 @@ def test_each_simulation_role_updates_exactly_its_declared_columns( "report_runs", "household_jobs", "budget_window_runs", + "cliff_impacts", ): updatable = { column @@ -577,3 +579,156 @@ def test_each_simulation_role_updates_exactly_its_declared_columns( connection.execute(text(statement)) else: _refused(connection, statement) + + +# What the simulation service inserts to start a run's cliff calculation, +# unless one that hasn't failed exists. Naming the partial unique index's +# conflict target needs SELECT as well as INSERT. +START_CLIFF_CALCULATION = ( + "INSERT INTO cliff_impacts (id, simulation_run_id, status) " + "VALUES (:id, :simulation_run_id, 'pending') " + "ON CONFLICT (simulation_run_id) WHERE status <> 'failed' DO NOTHING " + "RETURNING id" +) + + +def _start_cliff_calculation(connection: Connection, run_id: object) -> object: + return connection.execute( + text(START_CLIFF_CALCULATION), {"id": uuid4(), "simulation_run_id": run_id} + ).scalar_one_or_none() + + +def test_the_simulation_service_starts_cliff_calculations_and_records_calls( + connection: Connection, managed_v2_roles, public_api_rows: PublicApiRows +) -> None: + """The service inserts a run's calculation once, and records or fails its call. + + It never claims a calculation, writes its numbers, changes the run it + calculates or deletes it. + """ + _act_as(connection, managed_v2_roles.simulation_service) + ids = _create_simulation_rows(connection, public_api_rows) + + calculation_id = _start_cliff_calculation(connection, ids["run"]) + joined_calculation = _start_cliff_calculation(connection, ids["run"]) + recorded = connection.execute( + text( + "UPDATE cliff_impacts SET modal_call_id = 'fc-cliffs', " + "updated_at = now() WHERE id = :id AND status = 'pending' " + "AND modal_call_id IS NULL RETURNING id" + ), + {"id": calculation_id}, + ).scalar_one() + failed = connection.execute( + text( + "UPDATE cliff_impacts SET status = 'failed', " + "error_message = 'modal_refused: refused', completed_at = now(), " + "updated_at = now() WHERE id = :id AND status = 'pending' RETURNING id" + ), + {"id": calculation_id}, + ).scalar_one() + + assert calculation_id is not None + assert joined_calculation is None + assert recorded == failed == calculation_id + for statement in ( + "UPDATE cliff_impacts SET started_at = now() WHERE id = :id", + "UPDATE cliff_impacts SET cliff_gap = 1.0 WHERE id = :id", + "UPDATE cliff_impacts SET simulation_run_id = simulation_run_id WHERE id = :id", + "DELETE FROM cliff_impacts WHERE id = :id", + ): + _refused(connection, statement, id=calculation_id) + + +def test_modal_workers_claim_cliff_calculations_and_write_their_results( + connection: Connection, managed_v2_roles, public_api_rows: PublicApiRows +) -> None: + """A worker claims a pending calculation under its call and finishes it. + + It never inserts a calculation, changes the run it calculates or deletes + one. + """ + _act_as(connection, managed_v2_roles.simulation_service) + ids = _create_simulation_rows(connection, public_api_rows) + calculation_id = _start_cliff_calculation(connection, ids["run"]) + _act_as(connection, managed_v2_roles.modal_worker) + + claimed = connection.execute( + text( + "UPDATE cliff_impacts SET status = 'running', started_at = now(), " + "modal_call_id = 'fc-cliffs', updated_at = now() " + "WHERE id = :id AND status = 'pending' RETURNING id" + ), + {"id": calculation_id}, + ).scalar_one() + succeeded = connection.execute( + text( + "UPDATE cliff_impacts SET status = 'succeeded', cliff_gap = 1.5e9, " + "cliff_share = 0.04, completed_at = now(), updated_at = now() " + "WHERE id = :id AND status = 'running' RETURNING id" + ), + {"id": calculation_id}, + ).scalar_one() + + assert claimed == succeeded == calculation_id + _refused( + connection, + "INSERT INTO cliff_impacts (id, simulation_run_id, status) " + "VALUES (:id, :run_id, 'pending')", + id=uuid4(), + run_id=ids["run"], + ) + for statement in ( + "UPDATE cliff_impacts SET simulation_run_id = simulation_run_id WHERE id = :id", + "DELETE FROM cliff_impacts WHERE id = :id", + ): + _refused(connection, statement, id=calculation_id) + + +def test_the_public_api_reads_cliff_results_and_other_roles_cannot( + connection: Connection, managed_v2_roles, public_api_rows: PublicApiRows +) -> None: + """The Public API reads a report run's two cliff results and writes none. + + The catalog writer and the Stage 12 role can't read them. + """ + _act_as(connection, managed_v2_roles.simulation_service) + ids = _create_simulation_rows(connection, public_api_rows) + calculation_id = _start_cliff_calculation(connection, ids["run"]) + _act_as(connection, managed_v2_roles.modal_worker) + connection.execute( + text( + "UPDATE cliff_impacts SET status = 'succeeded', cliff_gap = 1.5e9, " + "cliff_share = 0.04, completed_at = now() WHERE id = :id" + ), + {"id": calculation_id}, + ) + _act_as(connection, managed_v2_roles.runtime) + + results = connection.execute( + text( + "SELECT cliff_impacts.cliff_gap, cliff_impacts.cliff_share " + "FROM report_runs JOIN cliff_impacts ON cliff_impacts.simulation_run_id " + "IN (report_runs.baseline_simulation_run_id, " + "report_runs.reform_simulation_run_id) " + "WHERE report_runs.id = :id AND cliff_impacts.status = 'succeeded'" + ), + {"id": ids["report_run"]}, + ).all() + + assert [tuple(result) for result in results] == [(1.5e9, 0.04)] + _refused( + connection, + "INSERT INTO cliff_impacts (id, simulation_run_id, status) " + "VALUES (:id, :run_id, 'pending')", + id=uuid4(), + run_id=ids["run"], + ) + _refused( + connection, + "UPDATE cliff_impacts SET cliff_gap = 0 WHERE id = :id", + id=calculation_id, + ) + for role in (managed_v2_roles.stage12, CATALOG_WRITER_ROLE): + _act_as(connection, role) + _refused(connection, "SELECT count(*) FROM cliff_impacts") diff --git a/tests/unit/test_alembic_workflows.py b/tests/unit/test_alembic_workflows.py index 73b063d32..7676d8a93 100644 --- a/tests/unit/test_alembic_workflows.py +++ b/tests/unit/test_alembic_workflows.py @@ -214,6 +214,7 @@ def test_reusable_v2_alembic_check_uses_only_disposable_postgres(): assert "test_alembic_v2_user_types.py" in lifecycle_script assert "test_alembic_v2_withheld_area_codes.py" in lifecycle_script assert "test_alembic_v2_shared_report_keys.py" in lifecycle_script + assert "test_alembic_v2_cliff_impacts.py" in lifecycle_script assert "redis:7.2-alpine" not in workflow assert "RUNTIME_CACHE_TEST_URL" not in workflow assert "test_v2_catalog_installed.py" not in workflow diff --git a/tests/unit/v2/test_alembic_v2_revisions.py b/tests/unit/v2/test_alembic_v2_revisions.py index 2c484b86d..108846b6c 100644 --- a/tests/unit/v2/test_alembic_v2_revisions.py +++ b/tests/unit/v2/test_alembic_v2_revisions.py @@ -21,6 +21,7 @@ POST_BASELINE_TABLE_NAMES = frozenset( { "budget_window_runs", + "cliff_impacts", "countries", "legacy_household_mappings", "legacy_policy_mappings", @@ -66,16 +67,21 @@ # The shared reports revision, on the withheld area codes revision, and parent # of the user invitations revision. SHARED_REPORTS_REVISION = "94dc43079186" -# The user invitations revision, on the shared reports revision. +# The user invitations revision, on the shared reports revision, and parent of +# the cliff impacts revision. USER_INVITATIONS_REVISION = "f519a77ba122" +# The cliff impacts revision, on the user invitations revision. +CLIFF_IMPACTS_REVISION = "bc334f9877b7" def test_v2_revision_chain_has_generated_policy_and_user_identity_changes() -> None: config = Config(str(REPO / "alembic-v2.ini")) script = ScriptDirectory.from_config(config) assert script.get_heads() == [V2_ALEMBIC_HEAD_REVISION] + assert V2_ALEMBIC_HEAD_REVISION == CLIFF_IMPACTS_REVISION assert [revision.revision for revision in script.walk_revisions()] == [ - V2_ALEMBIC_HEAD_REVISION, + CLIFF_IMPACTS_REVISION, + USER_INVITATIONS_REVISION, SHARED_REPORTS_REVISION, WITHHELD_AREA_CODES_REVISION, SPM_AVAILABILITY_REVISION, @@ -1132,3 +1138,55 @@ def test_user_invitations_revision_adds_its_table_and_the_dismissal_column() -> ) assert "ck_user_type_changes_source_allowed" in upgrade assert "source IN ('admin_route', 'script', 'invitation')" in upgrade + + +def test_cliff_impacts_revision_creates_only_its_table_with_one_correction() -> None: + """The revision after user invitations adds ``cliff_impacts``. + + It is generated, creates the table with its two indexes and its partial + unique index, and writes no data. Its one post-generation correction makes + ``status`` reuse the ``v2_simulation_status`` type the baseline created, + which the generated ``create_table`` would create again and fail on; so + the downgrade, which drops only the table, leaves the type to + ``simulation_runs``. + """ + (path,) = (REPO / "migrations/v2/versions").glob(f"{CLIFF_IMPACTS_REVISION}_*.py") + revision = path.read_text(encoding="utf-8") + upgrade = revision[ + revision.index("def upgrade()") : revision.index("def downgrade()") + ] + downgrade = revision[revision.index("def downgrade()") :] + + assert ( + "Generation: uv run alembic -c alembic-v2.ini revision --autogenerate" + in revision + ) + assert f'down_revision: Union[str, None] = "{USER_INVITATIONS_REVISION}"' in ( + revision + ) + assert revision.count("Dialect correction:") == 1 + assert re.search( + r"""name=["']v2_simulation_status["'],\s*create_type=False""", upgrade + ) + assert re.findall(r"""op\.create_table\(\s*["'](\w+)["']""", upgrade) == [ + "cliff_impacts" + ] + assert sorted( + re.findall(r"""op\.create_index\(\s*(?:op\.f\()?["'](\w+)["']""", upgrade) + ) == [ + "ix_cliff_impacts_simulation_run_id", + "ix_cliff_impacts_status_started_at", + "uq_cliff_impacts_unfailed", + ] + assert re.search( + r"""postgresql_where=sa\.text\(["']status <> 'failed'["']\)""", upgrade + ) + assert re.findall(r"""op\.drop_table\(\s*["'](\w+)["']""", downgrade) == [ + "cliff_impacts" + ] + for body in (upgrade, downgrade): + assert "op.execute(" not in body + assert "op.bulk_insert(" not in body + assert ".drop(op.get_bind())" not in body + assert "op.alter_column(" not in upgrade + assert "op.add_column(" not in upgrade diff --git a/tests/unit/v2/test_cliff_impact_models.py b/tests/unit/v2/test_cliff_impact_models.py new file mode 100644 index 000000000..c2009d4bd --- /dev/null +++ b/tests/unit/v2/test_cliff_impact_models.py @@ -0,0 +1,224 @@ +"""Each simulation run can have one cliff result (C1 ยท 24's answer 4b). + +A cliff calculation of a simulation run records its state and, once it +succeeds, the run's cliff gap and cliff share. A run has at most one +calculation that hasn't failed, so two requests asking for its cliffs at once +start one calculation; a failed calculation never counts, and the next request +starts another. The result inherits its run's versions, and is linked to the +run, not to any report. +""" + +from collections.abc import Iterator +from datetime import UTC, datetime +from uuid import UUID, uuid4 + +import pytest +import sqlalchemy as sa +from sqlalchemy.exc import IntegrityError +from sqlalchemy.orm import Session + +from policyengine_api.data.v2.models import ( + V2_METADATA, + CliffImpact, + SimulationRun, + SimulationStatus, +) + +CLIFF_IMPACT_COLUMNS = frozenset( + { + "id", + "created_at", + "updated_at", + "simulation_run_id", + "status", + "modal_call_id", + "error_message", + "started_at", + "completed_at", + "cliff_gap", + "cliff_share", + } +) +UNFAILED_CALCULATIONS = "status <> 'failed'" +FINISHED_STATUSES = frozenset({SimulationStatus.SUCCEEDED, SimulationStatus.FAILED}) + + +def _cliff_impacts() -> sa.Table: + return V2_METADATA.tables["cliff_impacts"] + + +def _checks() -> dict[str, str]: + return { + str(constraint.name): str(constraint.sqltext) + for constraint in _cliff_impacts().constraints + if isinstance(constraint, sa.CheckConstraint) + } + + +def _indexes() -> dict[str, sa.Index]: + return {str(index.name): index for index in _cliff_impacts().indexes} + + +def test_cliff_impacts_hold_one_calculation_of_a_simulation_run() -> None: + """The run it calculates, the calculation's state and the two numbers.""" + cliff_impacts = _cliff_impacts() + + assert set(cliff_impacts.c.keys()) == CLIFF_IMPACT_COLUMNS + assert not cliff_impacts.c.simulation_run_id.nullable + (run_key,) = cliff_impacts.c.simulation_run_id.foreign_keys + assert run_key.target_fullname == "simulation_runs.id" + # The result is part of its run, as poverty and inequality rows are. + assert run_key.ondelete == "CASCADE" + status = cliff_impacts.c.status + assert not status.nullable + assert isinstance(status.type, sa.Enum) + # A cliff calculation has a simulation run's states, in the same type. + assert status.type.name == "v2_simulation_status" + assert status.type.enums == ["pending", "running", "succeeded", "failed"] + assert cliff_impacts.c.modal_call_id.type.length == 255 + for timestamp in ("started_at", "completed_at"): + assert cliff_impacts.c[timestamp].nullable + assert cliff_impacts.c[timestamp].type.timezone + for number in ("cliff_gap", "cliff_share"): + assert cliff_impacts.c[number].nullable + assert isinstance(cliff_impacts.c[number].type, sa.Float) + # No version of its own: it inherits its run's. + assert { + "tax_benefit_model_version_id", + "country_package_version", + "policyengine_version", + "report_run_id", + }.isdisjoint(cliff_impacts.c.keys()) + + +def test_only_a_succeeded_cliff_calculation_has_a_result() -> None: + assert _checks() == { + "ck_cliff_impacts_finished_completion": ( + "status NOT IN ('succeeded', 'failed') OR completed_at IS NOT NULL" + ), + "ck_cliff_impacts_result_when_succeeded": ( + "(cliff_gap IS NULL) = (cliff_share IS NULL) " + "AND (status = 'succeeded') = (cliff_gap IS NOT NULL)" + ), + } + + +def test_a_simulation_run_has_one_cliff_calculation_that_has_not_failed() -> None: + """The partial unique index the simulation service names on conflict.""" + indexes = _indexes() + unfailed = indexes["uq_cliff_impacts_unfailed"] + + assert unfailed.unique + assert tuple(column.name for column in unfailed.columns) == ("simulation_run_id",) + assert str(unfailed.dialect_options["postgresql"]["where"]) == ( + UNFAILED_CALCULATIONS + ) + assert str(unfailed.dialect_options["sqlite"]["where"]) == UNFAILED_CALCULATIONS + # The run's key, for its cascade and for reads that include failed rows, + # and the stuck-run sweep's search by state and age. + assert { + name: tuple(column.name for column in index.columns) + for name, index in indexes.items() + if not index.unique + } == { + "ix_cliff_impacts_simulation_run_id": ("simulation_run_id",), + "ix_cliff_impacts_status_started_at": ("status", "started_at"), + } + + +def test_a_simulation_runs_cliff_calculations_go_with_it() -> None: + relationship = sa.inspect(SimulationRun).relationships["cliff_impacts"] + + assert relationship.mapper.local_table is _cliff_impacts() + assert "delete" in relationship.cascade + assert sa.inspect(CliffImpact).relationships["simulation_run"].mapper.class_ is ( + SimulationRun + ) + + +@pytest.fixture +def sqlite_session() -> Iterator[Session]: + engine = sa.create_engine("sqlite://") + V2_METADATA.create_all(engine) + with Session(engine) as session: + yield session + engine.dispose() + + +def _cliff_calculation( + simulation_run_id: UUID, + *, + status: SimulationStatus = SimulationStatus.PENDING, + cliff_gap: float | None = None, + cliff_share: float | None = None, +) -> CliffImpact: + return CliffImpact( + simulation_run_id=simulation_run_id, + status=status, + completed_at=datetime.now(UTC) if status in FINISHED_STATUSES else None, + cliff_gap=cliff_gap, + cliff_share=cliff_share, + ) + + +def test_sqlite_refuses_a_second_unfailed_cliff_calculation_like_postgres( + sqlite_session: Session, +) -> None: + """Failed calculations stay beside the one that hasn't failed.""" + simulation_run_id = uuid4() + sqlite_session.add_all( + [ + _cliff_calculation(simulation_run_id, status=SimulationStatus.FAILED), + _cliff_calculation(simulation_run_id, status=SimulationStatus.FAILED), + _cliff_calculation( + simulation_run_id, + status=SimulationStatus.SUCCEEDED, + cliff_gap=1.5e9, + cliff_share=0.04, + ), + _cliff_calculation(uuid4(), status=SimulationStatus.RUNNING), + ] + ) + sqlite_session.commit() + + sqlite_session.add(_cliff_calculation(simulation_run_id)) + with pytest.raises(IntegrityError, match="UNIQUE constraint failed: cliff_impacts"): + sqlite_session.commit() + + +@pytest.mark.parametrize( + ("status", "cliff_gap", "cliff_share", "check_name"), + [ + (SimulationStatus.SUCCEEDED, None, None, "ck_cliff_impacts_result_when"), + (SimulationStatus.SUCCEEDED, 1.0, None, "ck_cliff_impacts_result_when"), + (SimulationStatus.PENDING, 1.0, 0.1, "ck_cliff_impacts_result_when"), + (SimulationStatus.FAILED, 1.0, 0.1, "ck_cliff_impacts_result_when"), + (SimulationStatus.RUNNING, None, 0.1, "ck_cliff_impacts_result_when"), + ], +) +def test_sqlite_refuses_numbers_on_any_row_but_a_succeeded_one( + sqlite_session: Session, + status: SimulationStatus, + cliff_gap: float | None, + cliff_share: float | None, + check_name: str, +) -> None: + sqlite_session.add( + _cliff_calculation( + uuid4(), status=status, cliff_gap=cliff_gap, cliff_share=cliff_share + ) + ) + + with pytest.raises(IntegrityError, match=check_name): + sqlite_session.commit() + + +def test_sqlite_refuses_a_finished_cliff_calculation_without_its_end( + sqlite_session: Session, +) -> None: + sqlite_session.add( + CliffImpact(simulation_run_id=uuid4(), status=SimulationStatus.FAILED) + ) + + with pytest.raises(IntegrityError, match="ck_cliff_impacts_finished_completion"): + sqlite_session.commit() diff --git a/tests/unit/v2/test_privilege_manifest.py b/tests/unit/v2/test_privilege_manifest.py index 0a20c74a3..857872b5b 100644 --- a/tests/unit/v2/test_privilege_manifest.py +++ b/tests/unit/v2/test_privilege_manifest.py @@ -45,7 +45,8 @@ PROOF_FIXTURES = PROJECT_ROOT / "rules/fixtures/api.v2.runtime-privileges-declared" STAGE12_PACKAGES = frozenset({"comparison_runs"}) TEST_ENVIRONMENT = "staging" -# The rows the simulation service creates, and the run tables among them. +# The rows the simulation service creates, and the run tables among them. A +# simulation run's cliff calculation is started and finished like a run. SIMULATION_SERVICE_CREATES = frozenset( { "simulations", @@ -54,9 +55,12 @@ "report_runs", "budget_window_runs", "household_jobs", + "cliff_impacts", } ) -RUN_STATUS_TABLES = frozenset({"simulation_runs", "report_runs", "household_jobs"}) +RUN_STATUS_TABLES = frozenset( + {"simulation_runs", "report_runs", "household_jobs", "cliff_impacts"} +) # The run columns the Modal workers update: a run's state and its results. WORKER_RUN_STATE_COLUMNS = frozenset( { @@ -81,6 +85,7 @@ } ), "household_jobs": frozenset({"result"}), + "cliff_impacts": frozenset({"cliff_gap", "cliff_share"}), } # The run columns the simulation service updates: it records a Modal call's ID # when Modal accepts the call, and fails the run when Modal refuses it. @@ -150,6 +155,8 @@ "recalculate", } ), + # A cliff calculation always calculates the run it was inserted for. + "cliff_impacts": frozenset({"simulation_run_id"}), } # The policy, dynamic, household and catalog rows a run needs. RUN_INPUT_TABLES = frozenset( @@ -480,3 +487,25 @@ def test_the_public_api_records_each_users_report_run_requests() -> None: for role, tables in declared.items(): if role != RUNTIME_ROLE: assert tables["user_report_run_associations"] == NO_ACCESS, role + + +def test_cliff_calculations_are_started_by_the_service_and_finished_by_workers() -> ( + None +): + """The simulation service inserts a run's cliff calculation and records its call. + + The Modal worker claims it, writes the cliff gap and share or the failure, + and never inserts one; the Public API reads the results. The catalog + writer and the Stage 12 role can do neither. + """ + declared = declared_privileges(TEST_ENVIRONMENT) + + assert declared[SIMULATION_SERVICE_ROLE]["cliff_impacts"] == READ_INSERT | { + update_columns(*SERVICE_RUN_STATE_COLUMNS) + } + assert declared[MODAL_WORKER_ROLE]["cliff_impacts"] == READ | { + update_columns(*WORKER_RUN_STATE_COLUMNS, "cliff_gap", "cliff_share") + } + assert declared[RUNTIME_ROLE]["cliff_impacts"] == READ + for role in (CATALOG_WRITER_ROLE, stage12_role(TEST_ENVIRONMENT)): + assert declared[role]["cliff_impacts"] == NO_ACCESS, role diff --git a/tests/unit/v2/test_simulation_run_models.py b/tests/unit/v2/test_simulation_run_models.py index 0abdaca73..d3282dcb6 100644 --- a/tests/unit/v2/test_simulation_run_models.py +++ b/tests/unit/v2/test_simulation_run_models.py @@ -46,7 +46,8 @@ "relative_income_effect", "relative_substitution_effect", ) -PER_SIMULATION_RESULT_TABLES = ("inequality", "poverty") +# A simulation run's cliff calculation is one of its results too. +PER_SIMULATION_RESULT_TABLES = ("inequality", "poverty", "cliff_impacts") COMPARISON_RESULT_TABLES = ( "budget_summary", "congressional_district_impacts", From a2b29deac551c48fde6d77b445b2323e8548a338 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:42:11 +0400 Subject: [PATCH 02/20] Record each simulation run's cliff calculations, with grants Add cliff_impacts (revision bc334f9877b7, autogenerated on f519a77ba122): one row per cliff calculation of a simulation run, with its state and, once it succeeds, the run's cliff gap and cliff share. A partial unique index allows one calculation per run that hasn't failed, so identical requests join it and a failed one never counts. The row is deleted with its run, and inherits the run's versions. Its status reuses v2_simulation_status, the revision's one post-generation correction. The simulation service may insert calculations and record or fail their Modal calls, the Modal workers may write their state and results, the Public API may read them, and no other role may touch them. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/test_alembic_v2_lifecycle.sh | 3 +- .../simulation-run-cliff-impacts.added.md | 1 + docs/engineering/skills/alembic-migrations.md | 75 +++++++++++++++- ...7b7_record_each_simulation_run_s_cliff_.py | 86 ++++++++++++++++++ policyengine_api/data/v2/migration_target.py | 2 +- policyengine_api/data/v2/models/__init__.py | 2 + .../data/v2/models/run_results.py | 88 ++++++++++++++++++- .../data/v2/models/simulations.py | 14 ++- policyengine_api/data/v2/privileges.py | 23 +++-- tests/unit/v2/test_alembic_v2_revisions.py | 5 +- 10 files changed, 279 insertions(+), 20 deletions(-) create mode 100644 changelog.d/simulation-run-cliff-impacts.added.md create mode 100644 migrations/v2/versions/bc334f9877b7_record_each_simulation_run_s_cliff_.py diff --git a/.github/scripts/test_alembic_v2_lifecycle.sh b/.github/scripts/test_alembic_v2_lifecycle.sh index b122419df..7b6293df5 100755 --- a/.github/scripts/test_alembic_v2_lifecycle.sh +++ b/.github/scripts/test_alembic_v2_lifecycle.sh @@ -11,4 +11,5 @@ uv run --frozen --extra dev pytest -q \ tests/integration/test_alembic_v2_saved_item_keys.py \ tests/integration/test_alembic_v2_user_types.py \ tests/integration/test_alembic_v2_withheld_area_codes.py \ - tests/integration/test_alembic_v2_shared_report_keys.py + tests/integration/test_alembic_v2_shared_report_keys.py \ + tests/integration/test_alembic_v2_cliff_impacts.py diff --git a/changelog.d/simulation-run-cliff-impacts.added.md b/changelog.d/simulation-run-cliff-impacts.added.md new file mode 100644 index 000000000..3fa2c8e95 --- /dev/null +++ b/changelog.d/simulation-run-cliff-impacts.added.md @@ -0,0 +1 @@ +The v2 database can store one cliff result per simulation run, its cliff gap and cliff share, with the state of its calculation. The simulation service starts each calculation, its Modal workers write the result, and the Public API may read it. diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 157f8aecf..46577ed82 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -255,8 +255,8 @@ and a revision runs once per database, so it can't repair drift. | `policyengine_v2_runtime` | The Public API on Cloud Run | | `policyengine_v2_catalog_writer` | `scripts/publish_v2_metadata_catalog.py`, which also runs `ANALYZE` on seven catalog tables after every publication, with `MAINTAIN` (PostgreSQL 17) | | `policyengine_stage12_` | The simulation API and its Modal worker, on the temporary comparison-run tables | -| `policyengine_v2_simulation_service` | The simulation API on Cloud Run: creates simulations, reports, their runs, budget-window runs and household jobs, and reads the policy, dynamic, household and catalog rows a run needs. It updates only the status, Modal call ID, error and completion columns of the runs and household jobs whose Modal calls it starts, and the status, error and completion columns of a budget-window run, which it fails at once when Modal refuses the calls of the window's first years | -| `policyengine_v2_modal_worker` | The simulation API's Modal workers: write their runs' and household jobs' status and results, and budget-window runs' status, and read the rows a run needs. It updates only a run's status, Modal call ID, error, time and result columns, and a budget-window run's status, error and time columns: each year's coordinator starts the window's next unstarted year when its own year finishes, the last year to finish marks the window succeeded, and a failed year fails it. The workers' code, not the database, keeps a worker to its own run | +| `policyengine_v2_simulation_service` | The simulation API on Cloud Run: creates simulations, reports, their runs, budget-window runs, household jobs and simulation runs' cliff calculations, and reads the policy, dynamic, household and catalog rows a run needs. It updates only the status, Modal call ID, error and completion columns of the runs, household jobs and cliff calculations whose Modal calls it starts, and the status, error and completion columns of a budget-window run, which it fails at once when Modal refuses the calls of the window's first years | +| `policyengine_v2_modal_worker` | The simulation API's Modal workers: write their runs', household jobs' and cliff calculations' status and results, and budget-window runs' status, and read the rows a run needs. It updates only a run's or cliff calculation's status, Modal call ID, error, time and result columns, and a budget-window run's status, error and time columns: each year's coordinator starts the window's next unstarted year when its own year finishes, the last year to finish marks the window succeeded, and a failed year fails it. The workers' code, not the database, keeps a worker to its own run | Every v2 table has an entry for every role, so "no access" is a decision, not an omission. A privilege is declared on the whole table, or with @@ -456,6 +456,8 @@ it publishes that version, with nothing to restore it. Downgrading past the revision is therefore safe only while no version is pruned (no `tax_benefit_model_versions` row has `catalog_values_pruned_at` set). From the head, such a downgrade first runs the later revisions' downgrades: +`bc334f9877b7`'s drops `cliff_impacts` with every simulation run's cliff +results (see "API v2 simulation-run cliff impacts"), `f519a77ba122`'s drops `user_invitations` and needs no recorded change with source `invitation` (see "API v2 user invitations"), `94dc43079186`'s drops every user's report-run record, the simulation and @@ -1012,3 +1014,72 @@ change's source is `invitation`. `test_user_invitations_revision_adds_invitations_and_dismissals_only` and `test_user_invitations_revision_records_invitation_changes_until_downgraded` in `tests/integration/test_alembic_v2_user_types.py` check both. + +### API v2 simulation-run cliff impacts + +Revision `bc334f9877b7` (parent `f519a77ba122`) was autogenerated, with its +ID given by `--rev-id`, after the `CliffImpact` model was added. Each +simulation run can have one cliff result, linked to the run and not to any +report, which every report naming the run shares: cliffs need marginal tax +rates, which recalculate each household with extra earnings, so a shared run +never stores the cliff columns (US national runs keep their region-group +split), and a request that asks for cliffs starts a separate calculation of +the run on its dataset, policy and dynamic. + +It creates `cliff_impacts`, one row per cliff calculation of a simulation run: + +- `simulation_run_id`, a foreign key to `simulation_runs` with `CASCADE`, as + `poverty` and `inequality` have: the result is part of its run, and nothing + references it. A run can be deleted only once no report run names it. +- The calculation's state: `status` (`pending`, `running`, `succeeded` or + `failed`, in the `v2_simulation_status` type simulation runs use), + `modal_call_id`, `error_message` (`code: message`, as runs record theirs), + `started_at` and `completed_at`, with the run tables' check that a + succeeded or failed row has `completed_at` + (`ck_cliff_impacts_finished_completion`). +- The result: `cliff_gap`, the weighted total of the net income people would + lose from a small rise in their earnings, and `cliff_share`, the weighted + number of people on a cliff divided by the weighted number of adults, both + double precision. A succeeded row has both, and no other row has either + (`ck_cliff_impacts_result_when_succeeded`). Neither is range-checked: .py + doesn't keep the share to at most 1, and a filtered simulation with no + adults gives NaN. +- `uq_cliff_impacts_unfailed`, a partial unique index on `simulation_run_id` + where `status <> 'failed'` (also declared for SQLite): a run has at most one + calculation that hasn't failed, and so at most one result. The simulation + service starts one with `INSERT ... ON CONFLICT (simulation_run_id) WHERE + status <> 'failed' DO NOTHING`, so two requests at once start one + calculation and the second joins it. A failed calculation never counts: it + stays as a record, and the next request inserts another. +- An index on `(status, started_at)`, as `simulation_runs` has, for finding + unfinished calculations by age, as the simulation API's stuck-run sweep + does for runs: a calculation whose worker ended without recording its + outcome stays unfinished, and keeps later requests from starting another, + until something fails it. + +A result has no versions of its own: it inherits its run's catalog and +package versions, so it is calculated only for a run on the versions the +simulation API serves. The simulation service may read and insert rows and update their +status, Modal call ID, error and completion columns; the Modal worker may read +them and update their state and result columns, never insert them; the +runtime role may read them; neither simulation role may change the run a row +names or delete a row. The reconcile step after each schema upgrade grants +them. `report_runs`' four cliff columns stay until a later revision drops +them, once the Public API reads cliffs from here. + +It has one post-generation correction, commented in the revision: `status` +reuses the baseline's `v2_simulation_status` type +(`postgresql.ENUM(..., create_type=False)`), as `1356f658347d` does for +`simulation_runs.status`; the generated `create_table` would create the type +again and fail. So the downgrade, which drops only the table, leaves the type +to `simulation_runs`. + +The revision writes no data and changes no other table, and the previous +Public API revision, which doesn't map the table, keeps working at it. The +downgrade drops the table with every calculation and result; a later +calculation of the same runs on the same versions gives the same numbers. +`tests/integration/test_alembic_v2_cliff_impacts.py` checks that nothing +else changes, that the downgrade leaves the type and an upgrade works again, +and the index, checks and delete rule; +`tests/integration/test_v2_simulation_role_privileges.py` runs the writes +and reads as the roles that do them. diff --git a/migrations/v2/versions/bc334f9877b7_record_each_simulation_run_s_cliff_.py b/migrations/v2/versions/bc334f9877b7_record_each_simulation_run_s_cliff_.py new file mode 100644 index 000000000..b9bd3badd --- /dev/null +++ b/migrations/v2/versions/bc334f9877b7_record_each_simulation_run_s_cliff_.py @@ -0,0 +1,86 @@ +"""record each simulation run's cliff calculations + +Revision ID: bc334f9877b7 +Revises: f519a77ba122 +Create Date: 2026-11-17 17:38:09.806260 +Generation: uv run alembic -c alembic-v2.ini revision --autogenerate --rev-id bc334f9877b7 + +One post-generation correction, commented where it is made: +cliff_impacts.status reuses the existing v2_simulation_status type instead of +creating it again. + +Each simulation run can have one cliff result: its cliff gap and cliff share, +linked to the run and not to any report. It adds cliff_impacts, one row per +cliff calculation of a simulation run, holding the calculation's state +(status, Modal call, error and times) and, once it succeeds, the two numbers. +A partial unique index allows one calculation per run that hasn't failed, so +identical requests join it; a failed calculation never counts. Deleting a run +deletes its calculations. A result has no versions of its own: it inherits its +run's. + +It writes no data and changes no other table, and the previous Public API +revision, which doesn't map the table, keeps working at it. The downgrade +drops the table with every calculation and result, and leaves the type, +which simulation_runs still uses. +""" + +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +import sqlmodel +from sqlalchemy.dialects import postgresql + + +revision: str = 'bc334f9877b7' +down_revision: Union[str, None] = 'f519a77ba122' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('cliff_impacts', + sa.Column('id', sa.Uuid(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False), + sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False), + sa.Column('simulation_run_id', sa.Uuid(), nullable=False), + sa.Column( + 'status', + # Dialect correction: a cliff calculation has a simulation run's + # states, so the column reuses the baseline's v2_simulation_status + # type instead of creating it again, which would fail. + postgresql.ENUM( + 'pending', + 'running', + 'succeeded', + 'failed', + name='v2_simulation_status', + create_type=False, + ), + nullable=False, + ), + sa.Column('modal_call_id', sqlmodel.sql.sqltypes.AutoString(length=255), nullable=True), + sa.Column('error_message', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('started_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('completed_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('cliff_gap', sa.Float(), nullable=True), + sa.Column('cliff_share', sa.Float(), nullable=True), + sa.CheckConstraint("(cliff_gap IS NULL) = (cliff_share IS NULL) AND (status = 'succeeded') = (cliff_gap IS NOT NULL)", name=op.f('ck_cliff_impacts_result_when_succeeded')), + sa.CheckConstraint("status NOT IN ('succeeded', 'failed') OR completed_at IS NOT NULL", name=op.f('ck_cliff_impacts_finished_completion')), + sa.ForeignKeyConstraint(['simulation_run_id'], ['simulation_runs.id'], name=op.f('fk_cliff_impacts_simulation_run_id_simulation_runs'), ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id', name=op.f('pk_cliff_impacts')) + ) + op.create_index(op.f('ix_cliff_impacts_simulation_run_id'), 'cliff_impacts', ['simulation_run_id'], unique=False) + op.create_index('ix_cliff_impacts_status_started_at', 'cliff_impacts', ['status', 'started_at'], unique=False) + op.create_index('uq_cliff_impacts_unfailed', 'cliff_impacts', ['simulation_run_id'], unique=True, postgresql_where=sa.text("status <> 'failed'"), sqlite_where=sa.text("status <> 'failed'")) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index('uq_cliff_impacts_unfailed', table_name='cliff_impacts', postgresql_where=sa.text("status <> 'failed'"), sqlite_where=sa.text("status <> 'failed'")) + op.drop_index('ix_cliff_impacts_status_started_at', table_name='cliff_impacts') + op.drop_index(op.f('ix_cliff_impacts_simulation_run_id'), table_name='cliff_impacts') + op.drop_table('cliff_impacts') + # ### end Alembic commands ### diff --git a/policyengine_api/data/v2/migration_target.py b/policyengine_api/data/v2/migration_target.py index b51fd461c..21c2a2a5c 100644 --- a/policyengine_api/data/v2/migration_target.py +++ b/policyengine_api/data/v2/migration_target.py @@ -24,7 +24,7 @@ from collections.abc import Mapping V2_ALEMBIC_DISPOSABLE_TEST = "V2_ALEMBIC_DISPOSABLE_TEST" -V2_ALEMBIC_HEAD_REVISION = "f519a77ba122" +V2_ALEMBIC_HEAD_REVISION = "bc334f9877b7" DISPOSABLE_DATABASE_NAME = "policyengine_v2_alembic_test" DISPOSABLE_HOSTS = frozenset({"localhost", "127.0.0.1", "::1", "postgres"}) MIGRATION_ROLE = "policyengine_v2_migrator" diff --git a/policyengine_api/data/v2/models/__init__.py b/policyengine_api/data/v2/models/__init__.py index 973eb9c11..dfa9c0bdf 100644 --- a/policyengine_api/data/v2/models/__init__.py +++ b/policyengine_api/data/v2/models/__init__.py @@ -78,6 +78,7 @@ AggregateType, BudgetSummary, ChangeAggregate, + CliffImpact, CongressionalDistrictImpact, ConstituencyImpact, DecileImpact, @@ -124,6 +125,7 @@ "CatalogEntity", "CatalogEnumValue", "ChangeAggregate", + "CliffImpact", "CongressionalDistrictImpact", "ConstituencyImpact", "Country", diff --git a/policyengine_api/data/v2/models/run_results.py b/policyengine_api/data/v2/models/run_results.py index 2e691bd2f..3451515bf 100644 --- a/policyengine_api/data/v2/models/run_results.py +++ b/policyengine_api/data/v2/models/run_results.py @@ -2,10 +2,11 @@ Results that compare a report run's baseline and reform belong to the report run and name its two simulation runs; each such row is unique within its report -run. Poverty and inequality, which describe one simulation, belong to a -simulation run. +run. Poverty, inequality and cliff impacts, which describe one simulation, +belong to a simulation run. """ +from datetime import datetime from enum import StrEnum from typing import Any from uuid import UUID @@ -13,9 +14,16 @@ import sqlalchemy as sa from sqlmodel import Field, Relationship -from policyengine_api.data.v2.models.base import IdentifiedModel, enum_type +from policyengine_api.data.v2.models.base import ( + IdentifiedModel, + TimestampedModel, + enum_type, +) from policyengine_api.data.v2.models.reports import ReportRun -from policyengine_api.data.v2.models.simulations import SimulationRun +from policyengine_api.data.v2.models.simulations import ( + SimulationRun, + SimulationStatus, +) class OutputStatus(StrEnum): @@ -401,6 +409,78 @@ class Poverty(IdentifiedModel, table=True): simulation_run: SimulationRun = Relationship(back_populates="poverty_results") +# The cliff calculations a new request may join, of which a simulation run has +# at most one: a failed calculation never counts. +UNFAILED_CLIFF_CALCULATIONS = "status <> 'failed'" + + +class CliffImpact(TimestampedModel, table=True): + """One cliff calculation of a simulation run, and its result once it succeeds. + + ``cliff_gap`` is the weighted total of the net income people would lose + from a small rise in their earnings, and ``cliff_share`` the weighted + number of people on a cliff divided by the weighted number of adults. + They need marginal tax rates, which recalculate each household with extra + earnings, so a run's cliffs are calculated apart from the run, on its + dataset, policy and dynamic, only when a request asks for them, and only + for a run on the current versions. The result has no versions of its own: + it inherits its run's, and every report naming the run shares it. + + The simulation service inserts a pending calculation and records its + Modal call, or fails it when Modal refuses the call; the Modal worker + claims it under its call, then writes the two numbers with ``succeeded``, + or ``failed`` with its ``code: message`` error. A run has at most one + calculation that hasn't failed, which identical requests join; a failed + calculation never counts, and the next request starts another. Deleting + the run deletes its calculations. + """ + + __tablename__ = "cliff_impacts" + __table_args__ = ( + sa.CheckConstraint( + "status NOT IN ('succeeded', 'failed') OR completed_at IS NOT NULL", + name="ck_cliff_impacts_finished_completion", + ), + sa.CheckConstraint( + "(cliff_gap IS NULL) = (cliff_share IS NULL) " + "AND (status = 'succeeded') = (cliff_gap IS NOT NULL)", + name="ck_cliff_impacts_result_when_succeeded", + ), + sa.Index("ix_cliff_impacts_status_started_at", "status", "started_at"), + sa.Index( + "uq_cliff_impacts_unfailed", + "simulation_run_id", + unique=True, + postgresql_where=sa.text(UNFAILED_CLIFF_CALCULATIONS), + sqlite_where=sa.text(UNFAILED_CLIFF_CALCULATIONS), + ), + ) + + simulation_run_id: UUID = Field( + foreign_key="simulation_runs.id", + ondelete="CASCADE", + index=True, + ) + status: SimulationStatus = Field( + default=SimulationStatus.PENDING, + sa_type=enum_type(SimulationStatus, "v2_simulation_status"), + ) + modal_call_id: str | None = Field(default=None, max_length=255) + error_message: str | None = None + started_at: datetime | None = Field( + default=None, + sa_type=sa.DateTime(timezone=True), + ) + completed_at: datetime | None = Field( + default=None, + sa_type=sa.DateTime(timezone=True), + ) + cliff_gap: float | None = None + cliff_share: float | None = None + + simulation_run: SimulationRun = Relationship(back_populates="cliff_impacts") + + class ProgramStatistics(IdentifiedModel, table=True): """Baseline and reform totals, counts, winners and losers for one program. diff --git a/policyengine_api/data/v2/models/simulations.py b/policyengine_api/data/v2/models/simulations.py index ca213d3fb..28ba6b052 100644 --- a/policyengine_api/data/v2/models/simulations.py +++ b/policyengine_api/data/v2/models/simulations.py @@ -24,7 +24,11 @@ if TYPE_CHECKING: from policyengine_api.data.v2.models.reports import Report - from policyengine_api.data.v2.models.run_results import Inequality, Poverty + from policyengine_api.data.v2.models.run_results import ( + CliffImpact, + Inequality, + Poverty, + ) class SimulationStatus(StrEnum): @@ -168,7 +172,9 @@ class SimulationRun(TimestampedModel, table=True): dataset can't be deleted while a run names them, and deleting the region clears the reference. A household simulation's run stores its household in ``household_result``; an economy run's output file is ``output_uri``, with - its SHA-256. Each poverty and inequality result belongs to one run. + its SHA-256. Each poverty and inequality result belongs to one run, and so + does each calculation of its cliff impact (``CliffImpact``), which a + request asking for cliffs starts apart from the run. A simulation has at most one run that hasn't failed for each year, catalog version and pair of package versions, which identical requests join; a @@ -268,3 +274,7 @@ class SimulationRun(TimestampedModel, table=True): back_populates="simulation_run", cascade_delete=True, ) + cliff_impacts: list["CliffImpact"] = Relationship( + back_populates="simulation_run", + cascade_delete=True, + ) diff --git a/policyengine_api/data/v2/privileges.py b/policyengine_api/data/v2/privileges.py index ba116de22..5a27d1d6f 100644 --- a/policyengine_api/data/v2/privileges.py +++ b/policyengine_api/data/v2/privileges.py @@ -29,20 +29,22 @@ analyzes afterwards; its code isn't organized as connector modules, so the deploy check, not the connector analysis, covers it. - ``policyengine_v2_simulation_service``: the simulation API on Cloud Run. It - creates simulations, reports, their runs, budget-window runs and household - jobs, and reads the policy, dynamic, household and catalog rows a run needs. - It starts the Modal calls of runs and household jobs, so it may update their + creates simulations, reports, their runs, budget-window runs, household + jobs and simulation runs' cliff calculations, and reads the policy, + dynamic, household and catalog rows a run needs. It starts the Modal calls + of runs, household jobs and cliff calculations, so it may update their status, Modal call ID, error and completion columns: it records a call's ID once Modal accepts the call, and fails the run when Modal refuses it. It starts a budget-window run's first years at submit, so it may update the window run's status, error and completion columns, to fail it at once when Modal refuses those years' calls. - ``policyengine_v2_modal_worker``: the simulation API's Modal workers. They - write the status of the runs and household jobs they were given, and their - results, and read the rows a run needs. They also write a budget-window - run's status, error and times: each year's coordinator starts the window's - next unstarted year when its own year finishes, the last year to finish - marks the window succeeded, and a failed year fails it. + write the status of the runs, household jobs and cliff calculations they + were given, and their results, and read the rows a run needs. They also + write a budget-window run's status, error and times: each year's + coordinator starts the window's next unstarted year when its own year + finishes, the last year to finish marks the window succeeded, and a failed + year fails it. Both simulation API roles update only the columns ``update_columns`` names, so the database refuses any change to what a run is (its simulation or report, @@ -267,6 +269,11 @@ def _run_table( "reports": replace(_SIMULATION_DEFINITION, catalog_writer=READ), "simulation_runs": _run_table("output_uri", "output_sha256", "household_result"), "simulations": replace(_SIMULATION_DEFINITION, catalog_writer=READ), + # A simulation run's cliff calculations, started and finished as a run is: + # the simulation service inserts one and records or fails its Modal call, + # and the Modal worker claims it and writes its cliff gap and share. Neither + # may change the run a calculation names. + "cliff_impacts": _run_table("cliff_gap", "cliff_share"), # Results of simulation runs and report runs. "labor_supply_decile_responses": _RESULT, "labor_supply_responses": _RESULT, diff --git a/tests/unit/v2/test_alembic_v2_revisions.py b/tests/unit/v2/test_alembic_v2_revisions.py index 108846b6c..326a811f7 100644 --- a/tests/unit/v2/test_alembic_v2_revisions.py +++ b/tests/unit/v2/test_alembic_v2_revisions.py @@ -1161,8 +1161,9 @@ def test_cliff_impacts_revision_creates_only_its_table_with_one_correction() -> "Generation: uv run alembic -c alembic-v2.ini revision --autogenerate" in revision ) - assert f'down_revision: Union[str, None] = "{USER_INVITATIONS_REVISION}"' in ( - revision + assert re.search( + rf"""down_revision: Union\[str, None\] = ["']{USER_INVITATIONS_REVISION}["']""", + revision, ) assert revision.count("Dialect correction:") == 1 assert re.search( From becca3b366955769bde10cb5d71782de4bffe52c Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:59:32 +0400 Subject: [PATCH 03/20] Name the cliff impacts revision in the downgrade notes and table lists The Stage 9 and Stage 12A runbooks' downgrade chains now start with bc334f9877b7, and the head foreign-key test counts cliff_impacts among the simulation side's tables. The changelog fragment and the skill section say what each role may do, since the simulation API writes the table only once its own change lands. Co-Authored-By: Claude Opus 5.5 --- changelog.d/simulation-run-cliff-impacts.added.md | 2 +- docs/engineering/skills/alembic-migrations.md | 14 ++++++++------ docs/migration/stage-12a-user-login.md | 4 +++- docs/migration/stage-9-v2-metadata.md | 6 ++++-- .../integration/test_alembic_v2_simulation_runs.py | 5 +++-- 5 files changed, 19 insertions(+), 12 deletions(-) diff --git a/changelog.d/simulation-run-cliff-impacts.added.md b/changelog.d/simulation-run-cliff-impacts.added.md index 3fa2c8e95..f858abb2b 100644 --- a/changelog.d/simulation-run-cliff-impacts.added.md +++ b/changelog.d/simulation-run-cliff-impacts.added.md @@ -1 +1 @@ -The v2 database can store one cliff result per simulation run, its cliff gap and cliff share, with the state of its calculation. The simulation service starts each calculation, its Modal workers write the result, and the Public API may read it. +The v2 database can store one cliff result per simulation run, its cliff gap and cliff share, with the state of its calculation. The simulation service may start each calculation, its Modal workers may write the result, and the Public API may read it. diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 46577ed82..9e0f86351 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -1047,10 +1047,10 @@ It creates `cliff_impacts`, one row per cliff calculation of a simulation run: - `uq_cliff_impacts_unfailed`, a partial unique index on `simulation_run_id` where `status <> 'failed'` (also declared for SQLite): a run has at most one calculation that hasn't failed, and so at most one result. The simulation - service starts one with `INSERT ... ON CONFLICT (simulation_run_id) WHERE - status <> 'failed' DO NOTHING`, so two requests at once start one - calculation and the second joins it. A failed calculation never counts: it - stays as a record, and the next request inserts another. + service is to start one with `INSERT ... ON CONFLICT (simulation_run_id) + WHERE status <> 'failed' DO NOTHING`, so that two requests at once start + one calculation and the second joins it. A failed calculation never counts: + it stays as a record, and the next request inserts another. - An index on `(status, started_at)`, as `simulation_runs` has, for finding unfinished calculations by age, as the simulation API's stuck-run sweep does for runs: a calculation whose worker ended without recording its @@ -1064,8 +1064,10 @@ status, Modal call ID, error and completion columns; the Modal worker may read them and update their state and result columns, never insert them; the runtime role may read them; neither simulation role may change the run a row names or delete a row. The reconcile step after each schema upgrade grants -them. `report_runs`' four cliff columns stay until a later revision drops -them, once the Public API reads cliffs from here. +them. Until the simulation API writes the table, no run has a cliff +calculation, and its cliffs stay refused. `report_runs`' four cliff columns +stay until a later revision drops them, once the Public API reads cliffs from +here. It has one post-generation correction, commented in the revision: `status` reuses the baseline's `v2_simulation_status` type diff --git a/docs/migration/stage-12a-user-login.md b/docs/migration/stage-12a-user-login.md index d93eec83a..13f8475d8 100644 --- a/docs/migration/stage-12a-user-login.md +++ b/docs/migration/stage-12a-user-login.md @@ -770,7 +770,9 @@ admin; `scripts/set_v2_user_type.py` makes another admin afterwards. `users.primary_country`, so it fails while legacy-only rows, any simulation or report associations, or any unauthenticated user exist. Removing them first deletes users' saved work. From the head, the later revisions' - downgrades run first: the user invitations revision (`f519a77ba122`) drops + downgrades run first: the cliff impacts revision (`bc334f9877b7`) drops + every simulation run's cliff results, the user invitations revision + (`f519a77ba122`) drops every invitation and dismissal and needs no change with source `invitation`, the shared reports revision (`94dc43079186`) drops every user's report-run record, every simulation and report key, the runs' diff --git a/docs/migration/stage-9-v2-metadata.md b/docs/migration/stage-9-v2-metadata.md index 785d4a49a..431a5a148 100644 --- a/docs/migration/stage-9-v2-metadata.md +++ b/docs/migration/stage-9-v2-metadata.md @@ -835,8 +835,10 @@ pruning"). A schema downgrade past revision `334859ef4fec` drops `catalog_last_published_at` and `catalog_values_pruned_at`. From the head, -it first runs the later revisions' downgrades: `f519a77ba122`'s drops -`user_invitations` and needs no recorded change with source `invitation`, +it first runs the later revisions' downgrades: `bc334f9877b7`'s drops +`cliff_impacts` with every simulation run's cliff results, `f519a77ba122`'s +drops `user_invitations` and needs no recorded change with source +`invitation`, `94dc43079186`'s drops `user_report_run_associations` with every user's report-run record, the simulation and report keys, the runs' `forced` markers, the window runs' .py diff --git a/tests/integration/test_alembic_v2_simulation_runs.py b/tests/integration/test_alembic_v2_simulation_runs.py index 7d2ddf406..f70d2fe22 100644 --- a/tests/integration/test_alembic_v2_simulation_runs.py +++ b/tests/integration/test_alembic_v2_simulation_runs.py @@ -72,11 +72,12 @@ } ) # The tables the simulation service and its Modal workers write; the Public API -# writes every other table. withheld_area_codes came in a later revision. +# writes every other table. withheld_area_codes and cliff_impacts came in later +# revisions. SIMULATION_SIDE_TABLES = ( CHANGED_TABLES | NEW_TABLES - | {"aggregates", "change_aggregates", "withheld_area_codes"} + | {"aggregates", "change_aggregates", "withheld_area_codes", "cliff_impacts"} ) # The foreign keys from the simulation service's tables to the Public API's # rows, with their delete rules. From a4be631104c435d6788395ea2a95dc2485d5c4ae Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:56:08 +0400 Subject: [PATCH 04/20] Count cliff_impacts in the import test's v2 table total The v2 metadata now holds 51 tables. Co-Authored-By: Claude Opus 5.5 --- tests/unit/v2/test_import_side_effects.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/v2/test_import_side_effects.py b/tests/unit/v2/test_import_side_effects.py index 9bd2d7389..637e6d406 100644 --- a/tests/unit/v2/test_import_side_effects.py +++ b/tests/unit/v2/test_import_side_effects.py @@ -69,7 +69,7 @@ def reject_ddl(*args, **kwargs): import sys after = set(pathlib.Path.cwd().iterdir()) assert before == after -assert len(V2_METADATA.tables) == 50 +assert len(V2_METADATA.tables) == 51 assert "policyengine_api.data.v2.catalog.initialization" not in sys.modules assert "policyengine_api.data.v2.policy_migration_qualification" not in sys.modules assert "policyengine_api.data.v2.household_migration_qualification" not in sys.modules From ddc422cf6a9be9bb17a0f9a33e7d57f0bdebcdea Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:41:10 +0400 Subject: [PATCH 05/20] Call the service API v1 in the cliff impacts text The changelog fragment, the migrations skill, the revision's docstring and two test docstrings now name the service API v1, and the test of its reads is renamed to match. The revision's schema and grants are unchanged. Co-Authored-By: Claude Opus 5.5 --- changelog.d/simulation-run-cliff-impacts.added.md | 2 +- docs/engineering/skills/alembic-migrations.md | 6 +++--- .../bc334f9877b7_record_each_simulation_run_s_cliff_.py | 4 ++-- tests/integration/test_v2_simulation_role_privileges.py | 6 +++--- tests/unit/v2/test_privilege_manifest.py | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/changelog.d/simulation-run-cliff-impacts.added.md b/changelog.d/simulation-run-cliff-impacts.added.md index f858abb2b..eed61136b 100644 --- a/changelog.d/simulation-run-cliff-impacts.added.md +++ b/changelog.d/simulation-run-cliff-impacts.added.md @@ -1 +1 @@ -The v2 database can store one cliff result per simulation run, its cliff gap and cliff share, with the state of its calculation. The simulation service may start each calculation, its Modal workers may write the result, and the Public API may read it. +The v2 database can store one cliff result per simulation run, its cliff gap and cliff share, with the state of its calculation. The simulation service may start each calculation, its Modal workers may write the result, and API v1 may read it. diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 9e0f86351..5a10cf95d 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -1066,7 +1066,7 @@ runtime role may read them; neither simulation role may change the run a row names or delete a row. The reconcile step after each schema upgrade grants them. Until the simulation API writes the table, no run has a cliff calculation, and its cliffs stay refused. `report_runs`' four cliff columns -stay until a later revision drops them, once the Public API reads cliffs from +stay until a later revision drops them, once API v1 reads cliffs from here. It has one post-generation correction, commented in the revision: `status` @@ -1076,8 +1076,8 @@ reuses the baseline's `v2_simulation_status` type again and fail. So the downgrade, which drops only the table, leaves the type to `simulation_runs`. -The revision writes no data and changes no other table, and the previous -Public API revision, which doesn't map the table, keeps working at it. The +The revision writes no data and changes no other table, and API v1's +previous release, which doesn't map the table, keeps working at it. The downgrade drops the table with every calculation and result; a later calculation of the same runs on the same versions gives the same numbers. `tests/integration/test_alembic_v2_cliff_impacts.py` checks that nothing diff --git a/migrations/v2/versions/bc334f9877b7_record_each_simulation_run_s_cliff_.py b/migrations/v2/versions/bc334f9877b7_record_each_simulation_run_s_cliff_.py index b9bd3badd..ad8b683c8 100644 --- a/migrations/v2/versions/bc334f9877b7_record_each_simulation_run_s_cliff_.py +++ b/migrations/v2/versions/bc334f9877b7_record_each_simulation_run_s_cliff_.py @@ -18,8 +18,8 @@ deletes its calculations. A result has no versions of its own: it inherits its run's. -It writes no data and changes no other table, and the previous Public API -revision, which doesn't map the table, keeps working at it. The downgrade +It writes no data and changes no other table, and API v1's previous +release, which doesn't map the table, keeps working at it. The downgrade drops the table with every calculation and result, and leaves the type, which simulation_runs still uses. """ diff --git a/tests/integration/test_v2_simulation_role_privileges.py b/tests/integration/test_v2_simulation_role_privileges.py index 944aeeb9e..e64be932a 100644 --- a/tests/integration/test_v2_simulation_role_privileges.py +++ b/tests/integration/test_v2_simulation_role_privileges.py @@ -3,7 +3,7 @@ The simulation service creates simulations, reports, their runs, budget-window runs, household jobs and simulation runs' cliff calculations; its Modal workers write their runs' and cliff calculations' status and results and -their budget-window runs' status; the Public API reads them. Each +their budget-window runs' status; API v1 reads them. Each role holds only its declared privileges (``policyengine_api/data/v2/privileges.py``), so a statement outside them fails here as it would in staging and production. @@ -685,10 +685,10 @@ def test_modal_workers_claim_cliff_calculations_and_write_their_results( _refused(connection, statement, id=calculation_id) -def test_the_public_api_reads_cliff_results_and_other_roles_cannot( +def test_api_v1_reads_cliff_results_and_other_roles_cannot( connection: Connection, managed_v2_roles, public_api_rows: PublicApiRows ) -> None: - """The Public API reads a report run's two cliff results and writes none. + """API v1 reads a report run's two cliff results and writes none. The catalog writer and the Stage 12 role can't read them. """ diff --git a/tests/unit/v2/test_privilege_manifest.py b/tests/unit/v2/test_privilege_manifest.py index 857872b5b..7eca8c53d 100644 --- a/tests/unit/v2/test_privilege_manifest.py +++ b/tests/unit/v2/test_privilege_manifest.py @@ -495,7 +495,7 @@ def test_cliff_calculations_are_started_by_the_service_and_finished_by_workers() """The simulation service inserts a run's cliff calculation and records its call. The Modal worker claims it, writes the cliff gap and share or the failure, - and never inserts one; the Public API reads the results. The catalog + and never inserts one; API v1 reads the results. The catalog writer and the Stage 12 role can do neither. """ declared = declared_privileges(TEST_ENVIRONMENT) From c0b879a139e90344e4eb90ce2db26e6bdae079f9 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:13:03 +0400 Subject: [PATCH 06/20] Reach the dynamics revision by a downgrade in its downgrade test The cliff impacts revision now follows the dynamics revision, so the test's upgrade to the dynamics revision from the head did nothing, and its failing downgrade then rolled back the cliff impacts step too, leaving the database at bc334f9877b7. A downgrade to the dynamics revision restores what the test checks: the dynamics downgrade fails and changes nothing while a dynamic is stored. Co-Authored-By: Claude Opus 5.5 --- tests/integration/test_alembic_v2_dynamics.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/integration/test_alembic_v2_dynamics.py b/tests/integration/test_alembic_v2_dynamics.py index 3da55d7cf..79932106a 100644 --- a/tests/integration/test_alembic_v2_dynamics.py +++ b/tests/integration/test_alembic_v2_dynamics.py @@ -323,7 +323,10 @@ def test_the_downgrade_fails_changing_nothing_while_a_dynamic_is_stored( engine: Engine, ) -> None: config = alembic_v2_config() - command.upgrade(config, DYNAMICS_REVISION) + # The fixture leaves the database at the head, which a later revision may + # be, so a downgrade reaches the dynamics revision; an upgrade to an older + # revision does nothing. + command.downgrade(config, DYNAMICS_REVISION) with engine.begin() as connection: rows = insert_public_api_rows(connection) dynamic_id = _insert_dynamic(connection, rows) From ac9f05ca69d0c1538c80426fdf4360c5654d3e80 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:16:18 +0400 Subject: [PATCH 07/20] Check the dynamics downgrade's rollback directly, and reword its comment The failed downgrade leaves legacy_policy_mappings.dynamic_id in place, which the dynamics downgrade drops before the step that fails. Co-Authored-By: Claude Opus 5.5 --- tests/integration/test_alembic_v2_dynamics.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/integration/test_alembic_v2_dynamics.py b/tests/integration/test_alembic_v2_dynamics.py index 79932106a..658e244ca 100644 --- a/tests/integration/test_alembic_v2_dynamics.py +++ b/tests/integration/test_alembic_v2_dynamics.py @@ -323,9 +323,9 @@ def test_the_downgrade_fails_changing_nothing_while_a_dynamic_is_stored( engine: Engine, ) -> None: config = alembic_v2_config() - # The fixture leaves the database at the head, which a later revision may - # be, so a downgrade reaches the dynamics revision; an upgrade to an older - # revision does nothing. + # The fixture upgrades to the head before the test, and the head can be + # later than the dynamics revision, so a downgrade reaches it; an upgrade + # to an older revision does nothing. command.downgrade(config, DYNAMICS_REVISION) with engine.begin() as connection: rows = insert_public_api_rows(connection) @@ -334,6 +334,8 @@ def test_the_downgrade_fails_changing_nothing_while_a_dynamic_is_stored( with pytest.raises(IntegrityError, match="name"): command.downgrade(config, PREVIOUS_REVISION) assert _current_revision(engine) == DYNAMICS_REVISION + mapping_columns = inspect(engine).get_columns("legacy_policy_mappings") + assert "dynamic_id" in {column["name"] for column in mapping_columns} finally: with engine.begin() as connection: connection.execute( From d18a530f48f9fe61bc291b8afe6072166f0d338f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:29:16 +0400 Subject: [PATCH 08/20] Require CI to run the dynamics migration and persistence tests (failing) The V2 Postgres migration lifecycle job is to run test_alembic_v2_dynamics.py, and the cross-database integration job test_v2_dynamic_persistence.py, after the managed roles get their privileges, since it runs as the runtime role. Both came with #4325, and no CI job runs either yet. Co-Authored-By: Claude Opus 5.5 --- tests/unit/test_alembic_workflows.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/unit/test_alembic_workflows.py b/tests/unit/test_alembic_workflows.py index 7676d8a93..334f41380 100644 --- a/tests/unit/test_alembic_workflows.py +++ b/tests/unit/test_alembic_workflows.py @@ -215,6 +215,7 @@ def test_reusable_v2_alembic_check_uses_only_disposable_postgres(): assert "test_alembic_v2_withheld_area_codes.py" in lifecycle_script assert "test_alembic_v2_shared_report_keys.py" in lifecycle_script assert "test_alembic_v2_cliff_impacts.py" in lifecycle_script + assert "test_alembic_v2_dynamics.py" in lifecycle_script assert "redis:7.2-alpine" not in workflow assert "RUNTIME_CACHE_TEST_URL" not in workflow assert "test_v2_catalog_installed.py" not in workflow @@ -251,6 +252,14 @@ def test_reusable_v2_integration_check_runs_the_users_report_run_tests(): assert privileges_applied < workflow.index(module), module +def test_reusable_v2_integration_check_runs_the_dynamic_persistence_tests(): + """Storing dynamics and the v1-to-v2 copy run as the runtime role.""" + workflow = _workflow("v2-integration-check.yml") + + privileges_applied = workflow.index("reconcile_v2_privileges.py apply") + assert privileges_applied < workflow.index("test_v2_dynamic_persistence.py") + + def test_reusable_v2_integration_check_uses_disposable_databases_and_coverage(): workflow = _workflow("v2-integration-check.yml") From dc706b590808705f988342905cee7d96f7e5412d Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:31:22 +0400 Subject: [PATCH 09/20] Run the dynamics migration and persistence tests in CI The V2 Postgres migration lifecycle script now runs test_alembic_v2_dynamics.py after the cliff impacts module, against its own disposable database, and the cross-database integration job runs test_v2_dynamic_persistence.py in its policy persistence step, after the managed roles get their privileges. Both read only V2_MIGRATION_DATABASE_URL, V2_ALEMBIC_DISPOSABLE_TEST and, for the managed roles, DEPLOYMENT_ENVIRONMENT, which each job's env block already sets. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/test_alembic_v2_lifecycle.sh | 3 ++- .github/workflows/v2-integration-check.yml | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/scripts/test_alembic_v2_lifecycle.sh b/.github/scripts/test_alembic_v2_lifecycle.sh index 7b6293df5..aa86cfa4e 100755 --- a/.github/scripts/test_alembic_v2_lifecycle.sh +++ b/.github/scripts/test_alembic_v2_lifecycle.sh @@ -12,4 +12,5 @@ uv run --frozen --extra dev pytest -q \ tests/integration/test_alembic_v2_user_types.py \ tests/integration/test_alembic_v2_withheld_area_codes.py \ tests/integration/test_alembic_v2_shared_report_keys.py \ - tests/integration/test_alembic_v2_cliff_impacts.py + tests/integration/test_alembic_v2_cliff_impacts.py \ + tests/integration/test_alembic_v2_dynamics.py diff --git a/.github/workflows/v2-integration-check.yml b/.github/workflows/v2-integration-check.yml index 61d18738a..3c45278f7 100644 --- a/.github/workflows/v2-integration-check.yml +++ b/.github/workflows/v2-integration-check.yml @@ -75,8 +75,8 @@ jobs: run: uv run --frozen --extra dev python scripts/reconcile_v2_privileges.py verify - name: Test v2 metadata publication, resource routes, the countries list, reports, simulations and users' report runs run: uv run --frozen --extra dev coverage run --branch -m pytest -q tests/integration/test_v2_catalog_publication.py tests/integration/test_v2_catalog_publication_time_periods.py tests/integration/test_v2_catalog_publication_pruning.py tests/integration/test_v2_catalog_spm_availability.py tests/integration/test_v2_catalog_statistics.py tests/integration/test_v2_metadata_routes.py tests/integration/test_v2_country_routes.py tests/integration/test_v2_report_reads.py tests/integration/test_v2_report_creation.py tests/integration/test_v2_budget_window_report_reads.py tests/integration/test_v2_budget_window_report_creation.py tests/integration/test_v2_report_runs.py tests/integration/test_v2_report_reads_by_run.py tests/integration/test_v2_user_report_runs.py tests/integration/test_v2_user_report_run_requesters.py tests/integration/test_v2_user_budget_window_runs.py tests/integration/test_v2_forced_report_reruns.py tests/integration/test_v2_user_report_views.py - - name: Test v2 policy persistence and immediate v1 mirroring - run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_policy_persistence.py tests/integration/test_v1_policy_dual_write.py tests/integration/test_mysql_policy_dual_write.py tests/integration/test_v2_user_policy_mirroring.py tests/integration/test_v1_user_policy_dual_write.py + - name: Test v2 policy and dynamic persistence and immediate v1 mirroring + run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_policy_persistence.py tests/integration/test_v2_dynamic_persistence.py tests/integration/test_v1_policy_dual_write.py tests/integration/test_mysql_policy_dual_write.py tests/integration/test_v2_user_policy_mirroring.py tests/integration/test_v1_user_policy_dual_write.py - name: Test signed-in identity provisioning, user associations, saved detailed-save records and user types run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_user_identity_persistence.py tests/integration/test_v2_user_type_persistence.py tests/integration/test_v2_saved_detailed_save_records.py tests/integration/test_v2_saved_budget_window_reports.py - name: Test comparison-run persistence, the simulation API's roles, shared reports and runs, and privilege reconciliation as the managed roles From 22616f102a5d1e37538b341ba25483b437f1cb4c Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:41:53 +0400 Subject: [PATCH 10/20] Check the dynamics tests' target first, and keep them out of the integration job The dynamics migration tests' engine fixture now checks that the target is the disposable database before upgrading it, as the cliff impacts fixture does, so without one the tests are skipped instead of migrating whatever is configured. The integration workflow test now also requires that those migration tests stay out of that job, and says why in its docstring. Co-Authored-By: Claude Opus 5.5 --- tests/integration/test_alembic_v2_dynamics.py | 4 +++- tests/unit/test_alembic_workflows.py | 8 +++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/tests/integration/test_alembic_v2_dynamics.py b/tests/integration/test_alembic_v2_dynamics.py index 658e244ca..819344839 100644 --- a/tests/integration/test_alembic_v2_dynamics.py +++ b/tests/integration/test_alembic_v2_dynamics.py @@ -40,8 +40,10 @@ @pytest.fixture def engine() -> Iterator[Engine]: """Yield an engine on a database at head, and leave it at head.""" + # Check that the target is the disposable database before migrating it. + database_url = disposable_v2_url() command.upgrade(alembic_v2_config(), "head") - database_engine = create_engine(disposable_v2_url()) + database_engine = create_engine(database_url) try: yield database_engine finally: diff --git a/tests/unit/test_alembic_workflows.py b/tests/unit/test_alembic_workflows.py index 334f41380..b1f49c857 100644 --- a/tests/unit/test_alembic_workflows.py +++ b/tests/unit/test_alembic_workflows.py @@ -253,11 +253,17 @@ def test_reusable_v2_integration_check_runs_the_users_report_run_tests(): def test_reusable_v2_integration_check_runs_the_dynamic_persistence_tests(): - """Storing dynamics and the v1-to-v2 copy run as the runtime role.""" + """The dynamic persistence tests run after the managed roles get their privileges. + + The dynamics revision's migration tests downgrade and upgrade the schema, + which would drop tables the job granted privileges on, so they run in the + lifecycle job instead. + """ workflow = _workflow("v2-integration-check.yml") privileges_applied = workflow.index("reconcile_v2_privileges.py apply") assert privileges_applied < workflow.index("test_v2_dynamic_persistence.py") + assert "test_alembic_v2_dynamics.py" not in workflow def test_reusable_v2_integration_check_uses_disposable_databases_and_coverage(): From cc86a0f96133a1885899b0c77cd1794ea5ab9997 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:00:36 +0400 Subject: [PATCH 11/20] Require every database statement to go through the ORM (failing) Adds rule api.data.orm-only: code that reads or writes database rows declares tables only as SQLAlchemy ORM mapped classes, SQLModel classes included, and runs every statement through an ORM Session against them, never through Core Table objects, Connections or handwritten SQL, apart from the registry's named exceptions. It scans production code, scripts and tests, as strictly as sim's sim.persistence.orm-only, whose checker this ports with SQLModel treated as the ORM. The rule test fails for now: it finds 1,692 places in 131 files, which the following commits rewrite. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- docs/engineering/skills/alembic-migrations.md | 123 ++ docs/engineering/skills/rules-registry.md | 2 +- docs/generated/rules.md | 12 +- .../api.data.orm-only/bad_simulation_rows.py | 65 + .../api.data.orm-only/good_simulation_rows.py | 78 ++ rules/registry.toml | 35 + tests/unit/data/orm_access_support.py | 977 +++++++++++++++ tests/unit/data/test_orm_access_support.py | 1067 +++++++++++++++++ tests/unit/data/test_orm_only.py | 206 ++++ 10 files changed, 2562 insertions(+), 5 deletions(-) create mode 100644 rules/fixtures/api.data.orm-only/bad_simulation_rows.py create mode 100644 rules/fixtures/api.data.orm-only/good_simulation_rows.py create mode 100644 tests/unit/data/orm_access_support.py create mode 100644 tests/unit/data/test_orm_access_support.py create mode 100644 tests/unit/data/test_orm_only.py diff --git a/AGENTS.md b/AGENTS.md index 50694e54c..89d0b658b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -108,7 +108,7 @@ To add or change a rule, read `docs/engineering/skills/rules-registry.md`. ### Runtime persistence and route boundaries -- Checked: `api.data.runtime-sql-confined`, `api.data.sqlalchemy-and-alembic-only`, `api.legacy.removed-layers-stay-removed`, `api.routes.flask-blueprints-own-urls`, `api.routes.no-domain-logic-in-http`, `api.routes.no-inline-json-errors`, `api.services.no-direct-queries`, `api.services.session-ownership` +- Checked: `api.data.orm-only`, `api.data.runtime-sql-confined`, `api.data.sqlalchemy-and-alembic-only`, `api.legacy.removed-layers-stay-removed`, `api.routes.flask-blueprints-own-urls`, `api.routes.no-domain-logic-in-http`, `api.routes.no-inline-json-errors`, `api.services.no-direct-queries`, `api.services.session-ownership` ### Import and startup side effects diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 98ac08c83..b0e85d5e2 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -163,6 +163,129 @@ relational database. This rule does not cover it. autogenerated, never hand-written. - `api.startup.no-import-side-effects`: importing v2 modules, starting up and serving a request open no network connections. +- `api.data.orm-only`: every statement runs through an ORM Session on mapped + classes (see the next section). + +## Database statements through the ORM + +Rule `api.data.orm-only`: code that reads or writes database rows declares +tables only as SQLAlchemy ORM mapped classes, SQLModel classes included, and +runs every statement through an ORM `Session` against those classes. It never +uses Core `Table` objects, `Connection`s or handwritten SQL, apart from the +rule's named exceptions. It covers production code, scripts and tests. + +`tests/unit/data/test_orm_only.py` reads every Python file under +`policyengine_api/`, `scripts/`, `tests/` and `.github/`. It doesn't read +`migrations/`, which the rule's `migration-revision` exception names, or the +proof fixtures in `rules/fixtures/`. The checks are in +`tests/unit/data/orm_access_support.py`, a port of policyengine-sim-api's +checker for `sim.persistence.orm-only`. They check each file on its own, +through the file's own imports of `sqlalchemy` and `sqlmodel`: SQLModel +re-exports SQLAlchemy's names, so `from sqlmodel import text` counts as +SQLAlchemy's `text`. They report four kinds of finding: + +- **Core table declaration**: `Table(...)`, `Column(...)`, `table(...)`, + `column(...)` and their clause classes, and `MetaData(...)` outside a + declarative-base module. +- **Core table access**: a table read from a mapped class, a mapper or a + `MetaData` (`__table__`, `local_table`, `metadata.tables`, a column's + `.table`), and an annotation naming `Table` or `TableClause`. +- **Core engine or connection**: importing `Engine`, `create_engine` or + `Connection` outside a session-factory module; opening a Connection there + (`connect()`, `connection()`, `get_bind()`, or `begin()` on an engine); + `raw_connection()` in any module; `execute()` on anything not named as a + session, and `scalar()`, `scalars()`, `stream()` or `stream_scalars()` on a + name such as `connection`; listening for pool, engine or dialect events + (`connect`, `checkout`, `before_cursor_execute`, `handle_error` and the + rest) outside a session-factory module; and a public function of a + session-factory module that returns an `Engine` or `Connection`. +- **raw SQL**: `text()`, `literal_column()`, `exec_driver_sql()` and + `cursor()`, apart from `text()` given as a server default, a partial + index's condition or a check constraint's condition. + +`test_every_table_is_mapped_by_a_class` imports `policyengine_api.data` and +the test modules that write rows, and reports every table they hold that no +mapped class maps, including tables built in ways the source checks can't see. + +Two kinds of module have a role of their own: + +- **Session-factory modules** are the only modules that may create or hold an + Engine, open a Connection or attach pool events: + `policyengine_api/data/orm.py`, `policyengine_api/data/v2/database.py`, and + `tests/fixtures/database_sessions.py` for the tests. They hand out Session + factories, never an Engine or a Connection. When a module needs its own + engine settings, such as `NullPool`, a deploy-time role or a separate URL, + the session-factory module gets a function that returns a Session factory + with them. +- **Declarative-base modules** are the only modules that may build + `MetaData`: `policyengine_api/data/v1_models.py`, + `policyengine_api/data/v2/models/__init__.py`, and + `policyengine_api/data/v2/catalog/publication_staging_base.py`, the + publication staging tables' own declarative base. + +### Writing each kind of statement + +- **Rows**: `session.add(Model(...))` and `session.add_all(...)`; + `session.execute(insert(Model).values(...))`, including + `sqlalchemy.dialects.postgresql.insert(Model).on_conflict_do_nothing(...)`; + and `update(Model)`, `delete(Model)`, `select(Model)` and + `select(Model.column)` in `session.execute` or `session.scalars`. A test + helper such as `insert_row(connection, "table", **values)` becomes + `add_row(session, Model, **values)`, given a mapped class. +- **Postgres functions**: `func`, as in + `session.execute(select(func.current_database(), func.current_user()))`, + `func.pg_backend_pid()` and `func.has_table_privilege(...)`. +- **Schema reads**: SQLAlchemy's `Inspector`, which a function in a + session-factory module returns for a Session factory or a Session. Never + select from `information_schema` or `pg_catalog` with SQL text. +- **Roles in tests**: `act_as(session, role)` and `act_as_owner(session)` in + the test session module, which run `SET ROLE` and `RESET ROLE` inside the + session's transaction (a named exception), or a Session factory whose + engine runs `SET ROLE` when it connects. Setup rows stay in the same + rolled-back transaction where a test relies on that. +- **Refusals**: `refused(session, ...)` runs the statements inside it in + `session.begin_nested()` and expects the error. +- **TRUNCATE in test cleanup**: one helper in the test session module (a + named exception), or `delete(Model)` in dependency order where that is as + simple. +- **COPY**: the publication staging tables are mapped classes on their own + declarative base, not `V2_METADATA`, so Alembic never sees them. They stay + `TEMPORARY` with `ON COMMIT DROP`. COPY through the driver connection stays + the one driver-level exception, and the `INSERT ... SELECT` from the + staging tables into the real tables uses `insert(Model).from_select(...)`. + +### ORM-only exceptions + +The rule's exceptions are its `[[rule.exception]]` entries in +`rules/registry.toml`, which the rule test reads. Each has a `path`, a +`category` and a `reason`: + +- **`no-orm-form`**: one construct in one module that SQLAlchemy's ORM has no + form for. `path` names the module, and `match` is the finding's source + exactly as the check reports it, the text after its kind, such as + `text('RESET ROLE')`. The entry allows every finding in that module with + that source. +- **`migration-revision`**: a path pattern the rule test doesn't read. + +The rule test fails on a finding no entry names, on an entry that names no +finding, and on an entry with an unknown category, a `no-orm-form` entry +without a `match` or an existing file, or a `migration-revision` entry that +names no file. Only statements SQLAlchemy can't express get an entry: `GRANT` +and `REVOKE`, `CREATE`, `ALTER` and `DROP ROLE`, `SET ROLE` and `RESET ROLE`, +`TRUNCATE`, `COPY`, and Postgres session settings. Keep them in as few modules +as possible: the test session module, `privilege_reconciliation.py` and +`publication_staging.py`. The entries: + +1. **Alembic environments and revisions** (`migration-revision`), + `migrations/**/*.py`. The environments run Alembic's migration context on + a Connection, and the revisions are where schema changes belong + (`api.data.sqlalchemy-and-alembic-only`), so the rule test doesn't read + them. + +A new exception is a rule change: add a `[[rule.exception]]` entry to the rule +in `rules/registry.toml`, explain here why the ORM can't express the +statement, and get it reviewed as one. `rules/` is code-owned +(`api.process.rule-machinery-code-owned`). ## API v1 database targets diff --git a/docs/engineering/skills/rules-registry.md b/docs/engineering/skills/rules-registry.md index 3923eeab1..b3a65c0de 100644 --- a/docs/engineering/skills/rules-registry.md +++ b/docs/engineering/skills/rules-registry.md @@ -60,7 +60,7 @@ gap is visible, rather than leaving it out. | `[[rule.ci]]` | `workflow`, `job`, and an `invocation` string that must appear in that job's `run:` text (or its reusable-workflow `uses:`), or in a command of a Makefile target the job runs with `make `, following the targets' prerequisites and the `$(MAKE)` calls in their recipes (`scripts/rules/makefile.py`). | | `[rule.proof]` | Optional; see "Proof". | | `[rule.baseline]` | Only for `ratcheted` rules: `file` listing tolerated violations, and their `count`. | -| `[[rule.exception]]` | Carve-out: `path`, `reason`, and `expires`; or, for rules whose guard reads them, `match` (one site), `removal`, `issue` and `category` ([dependencies.md](dependencies.md#exceptions); for `api.data.sqlalchemy-and-alembic-only`, `match` is the exact construct and `category` is `driver-access`, `schema-change` or `migration-revision`: [alembic-migrations.md](alembic-migrations.md#declared-exceptions)). | +| `[[rule.exception]]` | Carve-out: `path`, `reason`, and `expires`; or, for rules whose guard reads them, `match` (one site), `removal`, `issue` and `category` ([dependencies.md](dependencies.md#exceptions); for `api.data.sqlalchemy-and-alembic-only`, `match` is the exact construct and `category` is `driver-access`, `schema-change` or `migration-revision`: [alembic-migrations.md](alembic-migrations.md#declared-exceptions); for `api.data.orm-only`, `match` is the finding's source and `category` is `no-orm-form` or `migration-revision`: [alembic-migrations.md](alembic-migrations.md#orm-only-exceptions)). | | `[rule.downgrade]` | Required `reason` when a rule moves from enforced/ratcheted to advisory/doc-only. | `blocking` is derived, never declared: a rule blocks merges when its status is diff --git a/docs/generated/rules.md b/docs/generated/rules.md index 3b17654f4..381493f41 100644 --- a/docs/generated/rules.md +++ b/docs/generated/rules.md @@ -8,11 +8,11 @@ Every rule that governs `policyengine-api` is listed here with how it is enforce | Tier | enforced | ratcheted | advisory | doc-only | Total | | --- | ---: | ---: | ---: | ---: | ---: | -| mechanical | 71 | 7 | 1 | 8 | 87 | +| mechanical | 72 | 7 | 1 | 8 | 88 | | metric | 2 | 0 | 0 | 0 | 2 | | judgment | 0 | 0 | 0 | 1 | 1 | -**Blocking:** 80 of 90 rules. +**Blocking:** 81 of 91 rules. ## Gaps @@ -71,6 +71,7 @@ Every rule that governs `policyengine-api` is listed here with how it is enforce ### Exceptions and review dates +- `api.data.orm-only`: exception for `migrations/**/*.py` allowed as a migration-revision (migrations/ holds the Alembic environments and the revisions Alembic generates. The environments run Alembic's migration context on a Connection, and the revisions are where schema changes belong (api.data.sqlalchemy-and-alembic-only), so the rule test doesn't read them.) - `api.data.sqlalchemy-and-alembic-only`: exception for `migrations/*/versions/*.py` allowed as a migration-revision (Alembic generates the revisions, and they are where schema changes belong, so the check doesn't scan them. Ruff skips the same files (extend-exclude in pyproject.toml).) - `api.data.sqlalchemy-and-alembic-only`: exception for `policyengine_api/data/orm_pool_events.py` (`attribute ._sock`) allowed as a driver-access (The v1 pool's diagnostics read the file descriptor and local port of pymysql's socket from the driver connection a SQLAlchemy pool event passes them, because SQLAlchemy has no API for a connection's socket. They never read or write through the socket or the driver connection, and import no driver.) - `api.data.sqlalchemy-and-alembic-only`: exception for `policyengine_api/data/v2/catalog/publication_staging.py` (`attribute .driver_connection`) allowed as a driver-access (Catalog publication runs COPY through the psycopg connection beneath a SQLAlchemy Connection that SQLAlchemy opened and still manages, so the transaction stays SQLAlchemy's.) @@ -164,6 +165,7 @@ flowchart LR | Rule | Statement | Tier | Status | Blocking | Enforced by | CI | Proof | | --- | --- | --- | --- | --- | --- | --- | --- | +| `api.data.orm-only` | Code that reads or writes database rows declares tables only as SQLAlchemy ORM mapped classes, SQLModel classes included, and runs every statement through an ORM Session against those classes. It never uses Core Table objects, Connections or handwritten SQL, apart from the registry's named exceptions. | mechanical | enforced | yes | pytest `tests/unit/data/test_orm_only.py` | `pr.yml:test` | yes | | `api.data.runtime-sql-confined` | Raw SQL is confined to the data-access layer; runtime modules and report orchestration use sessions and mapped models. | mechanical | enforced | yes | pytest `tests/unit/data/test_runtime_sql_boundaries.py` | `pr.yml:test` | **unproven** | | `api.data.sqlalchemy-and-alembic-only` | Code connects to relational databases only through SQLAlchemy engines, connections and sessions, never by calling a database driver directly, and changes persistent schema only through Alembic revisions. | mechanical | enforced | yes | pytest `tests/unit/data/test_database_access_boundaries.py` | `pr.yml:test` | yes | | `api.legacy.removed-layers-stay-removed` | Removed legacy persistence layers, the temporary DAO module and the legacy endpoints package stay removed. | mechanical | enforced | yes | pytest `tests/unit/data/test_runtime_sql_boundaries.py`, `tests/unit/routes/test_flask_route_boundaries.py`, `tests/unit/services/test_orm_service_boundaries.py` | `pr.yml:test` | **unproven** | @@ -175,9 +177,11 @@ flowchart LR ```mermaid flowchart LR + r_api_data_orm_only("api.data.orm-only (enforced)") + e_pytest_tests_unit_data_test_orm_only_py["pytest tests/unit/data/test_orm_only.py"] + j_CI_pr_yml_test["CI pr.yml:test"] r_api_data_runtime_sql_confined("api.data.runtime-sql-confined (enforced)") e_pytest_tests_unit_data_test_runtime_sql_boundaries_py["pytest tests/unit/data/test_runtime_sql_boundaries.py"] - j_CI_pr_yml_test["CI pr.yml:test"] r_api_data_sqlalchemy_and_alembic_only("api.data.sqlalchemy-and-alembic-only (enforced)") e_pytest_tests_unit_data_test_database_access_boundaries_py["pytest tests/unit/data/test_database_access_boundaries.py"] r_api_legacy_removed_layers_stay_removed("api.legacy.removed-layers-stay-removed (enforced)") @@ -190,6 +194,8 @@ flowchart LR e_pytest_tests_unit_services_test_local_data_service_boundaries_py__tests_unit_services_test_orchestration_service_database_boundaries_py__tests_unit_services_test_orm_service_boundaries_py__tests_unit_services_test_run_and_spec_service_database_boundaries_py["pytest tests/unit/services/test_local_data_service_boundaries.py, tests/unit/services/test_orchestration_service_database_boundaries.py, tests/unit/services/test_orm_service_boundaries.py, tests/unit/services/test_run_and_spec_service_database_boundaries.py"] r_api_services_session_ownership("api.services.session-ownership (enforced)") e_pytest_tests_unit_services_test_local_data_service_boundaries_py__tests_unit_services_test_orm_service_boundaries_py["pytest tests/unit/services/test_local_data_service_boundaries.py, tests/unit/services/test_orm_service_boundaries.py"] + r_api_data_orm_only --> e_pytest_tests_unit_data_test_orm_only_py + e_pytest_tests_unit_data_test_orm_only_py --> j_CI_pr_yml_test r_api_data_runtime_sql_confined --> e_pytest_tests_unit_data_test_runtime_sql_boundaries_py e_pytest_tests_unit_data_test_runtime_sql_boundaries_py --> j_CI_pr_yml_test r_api_data_sqlalchemy_and_alembic_only --> e_pytest_tests_unit_data_test_database_access_boundaries_py diff --git a/rules/fixtures/api.data.orm-only/bad_simulation_rows.py b/rules/fixtures/api.data.orm-only/bad_simulation_rows.py new file mode 100644 index 000000000..41eacb4a5 --- /dev/null +++ b/rules/fixtures/api.data.orm-only/bad_simulation_rows.py @@ -0,0 +1,65 @@ +"""Proof fixture: rows written with handwritten SQL on a Core Connection. + +The rule must reject it. ``insert_row``, ``refused`` and ``delete_rows`` are +the row helpers of ``tests/integration/simulation_rows.py`` as of d6693ad36: +they build INSERT and DELETE statements from strings and run them on a +``Connection``, inside a savepoint the Connection opens. ``STAGE_CATALOG_MODELS`` +is the Core table ``tests/unit/v2/test_catalog_publication.py`` declares for +catalog publication's COPY (added in f83b4b5fb), which no mapped class maps. +""" + +from __future__ import annotations + +from contextlib import contextmanager +from typing import TYPE_CHECKING + +import pytest +import sqlalchemy as sa +from sqlalchemy import text +from sqlalchemy.exc import IntegrityError + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator + from uuid import UUID + + from sqlalchemy import Connection + +STAGE_CATALOG_MODELS = sa.Table( + "stage_catalog_models", + sa.MetaData(), + sa.Column("id", sa.Integer), + sa.Column("name", sa.Text), +) + + +def insert_row(connection: Connection, table: str, **values: object) -> None: + """Insert one row of the named columns into ``table``.""" + columns = ", ".join(values) + placeholders = ", ".join(f":{column}" for column in values) + connection.execute( + text(f"INSERT INTO {table} ({columns}) VALUES ({placeholders})"), # noqa: S608 # the handwritten SQL the rule rejects + values, + ) + + +@contextmanager +def refused( + connection: Connection, + error: type[Exception] = IntegrityError, + *, + match: str | None = None, +) -> Iterator[None]: + """Expect the statements inside to fail with ``error``, then roll them back.""" + savepoint = connection.begin_nested() + with pytest.raises(error, match=match): + yield + savepoint.rollback() + + +def delete_rows(connection: Connection, rows: Iterable[tuple[str, UUID]]) -> None: + """Delete each row by its table's name and its id, in the order given.""" + for table, row_id in rows: + connection.execute( + text(f"DELETE FROM {table} WHERE id = :id"), # noqa: S608 # the handwritten SQL the rule rejects + {"id": row_id}, + ) diff --git a/rules/fixtures/api.data.orm-only/good_simulation_rows.py b/rules/fixtures/api.data.orm-only/good_simulation_rows.py new file mode 100644 index 000000000..37c478bb1 --- /dev/null +++ b/rules/fixtures/api.data.orm-only/good_simulation_rows.py @@ -0,0 +1,78 @@ +"""Proof fixture: rows written through an ORM Session on mapped classes. + +The rule must accept it. It is ``bad_simulation_rows.py`` written as the rule +asks: ``add_row`` adds a row of a mapped class, ``refused`` runs the statements +inside it in a savepoint the Session opens, and ``delete_rows`` deletes the v2 +rows with ``delete(Model)``. The staging table is a mapped class on a +declarative base of its own, so it stays out of the v2 metadata. +""" + +from __future__ import annotations + +from contextlib import contextmanager +from typing import TYPE_CHECKING + +import pytest +from sqlalchemy import Integer, Text, delete +from sqlalchemy.exc import IntegrityError +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column + +from policyengine_api.data.v2.models import ( + Dataset, + Household, + TaxBenefitModel, + TaxBenefitModelVersion, +) + +if TYPE_CHECKING: + from collections.abc import Iterator + from uuid import UUID + + from sqlalchemy.orm import Session + + +class StagingBase(DeclarativeBase): + """The staging tables' declarative base, apart from the v2 metadata.""" + + +class StageCatalogModel(StagingBase): + """One staged catalog model.""" + + __tablename__ = "stage_catalog_models" + id: Mapped[int] = mapped_column(Integer, primary_key=True) + name: Mapped[str | None] = mapped_column(Text) + + +def add_row(session: Session, model: type[object], **values: object) -> None: + """Add one row of the mapped class ``model`` and send it to the database.""" + session.add(model(**values)) + session.flush() + + +@contextmanager +def refused( + session: Session, + error: type[Exception] = IntegrityError, + *, + match: str | None = None, +) -> Iterator[None]: + """Expect the statements inside to fail with ``error``, then roll them back.""" + with pytest.raises(error, match=match), session.begin_nested(): + yield + + +def delete_rows( + session: Session, + *, + household_id: UUID, + dataset_id: UUID, + version_id: UUID, + model_id: UUID, +) -> None: + """Delete a household, a dataset, a model version and its model, in that order.""" + session.execute(delete(Household).where(Household.id == household_id)) + session.execute(delete(Dataset).where(Dataset.id == dataset_id)) + session.execute( + delete(TaxBenefitModelVersion).where(TaxBenefitModelVersion.id == version_id) + ) + session.execute(delete(TaxBenefitModel).where(TaxBenefitModel.id == model_id)) diff --git a/rules/registry.toml b/rules/registry.toml index 87a5cf6a8..eb32de3cf 100644 --- a/rules/registry.toml +++ b/rules/registry.toml @@ -617,6 +617,41 @@ path = "migrations/*/versions/*.py" category = "migration-revision" reason = "Alembic generates the revisions, and they are where schema changes belong, so the check doesn't scan them. Ruff skips the same files (extend-exclude in pyproject.toml)." +[[rule]] +id = "api.data.orm-only" +category = "runtime-layers" +statement = "Code that reads or writes database rows declares tables only as SQLAlchemy ORM mapped classes, SQLModel classes included, and runs every statement through an ORM Session against those classes. It never uses Core Table objects, Connections or handwritten SQL, apart from the registry's named exceptions." +rationale = "docs/engineering/skills/alembic-migrations.md#database-statements-through-the-orm" +scope = ["policyengine_api/**/*.py", "scripts/**/*.py", "tests/**/*.py", ".github/**/*.py"] +tier = "mechanical" +status = "enforced" +autofix = false +[rule.enforcer] +kind = "pytest" +nodes = [ + "tests/unit/data/test_orm_only.py::test_database_code_uses_only_the_orm", + "tests/unit/data/test_orm_only.py::test_every_table_is_mapped_by_a_class", + "tests/unit/data/test_orm_only.py::test_orm_only_exceptions_match_a_finding_and_name_a_category", + "tests/unit/data/test_orm_only.py::test_every_scanned_directory_contributes_files", +] +[[rule.ci]] +workflow = ".github/workflows/pr.yml" +job = "test" +invocation = "make test" +[rule.proof] +bad_fixture = "rules/fixtures/api.data.orm-only/bad_simulation_rows.py" +good_fixture = "rules/fixtures/api.data.orm-only/good_simulation_rows.py" +test = "tests/unit/data/test_orm_only.py::test_rule_proof_orm_only" +# Each exception names a module and, in match, the source of the one finding +# there that SQLAlchemy's ORM has no form for (category no-orm-form), or a path +# pattern the rule test doesn't read (category migration-revision). The rule +# test fails on a finding no exception names and on an exception that names +# nothing. +[[rule.exception]] +path = "migrations/**/*.py" +category = "migration-revision" +reason = "migrations/ holds the Alembic environments and the revisions Alembic generates. The environments run Alembic's migration context on a Connection, and the revisions are where schema changes belong (api.data.sqlalchemy-and-alembic-only), so the rule test doesn't read them." + [[rule]] id = "api.legacy.removed-layers-stay-removed" category = "runtime-layers" diff --git a/tests/unit/data/orm_access_support.py b/tests/unit/data/orm_access_support.py new file mode 100644 index 000000000..329a1a9b7 --- /dev/null +++ b/tests/unit/data/orm_access_support.py @@ -0,0 +1,977 @@ +"""Checks behind rule api.data.orm-only in rules/registry.toml. + +Code that reads or writes database rows declares tables only as SQLAlchemy ORM +mapped classes, SQLModel classes included, and runs every statement through an +ORM Session against them. ``orm_access_findings`` reads source, so the rule +test in ``test_orm_only.py`` runs it on the repository and the proof test runs +it on the fixtures under ``rules/fixtures/api.data.orm-only/``. +``unmapped_table_findings`` reports every table that given modules hold and no +mapped class maps, and ``unmapped_tables_in_packages`` imports whole packages +for it, which finds tables built in ways the source checks can't see. +``undeclared_findings`` and ``unused_exceptions`` compare the findings with the +rule's ``[[rule.exception]]`` entries. docs/engineering/skills/ +alembic-migrations.md explains the rule under "Database statements through the +ORM", with the way to write each kind of statement. + +This is a port of the checker behind sim.persistence.orm-only in +PolicyEngine/policyengine-sim-api +(``projects/policyengine-simulation-entry/tests/orm_access_support.py``). It +differs in four ways: + +- SQLModel is the ORM here, so importing it is not a finding, and SQLModel + table classes are mapped classes. SQLModel re-exports SQLAlchemy's names, + so a name imported from ``sqlmodel`` counts as the SQLAlchemy name it + re-exports: ``from sqlmodel import text`` is raw SQL and ``from sqlmodel + import create_engine`` creates an engine. +- The modules that may create or hold an Engine are the named + ``SESSION_FACTORY_MODULES``, and the modules that may build ``MetaData`` are + the named ``DECLARATIVE_BASE_MODULES``, rather than files matched by name. +- A session-factory module may also import ``Connection``, open a Connection + (``connect()``, ``connection()``, ``get_bind()`` and ``begin()`` on an + engine) and attach listeners for pool, engine or dialect events, which no + other module may do. ``raw_connection()`` hands out the driver's connection, + not SQLAlchemy's, and is reported in every module. +- A finding is allowed when a ``no-orm-form`` exception names its file and, + in ``match``, its ``source``; a ``migration-revision`` exception names a + path pattern the rule test doesn't read. + +The source checks look for Core rather than for the ORM, so any statement on +mapped classes passes. Each file is checked on its own, through its own imports: +``from sqlalchemy import text`` and ``import sqlalchemy as sa`` both count, and +a ``text``, ``Table`` or ``update`` from another package doesn't. A Core table is +reported where it starts: where it is declared, where it is read from a mapped +class, mapper or MetaData or as the bare name ``__table__``, and where an +annotation names ``Table`` or ``TableClause``, apart from a class's bare +``__table__`` annotation in a declarative-base module. Its later uses aren't +reported, because the rule has no baseline and the first finding already fails +it. + +A public function of a session-factory module may not return an Engine or +Connection, and only a session-factory module may read ``factory.kw["bind"]``. +The rules that go by a method or attribute name alone apply only in modules that +import sqlalchemy or sqlmodel: any ``.table`` read, ``kw["bind"]``, +``.execute()`` on anything not named as a session, ``.scalar()``, +``.scalars()``, ``.stream()`` and ``.stream_scalars()`` on a name such as +``connection``, and the ``.connect()``, ``.connection()``, +``.raw_connection()``, ``.get_bind()``, ``.begin()``, ``.cursor()`` and +``.exec_driver_sql()`` calls. + +The checks guard against ordinary Core use, not against deliberate evasion. They +don't see imports made through ``importlib`` or ``__import__``, engines or +connections passed around without an ``Engine`` or ``Connection`` annotation, so +a connection held under a name such as ``session`` isn't reported, a statement +method passed without being called, a function that returns an engine with no +return annotation, the engine an ``Inspector`` holds in ``bind`` or ``engine``, a +quoted name inside an annotation such as ``Optional["Table"]``, ``Table`` under +another local name such as ``Jobs = Table``, names from ``from sqlalchemy import +*``, a ``.table`` read in a module that doesn't import sqlalchemy or sqlmodel, a +Session's ``bind`` attribute, or an event listener whose target and event name +aren't its first two positional arguments, the name a string literal. ``.tables`` +of a MetaData isn't reported when the name holding it doesn't end in +``metadata`` and wasn't assigned ``MetaData(...)``. +""" + +from __future__ import annotations + +import ast +import importlib +import pkgutil +import re +from dataclasses import dataclass +from pathlib import Path, PurePosixPath +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator, Mapping + from types import ModuleType + + from sqlalchemy.orm import registry + + from scripts.rules.model import RuleException + +SQLALCHEMY_MODULE = "sqlalchemy" +SQLMODEL_MODULE = "sqlmodel" +# The libraries whose names the checks follow. SQLModel re-exports +# SQLAlchemy's, under the same names. +ORM_LIBRARY_MODULES = (SQLALCHEMY_MODULE, SQLMODEL_MODULE) +# Core's table declarations, the lightweight table() and column() included. +# MetaData may be built only in a declarative-base module, as the metadata of +# one of the library's DeclarativeBase classes. +TABLE_CONSTRUCTORS = frozenset( + {"Column", "ColumnClause", "MetaData", "Table", "TableClause", "column", "table"} +) +TABLE_TYPES = frozenset({"Table", "TableClause"}) +# A declarative base's classes may annotate what each of them maps. +MAPPED_TABLE_ATTRIBUTE = "__table__" +METADATA_CONSTRUCTOR = "MetaData" +# The modules that may build MetaData: the v1 declarative base, the v2 models' +# metadata (SQLModel's, with its naming convention), and the publication staging +# tables' own declarative base, which keeps them out of the v2 metadata Alembic +# compares. +DECLARATIVE_BASE_MODULES = frozenset( + { + "policyengine_api/data/v1_models.py", + "policyengine_api/data/v2/models/__init__.py", + "policyengine_api/data/v2/catalog/publication_staging_base.py", + } +) +# The modules that may create and hold an engine, open a Connection and attach +# pool events, to hand out Session factories: API v1's, API v2's and the tests'. +SESSION_FACTORY_MODULES = frozenset( + { + "policyengine_api/data/orm.py", + "policyengine_api/data/v2/database.py", + "tests/fixtures/database_sessions.py", + } +) +ENGINE_NAMES = frozenset( + { + "AsyncEngine", + "Engine", + "create_async_engine", + "create_engine", + "engine_from_config", + } +) +CONNECTION_NAMES = frozenset({"AsyncConnection", "Connection"}) +ENGINE_FACTORIES = frozenset({"create_async_engine", "create_engine"}) +ENGINE_TYPES = frozenset({"AsyncEngine", "Engine"}) +# A name such as engine or simulation_engine, but not policyengine. +ENGINE_NAME_PATTERN = re.compile(r"(?:^|_)engine$", re.IGNORECASE) +# Calls that open a Connection: on anything, and begin() on an engine. Only a +# session-factory module may make them. +CONNECTION_METHODS = frozenset({"connect", "connection", "get_bind"}) +ENGINE_TRANSACTION_METHOD = "begin" +# The call that hands out the driver's connection beneath SQLAlchemy's, which +# no module may make. +DRIVER_CONNECTION_METHODS = frozenset({"raw_connection"}) +# execute runs only on a name such as session or store_session, which finds a +# connection passed around without a Connection annotation. A Result has scalar +# and scalars too, so the others are reported only on a name such as connection. +EXECUTE_METHOD = "execute" +SESSION_NAME_PATTERN = re.compile(r"(?:^|_)session$", re.IGNORECASE) +CONNECTION_STATEMENT_METHODS = frozenset( + {"scalar", "scalars", "stream", "stream_scalars"} +) +CONNECTION_NAME_PATTERN = re.compile(r"(?:^|_)(?:connection|conn)$", re.IGNORECASE) +# What a session-factory module keeps to itself: no public function returns one +# of these, and only it reads the engine out of a sessionmaker's keywords. +HELD_DATABASE_TYPES = ENGINE_TYPES | CONNECTION_NAMES +SESSION_FACTORY_KEYWORDS = "kw" +SESSION_FACTORY_BIND_KEY = "bind" +# event.listen and event.listens_for, with the events of a pool, an engine or +# connection, and a dialect (SQLAlchemy's PoolEvents, ConnectionEvents and +# DialectEvents). Only a session-factory module may listen for them. Session, +# mapper, attribute and DDL events have other names. +EVENT_LISTENER_FUNCTIONS = frozenset({"listen", "listens_for"}) +DATABASE_EVENT_NAMES = frozenset( + { + # PoolEvents + "checkin", + "checkout", + "close", + "close_detached", + "connect", + "detach", + "first_connect", + "invalidate", + "reset", + "soft_invalidate", + # ConnectionEvents + "after_cursor_execute", + "after_execute", + "before_cursor_execute", + "before_execute", + "begin", + "begin_twophase", + "commit", + "commit_twophase", + "engine_connect", + "engine_disposed", + "prepare_twophase", + "release_savepoint", + "rollback", + "rollback_savepoint", + "rollback_twophase", + "savepoint", + "set_connection_execution_options", + "set_engine_execution_options", + # DialectEvents + "do_connect", + "do_execute", + "do_execute_no_params", + "do_executemany", + "do_setinputsizes", + "handle_error", + } +) +# Attributes that reach a Core table from a mapped class, its mapper or a +# MetaData, and the ones that do so only on a mapper, inspect() or a MetaData. +TABLE_ATTRIBUTES = frozenset( + {"__table__", "local_table", "persist_selectable", "sorted_tables"} +) +MAPPER_TABLE_ATTRIBUTES = frozenset({"selectable", "tables"}) +MAPPER_FUNCTIONS = frozenset({"class_mapper", "inspect", "object_mapper"}) +MAPPER_NAMES = frozenset({"__mapper__", "mapper"}) +# A column's or mapped attribute's table, as in HouseholdJob.id.table: read in a +# module that imports sqlalchemy or sqlmodel, any .table is reported. +COLUMN_TABLE_ATTRIBUTE = "table" +METADATA_SUFFIX = "metadata" +RAW_SQL_FUNCTIONS = frozenset({"TextClause", "literal_column", "text"}) +RAW_SQL_METHODS = frozenset({"cursor", "exec_driver_sql"}) +# A model's schema details given as SQL text: a server default and a partial +# index's condition, by keyword, and a check constraint's condition. +SCHEMA_DETAIL_KEYWORDS = frozenset( + {"postgresql_where", "server_default", "server_onupdate", "sqlite_where"} +) +CHECK_CONSTRAINT = "CheckConstraint" + +CORE_TABLE_DECLARATION = "Core table declaration" +CORE_TABLE_ACCESS = "Core table access" +CORE_CONNECTION = "Core engine or connection" +RAW_SQL = "raw SQL" +UNMAPPED_TABLE = "table without a mapped class" + +# The rule's [[rule.exception]] categories: one construct in one module that +# SQLAlchemy's ORM has no form for, named by the module's path and, in match, +# the finding's source; and a path pattern the rule test doesn't read at all. +NO_ORM_FORM = "no-orm-form" +MIGRATION_REVISION = "migration-revision" +EXCEPTION_CATEGORIES = (NO_ORM_FORM, MIGRATION_REVISION) + + +@dataclass(frozen=True) +class Finding: + """One place where code reaches the database without the ORM.""" + + file: str + line: int + check: str + source: str + + def __str__(self) -> str: + """Describe the finding as ``file:line: check: source``.""" + return f"{self.file}:{self.line}: {self.check}: {self.source}" + + +def _matches_module(module_name: str, parent_module: str) -> bool: + return module_name == parent_module or module_name.startswith(f"{parent_module}.") + + +def _orm_library(module_name: str) -> str | None: + """Return the ORM library ``module_name`` belongs to, or ``None``.""" + return next( + ( + library + for library in ORM_LIBRARY_MODULES + if _matches_module(module_name, library) + ), + None, + ) + + +def _orm_library_imports(tree: ast.Module) -> dict[str, str]: + """Map each name imported from sqlalchemy or sqlmodel to its dotted name.""" + imported: dict[str, str] = {} + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + library = _orm_library(alias.name) + if library is None: + continue + if alias.asname: + imported[alias.asname] = alias.name + else: + imported[library] = library + elif ( + isinstance(node, ast.ImportFrom) + and not node.level + and node.module is not None + and _orm_library(node.module) is not None + ): + for alias in node.names: + imported[alias.asname or alias.name] = f"{node.module}.{alias.name}" + return imported + + +def _qualified_name(node: ast.expr, imported: Mapping[str, str]) -> str | None: + if isinstance(node, ast.Name): + return imported.get(node.id) + if isinstance(node, ast.Attribute): + parent = _qualified_name(node.value, imported) + return None if parent is None else f"{parent}.{node.attr}" + return None + + +def _library_name(node: ast.expr, imported: Mapping[str, str]) -> str: + """Return the last part of the ORM library name ``node`` refers to, or ``""``.""" + qualified = _qualified_name(node, imported) + return qualified.rsplit(".", 1)[-1] if qualified else "" + + +def _annotation_names( + annotation: ast.expr | None, imported: Mapping[str, str] +) -> set[str]: + """Return the ORM library names an annotation refers to, unions included. + + A wholly quoted annotation is parsed. Strings inside one aren't, because + they may be anything, such as ``Literal`` values or ``Annotated`` metadata. + """ + if annotation is None: + return set() + if isinstance(annotation, ast.Constant) and isinstance(annotation.value, str): + try: + annotation = ast.parse(annotation.value, mode="eval").body + except SyntaxError: + return set() + return { + name + for node in ast.walk(annotation) + if isinstance(node, (ast.Name, ast.Attribute)) + and (name := _library_name(node, imported)) + } + + +def _bound_targets(target: ast.expr) -> list[str]: + """Return the names and attributes an assignment target binds.""" + if isinstance(target, ast.Name): + return [target.id] + if isinstance(target, ast.Attribute): + return [target.attr] + if isinstance(target, (ast.Tuple, ast.List)): + return [name for element in target.elts for name in _bound_targets(element)] + return [] + + +def _last_name(node: ast.expr) -> str: + if isinstance(node, ast.Call): + return _last_name(node.func) + if isinstance(node, ast.Attribute): + return node.attr + return node.id if isinstance(node, ast.Name) else "" + + +@dataclass +class _Module: + """One scanned file and the names it imports from sqlalchemy or sqlmodel.""" + + file: str + tree: ast.Module + imported: dict[str, str] + + @property + def uses_sqlalchemy(self) -> bool: + """Whether the module imports anything from sqlalchemy or sqlmodel.""" + return bool(self.imported) + + @property + def is_session_factory(self) -> bool: + return self.file in SESSION_FACTORY_MODULES + + @property + def is_declarative_base(self) -> bool: + return self.file in DECLARATIVE_BASE_MODULES + + +def _annotated_as(module: _Module, types: frozenset[str]) -> set[str]: + """Return the names and attributes annotated with one of ``types``.""" + names: set[str] = set() + for node in ast.walk(module.tree): + if isinstance(node, ast.arg): + if types & _annotation_names(node.annotation, module.imported): + names.add(node.arg) + elif isinstance(node, ast.AnnAssign) and types & _annotation_names( + node.annotation, module.imported + ): + names.update(_bound_targets(node.target)) + return names + + +def _bound_to_calls(module: _Module, functions: frozenset[str]) -> set[str]: + """Return the names and attributes bound to a call of one of ``functions``.""" + return { + name + for target, value in _assignment_nodes(module.tree) + if isinstance(value, ast.Call) + and _library_name(value.func, module.imported) in functions + for name in _bound_targets(target) + } + + +def _paired(target: ast.expr, value: ast.expr) -> Iterator[tuple[ast.expr, ast.expr]]: + """Pair each part of a tuple target with its value, nested tuples included.""" + if ( + isinstance(target, (ast.Tuple, ast.List)) + and isinstance(value, (ast.Tuple, ast.List)) + and len(target.elts) == len(value.elts) + ): + for element, element_value in zip(target.elts, value.elts, strict=True): + yield from _paired(element, element_value) + else: + yield target, value + + +def _assignment_nodes(tree: ast.AST) -> Iterator[tuple[ast.expr, ast.expr]]: + """Yield each assignment's target and value, pairing tuples. + + ``a, b = x, y`` yields ``a`` with ``x`` and ``b`` with ``y``. + """ + for node in ast.walk(tree): + if isinstance(node, ast.Assign): + for target in node.targets: + yield from _paired(target, node.value) + elif ( + isinstance(node, (ast.AnnAssign, ast.NamedExpr)) and node.value is not None + ): + yield node.target, node.value + + +def _bound_to_mappers(module: _Module) -> set[str]: + """Return the names and attributes assigned a mapper, as in ``m = X.__mapper__``.""" + return { + name + for target, value in _assignment_nodes(module.tree) + if isinstance(value, ast.Attribute) and value.attr in MAPPER_NAMES + for name in _bound_targets(target) + } + + +def _call_summary(call: ast.Call) -> str: + parts = [ast.unparse(call.args[0])] if call.args else [] + if len(call.args) > 1 or call.keywords: + parts.append("...") + return f"{ast.unparse(call.func)}({', '.join(parts)})" + + +def _schema_detail_calls(tree: ast.Module, imported: Mapping[str, str]) -> set[int]: + """Return the calls given as a default or as an index's or check's condition.""" + details = { + id(keyword.value) + for node in ast.walk(tree) + if isinstance(node, ast.Call) + for keyword in node.keywords + if keyword.arg in SCHEMA_DETAIL_KEYWORDS + } + details.update( + id(node.args[0]) + for node in ast.walk(tree) + if isinstance(node, ast.Call) + and node.args + and _library_name(node.func, imported) == CHECK_CONSTRAINT + ) + return details + + +@dataclass(frozen=True) +class _ModuleContext: + module: _Module + metadata_names: set[str] + mapper_names: set[str] + engine_names: set[str] + schema_details: set[int] + called: set[int] + mapped_table_annotations: set[int] + + +def _forbidden_connection_name(name: str, context: _ModuleContext) -> bool: + """Whether ``name`` creates or holds an Engine or Connection outside a factory.""" + return ( + name in ENGINE_NAMES or name in CONNECTION_NAMES + ) and not context.module.is_session_factory + + +def _import_findings( + node: ast.Import | ast.ImportFrom, context: _ModuleContext +) -> Iterator[tuple[str, str]]: + if ( + isinstance(node, ast.Import) + or node.level + or node.module is None + or _orm_library(node.module) is None + ): + return + for alias in node.names: + if _forbidden_connection_name(alias.name, context): + yield CORE_CONNECTION, f"{node.module}.{alias.name}" + + +def _reaches_mapped_table(node: ast.Attribute, context: _ModuleContext) -> bool: + if node.attr in TABLE_ATTRIBUTES: + return True + receiver = node.value + if node.attr == COLUMN_TABLE_ATTRIBUTE: + # A column's table is read, never called: sa.table(...) is a function. + return ( + context.module.uses_sqlalchemy + and isinstance(node.ctx, ast.Load) + and id(node) not in context.called + ) + if node.attr not in MAPPER_TABLE_ATTRIBUTES: + return False + if isinstance(receiver, ast.Call): + function = _library_name(receiver.func, context.module.imported) + return function in MAPPER_FUNCTIONS + receiver_name = _last_name(receiver) + return ( + receiver_name in MAPPER_NAMES + or receiver_name in context.mapper_names + or receiver_name in context.metadata_names + or receiver_name.lower().endswith(METADATA_SUFFIX) + ) + + +def _attribute_findings( + node: ast.Attribute, context: _ModuleContext +) -> Iterator[tuple[str, str]]: + if _reaches_mapped_table(node, context): + yield CORE_TABLE_ACCESS, ast.unparse(node) + elif _forbidden_connection_name( + _library_name(node, context.module.imported), context + ): + yield CORE_CONNECTION, str(_qualified_name(node, context.module.imported)) + + +def _runs_raw_sql(node: ast.Call, function: str, context: _ModuleContext) -> bool: + if function in RAW_SQL_FUNCTIONS: + return id(node) not in context.schema_details + return ( + context.module.uses_sqlalchemy + and isinstance(node.func, ast.Attribute) + and node.func.attr in RAW_SQL_METHODS + ) + + +def _opens_connection(node: ast.Call, context: _ModuleContext) -> bool: + """Whether a call opens a Connection where it may not, or a driver connection.""" + if not context.module.uses_sqlalchemy or not isinstance(node.func, ast.Attribute): + return False + if node.func.attr in DRIVER_CONNECTION_METHODS: + return True + if context.module.is_session_factory: + return False + if node.func.attr in CONNECTION_METHODS: + return True + if node.func.attr != ENGINE_TRANSACTION_METHOD: + return False + receiver = _last_name(node.func.value) + return receiver in context.engine_names or bool( + ENGINE_NAME_PATTERN.search(receiver) + ) + + +def _database_event_listener( + node: ast.Call, function: str, context: _ModuleContext +) -> str | None: + """Describe a pool, engine or dialect event listener outside a factory. + + The summary names the listener function, its target and the event, as in + ``event.listen(engine, 'connect')``. + """ + if ( + function not in EVENT_LISTENER_FUNCTIONS + or context.module.is_session_factory + # The listener's target, then the event's name. + or len(node.args) < 2 + ): + return None + event_name = node.args[1] + if not ( + isinstance(event_name, ast.Constant) + and event_name.value in DATABASE_EVENT_NAMES + ): + return None + target = ast.unparse(node.args[0]) + return f"{ast.unparse(node.func)}({target}, {event_name.value!r})" + + +def _runs_outside_a_session(node: ast.Call, context: _ModuleContext) -> bool: + """Whether a statement runs on something other than a session.""" + if not context.module.uses_sqlalchemy or not isinstance(node.func, ast.Attribute): + return False + receiver = _last_name(node.func.value) + if node.func.attr == EXECUTE_METHOD: + return not SESSION_NAME_PATTERN.search(receiver) + return node.func.attr in CONNECTION_STATEMENT_METHODS and bool( + CONNECTION_NAME_PATTERN.search(receiver) + ) + + +def _call_findings( + node: ast.Call, context: _ModuleContext +) -> Iterator[tuple[str, str]]: + function = _library_name(node.func, context.module.imported) + if function in TABLE_CONSTRUCTORS and not ( + function == METADATA_CONSTRUCTOR and context.module.is_declarative_base + ): + yield CORE_TABLE_DECLARATION, _call_summary(node) + elif _runs_raw_sql(node, function, context): + yield RAW_SQL, _call_summary(node) + elif _opens_connection(node, context): + yield CORE_CONNECTION, _call_summary(node) + elif listener := _database_event_listener(node, function, context): + yield CORE_CONNECTION, listener + elif _runs_outside_a_session(node, context): + yield CORE_CONNECTION, f"{ast.unparse(node.func)}(...)" + + +def _annotation_text(annotation: ast.expr) -> str: + if isinstance(annotation, ast.Constant) and isinstance(annotation.value, str): + return annotation.value + return ast.unparse(annotation) + + +def _table_annotation_findings( + label: str, annotation: ast.expr | None, context: _ModuleContext +) -> list[tuple[str, str]]: + """Report an annotation naming a Core table type, as in ``jobs: Table``.""" + names = _annotation_names(annotation, context.module.imported) + if annotation is None or not names & TABLE_TYPES: + return [] + return [(CORE_TABLE_ACCESS, f"{label}{_annotation_text(annotation)}")] + + +def _class_level_statements(node: ast.ClassDef) -> Iterator[ast.stmt]: + """Yield a class's own statements, including those under an ``if``.""" + pending: list[ast.stmt] = list(node.body) + while pending: + statement = pending.pop() + yield statement + if isinstance(statement, ast.If): + pending.extend([*statement.body, *statement.orelse]) + + +def _mapped_table_annotations(module: _Module) -> set[int]: + """Return each class's bare ``__table__`` annotation in a declarative base.""" + if not module.is_declarative_base: + return set() + return { + id(statement) + for node in ast.walk(module.tree) + if isinstance(node, ast.ClassDef) + for statement in _class_level_statements(node) + if isinstance(statement, ast.AnnAssign) + and statement.value is None + and isinstance(statement.target, ast.Name) + and statement.target.id == MAPPED_TABLE_ATTRIBUTE + } + + +def _annotated_assignment_findings( + node: ast.AnnAssign, context: _ModuleContext +) -> list[tuple[str, str]]: + if id(node) in context.mapped_table_annotations: + return [] + return _table_annotation_findings( + f"{ast.unparse(node.target)}: ", node.annotation, context + ) + + +def _function_findings( + node: ast.FunctionDef | ast.AsyncFunctionDef, context: _ModuleContext +) -> list[tuple[str, str]]: + """Report a function returning a Core table, or a factory module's engine.""" + findings = _table_annotation_findings(f"{node.name}() -> ", node.returns, context) + if not context.module.is_session_factory or node.name.startswith("_"): + return findings + returned = _annotation_names(node.returns, context.module.imported) + return findings + [ + (CORE_CONNECTION, f"{node.name}() -> {type_name}") + for type_name in sorted(returned & HELD_DATABASE_TYPES) + ] + + +def _reads_session_factory_engine(node: ast.Subscript, context: _ModuleContext) -> bool: + """Whether ``node`` is ``factory.kw["bind"]`` outside a session-factory module.""" + return ( + context.module.uses_sqlalchemy + and not context.module.is_session_factory + and isinstance(node.value, ast.Attribute) + and node.value.attr == SESSION_FACTORY_KEYWORDS + and isinstance(node.slice, ast.Constant) + and node.slice.value == SESSION_FACTORY_BIND_KEY + ) + + +def _subscript_findings( + node: ast.Subscript, context: _ModuleContext +) -> list[tuple[str, str]]: + if _reads_session_factory_engine(node, context): + return [(CORE_CONNECTION, ast.unparse(node))] + return [] + + +def _name_findings(node: ast.Name) -> list[tuple[str, str]]: + """Report a read of the bare name ``__table__``, as in a class body.""" + if node.id == MAPPED_TABLE_ATTRIBUTE and isinstance(node.ctx, ast.Load): + return [(CORE_TABLE_ACCESS, node.id)] + return [] + + +def _node_findings(node: ast.AST, context: _ModuleContext) -> list[tuple[str, str]]: + findings: Iterable[tuple[str, str]] = () + match node: + case ast.Import() | ast.ImportFrom(): + findings = _import_findings(node, context) + case ast.Name(): + findings = _name_findings(node) + case ast.Attribute(): + findings = _attribute_findings(node, context) + case ast.Call(): + findings = _call_findings(node, context) + case ast.FunctionDef() | ast.AsyncFunctionDef(): + findings = _function_findings(node, context) + case ast.arg(): + findings = _table_annotation_findings( + f"{node.arg}: ", node.annotation, context + ) + case ast.AnnAssign(): + findings = _annotated_assignment_findings(node, context) + case ast.Subscript(): + findings = _subscript_findings(node, context) + return list(findings) + + +def _module_context(module: _Module) -> _ModuleContext: + return _ModuleContext( + module=module, + metadata_names=_bound_to_calls(module, frozenset({METADATA_CONSTRUCTOR})), + mapper_names=_bound_to_calls(module, MAPPER_FUNCTIONS) + | _bound_to_mappers(module), + engine_names=_bound_to_calls(module, ENGINE_FACTORIES) + | _annotated_as(module, ENGINE_TYPES), + schema_details=_schema_detail_calls(module.tree, module.imported), + called={ + id(node.func) + for node in ast.walk(module.tree) + if isinstance(node, ast.Call) + }, + mapped_table_annotations=_mapped_table_annotations(module), + ) + + +def orm_access_findings(sources: Mapping[str, str]) -> list[Finding]: + """Return every place the sources reach the database without the ORM. + + ``sources`` maps a repository-relative file name to its source. + """ + findings: list[Finding] = [] + for file, source in sorted(sources.items()): + tree = ast.parse(source, filename=file) + module = _Module(file=file, tree=tree, imported=_orm_library_imports(tree)) + context = _module_context(module) + findings.extend( + Finding(file, getattr(node, "lineno", 0), check, finding_source) + for node in ast.walk(tree) + for check, finding_source in _node_findings(node, context) + ) + return sorted(findings, key=lambda finding: (finding.file, finding.line)) + + +def _relative_file(path: str | None, repository_root: Path) -> str: + if path is None: + return "" + return Path(path).resolve().relative_to(repository_root).as_posix() + + +def unmapped_table_findings( + modules: Iterable[ModuleType], repository_root: Path, *, location: str | None = None +) -> list[Finding]: + """Return each table the modules hold that no mapped class maps. + + A module holds a table through a global bound to the table, to a MetaData, + or to a declarative base or mapped class, SQLModel classes included. Each + table is reported once, at ``location`` when given, otherwise at the first + module that holds it. + """ + return _unmapped_findings( + (module, location or _relative_file(module.__file__, repository_root)) + for module in modules + ) + + +def _declared_registry(value: object) -> registry | None: + """Return the ORM registry of a declarative base or mapped class code defines. + + SQLModel classes share SQLModel's registry. The libraries' own base classes + are not the code's, so they count only through the code's subclasses. + """ + from sqlalchemy.orm import DeclarativeBase, DeclarativeBaseNoMeta + from sqlmodel import SQLModel + + if not isinstance(value, type) or _orm_library(value.__module__) is not None: + return None + if issubclass(value, (DeclarativeBase, DeclarativeBaseNoMeta)): + return value.registry + if issubclass(value, SQLModel): + return value._sa_registry + return None + + +def _unmapped_findings( + placed_modules: Iterable[tuple[ModuleType, str]], +) -> list[Finding]: + """Report each held table no mapped class of any of the modules maps.""" + from sqlalchemy import MetaData, Table + + # Each held table's full name and where it is reported, by the table's id. + held: dict[int, tuple[str, str]] = {} + mapped: set[int] = set() + for module, place in placed_modules: + for value in vars(module).values(): + class_registry = _declared_registry(value) + if isinstance(value, Table): + tables = [value] + elif isinstance(value, MetaData): + tables = list(value.tables.values()) + elif class_registry is not None: + mapped.update( + id(mapper.local_table) for mapper in class_registry.mappers + ) + tables = list(class_registry.metadata.tables.values()) + else: + tables = [] + for table in tables: + held.setdefault(id(table), (table.fullname, place)) + findings = [ + Finding(place, 0, UNMAPPED_TABLE, table_name) + for key, (table_name, place) in held.items() + if key not in mapped + ] + return sorted(findings, key=lambda finding: (finding.file, finding.source)) + + +def _package_modules(package_name: str) -> list[ModuleType]: + package = importlib.import_module(package_name) + names = sorted( + module.name + for module in pkgutil.walk_packages(package.__path__, f"{package_name}.") + ) + return [package, *(importlib.import_module(name) for name in names)] + + +def unmapped_tables_in_packages( + package_names: Iterable[str], repository_root: Path +) -> list[Finding]: + """Import the packages and return each table they hold that no class maps. + + A table is reported once, at the source directory of the first package + that holds it, in the order given. + """ + placed_modules: list[tuple[ModuleType, str]] = [] + for package_name in package_names: + package_modules = _package_modules(package_name) + directory = PurePosixPath( + _relative_file(package_modules[0].__file__, repository_root) + ).parent + placed_modules.extend((module, str(directory)) for module in package_modules) + return _unmapped_findings(placed_modules) + + +def _declared_constructs( + exceptions: Iterable[RuleException], +) -> frozenset[tuple[str, str]]: + """Return the (file, source) pairs the no-orm-form exceptions allow.""" + return frozenset( + (exception.path, exception.match) + for exception in exceptions + if exception.category == NO_ORM_FORM and exception.match is not None + ) + + +def undeclared_findings( + findings: Iterable[Finding], exceptions: Iterable[RuleException] +) -> list[Finding]: + """Return the findings that no no-orm-form exception names. + + An exception names a finding when its ``path`` is the finding's file and its + ``match`` is the finding's ``source``, exactly; it then allows every finding + in that file with that source. + """ + declared = _declared_constructs(exceptions) + return [ + finding + for finding in findings + if (finding.file, finding.source) not in declared + ] + + +def unused_exceptions( + findings: Iterable[Finding], exceptions: Iterable[RuleException] +) -> list[RuleException]: + """Return each no-orm-form exception that names no finding.""" + found = {(finding.file, finding.source) for finding in findings} + return [ + exception + for exception in exceptions + if exception.category == NO_ORM_FORM + and (exception.path, exception.match) not in found + ] + + +def unscanned_files( + exceptions: Iterable[RuleException], repository_root: Path +) -> frozenset[str]: + """Return the files the migration-revision exceptions' path patterns name.""" + return frozenset( + path.relative_to(repository_root).as_posix() + for exception in exceptions + if exception.category == MIGRATION_REVISION + for path in repository_root.glob(exception.path) + if path.is_file() + ) + + +def _construct_exception_problem( + exception: RuleException, repository_root: Path +) -> str | None: + """Describe what makes a no-orm-form exception unusable, or return ``None``.""" + where = f"exception for {exception.path}" + if exception.match is None: + return f"{where} names no construct: set match to the finding's source" + if not (repository_root / exception.path).is_file(): + return f"{where} must name one existing file" + return None + + +def _path_exception_problem( + exception: RuleException, read_files: frozenset[str], repository_root: Path +) -> str | None: + """Describe what makes a migration-revision exception unusable, or ``None``.""" + where = f"exception for {exception.path}" + if exception.match is not None: + return f"{where} skips whole files, so it takes no match" + if not unscanned_files([exception], repository_root) & read_files: + return f"{where} matches no file the rule test reads: remove it" + return None + + +def _exception_problem( + exception: RuleException, read_files: frozenset[str], repository_root: Path +) -> str | None: + """Describe what makes one exception unusable, or return ``None``.""" + if exception.category == NO_ORM_FORM: + return _construct_exception_problem(exception, repository_root) + if exception.category == MIGRATION_REVISION: + return _path_exception_problem(exception, read_files, repository_root) + return ( + f"exception for {exception.path} has unknown category " + f"{exception.category!r}: use one of {list(EXCEPTION_CATEGORIES)}" + ) + + +def exception_problems( + exceptions: Iterable[RuleException], + read_files: Iterable[str], + repository_root: Path, +) -> list[str]: + """Describe each exception with an unknown category, or no module or construct. + + ``read_files`` are the repository-relative files the rule test reads before + the migration-revision exceptions take theirs out. + """ + read = frozenset(read_files) + return [ + problem + for exception in exceptions + if (problem := _exception_problem(exception, read, repository_root)) + ] diff --git a/tests/unit/data/test_orm_access_support.py b/tests/unit/data/test_orm_access_support.py new file mode 100644 index 000000000..c5ab8de5d --- /dev/null +++ b/tests/unit/data/test_orm_access_support.py @@ -0,0 +1,1067 @@ +"""Unit tests for the checks behind rule api.data.orm-only. + +Ported from policyengine-sim-api's tests of the checker behind +sim.persistence.orm-only, with tests added for this repository's changes: +SQLModel's names, the named session-factory and declarative-base modules, event +listeners, and the rule's exceptions. +""" + +from __future__ import annotations + +import sys +import types +from pathlib import Path +from textwrap import dedent + +import pytest + +from scripts.rules.model import RuleException +from tests.unit.data.orm_access_support import ( + CORE_CONNECTION, + CORE_TABLE_ACCESS, + CORE_TABLE_DECLARATION, + DECLARATIVE_BASE_MODULES, + MIGRATION_REVISION, + NO_ORM_FORM, + RAW_SQL, + SESSION_FACTORY_MODULES, + UNMAPPED_TABLE, + Finding, + exception_problems, + orm_access_findings, + undeclared_findings, + unmapped_table_findings, + unscanned_files, + unused_exceptions, +) + +STORE = "policyengine_api/data/v2/example_store.py" +SESSION_FACTORY = "policyengine_api/data/v2/database.py" +DECLARATIVE_BASE = "policyengine_api/data/v1_models.py" +ROUTES = "policyengine_api/routes/example_routes.py" +MODELS = "policyengine_api/data/v2/example_models.py" + + +def _checks(sources: dict[str, str], file: str) -> list[tuple[str, str]]: + """Return the (check, source) findings in ``file``.""" + findings = orm_access_findings( + {name: dedent(source) for name, source in sources.items()} + ) + return [ + (finding.check, finding.source) for finding in findings if finding.file == file + ] + + +@pytest.mark.parametrize( + "statement", + [ + "select(func.count().label('jobs'))", + "select(cast(HouseholdJob.year, String).label('year'))", + "select(exists().where(HouseholdJob.id == job_id))", + "select(*columns)", + "select(pending.c.id).where(pending.c.id == job_id)", + "select(func.count()).select_from(HouseholdJob).join(Policy)", + "insert(HouseholdJob).values(id=job_id).on_conflict_do_nothing()", + "select(reports.c.id)", + ], +) +def test_orm_statements_are_accepted(statement: str) -> None: + store = f""" + from sqlalchemy import String, cast, exists, func, insert, select + + pending = select(HouseholdJob.id).subquery() + reports = select(Report.id).where(Report.year == 2026).subquery() + statement = {statement} + """ + + assert _checks({STORE: store}, STORE) == [] + + +@pytest.mark.parametrize( + ("declaration", "summary"), + [ + ("def read(jobs: Table): ...", "jobs: Table"), + ("def read(jobs: TableClause): ...", "jobs: TableClause"), + ("def read(jobs: 'sa.Table | None'): ...", "jobs: sa.Table | None"), + ("def read(*tables: Table): ...", "tables: Table"), + ("def read(**tables: Table): ...", "tables: Table"), + ("def read() -> Table: ...", "read() -> Table"), + ("async def read() -> list[Table]: ...", "read() -> list[Table]"), + ("selected: Table = choose()", "selected: Table"), + ("self.jobs: Table = source", "self.jobs: Table"), + ("class Rows:\n target: Table", "target: Table"), + ( + "def read(jobs: Annotated[Any, Marker(kind=Table)]): ...", + "jobs: Annotated[Any, Marker(kind=Table)]", + ), + ("def read(jobs: Literal[Table]): ...", "jobs: Literal[Table]"), + ], +) +def test_an_annotation_naming_a_core_table_type_is_reported( + declaration: str, summary: str +) -> None: + store = f""" +import sqlalchemy as sa +from sqlalchemy import Table, TableClause + +{declaration} +""" + + assert _checks({STORE: store}, STORE) == [(CORE_TABLE_ACCESS, summary)] + + +@pytest.mark.parametrize( + "annotation", + [ + 'Literal["Table"]', + 'Choice["Table", "View"]', + 'Annotated[str, "Table"]', + 'Annotated[str, "' + "x." * 1000 + 'y"]', + 'Optional["Table"]', + "\"list['Table']\"", + '"not a type ("', + ], +) +def test_a_quoted_name_inside_an_annotation_is_not_read(annotation: str) -> None: + """Only a wholly quoted annotation is parsed; other strings may be anything.""" + store = f""" +from sqlalchemy import Table + +def read(value: {annotation}): ... +""" + + assert _checks({STORE: store}, STORE) == [] + + +def test_an_engine_type_in_annotation_metadata_is_followed() -> None: + source = """ + from sqlalchemy import Engine + + def hand_out() -> Annotated[Any, Marker(kind=Engine)]: ... + + def run(handle: Annotated[Any, Marker(kind=Engine)]): + return handle.begin() + """ + + assert _checks({SESSION_FACTORY: source}, SESSION_FACTORY) == [ + (CORE_CONNECTION, "hand_out() -> Engine"), + ] + assert _checks({STORE: source}, STORE) == [ + (CORE_CONNECTION, "sqlalchemy.Engine"), + (CORE_CONNECTION, "handle.begin()"), + ] + + +def test_a_declarative_base_module_may_annotate_a_mapped_classs_table() -> None: + source = """ + from typing import ClassVar + + from sqlalchemy import Table + + class TableModel: + __table__: ClassVar[Table] + """ + + assert _checks({DECLARATIVE_BASE: source}, DECLARATIVE_BASE) == [] + assert _checks({STORE: source}, STORE) == [ + (CORE_TABLE_ACCESS, "__table__: ClassVar[Table]") + ] + + +@pytest.mark.parametrize( + ("declaration", "summary"), + [ + ("def read(jobs: Table): ...", "jobs: Table"), + ("selected: Table = choose()", "selected: Table"), + ("class Rows:\n target: Table", "target: Table"), + ("def read(__table__: Table): ...", "__table__: Table"), + ("__table__: Table = choose()", "__table__: Table"), + ( + "class Rows:\n def read(self):\n __table__: Table = choose()", + "__table__: Table", + ), + ], +) +def test_a_declarative_base_module_annotates_only_table_of_its_classes( + declaration: str, summary: str +) -> None: + source = f"from sqlalchemy import Table\n\n{declaration}\n" + + assert _checks({DECLARATIVE_BASE: source}, DECLARATIVE_BASE) == [ + (CORE_TABLE_ACCESS, summary) + ] + + +@pytest.mark.parametrize( + "guarded_class_body", + [ + "if TYPE_CHECKING:\n __table__: ClassVar[Table]", + "if RUNTIME:\n pass\n else:\n __table__: ClassVar[Table]", + ( + "if RUNTIME:\n pass\n elif TYPE_CHECKING:\n" + " __table__: ClassVar[Table]" + ), + ], +) +def test_a_guarded_table_annotation_in_a_class_is_accepted( + guarded_class_body: str, +) -> None: + source = f""" +from typing import TYPE_CHECKING, ClassVar + +from sqlalchemy import Table + +class TableModel: + {guarded_class_body} +""" + + assert _checks({DECLARATIVE_BASE: source}, DECLARATIVE_BASE) == [] + + +@pytest.mark.parametrize("file", [DECLARATIVE_BASE, STORE]) +def test_reading_a_bare_mapped_table_name_is_core_table_access(file: str) -> None: + source = """ + from typing import ClassVar + + from sqlalchemy import select + + class JobRecord: + __table__ = build_jobs_table() + pending = select(__table__) + """ + + assert _checks({file: source}, file) == [(CORE_TABLE_ACCESS, "__table__")] + + +def test_a_declarative_base_module_may_not_declare_a_core_table() -> None: + source = """ + from sqlalchemy import Table + + jobs = Table("household_jobs", metadata) + """ + + assert _checks({DECLARATIVE_BASE: source}, DECLARATIVE_BASE) == [ + (CORE_TABLE_DECLARATION, "Table('household_jobs', ...)") + ] + + +@pytest.mark.parametrize( + "table_expression", + [ + "HouseholdJob.__table__", + "inspect(HouseholdJob).local_table", + "inspect(HouseholdJob).persist_selectable", + "Base.metadata.sorted_tables", + ], +) +def test_a_table_is_reported_where_it_is_reached_and_not_where_it_is_used( + table_expression: str, +) -> None: + models = f""" + from policyengine_api.data.v2.models import Base, HouseholdJob + from sqlalchemy import inspect, select + + jobs = {table_expression} + statement = select(jobs) + """ + store = """ + from policyengine_api.data.v2.example_models import jobs + from sqlalchemy import select + + statement = select(jobs) + """ + sources = {MODELS: models, STORE: store} + + assert _checks(sources, MODELS) == [(CORE_TABLE_ACCESS, table_expression)] + assert _checks(sources, STORE) == [] + + +def test_a_table_declared_in_another_module_is_reported_where_it_is_declared() -> None: + tables = """ + from sqlalchemy import MetaData, Table + + metadata = MetaData() + household_jobs = Table("household_jobs", metadata) + """ + store = """ + from policyengine_api.data.v2.example_tables import household_jobs + from sqlalchemy import select + + statement = select(household_jobs) + """ + tables_module = "policyengine_api/data/v2/example_tables.py" + sources = {tables_module: tables, STORE: store} + + assert _checks(sources, tables_module) == [ + (CORE_TABLE_DECLARATION, "MetaData()"), + (CORE_TABLE_DECLARATION, "Table('household_jobs', ...)"), + ] + assert _checks(sources, STORE) == [] + + +def test_two_files_may_share_a_module_name() -> None: + sources = { + "policyengine_api/services/v2/reports/database_session.py": "", + "policyengine_api/services/v2/policies/database_session.py": "", + } + + assert orm_access_findings(sources) == [] + + +def test_a_bare_mapped_table_read_is_reported_without_a_sqlalchemy_import() -> None: + source = """ + class JobRecord: + __table__ = build_jobs_table() + pending = __table__.select() + """ + + assert _checks({STORE: source}, STORE) == [(CORE_TABLE_ACCESS, "__table__")] + + +def test_names_shared_with_core_tables_elsewhere_are_not_core_tables() -> None: + routes = """ + import pyarrow as pa + + def describe(regions: list[str], households, frame: pa.Table) -> str: + return ", ".join(regions) + str(households.columns) + str(frame.columns) + """ + + assert _checks({ROUTES: routes}, ROUTES) == [] + + +def test_sql_text_is_accepted_as_a_server_default_or_index_condition() -> None: + store = """ + from sqlalchemy import CheckConstraint, Index, text + from sqlalchemy.orm import mapped_column + + created_at = mapped_column(server_default=text("now()")) + positive = CheckConstraint(text("key_version > 0"), name="ck_key_version") + index = Index("ix_pending", "status", postgresql_where=text("status = 'pending'")) + """ + + assert _checks({STORE: store}, STORE) == [] + + +def test_names_from_other_packages_are_not_sqlalchemy() -> None: + store = """ + from textwrap import dedent as text + + settings.update(region="uk") + text("SELECT 1") + """ + + assert _checks({STORE: store}, STORE) == [] + + +def test_metadata_is_accepted_only_in_a_declarative_base_module() -> None: + source = """ + from sqlalchemy import MetaData + + metadata = MetaData(schema="public") + """ + + assert _checks({DECLARATIVE_BASE: source}, DECLARATIVE_BASE) == [] + assert _checks({STORE: source}, STORE) == [ + (CORE_TABLE_DECLARATION, "MetaData(...)") + ] + + +@pytest.mark.parametrize("file", sorted(DECLARATIVE_BASE_MODULES)) +def test_every_declarative_base_module_may_build_metadata(file: str) -> None: + source = "from sqlalchemy import MetaData\n\nmetadata = MetaData()\n" + + assert _checks({file: source}, file) == [] + + +def test_lightweight_tables_and_columns_are_core_declarations() -> None: + store = """ + import sqlalchemy as sa + + pg_class = sa.table("pg_class", sa.column("relname")) + """ + + assert _checks({STORE: store}, STORE) == [ + (CORE_TABLE_DECLARATION, "sa.table('pg_class', ...)"), + (CORE_TABLE_DECLARATION, "sa.column('relname')"), + ] + + +@pytest.mark.parametrize( + "expression", + [ + "Base.metadata.tables['household_jobs']", + "schema.tables['household_jobs']", + "schema.sorted_tables", + "HouseholdJob.__mapper__.local_table", + "HouseholdJob.__mapper__.tables", + "inspect(HouseholdJob).persist_selectable", + "inspect(HouseholdJob).selectable", + "HouseholdJob.__table__", + "class_mapper(HouseholdJob).tables", + "inspect(HouseholdJob).mapper.tables", + "job_mapper.tables", + "held_mapper.tables", + "inspected_mapper.tables", + "HouseholdJob.id.table", + ], +) +def test_reaching_a_mapped_class_or_metadata_table_is_core_table_access( + expression: str, +) -> None: + store = f""" + from sqlalchemy import MetaData, inspect + from sqlalchemy.orm import class_mapper + + schema = MetaData() + job_mapper = inspect(HouseholdJob) + held_mapper = HouseholdJob.__mapper__ + inspected_mapper = inspect(job).mapper + table = {expression} + """ + + assert [ + check + for check, _ in _checks({STORE: store}, STORE) + if check != CORE_TABLE_DECLARATION + ] == [CORE_TABLE_ACCESS] + + +def test_engines_are_held_only_by_a_session_factory_module() -> None: + source = """ + from sqlalchemy import Engine, create_engine + from sqlalchemy.orm import sessionmaker + """ + + assert _checks({SESSION_FACTORY: source}, SESSION_FACTORY) == [] + assert _checks({STORE: source}, STORE) == [ + (CORE_CONNECTION, "sqlalchemy.Engine"), + (CORE_CONNECTION, "sqlalchemy.create_engine"), + ] + + +@pytest.mark.parametrize("file", sorted(SESSION_FACTORY_MODULES)) +def test_every_session_factory_module_may_build_an_engine_and_connect( + file: str, +) -> None: + source = """ + from sqlalchemy import create_engine, event + from sqlalchemy.engine import Connection + + def _connect_sessions(url): + engine = create_engine(url) + event.listen(engine, "connect", _on_connect) + connection: Connection = engine.connect() + return connection + """ + + assert _checks({file: source}, file) == [] + + +def test_a_session_factory_module_may_open_connections_other_modules_may_not() -> None: + source = """ + from sqlalchemy import Engine + from sqlalchemy.engine import Connection + + def bounded_transaction(engine: Engine): + with engine.begin() as connection: + yield connection + + def store_transaction(store): + return store._engine.begin() + + def session_transaction(session_factory): + return session_factory.begin() + """ + + assert _checks({SESSION_FACTORY: source}, SESSION_FACTORY) == [] + assert _checks({STORE: source}, STORE) == [ + (CORE_CONNECTION, "sqlalchemy.Engine"), + (CORE_CONNECTION, "sqlalchemy.engine.Connection"), + (CORE_CONNECTION, "engine.begin()"), + (CORE_CONNECTION, "store._engine.begin()"), + ] + + +@pytest.mark.parametrize( + "call", + ["engine.connect()", "session.connection()", "session.get_bind()"], +) +def test_opening_a_connection_is_reported_outside_a_session_factory_module( + call: str, +) -> None: + source = f"import sqlalchemy\n\nvalue = {call}" + + assert _checks({STORE: source}, STORE) == [(CORE_CONNECTION, call)] + assert _checks({SESSION_FACTORY: source}, SESSION_FACTORY) == [] + + +def test_a_driver_connection_is_reported_in_every_module() -> None: + source = "import sqlalchemy\n\nvalue = engine.raw_connection()" + + for file in (STORE, SESSION_FACTORY): + assert _checks({file: source}, file) == [ + (CORE_CONNECTION, "engine.raw_connection()") + ] + + +@pytest.mark.parametrize( + ("call", "summary"), + [ + ("connection.execute(statement)", "connection.execute(...)"), + ("conn.scalar(statement)", "conn.scalar(...)"), + ("store_connection.scalars(statement)", "store_connection.scalars(...)"), + ("self._connection.execute(statement)", "self._connection.execute(...)"), + ("connection.stream(statement)", "connection.stream(...)"), + ("connection.stream_scalars(statement)", "connection.stream_scalars(...)"), + ("bind.execute(statement)", "bind.execute(...)"), + ("database.execute(statement)", "database.execute(...)"), + ("self.store.execute(statement)", "self.store.execute(...)"), + ("connections.execute(statement)", "connections.execute(...)"), + ], +) +def test_a_statement_on_an_unannotated_connection_is_reported( + call: str, summary: str +) -> None: + """``execute`` must run on a session, whatever else its receiver is called.""" + source = f"import sqlalchemy\n\nvalue = {call}" + + for file in (STORE, SESSION_FACTORY): + assert _checks({file: source}, file) == [(CORE_CONNECTION, summary)] + + +@pytest.mark.parametrize( + "call", + [ + "session.execute(statement)", + "session.scalar(statement)", + "session.scalars(statement)", + "self._session.execute(statement)", + "store_session.execute(statement)", + "Session(bind).execute(statement)", + "session.execute(statement).scalars()", + "result.scalars()", + "result.scalar()", + ], +) +def test_a_statement_on_a_session_is_not_reported(call: str) -> None: + source = f"import sqlalchemy\n\nvalue = {call}" + + assert _checks({STORE: source}, STORE) == [] + + +def test_a_connection_outside_sqlalchemy_is_not_reported() -> None: + assert _checks({ROUTES: "value = connection.execute(statement)"}, ROUTES) == [] + + +def test_a_session_factory_module_hands_out_no_engine_or_connection() -> None: + source = """ + from sqlalchemy import Connection, Engine, create_engine + from sqlalchemy.orm import Session, sessionmaker + + def _private_engine(url) -> Engine: + return create_engine(url) + + def public_engine(url) -> Engine: + return create_engine(url) + + def optional_engine(url) -> "Engine | None": + return None + + def public_connection(engine) -> Connection: + return engine.connect() + + def session_factory(engine: Engine) -> sessionmaker[Session]: + return sessionmaker(engine) + + class Sessions: + def engine(self) -> Engine: + return self._engine + """ + + assert _checks({SESSION_FACTORY: source}, SESSION_FACTORY) == [ + (CORE_CONNECTION, "public_engine() -> Engine"), + (CORE_CONNECTION, "optional_engine() -> Engine"), + (CORE_CONNECTION, "public_connection() -> Connection"), + (CORE_CONNECTION, "engine() -> Engine"), + ] + + +def test_only_a_session_factory_module_reads_a_session_factorys_engine() -> None: + source = """ + import sqlalchemy + + engine = session_factory.kw["bind"] + autoflush = session_factory.kw["autoflush"] + """ + + assert _checks({SESSION_FACTORY: source}, SESSION_FACTORY) == [] + assert _checks({STORE: source}, STORE) == [ + (CORE_CONNECTION, "session_factory.kw['bind']"), + ] + + +@pytest.mark.parametrize( + ("source", "summary"), + [ + ("sa.text('SELECT 1')", "sa.text('SELECT 1')"), + ("sa.literal_column('count(*)')", "sa.literal_column('count(*)')"), + ("session.exec_driver_sql('SELECT 1')", "session.exec_driver_sql('SELECT 1')"), + ("driver_connection.cursor()", "driver_connection.cursor()"), + ], +) +def test_raw_sql_is_reported(source: str, summary: str) -> None: + store = f""" + import sqlalchemy as sa + + statement = {source} + """ + + for file in (STORE, SESSION_FACTORY): + assert _checks({file: store}, file) == [(RAW_SQL, summary)] + + +@pytest.mark.parametrize( + "statement", + [ + "from sqlmodel import Field, Session, SQLModel, col, select", + "import sqlmodel", + "from sqlmodel.sql.sqltypes import AutoString", + ], +) +def test_sqlmodel_imports_are_accepted(statement: str) -> None: + assert _checks({STORE: statement}, STORE) == [] + + +@pytest.mark.parametrize( + ("source", "expected"), + [ + ( + "from sqlmodel import text\n\nstatement = text('SELECT 1')", + [(RAW_SQL, "text('SELECT 1')")], + ), + ( + "import sqlmodel\n\nstatement = sqlmodel.text('SELECT 1')", + [(RAW_SQL, "sqlmodel.text('SELECT 1')")], + ), + ( + "from sqlmodel import create_engine", + [(CORE_CONNECTION, "sqlmodel.create_engine")], + ), + ( + "import sqlmodel\n\nengine = sqlmodel.create_engine(url)", + [(CORE_CONNECTION, "sqlmodel.create_engine")], + ), + ( + "from sqlmodel import Table\n\njobs = Table('household_jobs', metadata)", + [(CORE_TABLE_DECLARATION, "Table('household_jobs', ...)")], + ), + ( + "from sqlmodel import SQLModel\n\ntables = SQLModel.metadata.tables", + [(CORE_TABLE_ACCESS, "SQLModel.metadata.tables")], + ), + ( + "from sqlmodel import Session\n\nrows = connection.execute(statement)", + [(CORE_CONNECTION, "connection.execute(...)")], + ), + ], +) +def test_sqlalchemy_names_imported_from_sqlmodel_are_checked( + source: str, expected: list[tuple[str, str]] +) -> None: + assert _checks({STORE: source}, STORE) == expected + + +@pytest.mark.parametrize( + ("listener", "summary"), + [ + ( + "event.listen(engine, 'connect', set_role)", + "event.listen(engine, 'connect')", + ), + ( + "event.listen(engine.pool, 'checkout', check)", + "event.listen(engine.pool, 'checkout')", + ), + ( + "event.listen(bind, 'before_cursor_execute', record, retval=True)", + "event.listen(bind, 'before_cursor_execute')", + ), + ( + "event.listen(engine, 'handle_error', record_error)", + "event.listen(engine, 'handle_error')", + ), + ( + "@sa.event.listens_for(engine, 'connect')\ndef on_connect(): ...", + "sa.event.listens_for(engine, 'connect')", + ), + ( + "@listens_for(engine, 'begin')\ndef on_begin(): ...", + "listens_for(engine, 'begin')", + ), + ], +) +def test_pool_engine_and_dialect_event_listeners_need_a_session_factory_module( + listener: str, summary: str +) -> None: + source = ( + "import sqlalchemy as sa\nfrom sqlalchemy import event\n" + f"from sqlalchemy.event import listens_for\n\n{listener}\n" + ) + + assert _checks({STORE: source}, STORE) == [(CORE_CONNECTION, summary)] + assert _checks({SESSION_FACTORY: source}, SESSION_FACTORY) == [] + + +@pytest.mark.parametrize( + "listener", + [ + "event.listen(factory, 'before_flush', refuse_flush)", + "event.listen(Session, 'after_commit', record)", + "event.listen(HouseholdJob, 'before_insert', stamp)", + "event.listen(engine, event_name, record)", + "signals.listen(engine, 'connect', record)", + ], +) +def test_session_and_mapper_event_listeners_are_accepted(listener: str) -> None: + source = f"from sqlalchemy import event\n\n{listener}\n" + + assert _checks({STORE: source}, STORE) == [] + + +@pytest.mark.parametrize( + ("binding", "receiver"), + [ + ("first, label = create_engine(url), 'primary'", "first"), + ("(first, label), other = (create_engine(url), 'a'), 1", "first"), + ("[first, label] = [create_engine(url), 'primary']", "first"), + ("self.first = create_engine(url)", "self.first"), + ("first: object = create_engine(url)", "first"), + ("value = (first := create_engine(url))", "first"), + ], +) +def test_every_way_of_binding_an_engine_is_followed_to_begin( + binding: str, receiver: str +) -> None: + source = f""" + from sqlalchemy import create_engine + + {binding} + transaction = {receiver}.begin() + """ + + assert _checks({STORE: source}, STORE) == [ + (CORE_CONNECTION, "sqlalchemy.create_engine"), + (CORE_CONNECTION, f"{receiver}.begin()"), + ] + + +def test_a_name_annotated_as_an_engine_is_followed_to_begin() -> None: + source = """ + from sqlalchemy import Engine + + def open_transaction(primary: "Engine | None", held: Engine): + return primary.begin(), held.begin() + """ + + assert _checks({STORE: source}, STORE) == [ + (CORE_CONNECTION, "sqlalchemy.Engine"), + (CORE_CONNECTION, "primary.begin()"), + (CORE_CONNECTION, "held.begin()"), + ] + + +@pytest.mark.parametrize( + ("binding", "read"), + [ + ("schema, label = MetaData(), 'public'", "schema.tables"), + ("job_mapper, label = inspect(HouseholdJob), 'jobs'", "job_mapper.tables"), + ("job_mapper, label = HouseholdJob.__mapper__, 'jobs'", "job_mapper.tables"), + ], +) +def test_tuple_assignments_bind_metadata_and_mappers(binding: str, read: str) -> None: + source = f""" + from sqlalchemy import MetaData, inspect + + {binding} + value = {read} + """ + + assert _checks({DECLARATIVE_BASE: source}, DECLARATIVE_BASE) == [ + (CORE_TABLE_ACCESS, read) + ] + + +def test_begin_counts_as_opening_a_connection_only_on_an_engine() -> None: + store = """ + from sqlalchemy import create_engine + + primary = create_engine(url) + first = primary.begin() + second = policyengine_settings.begin() + """ + + assert _checks({STORE: store}, STORE) == [ + (CORE_CONNECTION, "sqlalchemy.create_engine"), + (CORE_CONNECTION, "primary.begin()"), + ] + + +def test_async_engines_and_connections_are_reported() -> None: + store = "from sqlalchemy.ext.asyncio import AsyncConnection, AsyncEngine" + + assert _checks({STORE: store}, STORE) == [ + (CORE_CONNECTION, "sqlalchemy.ext.asyncio.AsyncConnection"), + (CORE_CONNECTION, "sqlalchemy.ext.asyncio.AsyncEngine"), + ] + + +@pytest.mark.parametrize( + ("source", "check"), + [ + ("sa.TableClause('household_jobs')", CORE_TABLE_DECLARATION), + ("sa.ColumnClause('id')", CORE_TABLE_DECLARATION), + ("sa.TextClause('SELECT 1')", RAW_SQL), + ], +) +def test_core_clause_classes_are_reported(source: str, check: str) -> None: + store = f""" + import sqlalchemy as sa + + clause = {source} + """ + + assert [found for found, _ in _checks({STORE: store}, STORE)] == [check] + + +def _load_module( + name: str, source: str, monkeypatch: pytest.MonkeyPatch +) -> types.ModuleType: + module = types.ModuleType(name) + # SQLAlchemy resolves a mapped class's annotations in its module. + monkeypatch.setitem(sys.modules, name, module) + exec(compile(dedent(source), name, "exec"), module.__dict__) # noqa: S102 # runs the test's own module source + return module + + +def test_the_runtime_check_accepts_tables_mapped_by_either_declarative_base( + monkeypatch: pytest.MonkeyPatch, +) -> None: + mapped = _load_module( + "orm_only_mapped_models", + """ + from sqlalchemy import MetaData, Table + from sqlalchemy.orm import ( + DeclarativeBase, + DeclarativeBaseNoMeta, + Mapped, + mapped_column, + ) + + class Base(DeclarativeBase): + pass + + class NoMetaBase(DeclarativeBaseNoMeta): + metadata = MetaData() + + class HouseholdJob(Base): + __tablename__ = "household_jobs" + id: Mapped[int] = mapped_column(primary_key=True) + + class Report(NoMetaBase): + __tablename__ = "reports" + id: Mapped[int] = mapped_column(primary_key=True) + + stray = Table("stray", Base.metadata) + """, + monkeypatch, + ) + + findings = unmapped_table_findings([mapped], Path(), location="example") + + assert [(finding.check, finding.source) for finding in findings] == [ + (UNMAPPED_TABLE, "stray") + ] + + +def test_the_runtime_check_accepts_sqlmodel_table_classes( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """SQLModel table classes are mapped classes. + + The classes use a registry of their own, so they stay out of the v2 tables' + metadata, which SQLModel's default registry holds. + """ + mapped = _load_module( + "orm_only_sqlmodel_models", + """ + from sqlalchemy import Table + from sqlalchemy.orm import registry + from sqlmodel import Field, SQLModel + + class ExampleBase(SQLModel, registry=registry()): + pass + + class HouseholdJob(ExampleBase, table=True): + __tablename__ = "household_jobs" + id: int | None = Field(default=None, primary_key=True) + + stray = Table("stray", ExampleBase.metadata) + """, + monkeypatch, + ) + + findings = unmapped_table_findings([mapped], Path(), location="example") + + assert [(finding.check, finding.source) for finding in findings] == [ + (UNMAPPED_TABLE, "stray") + ] + + +@pytest.mark.parametrize( + "expression", ["key.table", "job_id.table", "self.model.id.table", "rows.table"] +) +def test_any_table_read_in_a_module_using_sqlalchemy_is_core_table_access( + expression: str, +) -> None: + store = f""" + from sqlalchemy import insert + + def write(self, key, job_id, rows): + return insert({expression}) + """ + + assert _checks({STORE: store}, STORE) == [(CORE_TABLE_ACCESS, expression)] + + +def test_a_called_or_assigned_table_attribute_is_not_a_table_read() -> None: + store = """ + import sqlalchemy as sa + + class Report: + def __init__(self, rows, model): + self.table = model + self.rows = rows.table(columns=["id"]) + """ + + assert _checks({STORE: store}, STORE) == [] + + +def test_name_rules_apply_only_in_modules_that_use_sqlalchemy() -> None: + routes = """ + def publish(settings, socket, cache_engine, driver): + settings.bigquery.table + socket.connect() + cache_engine.begin() + driver.cursor() + event.listen(cache_engine, "connect", record) + """ + + assert _checks({ROUTES: routes}, ROUTES) == [] + + +def test_a_name_assigned_a_mapped_class_or_its_table_name_is_not_a_table() -> None: + store = """ + from policyengine_api.data.v2.models import HouseholdJob + from sqlalchemy import select + + job_model = HouseholdJob + table_name = HouseholdJob.__tablename__ + statement = select(job_model).where(job_model.id == table_name) + """ + + assert _checks({STORE: store}, STORE) == [] + + +def _finding(file: str, source: str, line: int = 1) -> Finding: + return Finding(file, line, RAW_SQL, source) + + +def _construct_exception(path: str, match: str | None) -> RuleException: + return RuleException( + path=path, reason="no ORM form", match=match, category=NO_ORM_FORM + ) + + +def test_an_exception_allows_every_finding_with_its_file_and_source() -> None: + set_role = "text(f'SET ROLE {role}')" + findings = [ + _finding(STORE, set_role, line=3), + _finding(STORE, set_role, line=9), + _finding(STORE, "text('RESET ROLE')", line=12), + _finding(SESSION_FACTORY, set_role, line=4), + ] + exceptions = [_construct_exception(STORE, set_role)] + + assert undeclared_findings(findings, exceptions) == [ + _finding(STORE, "text('RESET ROLE')", line=12), + _finding(SESSION_FACTORY, set_role, line=4), + ] + + +def test_an_exception_that_names_no_finding_is_unused() -> None: + findings = [_finding(STORE, "text('RESET ROLE')")] + used = _construct_exception(STORE, "text('RESET ROLE')") + other_file = _construct_exception(SESSION_FACTORY, "text('RESET ROLE')") + other_source = _construct_exception(STORE, "text('SET ROLE owner')") + path_exception = RuleException( + path="migrations/**/*.py", reason="revisions", category=MIGRATION_REVISION + ) + + assert unused_exceptions( + findings, [used, other_file, other_source, path_exception] + ) == [other_file, other_source] + + +def test_a_path_exception_takes_its_files_out_of_the_check(tmp_path: Path) -> None: + for file in ("migrations/v2/env.py", "migrations/v2/versions/one.py", "app.py"): + (tmp_path / file).parent.mkdir(parents=True, exist_ok=True) + (tmp_path / file).write_text("", encoding="utf-8") + exceptions = [ + RuleException( + path="migrations/**/*.py", reason="revisions", category=MIGRATION_REVISION + ), + _construct_exception("app.py", "text('SELECT 1')"), + ] + + assert unscanned_files(exceptions, tmp_path) == { + "migrations/v2/env.py", + "migrations/v2/versions/one.py", + } + + +def test_exception_problems_name_each_unusable_exception(tmp_path: Path) -> None: + (tmp_path / "migrations").mkdir() + (tmp_path / "migrations" / "env.py").write_text("", encoding="utf-8") + (tmp_path / "store.py").write_text("", encoding="utf-8") + exceptions = [ + _construct_exception("store.py", "text('SELECT 1')"), + _construct_exception("store.py", None), + _construct_exception("missing.py", "text('SELECT 1')"), + RuleException( + path="migrations/*.py", reason="revisions", category=MIGRATION_REVISION + ), + RuleException( + path="migrations/*.py", + reason="revisions", + match="text('SELECT 1')", + category=MIGRATION_REVISION, + ), + RuleException( + path="scripts/*.py", reason="scripts", category=MIGRATION_REVISION + ), + RuleException(path="store.py", reason="no category"), + RuleException(path="store.py", reason="driver", category="driver-access"), + ] + + assert exception_problems( + exceptions, ["migrations/env.py", "store.py"], tmp_path + ) == [ + "exception for store.py names no construct: set match to the finding's source", + "exception for missing.py must name one existing file", + "exception for migrations/*.py skips whole files, so it takes no match", + "exception for scripts/*.py matches no file the rule test reads: remove it", + "exception for store.py has unknown category None: use one of " + "['no-orm-form', 'migration-revision']", + "exception for store.py has unknown category 'driver-access': use one of " + "['no-orm-form', 'migration-revision']", + ] diff --git a/tests/unit/data/test_orm_only.py b/tests/unit/data/test_orm_only.py new file mode 100644 index 000000000..0029a3cc8 --- /dev/null +++ b/tests/unit/data/test_orm_only.py @@ -0,0 +1,206 @@ +"""Guards for rule api.data.orm-only (rules/registry.toml). + +Code that reads or writes database rows declares tables only as SQLAlchemy ORM +mapped classes, SQLModel classes included, and runs every statement through an +ORM Session against them. docs/engineering/skills/alembic-migrations.md +explains the rule under "Database statements through the ORM", with the way to +write each kind of statement. The checks live in orm_access_support.py. + +A finding fails unless one of the rule's ``no-orm-form`` [[rule.exception]] +entries names its module and, in ``match``, its source, and an entry that names +no finding fails too. The rule's ``migration-revision`` entry takes +``migrations/`` out of the check. +""" + +from __future__ import annotations + +import importlib +import importlib.util +import sys +from functools import cache +from pathlib import Path +from typing import TYPE_CHECKING + +from scripts.rules.load import load_registry +from tests.unit.data.orm_access_support import ( + CORE_CONNECTION, + CORE_TABLE_DECLARATION, + RAW_SQL, + UNMAPPED_TABLE, + Finding, + exception_problems, + orm_access_findings, + undeclared_findings, + unmapped_table_findings, + unmapped_tables_in_packages, + unscanned_files, + unused_exceptions, +) + +if TYPE_CHECKING: + from types import ModuleType + + import pytest + + from scripts.rules.model import Rule + +PROJECT_ROOT = Path(__file__).parents[3] +RULE_ID = "api.data.orm-only" +RULE_DOC = ( + "docs/engineering/skills/alembic-migrations.md#database-statements-through-the-orm" +) +FIXTURES_ROOT = PROJECT_ROOT / "rules" / "fixtures" / RULE_ID +# The directories the rule covers: its scope in rules/registry.toml. +SCANNED_DIRECTORIES = ("policyengine_api", "scripts", "tests", ".github") +# The directories the rule test reads: the scanned ones and migrations/, which +# the rule's migration-revision exception takes out again. +READ_DIRECTORIES = (*SCANNED_DIRECTORIES, "migrations") +# The packages that declare tables, and the test modules that write rows. Every +# table they hold needs a mapped class. +TABLE_PACKAGES = ("policyengine_api.data",) +ROW_HELPER_MODULES = ( + "tests.integration.catalog_rows", + "tests.integration.simulation_rows", + "tests.integration.stored_report_rows", + "tests.unit.v2.sqlite_report_rows", +) + + +@cache +def _rule() -> Rule: + registry, violations = load_registry(PROJECT_ROOT) + assert registry is not None, violations + rule = registry.rule(RULE_ID) + assert rule is not None, f"rules/registry.toml has no rule {RULE_ID}" + return rule + + +def _relative_name(source_file: Path) -> str: + return source_file.relative_to(PROJECT_ROOT).as_posix() + + +@cache +def _read_files() -> tuple[str, ...]: + """Return every Python file under READ_DIRECTORIES, as relative paths.""" + return tuple( + _relative_name(source_file) + for directory in READ_DIRECTORIES + for source_file in sorted((PROJECT_ROOT / directory).rglob("*.py")) + ) + + +def _scanned_files() -> list[str]: + """Return the files the rule checks: those read, less the unscanned ones.""" + unscanned = unscanned_files(_rule().exceptions, PROJECT_ROOT) + return [file for file in _read_files() if file not in unscanned] + + +@cache +def _repository_findings() -> tuple[Finding, ...]: + sources = { + file: (PROJECT_ROOT / file).read_text(encoding="utf-8") + for file in _scanned_files() + } + return tuple(orm_access_findings(sources)) + + +def _load_fixture(fixture_name: str, monkeypatch: pytest.MonkeyPatch) -> ModuleType: + path = FIXTURES_ROOT / fixture_name + spec = importlib.util.spec_from_file_location(f"orm_only_{path.stem}", path) + assert spec is not None + assert spec.loader is not None + module = importlib.util.module_from_spec(spec) + # SQLAlchemy resolves a mapped class's annotations in its module, which it + # finds in sys.modules. + monkeypatch.setitem(sys.modules, spec.name, module) + spec.loader.exec_module(module) + return module + + +def _fixture_findings(fixture_name: str) -> list[tuple[int, str, str]]: + fixture = FIXTURES_ROOT / fixture_name + findings = orm_access_findings({fixture_name: fixture.read_text(encoding="utf-8")}) + return [(finding.line, finding.check, finding.source) for finding in findings] + + +def test_database_code_uses_only_the_orm() -> None: + findings = _repository_findings() + exceptions = _rule().exceptions + + problems = [str(finding) for finding in undeclared_findings(findings, exceptions)] + problems.extend( + f"declared exception names no finding, remove it: {exception.path}: " + f"{exception.match}" + for exception in unused_exceptions(findings, exceptions) + ) + + assert problems == [], ( + "Code reaches the database without the ORM; use a mapped class and a " + f"Session ({RULE_DOC}). For a .table finding on converted code, name the " + "attribute after what it holds, such as model" + ) + + +def test_every_table_is_mapped_by_a_class() -> None: + row_helpers = [importlib.import_module(name) for name in ROW_HELPER_MODULES] + + findings = [ + *unmapped_tables_in_packages(TABLE_PACKAGES, PROJECT_ROOT), + *unmapped_table_findings(row_helpers, PROJECT_ROOT), + ] + + assert [str(finding) for finding in findings] == [] + + +def test_orm_only_exceptions_match_a_finding_and_name_a_category() -> None: + exceptions = _rule().exceptions + + problems = exception_problems(exceptions, _read_files(), PROJECT_ROOT) + problems.extend( + f"exception for {exception.path} names no finding: {exception.match}" + for exception in unused_exceptions(_repository_findings(), exceptions) + ) + + assert problems == [] + + +def test_every_scanned_directory_contributes_files() -> None: + scanned = _scanned_files() + + unscanned_directories = [ + directory + for directory in SCANNED_DIRECTORIES + if not any(file.startswith(f"{directory}/") for file in scanned) + ] + + assert unscanned_directories == [] + assert _rule().scope == tuple( + f"{directory}/**/*.py" for directory in SCANNED_DIRECTORIES + ) + + +def test_rule_proof_orm_only(monkeypatch: pytest.MonkeyPatch) -> None: + """Proof for rule api.data.orm-only (rules/registry.toml).""" + assert _fixture_findings("bad_simulation_rows.py") == [ + (25, CORE_CONNECTION, "sqlalchemy.Connection"), + (27, CORE_TABLE_DECLARATION, "sa.Table('stage_catalog_models', ...)"), + (29, CORE_TABLE_DECLARATION, "sa.MetaData()"), + (30, CORE_TABLE_DECLARATION, "sa.Column('id', ...)"), + (31, CORE_TABLE_DECLARATION, "sa.Column('name', ...)"), + (39, CORE_CONNECTION, "connection.execute(...)"), + ( + 40, + RAW_SQL, + "text(f'INSERT INTO {table} ({columns}) VALUES ({placeholders})')", + ), + (62, CORE_CONNECTION, "connection.execute(...)"), + (63, RAW_SQL, "text(f'DELETE FROM {table} WHERE id = :id')"), + ] + assert _fixture_findings("good_simulation_rows.py") == [] + bad_module = _load_fixture("bad_simulation_rows.py", monkeypatch) + good_module = _load_fixture("good_simulation_rows.py", monkeypatch) + assert [ + (finding.check, finding.source) + for finding in unmapped_table_findings([bad_module], PROJECT_ROOT) + ] == [(UNMAPPED_TABLE, "stage_catalog_models")] + assert unmapped_table_findings([good_module], PROJECT_ROOT) == [] From ac7340b0ed68ce6a66bd04be04cf0cae4be84e76 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:34:52 +0400 Subject: [PATCH 12/20] Give tests ORM session factories, and move the shared row helpers onto them tests/fixtures/database_sessions.py is the tests' one session-factory module: session factories for the disposable v2 PostgreSQL database as its owner or as a managed role, for the disposable MySQL database and for in-memory SQLite copies; act_as and act_as_owner through set_config; schema inspection; statement recording; and the few statements with no ORM form (TRUNCATE, CREATE and DROP ROLE, GRANT, SQLite's foreign-key PRAGMA), each a named exception. The shared row helpers and fixtures now take sessions and add rows through mapped classes, and the v1 and v2 session-factory modules gain unpooled session factories and schema inspectors for the production modules that build their own engines. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/v2-integration-check.yml | 4 +- docs/engineering/skills/alembic-migrations.md | 88 ++++- docs/generated/rules.md | 8 + policyengine_api/data/orm.py | 32 +- policyengine_api/data/v2/database.py | 52 ++- rules/registry.toml | 48 +++ tests/fixtures/database_sessions.py | 335 ++++++++++++++++ tests/fixtures/integration/alembic_v2.py | 12 +- tests/fixtures/v2_metadata_service.py | 37 +- tests/fixtures/v2_metadata_service_helpers.py | 28 +- tests/integration/catalog_rows.py | 93 +++-- tests/integration/conftest.py | 80 +++- tests/integration/simulation_rows.py | 98 +++-- tests/integration/stored_report_rows.py | 364 +++++++++--------- tests/integration/test_database_sessions.py | 243 ++++++++++++ tests/integration/user_report_run_support.py | 162 ++++---- tests/to_refactor/conftest.py | 33 +- tests/unit/conftest.py | 47 +-- tests/unit/data/orm_access_support.py | 4 +- tests/unit/data/test_database_sessions.py | 180 +++++++++ tests/unit/data/test_run_schema.py | 29 +- tests/unit/v2/sqlite_report_rows.py | 21 +- tests/unit/v2/user_service_support.py | 43 +-- 23 files changed, 1557 insertions(+), 484 deletions(-) create mode 100644 tests/fixtures/database_sessions.py create mode 100644 tests/integration/test_database_sessions.py create mode 100644 tests/unit/data/test_database_sessions.py diff --git a/.github/workflows/v2-integration-check.yml b/.github/workflows/v2-integration-check.yml index 3c45278f7..018370d8b 100644 --- a/.github/workflows/v2-integration-check.yml +++ b/.github/workflows/v2-integration-check.yml @@ -79,8 +79,8 @@ jobs: run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_policy_persistence.py tests/integration/test_v2_dynamic_persistence.py tests/integration/test_v1_policy_dual_write.py tests/integration/test_mysql_policy_dual_write.py tests/integration/test_v2_user_policy_mirroring.py tests/integration/test_v1_user_policy_dual_write.py - name: Test signed-in identity provisioning, user associations, saved detailed-save records and user types run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_user_identity_persistence.py tests/integration/test_v2_user_type_persistence.py tests/integration/test_v2_saved_detailed_save_records.py tests/integration/test_v2_saved_budget_window_reports.py - - name: Test comparison-run persistence, the simulation API's roles, shared reports and runs, and privilege reconciliation as the managed roles - run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_stage12_comparison_persistence.py tests/integration/test_v2_simulation_role_privileges.py tests/integration/test_v2_shared_report_rows.py tests/integration/test_v2_privilege_reconciliation.py + - name: Test comparison-run persistence, the simulation API's roles, shared reports and runs, privilege reconciliation as the managed roles, and the tests' database sessions + run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_stage12_comparison_persistence.py tests/integration/test_v2_simulation_role_privileges.py tests/integration/test_v2_shared_report_rows.py tests/integration/test_v2_privilege_reconciliation.py tests/integration/test_database_sessions.py - name: Test v2 household persistence, immediate v1 copying, household calculation reads and household reports run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_household_persistence.py tests/integration/test_v1_household_dual_write.py tests/integration/test_mysql_household_spm_dual_write.py tests/integration/test_v2_household_calculation_reads.py tests/integration/test_v2_household_reports.py - name: Test the row counts v1 ORM updates report on MySQL diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index b0e85d5e2..1926328ce 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -211,7 +211,9 @@ Two kinds of module have a role of their own: - **Session-factory modules** are the only modules that may create or hold an Engine, open a Connection or attach pool events: - `policyengine_api/data/orm.py`, `policyengine_api/data/v2/database.py`, and + `policyengine_api/data/orm.py` (with `policyengine_api/data/orm_pool_events.py`, + whose listeners record the v1 pool's events), + `policyengine_api/data/v2/database.py`, and `tests/fixtures/database_sessions.py` for the tests. They hand out Session factories, never an Engine or a Connection. When a module needs its own engine settings, such as `NullPool`, a deploy-time role or a separate URL, @@ -221,7 +223,44 @@ Two kinds of module have a role of their own: `MetaData`: `policyengine_api/data/v1_models.py`, `policyengine_api/data/v2/models/__init__.py`, and `policyengine_api/data/v2/catalog/publication_staging_base.py`, the - publication staging tables' own declarative base. + publication staging tables' own declarative base (SQLModel classes on a + `registry()` of their own, so `api.v2.single-orm-layer` holds). + +### Session factories + +Commands and scripts that run once take their Session factories from the +session-factory modules: + +| Function | What it gives | +| --- | --- | +| `orm.unpooled_v1_sessions(url)` | A context manager yielding API v1 Session factories for the database at `url`, on an engine with no pool, disposed of on exit. For the household mirror command and the v1 schema migration. | +| `orm.v1_schema_inspector(source)` | SQLAlchemy's `Inspector` of the database a v1 Session (inside its transaction) or Session factory uses. | +| `v2.database.unpooled_v2_sessions(url)` | The same for API v2, given `V2DatabaseSettings.connection.url` or `V2AlembicSettings.url`: catalog initialization and privilege reconciliation. | +| `v2.database.unpooled_v2_read_only_sessions(url)` | The same, with every transaction `READ ONLY` (`postgresql_readonly`): the migration qualification commands. | +| `v2.database.v2_schema_inspector(source)` | SQLAlchemy's `Inspector` of the database a v2 Session or Session factory uses, as the migration target checks need. | + +Tests take theirs from `tests/fixtures/database_sessions.py`, or from the +integration fixtures built on it (`tests/integration/conftest.py`): + +| Function or fixture | What it gives or does | +| --- | --- | +| `v2_owner_sessions(url)`; fixture `v2_owner_sessions` | Session factories of the disposable v2 PostgreSQL database's owner, its superuser. | +| `v2_role_sessions(url, role)`; fixture `v2_sessions_as_role(role)` | Session factories whose every connection starts as `role` (PostgreSQL's `role` startup option), so every statement is checked against its privileges. | +| `v1_sessions(url)`; fixture `v1_sessions` | API v1's Session factories of the disposable MySQL database. | +| `sqlite_v2_sessions(foreign_keys=False)` | Session factories of a new in-memory SQLite copy of the v2 schema, whose savepoints behave as on PostgreSQL (Python 3.12's sqlite3 `autocommit=False`); with `foreign_keys`, SQLite enforces the foreign keys. | +| `sqlite_v1_sessions(json_serializer=None)` | API v1's Session factories of a new in-memory SQLite copy of its schema, with SQLite numbering policies. | +| `serve_v1_sessions(monkeypatch, sessions)` | Makes `orm.get_v1_session_factory()` open `sessions`' connections for the test. | +| `act_as(session, role)`, `act_as_owner(session)` | Act as `role`, or as the database's owner again, until the transaction ends. | +| `schema_inspector(source)` | SQLAlchemy's `Inspector` of the database a Session or Session factory uses. | +| `recorded_statements(source)` | A context manager yielding the list of SQL statements sent through a Session or Session factory inside it. | +| `delete_all_rows(session, registry)` | Deletes every row of every table a registry's mapped classes map, such as `V1Base.registry`. | +| `truncate(session, *models)` | `TRUNCATE ... CASCADE` of the models' tables. | +| `create_role(session, role)`, `drop_role(session, role)` | Create a role that can't log in; drop what it owns and was granted, then the role. | +| `grant(session, privileges, on=Model, to=role)` | `GRANT privileges ON TABLE` the model's table `TO` the role. | +| `grant_declared_v2_privileges(url, declared)` | Creates the missing managed roles and grants their declared privileges, as `reconcile_v2_privileges.py apply --create-missing-roles` does. | + +`tests/integration/simulation_rows.py` has `add_row(session, Model, **values)` +and `refused(session, ...)`. ### Writing each kind of statement @@ -231,23 +270,28 @@ Two kinds of module have a role of their own: and `update(Model)`, `delete(Model)`, `select(Model)` and `select(Model.column)` in `session.execute` or `session.scalars`. A test helper such as `insert_row(connection, "table", **values)` becomes - `add_row(session, Model, **values)`, given a mapped class. + `add_row(session, Model, **values)`, given a mapped class. A JSON column + takes the Python value, such as `[2026]`, not its JSON text. - **Postgres functions**: `func`, as in `session.execute(select(func.current_database(), func.current_user()))`, `func.pg_backend_pid()` and `func.has_table_privilege(...)`. +- **Postgres settings**: `select(func.set_config(name, value, true()))` sets + one until the transaction ends, as `SET LOCAL` does; read-only transactions + use SQLAlchemy's `postgresql_readonly` option + (`unpooled_v2_read_only_sessions`). - **Schema reads**: SQLAlchemy's `Inspector`, which a function in a session-factory module returns for a Session factory or a Session. Never select from `information_schema` or `pg_catalog` with SQL text. -- **Roles in tests**: `act_as(session, role)` and `act_as_owner(session)` in - the test session module, which run `SET ROLE` and `RESET ROLE` inside the - session's transaction (a named exception), or a Session factory whose - engine runs `SET ROLE` when it connects. Setup rows stay in the same - rolled-back transaction where a test relies on that. +- **Roles in tests**: `act_as(session, role)` and `act_as_owner(session)` set + the `role` setting with `set_config` inside the session's transaction, as + `SET LOCAL ROLE` and `RESET ROLE` do; or a role's Session factory + (`v2_sessions_as_role`), whose connections start as the role. Setup rows + stay in the same rolled-back transaction where a test relies on that. - **Refusals**: `refused(session, ...)` runs the statements inside it in `session.begin_nested()` and expects the error. -- **TRUNCATE in test cleanup**: one helper in the test session module (a - named exception), or `delete(Model)` in dependency order where that is as - simple. +- **TRUNCATE in test cleanup**: `truncate(session, *models)` in the test + session module (a named exception), or `delete(Model)` in dependency order + where that is as simple. - **COPY**: the publication staging tables are mapped classes on their own declarative base, not `V2_METADATA`, so Alembic never sees them. They stay `TEMPORARY` with `ON COMMIT DROP`. COPY through the driver connection stays @@ -263,17 +307,19 @@ The rule's exceptions are its `[[rule.exception]]` entries in - **`no-orm-form`**: one construct in one module that SQLAlchemy's ORM has no form for. `path` names the module, and `match` is the finding's source exactly as the check reports it, the text after its kind, such as - `text('RESET ROLE')`. The entry allows every finding in that module with - that source. + `text(f'DROP ROLE {quoted_role}')`. The entry allows every finding in that + module with that source. - **`migration-revision`**: a path pattern the rule test doesn't read. The rule test fails on a finding no entry names, on an entry that names no finding, and on an entry with an unknown category, a `no-orm-form` entry without a `match` or an existing file, or a `migration-revision` entry that names no file. Only statements SQLAlchemy can't express get an entry: `GRANT` -and `REVOKE`, `CREATE`, `ALTER` and `DROP ROLE`, `SET ROLE` and `RESET ROLE`, -`TRUNCATE`, `COPY`, and Postgres session settings. Keep them in as few modules -as possible: the test session module, `privilege_reconciliation.py` and +and `REVOKE`, `CREATE`, `ALTER` and `DROP ROLE` (with `DROP OWNED BY`), +`TRUNCATE`, `COPY`, and connection settings no SQL function sets, such as +SQLite's `foreign_keys`. Roles and Postgres settings inside a transaction +need none: `set_config` sets them. Keep the entries in as few modules as +possible: the test session module, `privilege_reconciliation.py` and `publication_staging.py`. The entries: 1. **Alembic environments and revisions** (`migration-revision`), @@ -281,6 +327,16 @@ as possible: the test session module, `privilege_reconciliation.py` and a Connection, and the revisions are where schema changes belong (`api.data.sqlalchemy-and-alembic-only`), so the rule test doesn't read them. +2. **The rule's own check for unmapped tables** (`no-orm-form`, two + entries), in `tests/unit/data/orm_access_support.py`: it reads which + table each mapped class maps (`mapper.local_table`) and the tables a + declarative base's metadata holds (`class_registry.metadata.tables`). It + runs no statement. +3. **The tests' statements with no ORM form** (`no-orm-form`, six entries), + in `tests/fixtures/database_sessions.py`: SQLite's `PRAGMA foreign_keys` + on each new in-memory connection; `TRUNCATE ... CASCADE` for cleanup; and + `CREATE ROLE`, `DROP OWNED BY`, `DROP ROLE` and `GRANT` for the privilege + tests' temporary roles. A new exception is a rule change: add a `[[rule.exception]]` entry to the rule in `rules/registry.toml`, explain here why the ORM can't express the diff --git a/docs/generated/rules.md b/docs/generated/rules.md index 381493f41..9c4718945 100644 --- a/docs/generated/rules.md +++ b/docs/generated/rules.md @@ -72,6 +72,14 @@ Every rule that governs `policyengine-api` is listed here with how it is enforce ### Exceptions and review dates - `api.data.orm-only`: exception for `migrations/**/*.py` allowed as a migration-revision (migrations/ holds the Alembic environments and the revisions Alembic generates. The environments run Alembic's migration context on a Connection, and the revisions are where schema changes belong (api.data.sqlalchemy-and-alembic-only), so the rule test doesn't read them.) +- `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`sqlite_connection.execute(...)`) allowed as a no-orm-form (SQLite enforces foreign keys only once a connection sets PRAGMA foreign_keys, a connection setting SQLAlchemy has no API for. The in-memory SQLite test databases set it on each connection before its first transaction.) +- `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`text(f'CREATE ROLE {quoted_role} NOLOGIN')`) allowed as a no-orm-form (Roles have no ORM form. Privilege tests create a temporary role that can't log in.) +- `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`text(f'DROP OWNED BY {quoted_role}')`) allowed as a no-orm-form (Roles have no ORM form. Privilege tests drop what a temporary role owns and was granted, so the role can be dropped.) +- `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`text(f'DROP ROLE {quoted_role}')`) allowed as a no-orm-form (Roles have no ORM form. Privilege tests drop the temporary roles they create.) +- `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`text(f'GRANT {privileges} ON TABLE {table} TO {quoted_role}')`) allowed as a no-orm-form (Grants have no ORM form. Privilege tests grant a temporary role privileges the manifest doesn't declare, to check that verification reports them.) +- `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`text(f'TRUNCATE {tables} CASCADE')`) allowed as a no-orm-form (TRUNCATE has no ORM form. Test cleanup empties a table and every table that refers to it at once, as the catalog tests do after publishing.) +- `api.data.orm-only`: exception for `tests/unit/data/orm_access_support.py` (`class_registry.metadata.tables`) allowed as a no-orm-form (The rule's check for tables without a mapped class reads the tables a declarative base's metadata holds, to find those no class maps. It runs no statement.) +- `api.data.orm-only`: exception for `tests/unit/data/orm_access_support.py` (`mapper.local_table`) allowed as a no-orm-form (The rule's check for tables without a mapped class reads which table each mapped class maps. It runs no statement.) - `api.data.sqlalchemy-and-alembic-only`: exception for `migrations/*/versions/*.py` allowed as a migration-revision (Alembic generates the revisions, and they are where schema changes belong, so the check doesn't scan them. Ruff skips the same files (extend-exclude in pyproject.toml).) - `api.data.sqlalchemy-and-alembic-only`: exception for `policyengine_api/data/orm_pool_events.py` (`attribute ._sock`) allowed as a driver-access (The v1 pool's diagnostics read the file descriptor and local port of pymysql's socket from the driver connection a SQLAlchemy pool event passes them, because SQLAlchemy has no API for a connection's socket. They never read or write through the socket or the driver connection, and import no driver.) - `api.data.sqlalchemy-and-alembic-only`: exception for `policyengine_api/data/v2/catalog/publication_staging.py` (`attribute .driver_connection`) allowed as a driver-access (Catalog publication runs COPY through the psycopg connection beneath a SQLAlchemy Connection that SQLAlchemy opened and still manages, so the transaction stays SQLAlchemy's.) diff --git a/policyengine_api/data/orm.py b/policyengine_api/data/orm.py index fb3d00d94..e8ad345c1 100644 --- a/policyengine_api/data/orm.py +++ b/policyengine_api/data/orm.py @@ -4,17 +4,22 @@ import atexit import os +from contextlib import contextmanager from dataclasses import dataclass from typing import TYPE_CHECKING from dotenv import load_dotenv from google.cloud.sql.connector import Connector, IPTypes -from sqlalchemy import Engine, create_engine +from sqlalchemy import Engine, create_engine, inspect from sqlalchemy.orm import Session, sessionmaker +from sqlalchemy.pool import NullPool from policyengine_api.data.orm_pool_events import record_pool_events if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlalchemy.engine import URL, Inspector from sqlalchemy.engine.interfaces import DBAPIConnection load_dotenv() @@ -70,6 +75,31 @@ def build_session_factory(engine: Engine) -> sessionmaker[Session]: return sessionmaker(bind=engine, class_=Session, expire_on_commit=False) +@contextmanager +def unpooled_v1_sessions(url: str | URL) -> Iterator[sessionmaker[Session]]: + """Yield v1 Session factories for one command's work on the database at ``url``. + + For commands and scripts that run once, such as the household mirror + command and the v1 schema migration. Their engine keeps no connection + pool, so no connection outlives its Session, and is disposed of on exit. + """ + engine = create_engine(url, poolclass=NullPool) + try: + yield build_session_factory(engine) + finally: + engine.dispose() + + +def v1_schema_inspector(source: Session | sessionmaker[Session]) -> Inspector: + """Return SQLAlchemy's Inspector of the v1 database a Session or factory uses. + + A Session's Inspector reads the schema inside the Session's transaction. + """ + bind = source.connection() if isinstance(source, Session) else source.kw["bind"] + inspector: Inspector = inspect(bind) + return inspector + + def _build_remote_engine() -> Engine: config = get_remote_database_config() connector = Connector( diff --git a/policyengine_api/data/v2/database.py b/policyengine_api/data/v2/database.py index f72524f5c..3e3616bef 100644 --- a/policyengine_api/data/v2/database.py +++ b/policyengine_api/data/v2/database.py @@ -4,12 +4,14 @@ import atexit import os +from contextlib import contextmanager from dataclasses import dataclass from threading import Lock from typing import TYPE_CHECKING -from sqlalchemy import event +from sqlalchemy import event, inspect from sqlalchemy.orm import sessionmaker +from sqlalchemy.pool import NullPool from sqlmodel import Session, create_engine from policyengine_api.data.v2.settings import ( @@ -19,7 +21,10 @@ ) if TYPE_CHECKING: + from collections.abc import Iterator + from sqlalchemy import Engine + from sqlalchemy.engine import URL, Inspector DATABASE_POOL_RECYCLE_SECONDS = 1800 DATABASE_POOL_SIZE = 5 @@ -120,6 +125,51 @@ def build_v2_read_session_factory(engine: Engine) -> sessionmaker[Session]: return factory +@contextmanager +def unpooled_v2_sessions(url: str | URL) -> Iterator[sessionmaker[Session]]: + """Yield v2 Session factories for one command's work on the database at ``url``. + + For commands that run once, such as catalog initialization and privilege + reconciliation, given ``V2DatabaseSettings.connection.url`` or + ``V2AlembicSettings.url``. Their engine keeps no connection pool, so no + connection outlives its Session, and is disposed of on exit. + """ + engine = create_engine(url, poolclass=NullPool) + try: + yield build_v2_session_factory(engine) + finally: + engine.dispose() + + +@contextmanager +def unpooled_v2_read_only_sessions(url: str | URL) -> Iterator[sessionmaker[Session]]: + """Yield v2 Session factories whose transactions are all READ ONLY. + + For the migration qualification commands, which only read: PostgreSQL + refuses any write in their transactions (psycopg's read-only mode, set + through SQLAlchemy's ``postgresql_readonly`` option). Like + ``unpooled_v2_sessions``, the engine keeps no pool. + """ + engine = create_engine(url, poolclass=NullPool) + try: + yield build_v2_session_factory( + engine.execution_options(postgresql_readonly=True) + ) + finally: + engine.dispose() + + +def v2_schema_inspector(source: Session | sessionmaker[Session]) -> Inspector: + """Return SQLAlchemy's Inspector of the v2 database a Session or factory uses. + + A Session's Inspector reads the schema inside the Session's transaction, + as the migration target checks need. + """ + bind = source.connection() if isinstance(source, Session) else source.kw["bind"] + inspector: Inspector = inspect(bind) + return inspector + + def _discard_inherited_state(current_pid: int) -> None: """Drop pool state inherited through a process fork without touching parent FDs.""" if _engine_state.engine is not None: diff --git a/rules/registry.toml b/rules/registry.toml index eb32de3cf..0a549d6ed 100644 --- a/rules/registry.toml +++ b/rules/registry.toml @@ -652,6 +652,54 @@ path = "migrations/**/*.py" category = "migration-revision" reason = "migrations/ holds the Alembic environments and the revisions Alembic generates. The environments run Alembic's migration context on a Connection, and the revisions are where schema changes belong (api.data.sqlalchemy-and-alembic-only), so the rule test doesn't read them." +[[rule.exception]] +path = "tests/unit/data/orm_access_support.py" +match = "mapper.local_table" +category = "no-orm-form" +reason = "The rule's check for tables without a mapped class reads which table each mapped class maps. It runs no statement." + +[[rule.exception]] +path = "tests/unit/data/orm_access_support.py" +match = "class_registry.metadata.tables" +category = "no-orm-form" +reason = "The rule's check for tables without a mapped class reads the tables a declarative base's metadata holds, to find those no class maps. It runs no statement." + +[[rule.exception]] +path = "tests/fixtures/database_sessions.py" +match = "sqlite_connection.execute(...)" +category = "no-orm-form" +reason = "SQLite enforces foreign keys only once a connection sets PRAGMA foreign_keys, a connection setting SQLAlchemy has no API for. The in-memory SQLite test databases set it on each connection before its first transaction." + +[[rule.exception]] +path = "tests/fixtures/database_sessions.py" +match = "text(f'TRUNCATE {tables} CASCADE')" +category = "no-orm-form" +reason = "TRUNCATE has no ORM form. Test cleanup empties a table and every table that refers to it at once, as the catalog tests do after publishing." + +[[rule.exception]] +path = "tests/fixtures/database_sessions.py" +match = "text(f'CREATE ROLE {quoted_role} NOLOGIN')" +category = "no-orm-form" +reason = "Roles have no ORM form. Privilege tests create a temporary role that can't log in." + +[[rule.exception]] +path = "tests/fixtures/database_sessions.py" +match = "text(f'DROP OWNED BY {quoted_role}')" +category = "no-orm-form" +reason = "Roles have no ORM form. Privilege tests drop what a temporary role owns and was granted, so the role can be dropped." + +[[rule.exception]] +path = "tests/fixtures/database_sessions.py" +match = "text(f'DROP ROLE {quoted_role}')" +category = "no-orm-form" +reason = "Roles have no ORM form. Privilege tests drop the temporary roles they create." + +[[rule.exception]] +path = "tests/fixtures/database_sessions.py" +match = "text(f'GRANT {privileges} ON TABLE {table} TO {quoted_role}')" +category = "no-orm-form" +reason = "Grants have no ORM form. Privilege tests grant a temporary role privileges the manifest doesn't declare, to check that verification reports them." + [[rule]] id = "api.legacy.removed-layers-stay-removed" category = "runtime-layers" diff --git a/tests/fixtures/database_sessions.py b/tests/fixtures/database_sessions.py new file mode 100644 index 000000000..d4253c2b3 --- /dev/null +++ b/tests/fixtures/database_sessions.py @@ -0,0 +1,335 @@ +"""The tests' Session factories, and the few statements the ORM has no form for. + +This is the tests' one session-factory module (rule api.data.orm-only, in +``SESSION_FACTORY_MODULES`` of ``tests/unit/data/orm_access_support.py``): the +only test module that creates engines, opens connections or listens for their +events. Tests take Session factories from it and run every statement through a +Session on mapped classes. docs/engineering/skills/alembic-migrations.md shows +how to write each kind of statement, under "Database statements through the +ORM". + +The statements here that the ORM can't express (``TRUNCATE``, ``CREATE ROLE``, +``DROP OWNED BY``, ``DROP ROLE``, ``GRANT`` and SQLite's ``foreign_keys`` +setting) are each a ``no-orm-form`` exception of the rule in +rules/registry.toml. Roles and settings inside a transaction need none: +``act_as`` and ``act_as_owner`` call Postgres's ``set_config``, which is what +``SET LOCAL ROLE`` does. +""" + +from __future__ import annotations + +import re +import sqlite3 +import sys +from contextlib import contextmanager +from typing import TYPE_CHECKING, Any + +from sqlalchemy import ( + JSON, + Integer, + String, + create_engine, + delete, + event, + func, + inspect, + select, + text, + true, +) +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, sessionmaker +from sqlalchemy.orm import Session as OrmSession +from sqlalchemy.pool import NullPool, StaticPool + +from policyengine_api.data.orm import build_session_factory +from policyengine_api.data.v1_models import Policy, V1Base +from policyengine_api.data.v2.database import build_v2_session_factory +from policyengine_api.data.v2.models import V2_METADATA +from policyengine_api.data.v2.privilege_reconciliation import ( + apply_declared_privileges, + create_missing_roles, +) + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator, Mapping + + import pytest + from sqlalchemy.engine import Inspector + from sqlalchemy.orm import registry + from sqlmodel import Session + + from policyengine_api.data.v2.privilege_plans import ReconciliationPlan + from policyengine_api.data.v2.privileges import DeclaredPrivilege + +# A role name SET ROLE and a connection's startup options take as it is. +PLAIN_ROLE_NAME = re.compile(r"[a-z_][a-z0-9_]*") +# The role that means "no role": the session acts as the user it logged in as. +NO_ROLE = "none" +IN_MEMORY_SQLITE_URL = "sqlite://" + + +def _plain_role_name(role: str) -> str: + if not PLAIN_ROLE_NAME.fullmatch(role): + msg = f"role names here are lowercase letters, digits and _: {role!r}" + raise ValueError(msg) + return role + + +@contextmanager +def v2_owner_sessions(database_url: str) -> Iterator[sessionmaker[Session]]: + """Yield Session factories of the disposable v2 PostgreSQL database's owner. + + The owner is the database's superuser, which owns every table. The + engine keeps no connection pool and is disposed of on exit. + """ + engine = create_engine(database_url, poolclass=NullPool) + try: + yield build_v2_session_factory(engine) + finally: + engine.dispose() + + +@contextmanager +def v2_role_sessions(database_url: str, role: str) -> Iterator[sessionmaker[Session]]: + """Yield Session factories whose every connection acts as ``role``. + + Each connection starts with ``role`` as its role (PostgreSQL's ``role`` + startup option), so every statement is checked against that role's + privileges, as in staging and production. ``act_as_owner`` would still + switch a transaction to the database's owner, so a test acting as a role + uses these factories, or ``act_as`` on the owner's. + """ + engine = create_engine( + database_url, + poolclass=NullPool, + connect_args={"options": f"-c role={_plain_role_name(role)}"}, + ) + try: + yield build_v2_session_factory(engine) + finally: + engine.dispose() + + +@contextmanager +def v1_sessions(database_url: str) -> Iterator[sessionmaker[OrmSession]]: + """Yield API v1's Session factories for the disposable MySQL database.""" + engine = create_engine(database_url, poolclass=NullPool) + try: + yield build_session_factory(engine) + finally: + engine.dispose() + + +def _connect_to_sqlite(*, foreign_keys: bool) -> Callable[[], sqlite3.Connection]: + """Return a connector to in-memory SQLite that keeps SQLAlchemy's transactions. + + sqlite3's ``autocommit=False`` mode (Python 3.12 and later) opens every + transaction itself, so savepoints behave as they do on PostgreSQL. SQLite + ignores ``foreign_keys`` inside a transaction, so it is set before the + connection starts its first one. + """ + if sys.version_info < (3, 12): + msg = "SQLite test databases need Python 3.12's sqlite3 autocommit mode" + raise RuntimeError(msg) + + def connect() -> sqlite3.Connection: + sqlite_connection = sqlite3.connect( + ":memory:", check_same_thread=False, autocommit=True + ) + if foreign_keys: + sqlite_connection.execute("PRAGMA foreign_keys = ON") + sqlite_connection.autocommit = False + return sqlite_connection + + return connect + + +@contextmanager +def sqlite_v2_sessions( + *, foreign_keys: bool = False +) -> Iterator[sessionmaker[Session]]: + """Yield Session factories of a new in-memory SQLite copy of the v2 schema. + + Every Session shares the one connection. With ``foreign_keys``, SQLite + enforces the schema's foreign keys, which it otherwise ignores. + """ + engine = create_engine( + IN_MEMORY_SQLITE_URL, + creator=_connect_to_sqlite(foreign_keys=foreign_keys), + poolclass=StaticPool, + ) + V2_METADATA.create_all(engine) + try: + yield build_v2_session_factory(engine) + finally: + engine.dispose() + + +class _SqliteV1PolicyBase(DeclarativeBase): + """The declarative base of the SQLite copy of API v1's policy table.""" + + +class _SqliteV1Policy(_SqliteV1PolicyBase): + """API v1's policy table as SQLite can number it. + + API v1's key is (id, country_id, policy_hash), with id numbered by MySQL. + SQLite numbers only a table's lone integer key, so this copy's key is + ``id`` alone. Code still writes and reads it through API v1's ``Policy``. + """ + + __tablename__ = Policy.__tablename__ + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + country_id: Mapped[str] = mapped_column(String(3)) + label: Mapped[str | None] = mapped_column(String(255)) + api_version: Mapped[str] = mapped_column(String(10)) + policy_json: Mapped[Any] = mapped_column(JSON, nullable=False) + policy_hash: Mapped[str] = mapped_column(String(255)) + + +@contextmanager +def sqlite_v1_sessions( + *, json_serializer: Callable[[Any], str] | None = None +) -> Iterator[sessionmaker[OrmSession]]: + """Yield API v1's Session factories of a new in-memory SQLite copy of its schema. + + ``json_serializer`` replaces the engine's JSON serializer when given. + """ + engine_options = ( + {} if json_serializer is None else {"json_serializer": json_serializer} + ) + engine = create_engine( + IN_MEMORY_SQLITE_URL, + connect_args={"check_same_thread": False}, + poolclass=StaticPool, + **engine_options, + ) + # The policy copy first: the v1 schema then skips the table that exists. + _SqliteV1PolicyBase.metadata.create_all(engine) + V1Base.metadata.create_all(engine) + try: + yield build_session_factory(engine) + finally: + engine.dispose() + + +def serve_v1_sessions( + monkeypatch: pytest.MonkeyPatch, sessions: sessionmaker[OrmSession] +) -> None: + """Make API v1's own Session factory open ``sessions``' connections. + + ``policyengine_api.data.orm.get_v1_session_factory`` then builds its + factory on ``sessions``' engine; ``monkeypatch`` undoes it after the test. + """ + from policyengine_api.data import orm + + engine = sessions.kw["bind"] + monkeypatch.setattr(orm, "get_v1_engine", lambda: engine) + orm.clear_v1_session_factories() + + +def _set_transaction_role(session: OrmSession, role: str) -> None: + # set_config's third argument, true, keeps the setting to the transaction, + # as SET LOCAL does. + session.execute(select(func.set_config("role", role, true()))) + + +def act_as(session: OrmSession, role: str) -> None: + """Act as ``role`` for the rest of the session's transaction (SET LOCAL ROLE).""" + _set_transaction_role(session, _plain_role_name(role)) + + +def act_as_owner(session: OrmSession) -> None: + """Act as the database's owner again, for the rest of the transaction.""" + _set_transaction_role(session, NO_ROLE) + + +def schema_inspector(source: OrmSession | sessionmaker[Any]) -> Inspector: + """Return SQLAlchemy's Inspector of the database a Session or factory uses. + + A Session's Inspector reads the schema inside its transaction. Anything + else, such as the Engine a test not yet moved to Sessions holds, is + inspected as it is. + """ + bind: Any = source + if isinstance(source, OrmSession): + bind = source.connection() + elif isinstance(source, sessionmaker): + bind = source.kw["bind"] + inspector: Inspector = inspect(bind) + return inspector + + +@contextmanager +def recorded_statements( + source: OrmSession | sessionmaker[Any], +) -> Iterator[list[str]]: + """Yield a list of the SQL statements sent through ``source`` while inside.""" + engine = source.get_bind() if isinstance(source, OrmSession) else source.kw["bind"] + statements: list[str] = [] + + def record( + _connection: object, _cursor: object, statement: str, *_arguments: object + ) -> None: + statements.append(statement) + + event.listen(engine, "before_cursor_execute", record) + try: + yield statements + finally: + event.remove(engine, "before_cursor_execute", record) + + +def delete_all_rows(session: OrmSession, mapped_classes: registry) -> None: + """Delete every row of every table the registry's mapped classes map.""" + for mapper in mapped_classes.mappers: + session.execute(delete(mapper.class_)) + + +def _quoted(session: OrmSession, name: str) -> str: + return session.get_bind().dialect.identifier_preparer.quote_identifier(name) + + +def truncate(session: OrmSession, *models: type[Any]) -> None: + """Empty the models' tables and every table referring to them (TRUNCATE CASCADE).""" + tables = ", ".join(_quoted(session, model.__tablename__) for model in models) + session.execute(text(f"TRUNCATE {tables} CASCADE")) + + +def create_role(session: OrmSession, role: str) -> None: + """Create ``role``, which can't log in (CREATE ROLE ... NOLOGIN).""" + quoted_role = _quoted(session, role) + session.execute(text(f"CREATE ROLE {quoted_role} NOLOGIN")) + + +def drop_role(session: OrmSession, role: str) -> None: + """Drop ``role`` and everything it owns or was granted.""" + quoted_role = _quoted(session, role) + session.execute(text(f"DROP OWNED BY {quoted_role}")) + session.execute(text(f"DROP ROLE {quoted_role}")) + + +def grant(session: OrmSession, privileges: str, *, on: type[Any], to: str) -> None: + """Grant ``privileges`` on a model's table to a role, as in ``GRANT ... ON TABLE``. + + ``privileges`` is GRANT's privilege list, such as ``"SELECT, INSERT"`` or + ``"UPDATE (label, code)"``. + """ + table = f"public.{_quoted(session, on.__tablename__)}" + quoted_role = _quoted(session, to) + session.execute(text(f"GRANT {privileges} ON TABLE {table} TO {quoted_role}")) + + +def grant_declared_v2_privileges( + database_url: str, + declared: Mapping[str, Mapping[str, frozenset[DeclaredPrivilege]]], +) -> ReconciliationPlan: + """Create the declared roles that are missing and grant their privileges. + + It does what ``reconcile_v2_privileges.py apply --create-missing-roles`` + does, in one transaction as the database's owner, and returns the plan. + """ + with v2_owner_sessions(database_url) as sessions, sessions.begin() as session: + connection = session.connection() + create_missing_roles(connection, declared) + plan, _default_privileges = apply_declared_privileges(connection, declared) + return plan diff --git a/tests/fixtures/integration/alembic_v2.py b/tests/fixtures/integration/alembic_v2.py index ce72f8f86..9054f306e 100644 --- a/tests/fixtures/integration/alembic_v2.py +++ b/tests/fixtures/integration/alembic_v2.py @@ -1,10 +1,11 @@ """The disposable Postgres target and Alembic config of the v2 lifecycle tests.""" import os +from typing import Any import pytest from alembic.config import Config -from sqlalchemy import inspect +from sqlalchemy.engine.interfaces import ReflectedColumn from policyengine_api.constants import REPO from policyengine_api.data.v2.migration_target import ( @@ -12,6 +13,7 @@ load_v2_alembic_settings, ) from policyengine_api.data.v2.settings import V2_MIGRATION_DATABASE_URL +from tests.fixtures.database_sessions import schema_inspector def disposable_v2_url() -> str: @@ -33,8 +35,12 @@ def alembic_v2_config() -> Config: return Config(str(REPO / "alembic-v2.ini")) -def table_columns(engine, table_name: str) -> dict[str, dict]: +def table_columns(source: Any, table_name: str) -> dict[str, ReflectedColumn]: + """Return a public table's columns by name, as the database describes them. + + ``source`` is a Session or a Session factory (see ``schema_inspector``). + """ return { column["name"]: column - for column in inspect(engine).get_columns(table_name, schema="public") + for column in schema_inspector(source).get_columns(table_name, schema="public") } diff --git a/tests/fixtures/v2_metadata_service.py b/tests/fixtures/v2_metadata_service.py index a7a69798d..f8cb46c21 100644 --- a/tests/fixtures/v2_metadata_service.py +++ b/tests/fixtures/v2_metadata_service.py @@ -2,31 +2,26 @@ from __future__ import annotations +from typing import TYPE_CHECKING + import pytest -from sqlalchemy.pool import StaticPool -from sqlmodel import Session, create_engine -from policyengine_api.data.v2.models import V2_METADATA +from tests.fixtures.database_sessions import sqlite_v2_sessions from tests.fixtures.v2_catalog import normalized_catalog from tests.fixtures.v2_metadata_service_helpers import insert_country +if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlmodel import Session + @pytest.fixture -def catalog_session() -> Session: - engine = create_engine( - "sqlite://", - connect_args={"check_same_thread": False}, - poolclass=StaticPool, - ) - V2_METADATA.create_all(engine) - with Session(engine) as session: - for country in normalized_catalog().countries: - insert_country(session, country, include_model=True) - session.commit() - - session = Session(engine) - try: - yield session - finally: - session.close() - engine.dispose() +def catalog_session() -> Iterator[Session]: + with sqlite_v2_sessions() as sessions: + with sessions.begin() as session: + for country in normalized_catalog().countries: + insert_country(session, country, include_model=True) + + with sessions() as session: + yield session diff --git a/tests/fixtures/v2_metadata_service_helpers.py b/tests/fixtures/v2_metadata_service_helpers.py index f847d3017..e4a67015a 100644 --- a/tests/fixtures/v2_metadata_service_helpers.py +++ b/tests/fixtures/v2_metadata_service_helpers.py @@ -2,9 +2,8 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, TypeVar -from sqlalchemy import event from sqlmodel import Session, select from policyengine_api.data.v2.models import ( @@ -22,14 +21,21 @@ MetadataDatabaseSession, ) from policyengine_api.services.v2.metadata.services import V2MetadataService +from tests.fixtures import database_sessions from tests.fixtures.v2_catalog import POLICYENGINE_VERSION, normalized_catalog if TYPE_CHECKING: + from collections.abc import Callable + from policyengine_api.services.v2.metadata.process_state import ( SelectedCatalogStore, ) +# What a recorded read returns. +ReadResult = TypeVar("ReadResult") + + def insert_country( session: Session, country, @@ -213,16 +219,10 @@ def catalog_service( ) -def recorded_statements(session: Session, read): - statements: list[str] = [] - - def record_statement(_connection, _cursor, statement, *_args) -> None: - statements.append(statement.lower()) - - bind = session.get_bind() - event.listen(bind, "before_cursor_execute", record_statement) - try: +def recorded_statements( + session: Session, read: Callable[[], ReadResult] +) -> tuple[ReadResult, list[str]]: + """Return what ``read()`` returns and the SQL it sent, in lowercase.""" + with database_sessions.recorded_statements(session) as statements: result = read() - finally: - event.remove(bind, "before_cursor_execute", record_statement) - return result, statements + return result, [statement.lower() for statement in statements] diff --git a/tests/integration/catalog_rows.py b/tests/integration/catalog_rows.py index f44ab0865..084b8788a 100644 --- a/tests/integration/catalog_rows.py +++ b/tests/integration/catalog_rows.py @@ -7,15 +7,33 @@ from __future__ import annotations import json -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any -from sqlalchemy import text +from sqlalchemy import select +from sqlmodel import col + +from policyengine_api.data.v2.models import ( + Parameter, + ParameterNode, + ParameterValue, + Region, + TaxBenefitModel, + TaxBenefitModelVersion, + Variable, +) if TYPE_CHECKING: - from sqlalchemy.engine import Engine + from sqlalchemy.orm import Session, sessionmaker from policyengine_api.data.v2.catalog.records import NormalizedCatalog +# The mapped class of each catalog table, by the table's name. +CATALOG_MODELS: dict[str, Any] = { + "variables": Variable, + "parameter_nodes": ParameterNode, + "parameters": Parameter, + "regions": Region, +} # The columns each catalog table stores, named as on the catalog's records: # each table's key column first. Each country catalog names its records after # the table that stores them. @@ -54,20 +72,22 @@ def strict_json(value: object) -> str: return json.dumps(value, sort_keys=True, default=str) -def stored_catalog_rows(engine: Engine, table_name: str) -> dict[tuple, str]: +def stored_catalog_rows( + sessions: sessionmaker[Session], table_name: str +) -> dict[tuple, str]: """Return each row of a catalog table, keyed by model and name or code.""" - key_column, *columns = CATALOG_COLUMNS[table_name] - selected = ", ".join(f"catalog_row.{column}" for column in (key_column, *columns)) - with engine.connect() as connection: - rows = connection.execute( - text( - f""" - SELECT model.name, {selected} - FROM {table_name} AS catalog_row - JOIN tax_benefit_model_versions AS version - ON version.id = catalog_row.tax_benefit_model_version_id - JOIN tax_benefit_models AS model ON model.id = version.model_id - """ + model = CATALOG_MODELS[table_name] + selected = [getattr(model, column) for column in CATALOG_COLUMNS[table_name]] + with sessions.begin() as session: + rows = session.execute( + select(col(TaxBenefitModel.name), *selected) + .join( + TaxBenefitModelVersion, + col(TaxBenefitModelVersion.id) == model.tax_benefit_model_version_id, + ) + .join( + TaxBenefitModel, + col(TaxBenefitModel.id) == TaxBenefitModelVersion.model_id, ) ).all() return {(row[0], row[1]): strict_json(row[2:]) for row in rows} @@ -85,21 +105,26 @@ def catalog_rows(catalog: NormalizedCatalog, table_name: str) -> dict[tuple, str } -def stored_parameter_values(engine: Engine) -> dict[tuple, tuple]: +def stored_parameter_values(sessions: sessionmaker[Session]) -> dict[tuple, tuple]: """Return each parameter value's JSON and end date, by model, name and start.""" - with engine.connect() as connection: - rows = connection.execute( - text( - """ - SELECT model.name, parameter.name, parameter_value.start_date, - parameter_value.value_json, parameter_value.end_date - FROM parameter_values AS parameter_value - JOIN parameters AS parameter - ON parameter.id = parameter_value.parameter_id - JOIN tax_benefit_model_versions AS version - ON version.id = parameter.tax_benefit_model_version_id - JOIN tax_benefit_models AS model ON model.id = version.model_id - """ + with sessions.begin() as session: + rows = session.execute( + select( + col(TaxBenefitModel.name), + col(Parameter.name), + col(ParameterValue.start_date), + col(ParameterValue.value_json), + col(ParameterValue.end_date), + ) + .join(Parameter, col(Parameter.id) == ParameterValue.parameter_id) + .join( + TaxBenefitModelVersion, + col(TaxBenefitModelVersion.id) + == Parameter.tax_benefit_model_version_id, + ) + .join( + TaxBenefitModel, + col(TaxBenefitModel.id) == TaxBenefitModelVersion.model_id, ) ).all() return { @@ -121,10 +146,12 @@ def catalog_parameter_values(catalog: NormalizedCatalog) -> dict[tuple, tuple]: } -def assert_catalog_stored_unchanged(engine: Engine, catalog: NormalizedCatalog) -> None: +def assert_catalog_stored_unchanged( + sessions: sessionmaker[Session], catalog: NormalizedCatalog +) -> None: """Assert that the database holds exactly ``catalog``'s values and records.""" - assert stored_parameter_values(engine) == catalog_parameter_values(catalog) + assert stored_parameter_values(sessions) == catalog_parameter_values(catalog) for table_name in CATALOG_COLUMNS: - assert stored_catalog_rows(engine, table_name) == catalog_rows( + assert stored_catalog_rows(sessions, table_name) == catalog_rows( catalog, table_name ), table_name diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 9444a5af1..cfe9e9426 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -1,7 +1,11 @@ +from __future__ import annotations + import os import time import uuid +from contextlib import ExitStack from dataclasses import dataclass +from typing import TYPE_CHECKING import httpx import pytest @@ -11,6 +15,16 @@ deployed_api_client, ) +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + + from sqlalchemy.orm import Session as OrmSession + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + +# The database fixtures import the tests' session factories when they run, so +# the tests of deployed services load no database code. + INTEGRATION_TIMEOUT_SECONDS = float( os.environ.get("STAGING_API_TEST_TIMEOUT_SECONDS", "900") ) @@ -86,13 +100,6 @@ def managed_v2_roles(disposable_v2_database_url: str) -> ManagedV2Roles: ``reconcile_v2_privileges.py apply --create-missing-roles``. Repeating it here grants nothing more there, and lets the tests run locally on their own. """ - from sqlalchemy import create_engine - from sqlalchemy.pool import NullPool - - from policyengine_api.data.v2.privilege_reconciliation import ( - apply_declared_privileges, - create_missing_roles, - ) from policyengine_api.data.v2.privileges import ( MODAL_WORKER_ROLE, RUNTIME_ROLE, @@ -100,18 +107,14 @@ def managed_v2_roles(disposable_v2_database_url: str) -> ManagedV2Roles: declared_privileges, stage12_role, ) + from tests.fixtures import database_sessions deployment_environment = ( os.environ.get("DEPLOYMENT_ENVIRONMENT", "").strip() or "test" ) - declared = declared_privileges(deployment_environment) - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - try: - with engine.begin() as connection: - create_missing_roles(connection, declared) - plan, _default_privileges = apply_declared_privileges(connection, declared) - finally: - engine.dispose() + plan = database_sessions.grant_declared_v2_privileges( + disposable_v2_database_url, declared_privileges(deployment_environment) + ) if not plan.can_apply: pytest.fail( "the disposable v2 database lacks declared roles or tables: " @@ -126,13 +129,58 @@ def managed_v2_roles(disposable_v2_database_url: str) -> ManagedV2Roles: ) +@pytest.fixture(scope="session") +def v2_owner_sessions( + disposable_v2_database_url: str, +) -> Iterator[sessionmaker[Session]]: + """Return Session factories of the disposable v2 database's owner (superuser).""" + from tests.fixtures import database_sessions + + with database_sessions.v2_owner_sessions(disposable_v2_database_url) as sessions: + yield sessions + + +@pytest.fixture(scope="session") +def v2_sessions_as_role( + disposable_v2_database_url: str, managed_v2_roles: ManagedV2Roles +) -> Iterator[Callable[[str], sessionmaker[Session]]]: + """Return a builder of Session factories whose connections act as one role. + + Every statement is checked against that role's privileges, as in staging + and production, instead of the disposable database's owner's. The managed + roles exist and hold their declared privileges; a test may name a role it + created. The factories' engines are disposed of after the test session. + """ + from tests.fixtures import database_sessions + + with ExitStack() as factories: + + def build(role: str) -> sessionmaker[Session]: + return factories.enter_context( + database_sessions.v2_role_sessions(disposable_v2_database_url, role) + ) + + yield build + + +@pytest.fixture(scope="session") +def v1_sessions(disposable_v1_database_url: str) -> Iterator[sessionmaker[OrmSession]]: + """Return API v1's Session factories of the disposable MySQL database.""" + from tests.fixtures import database_sessions + + with database_sessions.v1_sessions(disposable_v1_database_url) as sessions: + yield sessions + + @pytest.fixture(scope="session") def v2_engine_as_role(disposable_v2_database_url: str, managed_v2_roles): """Return a builder of engines whose connections act as one managed role. Each new connection runs ``SET ROLE`` and commits it, so every statement on it is checked against that role's privileges, as in staging and production, - instead of the disposable database's superuser. + instead of the disposable database's superuser. Only for the tests that + still build engines, which rule api.data.orm-only reports: use + ``v2_sessions_as_role``. """ from psycopg import sql from sqlalchemy import create_engine, event diff --git a/tests/integration/simulation_rows.py b/tests/integration/simulation_rows.py index 214914f8e..57790a8a1 100644 --- a/tests/integration/simulation_rows.py +++ b/tests/integration/simulation_rows.py @@ -1,24 +1,35 @@ -"""Write simulation-side v2 rows with plain SQL in the integration tests. +"""Write simulation-side v2 rows through a Session in the integration tests. -The statements run as whichever role the connection acts as, so a test can +The statements run as whichever role the Session acts as, so a test can check what that role may do. Tests write inside a transaction they roll back. +``add_row`` writes one row of a mapped class, and ``refused`` expects the +statements inside it to fail. """ from __future__ import annotations from contextlib import contextmanager from dataclasses import dataclass -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any from uuid import UUID, uuid4 import pytest -from sqlalchemy import text +from sqlalchemy import delete, insert, text from sqlalchemy.exc import IntegrityError +from sqlmodel import col + +from policyengine_api.data.v2.models import ( + Dataset, + Household, + TaxBenefitModel, + TaxBenefitModelVersion, +) if TYPE_CHECKING: from collections.abc import Iterator from sqlalchemy import Connection + from sqlalchemy.orm import Session # The package versions a test run records. RUN_VERSIONS = {"country_package_version": "1.0.0", "policyengine_version": "4.0.0"} @@ -26,7 +37,7 @@ @dataclass(frozen=True) class PublicApiRows: - """The Public API's rows a simulation, report or household job names.""" + """API v1's rows a simulation, report or household job names.""" model_id: UUID version_id: UUID @@ -34,46 +45,54 @@ class PublicApiRows: household_id: UUID -def insert_public_api_rows(connection: Connection) -> PublicApiRows: +def add_row(session: Session, model: type[Any], **values: object) -> None: + """Insert one row of the mapped class ``model`` with the given columns. + + Columns not given take the model's defaults, then the database's. + """ + session.execute(insert(model).values(**values)) + + +def insert_public_api_rows(session: Session) -> PublicApiRows: """Store a model, one of its versions, a dataset and a US household. The simulation tables' foreign keys need them. Run it as the disposable - database's superuser: the simulation API's roles can't write these tables. + database's owner: the simulation API's roles can't write these tables. """ rows = PublicApiRows( model_id=uuid4(), version_id=uuid4(), dataset_id=uuid4(), household_id=uuid4() ) # Model names are unique and at most 32 characters. - insert_row( - connection, - "tax_benefit_models", + add_row( + session, + TaxBenefitModel, id=rows.model_id, name=f"runs-{rows.model_id.hex[:24]}", ) - insert_row( - connection, - "tax_benefit_model_versions", + add_row( + session, + TaxBenefitModelVersion, id=rows.version_id, model_id=rows.model_id, version="1.0.0", current_law_id=1, - metadata_time_periods="[2026]", + metadata_time_periods=[2026], ) - insert_row( - connection, - "datasets", + add_row( + session, + Dataset, id=rows.dataset_id, name="populace", year=2026, is_output_dataset=False, tax_benefit_model_version_id=rows.version_id, ) - insert_row( - connection, - "households", + add_row( + session, + Household, id=rows.household_id, country_id="us", - household_data="{}", + household_data={}, canonicalization_version=1, content_hash=uuid4().hex * 2, ) @@ -81,7 +100,11 @@ def insert_public_api_rows(connection: Connection) -> PublicApiRows: def insert_row(connection: Connection, table: str, **values: object) -> None: - """Insert one row of the named columns into ``table``.""" + """Insert one row of the named columns into ``table``, as handwritten SQL. + + Only for the callers that still pass a Connection and a table's name; + rule api.data.orm-only reports it. Use ``add_row``. + """ columns = ", ".join(values) placeholders = ", ".join(f":{column}" for column in values) connection.execute( @@ -91,24 +114,29 @@ def insert_row(connection: Connection, table: str, **values: object) -> None: @contextmanager def refused( - connection: Connection, + session: Session, error: type[Exception] = IntegrityError, *, match: str | None = None, ) -> Iterator[None]: - """Expect the statements inside to fail with ``error``, then roll them back.""" - savepoint = connection.begin_nested() - with pytest.raises(error, match=match): + """Expect the statements inside to fail with ``error``, then roll them back. + + They run in a savepoint (``Session.begin_nested``), so the test's + transaction goes on. + """ + with pytest.raises(error, match=match), session.begin_nested(): yield - savepoint.rollback() -def delete_public_api_rows(connection: Connection, rows: PublicApiRows) -> None: +def delete_public_api_rows(session: Session, rows: PublicApiRows) -> None: """Delete what ``insert_public_api_rows`` stored, once nothing names it.""" - for table, row_id in ( - ("households", rows.household_id), - ("datasets", rows.dataset_id), - ("tax_benefit_model_versions", rows.version_id), - ("tax_benefit_models", rows.model_id), - ): - connection.execute(text(f"DELETE FROM {table} WHERE id = :id"), {"id": row_id}) + session.execute(delete(Household).where(col(Household.id) == rows.household_id)) + session.execute(delete(Dataset).where(col(Dataset.id) == rows.dataset_id)) + session.execute( + delete(TaxBenefitModelVersion).where( + col(TaxBenefitModelVersion.id) == rows.version_id + ) + ) + session.execute( + delete(TaxBenefitModel).where(col(TaxBenefitModel.id) == rows.model_id) + ) diff --git a/tests/integration/stored_report_rows.py b/tests/integration/stored_report_rows.py index 9c5c16f9a..4c64ccd7a 100644 --- a/tests/integration/stored_report_rows.py +++ b/tests/integration/stored_report_rows.py @@ -1,10 +1,10 @@ """Store reports, simulations and their runs' results for the read integration tests. The simulation service and its Modal workers write these tables in staging -and production; here the disposable database's owner writes them, commits -them so the Public API's runtime role can read them, and deletes them again. -Results are stored through the port of the simulation service's writer in -``tests.fixtures.economy_results``. +and production; here the disposable database's owner writes them through a +Session on the mapped classes, commits them so API v1's runtime role can read +them, and deletes them again. Results are stored through the port of the +simulation service's writer in ``tests.fixtures.economy_results``. """ from __future__ import annotations @@ -15,17 +15,42 @@ from typing import TYPE_CHECKING, Any from uuid import UUID, uuid4 -from sqlalchemy import text -from sqlalchemy.dialects.postgresql import JSONB -from sqlalchemy.sql import bindparam - +from sqlalchemy import delete, select, update +from sqlmodel import col + +from policyengine_api.data.v2.models import ( + BudgetSummary, + BudgetWindowRun, + CongressionalDistrictImpact, + ConstituencyImpact, + Country, + Dataset, + DecileImpact, + Household, + Inequality, + IntraDecileImpact, + LaborSupplyDecileResponse, + LaborSupplyResponse, + LocalAuthorityImpact, + Policy, + Poverty, + ProgramStatistics, + Region, + Report, + ReportRun, + Simulation, + SimulationRun, + TaxBenefitModel, + TaxBenefitModelVersion, + WithheldAreaCode, +) from tests.fixtures.economy_results import RunIds, economy_result_rows -from tests.integration.simulation_rows import insert_row +from tests.integration.simulation_rows import add_row if TYPE_CHECKING: from collections.abc import Iterator - from sqlalchemy import Connection, Engine + from sqlalchemy.orm import Session, sessionmaker REGION_CODES = {"us": "state/ca", "uk": "country/wales"} DATASET_NAMES = {"us": "enhanced_cps_2024", "uk": "enhanced_frs_2023_24"} @@ -34,6 +59,25 @@ STARTED_AT = datetime(2026, 11, 1, 9, tzinfo=UTC) # The year of a report store_report stores, unless it is given another. STORED_REPORT_YEAR = 2026 +# The mapped class of each table the simulation service's writer stores +# result rows in, by the table's name in ``economy_result_rows``. +RESULT_MODELS: dict[str, type[Any]] = { + model.__tablename__: model + for model in ( + LaborSupplyResponse, + LaborSupplyDecileResponse, + BudgetSummary, + DecileImpact, + IntraDecileImpact, + Poverty, + Inequality, + ProgramStatistics, + CongressionalDistrictImpact, + ConstituencyImpact, + LocalAuthorityImpact, + WithheldAreaCode, + ) +} @dataclass @@ -60,17 +104,16 @@ class CatalogRows: area_dataset_ids: list[UUID] = field(default_factory=list) -def store_catalog(connection: Connection, country: str) -> CatalogRows: +def store_catalog(session: Session, country: str) -> CatalogRows: """Store a catalog version, dataset, region and policy of the country's model.""" model_name = f"policyengine-{country}" - model_id = connection.execute( - text("SELECT id FROM tax_benefit_models WHERE name = :name"), - {"name": model_name}, + model_id = session.execute( + select(col(TaxBenefitModel.id)).where(col(TaxBenefitModel.name) == model_name) ).scalar_one_or_none() created_model = model_id is None if model_id is None: model_id = uuid4() - insert_row(connection, "tax_benefit_models", id=model_id, name=model_name) + add_row(session, TaxBenefitModel, id=model_id, name=model_name) rows = CatalogRows( country=country, model_id=model_id, @@ -80,27 +123,27 @@ def store_catalog(connection: Connection, country: str) -> CatalogRows: policy_id=uuid4(), created_model=created_model, ) - insert_row( - connection, - "tax_benefit_model_versions", + add_row( + session, + TaxBenefitModelVersion, id=rows.version_id, model_id=model_id, version=f"reads-{rows.version_id.hex[:12]}", current_law_id=1, - metadata_time_periods="[2026]", + metadata_time_periods=[2026], ) - insert_row( - connection, - "datasets", + add_row( + session, + Dataset, id=rows.dataset_id, name=DATASET_NAMES[country], year=2026, is_output_dataset=False, tax_benefit_model_version_id=rows.version_id, ) - insert_row( - connection, - "regions", + add_row( + session, + Region, id=rows.region_id, code=REGION_CODES[country], label=REGION_CODES[country], @@ -109,9 +152,9 @@ def store_catalog(connection: Connection, country: str) -> CatalogRows: tax_benefit_model_version_id=rows.version_id, default_dataset_id=rows.dataset_id, ) - insert_row( - connection, - "policies", + add_row( + session, + Policy, id=rows.policy_id, country_id=country, tax_benefit_model_id=model_id, @@ -122,9 +165,7 @@ def store_catalog(connection: Connection, country: str) -> CatalogRows: return rows -def store_local_area_catalog( - connection: Connection, catalog: CatalogRows -) -> CatalogRows: +def store_local_area_catalog(session: Session, catalog: CatalogRows) -> CatalogRows: """Give a UK catalog version its UK-wide region and local areas, as .py 6.17.1. UK-wide uses the catalog's national dataset; a constituency and a local @@ -134,9 +175,9 @@ def store_local_area_catalog( ``catalog``'s lists, so ``delete_catalog(catalog)`` deletes it. """ local_area_dataset_id = uuid4() - insert_row( - connection, - "datasets", + add_row( + session, + Dataset, id=local_area_dataset_id, name=LOCAL_AREA_DATASET_NAME, year=2026, @@ -152,9 +193,9 @@ def store_local_area_catalog( region_ids = {} for code, (region_type, dataset_id) in regions.items(): region_ids[code] = uuid4() - insert_row( - connection, - "regions", + add_row( + session, + Region, id=region_ids[code], code=code, label=code, @@ -170,7 +211,7 @@ def store_local_area_catalog( def store_simulation( - connection: Connection, + session: Session, catalog: CatalogRows, *, policy_id: UUID | None, @@ -178,9 +219,9 @@ def store_simulation( ) -> UUID: """Store an economy simulation in ``year`` of the catalog's dataset and region.""" simulation_id = uuid4() - insert_row( - connection, - "simulations", + add_row( + session, + Simulation, id=simulation_id, simulation_type="economy", dataset_id=catalog.dataset_id, @@ -227,7 +268,7 @@ def finished(self) -> bool: def store_simulation_run( - connection: Connection, + session: Session, catalog: CatalogRows, simulation_id: UUID, settings: RunSettings, @@ -240,9 +281,9 @@ def store_simulation_run( """ run_id = uuid4() if settings.run_id is None else settings.run_id created_at = settings.created_at - insert_row( - connection, - "simulation_runs", + add_row( + session, + SimulationRun, id=run_id, created_at=created_at, simulation_id=simulation_id, @@ -269,8 +310,8 @@ class StoredReport: year: int = STORED_REPORT_YEAR -def store_report( # noqa: PLR0913 # the connection and catalog, then each column a test varies - connection: Connection, +def store_report( # noqa: PLR0913 # the session and catalog, then each column a test varies + session: Session, catalog: CatalogRows, *, household_id: UUID | None = None, @@ -290,56 +331,44 @@ def store_report( # noqa: PLR0913 # the connection and catalog, then each colu report = StoredReport( report_id=uuid4(), baseline_simulation_id=store_simulation( - connection, catalog, policy_id=None, year=year + session, catalog, policy_id=None, year=year ), reform_simulation_id=store_simulation( - connection, catalog, policy_id=catalog.policy_id, year=year + session, catalog, policy_id=catalog.policy_id, year=year ), year=year, ) - connection.execute( - text( - "INSERT INTO reports (id, label, description, country, type, " - "tax_benefit_model_id, policy_id, baseline_simulation_id, " - "reform_simulation_id, household_id, dataset_id, region_id, year, " - "budget_window_size, inputs, key_version, definition_key, " - "dataset_independent_key, created_at) VALUES (:id, :label, " - ":description, :country, :type, :model_id, :policy_id, :baseline, " - ":reform, :household_id, :dataset_id, :region_id, :year, " - ":budget_window_size, CAST(:inputs AS JSON), :key_version, " - ":definition_key, :dataset_independent_key, " - "COALESCE(CAST(:created_at AS timestamptz), now()))" - ), - { - "id": report.report_id, - "label": f"{catalog.country} reform", - "description": "A stored report", - "country": catalog.country, - "type": "economy", - "model_id": catalog.model_id, - "policy_id": catalog.policy_id, - "baseline": report.baseline_simulation_id, - "reform": report.reform_simulation_id, - "household_id": household_id, - "dataset_id": catalog.dataset_id, - "region_id": catalog.region_id, - "budget_window_size": budget_window_size, - "year": year, - "inputs": '{"include_cliffs": true}', - "key_version": None if dataset_independent_key is None else 1, - "definition_key": ( - None if dataset_independent_key is None else uuid4().hex * 2 - ), - "dataset_independent_key": dataset_independent_key, - "created_at": created_at, - }, + # Without a creation time, the report takes the model's: now. + creation = {} if created_at is None else {"created_at": created_at} + add_row( + 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, + policy_id=catalog.policy_id, + baseline_simulation_id=report.baseline_simulation_id, + reform_simulation_id=report.reform_simulation_id, + household_id=household_id, + dataset_id=catalog.dataset_id, + region_id=catalog.region_id, + year=year, + budget_window_size=budget_window_size, + inputs={"include_cliffs": True}, + key_version=None if dataset_independent_key is None else 1, + definition_key=None if dataset_independent_key is None else uuid4().hex * 2, + dataset_independent_key=dataset_independent_key, + **creation, ) catalog.report_ids.append(report.report_id) return report def store_report_run( - connection: Connection, + session: Session, catalog: CatalogRows, report: StoredReport, settings: RunSettings, @@ -358,14 +387,14 @@ def store_report_run( run_ids = RunIds( report_run_id=uuid4() if settings.run_id is None else settings.run_id, baseline_simulation_run_id=store_simulation_run( - connection, + session, catalog, report.baseline_simulation_id, simulation_run_settings, year=simulation_year, ), reform_simulation_run_id=store_simulation_run( - connection, + session, catalog, report.reform_simulation_id, simulation_run_settings, @@ -380,57 +409,39 @@ def store_report_run( result_columns: dict[str, Any] = ( {} if stored is None else dict(stored.report_run_columns) ) - spm_provenance = result_columns.pop("spm_provenance", None) created_at = settings.created_at - connection.execute( - text( - "INSERT INTO report_runs (id, created_at, report_id, " - "baseline_simulation_run_id, reform_simulation_run_id, " - "budget_window_run_id, year, " - "country_package_version, policyengine_version, status, trigger, " - "started_at, completed_at, error_message, spm_provenance, forced" - + "".join(f", {column}" for column in result_columns) - + ") VALUES (:id, :created_at, :report_id, :baseline_run, " - ":reform_run, :budget_window_run_id, :year, " - ":country_package_version, :policyengine_version, " - ":status, 'initial', :started_at, :completed_at, :error_message, " - ":spm_provenance, :forced" - + "".join(f", :{column}" for column in result_columns) - + ")" - ).bindparams(bindparam("spm_provenance", type_=JSONB)), - { - "id": run_ids.report_run_id, - "created_at": created_at, - "report_id": report.report_id, - "baseline_run": run_ids.baseline_simulation_run_id, - "reform_run": run_ids.reform_simulation_run_id, - "budget_window_run_id": ( - None - if budget_window_year is None - else budget_window_year.budget_window_run_id - ), - "year": None if budget_window_year is None else budget_window_year.year, - "status": settings.status, - "started_at": created_at, - "completed_at": ( - created_at + timedelta(minutes=10) if settings.finished else None - ), - "error_message": settings.error_message, - "spm_provenance": spm_provenance, - "forced": settings.forced, - **settings.versions, - **result_columns, - }, + add_row( + session, + ReportRun, + id=run_ids.report_run_id, + created_at=created_at, + report_id=report.report_id, + baseline_simulation_run_id=run_ids.baseline_simulation_run_id, + reform_simulation_run_id=run_ids.reform_simulation_run_id, + budget_window_run_id=( + None + if budget_window_year is None + else budget_window_year.budget_window_run_id + ), + 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, + forced=settings.forced, + **result_columns, + **settings.versions, ) if stored is not None: for table, rows in stored.rows.items(): for row in rows: - insert_row(connection, table, id=uuid4(), **row) + add_row(session, RESULT_MODELS[table], id=uuid4(), **row) return run_ids def store_budget_window_run( - connection: Connection, + session: Session, catalog: CatalogRows, report: StoredReport, settings: RunSettings, @@ -441,9 +452,9 @@ def store_budget_window_run( """ run_id = uuid4() if settings.run_id is None else settings.run_id created_at = settings.created_at - insert_row( - connection, - "budget_window_runs", + add_row( + session, + BudgetWindowRun, id=run_id, created_at=created_at, report_id=report.report_id, @@ -458,73 +469,64 @@ def store_budget_window_run( return run_id -def delete_catalog(connection: Connection, catalog: CatalogRows) -> None: +def _delete_rows(session: Session, model: type[Any], row_ids: list[UUID]) -> None: + for row_id in row_ids: + session.execute(delete(model).where(model.id == row_id)) + + +def delete_catalog(session: Session, catalog: CatalogRows) -> None: """Delete the reports, simulations, households and catalog rows of ``catalog``. A report's runs and results go with it, and a simulation's runs with it. """ - for report_id in catalog.report_ids: - connection.execute( - text("DELETE FROM reports WHERE id = :id"), {"id": report_id} - ) - for simulation_id in catalog.simulation_ids: - connection.execute( - text("DELETE FROM simulations WHERE id = :id"), {"id": simulation_id} - ) - for household_id in catalog.household_ids: - connection.execute( - text("DELETE FROM households WHERE id = :id"), {"id": household_id} - ) - for region_id in catalog.area_region_ids: - connection.execute( - text("DELETE FROM regions WHERE id = :id"), {"id": region_id} - ) - for dataset_id in catalog.area_dataset_ids: - connection.execute( - text("DELETE FROM datasets WHERE id = :id"), {"id": dataset_id} - ) - for table, row_id in ( - ("policies", catalog.policy_id), - ("regions", catalog.region_id), - ("datasets", catalog.dataset_id), - ("tax_benefit_model_versions", catalog.version_id), + _delete_rows(session, Report, catalog.report_ids) + _delete_rows(session, Simulation, catalog.simulation_ids) + _delete_rows(session, Household, catalog.household_ids) + _delete_rows(session, Region, catalog.area_region_ids) + _delete_rows(session, Dataset, catalog.area_dataset_ids) + for model, row_id in ( + (Policy, catalog.policy_id), + (Region, catalog.region_id), + (Dataset, catalog.dataset_id), + (TaxBenefitModelVersion, catalog.version_id), ): - connection.execute(text(f"DELETE FROM {table} WHERE id = :id"), {"id": row_id}) + _delete_rows(session, model, [row_id]) if catalog.created_model: - connection.execute( - text("DELETE FROM tax_benefit_models WHERE id = :id"), - {"id": catalog.model_id}, - ) + _delete_rows(session, TaxBenefitModel, [catalog.model_id]) + + +def _set_society_wide_enabled(session: Session, country: str, *, enabled: bool) -> None: + session.execute( + update(Country) + .where(col(Country.id) == country) + .values(society_wide_enabled=enabled) + ) @contextmanager -def household_only_catalog(engine: Engine, country: str) -> Iterator[CatalogRows]: +def household_only_catalog( + sessions: sessionmaker[Session], country: str +) -> Iterator[CatalogRows]: """Make the country household-only, store its catalog, and restore both after. The country keeps household calculations but loses economy reports. """ - with engine.begin() as connection: - connection.execute( - text("UPDATE countries SET society_wide_enabled = false WHERE id = :id"), - {"id": country}, - ) - catalog = store_catalog(connection, country) + with sessions.begin() as session: + _set_society_wide_enabled(session, country, enabled=False) + catalog = store_catalog(session, country) try: yield catalog finally: # Each in its own transaction, so a failed cleanup still restores the # country. - with engine.begin() as connection: - connection.execute( - text("UPDATE countries SET society_wide_enabled = true WHERE id = :id"), - {"id": country}, - ) - with engine.begin() as connection: - delete_catalog(connection, catalog) + with sessions.begin() as session: + _set_society_wide_enabled(session, country, enabled=True) + with sessions.begin() as session: + delete_catalog(session, catalog) def store_year_simulations( - connection: Connection, catalog: CatalogRows, report: StoredReport, year: int + session: Session, catalog: CatalogRows, report: StoredReport, year: int ) -> StoredReport: """Return the report with the simulations a year of its budget window uses. @@ -538,10 +540,10 @@ def store_year_simulations( return StoredReport( report_id=report.report_id, baseline_simulation_id=store_simulation( - connection, catalog, policy_id=None, year=year + session, catalog, policy_id=None, year=year ), reform_simulation_id=store_simulation( - connection, catalog, policy_id=catalog.policy_id, year=year + session, catalog, policy_id=catalog.policy_id, year=year ), year=report.year, ) diff --git a/tests/integration/test_database_sessions.py b/tests/integration/test_database_sessions.py new file mode 100644 index 000000000..48b4f2272 --- /dev/null +++ b/tests/integration/test_database_sessions.py @@ -0,0 +1,243 @@ +"""Tests of the tests' PostgreSQL and MySQL Session factories, and their statements. + +They need the disposable v2 PostgreSQL database and, for API v1's, the +disposable MySQL database (tests/integration/conftest.py). The SQLite Session +factories are tested in tests/unit/data/test_database_sessions.py. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING +from uuid import uuid4 + +import pytest +from sqlalchemy import delete, func, select +from sqlalchemy.exc import DBAPIError +from sqlmodel import col + +from policyengine_api.data.orm import unpooled_v1_sessions, v1_schema_inspector +from policyengine_api.data.v2.database import ( + unpooled_v2_read_only_sessions, + unpooled_v2_sessions, + v2_schema_inspector, +) +from policyengine_api.data.v2.models import ( + Country, + Region, + TaxBenefitModel, + TaxBenefitModelVersion, +) +from policyengine_api.data.v2.privileges import declared_privileges +from tests.fixtures.database_sessions import ( + act_as, + act_as_owner, + create_role, + drop_role, + grant, + grant_declared_v2_privileges, + schema_inspector, + truncate, +) +from tests.integration.simulation_rows import add_row, insert_public_api_rows + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + + from sqlalchemy.orm import Session, sessionmaker + + from tests.integration.conftest import ManagedV2Roles + +V2_DATABASE_NAME = "policyengine_v2_alembic_test" +V1_DATABASE_NAME = "policyengine_alembic_test" + + +def _current_user(session: Session) -> str: + return session.execute(select(func.current_user())).scalar_one() + + +def _has_table_privilege(session: Session, role: str, privilege: str) -> bool: + return bool( + session.execute( + select(func.has_table_privilege(role, "public.regions", privilege)) + ).scalar_one() + ) + + +@pytest.fixture +def owner_session(v2_owner_sessions: sessionmaker[Session]) -> Iterator[Session]: + """Yield an owner's Session whose writes are rolled back after the test.""" + with v2_owner_sessions() as session: + try: + yield session + finally: + session.rollback() + + +@pytest.fixture +def temporary_role(v2_owner_sessions: sessionmaker[Session]) -> Iterator[str]: + """Return a role that can't log in, dropped after the test.""" + role = f"policyengine_sessions_test_{uuid4().hex[:12]}" + with v2_owner_sessions.begin() as session: + create_role(session, role) + try: + yield role + finally: + with v2_owner_sessions.begin() as session: + drop_role(session, role) + + +def test_role_sessions_act_as_their_role_in_every_transaction( + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], + managed_v2_roles: ManagedV2Roles, +) -> None: + runtime_role = managed_v2_roles.runtime + runtime_sessions = v2_sessions_as_role(runtime_role) + + with runtime_sessions.begin() as session: + first = _current_user(session) + with runtime_sessions.begin() as session: + second = _current_user(session) + countries = session.scalars(select(col(Country.id))).all() + + assert (first, second) == (runtime_role, runtime_role) + assert countries + + +def test_role_sessions_hold_only_their_roles_privileges( + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], + managed_v2_roles: ManagedV2Roles, +) -> None: + runtime_sessions = v2_sessions_as_role(managed_v2_roles.runtime) + + with ( + runtime_sessions() as session, + pytest.raises(DBAPIError, match="permission denied for table countries"), + ): + session.execute(delete(Country)) + + +def test_act_as_lasts_until_act_as_owner_or_the_transaction_ends( + owner_session: Session, managed_v2_roles: ManagedV2Roles +) -> None: + runtime_role = managed_v2_roles.runtime + owner = _current_user(owner_session) + + act_as(owner_session, runtime_role) + acting = _current_user(owner_session) + act_as_owner(owner_session) + after_acting = _current_user(owner_session) + act_as(owner_session, runtime_role) + owner_session.rollback() + next_transaction = _current_user(owner_session) + + assert acting == runtime_role + assert after_acting == owner + assert next_transaction == owner + + +def test_a_temporary_role_is_granted_privileges_and_dropped( + v2_owner_sessions: sessionmaker[Session], temporary_role: str +) -> None: + with v2_owner_sessions.begin() as session: + before = _has_table_privilege(session, temporary_role, "SELECT") + grant(session, "SELECT, UPDATE (label, code)", on=Region, to=temporary_role) + after = _has_table_privilege(session, temporary_role, "SELECT") + can_update_label = session.execute( + select( + func.has_column_privilege( + temporary_role, "public.regions", "label", "UPDATE" + ) + ) + ).scalar_one() + + assert (before, after, can_update_label) == (False, True, True) + + +def test_a_dropped_role_no_longer_exists( + v2_owner_sessions: sessionmaker[Session], +) -> None: + role = f"policyengine_sessions_test_{uuid4().hex[:12]}" + with v2_owner_sessions.begin() as session: + create_role(session, role) + grant(session, "SELECT", on=Region, to=role) + created = session.execute(select(func.to_regrole(role))).scalar_one() + drop_role(session, role) + dropped = session.execute(select(func.to_regrole(role))).scalar_one() + + assert (created, dropped) == (role, None) + + +def test_truncate_empties_a_table_and_the_tables_referring_to_it( + owner_session: Session, +) -> None: + insert_public_api_rows(owner_session) + + truncate(owner_session, TaxBenefitModel) + + remaining = [ + owner_session.scalar(select(func.count()).select_from(model)) + for model in (TaxBenefitModel, TaxBenefitModelVersion) + ] + assert remaining == [0, 0] + + +def test_the_schema_inspector_reads_a_session_or_its_factory( + owner_session: Session, v2_owner_sessions: sessionmaker[Session] +) -> None: + tables = schema_inspector(owner_session).get_table_names(schema="public") + from_factory = schema_inspector(v2_owner_sessions).get_table_names(schema="public") + + assert {"reports", "alembic_version"} <= set(tables) + assert set(from_factory) == set(tables) + + +def test_declared_privileges_are_granted_again_without_error( + disposable_v2_database_url: str, managed_v2_roles: ManagedV2Roles +) -> None: + environment = managed_v2_roles.deployment_environment + + plan = grant_declared_v2_privileges( + disposable_v2_database_url, declared_privileges(environment) + ) + + assert plan.can_apply + + +def test_unpooled_v2_sessions_reach_the_database_at_the_url( + disposable_v2_database_url: str, +) -> None: + with unpooled_v2_sessions(disposable_v2_database_url) as sessions: + with sessions() as session: + database = session.execute(select(func.current_database())).scalar_one() + tables = v2_schema_inspector(sessions).get_table_names(schema="public") + + assert database == V2_DATABASE_NAME + assert "reports" in tables + + +def test_unpooled_v2_read_only_sessions_refuse_writes( + disposable_v2_database_url: str, +) -> None: + with ( + unpooled_v2_read_only_sessions(disposable_v2_database_url) as sessions, + sessions() as session, + ): + countries = session.scalars(select(col(Country.id))).all() + with pytest.raises(DBAPIError, match="read-only transaction"): + add_row(session, TaxBenefitModel, name=f"read-only-{uuid4().hex[:12]}") + + assert countries + + +def test_v1_sessions_reach_the_disposable_mysql_database( + v1_sessions: sessionmaker[Session], disposable_v1_database_url: str +) -> None: + with v1_sessions() as session: + database = session.execute(select(func.database())).scalar_one() + with unpooled_v1_sessions(disposable_v1_database_url) as sessions: + with sessions() as session: + unpooled_database = session.execute(select(func.database())).scalar_one() + tables = v1_schema_inspector(sessions).get_table_names() + + assert (database, unpooled_database) == (V1_DATABASE_NAME, V1_DATABASE_NAME) + assert "policy" in tables diff --git a/tests/integration/user_report_run_support.py b/tests/integration/user_report_run_support.py index 4ffeb2c9b..92be6dce6 100644 --- a/tests/integration/user_report_run_support.py +++ b/tests/integration/user_report_run_support.py @@ -2,8 +2,9 @@ ``JoiningSimulationService`` answers creates and re-runs as the simulation service does once identical requests share runs: with a run it names, or -with a new pending run it stores. The helpers serve the report routes as the -Public API's runtime role and read users' records and saved reports back. +with a new pending run it stores. The helpers serve the report routes as +API v1's runtime role and read users' records and saved reports back, through +Sessions of the disposable database's owner. """ from __future__ import annotations @@ -15,10 +16,18 @@ from fastapi.testclient import TestClient from flask import Flask -from sqlalchemy import text +from sqlalchemy import select, update +from sqlalchemy.dialects.postgresql import insert from sqlalchemy.exc import OperationalError +from sqlmodel import col from policyengine_api.asgi_factory import create_asgi_app +from policyengine_api.data.v2.models import ( + Report, + User, + UserReportAssociation, + UserReportRunAssociation, +) from policyengine_api.fastapi_routes.dependencies import NativeRouteDependencies from policyengine_api.libs.user_auth import UNAUTHENTICATED_USER_HEADER from policyengine_api.migration_flags import ( @@ -81,7 +90,7 @@ from collections.abc import Callable from contextlib import AbstractContextManager - from sqlalchemy import Connection, Engine + from sqlalchemy.orm import sessionmaker from sqlmodel import Session from policyengine_api.services.v2.identity.types import AccountPrincipal @@ -122,10 +131,11 @@ class JoiningSimulationService: create stores a new report with a pending run, and a re-run a new pending run of the report, as before, marked forced for a forced re-run. With ``during_call``, each create and re-run first runs it, as something - another request does while the simulation service is asked. + another request does while the simulation service is asked. It stores + through ``owner_sessions``. """ - engine: Engine + owner_sessions: sessionmaker[Session] catalog: CatalogRows joined_run: JoinedRun | None = None during_call: Callable[[], None] | None = None @@ -141,10 +151,10 @@ def submit_report(self, report: EconomyReportCreationInput) -> SubmittedReport: report_id=self.joined_run.report_id, report_run_id=self.joined_run.report_run_id, ) - with self.engine.begin() as connection: - stored = store_report(connection, self.catalog) + with self.owner_sessions.begin() as session: + stored = store_report(session, self.catalog) run_ids = store_report_run( - connection, + session, self.catalog, stored, RunSettings(versions=CURRENT_VERSIONS, status="pending"), @@ -166,9 +176,9 @@ def submit_budget_window( report_id=self.joined_run.report_id, budget_window_run_id=self.joined_run.budget_window_run_id, ) - with self.engine.begin() as connection: + with self.owner_sessions.begin() as session: window = store_window( - connection, + session, self.catalog, years=tuple( range(report.year, report.year + report.budget_window_size) @@ -189,16 +199,15 @@ def rerun_report(self, rerun: ReportRerunInput) -> StartedReportRun: report_run_id=self.joined_run.report_run_id, budget_window_run_id=self.joined_run.budget_window_run_id, ) - with self.engine.begin() as connection: - simulations = connection.execute( - text( - "SELECT baseline_simulation_id, reform_simulation_id FROM " - "reports WHERE id = :id" - ), - {"id": rerun.report_id}, + with self.owner_sessions.begin() as session: + simulations = session.execute( + select( + col(Report.baseline_simulation_id), + col(Report.reform_simulation_id), + ).where(col(Report.id) == rerun.report_id) ).one() run_ids = store_report_run( - connection, + session, self.catalog, StoredReport( report_id=rerun.report_id, @@ -288,23 +297,23 @@ def report_body(policy_id: UUID) -> dict[str, Any]: def store_joined_and_newer_forced_run( - connection: Any, catalog: CatalogRows, *, joined_status: str + session: Session, catalog: CatalogRows, *, joined_status: str ) -> tuple[StoredReport, UUID, UUID]: """Store a report with a run to join and a newer forced run beside it. A succeeded run to join has its result stored. Return the report, the run to join and the forced run, which is the report's newest. """ - report = store_report(connection, catalog) + report = store_report(session, catalog) joined = store_report_run( - connection, + session, catalog, report, RunSettings(versions=CURRENT_VERSIONS, status=joined_status), result=us_economy_result() if joined_status == "succeeded" else None, ) forced = store_report_run( - connection, + session, catalog, report, RunSettings( @@ -331,15 +340,23 @@ def as_browser(browser_id: UUID) -> dict[str, str]: return {UNAUTHENTICATED_USER_HEADER: str(browser_id)} -def stored_records(engine: Engine, user_ids: list[UUID]) -> list[RunRecord]: - with engine.begin() as connection: - rows = connection.execute( - text( - "SELECT user_id, report_run_id, trigger, requested_at FROM " - "user_report_run_associations WHERE user_id = ANY(:ids) " - "ORDER BY requested_at, user_id" - ), - {"ids": user_ids}, +def stored_records( + owner_sessions: sessionmaker[Session], user_ids: list[UUID] +) -> list[RunRecord]: + """Return the users' stored requests for report runs, oldest first.""" + with owner_sessions.begin() as session: + rows = session.execute( + select( + col(UserReportRunAssociation.user_id), + col(UserReportRunAssociation.report_run_id), + col(UserReportRunAssociation.trigger), + col(UserReportRunAssociation.requested_at), + ) + .where(col(UserReportRunAssociation.user_id).in_(user_ids)) + .order_by( + col(UserReportRunAssociation.requested_at), + col(UserReportRunAssociation.user_id), + ) ).all() return [ RunRecord( @@ -352,34 +369,40 @@ def stored_records(engine: Engine, user_ids: list[UUID]) -> list[RunRecord]: ] -def store_saved_report(engine: Engine, *, user_id: UUID, report_id: UUID) -> UUID: +def store_saved_report( + owner_sessions: sessionmaker[Session], *, user_id: UUID, report_id: UUID +) -> UUID: """Save the report for the user, with no last run time, and return its ID.""" saved_report_id = uuid4() - with engine.begin() as connection: - connection.execute( - text( - "INSERT INTO users (id, user_type) VALUES (:id, 'unauthenticated') " - "ON CONFLICT (id) DO NOTHING" - ), - {"id": user_id}, + with owner_sessions.begin() as session: + session.execute( + insert(User) + .values(id=user_id, user_type="unauthenticated") + .on_conflict_do_nothing(index_elements=[col(User.id)]) ) - connection.execute( - text( - "INSERT INTO user_report_associations (id, user_id, report_id, " - "country_id, name) VALUES (:id, :user_id, :report_id, 'us', " - "'My report')" - ), - {"id": saved_report_id, "user_id": user_id, "report_id": report_id}, + session.execute( + insert(UserReportAssociation).values( + id=saved_report_id, + user_id=user_id, + report_id=report_id, + country_id="us", + name="My report", + ) ) return saved_report_id -def saved_report_last_run_at(engine: Engine, saved_report_id: UUID) -> datetime | None: - with engine.begin() as connection: - return connection.execute( - text("SELECT last_run_at FROM user_report_associations WHERE id = :id"), - {"id": saved_report_id}, +def saved_report_last_run_at( + owner_sessions: sessionmaker[Session], saved_report_id: UUID +) -> datetime | None: + """Return when the saved report was last run, or None.""" + with owner_sessions.begin() as session: + last_run_at: datetime | None = session.execute( + select(col(UserReportAssociation.last_run_at)).where( + col(UserReportAssociation.id) == saved_report_id + ) ).scalar_one() + return last_run_at def rerun_as_browser(client: TestClient, report_id: UUID, browser_id: UUID) -> None: @@ -392,8 +415,11 @@ def rerun_as_browser(client: TestClient, report_id: UUID, browser_id: UUID) -> N assert response.status_code == 201, response.text -def newest_request(engine: Engine, user_id: UUID) -> datetime: - return max(record.requested_at for record in stored_records(engine, [user_id])) +def newest_request(owner_sessions: sessionmaker[Session], user_id: UUID) -> datetime: + """Return when the user last asked for a report run.""" + return max( + record.requested_at for record in stored_records(owner_sessions, [user_id]) + ) @dataclass(frozen=True) @@ -406,7 +432,7 @@ class StoredWindow: def store_window( - connection: Connection, + session: Session, catalog: CatalogRows, *, years: tuple[int, ...], @@ -415,16 +441,16 @@ def store_window( ) -> StoredWindow: """Store a window run of ``report`` (a new window if None) with a run per year.""" window = ( - store_report(connection, catalog, budget_window_size=len(years), year=years[0]) + store_report(session, catalog, budget_window_size=len(years), year=years[0]) if report is None else report ) - window_run_id = store_budget_window_run(connection, catalog, window, settings) + window_run_id = store_budget_window_run(session, catalog, window, settings) year_run_ids = tuple( store_report_run( - connection, + session, catalog, - store_year_simulations(connection, catalog, window, year), + store_year_simulations(session, catalog, window, year), RunSettings( versions=settings.versions, status=settings.status, @@ -458,17 +484,23 @@ def window_body(policy_id: UUID, *, years: int) -> dict[str, Any]: def store_signed_in_user( - sessions: Any, engine: Engine, *, user_type: str = "standard" + sessions: Any, + owner_sessions: sessionmaker[Session], + *, + user_type: str = "standard", ) -> tuple[UserPrincipal, UUID]: - """Provision a signed-in user of ``user_type``; return its principal and ID.""" + """Provision a signed-in user of ``user_type``; return its principal and ID. + + ``sessions`` provision the user as the runtime role does, and + ``owner_sessions`` then give it its type. + """ principal = UserPrincipal(issuer=ADMIN_ISSUER, subject=f"auth0|{uuid4()}") with sessions.begin() as session: user_id = resolve_principal_user_in_session( session, principal, country_id="us" ).user_id - with engine.begin() as connection: - connection.execute( - text("UPDATE users SET user_type = :user_type WHERE id = :id"), - {"user_type": user_type, "id": user_id}, + with owner_sessions.begin() as session: + session.execute( + update(User).where(col(User.id) == user_id).values(user_type=user_type) ) return principal, user_id diff --git a/tests/to_refactor/conftest.py b/tests/to_refactor/conftest.py index b33f66ebf..fa230c882 100644 --- a/tests/to_refactor/conftest.py +++ b/tests/to_refactor/conftest.py @@ -3,17 +3,16 @@ from collections.abc import Iterator import pytest -from sqlalchemy import Engine, create_engine -from sqlalchemy.pool import StaticPool +from sqlalchemy.orm import Session, sessionmaker from policyengine_api.constants import COUNTRY_PACKAGE_VERSIONS from policyengine_api.data import orm from policyengine_api.data.v1_models import Policy from policyengine_api.utils import hash_object -from tests.fixtures.local_v1_database import create_test_v1_schema +from tests.fixtures.database_sessions import serve_v1_sessions, sqlite_v1_sessions -def _seed_current_law_policies(engine: Engine) -> None: +def _seed_current_law_policies(sessions: sessionmaker[Session]) -> None: policies = [ Policy( id=policy_id, @@ -25,27 +24,19 @@ def _seed_current_law_policies(engine: Engine) -> None: ) for policy_id, country_id in enumerate(COUNTRY_PACKAGE_VERSIONS, start=1) ] - with orm.build_session_factory(engine).begin() as session: + with sessions.begin() as session: session.add_all(policies) @pytest.fixture(scope="session", autouse=True) def isolated_legacy_v1_database() -> Iterator[None]: """Bind legacy tests to explicit in-memory persistence, never Cloud SQL.""" - engine = create_engine( - "sqlite+pysqlite:///:memory:", - connect_args={"check_same_thread": False}, - poolclass=StaticPool, - ) - create_test_v1_schema(engine) - _seed_current_law_policies(engine) - patcher = pytest.MonkeyPatch() - patcher.setattr(orm, "get_v1_engine", lambda: engine) - orm.clear_v1_session_factories() - try: - yield - finally: - orm.clear_v1_session_factories() - patcher.undo() - engine.dispose() + with sqlite_v1_sessions() as sessions: + _seed_current_law_policies(sessions) + serve_v1_sessions(patcher, sessions) + try: + yield + finally: + orm.clear_v1_session_factories() + patcher.undo() diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py index 7b2688dbf..03500e4c5 100644 --- a/tests/unit/conftest.py +++ b/tests/unit/conftest.py @@ -1,38 +1,41 @@ +from __future__ import annotations + import os +from typing import TYPE_CHECKING import pytest -from sqlalchemy import create_engine -from sqlalchemy.pool import StaticPool os.environ.setdefault("FLASK_DEBUG", "1") from policyengine_api.data import orm from policyengine_api.data.v1_models import V1Base -from tests.fixtures.local_v1_database import create_test_v1_schema +from tests.fixtures.database_sessions import ( + delete_all_rows, + serve_v1_sessions, + sqlite_v1_sessions, +) + +if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlalchemy.orm import Session, sessionmaker @pytest.fixture(scope="session") -def test_engine(): - engine = create_engine( - "sqlite+pysqlite:///:memory:", - connect_args={"check_same_thread": False}, - poolclass=StaticPool, - ) - create_test_v1_schema(engine) - yield engine - engine.dispose() +def v1_test_sessions() -> Iterator[sessionmaker[Session]]: + """Return Session factories of an in-memory SQLite copy of API v1's schema.""" + with sqlite_v1_sessions() as sessions: + yield sessions @pytest.fixture(autouse=True) -def isolated_orm_database(test_engine, monkeypatch): +def isolated_orm_database( + v1_test_sessions: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch +) -> Iterator[None]: """Bind runtime factories to a clean in-memory ORM database per test.""" - monkeypatch.setattr(orm, "get_v1_engine", lambda: test_engine) - orm.clear_v1_session_factories() - factory = orm.get_v1_session_factory() - with factory.begin() as session: - production_tables = V1Base.metadata.sorted_tables - for table in reversed(production_tables): - session.execute(table.delete()) + serve_v1_sessions(monkeypatch, v1_test_sessions) + with orm.get_v1_session_factory().begin() as session: + delete_all_rows(session, V1Base.registry) try: yield finally: @@ -40,11 +43,11 @@ def isolated_orm_database(test_engine, monkeypatch): @pytest.fixture -def orm_session_factory(isolated_orm_database): +def orm_session_factory(isolated_orm_database: None) -> sessionmaker[Session]: return orm.get_v1_session_factory() @pytest.fixture -def orm_session(orm_session_factory): +def orm_session(orm_session_factory: sessionmaker[Session]) -> Iterator[Session]: with orm_session_factory() as session: yield session diff --git a/tests/unit/data/orm_access_support.py b/tests/unit/data/orm_access_support.py index 329a1a9b7..5eef73896 100644 --- a/tests/unit/data/orm_access_support.py +++ b/tests/unit/data/orm_access_support.py @@ -116,10 +116,12 @@ } ) # The modules that may create and hold an engine, open a Connection and attach -# pool events, to hand out Session factories: API v1's, API v2's and the tests'. +# pool events, to hand out Session factories: API v1's (with the listeners +# that record its pool's events), API v2's and the tests'. SESSION_FACTORY_MODULES = frozenset( { "policyengine_api/data/orm.py", + "policyengine_api/data/orm_pool_events.py", "policyengine_api/data/v2/database.py", "tests/fixtures/database_sessions.py", } diff --git a/tests/unit/data/test_database_sessions.py b/tests/unit/data/test_database_sessions.py new file mode 100644 index 000000000..8cf3b0778 --- /dev/null +++ b/tests/unit/data/test_database_sessions.py @@ -0,0 +1,180 @@ +"""Tests of the tests' SQLite Session factories in tests/fixtures/database_sessions.py. + +tests/integration/test_database_sessions.py tests the PostgreSQL and MySQL +ones, and the role, grant and cleanup statements. +""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING + +import pytest +from sqlalchemy import func, select +from sqlalchemy.exc import IntegrityError +from sqlmodel import col + +from policyengine_api.data import orm +from policyengine_api.data.v1_models import Policy, UserProfile, V1Base +from policyengine_api.data.v2.models import TaxBenefitModel, TaxBenefitModelVersion +from tests.fixtures.database_sessions import ( + act_as, + delete_all_rows, + recorded_statements, + schema_inspector, + sqlite_v1_sessions, + sqlite_v2_sessions, + v2_role_sessions, +) + +if TYPE_CHECKING: + from sqlalchemy.orm import Session, sessionmaker + + +def _version_of_a_missing_model() -> TaxBenefitModelVersion: + return TaxBenefitModelVersion( + model_id=TaxBenefitModel().id, + version="1.0.0", + current_law_id=1, + metadata_time_periods=[2026], + ) + + +def _policy(policy_hash: str) -> Policy: + return Policy( + country_id="us", + label="A reform", + api_version="1.0.0", + policy_json={}, + policy_hash=policy_hash, + ) + + +def test_sqlite_v2_sessions_enforce_foreign_keys_when_asked() -> None: + with sqlite_v2_sessions(foreign_keys=True) as sessions, sessions() as session: + session.add(_version_of_a_missing_model()) + with pytest.raises(IntegrityError, match="FOREIGN KEY"): + session.flush() + + +def test_sqlite_v2_sessions_ignore_foreign_keys_by_default() -> None: + with sqlite_v2_sessions() as sessions: + with sessions.begin() as session: + session.add(_version_of_a_missing_model()) + with sessions() as session: + stored = session.scalar( + select(func.count()).select_from(TaxBenefitModelVersion) + ) + + assert stored == 1 + + +def _add_a_model_then_fail(session: Session, name: str) -> None: + with session.begin_nested(): + session.add(TaxBenefitModel(name=name)) + session.flush() + raise RuntimeError(name) + + +def test_sqlite_v2_savepoints_roll_back_only_their_own_rows() -> None: + with sqlite_v2_sessions() as sessions, sessions() as session: + session.add(TaxBenefitModel(name="policyengine-us")) + session.flush() + with pytest.raises(RuntimeError): + _add_a_model_then_fail(session, "policyengine-uk") + names = session.scalars(select(col(TaxBenefitModel.name))).all() + + assert names == ["policyengine-us"] + + +def test_sqlite_v1_sessions_number_policies_as_api_v1_does() -> None: + with sqlite_v1_sessions() as sessions: + with sessions.begin() as session: + session.add_all([_policy("first"), _policy("second")]) + with sessions() as session: + numbered = session.execute( + select(Policy.policy_hash, Policy.id).order_by(Policy.id) + ).all() + + assert [tuple(row) for row in numbered] == [("first", 1), ("second", 2)] + + +def test_sqlite_v1_sessions_store_json_with_the_given_serializer() -> None: + serialized: list[object] = [] + + def serialize(value: object) -> str: + serialized.append(value) + return json.dumps(value) + + with ( + sqlite_v1_sessions(json_serializer=serialize) as sessions, + sessions.begin() as session, + ): + session.add(_policy("hash")) + + assert serialized == [{}] + + +def test_serving_v1_sessions_points_api_v1s_factory_at_them( + v1_test_sessions: sessionmaker[Session], +) -> None: + with v1_test_sessions.begin() as session: + session.add(_policy("served")) + + with orm.get_v1_session_factory()() as session: + hashes = session.scalars(select(Policy.policy_hash)).all() + + assert hashes == ["served"] + + +def test_delete_all_rows_empties_every_table_of_the_registry() -> None: + with sqlite_v1_sessions() as sessions: + with sessions.begin() as session: + session.add(_policy("hash")) + session.add( + UserProfile( + auth0_id="auth0|someone", primary_country="us", user_since=1 + ) + ) + with sessions.begin() as session: + delete_all_rows(session, V1Base.registry) + with sessions() as session: + remaining = [ + session.scalar(select(func.count()).select_from(model)) + for model in (Policy, UserProfile) + ] + + assert remaining == [0, 0] + + +def test_the_schema_inspector_reads_a_session_or_its_factory() -> None: + with sqlite_v2_sessions() as sessions, sessions() as session: + from_factory = schema_inspector(sessions).get_table_names() + from_session = schema_inspector(session).get_table_names() + + assert "reports" in from_factory + assert from_session == from_factory + + +def test_recorded_statements_are_the_sql_sent_inside() -> None: + with sqlite_v2_sessions() as sessions, sessions() as session: + session.scalars(select(col(TaxBenefitModel.name))).all() + with recorded_statements(session) as statements: + session.scalars(select(col(TaxBenefitModelVersion.version))).all() + + assert len(statements) == 1 + assert "FROM tax_benefit_model_versions" in statements[0] + + +@pytest.mark.parametrize("role", ["Runtime", "runtime; DROP TABLE users", "", "1st"]) +def test_a_role_is_named_in_lowercase_letters_digits_and_underscores( + role: str, +) -> None: + with sqlite_v2_sessions() as sessions, sessions() as session: + with pytest.raises(ValueError, match="role names"): + act_as(session, role) + with ( + pytest.raises(ValueError, match="role names"), + v2_role_sessions("postgresql+psycopg://localhost/unused", role), + ): + pass diff --git a/tests/unit/data/test_run_schema.py b/tests/unit/data/test_run_schema.py index 09d7740c5..5b90502f4 100644 --- a/tests/unit/data/test_run_schema.py +++ b/tests/unit/data/test_run_schema.py @@ -1,12 +1,23 @@ -from sqlalchemy import inspect +from __future__ import annotations +from typing import TYPE_CHECKING -def _column_names(test_engine, table_name: str) -> set[str]: - return {column["name"] for column in inspect(test_engine).get_columns(table_name)} +from tests.fixtures.database_sessions import schema_inspector +if TYPE_CHECKING: + from sqlalchemy.orm import Session, sessionmaker -def test_stage_one_run_schema_is_initialized_in_local_test_db(test_engine): - report_output_columns = _column_names(test_engine, "report_outputs") + +def _column_names(sessions: sessionmaker[Session], table_name: str) -> set[str]: + return { + column["name"] for column in schema_inspector(sessions).get_columns(table_name) + } + + +def test_stage_one_run_schema_is_initialized_in_local_test_db( + v1_test_sessions: sessionmaker[Session], +) -> None: + report_output_columns = _column_names(v1_test_sessions, "report_outputs") assert { "report_kind", "report_spec_json", @@ -16,7 +27,7 @@ def test_stage_one_run_schema_is_initialized_in_local_test_db(test_engine): "latest_successful_run_id", }.issubset(report_output_columns) - simulation_columns = _column_names(test_engine, "simulations") + simulation_columns = _column_names(v1_test_sessions, "simulations") assert { "simulation_spec_json", "simulation_spec_schema_version", @@ -24,7 +35,7 @@ def test_stage_one_run_schema_is_initialized_in_local_test_db(test_engine): "latest_successful_run_id", }.issubset(simulation_columns) - report_run_columns = _column_names(test_engine, "report_output_runs") + report_run_columns = _column_names(v1_test_sessions, "report_output_runs") assert { "id", "report_output_id", @@ -42,7 +53,7 @@ def test_stage_one_run_schema_is_initialized_in_local_test_db(test_engine): "resolved_options_hash", }.issubset(report_run_columns) - simulation_run_columns = _column_names(test_engine, "simulation_runs") + simulation_run_columns = _column_names(v1_test_sessions, "simulation_runs") assert { "id", "simulation_id", @@ -58,5 +69,5 @@ def test_stage_one_run_schema_is_initialized_in_local_test_db(test_engine): "simulation_cache_version", }.issubset(simulation_run_columns) - alias_columns = _column_names(test_engine, "legacy_report_output_aliases") + alias_columns = _column_names(v1_test_sessions, "legacy_report_output_aliases") assert {"legacy_report_output_id", "canonical_report_output_id"} == alias_columns diff --git a/tests/unit/v2/sqlite_report_rows.py b/tests/unit/v2/sqlite_report_rows.py index 6a3efa5e8..1aa3bac9a 100644 --- a/tests/unit/v2/sqlite_report_rows.py +++ b/tests/unit/v2/sqlite_report_rows.py @@ -11,12 +11,7 @@ from typing import TYPE_CHECKING from uuid import UUID, uuid4 -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import StaticPool -from sqlmodel import Session, create_engine - from policyengine_api.data.v2.models import ( - V2_METADATA, Report, Simulation, SimulationType, @@ -26,10 +21,14 @@ StoredReportDatabaseSession, ) from policyengine_api.services.v2.stored_reports.services import V2StoredReportService +from tests.fixtures.database_sessions import sqlite_v2_sessions if TYPE_CHECKING: from collections.abc import Iterator + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + STORED_AT = datetime(2026, 11, 14, 9, tzinfo=UTC) CURRENT_VERSIONS = PackageVersions( country_package_version="2.1.0", policyengine_version="6.17.1" @@ -38,16 +37,8 @@ def sqlite_sessions() -> Iterator[sessionmaker[Session]]: """Yield sessions of a new in-memory v2 schema, and dispose of it after.""" - engine = create_engine( - "sqlite://", - connect_args={"check_same_thread": False}, - poolclass=StaticPool, - ) - V2_METADATA.create_all(engine) - try: - yield sessionmaker(engine, class_=Session, expire_on_commit=False) - finally: - engine.dispose() + with sqlite_v2_sessions() as sessions: + yield sessions def report_service(sessions: sessionmaker[Session]) -> V2StoredReportService: diff --git a/tests/unit/v2/user_service_support.py b/tests/unit/v2/user_service_support.py index 6018df644..59435358b 100644 --- a/tests/unit/v2/user_service_support.py +++ b/tests/unit/v2/user_service_support.py @@ -8,12 +8,7 @@ from typing import TYPE_CHECKING from uuid import UUID -import sqlalchemy as sa -from sqlalchemy.orm import sessionmaker -from sqlmodel import Session, create_engine - from policyengine_api.data.v2.models import ( - V2_METADATA, Household, LegacyHouseholdMapping, LegacyPolicyMapping, @@ -31,11 +26,15 @@ from policyengine_api.services.v2.legacy_refs.validators import ( require_legacy_references, ) +from tests.fixtures.database_sessions import sqlite_v2_sessions from tests.fixtures.v2_countries import add_listed_countries if TYPE_CHECKING: from collections.abc import Collection, Iterator, Mapping + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + ISSUER = "https://auth.example.test/" ALICE = UserPrincipal(issuer=ISSUER, subject="google-oauth2|alice") BOB = UserPrincipal(issuer=ISSUER, subject="google-oauth2|bob") @@ -112,24 +111,16 @@ class V2Store: @contextmanager def v2_store() -> Iterator[V2Store]: - """Create an isolated SQLite v2 schema with mirrored v1 records.""" - engine = create_engine("sqlite://") - - @sa.event.listens_for(engine, "connect") - def enable_foreign_keys(dbapi_connection, _connection_record) -> None: - cursor = dbapi_connection.cursor() - cursor.execute("PRAGMA foreign_keys=ON") - cursor.close() - # SQLAlchemy's documented pysqlite recipe: let SQLAlchemy own BEGIN so - # provisioning savepoints behave as they do on Postgres. - dbapi_connection.isolation_level = None - - @sa.event.listens_for(engine, "begin") - def begin_transaction(connection) -> None: - connection.exec_driver_sql("BEGIN") - - V2_METADATA.create_all(engine) - sessions = sessionmaker(engine, class_=Session, expire_on_commit=False) + """Create an isolated SQLite v2 schema with mirrored v1 records. + + SQLite enforces its foreign keys, and provisioning's savepoints behave as + they do on PostgreSQL. + """ + with sqlite_v2_sessions(foreign_keys=True) as sessions: + yield _store_mirrored_records(sessions) + + +def _store_mirrored_records(sessions: sessionmaker[Session]) -> V2Store: with sessions() as session: add_listed_countries(session) with sessions.begin() as session: @@ -198,14 +189,10 @@ def begin_transaction(connection) -> None: ] ) session.flush() - store = V2Store( + return V2Store( sessions=sessions, policy_id=policy.id, uk_policy_id=uk_policy.id, household_id=household.id, uk_household_id=uk_household.id, ) - try: - yield store - finally: - engine.dispose() From b6196382310ecd3751687e5d103c7e2ab03b9e5d Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:27:00 +0400 Subject: [PATCH 13/20] Run every database statement in API v1 through the ORM Rewrites everything rule api.data.orm-only found (1,692 places in 131 files) so code declares tables only as mapped classes and runs every statement through an ORM Session; the rule test now passes. - Production: privilege reconciliation reads Postgres's catalog through read-only mapped classes; the migration target checks, the three migration qualification commands (READ ONLY Sessions), the v1 schema migration and the household mirror script take Sessions from the session-factory modules, whose engine functions become private. Catalog publication's staging tables are SQLModel classes on their own registry, still TEMPORARY with ON COMMIT DROP, and a full publication sequence sends the same 691 statements as before. Commands, arguments and environment variables are unchanged. - Tests: the Alembic lifecycle and revision tests, the report, run and role privilege tests, the persistence and v1 MySQL tests and the SQLite unit tests use the shared session factories, mapped classes (small ones for older revisions' tables) and SQLAlchemy's Inspector. ON CONFLICT on a partial index sends its condition as a literal, since a bound value fails once psycopg prepares the statement. - The registry names each statement with no ORM form, in the module that runs it: GRANT and REVOKE, CREATE ROLE, COPY and the staging tables' Connection, ANALYZE, Alembic's need for a Connection, the dialect's name, and the tests' TRUNCATE, DROP TABLE, EXPLAIN, BEGIN IMMEDIATE and roles. The old Connection test helpers are gone, and the migrations skill describes every helper and exception. Co-Authored-By: Claude Opus 5.5 --- docs/engineering/skills/alembic-migrations.md | 61 +- docs/generated/rules.md | 11 + migrations/v2/env.py | 13 +- policyengine_api/data/orm.py | 4 +- policyengine_api/data/v2/alembic_revision.py | 30 + .../extraction_variables_and_parameters.py | 7 +- .../data/v2/catalog/initialization.py | 52 +- .../data/v2/catalog/publication.py | 154 +- .../data/v2/catalog/publication_inserts.py | 370 ++-- .../publication_parameter_search_file.py | 37 +- .../v2/catalog/publication_parameter_tree.py | 51 +- .../data/v2/catalog/publication_pruning.py | 170 +- .../v2/catalog/publication_reconciliation.py | 448 ++--- .../data/v2/catalog/publication_staging.py | 256 +-- .../v2/catalog/publication_staging_base.py | 178 ++ .../data/v2/catalog/publication_statistics.py | 33 +- .../data/v2/catalog/publication_tables.py | 23 - .../data/v2/catalog/spm_availability.py | 67 +- policyengine_api/data/v2/database.py | 46 +- .../v2/household_migration_qualification.py | 114 +- policyengine_api/data/v2/migration_target.py | 48 +- policyengine_api/data/v2/models/__init__.py | 12 +- policyengine_api/data/v2/pending_revisions.py | 30 + .../data/v2/policy_migration_qualification.py | 116 +- .../data/v2/postgres_system_catalog.py | 88 + .../data/v2/privilege_reconciliation.py | 367 ++-- .../data/v2/privilege_requirements.py | 9 +- ...ser_association_migration_qualification.py | 87 +- .../routes/report_output_routes.py | 4 +- policyengine_api/routes/simulation_routes.py | 4 +- rules/registry.toml | 66 + scripts/process_v1_household_mirror_event.py | 46 +- scripts/v1_database_migration.py | 86 +- .../contract/test_policy_v2_compatibility.py | 6 +- tests/fixtures/database_sessions.py | 217 ++- tests/fixtures/integration/alembic_v2.py | 22 - tests/fixtures/local_v1_database.py | 32 - .../alembic_v2_previous_revision.py | 401 ++++ tests/integration/alembic_version_rows.py | 33 + .../catalog_publication_support.py | 97 + tests/integration/conftest.py | 28 - tests/integration/simulation_rows.py | 16 +- tests/integration/stored_report_rows.py | 3 +- .../test_alembic_mysql_lifecycle.py | 248 ++- .../test_alembic_v2_catalog_tables.py | 538 +++--- .../test_alembic_v2_cliff_impacts.py | 475 ++--- tests/integration/test_alembic_v2_dynamics.py | 305 ++-- .../integration/test_alembic_v2_lifecycle.py | 1609 ++++++++--------- .../test_alembic_v2_saved_item_keys.py | 203 +-- .../test_alembic_v2_shared_report_keys.py | 35 +- .../test_alembic_v2_simulation_runs.py | 590 +++--- .../integration/test_alembic_v2_user_types.py | 202 ++- .../test_alembic_v2_withheld_area_codes.py | 262 +-- .../test_mysql_household_spm_dual_write.py | 104 +- .../test_mysql_policy_dual_write.py | 152 +- .../test_mysql_update_row_counts.py | 211 +-- .../test_v1_household_dual_write.py | 149 +- .../integration/test_v1_policy_dual_write.py | 122 +- .../test_v1_schema_metadata_compatibility.py | 12 +- .../test_v1_user_policy_dual_write.py | 154 +- .../test_v2_budget_window_report_creation.py | 61 +- .../test_v2_budget_window_report_reads.py | 198 +- .../test_v2_catalog_installed_folders.py | 33 +- .../test_v2_catalog_publication.py | 893 ++++----- .../test_v2_catalog_publication_pruning.py | 998 +++++----- ...est_v2_catalog_publication_time_periods.py | 119 +- .../test_v2_catalog_spm_availability.py | 138 +- .../integration/test_v2_catalog_statistics.py | 192 +- tests/integration/test_v2_country_routes.py | 54 +- .../test_v2_dynamic_persistence.py | 100 +- .../test_v2_forced_report_reruns.py | 88 +- .../test_v2_household_calculation_reads.py | 67 +- .../test_v2_household_persistence.py | 106 +- .../integration/test_v2_household_reports.py | 175 +- tests/integration/test_v2_metadata_routes.py | 380 ++-- .../integration/test_v2_policy_persistence.py | 149 +- .../test_v2_privilege_reconciliation.py | 156 +- tests/integration/test_v2_report_creation.py | 81 +- tests/integration/test_v2_report_reads.py | 209 ++- .../test_v2_report_reads_by_run.py | 104 +- tests/integration/test_v2_report_runs.py | 301 +-- .../test_v2_saved_budget_window_reports.py | 94 +- .../test_v2_saved_detailed_save_records.py | 116 +- .../integration/test_v2_shared_report_rows.py | 789 ++++---- .../test_v2_simulation_role_privileges.py | 928 +++++----- .../test_v2_stage12_comparison_persistence.py | 23 +- .../test_v2_user_budget_window_runs.py | 93 +- .../test_v2_user_identity_persistence.py | 119 +- .../test_v2_user_policy_mirroring.py | 155 +- .../test_v2_user_report_run_requesters.py | 112 +- tests/integration/test_v2_user_report_runs.py | 296 ++- .../integration/test_v2_user_report_views.py | 213 +-- .../test_v2_user_type_persistence.py | 153 +- tests/unit/data/fake_driver_connections.py | 93 + tests/unit/data/orm_access_support.py | 4 + tests/unit/data/test_alembic_baseline.py | 9 +- .../data/test_database_access_boundaries.py | 59 +- tests/unit/data/test_orm_pool_events.py | 117 +- tests/unit/data/test_orm_sessions.py | 123 +- tests/unit/data/test_v1_database_migration.py | 50 +- tests/unit/data/test_v1_models.py | 82 +- .../unit/services/test_simulation_service.py | 15 +- tests/unit/test_household_event_command.py | 104 +- tests/unit/v2/qualification_sessions.py | 100 + tests/unit/v2/test_admin_user_deletion.py | 16 +- tests/unit/v2/test_alembic_v2.py | 47 +- tests/unit/v2/test_alembic_v2_revisions.py | 8 +- tests/unit/v2/test_catalog_initialization.py | 86 +- tests/unit/v2/test_catalog_metadata_fields.py | 4 +- tests/unit/v2/test_catalog_publication.py | 158 +- .../unit/v2/test_catalog_spm_availability.py | 24 +- tests/unit/v2/test_catalog_staging_rows.py | 18 +- tests/unit/v2/test_cliff_impact_models.py | 67 +- tests/unit/v2/test_country_service.py | 65 +- tests/unit/v2/test_database.py | 48 +- tests/unit/v2/test_dynamic_catalog.py | 86 +- tests/unit/v2/test_dynamic_table_models.py | 133 +- ...t_household_calculation_database_routes.py | 46 +- .../test_household_migration_qualification.py | 112 +- tests/unit/v2/test_household_models.py | 280 ++- tests/unit/v2/test_household_query.py | 55 +- tests/unit/v2/test_household_report_reads.py | 25 +- .../unit/v2/test_legacy_reference_service.py | 122 +- tests/unit/v2/test_metadata_service.py | 71 +- tests/unit/v2/test_metadata_validation.py | 22 +- tests/unit/v2/test_model_persistence.py | 146 +- tests/unit/v2/test_models.py | 719 ++++---- tests/unit/v2/test_pending_revisions.py | 19 + tests/unit/v2/test_policy_catalog.py | 220 +-- tests/unit/v2/test_policy_legacy_copy.py | 15 +- .../unit/v2/test_policy_legacy_translation.py | 97 +- .../v2/test_policy_migration_qualification.py | 119 +- .../unit/v2/test_policy_missing_parameters.py | 56 +- tests/unit/v2/test_policy_query.py | 63 +- tests/unit/v2/test_privilege_manifest.py | 29 +- .../unit/v2/test_privilege_reconciliation.py | 6 +- tests/unit/v2/test_privilege_requirements.py | 4 +- tests/unit/v2/test_publication_statistics.py | 6 +- tests/unit/v2/test_report_run_creation.py | 43 +- tests/unit/v2/test_report_runs.py | 109 +- tests/unit/v2/test_shared_report_models.py | 90 +- tests/unit/v2/test_simulation_run_models.py | 393 ++-- ...t_simulation_submission_database_routes.py | 47 +- .../v2/test_stage12_comparison_isolation.py | 7 +- .../unit/v2/test_stage12_comparison_models.py | 60 +- ...ser_association_migration_qualification.py | 100 +- tests/unit/v2/test_user_types.py | 5 +- tests/unit/v2/v2_schema_reading.py | 272 +++ 148 files changed, 11574 insertions(+), 10307 deletions(-) create mode 100644 policyengine_api/data/v2/alembic_revision.py create mode 100644 policyengine_api/data/v2/catalog/publication_staging_base.py delete mode 100644 policyengine_api/data/v2/catalog/publication_tables.py create mode 100644 policyengine_api/data/v2/pending_revisions.py create mode 100644 policyengine_api/data/v2/postgres_system_catalog.py delete mode 100644 tests/fixtures/local_v1_database.py create mode 100644 tests/integration/alembic_v2_previous_revision.py create mode 100644 tests/integration/alembic_version_rows.py create mode 100644 tests/integration/catalog_publication_support.py create mode 100644 tests/unit/data/fake_driver_connections.py create mode 100644 tests/unit/v2/qualification_sessions.py create mode 100644 tests/unit/v2/test_pending_revisions.py create mode 100644 tests/unit/v2/v2_schema_reading.py diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 1926328ce..8f32a44a3 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -114,9 +114,9 @@ The entries: Publication writes rows with Postgres `COPY ... FROM STDIN`, which SQLAlchemy has no API for. `copy_rows` in `policyengine_api/data/v2/catalog/publication_staging.py` uses the psycopg - connection beneath a SQLAlchemy `Connection` - (`connection.connection.driver_connection`) that SQLAlchemy opened and still - manages, so the transaction stays SQLAlchemy's. It imports `psycopg.sql` to + connection beneath the Connection the publishing Session holds + (`session.connection().connection.driver_connection`), which SQLAlchemy + opened and still manages, so the transaction stays the Session's. It imports `psycopg.sql` to compose the `COPY` statement and `psycopg.types.json.Jsonb` to send JSON values. 2. **Temporary staging tables** (`schema-change`). `create_staging_tables` in @@ -214,7 +214,11 @@ Two kinds of module have a role of their own: `policyengine_api/data/orm.py` (with `policyengine_api/data/orm_pool_events.py`, whose listeners record the v1 pool's events), `policyengine_api/data/v2/database.py`, and - `tests/fixtures/database_sessions.py` for the tests. They hand out Session + `tests/fixtures/database_sessions.py` for the tests, with + `tests/unit/data/test_orm_pool_events.py`, whose tests drive the pool + `orm_pool_events.py` listens to (they invalidate, detach and recycle + connections and hold two at once, which no Session offers; their statements + still run in Sessions). They hand out Session factories, never an Engine or a Connection. When a module needs its own engine settings, such as `NullPool`, a deploy-time role or a separate URL, the session-factory module gets a function that returns a Session factory @@ -250,11 +254,19 @@ integration fixtures built on it (`tests/integration/conftest.py`): | `sqlite_v2_sessions(foreign_keys=False)` | Session factories of a new in-memory SQLite copy of the v2 schema, whose savepoints behave as on PostgreSQL (Python 3.12's sqlite3 `autocommit=False`); with `foreign_keys`, SQLite enforces the foreign keys. | | `sqlite_v1_sessions(json_serializer=None)` | API v1's Session factories of a new in-memory SQLite copy of its schema, with SQLite numbering policies. | | `serve_v1_sessions(monkeypatch, sessions)` | Makes `orm.get_v1_session_factory()` open `sessions`' connections for the test. | +| `v1_cloud_sql_sessions(monkeypatch, url)` | API v1's own Session factory, its Cloud SQL engine built as in production but connected to the local MySQL server at `url`. | +| `sqlite_v2_file_sessions(path)` | Session factories of a SQLite file copy of the v2 schema, one connection per Session, every transaction starting with `BEGIN IMMEDIATE`, for concurrency tests. | +| `single_connection_v2_sessions(url)` | The owner's Session factories on a pool of exactly one connection, so every Session gets the same pooled connection back. | | `act_as(session, role)`, `act_as_owner(session)` | Act as `role`, or as the database's owner again, until the transaction ends. | | `schema_inspector(source)` | SQLAlchemy's `Inspector` of the database a Session or Session factory uses. | | `recorded_statements(source)` | A context manager yielding the list of SQL statements sent through a Session or Session factory inside it. | +| `recorded_driver_connection_states(source)` | A context manager yielding, for each statement, which driver connection it ran on, its autocommit mode and whether it was inside a transaction. | +| `query_plan(session, statement)` | PostgreSQL's plan (`EXPLAIN`) of an ORM statement, its rows joined. | +| `v2_schema_statements(dialect_name)` | The v2 schema's CREATE statements, compiled for a dialect, with no database. | | `delete_all_rows(session, registry)` | Deletes every row of every table a registry's mapped classes map, such as `V1Base.registry`. | | `truncate(session, *models)` | `TRUNCATE ... CASCADE` of the models' tables. | +| `drop_tables(session, *models)` | `DROP TABLE` of the models' tables, so a later query on them fails with the database's own error. | +| `create_registry_tables(session, registry)`, `drop_registry_tables(session, registry)` | Create a registry's tables (failing if one exists), or drop those that exist, in the Session's transaction, for tables a test declares itself. | | `create_role(session, role)`, `drop_role(session, role)` | Create a role that can't log in; drop what it owns and was granted, then the role. | | `grant(session, privileges, on=Model, to=role)` | `GRANT privileges ON TABLE` the model's table `TO` the role. | | `grant_declared_v2_privileges(url, declared)` | Creates the missing managed roles and grants their declared privileges, as `reconcile_v2_privileges.py apply --create-missing-roles` does. | @@ -316,11 +328,11 @@ finding, and on an entry with an unknown category, a `no-orm-form` entry without a `match` or an existing file, or a `migration-revision` entry that names no file. Only statements SQLAlchemy can't express get an entry: `GRANT` and `REVOKE`, `CREATE`, `ALTER` and `DROP ROLE` (with `DROP OWNED BY`), -`TRUNCATE`, `COPY`, and connection settings no SQL function sets, such as -SQLite's `foreign_keys`. Roles and Postgres settings inside a transaction -need none: `set_config` sets them. Keep the entries in as few modules as -possible: the test session module, `privilege_reconciliation.py` and -`publication_staging.py`. The entries: +`DROP TABLE`, `TRUNCATE`, `COPY`, `EXPLAIN`, `ANALYZE`, Alembic's need for a +Connection, and connection settings no SQL function sets, such as SQLite's +`foreign_keys` and `BEGIN IMMEDIATE`. Roles and Postgres settings inside a +transaction need none: `set_config` sets them. Keep the entries in as few +modules as possible. The entries: 1. **Alembic environments and revisions** (`migration-revision`), `migrations/**/*.py`. The environments run Alembic's migration context on @@ -332,11 +344,34 @@ possible: the test session module, `privilege_reconciliation.py` and table each mapped class maps (`mapper.local_table`) and the tables a declarative base's metadata holds (`class_registry.metadata.tables`). It runs no statement. -3. **The tests' statements with no ORM form** (`no-orm-form`, six entries), +3. **The tests' statements with no ORM form** (`no-orm-form`, nine entries), in `tests/fixtures/database_sessions.py`: SQLite's `PRAGMA foreign_keys` - on each new in-memory connection; `TRUNCATE ... CASCADE` for cleanup; and - `CREATE ROLE`, `DROP OWNED BY`, `DROP ROLE` and `GRANT` for the privilege - tests' temporary roles. + on each new in-memory connection; `BEGIN IMMEDIATE` on the concurrency + test's SQLite file; `TRUNCATE ... CASCADE` for cleanup; `DROP TABLE`, so a + route's catalog query fails with the database's own error; `EXPLAIN`, to + read the plan of an ORM statement; and `CREATE ROLE`, `DROP OWNED BY`, + `DROP ROLE` and `GRANT` for the privilege tests' temporary roles. +4. **Catalog publication** (`no-orm-form`, three entries). + `publication_staging.py` takes the Connection the publishing Session holds + (`session.connection()`) to create the `TEMPORARY` staging tables with + `MetaData.create_all` and to stream rows with `COPY ... FROM STDIN`, on a + cursor of the psycopg connection beneath it (`driver_connection.cursor()`). + `publication_statistics.py` runs one `ANALYZE` of the catalog tables a + publication wrote, after it commits. +5. **Privilege reconciliation** (`no-orm-form`, two entries), in + `privilege_reconciliation.py`: `CREATE ROLE ... NOLOGIN` for missing + managed roles, only in the disposable test database, and the `GRANT` and + `REVOKE` statements `privilege_plans` builds, with identifiers checked by + `safe_identifier` and quoted by the session's dialect. +6. **Alembic's Connection** (`no-orm-form`, two entries). Alembic's + `MigrationContext`, `compare_metadata` and `command.upgrade` take a + Connection, so `pending_revisions.py` (the migration qualification + commands' pending-revision check) and `scripts/v1_database_migration.py` + give them the Connection their Session holds, inside its transaction. +7. **The dialect's name** (`no-orm-form`), in + `services/v2/user_types/database_connectors/reads.py`: + `session.get_bind()` reads it to skip PostgreSQL's advisory lock on the + SQLite test databases. It runs no statement on the engine. A new exception is a rule change: add a `[[rule.exception]]` entry to the rule in `rules/registry.toml`, explain here why the ORM can't express the diff --git a/docs/generated/rules.md b/docs/generated/rules.md index 9c4718945..6ff876860 100644 --- a/docs/generated/rules.md +++ b/docs/generated/rules.md @@ -72,10 +72,21 @@ Every rule that governs `policyengine-api` is listed here with how it is enforce ### Exceptions and review dates - `api.data.orm-only`: exception for `migrations/**/*.py` allowed as a migration-revision (migrations/ holds the Alembic environments and the revisions Alembic generates. The environments run Alembic's migration context on a Connection, and the revisions are where schema changes belong (api.data.sqlalchemy-and-alembic-only), so the rule test doesn't read them.) +- `api.data.orm-only`: exception for `policyengine_api/data/v2/catalog/publication_staging.py` (`driver_connection.cursor()`) allowed as a no-orm-form (COPY ... FROM STDIN has no SQLAlchemy form. Publication runs it through psycopg's Cursor.copy, on a cursor of the driver connection beneath the publishing Session's Connection.) +- `api.data.orm-only`: exception for `policyengine_api/data/v2/catalog/publication_staging.py` (`session.connection()`) allowed as a no-orm-form (Catalog publication creates its TEMPORARY staging tables with MetaData.create_all, which takes a Connection, and streams rows with COPY ... FROM STDIN through the psycopg connection beneath the Connection. Both run on the Connection the publishing Session holds, in its transaction.) +- `api.data.orm-only`: exception for `policyengine_api/data/v2/catalog/publication_statistics.py` (`sa.text(f'ANALYZE {tables}')`) allowed as a no-orm-form (ANALYZE has no ORM form. After a publication commits, one ANALYZE refreshes the planner statistics of the catalog tables it wrote.) +- `api.data.orm-only`: exception for `policyengine_api/data/v2/pending_revisions.py` (`session.connection()`) allowed as a no-orm-form (Alembic's MigrationContext reads the database's current heads from its version table through a Connection. The migration qualification commands give it the Connection their Session holds, so the read runs inside the Session's READ ONLY transaction.) +- `api.data.orm-only`: exception for `policyengine_api/data/v2/privilege_reconciliation.py` (`text(f'CREATE ROLE {quote(safe_identifier(role))} NOLOGIN')`) allowed as a no-orm-form (CREATE ROLE has no SQLAlchemy form. reconcile_v2_privileges.py apply --create-missing-roles creates each missing managed role as NOLOGIN, only in the disposable test database, in the reconciliation's one transaction. The role name is checked by safe_identifier and quoted by the session's dialect.) +- `api.data.orm-only`: exception for `policyengine_api/data/v2/privilege_reconciliation.py` (`text(statement)`) allowed as a no-orm-form (GRANT and REVOKE have no SQLAlchemy form. apply runs the REVOKEs and GRANTs that privilege_plans' revoke_statements and grant_statements build from the declared privileges, with identifiers checked by safe_identifier and quoted by the session's dialect, in the reconciliation's one transaction.) +- `api.data.orm-only`: exception for `policyengine_api/services/v2/user_types/database_connectors/reads.py` (`session.get_bind()`) allowed as a no-orm-form (Reads the dialect's name, to skip PostgreSQL's advisory lock on the SQLite test databases, which have none. It runs no statement on the engine.) +- `api.data.orm-only`: exception for `scripts/v1_database_migration.py` (`session.connection()`) allowed as a no-orm-form (Alembic's MigrationContext, compare_metadata and command.upgrade take a Connection. The v1 schema migration gives them the Connection its Session holds, so the version reads, the schema comparison and the upgrade run in the Session's transaction, under the MySQL named lock the Session took.) +- `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`connection.exec_driver_sql('BEGIN IMMEDIATE')`) allowed as a no-orm-form (SQLite takes its write lock at the start of a transaction only with BEGIN IMMEDIATE, a transaction mode SQLAlchemy's SQLite dialect has no setting for. A concurrency test's file database starts every transaction that way, as SELECT ... FOR UPDATE makes writers wait on PostgreSQL.) - `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`sqlite_connection.execute(...)`) allowed as a no-orm-form (SQLite enforces foreign keys only once a connection sets PRAGMA foreign_keys, a connection setting SQLAlchemy has no API for. The in-memory SQLite test databases set it on each connection before its first transaction.) - `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`text(f'CREATE ROLE {quoted_role} NOLOGIN')`) allowed as a no-orm-form (Roles have no ORM form. Privilege tests create a temporary role that can't log in.) - `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`text(f'DROP OWNED BY {quoted_role}')`) allowed as a no-orm-form (Roles have no ORM form. Privilege tests drop what a temporary role owns and was granted, so the role can be dropped.) - `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`text(f'DROP ROLE {quoted_role}')`) allowed as a no-orm-form (Roles have no ORM form. Privilege tests drop the temporary roles they create.) +- `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`text(f'DROP TABLE {tables}')`) allowed as a no-orm-form (Dropping a table has no ORM form. Route tests drop a catalog table so the route's real catalog query fails with the database's own error.) +- `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`text(f'EXPLAIN {compiled}')`) allowed as a no-orm-form (EXPLAIN has no SQLAlchemy form. A test that checks an index serves a lookup reads PostgreSQL's plan for the ORM statement that does the lookup.) - `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`text(f'GRANT {privileges} ON TABLE {table} TO {quoted_role}')`) allowed as a no-orm-form (Grants have no ORM form. Privilege tests grant a temporary role privileges the manifest doesn't declare, to check that verification reports them.) - `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`text(f'TRUNCATE {tables} CASCADE')`) allowed as a no-orm-form (TRUNCATE has no ORM form. Test cleanup empties a table and every table that refers to it at once, as the catalog tests do after publishing.) - `api.data.orm-only`: exception for `tests/unit/data/orm_access_support.py` (`class_registry.metadata.tables`) allowed as a no-orm-form (The rule's check for tables without a mapped class reads the tables a declarative base's metadata holds, to find those no class maps. It runs no statement.) diff --git a/migrations/v2/env.py b/migrations/v2/env.py index 6f84f08c3..20ff3e93e 100644 --- a/migrations/v2/env.py +++ b/migrations/v2/env.py @@ -8,13 +8,14 @@ from alembic import context from alembic.script import ScriptDirectory from sqlalchemy import create_engine, pool +from sqlmodel import Session from policyengine_api.data.v2.migration_target import ( load_v2_alembic_settings, - qualify_v2_connection, + qualify_v2_target, validate_v2_head_schema, ) -from policyengine_api.data.v2.models import V2_METADATA +from policyengine_api.data.v2.models import V2_METADATA, V2_TABLE_NAMES if TYPE_CHECKING: from alembic.runtime.environment import NameFilterType @@ -42,7 +43,10 @@ def _include_application_object( def _configure(connection: Connection) -> None: - qualify_v2_connection(connection, settings) + # Each Session joins the connection's transaction, and closing it leaves + # that transaction to the environment. + with Session(bind=connection) as session: + qualify_v2_target(session, settings) context.configure( connection=connection, target_metadata=target_metadata, @@ -60,7 +64,8 @@ def _configure(connection: Connection) -> None: current_heads = frozenset(migration_context.get_current_heads()) script_heads = frozenset(script.get_heads()) if current_heads != previous_heads and current_heads == script_heads: - validate_v2_head_schema(connection, target_metadata) + with Session(bind=connection) as session: + validate_v2_head_schema(session, V2_TABLE_NAMES) def run_migrations_offline() -> None: diff --git a/policyengine_api/data/orm.py b/policyengine_api/data/orm.py index e8ad345c1..f6a382c9a 100644 --- a/policyengine_api/data/orm.py +++ b/policyengine_api/data/orm.py @@ -133,7 +133,7 @@ def get_connection() -> DBAPIConnection: return engine -def get_v1_engine() -> Engine: +def _v1_engine() -> Engine: """Return the process-owned Cloud SQL engine; never select SQLite.""" if _cloud_sql_state.engine is None: _cloud_sql_state.engine = _build_remote_engine() @@ -143,7 +143,7 @@ def get_v1_engine() -> Engine: def get_v1_session_factory() -> sessionmaker[Session]: """Return one configured Session factory for the Cloud SQL engine.""" if _cloud_sql_state.session_factory is None: - _cloud_sql_state.session_factory = build_session_factory(get_v1_engine()) + _cloud_sql_state.session_factory = build_session_factory(_v1_engine()) return _cloud_sql_state.session_factory diff --git a/policyengine_api/data/v2/alembic_revision.py b/policyengine_api/data/v2/alembic_revision.py new file mode 100644 index 000000000..c7c9b0feb --- /dev/null +++ b/policyengine_api/data/v2/alembic_revision.py @@ -0,0 +1,30 @@ +"""A read-only mapped class of Alembic's own revision table, ``alembic_version``. + +Alembic creates and writes the table: one row per head revision the database +is at, in its ``version_num`` column. Code reads it through ``AlembicRevision``, +as catalog publication does to check the v2 database's revision before it +writes anything, and never writes it. + +``AlembicRevision`` is on a registry of its own, on neither the v2 metadata +(``V2_METADATA``) nor the publication staging tables' registry, so Alembic never +compares it with the database and no ``create_all`` creates it. It names only +the table and its primary-key column, which API v1's MySQL database and the v2 +PostgreSQL database share. +""" + +from sqlalchemy.orm import registry +from sqlmodel import Field, SQLModel + +ALEMBIC_REVISION_TABLE = "alembic_version" + + +class AlembicRevisionBase(SQLModel, registry=registry()): + """The declarative base of ``AlembicRevision``, on a registry of its own.""" + + +class AlembicRevision(AlembicRevisionBase, table=True): + """One head revision Alembic recorded in ``alembic_version``. Read it only.""" + + __tablename__ = ALEMBIC_REVISION_TABLE + + version_num: str = Field(primary_key=True, max_length=32) diff --git a/policyengine_api/data/v2/catalog/extraction_variables_and_parameters.py b/policyengine_api/data/v2/catalog/extraction_variables_and_parameters.py index 1c6c0e8d8..3bdbcb408 100644 --- a/policyengine_api/data/v2/catalog/extraction_variables_and_parameters.py +++ b/policyengine_api/data/v2/catalog/extraction_variables_and_parameters.py @@ -6,6 +6,8 @@ from datetime import UTC, date, datetime, timedelta from typing import TYPE_CHECKING, Any +from sqlalchemy import inspect + from policyengine_api.data.v2.catalog.extraction_values import ( CatalogExtractionError, catalog_identifier, @@ -27,10 +29,13 @@ if TYPE_CHECKING: from uuid import UUID + from sqlalchemy.orm import Mapper + def _variable_column_length(column_name: str) -> int: """Return the length limit of one text column of the v2 ``variables`` table.""" - length = getattr(Variable.__table__.c[column_name].type, "length", None) + mapper: Mapper[Variable] = inspect(Variable) + length = getattr(mapper.columns[column_name].type, "length", None) if not isinstance(length, int): msg = f"variables.{column_name} has no length limit" raise TypeError(msg) diff --git a/policyengine_api/data/v2/catalog/initialization.py b/policyengine_api/data/v2/catalog/initialization.py index 3f357abdd..fbbe1fc4d 100644 --- a/policyengine_api/data/v2/catalog/initialization.py +++ b/policyengine_api/data/v2/catalog/initialization.py @@ -8,9 +8,6 @@ from dataclasses import dataclass, replace from typing import TYPE_CHECKING -from sqlalchemy import Engine, create_engine -from sqlalchemy.pool import NullPool - from policyengine_api.data.v2.catalog.certified_data_inspection import ( HuggingFaceDataInspector, ) @@ -40,6 +37,10 @@ if TYPE_CHECKING: from collections.abc import Callable, Mapping, Sequence + from contextlib import AbstractContextManager + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session from policyengine_api.data.v2.catalog.publication_types import ( SPMAvailabilityRecording, @@ -54,9 +55,16 @@ PRIVATE_DATA_COUNTRIES = frozenset({"uk"}) -def build_data_write_engine(settings: V2DatabaseSettings) -> Engine: - """Build an isolated, unpooled engine for one initialization attempt.""" - return create_engine(settings.connection.url, poolclass=NullPool) +def data_write_sessions( + settings: V2DatabaseSettings, +) -> AbstractContextManager[sessionmaker[Session]]: + """Return the Session factories of one initialization attempt, as a context. + + Their engine keeps no connection pool and is disposed of on exit. + """ + from policyengine_api.data.v2.database import unpooled_v2_sessions + + return unpooled_v2_sessions(settings.connection.url) def verify_installed_region_data( @@ -90,7 +98,7 @@ def verify_installed_region_data( def verify_unpublished_region_data( - engine: Engine, + sessions: sessionmaker[Session], catalog: NormalizedCatalog, environ: Mapping[str, str] | None = None, ) -> None: @@ -100,7 +108,7 @@ def verify_unpublished_region_data( with what is stored, so their artifacts are not read. """ verify_installed_region_data( - catalog, unpublished_countries(engine, catalog), environ + catalog, unpublished_countries(sessions, catalog), environ ) @@ -115,13 +123,13 @@ class PublicationSteps: """ verify_region_data: Callable[ - [Engine, NormalizedCatalog, Mapping[str, str] | None], None + [sessionmaker[Session], NormalizedCatalog, Mapping[str, str] | None], None ] = verify_unpublished_region_data - publish: Callable[[Engine, NormalizedCatalog], PublicationEvidence] = ( - publish_catalog - ) + publish: Callable[ + [sessionmaker[Session], NormalizedCatalog], PublicationEvidence + ] = publish_catalog record_spm_availability: Callable[ - [Engine, NormalizedCatalog, Mapping[str, str] | None], + [sessionmaker[Session], NormalizedCatalog, Mapping[str, str] | None], SPMAvailabilityRecording, ] = record_published_spm_availability @@ -130,27 +138,27 @@ def initialize_catalog( environ: Mapping[str, str] | None = None, *, extractor: Callable[[], NormalizedCatalog] = extract_installed_catalog, - engine_builder: Callable[[V2DatabaseSettings], Engine] = build_data_write_engine, + sessions_builder: Callable[ + [V2DatabaseSettings], AbstractContextManager[sessionmaker[Session]] + ] = data_write_sessions, steps: PublicationSteps | None = None, ) -> PublicationEvidence: """Load only row-write settings, extract fully, verify, then publish explicitly. After publishing, record each version's SPM availability, which the evidence returned reports. The simulation service's URL, which that - needs, is checked before anything else. + needs, is checked before anything else. Every step uses the Session + factories ``sessions_builder`` opens, which it closes when they end. """ selected_steps = steps or PublicationSteps() settings = load_v2_data_write_database_settings(environ) simulation_entrypoint_url(os.environ if environ is None else environ) catalog = extractor() - engine = engine_builder(settings) - try: - selected_steps.verify_region_data(engine, catalog, environ) - evidence = selected_steps.publish(engine, catalog) - recording = selected_steps.record_spm_availability(engine, catalog, environ) + with sessions_builder(settings) as sessions: + selected_steps.verify_region_data(sessions, catalog, environ) + evidence = selected_steps.publish(sessions, catalog) + recording = selected_steps.record_spm_availability(sessions, catalog, environ) return replace(evidence, spm_availability=recording) - finally: - engine.dispose() def _error_payload(error: Exception) -> dict[str, object]: diff --git a/policyengine_api/data/v2/catalog/publication.py b/policyengine_api/data/v2/catalog/publication.py index 75c51c6f4..318ab7980 100644 --- a/policyengine_api/data/v2/catalog/publication.py +++ b/policyengine_api/data/v2/catalog/publication.py @@ -9,8 +9,12 @@ from typing import TYPE_CHECKING, TypeVar import sqlalchemy as sa -from sqlalchemy import Connection, Engine +from sqlmodel import col +from policyengine_api.data.v2.alembic_revision import ( + ALEMBIC_REVISION_TABLE, + AlembicRevision, +) from policyengine_api.data.v2.catalog.publication_inserts import publish_new_country from policyengine_api.data.v2.catalog.publication_parameter_search_file import ( assert_parameter_search_files_written, @@ -62,6 +66,9 @@ if TYPE_CHECKING: from collections.abc import Callable, Mapping + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + from policyengine_api.data.v2.catalog.publication_pruning import ( PrunedRows, StoredCatalogVersion, @@ -74,16 +81,8 @@ # Stable application-defined PostgreSQL lock ID shared by all v2 catalog publishers. PUBLICATION_ADVISORY_LOCK_KEY = 8_629_020_026_090_001 -ALEMBIC_VERSION = sa.table( - "alembic_version", - sa.column("version_num", sa.String), -) -PROTECTED_TABLES = ( - DatasetVersion.__table__, - Simulation.__table__, - Report.__table__, - ReportRun.__table__, -) +# The tables whose rows publication must leave as they are. +PROTECTED_MODELS = (DatasetVersion, Simulation, Report, ReportRun) LOGGER = logging.getLogger(__name__) ResultT = TypeVar("ResultT") @@ -96,36 +95,37 @@ ] -def _verify_expected_revision(connection: Connection) -> None: - if connection.dialect.name != "postgresql": +def _verify_expected_revision(session: Session) -> None: + from policyengine_api.data.v2.database import v2_schema_inspector + + inspector = v2_schema_inspector(session) + if inspector.dialect.name != "postgresql": msg = "catalog publication requires PostgreSQL" raise CatalogPublicationError(msg) - if not sa.inspect(connection).has_table(ALEMBIC_VERSION.name): + if not inspector.has_table(ALEMBIC_REVISION_TABLE): msg = "the v2 Alembic revision table is absent" raise CatalogPublicationError(msg) - revisions = set( - connection.execute(sa.select(ALEMBIC_VERSION.c.version_num)).scalars() - ) + revisions = set(session.scalars(sa.select(col(AlembicRevision.version_num)))) if revisions != {V2_ALEMBIC_HEAD_REVISION}: msg = "the v2 database is not at the expected Alembic revision" raise CatalogPublicationError(msg) -def _acquire_publication_lock(connection: Connection) -> None: - connection.execute( +def _acquire_publication_lock(session: Session) -> None: + session.execute( sa.select(sa.func.pg_advisory_xact_lock(PUBLICATION_ADVISORY_LOCK_KEY)) ).scalar_one() -def _protected_row_counts(connection: Connection) -> tuple[int, int, int, int]: +def _protected_row_counts(session: Session) -> tuple[int, ...]: return tuple( - connection.execute(sa.select(sa.func.count()).select_from(table)).scalar_one() - for table in PROTECTED_TABLES + session.execute(sa.select(sa.func.count()).select_from(model)).scalar_one() + for model in PROTECTED_MODELS ) def unpublished_countries( - engine: Engine, catalog: NormalizedCatalog + sessions: sessionmaker[Session], catalog: NormalizedCatalog ) -> tuple[str, ...]: """Return the countries whose catalog version is not stored yet, in catalog order. @@ -134,27 +134,27 @@ def unpublished_countries( transaction: a version another publisher adds meanwhile is still compared with the staged one when this one publishes. """ - with engine.connect() as connection: - _verify_expected_revision(connection) + with sessions() as session: + _verify_expected_revision(session) return tuple( country.country_id for country in catalog.countries - if not version_exists(connection, country) + if not version_exists(session, country) ) def publish_catalog( - engine: Engine, + sessions: sessionmaker[Session], catalog: NormalizedCatalog, *, - checkpoint: Callable[[str, Connection], None] | None = None, + checkpoint: Callable[[str, Session], None] | None = None, ) -> PublicationEvidence: """Publish one complete catalog atomically and return non-secret evidence. A catalog version that is already stored is compared with the staged one and left as it is, apart from two exceptions: it keeps the regions it was published with, and it takes the staged time periods - (``metadata_time_periods``), the years the Public API offers for it. + (``metadata_time_periods``), the years API v1 offers for it. In the same transaction it writes the parameter tree and the parameter search file of each version in the catalog that has none, built from the catalog: the versions it publishes, and the installed version when an @@ -174,50 +174,48 @@ def publish_catalog( checks that its role may analyze them. """ started = time.monotonic() - with engine.begin() as connection: - _verify_expected_revision(connection) - _acquire_publication_lock(connection) - require_analyze_privilege(connection) - before = _protected_row_counts(connection) - create_staging_tables(connection) - stage_catalog(connection, catalog, checkpoint=checkpoint) + with sessions.begin() as session: + _verify_expected_revision(session) + _acquire_publication_lock(session) + require_analyze_privilege(session) + before = _protected_row_counts(session) + create_staging_tables(session) + stage_catalog(session, catalog, checkpoint=checkpoint) if checkpoint is not None: - checkpoint("after_copy", connection) + checkpoint("after_copy", session) - restored_versions = restore_pruned_catalog_versions( - connection, catalog.countries - ) - stored_versions = _reconcile_stored_versions(connection, catalog) + restored_versions = restore_pruned_catalog_versions(session, catalog.countries) + stored_versions = _reconcile_stored_versions(session, catalog) existing = stored_versions.countries for country in catalog.countries: if country.country_id not in existing: - publish_new_country(connection, country) - parameter_trees_written = write_parameter_trees(connection, catalog.countries) + publish_new_country(session, country) + parameter_trees_written = write_parameter_trees(session, catalog.countries) parameter_search_files_written = write_parameter_search_files( - connection, catalog.countries + session, catalog.countries ) - record_catalog_publication(connection, catalog.countries) + record_catalog_publication(session, catalog.countries) if checkpoint is not None: - checkpoint("after_reconciliation", connection) + checkpoint("after_reconciliation", session) for country in catalog.countries: assert_country_matches( - connection, + session, country, include_regions=country.country_id not in existing, ) - assert_canonical_value_uniqueness(connection) - assert_parameter_trees_written(connection, catalog.countries) - assert_parameter_search_files_written(connection, catalog.countries) - if _protected_row_counts(connection) != before: + assert_canonical_value_uniqueness(session) + assert_parameter_trees_written(session, catalog.countries) + assert_parameter_search_files_written(session, catalog.countries) + if _protected_row_counts(session) != before: msg = "publication changed simulation, report, or dataset-version rows" raise CatalogPublicationError(msg) if checkpoint is not None: - checkpoint("after_validation", connection) + checkpoint("after_validation", session) - pruning = _prune_older_versions(engine, catalog) - statistics = analyze_catalog_tables(engine) + pruning = _prune_older_versions(sessions, catalog) + statistics = analyze_catalog_tables(sessions) return replace( _evidence( catalog, @@ -248,7 +246,9 @@ class _PruningRun: left_to_prune: int -def _prune_older_versions(engine: Engine, catalog: NormalizedCatalog) -> _PruningRun: +def _prune_older_versions( + sessions: sessionmaker[Session], catalog: NormalizedCatalog +) -> _PruningRun: """Prune the catalog models' older versions, one transaction each. Runs after the publication committed, so an exception, of any kind, never @@ -270,7 +270,7 @@ def _prune_older_versions(engine: Engine, catalog: NormalizedCatalog) -> _Prunin country.model.name: country.country_id for country in catalog.countries } stored_versions = _returned_or_raised( - partial(_read_stored_versions, engine, installed_versions) + partial(_read_stored_versions, sessions, installed_versions) ) if isinstance(stored_versions, Exception): return _PruningRun( @@ -291,7 +291,7 @@ def _prune_older_versions(engine: Engine, catalog: NormalizedCatalog) -> _Prunin deleted = _returned_or_raised( partial( _prune_if_still_chosen, - engine, + sessions, stored, installed_versions[stored.model_name], ) @@ -314,14 +314,16 @@ def _prune_older_versions(engine: Engine, catalog: NormalizedCatalog) -> _Prunin def _read_stored_versions( - engine: Engine, installed_versions: Mapping[str, str] + sessions: sessionmaker[Session], installed_versions: Mapping[str, str] ) -> tuple[StoredCatalogVersion, ...]: - with engine.connect() as connection: - return read_stored_catalog_versions(connection, installed_versions) + with sessions() as session: + return read_stored_catalog_versions(session, installed_versions) def _prune_if_still_chosen( - engine: Engine, stored: StoredCatalogVersion, installed_version: str + sessions: sessionmaker[Session], + stored: StoredCatalogVersion, + installed_version: str, ) -> PrunedRows | None: """Prune one version in its own transaction, if the rule still chooses it. @@ -331,15 +333,15 @@ def _prune_if_still_chosen( returns None, deleting nothing, when ``catalog_versions_to_prune`` no longer chooses the version, or when it was pruned meanwhile. """ - with engine.begin() as connection: - _acquire_publication_lock(connection) - current_versions = read_stored_catalog_versions(connection, [stored.model_name]) + with sessions.begin() as session: + _acquire_publication_lock(session) + current_versions = read_stored_catalog_versions(session, [stored.model_name]) chosen = catalog_versions_to_prune( current_versions, {stored.model_name: installed_version} ) if all(version.id != stored.id for version in chosen): return None - return prune_catalog_version(connection, stored.id) + return prune_catalog_version(session, stored.id) def _returned_or_raised(action: Callable[[], ResultT]) -> ResultT | Exception: @@ -368,14 +370,14 @@ class _StoredVersions: def _reconcile_stored_versions( - connection: Connection, + session: Session, catalog: NormalizedCatalog, ) -> _StoredVersions: """Compare each stored catalog version, then give it the staged time periods. A stored version's regions stay as they were published even when the reference files differ now. Its time periods (``metadata_time_periods``) - become the staged ones, which come from the Public API's code. Every other + become the staged ones, which come from API v1's code. Every other table and column must still match exactly, or CatalogPublicationError is raised before anything is changed. """ @@ -383,15 +385,15 @@ def _reconcile_stored_versions( kept_region_summaries: list[tuple[str, str, int, int]] = [] time_period_updates: list[tuple[str, str, tuple[int, ...], tuple[int, ...]]] = [] for country in catalog.countries: - if version_exists(connection, country): - assert_country_matches(connection, country, include_regions=False) - kept = _kept_region_summary(connection, country) + if version_exists(session, country): + assert_country_matches(session, country, include_regions=False) + kept = _kept_region_summary(session, country) if kept is not None: kept_region_summaries.append(kept) countries.add(country.country_id) for country in catalog.countries: if country.country_id in countries: - update = _time_period_update(connection, country) + update = _time_period_update(session, country) if update is not None: time_period_updates.append(update) return _StoredVersions( @@ -402,7 +404,7 @@ def _reconcile_stored_versions( def _time_period_update( - connection: Connection, + session: Session, country: CountryCatalog, ) -> tuple[str, str, tuple[int, ...], tuple[int, ...]] | None: """Give a stored version the staged time periods, and log any change. @@ -410,7 +412,7 @@ def _time_period_update( Return the country, the version, and the stored and staged time periods when they differed; there is none when they are the same. """ - update = update_stored_time_periods(connection, country) + update = update_stored_time_periods(session, country) if update is None: return None stored, staged = update @@ -490,7 +492,7 @@ def _evidence( def _kept_region_summary( - connection: Connection, + session: Session, country: CountryCatalog, ) -> tuple[str, str, int, int] | None: """Return and log how a stored version's kept regions differ from the staged. @@ -499,7 +501,7 @@ def _kept_region_summary( counts; there is none when the regions are the same. The log names counts only. """ - staged_not_stored, stored_not_staged = count_region_differences(connection, country) + staged_not_stored, stored_not_staged = count_region_differences(session, country) if not staged_not_stored and not stored_not_staged: return None # The seed command configures no logging handler, so the details are in the @@ -523,7 +525,7 @@ def _kept_region_summary( return ( country.country_id, country.model_version.version, - count_stored_regions(connection, country), + count_stored_regions(session, country), len(country.regions), ) diff --git a/policyengine_api/data/v2/catalog/publication_inserts.py b/policyengine_api/data/v2/catalog/publication_inserts.py index 5aa013ab0..984f7a1fd 100644 --- a/policyengine_api/data/v2/catalog/publication_inserts.py +++ b/policyengine_api/data/v2/catalog/publication_inserts.py @@ -2,55 +2,68 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any import sqlalchemy as sa from sqlalchemy.dialects.postgresql import insert as postgresql_insert +from sqlmodel import col -from policyengine_api.data.v2.catalog.publication_staging import ( - STAGE_CATALOG_DATASETS, - STAGE_CATALOG_MODELS, - STAGE_CATALOG_PARAMETER_NODES, - STAGE_CATALOG_PARAMETER_VALUES, - STAGE_CATALOG_PARAMETERS, - STAGE_CATALOG_REGIONS, - STAGE_CATALOG_VARIABLES, +from policyengine_api.data.v2.catalog.publication_staging_base import ( + StagedDataset, + StagedModel, + StagedParameter, + StagedParameterNode, + StagedParameterValue, + StagedRegion, + StagedVariable, ) -from policyengine_api.data.v2.catalog.publication_tables import ( - DATASETS, - MODEL_VERSIONS, - MODELS, - PARAMETER_NODES, - PARAMETER_VALUES, - PARAMETERS, - REGIONS, - VARIABLES, +from policyengine_api.data.v2.models import ( + Dataset, + Parameter, + ParameterNode, + ParameterValue, + Region, + TaxBenefitModel, + TaxBenefitModelVersion, + Variable, ) if TYPE_CHECKING: - from sqlalchemy import Connection + from sqlalchemy.orm import Mapper + from sqlalchemy.types import TypeEngine + from sqlmodel import Session, SQLModel from policyengine_api.data.v2.catalog.records import CountryCatalog -COUNTRY_ID = sa.bindparam("country_id") +COUNTRY_ID: sa.BindParameter[str] = sa.bindparam("country_id") +# How a Session runs these statements: as written, with the country as their +# one parameter. Given parameters, an ORM INSERT otherwise takes them for rows +# to insert (its bulk strategy). +RAW_DML_STRATEGY: dict[str, Any] = {"dml_strategy": "raw"} + + +def column_type(model: type[SQLModel], column_name: str) -> TypeEngine[Any]: + """Return the SQL type of one column of a mapped class's table.""" + mapper: Mapper[Any] = sa.inspect(model) + return mapper.columns[column_name].type INSERT_MODEL = ( - postgresql_insert(MODELS) + postgresql_insert(TaxBenefitModel) .from_select( ["id", "created_at", "updated_at", "name", "description"], sa.select( - STAGE_CATALOG_MODELS.c.id, + col(StagedModel.id), sa.func.current_timestamp(), sa.func.current_timestamp(), - STAGE_CATALOG_MODELS.c.name, - STAGE_CATALOG_MODELS.c.description, - ).where(STAGE_CATALOG_MODELS.c.country_id == COUNTRY_ID), + col(StagedModel.name), + col(StagedModel.description), + ).where(col(StagedModel.country_id) == COUNTRY_ID), ) - .on_conflict_do_nothing(index_elements=[MODELS.c.name]) + .on_conflict_do_nothing(index_elements=[col(TaxBenefitModel.name)]) ) -INSERT_MODEL_VERSION = sa.insert(MODEL_VERSIONS).from_select( +INSERT_MODEL_VERSION = sa.insert(TaxBenefitModelVersion).from_select( [ "id", "created_at", @@ -64,33 +77,36 @@ "basic_inputs", ], sa.select( - STAGE_CATALOG_MODELS.c.version_id, + col(StagedModel.version_id), sa.func.current_timestamp(), - MODELS.c.id, - STAGE_CATALOG_MODELS.c.version, - STAGE_CATALOG_MODELS.c.version_description, - STAGE_CATALOG_MODELS.c.current_law_id, + col(TaxBenefitModel.id), + col(StagedModel.version), + col(StagedModel.version_description), + col(StagedModel.current_law_id), sa.cast( - STAGE_CATALOG_MODELS.c.metadata_time_periods, - MODEL_VERSIONS.c.metadata_time_periods.type, + col(StagedModel.metadata_time_periods), + column_type(TaxBenefitModelVersion, "metadata_time_periods"), ), - STAGE_CATALOG_MODELS.c.catalog_format, - sa.cast(STAGE_CATALOG_MODELS.c.entities, MODEL_VERSIONS.c.entities.type), + col(StagedModel.catalog_format), sa.cast( - STAGE_CATALOG_MODELS.c.basic_inputs, - MODEL_VERSIONS.c.basic_inputs.type, + col(StagedModel.entities), column_type(TaxBenefitModelVersion, "entities") + ), + sa.cast( + col(StagedModel.basic_inputs), + column_type(TaxBenefitModelVersion, "basic_inputs"), ), ) .select_from( - STAGE_CATALOG_MODELS.join( - MODELS, - MODELS.c.name == STAGE_CATALOG_MODELS.c.name, + sa.join( + StagedModel, + TaxBenefitModel, + col(TaxBenefitModel.name) == col(StagedModel.name), ) ) - .where(STAGE_CATALOG_MODELS.c.country_id == COUNTRY_ID), + .where(col(StagedModel.country_id) == COUNTRY_ID), ) -INSERT_DATASETS = sa.insert(DATASETS).from_select( +INSERT_DATASETS = sa.insert(Dataset).from_select( [ "id", "created_at", @@ -103,34 +119,35 @@ "tax_benefit_model_version_id", ], sa.select( - STAGE_CATALOG_DATASETS.c.id, + col(StagedDataset.id), sa.func.current_timestamp(), sa.func.current_timestamp(), - STAGE_CATALOG_DATASETS.c.name, - STAGE_CATALOG_DATASETS.c.description, - sa.cast(sa.null(), DATASETS.c.storage_path.type), - STAGE_CATALOG_DATASETS.c.year, + col(StagedDataset.name), + col(StagedDataset.description), + sa.cast(sa.null(), column_type(Dataset, "storage_path")), + col(StagedDataset.year), sa.literal(value=False), - MODEL_VERSIONS.c.id, + col(TaxBenefitModelVersion.id), ) .select_from( - STAGE_CATALOG_DATASETS.join( - STAGE_CATALOG_MODELS, - STAGE_CATALOG_MODELS.c.country_id == STAGE_CATALOG_DATASETS.c.country_id, + sa.join( + StagedDataset, + StagedModel, + col(StagedModel.country_id) == col(StagedDataset.country_id), ) - .join(MODELS, MODELS.c.name == STAGE_CATALOG_MODELS.c.name) + .join(TaxBenefitModel, col(TaxBenefitModel.name) == col(StagedModel.name)) .join( - MODEL_VERSIONS, + TaxBenefitModelVersion, sa.and_( - MODEL_VERSIONS.c.model_id == MODELS.c.id, - MODEL_VERSIONS.c.version == STAGE_CATALOG_MODELS.c.version, + col(TaxBenefitModelVersion.model_id) == col(TaxBenefitModel.id), + col(TaxBenefitModelVersion.version) == col(StagedModel.version), ), ) ) - .where(STAGE_CATALOG_DATASETS.c.country_id == COUNTRY_ID), + .where(col(StagedDataset.country_id) == COUNTRY_ID), ) -INSERT_VARIABLES = sa.insert(VARIABLES).from_select( +INSERT_VARIABLES = sa.insert(Variable).from_select( [ "id", "created_at", @@ -154,57 +171,58 @@ "tax_benefit_model_version_id", ], sa.select( - STAGE_CATALOG_VARIABLES.c.id, + col(StagedVariable.id), sa.func.current_timestamp(), - STAGE_CATALOG_VARIABLES.c.name, - STAGE_CATALOG_VARIABLES.c.label, - STAGE_CATALOG_VARIABLES.c.entity, - STAGE_CATALOG_VARIABLES.c.description, - STAGE_CATALOG_VARIABLES.c.data_type, + col(StagedVariable.name), + col(StagedVariable.label), + col(StagedVariable.entity), + col(StagedVariable.description), + col(StagedVariable.data_type), sa.cast( - STAGE_CATALOG_VARIABLES.c.possible_values, - VARIABLES.c.possible_values.type, + col(StagedVariable.possible_values), + column_type(Variable, "possible_values"), ), sa.cast( - STAGE_CATALOG_VARIABLES.c.default_value, - VARIABLES.c.default_value.type, + col(StagedVariable.default_value), + column_type(Variable, "default_value"), ), - sa.cast(STAGE_CATALOG_VARIABLES.c.adds, VARIABLES.c.adds.type), + sa.cast(col(StagedVariable.adds), column_type(Variable, "adds")), sa.cast( - STAGE_CATALOG_VARIABLES.c.subtracts, - VARIABLES.c.subtracts.type, + col(StagedVariable.subtracts), + column_type(Variable, "subtracts"), ), - STAGE_CATALOG_VARIABLES.c.is_input_variable, - STAGE_CATALOG_VARIABLES.c.hidden_input, - STAGE_CATALOG_VARIABLES.c.module_name, - STAGE_CATALOG_VARIABLES.c.adds_parameter_path, - STAGE_CATALOG_VARIABLES.c.subtracts_parameter_path, + col(StagedVariable.is_input_variable), + col(StagedVariable.hidden_input), + col(StagedVariable.module_name), + col(StagedVariable.adds_parameter_path), + col(StagedVariable.subtracts_parameter_path), sa.cast( - STAGE_CATALOG_VARIABLES.c.enum_values, - VARIABLES.c.enum_values.type, + col(StagedVariable.enum_values), + column_type(Variable, "enum_values"), ), - STAGE_CATALOG_VARIABLES.c.unit, - STAGE_CATALOG_VARIABLES.c.definition_period, - MODEL_VERSIONS.c.id, + col(StagedVariable.unit), + col(StagedVariable.definition_period), + col(TaxBenefitModelVersion.id), ) .select_from( - STAGE_CATALOG_VARIABLES.join( - STAGE_CATALOG_MODELS, - STAGE_CATALOG_MODELS.c.country_id == STAGE_CATALOG_VARIABLES.c.country_id, + sa.join( + StagedVariable, + StagedModel, + col(StagedModel.country_id) == col(StagedVariable.country_id), ) - .join(MODELS, MODELS.c.name == STAGE_CATALOG_MODELS.c.name) + .join(TaxBenefitModel, col(TaxBenefitModel.name) == col(StagedModel.name)) .join( - MODEL_VERSIONS, + TaxBenefitModelVersion, sa.and_( - MODEL_VERSIONS.c.model_id == MODELS.c.id, - MODEL_VERSIONS.c.version == STAGE_CATALOG_MODELS.c.version, + col(TaxBenefitModelVersion.model_id) == col(TaxBenefitModel.id), + col(TaxBenefitModelVersion.version) == col(StagedModel.version), ), ) ) - .where(STAGE_CATALOG_VARIABLES.c.country_id == COUNTRY_ID), + .where(col(StagedVariable.country_id) == COUNTRY_ID), ) -INSERT_PARAMETER_NODES = sa.insert(PARAMETER_NODES).from_select( +INSERT_PARAMETER_NODES = sa.insert(ParameterNode).from_select( [ "id", "created_at", @@ -214,32 +232,32 @@ "tax_benefit_model_version_id", ], sa.select( - STAGE_CATALOG_PARAMETER_NODES.c.id, + col(StagedParameterNode.id), sa.func.current_timestamp(), - STAGE_CATALOG_PARAMETER_NODES.c.name, - STAGE_CATALOG_PARAMETER_NODES.c.label, - STAGE_CATALOG_PARAMETER_NODES.c.description, - MODEL_VERSIONS.c.id, + col(StagedParameterNode.name), + col(StagedParameterNode.label), + col(StagedParameterNode.description), + col(TaxBenefitModelVersion.id), ) .select_from( - STAGE_CATALOG_PARAMETER_NODES.join( - STAGE_CATALOG_MODELS, - STAGE_CATALOG_MODELS.c.country_id - == STAGE_CATALOG_PARAMETER_NODES.c.country_id, + sa.join( + StagedParameterNode, + StagedModel, + col(StagedModel.country_id) == col(StagedParameterNode.country_id), ) - .join(MODELS, MODELS.c.name == STAGE_CATALOG_MODELS.c.name) + .join(TaxBenefitModel, col(TaxBenefitModel.name) == col(StagedModel.name)) .join( - MODEL_VERSIONS, + TaxBenefitModelVersion, sa.and_( - MODEL_VERSIONS.c.model_id == MODELS.c.id, - MODEL_VERSIONS.c.version == STAGE_CATALOG_MODELS.c.version, + col(TaxBenefitModelVersion.model_id) == col(TaxBenefitModel.id), + col(TaxBenefitModelVersion.version) == col(StagedModel.version), ), ) ) - .where(STAGE_CATALOG_PARAMETER_NODES.c.country_id == COUNTRY_ID), + .where(col(StagedParameterNode.country_id) == COUNTRY_ID), ) -INSERT_PARAMETERS = sa.insert(PARAMETERS).from_select( +INSERT_PARAMETERS = sa.insert(Parameter).from_select( [ "id", "created_at", @@ -253,35 +271,36 @@ "tax_benefit_model_version_id", ], sa.select( - STAGE_CATALOG_PARAMETERS.c.id, + col(StagedParameter.id), sa.func.current_timestamp(), - STAGE_CATALOG_PARAMETERS.c.name, - STAGE_CATALOG_PARAMETERS.c.label, - STAGE_CATALOG_PARAMETERS.c.description, - STAGE_CATALOG_PARAMETERS.c.data_type, - STAGE_CATALOG_PARAMETERS.c.unit, - STAGE_CATALOG_PARAMETERS.c.economy, - STAGE_CATALOG_PARAMETERS.c.household, - MODEL_VERSIONS.c.id, + col(StagedParameter.name), + col(StagedParameter.label), + col(StagedParameter.description), + col(StagedParameter.data_type), + col(StagedParameter.unit), + col(StagedParameter.economy), + col(StagedParameter.household), + col(TaxBenefitModelVersion.id), ) .select_from( - STAGE_CATALOG_PARAMETERS.join( - STAGE_CATALOG_MODELS, - STAGE_CATALOG_MODELS.c.country_id == STAGE_CATALOG_PARAMETERS.c.country_id, + sa.join( + StagedParameter, + StagedModel, + col(StagedModel.country_id) == col(StagedParameter.country_id), ) - .join(MODELS, MODELS.c.name == STAGE_CATALOG_MODELS.c.name) + .join(TaxBenefitModel, col(TaxBenefitModel.name) == col(StagedModel.name)) .join( - MODEL_VERSIONS, + TaxBenefitModelVersion, sa.and_( - MODEL_VERSIONS.c.model_id == MODELS.c.id, - MODEL_VERSIONS.c.version == STAGE_CATALOG_MODELS.c.version, + col(TaxBenefitModelVersion.model_id) == col(TaxBenefitModel.id), + col(TaxBenefitModelVersion.version) == col(StagedModel.version), ), ) ) - .where(STAGE_CATALOG_PARAMETERS.c.country_id == COUNTRY_ID), + .where(col(StagedParameter.country_id) == COUNTRY_ID), ) -INSERT_PARAMETER_VALUES = sa.insert(PARAMETER_VALUES).from_select( +INSERT_PARAMETER_VALUES = sa.insert(ParameterValue).from_select( [ "id", "created_at", @@ -293,44 +312,45 @@ "dynamic_id", ], sa.select( - STAGE_CATALOG_PARAMETER_VALUES.c.id, + col(StagedParameterValue.id), sa.func.current_timestamp(), - PARAMETERS.c.id, + col(Parameter.id), sa.cast( - STAGE_CATALOG_PARAMETER_VALUES.c.value_json, - PARAMETER_VALUES.c.value_json.type, + col(StagedParameterValue.value_json), + column_type(ParameterValue, "value_json"), ), - STAGE_CATALOG_PARAMETER_VALUES.c.start_date, - STAGE_CATALOG_PARAMETER_VALUES.c.end_date, - sa.cast(sa.null(), PARAMETER_VALUES.c.policy_id.type), - sa.cast(sa.null(), PARAMETER_VALUES.c.dynamic_id.type), + col(StagedParameterValue.start_date), + col(StagedParameterValue.end_date), + sa.cast(sa.null(), column_type(ParameterValue, "policy_id")), + sa.cast(sa.null(), column_type(ParameterValue, "dynamic_id")), ) .select_from( - STAGE_CATALOG_PARAMETER_VALUES.join( - STAGE_CATALOG_MODELS, - STAGE_CATALOG_MODELS.c.country_id - == STAGE_CATALOG_PARAMETER_VALUES.c.country_id, + sa.join( + StagedParameterValue, + StagedModel, + col(StagedModel.country_id) == col(StagedParameterValue.country_id), ) - .join(MODELS, MODELS.c.name == STAGE_CATALOG_MODELS.c.name) + .join(TaxBenefitModel, col(TaxBenefitModel.name) == col(StagedModel.name)) .join( - MODEL_VERSIONS, + TaxBenefitModelVersion, sa.and_( - MODEL_VERSIONS.c.model_id == MODELS.c.id, - MODEL_VERSIONS.c.version == STAGE_CATALOG_MODELS.c.version, + col(TaxBenefitModelVersion.model_id) == col(TaxBenefitModel.id), + col(TaxBenefitModelVersion.version) == col(StagedModel.version), ), ) .join( - PARAMETERS, + Parameter, sa.and_( - PARAMETERS.c.tax_benefit_model_version_id == MODEL_VERSIONS.c.id, - PARAMETERS.c.name == STAGE_CATALOG_PARAMETER_VALUES.c.parameter_name, + col(Parameter.tax_benefit_model_version_id) + == col(TaxBenefitModelVersion.id), + col(Parameter.name) == col(StagedParameterValue.parameter_name), ), ) ) - .where(STAGE_CATALOG_PARAMETER_VALUES.c.country_id == COUNTRY_ID), + .where(col(StagedParameterValue.country_id) == COUNTRY_ID), ) -INSERT_REGIONS = sa.insert(REGIONS).from_select( +INSERT_REGIONS = sa.insert(Region).from_select( [ "id", "created_at", @@ -349,44 +369,46 @@ "default_dataset_id", ], sa.select( - STAGE_CATALOG_REGIONS.c.id, + col(StagedRegion.id), sa.func.current_timestamp(), sa.func.current_timestamp(), - STAGE_CATALOG_REGIONS.c.code, - STAGE_CATALOG_REGIONS.c.label, - sa.cast(STAGE_CATALOG_REGIONS.c.region_type, REGIONS.c.region_type.type), - STAGE_CATALOG_REGIONS.c.requires_filter, - STAGE_CATALOG_REGIONS.c.filter_field, - STAGE_CATALOG_REGIONS.c.filter_value, - STAGE_CATALOG_REGIONS.c.filter_strategy, - STAGE_CATALOG_REGIONS.c.parent_code, - STAGE_CATALOG_REGIONS.c.state_code, - STAGE_CATALOG_REGIONS.c.state_name, - MODEL_VERSIONS.c.id, - DATASETS.c.id, + col(StagedRegion.code), + col(StagedRegion.label), + sa.cast(col(StagedRegion.region_type), column_type(Region, "region_type")), + col(StagedRegion.requires_filter), + col(StagedRegion.filter_field), + col(StagedRegion.filter_value), + col(StagedRegion.filter_strategy), + col(StagedRegion.parent_code), + col(StagedRegion.state_code), + col(StagedRegion.state_name), + col(TaxBenefitModelVersion.id), + col(Dataset.id), ) .select_from( - STAGE_CATALOG_REGIONS.join( - STAGE_CATALOG_MODELS, - STAGE_CATALOG_MODELS.c.country_id == STAGE_CATALOG_REGIONS.c.country_id, + sa.join( + StagedRegion, + StagedModel, + col(StagedModel.country_id) == col(StagedRegion.country_id), ) - .join(MODELS, MODELS.c.name == STAGE_CATALOG_MODELS.c.name) + .join(TaxBenefitModel, col(TaxBenefitModel.name) == col(StagedModel.name)) .join( - MODEL_VERSIONS, + TaxBenefitModelVersion, sa.and_( - MODEL_VERSIONS.c.model_id == MODELS.c.id, - MODEL_VERSIONS.c.version == STAGE_CATALOG_MODELS.c.version, + col(TaxBenefitModelVersion.model_id) == col(TaxBenefitModel.id), + col(TaxBenefitModelVersion.version) == col(StagedModel.version), ), ) .join( - DATASETS, + Dataset, sa.and_( - DATASETS.c.tax_benefit_model_version_id == MODEL_VERSIONS.c.id, - DATASETS.c.name == STAGE_CATALOG_REGIONS.c.default_dataset_name, + col(Dataset.tax_benefit_model_version_id) + == col(TaxBenefitModelVersion.id), + col(Dataset.name) == col(StagedRegion.default_dataset_name), ), ) ) - .where(STAGE_CATALOG_REGIONS.c.country_id == COUNTRY_ID), + .where(col(StagedRegion.country_id) == COUNTRY_ID), ) SET_BASED_INSERT_STATEMENTS = ( @@ -401,10 +423,16 @@ ) -def publish_new_country(connection: Connection, country: CountryCatalog) -> None: +def publish_new_country(session: Session, country: CountryCatalog) -> None: """Insert one country's staged catalog into the v2 tables, parents first. - The model row is reused if one with the same name already exists. + The model row is reused if one with the same name already exists. Each + statement is one ``INSERT ... SELECT`` from the staging tables, so no row + passes through Python. """ for statement in SET_BASED_INSERT_STATEMENTS: - connection.execute(statement, {"country_id": country.country_id}) + session.execute( + statement, + {"country_id": country.country_id}, + execution_options=RAW_DML_STRATEGY, + ) diff --git a/policyengine_api/data/v2/catalog/publication_parameter_search_file.py b/policyengine_api/data/v2/catalog/publication_parameter_search_file.py index 4bbda947e..cdbf44c8e 100644 --- a/policyengine_api/data/v2/catalog/publication_parameter_search_file.py +++ b/policyengine_api/data/v2/catalog/publication_parameter_search_file.py @@ -20,6 +20,7 @@ from uuid import uuid4 import sqlalchemy as sa +from sqlmodel import col from policyengine_api.data.v2.catalog.parameter_search_file import ( PARAMETER_SEARCH_FILE_FORMAT, @@ -33,23 +34,21 @@ from policyengine_api.data.v2.catalog.publication_types import ( CatalogPublicationError, ) -from policyengine_api.data.v2.models import V2_METADATA +from policyengine_api.data.v2.models import ParameterSearchFile if TYPE_CHECKING: from collections.abc import Sequence from uuid import UUID - from sqlalchemy import Connection + from sqlmodel import Session from policyengine_api.data.v2.catalog.records import CountryCatalog -PARAMETER_SEARCH_FILES = V2_METADATA.tables["parameter_search_files"] - def _version_for_search_file( - connection: Connection, country: CountryCatalog + session: Session, country: CountryCatalog ) -> StoredVersion: - stored = stored_version(connection, country) + stored = stored_version(session, country) if stored is None: msg = ( f"the {country.country_id} catalog version " @@ -59,18 +58,18 @@ def _version_for_search_file( return stored -def _stored_content_sha256(connection: Connection, version_id: UUID) -> str | None: - content_sha256: str | None = connection.execute( - sa.select(PARAMETER_SEARCH_FILES.c.content_sha256).where( - PARAMETER_SEARCH_FILES.c.tax_benefit_model_version_id == version_id, - PARAMETER_SEARCH_FILES.c.file_format == PARAMETER_SEARCH_FILE_FORMAT, +def _stored_content_sha256(session: Session, version_id: UUID) -> str | None: + content_sha256: str | None = session.execute( + sa.select(col(ParameterSearchFile.content_sha256)).where( + col(ParameterSearchFile.tax_benefit_model_version_id) == version_id, + col(ParameterSearchFile.file_format) == PARAMETER_SEARCH_FILE_FORMAT, ) ).scalar_one_or_none() return content_sha256 def write_parameter_search_files( - connection: Connection, + session: Session, countries: Sequence[CountryCatalog], ) -> tuple[tuple[str, str, int, int], ...]: """Write the search file of each published format 2 version that has none. @@ -81,14 +80,14 @@ def write_parameter_search_files( """ written = [] for country in sorted(countries, key=lambda item: item.model.name): - stored = _version_for_search_file(connection, country) + stored = _version_for_search_file(session, country) if stored.catalog_format is None: continue encoded = encode_parameter_search_file(country_search_file(country)) - stored_sha256 = _stored_content_sha256(connection, stored.id) + stored_sha256 = _stored_content_sha256(session, stored.id) if stored_sha256 is None: - connection.execute( - sa.insert(PARAMETER_SEARCH_FILES).values( + session.execute( + sa.insert(ParameterSearchFile).values( id=uuid4(), tax_benefit_model_version_id=stored.id, file_format=PARAMETER_SEARCH_FILE_FORMAT, @@ -117,7 +116,7 @@ def write_parameter_search_files( def assert_parameter_search_files_written( - connection: Connection, + session: Session, countries: Sequence[CountryCatalog], ) -> None: """Raise CatalogPublicationError if a catalog country's version has no file. @@ -125,10 +124,10 @@ def assert_parameter_search_files_written( A version stored before catalog format 2 is exempt: it gets no file. """ for country in countries: - stored = _version_for_search_file(connection, country) + stored = _version_for_search_file(session, country) if stored.catalog_format is None: continue - if _stored_content_sha256(connection, stored.id) is None: + if _stored_content_sha256(session, stored.id) is None: msg = ( f"the {country.country_id} catalog version " f"{country.model_version.version} has no parameter search file" diff --git a/policyengine_api/data/v2/catalog/publication_parameter_tree.py b/policyengine_api/data/v2/catalog/publication_parameter_tree.py index 3d07ef123..7b5dc1338 100644 --- a/policyengine_api/data/v2/catalog/publication_parameter_tree.py +++ b/policyengine_api/data/v2/catalog/publication_parameter_tree.py @@ -25,6 +25,7 @@ from uuid import uuid4 import sqlalchemy as sa +from sqlmodel import col from policyengine_api.data.v2.catalog.parameter_tree import ( ParameterTreeChildRow, @@ -36,7 +37,10 @@ StoredVersion, stored_version, ) -from policyengine_api.data.v2.catalog.publication_staging import copy_rows +from policyengine_api.data.v2.catalog.publication_staging import ( + column_names, + copy_rows, +) from policyengine_api.data.v2.catalog.publication_types import ( CatalogPublicationError, ) @@ -49,16 +53,13 @@ from collections.abc import Iterator, Sequence from uuid import UUID - from sqlalchemy import Connection + from sqlmodel import Session from policyengine_api.data.v2.catalog.records import CountryCatalog -PARAMETERS = Parameter.__table__ -PARAMETER_TREE_CHILDREN = ParameterTreeChild.__table__ - -def _version_for_tree(connection: Connection, country: CountryCatalog) -> StoredVersion: - stored = stored_version(connection, country) +def _version_for_tree(session: Session, country: CountryCatalog) -> StoredVersion: + stored = stored_version(session, country) if stored is None: msg = ( f"the {country.country_id} catalog version " @@ -68,24 +69,24 @@ def _version_for_tree(connection: Connection, country: CountryCatalog) -> Stored return stored -def _has_tree(connection: Connection, version_id: UUID) -> bool: +def _has_tree(session: Session, version_id: UUID) -> bool: return bool( - connection.execute( + session.execute( sa.select( sa.exists().where( - PARAMETER_TREE_CHILDREN.c.tax_benefit_model_version_id == version_id + col(ParameterTreeChild.tax_benefit_model_version_id) == version_id ) ) ).scalar_one() ) -def _stored_parameter_ids(connection: Connection, version_id: UUID) -> dict[str, UUID]: +def _stored_parameter_ids(session: Session, version_id: UUID) -> dict[str, UUID]: return { row.name: row.id - for row in connection.execute( - sa.select(PARAMETERS.c.name, PARAMETERS.c.id).where( - PARAMETERS.c.tax_benefit_model_version_id == version_id + for row in session.execute( + sa.select(col(Parameter.name), col(Parameter.id)).where( + col(Parameter.tax_benefit_model_version_id) == version_id ) ) } @@ -144,7 +145,7 @@ def _table_rows( rows: tuple[ParameterTreeChildRow, ...], ) -> Iterator[tuple[object, ...]]: created_at = datetime.now(UTC) - column_names = [column.name for column in PARAMETER_TREE_CHILDREN.columns] + names = column_names(ParameterTreeChild) for row in rows: values: dict[str, object] = { "id": uuid4(), @@ -162,11 +163,11 @@ def _table_rows( "economy": row.economy, "household": row.household, } - yield tuple(values[name] for name in column_names) + yield tuple(values[name] for name in names) def write_parameter_trees( - connection: Connection, + session: Session, countries: Sequence[CountryCatalog], ) -> tuple[tuple[str, str, int], ...]: """Write the tree of each catalog country's stored version that has none. @@ -179,15 +180,15 @@ def write_parameter_trees( """ written = [] for country in countries: - stored = _version_for_tree(connection, country) - if stored.catalog_format is None or _has_tree(connection, stored.id): + stored = _version_for_tree(session, country) + if stored.catalog_format is None or _has_tree(session, stored.id): continue rows = catalog_parameter_tree( - country, _stored_parameter_ids(connection, stored.id) + country, _stored_parameter_ids(session, stored.id) ) count = copy_rows( - connection, - table=PARAMETER_TREE_CHILDREN, + session, + model=ParameterTreeChild, rows=_table_rows(stored.id, rows), ) written.append((country.model.name, country.model_version.version, count)) @@ -195,7 +196,7 @@ def write_parameter_trees( def assert_parameter_trees_written( - connection: Connection, + session: Session, countries: Sequence[CountryCatalog], ) -> None: """Raise CatalogPublicationError if a catalog country's version has no tree. @@ -203,8 +204,8 @@ def assert_parameter_trees_written( Versions stored before catalog format 2 are exempt: they get no tree. """ for country in countries: - stored = _version_for_tree(connection, country) - if stored.catalog_format is not None and not _has_tree(connection, stored.id): + stored = _version_for_tree(session, country) + if stored.catalog_format is not None and not _has_tree(session, stored.id): msg = ( f"the {country.country_id} catalog version " f"{country.model_version.version} has no parameter tree" diff --git a/policyengine_api/data/v2/catalog/publication_pruning.py b/policyengine_api/data/v2/catalog/publication_pruning.py index 2fd089ee5..4f141b215 100644 --- a/policyengine_api/data/v2/catalog/publication_pruning.py +++ b/policyengine_api/data/v2/catalog/publication_pruning.py @@ -33,36 +33,42 @@ from collections import defaultdict from dataclasses import dataclass -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any, cast import sqlalchemy as sa from sqlalchemy.exc import SQLAlchemyError +from sqlmodel import col from policyengine_api.data.v2.catalog.publication_inserts import ( INSERT_PARAMETER_VALUES, -) -from policyengine_api.data.v2.catalog.publication_tables import ( - MODEL_VERSIONS, - MODELS, - PARAMETER_VALUES, - PARAMETERS, + RAW_DML_STRATEGY, ) from policyengine_api.data.v2.catalog.publication_types import ( CatalogPruningFailure, ) -from policyengine_api.data.v2.models import V2_METADATA +from policyengine_api.data.v2.models import ( + Parameter, + ParameterSearchFile, + ParameterTreeChild, + ParameterValue, + TaxBenefitModel, + TaxBenefitModelVersion, +) if TYPE_CHECKING: from collections.abc import Iterable, Mapping, Sequence from datetime import datetime from uuid import UUID - from sqlalchemy import Connection + from sqlalchemy import Delete, Update + from sqlalchemy.engine import CursorResult + from sqlmodel import Session from policyengine_api.data.v2.catalog.records import CountryCatalog -PARAMETER_TREE_CHILDREN = V2_METADATA.tables["parameter_tree_children"] -PARAMETER_SEARCH_FILES = V2_METADATA.tables["parameter_search_files"] +# Set-based UPDATEs and DELETEs run as written: no row they change is loaded +# in the Session, so the ORM need not find and refresh any. +SET_BASED = {"synchronize_session": False} KEPT_OTHER_CATALOG_VERSIONS = 2 """How many most recently published versions, besides the installed one, are kept. @@ -182,22 +188,26 @@ def catalog_versions_to_prune_now( def read_stored_catalog_versions( - connection: Connection, model_names: Iterable[str] + session: Session, model_names: Iterable[str] ) -> tuple[StoredCatalogVersion, ...]: """Return every stored version of the named models.""" - rows = connection.execute( + rows = session.execute( sa.select( - MODEL_VERSIONS.c.id, - MODELS.c.name, - MODEL_VERSIONS.c.version, - MODEL_VERSIONS.c.created_at, - MODEL_VERSIONS.c.catalog_values_pruned_at, - MODEL_VERSIONS.c.catalog_last_published_at, + col(TaxBenefitModelVersion.id), + col(TaxBenefitModel.name), + col(TaxBenefitModelVersion.version), + col(TaxBenefitModelVersion.created_at), + col(TaxBenefitModelVersion.catalog_values_pruned_at), + col(TaxBenefitModelVersion.catalog_last_published_at), ) .select_from( - MODEL_VERSIONS.join(MODELS, MODELS.c.id == MODEL_VERSIONS.c.model_id) + sa.join( + TaxBenefitModelVersion, + TaxBenefitModel, + col(TaxBenefitModel.id) == col(TaxBenefitModelVersion.model_id), + ) ) - .where(MODELS.c.name.in_(list(model_names))) + .where(col(TaxBenefitModel.name).in_(list(model_names))) ) return tuple( StoredCatalogVersion( @@ -213,7 +223,7 @@ def read_stored_catalog_versions( def record_catalog_publication( - connection: Connection, countries: Sequence[CountryCatalog] + session: Session, countries: Sequence[CountryCatalog] ) -> None: """Record that this publication published each catalog country's version. @@ -223,21 +233,22 @@ def record_catalog_publication( transaction, after the versions are stored. """ for country in countries: - connection.execute( - sa.update(MODEL_VERSIONS) + _changed_rows( + session, + sa.update(TaxBenefitModelVersion) .where( - MODEL_VERSIONS.c.version == country.model_version.version, - MODEL_VERSIONS.c.model_id.in_( - sa.select(MODELS.c.id).where(MODELS.c.name == country.model.name) + col(TaxBenefitModelVersion.version) == country.model_version.version, + col(TaxBenefitModelVersion.model_id).in_( + sa.select(col(TaxBenefitModel.id)).where( + col(TaxBenefitModel.name) == country.model.name + ) ), ) - .values(catalog_last_published_at=sa.func.current_timestamp()) + .values(catalog_last_published_at=sa.func.current_timestamp()), ) -def prune_catalog_version( - connection: Connection, version_id: UUID -) -> PrunedRows | None: +def prune_catalog_version(session: Session, version_id: UUID) -> PrunedRows | None: """Delete one version's current-law values, tree rows and search files. Sets the version's ``catalog_values_pruned_at`` first, only if it is @@ -245,41 +256,45 @@ def prune_catalog_version( Runs in the caller's transaction, which holds the publication lock, so the deletes and the marker commit or roll back together. """ - marked = connection.execute( - sa.update(MODEL_VERSIONS) + marked = _changed_rows( + session, + sa.update(TaxBenefitModelVersion) .where( - MODEL_VERSIONS.c.id == version_id, - MODEL_VERSIONS.c.catalog_values_pruned_at.is_(None), + col(TaxBenefitModelVersion.id) == version_id, + col(TaxBenefitModelVersion.catalog_values_pruned_at).is_(None), ) - .values(catalog_values_pruned_at=sa.func.current_timestamp()) + .values(catalog_values_pruned_at=sa.func.current_timestamp()), ) # A guard publication can't reach: every writer of the column (pruning # and restoration) holds the publication lock, and the caller checks under # it that the version is unpruned. It costs nothing in the UPDATE, and # keeps a writer that doesn't take the lock, such as an operator's SQL, # from having a version's time replaced or its rows deleted twice. - if marked.rowcount == 0: + if marked == 0: return None - version_parameter_ids = sa.select(PARAMETERS.c.id).where( - PARAMETERS.c.tax_benefit_model_version_id == version_id + version_parameter_ids = sa.select(col(Parameter.id)).where( + col(Parameter.tax_benefit_model_version_id) == version_id + ) + parameter_values = _changed_rows( + session, + sa.delete(ParameterValue).where( + col(ParameterValue.parameter_id).in_(version_parameter_ids), + col(ParameterValue.policy_id).is_(None), + col(ParameterValue.dynamic_id).is_(None), + ), + ) + tree_rows = _changed_rows( + session, + sa.delete(ParameterTreeChild).where( + col(ParameterTreeChild.tax_benefit_model_version_id) == version_id + ), + ) + search_files = _changed_rows( + session, + sa.delete(ParameterSearchFile).where( + col(ParameterSearchFile.tax_benefit_model_version_id) == version_id + ), ) - parameter_values = connection.execute( - sa.delete(PARAMETER_VALUES).where( - PARAMETER_VALUES.c.parameter_id.in_(version_parameter_ids), - PARAMETER_VALUES.c.policy_id.is_(None), - PARAMETER_VALUES.c.dynamic_id.is_(None), - ) - ).rowcount - tree_rows = connection.execute( - sa.delete(PARAMETER_TREE_CHILDREN).where( - PARAMETER_TREE_CHILDREN.c.tax_benefit_model_version_id == version_id - ) - ).rowcount - search_files = connection.execute( - sa.delete(PARAMETER_SEARCH_FILES).where( - PARAMETER_SEARCH_FILES.c.tax_benefit_model_version_id == version_id - ) - ).rowcount return PrunedRows( parameter_values=parameter_values, parameter_tree_children=tree_rows, @@ -287,6 +302,12 @@ def prune_catalog_version( ) +def _changed_rows(session: Session, statement: Update | Delete) -> int: + """Run a set-based UPDATE or DELETE and return how many rows it changed.""" + result = session.execute(statement, execution_options=SET_BASED) + return cast("CursorResult[Any]", result).rowcount + + def pruning_failure( country_id: str, version: str | None, error: Exception ) -> CatalogPruningFailure: @@ -325,23 +346,27 @@ class name and SQLSTATE of the error the database driver raised are ) -def _pruned_version_id(connection: Connection, country: CountryCatalog) -> UUID | None: - pruned_id: UUID | None = connection.execute( - sa.select(MODEL_VERSIONS.c.id) +def _pruned_version_id(session: Session, country: CountryCatalog) -> UUID | None: + pruned_id: UUID | None = session.execute( + sa.select(col(TaxBenefitModelVersion.id)) .select_from( - MODEL_VERSIONS.join(MODELS, MODELS.c.id == MODEL_VERSIONS.c.model_id) + sa.join( + TaxBenefitModelVersion, + TaxBenefitModel, + col(TaxBenefitModel.id) == col(TaxBenefitModelVersion.model_id), + ) ) .where( - MODELS.c.name == country.model.name, - MODEL_VERSIONS.c.version == country.model_version.version, - MODEL_VERSIONS.c.catalog_values_pruned_at.is_not(None), + col(TaxBenefitModel.name) == country.model.name, + col(TaxBenefitModelVersion.version) == country.model_version.version, + col(TaxBenefitModelVersion.catalog_values_pruned_at).is_not(None), ) ).scalar_one_or_none() return pruned_id def restore_pruned_catalog_versions( - connection: Connection, countries: Sequence[CountryCatalog] + session: Session, countries: Sequence[CountryCatalog] ) -> tuple[tuple[str, str, int], ...]: """Write back the current-law values of each staged version that was pruned. @@ -354,18 +379,21 @@ def restore_pruned_catalog_versions( """ restored = [] for country in countries: - version_id = _pruned_version_id(connection, country) + version_id = _pruned_version_id(session, country) if version_id is None: continue # SQLAlchemy keeps an INSERT's row count only when asked to. - parameter_values = connection.execute( + inserted = session.execute( INSERT_PARAMETER_VALUES.execution_options(preserve_rowcount=True), {"country_id": country.country_id}, - ).rowcount - connection.execute( - sa.update(MODEL_VERSIONS) - .where(MODEL_VERSIONS.c.id == version_id) - .values(catalog_values_pruned_at=None) + execution_options=RAW_DML_STRATEGY, + ) + parameter_values = cast("CursorResult[Any]", inserted).rowcount + _changed_rows( + session, + sa.update(TaxBenefitModelVersion) + .where(col(TaxBenefitModelVersion.id) == version_id) + .values(catalog_values_pruned_at=None), ) restored.append( (country.country_id, country.model_version.version, parameter_values) diff --git a/policyengine_api/data/v2/catalog/publication_reconciliation.py b/policyengine_api/data/v2/catalog/publication_reconciliation.py index 4706a2dab..cad40cb56 100644 --- a/policyengine_api/data/v2/catalog/publication_reconciliation.py +++ b/policyengine_api/data/v2/catalog/publication_reconciliation.py @@ -3,67 +3,80 @@ from __future__ import annotations from dataclasses import dataclass -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any import sqlalchemy as sa -from sqlalchemy import Connection, Select +from sqlalchemy import Select from sqlalchemy.dialects.postgresql import JSONB - -from policyengine_api.data.v2.catalog.publication_staging import ( - STAGE_CATALOG_DATASETS, - STAGE_CATALOG_MODELS, - STAGE_CATALOG_PARAMETER_NODES, - STAGE_CATALOG_PARAMETER_VALUES, - STAGE_CATALOG_PARAMETERS, - STAGE_CATALOG_REGIONS, - STAGE_CATALOG_VARIABLES, -) -from policyengine_api.data.v2.catalog.publication_tables import ( - DATASETS, - MODEL_VERSIONS, - MODELS, - PARAMETER_NODES, - PARAMETER_VALUES, - PARAMETERS, - REGIONS, - VARIABLES, +from sqlalchemy.orm import Mapped +from sqlmodel import col + +from policyengine_api.data.v2.catalog.publication_inserts import column_type +from policyengine_api.data.v2.catalog.publication_staging_base import ( + StagedDataset, + StagedModel, + StagedParameter, + StagedParameterNode, + StagedParameterValue, + StagedRegion, + StagedVariable, ) from policyengine_api.data.v2.catalog.publication_types import ( CatalogPublicationError, ) +from policyengine_api.data.v2.models import ( + Dataset, + Parameter, + ParameterNode, + ParameterValue, + Region, + TaxBenefitModel, + TaxBenefitModelVersion, + Variable, +) if TYPE_CHECKING: from uuid import UUID + from sqlmodel import Session + from policyengine_api.data.v2.catalog.records import CountryCatalog +# The catalog tables whose rows belong to one model version. +VersionedCatalogRow = Variable | ParameterNode | Parameter | Dataset | Region +# A selected column: a mapped attribute, or an expression such as a cast. +ColumnExpression = sa.ColumnElement[Any] | Mapped[Any] + -def version_exists(connection: Connection, country: CountryCatalog) -> bool: +def version_exists(session: Session, country: CountryCatalog) -> bool: """Return whether the model name and version of this country are already stored.""" statement = ( - sa.select(MODEL_VERSIONS.c.id) + sa.select(col(TaxBenefitModelVersion.id)) .select_from( - MODEL_VERSIONS.join( - MODELS, - MODELS.c.id == MODEL_VERSIONS.c.model_id, + sa.join( + TaxBenefitModelVersion, + TaxBenefitModel, + col(TaxBenefitModel.id) == col(TaxBenefitModelVersion.model_id), ) ) .where( - MODELS.c.name == country.model.name, - MODEL_VERSIONS.c.version == country.model_version.version, + col(TaxBenefitModel.name) == country.model.name, + col(TaxBenefitModelVersion.version) == country.model_version.version, ) .limit(1) ) - return connection.execute(statement).first() is not None + return session.execute(statement).first() is not None -def _versioned_table_from(table: sa.Table) -> sa.Join: - return table.join( - MODEL_VERSIONS, - MODEL_VERSIONS.c.id == table.c.tax_benefit_model_version_id, +def _versioned_from(model: type[VersionedCatalogRow]) -> sa.Join: + """Join a catalog table to its rows' model version and model.""" + return sa.join( + model, + TaxBenefitModelVersion, + col(TaxBenefitModelVersion.id) == col(model.tax_benefit_model_version_id), ).join( - MODELS, - MODELS.c.id == MODEL_VERSIONS.c.model_id, + TaxBenefitModel, + col(TaxBenefitModel.id) == col(TaxBenefitModelVersion.model_id), ) @@ -79,24 +92,25 @@ class StoredVersion: catalog_format: int | None -def stored_version( - connection: Connection, country: CountryCatalog -) -> StoredVersion | None: +def stored_version(session: Session, country: CountryCatalog) -> StoredVersion | None: """Return this country's stored catalog version, or None if it is not stored.""" statement = ( - sa.select(MODEL_VERSIONS.c.id, MODEL_VERSIONS.c.catalog_format) + sa.select( + col(TaxBenefitModelVersion.id), col(TaxBenefitModelVersion.catalog_format) + ) .select_from( - MODEL_VERSIONS.join( - MODELS, - MODELS.c.id == MODEL_VERSIONS.c.model_id, + sa.join( + TaxBenefitModelVersion, + TaxBenefitModel, + col(TaxBenefitModel.id) == col(TaxBenefitModelVersion.model_id), ) ) .where( - MODELS.c.name == country.model.name, - MODEL_VERSIONS.c.version == country.model_version.version, + col(TaxBenefitModel.name) == country.model.name, + col(TaxBenefitModelVersion.version) == country.model_version.version, ) ) - row = connection.execute(statement).one_or_none() + row = session.execute(statement).one_or_none() if row is None: return None return StoredVersion(id=row.id, catalog_format=row.catalog_format) @@ -116,180 +130,186 @@ def _comparison_pairs( version the staged ones (``update_stored_time_periods``). """ - def format_2(*columns: sa.ColumnElement) -> tuple[sa.ColumnElement, ...]: + def format_2(*columns: ColumnExpression) -> tuple[ColumnExpression, ...]: return columns if with_format_2 else () - staged_country = STAGE_CATALOG_MODELS.c.country_id == country.country_id + staged_country = col(StagedModel.country_id) == country.country_id selected_version = sa.and_( - MODELS.c.name == country.model.name, - MODEL_VERSIONS.c.version == country.model_version.version, + col(TaxBenefitModel.name) == country.model.name, + col(TaxBenefitModelVersion.version) == country.model_version.version, ) staged_model_version = sa.select( - STAGE_CATALOG_MODELS.c.version_description, - STAGE_CATALOG_MODELS.c.current_law_id, + col(StagedModel.version_description), + col(StagedModel.current_law_id), *format_2( - STAGE_CATALOG_MODELS.c.catalog_format, - STAGE_CATALOG_MODELS.c.entities, - STAGE_CATALOG_MODELS.c.basic_inputs, + col(StagedModel.catalog_format), + col(StagedModel.entities), + col(StagedModel.basic_inputs), ), ).where(staged_country) actual_model_version = ( sa.select( - MODEL_VERSIONS.c.description, - MODEL_VERSIONS.c.current_law_id, + col(TaxBenefitModelVersion.description), + col(TaxBenefitModelVersion.current_law_id), *format_2( - MODEL_VERSIONS.c.catalog_format, - sa.cast(MODEL_VERSIONS.c.entities, JSONB), - sa.cast(MODEL_VERSIONS.c.basic_inputs, JSONB), + col(TaxBenefitModelVersion.catalog_format), + sa.cast(col(TaxBenefitModelVersion.entities), JSONB), + sa.cast(col(TaxBenefitModelVersion.basic_inputs), JSONB), ), ) .select_from( - MODEL_VERSIONS.join( - MODELS, - MODELS.c.id == MODEL_VERSIONS.c.model_id, + sa.join( + TaxBenefitModelVersion, + TaxBenefitModel, + col(TaxBenefitModel.id) == col(TaxBenefitModelVersion.model_id), ) ) .where(selected_version) ) staged_variables = sa.select( - STAGE_CATALOG_VARIABLES.c.name, - STAGE_CATALOG_VARIABLES.c.label, - STAGE_CATALOG_VARIABLES.c.entity, - STAGE_CATALOG_VARIABLES.c.description, - STAGE_CATALOG_VARIABLES.c.data_type, - STAGE_CATALOG_VARIABLES.c.possible_values, - STAGE_CATALOG_VARIABLES.c.default_value, - STAGE_CATALOG_VARIABLES.c.adds, - STAGE_CATALOG_VARIABLES.c.subtracts, + col(StagedVariable.name), + col(StagedVariable.label), + col(StagedVariable.entity), + col(StagedVariable.description), + col(StagedVariable.data_type), + col(StagedVariable.possible_values), + col(StagedVariable.default_value), + col(StagedVariable.adds), + col(StagedVariable.subtracts), *format_2( - STAGE_CATALOG_VARIABLES.c.is_input_variable, - STAGE_CATALOG_VARIABLES.c.hidden_input, - STAGE_CATALOG_VARIABLES.c.module_name, - STAGE_CATALOG_VARIABLES.c.adds_parameter_path, - STAGE_CATALOG_VARIABLES.c.subtracts_parameter_path, - STAGE_CATALOG_VARIABLES.c.enum_values, - STAGE_CATALOG_VARIABLES.c.unit, - STAGE_CATALOG_VARIABLES.c.definition_period, + col(StagedVariable.is_input_variable), + col(StagedVariable.hidden_input), + col(StagedVariable.module_name), + col(StagedVariable.adds_parameter_path), + col(StagedVariable.subtracts_parameter_path), + col(StagedVariable.enum_values), + col(StagedVariable.unit), + col(StagedVariable.definition_period), ), - ).where(STAGE_CATALOG_VARIABLES.c.country_id == country.country_id) + ).where(col(StagedVariable.country_id) == country.country_id) actual_variables = ( sa.select( - VARIABLES.c.name, - VARIABLES.c.label, - VARIABLES.c.entity, - VARIABLES.c.description, - VARIABLES.c.data_type, - sa.cast(VARIABLES.c.possible_values, JSONB), - sa.cast(VARIABLES.c.default_value, JSONB), - sa.cast(VARIABLES.c.adds, JSONB), - sa.cast(VARIABLES.c.subtracts, JSONB), + col(Variable.name), + col(Variable.label), + col(Variable.entity), + col(Variable.description), + col(Variable.data_type), + sa.cast(col(Variable.possible_values), JSONB), + sa.cast(col(Variable.default_value), JSONB), + sa.cast(col(Variable.adds), JSONB), + sa.cast(col(Variable.subtracts), JSONB), *format_2( - VARIABLES.c.is_input_variable, - VARIABLES.c.hidden_input, - VARIABLES.c.module_name, - VARIABLES.c.adds_parameter_path, - VARIABLES.c.subtracts_parameter_path, - sa.cast(VARIABLES.c.enum_values, JSONB), - VARIABLES.c.unit, - VARIABLES.c.definition_period, + col(Variable.is_input_variable), + col(Variable.hidden_input), + col(Variable.module_name), + col(Variable.adds_parameter_path), + col(Variable.subtracts_parameter_path), + sa.cast(col(Variable.enum_values), JSONB), + col(Variable.unit), + col(Variable.definition_period), ), ) - .select_from(_versioned_table_from(VARIABLES)) + .select_from(_versioned_from(Variable)) .where(selected_version) ) staged_parameter_nodes = sa.select( - STAGE_CATALOG_PARAMETER_NODES.c.name, - STAGE_CATALOG_PARAMETER_NODES.c.label, - STAGE_CATALOG_PARAMETER_NODES.c.description, - ).where(STAGE_CATALOG_PARAMETER_NODES.c.country_id == country.country_id) + col(StagedParameterNode.name), + col(StagedParameterNode.label), + col(StagedParameterNode.description), + ).where(col(StagedParameterNode.country_id) == country.country_id) actual_parameter_nodes = ( sa.select( - PARAMETER_NODES.c.name, - PARAMETER_NODES.c.label, - PARAMETER_NODES.c.description, + col(ParameterNode.name), + col(ParameterNode.label), + col(ParameterNode.description), ) - .select_from(_versioned_table_from(PARAMETER_NODES)) + .select_from(_versioned_from(ParameterNode)) .where(selected_version) ) staged_parameters = sa.select( - STAGE_CATALOG_PARAMETERS.c.name, - STAGE_CATALOG_PARAMETERS.c.label, - STAGE_CATALOG_PARAMETERS.c.description, - STAGE_CATALOG_PARAMETERS.c.data_type, - STAGE_CATALOG_PARAMETERS.c.unit, + col(StagedParameter.name), + col(StagedParameter.label), + col(StagedParameter.description), + col(StagedParameter.data_type), + col(StagedParameter.unit), *format_2( - STAGE_CATALOG_PARAMETERS.c.economy, - STAGE_CATALOG_PARAMETERS.c.household, + col(StagedParameter.economy), + col(StagedParameter.household), ), - ).where(STAGE_CATALOG_PARAMETERS.c.country_id == country.country_id) + ).where(col(StagedParameter.country_id) == country.country_id) actual_parameters = ( sa.select( - PARAMETERS.c.name, - PARAMETERS.c.label, - PARAMETERS.c.description, - PARAMETERS.c.data_type, - PARAMETERS.c.unit, - *format_2(PARAMETERS.c.economy, PARAMETERS.c.household), + col(Parameter.name), + col(Parameter.label), + col(Parameter.description), + col(Parameter.data_type), + col(Parameter.unit), + *format_2(col(Parameter.economy), col(Parameter.household)), ) - .select_from(_versioned_table_from(PARAMETERS)) + .select_from(_versioned_from(Parameter)) .where(selected_version) ) staged_parameter_values = sa.select( - STAGE_CATALOG_PARAMETER_VALUES.c.parameter_name, - STAGE_CATALOG_PARAMETER_VALUES.c.value_json, - STAGE_CATALOG_PARAMETER_VALUES.c.start_date, - STAGE_CATALOG_PARAMETER_VALUES.c.end_date, - ).where(STAGE_CATALOG_PARAMETER_VALUES.c.country_id == country.country_id) + col(StagedParameterValue.parameter_name), + col(StagedParameterValue.value_json), + col(StagedParameterValue.start_date), + col(StagedParameterValue.end_date), + ).where(col(StagedParameterValue.country_id) == country.country_id) actual_parameter_values = ( sa.select( - PARAMETERS.c.name, - sa.cast(PARAMETER_VALUES.c.value_json, JSONB), - PARAMETER_VALUES.c.start_date, - PARAMETER_VALUES.c.end_date, + col(Parameter.name), + sa.cast(col(ParameterValue.value_json), JSONB), + col(ParameterValue.start_date), + col(ParameterValue.end_date), ) .select_from( - PARAMETER_VALUES.join( - PARAMETERS, - PARAMETERS.c.id == PARAMETER_VALUES.c.parameter_id, + sa.join( + ParameterValue, + Parameter, + col(Parameter.id) == col(ParameterValue.parameter_id), + ) + .join( + TaxBenefitModelVersion, + col(TaxBenefitModelVersion.id) + == col(Parameter.tax_benefit_model_version_id), ) .join( - MODEL_VERSIONS, - MODEL_VERSIONS.c.id == PARAMETERS.c.tax_benefit_model_version_id, + TaxBenefitModel, + col(TaxBenefitModel.id) == col(TaxBenefitModelVersion.model_id), ) - .join(MODELS, MODELS.c.id == MODEL_VERSIONS.c.model_id) ) .where( selected_version, - PARAMETER_VALUES.c.policy_id.is_(None), - PARAMETER_VALUES.c.dynamic_id.is_(None), + col(ParameterValue.policy_id).is_(None), + col(ParameterValue.dynamic_id).is_(None), ) ) staged_datasets = sa.select( - STAGE_CATALOG_DATASETS.c.name, - STAGE_CATALOG_DATASETS.c.description, - STAGE_CATALOG_DATASETS.c.year, + col(StagedDataset.name), + col(StagedDataset.description), + col(StagedDataset.year), sa.literal(value=False), - sa.cast(sa.null(), DATASETS.c.storage_path.type), - ).where(STAGE_CATALOG_DATASETS.c.country_id == country.country_id) + sa.cast(sa.null(), column_type(Dataset, "storage_path")), + ).where(col(StagedDataset.country_id) == country.country_id) actual_datasets = ( sa.select( - DATASETS.c.name, - DATASETS.c.description, - DATASETS.c.year, - DATASETS.c.is_output_dataset, - DATASETS.c.storage_path, + col(Dataset.name), + col(Dataset.description), + col(Dataset.year), + col(Dataset.is_output_dataset), + col(Dataset.storage_path), ) - .select_from(_versioned_table_from(DATASETS)) + .select_from(_versioned_from(Dataset)) .where( selected_version, - DATASETS.c.is_output_dataset.is_(False), - DATASETS.c.storage_path.is_(None), + col(Dataset.is_output_dataset).is_(False), + col(Dataset.storage_path).is_(None), ) ) @@ -306,40 +326,40 @@ def format_2(*columns: sa.ColumnElement) -> tuple[sa.ColumnElement, ...]: def _region_comparison_pair(country: CountryCatalog) -> tuple[Select, Select]: """Return the staged and stored region rows of one country's catalog version.""" selected_version = sa.and_( - MODELS.c.name == country.model.name, - MODEL_VERSIONS.c.version == country.model_version.version, + col(TaxBenefitModel.name) == country.model.name, + col(TaxBenefitModelVersion.version) == country.model_version.version, ) staged_regions = sa.select( - STAGE_CATALOG_REGIONS.c.code, - STAGE_CATALOG_REGIONS.c.label, - STAGE_CATALOG_REGIONS.c.region_type, - STAGE_CATALOG_REGIONS.c.requires_filter, - STAGE_CATALOG_REGIONS.c.filter_field, - STAGE_CATALOG_REGIONS.c.filter_value, - STAGE_CATALOG_REGIONS.c.filter_strategy, - STAGE_CATALOG_REGIONS.c.parent_code, - STAGE_CATALOG_REGIONS.c.state_code, - STAGE_CATALOG_REGIONS.c.state_name, - STAGE_CATALOG_REGIONS.c.default_dataset_name, - ).where(STAGE_CATALOG_REGIONS.c.country_id == country.country_id) + col(StagedRegion.code), + col(StagedRegion.label), + col(StagedRegion.region_type), + col(StagedRegion.requires_filter), + col(StagedRegion.filter_field), + col(StagedRegion.filter_value), + col(StagedRegion.filter_strategy), + col(StagedRegion.parent_code), + col(StagedRegion.state_code), + col(StagedRegion.state_name), + col(StagedRegion.default_dataset_name), + ).where(col(StagedRegion.country_id) == country.country_id) actual_regions = ( sa.select( - REGIONS.c.code, - REGIONS.c.label, - sa.cast(REGIONS.c.region_type, sa.Text), - REGIONS.c.requires_filter, - REGIONS.c.filter_field, - REGIONS.c.filter_value, - REGIONS.c.filter_strategy, - REGIONS.c.parent_code, - REGIONS.c.state_code, - REGIONS.c.state_name, - DATASETS.c.name, + col(Region.code), + col(Region.label), + sa.cast(col(Region.region_type), sa.Text), + col(Region.requires_filter), + col(Region.filter_field), + col(Region.filter_value), + col(Region.filter_strategy), + col(Region.parent_code), + col(Region.state_code), + col(Region.state_name), + col(Dataset.name), ) .select_from( - _versioned_table_from(REGIONS).join( - DATASETS, - DATASETS.c.id == REGIONS.c.default_dataset_id, + _versioned_from(Region).join( + Dataset, + col(Dataset.id) == col(Region.default_dataset_id), ) ) .where(selected_version) @@ -349,7 +369,7 @@ def _region_comparison_pair(country: CountryCatalog) -> tuple[Select, Select]: def _sets_differ( - connection: Connection, + session: Session, staged: Select, actual: Select, ) -> bool: @@ -359,11 +379,11 @@ def _sets_differ( sa.select(sa.literal(1)).select_from(missing), sa.select(sa.literal(1)).select_from(extra), ).limit(1) - return connection.execute(differences).first() is not None + return session.execute(differences).first() is not None def assert_country_matches( - connection: Connection, + session: Session, country: CountryCatalog, *, include_regions: bool = True, @@ -373,13 +393,13 @@ def assert_country_matches( Rows are compared as sets in both directions, so a missing row and an extra row both fail; the error names the first table that differs, never its rows. Without ``include_regions``, region rows are not compared: they come - from the Public API's reference files, which may change while the + from API v1's reference files, which may change while the PolicyEngine.py version stays the same. The model version's ``metadata_time_periods`` are never compared, for the same reason: they come from ``policyengine_api.economy_years``. A version published before catalog format 2 is compared without format 2's fields. """ - stored = stored_version(connection, country) + stored = stored_version(session, country) pairs = _comparison_pairs( country, with_format_2=stored is not None and stored.catalog_format is not None, @@ -387,7 +407,7 @@ def assert_country_matches( if include_regions: pairs = (*pairs, ("regions", *_region_comparison_pair(country))) for table_name, staged, actual in pairs: - if _sets_differ(connection, staged, actual): + if _sets_differ(session, staged, actual): msg = ( f"the stored {country.country_id} catalog version " f"{country.model_version.version} differs from the staged catalog " @@ -397,11 +417,11 @@ def assert_country_matches( def update_stored_time_periods( - connection: Connection, country: CountryCatalog + session: Session, country: CountryCatalog ) -> tuple[list[int], list[int]] | None: """Give this country's stored version the staged ``metadata_time_periods``. - They are the years the Public API offers for the version, which come from + They are the years API v1 offers for the version, which come from ``policyengine_api.economy_years`` and so may change while the PolicyEngine.py version stays the same. When the two lists differ, a change of order included, replace the stored list in the publication's @@ -410,22 +430,28 @@ def update_stored_time_periods( the country was not staged. """ staged_time_periods = ( - sa.select(STAGE_CATALOG_MODELS.c.metadata_time_periods) - .where(STAGE_CATALOG_MODELS.c.country_id == country.country_id) + sa.select(col(StagedModel.metadata_time_periods)) + .where(col(StagedModel.country_id) == country.country_id) .scalar_subquery() ) - row = connection.execute( + row = session.execute( sa.select( - MODEL_VERSIONS.c.id, - sa.cast(MODEL_VERSIONS.c.metadata_time_periods, JSONB).label("stored"), + col(TaxBenefitModelVersion.id), + sa.cast(col(TaxBenefitModelVersion.metadata_time_periods), JSONB).label( + "stored" + ), staged_time_periods.label("staged"), ) .select_from( - MODEL_VERSIONS.join(MODELS, MODELS.c.id == MODEL_VERSIONS.c.model_id) + sa.join( + TaxBenefitModelVersion, + TaxBenefitModel, + col(TaxBenefitModel.id) == col(TaxBenefitModelVersion.model_id), + ) ) .where( - MODELS.c.name == country.model.name, - MODEL_VERSIONS.c.version == country.model_version.version, + col(TaxBenefitModel.name) == country.model.name, + col(TaxBenefitModelVersion.version) == country.model_version.version, ) ).one_or_none() if row is None or row.staged is None: @@ -437,24 +463,26 @@ def update_stored_time_periods( raise CatalogPublicationError(msg) if row.stored == row.staged: return None - connection.execute( - sa.update(MODEL_VERSIONS) - .where(MODEL_VERSIONS.c.id == row.id) + session.execute( + sa.update(TaxBenefitModelVersion) + .where(col(TaxBenefitModelVersion.id) == row.id) .values(metadata_time_periods=row.staged) + .execution_options(synchronize_session=False) ) return list(row.stored), list(row.staged) -def count_stored_regions(connection: Connection, country: CountryCatalog) -> int: +def count_stored_regions(session: Session, country: CountryCatalog) -> int: """Count the region rows stored for one country's catalog version.""" _staged, actual = _region_comparison_pair(country) - return connection.execute( + count: int = session.execute( sa.select(sa.func.count()).select_from(actual.subquery()) ).scalar_one() + return count def count_region_differences( - connection: Connection, + session: Session, country: CountryCatalog, ) -> tuple[int, int]: """Count staged region rows the stored version lacks, and stored rows not staged.""" @@ -462,34 +490,34 @@ def count_region_differences( staged_not_stored = sa.except_(staged, actual).subquery() stored_not_staged = sa.except_(actual, staged).subquery() return ( - connection.execute( + session.execute( sa.select(sa.func.count()).select_from(staged_not_stored) ).scalar_one(), - connection.execute( + session.execute( sa.select(sa.func.count()).select_from(stored_not_staged) ).scalar_one(), ) -def assert_canonical_value_uniqueness(connection: Connection) -> None: +def assert_canonical_value_uniqueness(session: Session) -> None: """Raise CatalogPublicationError if a parameter has duplicate current-law values. Current-law values are those with neither a policy nor a dynamic; each parameter may have only one per start date. """ duplicates = ( - sa.select(PARAMETER_VALUES.c.parameter_id) + sa.select(col(ParameterValue.parameter_id)) .where( - PARAMETER_VALUES.c.policy_id.is_(None), - PARAMETER_VALUES.c.dynamic_id.is_(None), + col(ParameterValue.policy_id).is_(None), + col(ParameterValue.dynamic_id).is_(None), ) .group_by( - PARAMETER_VALUES.c.parameter_id, - PARAMETER_VALUES.c.start_date, + col(ParameterValue.parameter_id), + col(ParameterValue.start_date), ) .having(sa.func.count() > 1) .limit(1) ) - if connection.execute(duplicates).first() is not None: + if session.execute(duplicates).first() is not None: msg = "canonical parameter-value uniqueness validation failed" raise CatalogPublicationError(msg) diff --git a/policyengine_api/data/v2/catalog/publication_staging.py b/policyengine_api/data/v2/catalog/publication_staging.py index f4243fa64..82a7d8dbf 100644 --- a/policyengine_api/data/v2/catalog/publication_staging.py +++ b/policyengine_api/data/v2/catalog/publication_staging.py @@ -1,15 +1,28 @@ -"""Temporary-table staging for v2 catalog publication.""" +"""Temporary-table staging for v2 catalog publication. + +Publication COPYs every country's catalog records into the staging tables +(``publication_staging_base``), which it creates in its own transaction. +""" from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any import sqlalchemy as sa from psycopg import sql from psycopg.types.json import Jsonb -from sqlalchemy import Connection, MetaData, Table -from sqlalchemy.dialects.postgresql import JSONB +from policyengine_api.data.v2.catalog.publication_staging_base import ( + STAGING_METADATA, + STAGING_MODELS, + StagedDataset, + StagedModel, + StagedParameter, + StagedParameterNode, + StagedParameterValue, + StagedRegion, + StagedVariable, +) from policyengine_api.data.v2.catalog.publication_types import ( CatalogPublicationError, ) @@ -25,141 +38,10 @@ from collections.abc import Callable, Iterable, Iterator, Sequence from uuid import UUID -COPY_BATCH_SIZE = 10_000 - -STAGING_METADATA = MetaData() - -STAGE_CATALOG_MODELS = Table( - "stage_catalog_models", - STAGING_METADATA, - sa.Column("country_id", sa.Text, primary_key=True), - sa.Column("id", sa.Uuid, nullable=False), - sa.Column("name", sa.Text, nullable=False), - sa.Column("description", sa.Text), - sa.Column("version_id", sa.Uuid, nullable=False), - sa.Column("version", sa.Text, nullable=False), - sa.Column("version_description", sa.Text), - sa.Column("current_law_id", sa.Integer, nullable=False), - sa.Column("metadata_time_periods", JSONB, nullable=False), - sa.Column("catalog_format", sa.Integer, nullable=False), - sa.Column("entities", JSONB, nullable=False), - sa.Column("basic_inputs", JSONB, nullable=False), - prefixes=["TEMPORARY"], - postgresql_on_commit="DROP", -) - -STAGE_CATALOG_VARIABLES = Table( - "stage_catalog_variables", - STAGING_METADATA, - sa.Column("country_id", sa.Text, primary_key=True), - sa.Column("id", sa.Uuid, nullable=False), - sa.Column("name", sa.Text, primary_key=True), - sa.Column("label", sa.Text), - sa.Column("entity", sa.Text, nullable=False), - sa.Column("description", sa.Text), - sa.Column("data_type", sa.Text), - sa.Column("possible_values", JSONB), - sa.Column("default_value", JSONB, nullable=False), - sa.Column("adds", JSONB), - sa.Column("subtracts", JSONB), - sa.Column("is_input_variable", sa.Boolean), - sa.Column("hidden_input", sa.Boolean), - sa.Column("module_name", sa.Text), - sa.Column("adds_parameter_path", sa.Text), - sa.Column("subtracts_parameter_path", sa.Text), - sa.Column("enum_values", JSONB), - sa.Column("unit", sa.Text), - sa.Column("definition_period", sa.Text), - prefixes=["TEMPORARY"], - postgresql_on_commit="DROP", -) - -STAGE_CATALOG_PARAMETER_NODES = Table( - "stage_catalog_parameter_nodes", - STAGING_METADATA, - sa.Column("country_id", sa.Text, primary_key=True), - sa.Column("id", sa.Uuid, nullable=False), - sa.Column("name", sa.Text, primary_key=True), - sa.Column("label", sa.Text), - sa.Column("description", sa.Text), - prefixes=["TEMPORARY"], - postgresql_on_commit="DROP", -) - -STAGE_CATALOG_PARAMETERS = Table( - "stage_catalog_parameters", - STAGING_METADATA, - sa.Column("country_id", sa.Text, primary_key=True), - sa.Column("id", sa.Uuid, nullable=False), - sa.Column("name", sa.Text, primary_key=True), - sa.Column("label", sa.Text), - sa.Column("description", sa.Text), - sa.Column("data_type", sa.Text), - sa.Column("unit", sa.Text), - sa.Column("economy", sa.Boolean, nullable=False), - sa.Column("household", sa.Boolean, nullable=False), - prefixes=["TEMPORARY"], - postgresql_on_commit="DROP", -) - -STAGE_CATALOG_PARAMETER_VALUES = Table( - "stage_catalog_parameter_values", - STAGING_METADATA, - sa.Column("country_id", sa.Text, primary_key=True), - sa.Column("parameter_name", sa.Text, primary_key=True), - sa.Column("id", sa.Uuid, nullable=False), - sa.Column("value_json", JSONB, nullable=False), - sa.Column( - "start_date", - sa.DateTime(timezone=True), - primary_key=True, - ), - sa.Column("end_date", sa.DateTime(timezone=True)), - prefixes=["TEMPORARY"], - postgresql_on_commit="DROP", -) - -STAGE_CATALOG_DATASETS = Table( - "stage_catalog_datasets", - STAGING_METADATA, - sa.Column("country_id", sa.Text, primary_key=True), - sa.Column("id", sa.Uuid, nullable=False), - sa.Column("name", sa.Text, primary_key=True), - sa.Column("description", sa.Text), - sa.Column("year", sa.Integer, nullable=False), - prefixes=["TEMPORARY"], - postgresql_on_commit="DROP", -) - -STAGE_CATALOG_REGIONS = Table( - "stage_catalog_regions", - STAGING_METADATA, - sa.Column("country_id", sa.Text, primary_key=True), - sa.Column("id", sa.Uuid, nullable=False), - sa.Column("code", sa.Text, primary_key=True), - sa.Column("label", sa.Text, nullable=False), - sa.Column("region_type", sa.Text, nullable=False), - sa.Column("requires_filter", sa.Boolean, nullable=False), - sa.Column("filter_field", sa.Text), - sa.Column("filter_value", sa.Text), - sa.Column("filter_strategy", sa.Text), - sa.Column("parent_code", sa.Text), - sa.Column("state_code", sa.Text), - sa.Column("state_name", sa.Text), - sa.Column("default_dataset_name", sa.Text, nullable=False), - prefixes=["TEMPORARY"], - postgresql_on_commit="DROP", -) + from sqlalchemy.orm import Mapper + from sqlmodel import Session, SQLModel -STAGING_TABLES = ( - STAGE_CATALOG_MODELS, - STAGE_CATALOG_VARIABLES, - STAGE_CATALOG_PARAMETER_NODES, - STAGE_CATALOG_PARAMETERS, - STAGE_CATALOG_PARAMETER_VALUES, - STAGE_CATALOG_DATASETS, - STAGE_CATALOG_REGIONS, -) +COPY_BATCH_SIZE = 10_000 def _optional_json(value: object) -> Jsonb | None: @@ -319,76 +201,98 @@ def _region_rows( def _catalog_rows( country: CountryCatalog, -) -> dict[Table, Iterator[tuple[object, ...]]]: +) -> dict[type[SQLModel], Iterator[tuple[object, ...]]]: dataset_names = {dataset.id: dataset.name for dataset in country.datasets} return { - STAGE_CATALOG_MODELS: _model_rows(country), - STAGE_CATALOG_VARIABLES: _variable_rows(country), - STAGE_CATALOG_PARAMETER_NODES: _parameter_node_rows(country), - STAGE_CATALOG_PARAMETERS: _parameter_rows(country), - STAGE_CATALOG_PARAMETER_VALUES: _parameter_value_rows(country), - STAGE_CATALOG_DATASETS: _dataset_rows(country), - STAGE_CATALOG_REGIONS: _region_rows(country, dataset_names), + StagedModel: _model_rows(country), + StagedVariable: _variable_rows(country), + StagedParameterNode: _parameter_node_rows(country), + StagedParameter: _parameter_rows(country), + StagedParameterValue: _parameter_value_rows(country), + StagedDataset: _dataset_rows(country), + StagedRegion: _region_rows(country, dataset_names), } +def table_name(model: type[SQLModel]) -> str: + """Return the name of the table the mapped class ``model`` maps.""" + name = model.__tablename__ + if not isinstance(name, str): + msg = f"{model.__name__} names no table" + raise TypeError(msg) + return name + + +def column_names(model: type[SQLModel]) -> list[str]: + """Return the names of the mapped class's columns, in their declared order.""" + mapper: Mapper[Any] = sa.inspect(model) + return [column.name for column in mapper.columns] + + def copy_rows( - connection: Connection, + session: Session, *, - table: Table, + model: type[SQLModel], rows: Iterable[Sequence[object]], ) -> int: - """Write one bounded source stream through Psycopg COPY.""" - raw_connection = connection.connection.driver_connection + """Write one bounded source stream into ``model``'s table through Psycopg COPY. + + Each row gives the model's columns in their declared order. COPY runs on + the psycopg connection beneath the Session's Connection, so it is part of + the Session's transaction. + """ + driver_connection = session.connection().connection.driver_connection + if driver_connection is None: + msg = "the publishing Session's connection is closed" + raise CatalogPublicationError(msg) statement = sql.SQL("COPY {} ({}) FROM STDIN").format( - sql.Identifier(table.name), - sql.SQL(", ").join(sql.Identifier(column.name) for column in table.columns), + sql.Identifier(table_name(model)), + sql.SQL(", ").join([sql.Identifier(name) for name in column_names(model)]), ) count = 0 - with raw_connection.cursor() as cursor, cursor.copy(statement) as copy: + with driver_connection.cursor() as cursor, cursor.copy(statement) as copy: for row in rows: copy.write_row(row) count += 1 return count -def create_staging_tables(connection: Connection) -> None: - """Create the temporary staging tables, which Postgres drops at commit.""" - STAGING_METADATA.create_all(connection, checkfirst=False) +def create_staging_tables(session: Session) -> None: + """Create the temporary staging tables, which Postgres drops at commit. + + They are created on the Connection the Session holds, in its transaction. + """ + STAGING_METADATA.create_all(session.connection(), checkfirst=False) def stage_catalog( - connection: Connection, + session: Session, catalog: NormalizedCatalog, *, - checkpoint: Callable[[str, Connection], None] | None = None, + checkpoint: Callable[[str, Session], None] | None = None, ) -> dict[str, int]: """COPY every country's records into the staging tables and return rows per table. Raise CatalogPublicationError if the copied counts differ from the catalog's own counts. """ - observed = {table.name: 0 for table in STAGING_TABLES} + observed: dict[type[SQLModel], int] = dict.fromkeys(STAGING_MODELS, 0) for country in catalog.countries: - for table, rows in _catalog_rows(country).items(): - observed[table.name] += copy_rows( - connection, - table=table, - rows=rows, - ) + for model, rows in _catalog_rows(country).items(): + observed[model] += copy_rows(session, model=model, rows=rows) if checkpoint is not None: - checkpoint("during_copy", connection) + checkpoint("during_copy", session) expected = catalog.entity_counts() - expected_by_table = { - STAGE_CATALOG_MODELS.name: expected["models"], - STAGE_CATALOG_VARIABLES.name: expected["variables"], - STAGE_CATALOG_PARAMETER_NODES.name: expected["parameter_nodes"], - STAGE_CATALOG_PARAMETERS.name: expected["parameters"], - STAGE_CATALOG_PARAMETER_VALUES.name: expected["parameter_values"], - STAGE_CATALOG_DATASETS.name: expected["datasets"], - STAGE_CATALOG_REGIONS.name: expected["regions"], + expected_by_model = { + StagedModel: expected["models"], + StagedVariable: expected["variables"], + StagedParameterNode: expected["parameter_nodes"], + StagedParameter: expected["parameters"], + StagedParameterValue: expected["parameter_values"], + StagedDataset: expected["datasets"], + StagedRegion: expected["regions"], } - if observed != expected_by_table: + if observed != expected_by_model: msg = "COPY row counts differ from the catalog" raise CatalogPublicationError(msg) - return observed + return {table_name(model): count for model, count in observed.items()} diff --git a/policyengine_api/data/v2/catalog/publication_staging_base.py b/policyengine_api/data/v2/catalog/publication_staging_base.py new file mode 100644 index 000000000..5d2e86133 --- /dev/null +++ b/policyengine_api/data/v2/catalog/publication_staging_base.py @@ -0,0 +1,178 @@ +"""The temporary staging tables catalog publication COPYs a catalog into. + +Each table is a SQLModel class on ``StagingBase``, whose own registry keeps +them out of the v2 metadata (``V2_METADATA``) that Alembic compares with the +database: they are not persistent schema. Every one is TEMPORARY with ON COMMIT +DROP, so publication creates them in its transaction +(``publication_staging.create_staging_tables``) and PostgreSQL drops them when +it commits or rolls back. ``test_publication_staging_tables_are_temporary_and_ +dropped_at_commit`` checks every table. + +Each class declares its columns in the order publication COPYs them, which is +the order of the rows ``publication_staging`` builds. Publication inserts the +staged rows into the catalog tables with ``INSERT ... SELECT`` +(``publication_inserts``) and compares them with stored versions +(``publication_reconciliation``). +""" + +from datetime import datetime +from typing import Any +from uuid import UUID + +import sqlalchemy as sa +from sqlalchemy.dialects.postgresql import JSONB +from sqlalchemy.orm import registry +from sqlmodel import Field, SQLModel + +# PostgreSQL's TIMESTAMP WITH TIME ZONE. SQLModel's Field annotates sa_type as a +# type class, but a timezone-aware DateTime is an instance of one. +TIMESTAMP_WITH_TIME_ZONE: Any = sa.DateTime(timezone=True) +# What makes each staging table temporary, dropped when the transaction ends. +TEMPORARY_UNTIL_COMMIT: dict[str, Any] = { + "prefixes": ["TEMPORARY"], + "postgresql_on_commit": "DROP", +} + + +class StagingBase(SQLModel, registry=registry()): + """The declarative base of the staging tables, on a registry of their own.""" + + +STAGING_METADATA = StagingBase.metadata + + +class StagedModel(StagingBase, table=True): + """A country's model and model version, one row per country.""" + + __tablename__ = "stage_catalog_models" + __table_args__ = TEMPORARY_UNTIL_COMMIT + + country_id: str = Field(sa_type=sa.Text, primary_key=True) + id: UUID = Field(sa_type=sa.Uuid) + name: str = Field(sa_type=sa.Text) + description: str | None = Field(default=None, sa_type=sa.Text) + version_id: UUID = Field(sa_type=sa.Uuid) + version: str = Field(sa_type=sa.Text) + version_description: str | None = Field(default=None, sa_type=sa.Text) + current_law_id: int = Field(sa_type=sa.Integer) + metadata_time_periods: Any = Field(sa_type=JSONB, nullable=False) + catalog_format: int = Field(sa_type=sa.Integer) + entities: Any = Field(sa_type=JSONB, nullable=False) + basic_inputs: Any = Field(sa_type=JSONB, nullable=False) + + +class StagedVariable(StagingBase, table=True): + """One variable of a country's catalog.""" + + __tablename__ = "stage_catalog_variables" + __table_args__ = TEMPORARY_UNTIL_COMMIT + + country_id: str = Field(sa_type=sa.Text, primary_key=True) + id: UUID = Field(sa_type=sa.Uuid) + name: str = Field(sa_type=sa.Text, primary_key=True) + label: str | None = Field(default=None, sa_type=sa.Text) + entity: str = Field(sa_type=sa.Text) + description: str | None = Field(default=None, sa_type=sa.Text) + data_type: str | None = Field(default=None, sa_type=sa.Text) + possible_values: Any = Field(default=None, sa_type=JSONB, nullable=True) + default_value: Any = Field(sa_type=JSONB, nullable=False) + adds: Any = Field(default=None, sa_type=JSONB, nullable=True) + subtracts: Any = Field(default=None, sa_type=JSONB, nullable=True) + is_input_variable: bool | None = Field(default=None, sa_type=sa.Boolean) + hidden_input: bool | None = Field(default=None, sa_type=sa.Boolean) + module_name: str | None = Field(default=None, sa_type=sa.Text) + adds_parameter_path: str | None = Field(default=None, sa_type=sa.Text) + subtracts_parameter_path: str | None = Field(default=None, sa_type=sa.Text) + enum_values: Any = Field(default=None, sa_type=JSONB, nullable=True) + unit: str | None = Field(default=None, sa_type=sa.Text) + definition_period: str | None = Field(default=None, sa_type=sa.Text) + + +class StagedParameterNode(StagingBase, table=True): + """One parameter node of a country's catalog.""" + + __tablename__ = "stage_catalog_parameter_nodes" + __table_args__ = TEMPORARY_UNTIL_COMMIT + + country_id: str = Field(sa_type=sa.Text, primary_key=True) + id: UUID = Field(sa_type=sa.Uuid) + name: str = Field(sa_type=sa.Text, primary_key=True) + label: str | None = Field(default=None, sa_type=sa.Text) + description: str | None = Field(default=None, sa_type=sa.Text) + + +class StagedParameter(StagingBase, table=True): + """One parameter of a country's catalog.""" + + __tablename__ = "stage_catalog_parameters" + __table_args__ = TEMPORARY_UNTIL_COMMIT + + country_id: str = Field(sa_type=sa.Text, primary_key=True) + id: UUID = Field(sa_type=sa.Uuid) + name: str = Field(sa_type=sa.Text, primary_key=True) + label: str | None = Field(default=None, sa_type=sa.Text) + description: str | None = Field(default=None, sa_type=sa.Text) + data_type: str | None = Field(default=None, sa_type=sa.Text) + unit: str | None = Field(default=None, sa_type=sa.Text) + economy: bool = Field(sa_type=sa.Boolean) + household: bool = Field(sa_type=sa.Boolean) + + +class StagedParameterValue(StagingBase, table=True): + """One current-law value of a parameter, named by the parameter's name.""" + + __tablename__ = "stage_catalog_parameter_values" + __table_args__ = TEMPORARY_UNTIL_COMMIT + + country_id: str = Field(sa_type=sa.Text, primary_key=True) + parameter_name: str = Field(sa_type=sa.Text, primary_key=True) + id: UUID = Field(sa_type=sa.Uuid) + value_json: Any = Field(sa_type=JSONB, nullable=False) + start_date: datetime = Field(sa_type=TIMESTAMP_WITH_TIME_ZONE, primary_key=True) + end_date: datetime | None = Field(default=None, sa_type=TIMESTAMP_WITH_TIME_ZONE) + + +class StagedDataset(StagingBase, table=True): + """One logical input dataset of a country's catalog.""" + + __tablename__ = "stage_catalog_datasets" + __table_args__ = TEMPORARY_UNTIL_COMMIT + + country_id: str = Field(sa_type=sa.Text, primary_key=True) + id: UUID = Field(sa_type=sa.Uuid) + name: str = Field(sa_type=sa.Text, primary_key=True) + description: str | None = Field(default=None, sa_type=sa.Text) + year: int = Field(sa_type=sa.Integer) + + +class StagedRegion(StagingBase, table=True): + """One region of a country's catalog, naming its default dataset.""" + + __tablename__ = "stage_catalog_regions" + __table_args__ = TEMPORARY_UNTIL_COMMIT + + country_id: str = Field(sa_type=sa.Text, primary_key=True) + id: UUID = Field(sa_type=sa.Uuid) + code: str = Field(sa_type=sa.Text, primary_key=True) + label: str = Field(sa_type=sa.Text) + region_type: str = Field(sa_type=sa.Text) + requires_filter: bool = Field(sa_type=sa.Boolean) + filter_field: str | None = Field(default=None, sa_type=sa.Text) + filter_value: str | None = Field(default=None, sa_type=sa.Text) + filter_strategy: str | None = Field(default=None, sa_type=sa.Text) + parent_code: str | None = Field(default=None, sa_type=sa.Text) + state_code: str | None = Field(default=None, sa_type=sa.Text) + state_name: str | None = Field(default=None, sa_type=sa.Text) + default_dataset_name: str = Field(sa_type=sa.Text) + + +STAGING_MODELS = ( + StagedModel, + StagedVariable, + StagedParameterNode, + StagedParameter, + StagedParameterValue, + StagedDataset, + StagedRegion, +) +"""The staging tables, in the order publication COPYs each country into them.""" diff --git a/policyengine_api/data/v2/catalog/publication_statistics.py b/policyengine_api/data/v2/catalog/publication_statistics.py index a13ad89b7..d3447fb68 100644 --- a/policyengine_api/data/v2/catalog/publication_statistics.py +++ b/policyengine_api/data/v2/catalog/publication_statistics.py @@ -35,7 +35,8 @@ ) if TYPE_CHECKING: - from sqlalchemy import Connection, Engine + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session CATALOG_STATISTICS_TABLES: Final = ( "datasets", @@ -48,13 +49,18 @@ ) """The catalog tables publication analyzes, in name order.""" -_HAS_MAINTAIN = sa.text( - "SELECT has_table_privilege(current_user, :qualified_table, 'MAINTAIN')" -) + +def _has_maintain(qualified_table: str) -> sa.Select[tuple[bool]]: + """Select whether the current role holds ``MAINTAIN`` on the table.""" + return sa.select( + sa.func.has_table_privilege( + sa.func.current_user(), qualified_table, "MAINTAIN", type_=sa.Boolean + ) + ) -def require_analyze_privilege(connection: Connection) -> None: - """Raise unless the connection's role may ``ANALYZE`` every catalog table. +def require_analyze_privilege(session: Session) -> None: + """Raise unless the session's role may ``ANALYZE`` every catalog table. An owner holds every privilege, so ``has_table_privilege`` answers for ownership and a ``MAINTAIN`` grant alike. @@ -62,9 +68,7 @@ def require_analyze_privilege(connection: Connection) -> None: missing = [ table for table in CATALOG_STATISTICS_TABLES - if not connection.execute( - _HAS_MAINTAIN, {"qualified_table": f"public.{table}"} - ).scalar_one() + if not session.execute(_has_maintain(f"public.{table}")).scalar_one() ] if missing: msg = ( @@ -90,16 +94,17 @@ class CatalogStatisticsRefresh: failure_type: str | None = None -def analyze_catalog_tables(engine: Engine) -> CatalogStatisticsRefresh: +def analyze_catalog_tables(sessions: sessionmaker[Session]) -> CatalogStatisticsRefresh: """Run one ``ANALYZE`` over the catalog tables; a failure is returned, not raised. - It runs after the publication committed, so a failure, of any kind, never - undoes it; the next publication analyzes again. + It runs in a transaction of its own, after the publication committed, so a + failure, of any kind, never undoes it; the next publication analyzes again. + ``ANALYZE`` has no ORM form, so it is SQL text (a rule exception). """ tables = ", ".join(f"public.{table}" for table in CATALOG_STATISTICS_TABLES) try: - with engine.begin() as connection: - connection.execute(sa.text(f"ANALYZE {tables}")) + with sessions.begin() as session: + session.execute(sa.text(f"ANALYZE {tables}")) except Exception as error: # noqa: BLE001 # the publication has committed; the next one analyzes again return CatalogStatisticsRefresh(analyzed=(), failure_type=_failure(error)) return CatalogStatisticsRefresh(analyzed=CATALOG_STATISTICS_TABLES) diff --git a/policyengine_api/data/v2/catalog/publication_tables.py b/policyengine_api/data/v2/catalog/publication_tables.py deleted file mode 100644 index 8cc867b3d..000000000 --- a/policyengine_api/data/v2/catalog/publication_tables.py +++ /dev/null @@ -1,23 +0,0 @@ -"""The v2 catalog tables that publication compares with and inserts into.""" - -from __future__ import annotations - -from policyengine_api.data.v2.models import ( - Dataset, - Parameter, - ParameterNode, - ParameterValue, - Region, - TaxBenefitModel, - TaxBenefitModelVersion, - Variable, -) - -DATASETS = Dataset.__table__ -MODELS = TaxBenefitModel.__table__ -MODEL_VERSIONS = TaxBenefitModelVersion.__table__ -PARAMETERS = Parameter.__table__ -PARAMETER_NODES = ParameterNode.__table__ -PARAMETER_VALUES = ParameterValue.__table__ -REGIONS = Region.__table__ -VARIABLES = Variable.__table__ diff --git a/policyengine_api/data/v2/catalog/spm_availability.py b/policyengine_api/data/v2/catalog/spm_availability.py index acc30ef9c..4286457eb 100644 --- a/policyengine_api/data/v2/catalog/spm_availability.py +++ b/policyengine_api/data/v2/catalog/spm_availability.py @@ -25,27 +25,27 @@ import logging import os -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, cast import httpx import sqlalchemy as sa from pydantic import ValidationError +from sqlmodel import col -from policyengine_api.data.v2.catalog.publication_tables import ( - MODEL_VERSIONS, - MODELS, -) from policyengine_api.data.v2.catalog.publication_types import ( CatalogPublicationError, SPMAvailabilityRecording, ) +from policyengine_api.data.v2.models import TaxBenefitModel, TaxBenefitModelVersion from policyengine_api.data.v2.settings import V2ConfigurationError from policyengine_api.spm import SPMSelection if TYPE_CHECKING: from collections.abc import Callable, Iterable, Mapping - from sqlalchemy import Connection, Engine + from sqlalchemy.engine import CursorResult + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session from policyengine_api.data.v2.catalog.records import NormalizedCatalog @@ -136,7 +136,7 @@ def fetch_simulation_versions( def record_spm_availability( - connection: Connection, + session: Session, *, model_name: str, version: str, @@ -146,43 +146,52 @@ def record_spm_availability( Return whether the version was changed. """ - model_ids = sa.select(MODELS.c.id).where(MODELS.c.name == model_name) - result = connection.execute( - sa.update(MODEL_VERSIONS) + model_ids = sa.select(col(TaxBenefitModel.id)).where( + col(TaxBenefitModel.name) == model_name + ) + result = session.execute( + sa.update(TaxBenefitModelVersion) .where( - MODEL_VERSIONS.c.model_id.in_(model_ids), - MODEL_VERSIONS.c.version == version, - MODEL_VERSIONS.c.spm_availability.is_(None), + col(TaxBenefitModelVersion.model_id).in_(model_ids), + col(TaxBenefitModelVersion.version) == version, + col(TaxBenefitModelVersion.spm_availability).is_(None), ) - .values(spm_availability=dict(availability)) + .values(spm_availability=dict(availability)), + # No version row is loaded in the Session, so none needs refreshing. + execution_options={"synchronize_session": False}, ) - return bool(result.rowcount) + return bool(cast("CursorResult[Any]", result).rowcount) def read_unrecorded_versions( - connection: Connection, versions: Iterable[tuple[str, str]] + session: Session, versions: Iterable[tuple[str, str]] ) -> set[tuple[str, str]]: """Return the (model name, version) pairs whose SPM availability is unrecorded.""" requested = list(versions) if not requested: return set() - rows = connection.execute( - sa.select(MODELS.c.name, MODEL_VERSIONS.c.version) - .join(MODEL_VERSIONS, MODEL_VERSIONS.c.model_id == MODELS.c.id) + rows = session.execute( + sa.select(col(TaxBenefitModel.name), col(TaxBenefitModelVersion.version)) + .join( + TaxBenefitModelVersion, + col(TaxBenefitModelVersion.model_id) == col(TaxBenefitModel.id), + ) .where( - sa.tuple_(MODELS.c.name, MODEL_VERSIONS.c.version).in_(requested), - MODEL_VERSIONS.c.spm_availability.is_(None), + sa.tuple_( + col(TaxBenefitModel.name), col(TaxBenefitModelVersion.version) + ).in_(requested), + col(TaxBenefitModelVersion.spm_availability).is_(None), ) ).all() return {(row.name, row.version) for row in rows} def _still_unrecorded( - connection: Connection, catalog: NormalizedCatalog + session: Session, catalog: NormalizedCatalog ) -> tuple[tuple[str, str], ...]: """Return the catalog's versions, by country, whose availability is unrecorded.""" unrecorded = read_unrecorded_versions( - connection, + session, [ (country.model.name, country.model_version.version) for country in catalog.countries @@ -196,7 +205,7 @@ def _still_unrecorded( def record_published_spm_availability( - engine: Engine, + sessions: sessionmaker[Session], catalog: NormalizedCatalog, environ: Mapping[str, str] | None = None, *, @@ -215,8 +224,8 @@ def record_published_spm_availability( try: versions = fetch_versions(url) except CatalogPublicationError as error: - with engine.begin() as connection: - not_recorded = _still_unrecorded(connection, catalog) + with sessions.begin() as session: + not_recorded = _still_unrecorded(session, catalog) if not_recorded: LOGGER.warning( "SPM availability was not recorded; the next publication run " @@ -227,14 +236,14 @@ def record_published_spm_availability( not_recorded=not_recorded, versions_unreadable=str(error) ) recorded: list[tuple[str, str, bool]] = [] - with engine.begin() as connection: + with sessions.begin() as session: for country in catalog.countries: version = country.model_version.version availability = spm_availability( country.country_id, catalog.policyengine_version, versions ) if availability is not None and record_spm_availability( - connection, + session, model_name=country.model.name, version=version, availability=availability, @@ -242,5 +251,5 @@ def record_published_spm_availability( recorded.append( (country.country_id, version, bool(availability["available"])) ) - not_recorded = _still_unrecorded(connection, catalog) + not_recorded = _still_unrecorded(session, catalog) return SPMAvailabilityRecording(recorded=tuple(recorded), not_recorded=not_recorded) diff --git a/policyengine_api/data/v2/database.py b/policyengine_api/data/v2/database.py index 3e3616bef..01a14fc58 100644 --- a/policyengine_api/data/v2/database.py +++ b/policyengine_api/data/v2/database.py @@ -68,7 +68,7 @@ def _url_fingerprint(settings: V2DatabaseSettings) -> tuple[object, ...]: ) -def build_v2_engine(settings: V2DatabaseSettings) -> Engine: +def _build_v2_engine(settings: V2DatabaseSettings) -> Engine: """Construct an unconnected SQLModel engine for an explicit v2 target.""" return create_engine( settings.connection.url, @@ -98,24 +98,32 @@ def _refuse_flush(*_flush_arguments: object) -> None: raise ReadOnlySessionError(msg) -def build_v2_read_session_factory(engine: Engine) -> sessionmaker[Session]: +def build_v2_read_session_factory( + session_factory: sessionmaker[Session], +) -> sessionmaker[Session]: """Build a factory of Sessions for v2 metadata reads, run without a transaction. - The sessions share ``engine``'s pool in autocommit mode, so psycopg sends - each statement on its own: no BEGIN before the first read and no ROLLBACK - when the session closes. Only the metadata reader uses them: each of its - reads is one statement on a published catalog version. After publication - the version's row changes only in its time-period options, its - ``catalog_last_published_at`` (set by each publication of it), its - ``catalog_values_pruned_at`` (set by pruning, cleared by restoration) and - its ``spm_availability`` (recorded once after publishing it), and - its other rows only when pruning deletes its current-law values, tree rows - and search file, which restoration writes back identically. A read that - finds none of those rows reads ``catalog_values_pruned_at`` again, so no - common snapshot is needed. The sessions refuse to flush added or changed rows; + The sessions share the pool of ``session_factory``'s engine in autocommit + mode, so psycopg sends each statement on its own: no BEGIN before the first + read and no ROLLBACK when the session closes. Only the metadata reader uses + them: each of its reads is one statement on a published catalog version. + After publication the version's row changes only in its time-period + options, its ``catalog_last_published_at`` (set by each publication of it), + its ``catalog_values_pruned_at`` (set by pruning, cleared by restoration) + and its ``spm_availability`` (recorded once after publishing it), and its + other rows only when pruning deletes its current-law values, tree rows and + search file, which restoration writes back identically. A read that finds + none of those rows reads ``catalog_values_pruned_at`` again, so no common + snapshot is needed. The sessions refuse to flush added or changed rows; statements passed directly to ``execute`` are not checked, so they must stay reads. The pool restores the ordinary mode when a connection returns. """ + engine: Engine = session_factory.kw["bind"] + return _read_session_factory(engine) + + +def _read_session_factory(engine: Engine) -> sessionmaker[Session]: + """Build the read Session factory on ``engine``'s pool, as described above.""" factory = sessionmaker( bind=engine.execution_options(isolation_level="AUTOCOMMIT"), class_=Session, @@ -181,7 +189,7 @@ def _discard_inherited_state(current_pid: int) -> None: _engine_state.read_session_factory = None -def get_v2_engine(settings: V2DatabaseSettings | None = None) -> Engine: +def _v2_engine(settings: V2DatabaseSettings | None = None) -> Engine: """Return the one lazy v2 runtime engine owned by this process.""" current_pid = os.getpid() with _state_lock: @@ -202,7 +210,7 @@ def get_v2_engine(settings: V2DatabaseSettings | None = None) -> Engine: raise V2ConfigurationError(msg) return _engine_state.engine - _engine_state.engine = build_v2_engine(selected_settings) + _engine_state.engine = _build_v2_engine(selected_settings) _engine_state.engine_pid = current_pid _engine_state.engine_url_fingerprint = fingerprint return _engine_state.engine @@ -212,7 +220,7 @@ def get_v2_session_factory( settings: V2DatabaseSettings | None = None, ) -> sessionmaker[Session]: """Return the process-owned SQLModel Session factory without opening a session.""" - engine = get_v2_engine(settings) + engine = _v2_engine(settings) with _state_lock: if _engine_state.session_factory is None: _engine_state.session_factory = build_v2_session_factory(engine) @@ -226,10 +234,10 @@ def get_v2_read_session_factory( See ``build_v2_read_session_factory``. """ - engine = get_v2_engine(settings) + engine = _v2_engine(settings) with _state_lock: if _engine_state.read_session_factory is None: - _engine_state.read_session_factory = build_v2_read_session_factory(engine) + _engine_state.read_session_factory = _read_session_factory(engine) return _engine_state.read_session_factory diff --git a/policyengine_api/data/v2/household_migration_qualification.py b/policyengine_api/data/v2/household_migration_qualification.py index ce679323e..21a0720aa 100644 --- a/policyengine_api/data/v2/household_migration_qualification.py +++ b/policyengine_api/data/v2/household_migration_qualification.py @@ -7,13 +7,7 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Protocol -from alembic.config import Config -from alembic.migration import MigrationContext -from alembic.script import ScriptDirectory -from sqlalchemy import Connection, Engine, func, inspect, select -from sqlalchemy.exc import NoInspectionAvailable -from sqlalchemy.pool import NullPool -from sqlmodel import create_engine +from sqlalchemy import func, select from policyengine_api.data.v2.models import ( Household, @@ -22,6 +16,7 @@ Simulation, UserHouseholdAssociation, ) +from policyengine_api.data.v2.pending_revisions import v2_revision_is_pending from policyengine_api.data.v2.settings import ( V2ConfigurationError, V2DatabaseSettings, @@ -30,9 +25,12 @@ if TYPE_CHECKING: from collections.abc import Callable, Collection, Mapping + from contextlib import AbstractContextManager + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session HOUSEHOLD_MIGRATION_REVISION = "724b1b11a33e" -V2_ALEMBIC_CONFIG = "alembic-v2.ini" class ScalarExecutor(Protocol): @@ -153,52 +151,47 @@ def require_no_retained_household_data(counts: HouseholdDataCounts) -> None: raise RetainedHouseholdDataError(counts) -def build_qualification_engine(settings: V2DatabaseSettings) -> Engine: - """Build an isolated connection pool for one qualification attempt.""" - return create_engine(settings.connection.url, poolclass=NullPool) +def open_qualification_sessions( + settings: V2DatabaseSettings, +) -> AbstractContextManager[sessionmaker[Session]]: + """Open Session factories for one qualification attempt. + Their engine keeps no pool, and every transaction is READ ONLY. + """ + from policyengine_api.data.v2.database import unpooled_v2_read_only_sessions -def _read_and_require_counts(connection: Connection) -> HouseholdDataCounts: - try: - existing_tables = inspect(connection).get_table_names(schema="public") - except NoInspectionAvailable: - existing_tables = None - counts = read_household_data_counts(connection, existing_tables) + return unpooled_v2_read_only_sessions(settings.connection.url) + + +def _read_and_require_counts(session: Session) -> HouseholdDataCounts: + from policyengine_api.data.v2.database import v2_schema_inspector + + existing_tables = v2_schema_inspector(session).get_table_names(schema="public") + counts = read_household_data_counts(session, existing_tables) require_no_retained_household_data(counts) return counts -def household_migration_is_pending(connection: Connection) -> bool: +def household_migration_is_pending(session: Session) -> bool: """Return whether the Stage 11 household revision is in the upgrade path.""" - current_heads = MigrationContext.configure(connection).get_current_heads() - revisions = ScriptDirectory.from_config( - Config(V2_ALEMBIC_CONFIG) - ).iterate_revisions("heads", current_heads) - return HOUSEHOLD_MIGRATION_REVISION in { - migration.revision for migration in revisions - } + return v2_revision_is_pending(session, HOUSEHOLD_MIGRATION_REVISION) def qualify_household_migration_target( environ: Mapping[str, str] | None = None, *, - engine_builder: Callable[[V2DatabaseSettings], Engine] = ( - build_qualification_engine - ), + session_factories: Callable[ + [V2DatabaseSettings], AbstractContextManager[sessionmaker[Session]] + ] = open_qualification_sessions, ) -> HouseholdMigrationQualification: - """Qualify the configured Supabase target without changing it.""" + """Qualify the configured Supabase target without changing it. + + The rows are read in one READ ONLY transaction, rolled back when the + session closes. + """ settings = load_v2_migration_database_settings(environ) - engine = engine_builder(settings) - try: - with engine.connect() as connection: - transaction = connection.begin() - try: - connection.exec_driver_sql("SET TRANSACTION READ ONLY") - counts = _read_and_require_counts(connection) - finally: - transaction.rollback() - finally: - engine.dispose() + with session_factories(settings) as sessions, sessions() as session: + counts = _read_and_require_counts(session) return HouseholdMigrationQualification( environment=settings.target.environment, project_ref=settings.target.project_ref, @@ -209,31 +202,26 @@ def qualify_household_migration_target( def qualify_household_migration_if_pending( environ: Mapping[str, str] | None = None, *, - engine_builder: Callable[[V2DatabaseSettings], Engine] = ( - build_qualification_engine - ), - pending_checker: Callable[[Connection], bool] = household_migration_is_pending, + session_factories: Callable[ + [V2DatabaseSettings], AbstractContextManager[sessionmaker[Session]] + ] = open_qualification_sessions, + pending_checker: Callable[[Session], bool] = household_migration_is_pending, ) -> HouseholdMigrationQualification: - """Qualify affected rows only while the Stage 11 revision is pending.""" + """Qualify affected rows only while the Stage 11 revision is pending. + + The revision check and the rows are read in one READ ONLY transaction, + rolled back when the session closes. + """ settings = load_v2_migration_database_settings(environ) - engine = engine_builder(settings) - try: - with engine.connect() as connection: - transaction = connection.begin() - try: - connection.exec_driver_sql("SET TRANSACTION READ ONLY") - if not pending_checker(connection): - return HouseholdMigrationQualification( - environment=settings.target.environment, - project_ref=settings.target.project_ref, - counts=HouseholdDataCounts(0, 0, 0, 0, 0), - required=False, - ) - counts = _read_and_require_counts(connection) - finally: - transaction.rollback() - finally: - engine.dispose() + with session_factories(settings) as sessions, sessions() as session: + if not pending_checker(session): + return HouseholdMigrationQualification( + environment=settings.target.environment, + project_ref=settings.target.project_ref, + counts=HouseholdDataCounts(0, 0, 0, 0, 0), + required=False, + ) + counts = _read_and_require_counts(session) return HouseholdMigrationQualification( environment=settings.target.environment, project_ref=settings.target.project_ref, diff --git a/policyengine_api/data/v2/migration_target.py b/policyengine_api/data/v2/migration_target.py index 21c2a2a5c..6c3b6c7f4 100644 --- a/policyengine_api/data/v2/migration_target.py +++ b/policyengine_api/data/v2/migration_target.py @@ -7,7 +7,7 @@ from datetime import date from typing import TYPE_CHECKING -from sqlalchemy import Connection, MetaData, inspect, text +from sqlalchemy import func, select from sqlalchemy.engine import URL, make_url from sqlalchemy.exc import ArgumentError @@ -21,7 +21,10 @@ ) if TYPE_CHECKING: - from collections.abc import Mapping + from collections.abc import Collection, Mapping + + from sqlalchemy.engine import Inspector + from sqlmodel import Session V2_ALEMBIC_DISPOSABLE_TEST = "V2_ALEMBIC_DISPOSABLE_TEST" V2_ALEMBIC_HEAD_REVISION = "bc334f9877b7" @@ -136,12 +139,24 @@ def load_v2_alembic_settings( ) -def qualify_v2_connection( - connection: Connection, +def _schema_inspector(session: Session) -> Inspector: + """Return the Inspector of the session's database, inside its transaction.""" + from policyengine_api.data.v2.database import v2_schema_inspector + + return v2_schema_inspector(session) + + +def qualify_v2_target( + session: Session, settings: V2AlembicSettings, ) -> None: - """Verify live target identity and first-use state before Alembic runs.""" - if connection.dialect.name != "postgresql": + """Verify live target identity and first-use state before Alembic runs. + + The reads run in the session's transaction; the Alembic environment's + session shares the migration's connection and transaction. + """ + inspector = _schema_inspector(session) + if inspector.dialect.name != "postgresql": msg = "v2 Alembic requires a Postgres connection" raise V2MigrationTargetError(msg) if settings.disposable_test: @@ -151,21 +166,23 @@ def qualify_v2_connection( if target is None: msg = "persistent v2 Alembic target is missing" raise V2MigrationTargetError(msg) - identity = connection.execute(text("SELECT current_database(), current_user")).one() + identity = session.execute( + select(func.current_database(), func.current_user()) + ).one() if identity[0] != target.database_name or identity[1] != target.migration_role: msg = ( "the live database or migration identity does not match the configured " "v2 target" ) raise V2MigrationTargetError(msg) - can_create = connection.execute( - text("SELECT has_schema_privilege(current_user, 'public', 'CREATE')") + can_create = session.execute( + select(func.has_schema_privilege(func.current_user(), "public", "CREATE")) ).scalar_one() if can_create is not True: msg = "the configured v2 migration identity lacks public schema CREATE" raise V2MigrationTargetError(msg) - public_tables = set(inspect(connection).get_table_names(schema="public")) + public_tables = set(inspector.get_table_names(schema="public")) if "alembic_version" not in public_tables: if not target.freshness_audit_passed: msg = "the configured first-use freshness audit has not passed" @@ -178,11 +195,14 @@ def qualify_v2_connection( raise V2MigrationTargetError(msg) -def validate_v2_head_schema(connection: Connection, metadata: MetaData) -> None: - """Require live application tables to match authoritative ORM metadata.""" - public_tables = set(inspect(connection).get_table_names(schema="public")) +def validate_v2_head_schema(session: Session, table_names: Collection[str]) -> None: + """Require the live application tables to be exactly ``table_names``. + + ``table_names`` are the tables of the v2 mapped classes, ``V2_TABLE_NAMES``. + """ + public_tables = set(_schema_inspector(session).get_table_names(schema="public")) application_tables = public_tables - {"alembic_version"} - metadata_tables = {table.name for table in metadata.tables.values()} + metadata_tables = set(table_names) unexpected = application_tables - metadata_tables missing = metadata_tables - application_tables if unexpected or missing: diff --git a/policyengine_api/data/v2/models/__init__.py b/policyengine_api/data/v2/models/__init__.py index dfa9c0bdf..2802d5a03 100644 --- a/policyengine_api/data/v2/models/__init__.py +++ b/policyengine_api/data/v2/models/__init__.py @@ -1,6 +1,7 @@ """Controlled imports and metadata export for the reviewed v2 schema.""" from sqlmodel import SQLModel +from sqlmodel.main import default_registry from policyengine_api.data.v2.metadata_validation import ( validate_v2_metadata_table_names, @@ -112,12 +113,21 @@ ) V2_METADATA = SQLModel.metadata -validate_v2_metadata_table_names(V2_METADATA.tables) +# The registry that maps the v2 table classes: SQLModel's own, whose metadata is +# V2_METADATA. Every v2 table has a mapped class (rule api.data.orm-only), so +# V2_TABLE_NAMES, the tables its classes map, are all of V2_METADATA's tables. +V2_REGISTRY = default_registry +V2_TABLE_NAMES = frozenset( + mapper.class_.__tablename__ for mapper in V2_REGISTRY.mappers +) +validate_v2_metadata_table_names(V2_TABLE_NAMES) __all__ = [ "INVITATION_USER_TYPES", "SIGNED_IN_USER_TYPES", "V2_METADATA", + "V2_REGISTRY", + "V2_TABLE_NAMES", "AggregateOutput", "AggregateType", "BudgetSummary", diff --git a/policyengine_api/data/v2/pending_revisions.py b/policyengine_api/data/v2/pending_revisions.py new file mode 100644 index 000000000..d00b6357c --- /dev/null +++ b/policyengine_api/data/v2/pending_revisions.py @@ -0,0 +1,30 @@ +"""Whether a v2 Alembic revision is still to be applied to a database. + +The migration qualification commands check their own revision before they +count rows. Alembic's ``MigrationContext`` reads the database's current heads +from its version table through a Connection, so it gets the Session's own +connection and reads inside the Session's transaction (rule api.data.orm-only +names this exception). +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from alembic.config import Config +from alembic.migration import MigrationContext +from alembic.script import ScriptDirectory + +if TYPE_CHECKING: + from sqlmodel import Session + +V2_ALEMBIC_CONFIG = "alembic-v2.ini" + + +def v2_revision_is_pending(session: Session, revision: str) -> bool: + """Return whether ``revision`` is in the upgrade path from the database's heads.""" + current_heads = MigrationContext.configure(session.connection()).get_current_heads() + revisions = ScriptDirectory.from_config( + Config(V2_ALEMBIC_CONFIG) + ).iterate_revisions("heads", current_heads) + return revision in {migration.revision for migration in revisions} diff --git a/policyengine_api/data/v2/policy_migration_qualification.py b/policyengine_api/data/v2/policy_migration_qualification.py index beb03db24..ed95974a5 100644 --- a/policyengine_api/data/v2/policy_migration_qualification.py +++ b/policyengine_api/data/v2/policy_migration_qualification.py @@ -7,15 +7,10 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Protocol -from alembic.config import Config -from alembic.migration import MigrationContext -from alembic.script import ScriptDirectory -from sqlalchemy import Connection, Engine, func, inspect, select -from sqlalchemy.exc import NoInspectionAvailable -from sqlalchemy.pool import NullPool -from sqlmodel import create_engine +from sqlalchemy import func, select from policyengine_api.data.v2.models import ParameterValue, Policy, UserPolicy +from policyengine_api.data.v2.pending_revisions import v2_revision_is_pending from policyengine_api.data.v2.settings import ( V2ConfigurationError, V2DatabaseSettings, @@ -24,9 +19,12 @@ if TYPE_CHECKING: from collections.abc import Callable, Collection, Mapping + from contextlib import AbstractContextManager + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session POLICY_MIGRATION_REVISION = "711ec2f0a5a5" -V2_ALEMBIC_CONFIG = "alembic-v2.ini" class ScalarExecutor(Protocol): @@ -136,54 +134,47 @@ def require_no_retained_policy_data(counts: PolicyDataCounts) -> None: raise RetainedPolicyDataError(counts) -def build_qualification_engine(settings: V2DatabaseSettings) -> Engine: - """Build an isolated connection pool for one qualification attempt.""" - return create_engine(settings.connection.url, poolclass=NullPool) +def open_qualification_sessions( + settings: V2DatabaseSettings, +) -> AbstractContextManager[sessionmaker[Session]]: + """Open Session factories for one qualification attempt. + Their engine keeps no pool, and every transaction is READ ONLY. + """ + from policyengine_api.data.v2.database import unpooled_v2_read_only_sessions -def _read_and_require_counts(connection: Connection) -> PolicyDataCounts: - try: - existing_tables = inspect(connection).get_table_names(schema="public") - except NoInspectionAvailable: - existing_tables = None - counts = read_policy_data_counts(connection, existing_tables) - require_no_retained_policy_data(counts) - return counts + return unpooled_v2_read_only_sessions(settings.connection.url) -def _qualify_connection(connection: Connection) -> PolicyDataCounts: - transaction = connection.begin() - try: - connection.exec_driver_sql("SET TRANSACTION READ ONLY") - return _read_and_require_counts(connection) - finally: - transaction.rollback() +def _read_and_require_counts(session: Session) -> PolicyDataCounts: + from policyengine_api.data.v2.database import v2_schema_inspector + existing_tables = v2_schema_inspector(session).get_table_names(schema="public") + counts = read_policy_data_counts(session, existing_tables) + require_no_retained_policy_data(counts) + return counts -def policy_migration_is_pending(connection: Connection) -> bool: + +def policy_migration_is_pending(session: Session) -> bool: """Return whether the Phase 10 policy revision is in the upgrade path.""" - current_heads = MigrationContext.configure(connection).get_current_heads() - revisions = ScriptDirectory.from_config( - Config(V2_ALEMBIC_CONFIG) - ).iterate_revisions("heads", current_heads) - return POLICY_MIGRATION_REVISION in {migration.revision for migration in revisions} + return v2_revision_is_pending(session, POLICY_MIGRATION_REVISION) def qualify_policy_migration_target( environ: Mapping[str, str] | None = None, *, - engine_builder: Callable[[V2DatabaseSettings], Engine] = ( - build_qualification_engine - ), + session_factories: Callable[ + [V2DatabaseSettings], AbstractContextManager[sessionmaker[Session]] + ] = open_qualification_sessions, ) -> PolicyMigrationQualification: - """Qualify the configured Supabase target without changing it.""" + """Qualify the configured Supabase target without changing it. + + The rows are read in one READ ONLY transaction, rolled back when the + session closes. + """ settings = load_v2_migration_database_settings(environ) - engine = engine_builder(settings) - try: - with engine.connect() as connection: - counts = _qualify_connection(connection) - finally: - engine.dispose() + with session_factories(settings) as sessions, sessions() as session: + counts = _read_and_require_counts(session) return PolicyMigrationQualification( environment=settings.target.environment, project_ref=settings.target.project_ref, @@ -194,31 +185,26 @@ def qualify_policy_migration_target( def qualify_policy_migration_if_pending( environ: Mapping[str, str] | None = None, *, - engine_builder: Callable[[V2DatabaseSettings], Engine] = ( - build_qualification_engine - ), - pending_checker: Callable[[Connection], bool] = policy_migration_is_pending, + session_factories: Callable[ + [V2DatabaseSettings], AbstractContextManager[sessionmaker[Session]] + ] = open_qualification_sessions, + pending_checker: Callable[[Session], bool] = policy_migration_is_pending, ) -> PolicyMigrationQualification: - """Qualify predecessor rows only while the Phase 10 revision is pending.""" + """Qualify predecessor rows only while the Phase 10 revision is pending. + + The revision check and the rows are read in one READ ONLY transaction, + rolled back when the session closes. + """ settings = load_v2_migration_database_settings(environ) - engine = engine_builder(settings) - try: - with engine.connect() as connection: - transaction = connection.begin() - try: - connection.exec_driver_sql("SET TRANSACTION READ ONLY") - if not pending_checker(connection): - return PolicyMigrationQualification( - environment=settings.target.environment, - project_ref=settings.target.project_ref, - counts=PolicyDataCounts(0, 0, 0), - required=False, - ) - counts = _read_and_require_counts(connection) - finally: - transaction.rollback() - finally: - engine.dispose() + with session_factories(settings) as sessions, sessions() as session: + if not pending_checker(session): + return PolicyMigrationQualification( + environment=settings.target.environment, + project_ref=settings.target.project_ref, + counts=PolicyDataCounts(0, 0, 0), + required=False, + ) + counts = _read_and_require_counts(session) return PolicyMigrationQualification( environment=settings.target.environment, project_ref=settings.target.project_ref, diff --git a/policyengine_api/data/v2/postgres_system_catalog.py b/policyengine_api/data/v2/postgres_system_catalog.py new file mode 100644 index 000000000..dff03b119 --- /dev/null +++ b/policyengine_api/data/v2/postgres_system_catalog.py @@ -0,0 +1,88 @@ +"""Mapped classes of the PostgreSQL system catalog tables the reconciliation reads. + +PostgreSQL owns these tables and views, in its ``pg_catalog`` schema, which every +search path includes. Each class names only the columns the reconciliation +reads and a key, and is only ever read. They are SQLModel classes on a registry +of their own, so they stay out of ``V2_METADATA``, which Alembic compares with +the v2 schema. The access control lists (PostgreSQL's ``aclitem[]``) are never +read as values, only passed to ``aclexplode``, which returns one row per entry. +""" + +from __future__ import annotations + +from sqlalchemy import Boolean, SmallInteger, String +from sqlalchemy.dialects.postgresql import OID +from sqlalchemy.orm import registry +from sqlalchemy.types import UserDefinedType +from sqlmodel import Field, SQLModel + + +class AccessControlList(UserDefinedType[list[str]]): + """PostgreSQL's ``aclitem[]``, which SQLAlchemy has no type for. + + The lists are only passed to ``aclexplode``, never read as values. + """ + + cache_ok = True + + def get_col_spec(self, **_options: object) -> str: + """Name the type as PostgreSQL does.""" + return "aclitem[]" + + +class PostgresSystemCatalogTable(SQLModel, registry=registry()): + """The base of the system catalog classes, on a registry of their own.""" + + +class PgNamespace(PostgresSystemCatalogTable, table=True): + """A schema.""" + + __tablename__ = "pg_namespace" + + oid: int = Field(sa_type=OID, primary_key=True) + nspname: str = Field(sa_type=String) + + +class PgClass(PostgresSystemCatalogTable, table=True): + """A table or a table-like object, such as a view or a sequence.""" + + __tablename__ = "pg_class" + + oid: int = Field(sa_type=OID, primary_key=True) + relname: str = Field(sa_type=String) + relnamespace: int = Field(sa_type=OID) + relkind: str = Field(sa_type=String) + relacl: list[str] | None = Field(default=None, sa_type=AccessControlList) + + +class PgAttribute(PostgresSystemCatalogTable, table=True): + """A column of a table, numbered from 1; system columns are below zero.""" + + __tablename__ = "pg_attribute" + + attrelid: int = Field(sa_type=OID, primary_key=True) + attnum: int = Field(sa_type=SmallInteger, primary_key=True) + attname: str = Field(sa_type=String) + attisdropped: bool = Field(sa_type=Boolean) + attacl: list[str] | None = Field(default=None, sa_type=AccessControlList) + + +class PgRoles(PostgresSystemCatalogTable, table=True): + """A role (the ``pg_roles`` view of ``pg_authid``, readable by every role).""" + + __tablename__ = "pg_roles" + + oid: int = Field(sa_type=OID, primary_key=True) + rolname: str = Field(sa_type=String) + + +class PgDefaultAcl(PostgresSystemCatalogTable, table=True): + """The privileges a role's new objects of one type get, in one schema or all.""" + + __tablename__ = "pg_default_acl" + + oid: int = Field(sa_type=OID, primary_key=True) + defaclrole: int = Field(sa_type=OID) + defaclnamespace: int = Field(sa_type=OID) + defaclobjtype: str = Field(sa_type=String) + defaclacl: list[str] | None = Field(default=None, sa_type=AccessControlList) diff --git a/policyengine_api/data/v2/privilege_reconciliation.py b/policyengine_api/data/v2/privilege_reconciliation.py index 692fccfad..1b6b8d09e 100644 --- a/policyengine_api/data/v2/privilege_reconciliation.py +++ b/policyengine_api/data/v2/privilege_reconciliation.py @@ -45,14 +45,20 @@ from pathlib import Path from typing import TYPE_CHECKING -from sqlalchemy import bindparam, text -from sqlalchemy.pool import NullPool -from sqlmodel import create_engine +from sqlalchemy import Text, case, cast, false, func, or_, select, text, true +from sqlmodel import col from policyengine_api.data.v2.migration_target import ( V2AlembicSettings, load_v2_alembic_settings, - qualify_v2_connection, + qualify_v2_target, +) +from policyengine_api.data.v2.postgres_system_catalog import ( + PgAttribute, + PgClass, + PgDefaultAcl, + PgNamespace, + PgRoles, ) from policyengine_api.data.v2.privilege_plans import ( SCHEMA, @@ -82,8 +88,11 @@ if TYPE_CHECKING: from collections.abc import Callable, Collection, Iterable, Mapping, Sequence + from contextlib import AbstractContextManager - from sqlalchemy import Connection, Engine + from sqlalchemy.orm import sessionmaker + from sqlalchemy.sql.selectable import LateralFromClause + from sqlmodel import Session # Names other modules import from here; the planning and reporting half lives # in privilege_plans. @@ -123,118 +132,121 @@ # --- Database access ------------------------------------------------------- -_GRANTED_PRIVILEGES = text( - """ - SELECT grantee_role.rolname AS role_name, - table_class.relname AS table_name, - acl_entry.privilege_type AS privilege - FROM pg_class AS table_class - JOIN pg_namespace AS table_namespace - ON table_namespace.oid = table_class.relnamespace - CROSS JOIN LATERAL aclexplode(table_class.relacl) AS acl_entry - JOIN pg_roles AS grantee_role ON grantee_role.oid = acl_entry.grantee - WHERE table_namespace.nspname = :schema - AND table_class.relkind IN ('r', 'p', 'S', 'v', 'm') - AND grantee_role.rolname IN :roles - """ -).bindparams(bindparam("roles", expanding=True)) - -_EXISTING_ROLES = text( - "SELECT rolname FROM pg_roles WHERE rolname IN :roles" -).bindparams(bindparam("roles", expanding=True)) - -_PUBLIC_TABLES = text( - """ - SELECT table_class.relname - FROM pg_class AS table_class - JOIN pg_namespace AS table_namespace - ON table_namespace.oid = table_class.relnamespace - WHERE table_namespace.nspname = :schema AND table_class.relkind IN ('r', 'p') - """ -) - -_DEFAULT_PRIVILEGES = text( - """ - SELECT pg_get_userbyid(default_acl.defaclrole) AS creating_role, - coalesce(acl_namespace.nspname, '') AS schema_name, - CASE default_acl.defaclobjtype - WHEN 'r' THEN 'tables' WHEN 'S' THEN 'sequences' - WHEN 'f' THEN 'functions' WHEN 'T' THEN 'types' - WHEN 'n' THEN 'schemas' ELSE default_acl.defaclobjtype::text - END AS object_type, - coalesce(grantee_role.rolname, 'PUBLIC') AS grantee, - acl_entry.privilege_type AS privilege - FROM pg_default_acl AS default_acl - LEFT JOIN pg_namespace AS acl_namespace - ON acl_namespace.oid = default_acl.defaclnamespace - CROSS JOIN LATERAL aclexplode(default_acl.defaclacl) AS acl_entry - LEFT JOIN pg_roles AS grantee_role ON grantee_role.oid = acl_entry.grantee - WHERE coalesce(grantee_role.rolname, '') IN :roles - OR pg_get_userbyid(default_acl.defaclrole) IN :roles +# The relkind of the objects whose grants are read: tables, partitioned tables, +# sequences, views and materialized views; for column grants, the same less +# sequences; and the objects that hold rows, tables and partitioned tables. +_GRANTABLE_RELATION_KINDS = ("r", "p", "S", "v", "m") +_COLUMN_RELATION_KINDS = ("r", "p", "v", "m") +_TABLE_RELATION_KINDS = ("r", "p") +# pg_default_acl's object type codes, named as ALTER DEFAULT PRIVILEGES names them. +_DEFAULT_ACL_OBJECT_TYPES = { + "r": "tables", + "S": "sequences", + "f": "functions", + "T": "types", + "n": "schemas", +} +# The grantee aclexplode reports for a privilege granted to PUBLIC: no role. +_PUBLIC_GRANTEE = "PUBLIC" + + +def _acl_entries(access_control_list: object, name: str) -> LateralFromClause: + """Return the entries of an access control list, one row each (``aclexplode``). + + Each row has the entry's ``grantee`` role oid and ``privilege_type``. """ -).bindparams(bindparam("roles", expanding=True)) + return ( + func.aclexplode(access_control_list) + .table_valued("grantee", "privilege_type") + .lateral(name) + ) -_GRANTED_COLUMN_PRIVILEGES = text( - """ - SELECT grantee_role.rolname AS role_name, - table_class.relname AS table_name, - table_column.attname AS column_name, - acl_entry.privilege_type AS privilege - FROM pg_attribute AS table_column - JOIN pg_class AS table_class ON table_class.oid = table_column.attrelid - JOIN pg_namespace AS table_namespace - ON table_namespace.oid = table_class.relnamespace - CROSS JOIN LATERAL aclexplode(table_column.attacl) AS acl_entry - JOIN pg_roles AS grantee_role ON grantee_role.oid = acl_entry.grantee - WHERE table_namespace.nspname = :schema - AND table_class.relkind IN ('r', 'p', 'v', 'm') - AND table_column.attnum > 0 - AND NOT table_column.attisdropped - AND grantee_role.rolname IN :roles - """ -).bindparams(bindparam("roles", expanding=True)) -_HAS_TABLE_PRIVILEGE = text( - "SELECT has_table_privilege(:role, :qualified_table, :privilege)" -) +def _quote(session: Session) -> Callable[[str], str]: + """Return the session's dialect's identifier quoting.""" + from policyengine_api.data.v2.database import v2_schema_inspector -_HAS_COLUMN_PRIVILEGE = text( - "SELECT has_column_privilege(:role, :qualified_table, :column, :privilege)" -) + quote: Callable[[str], str] = v2_schema_inspector( + session + ).dialect.identifier_preparer.quote + return quote -def read_existing_roles(connection: Connection, roles: Collection[str]) -> set[str]: +def read_existing_roles(session: Session, roles: Collection[str]) -> set[str]: """Return which of ``roles`` exist.""" - return set(connection.execute(_EXISTING_ROLES, {"roles": list(roles)}).scalars()) + role_name = col(PgRoles.rolname) + return set(session.scalars(select(role_name).where(role_name.in_(list(roles))))) -def read_public_tables(connection: Connection) -> set[str]: +def read_public_tables(session: Session) -> set[str]: """Return every table in the public schema.""" - return set(connection.execute(_PUBLIC_TABLES, {"schema": SCHEMA}).scalars()) + return set( + session.scalars( + select(col(PgClass.relname)) + .join(PgNamespace, col(PgNamespace.oid) == col(PgClass.relnamespace)) + .where( + col(PgNamespace.nspname) == SCHEMA, + col(PgClass.relkind).in_(_TABLE_RELATION_KINDS), + ) + ) + ) def read_granted_privileges( - connection: Connection, roles: Collection[str] + session: Session, roles: Collection[str] ) -> dict[str, dict[str, set[str]]]: """Return the roles' direct grants on public tables, views and sequences.""" + acl_entry = _acl_entries(PgClass.relacl, "acl_entry") + statement = ( + select( + col(PgRoles.rolname).label("role_name"), + col(PgClass.relname).label("table_name"), + acl_entry.c.privilege_type.label("privilege"), + ) + .join(PgNamespace, col(PgNamespace.oid) == col(PgClass.relnamespace)) + .join(acl_entry, true()) + .join(PgRoles, col(PgRoles.oid) == acl_entry.c.grantee) + .where( + col(PgNamespace.nspname) == SCHEMA, + col(PgClass.relkind).in_(_GRANTABLE_RELATION_KINDS), + col(PgRoles.rolname).in_(list(roles)), + ) + ) granted: dict[str, dict[str, set[str]]] = defaultdict(lambda: defaultdict(set)) - for row in connection.execute( - _GRANTED_PRIVILEGES, {"schema": SCHEMA, "roles": list(roles)} - ): + for row in session.execute(statement): granted[row.role_name][row.table_name].add(row.privilege) return {role: dict(tables) for role, tables in granted.items()} def read_granted_column_privileges( - connection: Connection, roles: Collection[str] + session: Session, roles: Collection[str] ) -> dict[str, dict[str, dict[str, set[str]]]]: """Return the roles' direct grants on columns of public tables and views.""" + acl_entry = _acl_entries(PgAttribute.attacl, "acl_entry") + statement = ( + select( + col(PgRoles.rolname).label("role_name"), + col(PgClass.relname).label("table_name"), + col(PgAttribute.attname).label("column_name"), + acl_entry.c.privilege_type.label("privilege"), + ) + .select_from(PgAttribute) + .join(PgClass, col(PgClass.oid) == col(PgAttribute.attrelid)) + .join(PgNamespace, col(PgNamespace.oid) == col(PgClass.relnamespace)) + .join(acl_entry, true()) + .join(PgRoles, col(PgRoles.oid) == acl_entry.c.grantee) + .where( + col(PgNamespace.nspname) == SCHEMA, + col(PgClass.relkind).in_(_COLUMN_RELATION_KINDS), + col(PgAttribute.attnum) > 0, + col(PgAttribute.attisdropped).is_(false()), + col(PgRoles.rolname).in_(list(roles)), + ) + ) granted: dict[str, dict[str, dict[str, set[str]]]] = defaultdict( lambda: defaultdict(lambda: defaultdict(set)) ) - for row in connection.execute( - _GRANTED_COLUMN_PRIVILEGES, {"schema": SCHEMA, "roles": list(roles)} - ): + for row in session.execute(statement): granted[row.role_name][row.table_name][row.column_name].add(row.privilege) return { role: {table: dict(columns) for table, columns in tables.items()} @@ -243,11 +255,41 @@ def read_granted_column_privileges( def read_default_privileges( - connection: Connection, roles: Collection[str] + session: Session, roles: Collection[str] ) -> list[DefaultPrivilege]: """Return default privileges that involve the managed roles.""" + acl_entry = _acl_entries(PgDefaultAcl.defaclacl, "acl_entry") + creating_role = func.pg_get_userbyid(col(PgDefaultAcl.defaclrole)) + object_type_code = cast(col(PgDefaultAcl.defaclobjtype), Text) + grantee_role_name = col(PgRoles.rolname) + statement = ( + select( + creating_role.label("creating_role"), + func.coalesce(col(PgNamespace.nspname), "").label("schema_name"), + case( + _DEFAULT_ACL_OBJECT_TYPES, + value=object_type_code, + else_=object_type_code, + ).label("object_type"), + func.coalesce(grantee_role_name, _PUBLIC_GRANTEE).label("grantee"), + acl_entry.c.privilege_type.label("privilege"), + ) + .select_from(PgDefaultAcl) + .outerjoin( + PgNamespace, + col(PgNamespace.oid) == col(PgDefaultAcl.defaclnamespace), + ) + .join(acl_entry, true()) + .outerjoin(PgRoles, col(PgRoles.oid) == acl_entry.c.grantee) + .where( + or_( + func.coalesce(grantee_role_name, "").in_(list(roles)), + creating_role.in_(list(roles)), + ) + ) + ) grouped: dict[tuple[str, str, str, str], set[str]] = defaultdict(set) - for row in connection.execute(_DEFAULT_PRIVILEGES, {"roles": list(roles)}): + for row in session.execute(statement): grouped[(row.creating_role, row.schema_name, row.object_type, row.grantee)].add( row.privilege ) @@ -265,17 +307,17 @@ def read_default_privileges( ] -def create_missing_roles(connection: Connection, roles: Iterable[str]) -> list[str]: +def create_missing_roles(session: Session, roles: Iterable[str]) -> list[str]: """Create each missing role as NOLOGIN; only for the disposable test database.""" - missing = sorted(set(roles) - read_existing_roles(connection, list(roles))) - quote = connection.dialect.identifier_preparer.quote + missing = sorted(set(roles) - read_existing_roles(session, list(roles))) + quote = _quote(session) for role in missing: - connection.execute(text(f"CREATE ROLE {quote(safe_identifier(role))} NOLOGIN")) + session.execute(text(f"CREATE ROLE {quote(safe_identifier(role))} NOLOGIN")) return missing def apply_declared_privileges( - connection: Connection, + session: Session, declared: Mapping[str, Mapping[str, frozenset[DeclaredPrivilege]]], *, roles_awaiting_creation: Collection[str] = (), @@ -293,53 +335,49 @@ def apply_declared_privileges( plan = plan_reconciliation( declared, GrantedPrivileges( - tables=read_granted_privileges(connection, roles), - columns=read_granted_column_privileges(connection, roles), + tables=read_granted_privileges(session, roles), + columns=read_granted_column_privileges(session, roles), ), - existing_roles=read_existing_roles(connection, roles), - existing_tables=read_public_tables(connection), + existing_roles=read_existing_roles(session, roles), + existing_tables=read_public_tables(session), roles_awaiting_creation=roles_awaiting_creation, ) if plan.can_apply: - quote = connection.dialect.identifier_preparer.quote + quote = _quote(session) for statement in revoke_statements(plan, quote) + grant_statements(plan, quote): - connection.execute(text(statement)) - return plan, read_default_privileges(connection, roles) + session.execute(text(statement)) + return plan, read_default_privileges(session, roles) def skipped_roles( - connection: Connection, + session: Session, declared: Mapping[str, Mapping[str, frozenset[DeclaredPrivilege]]], roles_awaiting_creation: Collection[str], ) -> tuple[str, ...]: """Return the declared roles awaiting creation that don't exist yet.""" - existing_roles = read_existing_roles(connection, list(declared)) + existing_roles = read_existing_roles(session, list(declared)) return tuple( sorted((set(declared) & set(roles_awaiting_creation)) - existing_roles) ) def _privilege_checks( - connection: Connection, roles: Collection[str] + session: Session, roles: Collection[str] ) -> tuple[Callable[[str, str, str], bool], Callable[[str, str, str, str], bool]]: """Return checks of a role's effective table and column privileges. A missing role or table holds nothing. """ - existing_roles = read_existing_roles(connection, roles) - existing_tables = read_public_tables(connection) + existing_roles = read_existing_roles(session, roles) + existing_tables = read_public_tables(session) def has_privilege(role: str, table: str, privilege: str) -> bool: if role not in existing_roles or table not in existing_tables: return False + qualified_table = f"{SCHEMA}.{safe_identifier(table)}" return bool( - connection.execute( - _HAS_TABLE_PRIVILEGE, - { - "role": role, - "qualified_table": f"{SCHEMA}.{safe_identifier(table)}", - "privilege": privilege, - }, + session.execute( + select(func.has_table_privilege(role, qualified_table, privilege)) ).scalar_one() ) @@ -348,15 +386,14 @@ def has_column_privilege( ) -> bool: if role not in existing_roles or table not in existing_tables: return False + qualified_table = f"{SCHEMA}.{safe_identifier(table)}" return bool( - connection.execute( - _HAS_COLUMN_PRIVILEGE, - { - "role": role, - "qualified_table": f"{SCHEMA}.{safe_identifier(table)}", - "column": safe_identifier(column), - "privilege": privilege, - }, + session.execute( + select( + func.has_column_privilege( + role, qualified_table, safe_identifier(column), privilege + ) + ) ).scalar_one() ) @@ -364,7 +401,7 @@ def has_column_privilege( def check_declared_privileges( - connection: Connection, + session: Session, declared: Mapping[str, Mapping[str, frozenset[DeclaredPrivilege]]], ) -> list[PrivilegeEntry]: """Return every declared privilege a role doesn't effectively hold. @@ -372,16 +409,16 @@ def check_declared_privileges( A missing role or table counts as missing every privilege declared for it; leave out the roles ``skipped_roles`` returns to skip them. """ - has_privilege, has_column_privilege = _privilege_checks(connection, list(declared)) + has_privilege, has_column_privilege = _privilege_checks(session, list(declared)) return verification_failures(declared, has_privilege, has_column_privilege) def check_table_wide_overrides( - connection: Connection, + session: Session, declared: Mapping[str, Mapping[str, frozenset[DeclaredPrivilege]]], ) -> list[PrivilegeEntry]: """Return each column privilege a role also holds on the whole table.""" - has_privilege, _has_column_privilege = _privilege_checks(connection, list(declared)) + has_privilege, _has_column_privilege = _privilege_checks(session, list(declared)) return table_wide_overrides(declared, has_privilege) @@ -413,7 +450,7 @@ def _write_summary(environ: Mapping[str, str], summary: str) -> None: def _verify( - connection: Connection, + session: Session, declared: Mapping[str, Mapping[str, frozenset[DeclaredPrivilege]]], roles_awaiting_creation: Collection[str], environment: str, @@ -427,10 +464,10 @@ def _verify( The roles skipped, the privileges missing and the whole-table privileges are written to stdout and the job summary under one heading. """ - skipped = skipped_roles(connection, declared, roles_awaiting_creation) + skipped = skipped_roles(session, declared, roles_awaiting_creation) checked = {role: tables for role, tables in declared.items() if role not in skipped} - failures = check_declared_privileges(connection, checked) - overrides = check_table_wide_overrides(connection, checked) + failures = check_declared_privileges(session, checked) + overrides = check_table_wide_overrides(session, checked) heading = f"## v2 table privileges ({environment})\n\n" skipped_note = f"{skipped_roles_line(skipped)}\n\n" if skipped else "" if failures or overrides: @@ -450,8 +487,13 @@ def _verify( return 0 -def _build_engine(settings: V2AlembicSettings) -> Engine: - return create_engine(settings.url, poolclass=NullPool) +def open_reconciliation_sessions( + settings: V2AlembicSettings, +) -> AbstractContextManager[sessionmaker[Session]]: + """Open Session factories for the target, on an engine with no pool.""" + from policyengine_api.data.v2.database import unpooled_v2_sessions + + return unpooled_v2_sessions(settings.url) def run( @@ -459,9 +501,14 @@ def run( *, create_roles: bool = False, environ: Mapping[str, str] | None = None, - engine_builder: Callable[[V2AlembicSettings], Engine] = _build_engine, + session_factories: Callable[ + [V2AlembicSettings], AbstractContextManager[sessionmaker[Session]] + ] = open_reconciliation_sessions, ) -> int: - """Run ``apply`` or ``verify`` against the configured v2 database.""" + """Run ``apply`` or ``verify`` against the configured v2 database. + + Everything runs in one transaction, which commits when the mode finishes. + """ values = os.environ if environ is None else environ settings = load_v2_alembic_settings(values) environment = _deployment_environment(values, settings) @@ -470,31 +517,27 @@ def run( raise V2ConfigurationError(msg) declared = declared_privileges(environment) awaiting = ROLES_AWAITING_PROVISIONING - engine = engine_builder(settings) - try: - with engine.begin() as connection: - qualify_v2_connection(connection, settings) - if mode == "verify": - return _verify(connection, declared, awaiting, environment, values) - if create_roles: - created = create_missing_roles(connection, declared) - if created: - print("Created roles: " + ", ".join(created)) - plan, defaults = apply_declared_privileges( - connection, declared, roles_awaiting_creation=awaiting - ) - _write_summary( - values, - render_summary( - plan, - defaults, - deployment_environment=environment, - applied=plan.can_apply, - ), - ) - return 0 if plan.can_apply else 1 - finally: - engine.dispose() + with session_factories(settings) as sessions, sessions.begin() as session: + qualify_v2_target(session, settings) + if mode == "verify": + return _verify(session, declared, awaiting, environment, values) + if create_roles: + created = create_missing_roles(session, declared) + if created: + print("Created roles: " + ", ".join(created)) + plan, defaults = apply_declared_privileges( + session, declared, roles_awaiting_creation=awaiting + ) + _write_summary( + values, + render_summary( + plan, + defaults, + deployment_environment=environment, + applied=plan.can_apply, + ), + ) + return 0 if plan.can_apply else 1 def main(argv: Sequence[str] | None = None) -> int: diff --git a/policyengine_api/data/v2/privilege_requirements.py b/policyengine_api/data/v2/privilege_requirements.py index ea860adfc..5ed520189 100644 --- a/policyengine_api/data/v2/privilege_requirements.py +++ b/policyengine_api/data/v2/privilege_requirements.py @@ -49,7 +49,7 @@ class UnclassifiedConnectorError(ValueError): class RequiredPrivilege: """One privilege a connector module needs on one table, and why.""" - table: str + table_name: str privilege: TablePrivilege connector: str reason: str @@ -202,7 +202,7 @@ def required_privileges( } requirements = { RequiredPrivilege( - table=table, + table_name=table, privilege=privilege, connector=label, reason=f"{kind} module uses the table", @@ -214,7 +214,7 @@ def required_privileges( if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): requirements.update( RequiredPrivilege( - table=table, + table_name=table, privilege=TablePrivilege.UPDATE, connector=label, reason=f"{node.name} locks rows with with_for_update", @@ -236,5 +236,6 @@ def undeclared_requirements( return sorted( requirement for requirement in requirements - if requirement.privilege not in declared.get(requirement.table, frozenset()) + if requirement.privilege + not in declared.get(requirement.table_name, frozenset()) ) diff --git a/policyengine_api/data/v2/user_association_migration_qualification.py b/policyengine_api/data/v2/user_association_migration_qualification.py index 9d7aad2a5..d0ba2e26c 100644 --- a/policyengine_api/data/v2/user_association_migration_qualification.py +++ b/policyengine_api/data/v2/user_association_migration_qualification.py @@ -4,7 +4,7 @@ and ``user_report_associations`` tables (dropping their v2 foreign keys and legacy columns and adding a required ``country_id``). Before it is applied, those tables must be empty. This command reports the row counts of all four -v2 user-association tables through SQLAlchemy in a read-only, rolled-back +v2 user-association tables through an ORM Session in a read-only, rolled-back transaction and fails when the revision is pending and a dormant table still holds rows. It never writes, and it never prints the database URL. @@ -21,13 +21,7 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Protocol -from alembic.config import Config -from alembic.migration import MigrationContext -from alembic.script import ScriptDirectory -from sqlalchemy import Connection, Engine, func, inspect, select -from sqlalchemy.exc import NoInspectionAvailable -from sqlalchemy.pool import NullPool -from sqlmodel import create_engine +from sqlalchemy import func, select from policyengine_api.data.v2.models import ( UserHouseholdAssociation, @@ -35,6 +29,7 @@ UserReportAssociation, UserSimulationAssociation, ) +from policyengine_api.data.v2.pending_revisions import v2_revision_is_pending from policyengine_api.data.v2.settings import ( V2ConfigurationError, V2DatabaseSettings, @@ -43,9 +38,12 @@ if TYPE_CHECKING: from collections.abc import Callable, Collection, Mapping + from contextlib import AbstractContextManager + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session USER_ASSOCIATION_MIGRATION_REVISION = "fbb7488ebe8a" -V2_ALEMBIC_CONFIG = "alembic-v2.ini" class ScalarExecutor(Protocol): @@ -151,60 +149,51 @@ def require_empty_dormant_associations( raise RetainedDormantAssociationError(counts) -def user_association_migration_is_pending(connection: Connection) -> bool: +def user_association_migration_is_pending(session: Session) -> bool: """Return whether the Stage 12A revision is in the upgrade path.""" - current_heads = MigrationContext.configure(connection).get_current_heads() - revisions = ScriptDirectory.from_config( - Config(V2_ALEMBIC_CONFIG) - ).iterate_revisions("heads", current_heads) - return USER_ASSOCIATION_MIGRATION_REVISION in { - migration.revision for migration in revisions - } + return v2_revision_is_pending(session, USER_ASSOCIATION_MIGRATION_REVISION) -def build_qualification_engine(settings: V2DatabaseSettings) -> Engine: - """Build an isolated connection pool for one qualification attempt.""" - return create_engine(settings.connection.url, poolclass=NullPool) +def open_qualification_sessions( + settings: V2DatabaseSettings, +) -> AbstractContextManager[sessionmaker[Session]]: + """Open Session factories for one qualification attempt. + Their engine keeps no pool, and every transaction is READ ONLY: Postgres + enforces the read-only session characteristic, which is applied before + the transaction begins and reset on release. + """ + from policyengine_api.data.v2.database import unpooled_v2_read_only_sessions -def _existing_tables(connection: Connection) -> list[str] | None: - try: - return inspect(connection).get_table_names(schema="public") - except NoInspectionAvailable: - return None + return unpooled_v2_read_only_sessions(settings.connection.url) + + +def _public_tables(session: Session) -> list[str]: + from policyengine_api.data.v2.database import v2_schema_inspector + + return v2_schema_inspector(session).get_table_names(schema="public") def qualify_user_association_migration( environ: Mapping[str, str] | None = None, *, - engine_builder: Callable[[V2DatabaseSettings], Engine] = ( - build_qualification_engine - ), - pending_checker: Callable[[Connection], bool] = ( + session_factories: Callable[ + [V2DatabaseSettings], AbstractContextManager[sessionmaker[Session]] + ] = open_qualification_sessions, + pending_checker: Callable[[Session], bool] = ( user_association_migration_is_pending ), ) -> UserAssociationQualification: - """Report counts and stop when a pending reshape would affect rows.""" + """Report counts and stop when a pending reshape would affect rows. + + The revision check and the rows are read in one READ ONLY transaction, + rolled back when the session closes. + """ settings = load_v2_migration_database_settings(environ) - engine = engine_builder(settings) - try: - with engine.connect() as connection: - # Postgres enforces the read-only session characteristic; it is - # applied before the transaction begins and reset on release. - connection.execution_options(postgresql_readonly=True) - transaction = connection.begin() - try: - migration_pending = pending_checker(connection) - counts = read_user_association_counts( - connection, _existing_tables(connection) - ) - require_empty_dormant_associations( - counts, migration_pending=migration_pending - ) - finally: - transaction.rollback() - finally: - engine.dispose() + with session_factories(settings) as sessions, sessions() as session: + migration_pending = pending_checker(session) + counts = read_user_association_counts(session, _public_tables(session)) + require_empty_dormant_associations(counts, migration_pending=migration_pending) return UserAssociationQualification( environment=settings.target.environment, project_ref=settings.target.project_ref, diff --git a/policyengine_api/routes/report_output_routes.py b/policyengine_api/routes/report_output_routes.py index 026e9c724..493e9f9e0 100644 --- a/policyengine_api/routes/report_output_routes.py +++ b/policyengine_api/routes/report_output_routes.py @@ -26,8 +26,8 @@ def _serialize_v1_report_output(view: ReportOutputView) -> dict: """Project mapped report state onto the historical v1 response shape.""" report_output = view.report_output result = { - column.name: getattr(report_output, column.name) - for column in ReportOutput.__table__.columns + attribute.key: getattr(report_output, attribute.key) + for attribute in ReportOutput.__mapper__.column_attrs } if view.response_id is not None: result["id"] = view.response_id diff --git a/policyengine_api/routes/simulation_routes.py b/policyengine_api/routes/simulation_routes.py index 91ad8e0a0..6bcf4e86c 100644 --- a/policyengine_api/routes/simulation_routes.py +++ b/policyengine_api/routes/simulation_routes.py @@ -34,8 +34,8 @@ def _spm_override_response(payload: dict) -> Response | None: def _serialize_v1_simulation(simulation: Simulation) -> dict: """Project canonical ORM JSON objects onto the legacy v1 response shape.""" response = { - column.name: getattr(simulation, column.name) - for column in Simulation.__table__.columns + attribute.key: getattr(simulation, attribute.key) + for attribute in Simulation.__mapper__.column_attrs } for field in ("output", "simulation_spec_json"): value = response.get(field) diff --git a/rules/registry.toml b/rules/registry.toml index 0a549d6ed..701299723 100644 --- a/rules/registry.toml +++ b/rules/registry.toml @@ -664,12 +664,78 @@ match = "class_registry.metadata.tables" category = "no-orm-form" reason = "The rule's check for tables without a mapped class reads the tables a declarative base's metadata holds, to find those no class maps. It runs no statement." +[[rule.exception]] +path = "policyengine_api/data/v2/catalog/publication_staging.py" +match = "session.connection()" +category = "no-orm-form" +reason = "Catalog publication creates its TEMPORARY staging tables with MetaData.create_all, which takes a Connection, and streams rows with COPY ... FROM STDIN through the psycopg connection beneath the Connection. Both run on the Connection the publishing Session holds, in its transaction." + +[[rule.exception]] +path = "policyengine_api/data/v2/catalog/publication_staging.py" +match = "driver_connection.cursor()" +category = "no-orm-form" +reason = "COPY ... FROM STDIN has no SQLAlchemy form. Publication runs it through psycopg's Cursor.copy, on a cursor of the driver connection beneath the publishing Session's Connection." + +[[rule.exception]] +path = "policyengine_api/data/v2/catalog/publication_statistics.py" +match = "sa.text(f'ANALYZE {tables}')" +category = "no-orm-form" +reason = "ANALYZE has no ORM form. After a publication commits, one ANALYZE refreshes the planner statistics of the catalog tables it wrote." + +[[rule.exception]] +path = "policyengine_api/data/v2/privilege_reconciliation.py" +match = "text(f'CREATE ROLE {quote(safe_identifier(role))} NOLOGIN')" +category = "no-orm-form" +reason = "CREATE ROLE has no SQLAlchemy form. reconcile_v2_privileges.py apply --create-missing-roles creates each missing managed role as NOLOGIN, only in the disposable test database, in the reconciliation's one transaction. The role name is checked by safe_identifier and quoted by the session's dialect." + +[[rule.exception]] +path = "policyengine_api/data/v2/privilege_reconciliation.py" +match = "text(statement)" +category = "no-orm-form" +reason = "GRANT and REVOKE have no SQLAlchemy form. apply runs the REVOKEs and GRANTs that privilege_plans' revoke_statements and grant_statements build from the declared privileges, with identifiers checked by safe_identifier and quoted by the session's dialect, in the reconciliation's one transaction." + +[[rule.exception]] +path = "policyengine_api/data/v2/pending_revisions.py" +match = "session.connection()" +category = "no-orm-form" +reason = "Alembic's MigrationContext reads the database's current heads from its version table through a Connection. The migration qualification commands give it the Connection their Session holds, so the read runs inside the Session's READ ONLY transaction." + +[[rule.exception]] +path = "scripts/v1_database_migration.py" +match = "session.connection()" +category = "no-orm-form" +reason = "Alembic's MigrationContext, compare_metadata and command.upgrade take a Connection. The v1 schema migration gives them the Connection its Session holds, so the version reads, the schema comparison and the upgrade run in the Session's transaction, under the MySQL named lock the Session took." + +[[rule.exception]] +path = "policyengine_api/services/v2/user_types/database_connectors/reads.py" +match = "session.get_bind()" +category = "no-orm-form" +reason = "Reads the dialect's name, to skip PostgreSQL's advisory lock on the SQLite test databases, which have none. It runs no statement on the engine." + [[rule.exception]] path = "tests/fixtures/database_sessions.py" match = "sqlite_connection.execute(...)" category = "no-orm-form" reason = "SQLite enforces foreign keys only once a connection sets PRAGMA foreign_keys, a connection setting SQLAlchemy has no API for. The in-memory SQLite test databases set it on each connection before its first transaction." +[[rule.exception]] +path = "tests/fixtures/database_sessions.py" +match = "text(f'EXPLAIN {compiled}')" +category = "no-orm-form" +reason = "EXPLAIN has no SQLAlchemy form. A test that checks an index serves a lookup reads PostgreSQL's plan for the ORM statement that does the lookup." + +[[rule.exception]] +path = "tests/fixtures/database_sessions.py" +match = "connection.exec_driver_sql('BEGIN IMMEDIATE')" +category = "no-orm-form" +reason = "SQLite takes its write lock at the start of a transaction only with BEGIN IMMEDIATE, a transaction mode SQLAlchemy's SQLite dialect has no setting for. A concurrency test's file database starts every transaction that way, as SELECT ... FOR UPDATE makes writers wait on PostgreSQL." + +[[rule.exception]] +path = "tests/fixtures/database_sessions.py" +match = "text(f'DROP TABLE {tables}')" +category = "no-orm-form" +reason = "Dropping a table has no ORM form. Route tests drop a catalog table so the route's real catalog query fails with the database's own error." + [[rule.exception]] path = "tests/fixtures/database_sessions.py" match = "text(f'TRUNCATE {tables} CASCADE')" diff --git a/scripts/process_v1_household_mirror_event.py b/scripts/process_v1_household_mirror_event.py index 49717019b..45dbe3ef7 100755 --- a/scripts/process_v1_household_mirror_event.py +++ b/scripts/process_v1_household_mirror_event.py @@ -10,11 +10,9 @@ import sys from typing import TYPE_CHECKING, NamedTuple -from sqlalchemy import Engine, create_engine from sqlalchemy.engine import URL -from sqlalchemy.pool import NullPool -from policyengine_api.data.orm import build_session_factory +from policyengine_api.data.orm import unpooled_v1_sessions from policyengine_api.gcp_logging import logger from policyengine_api.services.household_mirroring import ( process_household_event_after_commit, @@ -114,11 +112,16 @@ def validate_command_environment( def _proxy_event_service( environ: Mapping[str, str], -) -> tuple[HouseholdService | None, Engine | None]: - """Use the workflow-authenticated Cloud SQL proxy when it is selected.""" + cleanup: contextlib.ExitStack, +) -> HouseholdService | None: + """Use the workflow-authenticated Cloud SQL proxy when it is selected. + + Its Session factories stay open until ``cleanup`` closes, which disposes + of their engine; the engine keeps no connection pool. + """ raw_port = environ.get("POLICYENGINE_DB_PROXY_PORT", "").strip() if not raw_port: - return None, None + return None try: port = int(raw_port) except ValueError as error: @@ -129,18 +132,19 @@ def _proxy_event_service( raise HouseholdEventCommandConfigurationError(msg) password = _required(environ, "POLICYENGINE_DB_PASSWORD") - engine = create_engine( - URL.create( - "mysql+pymysql", - username=V1_MIGRATION_USER, - password=password, - host=V1_PROXY_HOST, - port=port, - database=V1_DATABASE_NAME, - ), - poolclass=NullPool, + sessions = cleanup.enter_context( + unpooled_v1_sessions( + URL.create( + "mysql+pymysql", + username=V1_MIGRATION_USER, + password=password, + host=V1_PROXY_HOST, + port=port, + database=V1_DATABASE_NAME, + ) + ) ) - return HouseholdService(build_session_factory(engine)), engine + return HouseholdService(sessions) def _parser() -> argparse.ArgumentParser: @@ -209,10 +213,11 @@ def main( values = os.environ if environ is None else environ event = _SelectedEvent(args.country_id, args.legacy_household_id) identity: dict[str, str] | None = None - v1_engine: Engine | None = None + # Closes the proxy's Session factories, if any, and disposes of their engine. + proxy_cleanup = contextlib.ExitStack() try: identity = validate_command_environment(args.environment, values) - event_service, v1_engine = _proxy_event_service(values) + event_service = _proxy_event_service(values, proxy_cleanup) if event_service is None: result = process_household_event_after_commit( args.country_id, @@ -255,8 +260,7 @@ def main( ) return 1 finally: - if v1_engine is not None: - v1_engine.dispose() + proxy_cleanup.close() # Outcome logging must not change the command result. with contextlib.suppress(Exception): _record_command_outcome( diff --git a/scripts/v1_database_migration.py b/scripts/v1_database_migration.py index e7df33b0a..a646cc8c2 100644 --- a/scripts/v1_database_migration.py +++ b/scripts/v1_database_migration.py @@ -1,25 +1,36 @@ -"""Safely inspect and upgrade the API v1 Cloud SQL schema.""" +"""Safely inspect and upgrade the API v1 Cloud SQL schema. + +Every mode runs in one ORM Session. Alembic's ``MigrationContext``, +``compare_metadata`` and ``command.upgrade`` take a Connection, so they get +the Session's own (rule api.data.orm-only names these exceptions); everything +else runs through the Session. +""" from __future__ import annotations import argparse import os from enum import StrEnum +from typing import TYPE_CHECKING from alembic import command from alembic.autogenerate import compare_metadata from alembic.config import Config from alembic.migration import MigrationContext from alembic.script import ScriptDirectory -from sqlalchemy import Connection, create_engine, inspect, text +from sqlalchemy import func, select from sqlalchemy.engine import URL -from sqlalchemy.pool import NullPool from policyengine_api.constants import REPO +from policyengine_api.data.orm import unpooled_v1_sessions, v1_schema_inspector from policyengine_api.data.v1_models import V1Base +if TYPE_CHECKING: + from sqlalchemy.orm import Session + ALEMBIC_CONFIG = REPO / "alembic-v1.ini" MIGRATION_LOCK_NAME = "policyengine-api-v1-alembic" +MIGRATION_LOCK_TIMEOUT_SECONDS = 60 DATABASE_NAME = "policyengine" READONLY_USER = "policyengine_schema_reader" MIGRATION_USER = "policyengine_schema_migrator" @@ -107,9 +118,10 @@ def describe_metadata_difference(difference: object) -> str: raise ValueError(msg) -def _config(connection: Connection) -> Config: +def _config(session: Session) -> Config: + """Return the v1 Alembic configuration, migrating the Session's connection.""" config = Config(str(ALEMBIC_CONFIG)) - config.attributes["connection"] = connection + config.attributes["connection"] = session.connection() return config @@ -117,12 +129,12 @@ def _script_heads(config: Config) -> set[str]: return set(ScriptDirectory.from_config(config).get_heads()) -def database_state(connection: Connection) -> DatabaseState: +def database_state(session: Session) -> DatabaseState: """Return the database's Alembic state against the repository's revision heads.""" - inspector = inspect(connection) + inspector = v1_schema_inspector(session) version_table_exists = "alembic_version" in inspector.get_table_names() - context = MigrationContext.configure(connection) - config = _config(connection) + context = MigrationContext.configure(session.connection()) + config = _config(session) return classify_database_state( version_table_exists=version_table_exists, current_heads=set(context.get_current_heads()), @@ -130,13 +142,13 @@ def database_state(connection: Connection) -> DatabaseState: ) -def metadata_differences(connection: Connection) -> set[str]: +def metadata_differences(session: Session) -> set[str]: """Describe every difference between the live schema and the v1 models. Raise ValueError for a kind of difference that has no data-free description. """ context = MigrationContext.configure( - connection, + session.connection(), opts={"compare_type": True, "compare_server_default": True}, ) return { @@ -145,42 +157,41 @@ def metadata_differences(connection: Connection) -> set[str]: } -def verify_head_schema(connection: Connection) -> None: +def verify_head_schema(session: Session) -> None: """Raise RuntimeError unless the database is at the head with no schema drift.""" - state = database_state(connection) + state = database_state(session) if state is not DatabaseState.HEAD: msg = f"Database is not at the Alembic head; found {state}" raise RuntimeError(msg) - differences = metadata_differences(connection) + differences = metadata_differences(session) if differences: msg = f"Database metadata drift remains after migration: {sorted(differences)}" raise RuntimeError(msg) -def _acquire_lock(connection: Connection) -> None: - acquired = connection.scalar( - text("SELECT GET_LOCK(:name, 60)"), {"name": MIGRATION_LOCK_NAME} +def _acquire_lock(session: Session) -> None: + """Take MySQL's named migration lock, waiting up to 60 seconds for it.""" + acquired = session.scalar( + select(func.GET_LOCK(MIGRATION_LOCK_NAME, MIGRATION_LOCK_TIMEOUT_SECONDS)) ) if acquired != 1: msg = "Could not acquire the v1 Alembic migration lock" raise RuntimeError(msg) -def _release_lock(connection: Connection) -> None: - connection.execute( - text("SELECT RELEASE_LOCK(:name)"), {"name": MIGRATION_LOCK_NAME} - ) +def _release_lock(session: Session) -> None: + session.execute(select(func.RELEASE_LOCK(MIGRATION_LOCK_NAME))) -def upgrade_database(connection: Connection, *, backup_id: str) -> None: +def upgrade_database(session: Session, *, backup_id: str) -> None: """Upgrade a versioned database to head under a MySQL named lock, then verify it. A database already at head is only verified, so ``backup_id`` is required only when an upgrade will actually run. """ - _acquire_lock(connection) + _acquire_lock(session) try: - state = database_state(connection) + state = database_state(session) if state in {DatabaseState.UNVERSIONED, DatabaseState.INVALID}: msg = ( "database has no valid Alembic revision; automatic baseline " @@ -188,16 +199,16 @@ def upgrade_database(connection: Connection, *, backup_id: str) -> None: ) raise RuntimeError(msg) if state is DatabaseState.HEAD: - verify_head_schema(connection) + verify_head_schema(session) return if not backup_id.strip(): msg = "A completed Cloud SQL backup ID is required" raise ValueError(msg) - command.upgrade(_config(connection), "head") - verify_head_schema(connection) + command.upgrade(_config(session), "head") + verify_head_schema(session) finally: - _release_lock(connection) + _release_lock(session) def _database_target(mode: str) -> str | URL: @@ -246,20 +257,17 @@ def main(argv: list[str] | None = None) -> int: as the schema reader and upgrade as the migrator, in one transaction. """ args = _parse_args(argv) - engine = create_engine(_database_target(args.mode), poolclass=NullPool) - try: - connection_context = ( - engine.begin() if args.mode == "upgrade" else engine.connect() - ) - with connection_context as connection: + with unpooled_v1_sessions(_database_target(args.mode)) as sessions: + # The upgrade commits its one transaction; the read-only modes' sessions + # close without committing. + session_context = sessions.begin() if args.mode == "upgrade" else sessions() + with session_context as session: if args.mode == "state": - print(database_state(connection).value) + print(database_state(session).value) elif args.mode == "verify-head": - verify_head_schema(connection) + verify_head_schema(session) else: - upgrade_database(connection, backup_id=args.backup_id) - finally: - engine.dispose() + upgrade_database(session, backup_id=args.backup_id) return 0 diff --git a/tests/contract/test_policy_v2_compatibility.py b/tests/contract/test_policy_v2_compatibility.py index 9365efa0c..54a9e2ea4 100644 --- a/tests/contract/test_policy_v2_compatibility.py +++ b/tests/contract/test_policy_v2_compatibility.py @@ -5,6 +5,7 @@ from uuid import UUID import pytest +from sqlalchemy import inspect from policyengine_api.data.v2.models import Policy from policyengine_api.fastapi_routes.v2.policies.request_models import ( @@ -49,8 +50,9 @@ def test_app_v2_reform_label_maps_to_association_name_only() -> None: assert projection.description is None assert projection.user_id == USER_ID assert projection.policy_id == POLICY_ID - assert "name" not in Policy.__table__.c - assert "description" not in Policy.__table__.c + policy_columns = inspect(Policy).columns + assert "name" not in policy_columns + assert "description" not in policy_columns def test_core_policy_request_rejects_association_presentation_fields() -> None: diff --git a/tests/fixtures/database_sessions.py b/tests/fixtures/database_sessions.py index d4253c2b3..b7cb79835 100644 --- a/tests/fixtures/database_sessions.py +++ b/tests/fixtures/database_sessions.py @@ -18,17 +18,20 @@ from __future__ import annotations +import importlib import re import sqlite3 import sys from contextlib import contextmanager -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, NamedTuple +from psycopg.pq import TransactionStatus from sqlalchemy import ( JSON, Integer, String, create_engine, + create_mock_engine, delete, event, func, @@ -37,6 +40,8 @@ text, true, ) +from sqlalchemy.dialects import postgresql +from sqlalchemy.engine import make_url from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, sessionmaker from sqlalchemy.orm import Session as OrmSession from sqlalchemy.pool import NullPool, StaticPool @@ -52,10 +57,12 @@ if TYPE_CHECKING: from collections.abc import Callable, Iterator, Mapping + from pathlib import Path import pytest - from sqlalchemy.engine import Inspector + from sqlalchemy.engine import URL, Connection, Inspector from sqlalchemy.orm import registry + from sqlalchemy.sql import ClauseElement from sqlmodel import Session from policyengine_api.data.v2.privilege_plans import ReconciliationPlan @@ -89,6 +96,22 @@ def v2_owner_sessions(database_url: str) -> Iterator[sessionmaker[Session]]: engine.dispose() +@contextmanager +def single_connection_v2_sessions( + database_url: str, +) -> Iterator[sessionmaker[Session]]: + """Yield the v2 database owner's Session factories on a pool of one connection. + + Every Session gets the same pooled connection back, in the state the pool + returns it in. The engine is disposed of on exit. + """ + engine = create_engine(database_url, pool_size=1, max_overflow=0) + try: + yield build_v2_session_factory(engine) + finally: + engine.dispose() + + @contextmanager def v2_role_sessions(database_url: str, role: str) -> Iterator[sessionmaker[Session]]: """Yield Session factories whose every connection acts as ``role``. @@ -165,6 +188,53 @@ def sqlite_v2_sessions( engine.dispose() +@contextmanager +def sqlite_v2_file_sessions(path: Path) -> Iterator[sessionmaker[Session]]: + """Yield Session factories of a SQLite file copy of the v2 schema. + + Each Session gets its own connection, so threads can run transactions at + the same time. Every transaction starts with ``BEGIN IMMEDIATE``, which takes + SQLite's write lock at once, as ``SELECT ... FOR UPDATE`` makes writers wait + for each other on PostgreSQL. + """ + engine = create_engine( + f"sqlite:///{path}", connect_args={"check_same_thread": False, "timeout": 10} + ) + + @event.listens_for(engine, "connect") + def _leave_transactions_to_sqlalchemy( + dbapi_connection: sqlite3.Connection, _connection_record: object + ) -> None: + # pysqlite then never begins a transaction itself; the begin event does. + dbapi_connection.isolation_level = None + + @event.listens_for(engine, "begin") + def _begin_immediately(connection: Connection) -> None: + connection.exec_driver_sql("BEGIN IMMEDIATE") + + V2_METADATA.create_all(engine) + try: + yield build_v2_session_factory(engine) + finally: + engine.dispose() + + +def v2_schema_statements(dialect_name: str = "postgresql") -> list[str]: + """Return the CREATE statements of the v2 schema, compiled for a dialect. + + No database is involved: a mock engine records each statement that + ``create_all`` would send, in the order it would send them. + """ + statements: list[str] = [] + + def record(statement: Any, *_parameters: object, **_options: object) -> None: + statements.append(str(statement.compile(dialect=recording_engine.dialect))) + + recording_engine = create_mock_engine(f"{dialect_name}://", record) + V2_METADATA.create_all(recording_engine, checkfirst=False) + return statements + + class _SqliteV1PolicyBase(DeclarativeBase): """The declarative base of the SQLite copy of API v1's policy table.""" @@ -223,10 +293,70 @@ def serve_v1_sessions( from policyengine_api.data import orm engine = sessions.kw["bind"] - monkeypatch.setattr(orm, "get_v1_engine", lambda: engine) + monkeypatch.setattr(orm, "_v1_engine", lambda: engine) orm.clear_v1_session_factories() +class _LocalMySqlConnector: + """Stands in for Cloud SQL's Connector, connecting to a local MySQL server. + + The real connector's pymysql path passes every argument other than the + instance name and driver on to pymysql, so this one does the same. + """ + + def __init__(self, database_url: URL, **_connector_options: object) -> None: + self.database_url = database_url + + def connect( + self, *, instance_connection_string: str, driver: str, **driver_arguments: Any + ) -> Any: + del instance_connection_string + if driver != "pymysql": + message = f"API v1's Cloud SQL engine asked for driver {driver!r}" + raise ValueError(message) + # pymysql ships no type stubs, so the module is loaded untyped. + driver_module = importlib.import_module("pymysql") + return driver_module.connect( + host=self.database_url.host, + port=self.database_url.port or 3306, + **driver_arguments, + ) + + def close(self) -> None: + """Release nothing: each connection closes when its pool closes it.""" + + +@contextmanager +def v1_cloud_sql_sessions( + monkeypatch: pytest.MonkeyPatch, database_url: str +) -> Iterator[sessionmaker[OrmSession]]: + """Yield API v1's own Session factory, its Cloud SQL engine on local MySQL. + + ``orm.get_v1_session_factory()`` builds the engine as production does + (``orm._build_remote_engine``: its pool settings and connection arguments, + such as the ``CLIENT.FOUND_ROWS`` flag), but each connection goes to the + server at ``database_url``. ``monkeypatch`` undoes the state and settings + after the test. + """ + from policyengine_api.data import orm, orm_pool_events + + url = make_url(database_url) + monkeypatch.setattr(orm, "_cloud_sql_state", orm._CloudSqlState()) + monkeypatch.setattr( + orm, "Connector", lambda **options: _LocalMySqlConnector(url, **options) + ) + monkeypatch.setenv("POLICYENGINE_DB_INSTANCE_CONNECTION_NAME", "local:test:mysql") + monkeypatch.setenv("POLICYENGINE_DB_USER", url.username or "") + monkeypatch.setenv("POLICYENGINE_DB_NAME", url.database or "") + monkeypatch.setenv("POLICYENGINE_DB_PASSWORD", url.password or "") + try: + yield orm.get_v1_session_factory() + finally: + orm.close_v1_engines() + # Building the engine sends the connector's logs to the runtime; undo that. + orm_pool_events.stop_recording_connector_refresh_logs() + + def _set_transaction_role(session: OrmSession, role: str) -> None: # set_config's third argument, true, keeps the setting to the transaction, # as SET LOCAL does. @@ -259,6 +389,19 @@ def schema_inspector(source: OrmSession | sessionmaker[Any]) -> Inspector: return inspector +def query_plan(session: OrmSession, statement: ClauseElement) -> str: + """Return PostgreSQL's plan for an ORM statement (EXPLAIN), its rows joined. + + A test that checks an index serves a lookup reads the plan of the ORM + statement that does the lookup, in the session's transaction and as the + session's role. + """ + # The named paramstyle gives text() the :name parameters it parses. + compiled = statement.compile(dialect=postgresql.dialect(paramstyle="named")) + plan_rows = session.execute(text(f"EXPLAIN {compiled}"), compiled.params).scalars() + return "\n".join(plan_rows) + + @contextmanager def recorded_statements( source: OrmSession | sessionmaker[Any], @@ -279,12 +422,69 @@ def record( event.remove(engine, "before_cursor_execute", record) +class DriverConnectionState(NamedTuple): + """The driver connection a statement ran on, as it was after the statement.""" + + connection_id: int + autocommit: bool + in_transaction: bool + + +@contextmanager +def recorded_driver_connection_states( + source: OrmSession | sessionmaker[Any], +) -> Iterator[list[DriverConnectionState]]: + """Yield the state of the driver connection each of ``source``'s statements ran on. + + Each state is read after its statement: which connection, its autocommit + mode, and whether it is inside a transaction. It is read after, not before, + because psycopg sends BEGIN as part of a transaction's first statement. + """ + engine = source.get_bind() if isinstance(source, OrmSession) else source.kw["bind"] + states: list[DriverConnectionState] = [] + + def record(connection: Any, *_arguments: object) -> None: + driver_connection = connection.connection.dbapi_connection + states.append( + DriverConnectionState( + connection_id=id(driver_connection), + autocommit=driver_connection.autocommit, + in_transaction=( + driver_connection.info.transaction_status + == TransactionStatus.INTRANS + ), + ) + ) + + event.listen(engine, "after_cursor_execute", record) + try: + yield states + finally: + event.remove(engine, "after_cursor_execute", record) + + def delete_all_rows(session: OrmSession, mapped_classes: registry) -> None: """Delete every row of every table the registry's mapped classes map.""" for mapper in mapped_classes.mappers: session.execute(delete(mapper.class_)) +def create_registry_tables(session: OrmSession, mapped_classes: registry) -> None: + """Create the tables of a registry's mapped classes in the session's transaction. + + It fails if one already exists (CREATE TABLE, not IF NOT EXISTS). + """ + mapped_classes.metadata.create_all(session.connection(), checkfirst=False) + + +def drop_registry_tables(session: OrmSession, mapped_classes: registry) -> None: + """Drop whichever of a registry's tables exist, in the session's transaction. + + It skips a table that doesn't exist, as DROP TABLE IF EXISTS does. + """ + mapped_classes.metadata.drop_all(session.connection()) + + def _quoted(session: OrmSession, name: str) -> str: return session.get_bind().dialect.identifier_preparer.quote_identifier(name) @@ -295,6 +495,12 @@ def truncate(session: OrmSession, *models: type[Any]) -> None: session.execute(text(f"TRUNCATE {tables} CASCADE")) +def drop_tables(session: OrmSession, *models: type[Any]) -> None: + """Drop the models' tables, so later queries on them fail as on a broken catalog.""" + tables = ", ".join(_quoted(session, model.__tablename__) for model in models) + session.execute(text(f"DROP TABLE {tables}")) + + def create_role(session: OrmSession, role: str) -> None: """Create ``role``, which can't log in (CREATE ROLE ... NOLOGIN).""" quoted_role = _quoted(session, role) @@ -329,7 +535,6 @@ def grant_declared_v2_privileges( does, in one transaction as the database's owner, and returns the plan. """ with v2_owner_sessions(database_url) as sessions, sessions.begin() as session: - connection = session.connection() - create_missing_roles(connection, declared) - plan, _default_privileges = apply_declared_privileges(connection, declared) + create_missing_roles(session, declared) + plan, _default_privileges = apply_declared_privileges(session, declared) return plan diff --git a/tests/fixtures/integration/alembic_v2.py b/tests/fixtures/integration/alembic_v2.py index 9054f306e..8f55bf235 100644 --- a/tests/fixtures/integration/alembic_v2.py +++ b/tests/fixtures/integration/alembic_v2.py @@ -1,36 +1,14 @@ """The disposable Postgres target and Alembic config of the v2 lifecycle tests.""" -import os from typing import Any -import pytest from alembic.config import Config from sqlalchemy.engine.interfaces import ReflectedColumn from policyengine_api.constants import REPO -from policyengine_api.data.v2.migration_target import ( - V2_ALEMBIC_DISPOSABLE_TEST, - load_v2_alembic_settings, -) -from policyengine_api.data.v2.settings import V2_MIGRATION_DATABASE_URL from tests.fixtures.database_sessions import schema_inspector -def disposable_v2_url() -> str: - database_url = os.environ.get(V2_MIGRATION_DATABASE_URL, "") - if not database_url: - pytest.skip(f"{V2_MIGRATION_DATABASE_URL} is not set") - settings = load_v2_alembic_settings( - { - V2_MIGRATION_DATABASE_URL: database_url, - V2_ALEMBIC_DISPOSABLE_TEST: os.environ.get(V2_ALEMBIC_DISPOSABLE_TEST, ""), - } - ) - if not settings.disposable_test: - pytest.fail("v2 lifecycle tests require disposable-test mode") - return settings.url.render_as_string(hide_password=False) - - def alembic_v2_config() -> Config: return Config(str(REPO / "alembic-v2.ini")) diff --git a/tests/fixtures/local_v1_database.py b/tests/fixtures/local_v1_database.py deleted file mode 100644 index 833d6cdde..000000000 --- a/tests/fixtures/local_v1_database.py +++ /dev/null @@ -1,32 +0,0 @@ -"""SQLite-only v1 schema helper confined to explicit test fixtures.""" - -from sqlalchemy import JSON, Column, Engine, Integer, MetaData, String, Table - -from policyengine_api.data.v1_models import Policy, V1Base - -_sqlite_policy_metadata = MetaData() -Table( - Policy.__tablename__, - _sqlite_policy_metadata, - Column("id", Integer, primary_key=True, autoincrement=True), - Column("country_id", String(3), nullable=False), - Column("label", String(255)), - Column("api_version", String(10), nullable=False), - Column("policy_json", JSON, nullable=False), - Column("policy_hash", String(255), nullable=False), -) - - -def create_test_v1_schema(engine: Engine) -> None: - if engine.dialect.name != "sqlite": - msg = "the test-only v1 schema helper requires SQLite" - raise ValueError(msg) - V1Base.metadata.create_all( - engine, - tables=[ - table - for table in V1Base.metadata.sorted_tables - if table is not Policy.__table__ - ], - ) - _sqlite_policy_metadata.create_all(engine) diff --git a/tests/integration/alembic_v2_previous_revision.py b/tests/integration/alembic_v2_previous_revision.py new file mode 100644 index 000000000..93a44ef62 --- /dev/null +++ b/tests/integration/alembic_v2_previous_revision.py @@ -0,0 +1,401 @@ +"""Check that a v2 revision still serves the API v1 release before it. + +During a deploy the previous API v1 release runs beside the new revision. +``assert_revision_serves_previous_revision`` maps the parent revision's whole +schema with SQLAlchemy's automap, from what the database's Inspector +describes, upgrades, then runs that release's table usage through a Session on +those classes: every statement goes through the ORM (rule api.data.orm-only). + +pytest rewrites only test modules' asserts, so each assert here carries the +value that explains its failure. +""" + +from __future__ import annotations + +import itertools +from dataclasses import dataclass +from datetime import UTC, datetime, timedelta +from typing import TYPE_CHECKING, Any, cast +from uuid import uuid4 + +import sqlalchemy as sa +from alembic import command +from sqlalchemy import delete, func, insert, select, update +from sqlalchemy.ext.automap import automap_base + +from tests.fixtures.database_sessions import schema_inspector +from tests.fixtures.integration.alembic_v2 import alembic_v2_config + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator, Mapping + + from sqlalchemy.engine import CursorResult + from sqlalchemy.engine.interfaces import ( + ReflectedColumn, + ReflectedForeignKeyConstraint, + ) + from sqlalchemy.orm import Session, sessionmaker + +ALEMBIC_VERSION_TABLE = "alembic_version" +USER_ASSOCIATION_TABLES = ( + "user_policies", + "user_household_associations", + "user_simulation_associations", + "user_report_associations", +) +COUNTRY_COLUMN_NAMES = frozenset({"country", "country_id", "primary_country"}) +# Nullable references that a parent-revision check constraint requires: a +# standard user's country, and one of each association's two references. +REFERENCES_REQUIRED_BY_CHECKS = frozenset( + { + ("simulations", "household_id"), + ("users", "primary_country"), + ("user_policies", "policy_id"), + ("user_household_associations", "household_id"), + ("user_simulation_associations", "simulation_id"), + ("user_report_associations", "report_id"), + } +) +# Required values that a parent-revision check constraint restricts. +CHECKED_VALUES = {("datasets", "year"): 2026} + + +@dataclass(frozen=True) +class RevisionTable: + """One table at a revision: automap's class for it, and its description. + + ``columns``, ``primary_key`` and ``foreign_keys`` are what the database's + Inspector described at that revision. + """ + + name: str + model: Any + columns: dict[str, ReflectedColumn] + primary_key: tuple[str, ...] + foreign_keys: tuple[ReflectedForeignKeyConstraint, ...] + + def primary_key_clause(self, row: Mapping[str, Any]) -> sa.ColumnElement[bool]: + """Return the condition that selects ``row`` by its primary key.""" + return sa.and_( + *(getattr(self.model, name) == row[name] for name in self.primary_key) + ) + + +def _map_no_relationships(*_arguments: object, **_options: object) -> None: + """Tell automap to map no relationship between the tables' classes. + + The tests write rows with statements, and the database's foreign keys run + the cascades. + """ + + +def _mapped_revision(sessions: sessionmaker[Session]) -> dict[str, RevisionTable]: + """Map every public table at the database's current revision. + + Automap maps each table the Inspector describes to a class on a registry of + its own. Alembic's version table is left out, and a referenced table + comes before the tables that refer to it. + """ + with sessions() as session: + inspector = schema_inspector(session) + revision_classes = automap_base() + revision_classes.prepare( + autoload_with=inspector, generate_relationship=_map_no_relationships + ) + return { + table_name: RevisionTable( + name=table_name, + model=revision_classes.classes[table_name], + columns={ + column["name"]: column + for column in inspector.get_columns(table_name) + }, + primary_key=tuple( + inspector.get_pk_constraint(table_name)["constrained_columns"] + ), + foreign_keys=tuple(inspector.get_foreign_keys(table_name)), + ) + for table_name, _foreign_keys in inspector.get_sorted_table_and_fkc_names() + if table_name is not None and table_name != ALEMBIC_VERSION_TABLE + } + + +def _is_required_without_default(column: ReflectedColumn) -> bool: + return not column["nullable"] and column["default"] is None + + +def _new_required_columns( + parent_table: RevisionTable, head_table: RevisionTable +) -> set[str]: + return { + column_name + for column_name, column in head_table.columns.items() + if column_name not in parent_table.columns + and _is_required_without_default(column) + } + + +def _string_test_value(column_type: sa.String, sequence: Iterator[int]) -> str: + length = column_type.length or 255 + if length == 64: + return uuid4().hex + uuid4().hex + return f"value-{next(sequence)}"[:length] + + +# Checked in order: a column takes the value of the first type it is an +# instance of, so Enum, a String subclass, comes before String. +TYPED_TEST_VALUES: tuple[ + tuple[type[Any], Callable[[Any, Iterator[int]], object]], ... +] = ( + (sa.Enum, lambda column_type, _sequence: column_type.enums[0]), + (sa.Uuid, lambda _column_type, _sequence: uuid4()), + (sa.Boolean, lambda _column_type, _sequence: False), + (sa.Integer, lambda _column_type, _sequence: 1), + (sa.Float, lambda _column_type, _sequence: 0.0), + # Later than every server-default created_at, as retention checks need. + ( + sa.DateTime, + lambda _column_type, _sequence: datetime.now(UTC) + timedelta(days=1), + ), + (sa.JSON, lambda _column_type, _sequence: {}), + (sa.String, _string_test_value), +) + + +def _test_value( + table_name: str, column: ReflectedColumn, sequence: Iterator[int] +) -> object: + column_name = column["name"] + if (table_name, column_name) in CHECKED_VALUES: + return CHECKED_VALUES[(table_name, column_name)] + if column_name in COUNTRY_COLUMN_NAMES: + return "us" + for column_type, test_value in TYPED_TEST_VALUES: + if isinstance(column["type"], column_type): + return test_value(column["type"], sequence) + msg = f"no test value for {table_name}.{column_name}" + raise AssertionError(msg) + + +def _row_values( + table: RevisionTable, + stored_rows: dict[str, dict[str, Any]], + sequence: Iterator[int], + *, + head_table: RevisionTable | None = None, +) -> dict[str, Any]: + """Supply only what the parent revision requires, plus check-bound values. + + ``head_table`` adds the columns head newly requires; only rows of the + parent's read-only tables, which new code writes, may need them. + """ + values = { + column_name: _test_value(table.name, column, sequence) + for column_name, column in table.columns.items() + if _is_required_without_default(column) + or (table.name, column_name) in REFERENCES_REQUIRED_BY_CHECKS + } + if head_table is not None: + for column_name in _new_required_columns(table, head_table): + values[column_name] = _test_value( + head_table.name, head_table.columns[column_name], sequence + ) + for foreign_key in table.foreign_keys: + constrained_columns = foreign_key["constrained_columns"] + if not any(column_name in values for column_name in constrained_columns): + continue + referenced_row = stored_rows[foreign_key["referred_table"]] + for column_name, referred_column in zip( + constrained_columns, foreign_key["referred_columns"], strict=True + ): + values[column_name] = referenced_row[referred_column] + return values + + +def _insert_and_read_back( + session: Session, + table: RevisionTable, + values: dict[str, Any], + *, + insert_table: RevisionTable | None = None, +) -> dict[str, Any]: + """Insert a row, then read it back through the parent's mapped class. + + Rows of the parent's read-only tables are inserted through head's class, + as only new code writes them. + """ + target = insert_table if insert_table is not None else table + session.execute(insert(target.model).values(values)) + # Selecting every column the parent's table has reads every column it maps. + every_column = select( + *(getattr(table.model, column_name) for column_name in table.columns) + ).where(table.primary_key_clause(values)) + return dict(session.execute(every_column).mappings().one()) + + +def _changed_row_count(session: Session, statement: sa.Update | sa.Delete) -> int: + """Run an UPDATE or DELETE and return how many rows it changed.""" + return cast("CursorResult[Any]", session.execute(statement)).rowcount + + +def _rewrite_mapped_columns( + session: Session, table: RevisionTable, row: dict[str, Any] +) -> None: + """Update every non-key column the parent maps, as an ORM flush can.""" + key_columns = set(table.primary_key) | { + column_name + for foreign_key in table.foreign_keys + for column_name in foreign_key["constrained_columns"] + } + rewritten = _changed_row_count( + session, + update(table.model) + .where(table.primary_key_clause(row)) + .values( + { + # sa.null() keeps SQL NULL; a bare None becomes JSON null. + name: sa.null() if value is None else value + for name, value in row.items() + if name not in key_columns + } + ), + ) + assert rewritten == 1, table.name + + +@dataclass(frozen=True) +class PreviousRevisionSchemas: + """A previous revision's mapped tables and those of the revision it was upgraded to. + + ``read_only_tables`` are the previous revision's tables that only new code + writes, so their test rows are inserted through the upgraded table. + """ + + parent: dict[str, RevisionTable] + head: dict[str, RevisionTable] + read_only_tables: frozenset[str] + + def insert_table(self, table_name: str) -> RevisionTable | None: + """Return the upgraded table for a read-only table, otherwise ``None``.""" + if table_name in self.read_only_tables: + return self.head[table_name] + return None + + +def _assert_user_deletion_cascades( + session: Session, + schemas: PreviousRevisionSchemas, + stored_rows: dict[str, dict[str, Any]], + sequence: Iterator[int], +) -> None: + """Delete, through the parent's users class, a user who owns association rows.""" + parent, head = schemas.parent, schemas.head + users = parent["users"] + owner = _insert_and_read_back( + session, users, _row_values(users, stored_rows, sequence) + ) + owner_rows = {**stored_rows, "users": owner} + for table_name in USER_ASSOCIATION_TABLES: + table = parent[table_name] + head_table = schemas.insert_table(table_name) + _insert_and_read_back( + session, + table, + _row_values(table, owner_rows, sequence, head_table=head_table), + insert_table=head_table, + ) + session.execute( + insert(head["user_identities"].model).values( + id=uuid4(), + user_id=owner["id"], + issuer="https://auth.example.test/", + subject="google-oauth2|previous-revision", + ) + ) + + deleted = _changed_row_count( + session, delete(users.model).where(users.model.id == owner["id"]) + ) + + assert deleted == 1, users.name + for table_name in (*USER_ASSOCIATION_TABLES, "user_identities"): + model = head[table_name].model + remaining = session.scalar( + select(func.count()).select_from(model).where(model.user_id == owner["id"]) + ) + assert remaining == 0, table_name + + +def assert_revision_serves_previous_revision( + sessions: sessionmaker[Session], + previous_revision: str, + revision: str, + read_only_tables: frozenset[str], +) -> None: + """Run a previous API v1 revision's table usage against ``revision``. + + The parent revision's schema is mapped and then used, after upgrading + to ``revision``, the revision it ran beside during that deploy, + to insert a row into every table it maps (supplying only what it + requires), read the row back with every mapped column, rewrite those + columns, delete it, and delete a user who owns association rows so the + cascades run. ``revision`` may not give any table the parent revision + writes a new required column without a server default; ``read_only_tables`` + are the parent's tables that only new code writes. + """ + config = alembic_v2_config() + + try: + command.downgrade(config, previous_revision) + parent = _mapped_revision(sessions) + command.upgrade(config, revision) + head = _mapped_revision(sessions) + parent_tables = list(parent.values()) + + dropped_columns = sorted( + f"{table.name}.{column_name}" + for table in parent_tables + for column_name in table.columns + if table.name not in head or column_name not in head[table.name].columns + ) + assert dropped_columns == [], dropped_columns + tables_with_new_required_columns = { + table.name: sorted(new_required_columns) + for table in parent_tables + if (new_required_columns := _new_required_columns(table, head[table.name])) + } + assert set(tables_with_new_required_columns) <= read_only_tables, ( + tables_with_new_required_columns + ) + + schemas = PreviousRevisionSchemas(parent, head, read_only_tables) + sequence = itertools.count() + with sessions() as session: + try: + stored_rows: dict[str, dict[str, Any]] = {} + for table in parent_tables: + head_table = schemas.insert_table(table.name) + stored_rows[table.name] = _insert_and_read_back( + session, + table, + _row_values( + table, stored_rows, sequence, head_table=head_table + ), + insert_table=head_table, + ) + _rewrite_mapped_columns(session, table, stored_rows[table.name]) + + _assert_user_deletion_cascades(session, schemas, stored_rows, sequence) + + for table in reversed(parent_tables): + deleted = _changed_row_count( + session, + delete(table.model).where( + table.primary_key_clause(stored_rows[table.name]) + ), + ) + assert deleted == 1, table.name + finally: + session.rollback() + finally: + command.upgrade(config, "head") diff --git a/tests/integration/alembic_version_rows.py b/tests/integration/alembic_version_rows.py new file mode 100644 index 000000000..aa09b0c4e --- /dev/null +++ b/tests/integration/alembic_version_rows.py @@ -0,0 +1,33 @@ +"""Read the revision Alembic recorded in a database, through a Session. + +Alembic keeps the revision a database is at in its ``alembic_version`` table, +which has the same shape in API v1's MySQL database and the v2 PostgreSQL +database. The migration tests read it to check that a refused upgrade or +downgrade left the database where it was, through ``AlembicRevision``, the +table's mapped class on a registry of its own. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from sqlalchemy import select +from sqlmodel import col + +from policyengine_api.data.v2.alembic_revision import AlembicRevision + +if TYPE_CHECKING: + from sqlalchemy.orm import sessionmaker + + +def current_revision(sessions: sessionmaker[Any]) -> str | None: + """Return the revision the database is at, or None if it records none. + + It fails, as Alembic's ``MigrationContext.get_current_revision`` does, when + the database records more than one revision. + """ + with sessions() as session: + revision: str | None = session.scalars( + select(col(AlembicRevision.version_num)) + ).one_or_none() + return revision diff --git a/tests/integration/catalog_publication_support.py b/tests/integration/catalog_publication_support.py new file mode 100644 index 000000000..1c9459f29 --- /dev/null +++ b/tests/integration/catalog_publication_support.py @@ -0,0 +1,97 @@ +"""Shared setup and reads for the catalog publication integration tests. + +``emptied_catalog`` brings the disposable v2 database to the Alembic head and +empties its catalog before and after a test. ``row_counts`` and +``stored_identifiers`` read tables through their mapped classes, so a test can +check that a publication added, kept or removed exactly the rows it should. +""" + +from __future__ import annotations + +from contextlib import contextmanager +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from alembic import command +from alembic.config import Config +from sqlalchemy import func, select +from sqlmodel import col + +from policyengine_api.data.v2.models import ( + Dataset, + Parameter, + ParameterNode, + ParameterValue, + Region, + TaxBenefitModel, + TaxBenefitModelVersion, + Variable, +) +from tests.fixtures.database_sessions import truncate + +if TYPE_CHECKING: + from collections.abc import Iterator, Mapping + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + +REPO = Path(__file__).parents[2] +# The catalog tables publication writes, by name, with their mapped classes. +CATALOG_MODELS: dict[str, Any] = { + "tax_benefit_models": TaxBenefitModel, + "tax_benefit_model_versions": TaxBenefitModelVersion, + "variables": Variable, + "parameter_nodes": ParameterNode, + "parameters": Parameter, + "parameter_values": ParameterValue, + "datasets": Dataset, + "regions": Region, +} + + +@contextmanager +def emptied_catalog( + sessions: sessionmaker[Session], +) -> Iterator[sessionmaker[Session]]: + """Yield ``sessions`` on a v2 database at the Alembic head with no catalog. + + The catalog is emptied again on exit. Policies and dynamics name a model, so + the truncation removes them too, with every row that names a catalog row. + """ + command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") + with sessions.begin() as session: + truncate(session, TaxBenefitModel) + try: + yield sessions + finally: + with sessions.begin() as session: + truncate(session, TaxBenefitModel) + + +def row_counts( + sessions: sessionmaker[Session], models: Mapping[str, Any] +) -> dict[str, int]: + """Return the number of rows of each table, by the name ``models`` gives it.""" + with sessions() as session: + return { + table_name: session.execute( + select(func.count()).select_from(model) + ).scalar_one() + for table_name, model in models.items() + } + + +def stored_identifiers( + sessions: sessionmaker[Session], models: Mapping[str, Any] = CATALOG_MODELS +) -> dict[str, tuple[str, ...]]: + """Return every row ID of each table, in order, by the name ``models`` gives it.""" + with sessions() as session: + return { + table_name: tuple( + str(row_id) + for row_id in session.scalars( + select(col(model.id)).order_by(col(model.id)) + ) + ) + for table_name, model in models.items() + } diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index cfe9e9426..59c5c9da8 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -172,34 +172,6 @@ def v1_sessions(disposable_v1_database_url: str) -> Iterator[sessionmaker[OrmSes yield sessions -@pytest.fixture(scope="session") -def v2_engine_as_role(disposable_v2_database_url: str, managed_v2_roles): - """Return a builder of engines whose connections act as one managed role. - - Each new connection runs ``SET ROLE`` and commits it, so every statement on - it is checked against that role's privileges, as in staging and production, - instead of the disposable database's superuser. Only for the tests that - still build engines, which rule api.data.orm-only reports: use - ``v2_sessions_as_role``. - """ - from psycopg import sql - from sqlalchemy import create_engine, event - - def build(role: str, **engine_options): - set_role = sql.SQL("SET ROLE {}").format(sql.Identifier(role)) - engine = create_engine(disposable_v2_database_url, **engine_options) - - @event.listens_for(engine, "connect") - def act_as_role(dbapi_connection, _connection_record) -> None: - with dbapi_connection.cursor() as cursor: - cursor.execute(set_role) - dbapi_connection.commit() - - return engine - - return build - - @pytest.fixture def api_base_url() -> str: base_url = os.environ.get("API_BASE_URL") diff --git a/tests/integration/simulation_rows.py b/tests/integration/simulation_rows.py index 57790a8a1..5cd53148d 100644 --- a/tests/integration/simulation_rows.py +++ b/tests/integration/simulation_rows.py @@ -14,7 +14,7 @@ from uuid import UUID, uuid4 import pytest -from sqlalchemy import delete, insert, text +from sqlalchemy import delete, insert from sqlalchemy.exc import IntegrityError from sqlmodel import col @@ -28,7 +28,6 @@ if TYPE_CHECKING: from collections.abc import Iterator - from sqlalchemy import Connection from sqlalchemy.orm import Session # The package versions a test run records. @@ -99,19 +98,6 @@ def insert_public_api_rows(session: Session) -> PublicApiRows: return rows -def insert_row(connection: Connection, table: str, **values: object) -> None: - """Insert one row of the named columns into ``table``, as handwritten SQL. - - Only for the callers that still pass a Connection and a table's name; - rule api.data.orm-only reports it. Use ``add_row``. - """ - columns = ", ".join(values) - placeholders = ", ".join(f":{column}" for column in values) - connection.execute( - text(f"INSERT INTO {table} ({columns}) VALUES ({placeholders})"), values - ) - - @contextmanager def refused( session: Session, diff --git a/tests/integration/stored_report_rows.py b/tests/integration/stored_report_rows.py index 4c64ccd7a..47fc903ed 100644 --- a/tests/integration/stored_report_rows.py +++ b/tests/integration/stored_report_rows.py @@ -50,7 +50,8 @@ if TYPE_CHECKING: from collections.abc import Iterator - from sqlalchemy.orm import Session, sessionmaker + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session REGION_CODES = {"us": "state/ca", "uk": "country/wales"} DATASET_NAMES = {"us": "enhanced_cps_2024", "uk": "enhanced_frs_2023_24"} diff --git a/tests/integration/test_alembic_mysql_lifecycle.py b/tests/integration/test_alembic_mysql_lifecycle.py index 567d70f7e..d58833d23 100644 --- a/tests/integration/test_alembic_mysql_lifecycle.py +++ b/tests/integration/test_alembic_mysql_lifecycle.py @@ -1,33 +1,21 @@ """Exercise the complete Alembic lifecycle against an ephemeral MySQL schema.""" -import os +from __future__ import annotations + +from typing import TYPE_CHECKING, Any -import pytest from alembic import command -from alembic.autogenerate import compare_metadata from alembic.config import Config -from alembic.migration import MigrationContext -from sqlalchemy import ( - Column, - Integer, - MetaData, - String, - Table, - Text, - create_engine, - delete, - inspect, -) +from sqlalchemy import Integer, String, Text, delete from sqlalchemy.dialects.mysql import LONGTEXT -from sqlalchemy.engine import make_url -from sqlalchemy.orm import sessionmaker +from sqlalchemy.orm import Mapped, mapped_column, registry from policyengine_api.constants import REPO +from policyengine_api.data.orm import v1_schema_inspector from policyengine_api.data.v1_models import ( Household, HouseholdMirrorEvent, Policy, - V1Base, ) from policyengine_api.services.household_service import HouseholdService from policyengine_api.services.policy_service import PolicyService @@ -36,42 +24,41 @@ database_state, upgrade_database, ) +from tests.fixtures.database_sessions import drop_tables +from tests.integration.alembic_version_rows import current_revision + +if TYPE_CHECKING: + import pytest + from sqlalchemy.orm import Session, sessionmaker BASELINE_REVISION = "eafc2a547a4e" PREVIOUS_REVISION = "3d6e8f553ca5" +# The text columns of the question table: LONGTEXT on MySQL. +LONG_TEXT = Text().with_variant(LONGTEXT(), "mysql") +baseline_revision_tables = registry() -def _deployed_question_table() -> Table: - """Describe the orphaned production table without adding it to ORM metadata.""" - metadata = MetaData() - return Table( - "question", - metadata, - Column("question_id", Integer, primary_key=True, autoincrement=True), - Column("question", Text().with_variant(LONGTEXT(), "mysql"), nullable=False), - Column("answer", Text().with_variant(LONGTEXT(), "mysql")), - Column("policy_id", Integer), - Column("country_id", String(3), nullable=False), - Column("subtask", String(32), nullable=False), - Column("status", String(32), nullable=False), - ) +@baseline_revision_tables.mapped +class QuestionAtEafc2a547a4e: + """Production's orphaned ``question`` table, at the baseline revision. -def _ephemeral_mysql_url() -> str: - database_url = os.environ.get("ALEMBIC_DATABASE_URL", "") - if not database_url: - pytest.skip("ALEMBIC_DATABASE_URL is not set") + Fresh baseline schemas don't have it. Revision 01e49b3a056e drops it if it + exists, and its downgrade creates it, so downgrading to the base leaves it. + It is on a registry of its own, never in API v1's metadata. + """ - url = make_url(database_url) - if url.get_backend_name() != "mysql": - pytest.fail("ALEMBIC_DATABASE_URL must use MySQL for this test") - if url.host not in {"127.0.0.1", "localhost"}: - pytest.fail("Alembic lifecycle tests may only target local MySQL") - if url.database != "policyengine_alembic_test": - pytest.fail( - "Alembic lifecycle tests require the policyengine_alembic_test schema" - ) - return database_url + __tablename__ = "question" + + question_id: Mapped[int] = mapped_column( + Integer, primary_key=True, autoincrement=True + ) + question: Mapped[str] = mapped_column(LONG_TEXT) + answer: Mapped[str | None] = mapped_column(LONG_TEXT) + policy_id: Mapped[int | None] = mapped_column(Integer) + country_id: Mapped[str] = mapped_column(String(3)) + subtask: Mapped[str] = mapped_column(String(32)) + status: Mapped[str] = mapped_column(String(32)) def _alembic_config(database_url: str) -> Config: @@ -80,98 +67,94 @@ def _alembic_config(database_url: str) -> Config: return config -def test_fresh_upgrade_check_downgrade_and_reupgrade(): - database_url = _ephemeral_mysql_url() - config = _alembic_config(database_url) - engine = create_engine(database_url) - question = _deployed_question_table() +def _table_names(sessions: sessionmaker[Session]) -> list[str]: + return v1_schema_inspector(sessions).get_table_names() - try: - command.downgrade(config, "base") - question.drop(engine, checkfirst=True) - command.upgrade(config, "head") - command.check(config) - with engine.connect() as connection: - context = MigrationContext.configure(connection) - assert context.get_current_revision() is not None - assert compare_metadata(context, V1Base.metadata) == [] +def _drop_question_table(sessions: sessionmaker[Session]) -> None: + """Drop the orphaned question table if it exists, as on a fresh schema.""" + if QuestionAtEafc2a547a4e.__tablename__ in _table_names(sessions): + with sessions.begin() as session: + drop_tables(session, QuestionAtEafc2a547a4e) - inspector = inspect(engine) - assert "tracers" not in inspector.get_table_names() - reform_impact_columns = { - column["name"]: column for column in inspector.get_columns("reform_impact") - } - assert reform_impact_columns["dataset"]["default"] is None - assert reform_impact_columns["execution_id"]["nullable"] is False - assert "mirror_revision" in { - column["name"] for column in inspector.get_columns("user_policies") - } - assert "user_policy_mirror_events" in inspector.get_table_names() - assert "household_mirror_events" in inspector.get_table_names() - command.downgrade(config, BASELINE_REVISION) - assert "question" in inspect(engine).get_table_names() +def _assert_head_schema(sessions: sessionmaker[Session]) -> None: + """Check the tables and columns the head revisions add, remove or change.""" + inspector = v1_schema_inspector(sessions) + table_names = inspector.get_table_names() + assert "tracers" not in table_names + reform_impact_columns = { + column["name"]: column for column in inspector.get_columns("reform_impact") + } + assert reform_impact_columns["dataset"]["default"] is None + assert reform_impact_columns["execution_id"]["nullable"] is False + assert "mirror_revision" in { + column["name"] for column in inspector.get_columns("user_policies") + } + assert "user_policy_mirror_events" in table_names + assert "household_mirror_events" in table_names - command.upgrade(config, "head") - with engine.connect() as connection: - context = MigrationContext.configure(connection) - assert context.get_current_revision() is not None - assert compare_metadata(context, V1Base.metadata) == [] - finally: - engine.dispose() +def test_fresh_upgrade_check_downgrade_and_reupgrade( + disposable_v1_database_url: str, v1_sessions: sessionmaker[Session] +) -> None: + config = _alembic_config(disposable_v1_database_url) + + command.downgrade(config, "base") + _drop_question_table(v1_sessions) + command.upgrade(config, "head") + # The schema matches API v1's models (V1Base.metadata), the migration + # environment's target metadata, column types and server defaults included. + command.check(config) + + assert current_revision(v1_sessions) is not None + _assert_head_schema(v1_sessions) + + command.downgrade(config, BASELINE_REVISION) + assert "question" in _table_names(v1_sessions) + + command.upgrade(config, "head") + assert current_revision(v1_sessions) is not None + command.check(config) -def test_pending_upgrade_commits_head_revision(monkeypatch): - database_url = _ephemeral_mysql_url() - config = _alembic_config(database_url) - engine = create_engine(database_url) - question = _deployed_question_table() + +def test_pending_upgrade_commits_head_revision( + monkeypatch: pytest.MonkeyPatch, + disposable_v1_database_url: str, + v1_sessions: sessionmaker[Session], +) -> None: + config = _alembic_config(disposable_v1_database_url) try: command.downgrade(config, "base") - question.drop(engine, checkfirst=True) + _drop_question_table(v1_sessions) command.upgrade(config, "head") command.downgrade(config, PREVIOUS_REVISION) - assert "household_mirror_events" not in inspect(engine).get_table_names() + assert "household_mirror_events" not in _table_names(v1_sessions) - with engine.connect() as connection: - assert database_state(connection) is DatabaseState.PENDING + with v1_sessions() as session: + assert database_state(session) is DatabaseState.PENDING - with engine.begin() as connection: + with v1_sessions.begin() as session: monkeypatch.delenv("ALEMBIC_DATABASE_URL") - upgrade_database(connection, backup_id="test-backup") - - with engine.connect() as connection: - assert database_state(connection) is DatabaseState.HEAD - context = MigrationContext.configure(connection) - assert compare_metadata(context, V1Base.metadata) == [] - - inspector = inspect(engine) - assert "question" not in inspector.get_table_names() - assert "tracers" not in inspector.get_table_names() - reform_impact_columns = { - column["name"]: column for column in inspector.get_columns("reform_impact") - } - assert reform_impact_columns["dataset"]["default"] is None - assert reform_impact_columns["execution_id"]["nullable"] is False - assert "mirror_revision" in { - column["name"] for column in inspector.get_columns("user_policies") - } - assert "user_policy_mirror_events" in inspector.get_table_names() - assert "household_mirror_events" in inspector.get_table_names() + upgrade_database(session, backup_id="test-backup") + + with v1_sessions() as session: + assert database_state(session) is DatabaseState.HEAD + command.check(config) + + assert "question" not in _table_names(v1_sessions) + _assert_head_schema(v1_sessions) finally: command.upgrade(config, "head") - engine.dispose() -def test_policy_mirror_snapshot_uses_mysql_json_representation(): - database_url = _ephemeral_mysql_url() - command.upgrade(_alembic_config(database_url), "head") - engine = create_engine(database_url) - sessions = sessionmaker(engine, expire_on_commit=False) - service = PolicyService(sessions) +def test_policy_mirror_snapshot_uses_mysql_json_representation( + disposable_v1_database_url: str, v1_sessions: sessionmaker[Session] +) -> None: + command.upgrade(_alembic_config(disposable_v1_database_url), "head") + service = PolicyService(v1_sessions) result = None request_policy = {"gov.phase10.mysql_json_rate": {"2026": 0.040940000000000004}} @@ -193,27 +176,27 @@ def test_policy_mirror_snapshot_uses_mysql_json_representation(): } finally: if result is not None: - with engine.begin() as connection: - connection.execute( + with v1_sessions.begin() as session: + session.execute( delete(Policy).where( Policy.country_id == "us", Policy.id == result.policy_id, ) ) - engine.dispose() -def test_household_mirror_event_uses_mysql_json_representation(monkeypatch): - database_url = _ephemeral_mysql_url() - command.upgrade(_alembic_config(database_url), "head") - engine = create_engine(database_url) - sessions = sessionmaker(engine, expire_on_commit=False) - service = HouseholdService(sessions) +def test_household_mirror_event_uses_mysql_json_representation( + monkeypatch: pytest.MonkeyPatch, + disposable_v1_database_url: str, + v1_sessions: sessionmaker[Session], +) -> None: + command.upgrade(_alembic_config(disposable_v1_database_url), "head") + service = HouseholdService(v1_sessions) result = None request_household = { "people": {"you": {"phase11_mysql_json_rate": 0.040940000000000004}} } - resolved_spm = { + resolved_spm: dict[str, Any] = { "forecast_content_sha256": "a" * 64, "scenario": "baseline", "geography_kind": "national", @@ -245,24 +228,23 @@ def test_household_mirror_event_uses_mysql_json_representation(monkeypatch): "people": {"you": {"phase11_mysql_json_rate": 0.04094}}, "spm": resolved_spm, } - with sessions() as session: + with v1_sessions() as session: event = session.get(HouseholdMirrorEvent, result.mirror_event_id) assert event is not None pending = service._decode_mirror_event(event) assert pending.snapshot == result.snapshot finally: if result is not None: - with engine.begin() as connection: - connection.execute( + with v1_sessions.begin() as session: + session.execute( delete(HouseholdMirrorEvent).where( HouseholdMirrorEvent.country_id == "us", HouseholdMirrorEvent.legacy_household_id == result.household.id, ) ) - connection.execute( + session.execute( delete(Household).where( Household.country_id == "us", Household.id == result.household.id, ) ) - engine.dispose() diff --git a/tests/integration/test_alembic_v2_catalog_tables.py b/tests/integration/test_alembic_v2_catalog_tables.py index e42ac1798..c7acd1aa1 100644 --- a/tests/integration/test_alembic_v2_catalog_tables.py +++ b/tests/integration/test_alembic_v2_catalog_tables.py @@ -1,17 +1,35 @@ -"""Exercise the v2 catalog tables' revisions against disposable Postgres.""" +"""Exercise the v2 catalog tables' revisions against disposable Postgres. +Every statement runs through a Session (rule api.data.orm-only). Rows read or +written at head use the v2 models. Rows written at an earlier revision use the +small mapped classes below, which map the catalog columns a version stored +before catalog format 2 has; every revision these tests visit keeps them. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any from uuid import UUID, uuid4 -import pytest import sqlalchemy as sa from alembic import command -from sqlalchemy import create_engine, inspect, text - -from tests.fixtures.integration.alembic_v2 import ( - alembic_v2_config, - disposable_v2_url, - table_columns, +from sqlalchemy import delete, func, select, update +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column +from sqlmodel import col + +from policyengine_api.data.v2.models import ( + Parameter, + ParameterSearchFile, + ParameterTreeChild, + TaxBenefitModelVersion, + Variable, ) +from tests.fixtures.database_sessions import schema_inspector +from tests.fixtures.integration.alembic_v2 import alembic_v2_config, table_columns +from tests.integration.simulation_rows import add_row, refused + +if TYPE_CHECKING: + from sqlalchemy.orm import Session, sessionmaker CATALOG_FORMAT_2_PARENT_REVISION = "fb1a3e40d3d6" CATALOG_FORMAT_2_COLUMNS = { @@ -28,93 +46,161 @@ ), "parameters": ("economy", "household"), } +# The v2 model of each table with format 2 columns. +CATALOG_FORMAT_2_MODELS: dict[str, Any] = { + "tax_benefit_model_versions": TaxBenefitModelVersion, + "variables": Variable, + "parameters": Parameter, +} +PROBE_MODEL_NAME = "catalog-format-probe" + + +class CatalogBeforeFormat2Base(DeclarativeBase): + """The declarative base of the catalog tables before catalog format 2.""" + + +class TaxBenefitModelBeforeCatalogFormat2(CatalogBeforeFormat2Base): + """A tax-benefit model's name before catalog format 2.""" + + __tablename__ = "tax_benefit_models" + + id: Mapped[UUID] = mapped_column(primary_key=True) + name: Mapped[str] + + +class TaxBenefitModelVersionBeforeCatalogFormat2(CatalogBeforeFormat2Base): + """A model version's required columns before catalog format 2.""" + + __tablename__ = "tax_benefit_model_versions" + + id: Mapped[UUID] = mapped_column(primary_key=True) + model_id: Mapped[UUID] + version: Mapped[str] + current_law_id: Mapped[int] + metadata_time_periods: Mapped[list[int]] = mapped_column(sa.JSON) -def _catalog_version_published_before_format_2(connection: sa.Connection) -> UUID: +class VariableBeforeCatalogFormat2(CatalogBeforeFormat2Base): + """A variable's required columns before catalog format 2.""" + + __tablename__ = "variables" + + id: Mapped[UUID] = mapped_column(primary_key=True) + name: Mapped[str] + entity: Mapped[str] + default_value: Mapped[Any] = mapped_column(sa.JSON) + tax_benefit_model_version_id: Mapped[UUID] + + +class ParameterBeforeCatalogFormat2(CatalogBeforeFormat2Base): + """A parameter's required columns before catalog format 2.""" + + __tablename__ = "parameters" + + id: Mapped[UUID] = mapped_column(primary_key=True) + name: Mapped[str] + tax_benefit_model_version_id: Mapped[UUID] + + +def _catalog_version_published_before_format_2(session: Session) -> UUID: """Store a model version with one variable and one parameter; return its id.""" model_id = uuid4() version_id = uuid4() - connection.execute( - text( - "INSERT INTO tax_benefit_models (id, name) " - "VALUES (:model_id, 'catalog-format-probe')" - ), - {"model_id": model_id}, + add_row( + session, + TaxBenefitModelBeforeCatalogFormat2, + id=model_id, + name=PROBE_MODEL_NAME, ) - connection.execute( - text( - "INSERT INTO tax_benefit_model_versions " - "(id, model_id, version, current_law_id, metadata_time_periods) " - "VALUES (:version_id, :model_id, '0.0.1-probe', 1, '[2026]')" - ), - {"version_id": version_id, "model_id": model_id}, + add_row( + session, + TaxBenefitModelVersionBeforeCatalogFormat2, + id=version_id, + model_id=model_id, + version="0.0.1-probe", + current_law_id=1, + metadata_time_periods=[2026], ) - connection.execute( - text( - "INSERT INTO variables " - "(id, name, entity, default_value, tax_benefit_model_version_id) " - "VALUES (:variable_id, 'probe_income', 'person', '0', :version_id)" - ), - {"variable_id": uuid4(), "version_id": version_id}, + add_row( + session, + VariableBeforeCatalogFormat2, + id=uuid4(), + name="probe_income", + entity="person", + default_value=0, + tax_benefit_model_version_id=version_id, ) - connection.execute( - text( - "INSERT INTO parameters (id, name, tax_benefit_model_version_id) " - "VALUES (:parameter_id, 'gov.probe.rate', :version_id)" - ), - {"parameter_id": uuid4(), "version_id": version_id}, + add_row( + session, + ParameterBeforeCatalogFormat2, + id=uuid4(), + name="gov.probe.rate", + tax_benefit_model_version_id=version_id, ) return version_id -def _format_2_values(connection: sa.Connection, version_id: UUID) -> list[tuple]: +def _delete_probe_catalog(sessions: sessionmaker[Session]) -> None: + """Delete the probe model, and with it its versions and their catalog rows.""" + with sessions.begin() as session: + session.execute( + delete(TaxBenefitModelBeforeCatalogFormat2).where( + TaxBenefitModelBeforeCatalogFormat2.name == PROBE_MODEL_NAME + ) + ) + + +def _version_row_count(model: Any, version_id: UUID) -> sa.Select[tuple[int]]: + """Select how many of a catalog table's rows belong to the version.""" + return ( + select(func.count()) + .select_from(model) + .where(model.tax_benefit_model_version_id == version_id) + ) + + +def _format_2_values(session: Session, version_id: UUID) -> list[tuple[Any, ...]]: """Return the format 2 columns of the version's model, variable and parameter.""" rows = [] for table_name, columns in CATALOG_FORMAT_2_COLUMNS.items(): + model = CATALOG_FORMAT_2_MODELS[table_name] key = ( - "id" + model.id if table_name == "tax_benefit_model_versions" - else "tax_benefit_model_version_id" - ) - rows.append( - tuple( - connection.execute( - text( - f"SELECT {', '.join(columns)} FROM {table_name} " - f"WHERE {key} = :version_id" - ), - {"version_id": version_id}, - ).one() - ) + else model.tax_benefit_model_version_id ) + format_2_columns = select( + *(getattr(model, column_name) for column_name in columns) + ).where(key == version_id) + rows.append(tuple(session.execute(format_2_columns).one())) return rows -def test_catalog_format_2_columns_leave_earlier_versions_empty() -> None: +def test_catalog_format_2_columns_leave_earlier_versions_empty( + v2_owner_sessions: sessionmaker[Session], +) -> None: """A version stored before catalog format 2 keeps its format 2 fields null. Upgrading adds the columns as nullable without writing to stored rows, and downgrading drops them and keeps every row. """ config = alembic_v2_config() - engine = create_engine(disposable_v2_url()) - version_id = None try: command.downgrade(config, CATALOG_FORMAT_2_PARENT_REVISION) for table_name, columns in CATALOG_FORMAT_2_COLUMNS.items(): - assert set(columns).isdisjoint(table_columns(engine, table_name)) - with engine.begin() as connection: - version_id = _catalog_version_published_before_format_2(connection) + assert set(columns).isdisjoint(table_columns(v2_owner_sessions, table_name)) + with v2_owner_sessions.begin() as session: + version_id = _catalog_version_published_before_format_2(session) command.upgrade(config, "head") for table_name, columns in CATALOG_FORMAT_2_COLUMNS.items(): - stored_columns = table_columns(engine, table_name) + stored_columns = table_columns(v2_owner_sessions, table_name) for column_name in columns: assert stored_columns[column_name]["nullable"] assert stored_columns[column_name]["default"] is None - with engine.connect() as connection: - assert _format_2_values(connection, version_id) == [ + with v2_owner_sessions() as session: + assert _format_2_values(session, version_id) == [ (None, None, None), (None, None, None, None, None, None, None, None), (None, None), @@ -123,33 +209,30 @@ def test_catalog_format_2_columns_leave_earlier_versions_empty() -> None: command.downgrade(config, CATALOG_FORMAT_2_PARENT_REVISION) for table_name, columns in CATALOG_FORMAT_2_COLUMNS.items(): - assert set(columns).isdisjoint(table_columns(engine, table_name)) - with engine.connect() as connection: - counts = connection.execute( - text( - "SELECT (SELECT count(*) FROM variables " - "WHERE tax_benefit_model_version_id = :version_id), " - "(SELECT count(*) FROM parameters " - "WHERE tax_benefit_model_version_id = :version_id)" - ), - {"version_id": version_id}, + assert set(columns).isdisjoint(table_columns(v2_owner_sessions, table_name)) + with v2_owner_sessions() as session: + counts = session.execute( + select( + _version_row_count( + VariableBeforeCatalogFormat2, version_id + ).scalar_subquery(), + _version_row_count( + ParameterBeforeCatalogFormat2, version_id + ).scalar_subquery(), + ) ).one() assert tuple(counts) == (1, 1) finally: - with engine.begin() as connection: - connection.execute( - text( - "DELETE FROM tax_benefit_models WHERE name = 'catalog-format-probe'" - ) - ) + _delete_probe_catalog(v2_owner_sessions) command.upgrade(config, "head") - engine.dispose() PARAMETER_TREE_PARENT_REVISION = "e86f19a6c4da" -def test_parameter_tree_table_is_created_empty_and_dropped_without_data_loss() -> None: +def test_parameter_tree_table_is_created_empty_and_dropped_without_data_loss( + v2_owner_sessions: sessionmaker[Session], +) -> None: """The parameter tree revision creates an empty table and downgrades cleanly. The revision writes no rows: catalog publication writes each version's @@ -157,18 +240,22 @@ def test_parameter_tree_table_is_created_empty_and_dropped_without_data_loss() - downgrading drops the table while every catalog row stays. """ config = alembic_v2_config() - engine = create_engine(disposable_v2_url()) try: command.downgrade(config, PARAMETER_TREE_PARENT_REVISION) - assert "parameter_tree_children" not in inspect(engine).get_table_names() - with engine.begin() as connection: - version_id = _catalog_version_published_before_format_2(connection) + assert ( + "parameter_tree_children" + not in schema_inspector(v2_owner_sessions).get_table_names() + ) + with v2_owner_sessions.begin() as session: + version_id = _catalog_version_published_before_format_2(session) command.upgrade(config, "head") indexes = { index["name"]: (index["column_names"], index["unique"]) - for index in inspect(engine).get_indexes("parameter_tree_children") + for index in schema_inspector(v2_owner_sessions).get_indexes( + "parameter_tree_children" + ) } assert indexes["ix_parameter_tree_children_listing"] == ( ["tax_benefit_model_version_id", "parent_path", "position"], @@ -178,93 +265,77 @@ def test_parameter_tree_table_is_created_empty_and_dropped_without_data_loss() - ["tax_benefit_model_version_id", "parent_path", "reform_position"], True, ) - with engine.begin() as connection: + with v2_owner_sessions.begin() as session: assert ( - connection.execute( - text("SELECT count(*) FROM parameter_tree_children") - ).scalar_one() + session.scalar(select(func.count()).select_from(ParameterTreeChild)) == 0 ) - parameter_id = connection.execute( - text( - "SELECT id FROM parameters " - "WHERE tax_benefit_model_version_id = :version_id" - ), - {"version_id": version_id}, - ).scalar_one() + parameter_id = session.scalars( + select(col(Parameter.id)).where( + col(Parameter.tax_benefit_model_version_id) == version_id + ) + ).one() for path, parent, position, child_type, child_count, reference in ( ("gov", "", 0, "node", 1, None), ("gov.probe", "gov", 0, "node", 1, None), ("gov.probe.rate", "gov.probe", 0, "parameter", None, parameter_id), ): - connection.execute( - text( - "INSERT INTO parameter_tree_children (id, " - "tax_benefit_model_version_id, parent_path, path, position, " - "label, child_type, child_count, parameter_id) VALUES " - "(:id, :version_id, :parent, :path, :position, :path, " - ":child_type, :child_count, :parameter_id)" - ), - { - "id": uuid4(), - "version_id": version_id, - "parent": parent, - "path": path, - "position": position, - "child_type": child_type, - "child_count": child_count, - "parameter_id": reference, - }, + add_row( + session, + ParameterTreeChild, + id=uuid4(), + tax_benefit_model_version_id=version_id, + parent_path=parent, + path=path, + position=position, + label=path, + child_type=child_type, + child_count=child_count, + parameter_id=reference, ) - with pytest.raises(sa.exc.IntegrityError), connection.begin_nested(): - connection.execute( - text( - "INSERT INTO parameter_tree_children (id, " - "tax_benefit_model_version_id, parent_path, path, position, " - "label, child_type) VALUES (:id, :version_id, 'gov', " - "'gov.other', 0, 'Other', 'node')" - ), - {"id": uuid4(), "version_id": version_id}, + with refused(session): + add_row( + session, + ParameterTreeChild, + id=uuid4(), + tax_benefit_model_version_id=version_id, + parent_path="gov", + path="gov.other", + position=0, + label="Other", + child_type="node", ) - connection.execute( - text("DELETE FROM parameters WHERE id = :parameter_id"), - {"parameter_id": parameter_id}, - ) - assert connection.execute( - text("SELECT path FROM parameter_tree_children ORDER BY path") - ).scalars().all() == ["gov", "gov.probe"] + session.execute(delete(Parameter).where(col(Parameter.id) == parameter_id)) + assert session.scalars( + select(col(ParameterTreeChild.path)).order_by( + col(ParameterTreeChild.path) + ) + ).all() == ["gov", "gov.probe"] command.downgrade(config, PARAMETER_TREE_PARENT_REVISION) - assert "parameter_tree_children" not in inspect(engine).get_table_names() - with engine.connect() as connection: + assert ( + "parameter_tree_children" + not in schema_inspector(v2_owner_sessions).get_table_names() + ) + with v2_owner_sessions() as session: assert ( - connection.execute( - text( - "SELECT count(*) FROM variables " - "WHERE tax_benefit_model_version_id = :version_id" - ), - {"version_id": version_id}, - ).scalar_one() + session.scalar( + _version_row_count(VariableBeforeCatalogFormat2, version_id) + ) == 1 ) finally: command.upgrade(config, "head") - with engine.begin() as connection: - connection.execute( - text( - "DELETE FROM tax_benefit_models WHERE name = 'catalog-format-probe'" - ) - ) - engine.dispose() + _delete_probe_catalog(v2_owner_sessions) PARAMETER_SEARCH_FILE_PARENT_REVISION = "3869eb814a90" -def test_parameter_search_file_table_is_created_empty_and_dropped_without_loss() -> ( - None -): +def test_parameter_search_file_table_is_created_empty_and_dropped_without_loss( + v2_owner_sessions: sessionmaker[Session], +) -> None: """The search file revision creates an empty table and downgrades cleanly. The revision writes no rows: catalog publication writes each version's @@ -272,103 +343,91 @@ def test_parameter_search_file_table_is_created_empty_and_dropped_without_loss() version, and downgrading drops the table while every catalog row stays. """ config = alembic_v2_config() - engine = create_engine(disposable_v2_url()) try: command.downgrade(config, PARAMETER_SEARCH_FILE_PARENT_REVISION) - assert "parameter_search_files" not in inspect(engine).get_table_names() - with engine.begin() as connection: - version_id = _catalog_version_published_before_format_2(connection) + assert ( + "parameter_search_files" + not in schema_inspector(v2_owner_sessions).get_table_names() + ) + with v2_owner_sessions.begin() as session: + version_id = _catalog_version_published_before_format_2(session) command.upgrade(config, "head") - insert_file = text( - "INSERT INTO parameter_search_files (id, tax_benefit_model_version_id, " - "file_format, compressed_content, content_sha256, uncompressed_size, " - "compressed_size) VALUES (:id, :version_id, 1, :content, :sha, 2, 22)" - ) file_values = { - "version_id": version_id, - "content": b"\x1f\x8b compressed bytes", - "sha": "0" * 64, + "tax_benefit_model_version_id": version_id, + "file_format": 1, + "compressed_content": b"\x1f\x8b compressed bytes", + "content_sha256": "0" * 64, + "uncompressed_size": 2, + "compressed_size": 22, } - with engine.begin() as connection: + with v2_owner_sessions.begin() as session: assert ( - connection.execute( - text("SELECT count(*) FROM parameter_search_files") - ).scalar_one() + session.scalar(select(func.count()).select_from(ParameterSearchFile)) == 0 ) - connection.execute(insert_file, {"id": uuid4(), **file_values}) - with pytest.raises(sa.exc.IntegrityError), connection.begin_nested(): - connection.execute(insert_file, {"id": uuid4(), **file_values}) + add_row(session, ParameterSearchFile, id=uuid4(), **file_values) + with refused(session): + add_row(session, ParameterSearchFile, id=uuid4(), **file_values) assert ( - connection.execute( - text( - "SELECT compressed_content FROM parameter_search_files " - "WHERE tax_benefit_model_version_id = :version_id" - ), - {"version_id": version_id}, - ).scalar_one() - == file_values["content"] + session.scalars( + select(col(ParameterSearchFile.compressed_content)).where( + col(ParameterSearchFile.tax_benefit_model_version_id) + == version_id + ) + ).one() + == file_values["compressed_content"] ) command.downgrade(config, PARAMETER_SEARCH_FILE_PARENT_REVISION) - assert "parameter_search_files" not in inspect(engine).get_table_names() - with engine.connect() as connection: + assert ( + "parameter_search_files" + not in schema_inspector(v2_owner_sessions).get_table_names() + ) + with v2_owner_sessions() as session: assert ( - connection.execute( - text( - "SELECT count(*) FROM variables " - "WHERE tax_benefit_model_version_id = :version_id" - ), - {"version_id": version_id}, - ).scalar_one() + session.scalar( + _version_row_count(VariableBeforeCatalogFormat2, version_id) + ) == 1 ) command.upgrade(config, "head") - with engine.begin() as connection: - connection.execute(insert_file, {"id": uuid4(), **file_values}) - connection.execute( - text("DELETE FROM tax_benefit_model_versions WHERE id = :version_id"), - {"version_id": version_id}, + with v2_owner_sessions.begin() as session: + add_row(session, ParameterSearchFile, id=uuid4(), **file_values) + session.execute( + delete(TaxBenefitModelVersion).where( + col(TaxBenefitModelVersion.id) == version_id + ) ) assert ( - connection.execute( - text("SELECT count(*) FROM parameter_search_files") - ).scalar_one() + session.scalar(select(func.count()).select_from(ParameterSearchFile)) == 0 ) finally: command.upgrade(config, "head") - with engine.begin() as connection: - connection.execute( - text( - "DELETE FROM tax_benefit_models WHERE name = 'catalog-format-probe'" - ) - ) - engine.dispose() + _delete_probe_catalog(v2_owner_sessions) CATALOG_PRUNING_PARENT_REVISION = "c614b6bcccfc" CATALOG_PRUNING_COLUMNS = ("catalog_last_published_at", "catalog_values_pruned_at") -def _catalog_pruning_columns( - connection: sa.Connection, version_id: UUID -) -> tuple[object, object]: - row = connection.execute( - text( - "SELECT catalog_last_published_at, catalog_values_pruned_at " - "FROM tax_benefit_model_versions WHERE id = :version_id" - ), - {"version_id": version_id}, +def _catalog_pruning_columns(session: Session, version_id: UUID) -> tuple[Any, Any]: + last_published_at, values_pruned_at = session.execute( + select( + col(TaxBenefitModelVersion.catalog_last_published_at), + col(TaxBenefitModelVersion.catalog_values_pruned_at), + ).where(col(TaxBenefitModelVersion.id) == version_id) ).one() - return tuple(row) + return last_published_at, values_pruned_at -def test_catalog_pruning_columns_are_added_null_and_dropped_without_loss() -> None: +def test_catalog_pruning_columns_are_added_null_and_dropped_without_loss( + v2_owner_sessions: sessionmaker[Session], +) -> None: """The revision adds two null columns and downgrades cleanly. A stored version starts with neither a publication time nor a pruning @@ -377,67 +436,54 @@ def test_catalog_pruning_columns_are_added_null_and_dropped_without_loss() -> No version null in both. """ config = alembic_v2_config() - engine = create_engine(disposable_v2_url()) try: command.downgrade(config, CATALOG_PRUNING_PARENT_REVISION) for column_name in CATALOG_PRUNING_COLUMNS: assert column_name not in table_columns( - engine, "tax_benefit_model_versions" + v2_owner_sessions, "tax_benefit_model_versions" ) - with engine.begin() as connection: - version_id = _catalog_version_published_before_format_2(connection) + with v2_owner_sessions.begin() as session: + version_id = _catalog_version_published_before_format_2(session) command.upgrade(config, "head") - with engine.begin() as connection: - assert _catalog_pruning_columns(connection, version_id) == (None, None) - connection.execute( - text( - "UPDATE tax_benefit_model_versions " - "SET catalog_last_published_at = now(), " - "catalog_values_pruned_at = now() WHERE id = :version_id" - ), - {"version_id": version_id}, + with v2_owner_sessions.begin() as session: + assert _catalog_pruning_columns(session, version_id) == (None, None) + session.execute( + update(TaxBenefitModelVersion) + .where(col(TaxBenefitModelVersion.id) == version_id) + .values( + catalog_last_published_at=func.now(), + catalog_values_pruned_at=func.now(), + ) ) - assert None not in _catalog_pruning_columns(connection, version_id) + assert None not in _catalog_pruning_columns(session, version_id) command.downgrade(config, CATALOG_PRUNING_PARENT_REVISION) for column_name in CATALOG_PRUNING_COLUMNS: assert column_name not in table_columns( - engine, "tax_benefit_model_versions" + v2_owner_sessions, "tax_benefit_model_versions" ) - with engine.connect() as connection: + with v2_owner_sessions() as session: assert ( - connection.execute( - text( - "SELECT version FROM tax_benefit_model_versions " - "WHERE id = :version_id" - ), - {"version_id": version_id}, - ).scalar_one() + session.scalars( + select(TaxBenefitModelVersionBeforeCatalogFormat2.version).where( + TaxBenefitModelVersionBeforeCatalogFormat2.id == version_id + ) + ).one() == "0.0.1-probe" ) assert ( - connection.execute( - text( - "SELECT count(*) FROM parameters " - "WHERE tax_benefit_model_version_id = :version_id" - ), - {"version_id": version_id}, - ).scalar_one() + session.scalar( + _version_row_count(ParameterBeforeCatalogFormat2, version_id) + ) == 1 ) command.upgrade(config, "head") - with engine.connect() as connection: - assert _catalog_pruning_columns(connection, version_id) == (None, None) + with v2_owner_sessions() as session: + assert _catalog_pruning_columns(session, version_id) == (None, None) finally: command.upgrade(config, "head") - with engine.begin() as connection: - connection.execute( - text( - "DELETE FROM tax_benefit_models WHERE name = 'catalog-format-probe'" - ) - ) - engine.dispose() + _delete_probe_catalog(v2_owner_sessions) diff --git a/tests/integration/test_alembic_v2_cliff_impacts.py b/tests/integration/test_alembic_v2_cliff_impacts.py index d897d64f6..3eb18f8a4 100644 --- a/tests/integration/test_alembic_v2_cliff_impacts.py +++ b/tests/integration/test_alembic_v2_cliff_impacts.py @@ -8,125 +8,140 @@ ``simulation_runs`` still uses. """ -from collections.abc import Iterator -from typing import Any +from __future__ import annotations + +from typing import TYPE_CHECKING, Any from uuid import UUID, uuid4 import pytest from alembic import command -from sqlalchemy import Connection, Engine, create_engine, inspect, text +from sqlalchemy import delete, func, literal, select, update +from sqlalchemy.dialects import postgresql +from sqlalchemy.dialects.postgresql.base import PGInspector from sqlalchemy.exc import IntegrityError -from sqlalchemy.pool import NullPool +from sqlmodel import col -from tests.fixtures.integration.alembic_v2 import ( - alembic_v2_config, - disposable_v2_url, +from policyengine_api.data.v2.models import ( + CliffImpact, + Simulation, + SimulationRun, + SimulationStatus, ) +from tests.fixtures.database_sessions import schema_inspector +from tests.fixtures.integration.alembic_v2 import alembic_v2_config, table_columns from tests.integration.simulation_rows import ( RUN_VERSIONS, + add_row, insert_public_api_rows, - insert_row, refused, ) +if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + DYNAMICS_REVISION = "9d1d12a7ac58" CLIFF_IMPACTS_REVISION = "bc334f9877b7" -# What a request starting a run's cliff calculation inserts: the conflict -# target names the partial unique index's whole condition. -START_CLIFF_CALCULATION = ( - "INSERT INTO cliff_impacts (id, simulation_run_id, status) " - "VALUES (:id, :simulation_run_id, 'pending') " - "ON CONFLICT (simulation_run_id) WHERE status <> 'failed' DO NOTHING " - "RETURNING id" -) -def _schema_shape(engine: Engine) -> dict[str, dict[str, Any]]: +def _schema_shape(sessions: sessionmaker[Session]) -> dict[str, dict[str, Any]]: """Reflect every table's columns, keys, indexes and checks.""" - inspector = inspect(engine) - return { - table_name: { - "columns": [ - ( - column["name"], - str(column["type"]), - column["nullable"], - column.get("default"), - ) - for column in inspector.get_columns(table_name) - ], - "primary_key": inspector.get_pk_constraint(table_name), - "foreign_keys": sorted( - ( - key["name"], - key["constrained_columns"], - key["referred_table"], - key["options"].get("ondelete"), - ) - for key in inspector.get_foreign_keys(table_name) - ), - "unique_constraints": sorted( - (unique["name"], unique["column_names"]) - for unique in inspector.get_unique_constraints(table_name) - ), - "indexes": sorted( - ( - index["name"], - index["column_names"], - index["unique"], - index.get("dialect_options", {}).get("postgresql_where"), - ) - for index in inspector.get_indexes(table_name) - ), - "checks": { - check["name"]: check["sqltext"] - for check in inspector.get_check_constraints(table_name) - }, + with sessions() as session: + inspector = schema_inspector(session) + return { + table_name: { + "columns": [ + ( + column["name"], + str(column["type"]), + column["nullable"], + column.get("default"), + ) + for column in inspector.get_columns(table_name) + ], + "primary_key": inspector.get_pk_constraint(table_name), + "foreign_keys": sorted( + ( + key["name"], + key["constrained_columns"], + key["referred_table"], + key["options"].get("ondelete"), + ) + for key in inspector.get_foreign_keys(table_name) + ), + "unique_constraints": sorted( + (unique["name"], unique["column_names"]) + for unique in inspector.get_unique_constraints(table_name) + ), + "indexes": sorted( + ( + index["name"], + index["column_names"], + index["unique"], + index.get("dialect_options", {}).get("postgresql_where"), + ) + for index in inspector.get_indexes(table_name) + ), + "checks": { + check["name"]: check["sqltext"] + for check in inspector.get_check_constraints(table_name) + }, + } + for table_name in inspector.get_table_names(schema="public") + if table_name != "alembic_version" } - for table_name in inspector.get_table_names(schema="public") - if table_name != "alembic_version" - } -def _enum_labels(engine: Engine) -> dict[str, list[str]]: +def _enum_labels(sessions: sessionmaker[Session]) -> dict[str, list[str]]: """Return each enum type in the public schema with its labels in order.""" - with engine.connect() as connection: - rows = connection.execute( - text( - "SELECT type.typname, enum.enumlabel FROM pg_type AS type " - "JOIN pg_enum AS enum ON enum.enumtypid = type.oid " - "JOIN pg_namespace AS namespace ON namespace.oid = type.typnamespace " - "WHERE namespace.nspname = 'public' " - "ORDER BY type.typname, enum.enumsortorder" - ) - ).all() - labels: dict[str, list[str]] = {} - for type_name, label in rows: - labels.setdefault(type_name, []).append(label) - return labels + inspector = schema_inspector(sessions) + assert isinstance(inspector, PGInspector) + return { + enum_type["name"]: enum_type["labels"] + for enum_type in inspector.get_enums(schema="public") + } + + +def _table_names(sessions: sessionmaker[Session]) -> list[str]: + return schema_inspector(sessions).get_table_names() @pytest.fixture -def engine() -> Iterator[Engine]: - """Yield an engine on the disposable database, left at the v2 head.""" - database_engine = create_engine(disposable_v2_url(), poolclass=NullPool) +def sessions( + v2_owner_sessions: sessionmaker[Session], +) -> Iterator[sessionmaker[Session]]: + """Yield the disposable database owner's Session factories; leave it at head.""" try: - yield database_engine + yield v2_owner_sessions finally: command.upgrade(alembic_v2_config(), "head") - database_engine.dispose() -def test_cliff_impacts_revision_adds_only_its_table(engine: Engine) -> None: +@pytest.fixture +def session(sessions: sessionmaker[Session]) -> Iterator[Session]: + """Yield a Session at the v2 head whose writes are rolled back after the test.""" + command.upgrade(alembic_v2_config(), "head") + with sessions() as database_session: + try: + yield database_session + finally: + database_session.rollback() + + +def test_cliff_impacts_revision_adds_only_its_table( + sessions: sessionmaker[Session], +) -> None: """The revision adds one table, with no new enum type, and changes nothing else.""" config = alembic_v2_config() command.upgrade(config, "head") command.downgrade(config, DYNAMICS_REVISION) - parent_shape = _schema_shape(engine) - parent_enums = _enum_labels(engine) + parent_shape = _schema_shape(sessions) + parent_enums = _enum_labels(sessions) command.upgrade(config, CLIFF_IMPACTS_REVISION) - revision_shape = _schema_shape(engine) + revision_shape = _schema_shape(sessions) assert set(revision_shape) - set(parent_shape) == {"cliff_impacts"} assert { @@ -134,7 +149,7 @@ def test_cliff_impacts_revision_adds_only_its_table(engine: Engine) -> None: for table_name, shape in revision_shape.items() if table_name != "cliff_impacts" } == parent_shape - assert _enum_labels(engine) == parent_enums + assert _enum_labels(sessions) == parent_enums cliff_impacts = revision_shape["cliff_impacts"] assert cliff_impacts["primary_key"]["constrained_columns"] == ["id"] assert [ @@ -156,33 +171,30 @@ def test_cliff_impacts_revision_adds_only_its_table(engine: Engine) -> None: "ck_cliff_impacts_finished_completion", "ck_cliff_impacts_result_when_succeeded", } - with engine.connect() as connection: - column_types = dict( - connection.execute( - text( - "SELECT column_name, udt_name || ':' || is_nullable " - "FROM information_schema.columns " - "WHERE table_schema = 'public' AND table_name = 'cliff_impacts'" - ) - ).all() + column_types = { + column_name: ( + column["type"].compile(dialect=postgresql.dialect()), + column["nullable"], ) + for column_name, column in table_columns(sessions, "cliff_impacts").items() + } assert column_types == { - "id": "uuid:NO", - "created_at": "timestamptz:NO", - "updated_at": "timestamptz:NO", - "simulation_run_id": "uuid:NO", - "status": "v2_simulation_status:NO", - "modal_call_id": "varchar:YES", - "error_message": "varchar:YES", - "started_at": "timestamptz:YES", - "completed_at": "timestamptz:YES", - "cliff_gap": "float8:YES", - "cliff_share": "float8:YES", + "id": ("UUID", False), + "created_at": ("TIMESTAMP WITH TIME ZONE", False), + "updated_at": ("TIMESTAMP WITH TIME ZONE", False), + "simulation_run_id": ("UUID", False), + "status": ("v2_simulation_status", False), + "modal_call_id": ("VARCHAR(255)", True), + "error_message": ("VARCHAR", True), + "started_at": ("TIMESTAMP WITH TIME ZONE", True), + "completed_at": ("TIMESTAMP WITH TIME ZONE", True), + "cliff_gap": ("DOUBLE PRECISION", True), + "cliff_share": ("DOUBLE PRECISION", True), } def test_cliff_impacts_downgrade_drops_the_table_and_keeps_the_status_type( - engine: Engine, + sessions: sessionmaker[Session], ) -> None: """Downgrading drops only the table, so upgrading again works.""" config = alembic_v2_config() @@ -190,9 +202,9 @@ def test_cliff_impacts_downgrade_drops_the_table_and_keeps_the_status_type( command.upgrade(config, "head") command.downgrade(config, DYNAMICS_REVISION) - assert "cliff_impacts" not in inspect(engine).get_table_names() + assert "cliff_impacts" not in _table_names(sessions) # ``simulation_runs.status`` still uses the type. - assert _enum_labels(engine)["v2_simulation_status"] == [ + assert _enum_labels(sessions)["v2_simulation_status"] == [ "pending", "running", "succeeded", @@ -201,26 +213,26 @@ def test_cliff_impacts_downgrade_drops_the_table_and_keeps_the_status_type( command.upgrade(config, CLIFF_IMPACTS_REVISION) - assert "cliff_impacts" in inspect(engine).get_table_names() + assert "cliff_impacts" in _table_names(sessions) -def _insert_simulation_run(connection: Connection) -> UUID: +def _insert_simulation_run(session: Session) -> UUID: """Store an economy simulation and one pending run of it.""" - public_api_rows = insert_public_api_rows(connection) + public_api_rows = insert_public_api_rows(session) simulation_id = uuid4() run_id = uuid4() - insert_row( - connection, - "simulations", + add_row( + session, + Simulation, id=simulation_id, simulation_type="economy", dataset_id=public_api_rows.dataset_id, tax_benefit_model_version_id=public_api_rows.version_id, year=2026, ) - insert_row( - connection, - "simulation_runs", + add_row( + session, + SimulationRun, id=run_id, simulation_id=simulation_id, tax_benefit_model_version_id=public_api_rows.version_id, @@ -231,139 +243,160 @@ def _insert_simulation_run(connection: Connection) -> UUID: return run_id -def _start_cliff_calculation(connection: Connection, run_id: UUID) -> UUID | None: - """Insert a pending calculation unless one that hasn't failed exists.""" - return connection.execute( - text(START_CLIFF_CALCULATION), {"id": uuid4(), "simulation_run_id": run_id} - ).scalar_one_or_none() +def _start_cliff_calculation(session: Session, run_id: UUID) -> UUID | None: + """Insert a pending calculation unless one that hasn't failed exists. + + This is what a request starting a run's cliff calculation inserts + (INSERT ... ON CONFLICT DO NOTHING RETURNING id): the conflict target + names the partial unique index's whole condition, ``status <> 'failed'``. + The status is written into the statement as a literal: PostgreSQL matches + the condition to the index when it plans the statement, so a parameter + there fails once psycopg prepares the statement, after five runs on one + connection, and PostgreSQL plans it without the parameter's value. + """ + failed_status = literal(SimulationStatus.FAILED, literal_execute=True) + start_calculation = ( + postgresql.insert(CliffImpact) + .values(id=uuid4(), simulation_run_id=run_id, status=SimulationStatus.PENDING) + .on_conflict_do_nothing( + index_elements=["simulation_run_id"], + index_where=col(CliffImpact.status) != failed_status, + ) + .returning(col(CliffImpact.id)) + ) + return session.scalars(start_calculation).one_or_none() -def _fail_cliff_calculation(connection: Connection, calculation_id: UUID) -> None: - connection.execute( - text( - "UPDATE cliff_impacts SET status = 'failed', " - "error_message = 'modal_call_ended: the call ended', " - "completed_at = now() WHERE id = :id" - ), - {"id": calculation_id}, +def _finish_cliff_calculation( + session: Session, calculation_id: UUID | None, **assignments: object +) -> None: + """Update the calculation's columns (UPDATE cliff_impacts SET ...).""" + session.execute( + update(CliffImpact) + .where(col(CliffImpact.id) == calculation_id) + .values(**assignments) ) -def _cliff_statuses(connection: Connection, run_id: UUID) -> list[str]: +def _fail_cliff_calculation(session: Session, calculation_id: UUID) -> None: + _finish_cliff_calculation( + session, + calculation_id, + status=SimulationStatus.FAILED, + error_message="modal_call_ended: the call ended", + completed_at=func.now(), + ) + + +def _cliff_statuses(session: Session, run_id: UUID) -> list[str]: return list( - connection.execute( - text( - "SELECT status::text FROM cliff_impacts " - "WHERE simulation_run_id = :run_id ORDER BY created_at, status" - ), - {"run_id": run_id}, - ).scalars() + session.scalars( + select(col(CliffImpact.status)) + .where(col(CliffImpact.simulation_run_id) == run_id) + .order_by(col(CliffImpact.created_at), col(CliffImpact.status)) + ) ) -def test_a_run_starts_one_cliff_calculation_until_it_fails(engine: Engine) -> None: +def test_a_run_starts_one_cliff_calculation_until_it_fails(session: Session) -> None: """Two requests at once start one calculation; a failed one never counts.""" - command.upgrade(alembic_v2_config(), "head") + run_id = _insert_simulation_run(session) + first_calculation = _start_cliff_calculation(session, run_id) + joined_calculation = _start_cliff_calculation(session, run_id) + + assert first_calculation is not None + # The second request joins the pending calculation. + assert joined_calculation is None + with refused(session, IntegrityError, match="uq_cliff_impacts_unfailed"): + add_row( + session, + CliffImpact, + id=uuid4(), + simulation_run_id=run_id, + status="running", + ) - with engine.connect() as connection: - transaction = connection.begin() - try: - run_id = _insert_simulation_run(connection) - first_calculation = _start_cliff_calculation(connection, run_id) - joined_calculation = _start_cliff_calculation(connection, run_id) - - assert first_calculation is not None - # The second request joins the pending calculation. - assert joined_calculation is None - with refused(connection, IntegrityError, match="uq_cliff_impacts_unfailed"): - insert_row( - connection, - "cliff_impacts", - id=uuid4(), - simulation_run_id=run_id, - status="running", - ) - - _fail_cliff_calculation(connection, first_calculation) - retried_calculation = _start_cliff_calculation(connection, run_id) - - assert retried_calculation is not None - connection.execute( - text( - "UPDATE cliff_impacts SET status = 'succeeded', " - "cliff_gap = 1.5e9, cliff_share = 0.04, completed_at = now() " - "WHERE id = :id" - ), - {"id": retried_calculation}, - ) - assert _start_cliff_calculation(connection, run_id) is None - assert sorted(_cliff_statuses(connection, run_id)) == [ - "failed", - "succeeded", - ] - finally: - transaction.rollback() + _fail_cliff_calculation(session, first_calculation) + retried_calculation = _start_cliff_calculation(session, run_id) + + assert retried_calculation is not None + _finish_cliff_calculation( + session, + retried_calculation, + status=SimulationStatus.SUCCEEDED, + cliff_gap=1.5e9, + cliff_share=0.04, + completed_at=func.now(), + ) + assert _start_cliff_calculation(session, run_id) is None + assert sorted(_cliff_statuses(session, run_id)) == ["failed", "succeeded"] @pytest.mark.parametrize( ("assignments", "check_name"), [ - ("status = 'succeeded', completed_at = now()", "result_when_succeeded"), - ( - "status = 'succeeded', cliff_gap = 1.0, completed_at = now()", + pytest.param( + {"status": SimulationStatus.SUCCEEDED, "completed_at": func.now()}, "result_when_succeeded", + id="succeeded-with-no-numbers", ), - ("cliff_gap = 1.0, cliff_share = 0.1", "result_when_succeeded"), - ( - "status = 'failed', cliff_gap = 1.0, cliff_share = 0.1, " - "completed_at = now()", + pytest.param( + { + "status": SimulationStatus.SUCCEEDED, + "cliff_gap": 1.0, + "completed_at": func.now(), + }, "result_when_succeeded", + id="succeeded-with-a-gap-alone", ), - ("status = 'failed'", "finished_completion"), - ( - "status = 'succeeded', cliff_gap = 1.0, cliff_share = 0.1", + pytest.param( + {"cliff_gap": 1.0, "cliff_share": 0.1}, + "result_when_succeeded", + id="pending-with-numbers", + ), + pytest.param( + { + "status": SimulationStatus.FAILED, + "cliff_gap": 1.0, + "cliff_share": 0.1, + "completed_at": func.now(), + }, + "result_when_succeeded", + id="failed-with-numbers", + ), + pytest.param( + {"status": SimulationStatus.FAILED}, "finished_completion", + id="failed-with-no-completion-time", + ), + pytest.param( + { + "status": SimulationStatus.SUCCEEDED, + "cliff_gap": 1.0, + "cliff_share": 0.1, + }, + "finished_completion", + id="succeeded-with-no-completion-time", ), ], ) def test_only_a_finished_calculation_ends_and_only_a_succeeded_one_has_numbers( - engine: Engine, assignments: str, check_name: str + session: Session, assignments: dict[str, object], check_name: str ) -> None: - command.upgrade(alembic_v2_config(), "head") - - with engine.connect() as connection: - transaction = connection.begin() - try: - run_id = _insert_simulation_run(connection) - calculation_id = _start_cliff_calculation(connection, run_id) - - with refused( - connection, IntegrityError, match=f"ck_cliff_impacts_{check_name}" - ): - connection.execute( - text(f"UPDATE cliff_impacts SET {assignments} WHERE id = :id"), - {"id": calculation_id}, - ) - finally: - transaction.rollback() + run_id = _insert_simulation_run(session) + calculation_id = _start_cliff_calculation(session, run_id) + with refused(session, IntegrityError, match=f"ck_cliff_impacts_{check_name}"): + _finish_cliff_calculation(session, calculation_id, **assignments) -def test_a_runs_cliff_calculations_are_deleted_with_it(engine: Engine) -> None: - command.upgrade(alembic_v2_config(), "head") - with engine.connect() as connection: - transaction = connection.begin() - try: - run_id = _insert_simulation_run(connection) - failed_calculation = _start_cliff_calculation(connection, run_id) - assert failed_calculation is not None - _fail_cliff_calculation(connection, failed_calculation) - _start_cliff_calculation(connection, run_id) +def test_a_runs_cliff_calculations_are_deleted_with_it(session: Session) -> None: + run_id = _insert_simulation_run(session) + failed_calculation = _start_cliff_calculation(session, run_id) + assert failed_calculation is not None + _fail_cliff_calculation(session, failed_calculation) + _start_cliff_calculation(session, run_id) - connection.execute( - text("DELETE FROM simulation_runs WHERE id = :id"), {"id": run_id} - ) + session.execute(delete(SimulationRun).where(col(SimulationRun.id) == run_id)) - assert _cliff_statuses(connection, run_id) == [] - finally: - transaction.rollback() + assert _cliff_statuses(session, run_id) == [] diff --git a/tests/integration/test_alembic_v2_dynamics.py b/tests/integration/test_alembic_v2_dynamics.py index 819344839..4fab71132 100644 --- a/tests/integration/test_alembic_v2_dynamics.py +++ b/tests/integration/test_alembic_v2_dynamics.py @@ -10,119 +10,142 @@ from __future__ import annotations +from datetime import UTC, datetime from typing import TYPE_CHECKING, Any -from uuid import uuid4 +from uuid import UUID, uuid4 import pytest from alembic import command -from sqlalchemy import create_engine, inspect, text +from sqlalchemy import String, delete from sqlalchemy.exc import IntegrityError - -from tests.fixtures.integration.alembic_v2 import alembic_v2_config, disposable_v2_url +from sqlalchemy.orm import Mapped, mapped_column, registry +from sqlmodel import col + +from policyengine_api.data.v2.models import ( + Dynamic, + LegacyPolicyMapping, + Parameter, + ParameterValue, + Policy, +) +from tests.fixtures.database_sessions import schema_inspector +from tests.fixtures.integration.alembic_v2 import alembic_v2_config, table_columns +from tests.integration.alembic_version_rows import current_revision from tests.integration.simulation_rows import ( PublicApiRows, + add_row, delete_public_api_rows, insert_public_api_rows, - insert_row, refused, ) if TYPE_CHECKING: from collections.abc import Iterator - from sqlalchemy import Connection, Engine + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session PREVIOUS_REVISION = "f519a77ba122" DYNAMICS_REVISION = "9d1d12a7ac58" CHANGED_TABLES = frozenset({"dynamics", "legacy_policy_mappings", "parameter_values"}) +previous_revision_tables = registry() + + +@previous_revision_tables.mapped +class DynamicAtF519a77ba122: + """The ``dynamics`` table at revision f519a77ba122, before this revision. + + A dynamic then had a required name and a description. ``created_at`` and + ``updated_at``, which the database fills in, aren't mapped. + """ + + __tablename__ = "dynamics" + + id: Mapped[UUID] = mapped_column(primary_key=True) + name: Mapped[str] = mapped_column(String(255)) + description: Mapped[str | None] + @pytest.fixture -def engine() -> Iterator[Engine]: - """Yield an engine on a database at head, and leave it at head.""" - # Check that the target is the disposable database before migrating it. - database_url = disposable_v2_url() +def sessions( + v2_owner_sessions: sessionmaker[Session], +) -> Iterator[sessionmaker[Session]]: + """Yield the owner's Session factories on a database at head; leave it at head. + + ``v2_owner_sessions`` checks that the target is the disposable database + before this migrates it. + """ command.upgrade(alembic_v2_config(), "head") - database_engine = create_engine(database_url) try: - yield database_engine + yield v2_owner_sessions finally: command.upgrade(alembic_v2_config(), "head") - database_engine.dispose() @pytest.fixture -def connection(engine: Engine) -> Iterator[Connection]: - """Yield a connection at head whose writes are rolled back after the test.""" - with engine.connect() as database_connection: - transaction = database_connection.begin() +def session(sessions: sessionmaker[Session]) -> Iterator[Session]: + """Yield a Session at head whose writes are rolled back after the test.""" + with sessions() as database_session: try: - yield database_connection + yield database_session finally: - transaction.rollback() + database_session.rollback() -def _schema(engine: Engine) -> dict[str, dict[str, Any]]: +def _schema(sessions: sessionmaker[Session]) -> dict[str, dict[str, Any]]: """Return each table's columns, keys, checks and indexes, comparably.""" - inspector = inspect(engine) - return { - table_name: { - "columns": sorted( - (column["name"], str(column["type"]), column["nullable"]) - for column in inspector.get_columns(table_name) - ), - "foreign_keys": sorted( - ( - str(key["name"]), - tuple(key["constrained_columns"]), - key["referred_table"], - tuple(key["referred_columns"]), - key["options"].get("ondelete"), - ) - for key in inspector.get_foreign_keys(table_name) - ), - "unique": sorted( - (str(constraint["name"]), tuple(constraint["column_names"])) - for constraint in inspector.get_unique_constraints(table_name) - ), - "checks": sorted( - (str(check["name"]), check["sqltext"]) - for check in inspector.get_check_constraints(table_name) - ), - "indexes": sorted( - ( - str(index["name"]), - tuple(str(column) for column in index["column_names"]), - bool(index["unique"]), - str(index.get("dialect_options", {}).get("postgresql_where")), - ) - for index in inspector.get_indexes(table_name) - ), + with sessions() as session: + inspector = schema_inspector(session) + return { + table_name: { + "columns": sorted( + (column["name"], str(column["type"]), column["nullable"]) + for column in inspector.get_columns(table_name) + ), + "foreign_keys": sorted( + ( + str(key["name"]), + tuple(key["constrained_columns"]), + key["referred_table"], + tuple(key["referred_columns"]), + key["options"].get("ondelete"), + ) + for key in inspector.get_foreign_keys(table_name) + ), + "unique": sorted( + (str(constraint["name"]), tuple(constraint["column_names"])) + for constraint in inspector.get_unique_constraints(table_name) + ), + "checks": sorted( + (str(check["name"]), check["sqltext"]) + for check in inspector.get_check_constraints(table_name) + ), + "indexes": sorted( + ( + str(index["name"]), + tuple(str(column) for column in index["column_names"]), + bool(index["unique"]), + str(index.get("dialect_options", {}).get("postgresql_where")), + ) + for index in inspector.get_indexes(table_name) + ), + } + for table_name in inspector.get_table_names() } - for table_name in inspector.get_table_names() - } - - -def _current_revision(engine: Engine) -> str: - with engine.connect() as connection: - return str( - connection.execute( - text("SELECT version_num FROM alembic_version") - ).scalar_one() - ) def _insert_dynamic( - connection: Connection, + session: Session, rows: PublicApiRows, *, content_hash: str = "d" * 64, country_id: str = "us", -) -> object: +) -> UUID: dynamic_id = uuid4() - insert_row( - connection, - "dynamics", + add_row( + session, + Dynamic, id=dynamic_id, country_id=country_id, tax_benefit_model_id=rows.model_id, @@ -133,11 +156,11 @@ def _insert_dynamic( return dynamic_id -def _insert_parameter(connection: Connection, rows: PublicApiRows) -> object: +def _insert_parameter(session: Session, rows: PublicApiRows) -> UUID: parameter_id = uuid4() - insert_row( - connection, - "parameters", + add_row( + session, + Parameter, id=parameter_id, name="gov.simulation.labor_supply_responses.elasticities.income", tax_benefit_model_version_id=rows.version_id, @@ -145,13 +168,11 @@ def _insert_parameter(connection: Connection, rows: PublicApiRows) -> object: return parameter_id -def _insert_policy( - connection: Connection, rows: PublicApiRows, *, country_id: str -) -> object: +def _insert_policy(session: Session, rows: PublicApiRows, *, country_id: str) -> UUID: policy_id = uuid4() - insert_row( - connection, - "policies", + add_row( + session, + Policy, id=policy_id, country_id=country_id, tax_benefit_model_id=rows.model_id, @@ -162,14 +183,18 @@ def _insert_policy( return policy_id +def _delete_dynamic(session: Session, dynamic_id: UUID) -> None: + session.execute(delete(Dynamic).where(col(Dynamic.id) == dynamic_id)) + + def test_the_revision_changes_only_dynamics_their_values_and_mappings( - engine: Engine, + sessions: sessionmaker[Session], ) -> None: config = alembic_v2_config() command.downgrade(config, PREVIOUS_REVISION) - before = _schema(engine) + before = _schema(sessions) command.upgrade(config, DYNAMICS_REVISION) - after = _schema(engine) + after = _schema(sessions) assert {name: before[name] for name in before if name not in CHANGED_TABLES} == { name: after[name] for name in after if name not in CHANGED_TABLES @@ -219,54 +244,54 @@ def test_the_revision_changes_only_dynamics_their_values_and_mappings( } command.downgrade(config, PREVIOUS_REVISION) - assert _schema(engine) == before + assert _schema(sessions) == before command.upgrade(config, "head") command.check(config) def test_a_dynamic_is_stored_once_and_sets_one_value_per_parameter_and_date( - connection: Connection, + session: Session, ) -> None: - rows = insert_public_api_rows(connection) - parameter_id = _insert_parameter(connection, rows) - dynamic_id = _insert_dynamic(connection, rows) + rows = insert_public_api_rows(session) + parameter_id = _insert_parameter(session, rows) + dynamic_id = _insert_dynamic(session, rows) - with refused(connection, match="uq_dynamics_canonicalization_content_hash"): - _insert_dynamic(connection, rows) - with refused(connection, match="ck_dynamics_content_hash_length"): - _insert_dynamic(connection, rows, content_hash="short") + with refused(session, match="uq_dynamics_canonicalization_content_hash"): + _insert_dynamic(session, rows) + with refused(session, match="ck_dynamics_content_hash_length"): + _insert_dynamic(session, rows, content_hash="short") value = { "parameter_id": parameter_id, "dynamic_id": dynamic_id, - "value_json": "0.1", - "start_date": "2026-01-01T00:00:00Z", + "value_json": 0.1, + "start_date": datetime(2026, 1, 1, tzinfo=UTC), } - insert_row(connection, "parameter_values", id=uuid4(), **value) - with refused(connection, match="uq_parameter_values_dynamic_parameter_start_date"): - insert_row(connection, "parameter_values", id=uuid4(), **value) + add_row(session, ParameterValue, id=uuid4(), **value) + with refused(session, match="uq_parameter_values_dynamic_parameter_start_date"): + add_row(session, ParameterValue, id=uuid4(), **value) # Another dynamic may set the same parameter from the same date. - other_dynamic_id = _insert_dynamic(connection, rows, content_hash="e" * 64) - insert_row( - connection, - "parameter_values", + other_dynamic_id = _insert_dynamic(session, rows, content_hash="e" * 64) + add_row( + session, + ParameterValue, id=uuid4(), **{**value, "dynamic_id": other_dynamic_id}, ) def test_a_mapping_names_a_dynamic_of_its_country_which_stays_while_named( - connection: Connection, + session: Session, ) -> None: - rows = insert_public_api_rows(connection) - us_dynamic_id = _insert_dynamic(connection, rows) - us_policy_id = _insert_policy(connection, rows, country_id="us") - uk_policy_id = _insert_policy(connection, rows, country_id="uk") - - with refused(connection, match="fk_legacy_policy_mappings_dynamic_country"): - insert_row( - connection, - "legacy_policy_mappings", + rows = insert_public_api_rows(session) + us_dynamic_id = _insert_dynamic(session, rows) + us_policy_id = _insert_policy(session, rows, country_id="us") + uk_policy_id = _insert_policy(session, rows, country_id="uk") + + with refused(session, match="fk_legacy_policy_mappings_dynamic_country"): + add_row( + session, + LegacyPolicyMapping, id=uuid4(), country_id="uk", legacy_policy_id=1, @@ -274,9 +299,9 @@ def test_a_mapping_names_a_dynamic_of_its_country_which_stays_while_named( dynamic_id=us_dynamic_id, source_policy_hash="v1-hash", ) - insert_row( - connection, - "legacy_policy_mappings", + add_row( + session, + LegacyPolicyMapping, id=uuid4(), country_id="us", legacy_policy_id=1, @@ -285,62 +310,58 @@ def test_a_mapping_names_a_dynamic_of_its_country_which_stays_while_named( source_policy_hash="v1-hash", ) # A mapping without a dynamic is unaffected. - insert_row( - connection, - "legacy_policy_mappings", + add_row( + session, + LegacyPolicyMapping, id=uuid4(), country_id="us", legacy_policy_id=2, policy_id=us_policy_id, source_policy_hash="v1-hash-2", ) - with refused(connection, match="fk_legacy_policy_mappings_dynamic_country"): - connection.execute( - text("DELETE FROM dynamics WHERE id = :id"), {"id": us_dynamic_id} - ) + with refused(session, match="fk_legacy_policy_mappings_dynamic_country"): + _delete_dynamic(session, us_dynamic_id) def test_the_upgrade_fails_changing_nothing_while_a_dynamic_is_stored( - engine: Engine, + sessions: sessionmaker[Session], ) -> None: config = alembic_v2_config() command.downgrade(config, PREVIOUS_REVISION) dynamic_id = uuid4() - with engine.begin() as connection: - insert_row(connection, "dynamics", id=dynamic_id, name="stored before") + with sessions.begin() as session: + add_row(session, DynamicAtF519a77ba122, id=dynamic_id, name="stored before") try: with pytest.raises(IntegrityError, match="country_id"): command.upgrade(config, DYNAMICS_REVISION) - assert _current_revision(engine) == PREVIOUS_REVISION - dynamics_columns = inspect(engine).get_columns("dynamics") - assert "name" in {column["name"] for column in dynamics_columns} + assert current_revision(sessions) == PREVIOUS_REVISION + assert "name" in table_columns(sessions, "dynamics") finally: - with engine.begin() as connection: - connection.execute( - text("DELETE FROM dynamics WHERE id = :id"), {"id": dynamic_id} + with sessions.begin() as session: + session.execute( + delete(DynamicAtF519a77ba122).where( + DynamicAtF519a77ba122.id == dynamic_id + ) ) def test_the_downgrade_fails_changing_nothing_while_a_dynamic_is_stored( - engine: Engine, + sessions: sessionmaker[Session], ) -> None: config = alembic_v2_config() # The fixture upgrades to the head before the test, and the head can be # later than the dynamics revision, so a downgrade reaches it; an upgrade # to an older revision does nothing. command.downgrade(config, DYNAMICS_REVISION) - with engine.begin() as connection: - rows = insert_public_api_rows(connection) - dynamic_id = _insert_dynamic(connection, rows) + with sessions.begin() as session: + rows = insert_public_api_rows(session) + dynamic_id = _insert_dynamic(session, rows) try: with pytest.raises(IntegrityError, match="name"): command.downgrade(config, PREVIOUS_REVISION) - assert _current_revision(engine) == DYNAMICS_REVISION - mapping_columns = inspect(engine).get_columns("legacy_policy_mappings") - assert "dynamic_id" in {column["name"] for column in mapping_columns} + assert current_revision(sessions) == DYNAMICS_REVISION + assert "dynamic_id" in table_columns(sessions, "legacy_policy_mappings") finally: - with engine.begin() as connection: - connection.execute( - text("DELETE FROM dynamics WHERE id = :id"), {"id": dynamic_id} - ) - delete_public_api_rows(connection, rows) + with sessions.begin() as session: + _delete_dynamic(session, dynamic_id) + delete_public_api_rows(session, rows) diff --git a/tests/integration/test_alembic_v2_lifecycle.py b/tests/integration/test_alembic_v2_lifecycle.py index cc4459796..beacbbab5 100644 --- a/tests/integration/test_alembic_v2_lifecycle.py +++ b/tests/integration/test_alembic_v2_lifecycle.py @@ -1,38 +1,73 @@ -"""Exercise the isolated v2 Alembic lifecycle against disposable Postgres.""" +"""Exercise the isolated v2 Alembic lifecycle against disposable Postgres. -import itertools -from collections.abc import Iterator -from dataclasses import dataclass -from datetime import UTC, datetime, timedelta +Every statement runs through a Session (rule api.data.orm-only). Rows written +at head use the v2 models. Rows written at an older revision use the small +mapped classes below, each on a declarative base of its own named after the +revision whose tables it maps, because the v2 models map head's columns. The +checks that a revision serves the release before it map that release's whole +schema with automap (``tests/integration/alembic_v2_previous_revision.py``). +""" + +from __future__ import annotations + +import re +from datetime import datetime, timedelta +from typing import TYPE_CHECKING, Any from uuid import UUID, uuid4 import pytest import sqlalchemy as sa from alembic import command -from alembic.autogenerate import compare_metadata -from alembic.config import Config -from alembic.migration import MigrationContext -from sqlalchemy import Engine, create_engine, inspect, text +from sqlalchemy import delete, func, select from sqlalchemy.dialects import postgresql +from sqlalchemy.dialects.postgresql.base import PGInspector +from sqlalchemy.exc import IntegrityError +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column +from sqlmodel import col +from sqlmodel.main import default_registry from policyengine_api.data.v2.migration_target import ( V2_ALEMBIC_HEAD_REVISION, V2MigrationTargetError, ) -from policyengine_api.data.v2.models import V2_METADATA -from tests.fixtures.integration.alembic_v2 import ( - alembic_v2_config, - disposable_v2_url, - table_columns, +from policyengine_api.data.v2.models import ( + Country, + Household, + Report, + ReportRun, + Simulation, + SimulationRun, + Stage12ComparisonReport, + TaxBenefitModel, + TaxBenefitModelVersion, + User, + UserHouseholdAssociation, + UserReportAssociation, +) +from tests.fixtures.database_sessions import ( + create_registry_tables, + drop_registry_tables, + schema_inspector, +) +from tests.fixtures.integration.alembic_v2 import alembic_v2_config, table_columns +from tests.integration.alembic_v2_previous_revision import ( + ALEMBIC_VERSION_TABLE, + assert_revision_serves_previous_revision, ) from tests.integration.simulation_rows import ( RUN_VERSIONS, PublicApiRows, + add_row, delete_public_api_rows, insert_public_api_rows, - insert_row, + refused, ) +if TYPE_CHECKING: + from alembic.config import Config + from sqlalchemy.engine.interfaces import ReflectedForeignKeyConstraint + from sqlalchemy.orm import Session, sessionmaker + BASELINE_REVISION = "f5ef4347cb2a" STAGE_11_PREVIOUS_REVISION = "af34023a728f" STAGE_12_PREVIOUS_REVISION = "724b1b11a33e" @@ -44,35 +79,230 @@ # The catalog format 2 revision, the parent of the area impact coordinate removal. CATALOG_FORMAT_2_REVISION = "f5c1d9b4685b" AREA_IMPACT_COORDINATE_REVISION = "e86f19a6c4da" -V2_TABLE_NAMES = frozenset(table.name for table in V2_METADATA.tables.values()) +# Every table the v2 models map, which are the tables of V2_METADATA. +V2_TABLE_NAMES = frozenset( + mapper.class_.__tablename__ for mapper in default_registry.mappers +) AREA_IMPACT_TABLES = ("constituency_impacts", "local_authority_impacts") MAP_COORDINATE_COLUMNS = ("x", "y") -def _assert_head(engine) -> None: - assert set(inspect(engine).get_table_names(schema="public")) == ( - V2_TABLE_NAMES | {"alembic_version"} +def _existing_enum(type_name: str) -> postgresql.ENUM: + """Return the database's enum type ``type_name``, which these classes don't create. + + Rows name its values as text, which PostgreSQL checks against the type. + """ + return postgresql.ENUM(name=type_name, create_type=False) + + +class AlembicVersionBase(DeclarativeBase): + """The declarative base of Alembic's version table.""" + + +class AlembicVersion(AlembicVersionBase): + """The row in which Alembic records the database's revision.""" + + __tablename__ = ALEMBIC_VERSION_TABLE + + version_num: Mapped[str] = mapped_column(sa.String(32), primary_key=True) + + +class BaselineBase(DeclarativeBase): + """The declarative base of tables as the baseline revision created them.""" + + +class TaxBenefitModelAtBaseline(BaselineBase): + """A tax-benefit model's name at the baseline revision.""" + + __tablename__ = "tax_benefit_models" + + id: Mapped[UUID] = mapped_column(primary_key=True) + name: Mapped[str] + + +class DatasetAtBaseline(BaselineBase): + """A dataset at the baseline revision, which named its model directly.""" + + __tablename__ = "datasets" + + id: Mapped[UUID] = mapped_column(primary_key=True) + name: Mapped[str] + year: Mapped[int] + is_output_dataset: Mapped[bool] + tax_benefit_model_id: Mapped[UUID] + + +class RegionAtBaseline(BaselineBase): + """A region at the baseline revision, with its required default dataset.""" + + __tablename__ = "regions" + + id: Mapped[UUID] = mapped_column(primary_key=True) + code: Mapped[str] + label: Mapped[str] + region_type: Mapped[str] = mapped_column(_existing_enum("v2_region_type")) + requires_filter: Mapped[bool] + tax_benefit_model_id: Mapped[UUID] + default_dataset_id: Mapped[UUID] + + +class Stage12ComparisonParentBase(DeclarativeBase): + """The declarative base of tables as the Stage 12 comparison's parent left them.""" + + +class Stage12ReportBeforeComparison(Stage12ComparisonParentBase): + """A Stage 12 evaluation report's required columns, before comparison columns.""" + + __tablename__ = "stage12_evaluation_reports" + + evaluation_id: Mapped[UUID] = mapped_column(primary_key=True) + contract_version: Mapped[int] + status: Mapped[str] = mapped_column(_existing_enum("v2_stage12_evaluation_status")) + aggregation_status: Mapped[str] = mapped_column( + _existing_enum("v2_stage12_aggregation_status") ) - with engine.connect() as connection: - context = MigrationContext.configure(connection) - assert context.get_current_revision() == V2_ALEMBIC_HEAD_REVISION - assert compare_metadata(context, V2_METADATA) == [] - model_count = connection.execute( - text( - "SELECT count(*) FROM public.tax_benefit_models " - "WHERE name = 'stage8-platform-validation'" - ) - ).scalar_one() - version_count = connection.execute( - text( - "SELECT count(*) FROM public.tax_benefit_model_versions " - "WHERE version = 'stage8-platform-validation'" - ) - ).scalar_one() + environment: Mapped[str] + calculation_flow: Mapped[str] + originating_request_id: Mapped[str] + production_identity: Mapped[str] + worker_version: Mapped[str] + modal_application: Mapped[str] + report_coordinator_callable: Mapped[str] + version_manifest_sha256: Mapped[str] + policyengine_version: Mapped[str] + country_package_name: Mapped[str] + country_package_version: Mapped[str] + country: Mapped[str] + dataset_identity: Mapped[str] + dataset_uri: Mapped[str] + data_package_name: Mapped[str] + data_package_version: Mapped[str] + data_artifact_revision: Mapped[str] + retention_expires_at: Mapped[datetime] = mapped_column(sa.DateTime(timezone=True)) + + +class Stage12AParentBase(DeclarativeBase): + """The declarative base of tables as the Stage 12A revision's parent left them.""" + + +class UserBeforeStage12A(Stage12AParentBase): + """A user before Stage 12A, when every user had a country.""" + + __tablename__ = "users" + + id: Mapped[UUID] = mapped_column(primary_key=True) + primary_country: Mapped[str] + + +class TaxBenefitModelBeforeStage12A(Stage12AParentBase): + """A tax-benefit model's name before Stage 12A.""" + + __tablename__ = "tax_benefit_models" + + id: Mapped[UUID] = mapped_column(primary_key=True) + name: Mapped[str] + + +class ReportBeforeStage12A(Stage12AParentBase): + """A report's required columns before Stage 12A.""" + + __tablename__ = "reports" + + id: Mapped[UUID] = mapped_column(primary_key=True) + label: Mapped[str] + country: Mapped[str] + tax_benefit_model_id: Mapped[UUID] + inputs: Mapped[dict[str, Any]] = mapped_column(sa.JSON) + + +class UserReportAssociationBeforeStage12A(Stage12AParentBase): + """A saved report before Stage 12A, which named a stored v2 report.""" + + __tablename__ = "user_report_associations" + + id: Mapped[UUID] = mapped_column(primary_key=True) + user_id: Mapped[UUID] + report_id: Mapped[UUID] + country: Mapped[str] + + +class Stage12ABase(DeclarativeBase): + """The declarative base of tables as the Stage 12A revision left them.""" + + +class UserAtStage12A(Stage12ABase): + """A user at Stage 12A, before the countries table.""" + + __tablename__ = "users" + + id: Mapped[UUID] = mapped_column(primary_key=True) + primary_country: Mapped[str | None] + + +class UserReportAssociationAtStage12A(Stage12ABase): + """A saved report at Stage 12A, which may name an API v1 report instead.""" + + __tablename__ = "user_report_associations" + + id: Mapped[UUID] = mapped_column(primary_key=True) + user_id: Mapped[UUID] + country_id: Mapped[str] + legacy_report_id: Mapped[int | None] = mapped_column(sa.BigInteger) + + +class UnreviewedTableBase(DeclarativeBase): + """The declarative base of a table that no revision or v2 model declares.""" + + +class UnreviewedRuntimeTable(UnreviewedTableBase): + """A table created outside Alembic, which the upgrade to head must refuse.""" + + __tablename__ = "unreviewed_runtime_table" + + id: Mapped[int] = mapped_column(primary_key=True, autoincrement=False) + + +def _current_revision(sessions: sessionmaker[Session]) -> str | None: + """Return the revision Alembic records, or ``None`` when it records none. + + As Alembic's ``MigrationContext.get_current_revision`` does, a database + with no version table, or an empty one, is at no revision. + """ + if ALEMBIC_VERSION_TABLE not in schema_inspector(sessions).get_table_names( + schema="public" + ): + return None + with sessions() as session: + revisions = session.scalars(select(AlembicVersion.version_num)).all() + assert len(revisions) <= 1, revisions + return revisions[0] if revisions else None + + +def _assert_head(sessions: sessionmaker[Session]) -> None: + """Check the database is at head with exactly the v2 tables and its indexes. + + ``command.check``, which runs just before, compares the schema with the + v2 models. + """ + assert set(schema_inspector(sessions).get_table_names(schema="public")) == ( + V2_TABLE_NAMES | {ALEMBIC_VERSION_TABLE} + ) + assert _current_revision(sessions) == V2_ALEMBIC_HEAD_REVISION + with sessions() as session: + model_count = session.scalar( + select(func.count()) + .select_from(TaxBenefitModel) + .where(col(TaxBenefitModel.name) == "stage8-platform-validation") + ) + version_count = session.scalar( + select(func.count()) + .select_from(TaxBenefitModelVersion) + .where(col(TaxBenefitModelVersion.version) == "stage8-platform-validation") + ) assert (model_count, version_count) == (0, 0) parameter_value_indexes = { index["name"]: index - for index in inspect(engine).get_indexes("parameter_values") + for index in schema_inspector(sessions).get_indexes("parameter_values") } canonical_index = parameter_value_indexes[ "uq_parameter_values_canonical_parameter_start_date" @@ -81,7 +311,9 @@ def _assert_head(engine) -> None: assert canonical_index["column_names"] == ["parameter_id", "start_date"] policy_value_constraint = next( constraint - for constraint in inspect(engine).get_unique_constraints("parameter_values") + for constraint in schema_inspector(sessions).get_unique_constraints( + "parameter_values" + ) if constraint["name"] == "uq_parameter_values_policy_parameter_start_date" ) assert policy_value_constraint["column_names"] == [ @@ -94,29 +326,33 @@ def _assert_head(engine) -> None: "legacy_policy_mappings", "legacy_user_mappings", "legacy_user_policy_mappings", - } <= set(inspect(engine).get_table_names(schema="public")) + } <= set(schema_inspector(sessions).get_table_names(schema="public")) for table_name in AREA_IMPACT_TABLES: - assert set(MAP_COORDINATE_COLUMNS).isdisjoint(table_columns(engine, table_name)) + assert set(MAP_COORDINATE_COLUMNS).isdisjoint( + table_columns(sessions, table_name) + ) -def _assert_area_impact_coordinates_restored(engine: Engine) -> None: +def _assert_area_impact_coordinates_restored(sessions: sessionmaker[Session]) -> None: """Check the catalog format 2 revision's map coordinates are required integers.""" - _assert_revision(engine, CATALOG_FORMAT_2_REVISION) + _assert_revision(sessions, CATALOG_FORMAT_2_REVISION) for table_name in AREA_IMPACT_TABLES: - columns = table_columns(engine, table_name) + columns = table_columns(sessions, table_name) for column_name in MAP_COORDINATE_COLUMNS: assert isinstance(columns[column_name]["type"], sa.Integer) assert not columns[column_name]["nullable"] assert columns[column_name]["default"] is None -def _assert_pre_stage_12a_association_shape(engine) -> None: - assert "user_identities" not in inspect(engine).get_table_names(schema="public") +def _assert_pre_stage_12a_association_shape(sessions: sessionmaker[Session]) -> None: + assert "user_identities" not in schema_inspector(sessions).get_table_names( + schema="public" + ) for table_name, reference in ( ("user_simulation_associations", "simulation"), ("user_report_associations", "report"), ): - columns = table_columns(engine, table_name) + columns = table_columns(sessions, table_name) assert {"country", "label"} <= columns.keys() assert { "country_id", @@ -126,24 +362,26 @@ def _assert_pre_stage_12a_association_shape(engine) -> None: assert not columns[f"{reference}_id"]["nullable"] assert { foreign_key["referred_table"] - for foreign_key in inspect(engine).get_foreign_keys(table_name) + for foreign_key in schema_inspector(sessions).get_foreign_keys(table_name) } == {"users", f"{reference}s"} for table_name, reference in ( ("user_policies", "policy"), ("user_household_associations", "household"), ): - columns = table_columns(engine, table_name) + columns = table_columns(sessions, table_name) assert f"legacy_{reference}_id" not in columns assert not columns[f"{reference}_id"]["nullable"] - user_columns = table_columns(engine, "users") + user_columns = table_columns(sessions, "users") assert "user_type" not in user_columns assert not user_columns["primary_country"]["nullable"] -def _assert_stage_12a_association_shape(engine) -> None: +def _assert_stage_12a_association_shape(sessions: sessionmaker[Session]) -> None: identity_constraints = { constraint["name"]: constraint["column_names"] - for constraint in inspect(engine).get_unique_constraints("user_identities") + for constraint in schema_inspector(sessions).get_unique_constraints( + "user_identities" + ) } assert identity_constraints["uq_user_identities_issuer_subject"] == [ "issuer", @@ -155,7 +393,7 @@ def _assert_stage_12a_association_shape(engine) -> None: ("user_simulation_associations", "simulation"), ("user_report_associations", "report"), ): - columns = table_columns(engine, table_name) + columns = table_columns(sessions, table_name) assert columns[f"{reference}_id"]["nullable"] assert columns[f"legacy_{reference}_id"]["nullable"] assert not columns["country_id"]["nullable"] @@ -163,7 +401,9 @@ def _assert_stage_12a_association_shape(engine) -> None: # No uniqueness involves the owner, so a merge can move any row. assert [ constraint["column_names"] - for constraint in inspect(engine).get_unique_constraints(table_name) + for constraint in schema_inspector(sessions).get_unique_constraints( + table_name + ) ] == [["id", "country_id"]] # At head, a saved simulation or report names a stored v2 simulation or # report through one RESTRICT key (revision 81b728a088e7). @@ -177,28 +417,29 @@ def _assert_stage_12a_association_shape(engine) -> None: foreign_key["referred_table"], foreign_key["options"].get("ondelete"), ) - for foreign_key in inspect(engine).get_foreign_keys(table_name) + for foreign_key in schema_inspector(sessions).get_foreign_keys(table_name) if foreign_key["referred_table"] in {"simulations", "reports"} ] assert v2_record_keys == [([column_name], referred_table, "RESTRICT")] report_policy_key = next( foreign_key - for foreign_key in inspect(engine).get_foreign_keys("user_report_associations") + for foreign_key in schema_inspector(sessions).get_foreign_keys( + "user_report_associations" + ) if foreign_key["referred_table"] == "user_policies" ) assert report_policy_key["options"]["ondelete"] == "SET NULL" for table_name in ("user_simulation_associations", "user_report_associations"): - columns = table_columns(engine, table_name) + columns = table_columns(sessions, table_name) assert columns["country"]["nullable"] assert columns["label"]["nullable"] - user_columns = table_columns(engine, "users") + user_columns = table_columns(sessions, "users") assert not user_columns["user_type"]["nullable"] - assert "standard" in user_columns["user_type"]["default"] + user_type_default = user_columns["user_type"]["default"] + assert user_type_default is not None + assert "standard" in user_type_default assert user_columns["primary_country"]["nullable"] - user_checks = { - constraint["name"] - for constraint in inspect(engine).get_check_constraints("users") - } + user_checks = _check_names(sessions, "users") # The user types revision renamed the type check when it added author and # admin. assert { @@ -207,114 +448,115 @@ def _assert_stage_12a_association_shape(engine) -> None: } <= user_checks -def _upgrade_and_assert_head(config: Config, engine: Engine) -> None: +def _upgrade_and_assert_head(config: Config, sessions: sessionmaker[Session]) -> None: command.upgrade(config, "head") command.check(config) - _assert_head(engine) + _assert_head(sessions) + + +def _assert_revision(sessions: sessionmaker[Session], revision: str) -> None: + assert _current_revision(sessions) == revision -def _assert_revision(engine: Engine, revision: str) -> None: - with engine.connect() as connection: - context = MigrationContext.configure(connection) - assert context.get_current_revision() == revision +def _enum_type_names(sessions: sessionmaker[Session]) -> set[str]: + """Return the name of every enum type in the database, in any schema.""" + inspector = schema_inspector(sessions) + assert isinstance(inspector, PGInspector) + return {enum_type["name"] for enum_type in inspector.get_enums(schema="*")} def _assert_revision_without_enum_types( - engine: Engine, revision: str | None, enum_query: str + sessions: sessionmaker[Session], revision: str | None, enum_name_pattern: str ) -> None: - """Check the database revision, then that ``enum_query`` counts no enum types.""" - with engine.connect() as connection: - context = MigrationContext.configure(connection) - assert context.get_current_revision() == revision - enum_count = connection.execute(text(enum_query)).scalar_one() - assert enum_count == 0 + """Check the database revision, then that no enum type's name matches. + ``enum_name_pattern`` is a regular expression the whole name must match. + """ + assert _current_revision(sessions) == revision + matching_enum_types = sorted( + type_name + for type_name in _enum_type_names(sessions) + if re.fullmatch(enum_name_pattern, type_name) + ) + assert matching_enum_types == [] -def _insert_legacy_stage12_report(engine: Engine) -> UUID: + +def _insert_legacy_stage12_report(sessions: sessionmaker[Session]) -> UUID: """Store a report from before the comparison columns existed; return its id.""" legacy_report_id = uuid4() - with engine.begin() as connection: - connection.execute( - text( - "INSERT INTO stage12_evaluation_reports " - "(evaluation_id, contract_version, status, aggregation_status, " - "environment, calculation_flow, originating_request_id, " - "production_identity, worker_version, modal_application, " - "report_coordinator_callable, version_manifest_sha256, " - "policyengine_version, country_package_name, " - "country_package_version, country, dataset_identity, dataset_uri, " - "data_package_name, data_package_version, data_artifact_revision, " - "retention_expires_at) VALUES " - "(:evaluation_id, 1, 'pending', 'not_started', 'test', " - "'economy', 'request', 'production', '5.2.0', 'application', " - "'coordinate_report', :digest, '5.2.0', 'policyengine-us', " - "'1.0.0', 'us', 'dataset', 'hf://dataset/file@revision', " - "'data-package', '1.0.0', 'revision', now() + interval '1 day')" - ), - {"evaluation_id": legacy_report_id, "digest": "a" * 64}, + with sessions.begin() as session: + add_row( + session, + Stage12ReportBeforeComparison, + evaluation_id=legacy_report_id, + contract_version=1, + status="pending", + aggregation_status="not_started", + environment="test", + calculation_flow="economy", + originating_request_id="request", + production_identity="production", + worker_version="5.2.0", + modal_application="application", + report_coordinator_callable="coordinate_report", + version_manifest_sha256="a" * 64, + policyengine_version="5.2.0", + country_package_name="policyengine-us", + country_package_version="1.0.0", + country="us", + dataset_identity="dataset", + dataset_uri="hf://dataset/file@revision", + data_package_name="data-package", + data_package_version="1.0.0", + data_artifact_revision="revision", + # The database's clock, as created_at's server default uses. + retention_expires_at=func.now() + timedelta(days=1), ) return legacy_report_id -def _assert_comparison_downgrade_then_store_legacy_report(engine: Engine) -> UUID: +def _assert_comparison_downgrade_then_store_legacy_report( + sessions: sessionmaker[Session], +) -> UUID: """Check the comparison revision is gone, then store a pre-comparison report.""" _assert_revision_without_enum_types( - engine, + sessions, STAGE_12_COMPARISON_PREVIOUS_REVISION, - "SELECT count(*) FROM pg_type " - "WHERE typname = 'v2_stage12_result_comparison_status' " - "AND typtype = 'e'", + "v2_stage12_result_comparison_status", ) - report_columns = { - column["name"] - for column in inspect(engine).get_columns( - "stage12_evaluation_reports", - schema="public", - ) - } + report_columns = table_columns(sessions, "stage12_evaluation_reports") assert not any(name.startswith("comparison_") for name in report_columns) - return _insert_legacy_stage12_report(engine) + return _insert_legacy_stage12_report(sessions) def _assert_legacy_report_is_not_compared( - engine: Engine, legacy_report_id: UUID + sessions: sessionmaker[Session], legacy_report_id: UUID ) -> None: - with engine.connect() as connection: - comparison_status = connection.execute( - text( - "SELECT comparison_status FROM stage12_evaluation_reports " - "WHERE evaluation_id = :evaluation_id" - ), - {"evaluation_id": legacy_report_id}, - ).scalar_one() + with sessions() as session: + comparison_status = session.scalars( + select(col(Stage12ComparisonReport.comparison_status)).where( + col(Stage12ComparisonReport.evaluation_id) == legacy_report_id + ) + ).one() assert comparison_status == "not_requested" -def _assert_stage12_downgrade(engine: Engine) -> None: +def _assert_stage12_downgrade(sessions: sessionmaker[Session]) -> None: _assert_revision_without_enum_types( - engine, - STAGE_12_PREVIOUS_REVISION, - "SELECT count(*) FROM pg_type " - "WHERE typname LIKE 'v2_stage12_%' AND typtype = 'e'", + sessions, STAGE_12_PREVIOUS_REVISION, r"v2_stage12_.*" ) assert { "stage12_evaluation_reports", "stage12_evaluation_simulations", - }.isdisjoint(inspect(engine).get_table_names(schema="public")) + }.isdisjoint(schema_inspector(sessions).get_table_names(schema="public")) -def _assert_stage11_downgrade(engine: Engine) -> None: - _assert_revision(engine, STAGE_11_PREVIOUS_REVISION) - assert "legacy_household_mappings" not in inspect(engine).get_table_names( - schema="public" - ) - household_columns = { - column["name"]: column - for column in inspect(engine).get_columns( - "households", - schema="public", - ) - } +def _assert_stage11_downgrade(sessions: sessionmaker[Session]) -> None: + _assert_revision(sessions, STAGE_11_PREVIOUS_REVISION) + assert "legacy_household_mappings" not in schema_inspector( + sessions + ).get_table_names(schema="public") + household_columns = table_columns(sessions, "households") assert {"country", "label", "year"} <= household_columns.keys() assert { "country_id", @@ -322,48 +564,31 @@ def _assert_stage11_downgrade(engine: Engine) -> None: "canonicalization_version", "content_hash", }.isdisjoint(household_columns) - association_columns = { - column["name"]: column - for column in inspect(engine).get_columns( - "user_household_associations", - schema="public", - ) - } + association_columns = table_columns(sessions, "user_household_associations") assert {"country", "label"} <= association_columns.keys() assert {"country_id", "name", "description"}.isdisjoint(association_columns) - user_policy_id = next( - column - for column in inspect(engine).get_columns( - "user_policies", - schema="public", - ) - if column["name"] == "user_id" - ) + user_policy_id = table_columns(sessions, "user_policies")["user_id"] assert isinstance(user_policy_id["type"], postgresql.UUID) - user_columns = { - column["name"]: column - for column in inspect(engine).get_columns("users", schema="public") - } + user_columns = table_columns(sessions, "users") assert all( user_columns[field_name]["nullable"] for field_name in ("first_name", "last_name", "email") ) -def _assert_baseline_downgrade(engine: Engine) -> None: - _assert_revision(engine, BASELINE_REVISION) +def _assert_baseline_downgrade(sessions: sessionmaker[Session]) -> None: + _assert_revision(sessions, BASELINE_REVISION) assert "uq_parameter_values_canonical_parameter_start_date" not in { - index["name"] for index in inspect(engine).get_indexes("parameter_values") + index["name"] + for index in schema_inspector(sessions).get_indexes("parameter_values") } -def _assert_base(engine: Engine) -> None: - assert set(inspect(engine).get_table_names(schema="public")) <= {"alembic_version"} - _assert_revision_without_enum_types( - engine, - None, - "SELECT count(*) FROM pg_type WHERE typname LIKE 'v2_%' AND typtype = 'e'", - ) +def _assert_base(sessions: sessionmaker[Session]) -> None: + assert set(schema_inspector(sessions).get_table_names(schema="public")) <= { + ALEMBIC_VERSION_TABLE + } + _assert_revision_without_enum_types(sessions, None, r"v2_.*") # Every column that names a record's country, with the check it replaced. @@ -385,109 +610,113 @@ def _assert_base(engine: Engine) -> None: LISTED_COUNTRIES = [("uk", True, True), ("us", True, True)] -def _country_foreign_keys(engine, table_name: str) -> list[dict]: +def _country_foreign_keys( + sessions: sessionmaker[Session], table_name: str +) -> list[ReflectedForeignKeyConstraint]: return [ foreign_key - for foreign_key in inspect(engine).get_foreign_keys(table_name) + for foreign_key in schema_inspector(sessions).get_foreign_keys(table_name) if foreign_key["referred_table"] == "countries" ] -def _check_names(engine, table_name: str) -> set[str]: +def _check_names(sessions: sessionmaker[Session], table_name: str) -> set[str | None]: return { constraint["name"] - for constraint in inspect(engine).get_check_constraints(table_name) + for constraint in schema_inspector(sessions).get_check_constraints(table_name) } -def _listed_countries(engine) -> list[tuple]: - with engine.connect() as connection: - return [ - tuple(row) - for row in connection.execute( - text( - "SELECT id, household_enabled, society_wide_enabled " - "FROM countries ORDER BY id" - ) - ) - ] +def _listed_countries(sessions: sessionmaker[Session]) -> list[tuple[Any, ...]]: + with sessions() as session: + rows = session.execute( + select( + col(Country.id), + col(Country.household_enabled), + col(Country.society_wide_enabled), + ).order_by(col(Country.id)) + ).all() + return [tuple(row) for row in rows] -def _assert_countries_shape(engine) -> None: - assert _listed_countries(engine) == LISTED_COUNTRIES +def _assert_countries_shape(sessions: sessionmaker[Session]) -> None: + assert _listed_countries(sessions) == LISTED_COUNTRIES assert "ck_countries_society_wide_requires_household" in _check_names( - engine, "countries" + sessions, "countries" ) for (table_name, column_name), check_name in COUNTRY_REFERENCE_COLUMNS.items(): - country_keys = _country_foreign_keys(engine, table_name) + country_keys = _country_foreign_keys(sessions, table_name) assert len(country_keys) == 1, table_name assert country_keys[0]["name"] == f"fk_{table_name}_{column_name}_countries" assert country_keys[0]["constrained_columns"] == [column_name] assert country_keys[0]["referred_columns"] == ["id"] assert country_keys[0]["options"]["ondelete"] == "RESTRICT" - assert check_name not in _check_names(engine, table_name) + assert check_name not in _check_names(sessions, table_name) -def _assert_pre_countries_shape(engine) -> None: - assert "countries" not in inspect(engine).get_table_names(schema="public") +def _assert_pre_countries_shape(sessions: sessionmaker[Session]) -> None: + assert "countries" not in schema_inspector(sessions).get_table_names( + schema="public" + ) for (table_name, _column_name), check_name in COUNTRY_REFERENCE_COLUMNS.items(): - assert _country_foreign_keys(engine, table_name) == [] - assert check_name in _check_names(engine, table_name) + assert _country_foreign_keys(sessions, table_name) == [] + assert check_name in _check_names(sessions, table_name) -def test_empty_upgrade_check_base_downgrade_and_reupgrade() -> None: - database_url = disposable_v2_url() +def test_empty_upgrade_check_base_downgrade_and_reupgrade( + v2_owner_sessions: sessionmaker[Session], +) -> None: config = alembic_v2_config() - engine = create_engine(database_url) try: command.downgrade(config, "base") - assert set(inspect(engine).get_table_names(schema="public")) <= { - "alembic_version" - } + assert set( + schema_inspector(v2_owner_sessions).get_table_names(schema="public") + ) <= {ALEMBIC_VERSION_TABLE} - _upgrade_and_assert_head(config, engine) - _assert_countries_shape(engine) + _upgrade_and_assert_head(config, v2_owner_sessions) + _assert_countries_shape(v2_owner_sessions) command.downgrade(config, CATALOG_FORMAT_2_REVISION) - _assert_area_impact_coordinates_restored(engine) - _upgrade_and_assert_head(config, engine) + _assert_area_impact_coordinates_restored(v2_owner_sessions) + _upgrade_and_assert_head(config, v2_owner_sessions) command.downgrade(config, COUNTRIES_PREVIOUS_REVISION) - _assert_revision(engine, COUNTRIES_PREVIOUS_REVISION) - _assert_pre_countries_shape(engine) - _upgrade_and_assert_head(config, engine) - _assert_countries_shape(engine) + _assert_revision(v2_owner_sessions, COUNTRIES_PREVIOUS_REVISION) + _assert_pre_countries_shape(v2_owner_sessions) + _upgrade_and_assert_head(config, v2_owner_sessions) + _assert_countries_shape(v2_owner_sessions) command.downgrade(config, STAGE_12A_PREVIOUS_REVISION) - _assert_revision(engine, STAGE_12A_PREVIOUS_REVISION) - _assert_pre_stage_12a_association_shape(engine) - _upgrade_and_assert_head(config, engine) - _assert_stage_12a_association_shape(engine) + _assert_revision(v2_owner_sessions, STAGE_12A_PREVIOUS_REVISION) + _assert_pre_stage_12a_association_shape(v2_owner_sessions) + _upgrade_and_assert_head(config, v2_owner_sessions) + _assert_stage_12a_association_shape(v2_owner_sessions) command.downgrade(config, STAGE_12_COMPARISON_PREVIOUS_REVISION) - legacy_report_id = _assert_comparison_downgrade_then_store_legacy_report(engine) - _upgrade_and_assert_head(config, engine) - _assert_legacy_report_is_not_compared(engine, legacy_report_id) + legacy_report_id = _assert_comparison_downgrade_then_store_legacy_report( + v2_owner_sessions + ) + _upgrade_and_assert_head(config, v2_owner_sessions) + _assert_legacy_report_is_not_compared(v2_owner_sessions, legacy_report_id) command.downgrade(config, STAGE_12_PREVIOUS_REVISION) - _assert_stage12_downgrade(engine) - _upgrade_and_assert_head(config, engine) + _assert_stage12_downgrade(v2_owner_sessions) + _upgrade_and_assert_head(config, v2_owner_sessions) command.downgrade(config, STAGE_11_PREVIOUS_REVISION) - _assert_stage11_downgrade(engine) - _upgrade_and_assert_head(config, engine) + _assert_stage11_downgrade(v2_owner_sessions) + _upgrade_and_assert_head(config, v2_owner_sessions) command.downgrade(config, BASELINE_REVISION) - _assert_baseline_downgrade(engine) - _upgrade_and_assert_head(config, engine) + _assert_baseline_downgrade(v2_owner_sessions) + _upgrade_and_assert_head(config, v2_owner_sessions) command.downgrade(config, "base") - _assert_base(engine) - _upgrade_and_assert_head(config, engine) + _assert_base(v2_owner_sessions) + _upgrade_and_assert_head(config, v2_owner_sessions) finally: command.upgrade(config, "head") - engine.dispose() # Dormant at the Stage 12A parent revision: its models map these tables, and @@ -496,359 +725,71 @@ def test_empty_upgrade_check_base_downgrade_and_reupgrade() -> None: STAGE_12A_PARENT_READ_ONLY_TABLES = frozenset( {"user_simulation_associations", "user_report_associations"} ) -USER_ASSOCIATION_TABLES = ( - "user_policies", - "user_household_associations", - "user_simulation_associations", - "user_report_associations", -) -COUNTRY_COLUMN_NAMES = frozenset({"country", "country_id", "primary_country"}) -# Nullable references that a parent-revision check constraint requires: a -# standard user's country, and one of each association's two references. -REFERENCES_REQUIRED_BY_CHECKS = frozenset( - { - ("simulations", "household_id"), - ("users", "primary_country"), - ("user_policies", "policy_id"), - ("user_household_associations", "household_id"), - ("user_simulation_associations", "simulation_id"), - ("user_report_associations", "report_id"), - } -) -# Required values that a parent-revision check constraint restricts. -CHECKED_VALUES = {("datasets", "year"): 2026} - - -def _is_required_without_default(column: sa.Column) -> bool: - return not column.nullable and column.server_default is None - - -def _new_required_columns(parent_table: sa.Table, head_table: sa.Table) -> set[str]: - return { - column.name - for column in head_table.columns - if column.name not in parent_table.columns - and _is_required_without_default(column) - } - - -def _string_test_value(column_type: sa.String, sequence: Iterator[int]) -> str: - length = column_type.length or 255 - if length == 64: - return uuid4().hex + uuid4().hex - return f"value-{next(sequence)}"[:length] - - -# Checked in order: a column takes the value of the first type it is an -# instance of, so Enum, a String subclass, comes before String. -TYPED_TEST_VALUES = ( - (sa.Enum, lambda column_type, _sequence: column_type.enums[0]), - (sa.Uuid, lambda _column_type, _sequence: uuid4()), - (sa.Boolean, lambda _column_type, _sequence: False), - (sa.Integer, lambda _column_type, _sequence: 1), - (sa.Float, lambda _column_type, _sequence: 0.0), - # Later than every server-default created_at, as retention checks need. - ( - sa.DateTime, - lambda _column_type, _sequence: datetime.now(UTC) + timedelta(days=1), - ), - (sa.JSON, lambda _column_type, _sequence: {}), - (sa.String, _string_test_value), -) - - -def _test_value(table: sa.Table, column: sa.Column, sequence: Iterator[int]): - if (table.name, column.name) in CHECKED_VALUES: - return CHECKED_VALUES[(table.name, column.name)] - if column.name in COUNTRY_COLUMN_NAMES: - return "us" - for column_type, test_value in TYPED_TEST_VALUES: - if isinstance(column.type, column_type): - return test_value(column.type, sequence) - msg = f"no test value for {table.name}.{column.name}" - raise AssertionError(msg) - - -def _row_values( - table: sa.Table, - stored_rows: dict[str, dict], - sequence: Iterator[int], - *, - head_table: sa.Table | None = None, -) -> dict: - """Supply only what the parent revision requires, plus check-bound values. - - ``head_table`` adds the columns head newly requires; only rows of the - parent's read-only tables, which new code writes, may need them. - """ - values = { - column.name: _test_value(table, column, sequence) - for column in table.columns - if _is_required_without_default(column) - or (table.name, column.name) in REFERENCES_REQUIRED_BY_CHECKS - } - if head_table is not None: - for column_name in _new_required_columns(table, head_table): - values[column_name] = _test_value( - head_table, head_table.columns[column_name], sequence - ) - for foreign_key in table.foreign_key_constraints: - if not any(element.parent.name in values for element in foreign_key.elements): - continue - referenced_row = stored_rows[foreign_key.referred_table.name] - for element in foreign_key.elements: - values[element.parent.name] = referenced_row[element.column.name] - return values - - -def _primary_key_clause(table: sa.Table, row: dict): - return sa.and_( - *(column == row[column.name] for column in table.primary_key.columns) - ) - - -def _insert_and_read_back( - connection, - table: sa.Table, - values: dict, - *, - insert_table: sa.Table | None = None, -) -> dict: - """Insert a row, then read it back through the parent's reflected table. - - Rows of the parent's read-only tables are inserted through head's table, - as only new code writes them. - """ - target = insert_table if insert_table is not None else table - connection.execute(target.insert().values(values)) - # Selecting the reflected table reads every column the parent maps. - return dict( - connection.execute(sa.select(table).where(_primary_key_clause(table, values))) - .mappings() - .one() - ) - - -def _rewrite_mapped_columns(connection, table: sa.Table, row: dict) -> None: - """Update every non-key column the parent maps, as an ORM flush can.""" - key_columns = {column.name for column in table.primary_key.columns} | { - element.parent.name - for foreign_key in table.foreign_key_constraints - for element in foreign_key.elements - } - result = connection.execute( - table.update() - .where(_primary_key_clause(table, row)) - .values( - { - # sa.null() keeps SQL NULL; a bare None becomes JSON null. - name: sa.null() if value is None else value - for name, value in row.items() - if name not in key_columns - } - ) - ) - assert result.rowcount == 1, table.name - - -@dataclass(frozen=True) -class PreviousRevisionSchemas: - """A previous revision's reflected schema and the one it was upgraded to. - ``read_only_tables`` are the previous revision's tables that only new code - writes, so their test rows are inserted through the upgraded table. - """ - - parent: sa.MetaData - head: sa.MetaData - read_only_tables: frozenset[str] - - def insert_table(self, table_name: str) -> sa.Table | None: - """Return the upgraded table for a read-only table, otherwise ``None``.""" - if table_name in self.read_only_tables: - return self.head.tables[table_name] - return None - -def _assert_user_deletion_cascades( - connection, - schemas: PreviousRevisionSchemas, - stored_rows: dict[str, dict], - sequence: Iterator[int], +def test_stage_12a_schema_serves_the_previous_revision( + v2_owner_sessions: sessionmaker[Session], ) -> None: - """Delete, through the parent's users table, a user who owns association rows.""" - parent, head = schemas.parent, schemas.head - users = parent.tables["users"] - owner = _insert_and_read_back( - connection, users, _row_values(users, stored_rows, sequence) - ) - owner_rows = {**stored_rows, "users": owner} - for table_name in USER_ASSOCIATION_TABLES: - table = parent.tables[table_name] - head_table = schemas.insert_table(table_name) - _insert_and_read_back( - connection, - table, - _row_values(table, owner_rows, sequence, head_table=head_table), - insert_table=head_table, - ) - identities = head.tables["user_identities"] - connection.execute( - identities.insert().values( - id=uuid4(), - user_id=owner["id"], - issuer="https://auth.example.test/", - subject="google-oauth2|previous-revision", - ) - ) - - result = connection.execute(users.delete().where(users.c.id == owner["id"])) - - assert result.rowcount == 1 - for table_name in (*USER_ASSOCIATION_TABLES, "user_identities"): - table = head.tables[table_name] - remaining = connection.execute( - sa.select(sa.func.count()) - .select_from(table) - .where(table.c.user_id == owner["id"]) - ).scalar_one() - assert remaining == 0, table_name - - -def _assert_revision_serves_previous_revision( - previous_revision: str, - revision: str, - read_only_tables: frozenset[str], -) -> None: - """Run a previous Public API revision's table usage against ``revision``. - - The parent revision's schema is reflected and then used, after upgrading - to ``revision``, the revision it ran beside during that deploy, - to insert a row into every table it maps (supplying only what it - requires), read the row back with every mapped column, rewrite those - columns, delete it, and delete a user who owns association rows so the - cascades run. ``revision`` may not give any table the parent revision - writes a new required column without a server default; ``read_only_tables`` - are the parent's tables that only new code writes. - """ - database_url = disposable_v2_url() - config = alembic_v2_config() - engine = create_engine(database_url) - - try: - command.downgrade(config, previous_revision) - parent = sa.MetaData() - parent.reflect(engine) - command.upgrade(config, revision) - head = sa.MetaData() - head.reflect(engine) - parent_tables = [ - table for table in parent.sorted_tables if table.name != "alembic_version" - ] - - dropped_columns = sorted( - f"{table.name}.{column.name}" - for table in parent_tables - for column in table.columns - if table.name not in head.tables - or column.name not in head.tables[table.name].columns - ) - assert dropped_columns == [] - tables_with_new_required_columns = { - table.name: sorted(_new_required_columns(table, head.tables[table.name])) - for table in parent_tables - if _new_required_columns(table, head.tables[table.name]) - } - assert set(tables_with_new_required_columns) <= read_only_tables, ( - tables_with_new_required_columns - ) - - schemas = PreviousRevisionSchemas(parent, head, read_only_tables) - sequence = itertools.count() - with engine.connect() as connection: - transaction = connection.begin() - try: - stored_rows: dict[str, dict] = {} - for table in parent_tables: - head_table = schemas.insert_table(table.name) - stored_rows[table.name] = _insert_and_read_back( - connection, - table, - _row_values( - table, stored_rows, sequence, head_table=head_table - ), - insert_table=head_table, - ) - _rewrite_mapped_columns(connection, table, stored_rows[table.name]) - - _assert_user_deletion_cascades( - connection, schemas, stored_rows, sequence - ) - - for table in reversed(parent_tables): - result = connection.execute( - table.delete().where( - _primary_key_clause(table, stored_rows[table.name]) - ) - ) - assert result.rowcount == 1, table.name - finally: - transaction.rollback() - finally: - command.upgrade(config, "head") - engine.dispose() - - -def test_stage_12a_schema_serves_the_previous_revision() -> None: - _assert_revision_serves_previous_revision( + assert_revision_serves_previous_revision( + v2_owner_sessions, STAGE_12A_PREVIOUS_REVISION, STAGE_12A_REVISION, STAGE_12A_PARENT_READ_ONLY_TABLES, ) -def test_countries_schema_serves_the_previous_revision() -> None: +def test_countries_schema_serves_the_previous_revision( + v2_owner_sessions: sessionmaker[Session], +) -> None: """The release before the countries table keeps working during a deploy.""" - _assert_revision_serves_previous_revision( + assert_revision_serves_previous_revision( + v2_owner_sessions, COUNTRIES_PREVIOUS_REVISION, COUNTRIES_REVISION, frozenset(), ) -def test_area_impact_coordinate_removal_changes_nothing_else() -> None: +def _column_names_by_table(sessions: sessionmaker[Session]) -> dict[str, set[str]]: + """Return the names of every public table's columns, by the table's name.""" + inspector = schema_inspector(sessions) + return { + table_name: {column["name"] for column in inspector.get_columns(table_name)} + for table_name in inspector.get_table_names() + } + + +def test_area_impact_coordinate_removal_changes_nothing_else( + v2_owner_sessions: sessionmaker[Session], +) -> None: """Check that the coordinate revision drops the map coordinates and nothing else. The revision is compared with its parent, the catalog format 2 revision. The - previous Public API revision still maps those four columns, but it can't + previous API v1 revision still maps those four columns, but it can't read or write either table: no managed database role holds any privilege on them (``policyengine_api/data/v2/privileges.py``). Every table it can use keeps every column. """ - database_url = disposable_v2_url() config = alembic_v2_config() - engine = create_engine(database_url) try: command.downgrade(config, CATALOG_FORMAT_2_REVISION) - parent = sa.MetaData() - parent.reflect(engine) + parent = _column_names_by_table(v2_owner_sessions) command.upgrade(config, AREA_IMPACT_COORDINATE_REVISION) - head = sa.MetaData() - head.reflect(engine) + head = _column_names_by_table(v2_owner_sessions) - assert set(head.tables) == set(parent.tables) + assert set(head) == set(parent) dropped_columns = sorted( - f"{table.name}.{column.name}" - for table in parent.tables.values() - for column in table.columns - if column.name not in head.tables[table.name].columns + f"{table_name}.{column_name}" + for table_name, column_names in parent.items() + for column_name in column_names + if column_name not in head[table_name] ) added_columns = sorted( - f"{table.name}.{column.name}" - for table in head.tables.values() - for column in table.columns - if column.name not in parent.tables[table.name].columns + f"{table_name}.{column_name}" + for table_name, column_names in head.items() + for column_name in column_names + if column_name not in parent[table_name] ) assert dropped_columns == sorted( f"{table_name}.{column_name}" @@ -858,18 +799,17 @@ def test_area_impact_coordinate_removal_changes_nothing_else() -> None: assert added_columns == [] finally: command.upgrade(config, "head") - engine.dispose() -def test_upgrade_to_head_validates_the_resulting_schema_against_metadata() -> None: - database_url = disposable_v2_url() +def test_upgrade_to_head_validates_the_resulting_schema_against_metadata( + v2_owner_sessions: sessionmaker[Session], +) -> None: config = alembic_v2_config() - engine = create_engine(database_url) try: command.downgrade(config, "base") - with engine.begin() as connection: - connection.execute(text("CREATE TABLE unreviewed_runtime_table (id INT)")) + with v2_owner_sessions.begin() as session: + create_registry_tables(session, UnreviewedTableBase.registry) with pytest.raises( V2MigrationTargetError, @@ -877,33 +817,25 @@ def test_upgrade_to_head_validates_the_resulting_schema_against_metadata() -> No ): command.upgrade(config, "head") - with engine.connect() as connection: - context = MigrationContext.configure(connection) - assert context.get_current_revision() is None + assert _current_revision(v2_owner_sessions) is None finally: - with engine.begin() as connection: - connection.execute(text("DROP TABLE IF EXISTS unreviewed_runtime_table")) + with v2_owner_sessions.begin() as session: + drop_registry_tables(session, UnreviewedTableBase.registry) command.upgrade(config, "head") - engine.dispose() -def test_baseline_uses_native_uuid_report_run_idempotency() -> None: - database_url = disposable_v2_url() +def test_baseline_uses_native_uuid_report_run_idempotency( + v2_owner_sessions: sessionmaker[Session], +) -> None: config = alembic_v2_config() - engine = create_engine(database_url) - def idempotency_column_type(): - return next( - column["type"] - for column in inspect(engine).get_columns("report_runs") - if column["name"] == "idempotency_key" - ) + def idempotency_column_type() -> object: + return table_columns(v2_owner_sessions, "report_runs")["idempotency_key"][ + "type" + ] - def report_run_checks() -> set[str]: - return { - constraint["name"] - for constraint in inspect(engine).get_check_constraints("report_runs") - } + def report_run_checks() -> set[str | None]: + return _check_names(v2_owner_sessions, "report_runs") report_id = uuid4() report_run_id = uuid4() @@ -915,20 +847,20 @@ def report_run_checks() -> set[str]: assert isinstance(idempotency_column_type(), postgresql.UUID) assert "ck_report_runs_idempotency_key_nonblank" not in report_run_checks() - with engine.begin() as connection: - public_api_rows = insert_public_api_rows(connection) - insert_row( - connection, - "simulations", + with v2_owner_sessions.begin() as session: + public_api_rows = insert_public_api_rows(session) + add_row( + session, + Simulation, id=simulation_id, simulation_type="economy", dataset_id=public_api_rows.dataset_id, tax_benefit_model_version_id=public_api_rows.version_id, ) simulation_run_id = uuid4() - insert_row( - connection, - "simulation_runs", + add_row( + session, + SimulationRun, id=simulation_run_id, simulation_id=simulation_id, tax_benefit_model_version_id=public_api_rows.version_id, @@ -936,79 +868,73 @@ def report_run_checks() -> set[str]: status="pending", **RUN_VERSIONS, ) - connection.execute( - text( - "INSERT INTO reports " - "(id, label, country, tax_benefit_model_id, inputs) " - "VALUES (:id, 'UUID cast report', 'us', :model_id, '{}')" - ), - {"id": report_id, "model_id": public_api_rows.model_id}, + add_row( + session, + Report, + id=report_id, + label="UUID cast report", + country="us", + tax_benefit_model_id=public_api_rows.model_id, + inputs={}, ) - connection.execute( - text( - "INSERT INTO report_runs " - "(id, report_id, baseline_simulation_run_id, " - "country_package_version, policyengine_version, status, " - "trigger, idempotency_key) " - "VALUES (:id, :report_id, :simulation_run_id, '1.0', '1.0', " - "'pending', 'manual', :request_key)" - ), - { - "id": report_run_id, - "report_id": report_id, - "simulation_run_id": simulation_run_id, - "request_key": str(request_key), - }, + add_row( + session, + ReportRun, + id=report_run_id, + report_id=report_id, + baseline_simulation_run_id=simulation_run_id, + 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), ) - with engine.connect() as connection: - stored_key = connection.execute( - text("SELECT idempotency_key FROM report_runs WHERE id = :run_id"), - {"run_id": report_run_id}, - ).scalar_one() + with v2_owner_sessions() as session: + stored_key = session.scalars( + select(col(ReportRun.idempotency_key)).where( + col(ReportRun.id) == report_run_id + ) + ).one() assert stored_key == request_key assert isinstance(stored_key, UUID) finally: - with engine.begin() as connection: - connection.execute( - text("DELETE FROM report_runs WHERE id = :run_id"), - {"run_id": report_run_id}, - ) - connection.execute( - text("DELETE FROM reports WHERE id = :report_id"), - {"report_id": report_id}, - ) - connection.execute( - text("DELETE FROM simulations WHERE id = :simulation_id"), - {"simulation_id": simulation_id}, + with v2_owner_sessions.begin() as session: + session.execute(delete(ReportRun).where(col(ReportRun.id) == report_run_id)) + session.execute(delete(Report).where(col(Report.id) == report_id)) + session.execute( + delete(Simulation).where(col(Simulation.id) == simulation_id) ) if public_api_rows is not None: - delete_public_api_rows(connection, public_api_rows) + delete_public_api_rows(session, public_api_rows) command.upgrade(config, "head") - engine.dispose() -def test_baseline_region_default_enforces_same_model_dataset() -> None: - database_url = disposable_v2_url() +def test_baseline_region_default_enforces_same_model_dataset( + v2_owner_sessions: sessionmaker[Session], +) -> None: config = alembic_v2_config() - engine = create_engine(database_url) first_model_id = uuid4() second_model_id = uuid4() first_dataset_id = uuid4() second_dataset_id = uuid4() + model_ids = (first_model_id, second_model_id) try: command.downgrade(config, BASELINE_REVISION) - assert "region_datasets" not in inspect(engine).get_table_names(schema="public") - default_column = next( - column - for column in inspect(engine).get_columns("regions") - if column["name"] == "default_dataset_id" - ) + assert "region_datasets" not in schema_inspector( + v2_owner_sessions + ).get_table_names(schema="public") + default_column = table_columns(v2_owner_sessions, "regions")[ + "default_dataset_id" + ] assert not default_column["nullable"] default_constraint = next( constraint - for constraint in inspect(engine).get_foreign_keys("regions") + for constraint in schema_inspector(v2_owner_sessions).get_foreign_keys( + "regions" + ) if constraint["name"] == "fk_regions_default_dataset_model_datasets" ) assert default_constraint["constrained_columns"] == [ @@ -1020,318 +946,265 @@ def test_baseline_region_default_enforces_same_model_dataset() -> None: "tax_benefit_model_id", ] - with engine.begin() as connection: - connection.execute( - text( - "INSERT INTO tax_benefit_models (id, name) " - "VALUES (:first_id, :first_name), (:second_id, :second_name)" - ), - { - "first_id": first_model_id, - "first_name": f"region-default-{first_model_id.hex[:8]}", - "second_id": second_model_id, - "second_name": f"region-default-{second_model_id.hex[:8]}", - }, - ) - connection.execute( - text( - "INSERT INTO datasets " - "(id, name, year, is_output_dataset, tax_benefit_model_id) " - "VALUES (:first_id, 'logical-input', 2024, false, :first_model), " - "(:second_id, 'logical-input', 2024, false, :second_model)" - ), - { - "first_id": first_dataset_id, - "first_model": first_model_id, - "second_id": second_dataset_id, - "second_model": second_model_id, - }, - ) - connection.execute( - text( - "INSERT INTO regions " - "(id, code, label, region_type, requires_filter, " - "tax_benefit_model_id, default_dataset_id) " - "VALUES (:id, 'us', 'United States', 'national', false, " - ":model_id, :dataset_id)" - ), - { - "id": uuid4(), - "model_id": first_model_id, - "dataset_id": first_dataset_id, - }, + with v2_owner_sessions.begin() as session: + for model_id in model_ids: + add_row( + session, + TaxBenefitModelAtBaseline, + id=model_id, + name=f"region-default-{model_id.hex[:8]}", + ) + for dataset_id, model_id in ( + (first_dataset_id, first_model_id), + (second_dataset_id, second_model_id), + ): + add_row( + session, + DatasetAtBaseline, + id=dataset_id, + name="logical-input", + year=2024, + is_output_dataset=False, + tax_benefit_model_id=model_id, + ) + add_row( + session, + RegionAtBaseline, + id=uuid4(), + code="us", + label="United States", + region_type="national", + requires_filter=False, + tax_benefit_model_id=first_model_id, + default_dataset_id=first_dataset_id, ) - with pytest.raises(sa.exc.IntegrityError), engine.begin() as connection: - connection.execute( - text( - "INSERT INTO regions " - "(id, code, label, region_type, requires_filter, " - "tax_benefit_model_id, default_dataset_id) " - "VALUES (:id, 'state/ca', 'California', 'state', false, " - ":model_id, :dataset_id)" - ), - { - "id": uuid4(), - "model_id": first_model_id, - "dataset_id": second_dataset_id, - }, + with pytest.raises(IntegrityError), v2_owner_sessions.begin() as session: + add_row( + session, + RegionAtBaseline, + id=uuid4(), + code="state/ca", + label="California", + region_type="state", + requires_filter=False, + tax_benefit_model_id=first_model_id, + default_dataset_id=second_dataset_id, ) - with pytest.raises(sa.exc.IntegrityError), engine.begin() as connection: - connection.execute( - text( - "INSERT INTO datasets " - "(id, name, year, is_output_dataset, " - "tax_benefit_model_id) " - "VALUES (:id, 'missing-output-path', 2024, true, :model_id)" - ), - {"id": uuid4(), "model_id": first_model_id}, + with pytest.raises(IntegrityError), v2_owner_sessions.begin() as session: + add_row( + session, + DatasetAtBaseline, + id=uuid4(), + name="missing-output-path", + year=2024, + is_output_dataset=True, + tax_benefit_model_id=first_model_id, ) finally: - with engine.begin() as connection: - connection.execute( - text("DELETE FROM regions WHERE tax_benefit_model_id IN (:a, :b)"), - {"a": first_model_id, "b": second_model_id}, + with v2_owner_sessions.begin() as session: + session.execute( + delete(RegionAtBaseline).where( + RegionAtBaseline.tax_benefit_model_id.in_(model_ids) + ) ) - connection.execute( - text("DELETE FROM datasets WHERE tax_benefit_model_id IN (:a, :b)"), - {"a": first_model_id, "b": second_model_id}, + session.execute( + delete(DatasetAtBaseline).where( + DatasetAtBaseline.tax_benefit_model_id.in_(model_ids) + ) ) - connection.execute( - text("DELETE FROM tax_benefit_models WHERE id IN (:a, :b)"), - {"a": first_model_id, "b": second_model_id}, + session.execute( + delete(TaxBenefitModelAtBaseline).where( + TaxBenefitModelAtBaseline.id.in_(model_ids) + ) ) command.upgrade(config, "head") - engine.dispose() -def test_stage_12a_reshape_refuses_retained_dormant_association_rows() -> None: +def test_stage_12a_reshape_refuses_retained_dormant_association_rows( + v2_owner_sessions: sessionmaker[Session], +) -> None: """A retained pre-12A report association stops the reshape unchanged.""" - database_url = disposable_v2_url() config = alembic_v2_config() - engine = create_engine(database_url) user_id = uuid4() model_id = uuid4() report_id = uuid4() - def reflected(name: str) -> sa.Table: - return sa.Table(name, sa.MetaData(), autoload_with=engine) - try: command.downgrade(config, STAGE_12A_PREVIOUS_REVISION) - with engine.begin() as connection: - connection.execute( - sa.insert(reflected("users")).values(id=user_id, primary_country="us") - ) - connection.execute( - sa.insert(reflected("tax_benefit_models")).values( - id=model_id, name=f"stage12a-{model_id.hex[:8]}" - ) + with v2_owner_sessions.begin() as session: + add_row(session, UserBeforeStage12A, id=user_id, primary_country="us") + add_row( + session, + TaxBenefitModelBeforeStage12A, + id=model_id, + name=f"stage12a-{model_id.hex[:8]}", ) - connection.execute( - sa.insert(reflected("reports")).values( - id=report_id, - label="Stage 12A retained report", - country="us", - tax_benefit_model_id=model_id, - inputs={}, - ) + add_row( + session, + ReportBeforeStage12A, + id=report_id, + label="Stage 12A retained report", + country="us", + tax_benefit_model_id=model_id, + inputs={}, ) - connection.execute( - sa.insert(reflected("user_report_associations")).values( - id=uuid4(), user_id=user_id, report_id=report_id, country="us" - ) + add_row( + session, + UserReportAssociationBeforeStage12A, + id=uuid4(), + user_id=user_id, + report_id=report_id, + country="us", ) - with pytest.raises(sa.exc.IntegrityError): + with pytest.raises(IntegrityError): command.upgrade(config, "head") - with engine.connect() as connection: - context = MigrationContext.configure(connection) - assert context.get_current_revision() == STAGE_12A_PREVIOUS_REVISION - _assert_pre_stage_12a_association_shape(engine) + _assert_revision(v2_owner_sessions, STAGE_12A_PREVIOUS_REVISION) + _assert_pre_stage_12a_association_shape(v2_owner_sessions) finally: - with engine.begin() as connection: - for table_name, row_id in ( - ("users", user_id), - ("reports", report_id), - ("tax_benefit_models", model_id), + with v2_owner_sessions.begin() as session: + for model, row_id in ( + (UserBeforeStage12A, user_id), + (ReportBeforeStage12A, report_id), + (TaxBenefitModelBeforeStage12A, model_id), ): - table = reflected(table_name) - connection.execute(sa.delete(table).where(table.c.id == row_id)) + session.execute(delete(model).where(model.id == row_id)) command.upgrade(config, "head") - engine.dispose() -def test_countries_revision_keeps_existing_rows_and_rejects_unlisted_countries() -> ( - None -): +def test_countries_revision_keeps_existing_rows_and_rejects_unlisted_countries( + v2_owner_sessions: sessionmaker[Session], +) -> None: """Rows saved before the revision survive it, and only listed countries pass.""" - database_url = disposable_v2_url() config = alembic_v2_config() - engine = create_engine(database_url) user_id = uuid4() - def reflected(name: str) -> sa.Table: - return sa.Table(name, sa.MetaData(), autoload_with=engine) - try: command.downgrade(config, COUNTRIES_PREVIOUS_REVISION) - with engine.begin() as connection: - connection.execute( - sa.insert(reflected("users")).values(id=user_id, primary_country="uk") - ) - connection.execute( - sa.insert(reflected("user_report_associations")).values( - id=uuid4(), - user_id=user_id, - country_id="uk", - legacy_report_id=7, - ) + with v2_owner_sessions.begin() as session: + add_row(session, UserAtStage12A, id=user_id, primary_country="uk") + add_row( + session, + UserReportAssociationAtStage12A, + id=uuid4(), + user_id=user_id, + country_id="uk", + legacy_report_id=7, ) command.upgrade(config, "head") command.check(config) - _assert_countries_shape(engine) - - with engine.connect() as connection: - stored_countries = connection.execute( - text( - "SELECT users.primary_country, " - "user_report_associations.country_id FROM users " - "JOIN user_report_associations " - "ON user_report_associations.user_id = users.id " - "WHERE users.id = :user_id" - ), - {"user_id": user_id}, + _assert_countries_shape(v2_owner_sessions) + + with v2_owner_sessions() as session: + stored_countries = session.execute( + select(col(User.primary_country), col(UserReportAssociation.country_id)) + .join( + UserReportAssociation, + col(UserReportAssociation.user_id) == col(User.id), + ) + .where(col(User.id) == user_id) ).one() assert tuple(stored_countries) == ("uk", "uk") - with engine.connect() as connection, pytest.raises(sa.exc.IntegrityError): - connection.execute( - sa.insert(reflected("user_report_associations")).values( - id=uuid4(), - user_id=user_id, - country_id="ca", - legacy_report_id=8, - ) + with v2_owner_sessions() as session, refused(session): + add_row( + session, + UserReportAssociation, + id=uuid4(), + user_id=user_id, + country_id="ca", + legacy_report_id=8, ) - with engine.connect() as connection, pytest.raises(sa.exc.IntegrityError): - connection.execute(text("DELETE FROM countries WHERE id = 'uk'")) + with v2_owner_sessions() as session, refused(session): + session.execute(delete(Country).where(col(Country.id) == "uk")) finally: - with engine.begin() as connection: - users = reflected("users") - connection.execute(sa.delete(users).where(users.c.id == user_id)) + with v2_owner_sessions.begin() as session: + session.execute(delete(UserAtStage12A).where(UserAtStage12A.id == user_id)) command.upgrade(config, "head") - engine.dispose() -def test_countries_downgrade_refuses_records_of_an_unlisted_country() -> None: +def test_countries_downgrade_refuses_records_of_an_unlisted_country( + v2_owner_sessions: sessionmaker[Session], +) -> None: """The restored US-and-UK checks stop a downgrade that would orphan records.""" - database_url = disposable_v2_url() config = alembic_v2_config() - engine = create_engine(database_url) user_id = uuid4() try: command.upgrade(config, "head") - with engine.begin() as connection: - connection.execute( - text( - "INSERT INTO countries " - "(id, household_enabled, society_wide_enabled) " - "VALUES ('be', true, false)" - ) - ) - connection.execute( - text("INSERT INTO users (id, primary_country) VALUES (:user_id, 'be')"), - {"user_id": user_id}, + with v2_owner_sessions.begin() as session: + add_row( + session, + Country, + id="be", + household_enabled=True, + society_wide_enabled=False, ) + add_row(session, User, id=user_id, primary_country="be") - with pytest.raises(sa.exc.IntegrityError): + with pytest.raises(IntegrityError): command.downgrade(config, COUNTRIES_PREVIOUS_REVISION) - with engine.connect() as connection: - context = MigrationContext.configure(connection) - assert context.get_current_revision() == V2_ALEMBIC_HEAD_REVISION + _assert_revision(v2_owner_sessions, V2_ALEMBIC_HEAD_REVISION) finally: - with engine.begin() as connection: - connection.execute( - text("DELETE FROM users WHERE id = :user_id"), {"user_id": user_id} - ) - connection.execute(text("DELETE FROM countries WHERE id = 'be'")) + with v2_owner_sessions.begin() as session: + session.execute(delete(User).where(col(User.id) == user_id)) + session.execute(delete(Country).where(col(Country.id) == "be")) command.upgrade(config, "head") - engine.dispose() -def test_a_household_only_country_row_lets_records_name_that_country() -> None: +def test_a_household_only_country_row_lets_records_name_that_country( + v2_owner_sessions: sessionmaker[Session], +) -> None: """Once a household-only country has a row, its records can be stored.""" - database_url = disposable_v2_url() config = alembic_v2_config() - engine = create_engine(database_url) user_id = uuid4() household_id = uuid4() - try: - command.upgrade(config, "head") - with engine.connect() as connection: - transaction = connection.begin() - try: - with pytest.raises(sa.exc.IntegrityError), connection.begin_nested(): - connection.execute( - text( - "INSERT INTO users (id, primary_country) " - "VALUES (:user_id, 'be')" - ), - {"user_id": user_id}, - ) - - connection.execute( - text( - "INSERT INTO countries " - "(id, household_enabled, society_wide_enabled) " - "VALUES ('be', true, false)" - ) - ) - connection.execute( - text( - "INSERT INTO users (id, primary_country) " - "VALUES (:user_id, 'be')" - ), - {"user_id": user_id}, - ) - connection.execute( - text( - "INSERT INTO households (id, country_id, household_data, " - "canonicalization_version, content_hash) VALUES " - "(:household_id, 'be', '{}'::jsonb, 1, :content_hash)" - ), - {"household_id": household_id, "content_hash": "c" * 64}, - ) - connection.execute( - text( - "INSERT INTO user_household_associations " - "(id, user_id, household_id, country_id) VALUES " - "(:association_id, :user_id, :household_id, 'be')" - ), - { - "association_id": uuid4(), - "user_id": user_id, - "household_id": household_id, - }, - ) + command.upgrade(config, "head") + with v2_owner_sessions() as session: + try: + with refused(session): + add_row(session, User, id=user_id, primary_country="be") + + add_row( + session, + Country, + id="be", + household_enabled=True, + society_wide_enabled=False, + ) + add_row(session, User, id=user_id, primary_country="be") + add_row( + session, + Household, + id=household_id, + country_id="be", + household_data={}, + canonicalization_version=1, + content_hash="c" * 64, + ) + add_row( + session, + UserHouseholdAssociation, + id=uuid4(), + user_id=user_id, + household_id=household_id, + country_id="be", + ) - with pytest.raises(sa.exc.IntegrityError), connection.begin_nested(): - connection.execute( - text( - "INSERT INTO countries " - "(id, household_enabled, society_wide_enabled) " - "VALUES ('xx', false, true)" - ) - ) - finally: - transaction.rollback() - finally: - engine.dispose() + with refused(session): + add_row( + session, + Country, + id="xx", + household_enabled=False, + society_wide_enabled=True, + ) + finally: + session.rollback() diff --git a/tests/integration/test_alembic_v2_saved_item_keys.py b/tests/integration/test_alembic_v2_saved_item_keys.py index ef00d5f6f..b46cda09e 100644 --- a/tests/integration/test_alembic_v2_saved_item_keys.py +++ b/tests/integration/test_alembic_v2_saved_item_keys.py @@ -10,26 +10,37 @@ from __future__ import annotations -from typing import TYPE_CHECKING -from uuid import uuid4 +from typing import TYPE_CHECKING, Any +from uuid import UUID, uuid4 import pytest from alembic import command -from sqlalchemy import create_engine, inspect, text +from sqlalchemy import delete from sqlalchemy.exc import IntegrityError - -from tests.fixtures.integration.alembic_v2 import alembic_v2_config, disposable_v2_url +from sqlmodel import col + +from policyengine_api.data.v2.models import ( + Report, + Simulation, + User, + UserReportAssociation, + UserSimulationAssociation, +) +from tests.fixtures.database_sessions import schema_inspector +from tests.fixtures.integration.alembic_v2 import alembic_v2_config +from tests.integration.alembic_version_rows import current_revision from tests.integration.simulation_rows import ( PublicApiRows, + add_row, insert_public_api_rows, - insert_row, refused, ) if TYPE_CHECKING: from collections.abc import Iterator - from sqlalchemy import Connection, Engine + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session SAVED_ITEM_KEYS_PREVIOUS_REVISION = "1356f658347d" SAVED_ITEM_KEYS_REVISION = "81b728a088e7" @@ -45,37 +56,41 @@ "simulations", ), } +# Each association table's mapped class. Neither table's columns change between +# the previous revision and the head. +SAVED_ITEM_MODELS: dict[str, type[Any]] = { + "user_report_associations": UserReportAssociation, + "user_simulation_associations": UserSimulationAssociation, +} @pytest.fixture -def engine() -> Iterator[Engine]: - """Yield an engine on a database at head, and leave it at head.""" +def sessions( + v2_owner_sessions: sessionmaker[Session], +) -> Iterator[sessionmaker[Session]]: + """Yield the owner's Session factories on a database at head; leave it at head.""" command.upgrade(alembic_v2_config(), "head") - database_engine = create_engine(disposable_v2_url()) try: - yield database_engine + yield v2_owner_sessions finally: command.upgrade(alembic_v2_config(), "head") - database_engine.dispose() @pytest.fixture -def connection(engine: Engine) -> Iterator[Connection]: - """Yield a connection at head whose writes are rolled back after the test.""" - command.upgrade(alembic_v2_config(), "head") - with engine.connect() as database_connection: - transaction = database_connection.begin() +def session(sessions: sessionmaker[Session]) -> Iterator[Session]: + """Yield a Session at head whose writes are rolled back after the test.""" + with sessions() as database_session: try: - yield database_connection + yield database_session finally: - transaction.rollback() + database_session.rollback() def _saved_item_keys( - engine: Engine, + sessions: sessionmaker[Session], ) -> dict[str, tuple[str | None, list[str], str, str | None]]: """Return each association table's keys to ``reports`` or ``simulations``.""" - inspector = inspect(engine) + inspector = schema_inspector(sessions) return { table_name: ( key["name"], @@ -89,18 +104,18 @@ def _saved_item_keys( } -def _insert_user(connection: Connection) -> object: +def _insert_user(session: Session) -> UUID: """Store a standard user, which needs a primary country.""" user_id = uuid4() - insert_row(connection, "users", id=user_id, primary_country="us") + add_row(session, User, id=user_id, primary_country="us") return user_id -def _insert_simulation(connection: Connection, rows: PublicApiRows) -> object: +def _insert_simulation(session: Session, rows: PublicApiRows) -> UUID: simulation_id = uuid4() - insert_row( - connection, - "simulations", + add_row( + session, + Simulation, id=simulation_id, simulation_type="economy", dataset_id=rows.dataset_id, @@ -110,86 +125,78 @@ def _insert_simulation(connection: Connection, rows: PublicApiRows) -> object: return simulation_id -def _insert_report(connection: Connection, rows: PublicApiRows) -> object: +def _insert_report(session: Session, rows: PublicApiRows) -> UUID: report_id = uuid4() - insert_row( - connection, - "reports", + add_row( + session, + Report, id=report_id, label="Saved report", country="us", tax_benefit_model_id=rows.model_id, - inputs="{}", + inputs={}, ) return report_id def _save( - connection: Connection, table_name: str, user_id: object, **reference: object -) -> None: - insert_row( - connection, - table_name, - id=uuid4(), + session: Session, model: type[Any], user_id: UUID, **reference: object +) -> UUID: + saved_item_id = uuid4() + add_row( + session, + model, + id=saved_item_id, user_id=user_id, country_id="us", **reference, ) + return saved_item_id def test_a_saved_item_must_name_a_stored_report_or_simulation( - connection: Connection, + session: Session, ) -> None: - rows = insert_public_api_rows(connection) - user_id = _insert_user(connection) - report_id = _insert_report(connection, rows) - simulation_id = _insert_simulation(connection, rows) - - with refused(connection, IntegrityError, match="fk_user_report_associations"): - _save(connection, "user_report_associations", user_id, report_id=uuid4()) - with refused(connection, IntegrityError, match="fk_user_simulation_associations"): - _save( - connection, "user_simulation_associations", user_id, simulation_id=uuid4() - ) - - _save(connection, "user_report_associations", user_id, report_id=report_id) - _save( - connection, "user_simulation_associations", user_id, simulation_id=simulation_id - ) + rows = insert_public_api_rows(session) + user_id = _insert_user(session) + report_id = _insert_report(session, rows) + simulation_id = _insert_simulation(session, rows) + + with refused(session, IntegrityError, match="fk_user_report_associations"): + _save(session, UserReportAssociation, user_id, report_id=uuid4()) + with refused(session, IntegrityError, match="fk_user_simulation_associations"): + _save(session, UserSimulationAssociation, user_id, simulation_id=uuid4()) + + _save(session, UserReportAssociation, user_id, report_id=report_id) + _save(session, UserSimulationAssociation, user_id, simulation_id=simulation_id) # A saved item that names only its v1 report or simulation is unaffected. - _save(connection, "user_report_associations", user_id, legacy_report_id=42) - _save(connection, "user_simulation_associations", user_id, legacy_simulation_id=42) + _save(session, UserReportAssociation, user_id, legacy_report_id=42) + _save(session, UserSimulationAssociation, user_id, legacy_simulation_id=42) def test_a_report_or_simulation_a_saved_item_names_cannot_be_deleted( - connection: Connection, + session: Session, ) -> None: - rows = insert_public_api_rows(connection) - user_id = _insert_user(connection) - report_id = _insert_report(connection, rows) - simulation_id = _insert_simulation(connection, rows) - _save(connection, "user_report_associations", user_id, report_id=report_id) - _save( - connection, "user_simulation_associations", user_id, simulation_id=simulation_id - ) + rows = insert_public_api_rows(session) + user_id = _insert_user(session) + report_id = _insert_report(session, rows) + simulation_id = _insert_simulation(session, rows) + _save(session, UserReportAssociation, user_id, report_id=report_id) + _save(session, UserSimulationAssociation, user_id, simulation_id=simulation_id) - with refused(connection, IntegrityError, match="fk_user_report_associations"): - connection.execute( - text("DELETE FROM reports WHERE id = :id"), {"id": report_id} - ) - with refused(connection, IntegrityError, match="fk_user_simulation_associations"): - connection.execute( - text("DELETE FROM simulations WHERE id = :id"), {"id": simulation_id} - ) + with refused(session, IntegrityError, match="fk_user_report_associations"): + session.execute(delete(Report).where(col(Report.id) == report_id)) + with refused(session, IntegrityError, match="fk_user_simulation_associations"): + session.execute(delete(Simulation).where(col(Simulation.id) == simulation_id)) def test_the_revision_adds_the_keys_and_drops_them_on_downgrade( - engine: Engine, + sessions: sessionmaker[Session], ) -> None: config = alembic_v2_config() command.downgrade(config, SAVED_ITEM_KEYS_PREVIOUS_REVISION) command.upgrade(config, SAVED_ITEM_KEYS_REVISION) - assert _saved_item_keys(engine) == { + assert _saved_item_keys(sessions) == { table_name: (key_name, [column_name], referred_table, "RESTRICT") for table_name, ( key_name, @@ -199,23 +206,14 @@ def test_the_revision_adds_the_keys_and_drops_them_on_downgrade( } command.downgrade(config, SAVED_ITEM_KEYS_PREVIOUS_REVISION) - assert _saved_item_keys(engine) == {} + assert _saved_item_keys(sessions) == {} command.upgrade(config, SAVED_ITEM_KEYS_REVISION) - assert set(_saved_item_keys(engine)) == set(SAVED_ITEM_KEYS) + assert set(_saved_item_keys(sessions)) == set(SAVED_ITEM_KEYS) command.upgrade(config, "head") command.check(config) -def _current_revision(engine: Engine) -> str: - with engine.connect() as connection: - return str( - connection.execute( - text("SELECT version_num FROM alembic_version") - ).scalar_one() - ) - - @pytest.mark.parametrize( ("table_name", "reference"), [ @@ -224,7 +222,7 @@ def _current_revision(engine: Engine) -> str: ], ) def test_the_upgrade_fails_changing_nothing_while_a_saved_item_names_a_missing_row( - engine: Engine, table_name: str, reference: dict[str, object] + sessions: sessionmaker[Session], table_name: str, reference: dict[str, object] ) -> None: """Adding a key checks every existing row, so the upgrade fails and stays put. @@ -233,28 +231,17 @@ def test_the_upgrade_fails_changing_nothing_while_a_saved_item_names_a_missing_r leaving the database at the parent revision with no new key. """ config = alembic_v2_config() + model = SAVED_ITEM_MODELS[table_name] command.downgrade(config, SAVED_ITEM_KEYS_PREVIOUS_REVISION) - saved_item_id = uuid4() - with engine.begin() as connection: - user_id = _insert_user(connection) - insert_row( - connection, - table_name, - id=saved_item_id, - user_id=user_id, - country_id="us", - **reference, - ) + with sessions.begin() as session: + user_id = _insert_user(session) + saved_item_id = _save(session, model, user_id, **reference) try: with pytest.raises(IntegrityError, match=SAVED_ITEM_KEYS[table_name][0]): command.upgrade(config, SAVED_ITEM_KEYS_REVISION) - assert _current_revision(engine) == SAVED_ITEM_KEYS_PREVIOUS_REVISION - assert _saved_item_keys(engine) == {} + assert current_revision(sessions) == SAVED_ITEM_KEYS_PREVIOUS_REVISION + assert _saved_item_keys(sessions) == {} finally: - with engine.begin() as connection: - connection.execute( - text(f"DELETE FROM {table_name} WHERE id = :id"), {"id": saved_item_id} - ) - connection.execute( - text("DELETE FROM users WHERE id = :id"), {"id": user_id} - ) + with sessions.begin() as session: + session.execute(delete(model).where(col(model.id) == saved_item_id)) + session.execute(delete(User).where(col(User.id) == user_id)) diff --git a/tests/integration/test_alembic_v2_shared_report_keys.py b/tests/integration/test_alembic_v2_shared_report_keys.py index 7b3562bf0..271bf38e6 100644 --- a/tests/integration/test_alembic_v2_shared_report_keys.py +++ b/tests/integration/test_alembic_v2_shared_report_keys.py @@ -19,15 +19,17 @@ import pytest from alembic import command -from sqlalchemy import create_engine, inspect from sqlalchemy.dialects import postgresql -from tests.fixtures.integration.alembic_v2 import alembic_v2_config, disposable_v2_url +from tests.fixtures.database_sessions import schema_inspector +from tests.fixtures.integration.alembic_v2 import alembic_v2_config if TYPE_CHECKING: from collections.abc import Iterator - from sqlalchemy import Engine + from sqlalchemy.engine import Inspector + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session SHARED_REPORTS_PREVIOUS_REVISION = "1e1e3f079f2c" SHARED_REPORTS_REVISION = "94dc43079186" @@ -49,19 +51,24 @@ @pytest.fixture -def engine() -> Iterator[Engine]: - """Yield an engine on the disposable database, and leave it at head.""" - database_engine = create_engine(disposable_v2_url()) +def sessions( + v2_owner_sessions: sessionmaker[Session], +) -> Iterator[sessionmaker[Session]]: + """Yield the disposable database owner's Session factories; leave it at head.""" try: - yield database_engine + yield v2_owner_sessions finally: command.upgrade(alembic_v2_config(), "head") - database_engine.dispose() -def _schema_shape(engine: Engine) -> dict[str, dict[str, Any]]: +def _schema_shape(sessions: sessionmaker[Session]) -> dict[str, dict[str, Any]]: """Reflect every table's columns, keys, indexes (with conditions) and checks.""" - inspector = inspect(engine) + with sessions() as session: + return _reflected_shape(schema_inspector(session)) + + +def _reflected_shape(inspector: Inspector) -> dict[str, dict[str, Any]]: + """Describe each public table but Alembic's own, as the Inspector reads it.""" return { table_name: { "columns": { @@ -138,14 +145,14 @@ def _added( def test_shared_reports_revision_changes_only_its_tables_and_downgrades_exactly( - engine: Engine, + sessions: sessionmaker[Session], ) -> None: config = alembic_v2_config() command.upgrade(config, "head") command.downgrade(config, SHARED_REPORTS_PREVIOUS_REVISION) - parent = _schema_shape(engine) + parent = _schema_shape(sessions) command.upgrade(config, SHARED_REPORTS_REVISION) - revision = _schema_shape(engine) + revision = _schema_shape(sessions) assert set(revision) - set(parent) == {"user_report_run_associations"} assert sorted( @@ -309,4 +316,4 @@ def test_shared_reports_revision_changes_only_its_tables_and_downgrades_exactly( assert set(records["checks"]) == {"ck_user_report_run_associations_trigger"} command.downgrade(config, SHARED_REPORTS_PREVIOUS_REVISION) - assert _schema_shape(engine) == full_parent + assert _schema_shape(sessions) == full_parent diff --git a/tests/integration/test_alembic_v2_simulation_runs.py b/tests/integration/test_alembic_v2_simulation_runs.py index f70d2fe22..48004685f 100644 --- a/tests/integration/test_alembic_v2_simulation_runs.py +++ b/tests/integration/test_alembic_v2_simulation_runs.py @@ -15,33 +15,49 @@ from __future__ import annotations -import os -from typing import TYPE_CHECKING -from uuid import uuid4 +from datetime import UTC, datetime +from typing import TYPE_CHECKING, Any +from uuid import UUID, uuid4 import pytest from alembic import command from alembic.config import Config -from sqlalchemy import create_engine, inspect, text +from sqlalchemy import delete, func, select, update +from sqlalchemy.dialects.postgresql.base import PGInspector +from sqlmodel import col from policyengine_api.constants import REPO -from policyengine_api.data.v2.migration_target import ( - V2_ALEMBIC_DISPOSABLE_TEST, - load_v2_alembic_settings, +from policyengine_api.data.v2.models import ( + BudgetSummary, + BudgetWindowRun, + ConstituencyImpact, + DecileImpact, + HouseholdJob, + LaborSupplyDecileResponse, + LaborSupplyResponse, + Poverty, + ProgramStatistics, + Report, + ReportRun, + Simulation, + SimulationRun, ) -from policyengine_api.data.v2.settings import V2_MIGRATION_DATABASE_URL +from tests.fixtures.database_sessions import schema_inspector +from tests.fixtures.integration.alembic_v2 import table_columns from tests.integration.simulation_rows import ( RUN_VERSIONS, PublicApiRows, + add_row, insert_public_api_rows, - insert_row, refused, ) if TYPE_CHECKING: from collections.abc import Iterator - from sqlalchemy import Connection, Engine + from sqlalchemy.engine import Inspector + from sqlalchemy.orm import Mapped, sessionmaker + from sqlmodel import Session # The catalog pruning revision, the simulation runs revision's parent. SIMULATION_RUNS_PREVIOUS_REVISION = "334859ef4fec" @@ -129,22 +145,7 @@ "weekly_hours_substitution_effect", ) SHA256_HEX = "a" * 64 -COMPLETED_AT = "2026-11-04T00:00:00Z" - - -def _disposable_url() -> str: - database_url = os.environ.get(V2_MIGRATION_DATABASE_URL, "") - if not database_url: - pytest.skip(f"{V2_MIGRATION_DATABASE_URL} is not set") - settings = load_v2_alembic_settings( - { - V2_MIGRATION_DATABASE_URL: database_url, - V2_ALEMBIC_DISPOSABLE_TEST: os.environ.get(V2_ALEMBIC_DISPOSABLE_TEST, ""), - } - ) - if not settings.disposable_test: - pytest.fail("v2 lifecycle tests require disposable-test mode") - return settings.url.render_as_string(hide_password=False) +COMPLETED_AT = datetime(2026, 11, 4, tzinfo=UTC) @pytest.fixture @@ -153,30 +154,29 @@ def config() -> Config: @pytest.fixture -def engine(config: Config) -> Iterator[Engine]: - database_engine = create_engine(_disposable_url()) +def sessions( + config: Config, v2_owner_sessions: sessionmaker[Session] +) -> Iterator[sessionmaker[Session]]: + """Yield the disposable database owner's Session factories; leave it at head.""" try: - yield database_engine + yield v2_owner_sessions finally: command.upgrade(config, "head") - database_engine.dispose() @pytest.fixture -def connection(config: Config, engine: Engine) -> Iterator[Connection]: - """Yield a connection at head whose writes are rolled back after the test.""" +def session(config: Config, sessions: sessionmaker[Session]) -> Iterator[Session]: + """Yield a Session at head whose writes are rolled back after the test.""" command.upgrade(config, "head") - with engine.connect() as database_connection: - transaction = database_connection.begin() + with sessions() as database_session: try: - yield database_connection + yield database_session finally: - transaction.rollback() + database_session.rollback() -def _table_shape(engine: Engine, table_name: str) -> dict[str, object]: +def _table_shape(inspector: Inspector, table_name: str) -> dict[str, object]: """Describe one table's columns, keys, indexes and checks for comparison.""" - inspector = inspect(engine) return { "columns": [ (column["name"], str(column["type"]), column["nullable"], column["default"]) @@ -184,69 +184,66 @@ def _table_shape(engine: Engine, table_name: str) -> dict[str, object]: ], "primary_key": inspector.get_pk_constraint(table_name), "foreign_keys": sorted( - inspector.get_foreign_keys(table_name), key=lambda key: key["name"] + inspector.get_foreign_keys(table_name), key=lambda key: str(key["name"]) ), "indexes": sorted( - inspector.get_indexes(table_name), key=lambda index: index["name"] + inspector.get_indexes(table_name), key=lambda index: str(index["name"]) ), "unique_constraints": sorted( inspector.get_unique_constraints(table_name), - key=lambda constraint: constraint["name"], + key=lambda constraint: str(constraint["name"]), ), "check_constraints": sorted( inspector.get_check_constraints(table_name), - key=lambda constraint: constraint["name"], + key=lambda constraint: str(constraint["name"]), ), } -def _shapes(engine: Engine) -> dict[str, dict[str, object]]: - return { - table_name: _table_shape(engine, table_name) - for table_name in inspect(engine).get_table_names(schema="public") - } +def _shapes(sessions: sessionmaker[Session]) -> dict[str, dict[str, object]]: + with sessions() as session: + inspector = schema_inspector(session) + return { + table_name: _table_shape(inspector, table_name) + for table_name in inspector.get_table_names(schema="public") + } -def _column_names(engine: Engine, table_name: str) -> set[str]: - return {column["name"] for column in inspect(engine).get_columns(table_name)} +def _column_names(sessions: sessionmaker[Session], table_name: str) -> set[str]: + return set(table_columns(sessions, table_name)) -def _enum_type_names(engine: Engine) -> set[str]: - with engine.connect() as type_connection: - return set( - type_connection.execute( - text("SELECT typname FROM pg_type WHERE typtype = 'e'") - ).scalars() - ) +def _enum_type_names(sessions: sessionmaker[Session]) -> set[str]: + """Return the name of every enum type, in every schema.""" + inspector = schema_inspector(sessions) + assert isinstance(inspector, PGInspector) + return {enum_type["name"] for enum_type in inspector.get_enums(schema="*")} def test_the_revision_downgrades_to_its_parent_and_upgrades_again( - config: Config, engine: Engine + config: Config, sessions: sessionmaker[Session] ) -> None: """The revision adds its tables and changes only simulation-side tables.""" command.upgrade(config, "head") command.downgrade(config, SIMULATION_RUNS_PREVIOUS_REVISION) - before = _shapes(engine) + before = _shapes(sessions) assert NEW_TABLES.isdisjoint(before) assert {"status", "household_result", "output_dataset_id"} <= _column_names( - engine, "simulations" + sessions, "simulations" ) - assert {"report_run_id", "simulation_id"} <= _column_names(engine, "poverty") + assert {"report_run_id", "simulation_id"} <= _column_names(sessions, "poverty") assert {"datasets", "households", "policies"} <= { - key["referred_table"] for key in inspect(engine).get_foreign_keys("simulations") + key["referred_table"] + for key in schema_inspector(sessions).get_foreign_keys("simulations") } - program_entity = next( - column - for column in inspect(engine).get_columns("program_statistics") - if column["name"] == "entity" - ) + program_entity = table_columns(sessions, "program_statistics")["entity"] assert not program_entity["nullable"] - assert "v2_simulation_status" in _enum_type_names(engine) + assert "v2_simulation_status" in _enum_type_names(sessions) # Upgrade to this revision alone: later revisions change other tables. command.upgrade(config, SIMULATION_RUNS_REVISION) - after = _shapes(engine) + after = _shapes(sessions) command.upgrade(config, "head") command.check(config) assert set(after) - set(before) == NEW_TABLES @@ -256,16 +253,16 @@ def test_the_revision_downgrades_to_its_parent_and_upgrades_again( } assert changed == CHANGED_TABLES assert {"baseline_simulation_run_id", "reform_simulation_run_id"} <= ( - _column_names(engine, "report_runs") + _column_names(sessions, "report_runs") ) def test_head_keeps_the_foreign_keys_to_the_public_api_tables( - config: Config, engine: Engine + config: Config, sessions: sessionmaker[Session] ) -> None: """Each service writes only its own tables; the keys between them stay.""" command.upgrade(config, "head") - inspector = inspect(engine) + inspector = schema_inspector(sessions) public_api_keys = { (table_name, column_name): (key["referred_table"], key["options"]["ondelete"]) @@ -281,26 +278,22 @@ def test_head_keeps_the_foreign_keys_to_the_public_api_tables( } -def _count(connection: Connection, table: str, column: str, value: object) -> int: - return connection.execute( - text(f"SELECT count(*) FROM {table} WHERE {column} = :value"), - {"value": value}, - ).scalar_one() +def _count(session: Session, column: Mapped[Any], value: object) -> int: + """Count the rows whose ``column`` holds ``value``.""" + return session.scalars(select(func.count()).where(column == value)).one() @pytest.fixture -def public_api_rows(connection: Connection) -> PublicApiRows: - return insert_public_api_rows(connection) +def public_api_rows(session: Session) -> PublicApiRows: + return insert_public_api_rows(session) -def _insert_simulation( - connection: Connection, public_api_rows: PublicApiRows -) -> object: +def _insert_simulation(session: Session, public_api_rows: PublicApiRows) -> UUID: """Store an economy simulation of the stored dataset and catalog version.""" simulation_id = uuid4() - insert_row( - connection, - "simulations", + add_row( + session, + Simulation, id=simulation_id, simulation_type="economy", dataset_id=public_api_rows.dataset_id, @@ -311,22 +304,23 @@ def _insert_simulation( def _insert_simulation_run( - connection: Connection, - simulation_id: object, + session: Session, + simulation_id: UUID, *, status: str = "pending", year: int = 2026, **values: object, -) -> object: +) -> UUID: """Store a run of the simulation for ``year`` on its catalog version.""" run_id = uuid4() - version_id = connection.execute( - text("SELECT tax_benefit_model_version_id FROM simulations WHERE id = :id"), - {"id": simulation_id}, - ).scalar_one() - insert_row( - connection, - "simulation_runs", + version_id = session.scalars( + select(col(Simulation.tax_benefit_model_version_id)).where( + col(Simulation.id) == simulation_id + ) + ).one() + add_row( + session, + SimulationRun, id=run_id, simulation_id=simulation_id, tax_benefit_model_version_id=version_id, @@ -339,25 +333,25 @@ def _insert_simulation_run( def _insert_report_run( - connection: Connection, + session: Session, public_api_rows: PublicApiRows, - baseline_run_id: object, - reform_run_id: object | None = None, -) -> object: + baseline_run_id: UUID | None, + reform_run_id: UUID | None = None, +) -> UUID: """Store a report and one run of it comparing the two simulation runs.""" report_id, report_run_id = uuid4(), uuid4() - insert_row( - connection, - "reports", + add_row( + session, + Report, id=report_id, label="Report", country="us", tax_benefit_model_id=public_api_rows.model_id, - inputs="{}", + inputs={}, ) - insert_row( - connection, - "report_runs", + add_row( + session, + ReportRun, id=report_run_id, report_id=report_id, baseline_simulation_run_id=baseline_run_id, @@ -369,16 +363,28 @@ def _insert_report_run( return report_run_id +def _update_simulation_run(session: Session, run_id: UUID, **values: object) -> None: + session.execute( + update(SimulationRun).where(col(SimulationRun.id) == run_id).values(**values) + ) + + +def _update_report_run(session: Session, report_run_id: UUID, **values: object) -> None: + session.execute( + update(ReportRun).where(col(ReportRun.id) == report_run_id).values(**values) + ) + + def test_rows_naming_a_missing_public_api_row_are_refused( - connection: Connection, public_api_rows: PublicApiRows + session: Session, public_api_rows: PublicApiRows ) -> None: """PostgreSQL checks each row a simulation-side row names when it is written.""" - simulation_id = _insert_simulation(connection, public_api_rows) + simulation_id = _insert_simulation(session, public_api_rows) - with refused(connection, match="foreign key constraint"): - insert_row( - connection, - "simulation_runs", + with refused(session, match="foreign key constraint"): + add_row( + session, + SimulationRun, id=uuid4(), simulation_id=simulation_id, tax_benefit_model_version_id=uuid4(), @@ -386,15 +392,15 @@ def test_rows_naming_a_missing_public_api_row_are_refused( year=2026, **RUN_VERSIONS, ) - with refused(connection, match="foreign key constraint"): - insert_row( - connection, - "household_jobs", + with refused(session, match="foreign key constraint"): + add_row( + session, + HouseholdJob, id=uuid4(), country="us", household_id=uuid4(), year=2026, - request_data="{}", + request_data={}, tax_benefit_model_version_id=public_api_rows.version_id, status="pending", **RUN_VERSIONS, @@ -402,104 +408,97 @@ def test_rows_naming_a_missing_public_api_row_are_refused( def test_simulation_runs_need_a_completion_time_and_a_whole_output( - connection: Connection, public_api_rows: PublicApiRows + session: Session, public_api_rows: PublicApiRows ) -> None: - simulation_id = _insert_simulation(connection, public_api_rows) - run_id = _insert_simulation_run(connection, simulation_id) + simulation_id = _insert_simulation(session, public_api_rows) + run_id = _insert_simulation_run(session, simulation_id) - with refused(connection): - connection.execute( - text("UPDATE simulation_runs SET status = 'succeeded' WHERE id = :id"), - {"id": run_id}, - ) + with refused(session): + _update_simulation_run(session, run_id, status="succeeded") # Named, since a second unfailed run on the same versions is refused too. - with refused(connection, match="ck_simulation_runs_output_pair"): + with refused(session, match="ck_simulation_runs_output_pair"): _insert_simulation_run( - connection, simulation_id, output_uri="gs://bucket/run.parquet" + session, simulation_id, output_uri="gs://bucket/run.parquet" ) - with refused(connection, match="ck_simulation_runs_output_sha256_length"): + with refused(session, match="ck_simulation_runs_output_sha256_length"): _insert_simulation_run( - connection, + session, simulation_id, output_uri="gs://bucket/run.parquet", output_sha256="short", ) # A simulation has one unfailed run per version set, so the run finishes. - connection.execute( - text( - "UPDATE simulation_runs SET status = 'succeeded', " - "completed_at = :completed_at, output_uri = 'gs://bucket/run.parquet', " - "output_sha256 = :output_sha256 WHERE id = :id" - ), - {"id": run_id, "completed_at": COMPLETED_AT, "output_sha256": SHA256_HEX}, - ) - insert_row( - connection, - "poverty", + _update_simulation_run( + session, + run_id, + status="succeeded", + completed_at=COMPLETED_AT, + output_uri="gs://bucket/run.parquet", + output_sha256=SHA256_HEX, + ) + add_row( + session, + Poverty, id=uuid4(), simulation_run_id=run_id, poverty_type="spm", entity="person", ) - connection.execute( - text("DELETE FROM simulations WHERE id = :id"), {"id": simulation_id} - ) - assert _count(connection, "simulation_runs", "simulation_id", simulation_id) == 0 - assert _count(connection, "poverty", "simulation_run_id", run_id) == 0 + session.execute(delete(Simulation).where(col(Simulation.id) == simulation_id)) + assert _count(session, col(SimulationRun.simulation_id), simulation_id) == 0 + assert _count(session, col(Poverty.simulation_run_id), run_id) == 0 def test_report_runs_name_a_baseline_run_and_keep_their_simulation_runs( - connection: Connection, public_api_rows: PublicApiRows + session: Session, public_api_rows: PublicApiRows ) -> None: baseline_run_id = _insert_simulation_run( - connection, _insert_simulation(connection, public_api_rows) + session, _insert_simulation(session, public_api_rows) ) reform_run_id = _insert_simulation_run( - connection, _insert_simulation(connection, public_api_rows) + session, _insert_simulation(session, public_api_rows) ) - with refused(connection, match="baseline_simulation_run_id"): - _insert_report_run(connection, public_api_rows, None) - with refused(connection, match="foreign key constraint"): - _insert_report_run(connection, public_api_rows, uuid4()) + with refused(session, match="baseline_simulation_run_id"): + _insert_report_run(session, public_api_rows, None) + with refused(session, match="foreign key constraint"): + _insert_report_run(session, public_api_rows, uuid4()) # A household report with only a baseline names no reform run. - _insert_report_run(connection, public_api_rows, baseline_run_id) + _insert_report_run(session, public_api_rows, baseline_run_id) report_run_id = _insert_report_run( - connection, public_api_rows, baseline_run_id, reform_run_id + session, public_api_rows, baseline_run_id, reform_run_id ) for run_id in (baseline_run_id, reform_run_id): - with refused(connection, match="foreign key constraint"): - connection.execute( - text("DELETE FROM simulation_runs WHERE id = :id"), {"id": run_id} + with refused(session, match="foreign key constraint"): + session.execute( + delete(SimulationRun).where(col(SimulationRun.id) == run_id) ) - connection.execute( - text("DELETE FROM report_runs WHERE id = :id"), {"id": report_run_id} - ) - assert _count(connection, "simulation_runs", "id", reform_run_id) == 1 + session.execute(delete(ReportRun).where(col(ReportRun.id) == report_run_id)) + assert _count(session, col(SimulationRun.id), reform_run_id) == 1 def test_results_are_unique_per_run_and_name_runs_that_exist( - connection: Connection, public_api_rows: PublicApiRows + session: Session, public_api_rows: PublicApiRows ) -> None: baseline_run_id = _insert_simulation_run( - connection, _insert_simulation(connection, public_api_rows) + session, _insert_simulation(session, public_api_rows) ) reform_run_id = _insert_simulation_run( - connection, _insert_simulation(connection, public_api_rows) + session, _insert_simulation(session, public_api_rows) ) comparison_runs = { "report_run_id": _insert_report_run( - connection, public_api_rows, baseline_run_id, reform_run_id + session, public_api_rows, baseline_run_id, reform_run_id ), "baseline_simulation_run_id": baseline_run_id, "reform_simulation_run_id": reform_run_id, } - with refused(connection): - insert_row( - connection, - "budget_summary", + with refused(session): + add_row( + session, + BudgetSummary, id=uuid4(), variable_name="household_net_income", entity="household", @@ -510,13 +509,13 @@ def test_results_are_unique_per_run_and_name_runs_that_exist( "poverty_type": "spm", "entity": "person", } - insert_row(connection, "poverty", id=uuid4(), **poverty) - with refused(connection): - insert_row(connection, "poverty", id=uuid4(), **poverty) + add_row(session, Poverty, id=uuid4(), **poverty) + with refused(session): + add_row(session, Poverty, id=uuid4(), **poverty) for group in ("child", "adult"): - insert_row( - connection, - "poverty", + add_row( + session, + Poverty, id=uuid4(), filter_variable="age", filter_group=group, @@ -529,38 +528,38 @@ def test_results_are_unique_per_run_and_name_runs_that_exist( "quantiles": 10, **comparison_runs, } - insert_row(connection, "decile_impacts", id=uuid4(), **decile) - insert_row( - connection, - "decile_impacts", + add_row(session, DecileImpact, id=uuid4(), **decile) + add_row( + session, + DecileImpact, id=uuid4(), decile_variable="household_wealth_decile", **decile, ) - with refused(connection): - insert_row(connection, "decile_impacts", id=uuid4(), **decile) + with refused(session): + add_row(session, DecileImpact, id=uuid4(), **decile) budget = {"variable_name": "household_tax", "entity": "household"} - insert_row(connection, "budget_summary", id=uuid4(), **budget, **comparison_runs) + add_row(session, BudgetSummary, id=uuid4(), **budget, **comparison_runs) # A report run compares one pair, so its rows are unique within it. - with refused(connection): - insert_row( - connection, - "budget_summary", + with refused(session): + add_row( + session, + BudgetSummary, id=uuid4(), **budget, **{**comparison_runs, "reform_simulation_run_id": baseline_run_id}, ) - insert_row( - connection, - "program_statistics", + add_row( + session, + ProgramStatistics, id=uuid4(), program_name="income_tax", **comparison_runs, ) - with refused(connection): - insert_row( - connection, - "program_statistics", + with refused(session): + add_row( + session, + ProgramStatistics, id=uuid4(), program_name="income_tax", **comparison_runs, @@ -572,18 +571,18 @@ def test_results_are_unique_per_run_and_name_runs_that_exist( "population": 100.0, **comparison_runs, } - insert_row( - connection, - "constituency_impacts", + add_row( + session, + ConstituencyImpact, id=uuid4(), constituency_code="E14000530", disclosure_tier="approximate", **constituency, ) - with refused(connection): - insert_row( - connection, - "constituency_impacts", + with refused(session): + add_row( + session, + ConstituencyImpact, id=uuid4(), constituency_code="E14000531", disclosure_tier="withheld", @@ -592,48 +591,44 @@ def test_results_are_unique_per_run_and_name_runs_that_exist( def test_a_report_runs_labor_supply_and_cliff_impact_are_typed( - connection: Connection, public_api_rows: PublicApiRows + session: Session, public_api_rows: PublicApiRows ) -> None: report_run_id = _insert_report_run( - connection, + session, public_api_rows, - _insert_simulation_run( - connection, _insert_simulation(connection, public_api_rows) - ), - _insert_simulation_run( - connection, _insert_simulation(connection, public_api_rows) - ), + _insert_simulation_run(session, _insert_simulation(session, public_api_rows)), + _insert_simulation_run(session, _insert_simulation(session, public_api_rows)), ) response = dict.fromkeys(LABOR_SUPPLY_RESPONSE_COLUMNS, 1.0) - insert_row( - connection, - "labor_supply_responses", + add_row( + session, + LaborSupplyResponse, id=uuid4(), report_run_id=report_run_id, **response, ) - with refused(connection): - insert_row( - connection, - "labor_supply_responses", + with refused(session): + add_row( + session, + LaborSupplyResponse, id=uuid4(), report_run_id=report_run_id, **response, ) # .py reports a relative response only for deciles above zero. - insert_row( - connection, - "labor_supply_decile_responses", + add_row( + session, + LaborSupplyDecileResponse, id=uuid4(), report_run_id=report_run_id, decile=0, average_income_effect=-1.0, average_substitution_effect=2.0, ) - insert_row( - connection, - "labor_supply_decile_responses", + add_row( + session, + LaborSupplyDecileResponse, id=uuid4(), report_run_id=report_run_id, decile=1, @@ -642,65 +637,65 @@ def test_a_report_runs_labor_supply_and_cliff_impact_are_typed( relative_income_effect=-0.01, relative_substitution_effect=0.02, ) - with refused(connection): - insert_row( - connection, - "labor_supply_decile_responses", + with refused(session): + add_row( + session, + LaborSupplyDecileResponse, id=uuid4(), report_run_id=report_run_id, decile=1, ) - with refused(connection, match="ck_report_runs_cliff_impact_complete"): - connection.execute( - text("UPDATE report_runs SET baseline_cliff_gap = 1.0 WHERE id = :id"), - {"id": report_run_id}, + with refused(session, match="ck_report_runs_cliff_impact_complete"): + _update_report_run(session, report_run_id, baseline_cliff_gap=1.0) + _update_report_run( + session, + report_run_id, + baseline_cliff_gap=1.0, + baseline_cliff_share=0.1, + reform_cliff_gap=2.0, + reform_cliff_share=0.2, + data_version="1.0.0", + spm_provenance={"source": "census"}, + ) + receipt_type = session.scalars( + select(func.jsonb_typeof(col(ReportRun.spm_provenance))).where( + col(ReportRun.id) == report_run_id ) - connection.execute( - text( - "UPDATE report_runs SET baseline_cliff_gap = 1.0, " - "baseline_cliff_share = 0.1, reform_cliff_gap = 2.0, " - "reform_cliff_share = 0.2, data_version = '1.0.0', " - "spm_provenance = CAST(:receipt AS jsonb) WHERE id = :id" - ), - {"id": report_run_id, "receipt": '{"source": "census"}'}, - ) - receipt_type = connection.execute( - text("SELECT jsonb_typeof(spm_provenance) FROM report_runs WHERE id = :id"), - {"id": report_run_id}, - ).scalar_one() + ).one() assert receipt_type == "object" - connection.execute( - text("DELETE FROM report_runs WHERE id = :id"), {"id": report_run_id} - ) - for table in ("labor_supply_responses", "labor_supply_decile_responses"): - assert _count(connection, table, "report_run_id", report_run_id) == 0 + session.execute(delete(ReportRun).where(col(ReportRun.id) == report_run_id)) + for report_run_column in ( + col(LaborSupplyResponse.report_run_id), + col(LaborSupplyDecileResponse.report_run_id), + ): + assert _count(session, report_run_column, report_run_id) == 0 def _insert_report( - connection: Connection, public_api_rows: PublicApiRows, **values: object -) -> object: + session: Session, public_api_rows: PublicApiRows, **values: object +) -> UUID: report_id = uuid4() - insert_row( - connection, - "reports", + add_row( + session, + Report, id=report_id, label="Budget window", country="us", tax_benefit_model_id=public_api_rows.model_id, - inputs="{}", + inputs={}, **values, ) return report_id def _insert_budget_window_run( - connection: Connection, public_api_rows: PublicApiRows, report_id: object -) -> object: + session: Session, public_api_rows: PublicApiRows, report_id: UUID +) -> UUID: window_run_id = uuid4() - insert_row( - connection, - "budget_window_runs", + add_row( + session, + BudgetWindowRun, id=window_run_id, report_id=report_id, tax_benefit_model_version_id=public_api_rows.version_id, @@ -712,7 +707,7 @@ def _insert_budget_window_run( def test_budget_windows_hold_one_report_run_per_year( - connection: Connection, public_api_rows: PublicApiRows + session: Session, public_api_rows: PublicApiRows ) -> None: for refused_values in ( {"year": 2026, "budget_window_size": 0}, @@ -721,22 +716,22 @@ def test_budget_windows_hold_one_report_run_per_year( {"budget_window_size": 3}, {"year": 2026, "budget_window_size": 3, "household_id": None}, ): - values = dict(refused_values) + values: dict[str, object] = dict(refused_values) if "household_id" in values: values["household_id"] = public_api_rows.household_id - with refused(connection, match="ck_reports_budget_window_size"): - _insert_report(connection, public_api_rows, **values) + with refused(session, match="ck_reports_budget_window_size"): + _insert_report(session, public_api_rows, **values) report_id = _insert_report( - connection, public_api_rows, year=2026, budget_window_size=3 + session, public_api_rows, year=2026, budget_window_size=3 ) - other_report_id = _insert_report(connection, public_api_rows, year=2026) - window_run_id = _insert_budget_window_run(connection, public_api_rows, report_id) - simulation_id = _insert_simulation(connection, public_api_rows) - - def insert_year(year: int | None, *, of_report: object = report_id) -> None: - insert_row( - connection, - "report_runs", + other_report_id = _insert_report(session, public_api_rows, year=2026) + window_run_id = _insert_budget_window_run(session, public_api_rows, report_id) + simulation_id = _insert_simulation(session, public_api_rows) + + def insert_year(year: int | None, *, of_report: UUID = report_id) -> None: + add_row( + session, + ReportRun, id=uuid4(), report_id=of_report, budget_window_run_id=window_run_id, @@ -744,8 +739,8 @@ def insert_year(year: int | None, *, of_report: object = report_id) -> None: # Each year of a window has simulations of its own, as the # simulation service gives it. baseline_simulation_run_id=_insert_simulation_run( - connection, - _insert_simulation(connection, public_api_rows), + session, + _insert_simulation(session, public_api_rows), year=year or 2026, ), status="pending", @@ -755,61 +750,60 @@ def insert_year(year: int | None, *, of_report: object = report_id) -> None: insert_year(2026) insert_year(2027) - with refused(connection, match="uq_report_runs_budget_window_run_id_year"): + with refused(session, match="uq_report_runs_budget_window_run_id_year"): insert_year(2027) - with refused(connection, match="ck_report_runs_budget_window_year"): + with refused(session, match="ck_report_runs_budget_window_year"): insert_year(None) - with refused(connection, match="foreign key constraint"): + with refused(session, match="foreign key constraint"): insert_year(2028, of_report=other_report_id) - with refused(connection, match="ck_simulation_runs_year"): - _insert_simulation_run(connection, simulation_id, year=1800) + with refused(session, match="ck_simulation_runs_year"): + _insert_simulation_run(session, simulation_id, year=1800) # A window run owns its years, as the report owns its runs. second_window_run_id = _insert_budget_window_run( - connection, public_api_rows, report_id + session, public_api_rows, report_id ) - connection.execute( - text("DELETE FROM budget_window_runs WHERE id = :id"), - {"id": window_run_id}, + session.execute( + delete(BudgetWindowRun).where(col(BudgetWindowRun.id) == window_run_id) ) - assert _count(connection, "report_runs", "budget_window_run_id", window_run_id) == 0 + assert _count(session, col(ReportRun.budget_window_run_id), window_run_id) == 0 - connection.execute(text("DELETE FROM reports WHERE id = :id"), {"id": report_id}) - assert _count(connection, "budget_window_runs", "id", second_window_run_id) == 0 - assert _count(connection, "report_runs", "report_id", report_id) == 0 + session.execute(delete(Report).where(col(Report.id) == report_id)) + assert _count(session, col(BudgetWindowRun.id), second_window_run_id) == 0 + assert _count(session, col(ReportRun.report_id), report_id) == 0 def test_household_jobs_take_a_valid_year_and_record_when_they_end( - connection: Connection, public_api_rows: PublicApiRows + session: Session, public_api_rows: PublicApiRows ) -> None: household_job = { "country": "us", "household_id": public_api_rows.household_id, - "request_data": "{}", + "request_data": {}, "tax_benefit_model_version_id": public_api_rows.version_id, **RUN_VERSIONS, } - insert_row( - connection, - "household_jobs", + add_row( + session, + HouseholdJob, id=uuid4(), year=2026, status="pending", **household_job, ) - with refused(connection): - insert_row( - connection, - "household_jobs", + with refused(session): + add_row( + session, + HouseholdJob, id=uuid4(), year=1800, status="pending", **household_job, ) - with refused(connection): - insert_row( - connection, - "household_jobs", + with refused(session): + add_row( + session, + HouseholdJob, id=uuid4(), year=2026, status="failed", diff --git a/tests/integration/test_alembic_v2_user_types.py b/tests/integration/test_alembic_v2_user_types.py index 57d29b3d0..6c5cf96df 100644 --- a/tests/integration/test_alembic_v2_user_types.py +++ b/tests/integration/test_alembic_v2_user_types.py @@ -10,20 +10,29 @@ source is invitation. """ +from __future__ import annotations + import re -from typing import Any +from typing import TYPE_CHECKING, Any from uuid import UUID, uuid4 import pytest -import sqlalchemy as sa from alembic import command -from alembic.migration import MigrationContext -from sqlalchemy import Engine, create_engine, inspect, text - -from tests.fixtures.integration.alembic_v2 import ( - alembic_v2_config, - disposable_v2_url, -) +from sqlalchemy import String, delete, select +from sqlalchemy.exc import IntegrityError +from sqlalchemy.orm import Mapped, mapped_column, registry +from sqlmodel import col + +from policyengine_api.data.v2.models import User +from tests.fixtures.database_sessions import schema_inspector +from tests.fixtures.integration.alembic_v2 import alembic_v2_config +from tests.integration.alembic_version_rows import current_revision +from tests.integration.simulation_rows import add_row + +if TYPE_CHECKING: + from sqlalchemy.engine import Inspector + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session # The saved-item keys revision, the parent of the user types revision. USER_TYPES_PREVIOUS_REVISION = "81b728a088e7" @@ -34,17 +43,44 @@ SHARED_REPORTS_REVISION = "94dc43079186" USER_INVITATIONS_REVISION = "f519a77ba122" +shared_reports_revision_tables = registry() + + +@shared_reports_revision_tables.mapped +class UserTypeChangeAt94dc43079186: + """The ``user_type_changes`` table at revision 94dc43079186. + + It has no ``dismissed_at`` until the user invitations revision on it, + f519a77ba122, which keeps every column mapped here. ``created_at``, which + the database fills in, isn't mapped. ``users`` has the same columns at + every revision these tests reach, so they write it through ``User``. + """ + + __tablename__ = "user_type_changes" -def _check_names(engine: Engine, table_name: str) -> set[str]: + id: Mapped[UUID] = mapped_column(primary_key=True) + user_id: Mapped[UUID] + changed_by_user_id: Mapped[UUID | None] + previous_user_type: Mapped[str] = mapped_column(String(16)) + new_user_type: Mapped[str] = mapped_column(String(16)) + source: Mapped[str] = mapped_column(String(16)) + + +def _check_names(sessions: sessionmaker[Session], table_name: str) -> set[str | None]: return { constraint["name"] - for constraint in inspect(engine).get_check_constraints(table_name) + for constraint in schema_inspector(sessions).get_check_constraints(table_name) } -def _schema_shape(engine: Engine) -> dict[str, dict[str, Any]]: +def _schema_shape(sessions: sessionmaker[Session]) -> dict[str, dict[str, Any]]: """Reflect every table's columns and defaults, keys, indexes and checks.""" - inspector = inspect(engine) + with sessions() as session: + return _reflected_shape(schema_inspector(session)) + + +def _reflected_shape(inspector: Inspector) -> dict[str, dict[str, Any]]: + """Describe each public table but Alembic's own, as the Inspector reads it.""" return { table_name: { "columns": [ @@ -79,17 +115,17 @@ def _schema_shape(engine: Engine) -> dict[str, dict[str, Any]]: } -def test_user_types_revision_changes_only_the_user_type_check() -> None: +def test_user_types_revision_changes_only_the_user_type_check( + v2_owner_sessions: sessionmaker[Session], +) -> None: """The revision replaces the users type check and changes nothing else.""" - database_url = disposable_v2_url() config = alembic_v2_config() - engine = create_engine(database_url) try: command.downgrade(config, USER_TYPES_PREVIOUS_REVISION) - parent = _schema_shape(engine) + parent = _schema_shape(v2_owner_sessions) command.upgrade(config, USER_TYPES_REVISION) - revision = _schema_shape(engine) + revision = _schema_shape(v2_owner_sessions) changed_tables = sorted( table_name @@ -117,72 +153,71 @@ def test_user_types_revision_changes_only_the_user_type_check() -> None: assert revision_checks == parent_checks finally: command.upgrade(config, "head") - engine.dispose() + + +def _delete_user(sessions: sessionmaker[Session], user_id: UUID) -> None: + """Delete the user, and the changes of its type with it.""" + with sessions.begin() as session: + session.execute(delete(User).where(col(User.id) == user_id)) @pytest.mark.parametrize("user_type", ["author", "admin"]) def test_user_types_revision_accepts_authors_and_admins_until_downgraded( - user_type: str, + v2_owner_sessions: sessionmaker[Session], user_type: str ) -> None: """Either type is stored, and alone keeps the downgrade from running.""" - database_url = disposable_v2_url() config = alembic_v2_config() - engine = create_engine(database_url) user_id = uuid4() def insert_user(inserted_id: UUID, inserted_type: str) -> None: - with engine.begin() as connection: - connection.execute( - text( - "INSERT INTO users (id, user_type, primary_country) " - "VALUES (:user_id, :user_type, 'us')" - ), - {"user_id": inserted_id, "user_type": inserted_type}, + with v2_owner_sessions.begin() as session: + add_row( + session, + User, + id=inserted_id, + user_type=inserted_type, + primary_country="us", ) try: command.downgrade(config, USER_TYPES_PREVIOUS_REVISION) - with pytest.raises(sa.exc.IntegrityError): + with pytest.raises(IntegrityError): insert_user(user_id, user_type) command.upgrade(config, USER_TYPES_REVISION) insert_user(user_id, user_type) - with pytest.raises(sa.exc.IntegrityError): + with pytest.raises(IntegrityError): insert_user(uuid4(), "editor") - with pytest.raises(sa.exc.IntegrityError): + with pytest.raises(IntegrityError): command.downgrade(config, USER_TYPES_PREVIOUS_REVISION) - with engine.connect() as connection: - context = MigrationContext.configure(connection) - assert context.get_current_revision() == USER_TYPES_REVISION - stored_type = connection.execute( - text("SELECT user_type FROM users WHERE id = :user_id"), - {"user_id": user_id}, - ).scalar_one() + assert current_revision(v2_owner_sessions) == USER_TYPES_REVISION + with v2_owner_sessions() as session: + stored_type = session.scalars( + select(col(User.user_type)).where(col(User.id) == user_id) + ).one() assert stored_type == user_type # The refused downgrade left the revision's check in place. - assert _check_names(engine, "users") >= {"ck_users_user_type_allowed"} - assert "ck_users_user_type" not in _check_names(engine, "users") + assert _check_names(v2_owner_sessions, "users") >= { + "ck_users_user_type_allowed" + } + assert "ck_users_user_type" not in _check_names(v2_owner_sessions, "users") finally: - with engine.begin() as connection: - connection.execute( - text("DELETE FROM users WHERE id = :user_id"), {"user_id": user_id} - ) + _delete_user(v2_owner_sessions, user_id) command.downgrade(config, USER_TYPES_PREVIOUS_REVISION) command.upgrade(config, "head") - engine.dispose() -def test_user_type_changes_revision_adds_only_its_table() -> None: +def test_user_type_changes_revision_adds_only_its_table( + v2_owner_sessions: sessionmaker[Session], +) -> None: """The revision adds user_type_changes, and its downgrade drops only that.""" - database_url = disposable_v2_url() config = alembic_v2_config() - engine = create_engine(database_url) try: command.downgrade(config, USER_TYPES_REVISION) - parent = _schema_shape(engine) + parent = _schema_shape(v2_owner_sessions) command.upgrade(config, USER_TYPE_CHANGES_REVISION) - revision = _schema_shape(engine) + revision = _schema_shape(v2_owner_sessions) assert set(revision) - set(parent) == {"user_type_changes"} assert {table_name: revision[table_name] for table_name in parent} == parent @@ -200,20 +235,19 @@ def test_user_type_changes_revision_adds_only_its_table() -> None: } finally: command.upgrade(config, "head") - engine.dispose() -def test_user_invitations_revision_adds_invitations_and_dismissals_only() -> None: +def test_user_invitations_revision_adds_invitations_and_dismissals_only( + v2_owner_sessions: sessionmaker[Session], +) -> None: """The revision adds user_invitations, dismissed_at and a wider source check.""" - database_url = disposable_v2_url() config = alembic_v2_config() - engine = create_engine(database_url) try: command.downgrade(config, SHARED_REPORTS_REVISION) - parent = _schema_shape(engine) + parent = _schema_shape(v2_owner_sessions) command.upgrade(config, USER_INVITATIONS_REVISION) - revision = _schema_shape(engine) + revision = _schema_shape(v2_owner_sessions) assert set(revision) - set(parent) == {"user_invitations"} changed_tables = sorted( @@ -263,55 +297,43 @@ def test_user_invitations_revision_adds_invitations_and_dismissals_only() -> Non } finally: command.upgrade(config, "head") - engine.dispose() -def test_user_invitations_revision_records_invitation_changes_until_downgraded() -> ( - None -): +def test_user_invitations_revision_records_invitation_changes_until_downgraded( + v2_owner_sessions: sessionmaker[Session], +) -> None: """A change from an invitation is stored, and keeps the downgrade from running.""" - database_url = disposable_v2_url() config = alembic_v2_config() - engine = create_engine(database_url) user_id = uuid4() def insert_change() -> None: - with engine.begin() as connection: - connection.execute( - text( - "INSERT INTO user_type_changes (id, user_id, " - "previous_user_type, new_user_type, source) VALUES " - "(:change_id, :user_id, 'standard', 'author', 'invitation')" - ), - {"change_id": uuid4(), "user_id": user_id}, + with v2_owner_sessions.begin() as session: + add_row( + session, + UserTypeChangeAt94dc43079186, + id=uuid4(), + user_id=user_id, + previous_user_type="standard", + new_user_type="author", + source="invitation", ) try: command.downgrade(config, SHARED_REPORTS_REVISION) - with engine.begin() as connection: - connection.execute( - text( - "INSERT INTO users (id, user_type, primary_country) " - "VALUES (:user_id, 'author', 'us')" - ), - {"user_id": user_id}, - ) - with pytest.raises(sa.exc.IntegrityError): + with v2_owner_sessions.begin() as session: + add_row(session, User, id=user_id, user_type="author", primary_country="us") + with pytest.raises(IntegrityError): insert_change() command.upgrade(config, USER_INVITATIONS_REVISION) insert_change() - with pytest.raises(sa.exc.IntegrityError): + with pytest.raises(IntegrityError): command.downgrade(config, SHARED_REPORTS_REVISION) - with engine.connect() as connection: - context = MigrationContext.configure(connection) - assert context.get_current_revision() == USER_INVITATIONS_REVISION - assert "user_invitations" in inspect(engine).get_table_names() + assert current_revision(v2_owner_sessions) == USER_INVITATIONS_REVISION + assert ( + "user_invitations" in schema_inspector(v2_owner_sessions).get_table_names() + ) finally: - with engine.begin() as connection: - connection.execute( - text("DELETE FROM users WHERE id = :user_id"), {"user_id": user_id} - ) + _delete_user(v2_owner_sessions, user_id) command.downgrade(config, SHARED_REPORTS_REVISION) command.upgrade(config, "head") - engine.dispose() diff --git a/tests/integration/test_alembic_v2_withheld_area_codes.py b/tests/integration/test_alembic_v2_withheld_area_codes.py index 448e2b4bc..6e6f48b24 100644 --- a/tests/integration/test_alembic_v2_withheld_area_codes.py +++ b/tests/integration/test_alembic_v2_withheld_area_codes.py @@ -7,116 +7,125 @@ then the type. """ -from collections.abc import Iterator -from typing import Any +from __future__ import annotations + +from typing import TYPE_CHECKING, Any from uuid import UUID, uuid4 import pytest from alembic import command -from sqlalchemy import Connection, Engine, create_engine, inspect, text +from sqlalchemy import delete, select +from sqlalchemy.dialects.postgresql.base import PGInspector from sqlalchemy.exc import DataError, IntegrityError -from sqlalchemy.pool import NullPool - -from tests.fixtures.integration.alembic_v2 import ( - alembic_v2_config, - disposable_v2_url, +from sqlmodel import col + +from policyengine_api.data.v2.models import ( + Report, + ReportRun, + Simulation, + SimulationRun, + WithheldAreaCode, ) +from tests.fixtures.database_sessions import schema_inspector +from tests.fixtures.integration.alembic_v2 import alembic_v2_config from tests.integration.simulation_rows import ( RUN_VERSIONS, + add_row, insert_public_api_rows, - insert_row, refused, ) +if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + SPM_AVAILABILITY_REVISION = "0c136a278f29" WITHHELD_AREA_CODES_REVISION = "1e1e3f079f2c" -def _schema_shape(engine: Engine) -> dict[str, dict[str, Any]]: +def _schema_shape(sessions: sessionmaker[Session]) -> dict[str, dict[str, Any]]: """Reflect every table's columns, keys, indexes and checks.""" - inspector = inspect(engine) - return { - table_name: { - "columns": [ - ( - column["name"], - str(column["type"]), - column["nullable"], - column.get("default"), - ) - for column in inspector.get_columns(table_name) - ], - "primary_key": inspector.get_pk_constraint(table_name), - "foreign_keys": sorted( - ( - key["name"], - key["constrained_columns"], - key["referred_table"], - key["options"].get("ondelete"), - ) - for key in inspector.get_foreign_keys(table_name) - ), - "unique_constraints": sorted( - (unique["name"], unique["column_names"]) - for unique in inspector.get_unique_constraints(table_name) - ), - "indexes": sorted( - (index["name"], index["column_names"]) - for index in inspector.get_indexes(table_name) - ), - "checks": { - check["name"]: check["sqltext"] - for check in inspector.get_check_constraints(table_name) - }, + with sessions() as session: + inspector = schema_inspector(session) + return { + table_name: { + "columns": [ + ( + column["name"], + str(column["type"]), + column["nullable"], + column.get("default"), + ) + for column in inspector.get_columns(table_name) + ], + "primary_key": inspector.get_pk_constraint(table_name), + "foreign_keys": sorted( + ( + key["name"], + key["constrained_columns"], + key["referred_table"], + key["options"].get("ondelete"), + ) + for key in inspector.get_foreign_keys(table_name) + ), + "unique_constraints": sorted( + (unique["name"], unique["column_names"]) + for unique in inspector.get_unique_constraints(table_name) + ), + "indexes": sorted( + (index["name"], index["column_names"]) + for index in inspector.get_indexes(table_name) + ), + "checks": { + check["name"]: check["sqltext"] + for check in inspector.get_check_constraints(table_name) + }, + } + for table_name in inspector.get_table_names(schema="public") + if table_name != "alembic_version" } - for table_name in inspector.get_table_names(schema="public") - if table_name != "alembic_version" - } -def _enum_labels(engine: Engine) -> dict[str, list[str]]: +def _enum_labels(sessions: sessionmaker[Session]) -> dict[str, list[str]]: """Return each enum type in the public schema with its labels in order.""" - with engine.connect() as connection: - rows = connection.execute( - text( - "SELECT type.typname, enum.enumlabel FROM pg_type AS type " - "JOIN pg_enum AS enum ON enum.enumtypid = type.oid " - "JOIN pg_namespace AS namespace ON namespace.oid = type.typnamespace " - "WHERE namespace.nspname = 'public' " - "ORDER BY type.typname, enum.enumsortorder" - ) - ).all() - labels: dict[str, list[str]] = {} - for type_name, label in rows: - labels.setdefault(type_name, []).append(label) - return labels + inspector = schema_inspector(sessions) + assert isinstance(inspector, PGInspector) + return { + enum_type["name"]: enum_type["labels"] + for enum_type in inspector.get_enums(schema="public") + } + + +def _table_names(sessions: sessionmaker[Session]) -> list[str]: + return schema_inspector(sessions).get_table_names() @pytest.fixture -def engine() -> Iterator[Engine]: - """Yield an engine on the disposable database, left at the v2 head.""" - database_url = disposable_v2_url() - database_engine = create_engine(database_url, poolclass=NullPool) +def sessions( + v2_owner_sessions: sessionmaker[Session], +) -> Iterator[sessionmaker[Session]]: + """Yield the disposable database owner's Session factories; leave it at head.""" try: - yield database_engine + yield v2_owner_sessions finally: command.upgrade(alembic_v2_config(), "head") - database_engine.dispose() def test_withheld_area_codes_revision_adds_only_the_table_and_its_type( - engine: Engine, + sessions: sessionmaker[Session], ) -> None: """The revision adds one table and one enum type and changes nothing else.""" config = alembic_v2_config() command.upgrade(config, "head") command.downgrade(config, SPM_AVAILABILITY_REVISION) - parent_shape = _schema_shape(engine) - parent_enums = _enum_labels(engine) + parent_shape = _schema_shape(sessions) + parent_enums = _enum_labels(sessions) command.upgrade(config, WITHHELD_AREA_CODES_REVISION) - revision_shape = _schema_shape(engine) - revision_enums = _enum_labels(engine) + revision_shape = _schema_shape(sessions) + revision_enums = _enum_labels(sessions) assert set(revision_shape) - set(parent_shape) == {"withheld_area_codes"} assert { @@ -147,7 +156,7 @@ def test_withheld_area_codes_revision_adds_only_the_table_and_its_type( def test_withheld_area_codes_downgrade_removes_the_table_and_its_type( - engine: Engine, + sessions: sessionmaker[Session], ) -> None: """Downgrading drops the table and the type, so upgrading again works.""" config = alembic_v2_config() @@ -156,39 +165,39 @@ def test_withheld_area_codes_downgrade_removes_the_table_and_its_type( command.downgrade(config, WITHHELD_AREA_CODES_REVISION) command.downgrade(config, SPM_AVAILABILITY_REVISION) - assert "withheld_area_codes" not in inspect(engine).get_table_names() - assert "v2_uk_area_type" not in _enum_labels(engine) + assert "withheld_area_codes" not in _table_names(sessions) + assert "v2_uk_area_type" not in _enum_labels(sessions) command.upgrade(config, WITHHELD_AREA_CODES_REVISION) - assert "withheld_area_codes" in inspect(engine).get_table_names() - assert _enum_labels(engine)["v2_uk_area_type"] == [ + assert "withheld_area_codes" in _table_names(sessions) + assert _enum_labels(sessions)["v2_uk_area_type"] == [ "constituency", "local_authority", ] -def _insert_report_run(connection: Connection) -> dict[str, UUID]: +def _insert_report_run(session: Session) -> dict[str, UUID]: """Store a UK report run comparing two simulation runs, and a spare run.""" - public_api_rows = insert_public_api_rows(connection) + public_api_rows = insert_public_api_rows(session) run_names = ("baseline_run", "reform_run", "unrelated_run") ids = {name: uuid4() for name in (*run_names, "report", "report_run")} # Each run is of a simulation of its own: a simulation has one unfailed # run per version set. for run_name in run_names: simulation_id = uuid4() - insert_row( - connection, - "simulations", + add_row( + session, + Simulation, id=simulation_id, simulation_type="economy", dataset_id=public_api_rows.dataset_id, tax_benefit_model_version_id=public_api_rows.version_id, year=2026, ) - insert_row( - connection, - "simulation_runs", + add_row( + session, + SimulationRun, id=ids[run_name], simulation_id=simulation_id, tax_benefit_model_version_id=public_api_rows.version_id, @@ -196,19 +205,19 @@ def _insert_report_run(connection: Connection) -> dict[str, UUID]: status="pending", **RUN_VERSIONS, ) - insert_row( - connection, - "reports", + add_row( + session, + Report, id=ids["report"], label="Local areas", country="uk", tax_benefit_model_id=public_api_rows.model_id, year=2026, - inputs="{}", + inputs={}, ) - insert_row( - connection, - "report_runs", + add_row( + session, + ReportRun, id=ids["report_run"], report_id=ids["report"], baseline_simulation_run_id=ids["baseline_run"], @@ -221,16 +230,16 @@ def _insert_report_run(connection: Connection) -> dict[str, UUID]: def _insert_withheld_code( - connection: Connection, + session: Session, ids: dict[str, UUID], *, area_type: str, code: str, reform_run: str = "reform_run", ) -> None: - insert_row( - connection, - "withheld_area_codes", + add_row( + session, + WithheldAreaCode, id=uuid4(), report_run_id=ids["report_run"], baseline_simulation_run_id=ids["baseline_run"], @@ -240,66 +249,63 @@ def _insert_withheld_code( ) -def _withheld_codes(connection: Connection, report_run_id: UUID) -> list[tuple]: - return connection.execute( - text( - "SELECT area_type::text, code FROM withheld_area_codes " - "WHERE report_run_id = :report_run_id ORDER BY area_type, code" - ), - {"report_run_id": report_run_id}, - ).all() +def _withheld_codes(session: Session, report_run_id: UUID) -> list[tuple[str, str]]: + return list( + session.execute( + select(col(WithheldAreaCode.area_type), col(WithheldAreaCode.code)) + .where(col(WithheldAreaCode.report_run_id) == report_run_id) + .order_by(col(WithheldAreaCode.area_type), col(WithheldAreaCode.code)) + ).tuples() + ) def test_withheld_area_codes_hold_each_area_once_and_go_with_their_run( - engine: Engine, + sessions: sessionmaker[Session], ) -> None: """Each run lists an area once, of a known type; deleting the run drops it.""" command.upgrade(alembic_v2_config(), "head") - with engine.connect() as connection: - transaction = connection.begin() + with sessions() as session: try: - ids = _insert_report_run(connection) + ids = _insert_report_run(session) _insert_withheld_code( - connection, ids, area_type="constituency", code="E14001063" + session, ids, area_type="constituency", code="E14001063" ) # The same code under the other area type is a different area. _insert_withheld_code( - connection, ids, area_type="local_authority", code="E14001063" + session, ids, area_type="local_authority", code="E14001063" ) _insert_withheld_code( - connection, + session, ids, area_type="local_authority", code="E06000001", reform_run="unrelated_run", ) - with refused(connection, IntegrityError, match="uq_withheld_area_codes"): - _insert_withheld_code( - connection, ids, area_type="constituency", code="E14001063" - ) - with refused(connection, DataError, match="v2_uk_area_type"): + with refused(session, IntegrityError, match="uq_withheld_area_codes"): _insert_withheld_code( - connection, ids, area_type="ward", code="E05000001" + session, ids, area_type="constituency", code="E14001063" ) + with refused(session, DataError, match="v2_uk_area_type"): + _insert_withheld_code(session, ids, area_type="ward", code="E05000001") # A simulation run that withheld codes name stays while they do. - with refused(connection, IntegrityError, match="withheld_area_codes"): - connection.execute( - text("DELETE FROM simulation_runs WHERE id = :id"), - {"id": ids["unrelated_run"]}, + with refused(session, IntegrityError, match="withheld_area_codes"): + session.execute( + delete(SimulationRun).where( + col(SimulationRun.id) == ids["unrelated_run"] + ) ) - assert _withheld_codes(connection, ids["report_run"]) == [ + assert _withheld_codes(session, ids["report_run"]) == [ ("constituency", "E14001063"), ("local_authority", "E06000001"), ("local_authority", "E14001063"), ] - connection.execute( - text("DELETE FROM report_runs WHERE id = :id"), - {"id": ids["report_run"]}, + session.execute( + delete(ReportRun).where(col(ReportRun.id) == ids["report_run"]) ) - assert _withheld_codes(connection, ids["report_run"]) == [] + assert _withheld_codes(session, ids["report_run"]) == [] finally: - transaction.rollback() + session.rollback() diff --git a/tests/integration/test_mysql_household_spm_dual_write.py b/tests/integration/test_mysql_household_spm_dual_write.py index d76a99a50..23d5e5cc5 100644 --- a/tests/integration/test_mysql_household_spm_dual_write.py +++ b/tests/integration/test_mysql_household_spm_dual_write.py @@ -11,13 +11,12 @@ from contextlib import contextmanager from copy import deepcopy from dataclasses import dataclass +from typing import TYPE_CHECKING from uuid import uuid4 import pytest -from sqlalchemy import create_engine, delete, select, text +from sqlalchemy import String, delete, literal, select, type_coerce from sqlalchemy.exc import DataError -from sqlalchemy.orm import sessionmaker -from sqlmodel import Session from policyengine_api.constants import COUNTRY_PACKAGE_VERSIONS from policyengine_api.data.v1_models import ( @@ -41,7 +40,11 @@ legacy_household_fingerprint, ) from policyengine_api.utils import hash_object -from tests.integration.test_mysql_policy_dual_write import _mysql_url, _postgres_url + +if TYPE_CHECKING: + from sqlalchemy.orm import Session as OrmSession + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session NATIONAL_SPM = { "forecast_content_sha256": "a" * 64, @@ -76,8 +79,8 @@ def _source_document(marker: str, value: float = 40.0) -> dict: @dataclass class HouseholdDatabases: - mysql_sessions: sessionmaker - postgres_sessions: sessionmaker + mysql_sessions: sessionmaker[OrmSession] + postgres_sessions: sessionmaker[Session] source: HouseholdService destination: V2HouseholdService marker: str @@ -117,16 +120,11 @@ def source_receipt(self, creation): @pytest.fixture -def databases(monkeypatch): - # Validate both explicit disposable targets before constructing either engine. - mysql_url, postgres_url = _mysql_url(), _postgres_url() - mysql_engine = create_engine(mysql_url) - postgres_engine = create_engine(postgres_url) - mysql_sessions = sessionmaker(mysql_engine, expire_on_commit=False) - postgres_sessions = sessionmaker( - postgres_engine, class_=Session, expire_on_commit=False - ) - +def databases( + monkeypatch, + v1_sessions: sessionmaker[OrmSession], + v2_owner_sessions: sessionmaker[Session], +): def resolved_selection(country_id, selection): assert country_id == "us" return deepcopy(NATIONAL_SPM if selection is None else selection) @@ -137,51 +135,39 @@ def resolved_selection(country_id, selection): marker = f"mysql-household-spm-{uuid4().hex}" try: yield HouseholdDatabases( - mysql_sessions, - postgres_sessions, - HouseholdService(mysql_sessions), - V2HouseholdService(HouseholdDatabaseSession(postgres_sessions)), + v1_sessions, + v2_owner_sessions, + HouseholdService(v1_sessions), + V2HouseholdService(HouseholdDatabaseSession(v2_owner_sessions)), marker, ) finally: - try: - with mysql_sessions() as session: - source_ids = list( - session.scalars( - select(V1Household.id).where(V1Household.label == marker) - ) - ) - with postgres_engine.begin() as connection: - mapping_filter = ( - LegacyHouseholdMapping.country_id == "us", - LegacyHouseholdMapping.legacy_household_id.in_(source_ids), - ) - destination_ids = list( - connection.scalars( - select(LegacyHouseholdMapping.household_id).where( - *mapping_filter - ) - ) + with v1_sessions() as session: + source_ids = list( + session.scalars( + select(V1Household.id).where(V1Household.label == marker) ) - connection.execute( - delete(LegacyHouseholdMapping).where(*mapping_filter) - ) - connection.execute( - delete(Household).where(Household.id.in_(destination_ids)) - ) - with mysql_engine.begin() as connection: - connection.execute( - delete(HouseholdMirrorEvent).where( - HouseholdMirrorEvent.legacy_household_id.in_(source_ids), - HouseholdMirrorEvent.country_id == "us", - ) + ) + with v2_owner_sessions.begin() as session: + mapping_filter = ( + LegacyHouseholdMapping.country_id == "us", + LegacyHouseholdMapping.legacy_household_id.in_(source_ids), + ) + destination_ids = list( + session.scalars( + select(LegacyHouseholdMapping.household_id).where(*mapping_filter) ) - connection.execute( - delete(V1Household).where(V1Household.id.in_(source_ids)) + ) + session.execute(delete(LegacyHouseholdMapping).where(*mapping_filter)) + session.execute(delete(Household).where(Household.id.in_(destination_ids))) + with v1_sessions.begin() as session: + session.execute( + delete(HouseholdMirrorEvent).where( + HouseholdMirrorEvent.legacy_household_id.in_(source_ids), + HouseholdMirrorEvent.country_id == "us", ) - finally: - mysql_engine.dispose() - postgres_engine.dispose() + ) + session.execute(delete(V1Household).where(V1Household.id.in_(source_ids))) @pytest.mark.parametrize("fail_destination", [False, True], ids=["success", "rollback"]) @@ -204,9 +190,11 @@ def test_spm_source_event_and_postgres_retry_keep_exact_persisted_identity( ) assert before["fingerprint"] == legacy_household_fingerprint(creation.snapshot) with databases.mysql_sessions() as session: + # MySQL's own text of the stored JSON, which the JSON type would parse. raw_json = session.execute( - text("SELECT household_json FROM household WHERE id = :id"), - {"id": creation.household.id}, + select(type_coerce(V1Household.household_json, String)).where( + V1Household.id == creation.household.id + ) ).scalar_one() assert json.loads(raw_json) == before["household_json"] stored_value = before["household_json"]["people"]["adult"]["employment_income"][ @@ -227,7 +215,7 @@ class FailingTransaction(HouseholdDatabaseSession): def transaction(self): with super().transaction() as session: yield session - session.execute(text("SELECT 1 / 0")) + session.execute(select(literal(1) / literal(0))) with pytest.raises(HouseholdMirrorUnavailableError) as failure: databases.mirror( diff --git a/tests/integration/test_mysql_policy_dual_write.py b/tests/integration/test_mysql_policy_dual_write.py index b7e678d05..8be8dd011 100644 --- a/tests/integration/test_mysql_policy_dual_write.py +++ b/tests/integration/test_mysql_policy_dual_write.py @@ -10,24 +10,17 @@ from __future__ import annotations import json -import os from contextlib import contextmanager from dataclasses import dataclass +from typing import TYPE_CHECKING from uuid import UUID, uuid4 import pytest -from sqlalchemy import create_engine, delete, func, select, text -from sqlalchemy.engine import Engine, make_url +from sqlalchemy import String, delete, func, literal, select, type_coerce from sqlalchemy.exc import DataError -from sqlalchemy.orm import sessionmaker -from sqlmodel import Session from policyengine_api.constants import POLICYENGINE_VERSION from policyengine_api.data.v1_models import Policy as V1Policy -from policyengine_api.data.v2.migration_target import ( - V2_ALEMBIC_DISPOSABLE_TEST, - load_v2_alembic_settings, -) from policyengine_api.data.v2.models import ( LegacyPolicyMapping, Parameter, @@ -36,7 +29,6 @@ TaxBenefitModel, TaxBenefitModelVersion, ) -from policyengine_api.data.v2.settings import V2_MIGRATION_DATABASE_URL from policyengine_api.services.policy_mirroring import ( PolicyMirrorUnavailableError, mirror_policy_after_commit, @@ -50,49 +42,20 @@ ) from policyengine_api.utils import hash_object +if TYPE_CHECKING: + from sqlalchemy.orm import Session as OrmSession + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + INPUT_VALUE = 0.04 + 3 / 1_000_000 STORED_VALUE = 0.040003 PARAMETER_NAME = "gov.phase10.mysql_storage_rate" PERIOD = "2026-01-01.2100-12-31" -def _mysql_url() -> str: - database_url = os.environ.get("ALEMBIC_DATABASE_URL", "") - if not database_url: - pytest.skip("ALEMBIC_DATABASE_URL is not set") - url = make_url(database_url) - if ( - url.drivername != "mysql+pymysql" - or url.host not in {"127.0.0.1", "localhost"} - or url.database != "policyengine_alembic_test" - or not url.username - or url.password is None - ): - pytest.fail( - "MySQL mirror tests require explicit test credentials and the local " - "mysql+pymysql policyengine_alembic_test schema" - ) - return database_url - - -def _postgres_url() -> str: - database_url = os.environ.get(V2_MIGRATION_DATABASE_URL, "") - if not database_url: - pytest.skip(f"{V2_MIGRATION_DATABASE_URL} is not set") - if os.environ.get(V2_ALEMBIC_DISPOSABLE_TEST) != "1": - pytest.fail("MySQL mirror tests require v2 disposable-test mode") - settings = load_v2_alembic_settings( - { - V2_MIGRATION_DATABASE_URL: database_url, - V2_ALEMBIC_DISPOSABLE_TEST: "1", - } - ) - return settings.url.render_as_string(hide_password=False) - - @dataclass class MySQLSource: - engine: Engine + sessions: sessionmaker[OrmSession] service: PolicyService label_prefix: str @@ -106,30 +69,24 @@ def create(self, label: str = "first") -> PolicySetResult: @pytest.fixture -def mysql_source(): - engine = create_engine(_mysql_url()) +def mysql_source(v1_sessions: sessionmaker[OrmSession]): source = MySQLSource( - engine, - PolicyService(sessionmaker(engine, expire_on_commit=False)), - f"mysql-mirror-{uuid4().hex}-", + v1_sessions, PolicyService(v1_sessions), f"mysql-mirror-{uuid4().hex}-" ) try: yield source finally: - try: - with engine.begin() as connection: - connection.execute( - delete(V1Policy).where( - V1Policy.label.startswith(source.label_prefix, autoescape=True) - ) + with v1_sessions.begin() as session: + session.execute( + delete(V1Policy).where( + V1Policy.label.startswith(source.label_prefix, autoescape=True) ) - finally: - engine.dispose() + ) @dataclass class PostgreSQLDestination: - sessions: sessionmaker + sessions: sessionmaker[Session] service: V2PolicyService model_id: UUID @@ -159,12 +116,10 @@ def counts(self) -> tuple[int, int, int]: @pytest.fixture -def postgres_destination(): - engine = create_engine(_postgres_url()) - sessions = sessionmaker(engine, class_=Session, expire_on_commit=False) +def postgres_destination(v2_owner_sessions: sessionmaker[Session]): model_id = None try: - with sessions.begin() as session: + with v2_owner_sessions.begin() as session: model = TaxBenefitModel(name="policyengine-us") version = TaxBenefitModelVersion( model=model, @@ -181,38 +136,37 @@ def postgres_destination(): session.flush() model_id = model.id yield PostgreSQLDestination( - sessions, V2PolicyService(PolicyDatabaseSession(sessions)), model_id + v2_owner_sessions, + V2PolicyService(PolicyDatabaseSession(v2_owner_sessions)), + model_id, ) finally: - try: - if model_id is not None: - with engine.begin() as connection: - policy_ids = select(Policy.id).where( - Policy.tax_benefit_model_id == model_id - ) - version_ids = select(TaxBenefitModelVersion.id).where( - TaxBenefitModelVersion.model_id == model_id - ) - for table, clause in ( - ( - LegacyPolicyMapping, - LegacyPolicyMapping.policy_id.in_(policy_ids), - ), - (ParameterValue, ParameterValue.policy_id.in_(policy_ids)), - (Policy, Policy.tax_benefit_model_id == model_id), - ( - Parameter, - Parameter.tax_benefit_model_version_id.in_(version_ids), - ), - ( - TaxBenefitModelVersion, - TaxBenefitModelVersion.model_id == model_id, - ), - (TaxBenefitModel, TaxBenefitModel.id == model_id), - ): - connection.execute(delete(table).where(clause)) - finally: - engine.dispose() + if model_id is not None: + with v2_owner_sessions.begin() as session: + policy_ids = select(Policy.id).where( + Policy.tax_benefit_model_id == model_id + ) + version_ids = select(TaxBenefitModelVersion.id).where( + TaxBenefitModelVersion.model_id == model_id + ) + for mapped_class, clause in ( + ( + LegacyPolicyMapping, + LegacyPolicyMapping.policy_id.in_(policy_ids), + ), + (ParameterValue, ParameterValue.policy_id.in_(policy_ids)), + (Policy, Policy.tax_benefit_model_id == model_id), + ( + Parameter, + Parameter.tax_benefit_model_version_id.in_(version_ids), + ), + ( + TaxBenefitModelVersion, + TaxBenefitModelVersion.model_id == model_id, + ), + (TaxBenefitModel, TaxBenefitModel.id == model_id), + ): + session.execute(delete(mapped_class).where(clause)) def test_first_snapshot_matches_real_mysql_json_storage( @@ -220,10 +174,12 @@ def test_first_snapshot_matches_real_mysql_json_storage( ) -> None: creation = mysql_source.create() assert creation.snapshot is not None - with mysql_source.engine.connect() as connection: - raw_json = connection.execute( - text("SELECT policy_json FROM policy WHERE id = :id AND country_id = 'us'"), - {"id": creation.policy_id}, + with mysql_source.sessions() as session: + # MySQL's own text of the stored JSON, which the JSON type would parse. + raw_json = session.execute( + select(type_coerce(V1Policy.policy_json, String)).where( + V1Policy.id == creation.policy_id, V1Policy.country_id == "us" + ) ).scalar_one() persisted = json.loads(raw_json) record_property("input_value", repr(INPUT_VALUE)) @@ -264,7 +220,7 @@ def transaction(self): yield session # Fail on the real server after policy/value/mapping inserts # and before COMMIT, exercising PostgreSQL rollback itself. - session.execute(text("SELECT 1 / 0")) + session.execute(select(literal(1) / literal(0))) failing_service = V2PolicyService( FailingTransaction(postgres_destination.sessions) diff --git a/tests/integration/test_mysql_update_row_counts.py b/tests/integration/test_mysql_update_row_counts.py index 6e3df1d05..a27973780 100644 --- a/tests/integration/test_mysql_update_row_counts.py +++ b/tests/integration/test_mysql_update_row_counts.py @@ -5,107 +5,59 @@ sets the CLIENT.FOUND_ROWS flag, so an UPDATE that writes values the row already holds reports 0 rows without it. -Use the local, Alembic-migrated target required by test_mysql_policy_dual_write. -The Cloud SQL connector is replaced by one that opens pymysql connections to -that server, passing on the connection arguments the engine gives it as the -real connector does. Only the row each test creates is removed during cleanup. +Use the local, Alembic-migrated MySQL database that ``ALEMBIC_DATABASE_URL`` +names. API v1's own engine is built as in production, with a stand-in for the +Cloud SQL connector that opens pymysql connections to that server and passes on +the connection arguments the engine gives it, as the real connector does +(``v1_cloud_sql_sessions``). Only the row each test creates is removed during +cleanup. """ from __future__ import annotations -import pymysql +from typing import TYPE_CHECKING, Any, cast + import pytest -from sqlalchemy import Engine, create_engine, delete, select, update -from sqlalchemy.engine import URL, make_url +from sqlalchemy import delete, select, update from sqlalchemy.orm.exc import StaleDataError -from sqlalchemy.pool import NullPool -from policyengine_api.data import orm, orm_pool_events +from policyengine_api.data import orm from policyengine_api.data.v1_models import ReportOutput -from tests.integration.test_mysql_policy_dual_write import _mysql_url - -MYSQL_DEFAULT_PORT = 3306 - - -class LocalMySqlConnector: - """Stands in for the Cloud SQL connector, connecting to the local test server. - - The real connector's pymysql path passes every argument other than the - instance name and driver on to pymysql, so this one does the same. - """ - - def __init__(self, database_url: URL, **connector_options): - self.database_url = database_url - self.connector_options = connector_options - - def connect(self, *, instance_connection_string, driver, **driver_arguments): - assert driver == "pymysql" - return pymysql.connect( - host=self.database_url.host, - port=self.database_url.port or MYSQL_DEFAULT_PORT, - **driver_arguments, - ) +from tests.fixtures.database_sessions import v1_cloud_sql_sessions - def close(self): - pass +if TYPE_CHECKING: + from collections.abc import Iterator - -@pytest.fixture -def mysql_database_url() -> URL: - return make_url(_mysql_url()) + from sqlalchemy import CursorResult + from sqlalchemy.orm import Session, sessionmaker + from sqlalchemy.sql.dml import Update @pytest.fixture -def v1_remote_engine(monkeypatch, mysql_database_url): - """Yield the engine orm._build_remote_engine builds, connected to local MySQL.""" - monkeypatch.setattr(orm, "_cloud_sql_state", orm._CloudSqlState()) - monkeypatch.setattr( - orm, - "Connector", - lambda **connector_options: LocalMySqlConnector( - mysql_database_url, **connector_options - ), - ) - monkeypatch.setenv("POLICYENGINE_DB_INSTANCE_CONNECTION_NAME", "local:test:mysql") - monkeypatch.setenv("POLICYENGINE_DB_USER", mysql_database_url.username) - monkeypatch.setenv("POLICYENGINE_DB_NAME", mysql_database_url.database) - monkeypatch.setenv("POLICYENGINE_DB_PASSWORD", mysql_database_url.password) - engine = orm._build_remote_engine() - try: - yield engine - finally: - engine.dispose() - # Building the engine sends the connector's logs to the runtime; undo - # that, so later tests in this process see the logger unchanged. - orm_pool_events.stop_recording_connector_refresh_logs() +def v1_engine_sessions( + monkeypatch: pytest.MonkeyPatch, disposable_v1_database_url: str +) -> Iterator[sessionmaker[Session]]: + """Yield API v1's Session factory, on the engine orm._build_remote_engine builds.""" + with v1_cloud_sql_sessions(monkeypatch, disposable_v1_database_url) as sessions: + yield sessions @pytest.fixture -def engine_without_found_rows(mysql_database_url): - """Yield an engine whose creator opens pymysql connections with no client flags.""" - - def connect_without_found_rows(): - return pymysql.connect( - host=mysql_database_url.host, - port=mysql_database_url.port or MYSQL_DEFAULT_PORT, - user=mysql_database_url.username, - password=mysql_database_url.password, - database=mysql_database_url.database, - ) +def sessions_without_found_rows( + monkeypatch: pytest.MonkeyPatch, disposable_v1_database_url: str +) -> Iterator[sessionmaker[Session]]: + """Yield Session factories on the v1 engine, its connections with no client flags. - engine = create_engine( - "mysql+pymysql://", - creator=connect_without_found_rows, - poolclass=NullPool, - ) - try: - yield engine - finally: - engine.dispose() + Only the CLIENT.FOUND_ROWS flag the engine passes to each connection + differs from API v1's engine: it is replaced by none. + """ + monkeypatch.setattr(orm, "MYSQL_CLIENT_FOUND_ROWS_FLAG", 0) + with v1_cloud_sql_sessions(monkeypatch, disposable_v1_database_url) as sessions: + yield sessions -def _create_pending_report_output(engine: Engine) -> int: - with orm.build_session_factory(engine).begin() as session: +def _create_pending_report_output(sessions: sessionmaker[Session]) -> int: + with sessions.begin() as session: report_output = ReportOutput( country_id="us", simulation_1_id=0, @@ -117,23 +69,52 @@ def _create_pending_report_output(engine: Engine) -> int: return report_output.id -def _delete_report_output(engine: Engine, report_output_id: int) -> None: - with engine.begin() as connection: - connection.execute( - delete(ReportOutput).where(ReportOutput.id == report_output_id) - ) +def _delete_report_output( + sessions: sessionmaker[Session], report_output_id: int +) -> None: + with sessions.begin() as session: + session.execute(delete(ReportOutput).where(ReportOutput.id == report_output_id)) + + +def _set_complete(report_output_id: int) -> Update: + """Return an ORM UPDATE that sets the row complete behind any loaded object.""" + return ( + update(ReportOutput) + .where(ReportOutput.id == report_output_id) + .values(status="complete") + .execution_options(synchronize_session=False) + ) + + +def _row_count(session: Session, statement: Update) -> int: + """Run an UPDATE in the Session and return the row count MySQL reports.""" + result = cast("CursorResult[Any]", session.execute(statement)) + return result.rowcount + +def _rows_reported_for_unchanged_update( + sessions: sessionmaker[Session], report_output_id: int +) -> int: + """Return the row count of an ORM UPDATE that writes the values the row holds. -def _complete_report_output_already_completed_by_sql( - engine: Engine, report_output_id: int + The first UPDATE sets the pending row complete and the second sets it + complete again. Closing the Session rolls both back. + """ + with sessions() as session: + assert _row_count(session, _set_complete(report_output_id)) == 1 + return _row_count(session, _set_complete(report_output_id)) + + +def _complete_report_output_already_completed_by_statement( + sessions: sessionmaker[Session], report_output_id: int ) -> None: - """Have the ORM write a status that SQL set earlier in the same transaction. + """Have the ORM write a status that an UPDATE set earlier in the same transaction. - The ORM loads the row while it is pending, a Core UPDATE then sets it - complete without the ORM seeing it, and the ORM sets complete again and - flushes. MySQL finds the row but changes nothing. + The ORM loads the row while it is pending, an ORM UPDATE statement then sets + it complete without changing the loaded object, and the object sets complete + again and flushes. MySQL finds the row but changes nothing. """ - with orm.build_session_factory(engine).begin() as session: + with sessions.begin() as session: report_output = session.scalar( select(ReportOutput) .where(ReportOutput.id == report_output_id) @@ -141,38 +122,46 @@ def _complete_report_output_already_completed_by_sql( ) assert report_output is not None assert report_output.status == "pending" - session.connection().execute( - update(ReportOutput.__table__) - .where(ReportOutput.__table__.c.id == report_output_id) - .values(status="complete") - ) + session.execute(_set_complete(report_output_id)) report_output.status = "complete" session.flush() def test_orm_update_to_unchanged_values_raises_without_found_rows( - engine_without_found_rows, -): - report_output_id = _create_pending_report_output(engine_without_found_rows) + sessions_without_found_rows: sessionmaker[Session], +) -> None: + report_output_id = _create_pending_report_output(sessions_without_found_rows) try: + assert ( + _rows_reported_for_unchanged_update( + sessions_without_found_rows, report_output_id + ) + == 0 + ) with pytest.raises(StaleDataError, match="0 were matched"): - _complete_report_output_already_completed_by_sql( - engine_without_found_rows, report_output_id + _complete_report_output_already_completed_by_statement( + sessions_without_found_rows, report_output_id ) finally: - _delete_report_output(engine_without_found_rows, report_output_id) + _delete_report_output(sessions_without_found_rows, report_output_id) -def test_v1_engine_orm_update_to_unchanged_values_succeeds(v1_remote_engine): - report_output_id = _create_pending_report_output(v1_remote_engine) +def test_v1_engine_orm_update_to_unchanged_values_succeeds( + v1_engine_sessions: sessionmaker[Session], +) -> None: + report_output_id = _create_pending_report_output(v1_engine_sessions) try: - _complete_report_output_already_completed_by_sql( - v1_remote_engine, report_output_id + assert ( + _rows_reported_for_unchanged_update(v1_engine_sessions, report_output_id) + == 1 + ) + _complete_report_output_already_completed_by_statement( + v1_engine_sessions, report_output_id ) - with orm.build_session_factory(v1_remote_engine)() as session: + with v1_engine_sessions() as session: report_output = session.get(ReportOutput, report_output_id) assert report_output is not None assert report_output.status == "complete" finally: - _delete_report_output(v1_remote_engine, report_output_id) + _delete_report_output(v1_engine_sessions, report_output_id) diff --git a/tests/integration/test_v1_household_dual_write.py b/tests/integration/test_v1_household_dual_write.py index a8bdceeaf..fc078bd1e 100644 --- a/tests/integration/test_v1_household_dual_write.py +++ b/tests/integration/test_v1_household_dual_write.py @@ -2,13 +2,12 @@ from __future__ import annotations +from typing import TYPE_CHECKING from unittest.mock import patch import pytest -from sqlalchemy import create_engine, delete, func, select +from sqlalchemy import delete, func, select from sqlalchemy.exc import OperationalError -from sqlalchemy.orm import sessionmaker -from sqlmodel import Session from policyengine_api.data.v1_models import ( Household as V1Household, @@ -33,20 +32,21 @@ mirror_legacy_household_in_session, ) +if TYPE_CHECKING: + from sqlalchemy.orm import Session as OrmSession + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session -def _v1_service(database_url: str): - engine = create_engine(database_url) - with engine.begin() as connection: - connection.execute(delete(HouseholdMirrorEvent)) - connection.execute(delete(V1Household)) - sessions = sessionmaker(engine, expire_on_commit=False) - return engine, sessions, HouseholdService(sessions) +def _v1_service(v1_sessions: sessionmaker[OrmSession]) -> HouseholdService: + _cleanup_v1(v1_sessions) + return HouseholdService(v1_sessions) -def _cleanup_v1(engine) -> None: - with engine.begin() as connection: - connection.execute(delete(HouseholdMirrorEvent)) - connection.execute(delete(V1Household)) + +def _cleanup_v1(v1_sessions: sessionmaker[OrmSession]) -> None: + with v1_sessions.begin() as session: + session.execute(delete(HouseholdMirrorEvent)) + session.execute(delete(V1Household)) def _source_document() -> dict[str, object]: @@ -71,21 +71,19 @@ def _create_v1(service: HouseholdService): ) -def _cleanup_v2(v2_engine) -> None: - with v2_engine.begin() as connection: - connection.execute(delete(LegacyHouseholdMapping)) - connection.execute(delete(Household)) +def _cleanup_v2(v2_owner_sessions: sessionmaker[Session]) -> None: + with v2_owner_sessions.begin() as session: + session.execute(delete(LegacyHouseholdMapping)) + session.execute(delete(Household)) def test_both_commits_and_client_retry_create_distinct_sources_one_content_row( - disposable_v1_database_url: str, - disposable_v2_database_url: str, + v1_sessions: sessionmaker[OrmSession], + v2_owner_sessions: sessionmaker[Session], ) -> None: - v2_engine = create_engine(disposable_v2_database_url) - v2_sessions = sessionmaker(v2_engine, class_=Session, expire_on_commit=False) - v1_engine, v1_sessions, v1_service = _v1_service(disposable_v1_database_url) + v1_service = _v1_service(v1_sessions) try: - mirror_service = V2HouseholdService(HouseholdDatabaseSession(v2_sessions)) + mirror_service = V2HouseholdService(HouseholdDatabaseSession(v2_owner_sessions)) first = _create_v1(v1_service) first_result = process_household_event_after_commit( "us", @@ -117,32 +115,28 @@ def test_both_commits_and_client_retry_create_distinct_sources_one_content_row( ) == 2 ) - with v2_sessions() as session: + with v2_owner_sessions() as session: assert session.scalar(select(func.count()).select_from(Household)) == 1 assert ( session.scalar(select(func.count()).select_from(LegacyHouseholdMapping)) == 2 ) finally: - _cleanup_v2(v2_engine) - _cleanup_v1(v1_engine) - v1_engine.dispose() - v2_engine.dispose() + _cleanup_v2(v2_owner_sessions) + _cleanup_v1(v1_sessions) def test_destination_failure_leaves_source_and_event_pending_for_exact_replay( - disposable_v1_database_url: str, - disposable_v2_database_url: str, + v1_sessions: sessionmaker[OrmSession], + v2_owner_sessions: sessionmaker[Session], ) -> None: - v2_engine = create_engine(disposable_v2_database_url) - v2_sessions = sessionmaker(v2_engine, class_=Session, expire_on_commit=False) - v1_engine, v1_sessions, v1_service = _v1_service(disposable_v1_database_url) + v1_service = _v1_service(v1_sessions) try: creation = _create_v1(v1_service) class FailingMirror: def mirror_legacy_household(self, snapshot): - with v2_sessions.begin() as session: + with v2_owner_sessions.begin() as session: mirror_legacy_household_in_session(session, snapshot) msg = "forced transaction failure" raise OperationalError( @@ -164,7 +158,7 @@ def mirror_legacy_household(self, snapshot): assert event is not None assert event.processed_at is None assert session.get(V1Household, creation.household.id) is not None - with v2_sessions() as session: + with v2_owner_sessions() as session: assert session.scalar(select(func.count()).select_from(Household)) == 0 replay = process_household_event_after_commit( @@ -172,29 +166,25 @@ def mirror_legacy_household(self, snapshot): creation.household.id, event_service=v1_service, mirror_factory=lambda: V2HouseholdService( - HouseholdDatabaseSession(v2_sessions) + HouseholdDatabaseSession(v2_owner_sessions) ), require_pending=True, ) assert replay.mapping_created is True finally: - _cleanup_v2(v2_engine) - _cleanup_v1(v1_engine) - v1_engine.dispose() - v2_engine.dispose() + _cleanup_v2(v2_owner_sessions) + _cleanup_v1(v1_sessions) def test_replay_after_destination_commit_verifies_mapping_then_completes_event( - disposable_v1_database_url: str, - disposable_v2_database_url: str, + v1_sessions: sessionmaker[OrmSession], + v2_owner_sessions: sessionmaker[Session], ) -> None: - v2_engine = create_engine(disposable_v2_database_url) - v2_sessions = sessionmaker(v2_engine, class_=Session, expire_on_commit=False) - v1_engine, v1_sessions, v1_service = _v1_service(disposable_v1_database_url) + v1_service = _v1_service(v1_sessions) try: creation = _create_v1(v1_service) assert creation.snapshot is not None - mirror_service = V2HouseholdService(HouseholdDatabaseSession(v2_sessions)) + mirror_service = V2HouseholdService(HouseholdDatabaseSession(v2_owner_sessions)) committed = mirror_service.mirror_legacy_household(creation.snapshot) with v1_sessions() as session: @@ -218,16 +208,14 @@ def test_replay_after_destination_commit_verifies_mapping_then_completes_event( assert event is not None assert event.processed_at is not None finally: - _cleanup_v2(v2_engine) - _cleanup_v1(v1_engine) - v1_engine.dispose() - v2_engine.dispose() + _cleanup_v2(v2_owner_sessions) + _cleanup_v1(v1_sessions) def test_source_event_failure_rolls_back_the_source_household( - disposable_v1_database_url: str, + v1_sessions: sessionmaker[OrmSession], ) -> None: - v1_engine, v1_sessions, v1_service = _v1_service(disposable_v1_database_url) + v1_service = _v1_service(v1_sessions) try: with ( patch.object( @@ -246,17 +234,14 @@ def test_source_event_failure_rolls_back_the_source_household( == 0 ) finally: - _cleanup_v1(v1_engine) - v1_engine.dispose() + _cleanup_v1(v1_sessions) def test_translation_failure_retains_one_pending_event_until_explicit_replay( - disposable_v1_database_url: str, - disposable_v2_database_url: str, + v1_sessions: sessionmaker[OrmSession], + v2_owner_sessions: sessionmaker[Session], ) -> None: - v2_engine = create_engine(disposable_v2_database_url) - v2_sessions = sessionmaker(v2_engine, class_=Session, expire_on_commit=False) - v1_engine, v1_sessions, v1_service = _v1_service(disposable_v1_database_url) + v1_service = _v1_service(v1_sessions) try: creation = v1_service.create_household( "us", @@ -270,7 +255,7 @@ def test_translation_failure_retains_one_pending_event_until_explicit_replay( creation.household.id, event_service=v1_service, mirror_factory=lambda: V2HouseholdService( - HouseholdDatabaseSession(v2_sessions) + HouseholdDatabaseSession(v2_owner_sessions) ), ) @@ -278,7 +263,7 @@ def test_translation_failure_retains_one_pending_event_until_explicit_replay( event = session.get(HouseholdMirrorEvent, creation.mirror_event_id) assert event is not None assert event.processed_at is None - with v2_sessions() as session: + with v2_owner_sessions() as session: assert ( session.scalar( select(func.count()) @@ -292,22 +277,18 @@ def test_translation_failure_retains_one_pending_event_until_explicit_replay( == 0 ) finally: - _cleanup_v2(v2_engine) - _cleanup_v1(v1_engine) - v1_engine.dispose() - v2_engine.dispose() + _cleanup_v2(v2_owner_sessions) + _cleanup_v1(v1_sessions) def test_changed_retained_event_fingerprint_cannot_mutate_destination( - disposable_v1_database_url: str, - disposable_v2_database_url: str, + v1_sessions: sessionmaker[OrmSession], + v2_owner_sessions: sessionmaker[Session], ) -> None: - v2_engine = create_engine(disposable_v2_database_url) - v2_sessions = sessionmaker(v2_engine, class_=Session, expire_on_commit=False) - v1_engine, v1_sessions, v1_service = _v1_service(disposable_v1_database_url) + v1_service = _v1_service(v1_sessions) try: creation = _create_v1(v1_service) - mirror_service = V2HouseholdService(HouseholdDatabaseSession(v2_sessions)) + mirror_service = V2HouseholdService(HouseholdDatabaseSession(v2_owner_sessions)) committed = process_household_event_after_commit( "us", creation.household.id, @@ -331,7 +312,7 @@ def test_changed_retained_event_fingerprint_cannot_mutate_destination( mirror_factory=lambda: mirror_service, ) - with v2_sessions() as session: + with v2_owner_sessions() as session: mappings = session.scalars( select(LegacyHouseholdMapping).where( LegacyHouseholdMapping.country_id == "us", @@ -341,21 +322,17 @@ def test_changed_retained_event_fingerprint_cannot_mutate_destination( assert len(mappings) == 1 assert mappings[0].household_id == committed.household_id finally: - _cleanup_v2(v2_engine) - _cleanup_v1(v1_engine) - v1_engine.dispose() - v2_engine.dispose() + _cleanup_v2(v2_owner_sessions) + _cleanup_v1(v1_sessions) @pytest.mark.parametrize("country_id", ["us", "uk"]) def test_cloud_sql_only_writes_create_no_event_or_destination_mapping( country_id: str, - disposable_v1_database_url: str, - disposable_v2_database_url: str, + v1_sessions: sessionmaker[OrmSession], + v2_owner_sessions: sessionmaker[Session], ) -> None: - v2_engine = create_engine(disposable_v2_database_url) - v2_sessions = sessionmaker(v2_engine, class_=Session, expire_on_commit=False) - v1_engine, v1_sessions, v1_service = _v1_service(disposable_v1_database_url) + v1_service = _v1_service(v1_sessions) try: creation = v1_service.create_household( country_id, @@ -371,7 +348,7 @@ def test_cloud_sql_only_writes_create_no_event_or_destination_mapping( session.scalar(select(func.count()).select_from(HouseholdMirrorEvent)) == 0 ) - with v2_sessions() as session: + with v2_owner_sessions() as session: assert ( session.scalar( select(func.count()) @@ -385,7 +362,5 @@ def test_cloud_sql_only_writes_create_no_event_or_destination_mapping( == 0 ) finally: - _cleanup_v2(v2_engine) - _cleanup_v1(v1_engine) - v1_engine.dispose() - v2_engine.dispose() + _cleanup_v2(v2_owner_sessions) + _cleanup_v1(v1_sessions) diff --git a/tests/integration/test_v1_policy_dual_write.py b/tests/integration/test_v1_policy_dual_write.py index 5c026d112..98b8a5474 100644 --- a/tests/integration/test_v1_policy_dual_write.py +++ b/tests/integration/test_v1_policy_dual_write.py @@ -2,11 +2,11 @@ from __future__ import annotations +from typing import TYPE_CHECKING + import pytest -from sqlalchemy import create_engine, delete, func, select +from sqlalchemy import delete, func, select from sqlalchemy.exc import OperationalError -from sqlalchemy.orm import sessionmaker -from sqlmodel import Session from policyengine_api.constants import POLICYENGINE_VERSION from policyengine_api.data.v1_models import Policy as V1Policy @@ -31,22 +31,26 @@ mirror_legacy_policy_in_session, ) +if TYPE_CHECKING: + from sqlalchemy.orm import Session as OrmSession + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + -def _v1_service(database_url: str): - engine = create_engine(database_url) - with engine.begin() as connection: - connection.execute(delete(V1Policy)) - sessions = sessionmaker(engine, expire_on_commit=False) - return engine, PolicyService(sessions) +def _v1_service(v1_sessions: sessionmaker[OrmSession]) -> PolicyService: + _cleanup_v1(v1_sessions) + return PolicyService(v1_sessions) -def _cleanup_v1(engine) -> None: - with engine.begin() as connection: - connection.execute(delete(V1Policy)) +def _cleanup_v1(v1_sessions: sessionmaker[OrmSession]) -> None: + with v1_sessions.begin() as session: + session.execute(delete(V1Policy)) -def _seed_catalog(v2_sessions, country_id: str = "us") -> tuple[object, str]: - with v2_sessions.begin() as session: +def _seed_catalog( + v2_owner_sessions: sessionmaker[Session], country_id: str = "us" +) -> tuple[object, str]: + with v2_owner_sessions.begin() as session: model = TaxBenefitModel(name=f"policyengine-{country_id}") version = TaxBenefitModelVersion( model=model, @@ -63,38 +67,34 @@ def _seed_catalog(v2_sessions, country_id: str = "us") -> tuple[object, str]: return model.id, parameter.name -def _cleanup_v2(v2_engine, model_id) -> None: +def _cleanup_v2(v2_owner_sessions: sessionmaker[Session], model_id) -> None: if model_id is None: return - with v2_engine.begin() as connection: + with v2_owner_sessions.begin() as session: policy_ids = select(Policy.id).where(Policy.tax_benefit_model_id == model_id) - connection.execute( + session.execute( delete(LegacyPolicyMapping).where( LegacyPolicyMapping.policy_id.in_(policy_ids) ) ) - connection.execute( + session.execute( delete(ParameterValue).where(ParameterValue.policy_id.in_(policy_ids)) ) - connection.execute( - delete(Policy).where(Policy.tax_benefit_model_id == model_id) - ) + session.execute(delete(Policy).where(Policy.tax_benefit_model_id == model_id)) version_ids = select(TaxBenefitModelVersion.id).where( TaxBenefitModelVersion.model_id == model_id ) - connection.execute( + session.execute( delete(Parameter).where( Parameter.tax_benefit_model_version_id.in_(version_ids) ) ) - connection.execute( + session.execute( delete(TaxBenefitModelVersion).where( TaxBenefitModelVersion.model_id == model_id ) ) - connection.execute( - delete(TaxBenefitModel).where(TaxBenefitModel.id == model_id) - ) + session.execute(delete(TaxBenefitModel).where(TaxBenefitModel.id == model_id)) def _create_v1( @@ -113,16 +113,14 @@ def _create_v1( @pytest.mark.parametrize("country_id", ["us", "uk"]) def test_both_commits_and_interrupted_response_retry_resolve_one_mapping( country_id: str, - disposable_v1_database_url: str, - disposable_v2_database_url: str, + v1_sessions: sessionmaker[OrmSession], + v2_owner_sessions: sessionmaker[Session], ) -> None: - v2_engine = create_engine(disposable_v2_database_url) - v2_sessions = sessionmaker(v2_engine, class_=Session, expire_on_commit=False) - v1_engine, v1_service = _v1_service(disposable_v1_database_url) + v1_service = _v1_service(v1_sessions) model_id = None try: - model_id, parameter_name = _seed_catalog(v2_sessions, country_id) - mirror_service = V2PolicyService(PolicyDatabaseSession(v2_sessions)) + model_id, parameter_name = _seed_catalog(v2_owner_sessions, country_id) + mirror_service = V2PolicyService(PolicyDatabaseSession(v2_owner_sessions)) creation = _create_v1(v1_service, parameter_name, country_id) first = mirror_policy_after_commit( creation.snapshot, @@ -140,7 +138,7 @@ def test_both_commits_and_interrupted_response_retry_resolve_one_mapping( assert creation.is_existing_policy is False assert retry_creation.is_existing_policy is True assert retry.policy_id == first.policy_id - with v2_sessions() as session: + with v2_owner_sessions() as session: assert ( session.scalar(select(func.count()).select_from(LegacyPolicyMapping)) == 1 @@ -148,24 +146,20 @@ def test_both_commits_and_interrupted_response_retry_resolve_one_mapping( assert session.scalar(select(func.count()).select_from(Policy)) == 1 assert v1_service.get_policy(country_id, creation.policy_id) is not None finally: - _cleanup_v2(v2_engine, model_id) - _cleanup_v1(v1_engine) - v1_engine.dispose() - v2_engine.dispose() + _cleanup_v2(v2_owner_sessions, model_id) + _cleanup_v1(v1_sessions) def test_catalog_failure_leaves_cloud_sql_committed_and_retry_completes( - disposable_v1_database_url: str, - disposable_v2_database_url: str, + v1_sessions: sessionmaker[OrmSession], + v2_owner_sessions: sessionmaker[Session], ) -> None: - v2_engine = create_engine(disposable_v2_database_url) - v2_sessions = sessionmaker(v2_engine, class_=Session, expire_on_commit=False) - v1_engine, v1_service = _v1_service(disposable_v1_database_url) + v1_service = _v1_service(v1_sessions) model_id = None parameter_name = "gov.phase10.us.cross_database_rate" try: creation = _create_v1(v1_service, parameter_name) - mirror_service = V2PolicyService(PolicyDatabaseSession(v2_sessions)) + mirror_service = V2PolicyService(PolicyDatabaseSession(v2_owner_sessions)) with pytest.raises(PolicyMirrorUnavailableError): mirror_policy_after_commit( @@ -174,13 +168,13 @@ def test_catalog_failure_leaves_cloud_sql_committed_and_retry_completes( ) assert v1_service.get_policy("us", creation.policy_id) is not None - with v2_sessions() as session: + with v2_owner_sessions() as session: assert ( session.scalar(select(func.count()).select_from(LegacyPolicyMapping)) == 0 ) - model_id, _parameter_name = _seed_catalog(v2_sessions) + model_id, _parameter_name = _seed_catalog(v2_owner_sessions) retry_creation = _create_v1(v1_service, parameter_name) result = mirror_policy_after_commit( retry_creation.snapshot, @@ -190,27 +184,23 @@ def test_catalog_failure_leaves_cloud_sql_committed_and_retry_completes( assert retry_creation.is_existing_policy is True assert result.mapping_created is True finally: - _cleanup_v2(v2_engine, model_id) - _cleanup_v1(v1_engine) - v1_engine.dispose() - v2_engine.dispose() + _cleanup_v2(v2_owner_sessions, model_id) + _cleanup_v1(v1_sessions) def test_supabase_transaction_failure_rolls_back_and_has_no_background_repair( - disposable_v1_database_url: str, - disposable_v2_database_url: str, + v1_sessions: sessionmaker[OrmSession], + v2_owner_sessions: sessionmaker[Session], ) -> None: - v2_engine = create_engine(disposable_v2_database_url) - v2_sessions = sessionmaker(v2_engine, class_=Session, expire_on_commit=False) - v1_engine, v1_service = _v1_service(disposable_v1_database_url) + v1_service = _v1_service(v1_sessions) model_id = None try: - model_id, parameter_name = _seed_catalog(v2_sessions) + model_id, parameter_name = _seed_catalog(v2_owner_sessions) creation = _create_v1(v1_service, parameter_name) class FailingMirror: def mirror_legacy_policy(self, snapshot): - with v2_sessions.begin() as session: + with v2_owner_sessions.begin() as session: mirror_legacy_policy_in_session(session, snapshot) msg = "forced transaction failure" raise OperationalError( @@ -225,29 +215,29 @@ def mirror_legacy_policy(self, snapshot): mirror_factory=FailingMirror, ) - with v2_sessions() as session: + with v2_owner_sessions() as session: assert session.scalar(select(func.count()).select_from(Policy)) == 0 assert ( session.scalar(select(func.count()).select_from(LegacyPolicyMapping)) == 0 ) - with v1_engine.connect() as connection: - assert connection.scalar(select(func.count()).select_from(V1Policy)) == 1 + with v1_sessions() as v1_session: + assert v1_session.scalar(select(func.count()).select_from(V1Policy)) == 1 # No process is scheduled to change this state. Only an explicit retry # invokes the mirror and creates the missing destination rows. - with v2_sessions() as session: + with v2_owner_sessions() as session: assert ( session.scalar(select(func.count()).select_from(LegacyPolicyMapping)) == 0 ) result = mirror_policy_after_commit( creation.snapshot, - mirror_factory=lambda: V2PolicyService(PolicyDatabaseSession(v2_sessions)), + mirror_factory=lambda: V2PolicyService( + PolicyDatabaseSession(v2_owner_sessions) + ), ) assert result.mapping_created is True finally: - _cleanup_v2(v2_engine, model_id) - _cleanup_v1(v1_engine) - v1_engine.dispose() - v2_engine.dispose() + _cleanup_v2(v2_owner_sessions, model_id) + _cleanup_v1(v1_sessions) diff --git a/tests/integration/test_v1_schema_metadata_compatibility.py b/tests/integration/test_v1_schema_metadata_compatibility.py index f08fdc6ae..10ede04df 100644 --- a/tests/integration/test_v1_schema_metadata_compatibility.py +++ b/tests/integration/test_v1_schema_metadata_compatibility.py @@ -3,25 +3,21 @@ import os import pytest -from sqlalchemy import create_engine +from policyengine_api.data.orm import unpooled_v1_sessions from scripts.v1_database_migration import metadata_differences def compare_existing_schema(database_url: str) -> list[str]: """Return metadata drift without mutating the target database.""" - engine = create_engine(database_url) - try: - with engine.connect() as connection: - return sorted(metadata_differences(connection)) - finally: - engine.dispose() + with unpooled_v1_sessions(database_url) as sessions, sessions() as session: + return sorted(metadata_differences(session)) @pytest.mark.skipif( "STAGE7_EXISTING_DATABASE_URL" not in os.environ, reason="A read-only existing Cloud SQL URL was not supplied", ) -def test_live_existing_schema_matches_metadata_without_mutation(): +def test_live_existing_schema_matches_metadata_without_mutation() -> None: database_url = os.environ["STAGE7_EXISTING_DATABASE_URL"] assert compare_existing_schema(database_url) == [] diff --git a/tests/integration/test_v1_user_policy_dual_write.py b/tests/integration/test_v1_user_policy_dual_write.py index 1e2bc2fe6..8ae92130e 100644 --- a/tests/integration/test_v1_user_policy_dual_write.py +++ b/tests/integration/test_v1_user_policy_dual_write.py @@ -2,10 +2,10 @@ from __future__ import annotations +from typing import TYPE_CHECKING + import pytest -from sqlalchemy import create_engine, delete, func, select -from sqlalchemy.orm import sessionmaker -from sqlmodel import Session +from sqlalchemy import delete, func, select from policyengine_api.constants import POLICYENGINE_VERSION from policyengine_api.data.v1_models import ( @@ -42,26 +42,28 @@ ) from policyengine_api.services.v2.user_policies.services import V2UserPolicyService +if TYPE_CHECKING: + from sqlalchemy.orm import Session as OrmSession + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + -def _v1_services(database_url: str): - engine = create_engine(database_url) - with engine.begin() as connection: - connection.execute(delete(UserPolicyMirrorEvent)) - connection.execute(delete(V1UserPolicy)) - connection.execute(delete(V1Policy)) - sessions = sessionmaker(engine, expire_on_commit=False) - return engine, PolicyService(sessions), UserPolicyService(sessions), sessions +def _v1_services( + v1_sessions: sessionmaker[OrmSession], +) -> tuple[PolicyService, UserPolicyService]: + _cleanup_v1(v1_sessions) + return PolicyService(v1_sessions), UserPolicyService(v1_sessions) -def _cleanup_v1(engine) -> None: - with engine.begin() as connection: - connection.execute(delete(UserPolicyMirrorEvent)) - connection.execute(delete(V1UserPolicy)) - connection.execute(delete(V1Policy)) +def _cleanup_v1(v1_sessions: sessionmaker[OrmSession]) -> None: + with v1_sessions.begin() as session: + session.execute(delete(UserPolicyMirrorEvent)) + session.execute(delete(V1UserPolicy)) + session.execute(delete(V1Policy)) -def _seed_catalog(sessions): - with sessions.begin() as session: +def _seed_catalog(v2_owner_sessions: sessionmaker[Session]): + with v2_owner_sessions.begin() as session: model = TaxBenefitModel(name="policyengine-us") version = TaxBenefitModelVersion( model=model, @@ -100,20 +102,16 @@ def _saved_values(reform_id: int, **changes): return values -def _cleanup(engine, model_id) -> None: +def _cleanup(v2_owner_sessions: sessionmaker[Session], model_id) -> None: if model_id is None: return - with engine.begin() as connection: - user_ids = ( - connection.execute( - select(LegacyUserMapping.user_id).where( - LegacyUserMapping.legacy_user_id == "auth0|cross-database" - ) + with v2_owner_sessions.begin() as session: + user_ids = session.scalars( + select(LegacyUserMapping.user_id).where( + LegacyUserMapping.legacy_user_id == "auth0|cross-database" ) - .scalars() - .all() - ) - connection.execute( + ).all() + session.execute( delete(LegacyUserMapping).where( LegacyUserMapping.legacy_user_id == "auth0|cross-database" ) @@ -122,57 +120,47 @@ def _cleanup(engine, model_id) -> None: association_ids = select(UserPolicy.id).where( UserPolicy.policy_id.in_(policy_ids) ) - connection.execute( + session.execute( delete(LegacyUserPolicyMapping).where( LegacyUserPolicyMapping.user_policy_id.in_(association_ids) ) ) - connection.execute( - delete(UserPolicy).where(UserPolicy.policy_id.in_(policy_ids)) - ) + session.execute(delete(UserPolicy).where(UserPolicy.policy_id.in_(policy_ids))) if user_ids: - connection.execute(delete(User).where(User.id.in_(user_ids))) - connection.execute( + session.execute(delete(User).where(User.id.in_(user_ids))) + session.execute( delete(LegacyPolicyMapping).where( LegacyPolicyMapping.policy_id.in_(policy_ids) ) ) - connection.execute( + session.execute( delete(ParameterValue).where(ParameterValue.policy_id.in_(policy_ids)) ) - connection.execute( - delete(Policy).where(Policy.tax_benefit_model_id == model_id) - ) + session.execute(delete(Policy).where(Policy.tax_benefit_model_id == model_id)) version_ids = select(TaxBenefitModelVersion.id).where( TaxBenefitModelVersion.model_id == model_id ) - connection.execute( + session.execute( delete(Parameter).where( Parameter.tax_benefit_model_version_id.in_(version_ids) ) ) - connection.execute( + session.execute( delete(TaxBenefitModelVersion).where( TaxBenefitModelVersion.model_id == model_id ) ) - connection.execute( - delete(TaxBenefitModel).where(TaxBenefitModel.id == model_id) - ) + session.execute(delete(TaxBenefitModel).where(TaxBenefitModel.id == model_id)) def test_create_update_and_v1_only_change_mirror_one_association( - disposable_v1_database_url: str, - disposable_v2_database_url: str, + v1_sessions: sessionmaker[OrmSession], + v2_owner_sessions: sessionmaker[Session], ) -> None: - v2_engine = create_engine(disposable_v2_database_url) - v2_sessions = sessionmaker(v2_engine, class_=Session, expire_on_commit=False) - v1_engine, policy_service, saved_service, _v1_sessions = _v1_services( - disposable_v1_database_url - ) + policy_service, saved_service = _v1_services(v1_sessions) model_id = None try: - model_id, parameter_name = _seed_catalog(v2_sessions) + model_id, parameter_name = _seed_catalog(v2_owner_sessions) reform = policy_service.set_policy( "us", "Legacy reform label", @@ -183,7 +171,9 @@ def test_create_update_and_v1_only_change_mirror_one_association( _saved_values(reform.policy_id), record_mirror_event=True, ) - mirror_service = V2UserPolicyService(UserPolicyDatabaseSession(v2_sessions)) + mirror_service = V2UserPolicyService( + UserPolicyDatabaseSession(v2_owner_sessions) + ) first = mirror_pending_user_policy_events_after_commit( "us", created.user_policy.id, @@ -232,7 +222,7 @@ def test_create_update_and_v1_only_change_mirror_one_association( assert first.association_id == v1_only_result.association_id assert rename_result.association_updated is True assert v1_only_result.association_updated is False - with v2_sessions() as session: + with v2_owner_sessions() as session: association = session.get(UserPolicy, first.association_id) assert association.name == "Renamed" assert association.description is None @@ -248,21 +238,15 @@ def test_create_update_and_v1_only_change_mirror_one_association( mapping = session.scalar(select(LegacyUserPolicyMapping)) assert mapping.last_applied_source_revision == 3 finally: - _cleanup(v2_engine, model_id) - _cleanup_v1(v1_engine) - v1_engine.dispose() - v2_engine.dispose() + _cleanup(v2_owner_sessions, model_id) + _cleanup_v1(v1_sessions) def test_failure_after_cloud_commit_and_identical_create_retry_are_idempotent( - disposable_v1_database_url: str, - disposable_v2_database_url: str, + v1_sessions: sessionmaker[OrmSession], + v2_owner_sessions: sessionmaker[Session], ) -> None: - v2_engine = create_engine(disposable_v2_database_url) - v2_sessions = sessionmaker(v2_engine, class_=Session, expire_on_commit=False) - v1_engine, policy_service, saved_service, v1_sessions = _v1_services( - disposable_v1_database_url - ) + policy_service, saved_service = _v1_services(v1_sessions) model_id = None parameter_name = "gov.phase10.cross_database_saved_rate" try: @@ -275,7 +259,9 @@ def test_failure_after_cloud_commit_and_identical_create_retry_are_idempotent( _saved_values(reform.policy_id), record_mirror_event=True, ) - mirror_service = V2UserPolicyService(UserPolicyDatabaseSession(v2_sessions)) + mirror_service = V2UserPolicyService( + UserPolicyDatabaseSession(v2_owner_sessions) + ) with pytest.raises(UserPolicyMirrorUnavailableError): mirror_pending_user_policy_events_after_commit( @@ -298,7 +284,7 @@ def test_failure_after_cloud_commit_and_identical_create_retry_are_idempotent( ) event = session.scalar(select(UserPolicyMirrorEvent)) assert event.processed_at is None - with v2_sessions() as session: + with v2_owner_sessions() as session: assert session.scalar(select(func.count()).select_from(User)) == 0 assert ( session.scalar(select(func.count()).select_from(LegacyUserMapping)) == 0 @@ -310,7 +296,7 @@ def test_failure_after_cloud_commit_and_identical_create_retry_are_idempotent( == 0 ) - model_id, _parameter_name = _seed_catalog(v2_sessions) + model_id, _parameter_name = _seed_catalog(v2_owner_sessions) retry = saved_service.create_or_get_user_policy( _saved_values(reform.policy_id, number_of_provisions=99), record_mirror_event=True, @@ -333,7 +319,7 @@ def test_failure_after_cloud_commit_and_identical_create_retry_are_idempotent( events = session.scalars(select(UserPolicyMirrorEvent)).all() assert [event.source_revision for event in events] == [1, 2] assert all(event.processed_at is not None for event in events) - with v2_sessions() as session: + with v2_owner_sessions() as session: mapping = session.scalar(select(LegacyUserPolicyMapping)) assert mapping.last_applied_source_revision == 2 assert session.scalar(select(func.count()).select_from(User)) == 1 @@ -341,24 +327,18 @@ def test_failure_after_cloud_commit_and_identical_create_retry_are_idempotent( session.scalar(select(func.count()).select_from(LegacyUserMapping)) == 1 ) finally: - _cleanup(v2_engine, model_id) - _cleanup_v1(v1_engine) - v1_engine.dispose() - v2_engine.dispose() + _cleanup(v2_owner_sessions, model_id) + _cleanup_v1(v1_sessions) def test_destination_commit_replays_when_source_processing_marker_is_missing( - disposable_v1_database_url: str, - disposable_v2_database_url: str, + v1_sessions: sessionmaker[OrmSession], + v2_owner_sessions: sessionmaker[Session], ) -> None: - v2_engine = create_engine(disposable_v2_database_url) - v2_sessions = sessionmaker(v2_engine, class_=Session, expire_on_commit=False) - v1_engine, policy_service, saved_service, v1_sessions = _v1_services( - disposable_v1_database_url - ) + policy_service, saved_service = _v1_services(v1_sessions) model_id = None try: - model_id, parameter_name = _seed_catalog(v2_sessions) + model_id, parameter_name = _seed_catalog(v2_owner_sessions) reform = policy_service.set_policy( "us", "Legacy reform label", @@ -369,7 +349,9 @@ def test_destination_commit_replays_when_source_processing_marker_is_missing( _saved_values(reform.policy_id), record_mirror_event=True, ) - mirror_service = V2UserPolicyService(UserPolicyDatabaseSession(v2_sessions)) + mirror_service = V2UserPolicyService( + UserPolicyDatabaseSession(v2_owner_sessions) + ) committed = mirror_user_policy_after_commit( created.snapshot, @@ -397,7 +379,7 @@ def test_destination_commit_replays_when_source_processing_marker_is_missing( with v1_sessions() as session: event = session.scalar(select(UserPolicyMirrorEvent)) assert event.processed_at is not None - with v2_sessions() as session: + with v2_owner_sessions() as session: assert session.scalar(select(func.count()).select_from(UserPolicy)) == 1 assert session.scalar(select(func.count()).select_from(User)) == 1 assert ( @@ -406,7 +388,5 @@ def test_destination_commit_replays_when_source_processing_marker_is_missing( mapping = session.scalar(select(LegacyUserPolicyMapping)) assert mapping.last_applied_source_revision == 1 finally: - _cleanup(v2_engine, model_id) - _cleanup_v1(v1_engine) - v1_engine.dispose() - v2_engine.dispose() + _cleanup(v2_owner_sessions, model_id) + _cleanup_v1(v1_sessions) diff --git a/tests/integration/test_v2_budget_window_report_creation.py b/tests/integration/test_v2_budget_window_report_creation.py index 25f8d1909..cf62a1d16 100644 --- a/tests/integration/test_v2_budget_window_report_creation.py +++ b/tests/integration/test_v2_budget_window_report_creation.py @@ -19,10 +19,6 @@ from alembic.config import Config from fastapi.testclient import TestClient from flask import Flask -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import NullPool -from sqlmodel import Session from policyengine_api.asgi_factory import create_asgi_app from policyengine_api.constants import REPO @@ -70,13 +66,15 @@ ) if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator - from sqlalchemy import Engine + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session from policyengine_api.services.v2.simulation_service.types import ( BudgetWindowReportCreationInput, ) + from tests.integration.conftest import ManagedV2Roles from tests.integration.stored_report_rows import CatalogRows CURRENT_VERSIONS = {"country_package_version": "1.5.0", "policyengine_version": "4.2.0"} @@ -90,7 +88,7 @@ def current_versions(country_id: str) -> PackageVersions: class StoringSimulationService: """Store the budget window the simulation service would create; answer its IDs.""" - engine: Engine + owner_sessions: sessionmaker[Session] catalog: CatalogRows windows: list[BudgetWindowReportCreationInput] = field(default_factory=list) @@ -98,22 +96,22 @@ def submit_budget_window( self, report: BudgetWindowReportCreationInput ) -> SubmittedBudgetWindow: self.windows.append(report) - with self.engine.begin() as connection: + with self.owner_sessions.begin() as session: stored = store_report( - connection, + session, self.catalog, budget_window_size=report.budget_window_size, year=report.year, ) pending = RunSettings(versions=CURRENT_VERSIONS, status="pending") window_run_id = store_budget_window_run( - connection, self.catalog, stored, pending + session, self.catalog, stored, pending ) for year in range(report.year, report.year + report.budget_window_size): store_report_run( - connection, + session, self.catalog, - store_year_simulations(connection, self.catalog, stored, year), + store_year_simulations(session, self.catalog, stored, year), RunSettings( versions=CURRENT_VERSIONS, status="pending", @@ -128,27 +126,28 @@ def submit_budget_window( @pytest.fixture -def owner_engine(disposable_v2_database_url: str) -> Iterator[Engine]: +def owner_sessions( + v2_owner_sessions: sessionmaker[Session], +) -> sessionmaker[Session]: command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - yield engine - engine.dispose() + return v2_owner_sessions @pytest.fixture -def catalog(owner_engine: Engine) -> Iterator[CatalogRows]: - with owner_engine.begin() as connection: - stored = store_catalog(connection, "us") +def catalog(owner_sessions: sessionmaker[Session]) -> Iterator[CatalogRows]: + with owner_sessions.begin() as session: + stored = store_catalog(session, "us") yield stored - with owner_engine.begin() as connection: - delete_catalog(connection, stored) + with owner_sessions.begin() as session: + delete_catalog(session, stored) @pytest.fixture -def runtime_sessions(managed_v2_roles, v2_engine_as_role) -> Iterator[Any]: - engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - yield sessionmaker(engine, class_=Session) - engine.dispose() +def runtime_sessions( + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], +) -> sessionmaker[Session]: + return v2_sessions_as_role(managed_v2_roles.runtime) def client_for( @@ -202,9 +201,11 @@ def window_body(policy_id: UUID) -> dict[str, Any]: def test_a_created_budget_window_is_answered_as_the_tables_hold_it( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - simulation_service = StoringSimulationService(owner_engine, catalog) + simulation_service = StoringSimulationService(owner_sessions, catalog) response = client_for(runtime_sessions, simulation_service).post( "/v2/reports?country_id=us", json=window_body(catalog.policy_id) @@ -229,9 +230,11 @@ def test_a_created_budget_window_is_answered_as_the_tables_hold_it( def test_a_budget_window_naming_a_policy_the_country_does_not_store_is_not_sent( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - simulation_service = StoringSimulationService(owner_engine, catalog) + simulation_service = StoringSimulationService(owner_sessions, catalog) response = client_for(runtime_sessions, simulation_service).post( "/v2/reports?country_id=us", json=window_body(uuid4()) diff --git a/tests/integration/test_v2_budget_window_report_reads.py b/tests/integration/test_v2_budget_window_report_reads.py index 71548db1e..01be7baf1 100644 --- a/tests/integration/test_v2_budget_window_report_reads.py +++ b/tests/integration/test_v2_budget_window_report_reads.py @@ -20,10 +20,6 @@ from alembic.config import Config from fastapi.testclient import TestClient from flask import Flask -from sqlalchemy import create_engine, event -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import NullPool -from sqlmodel import Session from policyengine_api.asgi_factory import create_asgi_app from policyengine_api.constants import REPO @@ -37,6 +33,7 @@ StoredReportDatabaseSession, ) from policyengine_api.services.v2.stored_reports.services import V2StoredReportService +from tests.fixtures.database_sessions import recorded_statements from tests.fixtures.economy_results import RunIds, uk_economy_result, us_economy_result from tests.integration.stored_report_rows import ( STARTED_AT, @@ -51,10 +48,12 @@ ) if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator - from sqlalchemy import Connection, Engine + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + from tests.integration.conftest import ManagedV2Roles from tests.integration.stored_report_rows import CatalogRows, StoredReport CURRENT_VERSIONS = {"country_package_version": "1.5.0", "policyengine_version": "4.2.0"} @@ -74,31 +73,31 @@ def current_versions(country_id: str) -> PackageVersions: @pytest.fixture -def owner_engine(disposable_v2_database_url: str) -> Iterator[Engine]: +def owner_sessions( + v2_owner_sessions: sessionmaker[Session], +) -> sessionmaker[Session]: command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - yield engine - engine.dispose() + return v2_owner_sessions @pytest.fixture -def catalogs(owner_engine: Engine) -> Iterator[dict[str, CatalogRows]]: +def catalogs(owner_sessions: sessionmaker[Session]) -> Iterator[dict[str, CatalogRows]]: """Store a US and a UK catalog, and delete them and their reports after.""" - with owner_engine.begin() as connection: - stored = { - country: store_catalog(connection, country) for country in ("us", "uk") - } + with owner_sessions.begin() as session: + stored = {country: store_catalog(session, country) for country in ("us", "uk")} yield stored - with owner_engine.begin() as connection: + with owner_sessions.begin() as session: for catalog in stored.values(): - delete_catalog(connection, catalog) + delete_catalog(session, catalog) @pytest.fixture -def client(managed_v2_roles, v2_engine_as_role) -> Iterator[TestClient]: +def client( + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], +) -> TestClient: """Serve the report routes as the runtime role.""" - runtime_engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - sessions = sessionmaker(runtime_engine, class_=Session) + sessions = v2_sessions_as_role(managed_v2_roles.runtime) dependencies = NativeRouteDependencies( readiness_probe=lambda: True, gateway_client_factory=lambda: None, @@ -112,12 +111,11 @@ def client(managed_v2_roles, v2_engine_as_role) -> Iterator[TestClient]: specification=RouteImplementation.FLASK_FALLBACK, metadata=RouteImplementation.FLASK_FALLBACK, ) - yield TestClient( + return TestClient( create_asgi_app( Flask(__name__), dependencies=dependencies, route_settings=settings ) ) - runtime_engine.dispose() def year_result(country: str, year: int) -> dict[str, Any]: @@ -148,7 +146,7 @@ class StoredWindow: def store_window( - connection: Connection, + session: Session, catalog: CatalogRows, report: StoredReport, window: StoredWindow, @@ -158,13 +156,13 @@ def store_window( Return the window run's ID and each year's report and simulation run IDs. """ settings = window.settings - window_run_id = store_budget_window_run(connection, catalog, report, settings) + window_run_id = store_budget_window_run(session, catalog, report, settings) year_run_ids = {} for year, status in window.year_statuses.items(): run_ids = store_report_run( - connection, + session, catalog, - store_year_simulations(connection, catalog, report, year), + store_year_simulations(session, catalog, report, year), RunSettings( versions=settings.versions, status=status, @@ -196,13 +194,15 @@ def read_item(client: TestClient, report_id: UUID, country: str) -> dict[str, An def test_a_budget_window_reads_its_newest_run_years_and_result( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: catalog = catalogs["us"] - with owner_engine.begin() as connection: - report = store_report(connection, catalog, budget_window_size=3) + with owner_sessions.begin() as session: + report = store_report(session, catalog, budget_window_size=3) window_run_id, year_run_ids = store_window( - connection, + session, catalog, report, StoredWindow( @@ -266,13 +266,15 @@ def test_a_budget_window_reads_its_newest_run_years_and_result( def test_a_uk_budget_window_has_no_state_tax( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: catalog = catalogs["uk"] - with owner_engine.begin() as connection: - report = store_report(connection, catalog, budget_window_size=2) + with owner_sessions.begin() as session: + report = store_report(session, catalog, budget_window_size=2) store_window( - connection, + session, catalog, report, StoredWindow( @@ -291,13 +293,15 @@ def test_a_uk_budget_window_has_no_state_tax( def test_a_running_window_answers_each_years_status_without_a_result( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: catalog = catalogs["us"] - with owner_engine.begin() as connection: - report = store_report(connection, catalog, budget_window_size=3) + with owner_sessions.begin() as session: + report = store_report(session, catalog, budget_window_size=3) store_window( - connection, + session, catalog, report, StoredWindow( @@ -319,14 +323,16 @@ def test_a_running_window_answers_each_years_status_without_a_result( def test_a_failed_window_says_why_and_which_years_failed( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: catalog = catalogs["us"] message = "budget_window_year_failed: The budget window's 2027 report run failed." - with owner_engine.begin() as connection: - report = store_report(connection, catalog, budget_window_size=3) + with owner_sessions.begin() as session: + report = store_report(session, catalog, budget_window_size=3) store_window( - connection, + session, catalog, report, StoredWindow( @@ -346,11 +352,13 @@ def test_a_failed_window_says_why_and_which_years_failed( def test_a_budget_window_with_no_run_answers_its_definition( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: catalog = catalogs["us"] - with owner_engine.begin() as connection: - report = store_report(connection, catalog, budget_window_size=10) + with owner_sessions.begin() as session: + report = store_report(session, catalog, budget_window_size=10) item = read_item(client, report.report_id, "us") @@ -359,13 +367,15 @@ def test_a_budget_window_with_no_run_answers_its_definition( def test_an_older_succeeded_window_run_is_read_before_a_newer_pending_one( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: catalog = catalogs["us"] - with owner_engine.begin() as connection: - report = store_report(connection, catalog, budget_window_size=2) + with owner_sessions.begin() as session: + report = store_report(session, catalog, budget_window_size=2) succeeded_run_id, _ = store_window( - connection, + session, catalog, report, StoredWindow( @@ -374,7 +384,7 @@ def test_an_older_succeeded_window_run_is_read_before_a_newer_pending_one( ), ) store_window( - connection, + session, catalog, report, StoredWindow( @@ -396,15 +406,17 @@ def test_an_older_succeeded_window_run_is_read_before_a_newer_pending_one( def test_of_two_window_runs_created_together_the_larger_id_is_the_newest( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: catalog = catalogs["us"] - with owner_engine.begin() as connection: - report = store_report(connection, catalog, budget_window_size=1) + with owner_sessions.begin() as session: + report = store_report(session, catalog, budget_window_size=1) # The larger ID is stored first, so insertion order can't pick it. for run_id, status in ((LARGER_RUN_ID, "failed"), (SMALLER_RUN_ID, "pending")): store_window( - connection, + session, catalog, report, StoredWindow( @@ -422,13 +434,15 @@ def test_of_two_window_runs_created_together_the_larger_id_is_the_newest( def test_a_succeeded_window_missing_a_years_result_is_unreadable( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: catalog = catalogs["us"] - with owner_engine.begin() as connection: - report = store_report(connection, catalog, budget_window_size=2) + with owner_sessions.begin() as session: + report = store_report(session, catalog, budget_window_size=2) store_window( - connection, + session, catalog, report, StoredWindow( @@ -448,11 +462,13 @@ def test_a_succeeded_window_missing_a_years_result_is_unreadable( def test_a_budget_window_is_not_found_in_another_country( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: catalog = catalogs["us"] - with owner_engine.begin() as connection: - report = store_report(connection, catalog, budget_window_size=2) + with owner_sessions.begin() as session: + report = store_report(session, catalog, budget_window_size=2) response = client.get(f"/v2/reports/{report.report_id}?country_id=uk") @@ -460,21 +476,23 @@ def test_a_budget_window_is_not_found_in_another_country( def test_listing_answers_budget_windows_with_their_years_beside_economy_reports( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: catalog = catalogs["us"] - with owner_engine.begin() as connection: - economy = store_report(connection, catalog) + with owner_sessions.begin() as session: + economy = store_report(session, catalog) store_report_run( - connection, + session, catalog, economy, RunSettings(versions=CURRENT_VERSIONS), result=us_economy_result(), ) - succeeded_window = store_report(connection, catalog, budget_window_size=2) + succeeded_window = store_report(session, catalog, budget_window_size=2) window_run_id, _ = store_window( - connection, + session, catalog, succeeded_window, StoredWindow( @@ -482,7 +500,7 @@ def test_listing_answers_budget_windows_with_their_years_beside_economy_reports( {2026: "succeeded", 2027: "succeeded"}, ), ) - unrun_window = store_report(connection, catalog, budget_window_size=5) + unrun_window = store_report(session, catalog, budget_window_size=5) named = ( succeeded_window.report_id, uuid4(), @@ -511,15 +529,17 @@ def test_listing_answers_budget_windows_with_their_years_beside_economy_reports( def test_a_succeeded_window_whose_result_cannot_be_read_is_still_listed( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: # Listing never reads the window's figures, so a window whose years # stored no result rows is listed like any other. catalog = catalogs["us"] - with owner_engine.begin() as connection: - report = store_report(connection, catalog, budget_window_size=2) + with owner_sessions.begin() as session: + report = store_report(session, catalog, budget_window_size=2) store_window( - connection, + session, catalog, report, StoredWindow( @@ -538,18 +558,18 @@ def test_a_succeeded_window_whose_result_cannot_be_read_is_still_listed( def test_listing_reads_any_number_of_windows_in_two_queries( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalogs: dict[str, CatalogRows], - managed_v2_roles, - v2_engine_as_role, + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> None: catalog = catalogs["us"] - with owner_engine.begin() as connection: - reports = [store_report(connection, catalog)] + with owner_sessions.begin() as session: + reports = [store_report(session, catalog)] for _ in range(3): - window = store_report(connection, catalog, budget_window_size=2) + window = store_report(session, catalog, budget_window_size=2) store_window( - connection, + session, catalog, window, StoredWindow( @@ -558,24 +578,16 @@ def test_listing_reads_any_number_of_windows_in_two_queries( ), ) reports.append(window) - runtime_engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - statements: list[str] = [] - - def record_statement( - _connection: Any, _cursor: Any, statement: str, *_arguments: Any - ) -> None: - statements.append(statement) - - event.listen(runtime_engine, "before_cursor_execute", record_statement) + runtime_sessions = v2_sessions_as_role(managed_v2_roles.runtime) service = V2StoredReportService( - StoredReportDatabaseSession(sessionmaker(runtime_engine, class_=Session)), + StoredReportDatabaseSession(runtime_sessions), current_versions=current_versions, ) - listed = service.list_reports( - country_id="us", report_ids=[report.report_id for report in reports] - ) - runtime_engine.dispose() + with recorded_statements(runtime_sessions) as statements: + listed = service.list_reports( + country_id="us", report_ids=[report.report_id for report in reports] + ) assert [read.kind for read in listed] == [ "economy", diff --git a/tests/integration/test_v2_catalog_installed_folders.py b/tests/integration/test_v2_catalog_installed_folders.py index b278cc4ac..1aaa5e537 100644 --- a/tests/integration/test_v2_catalog_installed_folders.py +++ b/tests/integration/test_v2_catalog_installed_folders.py @@ -25,18 +25,19 @@ import pytest from alembic import command from alembic.config import Config -from sqlalchemy import create_engine, text -from sqlalchemy.pool import NullPool from policyengine_api.data.v2.catalog.extraction import extract_catalog from policyengine_api.data.v2.catalog.publication import publish_catalog from policyengine_api.data.v2.catalog.region_references import load_region_references +from policyengine_api.data.v2.models import TaxBenefitModel +from tests.fixtures.database_sessions import truncate from tests.integration.catalog_rows import assert_catalog_stored_unchanged if TYPE_CHECKING: from collections.abc import Iterable, Iterator, Mapping - from sqlalchemy.engine import Engine + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session from policyengine_api.data.v2.catalog.records import ( NormalizedCatalog, @@ -164,16 +165,16 @@ def selected_catalog(installed_models: Mapping[str, object]) -> NormalizedCatalo @pytest.fixture -def publication_engine(disposable_v2_database_url: str) -> Iterator[Engine]: - """Return an engine for the disposable v2 database, with no catalog in it.""" +def publication_sessions( + v2_owner_sessions: sessionmaker[Session], +) -> Iterator[sessionmaker[Session]]: + """Return Session factories of the disposable v2 database, with no catalog.""" command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - with engine.begin() as connection: - connection.execute(text("TRUNCATE tax_benefit_models CASCADE")) - yield engine - with engine.begin() as connection: - connection.execute(text("TRUNCATE tax_benefit_models CASCADE")) - engine.dispose() + with v2_owner_sessions.begin() as session: + truncate(session, TaxBenefitModel) + yield v2_owner_sessions + with v2_owner_sessions.begin() as session: + truncate(session, TaxBenefitModel) def _values(catalog: NormalizedCatalog) -> list[ParameterValueRecord]: @@ -243,11 +244,11 @@ def test_selected_folders_hold_every_value_shape_the_installed_models_hold( def test_selected_folders_publish_and_come_back_unchanged( selected_catalog: NormalizedCatalog, - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: - publish_catalog(publication_engine, selected_catalog) + publish_catalog(publication_sessions, selected_catalog) # Publishing the same version again compares every stored row with the # catalog in both directions and fails on any difference. - publish_catalog(publication_engine, selected_catalog) + publish_catalog(publication_sessions, selected_catalog) - assert_catalog_stored_unchanged(publication_engine, selected_catalog) + assert_catalog_stored_unchanged(publication_sessions, selected_catalog) diff --git a/tests/integration/test_v2_catalog_publication.py b/tests/integration/test_v2_catalog_publication.py index c46fa0f6e..c2e5c9e5d 100644 --- a/tests/integration/test_v2_catalog_publication.py +++ b/tests/integration/test_v2_catalog_publication.py @@ -5,21 +5,17 @@ import gzip import hashlib import json -import os from concurrent.futures import ThreadPoolExecutor from dataclasses import replace from datetime import UTC, datetime -from pathlib import Path from types import SimpleNamespace +from typing import TYPE_CHECKING, Any from uuid import uuid4 import pytest -from alembic import command -from alembic.config import Config -from sqlalchemy import create_engine, text -from sqlalchemy.engine import Engine, make_url -from sqlalchemy.pool import NullPool -from sqlmodel import Session, select +import sqlalchemy as sa +from sqlalchemy.engine import make_url +from sqlmodel import col, select from policyengine_api.data.v2.catalog import publication as publication_module from policyengine_api.data.v2.catalog.extraction import extract_catalog @@ -32,6 +28,11 @@ from policyengine_api.data.v2.models import ( Dataset, DatasetVersion, + Parameter, + ParameterNode, + ParameterSearchFile, + ParameterTreeChild, + ParameterValue, Region, Report, ReportRun, @@ -39,9 +40,10 @@ SimulationRun, TaxBenefitModel, TaxBenefitModelVersion, + Variable, ) from policyengine_api.data.v2.privileges import CATALOG_WRITER_ROLE -from policyengine_api.data.v2.settings import V2_MIGRATION_DATABASE_URL +from tests.fixtures import database_sessions from tests.fixtures.v2_catalog import ( POLICYENGINE_VERSION, add_format_2_variable_records, @@ -56,6 +58,11 @@ REGION_FILTER_VALUES, value_shape_catalog, ) +from tests.integration.catalog_publication_support import ( + emptied_catalog, + row_counts, + stored_identifiers, +) from tests.integration.catalog_rows import ( CATALOG_COLUMNS, assert_catalog_stored_unchanged, @@ -64,99 +71,80 @@ strict_json, ) -REPO = Path(__file__).parents[2] -DISPOSABLE_DATABASE = "policyengine_v2_alembic_test" +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + +# The tables whose rows the tests count: the catalog's, and those that name it. +COUNTED_MODELS: dict[str, Any] = { + "tax_benefit_models": TaxBenefitModel, + "tax_benefit_model_versions": TaxBenefitModelVersion, + "variables": Variable, + "parameter_nodes": ParameterNode, + "parameters": Parameter, + "parameter_values": ParameterValue, + "datasets": Dataset, + "dataset_versions": DatasetVersion, + "regions": Region, + "simulations": Simulation, + "reports": Report, + "report_runs": ReportRun, +} -def _disposable_url() -> str: - database_url = os.environ.get(V2_MIGRATION_DATABASE_URL, "") - if not database_url: - pytest.skip(f"{V2_MIGRATION_DATABASE_URL} is not set") - url = make_url(database_url) - if url.database != DISPOSABLE_DATABASE or url.host not in { - "localhost", - "127.0.0.1", - "::1", - "postgres", - }: - pytest.fail("catalog publication tests require disposable local Postgres") - return database_url +@pytest.fixture +def publication_sessions( + v2_owner_sessions: sessionmaker[Session], +) -> Iterator[sessionmaker[Session]]: + with emptied_catalog(v2_owner_sessions) as sessions: + yield sessions -@pytest.fixture -def publication_engine() -> Engine: - database_url = _disposable_url() - config = Config(str(REPO / "alembic-v2.ini")) - command.upgrade(config, "head") - engine = create_engine(database_url, poolclass=NullPool) - with engine.begin() as connection: - connection.execute(text("TRUNCATE tax_benefit_models CASCADE")) - yield engine - with engine.begin() as connection: - connection.execute(text("TRUNCATE tax_benefit_models CASCADE")) - engine.dispose() - - -def _counts(engine: Engine) -> dict[str, int]: - with engine.connect() as connection: - return { - table_name: connection.execute( - text(f"SELECT count(*) FROM {table_name}") - ).scalar_one() - for table_name in ( - "tax_benefit_models", - "tax_benefit_model_versions", - "variables", - "parameter_nodes", - "parameters", - "parameter_values", - "datasets", - "dataset_versions", - "regions", - "simulations", - "reports", - "report_runs", - ) - } +def _counts(sessions: sessionmaker[Session]) -> dict[str, int]: + return row_counts(sessions, COUNTED_MODELS) -def _identifiers(engine: Engine) -> dict[str, tuple[str, ...]]: - with engine.connect() as connection: - return { - table_name: tuple( - str(value) - for value in connection.execute( - text(f"SELECT id FROM {table_name} ORDER BY id") - ).scalars() - ) - for table_name in ( - "tax_benefit_models", - "tax_benefit_model_versions", - "variables", - "parameter_nodes", - "parameters", - "parameter_values", - "datasets", - "regions", - ) - } +def _identifiers(sessions: sessionmaker[Session]) -> dict[str, tuple[str, ...]]: + return stored_identifiers(sessions) + + +def _us_version_id() -> sa.ScalarSelect[Any]: + """Select the ID of the US model's stored version, of which there is one.""" + return ( + select(col(TaxBenefitModelVersion.id)) + .join( + TaxBenefitModel, + col(TaxBenefitModel.id) == col(TaxBenefitModelVersion.model_id), + ) + .where(col(TaxBenefitModel.name) == "policyengine-us") + .scalar_subquery() + ) + + +def _version_ids(version: str) -> sa.Select[Any]: + """Select the IDs of the stored versions of one .py version, for every model.""" + return select(col(TaxBenefitModelVersion.id)).where( + col(TaxBenefitModelVersion.version) == version + ) def test_publish_and_republish_preserve_complete_catalog( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: catalog = normalized_catalog() - first = publish_catalog(publication_engine, catalog) - first_counts = _counts(publication_engine) - first_ids = _identifiers(publication_engine) - second = publish_catalog(publication_engine, catalog) + first = publish_catalog(publication_sessions, catalog) + first_counts = _counts(publication_sessions) + first_ids = _identifiers(publication_sessions) + second = publish_catalog(publication_sessions, catalog) assert first.as_dict()["outcome"] == "ok" assert first.omitted_region_summaries == (("us", "place", 1),) assert second.policyengine_version == first.policyengine_version assert ( - _counts(publication_engine) + _counts(publication_sessions) == first_counts == { "tax_benefit_models": 2, @@ -173,24 +161,20 @@ def test_publish_and_republish_preserve_complete_catalog( "report_runs": 0, } ) - assert _identifiers(publication_engine) == first_ids - - with publication_engine.connect() as connection: - datasets = connection.execute( - text( - "SELECT name, storage_path, is_output_dataset " - "FROM datasets ORDER BY name" - ) + assert _identifiers(publication_sessions) == first_ids + + with publication_sessions() as session: + datasets = session.execute( + select( + col(Dataset.name), + col(Dataset.storage_path), + col(Dataset.is_output_dataset), + ).order_by(col(Dataset.name)) ).all() - region_defaults = connection.execute( - text( - """ - SELECT region.code, dataset.name - FROM regions AS region - JOIN datasets AS dataset ON dataset.id = region.default_dataset_id - ORDER BY region.code - """ - ) + region_defaults = session.execute( + select(col(Region.code), col(Dataset.name)) + .join(Dataset, col(Dataset.id) == col(Region.default_dataset_id)) + .order_by(col(Region.code)) ).all() assert all( storage_path is None and not output for _, storage_path, output in datasets @@ -207,31 +191,34 @@ def test_publish_and_republish_preserve_complete_catalog( } -def test_unpublished_country_check_reports_a_missing_schema_specifically() -> None: +def test_unpublished_country_check_reports_a_missing_schema_specifically( + disposable_v2_database_url: str, +) -> None: # The same server's maintenance database has no v2 schema at all. - schema_less = make_url(_disposable_url()).set(database="postgres") - engine = create_engine(schema_less, poolclass=NullPool) - try: - with pytest.raises( + schema_less = make_url(disposable_v2_database_url).set(database="postgres") + with ( + database_sessions.v2_owner_sessions( + schema_less.render_as_string(hide_password=False) + ) as schema_less_sessions, + pytest.raises( CatalogPublicationError, match=r"^the v2 Alembic revision table is absent$", - ): - unpublished_countries(engine, normalized_catalog()) - finally: - engine.dispose() + ), + ): + unpublished_countries(schema_less_sessions, normalized_catalog()) def test_lists_only_countries_whose_catalog_version_is_not_stored( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: catalog = normalized_catalog() newer = normalized_catalog(policyengine_version="4.21.0") - assert unpublished_countries(publication_engine, catalog) == ("us", "uk") - publish_catalog(publication_engine, catalog) + assert unpublished_countries(publication_sessions, catalog) == ("us", "uk") + publish_catalog(publication_sessions, catalog) - assert unpublished_countries(publication_engine, catalog) == () - assert unpublished_countries(publication_engine, newer) == ("us", "uk") + assert unpublished_countries(publication_sessions, catalog) == () + assert unpublished_countries(publication_sessions, newer) == ("us", "uk") @pytest.mark.parametrize( @@ -239,31 +226,31 @@ def test_lists_only_countries_whose_catalog_version_is_not_stored( ["during_copy", "after_reconciliation", "after_validation"], ) def test_failure_during_publication_rolls_back_every_catalog_write( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], failure_point: str, ) -> None: - def fail(point: str, _connection) -> None: + def fail(point: str, _session) -> None: if point == failure_point: msg = "injected failure" raise RuntimeError(msg) with pytest.raises(RuntimeError, match="injected failure"): publish_catalog( - publication_engine, + publication_sessions, normalized_catalog(), checkpoint=fail, ) - assert all(count == 0 for count in _counts(publication_engine).values()) + assert all(count == 0 for count in _counts(publication_sessions).values()) def test_same_version_with_changed_content_fails_without_mutation( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: catalog = normalized_catalog() - publish_catalog(publication_engine, catalog) - before_ids = _identifiers(publication_engine) - before_counts = _counts(publication_engine) + publish_catalog(publication_sessions, catalog) + before_ids = _identifiers(publication_sessions) + before_counts = _counts(publication_sessions) us = catalog.country("us") changed_variable = replace(us.variables[0], label="Changed label") changed_us = replace(us, variables=(changed_variable,)) @@ -277,17 +264,17 @@ def test_same_version_with_changed_content_fails_without_mutation( match=r"^the stored us catalog version 5\.0\.4 differs from the staged " r"catalog in its variables$", ): - publish_catalog(publication_engine, changed) + publish_catalog(publication_sessions, changed) - assert _identifiers(publication_engine) == before_ids - assert _counts(publication_engine) == before_counts + assert _identifiers(publication_sessions) == before_ids + assert _counts(publication_sessions) == before_counts def test_stored_version_with_a_different_dataset_names_the_datasets( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: catalog = normalized_catalog() - publish_catalog(publication_engine, catalog) + publish_catalog(publication_sessions, catalog) uk = catalog.country("uk") changed = replace( catalog, @@ -308,23 +295,28 @@ def test_stored_version_with_a_different_dataset_names_the_datasets( match=r"^the stored uk catalog version 5\.0\.4 differs from the staged " r"catalog in its datasets$", ): - publish_catalog(publication_engine, changed) + publish_catalog(publication_sessions, changed) -def _region_rows(engine: Engine) -> list[tuple[object, ...]]: - with engine.connect() as connection: +def _region_rows(sessions: sessionmaker[Session]) -> list[tuple[object, ...]]: + with sessions() as session: return [ tuple(row) - for row in connection.execute( - text( - """ - SELECT id, code, label, region_type, requires_filter, - filter_field, filter_value, filter_strategy, - parent_code, state_code, state_name, default_dataset_id - FROM regions - ORDER BY id - """ - ) + for row in session.execute( + sa.select( + col(Region.id), + col(Region.code), + col(Region.label), + col(Region.region_type), + col(Region.requires_filter), + col(Region.filter_field), + col(Region.filter_value), + col(Region.filter_strategy), + col(Region.parent_code), + col(Region.state_code), + col(Region.state_name), + col(Region.default_dataset_id), + ).order_by(col(Region.id)) ) ] @@ -346,14 +338,14 @@ def _with_changed_us_regions(catalog): def test_stored_version_keeps_its_published_regions_and_logs_the_difference( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch, ) -> None: catalog = normalized_catalog() - publish_catalog(publication_engine, catalog) - before_regions = _region_rows(publication_engine) - before_ids = _identifiers(publication_engine) - before_counts = _counts(publication_engine) + publish_catalog(publication_sessions, catalog) + before_regions = _region_rows(publication_sessions) + before_ids = _identifiers(publication_sessions) + before_counts = _counts(publication_sessions) # Alembic's logging configuration disables existing loggers, so the # warnings are recorded where they are emitted. warnings: list[tuple[str, dict]] = [] @@ -363,12 +355,12 @@ def test_stored_version_keeps_its_published_regions_and_logs_the_difference( lambda message, *args, **kwargs: warnings.append((message % args, kwargs)), ) - evidence = publish_catalog(publication_engine, _with_changed_us_regions(catalog)) + evidence = publish_catalog(publication_sessions, _with_changed_us_regions(catalog)) assert evidence.as_dict()["outcome"] == "ok" - assert _region_rows(publication_engine) == before_regions - assert _identifiers(publication_engine) == before_ids - assert _counts(publication_engine) == before_counts + assert _region_rows(publication_sessions) == before_regions + assert _identifiers(publication_sessions) == before_ids + assert _counts(publication_sessions) == before_counts # The evidence describes the stored rows, not the staged regions. assert evidence.entity_counts == { "models": before_counts["tax_benefit_models"], @@ -406,11 +398,11 @@ def test_stored_version_keeps_its_published_regions_and_logs_the_difference( def test_stored_version_with_changed_regions_still_fails_on_other_tables( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: catalog = normalized_catalog() - publish_catalog(publication_engine, catalog) - before_regions = _region_rows(publication_engine) + publish_catalog(publication_sessions, catalog) + before_regions = _region_rows(publication_sessions) changed = _with_changed_us_regions(catalog) us = changed.country("us") changed = replace( @@ -422,31 +414,35 @@ def test_stored_version_with_changed_regions_still_fails_on_other_tables( ) with pytest.raises(CatalogPublicationError, match="differs"): - publish_catalog(publication_engine, changed) + publish_catalog(publication_sessions, changed) - assert _region_rows(publication_engine) == before_regions + assert _region_rows(publication_sessions) == before_regions def test_new_version_publishes_the_reference_file_regions( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: - publish_catalog(publication_engine, normalized_catalog()) + publish_catalog(publication_sessions, normalized_catalog()) newer = _with_changed_us_regions(normalized_catalog(policyengine_version="4.21.0")) - publish_catalog(publication_engine, newer) + publish_catalog(publication_sessions, newer) - with publication_engine.connect() as connection: + with publication_sessions() as session: newer_us_regions = dict( - connection.execute( - text( - """ - SELECT region.code, region.label - FROM regions AS region - JOIN tax_benefit_model_versions AS version - ON version.id = region.tax_benefit_model_version_id - JOIN tax_benefit_models AS model ON model.id = version.model_id - WHERE version.version = '4.21.0' AND model.name = 'policyengine-us' - """ + session.execute( + select(col(Region.code), col(Region.label)) + .join( + TaxBenefitModelVersion, + col(TaxBenefitModelVersion.id) + == col(Region.tax_benefit_model_version_id), + ) + .join( + TaxBenefitModel, + col(TaxBenefitModel.id) == col(TaxBenefitModelVersion.model_id), + ) + .where( + col(TaxBenefitModelVersion.version) == "4.21.0", + col(TaxBenefitModel.name) == "policyengine-us", ) ).all() ) @@ -457,12 +453,12 @@ def test_new_version_publishes_the_reference_file_regions( def test_republish_preserves_existing_run_and_dataset_version_records( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: catalog = normalized_catalog() - publish_catalog(publication_engine, catalog) + publish_catalog(publication_sessions, catalog) - with Session(publication_engine) as session: + with publication_sessions() as session: model = session.exec( select(TaxBenefitModel).where(TaxBenefitModel.name == "policyengine-us") ).one() @@ -540,9 +536,9 @@ def test_republish_preserves_existing_run_and_dataset_version_records( dataset_version.dataset_id, ) - publish_catalog(publication_engine, catalog) + publish_catalog(publication_sessions, catalog) - with Session(publication_engine) as session: + with publication_sessions() as session: persisted_dataset_version = session.get(DatasetVersion, protected_ids[0]) persisted_simulation = session.get(Simulation, protected_ids[1]) persisted_report = session.get(Report, protected_ids[2]) @@ -572,16 +568,16 @@ def test_republish_preserves_existing_run_and_dataset_version_records( def test_new_version_is_additive_and_concurrent_retries_serialize( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: first = normalized_catalog() newer = normalized_catalog(policyengine_version="4.21.0") - publish_catalog(publication_engine, first) + publish_catalog(publication_sessions, first) with ThreadPoolExecutor(max_workers=2) as executor: results = list( executor.map( - lambda _index: publish_catalog(publication_engine, newer), + lambda _index: publish_catalog(publication_sessions, newer), range(2), ) ) @@ -590,7 +586,7 @@ def test_new_version_is_additive_and_concurrent_retries_serialize( "4.21.0", "4.21.0", ] - assert _counts(publication_engine) == { + assert _counts(publication_sessions) == { "tax_benefit_models": 2, "tax_benefit_model_versions": 4, "variables": 4, @@ -607,18 +603,18 @@ def test_new_version_is_additive_and_concurrent_retries_serialize( def test_publication_stores_every_value_shape_unchanged( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: catalog = value_shape_catalog() - publish_catalog(publication_engine, catalog) + publish_catalog(publication_sessions, catalog) # Publishing the same version again compares every stored row with the # catalog in both directions and fails on any difference, so this also # checks that the comparison reads each shape back as it was written. - publish_catalog(publication_engine, catalog) + publish_catalog(publication_sessions, catalog) - assert_catalog_stored_unchanged(publication_engine, catalog) - stored_values = stored_parameter_values(publication_engine) + assert_catalog_stored_unchanged(publication_sessions, catalog) + stored_values = stored_parameter_values(publication_sessions) us_model = catalog.country("us").model.name for case in PARAMETER_CASES: assert [ @@ -629,7 +625,7 @@ def test_publication_stores_every_value_shape_unchanged( if (model_name, parameter_name) == (us_model, case.name) ] == [strict_json(value.stored_value) for value in case.values], case.name - stored_regions = stored_catalog_rows(publication_engine, "regions") + stored_regions = stored_catalog_rows(publication_sessions, "regions") filter_value_index = CATALOG_COLUMNS["regions"].index("filter_value") - 1 for (country_id, code), filter_value in REGION_FILTER_VALUES.items(): model_name = catalog.country(country_id).model.name @@ -637,37 +633,35 @@ def test_publication_stores_every_value_shape_unchanged( assert stored_columns[filter_value_index] == filter_value, code -def _format_2_values(engine: Engine) -> dict[str, object]: +def _format_2_values(sessions: sessionmaker[Session]) -> dict[str, object]: """Return the US version's stored catalog format 2 fields.""" - with engine.connect() as connection: - version = connection.execute( - text( - "SELECT version.catalog_format, version.entities, version.basic_inputs " - "FROM tax_benefit_model_versions AS version " - "JOIN tax_benefit_models AS model ON model.id = version.model_id " - "WHERE model.name = 'policyengine-us'" - ) + with sessions() as session: + version = session.execute( + select( + col(TaxBenefitModelVersion.catalog_format), + col(TaxBenefitModelVersion.entities), + col(TaxBenefitModelVersion.basic_inputs), + ).where(col(TaxBenefitModelVersion.id) == _us_version_id()) ).one() - variable = connection.execute( - text( - "SELECT is_input_variable, hidden_input, module_name, " - "adds_parameter_path, subtracts_parameter_path, enum_values, " - "unit, definition_period " - "FROM variables WHERE name = 'employment_income' " - "AND tax_benefit_model_version_id = (" - "SELECT version.id FROM tax_benefit_model_versions AS version " - "JOIN tax_benefit_models AS model ON model.id = version.model_id " - "WHERE model.name = 'policyengine-us')" + variable = session.execute( + sa.select( + col(Variable.is_input_variable), + col(Variable.hidden_input), + col(Variable.module_name), + col(Variable.adds_parameter_path), + col(Variable.subtracts_parameter_path), + col(Variable.enum_values), + col(Variable.unit), + col(Variable.definition_period), + ).where( + col(Variable.name) == "employment_income", + col(Variable.tax_benefit_model_version_id) == _us_version_id(), ) ).one() - parameter = connection.execute( - text( - "SELECT economy, household FROM parameters " - "WHERE name = 'gov.example.rate' " - "AND tax_benefit_model_version_id = (" - "SELECT version.id FROM tax_benefit_model_versions AS version " - "JOIN tax_benefit_models AS model ON model.id = version.model_id " - "WHERE model.name = 'policyengine-us')" + parameter = session.execute( + select(col(Parameter.economy), col(Parameter.household)).where( + col(Parameter.name) == "gov.example.rate", + col(Parameter.tax_benefit_model_version_id) == _us_version_id(), ) ).one() return { @@ -677,34 +671,38 @@ def _format_2_values(engine: Engine) -> dict[str, object]: } -def _clear_format_2_fields(engine: Engine) -> None: - """Make every stored version look as if published before catalog format 2.""" - with engine.begin() as connection: - connection.execute( - text( - "UPDATE tax_benefit_model_versions SET catalog_format = NULL, " - "entities = NULL, basic_inputs = NULL" +def _clear_format_2_fields(sessions: sessionmaker[Session]) -> None: + """Make every stored version look as if published before catalog format 2. + + The JSON columns get SQL NULL (``sa.null()``), not JSON's null. + """ + with sessions.begin() as session: + session.execute( + sa.update(TaxBenefitModelVersion).values( + catalog_format=None, entities=sa.null(), basic_inputs=sa.null() ) ) - connection.execute( - text( - "UPDATE variables SET is_input_variable = NULL, hidden_input = NULL, " - "module_name = NULL, adds_parameter_path = NULL, " - "subtracts_parameter_path = NULL, enum_values = NULL, " - "unit = NULL, definition_period = NULL" + session.execute( + sa.update(Variable).values( + is_input_variable=None, + hidden_input=None, + module_name=None, + adds_parameter_path=None, + subtracts_parameter_path=None, + enum_values=sa.null(), + unit=None, + definition_period=None, ) ) - connection.execute( - text("UPDATE parameters SET economy = NULL, household = NULL") - ) + session.execute(sa.update(Parameter).values(economy=None, household=None)) def test_publication_stores_catalog_format_2_fields( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: - publish_catalog(publication_engine, normalized_catalog()) + publish_catalog(publication_sessions, normalized_catalog()) - assert _format_2_values(publication_engine) == { + assert _format_2_values(publication_sessions) == { "version": ( 2, [ @@ -728,18 +726,18 @@ def test_publication_stores_catalog_format_2_fields( def test_version_stored_before_format_2_keeps_its_fields_empty_on_republish( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: catalog = normalized_catalog() - publish_catalog(publication_engine, catalog) - _clear_format_2_fields(publication_engine) - before_ids = _identifiers(publication_engine) + publish_catalog(publication_sessions, catalog) + _clear_format_2_fields(publication_sessions) + before_ids = _identifiers(publication_sessions) - result = publish_catalog(publication_engine, catalog) + result = publish_catalog(publication_sessions, catalog) assert result.as_dict()["outcome"] == "ok" - assert _identifiers(publication_engine) == before_ids - assert _format_2_values(publication_engine) == { + assert _identifiers(publication_sessions) == before_ids + assert _format_2_values(publication_sessions) == { "version": (None, None, None), "variable": (None, None, None, None, None, None, None, None), "parameter": (None, None), @@ -747,11 +745,11 @@ def test_version_stored_before_format_2_keeps_its_fields_empty_on_republish( def test_version_stored_with_format_2_fails_when_a_format_2_field_changes( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: catalog = normalized_catalog() - publish_catalog(publication_engine, catalog) - before_counts = _counts(publication_engine) + publish_catalog(publication_sessions, catalog) + before_counts = _counts(publication_sessions) us = catalog.country("us") changed_parameter = replace(us.parameters[0], household=True) changed = replace( @@ -763,10 +761,10 @@ def test_version_stored_with_format_2_fails_when_a_format_2_field_changes( ) with pytest.raises(CatalogPublicationError, match="differs"): - publish_catalog(publication_engine, changed) + publish_catalog(publication_sessions, changed) - assert _counts(publication_engine) == before_counts - assert _format_2_values(publication_engine)["parameter"] == (True, False) + assert _counts(publication_sessions) == before_counts + assert _format_2_values(publication_sessions)["parameter"] == (True, False) def _catalog_with_format_2_variable_records(): @@ -781,19 +779,19 @@ def _catalog_with_format_2_variable_records(): ) -def _stored_us_variables(engine: Engine) -> dict[str, tuple[object, ...]]: - with engine.connect() as connection: - rows = connection.execute( - text( - "SELECT variable.name, variable.enum_values, " - "variable.adds_parameter_path, variable.subtracts_parameter_path, " - "variable.unit, variable.definition_period " - "FROM variables AS variable " - "JOIN tax_benefit_model_versions AS version " - "ON version.id = variable.tax_benefit_model_version_id " - "JOIN tax_benefit_models AS model ON model.id = version.model_id " - "WHERE model.name = 'policyengine-us'" - ) +def _stored_us_variables( + sessions: sessionmaker[Session], +) -> dict[str, tuple[object, ...]]: + with sessions() as session: + rows = session.execute( + sa.select( + col(Variable.name), + col(Variable.enum_values), + col(Variable.adds_parameter_path), + col(Variable.subtracts_parameter_path), + col(Variable.unit), + col(Variable.definition_period), + ).where(col(Variable.tax_benefit_model_version_id) == _us_version_id()) ).all() return {row[0]: tuple(row[1:]) for row in rows} @@ -811,14 +809,14 @@ def _with_changed_us_variable(catalog, name: str, **changes: object): def test_enum_labels_parameter_paths_units_and_periods_round_trip_exactly( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: catalog = _catalog_with_format_2_variable_records() - publish_catalog(publication_engine, catalog) - before_ids = _identifiers(publication_engine) - stored = _stored_us_variables(publication_engine) - republished = publish_catalog(publication_engine, catalog) + publish_catalog(publication_sessions, catalog) + before_ids = _identifiers(publication_sessions) + stored = _stored_us_variables(publication_sessions) + republished = publish_catalog(publication_sessions, catalog) assert stored["filing_status"] == ( [{"value": "SINGLE", "label": "Single"}, {"value": "JOINT", "label": 2}], @@ -836,7 +834,7 @@ def test_enum_labels_parameter_paths_units_and_periods_round_trip_exactly( "month", ) assert republished.as_dict()["outcome"] == "ok" - assert _identifiers(publication_engine) == before_ids + assert _identifiers(publication_sessions) == before_ids @pytest.mark.parametrize( @@ -858,13 +856,13 @@ def test_enum_labels_parameter_paths_units_and_periods_round_trip_exactly( ], ) def test_republication_detects_a_changed_enum_label_parameter_path_unit_or_period( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], variable_name: str, changes: dict[str, object], ) -> None: catalog = _catalog_with_format_2_variable_records() - publish_catalog(publication_engine, catalog) - stored = _stored_us_variables(publication_engine) + publish_catalog(publication_sessions, catalog) + stored = _stored_us_variables(publication_sessions) with pytest.raises( CatalogPublicationError, @@ -872,55 +870,74 @@ def test_republication_detects_a_changed_enum_label_parameter_path_unit_or_perio r"catalog in its variables$", ): publish_catalog( - publication_engine, + publication_sessions, _with_changed_us_variable(catalog, variable_name, **changes), ) - assert _stored_us_variables(publication_engine) == stored + assert _stored_us_variables(publication_sessions) == stored def _stored_tree( - engine: Engine, + sessions: sessionmaker[Session], model_name: str, version: str, *, - parameter_column: str = "parameter.name", + by_parameter_id: bool = False, ) -> list[tuple]: """Return a stored version's tree rows; each parameter by name by default.""" - with engine.connect() as connection: + parameter_column = ( + col(ParameterTreeChild.parameter_id) if by_parameter_id else col(Parameter.name) + ) + with sessions() as session: return [ tuple(row) - for row in connection.execute( - text( - "SELECT tree.parent_path, tree.path, tree.position, tree.label, " - "tree.child_type, tree.child_count, tree.reform_position, " - f"tree.reform_child_count, {parameter_column}, tree.economy, " - "tree.household " - "FROM parameter_tree_children AS tree " - "JOIN tax_benefit_model_versions AS version " - "ON version.id = tree.tax_benefit_model_version_id " - "JOIN tax_benefit_models AS model ON model.id = version.model_id " - "LEFT JOIN parameters AS parameter " - "ON parameter.id = tree.parameter_id " - "WHERE model.name = :model_name AND version.version = :version " - "ORDER BY tree.parent_path, tree.position" - ), - {"model_name": model_name, "version": version}, + for row in session.execute( + sa.select( + col(ParameterTreeChild.parent_path), + col(ParameterTreeChild.path), + col(ParameterTreeChild.position), + col(ParameterTreeChild.label), + col(ParameterTreeChild.child_type), + col(ParameterTreeChild.child_count), + col(ParameterTreeChild.reform_position), + col(ParameterTreeChild.reform_child_count), + parameter_column, + col(ParameterTreeChild.economy), + col(ParameterTreeChild.household), + ) + .join( + TaxBenefitModelVersion, + col(TaxBenefitModelVersion.id) + == col(ParameterTreeChild.tax_benefit_model_version_id), + ) + .join( + TaxBenefitModel, + col(TaxBenefitModel.id) == col(TaxBenefitModelVersion.model_id), + ) + .outerjoin( + Parameter, col(Parameter.id) == col(ParameterTreeChild.parameter_id) + ) + .where( + col(TaxBenefitModel.name) == model_name, + col(TaxBenefitModelVersion.version) == version, + ) + .order_by( + col(ParameterTreeChild.parent_path), + col(ParameterTreeChild.position), + ) ) ] -def _delete_tree(engine: Engine, version: str) -> None: +def _delete_tree(sessions: sessionmaker[Session], version: str) -> None: """Make the stored versions of one .py version look stored before the tree.""" - with engine.begin() as connection: - connection.execute( - text( - "DELETE FROM parameter_tree_children AS tree " - "USING tax_benefit_model_versions AS version " - "WHERE version.id = tree.tax_benefit_model_version_id " - "AND version.version = :version" - ), - {"version": version}, + with sessions.begin() as session: + session.execute( + sa.delete(ParameterTreeChild).where( + col(ParameterTreeChild.tax_benefit_model_version_id).in_( + _version_ids(version) + ) + ) ) @@ -944,16 +961,16 @@ def _delete_tree(engine: Engine, version: str) -> None: def test_publication_writes_each_new_version_parameter_tree( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: catalog = normalized_catalog() - evidence = publish_catalog(publication_engine, catalog) + evidence = publish_catalog(publication_sessions, catalog) for country in catalog.countries: assert ( _stored_tree( - publication_engine, + publication_sessions, country.model.name, country.model_version.version, ) @@ -966,11 +983,9 @@ def test_publication_writes_each_new_version_parameter_tree( def _stored_tree_with_parameter_ids( - engine: Engine, model_name: str, version: str + sessions: sessionmaker[Session], model_name: str, version: str ) -> list[tuple]: - return _stored_tree( - engine, model_name, version, parameter_column="tree.parameter_id" - ) + return _stored_tree(sessions, model_name, version, by_parameter_id=True) def _with_other_parameter_ids(catalog): @@ -995,7 +1010,7 @@ def _with_other_parameter_ids(catalog): def test_publication_gives_the_installed_stored_version_its_tree( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: """The installed version, stored by a release without the tree, gets one. @@ -1006,18 +1021,18 @@ def test_publication_gives_the_installed_stored_version_its_tree( """ catalog = normalized_catalog() current_version = catalog.country("us").model_version.version - publish_catalog(publication_engine, _with_other_parameter_ids(catalog)) + publish_catalog(publication_sessions, _with_other_parameter_ids(catalog)) fresh = { country.model.name: _stored_tree_with_parameter_ids( - publication_engine, country.model.name, current_version + publication_sessions, country.model.name, current_version ) for country in catalog.countries } - _delete_tree(publication_engine, current_version) - before_ids = _identifiers(publication_engine) + _delete_tree(publication_sessions, current_version) + before_ids = _identifiers(publication_sessions) - evidence = publish_catalog(publication_engine, catalog) - again = publish_catalog(publication_engine, catalog) + evidence = publish_catalog(publication_sessions, catalog) + again = publish_catalog(publication_sessions, catalog) assert evidence.parameter_trees_written == tuple( (country.model.name, current_version, len(FIXTURE_TREE)) @@ -1027,11 +1042,11 @@ def test_publication_gives_the_installed_stored_version_its_tree( for country in catalog.countries: assert ( _stored_tree_with_parameter_ids( - publication_engine, country.model.name, current_version + publication_sessions, country.model.name, current_version ) == fresh[country.model.name] ) - assert _identifiers(publication_engine) == before_ids + assert _identifiers(publication_sessions) == before_ids catalog_parameter_ids = { parameter.id for country in catalog.countries @@ -1044,7 +1059,7 @@ def test_publication_gives_the_installed_stored_version_its_tree( def test_an_installed_version_stored_before_format_2_gets_no_tree( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: """A version stored before catalog format 2 stores no flags, so no tree. @@ -1054,22 +1069,23 @@ def test_an_installed_version_stored_before_format_2_gets_no_tree( """ catalog = normalized_catalog() current_version = catalog.country("us").model_version.version - publish_catalog(publication_engine, catalog) - _clear_format_2_fields(publication_engine) - _delete_tree(publication_engine, current_version) + publish_catalog(publication_sessions, catalog) + _clear_format_2_fields(publication_sessions) + _delete_tree(publication_sessions, current_version) - evidence = publish_catalog(publication_engine, catalog) + evidence = publish_catalog(publication_sessions, catalog) assert evidence.as_dict()["outcome"] == "ok" assert evidence.parameter_trees_written == () for country in catalog.countries: assert ( - _stored_tree(publication_engine, country.model.name, current_version) == [] + _stored_tree(publication_sessions, country.model.name, current_version) + == [] ) def test_publication_writes_no_tree_for_another_version_stored_without_one( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: """A stored version that is not the installed one keeps having no tree. @@ -1079,52 +1095,50 @@ def test_publication_writes_no_tree_for_another_version_stored_without_one( older = normalized_catalog(policyengine_version="1.0.0") catalog = normalized_catalog() older_version = older.country("us").model_version.version - publish_catalog(publication_engine, older) - _delete_tree(publication_engine, older_version) + publish_catalog(publication_sessions, older) + _delete_tree(publication_sessions, older_version) - evidence = publish_catalog(publication_engine, catalog) - again = publish_catalog(publication_engine, catalog) + evidence = publish_catalog(publication_sessions, catalog) + again = publish_catalog(publication_sessions, catalog) assert {version for _model, version, _rows in evidence.parameter_trees_written} == { catalog.country("us").model_version.version } assert again.parameter_trees_written == () for country in catalog.countries: - assert _stored_tree(publication_engine, country.model.name, older_version) == [] + assert ( + _stored_tree(publication_sessions, country.model.name, older_version) == [] + ) def test_publication_fails_when_a_published_version_is_left_without_a_tree( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( publication_module, "write_parameter_trees", - lambda _connection, _countries: (), + lambda _session, _countries: (), ) with pytest.raises(CatalogPublicationError, match="has no parameter tree"): - publish_catalog(publication_engine, normalized_catalog()) + publish_catalog(publication_sessions, normalized_catalog()) - assert _counts(publication_engine)["tax_benefit_model_versions"] == 0 + assert _counts(publication_sessions)["tax_benefit_model_versions"] == 0 def test_the_catalog_writer_role_publishes_the_parameter_tree( - publication_engine: Engine, - managed_v2_roles, - v2_engine_as_role, + publication_sessions: sessionmaker[Session], + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> None: """Publication as the catalog writer, with only its declared privileges. It writes each published version's tree, which needs the role's INSERT grant on the tree table. """ - writer_engine = v2_engine_as_role(CATALOG_WRITER_ROLE, poolclass=NullPool) catalog = normalized_catalog() - try: - evidence = publish_catalog(writer_engine, catalog) - finally: - writer_engine.dispose() + + evidence = publish_catalog(v2_sessions_as_role(CATALOG_WRITER_ROLE), catalog) assert evidence.parameter_trees_written == tuple( (country.model.name, country.model_version.version, len(FIXTURE_TREE)) @@ -1133,7 +1147,7 @@ def test_the_catalog_writer_role_publishes_the_parameter_tree( for country in catalog.countries: assert ( _stored_tree( - publication_engine, + publication_sessions, country.model.name, country.model_version.version, ) @@ -1141,21 +1155,32 @@ def test_the_catalog_writer_role_publishes_the_parameter_tree( ) -def _stored_search_file(engine: Engine, model_name: str, version: str) -> dict: +def _stored_search_file( + sessions: sessionmaker[Session], model_name: str, version: str +) -> dict: """Return a stored version's search file, checking its hash and sizes.""" - with engine.connect() as connection: - row = connection.execute( - text( - "SELECT search_file.file_format, search_file.compressed_content, " - "search_file.content_sha256, search_file.uncompressed_size, " - "search_file.compressed_size " - "FROM parameter_search_files AS search_file " - "JOIN tax_benefit_model_versions AS version " - "ON version.id = search_file.tax_benefit_model_version_id " - "JOIN tax_benefit_models AS model ON model.id = version.model_id " - "WHERE model.name = :model_name AND version.version = :version" - ), - {"model_name": model_name, "version": version}, + with sessions() as session: + row = session.execute( + sa.select( + col(ParameterSearchFile.file_format), + col(ParameterSearchFile.compressed_content), + col(ParameterSearchFile.content_sha256), + col(ParameterSearchFile.uncompressed_size), + col(ParameterSearchFile.compressed_size), + ) + .join( + TaxBenefitModelVersion, + col(TaxBenefitModelVersion.id) + == col(ParameterSearchFile.tax_benefit_model_version_id), + ) + .join( + TaxBenefitModel, + col(TaxBenefitModel.id) == col(TaxBenefitModelVersion.model_id), + ) + .where( + col(TaxBenefitModel.name) == model_name, + col(TaxBenefitModelVersion.version) == version, + ) ).one() content = gzip.decompress(row.compressed_content) assert row.file_format == 1 @@ -1165,18 +1190,30 @@ def _stored_search_file(engine: Engine, model_name: str, version: str) -> dict: return json.loads(content) -def _delete_search_files(engine: Engine, version: str) -> None: +def _delete_search_files(sessions: sessionmaker[Session], version: str) -> None: """Make the stored versions of one .py version look stored before the files.""" - with engine.begin() as connection: - connection.execute( - text( - "DELETE FROM parameter_search_files AS search_file " - "USING tax_benefit_model_versions AS version " - "WHERE version.id = search_file.tax_benefit_model_version_id " - "AND version.version = :version" - ), - {"version": version}, + with sessions.begin() as session: + session.execute( + sa.delete(ParameterSearchFile).where( + col(ParameterSearchFile.tax_benefit_model_version_id).in_( + _version_ids(version) + ) + ) + ) + + +def _search_file_count(sessions: sessionmaker[Session], version: str | None) -> int: + """Count the stored search files, of one .py version's versions if given.""" + statement = sa.select(sa.func.count()).select_from(ParameterSearchFile) + if version is not None: + statement = statement.where( + col(ParameterSearchFile.tax_benefit_model_version_id).in_( + _version_ids(version) + ) ) + with sessions() as session: + count: int = session.execute(statement).scalar_one() + return count def _fixture_search_file(country_id: str, version: str) -> dict: @@ -1199,16 +1236,16 @@ def _fixture_search_file(country_id: str, version: str) -> dict: def test_publication_writes_each_new_version_parameter_search_file( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: catalog = normalized_catalog() - evidence = publish_catalog(publication_engine, catalog) + evidence = publish_catalog(publication_sessions, catalog) for country in catalog.countries: version = country.model_version.version assert _stored_search_file( - publication_engine, country.model.name, version + publication_sessions, country.model.name, version ) == _fixture_search_file(country.country_id, version) assert [ (model_name, version) @@ -1222,7 +1259,7 @@ def test_publication_writes_each_new_version_parameter_search_file( def test_republication_writes_only_the_installed_version_search_file( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: """A stored version gets its file only when its packages are installed. @@ -1235,15 +1272,15 @@ def test_republication_writes_only_the_installed_version_search_file( catalog = normalized_catalog() older_country_version = older.country("us").model_version.version current_country_version = catalog.country("us").model_version.version - publish_catalog(publication_engine, older) - publish_catalog(publication_engine, catalog) - _delete_search_files(publication_engine, older_country_version) - _delete_search_files(publication_engine, current_country_version) - before_ids = _identifiers(publication_engine) - before_counts = _counts(publication_engine) + publish_catalog(publication_sessions, older) + publish_catalog(publication_sessions, catalog) + _delete_search_files(publication_sessions, older_country_version) + _delete_search_files(publication_sessions, current_country_version) + before_ids = _identifiers(publication_sessions) + before_counts = _counts(publication_sessions) - evidence = publish_catalog(publication_engine, catalog) - again = publish_catalog(publication_engine, catalog) + evidence = publish_catalog(publication_sessions, catalog) + again = publish_catalog(publication_sessions, catalog) assert [ (model_name, version) @@ -1257,44 +1294,30 @@ def test_republication_writes_only_the_installed_version_search_file( assert again.parameter_search_files_written == () for country in catalog.countries: assert _stored_search_file( - publication_engine, country.model.name, current_country_version + publication_sessions, country.model.name, current_country_version ) == _fixture_search_file(country.country_id, current_country_version) - with publication_engine.connect() as connection: - assert ( - connection.execute( - text( - "SELECT count(*) FROM parameter_search_files AS search_file " - "JOIN tax_benefit_model_versions AS version " - "ON version.id = search_file.tax_benefit_model_version_id " - "WHERE version.version = :version" - ), - {"version": older_country_version}, - ).scalar_one() - == 0 - ) - assert _identifiers(publication_engine) == before_ids - assert _counts(publication_engine) == before_counts + assert _search_file_count(publication_sessions, older_country_version) == 0 + assert _identifiers(publication_sessions) == before_ids + assert _counts(publication_sessions) == before_counts def test_republication_refuses_a_stored_search_file_that_differs( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: catalog = normalized_catalog() - publish_catalog(publication_engine, catalog) - with publication_engine.begin() as connection: - connection.execute( - text("UPDATE parameter_search_files SET content_sha256 = repeat('0', 64)") - ) + publish_catalog(publication_sessions, catalog) + with publication_sessions.begin() as session: + session.execute(sa.update(ParameterSearchFile).values(content_sha256="0" * 64)) with pytest.raises( CatalogPublicationError, match=r"stored parameter search file .* differs from the installed packages'", ): - publish_catalog(publication_engine, catalog) + publish_catalog(publication_sessions, catalog) def test_search_file_editability_follows_the_stored_current_law_values( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: models = source_models() add_format_2_variable_records(models["us"]) @@ -1334,11 +1357,11 @@ def test_search_file_editability_follows_the_stored_current_law_values( region_references=region_references(), ) - publish_catalog(publication_engine, catalog) + publish_catalog(publication_sessions, catalog) us = catalog.country("us") search_file = _stored_search_file( - publication_engine, us.model.name, us.model_version.version + publication_sessions, us.model.name, us.model_version.version ) entries = {entry["path"]: entry for entry in search_file["parameters"]} assert entries["gov.example.bracket[1].rate"] == { @@ -1359,36 +1382,32 @@ def test_search_file_editability_follows_the_stored_current_law_values( def test_publication_fails_when_a_published_version_has_no_search_file( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr( publication_module, "write_parameter_search_files", - lambda _connection, _countries: (), + lambda _session, _countries: (), ) with pytest.raises(CatalogPublicationError, match="has no parameter search file"): - publish_catalog(publication_engine, normalized_catalog()) + publish_catalog(publication_sessions, normalized_catalog()) - assert _counts(publication_engine)["tax_benefit_model_versions"] == 0 + assert _counts(publication_sessions)["tax_benefit_model_versions"] == 0 def test_the_catalog_writer_role_publishes_the_search_files( - publication_engine: Engine, - managed_v2_roles, - v2_engine_as_role, + publication_sessions: sessionmaker[Session], + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> None: """Publication as the catalog writer writes each version's search file. That needs the role's declared INSERT grant on the search files' table. """ - writer_engine = v2_engine_as_role(CATALOG_WRITER_ROLE, poolclass=NullPool) catalog = normalized_catalog() - try: - evidence = publish_catalog(writer_engine, catalog) - finally: - writer_engine.dispose() + + evidence = publish_catalog(v2_sessions_as_role(CATALOG_WRITER_ROLE), catalog) assert [ (model_name, version) @@ -1402,21 +1421,21 @@ def test_the_catalog_writer_role_publishes_the_search_files( for country in catalog.countries: version = country.model_version.version assert _stored_search_file( - publication_engine, country.model.name, version + publication_sessions, country.model.name, version ) == _fixture_search_file(country.country_id, version) def test_one_publication_gives_the_installed_stored_version_its_tree_and_file( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: """The installed version stored without either gets both in one run.""" catalog = normalized_catalog() current_version = catalog.country("us").model_version.version - publish_catalog(publication_engine, catalog) - _delete_tree(publication_engine, current_version) - _delete_search_files(publication_engine, current_version) + publish_catalog(publication_sessions, catalog) + _delete_tree(publication_sessions, current_version) + _delete_search_files(publication_sessions, current_version) - evidence = publish_catalog(publication_engine, catalog) + evidence = publish_catalog(publication_sessions, catalog) model_names = [ country.model.name @@ -1431,28 +1450,28 @@ def test_one_publication_gives_the_installed_stored_version_its_tree_and_file( ] == model_names for country in catalog.countries: assert ( - _stored_tree(publication_engine, country.model.name, current_version) + _stored_tree(publication_sessions, country.model.name, current_version) == FIXTURE_TREE ) assert _stored_search_file( - publication_engine, country.model.name, current_version + publication_sessions, country.model.name, current_version ) == _fixture_search_file(country.country_id, current_version) -def _mark_stored_before_catalog_format_2(engine: Engine, version: str) -> None: +def _mark_stored_before_catalog_format_2( + sessions: sessionmaker[Session], version: str +) -> None: """Make the stored versions of one .py version look stored before format 2.""" - with engine.begin() as connection: - connection.execute( - text( - "UPDATE tax_benefit_model_versions SET catalog_format = NULL " - "WHERE version = :version" - ), - {"version": version}, + with sessions.begin() as session: + session.execute( + sa.update(TaxBenefitModelVersion) + .where(col(TaxBenefitModelVersion.version) == version) + .values(catalog_format=None) ) def test_an_installed_version_stored_before_catalog_format_2_gets_no_search_file( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: """A version stored without format 2's flags keeps having no search file. @@ -1462,17 +1481,11 @@ def test_an_installed_version_stored_before_catalog_format_2_gets_no_search_file """ catalog = normalized_catalog() current_version = catalog.country("us").model_version.version - publish_catalog(publication_engine, catalog) - _delete_search_files(publication_engine, current_version) - _mark_stored_before_catalog_format_2(publication_engine, current_version) + publish_catalog(publication_sessions, catalog) + _delete_search_files(publication_sessions, current_version) + _mark_stored_before_catalog_format_2(publication_sessions, current_version) - evidence = publish_catalog(publication_engine, catalog) + evidence = publish_catalog(publication_sessions, catalog) assert evidence.parameter_search_files_written == () - with publication_engine.connect() as connection: - assert ( - connection.execute( - text("SELECT count(*) FROM parameter_search_files") - ).scalar_one() - == 0 - ) + assert _search_file_count(publication_sessions, None) == 0 diff --git a/tests/integration/test_v2_catalog_publication_pruning.py b/tests/integration/test_v2_catalog_publication_pruning.py index 075ebe715..bbb620e7d 100644 --- a/tests/integration/test_v2_catalog_publication_pruning.py +++ b/tests/integration/test_v2_catalog_publication_pruning.py @@ -10,22 +10,17 @@ from __future__ import annotations -import os import time from concurrent.futures import Future, ThreadPoolExecutor -from datetime import UTC, datetime -from pathlib import Path +from datetime import UTC, datetime, timedelta +from typing import TYPE_CHECKING, Any from uuid import UUID, uuid4 import pytest -from alembic import command -from alembic.config import Config +import sqlalchemy as sa from fastapi.testclient import TestClient from flask import Flask -from sqlalchemy import create_engine, text -from sqlalchemy.engine import Engine, make_url -from sqlalchemy.pool import NullPool -from sqlmodel import Session, select +from sqlmodel import col, select from policyengine_api.asgi_factory import create_asgi_app from policyengine_api.data.v2.catalog import publication as publication_module @@ -39,15 +34,20 @@ ) from policyengine_api.data.v2.database import build_v2_read_session_factory from policyengine_api.data.v2.models import ( + Dataset, Dynamic, Parameter, + ParameterNode, + ParameterSearchFile, + ParameterTreeChild, ParameterValue, Policy, + Region, TaxBenefitModel, TaxBenefitModelVersion, + Variable, ) from policyengine_api.data.v2.privileges import CATALOG_WRITER_ROLE -from policyengine_api.data.v2.settings import V2_MIGRATION_DATABASE_URL from policyengine_api.fastapi_routes.dependencies import NativeRouteDependencies from policyengine_api.fastapi_routes.v2.metadata.response_cache_support import ( MetadataResponseCache, @@ -64,9 +64,14 @@ ) from policyengine_api.services.v2.metadata.services import V2MetadataService from tests.fixtures.v2_catalog import normalized_catalog +from tests.integration.catalog_publication_support import emptied_catalog + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session -REPO = Path(__file__).parents[2] -DISPOSABLE_DATABASE = "policyengine_v2_alembic_test" OLD_VERSION = "5.0.1" # The earlier of the two other versions pruning keeps, with the previous one. EARLIER_KEPT_VERSION = "5.0.2" @@ -79,168 +84,210 @@ # three parameter tree rows and one search file. FIXTURE_PRUNED_ROWS = {"parameter_values": 2, "tree_rows": 3, "search_files": 1} # The tables pruning never changes, read per catalog version. -VERSIONED_TABLES = ("variables", "parameter_nodes", "parameters", "datasets", "regions") +VERSIONED_MODELS: dict[str, Any] = { + "variables": Variable, + "parameter_nodes": ParameterNode, + "parameters": Parameter, + "datasets": Dataset, + "regions": Region, +} -def _disposable_url() -> str: - database_url = os.environ.get(V2_MIGRATION_DATABASE_URL, "") - if not database_url: - pytest.skip(f"{V2_MIGRATION_DATABASE_URL} is not set") - url = make_url(database_url) - if url.database != DISPOSABLE_DATABASE or url.host not in { - "localhost", - "127.0.0.1", - "::1", - "postgres", - }: - pytest.fail("catalog pruning tests require disposable local Postgres") - return database_url +@pytest.fixture +def publication_sessions( + v2_owner_sessions: sessionmaker[Session], +) -> Iterator[sessionmaker[Session]]: + with emptied_catalog(v2_owner_sessions) as sessions: + yield sessions -def _clear_catalog(engine: Engine) -> None: - # Policies and dynamics name a model, so the truncation removes them too. - with engine.begin() as connection: - connection.execute(text("TRUNCATE tax_benefit_models CASCADE")) +def _publish(sessions: sessionmaker[Session], version: str): + return publish_catalog(sessions, normalized_catalog(policyengine_version=version)) -@pytest.fixture -def publication_engine() -> Engine: - database_url = _disposable_url() - command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(database_url, poolclass=NullPool) - _clear_catalog(engine) - yield engine - _clear_catalog(engine) - engine.dispose() - - -def _publish(engine: Engine, version: str): - return publish_catalog(engine, normalized_catalog(policyengine_version=version)) - - -def _version_id(engine: Engine, model_name: str, version: str) -> UUID: - with engine.connect() as connection: - return connection.execute( - text( - "SELECT version.id FROM tax_benefit_model_versions AS version " - "JOIN tax_benefit_models AS model ON model.id = version.model_id " - "WHERE model.name = :model_name AND version.version = :version" - ), - {"model_name": model_name, "version": version}, +def _version_id(sessions: sessionmaker[Session], model_name: str, version: str) -> UUID: + with sessions() as session: + version_id: UUID = session.execute( + sa.select(col(TaxBenefitModelVersion.id)) + .join( + TaxBenefitModel, + col(TaxBenefitModel.id) == col(TaxBenefitModelVersion.model_id), + ) + .where( + col(TaxBenefitModel.name) == model_name, + col(TaxBenefitModelVersion.version) == version, + ) ).scalar_one() + return version_id -def _pruned_at(engine: Engine, model_name: str, version: str) -> datetime | None: - with engine.connect() as connection: - return connection.execute( - text( - "SELECT catalog_values_pruned_at FROM tax_benefit_model_versions " - "WHERE id = :version_id" - ), - {"version_id": _version_id(engine, model_name, version)}, +def _version_column( + sessions: sessionmaker[Session], column: Any, model_name: str, version: str +) -> Any: + """Return one column of a stored version's row.""" + version_id = _version_id(sessions, model_name, version) + with sessions() as session: + return session.execute( + sa.select(column).where(col(TaxBenefitModelVersion.id) == version_id) ).scalar_one() -def _rows(engine: Engine, statement: str, version_id: UUID) -> list[tuple]: - with engine.connect() as connection: - return [ - tuple(row) - for row in connection.execute(text(statement), {"version_id": version_id}) - ] +def _pruned_at( + sessions: sessionmaker[Session], model_name: str, version: str +) -> datetime | None: + pruned_at: datetime | None = _version_column( + sessions, + col(TaxBenefitModelVersion.catalog_values_pruned_at), + model_name, + version, + ) + return pruned_at + + +def _rows(sessions: sessionmaker[Session], statement: sa.Select[Any]) -> list[tuple]: + with sessions() as session: + return [tuple(row) for row in session.execute(statement)] + + +def _every_column(model: Any) -> list[Any]: + """Return each column attribute of a mapped class, as ``SELECT *`` reads them.""" + return [ + getattr(model, attribute.key) for attribute in sa.inspect(model).column_attrs + ] + +def _as_json_text(column: Any) -> sa.Cast[str]: + """Read a JSON column as its text, which tells 1, 1.0 and true apart.""" + return sa.cast(column, sa.Text) -def _prunable_rows(engine: Engine, model_name: str, version: str) -> dict: + +def _prunable_rows( + sessions: sessionmaker[Session], model_name: str, version: str +) -> dict: """Return what pruning deletes from one stored version, in a stable order. Tree rows leave out their random IDs and creation times, which differ between any two publications. """ - version_id = _version_id(engine, model_name, version) + version_id = _version_id(sessions, model_name, version) return { "parameter_values": _rows( - engine, - "SELECT value.id, value.parameter_id, value.value_json::text, " - "value.start_date, value.end_date FROM parameter_values AS value " - "JOIN parameters AS parameter ON parameter.id = value.parameter_id " - "WHERE parameter.tax_benefit_model_version_id = :version_id " - "AND value.policy_id IS NULL AND value.dynamic_id IS NULL " - "ORDER BY value.id", - version_id, + sessions, + sa.select( + col(ParameterValue.id), + col(ParameterValue.parameter_id), + _as_json_text(col(ParameterValue.value_json)), + col(ParameterValue.start_date), + col(ParameterValue.end_date), + ) + .join(Parameter, col(Parameter.id) == col(ParameterValue.parameter_id)) + .where( + col(Parameter.tax_benefit_model_version_id) == version_id, + col(ParameterValue.policy_id).is_(None), + col(ParameterValue.dynamic_id).is_(None), + ) + .order_by(col(ParameterValue.id)), ), "tree_rows": _rows( - engine, - "SELECT parent_path, path, position, label, child_type, child_count, " - "reform_position, reform_child_count, parameter_id, economy, household " - "FROM parameter_tree_children " - "WHERE tax_benefit_model_version_id = :version_id ORDER BY path", - version_id, + sessions, + sa.select( + col(ParameterTreeChild.parent_path), + col(ParameterTreeChild.path), + col(ParameterTreeChild.position), + col(ParameterTreeChild.label), + col(ParameterTreeChild.child_type), + col(ParameterTreeChild.child_count), + col(ParameterTreeChild.reform_position), + col(ParameterTreeChild.reform_child_count), + col(ParameterTreeChild.parameter_id), + col(ParameterTreeChild.economy), + col(ParameterTreeChild.household), + ) + .where(col(ParameterTreeChild.tax_benefit_model_version_id) == version_id) + .order_by(col(ParameterTreeChild.path)), ), "search_files": _rows( - engine, - "SELECT file_format, compressed_content, content_sha256, " - "uncompressed_size, compressed_size FROM parameter_search_files " - "WHERE tax_benefit_model_version_id = :version_id ORDER BY file_format", - version_id, + sessions, + sa.select( + col(ParameterSearchFile.file_format), + col(ParameterSearchFile.compressed_content), + col(ParameterSearchFile.content_sha256), + col(ParameterSearchFile.uncompressed_size), + col(ParameterSearchFile.compressed_size), + ) + .where(col(ParameterSearchFile.tax_benefit_model_version_id) == version_id) + .order_by(col(ParameterSearchFile.file_format)), ), } -def _kept_rows(engine: Engine, model_name: str, version: str) -> dict: +def _kept_rows(sessions: sessionmaker[Session], model_name: str, version: str) -> dict: """Return every row of one stored version that pruning never changes.""" - version_id = _version_id(engine, model_name, version) + version_id = _version_id(sessions, model_name, version) kept = { table_name: _rows( - engine, - f"SELECT * FROM {table_name} " - "WHERE tax_benefit_model_version_id = :version_id ORDER BY id", - version_id, + sessions, + sa.select(*_every_column(model)) + .where(col(model.tax_benefit_model_version_id) == version_id) + .order_by(col(model.id)), ) - for table_name in VERSIONED_TABLES + for table_name, model in VERSIONED_MODELS.items() } kept["tax_benefit_model_versions"] = _rows( - engine, - "SELECT id, created_at, model_id, version, description, current_law_id, " - "metadata_time_periods::text, catalog_format, entities::text, " - "basic_inputs::text FROM tax_benefit_model_versions WHERE id = :version_id", - version_id, + sessions, + sa.select( + col(TaxBenefitModelVersion.id), + col(TaxBenefitModelVersion.created_at), + col(TaxBenefitModelVersion.model_id), + col(TaxBenefitModelVersion.version), + col(TaxBenefitModelVersion.description), + col(TaxBenefitModelVersion.current_law_id), + _as_json_text(col(TaxBenefitModelVersion.metadata_time_periods)), + col(TaxBenefitModelVersion.catalog_format), + _as_json_text(col(TaxBenefitModelVersion.entities)), + _as_json_text(col(TaxBenefitModelVersion.basic_inputs)), + ).where(col(TaxBenefitModelVersion.id) == version_id), ) return kept -def _owned_rows(engine: Engine) -> dict[str, list[tuple]]: +def _owned_rows(sessions: sessionmaker[Session]) -> dict[str, list[tuple]]: """Return every policy, dynamic and value a policy or dynamic owns.""" - with engine.connect() as connection: - return { - "owned_values": [ - tuple(row) - for row in connection.execute( - text( - "SELECT id, created_at, parameter_id, value_json::text, " - "start_date, end_date, policy_id, dynamic_id " - "FROM parameter_values " - "WHERE policy_id IS NOT NULL OR dynamic_id IS NOT NULL " - "ORDER BY id" - ) - ) - ], - "policies": [ - tuple(row) - for row in connection.execute( - text("SELECT * FROM policies ORDER BY id") - ) - ], - "dynamics": [ - tuple(row) - for row in connection.execute( - text("SELECT * FROM dynamics ORDER BY id") + return { + "owned_values": _rows( + sessions, + sa.select( + col(ParameterValue.id), + col(ParameterValue.created_at), + col(ParameterValue.parameter_id), + _as_json_text(col(ParameterValue.value_json)), + col(ParameterValue.start_date), + col(ParameterValue.end_date), + col(ParameterValue.policy_id), + col(ParameterValue.dynamic_id), + ) + .where( + sa.or_( + col(ParameterValue.policy_id).is_not(None), + col(ParameterValue.dynamic_id).is_not(None), ) - ], - } + ) + .order_by(col(ParameterValue.id)), + ), + "policies": _rows( + sessions, sa.select(*_every_column(Policy)).order_by(col(Policy.id)) + ), + "dynamics": _rows( + sessions, sa.select(*_every_column(Dynamic)).order_by(col(Dynamic.id)) + ), + } -def _add_saved_reform_and_dynamic(engine: Engine, version: str) -> None: +def _add_saved_reform_and_dynamic( + sessions: sessionmaker[Session], version: str +) -> None: """Store a policy and a dynamic, each with its own value of a US parameter.""" - with Session(engine) as session: + with sessions() as session: model = session.exec( select(TaxBenefitModel).where(TaxBenefitModel.name == US_MODEL) ).one() @@ -291,6 +338,34 @@ def _add_saved_reform_and_dynamic(engine: Engine, version: str) -> None: session.commit() +def _divide_by_zero(session: Session) -> None: + """Fail as the database does on a statement it can't run (DivisionByZero).""" + session.execute(sa.select(sa.literal(1) / sa.literal(0))) + + +def _publish_tomorrow(session: Session, version_id: UUID) -> None: + """Record a version as published a day from now, as a later publication would.""" + session.execute( + sa.update(TaxBenefitModelVersion) + .where(col(TaxBenefitModelVersion.id) == version_id) + .values(catalog_last_published_at=sa.func.now() + timedelta(days=1)) + ) + + +def _delete_tree_and_search_file(session: Session, version_id: UUID) -> None: + """Delete a version's parameter tree rows and search files.""" + session.execute( + sa.delete(ParameterTreeChild).where( + col(ParameterTreeChild.tax_benefit_model_version_id) == version_id + ) + ) + session.execute( + sa.delete(ParameterSearchFile).where( + col(ParameterSearchFile.tax_benefit_model_version_id) == version_id + ) + ) + + def _fixture_pruned(country_id: str, version: str) -> PrunedCatalogVersion: return PrunedCatalogVersion( country_id=country_id, @@ -302,9 +377,9 @@ def _fixture_pruned(country_id: str, version: str) -> PrunedCatalogVersion: def test_publication_prunes_versions_older_than_the_kept_ones_as_the_writer( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], managed_v2_roles, - v2_engine_as_role, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> None: """Pruning deletes exactly the old version's current-law data, as the writer. @@ -313,25 +388,22 @@ def test_publication_prunes_versions_older_than_the_kept_ones_as_the_writer( file go; its marker is set. The kept versions, the reform, the dynamic, their values, the old version's parameters and every other row stay. """ - writer_engine = v2_engine_as_role(CATALOG_WRITER_ROLE, poolclass=NullPool) - try: - _publish(writer_engine, OLD_VERSION) - _add_saved_reform_and_dynamic(publication_engine, OLD_VERSION) - _publish(writer_engine, EARLIER_KEPT_VERSION) - second = _publish(writer_engine, PREVIOUS_VERSION) - before = { - (model_name, version): ( - _kept_rows(publication_engine, model_name, version), - _prunable_rows(publication_engine, model_name, version), - ) - for model_name in MODEL_NAMES - for version in (OLD_VERSION, EARLIER_KEPT_VERSION, PREVIOUS_VERSION) - } - owned_before = _owned_rows(publication_engine) + writer_sessions = v2_sessions_as_role(CATALOG_WRITER_ROLE) + _publish(writer_sessions, OLD_VERSION) + _add_saved_reform_and_dynamic(publication_sessions, OLD_VERSION) + _publish(writer_sessions, EARLIER_KEPT_VERSION) + second = _publish(writer_sessions, PREVIOUS_VERSION) + before = { + (model_name, version): ( + _kept_rows(publication_sessions, model_name, version), + _prunable_rows(publication_sessions, model_name, version), + ) + for model_name in MODEL_NAMES + for version in (OLD_VERSION, EARLIER_KEPT_VERSION, PREVIOUS_VERSION) + } + owned_before = _owned_rows(publication_sessions) - third = _publish(writer_engine, INSTALLED_VERSION) - finally: - writer_engine.dispose() + third = _publish(writer_sessions, INSTALLED_VERSION) assert second.pruned_catalog_versions == () assert third.pruned_catalog_versions == ( @@ -340,34 +412,34 @@ def test_publication_prunes_versions_older_than_the_kept_ones_as_the_writer( ) assert third.catalog_pruning_failures == () assert len(owned_before["owned_values"]) == 2 - assert _owned_rows(publication_engine) == owned_before + assert _owned_rows(publication_sessions) == owned_before for model_name in MODEL_NAMES: old_kept, old_prunable = before[(model_name, OLD_VERSION)] assert all(old_prunable.values()), model_name - assert _kept_rows(publication_engine, model_name, OLD_VERSION) == old_kept - assert _prunable_rows(publication_engine, model_name, OLD_VERSION) == { + assert _kept_rows(publication_sessions, model_name, OLD_VERSION) == old_kept + assert _prunable_rows(publication_sessions, model_name, OLD_VERSION) == { "parameter_values": [], "tree_rows": [], "search_files": [], } - assert _pruned_at(publication_engine, model_name, OLD_VERSION) is not None + assert _pruned_at(publication_sessions, model_name, OLD_VERSION) is not None for version in (EARLIER_KEPT_VERSION, PREVIOUS_VERSION): assert ( - _kept_rows(publication_engine, model_name, version), - _prunable_rows(publication_engine, model_name, version), + _kept_rows(publication_sessions, model_name, version), + _prunable_rows(publication_sessions, model_name, version), ) == before[(model_name, version)] for version in (EARLIER_KEPT_VERSION, PREVIOUS_VERSION, INSTALLED_VERSION): - assert _pruned_at(publication_engine, model_name, version) is None - installed = _prunable_rows(publication_engine, model_name, INSTALLED_VERSION) + assert _pruned_at(publication_sessions, model_name, version) is None + installed = _prunable_rows(publication_sessions, model_name, INSTALLED_VERSION) assert {name: len(rows) for name, rows in installed.items()} == ( FIXTURE_PRUNED_ROWS ) def test_republishing_a_pruned_version_restores_what_its_publication_wrote( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], managed_v2_roles, - v2_engine_as_role, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> None: """A rollback that installs a pruned version restores its rows and marker. @@ -376,37 +448,35 @@ def test_republishing_a_pruned_version_restores_what_its_publication_wrote( installed version and the two most recently published other ones, so it prunes the earliest of the versions released after it. """ - writer_engine = v2_engine_as_role(CATALOG_WRITER_ROLE, poolclass=NullPool) - try: - _publish(writer_engine, OLD_VERSION) - first_published = { - model_name: _prunable_rows(publication_engine, model_name, OLD_VERSION) - for model_name in MODEL_NAMES - } - _publish(writer_engine, EARLIER_KEPT_VERSION) - _publish(writer_engine, PREVIOUS_VERSION) - _publish(writer_engine, INSTALLED_VERSION) - assert all( - _pruned_at(publication_engine, model_name, OLD_VERSION) is not None - for model_name in MODEL_NAMES - ) + writer_sessions = v2_sessions_as_role(CATALOG_WRITER_ROLE) + _publish(writer_sessions, OLD_VERSION) + first_published = { + model_name: _prunable_rows(publication_sessions, model_name, OLD_VERSION) + for model_name in MODEL_NAMES + } + _publish(writer_sessions, EARLIER_KEPT_VERSION) + _publish(writer_sessions, PREVIOUS_VERSION) + _publish(writer_sessions, INSTALLED_VERSION) + assert all( + _pruned_at(publication_sessions, model_name, OLD_VERSION) is not None + for model_name in MODEL_NAMES + ) - rollback = _publish(writer_engine, OLD_VERSION) - again = _publish(writer_engine, OLD_VERSION) - finally: - writer_engine.dispose() + rollback = _publish(writer_sessions, OLD_VERSION) + again = _publish(writer_sessions, OLD_VERSION) for model_name in MODEL_NAMES: assert ( - _prunable_rows(publication_engine, model_name, OLD_VERSION) + _prunable_rows(publication_sessions, model_name, OLD_VERSION) == first_published[model_name] ) - assert _pruned_at(publication_engine, model_name, OLD_VERSION) is None + assert _pruned_at(publication_sessions, model_name, OLD_VERSION) is None assert ( - _pruned_at(publication_engine, model_name, EARLIER_KEPT_VERSION) is not None + _pruned_at(publication_sessions, model_name, EARLIER_KEPT_VERSION) + is not None ) for version in (PREVIOUS_VERSION, INSTALLED_VERSION): - assert _pruned_at(publication_engine, model_name, version) is None + assert _pruned_at(publication_sessions, model_name, version) is None assert rollback.restored_catalog_versions == ( ("us", OLD_VERSION, FIXTURE_PRUNED_ROWS["parameter_values"]), ("uk", OLD_VERSION, FIXTURE_PRUNED_ROWS["parameter_values"]), @@ -440,7 +510,7 @@ def test_republishing_a_pruned_version_restores_what_its_publication_wrote( def test_a_pruning_failure_rolls_back_that_version_and_publication_succeeds( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch, ) -> None: """One version's failure leaves it unchanged; the others are still pruned. @@ -449,23 +519,23 @@ def test_a_pruning_failure_rolls_back_that_version_and_publication_succeeds( transaction, so all of them roll back. Publication still returns its evidence, which reports the failure, and the next run prunes the version. """ - _publish(publication_engine, OLD_VERSION) - _publish(publication_engine, EARLIER_KEPT_VERSION) - _publish(publication_engine, PREVIOUS_VERSION) - failing_version_id = _version_id(publication_engine, US_MODEL, OLD_VERSION) - us_old_before = _prunable_rows(publication_engine, US_MODEL, OLD_VERSION) + _publish(publication_sessions, OLD_VERSION) + _publish(publication_sessions, EARLIER_KEPT_VERSION) + _publish(publication_sessions, PREVIOUS_VERSION) + failing_version_id = _version_id(publication_sessions, US_MODEL, OLD_VERSION) + us_old_before = _prunable_rows(publication_sessions, US_MODEL, OLD_VERSION) prune_catalog_version = publication_module.prune_catalog_version - def prune_then_fail_for_one_version(connection, version_id): - deleted = prune_catalog_version(connection, version_id) + def prune_then_fail_for_one_version(session, version_id): + deleted = prune_catalog_version(session, version_id) if version_id == failing_version_id: - connection.execute(text("SELECT 1 / 0")) + _divide_by_zero(session) return deleted monkeypatch.setattr( publication_module, "prune_catalog_version", prune_then_fail_for_one_version ) - evidence = _publish(publication_engine, INSTALLED_VERSION) + evidence = _publish(publication_sessions, INSTALLED_VERSION) monkeypatch.undo() expected_failure = CatalogPruningFailure( @@ -487,19 +557,19 @@ def prune_then_fail_for_one_version(connection, version_id): } ] assert evidence.pruned_catalog_versions == (_fixture_pruned("uk", OLD_VERSION),) - assert _prunable_rows(publication_engine, US_MODEL, OLD_VERSION) == us_old_before - assert _pruned_at(publication_engine, US_MODEL, OLD_VERSION) is None - assert _pruned_at(publication_engine, UK_MODEL, OLD_VERSION) is not None - assert _version_id(publication_engine, US_MODEL, INSTALLED_VERSION) is not None + assert _prunable_rows(publication_sessions, US_MODEL, OLD_VERSION) == us_old_before + assert _pruned_at(publication_sessions, US_MODEL, OLD_VERSION) is None + assert _pruned_at(publication_sessions, UK_MODEL, OLD_VERSION) is not None + assert _version_id(publication_sessions, US_MODEL, INSTALLED_VERSION) is not None - retried = _publish(publication_engine, INSTALLED_VERSION) + retried = _publish(publication_sessions, INSTALLED_VERSION) assert retried.pruned_catalog_versions == (_fixture_pruned("us", OLD_VERSION),) assert retried.catalog_pruning_failures == () def test_a_failure_to_read_the_stored_versions_is_reported_and_publication_succeeds( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch, ) -> None: """A database error choosing the versions to prune doesn't fail publication. @@ -508,19 +578,19 @@ def test_a_failure_to_read_the_stored_versions_is_reported_and_publication_succe failure prunes nothing and is reported for each country of the catalog, without a version, since none was chosen; the next run prunes them. """ - _publish(publication_engine, OLD_VERSION) - _publish(publication_engine, EARLIER_KEPT_VERSION) - _publish(publication_engine, PREVIOUS_VERSION) + _publish(publication_sessions, OLD_VERSION) + _publish(publication_sessions, EARLIER_KEPT_VERSION) + _publish(publication_sessions, PREVIOUS_VERSION) - def fail_to_read_stored_versions(connection, model_names): - connection.execute(text("SELECT 1 / 0")) + def fail_to_read_stored_versions(session, model_names): + _divide_by_zero(session) monkeypatch.setattr( publication_module, "read_stored_catalog_versions", fail_to_read_stored_versions, ) - evidence = _publish(publication_engine, INSTALLED_VERSION) + evidence = _publish(publication_sessions, INSTALLED_VERSION) monkeypatch.undo() assert evidence.pruned_catalog_versions == () @@ -542,10 +612,10 @@ def fail_to_read_stored_versions(connection, model_names): for failure in evidence.as_dict()["catalog_pruning_failures"] ] == [None, None] for model_name in MODEL_NAMES: - assert _version_id(publication_engine, model_name, INSTALLED_VERSION) - assert _pruned_at(publication_engine, model_name, OLD_VERSION) is None + assert _version_id(publication_sessions, model_name, INSTALLED_VERSION) + assert _pruned_at(publication_sessions, model_name, OLD_VERSION) is None - retried = _publish(publication_engine, INSTALLED_VERSION) + retried = _publish(publication_sessions, INSTALLED_VERSION) assert retried.pruned_catalog_versions == ( _fixture_pruned("uk", OLD_VERSION), @@ -567,9 +637,11 @@ def _route_client(dependencies: NativeRouteDependencies) -> TestClient: ) -def _runtime_client(engine: Engine, **reader_options) -> TestClient: - """Serve the metadata routes from ``engine`` with the installed version running.""" - read_sessions = build_v2_read_session_factory(engine) +def _runtime_client( + sessions: sessionmaker[Session], **reader_options: Any +) -> TestClient: + """Serve the metadata routes from ``sessions``, the installed version running.""" + read_sessions = build_v2_read_session_factory(sessions) selected_catalogs = reader_options.get("selected_catalogs") return _route_client( NativeRouteDependencies( @@ -595,9 +667,9 @@ def _pruned_message(country_id: str, version: str) -> str: def test_routes_answer_404_for_a_pruned_version_and_serve_its_kept_rows( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], managed_v2_roles, - v2_engine_as_role, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> None: """Read as the Public API's runtime role, with its declared privileges.""" for version in ( @@ -606,58 +678,55 @@ def test_routes_answer_404_for_a_pruned_version_and_serve_its_kept_rows( PREVIOUS_VERSION, INSTALLED_VERSION, ): - _publish(publication_engine, version) + _publish(publication_sessions, version) old_catalog = normalized_catalog(policyengine_version=OLD_VERSION).country("us") old_query = {"country_id": "us", "policyengine_version": OLD_VERSION} - runtime_engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - try: - client = _runtime_client(runtime_engine) - pruned_responses = { - label: client.get(path, params=params, headers=headers) - for label, path, params, headers in ( - ("values", "/v2/parameter-values", old_query, {}), - ( - "one value", - f"/v2/parameter-values/{old_catalog.parameters[0].values[0].id}", - old_query, - {}, - ), - ("tree", "/v2/parameters/children", old_query, {}), - ("search file", "/v2/parameters/search-file", old_query, {}), - ( - "search file revalidation", - "/v2/parameters/search-file", - old_query, - {"If-None-Match": '"0123"'}, - ), - ("variables", "/v2/model-catalog/variables", old_query, {}), - ( - "parameters", - "/v2/model-catalog/parameters", - {**old_query, "name": "gov.example.rate"}, - {}, - ), - ) - } - kept_responses = { - path: client.get(path, params=old_query) - for path in ( - "/v2/parameters", - f"/v2/parameters/{old_catalog.parameters[0].id}", - "/v2/variables", - "/v2/model-catalog", - "/v2/regions", - "/v2/datasets", - "/v2/economy-options", - "/v2/tax-benefit-model-versions", - ) - } - previous_values = client.get( - "/v2/parameter-values", - params={"country_id": "us", "policyengine_version": PREVIOUS_VERSION}, + runtime_sessions = v2_sessions_as_role(managed_v2_roles.runtime) + client = _runtime_client(runtime_sessions) + pruned_responses = { + label: client.get(path, params=params, headers=headers) + for label, path, params, headers in ( + ("values", "/v2/parameter-values", old_query, {}), + ( + "one value", + f"/v2/parameter-values/{old_catalog.parameters[0].values[0].id}", + old_query, + {}, + ), + ("tree", "/v2/parameters/children", old_query, {}), + ("search file", "/v2/parameters/search-file", old_query, {}), + ( + "search file revalidation", + "/v2/parameters/search-file", + old_query, + {"If-None-Match": '"0123"'}, + ), + ("variables", "/v2/model-catalog/variables", old_query, {}), + ( + "parameters", + "/v2/model-catalog/parameters", + {**old_query, "name": "gov.example.rate"}, + {}, + ), + ) + } + kept_responses = { + path: client.get(path, params=old_query) + for path in ( + "/v2/parameters", + f"/v2/parameters/{old_catalog.parameters[0].id}", + "/v2/variables", + "/v2/model-catalog", + "/v2/regions", + "/v2/datasets", + "/v2/economy-options", + "/v2/tax-benefit-model-versions", ) - finally: - runtime_engine.dispose() + } + previous_values = client.get( + "/v2/parameter-values", + params={"country_id": "us", "policyengine_version": PREVIOUS_VERSION}, + ) for label, response in pruned_responses.items(): assert response.status_code == 404, label @@ -672,9 +741,9 @@ def test_routes_answer_404_for_a_pruned_version_and_serve_its_kept_rows( def test_a_process_that_selected_a_version_before_its_pruning_answers_404( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], managed_v2_roles, - v2_engine_as_role, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> None: """The production reader keeps selections and whole-version responses. @@ -685,41 +754,38 @@ def test_a_process_that_selected_a_version_before_its_pruning_answers_404( built before the pruning stays kept: it answers 200 with that body, and 304 to its ETag, which equal what restoring the version writes. """ - _publish(publication_engine, OLD_VERSION) - _publish(publication_engine, EARLIER_KEPT_VERSION) - _publish(publication_engine, PREVIOUS_VERSION) + _publish(publication_sessions, OLD_VERSION) + _publish(publication_sessions, EARLIER_KEPT_VERSION) + _publish(publication_sessions, PREVIOUS_VERSION) old_query = {"country_id": "us", "policyengine_version": OLD_VERSION} selected_catalogs = SelectedCatalogStore() - runtime_engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - try: - client = _runtime_client( - runtime_engine, - selected_catalogs=selected_catalogs, - response_cache=MetadataResponseCache(), - ) - before_pruning = client.get("/v2/parameter-values", params=old_query) - variables_before_pruning = client.get( - "/v2/model-catalog/variables", params=old_query - ) - _publish(publication_engine, INSTALLED_VERSION) - variables_after_pruning = client.get( - "/v2/model-catalog/variables", params=old_query - ) - variables_revalidated = client.get( - "/v2/model-catalog/variables", - params=old_query, - headers={"If-None-Match": variables_before_pruning.headers["etag"]}, + runtime_sessions = v2_sessions_as_role(managed_v2_roles.runtime) + client = _runtime_client( + runtime_sessions, + selected_catalogs=selected_catalogs, + response_cache=MetadataResponseCache(), + ) + before_pruning = client.get("/v2/parameter-values", params=old_query) + variables_before_pruning = client.get( + "/v2/model-catalog/variables", params=old_query + ) + _publish(publication_sessions, INSTALLED_VERSION) + variables_after_pruning = client.get( + "/v2/model-catalog/variables", params=old_query + ) + variables_revalidated = client.get( + "/v2/model-catalog/variables", + params=old_query, + headers={"If-None-Match": variables_before_pruning.headers["etag"]}, + ) + after_pruning = { + path: client.get(path, params=old_query) + for path in ( + "/v2/parameter-values", + "/v2/parameters/children", + "/v2/parameters/search-file", ) - after_pruning = { - path: client.get(path, params=old_query) - for path in ( - "/v2/parameter-values", - "/v2/parameters/children", - "/v2/parameters/search-file", - ) - } - finally: - runtime_engine.dispose() + } assert before_pruning.status_code == 200 assert len(before_pruning.json()["result"]["items"]) == 2 @@ -741,9 +807,9 @@ def test_a_process_that_selected_a_version_before_its_pruning_answers_404( def test_a_process_that_selected_a_pruned_version_serves_it_once_restored( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], managed_v2_roles, - v2_engine_as_role, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> None: """A selection kept while the version was pruned doesn't outlive restoration. @@ -757,28 +823,25 @@ def test_a_process_that_selected_a_pruned_version_serves_it_once_restored( PREVIOUS_VERSION, INSTALLED_VERSION, ): - _publish(publication_engine, version) + _publish(publication_sessions, version) old_query = {"country_id": "us", "policyengine_version": OLD_VERSION} selected_catalogs = SelectedCatalogStore() - runtime_engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - try: - client = _runtime_client( - runtime_engine, - selected_catalogs=selected_catalogs, - response_cache=MetadataResponseCache(), + runtime_sessions = v2_sessions_as_role(managed_v2_roles.runtime) + client = _runtime_client( + runtime_sessions, + selected_catalogs=selected_catalogs, + response_cache=MetadataResponseCache(), + ) + while_pruned = client.get("/v2/parameter-values", params=old_query) + _publish(publication_sessions, OLD_VERSION) + after_restoration = { + path: client.get(path, params=old_query) + for path in ( + "/v2/parameter-values", + "/v2/parameters/children", + "/v2/parameters/search-file", ) - while_pruned = client.get("/v2/parameter-values", params=old_query) - _publish(publication_engine, OLD_VERSION) - after_restoration = { - path: client.get(path, params=old_query) - for path in ( - "/v2/parameter-values", - "/v2/parameters/children", - "/v2/parameters/search-file", - ) - } - finally: - runtime_engine.dispose() + } assert while_pruned.status_code == 404 for path, response in after_restoration.items(): @@ -791,7 +854,7 @@ def test_a_process_that_selected_a_pruned_version_serves_it_once_restored( def test_a_version_kept_by_the_time_its_transaction_runs_is_not_pruned( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch, ) -> None: """Each pruning transaction chooses again, under the publication lock. @@ -802,26 +865,19 @@ def test_a_version_kept_by_the_time_its_transaction_runs_is_not_pruned( the installed one, as that publication sets it. Its transaction then skips it, and nothing reports it as pruned or failed. """ - _publish(publication_engine, OLD_VERSION) - _publish(publication_engine, EARLIER_KEPT_VERSION) - _publish(publication_engine, PREVIOUS_VERSION) - kept_meanwhile = _version_id(publication_engine, US_MODEL, OLD_VERSION) - us_old_before = _prunable_rows(publication_engine, US_MODEL, OLD_VERSION) + _publish(publication_sessions, OLD_VERSION) + _publish(publication_sessions, EARLIER_KEPT_VERSION) + _publish(publication_sessions, PREVIOUS_VERSION) + kept_meanwhile = _version_id(publication_sessions, US_MODEL, OLD_VERSION) + us_old_before = _prunable_rows(publication_sessions, US_MODEL, OLD_VERSION) read_stored_catalog_versions = publication_module.read_stored_catalog_versions reads: list[str] = [] - def read_then_change_the_stored_versions(connection, model_names): - stored_versions = read_stored_catalog_versions(connection, model_names) + def read_then_change_the_stored_versions(session, model_names): + stored_versions = read_stored_catalog_versions(session, model_names) if not reads: - with publication_engine.begin() as other_publisher: - other_publisher.execute( - text( - "UPDATE tax_benefit_model_versions " - "SET catalog_last_published_at = now() + interval '1 day' " - "WHERE id = :version_id" - ), - {"version_id": kept_meanwhile}, - ) + with publication_sessions.begin() as other_publisher_session: + _publish_tomorrow(other_publisher_session, kept_meanwhile) reads.append("read") return stored_versions @@ -830,19 +886,19 @@ def read_then_change_the_stored_versions(connection, model_names): "read_stored_catalog_versions", read_then_change_the_stored_versions, ) - evidence = _publish(publication_engine, INSTALLED_VERSION) + evidence = _publish(publication_sessions, INSTALLED_VERSION) monkeypatch.undo() assert evidence.pruned_catalog_versions == (_fixture_pruned("uk", OLD_VERSION),) assert evidence.catalog_pruning_failures == () - assert _prunable_rows(publication_engine, US_MODEL, OLD_VERSION) == us_old_before - assert _pruned_at(publication_engine, US_MODEL, OLD_VERSION) is None + assert _prunable_rows(publication_sessions, US_MODEL, OLD_VERSION) == us_old_before + assert _pruned_at(publication_sessions, US_MODEL, OLD_VERSION) is None # The rule now chooses the US 5.0.2, which this run's first choice didn't. - assert _pruned_at(publication_engine, US_MODEL, EARLIER_KEPT_VERSION) is None + assert _pruned_at(publication_sessions, US_MODEL, EARLIER_KEPT_VERSION) is None def test_a_non_database_error_rolls_back_that_version_and_publication_succeeds( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch, ) -> None: """Any exception pruning one version is reported, not only a database error. @@ -850,15 +906,15 @@ def test_a_non_database_error_rolls_back_that_version_and_publication_succeeds( It comes after that version's deletes and marker, so they roll back; the other version is still pruned and publication returns its evidence. """ - _publish(publication_engine, OLD_VERSION) - _publish(publication_engine, EARLIER_KEPT_VERSION) - _publish(publication_engine, PREVIOUS_VERSION) - failing_version_id = _version_id(publication_engine, US_MODEL, OLD_VERSION) - us_old_before = _prunable_rows(publication_engine, US_MODEL, OLD_VERSION) + _publish(publication_sessions, OLD_VERSION) + _publish(publication_sessions, EARLIER_KEPT_VERSION) + _publish(publication_sessions, PREVIOUS_VERSION) + failing_version_id = _version_id(publication_sessions, US_MODEL, OLD_VERSION) + us_old_before = _prunable_rows(publication_sessions, US_MODEL, OLD_VERSION) prune_catalog_version = publication_module.prune_catalog_version - def prune_then_raise_for_one_version(connection, version_id): - deleted = prune_catalog_version(connection, version_id) + def prune_then_raise_for_one_version(session, version_id): + deleted = prune_catalog_version(session, version_id) if version_id == failing_version_id: missing_name = "gov.example.rate" raise KeyError(missing_name) @@ -867,7 +923,7 @@ def prune_then_raise_for_one_version(connection, version_id): monkeypatch.setattr( publication_module, "prune_catalog_version", prune_then_raise_for_one_version ) - evidence = _publish(publication_engine, INSTALLED_VERSION) + evidence = _publish(publication_sessions, INSTALLED_VERSION) monkeypatch.undo() assert evidence.catalog_pruning_failures == ( @@ -882,12 +938,12 @@ def prune_then_raise_for_one_version(connection, version_id): ), ) assert evidence.pruned_catalog_versions == (_fixture_pruned("uk", OLD_VERSION),) - assert _prunable_rows(publication_engine, US_MODEL, OLD_VERSION) == us_old_before - assert _pruned_at(publication_engine, US_MODEL, OLD_VERSION) is None + assert _prunable_rows(publication_sessions, US_MODEL, OLD_VERSION) == us_old_before + assert _pruned_at(publication_sessions, US_MODEL, OLD_VERSION) is None def test_a_run_prunes_at_most_two_versions_and_the_next_run_the_rest( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch, ) -> None: """The first run after many releases prunes the two oldest versions only. @@ -902,12 +958,12 @@ def test_a_run_prunes_at_most_two_versions_and_the_next_run_the_rest( lambda stored_versions, installed_versions: (), ) for version in ("5.0.1", "5.0.2", "5.0.3", "5.0.4"): - _publish(publication_engine, version) + _publish(publication_sessions, version) monkeypatch.undo() - first = _publish(publication_engine, "5.0.5") - second = _publish(publication_engine, "5.0.5") - third = _publish(publication_engine, "5.0.5") + first = _publish(publication_sessions, "5.0.5") + second = _publish(publication_sessions, "5.0.5") + third = _publish(publication_sessions, "5.0.5") assert first.pruned_catalog_versions == ( _fixture_pruned("uk", "5.0.1"), @@ -922,30 +978,32 @@ def test_a_run_prunes_at_most_two_versions_and_the_next_run_the_rest( assert third.pruned_catalog_versions == () for model_name in MODEL_NAMES: for kept_version in ("5.0.3", "5.0.4"): - assert _pruned_at(publication_engine, model_name, kept_version) is None + assert _pruned_at(publication_sessions, model_name, kept_version) is None def test_a_version_without_current_law_rows_is_marked_pruned_with_zero_counts( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: """Pruning a version that holds none of the rows it deletes still marks it.""" - _publish(publication_engine, OLD_VERSION) - us_old_id = _version_id(publication_engine, US_MODEL, OLD_VERSION) - with publication_engine.begin() as connection: - for statement in ( - "DELETE FROM parameter_values WHERE policy_id IS NULL " - "AND dynamic_id IS NULL AND parameter_id IN (SELECT id FROM parameters " - "WHERE tax_benefit_model_version_id = :version_id)", - "DELETE FROM parameter_tree_children " - "WHERE tax_benefit_model_version_id = :version_id", - "DELETE FROM parameter_search_files " - "WHERE tax_benefit_model_version_id = :version_id", - ): - connection.execute(text(statement), {"version_id": us_old_id}) - _publish(publication_engine, EARLIER_KEPT_VERSION) - _publish(publication_engine, PREVIOUS_VERSION) - - evidence = _publish(publication_engine, INSTALLED_VERSION) + _publish(publication_sessions, OLD_VERSION) + us_old_id = _version_id(publication_sessions, US_MODEL, OLD_VERSION) + with publication_sessions.begin() as session: + session.execute( + sa.delete(ParameterValue).where( + col(ParameterValue.policy_id).is_(None), + col(ParameterValue.dynamic_id).is_(None), + col(ParameterValue.parameter_id).in_( + sa.select(col(Parameter.id)).where( + col(Parameter.tax_benefit_model_version_id) == us_old_id + ) + ), + ) + ) + _delete_tree_and_search_file(session, us_old_id) + _publish(publication_sessions, EARLIER_KEPT_VERSION) + _publish(publication_sessions, PREVIOUS_VERSION) + + evidence = _publish(publication_sessions, INSTALLED_VERSION) assert evidence.pruned_catalog_versions == ( _fixture_pruned("uk", OLD_VERSION), @@ -958,22 +1016,23 @@ def test_a_version_without_current_law_rows_is_marked_pruned_with_zero_counts( ), ) assert evidence.catalog_pruning_failures == () - assert _pruned_at(publication_engine, US_MODEL, OLD_VERSION) is not None + assert _pruned_at(publication_sessions, US_MODEL, OLD_VERSION) is not None -def _last_published_at(engine: Engine, model_name: str, version: str) -> datetime: - with engine.connect() as connection: - return connection.execute( - text( - "SELECT catalog_last_published_at FROM tax_benefit_model_versions " - "WHERE id = :version_id" - ), - {"version_id": _version_id(engine, model_name, version)}, - ).scalar_one() +def _last_published_at( + sessions: sessionmaker[Session], model_name: str, version: str +) -> datetime: + published_at: datetime = _version_column( + sessions, + col(TaxBenefitModelVersion.catalog_last_published_at), + model_name, + version, + ) + return published_at def test_every_publication_records_when_it_published_the_version( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: """A new version, a republish with no change and a restoring one all record it. @@ -981,30 +1040,30 @@ def test_every_publication_records_when_it_published_the_version( publishes, in its own transaction, and no other version's. Pruning leaves it as it was. """ - _publish(publication_engine, OLD_VERSION) + _publish(publication_sessions, OLD_VERSION) first = { - model_name: _last_published_at(publication_engine, model_name, OLD_VERSION) + model_name: _last_published_at(publication_sessions, model_name, OLD_VERSION) for model_name in MODEL_NAMES } - _publish(publication_engine, OLD_VERSION) + _publish(publication_sessions, OLD_VERSION) unchanged_republish = { - model_name: _last_published_at(publication_engine, model_name, OLD_VERSION) + model_name: _last_published_at(publication_sessions, model_name, OLD_VERSION) for model_name in MODEL_NAMES } for version in (EARLIER_KEPT_VERSION, PREVIOUS_VERSION, INSTALLED_VERSION): - _publish(publication_engine, version) + _publish(publication_sessions, version) while_pruned = { - model_name: _last_published_at(publication_engine, model_name, OLD_VERSION) + model_name: _last_published_at(publication_sessions, model_name, OLD_VERSION) for model_name in MODEL_NAMES } installed_before = { model_name: _last_published_at( - publication_engine, model_name, INSTALLED_VERSION + publication_sessions, model_name, INSTALLED_VERSION ) for model_name in MODEL_NAMES } - restoring = _publish(publication_engine, OLD_VERSION) + restoring = _publish(publication_sessions, OLD_VERSION) assert { (country_id, version) @@ -1013,14 +1072,14 @@ def test_every_publication_records_when_it_published_the_version( for model_name in MODEL_NAMES: assert first[model_name] is not None assert unchanged_republish[model_name] > first[model_name] - assert _pruned_at(publication_engine, model_name, OLD_VERSION) is None + assert _pruned_at(publication_sessions, model_name, OLD_VERSION) is None assert while_pruned[model_name] == unchanged_republish[model_name] assert ( - _last_published_at(publication_engine, model_name, OLD_VERSION) + _last_published_at(publication_sessions, model_name, OLD_VERSION) > while_pruned[model_name] ) assert ( - _last_published_at(publication_engine, model_name, INSTALLED_VERSION) + _last_published_at(publication_sessions, model_name, INSTALLED_VERSION) == installed_before[model_name] ) @@ -1029,25 +1088,30 @@ def test_every_publication_records_when_it_published_the_version( LOCK_WAIT_LIMIT_SECONDS = 30 -def _wait_until_blocked_on_an_advisory_lock_or_done( - engine: Engine, pruning: Future +def _wait_until_blocked_on_a_lock_or_done( + sessions: sessionmaker[Session], pruning: Future, pruning_backends: list[int] ) -> None: - """Return once ``pruning`` waits for an advisory lock, or has finished. + """Return once ``pruning`` waits for a lock, or has finished. - The disposable database's only advisory lock is the publication lock, so - an advisory lock that isn't granted is the pruning thread's. The sleep only - paces the polling of ``pg_locks``; the state read decides when to return. + ``pruning_backends`` receives the server process ID of the pruning's + connection just before it asks for the publication lock, and + ``pg_blocking_pids`` names the processes holding a lock that one waits + for. The sleep only paces the polling; the state read decides when to + return. """ deadline = time.monotonic() + LOCK_WAIT_LIMIT_SECONDS - with engine.connect() as observer: + with sessions() as observer_session: while not pruning.done(): - waiting = observer.execute( - text( - "SELECT count(*) FROM pg_locks " - "WHERE locktype = 'advisory' AND NOT granted" - ) - ).scalar_one() - if waiting: + if ( + pruning_backends + and observer_session.execute( + sa.select( + sa.func.cardinality( + sa.func.pg_blocking_pids(pruning_backends[0]) + ) + ) + ).scalar_one() + ): return if time.monotonic() > deadline: pytest.fail("the pruning neither waited for the lock nor finished") @@ -1055,7 +1119,7 @@ def _wait_until_blocked_on_an_advisory_lock_or_done( def test_a_pruning_transaction_chooses_again_after_waiting_for_the_lock( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch, ) -> None: """A version another publisher keeps while pruning waits for the lock stays. @@ -1077,42 +1141,48 @@ def test_a_pruning_transaction_chooses_again_after_waiting_for_the_lock( PREVIOUS_VERSION, INSTALLED_VERSION, ): - _publish(publication_engine, version) + _publish(publication_sessions, version) monkeypatch.undo() - with publication_engine.connect() as connection: + with publication_sessions() as session: us_old = next( stored - for stored in read_stored_catalog_versions(connection, [US_MODEL]) + for stored in read_stored_catalog_versions(session, [US_MODEL]) if stored.version == OLD_VERSION ) - us_old_before = _prunable_rows(publication_engine, US_MODEL, OLD_VERSION) + us_old_before = _prunable_rows(publication_sessions, US_MODEL, OLD_VERSION) + acquire_publication_lock = publication_module._acquire_publication_lock + pruning_backends: list[int] = [] + + def record_backend_then_acquire_lock(session): + pruning_backends.append( + session.execute(sa.select(sa.func.pg_backend_pid())).scalar_one() + ) + acquire_publication_lock(session) + + monkeypatch.setattr( + publication_module, + "_acquire_publication_lock", + record_backend_then_acquire_lock, + ) with ThreadPoolExecutor(max_workers=1) as executor: - with publication_engine.connect() as other_publisher, other_publisher.begin(): - other_publisher.execute( - text("SELECT pg_advisory_xact_lock(:lock_key)"), - {"lock_key": publication_module.PUBLICATION_ADVISORY_LOCK_KEY}, - ) + with publication_sessions.begin() as other_publisher_session: + acquire_publication_lock(other_publisher_session) pruning = executor.submit( publication_module._prune_if_still_chosen, - publication_engine, + publication_sessions, us_old, INSTALLED_VERSION, ) - _wait_until_blocked_on_an_advisory_lock_or_done(publication_engine, pruning) - other_publisher.execute( - text( - "UPDATE tax_benefit_model_versions " - "SET catalog_last_published_at = now() + interval '1 day' " - "WHERE id = :version_id" - ), - {"version_id": us_old.id}, + _wait_until_blocked_on_a_lock_or_done( + publication_sessions, pruning, pruning_backends ) + _publish_tomorrow(other_publisher_session, us_old.id) deleted = pruning.result(timeout=LOCK_WAIT_LIMIT_SECONDS) assert deleted is None - assert _pruned_at(publication_engine, US_MODEL, OLD_VERSION) is None - assert _prunable_rows(publication_engine, US_MODEL, OLD_VERSION) == us_old_before + assert _pruned_at(publication_sessions, US_MODEL, OLD_VERSION) is None + assert _prunable_rows(publication_sessions, US_MODEL, OLD_VERSION) == us_old_before class _InjectedPublicationError(RuntimeError): @@ -1120,7 +1190,7 @@ class _InjectedPublicationError(RuntimeError): def test_a_failed_republish_of_a_pruned_version_leaves_it_pruned( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: """Restoring is part of the publication transaction, and rolls back with it. @@ -1134,34 +1204,35 @@ def test_a_failed_republish_of_a_pruned_version_leaves_it_pruned( PREVIOUS_VERSION, INSTALLED_VERSION, ): - _publish(publication_engine, version) + _publish(publication_sessions, version) before = { model_name: ( - _prunable_rows(publication_engine, model_name, OLD_VERSION), - _pruned_at(publication_engine, model_name, OLD_VERSION), - _last_published_at(publication_engine, model_name, OLD_VERSION), + _prunable_rows(publication_sessions, model_name, OLD_VERSION), + _pruned_at(publication_sessions, model_name, OLD_VERSION), + _last_published_at(publication_sessions, model_name, OLD_VERSION), ) for model_name in MODEL_NAMES } restored_inside_the_transaction: list[int] = [] - def fail_after_restoring(stage: str, connection) -> None: + def fail_after_restoring(stage: str, session) -> None: if stage != "after_reconciliation": return restored_inside_the_transaction.append( - connection.execute( - text( - "SELECT count(*) FROM tax_benefit_model_versions " - "WHERE version = :version AND catalog_values_pruned_at IS NULL" - ), - {"version": OLD_VERSION}, + session.execute( + sa.select(sa.func.count()) + .select_from(TaxBenefitModelVersion) + .where( + col(TaxBenefitModelVersion.version) == OLD_VERSION, + col(TaxBenefitModelVersion.catalog_values_pruned_at).is_(None), + ) ).scalar_one() ) raise _InjectedPublicationError(stage) with pytest.raises(_InjectedPublicationError): publish_catalog( - publication_engine, + publication_sessions, normalized_catalog(policyengine_version=OLD_VERSION), checkpoint=fail_after_restoring, ) @@ -1176,17 +1247,18 @@ def fail_after_restoring(stage: str, connection) -> None: } assert pruned_at is not None assert ( - _prunable_rows(publication_engine, model_name, OLD_VERSION) == prunable_rows + _prunable_rows(publication_sessions, model_name, OLD_VERSION) + == prunable_rows ) - assert _pruned_at(publication_engine, model_name, OLD_VERSION) == pruned_at + assert _pruned_at(publication_sessions, model_name, OLD_VERSION) == pruned_at assert ( - _last_published_at(publication_engine, model_name, OLD_VERSION) + _last_published_at(publication_sessions, model_name, OLD_VERSION) == last_published_at ) def test_restoring_a_version_stored_before_catalog_format_2_writes_values_only( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: """A version stored before catalog format 2 gets back only its values. @@ -1195,41 +1267,39 @@ def test_restoring_a_version_stored_before_catalog_format_2_writes_values_only( writes neither for it. Restoring it writes back its current-law values alone, equal to those it had. """ - _publish(publication_engine, OLD_VERSION) - with publication_engine.begin() as connection: + _publish(publication_sessions, OLD_VERSION) + with publication_sessions.begin() as session: for model_name in MODEL_NAMES: - version_id = _version_id(publication_engine, model_name, OLD_VERSION) - for statement in ( - "UPDATE tax_benefit_model_versions SET catalog_format = NULL, " - "entities = NULL, basic_inputs = NULL WHERE id = :version_id", - "DELETE FROM parameter_tree_children " - "WHERE tax_benefit_model_version_id = :version_id", - "DELETE FROM parameter_search_files " - "WHERE tax_benefit_model_version_id = :version_id", - ): - connection.execute(text(statement), {"version_id": version_id}) + version_id = _version_id(publication_sessions, model_name, OLD_VERSION) + # The JSON columns get SQL NULL (sa.null()), not JSON's null. + session.execute( + sa.update(TaxBenefitModelVersion) + .where(col(TaxBenefitModelVersion.id) == version_id) + .values(catalog_format=None, entities=sa.null(), basic_inputs=sa.null()) + ) + _delete_tree_and_search_file(session, version_id) before = { - model_name: _prunable_rows(publication_engine, model_name, OLD_VERSION) + model_name: _prunable_rows(publication_sessions, model_name, OLD_VERSION) for model_name in MODEL_NAMES } for version in (EARLIER_KEPT_VERSION, PREVIOUS_VERSION, INSTALLED_VERSION): - _publish(publication_engine, version) + _publish(publication_sessions, version) assert all( - _pruned_at(publication_engine, model_name, OLD_VERSION) is not None + _pruned_at(publication_sessions, model_name, OLD_VERSION) is not None for model_name in MODEL_NAMES ) - restoring = _publish(publication_engine, OLD_VERSION) + restoring = _publish(publication_sessions, OLD_VERSION) for model_name in MODEL_NAMES: assert before[model_name]["parameter_values"] assert before[model_name]["tree_rows"] == [] assert before[model_name]["search_files"] == [] assert ( - _prunable_rows(publication_engine, model_name, OLD_VERSION) + _prunable_rows(publication_sessions, model_name, OLD_VERSION) == before[model_name] ) - assert _pruned_at(publication_engine, model_name, OLD_VERSION) is None + assert _pruned_at(publication_sessions, model_name, OLD_VERSION) is None assert { (country_id, version) for country_id, version, _values in restoring.restored_catalog_versions diff --git a/tests/integration/test_v2_catalog_publication_time_periods.py b/tests/integration/test_v2_catalog_publication_time_periods.py index 8135fb2f5..924135d22 100644 --- a/tests/integration/test_v2_catalog_publication_time_periods.py +++ b/tests/integration/test_v2_catalog_publication_time_periods.py @@ -1,75 +1,49 @@ """Disposable-Postgres coverage: republication and a stored version's time periods. A stored catalog version takes the staged time periods (metadata_time_periods), -the years the Public API offers for it, which come from +the years API v1 offers for it, which come from policyengine_api.economy_years. Every other column and table must still match. """ from __future__ import annotations -import os from dataclasses import replace -from pathlib import Path +from typing import TYPE_CHECKING import pytest -from alembic import command -from alembic.config import Config -from sqlalchemy import create_engine, text -from sqlalchemy.engine import Engine, make_url -from sqlalchemy.pool import NullPool +from sqlalchemy import select +from sqlmodel import col from policyengine_api.data.v2.catalog import publication as publication_module from policyengine_api.data.v2.catalog.publication import ( CatalogPublicationError, publish_catalog, ) -from policyengine_api.data.v2.settings import V2_MIGRATION_DATABASE_URL +from policyengine_api.data.v2.models import TaxBenefitModel, TaxBenefitModelVersion from policyengine_api.economy_years import UK_ECONOMY_YEARS, US_ECONOMY_YEARS from tests.fixtures.v2_catalog import normalized_catalog +from tests.integration.catalog_publication_support import ( + emptied_catalog, + stored_identifiers, +) + +if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session -REPO = Path(__file__).parents[2] -DISPOSABLE_DATABASE = "policyengine_v2_alembic_test" # The US years catalog versions were stored with before 2022 and 2023 were # dropped: 2035 to 2022, newest first. PREVIOUS_US_YEARS = tuple(range(2035, 2021, -1)) -CATALOG_TABLES = ( - "tax_benefit_models", - "tax_benefit_model_versions", - "variables", - "parameter_nodes", - "parameters", - "parameter_values", - "datasets", - "regions", -) - - -def _disposable_url() -> str: - database_url = os.environ.get(V2_MIGRATION_DATABASE_URL, "") - if not database_url: - pytest.skip(f"{V2_MIGRATION_DATABASE_URL} is not set") - url = make_url(database_url) - if url.database != DISPOSABLE_DATABASE or url.host not in { - "localhost", - "127.0.0.1", - "::1", - "postgres", - }: - pytest.fail("catalog publication tests require disposable local Postgres") - return database_url @pytest.fixture -def publication_engine() -> Engine: - database_url = _disposable_url() - command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(database_url, poolclass=NullPool) - with engine.begin() as connection: - connection.execute(text("TRUNCATE tax_benefit_models CASCADE")) - yield engine - with engine.begin() as connection: - connection.execute(text("TRUNCATE tax_benefit_models CASCADE")) - engine.dispose() +def publication_sessions( + v2_owner_sessions: sessionmaker[Session], +) -> Iterator[sessionmaker[Session]]: + with emptied_catalog(v2_owner_sessions) as sessions: + yield sessions def _with_us_years(catalog, years: tuple[int, ...]): @@ -81,42 +55,31 @@ def _with_us_years(catalog, years: tuple[int, ...]): ) -def _stored_years(engine: Engine) -> dict[str, list[int]]: - with engine.connect() as connection: - rows = connection.execute( - text( - "SELECT model.name, version.metadata_time_periods " - "FROM tax_benefit_model_versions AS version " - "JOIN tax_benefit_models AS model ON model.id = version.model_id" +def _stored_years(sessions: sessionmaker[Session]) -> dict[str, list[int]]: + with sessions() as session: + rows = session.execute( + select( + col(TaxBenefitModel.name), + col(TaxBenefitModelVersion.metadata_time_periods), + ).join( + TaxBenefitModel, + col(TaxBenefitModel.id) == col(TaxBenefitModelVersion.model_id), ) ).all() return {model_name: list(years) for model_name, years in rows} -def _identifiers(engine: Engine) -> dict[str, tuple[str, ...]]: - with engine.connect() as connection: - return { - table_name: tuple( - str(value) - for value in connection.execute( - text(f"SELECT id FROM {table_name} ORDER BY id") - ).scalars() - ) - for table_name in CATALOG_TABLES - } - - def test_stored_version_takes_the_staged_time_periods_and_logs_them( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch, ) -> None: catalog = normalized_catalog() - publish_catalog(publication_engine, _with_us_years(catalog, PREVIOUS_US_YEARS)) - assert _stored_years(publication_engine) == { + publish_catalog(publication_sessions, _with_us_years(catalog, PREVIOUS_US_YEARS)) + assert _stored_years(publication_sessions) == { "policyengine-us": list(PREVIOUS_US_YEARS), "policyengine-uk": list(UK_ECONOMY_YEARS), } - before_ids = _identifiers(publication_engine) + before_ids = stored_identifiers(publication_sessions) # Alembic's logging configuration disables existing loggers, so the # warnings are recorded where they are emitted. warnings: list[tuple[str, dict]] = [] @@ -126,13 +89,13 @@ def test_stored_version_takes_the_staged_time_periods_and_logs_them( lambda message, *args, **kwargs: warnings.append((message % args, kwargs)), ) - evidence = publish_catalog(publication_engine, catalog) + evidence = publish_catalog(publication_sessions, catalog) - assert _stored_years(publication_engine) == { + assert _stored_years(publication_sessions) == { "policyengine-us": list(US_ECONOMY_YEARS), "policyengine-uk": list(UK_ECONOMY_YEARS), } - assert _identifiers(publication_engine) == before_ids + assert stored_identifiers(publication_sessions) == before_ids version = catalog.policyengine_version assert evidence.time_period_updates == ( ("us", version, PREVIOUS_US_YEARS, US_ECONOMY_YEARS), @@ -164,16 +127,16 @@ def test_stored_version_takes_the_staged_time_periods_and_logs_them( ] # Publishing the same years again changes and reports nothing. - again = publish_catalog(publication_engine, catalog) + again = publish_catalog(publication_sessions, catalog) assert again.time_period_updates == () assert again.as_dict()["updated_time_periods"] == [] def test_stored_version_with_changed_time_periods_still_fails_on_other_tables( - publication_engine: Engine, + publication_sessions: sessionmaker[Session], ) -> None: catalog = normalized_catalog() - publish_catalog(publication_engine, _with_us_years(catalog, PREVIOUS_US_YEARS)) + publish_catalog(publication_sessions, _with_us_years(catalog, PREVIOUS_US_YEARS)) us = catalog.country("us") changed = replace( catalog, @@ -188,8 +151,8 @@ def test_stored_version_with_changed_time_periods_still_fails_on_other_tables( match=r"^the stored us catalog version 5\.0\.4 differs from the staged " r"catalog in its variables$", ): - publish_catalog(publication_engine, changed) + publish_catalog(publication_sessions, changed) - assert _stored_years(publication_engine)["policyengine-us"] == list( + assert _stored_years(publication_sessions)["policyengine-us"] == list( PREVIOUS_US_YEARS ) diff --git a/tests/integration/test_v2_catalog_spm_availability.py b/tests/integration/test_v2_catalog_spm_availability.py index 672cd8147..826c32a01 100644 --- a/tests/integration/test_v2_catalog_spm_availability.py +++ b/tests/integration/test_v2_catalog_spm_availability.py @@ -8,19 +8,15 @@ from __future__ import annotations from types import SimpleNamespace +from typing import TYPE_CHECKING from uuid import uuid4 import sqlalchemy as sa from alembic import command from alembic.config import Config -from sqlalchemy import create_engine -from sqlalchemy.pool import NullPool +from sqlmodel import col from policyengine_api.constants import REPO -from policyengine_api.data.v2.catalog.publication_tables import ( - MODEL_VERSIONS, - MODELS, -) from policyengine_api.data.v2.catalog.publication_types import ( CatalogPublicationError, SPMAvailabilityRecording, @@ -29,68 +25,83 @@ record_published_spm_availability, record_spm_availability, ) +from policyengine_api.data.v2.models import TaxBenefitModel, TaxBenefitModelVersion from policyengine_api.data.v2.privileges import CATALOG_WRITER_ROLE +from tests.integration.simulation_rows import add_row + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable + from uuid import UUID + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session AVAILABLE = {"available": True, "settings_schema": {}, "defaults": {"scenario": "x"}} UNAVAILABLE = {"available": False} +def _delete_models(sessions: sessionmaker[Session], model_ids: Iterable[UUID]) -> None: + """Delete the test's models and their versions.""" + with sessions.begin() as session: + for model_id in model_ids: + session.execute( + sa.delete(TaxBenefitModelVersion).where( + col(TaxBenefitModelVersion.model_id) == model_id + ) + ) + session.execute( + sa.delete(TaxBenefitModel).where(col(TaxBenefitModel.id) == model_id) + ) + + def test_availability_fills_only_the_named_version_and_only_once( - disposable_v2_database_url: str, managed_v2_roles, v2_engine_as_role + v2_owner_sessions: sessionmaker[Session], + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> None: command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - writer_engine = v2_engine_as_role(CATALOG_WRITER_ROLE, poolclass=NullPool) + writer_sessions = v2_sessions_as_role(CATALOG_WRITER_ROLE) model_id, version_id, other_version_id = uuid4(), uuid4(), uuid4() model_name = f"policyengine-us-{model_id.hex[:8]}" try: - with engine.begin() as connection: - connection.execute(sa.insert(MODELS).values(id=model_id, name=model_name)) - connection.execute( - sa.insert(MODEL_VERSIONS), - [ - { - "id": identifier, - "model_id": model_id, - "version": version, - "current_law_id": 2, - "metadata_time_periods": [2026], - } - for identifier, version in ( - (version_id, "1.450.0"), - (other_version_id, "1.449.0"), - ) - ], - ) - with writer_engine.begin() as connection: + with v2_owner_sessions.begin() as session: + add_row(session, TaxBenefitModel, id=model_id, name=model_name) + for identifier, version in ( + (version_id, "1.450.0"), + (other_version_id, "1.449.0"), + ): + add_row( + session, + TaxBenefitModelVersion, + id=identifier, + model_id=model_id, + version=version, + current_law_id=2, + metadata_time_periods=[2026], + ) + with writer_sessions.begin() as session: first = record_spm_availability( - connection, + session, model_name=model_name, version="1.450.0", availability=AVAILABLE, ) again = record_spm_availability( - connection, + session, model_name=model_name, version="1.450.0", availability=UNAVAILABLE, ) - with engine.connect() as connection: + with v2_owner_sessions() as session: stored = dict( - connection.execute( + session.execute( sa.select( - MODEL_VERSIONS.c.id, MODEL_VERSIONS.c.spm_availability - ).where(MODEL_VERSIONS.c.model_id == model_id) + col(TaxBenefitModelVersion.id), + col(TaxBenefitModelVersion.spm_availability), + ).where(col(TaxBenefitModelVersion.model_id) == model_id) ).all() ) finally: - with engine.begin() as connection: - connection.execute( - sa.delete(MODEL_VERSIONS).where(MODEL_VERSIONS.c.model_id == model_id) - ) - connection.execute(sa.delete(MODELS).where(MODELS.c.id == model_id)) - writer_engine.dispose() - engine.dispose() + _delete_models(v2_owner_sessions, [model_id]) assert first assert not again @@ -103,11 +114,11 @@ def _unreadable_versions(_url: str) -> object: def test_publication_lists_only_versions_still_unrecorded( - disposable_v2_database_url: str, managed_v2_roles, v2_engine_as_role + v2_owner_sessions: sessionmaker[Session], + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> None: command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - writer_engine = v2_engine_as_role(CATALOG_WRITER_ROLE, poolclass=NullPool) + writer_sessions = v2_sessions_as_role(CATALOG_WRITER_ROLE) model_ids = {"us": uuid4(), "uk": uuid4()} model_names = { country_id: f"policyengine-{country_id}-{model_id.hex[:8]}" @@ -125,10 +136,10 @@ def test_publication_lists_only_versions_still_unrecorded( ], ) try: - with engine.begin() as connection: + with v2_owner_sessions.begin() as session: for country_id, model_id in model_ids.items(): - connection.execute( - sa.insert(MODELS).values(id=model_id, name=model_names[country_id]) + add_row( + session, TaxBenefitModel, id=model_id, name=model_names[country_id] ) # An earlier publication recorded the US version. The UK one # leaves the column out, as publication's insert does, so it @@ -136,40 +147,31 @@ def test_publication_lists_only_versions_still_unrecorded( recorded_earlier = ( {"spm_availability": AVAILABLE} if country_id == "us" else {} ) - connection.execute( - sa.insert(MODEL_VERSIONS).values( - id=uuid4(), - model_id=model_id, - version="1.450.0", - current_law_id=2, - metadata_time_periods=[2026], - **recorded_earlier, - ) + add_row( + session, + TaxBenefitModelVersion, + id=uuid4(), + model_id=model_id, + version="1.450.0", + current_law_id=2, + metadata_time_periods=[2026], + **recorded_earlier, ) unreadable = record_published_spm_availability( - writer_engine, + writer_sessions, catalog, {"SIMULATION_ENTRYPOINT_URL": "https://simulation.example"}, fetch_versions=_unreadable_versions, ) # The simulation service serves no PolicyEngine.py version yet. not_served = record_published_spm_availability( - writer_engine, + writer_sessions, catalog, {"SIMULATION_ENTRYPOINT_URL": "https://simulation.example"}, fetch_versions=lambda _url: {"policyengine": {}}, ) finally: - with engine.begin() as connection: - for model_id in model_ids.values(): - connection.execute( - sa.delete(MODEL_VERSIONS).where( - MODEL_VERSIONS.c.model_id == model_id - ) - ) - connection.execute(sa.delete(MODELS).where(MODELS.c.id == model_id)) - writer_engine.dispose() - engine.dispose() + _delete_models(v2_owner_sessions, model_ids.values()) assert unreadable == SPMAvailabilityRecording( not_recorded=(("uk", "1.450.0"),), diff --git a/tests/integration/test_v2_catalog_statistics.py b/tests/integration/test_v2_catalog_statistics.py index cb60d91bd..feff77bdc 100644 --- a/tests/integration/test_v2_catalog_statistics.py +++ b/tests/integration/test_v2_catalog_statistics.py @@ -14,22 +14,20 @@ from __future__ import annotations -import os -from pathlib import Path from typing import TYPE_CHECKING from uuid import uuid4 import pytest -from alembic import command -from alembic.config import Config -from sqlalchemy import create_engine, event, text -from sqlalchemy.engine import make_url -from sqlalchemy.pool import NullPool +from sqlalchemy import cast, func, select +from sqlalchemy.dialects.postgresql import REGCLASS +from policyengine_api.data.v2.catalog import publication as publication_module +from policyengine_api.data.v2.catalog import publication_statistics from policyengine_api.data.v2.catalog.publication import publish_catalog from policyengine_api.data.v2.catalog.publication_types import ( CatalogPublicationError, ) +from policyengine_api.data.v2.models import TaxBenefitModelVersion from policyengine_api.data.v2.privilege_reconciliation import ( apply_declared_privileges, ) @@ -37,17 +35,17 @@ CATALOG_WRITER_ROLE, declared_privileges, ) -from policyengine_api.data.v2.settings import V2_MIGRATION_DATABASE_URL +from tests.fixtures.database_sessions import create_role, drop_role from tests.fixtures.v2_catalog import normalized_catalog +from tests.integration.catalog_publication_support import emptied_catalog if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator from datetime import datetime - from sqlalchemy.engine import Engine + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session -REPO = Path(__file__).parents[2] -DISPOSABLE_DATABASE = "policyengine_v2_alembic_test" UNDEFINED_TABLE_FAILURE = "psycopg.errors.UndefinedTable (SQLSTATE 42P01)" ANALYZED_TABLES = ( "datasets", @@ -60,70 +58,65 @@ ) -def _disposable_url() -> str: - database_url = os.environ.get(V2_MIGRATION_DATABASE_URL, "") - if not database_url: - pytest.skip(f"{V2_MIGRATION_DATABASE_URL} is not set") - url = make_url(database_url) - if url.database != DISPOSABLE_DATABASE or url.host not in { - "localhost", - "127.0.0.1", - "::1", - "postgres", - }: - pytest.fail("catalog publication tests require disposable local Postgres") - return database_url - - @pytest.fixture -def superuser_engine() -> Iterator[Engine]: +def superuser_sessions( + v2_owner_sessions: sessionmaker[Session], +) -> Iterator[sessionmaker[Session]]: """Upgrade the disposable database and empty its catalog before and after.""" - database_url = _disposable_url() - command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(database_url, poolclass=NullPool) - with engine.begin() as connection: - connection.execute(text("TRUNCATE tax_benefit_models CASCADE")) - try: - yield engine - finally: - with engine.begin() as connection: - connection.execute(text("TRUNCATE tax_benefit_models CASCADE")) - engine.dispose() + with emptied_catalog(v2_owner_sessions) as sessions: + yield sessions @pytest.fixture -def writer_engine(superuser_engine, v2_engine_as_role) -> Iterator[Engine]: - engine = v2_engine_as_role(CATALOG_WRITER_ROLE, poolclass=NullPool) - try: - yield engine - finally: - engine.dispose() +def writer_sessions( + superuser_sessions: sessionmaker[Session], + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], +) -> sessionmaker[Session]: + return v2_sessions_as_role(CATALOG_WRITER_ROLE) -def _database_time(engine: Engine) -> datetime: - with engine.connect() as connection: - return connection.execute(text("SELECT clock_timestamp()")).scalar_one() +def _database_time(sessions: sessionmaker[Session]) -> datetime: + with sessions() as session: + moment: datetime = session.execute(select(func.clock_timestamp())).scalar_one() + return moment -def _last_manual_analyze(engine: Engine) -> dict[str, datetime | None]: - with engine.connect() as connection: - rows = connection.execute( - text( - "SELECT relname, last_analyze FROM pg_stat_user_tables " - "WHERE schemaname = 'public' AND relname = ANY(:tables)" - ), - {"tables": list(ANALYZED_TABLES)}, - ) - return {row.relname: row.last_analyze for row in rows} +def _last_manual_analyze( + sessions: sessionmaker[Session], +) -> dict[str, datetime | None]: + """Return when each catalog table was last analyzed by an ``ANALYZE``. + + ``pg_stat_get_last_analyze_time`` is what ``pg_stat_user_tables`` reports + as ``last_analyze``. + """ + with sessions() as session: + return { + table: session.execute( + select( + func.pg_stat_get_last_analyze_time( + cast(f"public.{table}", REGCLASS) + ) + ) + ).scalar_one() + for table in ANALYZED_TABLES + } + + +def _stored_version_count(sessions: sessionmaker[Session]) -> int: + with sessions() as session: + count: int = session.execute( + select(func.count()).select_from(TaxBenefitModelVersion) + ).scalar_one() + return count def test_publishing_a_new_version_as_the_catalog_writer_analyzes_the_catalog( - superuser_engine, writer_engine + superuser_sessions: sessionmaker[Session], writer_sessions: sessionmaker[Session] ) -> None: - started = _database_time(superuser_engine) + started = _database_time(superuser_sessions) - evidence = publish_catalog(writer_engine, normalized_catalog()) - last_analyze = _last_manual_analyze(superuser_engine) + evidence = publish_catalog(writer_sessions, normalized_catalog()) + last_analyze = _last_manual_analyze(superuser_sessions) assert evidence.catalog_tables_analyzed == ANALYZED_TABLES assert evidence.as_dict()["catalog_tables_analyzed"] == list(ANALYZED_TABLES) @@ -135,15 +128,15 @@ def test_publishing_a_new_version_as_the_catalog_writer_analyzes_the_catalog( def test_republishing_an_unchanged_catalog_analyzes_it_again( - superuser_engine, writer_engine + superuser_sessions: sessionmaker[Session], writer_sessions: sessionmaker[Session] ) -> None: """Every run analyzes, so a run after a failed ``ANALYZE`` repeats it.""" catalog = normalized_catalog() - publish_catalog(writer_engine, catalog) - second_started = _database_time(superuser_engine) + publish_catalog(writer_sessions, catalog) + second_started = _database_time(superuser_sessions) - second = publish_catalog(writer_engine, catalog) - last_analyze = _last_manual_analyze(superuser_engine) + second = publish_catalog(writer_sessions, catalog) + last_analyze = _last_manual_analyze(superuser_sessions) assert second.catalog_tables_analyzed == ANALYZED_TABLES assert second.catalog_statistics_failure is None @@ -154,30 +147,33 @@ def test_republishing_an_unchanged_catalog_analyzes_it_again( def test_a_failed_analyze_is_recorded_and_the_publication_kept( - superuser_engine, writer_engine + superuser_sessions: sessionmaker[Session], + writer_sessions: sessionmaker[Session], + monkeypatch: pytest.MonkeyPatch, ) -> None: """The database refuses the ``ANALYZE``, and SQLAlchemy wraps its error. The evidence names the driver's error and SQLSTATE, as a failed pruning's does, not SQLAlchemy's wrapper, which is the same for any database error. + The ``ANALYZE`` names a table that doesn't exist, once publication has + checked the privileges on the real ones. """ + analyze_catalog_tables = publication_statistics.analyze_catalog_tables - def analyze_a_missing_table( - _connection, _cursor, statement, parameters, *_arguments - ): - if statement.startswith("ANALYZE"): - return "ANALYZE public.no_such_catalog_table", parameters - return statement, parameters + def analyze_a_missing_table(sessions: sessionmaker[Session]): + monkeypatch.setattr( + publication_statistics, + "CATALOG_STATISTICS_TABLES", + ("no_such_catalog_table",), + ) + return analyze_catalog_tables(sessions) - event.listen( - writer_engine, "before_cursor_execute", analyze_a_missing_table, retval=True + monkeypatch.setattr( + publication_module, "analyze_catalog_tables", analyze_a_missing_table ) - evidence = publish_catalog(writer_engine, normalized_catalog()) - with superuser_engine.connect() as connection: - stored_versions = connection.execute( - text("SELECT count(*) FROM tax_benefit_model_versions") - ).scalar_one() + evidence = publish_catalog(writer_sessions, normalized_catalog()) + stored_versions = _stored_version_count(superuser_sessions) assert stored_versions > 0 assert evidence.catalog_tables_analyzed == () @@ -186,7 +182,9 @@ def analyze_a_missing_table( @pytest.fixture -def writer_without_maintain(superuser_engine) -> Iterator[str]: +def writer_without_maintain( + superuser_sessions: sessionmaker[Session], +) -> Iterator[str]: """Create a role with the catalog writer's declared privileges except MAINTAIN.""" role = f"policyengine_catalog_test_{uuid4().hex[:12]}" writer_tables = declared_privileges("test")[CATALOG_WRITER_ROLE] @@ -198,30 +196,26 @@ def writer_without_maintain(superuser_engine) -> Iterator[str]: for table, privileges in writer_tables.items() } } - with superuser_engine.begin() as connection: - connection.execute(text(f'CREATE ROLE "{role}" NOLOGIN')) - apply_declared_privileges(connection, declared) + with superuser_sessions.begin() as session: + create_role(session, role) + apply_declared_privileges(session, declared) try: yield role finally: - with superuser_engine.begin() as connection: - connection.execute(text(f'DROP OWNED BY "{role}"')) - connection.execute(text(f'DROP ROLE "{role}"')) + with superuser_sessions.begin() as session: + drop_role(session, role) def test_a_role_that_cannot_analyze_the_catalog_fails_before_writing( - superuser_engine, v2_engine_as_role, writer_without_maintain + superuser_sessions: sessionmaker[Session], + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], + writer_without_maintain: str, ) -> None: - engine = v2_engine_as_role(writer_without_maintain, poolclass=NullPool) - try: - with pytest.raises(CatalogPublicationError) as raised: - publish_catalog(engine, normalized_catalog()) - finally: - engine.dispose() - with superuser_engine.connect() as connection: - stored_versions = connection.execute( - text("SELECT count(*) FROM tax_benefit_model_versions") - ).scalar_one() + with pytest.raises(CatalogPublicationError) as raised: + publish_catalog( + v2_sessions_as_role(writer_without_maintain), normalized_catalog() + ) + stored_versions = _stored_version_count(superuser_sessions) assert "MAINTAIN" in str(raised.value) assert "parameters" in str(raised.value) diff --git a/tests/integration/test_v2_country_routes.py b/tests/integration/test_v2_country_routes.py index 804b9f6f2..1b9d35932 100644 --- a/tests/integration/test_v2_country_routes.py +++ b/tests/integration/test_v2_country_routes.py @@ -7,18 +7,19 @@ from __future__ import annotations +from typing import TYPE_CHECKING + import pytest from alembic import command from alembic.config import Config from fastapi.testclient import TestClient from flask import Flask -from sqlalchemy import create_engine, text -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import NullPool -from sqlmodel import Session +from sqlalchemy import delete +from sqlmodel import col from policyengine_api.asgi_factory import create_asgi_app from policyengine_api.constants import REPO +from policyengine_api.data.v2.models import Country from policyengine_api.fastapi_routes.dependencies import NativeRouteDependencies from policyengine_api.migration_flags import ( RouteImplementation, @@ -33,15 +34,21 @@ ) from policyengine_api.supported_countries import SUPPORTED_COUNTRY_IDS from tests.fixtures.v2_countries import LISTED_COUNTRY_ROWS +from tests.integration.simulation_rows import add_row + +if TYPE_CHECKING: + from collections.abc import Callable + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session def test_postgres_countries_list_the_rows_the_revision_inserted( managed_v2_roles, - v2_engine_as_role, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> None: command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - runtime_engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - sessions = sessionmaker(runtime_engine, class_=Session) + sessions = v2_sessions_as_role(managed_v2_roles.runtime) dependencies = NativeRouteDependencies( readiness_probe=lambda: True, gateway_client_factory=lambda: None, @@ -63,10 +70,7 @@ def test_postgres_countries_list_the_rows_the_revision_inserted( ) ) - try: - response = client.get("/v2/countries") - finally: - runtime_engine.dispose() + response = client.get("/v2/countries") assert response.status_code == 200 assert response.json() == { @@ -78,33 +82,29 @@ def test_postgres_countries_list_the_rows_the_revision_inserted( def test_postgres_countries_match_the_code_list_as_the_runtime_role( managed_v2_roles, - v2_engine_as_role, - disposable_v2_database_url: str, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], + v2_owner_sessions: sessionmaker[Session], ) -> None: """The startup check passes on the revision's rows and fails on an extra row.""" command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - runtime_engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) service = V2CountryService( - CountryDatabaseSession(sessionmaker(runtime_engine, class_=Session)) + CountryDatabaseSession(v2_sessions_as_role(managed_v2_roles.runtime)) ) - owner_engine = create_engine(disposable_v2_database_url, poolclass=NullPool) try: service.verify_countries_match_code_list(SUPPORTED_COUNTRY_IDS) - with owner_engine.begin() as connection: - connection.execute( - text( - "INSERT INTO countries " - "(id, household_enabled, society_wide_enabled) " - "VALUES ('ca', true, false)" - ) + with v2_owner_sessions.begin() as session: + add_row( + session, + Country, + id="ca", + household_enabled=True, + society_wide_enabled=False, ) with pytest.raises(CountryListMismatchError) as raised: service.verify_countries_match_code_list(SUPPORTED_COUNTRY_IDS) assert raised.value.rows_not_listed == ("ca",) finally: - with owner_engine.begin() as connection: - connection.execute(text("DELETE FROM countries WHERE id = 'ca'")) - owner_engine.dispose() - runtime_engine.dispose() + with v2_owner_sessions.begin() as session: + session.execute(delete(Country).where(col(Country.id) == "ca")) diff --git a/tests/integration/test_v2_dynamic_persistence.py b/tests/integration/test_v2_dynamic_persistence.py index e93ef080d..379b5db16 100644 --- a/tests/integration/test_v2_dynamic_persistence.py +++ b/tests/integration/test_v2_dynamic_persistence.py @@ -7,20 +7,13 @@ from __future__ import annotations -import os from dataclasses import dataclass from typing import TYPE_CHECKING from uuid import UUID, uuid4 import pytest -from sqlalchemy import create_engine, delete, or_, select -from sqlalchemy.orm import sessionmaker -from sqlmodel import Session +from sqlalchemy import delete, or_, select -from policyengine_api.data.v2.migration_target import ( - V2_ALEMBIC_DISPOSABLE_TEST, - load_v2_alembic_settings, -) from policyengine_api.data.v2.models import ( Dynamic, LegacyPolicyMapping, @@ -30,7 +23,6 @@ TaxBenefitModel, TaxBenefitModelVersion, ) -from policyengine_api.data.v2.settings import V2_MIGRATION_DATABASE_URL from policyengine_api.services.v2.dynamics.database_session import ( DynamicDatabaseSession, ) @@ -44,7 +36,12 @@ from policyengine_api.services.v2.policies.types import LegacyPolicySnapshot if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + from tests.integration.conftest import ManagedV2Roles RUNNING_VERSION = "5.2.0" US_INCOME_ELASTICITY = "gov.simulation.labor_supply_responses.elasticities.income" @@ -55,21 +52,6 @@ UK_TAX_RATE = "gov.hmrc.income_tax.rate" -def _disposable_url() -> str: - database_url = os.environ.get(V2_MIGRATION_DATABASE_URL, "") - if not database_url: - pytest.skip(f"{V2_MIGRATION_DATABASE_URL} is not set") - settings = load_v2_alembic_settings( - { - V2_MIGRATION_DATABASE_URL: database_url, - V2_ALEMBIC_DISPOSABLE_TEST: os.environ.get(V2_ALEMBIC_DISPOSABLE_TEST, ""), - } - ) - if not settings.disposable_test: - pytest.fail("dynamic persistence tests require disposable-test mode") - return settings.url.render_as_string(hide_password=False) - - @dataclass(frozen=True) class StoredCatalog: """A country's running catalog version and its parameters' IDs by name.""" @@ -101,15 +83,17 @@ def _store_catalog( ) -def _remove_catalog(engine, catalog: StoredCatalog) -> None: - with engine.begin() as connection: +def _remove_catalog( + v2_owner_sessions: sessionmaker[Session], catalog: StoredCatalog +) -> None: + with v2_owner_sessions.begin() as session: dynamic_ids = select(Dynamic.id).where( Dynamic.tax_benefit_model_id == catalog.model_id ) policy_ids = select(Policy.id).where( Policy.tax_benefit_model_id == catalog.model_id ) - connection.execute( + session.execute( delete(LegacyPolicyMapping).where( or_( LegacyPolicyMapping.policy_id.in_(policy_ids), @@ -117,7 +101,7 @@ def _remove_catalog(engine, catalog: StoredCatalog) -> None: ) ) ) - connection.execute( + session.execute( delete(ParameterValue).where( or_( ParameterValue.policy_id.in_(policy_ids), @@ -125,68 +109,56 @@ def _remove_catalog(engine, catalog: StoredCatalog) -> None: ) ) ) - connection.execute( + session.execute( delete(Dynamic).where(Dynamic.tax_benefit_model_id == catalog.model_id) ) - connection.execute( + session.execute( delete(Policy).where(Policy.tax_benefit_model_id == catalog.model_id) ) - connection.execute( + session.execute( delete(Parameter).where( Parameter.tax_benefit_model_version_id == catalog.version_id ) ) - connection.execute( + session.execute( delete(TaxBenefitModelVersion).where( TaxBenefitModelVersion.id == catalog.version_id ) ) - connection.execute( + session.execute( delete(TaxBenefitModel).where(TaxBenefitModel.id == catalog.model_id) ) -@pytest.fixture -def superuser_engine() -> Iterator[object]: - engine = create_engine(_disposable_url()) - try: - yield engine - finally: - engine.dispose() - - @pytest.fixture def runtime_sessions( - managed_v2_roles, v2_engine_as_role -) -> Iterator[sessionmaker[Session]]: + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], +) -> sessionmaker[Session]: """Open sessions as API v1's runtime role.""" - runtime_engine = v2_engine_as_role(managed_v2_roles.runtime) - try: - yield sessionmaker(runtime_engine, class_=Session, expire_on_commit=False) - finally: - runtime_engine.dispose() + return v2_sessions_as_role(managed_v2_roles.runtime) @pytest.fixture -def us_catalog(superuser_engine) -> Iterator[StoredCatalog]: - with Session(superuser_engine) as session, session.begin(): +def us_catalog(v2_owner_sessions: sessionmaker[Session]) -> Iterator[StoredCatalog]: + with v2_owner_sessions.begin() as session: catalog = _store_catalog( session, "us", [US_INCOME_ELASTICITY, US_MTR_DELTA, US_TAX_RATE] ) try: yield catalog finally: - _remove_catalog(superuser_engine, catalog) + _remove_catalog(v2_owner_sessions, catalog) @pytest.fixture -def uk_catalog(superuser_engine) -> Iterator[StoredCatalog]: - with Session(superuser_engine) as session, session.begin(): +def uk_catalog(v2_owner_sessions: sessionmaker[Session]) -> Iterator[StoredCatalog]: + with v2_owner_sessions.begin() as session: catalog = _store_catalog(session, "uk", [UK_INCOME_ELASTICITY, UK_TAX_RATE]) try: yield catalog finally: - _remove_catalog(superuser_engine, catalog) + _remove_catalog(v2_owner_sessions, catalog) def _dynamic_service(sessions: sessionmaker[Session]) -> V2DynamicService: @@ -251,7 +223,7 @@ def _stored_names(session: Session, *, policy_id=None, dynamic_id=None) -> set[s def test_identical_dynamic_content_is_stored_once_and_read_back( - runtime_sessions, us_catalog, superuser_engine + runtime_sessions, us_catalog, v2_owner_sessions ) -> None: service = _dynamic_service(runtime_sessions) @@ -271,7 +243,7 @@ def test_identical_dynamic_content_is_stored_once_and_read_back( (US_INCOME_ELASTICITY, 0.25), (US_MTR_DELTA, 500), } - with Session(superuser_engine) as session: + with v2_owner_sessions() as session: stored = session.scalars( select(Dynamic).where(Dynamic.tax_benefit_model_id == us_catalog.model_id) ).all() @@ -295,7 +267,7 @@ def test_a_dynamic_is_read_only_in_its_own_country( def test_the_copy_splits_a_us_policy_into_a_policy_and_a_dynamic( - runtime_sessions, us_catalog, superuser_engine + runtime_sessions, us_catalog, v2_owner_sessions ) -> None: service = _policy_service(runtime_sessions) snapshot = _snapshot( @@ -317,7 +289,7 @@ def test_the_copy_splits_a_us_policy_into_a_policy_and_a_dynamic( assert retry.policy_id == first.policy_id assert retry.dynamic_id == first.dynamic_id assert retry.mapping_created is False - with Session(superuser_engine) as session: + with v2_owner_sessions() as session: assert _stored_names(session, policy_id=first.policy_id) == {US_TAX_RATE} assert _stored_names(session, dynamic_id=first.dynamic_id) == { US_INCOME_ELASTICITY, @@ -336,7 +308,7 @@ def test_the_copy_splits_a_us_policy_into_a_policy_and_a_dynamic( def test_the_copy_rewrites_the_uk_old_spelling_into_the_dynamic( - runtime_sessions, uk_catalog, superuser_engine + runtime_sessions, uk_catalog, v2_owner_sessions ) -> None: service = _policy_service(runtime_sessions) dynamic_values_only = service.mirror_legacy_policy( @@ -354,7 +326,7 @@ def test_the_copy_rewrites_the_uk_old_spelling_into_the_dynamic( assert same_values_new_spelling.dynamic_created is False assert no_dynamic_values.dynamic_id is None assert no_dynamic_values.dynamic_created is False - with Session(superuser_engine) as session: + with v2_owner_sessions() as session: # A v1 policy holding only dynamic values maps to an empty policy. assert _stored_names(session, policy_id=dynamic_values_only.policy_id) == set() assert _stored_names(session, dynamic_id=dynamic_values_only.dynamic_id) == { @@ -367,10 +339,10 @@ def test_the_copy_rewrites_the_uk_old_spelling_into_the_dynamic( def test_a_copy_made_before_the_split_keeps_its_mapping_without_a_dynamic( - runtime_sessions, us_catalog, superuser_engine + runtime_sessions, us_catalog, v2_owner_sessions ) -> None: snapshot = _snapshot("us", 9301, {US_INCOME_ELASTICITY: {"2026": 0.25}}) - with Session(superuser_engine) as session, session.begin(): + with v2_owner_sessions.begin() as session: earlier_copy = Policy( country_id="us", tax_benefit_model_id=us_catalog.model_id, diff --git a/tests/integration/test_v2_forced_report_reruns.py b/tests/integration/test_v2_forced_report_reruns.py index 4506c1cca..b1a4abf2a 100644 --- a/tests/integration/test_v2_forced_report_reruns.py +++ b/tests/integration/test_v2_forced_report_reruns.py @@ -9,18 +9,17 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING from uuid import UUID, uuid4 import pytest from alembic import command from alembic.config import Config -from sqlalchemy import create_engine, text -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import NullPool -from sqlmodel import Session +from sqlalchemy import delete +from sqlmodel import col from policyengine_api.constants import REPO +from policyengine_api.data.v2.models import User from tests.integration.stored_report_rows import ( delete_catalog, store_catalog, @@ -35,54 +34,57 @@ ) if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator - from sqlalchemy import Engine + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + from tests.integration.conftest import ManagedV2Roles from tests.integration.stored_report_rows import CatalogRows @pytest.fixture -def owner_engine(disposable_v2_database_url: str) -> Iterator[Engine]: +def owner_sessions( + v2_owner_sessions: sessionmaker[Session], +) -> sessionmaker[Session]: command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - yield engine - engine.dispose() + return v2_owner_sessions @pytest.fixture -def catalog(owner_engine: Engine) -> Iterator[CatalogRows]: - with owner_engine.begin() as connection: - stored = store_catalog(connection, "us") +def catalog(owner_sessions: sessionmaker[Session]) -> Iterator[CatalogRows]: + with owner_sessions.begin() as session: + stored = store_catalog(session, "us") yield stored - with owner_engine.begin() as connection: - delete_catalog(connection, stored) + with owner_sessions.begin() as session: + delete_catalog(session, stored) @pytest.fixture -def runtime_sessions(managed_v2_roles, v2_engine_as_role) -> Iterator[Any]: - engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - yield sessionmaker(engine, class_=Session) - engine.dispose() +def runtime_sessions( + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], +) -> sessionmaker[Session]: + return v2_sessions_as_role(managed_v2_roles.runtime) @pytest.fixture -def user_ids(owner_engine: Engine) -> Iterator[list[UUID]]: +def user_ids(owner_sessions: sessionmaker[Session]) -> Iterator[list[UUID]]: """Collect the users a test makes, and delete them and their records after.""" collected: list[UUID] = [] yield collected - with owner_engine.begin() as connection: - connection.execute( - text("DELETE FROM users WHERE id = ANY(:ids)"), {"ids": collected} - ) + with owner_sessions.begin() as session: + session.execute(delete(User).where(col(User.id).in_(collected))) def test_a_forced_rerun_without_a_user_credential_is_refused_with_401( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - with owner_engine.begin() as connection: - report = store_report(connection, catalog) - simulation_service = JoiningSimulationService(owner_engine, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) + simulation_service = JoiningSimulationService(owner_sessions, catalog) response = client_for(runtime_sessions, simulation_service).post( f"/v2/reports/{report.report_id}/runs?country_id=us", json={"force": True} @@ -96,15 +98,15 @@ def test_a_forced_rerun_without_a_user_credential_is_refused_with_401( @pytest.mark.parametrize("requester_type", ["unauthenticated", "standard", "author"]) def test_a_forced_rerun_by_anyone_below_admin_is_refused_with_403( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], user_ids: list[UUID], requester_type: str, ) -> None: - with owner_engine.begin() as connection: - report = store_report(connection, catalog) - simulation_service = JoiningSimulationService(owner_engine, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) + simulation_service = JoiningSimulationService(owner_sessions, catalog) if requester_type == "unauthenticated": browser_id = uuid4() user_ids.append(browser_id) @@ -112,7 +114,7 @@ def test_a_forced_rerun_by_anyone_below_admin_is_refused_with_403( headers = as_browser(browser_id) else: principal, user_id = store_signed_in_user( - runtime_sessions, owner_engine, user_type=requester_type + runtime_sessions, owner_sessions, user_type=requester_type ) user_ids.append(user_id) client = client_for(runtime_sessions, simulation_service, requester=principal) @@ -127,22 +129,22 @@ def test_a_forced_rerun_by_anyone_below_admin_is_refused_with_403( assert response.status_code == 403, response.text assert "admin" in response.json()["message"] assert simulation_service.reruns == [] - assert stored_records(owner_engine, user_ids) == [] + assert stored_records(owner_sessions, user_ids) == [] def test_an_admins_forced_rerun_is_sent_and_recorded( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], user_ids: list[UUID], ) -> None: - with owner_engine.begin() as connection: - report = store_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) admin, admin_id = store_signed_in_user( - runtime_sessions, owner_engine, user_type="admin" + runtime_sessions, owner_sessions, user_type="admin" ) user_ids.append(admin_id) - simulation_service = JoiningSimulationService(owner_engine, catalog) + simulation_service = JoiningSimulationService(owner_sessions, catalog) response = client_for(runtime_sessions, simulation_service, requester=admin).post( f"/v2/reports/{report.report_id}/runs?country_id=us", json={"force": True} @@ -151,6 +153,6 @@ def test_an_admins_forced_rerun_is_sent_and_recorded( assert response.status_code == 201, response.text (rerun,) = simulation_service.reruns assert rerun.force is True - (record,) = stored_records(owner_engine, [admin_id]) + (record,) = stored_records(owner_sessions, [admin_id]) assert str(record.report_run_id) == response.json()["result"]["item"]["run"]["id"] assert record.trigger == "manual" diff --git a/tests/integration/test_v2_household_calculation_reads.py b/tests/integration/test_v2_household_calculation_reads.py index d5abc7ece..7550d02a1 100644 --- a/tests/integration/test_v2_household_calculation_reads.py +++ b/tests/integration/test_v2_household_calculation_reads.py @@ -18,12 +18,11 @@ import pytest from alembic import command from alembic.config import Config -from sqlalchemy import create_engine, text -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import NullPool -from sqlmodel import Session +from sqlalchemy import delete +from sqlmodel import col from policyengine_api.constants import REPO +from policyengine_api.data.v2.models import HouseholdJob from policyengine_api.services.v2.countries.database_session import ( CountryDatabaseSession, ) @@ -58,14 +57,17 @@ from tests.integration.simulation_rows import ( RUN_VERSIONS, PublicApiRows, + add_row, delete_public_api_rows, insert_public_api_rows, - insert_row, ) if TYPE_CHECKING: from collections.abc import Iterator + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + COMPLETED_AT = datetime(2026, 11, 10, 12, 0, 9, tzinfo=UTC) @@ -81,16 +83,20 @@ class StoredJobs: def _insert_job( - connection, rows: PublicApiRows, job_id: UUID, status: str, **columns: object + session: Session, + rows: PublicApiRows, + job_id: UUID, + status: str, + **columns: object, ) -> None: - insert_row( - connection, - "household_jobs", + add_row( + session, + HouseholdJob, id=job_id, country="us", household_id=rows.household_id, year=2026, - request_data="{}", + request_data={}, tax_benefit_model_version_id=rows.version_id, status=status, **RUN_VERSIONS, @@ -99,16 +105,17 @@ def _insert_job( @pytest.fixture -def stored_jobs(disposable_v2_database_url, managed_v2_roles) -> Iterator[StoredJobs]: +def stored_jobs( + v2_owner_sessions: sessionmaker[Session], managed_v2_roles +) -> Iterator[StoredJobs]: """Commit, as the superuser, one job of each outcome; delete them afterwards. The service reads on connections of its own, so the rows are committed rather than left in a transaction the test rolls back. """ command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - with engine.begin() as connection: - rows = insert_public_api_rows(connection) + with v2_owner_sessions.begin() as session: + rows = insert_public_api_rows(session) jobs = StoredJobs( public_api_rows=rows, succeeded=uuid4(), @@ -117,42 +124,42 @@ def stored_jobs(disposable_v2_database_url, managed_v2_roles) -> Iterator[Stored pending=uuid4(), ) _insert_job( - connection, + session, rows, jobs.succeeded, "succeeded", # A json column keeps the document's text, so its key order too. - result=json.dumps(succeeded_document()), + result=succeeded_document(), completed_at=COMPLETED_AT, ) _insert_job( - connection, + session, rows, jobs.refused, "failed", - result=json.dumps(failed_document()), + result=failed_document(), error_message=FAILURE_SUMMARY, completed_at=COMPLETED_AT, ) _insert_job( - connection, + session, rows, jobs.failed_unexpectedly, "failed", error_message="household_function_error: the Modal call ended", completed_at=COMPLETED_AT, ) - _insert_job(connection, rows, jobs.pending, "pending") + _insert_job(session, rows, jobs.pending, "pending") try: yield jobs finally: - with engine.begin() as connection: - connection.execute( - text("DELETE FROM household_jobs WHERE household_id = :household_id"), - {"household_id": rows.household_id}, + with v2_owner_sessions.begin() as session: + session.execute( + delete(HouseholdJob).where( + col(HouseholdJob.household_id) == rows.household_id + ) ) - delete_public_api_rows(connection, rows) - engine.dispose() + delete_public_api_rows(session, rows) def _no_simulation_service(): @@ -161,11 +168,10 @@ def _no_simulation_service(): @pytest.fixture -def runtime_service(managed_v2_roles, v2_engine_as_role): +def runtime_service(managed_v2_roles, v2_sessions_as_role): """Return the household calculation service, reading as the runtime role.""" - runtime_engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - sessions = sessionmaker(runtime_engine, class_=Session) - yield V2HouseholdCalculationService( + sessions = v2_sessions_as_role(managed_v2_roles.runtime) + return V2HouseholdCalculationService( countries=V2CountryService(CountryDatabaseSession(sessions)), households=V2HouseholdService(HouseholdDatabaseSession(sessions)), policies=V2PolicyService( @@ -174,7 +180,6 @@ def runtime_service(managed_v2_roles, v2_engine_as_role): database_session=HouseholdCalculationDatabaseSession(sessions), simulation_factory=_no_simulation_service, ) - runtime_engine.dispose() def test_the_runtime_role_reads_a_succeeded_calculation_in_its_stored_order( diff --git a/tests/integration/test_v2_household_persistence.py b/tests/integration/test_v2_household_persistence.py index 0869cffb5..443f131cc 100644 --- a/tests/integration/test_v2_household_persistence.py +++ b/tests/integration/test_v2_household_persistence.py @@ -2,28 +2,21 @@ from __future__ import annotations -import os from concurrent.futures import ThreadPoolExecutor from threading import Barrier +from typing import TYPE_CHECKING from uuid import UUID, uuid4 import pytest -from sqlalchemy import create_engine, delete, func, select +from sqlalchemy import delete, func, inspect, select from sqlalchemy.exc import IntegrityError -from sqlalchemy.orm import sessionmaker -from sqlmodel import Session -from policyengine_api.data.v2.migration_target import ( - V2_ALEMBIC_DISPOSABLE_TEST, - load_v2_alembic_settings, -) from policyengine_api.data.v2.models import ( Household, LegacyHouseholdMapping, User, UserHouseholdAssociation, ) -from policyengine_api.data.v2.settings import V2_MIGRATION_DATABASE_URL from policyengine_api.services.v2.households.services import ( create_normalized_household, mirror_legacy_household_in_session, @@ -56,23 +49,9 @@ ) from tests.unit.v2.user_service_support import FakeLegacyReferences - -def _disposable_url() -> str: - database_url = os.environ.get(V2_MIGRATION_DATABASE_URL, "") - if not database_url: - pytest.skip(f"{V2_MIGRATION_DATABASE_URL} is not set") - settings = load_v2_alembic_settings( - { - V2_MIGRATION_DATABASE_URL: database_url, - V2_ALEMBIC_DISPOSABLE_TEST: os.environ.get( - V2_ALEMBIC_DISPOSABLE_TEST, - "", - ), - } - ) - if not settings.disposable_test: - pytest.fail("household persistence tests require disposable-test mode") - return settings.url.render_as_string(hide_password=False) +if TYPE_CHECKING: + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session def _normalized_input(marker: str, *, default_year: int | None = 2026): @@ -124,29 +103,30 @@ def _legacy_snapshot(legacy_id: int, marker: str, *, label: str): def _cleanup( - engine, + v2_owner_sessions: sessionmaker[Session], *, household_ids: set[UUID], user_ids: set[UUID] | None = None, ) -> None: - with engine.begin() as connection: - connection.execute( + with v2_owner_sessions.begin() as session: + session.execute( delete(UserHouseholdAssociation).where( UserHouseholdAssociation.household_id.in_(household_ids) ) ) - connection.execute( + session.execute( delete(LegacyHouseholdMapping).where( LegacyHouseholdMapping.household_id.in_(household_ids) ) ) - connection.execute(delete(Household).where(Household.id.in_(household_ids))) + session.execute(delete(Household).where(Household.id.in_(household_ids))) if user_ids: - connection.execute(delete(User).where(User.id.in_(user_ids))) + session.execute(delete(User).where(User.id.in_(user_ids))) -def test_concurrent_equivalent_content_resolves_to_one_household() -> None: - engine = create_engine(_disposable_url()) +def test_concurrent_equivalent_content_resolves_to_one_household( + v2_owner_sessions: sessionmaker[Session], +) -> None: household_ids: set[UUID] = set() household_input = _normalized_input(f"concurrent-{uuid4()}") barrier = Barrier(2) @@ -157,7 +137,7 @@ def synchronized_canonicalizer(command): barrier.wait(timeout=10) return content - with Session(engine) as session, session.begin(): + with v2_owner_sessions.begin() as session: result = create_normalized_household( session, household_input, @@ -172,7 +152,7 @@ def synchronized_canonicalizer(command): assert len(household_ids) == 1 assert sorted(result[1] for result in results) == [False, True] - with Session(engine) as session: + with v2_owner_sessions() as session: assert ( session.scalar( select(func.count()) @@ -183,17 +163,17 @@ def synchronized_canonicalizer(command): ) finally: if household_ids: - _cleanup(engine, household_ids=household_ids) - engine.dispose() + _cleanup(v2_owner_sessions, household_ids=household_ids) -def test_hash_collision_rolls_back_without_changing_stored_content() -> None: - engine = create_engine(_disposable_url()) +def test_hash_collision_rolls_back_without_changing_stored_content( + v2_owner_sessions: sessionmaker[Session], +) -> None: household_ids: set[UUID] = set() original = _normalized_input(f"original-{uuid4()}") changed = _normalized_input(f"changed-{uuid4()}") try: - with Session(engine) as session, session.begin(): + with v2_owner_sessions.begin() as session: first = create_normalized_household(session, original) household_ids.add(first.household_id) original_identity = canonicalize_household(original) @@ -206,8 +186,7 @@ def simulated_collision(command) -> CanonicalHouseholdContent: ) with ( - Session(engine) as session, - session.begin(), + v2_owner_sessions.begin() as session, pytest.raises(HouseholdContentHashCollisionError), ): create_normalized_household( @@ -216,29 +195,29 @@ def simulated_collision(command) -> CanonicalHouseholdContent: canonicalizer=simulated_collision, ) - with Session(engine) as session: + with v2_owner_sessions() as session: stored = session.get(Household, first.household_id) assert stored is not None assert stored.household_data == original.household_data finally: if household_ids: - _cleanup(engine, household_ids=household_ids) - engine.dispose() + _cleanup(v2_owner_sessions, household_ids=household_ids) -def test_legacy_mappings_are_many_to_one_and_conflicts_roll_back() -> None: - engine = create_engine(_disposable_url()) +def test_legacy_mappings_are_many_to_one_and_conflicts_roll_back( + v2_owner_sessions: sessionmaker[Session], +) -> None: household_ids: set[UUID] = set() source_marker = f"legacy-{uuid4()}" first = _legacy_snapshot(910001, source_marker, label="First label") second = _legacy_snapshot(910002, source_marker, label="Second label") try: - with Session(engine) as session, session.begin(): + with v2_owner_sessions.begin() as session: first_result = mirror_legacy_household_in_session(session, first) second_result = mirror_legacy_household_in_session(session, second) household_ids.add(first_result.household_id) - with Session(engine) as session, session.begin(): + with v2_owner_sessions.begin() as session: retry = mirror_legacy_household_in_session(session, first) assert first_result.household_id == second_result.household_id @@ -247,13 +226,12 @@ def test_legacy_mappings_are_many_to_one_and_conflicts_roll_back() -> None: conflicting = first.model_copy(update={"label": "Changed source label"}) with ( - Session(engine) as session, - session.begin(), + v2_owner_sessions.begin() as session, pytest.raises(LegacyHouseholdMappingIntegrityError), ): mirror_legacy_household_in_session(session, conflicting) - with Session(engine) as session: + with v2_owner_sessions() as session: mappings = session.scalars( select(LegacyHouseholdMapping).where( LegacyHouseholdMapping.household_id == first_result.household_id @@ -262,16 +240,15 @@ def test_legacy_mappings_are_many_to_one_and_conflicts_roll_back() -> None: assert len(mappings) == 2 finally: if household_ids: - _cleanup(engine, household_ids=household_ids) - engine.dispose() + _cleanup(v2_owner_sessions, household_ids=household_ids) -def test_content_edit_creates_replacement_and_reassigns_named_association() -> None: - engine = create_engine(_disposable_url()) - sessions = sessionmaker(engine, class_=Session, expire_on_commit=False) +def test_content_edit_creates_replacement_and_reassigns_named_association( + v2_owner_sessions: sessionmaker[Session], +) -> None: replacement_legacy_id = int(uuid4().int % 1_000_000_000) + 1 association_service = V2UserHouseholdService( - UserHouseholdDatabaseSession(sessions), + UserHouseholdDatabaseSession(v2_owner_sessions), FakeLegacyReferences( {("us", LegacyRecordKind.HOUSEHOLD): {replacement_legacy_id}} ), @@ -283,7 +260,7 @@ def test_content_edit_creates_replacement_and_reassigns_named_association() -> N household_ids: set[UUID] = set() user_ids: set[UUID] = set() try: - with sessions.begin() as session: + with v2_owner_sessions.begin() as session: original = create_normalized_household( session, _normalized_input(f"before-edit-{uuid4()}"), @@ -338,10 +315,10 @@ def test_content_edit_creates_replacement_and_reassigns_named_association() -> N assert reassigned.legacy_household_id == replacement_legacy_id assert reassigned.name == "Edited application display label" assert {"name", "description", "label"}.isdisjoint( - Household.__table__.columns.keys() + inspect(Household).columns.keys() ) - with pytest.raises(IntegrityError), sessions.begin() as session: + with pytest.raises(IntegrityError), v2_owner_sessions.begin() as session: session.execute( delete(Household).where(Household.id == original.household_id) ) @@ -352,14 +329,13 @@ def test_content_edit_creates_replacement_and_reassigns_named_association() -> N country_id="us", association_id=association_id, ) - with sessions() as session: + with v2_owner_sessions() as session: assert session.get(Household, original.household_id) is not None assert session.get(Household, replacement.household_id) is not None finally: if household_ids: _cleanup( - engine, + v2_owner_sessions, household_ids=household_ids, user_ids=user_ids, ) - engine.dispose() diff --git a/tests/integration/test_v2_household_reports.py b/tests/integration/test_v2_household_reports.py index a64d971e8..60928fa18 100644 --- a/tests/integration/test_v2_household_reports.py +++ b/tests/integration/test_v2_household_reports.py @@ -12,7 +12,6 @@ from __future__ import annotations -import json from dataclasses import dataclass, field from datetime import timedelta from typing import TYPE_CHECKING, Any @@ -23,13 +22,16 @@ from alembic.config import Config from fastapi.testclient import TestClient from flask import Flask -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import NullPool -from sqlmodel import Session from policyengine_api.asgi_factory import create_asgi_app from policyengine_api.constants import REPO +from policyengine_api.data.v2.models import ( + Household, + Report, + ReportRun, + Simulation, + SimulationRun, +) from policyengine_api.fastapi_routes.dependencies import NativeRouteDependencies from policyengine_api.migration_flags import ( RouteImplementation, @@ -62,7 +64,7 @@ StoredReportDatabaseSession, ) from policyengine_api.services.v2.stored_reports.services import V2StoredReportService -from tests.integration.simulation_rows import insert_row +from tests.integration.simulation_rows import add_row from tests.integration.stored_report_rows import ( STARTED_AT, household_only_catalog, @@ -70,9 +72,10 @@ ) if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator - from sqlalchemy import Connection, Engine + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session from policyengine_api.services.v2.simulation_service.types import ( HouseholdReportCreationInput, @@ -129,17 +132,17 @@ class StoredHouseholdReport: def store_household( - connection: Connection, catalog: CatalogRows, *, default_year: int | None = 2026 + session: Session, catalog: CatalogRows, *, default_year: int | None = 2026 ) -> UUID: """Store a household in the catalog's country; ``delete_catalog`` removes it.""" household_id = uuid4() - insert_row( - connection, - "households", + add_row( + session, + Household, id=household_id, country_id=catalog.country, default_year=default_year, - household_data=json.dumps(STORED_HOUSEHOLD), + household_data=STORED_HOUSEHOLD, canonicalization_version=1, content_hash=uuid4().hex * 2, ) @@ -160,7 +163,7 @@ def finished(self) -> bool: def store_household_simulation( - connection: Connection, + session: Session, catalog: CatalogRows, household_id: UUID, *, @@ -169,9 +172,9 @@ def store_household_simulation( ) -> tuple[UUID, UUID]: """Store a household simulation and one run; return both IDs.""" simulation_id = uuid4() - insert_row( - connection, - "simulations", + add_row( + session, + Simulation, id=simulation_id, simulation_type="household", household_id=household_id, @@ -181,9 +184,11 @@ def store_household_simulation( ) catalog.simulation_ids.append(simulation_id) run_id = uuid4() - insert_row( - connection, - "simulation_runs", + # A run without a calculated household holds SQL NULL, not JSON null. + calculated = {} if run.document is None else {"household_result": run.document} + add_row( + session, + SimulationRun, id=run_id, simulation_id=simulation_id, year=2026, @@ -191,7 +196,7 @@ def store_household_simulation( status=run.status, started_at=STARTED_AT, completed_at=STARTED_AT + timedelta(minutes=1) if run.finished else None, - household_result=None if run.document is None else json.dumps(run.document), + **calculated, **CURRENT_VERSIONS, ) return simulation_id, run_id @@ -229,7 +234,7 @@ def runs(self) -> tuple[SimulationRunToStore, SimulationRunToStore]: def store_household_report( - connection: Connection, + session: Session, catalog: CatalogRows, household_id: UUID, report: HouseholdReportToStore | None = None, @@ -243,21 +248,21 @@ def store_household_report( with_reform = report.with_reform baseline_run, reform_run = report.runs() baseline_id, baseline_run_id = store_household_simulation( - connection, catalog, household_id, policy_id=None, run=baseline_run + session, catalog, household_id, policy_id=None, run=baseline_run ) reform_id = reform_run_id = None if with_reform: reform_id, reform_run_id = store_household_simulation( - connection, + session, catalog, household_id, policy_id=catalog.policy_id, run=reform_run, ) report_id = uuid4() - insert_row( - connection, - "reports", + add_row( + session, + Report, id=report_id, label="My household under the reform", country=catalog.country, @@ -267,13 +272,13 @@ def store_household_report( reform_simulation_id=reform_id, household_id=household_id, year=2026, - inputs=json.dumps({}), + inputs={}, ) catalog.report_ids.append(report_id) report_run_id = uuid4() - insert_row( - connection, - "report_runs", + add_row( + session, + ReportRun, id=report_run_id, report_id=report_id, baseline_simulation_run_id=baseline_run_id, @@ -295,7 +300,7 @@ def store_household_report( class StoringHouseholdReportService: """Store what the simulation service would create for a household report.""" - engine: Engine + owner_sessions: sessionmaker[Session] catalog: CatalogRows household_reports: list[HouseholdReportCreationInput] = field(default_factory=list) @@ -303,9 +308,9 @@ def submit_household_report( self, report: HouseholdReportCreationInput ) -> SubmittedReport: self.household_reports.append(report) - with self.engine.begin() as connection: + with self.owner_sessions.begin() as session: stored = store_household_report( - connection, + session, self.catalog, report.household_id, HouseholdReportToStore(status="pending"), @@ -316,25 +321,23 @@ def submit_household_report( @pytest.fixture -def owner_engine(disposable_v2_database_url: str) -> Iterator[Engine]: +def owner_sessions(v2_owner_sessions: sessionmaker[Session]) -> sessionmaker[Session]: command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - yield engine - engine.dispose() + return v2_owner_sessions @pytest.fixture -def household_only_uk(owner_engine: Engine) -> Iterator[CatalogRows]: +def household_only_uk(owner_sessions: sessionmaker[Session]) -> Iterator[CatalogRows]: """Make the UK household-only, store a UK catalog, and restore both after.""" - with household_only_catalog(owner_engine, "uk") as uk_catalog: + with household_only_catalog(owner_sessions, "uk") as uk_catalog: yield uk_catalog @pytest.fixture -def runtime_sessions(managed_v2_roles, v2_engine_as_role) -> Iterator[Any]: - engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - yield sessionmaker(engine, class_=Session) - engine.dispose() +def runtime_sessions( + managed_v2_roles, v2_sessions_as_role: Callable[[str], sessionmaker[Session]] +) -> sessionmaker[Session]: + return v2_sessions_as_role(managed_v2_roles.runtime) def client_for( @@ -386,12 +389,14 @@ def household_body(household_id: UUID, policy_id: UUID) -> dict[str, Any]: def test_a_household_report_answers_both_calculated_households( - owner_engine: Engine, household_only_uk: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + household_only_uk: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: catalog = household_only_uk - with owner_engine.begin() as connection: - household_id = store_household(connection, catalog) - stored = store_household_report(connection, catalog, household_id) + with owner_sessions.begin() as session: + household_id = store_household(session, catalog) + stored = store_household_report(session, catalog, household_id) response = client_for(runtime_sessions).get( f"/v2/reports/{stored.report_id}?country_id=uk" @@ -410,12 +415,14 @@ def test_a_household_report_answers_both_calculated_households( def test_a_household_report_of_the_baseline_alone_answers_no_reform( - owner_engine: Engine, household_only_uk: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + household_only_uk: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - with owner_engine.begin() as connection: - household_id = store_household(connection, household_only_uk) + with owner_sessions.begin() as session: + household_id = store_household(session, household_only_uk) stored = store_household_report( - connection, + session, household_only_uk, household_id, HouseholdReportToStore(with_reform=False), @@ -434,12 +441,14 @@ def test_a_household_report_of_the_baseline_alone_answers_no_reform( def test_a_failed_household_report_answers_each_sides_failure( - owner_engine: Engine, household_only_uk: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + household_only_uk: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - with owner_engine.begin() as connection: - household_id = store_household(connection, household_only_uk) + with owner_sessions.begin() as session: + household_id = store_household(session, household_only_uk) stored = store_household_report( - connection, + session, household_only_uk, household_id, # Both sides are calculated: the baseline succeeded, the reform's @@ -466,12 +475,14 @@ def test_a_failed_household_report_answers_each_sides_failure( def test_a_succeeded_household_report_missing_a_calculation_answers_500( - owner_engine: Engine, household_only_uk: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + household_only_uk: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - with owner_engine.begin() as connection: - household_id = store_household(connection, household_only_uk) + with owner_sessions.begin() as session: + household_id = store_household(session, household_only_uk) stored = store_household_report( - connection, + session, household_only_uk, household_id, HouseholdReportToStore( @@ -496,15 +507,17 @@ def test_a_succeeded_household_report_missing_a_calculation_answers_500( def test_household_reports_are_listed_beside_economy_reports( - owner_engine: Engine, household_only_uk: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + household_only_uk: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: catalog = household_only_uk - with owner_engine.begin() as connection: - household_id = store_household(connection, catalog) + with owner_sessions.begin() as session: + household_id = store_household(session, catalog) household_report = store_household_report( - connection, catalog, household_id, HouseholdReportToStore(status="running") + session, catalog, household_id, HouseholdReportToStore(status="running") ) - economy_report = store_report(connection, catalog) + economy_report = store_report(session, catalog) response = client_for(runtime_sessions).get( "/v2/reports?country_id=uk" @@ -523,12 +536,14 @@ def test_household_reports_are_listed_beside_economy_reports( def test_a_household_only_country_creates_a_household_report( - owner_engine: Engine, household_only_uk: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + household_only_uk: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: catalog = household_only_uk - with owner_engine.begin() as connection: - household_id = store_household(connection, catalog) - simulation_service = StoringHouseholdReportService(owner_engine, catalog) + with owner_sessions.begin() as session: + household_id = store_household(session, catalog) + simulation_service = StoringHouseholdReportService(owner_sessions, catalog) response = client_for(runtime_sessions, simulation_service).post( "/v2/reports?country_id=uk", @@ -546,9 +561,13 @@ def test_a_household_only_country_creates_a_household_report( def test_a_household_the_country_does_not_store_is_not_sent( - owner_engine: Engine, household_only_uk: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + household_only_uk: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - simulation_service = StoringHouseholdReportService(owner_engine, household_only_uk) + simulation_service = StoringHouseholdReportService( + owner_sessions, household_only_uk + ) response = client_for(runtime_sessions, simulation_service).post( "/v2/reports?country_id=uk", @@ -560,11 +579,15 @@ def test_a_household_the_country_does_not_store_is_not_sent( def test_a_household_with_no_default_year_is_not_sent( - owner_engine: Engine, household_only_uk: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + household_only_uk: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - with owner_engine.begin() as connection: - household_id = store_household(connection, household_only_uk, default_year=None) - simulation_service = StoringHouseholdReportService(owner_engine, household_only_uk) + with owner_sessions.begin() as session: + household_id = store_household(session, household_only_uk, default_year=None) + simulation_service = StoringHouseholdReportService( + owner_sessions, household_only_uk + ) response = client_for(runtime_sessions, simulation_service).post( "/v2/reports?country_id=uk", @@ -579,7 +602,7 @@ def test_a_household_with_no_default_year_is_not_sent( def test_a_household_only_country_still_refuses_economy_reports( - household_only_uk: CatalogRows, runtime_sessions: Any + household_only_uk: CatalogRows, runtime_sessions: sessionmaker[Session] ) -> None: response = client_for(runtime_sessions).post( "/v2/reports?country_id=uk", diff --git a/tests/integration/test_v2_metadata_routes.py b/tests/integration/test_v2_metadata_routes.py index 810d753de..2c3387f64 100644 --- a/tests/integration/test_v2_metadata_routes.py +++ b/tests/integration/test_v2_metadata_routes.py @@ -4,21 +4,16 @@ import gzip import json -import os from datetime import UTC, datetime -from pathlib import Path from types import SimpleNamespace +from typing import TYPE_CHECKING from uuid import uuid4 import pytest -from alembic import command -from alembic.config import Config +import sqlalchemy as sa from fastapi.testclient import TestClient from flask import Flask, jsonify -from sqlalchemy import create_engine, event, text -from sqlalchemy.engine import Engine, make_url -from sqlalchemy.pool import NullPool -from sqlmodel import Session, select +from sqlmodel import col, select from policyengine_api.asgi_factory import create_asgi_app from policyengine_api.data.v2.catalog.extraction import extract_catalog @@ -29,12 +24,14 @@ from policyengine_api.data.v2.models import ( Dataset, Parameter, + ParameterSearchFile, + ParameterTreeChild, ParameterValue, + Region, TaxBenefitModel, TaxBenefitModelVersion, Variable, ) -from policyengine_api.data.v2.settings import V2_MIGRATION_DATABASE_URL from policyengine_api.fastapi_routes.dependencies import NativeRouteDependencies from policyengine_api.migration_flags import ( RouteImplementation, @@ -45,6 +42,7 @@ ) from policyengine_api.services.v2.metadata.services import V2MetadataService from policyengine_api.services.v2.metadata.types import ParameterTreeLevel +from tests.fixtures import database_sessions from tests.fixtures.v2_catalog import ( POLICYENGINE_VERSION, bundle, @@ -53,41 +51,41 @@ region_references, source_models, ) +from tests.integration.catalog_publication_support import emptied_catalog, row_counts -REPO = Path(__file__).parents[2] -DISPOSABLE_DATABASE = "policyengine_v2_alembic_test" +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session -def _disposable_url() -> str: - database_url = os.environ.get(V2_MIGRATION_DATABASE_URL, "") - if not database_url: - pytest.skip(f"{V2_MIGRATION_DATABASE_URL} is not set") - url = make_url(database_url) - if url.database != DISPOSABLE_DATABASE or url.host not in { - "localhost", - "127.0.0.1", - "::1", - "postgres", - }: - pytest.fail("v2 metadata route tests require disposable local PostgreSQL") - return database_url +# The catalog tables whose rows the read-only routes must leave as they are. +COUNTED_MODELS = { + "variables": Variable, + "parameters": Parameter, + "parameter_values": ParameterValue, + "datasets": Dataset, + "regions": Region, +} @pytest.fixture -def published_engine() -> Engine: - database_url = _disposable_url() - command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(database_url, poolclass=NullPool) - with engine.begin() as connection: - connection.execute(text("TRUNCATE tax_benefit_models CASCADE")) - publish_catalog(engine, normalized_catalog()) - yield engine - with engine.begin() as connection: - connection.execute(text("TRUNCATE tax_benefit_models CASCADE")) - engine.dispose() - - -def _client(engine: Engine) -> TestClient: +def published_sessions( + v2_owner_sessions: sessionmaker[Session], +) -> Iterator[sessionmaker[Session]]: + with emptied_catalog(v2_owner_sessions) as sessions: + publish_catalog(sessions, normalized_catalog()) + yield sessions + + +def _republish(sessions: sessionmaker[Session], catalog) -> None: + """Replace the published catalog with ``catalog``.""" + with sessions.begin() as session: + database_sessions.truncate(session, TaxBenefitModel) + publish_catalog(sessions, catalog) + + +def _client(sessions: sessionmaker[Session]) -> TestClient: flask_app = Flask(__name__) @flask_app.get("//metadata") @@ -99,7 +97,7 @@ def v1_metadata(country_id: str): gateway_client_factory=lambda: None, metadata_reader_factory=lambda: None, v2_metadata_reader_factory=lambda: V2MetadataService( - MetadataDatabaseSession(Session(engine)), + MetadataDatabaseSession(sessions()), running_policyengine_version=POLICYENGINE_VERSION, ), ) @@ -117,22 +115,8 @@ def v1_metadata(country_id: str): ) -def _catalog_counts(engine: Engine) -> tuple[int, ...]: - with engine.connect() as connection: - return tuple( - connection.execute( - text( - """ - SELECT - (SELECT count(*) FROM variables), - (SELECT count(*) FROM parameters), - (SELECT count(*) FROM parameter_values), - (SELECT count(*) FROM datasets), - (SELECT count(*) FROM regions) - """ - ) - ).one() - ) +def _catalog_counts(sessions: sessionmaker[Session]) -> tuple[int, ...]: + return tuple(row_counts(sessions, COUNTED_MODELS).values()) @pytest.mark.parametrize( @@ -140,13 +124,13 @@ def _catalog_counts(engine: Engine) -> tuple[int, ...]: [("us", 2, "Microcosm"), ("uk", 1, "Microcosm")], ) def test_postgres_resource_collections_are_separate_and_read_only( - published_engine: Engine, + published_sessions: sessionmaker[Session], country_id: str, current_law_id: int, dataset_label: str, ) -> None: - client = _client(published_engine) - before = _catalog_counts(published_engine) + client = _client(published_sessions) + before = _catalog_counts(published_sessions) query = {"country_id": country_id} models = client.get("/v2/tax-benefit-models", params=query) @@ -198,13 +182,13 @@ def test_postgres_resource_collections_are_separate_and_read_only( isinstance(period["name"], int) and isinstance(period["label"], str) for period in option_result["time_period"] ) - assert _catalog_counts(published_engine) == before + assert _catalog_counts(published_sessions) == before def test_postgres_parameter_tree_returns_direct_children_and_leaf_details( - published_engine: Engine, + published_sessions: sessionmaker[Session], ) -> None: - client = _client(published_engine) + client = _client(published_sessions) query = {"country_id": "us"} root = client.get("/v2/parameters/children", params=query) @@ -231,9 +215,9 @@ def test_postgres_parameter_tree_returns_direct_children_and_leaf_details( def test_postgres_collection_ids_resolve_through_detail_routes( - published_engine: Engine, + published_sessions: sessionmaker[Session], ) -> None: - client = _client(published_engine) + client = _client(published_sessions) query = {"country_id": "us"} resources = ( ("tax-benefit-models", "model_id"), @@ -261,9 +245,9 @@ def test_postgres_collection_ids_resolve_through_detail_routes( def test_postgres_dataset_collection_excludes_an_existing_output( - published_engine: Engine, + published_sessions: sessionmaker[Session], ) -> None: - with Session(published_engine) as session: + with published_sessions() as session: model = session.exec( select(TaxBenefitModel).where(TaxBenefitModel.name == "policyengine-us") ).one() @@ -287,7 +271,7 @@ def test_postgres_dataset_collection_excludes_an_existing_output( ) session.commit() - response = _client(published_engine).get( + response = _client(published_sessions).get( "/v2/datasets", params={"country_id": "us"}, ) @@ -300,14 +284,14 @@ def test_postgres_dataset_collection_excludes_an_existing_output( @pytest.mark.parametrize("country_id", ["us", "uk"]) def test_postgres_resources_default_to_running_version_and_accept_exact_override( - published_engine: Engine, + published_sessions: sessionmaker[Session], country_id: str, ) -> None: publish_catalog( - published_engine, + published_sessions, normalized_catalog(policyengine_version="5.0.5"), ) - client = _client(published_engine) + client = _client(published_sessions) default_response = client.get( "/v2/variables", @@ -329,9 +313,9 @@ def test_postgres_resources_default_to_running_version_and_accept_exact_override def test_postgres_resources_distinguish_invalid_and_absent_versions( - published_engine: Engine, + published_sessions: sessionmaker[Session], ) -> None: - client = _client(published_engine) + client = _client(published_sessions) invalid = client.get( "/v2/variables", @@ -351,27 +335,28 @@ def test_postgres_resources_distinguish_invalid_and_absent_versions( def test_postgres_parameter_collection_remains_available_without_values( - published_engine: Engine, + published_sessions: sessionmaker[Session], ) -> None: - with published_engine.begin() as connection: - connection.execute( - text( - """ - DELETE FROM parameter_values - WHERE parameter_id IN ( - SELECT parameter.id - FROM parameters AS parameter - JOIN tax_benefit_model_versions AS model_version - ON model_version.id = parameter.tax_benefit_model_version_id - JOIN tax_benefit_models AS model - ON model.id = model_version.model_id - WHERE model.name = 'policyengine-us' + with published_sessions.begin() as session: + session.execute( + sa.delete(ParameterValue).where( + col(ParameterValue.parameter_id).in_( + select(col(Parameter.id)) + .join( + TaxBenefitModelVersion, + col(TaxBenefitModelVersion.id) + == col(Parameter.tax_benefit_model_version_id), + ) + .join( + TaxBenefitModel, + col(TaxBenefitModel.id) == col(TaxBenefitModelVersion.model_id), + ) + .where(col(TaxBenefitModel.name) == "policyengine-us") ) - """ ) ) - client = _client(published_engine) + client = _client(published_sessions) parameters = client.get("/v2/parameters", params={"country_id": "us"}) values = client.get("/v2/parameter-values", params={"country_id": "us"}) @@ -382,10 +367,10 @@ def test_postgres_parameter_collection_remains_available_without_values( @pytest.mark.parametrize("country_id", ["us", "uk"]) def test_postgres_model_catalog_serves_the_small_parts_of_a_version( - published_engine: Engine, + published_sessions: sessionmaker[Session], country_id: str, ) -> None: - client = _client(published_engine) + client = _client(published_sessions) country = normalized_catalog().country(country_id) running = client.get("/v2/model-catalog", params={"country_id": country_id}) @@ -430,8 +415,8 @@ def test_postgres_model_catalog_serves_the_small_parts_of_a_version( assert revalidated.status_code == 304 -def _us_model_version_id(engine: Engine): - with Session(engine) as session: +def _us_model_version_id(sessions: sessionmaker[Session]): + with sessions() as session: return session.exec( select(TaxBenefitModelVersion.id) .join( @@ -442,11 +427,11 @@ def _us_model_version_id(engine: Engine): def test_postgres_catalog_variables_carry_part_parameter_values_by_date( - published_engine: Engine, + published_sessions: sessionmaker[Session], ) -> None: - model_version_id = _us_model_version_id(published_engine) + model_version_id = _us_model_version_id(published_sessions) parts_id = uuid4() - with Session(published_engine) as session: + with published_sessions() as session: session.add( Parameter( id=parts_id, @@ -485,7 +470,7 @@ def test_postgres_catalog_variables_carry_part_parameter_values_by_date( ] ) session.commit() - client = _client(published_engine) + client = _client(published_sessions) response = client.get( "/v2/model-catalog/variables", @@ -527,9 +512,9 @@ def test_postgres_catalog_variables_carry_part_parameter_values_by_date( def test_postgres_catalog_parameters_load_values_and_breadcrumb_labels( - published_engine: Engine, + published_sessions: sessionmaker[Session], ) -> None: - client = _client(published_engine) + client = _client(published_sessions) response = client.get( "/v2/model-catalog/parameters", @@ -562,57 +547,53 @@ def test_postgres_catalog_parameters_load_values_and_breadcrumb_labels( def test_postgres_metadata_reads_send_no_transaction_statements( - published_engine: Engine, + published_sessions: sessionmaker[Session], + disposable_v2_database_url: str, ) -> None: # Each metadata read is one statement on rows a published catalog never # changes, so the read session runs in autocommit mode: psycopg then sends # no BEGIN before the reads and no ROLLBACK when the session closes. The # engine has one pooled connection, so the writer below must get the same # connection back in the ordinary, transactional mode. - from psycopg.pq import TransactionStatus - from policyengine_api.data.v2.database import build_v2_read_session_factory - del published_engine # publishes the catalog this pooled engine reads - pooled_engine = create_engine(_disposable_url(), pool_size=1, max_overflow=0) - read_connections: list[object] = [] - autocommit_modes: list[bool] = [] + del published_sessions # publishes the catalog these pooled sessions read + with database_sessions.single_connection_v2_sessions( + disposable_v2_database_url + ) as pooled_sessions: + with database_sessions.recorded_driver_connection_states( + pooled_sessions + ) as read_states: + service = V2MetadataService( + MetadataDatabaseSession( + build_v2_read_session_factory(pooled_sessions)() + ), + running_policyengine_version=POLICYENGINE_VERSION, + ) + result = service.list_parameters("us") + service.close() - def record_mode(connection, _cursor, _statement, *_args) -> None: - dbapi_connection = connection.connection.dbapi_connection - read_connections.append(dbapi_connection) - autocommit_modes.append(dbapi_connection.autocommit) - - try: - event.listen(pooled_engine, "before_cursor_execute", record_mode) - service = V2MetadataService( - MetadataDatabaseSession(build_v2_read_session_factory(pooled_engine)()), - running_policyengine_version=POLICYENGINE_VERSION, - ) - result = service.list_parameters("us") - service.close() - event.remove(pooled_engine, "before_cursor_execute", record_mode) - - with Session(pooled_engine) as writer: - writer_connection = writer.connection().connection.dbapi_connection - writer.execute(text("SELECT 1")) - writer_status = writer_connection.info.transaction_status - writer_autocommit = writer_connection.autocommit - finally: - pooled_engine.dispose() + with ( + database_sessions.recorded_driver_connection_states( + pooled_sessions + ) as writer_states, + pooled_sessions() as writer_session, + ): + writer_session.execute(sa.select(sa.literal(1))) assert [item.name for item in result.items] == ["gov.example.rate"] - assert autocommit_modes - assert all(autocommit_modes) - assert {id(connection) for connection in read_connections} == { - id(writer_connection) + assert read_states + assert all(state.autocommit for state in read_states) + [writer_state] = writer_states + assert {state.connection_id for state in read_states} == { + writer_state.connection_id } - assert writer_autocommit is False - assert writer_status == TransactionStatus.INTRANS + assert writer_state.autocommit is False + assert writer_state.in_transaction is True def test_postgres_production_metadata_reader_keeps_catalogs_and_responses( - published_engine: Engine, + published_sessions: sessionmaker[Session], ) -> None: # The production combination: autocommit read sessions, the process's # selected catalogs and its whole-version response cache. @@ -624,12 +605,8 @@ def test_postgres_production_metadata_reader_keeps_catalogs_and_responses( SelectedCatalogStore, ) - read_factory = build_v2_read_session_factory(published_engine) + read_factory = build_v2_read_session_factory(published_sessions) selected_catalogs = SelectedCatalogStore() - statements: list[str] = [] - - def record_statement(_connection, _cursor, statement, *_args) -> None: - statements.append(statement) dependencies = NativeRouteDependencies( readiness_probe=lambda: True, @@ -654,8 +631,7 @@ def record_statement(_connection, _cursor, statement, *_args) -> None: ) query = {"country_id": "us", "policyengine_version": POLICYENGINE_VERSION} - event.listen(published_engine, "before_cursor_execute", record_statement) - try: + with database_sessions.recorded_statements(published_sessions) as statements: first_variables = client.get( "/v2/model-catalog/variables", params={"country_id": "us"} ) @@ -668,8 +644,6 @@ def record_statement(_connection, _cursor, statement, *_args) -> None: statements_for_parameters = ( len(statements) - statements_for_first - statements_for_repeat ) - finally: - event.remove(published_engine, "before_cursor_execute", record_statement) assert first_variables.status_code == 200 assert repeated_variables.content == first_variables.content @@ -712,7 +686,7 @@ def record_statement(_connection, _cursor, statement, *_args) -> None: ], ) def test_postgres_current_values_and_their_lifetime_use_one_instant( - published_engine: Engine, + published_sessions: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch, case: tuple[datetime, datetime, list[float], str], ) -> None: @@ -722,7 +696,7 @@ def test_postgres_current_values_and_their_lifetime_use_one_instant( instants = iter([read_instant, header_instant]) monkeypatch.setattr(route_support, "utc_now", lambda: next(instants)) - response = _client(published_engine).get( + response = _client(published_sessions).get( "/v2/parameter-values", params={ "country_id": "us", @@ -800,12 +774,10 @@ def _items(response) -> list[tuple]: def test_postgres_parameter_tree_nests_schedules_and_filters_reform_changes( - published_engine: Engine, + published_sessions: sessionmaker[Session], ) -> None: - with published_engine.begin() as connection: - connection.execute(text("TRUNCATE tax_benefit_models CASCADE")) - publish_catalog(published_engine, _catalog_with_a_bracket_schedule()) - client = _client(published_engine) + _republish(published_sessions, _catalog_with_a_bracket_schedule()) + client = _client(published_sessions) query = {"country_id": "uk"} rates = client.get( @@ -860,23 +832,20 @@ def test_postgres_parameter_tree_nests_schedules_and_filters_reform_changes( def test_postgres_parameter_tree_reads_as_the_runtime_role( - published_engine: Engine, + published_sessions: sessionmaker[Session], managed_v2_roles, - v2_engine_as_role, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> None: """The Public API's runtime role can read the tree with its declared privileges.""" - runtime_engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - try: - with Session(runtime_engine) as session: - result = V2MetadataService( - MetadataDatabaseSession(session), - running_policyengine_version=POLICYENGINE_VERSION, - ).list_parameter_children( - "us", - level=ParameterTreeLevel(parent_path="gov", reform_changeable=True), - ) - finally: - runtime_engine.dispose() + runtime_sessions = v2_sessions_as_role(managed_v2_roles.runtime) + with runtime_sessions() as session: + result = V2MetadataService( + MetadataDatabaseSession(session), + running_policyengine_version=POLICYENGINE_VERSION, + ).list_parameter_children( + "us", + level=ParameterTreeLevel(parent_path="gov", reform_changeable=True), + ) assert [(item.path, item.child_count) for item in result.items] == [ ("gov.example", 1) @@ -971,12 +940,10 @@ def _catalog_shaped_like_policyengine_py_output(): def test_postgres_parameter_tree_from_records_shaped_like_policyengine_py( - published_engine: Engine, + published_sessions: sessionmaker[Session], ) -> None: - with published_engine.begin() as connection: - connection.execute(text("TRUNCATE tax_benefit_models CASCADE")) - publish_catalog(published_engine, _catalog_shaped_like_policyengine_py_output()) - client = _client(published_engine) + _republish(published_sessions, _catalog_shaped_like_policyengine_py_output()) + client = _client(published_sessions) def level(parent_path: str) -> list[tuple]: return _items( @@ -1024,34 +991,36 @@ def level(parent_path: str) -> list[tuple]: def test_postgres_a_version_stored_before_format_2_returns_the_tree_503( - published_engine: Engine, + published_sessions: sessionmaker[Session], ) -> None: """A version stored before catalog format 2 gets no tree on republication. Its parameter tree request returns 503 with the message naming it. """ - with published_engine.begin() as connection: - connection.execute( - text( - "UPDATE tax_benefit_model_versions SET catalog_format = NULL, " - "entities = NULL, basic_inputs = NULL" + # The JSON columns get SQL NULL (sa.null()), not JSON's null. + with published_sessions.begin() as session: + session.execute( + sa.update(TaxBenefitModelVersion).values( + catalog_format=None, entities=sa.null(), basic_inputs=sa.null() ) ) - connection.execute( - text( - "UPDATE variables SET is_input_variable = NULL, hidden_input = NULL, " - "module_name = NULL, adds_parameter_path = NULL, " - "subtracts_parameter_path = NULL, enum_values = NULL, " - "unit = NULL, definition_period = NULL" + session.execute( + sa.update(Variable).values( + is_input_variable=None, + hidden_input=None, + module_name=None, + adds_parameter_path=None, + subtracts_parameter_path=None, + enum_values=sa.null(), + unit=None, + definition_period=None, ) ) - connection.execute( - text("UPDATE parameters SET economy = NULL, household = NULL") - ) - connection.execute(text("DELETE FROM parameter_tree_children")) - evidence = publish_catalog(published_engine, normalized_catalog()) + session.execute(sa.update(Parameter).values(economy=None, household=None)) + session.execute(sa.delete(ParameterTreeChild)) + evidence = publish_catalog(published_sessions, normalized_catalog()) - response = _client(published_engine).get( + response = _client(published_sessions).get( "/v2/parameters/children", params={"country_id": "us", "policyengine_version": POLICYENGINE_VERSION}, ) @@ -1070,9 +1039,9 @@ def test_postgres_a_version_stored_before_format_2_returns_the_tree_503( def test_postgres_search_file_is_served_with_its_etag_and_revalidated( - published_engine: Engine, + published_sessions: sessionmaker[Session], ) -> None: - client = _client(published_engine) + client = _client(published_sessions) expected = country_search_file(normalized_catalog().country("uk")) response = client.get( @@ -1098,12 +1067,12 @@ def test_postgres_search_file_is_served_with_its_etag_and_revalidated( def test_postgres_search_file_of_a_version_without_one_is_unavailable( - published_engine: Engine, + published_sessions: sessionmaker[Session], ) -> None: - with published_engine.begin() as connection: - connection.execute(text("DELETE FROM parameter_search_files")) + with published_sessions.begin() as session: + session.execute(sa.delete(ParameterSearchFile)) - response = _client(published_engine).get( + response = _client(published_sessions).get( "/v2/parameters/search-file", params={"country_id": "us"} ) @@ -1120,22 +1089,19 @@ def test_postgres_search_file_of_a_version_without_one_is_unavailable( def test_postgres_search_file_reads_as_the_runtime_role( - published_engine: Engine, + published_sessions: sessionmaker[Session], managed_v2_roles, - v2_engine_as_role, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> None: """The Public API's runtime role reads the file with its declared privileges.""" - runtime_engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - try: - with Session(runtime_engine) as session: - service = V2MetadataService( - MetadataDatabaseSession(session), - running_policyengine_version=POLICYENGINE_VERSION, - ) - search_file = service.get_parameter_search_file("us") - content_sha256 = service.get_parameter_search_file_hash("us") - finally: - runtime_engine.dispose() + runtime_sessions = v2_sessions_as_role(managed_v2_roles.runtime) + with runtime_sessions() as session: + service = V2MetadataService( + MetadataDatabaseSession(session), + running_policyengine_version=POLICYENGINE_VERSION, + ) + search_file = service.get_parameter_search_file("us") + content_sha256 = service.get_parameter_search_file_hash("us") assert json.loads(gzip.decompress(search_file.compressed_content)) == ( country_search_file(normalized_catalog().country("us")) @@ -1144,9 +1110,9 @@ def test_postgres_search_file_reads_as_the_runtime_role( def test_postgres_search_file_of_an_unknown_catalog_version_is_absent( - published_engine: Engine, + published_sessions: sessionmaker[Session], ) -> None: - response = _client(published_engine).get( + response = _client(published_sessions).get( "/v2/parameters/search-file", params={"country_id": "us", "policyengine_version": "99.0.0"}, ) diff --git a/tests/integration/test_v2_policy_persistence.py b/tests/integration/test_v2_policy_persistence.py index 7597f5c3d..4d756c8c7 100644 --- a/tests/integration/test_v2_policy_persistence.py +++ b/tests/integration/test_v2_policy_persistence.py @@ -2,20 +2,15 @@ from __future__ import annotations -import os from concurrent.futures import ThreadPoolExecutor from threading import Barrier +from typing import TYPE_CHECKING from uuid import UUID, uuid4 import pytest -from sqlalchemy import create_engine, delete, func, select +from sqlalchemy import delete, func, select from sqlalchemy.exc import IntegrityError -from sqlmodel import Session -from policyengine_api.data.v2.migration_target import ( - V2_ALEMBIC_DISPOSABLE_TEST, - load_v2_alembic_settings, -) from policyengine_api.data.v2.models import ( LegacyPolicyMapping, Parameter, @@ -24,7 +19,6 @@ TaxBenefitModel, TaxBenefitModelVersion, ) -from policyengine_api.data.v2.settings import V2_MIGRATION_DATABASE_URL from policyengine_api.services.v2.policies.services import ( create_resolved_policy, mirror_legacy_policy_in_session, @@ -43,23 +37,9 @@ PolicyContentHashCollisionError, ) - -def _disposable_url() -> str: - database_url = os.environ.get(V2_MIGRATION_DATABASE_URL, "") - if not database_url: - pytest.skip(f"{V2_MIGRATION_DATABASE_URL} is not set") - settings = load_v2_alembic_settings( - { - V2_MIGRATION_DATABASE_URL: database_url, - V2_ALEMBIC_DISPOSABLE_TEST: os.environ.get( - V2_ALEMBIC_DISPOSABLE_TEST, - "", - ), - } - ) - if not settings.disposable_test: - pytest.fail("policy persistence tests require disposable-test mode") - return settings.url.render_as_string(hide_password=False) +if TYPE_CHECKING: + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session def _catalog(session: Session, *, country_id: str | None = None): @@ -108,56 +88,53 @@ def _command( ) -def _cleanup(engine, model_id: UUID) -> None: - with engine.begin() as connection: +def _cleanup(v2_owner_sessions: sessionmaker[Session], model_id: UUID) -> None: + with v2_owner_sessions.begin() as session: policy_ids = select(Policy.id).where(Policy.tax_benefit_model_id == model_id) - connection.execute( + session.execute( delete(LegacyPolicyMapping).where( LegacyPolicyMapping.policy_id.in_(policy_ids) ) ) - connection.execute( + session.execute( delete(ParameterValue).where(ParameterValue.policy_id.in_(policy_ids)) ) - connection.execute( - delete(Policy).where(Policy.tax_benefit_model_id == model_id) - ) + session.execute(delete(Policy).where(Policy.tax_benefit_model_id == model_id)) version_ids = select(TaxBenefitModelVersion.id).where( TaxBenefitModelVersion.model_id == model_id ) - connection.execute( + session.execute( delete(Parameter).where( Parameter.tax_benefit_model_version_id.in_(version_ids) ) ) - connection.execute( + session.execute( delete(TaxBenefitModelVersion).where( TaxBenefitModelVersion.model_id == model_id ) ) - connection.execute( - delete(TaxBenefitModel).where(TaxBenefitModel.id == model_id) - ) + session.execute(delete(TaxBenefitModel).where(TaxBenefitModel.id == model_id)) -def test_equivalent_create_returns_one_policy_and_one_child_set() -> None: - engine = create_engine(_disposable_url()) +def test_equivalent_create_returns_one_policy_and_one_child_set( + v2_owner_sessions: sessionmaker[Session], +) -> None: model_id = None try: - with Session(engine) as session, session.begin(): + with v2_owner_sessions.begin() as session: model, version, parameter = _catalog(session) model_id = model.id command = _command(model.id, version.id, parameter.id) first = create_resolved_policy(session, command) - with Session(engine) as session, session.begin(): + with v2_owner_sessions.begin() as session: second = create_resolved_policy(session, command) assert first.created is True assert second.created is False assert second.policy_id == first.policy_id - with Session(engine) as session: + with v2_owner_sessions() as session: policy_count = session.scalar( select(func.count()) .select_from(Policy) @@ -171,15 +148,15 @@ def test_equivalent_create_returns_one_policy_and_one_child_set() -> None: assert (policy_count, value_count) == (1, 1) finally: if model_id is not None: - _cleanup(engine, model_id) - engine.dispose() + _cleanup(v2_owner_sessions, model_id) -def test_equal_hash_with_different_canonical_bytes_is_an_integrity_error() -> None: - engine = create_engine(_disposable_url()) +def test_equal_hash_with_different_canonical_bytes_is_an_integrity_error( + v2_owner_sessions: sessionmaker[Session], +) -> None: model_id = None try: - with Session(engine) as session, session.begin(): + with v2_owner_sessions.begin() as session: model, version, parameter = _catalog(session) model_id = model.id version_id = version.id @@ -200,8 +177,7 @@ def simulated_collision( ) with ( - Session(engine) as session, - session.begin(), + v2_owner_sessions.begin() as session, pytest.raises(PolicyContentHashCollisionError), ): create_resolved_policy( @@ -210,7 +186,7 @@ def simulated_collision( canonicalizer=simulated_collision, ) - with Session(engine) as session: + with v2_owner_sessions() as session: values = session.scalars( select(ParameterValue.value_json) .join( @@ -222,15 +198,15 @@ def simulated_collision( assert values == [0.2] finally: if model_id is not None: - _cleanup(engine, model_id) - engine.dispose() + _cleanup(v2_owner_sessions, model_id) -def test_legacy_policy_mapping_is_many_to_one_and_retry_safe() -> None: - engine = create_engine(_disposable_url()) +def test_legacy_policy_mapping_is_many_to_one_and_retry_safe( + v2_owner_sessions: sessionmaker[Session], +) -> None: model_id = None try: - with Session(engine) as session, session.begin(): + with v2_owner_sessions.begin() as session: model, version, parameter = _catalog(session, country_id="us") model_id = model.id first = LegacyPolicySnapshot( @@ -260,7 +236,7 @@ def test_legacy_policy_mapping_is_many_to_one_and_retry_safe() -> None: running_policyengine_version=version.version, ) - with Session(engine) as session, session.begin(): + with v2_owner_sessions.begin() as session: retry = mirror_legacy_policy_in_session( session, first, @@ -275,7 +251,7 @@ def test_legacy_policy_mapping_is_many_to_one_and_retry_safe() -> None: policy_created=False, mapping_created=False, ) - with Session(engine) as session: + with v2_owner_sessions() as session: mappings = session.scalars( select(LegacyPolicyMapping).where( LegacyPolicyMapping.policy_id == first_result.policy_id @@ -284,15 +260,15 @@ def test_legacy_policy_mapping_is_many_to_one_and_retry_safe() -> None: assert {mapping.legacy_policy_id for mapping in mappings} == {301, 302} finally: if model_id is not None: - _cleanup(engine, model_id) - engine.dispose() + _cleanup(v2_owner_sessions, model_id) -def test_changed_hash_for_one_legacy_identity_rolls_back_without_mutation() -> None: - engine = create_engine(_disposable_url()) +def test_changed_hash_for_one_legacy_identity_rolls_back_without_mutation( + v2_owner_sessions: sessionmaker[Session], +) -> None: model_id = None try: - with Session(engine) as session, session.begin(): + with v2_owner_sessions.begin() as session: model, version, parameter = _catalog(session, country_id="us") model_id = model.id parameter_name = parameter.name @@ -317,8 +293,7 @@ def test_changed_hash_for_one_legacy_identity_rolls_back_without_mutation() -> N ) with ( pytest.raises(LegacyPolicyMappingIntegrityError, match="different"), - Session(engine) as session, - session.begin(), + v2_owner_sessions.begin() as session, ): mirror_legacy_policy_in_session( session, @@ -326,7 +301,7 @@ def test_changed_hash_for_one_legacy_identity_rolls_back_without_mutation() -> N running_policyengine_version="5.2.0", ) - with Session(engine) as session: + with v2_owner_sessions() as session: mapping = session.scalar( select(LegacyPolicyMapping).where( LegacyPolicyMapping.legacy_policy_id == 401 @@ -343,15 +318,15 @@ def test_changed_hash_for_one_legacy_identity_rolls_back_without_mutation() -> N assert policy_count == 1 finally: if model_id is not None: - _cleanup(engine, model_id) - engine.dispose() + _cleanup(v2_owner_sessions, model_id) -def test_concurrent_equivalent_creates_return_one_policy_uuid() -> None: - engine = create_engine(_disposable_url()) +def test_concurrent_equivalent_creates_return_one_policy_uuid( + v2_owner_sessions: sessionmaker[Session], +) -> None: model_id = None try: - with Session(engine) as session, session.begin(): + with v2_owner_sessions.begin() as session: model, version, parameter = _catalog(session) model_id = model.id command = _command(model.id, version.id, parameter.id) @@ -359,7 +334,7 @@ def test_concurrent_equivalent_creates_return_one_policy_uuid() -> None: barrier = Barrier(2, timeout=10) def create(): - with Session(engine) as session, session.begin(): + with v2_owner_sessions.begin() as session: barrier.wait() return create_resolved_policy(session, command) @@ -369,7 +344,7 @@ def create(): assert {result.policy_id for result in results} == {results[0].policy_id} assert sorted(result.created for result in results) == [False, True] - with Session(engine) as session: + with v2_owner_sessions() as session: policy_count = session.scalar( select(func.count()) .select_from(Policy) @@ -383,15 +358,15 @@ def create(): assert (policy_count, value_count) == (1, 1) finally: if model_id is not None: - _cleanup(engine, model_id) - engine.dispose() + _cleanup(v2_owner_sessions, model_id) -def test_empty_and_distinct_policy_content_persist_independently() -> None: - engine = create_engine(_disposable_url()) +def test_empty_and_distinct_policy_content_persist_independently( + v2_owner_sessions: sessionmaker[Session], +) -> None: model_id = None try: - with Session(engine) as session, session.begin(): + with v2_owner_sessions.begin() as session: model, version, parameter = _catalog(session) model_id = model.id empty = ResolvedPolicyCreationInput( @@ -412,7 +387,7 @@ def test_empty_and_distinct_policy_content_persist_independently() -> None: ) assert len({first.policy_id, second.policy_id, third.policy_id}) == 3 - with Session(engine) as session: + with v2_owner_sessions() as session: empty_value_count = session.scalar( select(func.count()) .select_from(ParameterValue) @@ -421,15 +396,15 @@ def test_empty_and_distinct_policy_content_persist_independently() -> None: assert empty_value_count == 0 finally: if model_id is not None: - _cleanup(engine, model_id) - engine.dispose() + _cleanup(v2_owner_sessions, model_id) -def test_child_insert_failure_rolls_back_the_policy_and_all_values() -> None: - engine = create_engine(_disposable_url()) +def test_child_insert_failure_rolls_back_the_policy_and_all_values( + v2_owner_sessions: sessionmaker[Session], +) -> None: model_id = None try: - with Session(engine) as session, session.begin(): + with v2_owner_sessions.begin() as session: model, version, _parameter = _catalog(session) model_id = model.id invalid = _command(model.id, version.id, uuid4()) @@ -437,12 +412,11 @@ def test_child_insert_failure_rolls_back_the_policy_and_all_values() -> None: with ( pytest.raises(IntegrityError), - Session(engine) as session, - session.begin(), + v2_owner_sessions.begin() as session, ): create_resolved_policy(session, invalid) - with Session(engine) as session: + with v2_owner_sessions() as session: policy_count = session.scalar( select(func.count()) .select_from(Policy) @@ -457,5 +431,4 @@ def test_child_insert_failure_rolls_back_the_policy_and_all_values() -> None: assert owned_value_count == 0 finally: if model_id is not None: - _cleanup(engine, model_id) - engine.dispose() + _cleanup(v2_owner_sessions, model_id) diff --git a/tests/integration/test_v2_privilege_reconciliation.py b/tests/integration/test_v2_privilege_reconciliation.py index 4cf7dac64..af5f9be95 100644 --- a/tests/integration/test_v2_privilege_reconciliation.py +++ b/tests/integration/test_v2_privilege_reconciliation.py @@ -12,11 +12,11 @@ from uuid import uuid4 import pytest -from sqlalchemy import create_engine, text -from sqlalchemy.pool import NullPool +from sqlalchemy import func, select from policyengine_api.data.v2 import privilege_reconciliation from policyengine_api.data.v2.migration_target import V2_ALEMBIC_DISPOSABLE_TEST +from policyengine_api.data.v2.models import Region from policyengine_api.data.v2.privilege_reconciliation import ( DEPLOYMENT_ENVIRONMENT, PrivilegeEntry, @@ -28,81 +28,76 @@ ) from policyengine_api.data.v2.privileges import READ, TablePrivilege, update_columns from policyengine_api.data.v2.settings import V2_MIGRATION_DATABASE_URL +from tests.fixtures.database_sessions import create_role, drop_role, grant if TYPE_CHECKING: from collections.abc import Callable, Iterator - from sqlalchemy import Engine + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session @pytest.fixture -def superuser_engine(disposable_v2_database_url) -> Iterator[Engine]: - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - try: - yield engine - finally: - engine.dispose() - - -@pytest.fixture -def temporary_role(superuser_engine) -> Iterator[Callable[[], str]]: +def temporary_role(v2_owner_sessions) -> Iterator[Callable[[], str]]: """Return a builder of NOLOGIN roles that are dropped after the test.""" created_roles: list[str] = [] - def create_role() -> str: + def create_temporary_role() -> str: role = f"policyengine_privilege_test_{uuid4().hex[:12]}" - with superuser_engine.begin() as connection: - connection.execute(text(f'CREATE ROLE "{role}" NOLOGIN')) + with v2_owner_sessions.begin() as session: + create_role(session, role) created_roles.append(role) return role try: - yield create_role + yield create_temporary_role finally: - with superuser_engine.begin() as connection: + with v2_owner_sessions.begin() as session: for role in created_roles: - connection.execute(text(f'DROP OWNED BY "{role}"')) - connection.execute(text(f'DROP ROLE "{role}"')) + drop_role(session, role) -def _has_privilege(engine: Engine, role: str, table: str, privilege: str) -> bool: - with engine.connect() as connection: +def _has_privilege( + sessions: sessionmaker[Session], role: str, table: str, privilege: str +) -> bool: + with sessions() as session: return bool( - connection.execute( - text("SELECT has_table_privilege(:role, :table, :privilege)"), - {"role": role, "table": f"public.{table}", "privilege": privilege}, + session.execute( + select(func.has_table_privilege(role, f"public.{table}", privilege)) ).scalar_one() ) def _has_column_privilege( - engine: Engine, role: str, table: str, column: str, privilege: str + sessions: sessionmaker[Session], + role: str, + table: str, + column: str, + privilege: str, ) -> bool: - with engine.connect() as connection: + with sessions() as session: return bool( - connection.execute( - text("SELECT has_column_privilege(:role, :table, :column, :privilege)"), - { - "role": role, - "table": f"public.{table}", - "column": column, - "privilege": privilege, - }, + session.execute( + select( + func.has_column_privilege( + role, f"public.{table}", column, privilege + ) + ) ).scalar_one() ) def test_apply_grants_declared_columns_alone_and_verify_checks_them( - superuser_engine, temporary_role + v2_owner_sessions, temporary_role ) -> None: role = temporary_role() declared = {role: {"regions": READ | {update_columns("label")}}} - with superuser_engine.begin() as connection: - first_plan, _defaults = apply_declared_privileges(connection, declared) - with superuser_engine.begin() as connection: - second_plan, _defaults = apply_declared_privileges(connection, declared) - missing = check_declared_privileges(connection, declared) - overrides = check_table_wide_overrides(connection, declared) + with v2_owner_sessions.begin() as session: + first_plan, _defaults = apply_declared_privileges(session, declared) + with v2_owner_sessions.begin() as session: + second_plan, _defaults = apply_declared_privileges(session, declared) + missing = check_declared_privileges(session, declared) + overrides = check_table_wide_overrides(session, declared) assert first_plan.grants == ( PrivilegeEntry(role, "regions", "SELECT"), @@ -110,15 +105,15 @@ def test_apply_grants_declared_columns_alone_and_verify_checks_them( ) assert (second_plan.grants, second_plan.undeclared) == ((), ()) assert (missing, overrides) == ([], []) - assert _has_column_privilege(superuser_engine, role, "regions", "label", "UPDATE") + assert _has_column_privilege(v2_owner_sessions, role, "regions", "label", "UPDATE") assert not _has_column_privilege( - superuser_engine, role, "regions", "code", "UPDATE" + v2_owner_sessions, role, "regions", "code", "UPDATE" ) - assert not _has_privilege(superuser_engine, role, "regions", "UPDATE") + assert not _has_privilege(v2_owner_sessions, role, "regions", "UPDATE") def test_verify_fails_when_a_role_can_update_the_whole_table( - disposable_v2_database_url, superuser_engine, temporary_role, monkeypatch, tmp_path + disposable_v2_database_url, v2_owner_sessions, temporary_role, monkeypatch, tmp_path ) -> None: """``UPDATE`` on the whole table would let the role change every column.""" role = temporary_role() @@ -139,8 +134,8 @@ def test_verify_fails_when_a_role_can_update_the_whole_table( } apply_status = run("apply", environ=environ) - with superuser_engine.begin() as connection: - connection.execute(text(f'GRANT UPDATE ON TABLE public.regions TO "{role}"')) + with v2_owner_sessions.begin() as session: + grant(session, "UPDATE", on=Region, to=role) verify_status = run("verify", environ=environ) summary = summary_path.read_text(encoding="utf-8") @@ -152,7 +147,7 @@ def test_verify_fails_when_a_role_can_update_the_whole_table( def test_apply_revokes_a_new_tables_whole_table_update_and_verify_passes( - disposable_v2_database_url, superuser_engine, temporary_role, monkeypatch, tmp_path + disposable_v2_database_url, v2_owner_sessions, temporary_role, monkeypatch, tmp_path ) -> None: """A new table's default privileges give UPDATE on the whole table. @@ -171,16 +166,9 @@ def test_apply_revokes_a_new_tables_whole_table_update_and_verify_passes( monkeypatch.setattr( privilege_reconciliation, "ROLES_AWAITING_PROVISIONING", frozenset() ) - with superuser_engine.begin() as connection: - connection.execute( - text( - "GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE public.regions " - f'TO "{role}"' - ) - ) - connection.execute( - text(f'GRANT UPDATE (label, code) ON TABLE public.regions TO "{role}"') - ) + with v2_owner_sessions.begin() as session: + grant(session, "SELECT, INSERT, UPDATE, DELETE", on=Region, to=role) + grant(session, "UPDATE (label, code)", on=Region, to=role) summary_path = tmp_path / "summary.md" environ = { V2_MIGRATION_DATABASE_URL: disposable_v2_database_url, @@ -192,19 +180,19 @@ def test_apply_revokes_a_new_tables_whole_table_update_and_verify_passes( apply_status = run("apply", environ=environ) verify_status = run("verify", environ=environ) summary = summary_path.read_text(encoding="utf-8") - with superuser_engine.begin() as connection: - second_plan, _defaults = apply_declared_privileges(connection, declared) + with v2_owner_sessions.begin() as session: + second_plan, _defaults = apply_declared_privileges(session, declared) assert (apply_status, verify_status) == (0, 0) assert f"| `{role}` | `regions` | UPDATE, UPDATE (code) |" in summary assert f"| `{role}` | `regions` | UPDATE (label) |" in summary assert f"| `{role}` | `regions` | DELETE, INSERT |" in summary - assert not _has_privilege(superuser_engine, role, "regions", "UPDATE") - assert _has_column_privilege(superuser_engine, role, "regions", "label", "UPDATE") + assert not _has_privilege(v2_owner_sessions, role, "regions", "UPDATE") + assert _has_column_privilege(v2_owner_sessions, role, "regions", "label", "UPDATE") assert not _has_column_privilege( - superuser_engine, role, "regions", "code", "UPDATE" + v2_owner_sessions, role, "regions", "code", "UPDATE" ) - assert _has_privilege(superuser_engine, role, "regions", "DELETE") + assert _has_privilege(v2_owner_sessions, role, "regions", "DELETE") assert (second_plan.revocations, second_plan.grants) == ((), ()) @@ -233,26 +221,26 @@ def test_apply_grants_nothing_the_second_time_and_verify_passes( def test_apply_reports_an_extra_privilege_and_does_not_revoke_it( - superuser_engine, temporary_role + v2_owner_sessions, temporary_role ) -> None: role = temporary_role() declared = {role: {"regions": READ}} - with superuser_engine.begin() as connection: - first_plan, _defaults = apply_declared_privileges(connection, declared) - connection.execute(text(f'GRANT DELETE ON TABLE public.regions TO "{role}"')) - with superuser_engine.begin() as connection: - second_plan, _defaults = apply_declared_privileges(connection, declared) - missing_after_apply = check_declared_privileges(connection, declared) + with v2_owner_sessions.begin() as session: + first_plan, _defaults = apply_declared_privileges(session, declared) + grant(session, "DELETE", on=Region, to=role) + with v2_owner_sessions.begin() as session: + second_plan, _defaults = apply_declared_privileges(session, declared) + missing_after_apply = check_declared_privileges(session, declared) assert first_plan.grants == (PrivilegeEntry(role, "regions", "SELECT"),) assert second_plan.grants == () assert second_plan.undeclared == (PrivilegeEntry(role, "regions", "DELETE"),) assert missing_after_apply == [] - assert _has_privilege(superuser_engine, role, "regions", "DELETE") + assert _has_privilege(v2_owner_sessions, role, "regions", "DELETE") def test_a_missing_role_blocks_every_grant_and_fails_verification( - superuser_engine, temporary_role + v2_owner_sessions, temporary_role ) -> None: role = temporary_role() absent_role = f"policyengine_privilege_test_absent_{uuid4().hex[:12]}" @@ -260,13 +248,13 @@ def test_a_missing_role_blocks_every_grant_and_fails_verification( role: {"regions": READ}, absent_role: {"regions": frozenset({TablePrivilege.SELECT})}, } - with superuser_engine.begin() as connection: - plan, _defaults = apply_declared_privileges(connection, declared) - missing = check_declared_privileges(connection, declared) + with v2_owner_sessions.begin() as session: + plan, _defaults = apply_declared_privileges(session, declared) + missing = check_declared_privileges(session, declared) assert not plan.can_apply assert plan.missing_roles == (absent_role,) - assert not _has_privilege(superuser_engine, role, "regions", "SELECT") + assert not _has_privilege(v2_owner_sessions, role, "regions", "SELECT") assert missing == sorted( [ PrivilegeEntry(absent_role, "regions", "SELECT"), @@ -276,18 +264,18 @@ def test_a_missing_role_blocks_every_grant_and_fails_verification( def test_a_role_awaiting_creation_is_skipped_until_it_exists( - superuser_engine, temporary_role + v2_owner_sessions, temporary_role ) -> None: role = temporary_role() absent_role = f"policyengine_privilege_test_absent_{uuid4().hex[:12]}" declared = {role: {"regions": READ}, absent_role: {"regions": READ}} - with superuser_engine.begin() as connection: + with v2_owner_sessions.begin() as session: plan, _defaults = apply_declared_privileges( - connection, declared, roles_awaiting_creation={absent_role} + session, declared, roles_awaiting_creation={absent_role} ) - skipped = skipped_roles(connection, declared, {absent_role}) + skipped = skipped_roles(session, declared, {absent_role}) missing = check_declared_privileges( - connection, + session, {name: tables for name, tables in declared.items() if name not in skipped}, ) @@ -296,7 +284,7 @@ def test_a_role_awaiting_creation_is_skipped_until_it_exists( assert plan.grants == (PrivilegeEntry(role, "regions", "SELECT"),) assert skipped == (absent_role,) assert missing == [] - assert _has_privilege(superuser_engine, role, "regions", "SELECT") + assert _has_privilege(v2_owner_sessions, role, "regions", "SELECT") def test_the_deploy_steps_pass_and_name_a_role_awaiting_creation( diff --git a/tests/integration/test_v2_report_creation.py b/tests/integration/test_v2_report_creation.py index 98ef13935..a4aa33544 100644 --- a/tests/integration/test_v2_report_creation.py +++ b/tests/integration/test_v2_report_creation.py @@ -17,10 +17,6 @@ from alembic.config import Config from fastapi.testclient import TestClient from flask import Flask -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import NullPool -from sqlmodel import Session from policyengine_api.asgi_factory import create_asgi_app from policyengine_api.constants import REPO @@ -74,14 +70,16 @@ ) if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator - from sqlalchemy import Engine + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session from policyengine_api.services.v2.simulation_service.types import ( EconomyReportCreationInput, EconomySimulationCreationInput, ) + from tests.integration.conftest import ManagedV2Roles from tests.integration.stored_report_rows import CatalogRows CURRENT_VERSIONS = {"country_package_version": "1.5.0", "policyengine_version": "4.2.0"} @@ -99,7 +97,7 @@ class StoringSimulationService: keeps them in ``unstored_ids`` (a report's run in ``unstored_run_ids``). """ - engine: Engine + owner_sessions: sessionmaker[Session] catalog: CatalogRows answer_unstored: bool = False reports: list[EconomyReportCreationInput] = field(default_factory=list) @@ -116,10 +114,10 @@ def submit_report(self, report: EconomyReportCreationInput) -> SubmittedReport: report_id=self.unstored_ids[-1], report_run_id=self.unstored_run_ids[-1], ) - with self.engine.begin() as connection: - stored = store_report(connection, self.catalog) + with self.owner_sessions.begin() as session: + stored = store_report(session, self.catalog) run_ids = store_report_run( - connection, + session, self.catalog, stored, RunSettings(versions=CURRENT_VERSIONS, status="pending"), @@ -137,12 +135,12 @@ def submit_simulation( return SubmittedSimulation( simulation_id=self.unstored_ids[-1], simulation_run_id=uuid4() ) - with self.engine.begin() as connection: + with self.owner_sessions.begin() as session: simulation_id = store_simulation( - connection, self.catalog, policy_id=simulation.policy_id + session, self.catalog, policy_id=simulation.policy_id ) run_id = store_simulation_run( - connection, + session, self.catalog, simulation_id, RunSettings(versions=CURRENT_VERSIONS, status="pending"), @@ -153,27 +151,28 @@ def submit_simulation( @pytest.fixture -def owner_engine(disposable_v2_database_url: str) -> Iterator[Engine]: +def owner_sessions( + v2_owner_sessions: sessionmaker[Session], +) -> sessionmaker[Session]: command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - yield engine - engine.dispose() + return v2_owner_sessions @pytest.fixture -def catalog(owner_engine: Engine) -> Iterator[CatalogRows]: - with owner_engine.begin() as connection: - stored = store_catalog(connection, "us") +def catalog(owner_sessions: sessionmaker[Session]) -> Iterator[CatalogRows]: + with owner_sessions.begin() as session: + stored = store_catalog(session, "us") yield stored - with owner_engine.begin() as connection: - delete_catalog(connection, stored) + with owner_sessions.begin() as session: + delete_catalog(session, stored) @pytest.fixture -def runtime_sessions(managed_v2_roles, v2_engine_as_role) -> Iterator[Any]: - engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - yield sessionmaker(engine, class_=Session) - engine.dispose() +def runtime_sessions( + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], +) -> sessionmaker[Session]: + return v2_sessions_as_role(managed_v2_roles.runtime) def client_for( @@ -232,9 +231,11 @@ def report_body(policy_id: UUID) -> dict[str, Any]: def test_a_created_report_is_answered_as_the_tables_hold_it( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - simulation_service = StoringSimulationService(owner_engine, catalog) + simulation_service = StoringSimulationService(owner_sessions, catalog) response = client_for(runtime_sessions, simulation_service).post( "/v2/reports?country_id=us", json=report_body(catalog.policy_id) @@ -254,9 +255,11 @@ def test_a_created_report_is_answered_as_the_tables_hold_it( def test_a_report_naming_a_policy_the_country_does_not_store_is_not_sent( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - simulation_service = StoringSimulationService(owner_engine, catalog) + simulation_service = StoringSimulationService(owner_sessions, catalog) response = client_for(runtime_sessions, simulation_service).post( "/v2/reports?country_id=us", json=report_body(uuid4()) @@ -267,12 +270,14 @@ def test_a_report_naming_a_policy_the_country_does_not_store_is_not_sent( def test_a_created_report_that_cannot_be_read_back_answers_its_id( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: # The simulation service answered that it created the report, so the # record exists: the caller gets its ID and is not invited to submit again. simulation_service = StoringSimulationService( - owner_engine, catalog, answer_unstored=True + owner_sessions, catalog, answer_unstored=True ) response = client_for(runtime_sessions, simulation_service).post( @@ -295,10 +300,12 @@ def test_a_created_report_that_cannot_be_read_back_answers_its_id( def test_a_created_simulation_that_cannot_be_read_back_answers_its_id( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: simulation_service = StoringSimulationService( - owner_engine, catalog, answer_unstored=True + owner_sessions, catalog, answer_unstored=True ) response = client_for(runtime_sessions, simulation_service).post( @@ -325,9 +332,11 @@ def test_a_created_simulation_that_cannot_be_read_back_answers_its_id( def test_a_created_simulation_is_answered_as_the_tables_hold_it( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - simulation_service = StoringSimulationService(owner_engine, catalog) + simulation_service = StoringSimulationService(owner_sessions, catalog) response = client_for(runtime_sessions, simulation_service).post( "/v2/simulations?country_id=us", diff --git a/tests/integration/test_v2_report_reads.py b/tests/integration/test_v2_report_reads.py index dcf12be22..2456d6fd9 100644 --- a/tests/integration/test_v2_report_reads.py +++ b/tests/integration/test_v2_report_reads.py @@ -20,10 +20,6 @@ from alembic.config import Config from fastapi.testclient import TestClient from flask import Flask -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import NullPool -from sqlmodel import Session from policyengine_api.asgi_factory import create_asgi_app from policyengine_api.constants import REPO @@ -63,10 +59,12 @@ ) if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator - from sqlalchemy import Engine + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + from tests.integration.conftest import ManagedV2Roles from tests.integration.stored_report_rows import CatalogRows CURRENT_VERSIONS = {"country_package_version": "1.5.0", "policyengine_version": "4.2.0"} @@ -82,31 +80,31 @@ def current_versions(country_id: str) -> PackageVersions: @pytest.fixture -def owner_engine(disposable_v2_database_url: str) -> Iterator[Engine]: +def owner_sessions( + v2_owner_sessions: sessionmaker[Session], +) -> sessionmaker[Session]: command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - yield engine - engine.dispose() + return v2_owner_sessions @pytest.fixture -def catalogs(owner_engine: Engine) -> Iterator[dict[str, CatalogRows]]: +def catalogs(owner_sessions: sessionmaker[Session]) -> Iterator[dict[str, CatalogRows]]: """Store a US and a UK catalog, and delete them and their reports after.""" - with owner_engine.begin() as connection: - stored = { - country: store_catalog(connection, country) for country in ("us", "uk") - } + with owner_sessions.begin() as session: + stored = {country: store_catalog(session, country) for country in ("us", "uk")} yield stored - with owner_engine.begin() as connection: + with owner_sessions.begin() as session: for catalog in stored.values(): - delete_catalog(connection, catalog) + delete_catalog(session, catalog) @pytest.fixture -def client(managed_v2_roles, v2_engine_as_role) -> Iterator[TestClient]: +def client( + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], +) -> TestClient: """Serve the report and simulation routes as the runtime role.""" - runtime_engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - sessions = sessionmaker(runtime_engine, class_=Session) + sessions = v2_sessions_as_role(managed_v2_roles.runtime) dependencies = NativeRouteDependencies( readiness_probe=lambda: True, gateway_client_factory=lambda: None, @@ -124,12 +122,11 @@ def client(managed_v2_roles, v2_engine_as_role) -> Iterator[TestClient]: specification=RouteImplementation.FLASK_FALLBACK, metadata=RouteImplementation.FLASK_FALLBACK, ) - yield TestClient( + return TestClient( create_asgi_app( Flask(__name__), dependencies=dependencies, route_settings=settings ) ) - runtime_engine.dispose() def _as_json(value: Any) -> Any: @@ -142,7 +139,7 @@ def _as_json(value: Any) -> Any: ids=["us", "uk"], ) def test_a_report_reads_its_newest_unforced_success_and_that_runs_result( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalogs: dict[str, CatalogRows], client: TestClient, country: str, @@ -151,10 +148,10 @@ def test_a_report_reads_its_newest_unforced_success_and_that_runs_result( catalog = catalogs[country] forced_output = json.loads(json.dumps(output)) forced_output["budget"]["tax_revenue_impact"] = 1.0 - with owner_engine.begin() as connection: - report = store_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) newest = store_report_run( - connection, + session, catalog, report, RunSettings(versions=OLDER_VERSIONS), @@ -163,7 +160,7 @@ def test_a_report_reads_its_newest_unforced_success_and_that_runs_result( # On the same versions, the newer run is a forced re-run's, which is # never a read's default run. store_report_run( - connection, + session, catalog, report, RunSettings( @@ -202,20 +199,22 @@ def test_a_report_reads_its_newest_unforced_success_and_that_runs_result( def test_an_older_success_is_read_before_a_newer_run_still_running( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: catalog = catalogs["us"] - with owner_engine.begin() as connection: - report = store_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) store_report_run( - connection, + session, catalog, report, RunSettings(versions=OLDER_VERSIONS), result=us_economy_result(), ) store_report_run( - connection, + session, catalog, report, RunSettings( @@ -235,13 +234,15 @@ def test_an_older_success_is_read_before_a_newer_run_still_running( def test_a_failed_newest_run_says_why_without_a_result( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: catalog = catalogs["us"] - with owner_engine.begin() as connection: - report = store_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) store_report_run( - connection, + session, catalog, report, RunSettings( @@ -263,11 +264,13 @@ def test_a_failed_newest_run_says_why_without_a_result( def test_a_report_with_no_run_answers_its_definition( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: catalog = catalogs["uk"] - with owner_engine.begin() as connection: - report = store_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) response = client.get(f"/v2/reports/{report.report_id}?country_id=uk") @@ -283,10 +286,12 @@ def test_a_report_with_no_run_answers_its_definition( def test_a_report_is_not_found_in_another_country( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: - with owner_engine.begin() as connection: - report = store_report(connection, catalogs["us"]) + with owner_sessions.begin() as session: + report = store_report(session, catalogs["us"]) response = client.get(f"/v2/reports/{report.report_id}?country_id=uk") @@ -295,13 +300,15 @@ def test_a_report_is_not_found_in_another_country( def test_a_succeeded_run_without_result_rows_is_unreadable( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: catalog = catalogs["us"] - with owner_engine.begin() as connection: - report = store_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) store_report_run( - connection, catalog, report, RunSettings(versions=CURRENT_VERSIONS) + session, catalog, report, RunSettings(versions=CURRENT_VERSIONS) ) response = client.get(f"/v2/reports/{report.report_id}?country_id=us") @@ -314,21 +321,23 @@ def test_a_succeeded_run_without_result_rows_is_unreadable( def test_listing_reads_named_reports_in_the_order_asked( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: catalog = catalogs["us"] - with owner_engine.begin() as connection: - first = store_report(connection, catalog) + with owner_sessions.begin() as session: + first = store_report(session, catalog) store_report_run( - connection, + session, catalog, first, RunSettings(versions=CURRENT_VERSIONS), result=us_economy_result(), ) - second = store_report(connection, catalog) - budget_window = store_report(connection, catalog, budget_window_size=3) - other_country = store_report(connection, catalogs["uk"]) + second = store_report(session, catalog) + budget_window = store_report(session, catalog, budget_window_size=3) + other_country = store_report(session, catalogs["uk"]) named = ( second.report_id, uuid4(), @@ -361,18 +370,18 @@ def test_listing_reads_named_reports_in_the_order_asked( def test_a_simulation_reads_its_newest_run_in_its_country( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: catalog = catalogs["uk"] - with owner_engine.begin() as connection: - simulation_id = store_simulation( - connection, catalog, policy_id=catalog.policy_id - ) + with owner_sessions.begin() as session: + simulation_id = store_simulation(session, catalog, policy_id=catalog.policy_id) store_simulation_run( - connection, catalog, simulation_id, RunSettings(versions=OLDER_VERSIONS) + session, catalog, simulation_id, RunSettings(versions=OLDER_VERSIONS) ) newest_run_id = store_simulation_run( - connection, + session, catalog, simulation_id, RunSettings( @@ -401,11 +410,13 @@ def test_a_simulation_reads_its_newest_run_in_its_country( def test_a_simulation_with_no_run_answers_its_definition( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: catalog = catalogs["us"] - with owner_engine.begin() as connection: - simulation_id = store_simulation(connection, catalog, policy_id=None) + with owner_sessions.begin() as session: + simulation_id = store_simulation(session, catalog, policy_id=None) item = client.get(f"/v2/simulations/{simulation_id}?country_id=us").json()[ "result" @@ -418,13 +429,15 @@ def test_a_simulation_with_no_run_answers_its_definition( def test_of_two_unsucceeded_runs_created_together_the_larger_id_is_read( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: catalog = catalogs["us"] - with owner_engine.begin() as connection: - report = store_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) store_report_run( - connection, + session, catalog, report, RunSettings( @@ -435,7 +448,7 @@ def test_of_two_unsucceeded_runs_created_together_the_larger_id_is_read( ), ) store_report_run( - connection, + session, catalog, report, RunSettings( @@ -457,13 +470,15 @@ def test_of_two_unsucceeded_runs_created_together_the_larger_id_is_read( def test_of_two_simulation_runs_created_together_the_larger_id_is_the_newest( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: catalog = catalogs["us"] - with owner_engine.begin() as connection: - simulation_id = store_simulation(connection, catalog, policy_id=None) + with owner_sessions.begin() as session: + simulation_id = store_simulation(session, catalog, policy_id=None) store_simulation_run( - connection, + session, catalog, simulation_id, RunSettings( @@ -471,7 +486,7 @@ def test_of_two_simulation_runs_created_together_the_larger_id_is_the_newest( ), ) store_simulation_run( - connection, + session, catalog, simulation_id, RunSettings(versions=OLDER_VERSIONS, run_id=SMALLER_RUN_ID), @@ -489,22 +504,24 @@ def test_of_two_simulation_runs_created_together_the_larger_id_is_the_newest( def test_a_search_finds_the_countrys_reports_with_the_key_newest_first( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: - with owner_engine.begin() as connection: + with owner_sessions.begin() as session: older, newer = ( store_report( - connection, + session, catalogs["uk"], dataset_independent_key=DATASET_INDEPENDENT_KEY, created_at=STARTED_AT + timedelta(hours=hours), ) for hours in (1, 2) ) - store_report(connection, catalogs["uk"], dataset_independent_key="0" * 64) - store_report(connection, catalogs["uk"]) + store_report(session, catalogs["uk"], dataset_independent_key="0" * 64) + store_report(session, catalogs["uk"]) store_report( - connection, catalogs["us"], dataset_independent_key=DATASET_INDEPENDENT_KEY + session, catalogs["us"], dataset_independent_key=DATASET_INDEPENDENT_KEY ) response = client.get( @@ -527,14 +544,16 @@ def test_a_search_finds_the_countrys_reports_with_the_key_newest_first( def test_a_local_area_report_reads_its_areas_and_withheld_codes( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: output = uk_local_area_economy_result() - with owner_engine.begin() as connection: - local_areas = store_local_area_catalog(connection, catalogs["uk"]) - report = store_report(connection, local_areas) + with owner_sessions.begin() as session: + local_areas = store_local_area_catalog(session, catalogs["uk"]) + report = store_report(session, local_areas) store_report_run( - connection, + session, local_areas, report, RunSettings(versions=CURRENT_VERSIONS), @@ -555,22 +574,22 @@ def test_a_local_area_report_reads_its_areas_and_withheld_codes( @pytest.mark.parametrize("region_code", ["uk", "country/wales"], ids=["uk", "nation"]) def test_a_uk_wide_or_nation_report_on_its_own_dataset_reads_no_withheld_codes( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalogs: dict[str, CatalogRows], client: TestClient, region_code: str, ) -> None: - with owner_engine.begin() as connection: - local_areas = store_local_area_catalog(connection, catalogs["uk"]) + with owner_sessions.begin() as session: + local_areas = store_local_area_catalog(session, catalogs["uk"]) # UK-wide on the national dataset, or the catalog's Wales region. on_national_dataset = ( replace(local_areas, dataset_id=catalogs["uk"].dataset_id) if region_code == "uk" else catalogs["uk"] ) - report = store_report(connection, on_national_dataset) + report = store_report(session, on_national_dataset) store_report_run( - connection, + session, on_national_dataset, report, RunSettings(versions=CURRENT_VERSIONS), @@ -588,7 +607,9 @@ def test_a_uk_wide_or_nation_report_on_its_own_dataset_reads_no_withheld_codes( def test_a_local_area_report_with_every_area_of_a_level_withheld_reads_it_empty( - owner_engine: Engine, catalogs: dict[str, CatalogRows], client: TestClient + owner_sessions: sessionmaker[Session], + catalogs: dict[str, CatalogRows], + client: TestClient, ) -> None: output = { **uk_local_area_economy_result(), @@ -596,11 +617,11 @@ def test_a_local_area_report_with_every_area_of_a_level_withheld_reads_it_empty( "constituency_withheld_codes": ["E14001063", "W07000081"], "local_authority_withheld_codes": [], } - with owner_engine.begin() as connection: - local_areas = store_local_area_catalog(connection, catalogs["uk"]) - report = store_report(connection, local_areas) + with owner_sessions.begin() as session: + local_areas = store_local_area_catalog(session, catalogs["uk"]) + report = store_report(session, local_areas) store_report_run( - connection, + session, local_areas, report, RunSettings(versions=CURRENT_VERSIONS), diff --git a/tests/integration/test_v2_report_reads_by_run.py b/tests/integration/test_v2_report_reads_by_run.py index 729f743b1..2e0c4d00b 100644 --- a/tests/integration/test_v2_report_reads_by_run.py +++ b/tests/integration/test_v2_report_reads_by_run.py @@ -17,13 +17,10 @@ from alembic.config import Config from fastapi.testclient import TestClient from flask import Flask -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import NullPool -from sqlmodel import Session from policyengine_api.asgi_factory import create_asgi_app from policyengine_api.constants import REPO +from policyengine_api.data.v2.models import Household from policyengine_api.fastapi_routes.dependencies import NativeRouteDependencies from policyengine_api.migration_flags import ( RouteImplementation, @@ -35,7 +32,7 @@ ) from policyengine_api.services.v2.stored_reports.services import V2StoredReportService from tests.fixtures.economy_results import us_economy_result -from tests.integration.simulation_rows import insert_row +from tests.integration.simulation_rows import add_row from tests.integration.stored_report_rows import ( STARTED_AT, BudgetWindowYear, @@ -49,10 +46,12 @@ ) if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator - from sqlalchemy import Engine + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + from tests.integration.conftest import ManagedV2Roles from tests.integration.stored_report_rows import CatalogRows CURRENT_VERSIONS = {"country_package_version": "1.5.0", "policyengine_version": "4.2.0"} @@ -65,27 +64,29 @@ def current_versions(country_id: str) -> PackageVersions: @pytest.fixture -def owner_engine(disposable_v2_database_url: str) -> Iterator[Engine]: +def owner_sessions( + v2_owner_sessions: sessionmaker[Session], +) -> sessionmaker[Session]: command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - yield engine - engine.dispose() + return v2_owner_sessions @pytest.fixture -def catalog(owner_engine: Engine) -> Iterator[CatalogRows]: - with owner_engine.begin() as connection: - stored = store_catalog(connection, "us") +def catalog(owner_sessions: sessionmaker[Session]) -> Iterator[CatalogRows]: + with owner_sessions.begin() as session: + stored = store_catalog(session, "us") yield stored - with owner_engine.begin() as connection: - delete_catalog(connection, stored) + with owner_sessions.begin() as session: + delete_catalog(session, stored) @pytest.fixture -def client(managed_v2_roles, v2_engine_as_role) -> Iterator[TestClient]: +def client( + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], +) -> TestClient: """Serve the report routes as the runtime role.""" - runtime_engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - sessions = sessionmaker(runtime_engine, class_=Session) + sessions = v2_sessions_as_role(managed_v2_roles.runtime) dependencies = NativeRouteDependencies( readiness_probe=lambda: True, gateway_client_factory=lambda: None, @@ -99,28 +100,27 @@ def client(managed_v2_roles, v2_engine_as_role) -> Iterator[TestClient]: specification=RouteImplementation.FLASK_FALLBACK, metadata=RouteImplementation.FLASK_FALLBACK, ) - yield TestClient( + return TestClient( create_asgi_app( Flask(__name__), dependencies=dependencies, route_settings=settings ) ) - runtime_engine.dispose() def test_an_economy_report_is_read_with_the_run_named_rather_than_its_newest( - owner_engine: Engine, catalog: CatalogRows, client: TestClient + owner_sessions: sessionmaker[Session], catalog: CatalogRows, client: TestClient ) -> None: - with owner_engine.begin() as connection: - report = store_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) named = store_report_run( - connection, + session, catalog, report, RunSettings(versions=OLDER_VERSIONS, status="succeeded"), result=us_economy_result(), ) newest = store_report_run( - connection, + session, catalog, report, RunSettings( @@ -151,23 +151,23 @@ def test_an_economy_report_is_read_with_the_run_named_rather_than_its_newest( def test_a_run_that_is_not_one_of_the_reports_own_is_not_found( - owner_engine: Engine, catalog: CatalogRows, client: TestClient + owner_sessions: sessionmaker[Session], catalog: CatalogRows, client: TestClient ) -> None: - with owner_engine.begin() as connection: - report = store_report(connection, catalog) - store_report_run(connection, catalog, report, RunSettings(CURRENT_VERSIONS)) - other_report = store_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) + store_report_run(session, catalog, report, RunSettings(CURRENT_VERSIONS)) + other_report = store_report(session, catalog) other_run = store_report_run( - connection, catalog, other_report, RunSettings(CURRENT_VERSIONS) + session, catalog, other_report, RunSettings(CURRENT_VERSIONS) ) - window = store_report(connection, catalog, budget_window_size=2) + window = store_report(session, catalog, budget_window_size=2) window_run_id = store_budget_window_run( - connection, catalog, window, RunSettings(CURRENT_VERSIONS) + session, catalog, window, RunSettings(CURRENT_VERSIONS) ) year_run = store_report_run( - connection, + session, catalog, - store_year_simulations(connection, catalog, window, WINDOW_YEARS[0]), + store_year_simulations(session, catalog, window, WINDOW_YEARS[0]), RunSettings( CURRENT_VERSIONS, budget_window_year=BudgetWindowYear( @@ -200,10 +200,10 @@ def test_a_run_that_is_not_one_of_the_reports_own_is_not_found( def test_a_budget_window_is_read_with_the_window_run_named_and_its_years( - owner_engine: Engine, catalog: CatalogRows, client: TestClient + owner_sessions: sessionmaker[Session], catalog: CatalogRows, client: TestClient ) -> None: - with owner_engine.begin() as connection: - window = store_report(connection, catalog, budget_window_size=2) + with owner_sessions.begin() as session: + window = store_report(session, catalog, budget_window_size=2) window_run_ids = [] for days_later, status in ((0, "failed"), (1, "pending")): settings = RunSettings( @@ -211,15 +211,13 @@ def test_a_budget_window_is_read_with_the_window_run_named_and_its_years( status=status, created_at=STARTED_AT + timedelta(days=days_later), ) - window_run_id = store_budget_window_run( - connection, catalog, window, settings - ) + window_run_id = store_budget_window_run(session, catalog, window, settings) window_run_ids.append(window_run_id) for year in WINDOW_YEARS: store_report_run( - connection, + session, catalog, - store_year_simulations(connection, catalog, window, year), + store_year_simulations(session, catalog, window, year), RunSettings( versions=CURRENT_VERSIONS, status=status, @@ -245,29 +243,29 @@ def test_a_budget_window_is_read_with_the_window_run_named_and_its_years( def test_a_household_report_is_read_with_the_run_named( - owner_engine: Engine, catalog: CatalogRows, client: TestClient + owner_sessions: sessionmaker[Session], catalog: CatalogRows, client: TestClient ) -> None: - with owner_engine.begin() as connection: + with owner_sessions.begin() as session: household_id = uuid4() - insert_row( - connection, - "households", + add_row( + session, + Household, id=household_id, country_id=catalog.country, - household_data="{}", + household_data={}, canonicalization_version=1, content_hash=uuid4().hex * 2, ) catalog.household_ids.append(household_id) - report = store_report(connection, catalog, household_id=household_id) + report = store_report(session, catalog, household_id=household_id) named = store_report_run( - connection, + session, catalog, report, RunSettings(versions=OLDER_VERSIONS, status="pending"), ) store_report_run( - connection, + session, catalog, report, RunSettings( diff --git a/tests/integration/test_v2_report_runs.py b/tests/integration/test_v2_report_runs.py index 96e17b9b0..57ab7a523 100644 --- a/tests/integration/test_v2_report_runs.py +++ b/tests/integration/test_v2_report_runs.py @@ -19,13 +19,18 @@ from alembic.config import Config from fastapi.testclient import TestClient from flask import Flask -from sqlalchemy import create_engine, text -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import NullPool -from sqlmodel import Session +from sqlalchemy import delete, select, update +from sqlmodel import Session, col from policyengine_api.asgi_factory import create_asgi_app from policyengine_api.constants import REPO +from policyengine_api.data.v2.models import ( + BudgetWindowRun, + Household, + Report, + ReportRun, + User, +) from policyengine_api.fastapi_routes.dependencies import NativeRouteDependencies from policyengine_api.migration_flags import ( RouteImplementation, @@ -67,7 +72,7 @@ StoredReportDatabaseSession, ) from policyengine_api.services.v2.stored_reports.services import V2StoredReportService -from tests.integration.simulation_rows import insert_row +from tests.integration.simulation_rows import add_row from tests.integration.stored_report_rows import ( STARTED_AT, BudgetWindowYear, @@ -84,14 +89,15 @@ from tests.integration.user_report_run_support import store_signed_in_user if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator - from sqlalchemy import Connection, Engine + from sqlalchemy.orm import sessionmaker from policyengine_api.services.v2.identity.types import ( AccountPrincipal, UserPrincipal, ) + from tests.integration.conftest import ManagedV2Roles from tests.integration.stored_report_rows import CatalogRows CURRENT_VERSIONS = {"country_package_version": "1.5.0", "policyengine_version": "4.2.0"} @@ -102,41 +108,38 @@ def current_versions(country_id: str) -> PackageVersions: return PackageVersions(**CURRENT_VERSIONS) -def mark_manual(connection: Connection, run_id: UUID) -> None: +def mark_manual(session: Session, run_id: UUID) -> None: """Record the report run as a re-run, as the simulation service creates one.""" - connection.execute( - text("UPDATE report_runs SET trigger = 'manual' WHERE id = :id"), - {"id": run_id}, + session.execute( + update(ReportRun).where(col(ReportRun.id) == run_id).values(trigger="manual") ) def mark_window_manual( - connection: Connection, window_run_id: UUID, *, recalculate: bool + session: Session, window_run_id: UUID, *, recalculate: bool ) -> None: """Record the window run as a re-run, as the simulation service creates one.""" - connection.execute( - text( - "UPDATE budget_window_runs SET trigger = 'manual', recalculate = " - ":recalculate WHERE id = :id" - ), - {"id": window_run_id, "recalculate": recalculate}, + session.execute( + update(BudgetWindowRun) + .where(col(BudgetWindowRun.id) == window_run_id) + .values(trigger="manual", recalculate=recalculate) ) def store_window_run( - connection: Connection, + session: Session, catalog: CatalogRows, report: StoredReport, settings: RunSettings, years: tuple[int, ...], ) -> UUID: """Store a budget-window run and a report run of each year, with ``settings``.""" - window_run_id = store_budget_window_run(connection, catalog, report, settings) + window_run_id = store_budget_window_run(session, catalog, report, settings) for year in years: store_report_run( - connection, + session, catalog, - store_year_simulations(connection, catalog, report, year), + store_year_simulations(session, catalog, report, year), replace( settings, budget_window_year=BudgetWindowYear( @@ -159,7 +162,7 @@ class RerunningSimulationService: a budget-window run with a pending report run for each of those years. """ - engine: Engine + owner_sessions: sessionmaker[Session] catalog: CatalogRows delete_report: bool = False refusal: Exception | None = None @@ -175,13 +178,12 @@ def rerun_report(self, rerun: ReportRerunInput) -> StartedReportRun: self.open_sessions_when_asked.append(self.database_session.open_sessions) if self.refusal is not None: raise self.refusal - with self.engine.begin() as connection: - simulations = connection.execute( - text( - "SELECT baseline_simulation_id, reform_simulation_id FROM " - "reports WHERE id = :id" - ), - {"id": rerun.report_id}, + with self.owner_sessions.begin() as session: + simulations = session.execute( + select( + col(Report.baseline_simulation_id), + col(Report.reform_simulation_id), + ).where(col(Report.id) == rerun.report_id) ).one() report = StoredReport( report_id=rerun.report_id, @@ -195,66 +197,65 @@ def rerun_report(self, rerun: ReportRerunInput) -> StartedReportRun: ) if self.window_years: window_run_id = store_window_run( - connection, self.catalog, report, settings, self.window_years + session, self.catalog, report, settings, self.window_years ) - mark_window_manual(connection, window_run_id, recalculate=rerun.force) + mark_window_manual(session, window_run_id, recalculate=rerun.force) self.new_run_ids.append(window_run_id) started = StartedReportRun( - report_run_id=connection.execute( - text( - "SELECT id FROM report_runs WHERE budget_window_run_id " - "= :id ORDER BY year LIMIT 1" - ), - {"id": window_run_id}, + report_run_id=session.execute( + select(col(ReportRun.id)) + .where(col(ReportRun.budget_window_run_id) == window_run_id) + .order_by(col(ReportRun.year)) + .limit(1) ).scalar_one(), budget_window_run_id=window_run_id, ) else: - run_ids = store_report_run(connection, self.catalog, report, settings) - mark_manual(connection, run_ids.report_run_id) + run_ids = store_report_run(session, self.catalog, report, settings) + mark_manual(session, run_ids.report_run_id) self.new_run_ids.append(run_ids.report_run_id) started = StartedReportRun(report_run_id=run_ids.report_run_id) if self.delete_report: - connection.execute( - text("DELETE FROM reports WHERE id = :id"), - {"id": rerun.report_id}, - ) + session.execute(delete(Report).where(col(Report.id) == rerun.report_id)) return started @pytest.fixture -def owner_engine(disposable_v2_database_url: str) -> Iterator[Engine]: +def owner_sessions( + v2_owner_sessions: sessionmaker[Session], +) -> sessionmaker[Session]: command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - yield engine - engine.dispose() + return v2_owner_sessions @pytest.fixture -def catalog(owner_engine: Engine) -> Iterator[CatalogRows]: - with owner_engine.begin() as connection: - stored = store_catalog(connection, "us") +def catalog(owner_sessions: sessionmaker[Session]) -> Iterator[CatalogRows]: + with owner_sessions.begin() as session: + stored = store_catalog(session, "us") yield stored - with owner_engine.begin() as connection: - delete_catalog(connection, stored) + with owner_sessions.begin() as session: + delete_catalog(session, stored) @pytest.fixture -def runtime_sessions(managed_v2_roles, v2_engine_as_role) -> Iterator[Any]: - engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - yield sessionmaker(engine, class_=Session) - engine.dispose() +def runtime_sessions( + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], +) -> sessionmaker[Session]: + return v2_sessions_as_role(managed_v2_roles.runtime) @pytest.fixture -def admin(owner_engine: Engine, runtime_sessions: Any) -> Iterator[UserPrincipal]: +def admin( + owner_sessions: sessionmaker[Session], runtime_sessions: sessionmaker[Session] +) -> Iterator[UserPrincipal]: """Provision an admin user, who may force a re-run; delete it after.""" principal, user_id = store_signed_in_user( - runtime_sessions, owner_engine, user_type="admin" + runtime_sessions, owner_sessions, user_type="admin" ) yield principal - with owner_engine.begin() as connection: - connection.execute(text("DELETE FROM users WHERE id = :id"), {"id": user_id}) + with owner_sessions.begin() as session: + session.execute(delete(User).where(col(User.id) == user_id)) class CountingDatabaseSession(StoredReportDatabaseSession): @@ -324,18 +325,20 @@ def client_for( def test_a_reports_runs_are_listed_newest_first_with_their_versions( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - with owner_engine.begin() as connection: - report = store_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) first = store_report_run( - connection, + session, catalog, report, RunSettings(versions=OLDER_VERSIONS, status="succeeded"), ) failed = store_report_run( - connection, + session, catalog, report, RunSettings( @@ -345,9 +348,9 @@ def test_a_reports_runs_are_listed_newest_first_with_their_versions( error_message="The reform simulation failed", ), ) - mark_manual(connection, failed.report_run_id) + mark_manual(session, failed.report_run_id) newest = store_report_run( - connection, + session, catalog, report, RunSettings( @@ -356,16 +359,16 @@ def test_a_reports_runs_are_listed_newest_first_with_their_versions( created_at=STARTED_AT + timedelta(days=2), ), ) - mark_manual(connection, newest.report_run_id) - other_report = store_report(connection, catalog) + mark_manual(session, newest.report_run_id) + other_report = store_report(session, catalog) store_report_run( - connection, + session, catalog, other_report, RunSettings(versions=CURRENT_VERSIONS), ) client = client_for( - runtime_sessions, RerunningSimulationService(owner_engine, catalog) + runtime_sessions, RerunningSimulationService(owner_sessions, catalog) ) response = client.get(f"/v2/reports/{report.report_id}/runs?country_id=us") @@ -399,12 +402,14 @@ def test_a_reports_runs_are_listed_newest_first_with_their_versions( def test_a_report_with_no_run_lists_none( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - with owner_engine.begin() as connection: - report = store_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) client = client_for( - runtime_sessions, RerunningSimulationService(owner_engine, catalog) + runtime_sessions, RerunningSimulationService(owner_sessions, catalog) ) response = client.get(f"/v2/reports/{report.report_id}/runs?country_id=us") @@ -415,11 +420,14 @@ def test_a_report_with_no_run_lists_none( @pytest.mark.parametrize("method", ["get", "post"]) def test_another_countrys_report_or_an_unknown_one_is_not_found( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any, method: str + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], + method: str, ) -> None: - with owner_engine.begin() as connection: - report = store_report(connection, catalog) - simulation_service = RerunningSimulationService(owner_engine, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) + simulation_service = RerunningSimulationService(owner_sessions, catalog) client = client_for(runtime_sessions, simulation_service) other_country = client.request( @@ -434,44 +442,44 @@ def test_another_countrys_report_or_an_unknown_one_is_not_found( assert simulation_service.reruns == [] -def store_household_report( - connection: Connection, catalog: CatalogRows -) -> StoredReport: +def store_household_report(session: Session, catalog: CatalogRows) -> StoredReport: """Store a household and a report over it, without a run.""" household_id = uuid4() - insert_row( - connection, - "households", + add_row( + session, + Household, id=household_id, country_id=catalog.country, - household_data="{}", + household_data={}, canonicalization_version=1, content_hash=uuid4().hex * 2, ) catalog.household_ids.append(household_id) - return store_report(connection, catalog, household_id=household_id) + return store_report(session, catalog, household_id=household_id) @pytest.fixture -def household_only_uk(owner_engine: Engine) -> Iterator[CatalogRows]: +def household_only_uk(owner_sessions: sessionmaker[Session]) -> Iterator[CatalogRows]: """Make the UK household-only, store a UK catalog, and restore both after.""" - with household_only_catalog(owner_engine, "uk") as uk_catalog: + with household_only_catalog(owner_sessions, "uk") as uk_catalog: yield uk_catalog def test_a_household_reports_runs_are_listed_newest_first_with_their_versions( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - with owner_engine.begin() as connection: - report = store_household_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_household_report(session, catalog) first = store_report_run( - connection, + session, catalog, report, RunSettings(versions=OLDER_VERSIONS, status="succeeded"), ) newest = store_report_run( - connection, + session, catalog, report, RunSettings( @@ -480,9 +488,9 @@ def test_a_household_reports_runs_are_listed_newest_first_with_their_versions( created_at=STARTED_AT + timedelta(days=1), ), ) - mark_manual(connection, newest.report_run_id) + mark_manual(session, newest.report_run_id) client = client_for( - runtime_sessions, RerunningSimulationService(owner_engine, catalog) + runtime_sessions, RerunningSimulationService(owner_sessions, catalog) ) response = client.get(f"/v2/reports/{report.report_id}/runs?country_id=us") @@ -505,19 +513,21 @@ def test_a_household_reports_runs_are_listed_newest_first_with_their_versions( def test_a_household_report_runs_again_where_households_are_calculated( - owner_engine: Engine, household_only_uk: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + household_only_uk: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: # The UK here has household calculations but no economy reports, so a # household report's re-run passes only the household check. - with owner_engine.begin() as connection: - report = store_household_report(connection, household_only_uk) + with owner_sessions.begin() as session: + report = store_household_report(session, household_only_uk) first = store_report_run( - connection, + session, household_only_uk, report, RunSettings(versions=OLDER_VERSIONS, status="succeeded"), ) - simulation_service = RerunningSimulationService(owner_engine, household_only_uk) + simulation_service = RerunningSimulationService(owner_sessions, household_only_uk) client = client_for(runtime_sessions, simulation_service) response = client.post( @@ -551,18 +561,18 @@ def test_a_household_report_runs_again_where_households_are_calculated( @pytest.mark.parametrize("force", [False, True]) def test_running_a_report_again_answers_it_with_its_new_run( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], admin: UserPrincipal, force: bool, # noqa: FBT001 # pytest passes parameters positionally ) -> None: - with owner_engine.begin() as connection: - report = store_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) first = store_report_run( - connection, catalog, report, RunSettings(versions=OLDER_VERSIONS) + session, catalog, report, RunSettings(versions=OLDER_VERSIONS) ) - simulation_service = RerunningSimulationService(owner_engine, catalog) + simulation_service = RerunningSimulationService(owner_sessions, catalog) # Only an admin user may force a re-run. client = client_for( runtime_sessions, simulation_service, requester=admin if force else None @@ -599,22 +609,25 @@ def test_running_a_report_again_answers_it_with_its_new_run( def test_a_report_whose_reform_simulation_is_gone_is_left_to_the_service_to_refuse( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: # The Public API checks the policies that remain and asks the simulation # service, which refuses a report missing a simulation. - with owner_engine.begin() as connection: - report = store_report(connection, catalog) - connection.execute( - text("UPDATE reports SET reform_simulation_id = NULL WHERE id = :id"), - {"id": report.report_id}, + with owner_sessions.begin() as session: + report = store_report(session, catalog) + session.execute( + update(Report) + .where(col(Report.id) == report.report_id) + .values(reform_simulation_id=None) ) message = ( "The simulation service will not run the report again now " "(rerun_not_supported): The report has no reform simulation." ) simulation_service = RerunningSimulationService( - owner_engine, catalog, refusal=SimulationServiceConflictError(message) + owner_sessions, catalog, refusal=SimulationServiceConflictError(message) ) client = client_for(runtime_sessions, simulation_service) @@ -628,12 +641,14 @@ def test_a_report_whose_reform_simulation_is_gone_is_left_to_the_service_to_refu def test_a_new_run_whose_report_cannot_be_read_back_answers_the_reports_id( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - with owner_engine.begin() as connection: - report = store_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) simulation_service = RerunningSimulationService( - owner_engine, catalog, delete_report=True + owner_sessions, catalog, delete_report=True ) response = client_for(runtime_sessions, simulation_service).post( @@ -656,13 +671,15 @@ def test_a_new_run_whose_report_cannot_be_read_back_answers_the_reports_id( def test_no_report_session_is_open_while_the_simulation_service_is_asked( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - with owner_engine.begin() as connection: - report = store_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) database_session = CountingDatabaseSession(runtime_sessions) simulation_service = RerunningSimulationService( - owner_engine, catalog, database_session=database_session + owner_sessions, catalog, database_session=database_session ) client = client_for(runtime_sessions, simulation_service, database_session) @@ -676,15 +693,17 @@ def test_no_report_session_is_open_while_the_simulation_service_is_asked( def test_the_simulation_services_refusal_is_answered_as_its_own( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: # The report exists, so the service's refusal is not mistaken for a # report that cannot be read back. - with owner_engine.begin() as connection: - report = store_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) message = "The simulation service is unavailable (503 manifest_unavailable)." simulation_service = RerunningSimulationService( - owner_engine, catalog, refusal=SimulationServiceUnavailableError(message) + owner_sessions, catalog, refusal=SimulationServiceUnavailableError(message) ) response = client_for(runtime_sessions, simulation_service).post( @@ -696,19 +715,21 @@ def test_the_simulation_services_refusal_is_answered_as_its_own( def test_a_budget_windows_runs_are_listed_newest_first_with_their_years( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - with owner_engine.begin() as connection: - window = store_report(connection, catalog, budget_window_size=2) + with owner_sessions.begin() as session: + window = store_report(session, catalog, budget_window_size=2) first_run_id = store_window_run( - connection, + session, catalog, window, RunSettings(versions=OLDER_VERSIONS, status="succeeded"), (2026, 2027), ) newest_run_id = store_window_run( - connection, + session, catalog, window, RunSettings( @@ -718,9 +739,9 @@ def test_a_budget_windows_runs_are_listed_newest_first_with_their_years( ), (2026, 2027), ) - mark_window_manual(connection, newest_run_id, recalculate=True) + mark_window_manual(session, newest_run_id, recalculate=True) client = client_for( - runtime_sessions, RerunningSimulationService(owner_engine, catalog) + runtime_sessions, RerunningSimulationService(owner_sessions, catalog) ) response = client.get(f"/v2/reports/{window.report_id}/runs?country_id=us") @@ -744,23 +765,23 @@ def test_a_budget_windows_runs_are_listed_newest_first_with_their_years( @pytest.mark.parametrize("force", [False, True]) def test_running_a_budget_window_again_answers_it_with_its_new_run( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], admin: UserPrincipal, force: bool, # noqa: FBT001 # pytest passes parameters positionally ) -> None: - with owner_engine.begin() as connection: - window = store_report(connection, catalog, budget_window_size=2) + with owner_sessions.begin() as session: + window = store_report(session, catalog, budget_window_size=2) first_run_id = store_window_run( - connection, + session, catalog, window, RunSettings(versions=OLDER_VERSIONS), (2026, 2027), ) simulation_service = RerunningSimulationService( - owner_engine, catalog, window_years=(2026, 2027) + owner_sessions, catalog, window_years=(2026, 2027) ) # Only an admin user may force a re-run. client = client_for( diff --git a/tests/integration/test_v2_saved_budget_window_reports.py b/tests/integration/test_v2_saved_budget_window_reports.py index 088710303..d071f84f0 100644 --- a/tests/integration/test_v2_saved_budget_window_reports.py +++ b/tests/integration/test_v2_saved_budget_window_reports.py @@ -1,6 +1,6 @@ """Save budget-window reports in migrated PostgreSQL. -The saved-report service runs as the Public API's runtime role. A saved +The saved-report service runs as API v1's runtime role. A saved report naming a detailed-save report gives that report's budget window as ``budget_window_years``, read from ``reports.budget_window_size`` in the write's transaction, or none for a report without a window of two or more @@ -15,10 +15,7 @@ import pytest from alembic import command from alembic.config import Config -from sqlalchemy import create_engine, delete -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import NullPool -from sqlmodel import Session +from sqlalchemy import delete from policyengine_api.constants import REPO from policyengine_api.data.v2.models import User @@ -47,50 +44,55 @@ from tests.unit.v2.user_service_support import default_legacy_references if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator from uuid import UUID - from sqlalchemy import Engine + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + from tests.integration.conftest import ManagedV2Roles from tests.integration.stored_report_rows import CatalogRows @pytest.fixture -def owner_engine(disposable_v2_database_url: str) -> Iterator[Engine]: +def owner_sessions(v2_owner_sessions: sessionmaker[Session]) -> sessionmaker[Session]: + """Return the database owner's Session factories, its schema migrated to head.""" command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - yield engine - engine.dispose() + return v2_owner_sessions @pytest.fixture -def browsers(owner_engine: Engine) -> Iterator[list[UUID]]: +def browsers(owner_sessions: sessionmaker[Session]) -> Iterator[list[UUID]]: """Signed-out browsers' user IDs; their users and saved records go afterwards.""" user_ids: list[UUID] = [] yield user_ids - with owner_engine.begin() as connection: - connection.execute(delete(User).where(User.id.in_(user_ids))) + with owner_sessions.begin() as session: + session.execute(delete(User).where(User.id.in_(user_ids))) @pytest.fixture -def catalog(owner_engine: Engine, browsers: list[UUID]) -> Iterator[CatalogRows]: +def catalog( + owner_sessions: sessionmaker[Session], browsers: list[UUID] +) -> Iterator[CatalogRows]: """Store a US catalog; delete it after the saved records that name its reports.""" - with owner_engine.begin() as connection: - stored = store_catalog(connection, "us") + with owner_sessions.begin() as session: + stored = store_catalog(session, "us") yield stored - with owner_engine.begin() as connection: - connection.execute(delete(User).where(User.id.in_(browsers))) - delete_catalog(connection, stored) + with owner_sessions.begin() as session: + session.execute(delete(User).where(User.id.in_(browsers))) + delete_catalog(session, stored) @pytest.fixture -def service(managed_v2_roles, v2_engine_as_role) -> Iterator[V2UserReportService]: - engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - sessions = sessionmaker(engine, class_=Session, expire_on_commit=False) - yield V2UserReportService( - UserReportDatabaseSession(sessions), default_legacy_references() +def service( + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], +) -> V2UserReportService: + """Return the saved-report service, its Sessions acting as API v1's runtime role.""" + return V2UserReportService( + UserReportDatabaseSession(v2_sessions_as_role(managed_v2_roles.runtime)), + default_legacy_references(), ) - engine.dispose() def browser(browsers: list[UUID]) -> UnauthenticatedPrincipal: @@ -111,15 +113,15 @@ def save( def test_a_saved_budget_window_gives_the_reports_window( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, browsers: list[UUID], service: V2UserReportService, ) -> None: - with owner_engine.begin() as connection: - window = store_report(connection, catalog, budget_window_size=10) - one_year = store_report(connection, catalog, budget_window_size=1) - economy = store_report(connection, catalog) + with owner_sessions.begin() as session: + window = store_report(session, catalog, budget_window_size=10) + one_year = store_report(session, catalog, budget_window_size=1) + economy = store_report(session, catalog) principal = browser(browsers) saved = [ @@ -143,17 +145,15 @@ def test_a_saved_budget_window_gives_the_reports_window( "window", list(DISAGREEING_WINDOWS.values()), ids=list(DISAGREEING_WINDOWS) ) def test_a_saved_report_disagreeing_with_the_reports_window_is_refused( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, browsers: list[UUID], service: V2UserReportService, window: tuple[int | None, int | None], ) -> None: budget_window_size, budget_window_years = window - with owner_engine.begin() as connection: - report = store_report( - connection, catalog, budget_window_size=budget_window_size - ) + with owner_sessions.begin() as session: + report = store_report(session, catalog, budget_window_size=budget_window_size) with pytest.raises( AssociationBudgetWindowConflictError, match=str(report.report_id) @@ -167,15 +167,15 @@ def test_a_saved_report_disagreeing_with_the_reports_window_is_refused( def test_an_update_keeps_the_saved_window_agreeing_with_its_report( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, browsers: list[UUID], service: V2UserReportService, ) -> None: - with owner_engine.begin() as connection: - window = store_report(connection, catalog, budget_window_size=10) - other_window = store_report(connection, catalog, budget_window_size=5) - economy = store_report(connection, catalog) + with owner_sessions.begin() as session: + window = store_report(session, catalog, budget_window_size=10) + other_window = store_report(session, catalog, budget_window_size=5) + economy = store_report(session, catalog) principal = browser(browsers) saved = save(service, principal, report_id=economy.report_id) @@ -214,7 +214,7 @@ def test_a_v1_saved_report_keeps_its_own_window( def test_a_succeeded_window_whose_result_cannot_be_read_can_still_be_saved( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, browsers: list[UUID], service: V2UserReportService, @@ -222,16 +222,16 @@ def test_a_succeeded_window_whose_result_cannot_be_read_can_still_be_saved( # Saving reads only the report's window size, never its figures, so a # window whose years stored no result rows is saved like any other. versions = {"country_package_version": "1.5.0", "policyengine_version": "4.2.0"} - with owner_engine.begin() as connection: - window = store_report(connection, catalog, budget_window_size=2) + with owner_sessions.begin() as session: + window = store_report(session, catalog, budget_window_size=2) window_run_id = store_budget_window_run( - connection, catalog, window, RunSettings(versions=versions) + session, catalog, window, RunSettings(versions=versions) ) for year in (2026, 2027): store_report_run( - connection, + session, catalog, - store_year_simulations(connection, catalog, window, year), + store_year_simulations(session, catalog, window, year), RunSettings( versions=versions, budget_window_year=BudgetWindowYear( diff --git a/tests/integration/test_v2_saved_detailed_save_records.py b/tests/integration/test_v2_saved_detailed_save_records.py index f73b63abc..ad1827bba 100644 --- a/tests/integration/test_v2_saved_detailed_save_records.py +++ b/tests/integration/test_v2_saved_detailed_save_records.py @@ -1,6 +1,6 @@ """Save detailed-save reports and simulations in migrated PostgreSQL. -The saved-record services run as the Public API's runtime role. A saved +The saved-record services run as API v1's runtime role. A saved report or simulation names a stored record of its country, checked with a SELECT in the write's own transaction; the database's ``RESTRICT`` foreign keys refuse one deleted between the check and the write, which is answered @@ -16,10 +16,7 @@ import pytest from alembic import command from alembic.config import Config -from sqlalchemy import create_engine, delete -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import NullPool -from sqlmodel import Session +from sqlalchemy import delete from policyengine_api.constants import REPO from policyengine_api.data.v2.models import User @@ -64,52 +61,53 @@ from tests.unit.v2.user_service_support import default_legacy_references if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator from uuid import UUID - from sqlalchemy import Engine + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + from tests.integration.conftest import ManagedV2Roles from tests.integration.stored_report_rows import CatalogRows @pytest.fixture -def owner_engine(disposable_v2_database_url: str) -> Iterator[Engine]: +def owner_sessions(v2_owner_sessions: sessionmaker[Session]) -> sessionmaker[Session]: + """Return the database owner's Session factories, its schema migrated to head.""" command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - yield engine - engine.dispose() + return v2_owner_sessions @pytest.fixture -def browsers(owner_engine: Engine) -> Iterator[list[UUID]]: +def browsers(owner_sessions: sessionmaker[Session]) -> Iterator[list[UUID]]: """Signed-out browsers' user IDs; their users and saved records go afterwards.""" user_ids: list[UUID] = [] yield user_ids - with owner_engine.begin() as connection: - connection.execute(delete(User).where(User.id.in_(user_ids))) + with owner_sessions.begin() as session: + session.execute(delete(User).where(User.id.in_(user_ids))) @pytest.fixture def catalogs( - owner_engine: Engine, browsers: list[UUID] + owner_sessions: sessionmaker[Session], browsers: list[UUID] ) -> Iterator[dict[str, CatalogRows]]: """Store a US and a UK catalog; delete them after the records that name them.""" - with owner_engine.begin() as connection: - stored = { - country: store_catalog(connection, country) for country in ("us", "uk") - } + with owner_sessions.begin() as session: + stored = {country: store_catalog(session, country) for country in ("us", "uk")} yield stored - with owner_engine.begin() as connection: - connection.execute(delete(User).where(User.id.in_(browsers))) + with owner_sessions.begin() as session: + session.execute(delete(User).where(User.id.in_(browsers))) for catalog in stored.values(): - delete_catalog(connection, catalog) + delete_catalog(session, catalog) @pytest.fixture -def runtime_sessions(managed_v2_roles, v2_engine_as_role) -> Iterator[sessionmaker]: - engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - yield sessionmaker(engine, class_=Session, expire_on_commit=False) - engine.dispose() +def runtime_sessions( + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], +) -> sessionmaker[Session]: + """Return Session factories acting as API v1's runtime role.""" + return v2_sessions_as_role(managed_v2_roles.runtime) def browser(browsers: list[UUID]) -> UnauthenticatedPrincipal: @@ -131,13 +129,13 @@ def simulation_service(sessions: sessionmaker) -> V2UserSimulationService: def test_a_saved_report_names_a_stored_report_of_its_country( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalogs: dict[str, CatalogRows], browsers: list[UUID], runtime_sessions: sessionmaker, ) -> None: - with owner_engine.begin() as connection: - report = store_report(connection, catalogs["us"]) + with owner_sessions.begin() as session: + report = store_report(session, catalogs["us"]) service = report_service(runtime_sessions) saved = service.create_user_report( @@ -154,13 +152,13 @@ def test_a_saved_report_names_a_stored_report_of_its_country( def test_a_saved_report_naming_a_missing_or_foreign_report_is_not_found( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalogs: dict[str, CatalogRows], browsers: list[UUID], runtime_sessions: sessionmaker, ) -> None: - with owner_engine.begin() as connection: - uk_report = store_report(connection, catalogs["uk"]) + with owner_sessions.begin() as session: + uk_report = store_report(session, catalogs["uk"]) service = report_service(runtime_sessions) principal = browser(browsers) @@ -175,13 +173,13 @@ def test_a_saved_report_naming_a_missing_or_foreign_report_is_not_found( def test_a_saved_report_naming_both_references_is_refused( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalogs: dict[str, CatalogRows], browsers: list[UUID], runtime_sessions: sessionmaker, ) -> None: - with owner_engine.begin() as connection: - report = store_report(connection, catalogs["us"]) + with owner_sessions.begin() as session: + report = store_report(session, catalogs["us"]) with pytest.raises(AssociationReferenceConflictError, match="not both"): report_service(runtime_sessions).create_user_report( @@ -193,13 +191,13 @@ def test_a_saved_report_naming_both_references_is_refused( def test_a_saved_report_cannot_come_to_name_both_references( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalogs: dict[str, CatalogRows], browsers: list[UUID], runtime_sessions: sessionmaker, ) -> None: - with owner_engine.begin() as connection: - report = store_report(connection, catalogs["us"]) + with owner_sessions.begin() as session: + report = store_report(session, catalogs["us"]) service = report_service(runtime_sessions) principal = browser(browsers) by_number = service.create_user_report( @@ -228,14 +226,14 @@ def test_a_saved_report_cannot_come_to_name_both_references( def test_a_saved_report_is_repointed_only_to_a_stored_report( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalogs: dict[str, CatalogRows], browsers: list[UUID], runtime_sessions: sessionmaker, ) -> None: - with owner_engine.begin() as connection: - first = store_report(connection, catalogs["us"]) - second = store_report(connection, catalogs["us"]) + with owner_sessions.begin() as session: + first = store_report(session, catalogs["us"]) + second = store_report(session, catalogs["us"]) service = report_service(runtime_sessions) principal = browser(browsers) saved = service.create_user_report( @@ -285,13 +283,13 @@ def test_a_report_gone_after_the_check_is_refused_by_its_foreign_key( def test_a_report_gone_before_a_repoint_is_refused_by_its_foreign_key( monkeypatch: pytest.MonkeyPatch, - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalogs: dict[str, CatalogRows], browsers: list[UUID], runtime_sessions: sessionmaker, ) -> None: - with owner_engine.begin() as connection: - report = store_report(connection, catalogs["us"]) + with owner_sessions.begin() as session: + report = store_report(session, catalogs["us"]) service = report_service(runtime_sessions) principal = browser(browsers) saved = service.create_user_report( @@ -322,16 +320,14 @@ def test_a_report_gone_before_a_repoint_is_refused_by_its_foreign_key( def test_a_saved_simulation_names_a_stored_simulation_of_its_country( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalogs: dict[str, CatalogRows], browsers: list[UUID], runtime_sessions: sessionmaker, ) -> None: - with owner_engine.begin() as connection: - simulation_id = store_simulation(connection, catalogs["uk"], policy_id=None) - other_simulation_id = store_simulation( - connection, catalogs["uk"], policy_id=None - ) + with owner_sessions.begin() as session: + simulation_id = store_simulation(session, catalogs["uk"], policy_id=None) + other_simulation_id = store_simulation(session, catalogs["uk"], policy_id=None) service = simulation_service(runtime_sessions) principal = browser(browsers) @@ -354,13 +350,13 @@ def test_a_saved_simulation_names_a_stored_simulation_of_its_country( def test_a_saved_simulation_of_another_country_or_none_is_not_found( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalogs: dict[str, CatalogRows], browsers: list[UUID], runtime_sessions: sessionmaker, ) -> None: - with owner_engine.begin() as connection: - uk_simulation_id = store_simulation(connection, catalogs["uk"], policy_id=None) + with owner_sessions.begin() as session: + uk_simulation_id = store_simulation(session, catalogs["uk"], policy_id=None) service = simulation_service(runtime_sessions) principal = browser(browsers) @@ -377,13 +373,13 @@ def test_a_saved_simulation_of_another_country_or_none_is_not_found( def test_a_saved_simulation_never_names_both_references( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalogs: dict[str, CatalogRows], browsers: list[UUID], runtime_sessions: sessionmaker, ) -> None: - with owner_engine.begin() as connection: - simulation_id = store_simulation(connection, catalogs["us"], policy_id=None) + with owner_sessions.begin() as session: + simulation_id = store_simulation(session, catalogs["us"], policy_id=None) service = simulation_service(runtime_sessions) principal = browser(browsers) by_number = service.create_user_simulation( @@ -435,13 +431,13 @@ def test_a_simulation_gone_after_the_check_is_refused_by_its_foreign_key( def test_a_simulation_gone_before_a_repoint_is_refused_by_its_foreign_key( monkeypatch: pytest.MonkeyPatch, - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalogs: dict[str, CatalogRows], browsers: list[UUID], runtime_sessions: sessionmaker, ) -> None: - with owner_engine.begin() as connection: - simulation_id = store_simulation(connection, catalogs["uk"], policy_id=None) + with owner_sessions.begin() as session: + simulation_id = store_simulation(session, catalogs["uk"], policy_id=None) service = simulation_service(runtime_sessions) principal = browser(browsers) saved = service.create_user_simulation( diff --git a/tests/integration/test_v2_shared_report_rows.py b/tests/integration/test_v2_shared_report_rows.py index b193f347e..c3c6e9a3a 100644 --- a/tests/integration/test_v2_shared_report_rows.py +++ b/tests/integration/test_v2_shared_report_rows.py @@ -7,149 +7,297 @@ request for a report run. Each statement runs as the role that runs it in staging and production, holding only its declared privileges (``policyengine_api/data/v2/privileges.py``). + +Every statement runs through one Session of the database's owner, which +``act_as`` switches to a role for the rest of its transaction and +``act_as_owner`` returns to the owner. The partial indexes' conditions are +sent as literals, as the indexes hold them, so PostgreSQL matches the index +however often a statement runs. """ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any from uuid import UUID, uuid4 import pytest from alembic import command from alembic.config import Config -from sqlalchemy import create_engine, text +from sqlalchemy import ( + and_, + bindparam, + delete, + func, + insert, + not_, + select, + true, + update, +) +from sqlalchemy.dialects import postgresql from sqlalchemy.exc import IntegrityError, ProgrammingError -from sqlalchemy.pool import NullPool +from sqlmodel import col from policyengine_api.constants import REPO +from policyengine_api.data.v2.models import ( + BudgetWindowRun, + Report, + ReportRun, + ReportRunStatus, + Simulation, + SimulationRun, + SimulationStatus, + User, + UserReportRunAssociation, +) +from tests.fixtures.database_sessions import act_as, act_as_owner, query_plan from tests.integration.simulation_rows import ( RUN_VERSIONS, PublicApiRows, + add_row, insert_public_api_rows, - insert_row, refused, ) if TYPE_CHECKING: from collections.abc import Iterator - from sqlalchemy import Connection + from sqlalchemy import Executable, Update + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + from tests.integration.conftest import ManagedV2Roles # SHA-256 digests, as the simulation service computes keys. NATIONAL_KEY = "4bb1299756cb0a89" * 4 LOCAL_AREA_KEY = "907455a2702b0559" * 4 DATASET_INDEPENDENT_KEY = "bcabc98b4e0d3eff" * 4 NEWER_VERSIONS = {"country_package_version": "1.1.0", "policyengine_version": "4.1.0"} +# The keyed tables' mapped classes, by the table names the key tests use. +KEYED_MODELS: dict[str, type[Any]] = { + "simulations": Simulation, + "reports": Report, +} + + +def _unfailed(status: Any, failed_status: str) -> Any: + """Return ``status <> 'failed'``, with the failed status sent as a literal.""" + return status != bindparam("failed_status", failed_status, literal_execute=True) + # What the simulation service will send: a new row, or nothing when one with # the same key, or an unfailed unforced run on the same versions, exists. -FIND_OR_CREATE_SIMULATION = ( - "INSERT INTO simulations (id, simulation_type, dataset_id, " - "tax_benefit_model_version_id, year, key_version, definition_key) " - "VALUES (:id, 'economy', :dataset_id, :version_id, 2026, 1, :key) " - "ON CONFLICT (key_version, definition_key) DO NOTHING RETURNING id" -) -FIND_OR_CREATE_REPORT = ( - "INSERT INTO reports (id, label, country, tax_benefit_model_id, year, inputs, " - "key_version, definition_key, dataset_independent_key) " - "VALUES (:id, 'Report', 'us', :model_id, 2026, '{}', 1, :key, " - ":dataset_independent_key) " - "ON CONFLICT (key_version, definition_key) DO NOTHING RETURNING id" -) -FIND_OR_CREATE_SIMULATION_RUN = ( - "INSERT INTO simulation_runs (id, simulation_id, year, " - "tax_benefit_model_version_id, country_package_version, " - "policyengine_version, status, forced) " - "VALUES (:id, :simulation_id, :year, :version_id, :country_package_version, " - ":policyengine_version, 'pending', :forced) " - "ON CONFLICT (simulation_id, year, tax_benefit_model_version_id, " - "country_package_version, policyengine_version) " - "WHERE status <> 'failed' AND NOT forced DO NOTHING RETURNING id" -) -FIND_OR_CREATE_REPORT_RUN = ( - "INSERT INTO report_runs (id, report_id, baseline_simulation_run_id, " - "country_package_version, policyengine_version, status, trigger, forced) " - "VALUES (:id, :report_id, :baseline_run_id, :country_package_version, " - ":policyengine_version, 'pending', 'initial', :forced) " - "ON CONFLICT (report_id, country_package_version, policyengine_version) " - "WHERE budget_window_run_id IS NULL AND status <> 'failed' AND NOT forced " - "DO NOTHING RETURNING id" -) -FIND_OR_CREATE_WINDOW_RUN = ( - "INSERT INTO budget_window_runs (id, report_id, tax_benefit_model_version_id, " - "policyengine_version, trigger, recalculate, status) " - "VALUES (:id, :report_id, :version_id, :policyengine_version, 'initial', " - ":recalculate, 'pending') " - "ON CONFLICT (report_id, tax_benefit_model_version_id, policyengine_version) " - "WHERE status <> 'failed' AND NOT recalculate DO NOTHING RETURNING id" -) -RECORD_REQUEST = ( - "INSERT INTO user_report_run_associations (id, user_id, report_run_id, " - "requested_at, trigger) VALUES (:id, :user_id, :report_run_id, now(), :trigger)" -) +def _find_or_create_simulation(public_api_rows: PublicApiRows, key: str) -> Executable: + return ( + postgresql.insert(Simulation) + .values( + id=uuid4(), + simulation_type="economy", + dataset_id=public_api_rows.dataset_id, + tax_benefit_model_version_id=public_api_rows.version_id, + year=2026, + key_version=1, + definition_key=key, + ) + .on_conflict_do_nothing( + index_elements=[col(Simulation.key_version), col(Simulation.definition_key)] + ) + .returning(col(Simulation.id)) + ) + + +def _find_or_create_report(public_api_rows: PublicApiRows, key: str) -> Executable: + return ( + postgresql.insert(Report) + .values( + id=uuid4(), + label="Report", + country="us", + tax_benefit_model_id=public_api_rows.model_id, + year=2026, + inputs={}, + key_version=1, + definition_key=key, + dataset_independent_key=DATASET_INDEPENDENT_KEY, + ) + .on_conflict_do_nothing( + index_elements=[col(Report.key_version), col(Report.definition_key)] + ) + .returning(col(Report.id)) + ) + + +def _find_or_create_simulation_run( + public_api_rows: PublicApiRows, + simulation_id: UUID, + *, + year: int, + versions: dict[str, str], + forced: bool, +) -> Executable: + return ( + postgresql.insert(SimulationRun) + .values( + id=uuid4(), + simulation_id=simulation_id, + year=year, + tax_benefit_model_version_id=public_api_rows.version_id, + status="pending", + forced=forced, + **versions, + ) + .on_conflict_do_nothing( + index_elements=[ + col(SimulationRun.simulation_id), + col(SimulationRun.year), + col(SimulationRun.tax_benefit_model_version_id), + col(SimulationRun.country_package_version), + col(SimulationRun.policyengine_version), + ], + index_where=and_( + _unfailed(col(SimulationRun.status), SimulationStatus.FAILED), + not_(col(SimulationRun.forced)), + ), + ) + .returning(col(SimulationRun.id)) + ) + + +def _find_or_create_report_run( + report_id: UUID, + baseline_run_id: UUID | None, + *, + versions: dict[str, str], + forced: bool, +) -> Executable: + return ( + postgresql.insert(ReportRun) + .values( + id=uuid4(), + report_id=report_id, + baseline_simulation_run_id=baseline_run_id, + status="pending", + trigger="initial", + forced=forced, + **versions, + ) + .on_conflict_do_nothing( + index_elements=[ + col(ReportRun.report_id), + col(ReportRun.country_package_version), + col(ReportRun.policyengine_version), + ], + index_where=and_( + col(ReportRun.budget_window_run_id).is_(None), + _unfailed(col(ReportRun.status), ReportRunStatus.FAILED), + not_(col(ReportRun.forced)), + ), + ) + .returning(col(ReportRun.id)) + ) + + +def _find_or_create_window_run( + public_api_rows: PublicApiRows, + report_id: UUID, + *, + policyengine_version: str, + recalculate: bool, +) -> Executable: + return ( + postgresql.insert(BudgetWindowRun) + .values( + id=uuid4(), + report_id=report_id, + tax_benefit_model_version_id=public_api_rows.version_id, + policyengine_version=policyengine_version, + trigger="initial", + recalculate=recalculate, + status="pending", + ) + .on_conflict_do_nothing( + index_elements=[ + col(BudgetWindowRun.report_id), + col(BudgetWindowRun.tax_benefit_model_version_id), + col(BudgetWindowRun.policyengine_version), + ], + index_where=and_( + _unfailed(col(BudgetWindowRun.status), ReportRunStatus.FAILED), + not_(col(BudgetWindowRun.recalculate)), + ), + ) + .returning(col(BudgetWindowRun.id)) + ) + + +def _record_request( + user_id: UUID, + report_run_id: UUID | None, + trigger: str, + record_id: UUID | None = None, +) -> Executable: + """Build API v1's record of the user's request for the report run.""" + return insert(UserReportRunAssociation).values( + id=uuid4() if record_id is None else record_id, + user_id=user_id, + report_run_id=report_run_id, + requested_at=func.now(), + trigger=trigger, + ) @pytest.fixture -def connection(disposable_v2_database_url, managed_v2_roles) -> Iterator[Connection]: - """Yield a connection at head whose writes are rolled back after the test. +def session( + v2_owner_sessions: sessionmaker[Session], managed_v2_roles: ManagedV2Roles +) -> Iterator[Session]: + """Yield a Session at head whose writes are rolled back after the test. - It connects as the disposable database's superuser, which owns every - table; ``_act_as`` switches it to one managed role and ``_act_as_owner`` + It acts as the disposable database's owner (superuser), which owns every + table; ``act_as`` switches it to one managed role and ``act_as_owner`` back. """ command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - try: - with engine.connect() as database_connection: - transaction = database_connection.begin() - try: - yield database_connection - finally: - transaction.rollback() - finally: - engine.dispose() + with v2_owner_sessions() as owner_session: + try: + yield owner_session + finally: + owner_session.rollback() @pytest.fixture -def public_api_rows(connection: Connection) -> PublicApiRows: - return insert_public_api_rows(connection) +def public_api_rows(session: Session) -> PublicApiRows: + return insert_public_api_rows(session) -def _act_as(connection: Connection, role: str) -> None: - quoted_role = connection.dialect.identifier_preparer.quote(role) - connection.execute(text(f"SET LOCAL ROLE {quoted_role}")) - - -def _act_as_owner(connection: Connection) -> None: - connection.execute(text("RESET ROLE")) - - -def _inserted_id( - connection: Connection, statement: str, **values: object -) -> UUID | None: +def _inserted_id(session: Session, statement: Executable) -> UUID | None: """Run an ``INSERT ... RETURNING id``; return the new row's ID, or None.""" - return connection.execute(text(statement), values).scalar_one_or_none() + inserted: UUID | None = session.execute(statement).scalar_one_or_none() + return inserted def _refused( - connection: Connection, - statement: str, + session: Session, + statement: Executable, error: type[Exception] = IntegrityError, match: str | None = None, - **values: object, ) -> None: - with refused(connection, error, match=match): - connection.execute(text(statement), values) + with refused(session, error, match=match): + session.execute(statement) + + +def _update_row(model: type[Any], row_id: object, **values: object) -> Update: + """Build an UPDATE of the model's row with ID ``row_id``, setting ``values``.""" + return update(model).where(model.id == row_id).values(**values) def _simulation( - connection: Connection, public_api_rows: PublicApiRows, key: str | None = None + session: Session, public_api_rows: PublicApiRows, key: str | None = None ) -> UUID: """Create an economy simulation of 2026, keyed when ``key`` is given.""" simulation_id = uuid4() - insert_row( - connection, - "simulations", + add_row( + session, + Simulation, id=simulation_id, simulation_type="economy", dataset_id=public_api_rows.dataset_id, @@ -162,7 +310,7 @@ def _simulation( def _simulation_run( # noqa: PLR0913 # the simulation, then each part of its run - connection: Connection, + session: Session, public_api_rows: PublicApiRows, simulation_id: UUID, *, @@ -172,115 +320,84 @@ def _simulation_run( # noqa: PLR0913 # the simulation, then each part of its r ) -> UUID | None: """Find or create the simulation's run; return its ID if this call created it.""" return _inserted_id( - connection, - FIND_OR_CREATE_SIMULATION_RUN, - id=uuid4(), - simulation_id=simulation_id, - year=year, - version_id=public_api_rows.version_id, - forced=forced, - **versions, + session, + _find_or_create_simulation_run( + public_api_rows, simulation_id, year=year, versions=versions, forced=forced + ), ) -def _report(connection: Connection, public_api_rows: PublicApiRows) -> UUID: +def _report(session: Session, public_api_rows: PublicApiRows) -> UUID: report_id = uuid4() - insert_row( - connection, - "reports", + add_row( + session, + Report, id=report_id, label="Report", country="us", tax_benefit_model_id=public_api_rows.model_id, year=2026, - inputs="{}", + inputs={}, ) return report_id def _report_run( - connection: Connection, + session: Session, report_id: UUID, - baseline_run_id: UUID, + baseline_run_id: UUID | None, *, versions: dict[str, str] = RUN_VERSIONS, forced: bool = False, ) -> UUID | None: """Find or create the report's run; return its ID if this call created it.""" return _inserted_id( - connection, - FIND_OR_CREATE_REPORT_RUN, - id=uuid4(), - report_id=report_id, - baseline_run_id=baseline_run_id, - forced=forced, - **versions, + session, + _find_or_create_report_run( + report_id, baseline_run_id, versions=versions, forced=forced + ), ) -def _fail(connection: Connection, table: str, run_id: UUID) -> None: - connection.execute( - text( - f"UPDATE {table} SET status = 'failed', error_message = 'failed', " - "completed_at = now(), updated_at = now() WHERE id = :id" - ), - {"id": run_id}, +def _fail(session: Session, model: type[Any], run_id: UUID | None) -> None: + session.execute( + _update_row( + model, + run_id, + status="failed", + error_message="failed", + completed_at=func.now(), + updated_at=func.now(), + ) ) -def _user(connection: Connection) -> UUID: +def _user(session: Session) -> UUID: user_id = uuid4() - insert_row( - connection, "users", id=user_id, user_type="standard", primary_country="us" - ) + add_row(session, User, id=user_id, user_type="standard", primary_country="us") return user_id def test_identical_keys_name_one_simulation_and_one_report( - connection: Connection, managed_v2_roles, public_api_rows: PublicApiRows + session: Session, managed_v2_roles: ManagedV2Roles, public_api_rows: PublicApiRows ) -> None: - _act_as(connection, managed_v2_roles.simulation_service) + act_as(session, managed_v2_roles.simulation_service) simulation_id = _inserted_id( - connection, - FIND_OR_CREATE_SIMULATION, - id=uuid4(), - dataset_id=public_api_rows.dataset_id, - version_id=public_api_rows.version_id, - key=NATIONAL_KEY, + session, _find_or_create_simulation(public_api_rows, NATIONAL_KEY) ) joined_simulation = _inserted_id( - connection, - FIND_OR_CREATE_SIMULATION, - id=uuid4(), - dataset_id=public_api_rows.dataset_id, - version_id=public_api_rows.version_id, - key=NATIONAL_KEY, + session, _find_or_create_simulation(public_api_rows, NATIONAL_KEY) ) national_report = _inserted_id( - connection, - FIND_OR_CREATE_REPORT, - id=uuid4(), - model_id=public_api_rows.model_id, - key=NATIONAL_KEY, - dataset_independent_key=DATASET_INDEPENDENT_KEY, + session, _find_or_create_report(public_api_rows, NATIONAL_KEY) ) joined_report = _inserted_id( - connection, - FIND_OR_CREATE_REPORT, - id=uuid4(), - model_id=public_api_rows.model_id, - key=NATIONAL_KEY, - dataset_independent_key=DATASET_INDEPENDENT_KEY, + session, _find_or_create_report(public_api_rows, NATIONAL_KEY) ) # The local-area report is its own report, linked by the shared key. local_area_report = _inserted_id( - connection, - FIND_OR_CREATE_REPORT, - id=uuid4(), - model_id=public_api_rows.model_id, - key=LOCAL_AREA_KEY, - dataset_independent_key=DATASET_INDEPENDENT_KEY, + session, _find_or_create_report(public_api_rows, LOCAL_AREA_KEY) ) assert simulation_id is not None @@ -288,25 +405,26 @@ def test_identical_keys_name_one_simulation_and_one_report( assert national_report is not None assert joined_report is None assert local_area_report not in {None, national_report} - found = connection.execute( - text( - "SELECT id FROM simulations WHERE key_version = 1 AND definition_key = :key" - ), - {"key": NATIONAL_KEY}, + found = session.execute( + select(col(Simulation.id)).where( + col(Simulation.key_version) == 1, + col(Simulation.definition_key) == NATIONAL_KEY, + ) ).scalar_one() assert found == simulation_id - linked = connection.execute( - text("SELECT count(*) FROM reports WHERE dataset_independent_key = :key"), - {"key": DATASET_INDEPENDENT_KEY}, + linked = session.execute( + select(func.count()) + .select_from(Report) + .where(col(Report.dataset_independent_key) == DATASET_INDEPENDENT_KEY) ).scalar_one() assert linked == 2 # Rows from before the keys, and a later key format, stay apart. - assert _simulation(connection, public_api_rows) != _simulation( - connection, public_api_rows + assert _simulation(session, public_api_rows) != _simulation( + session, public_api_rows ) - insert_row( - connection, - "simulations", + add_row( + session, + Simulation, id=uuid4(), simulation_type="economy", dataset_id=public_api_rows.dataset_id, @@ -318,38 +436,29 @@ def test_identical_keys_name_one_simulation_and_one_report( def test_the_public_api_finds_reports_by_the_shared_key_alone( - connection: Connection, managed_v2_roles, public_api_rows: PublicApiRows + session: Session, managed_v2_roles: ManagedV2Roles, public_api_rows: PublicApiRows ) -> None: """The app looks a local-area report up by the national report's key. The key holds its own key version, so the lookup names the key alone, and the index on that column alone serves it. """ - _act_as(connection, managed_v2_roles.simulation_service) + act_as(session, managed_v2_roles.simulation_service) stored_report_ids = { - _inserted_id( - connection, - FIND_OR_CREATE_REPORT, - id=uuid4(), - model_id=public_api_rows.model_id, - key=key, - dataset_independent_key=DATASET_INDEPENDENT_KEY, - ) + _inserted_id(session, _find_or_create_report(public_api_rows, key)) for key in (NATIONAL_KEY, LOCAL_AREA_KEY) } - _act_as(connection, managed_v2_roles.runtime) - lookup = "SELECT id FROM reports WHERE dataset_independent_key = :key" - - found_report_ids = set( - connection.execute(text(lookup), {"key": DATASET_INDEPENDENT_KEY}).scalars() - ) - connection.execute(text("SET LOCAL enable_seqscan = off")) - plan = "\n".join( - connection.execute( - text(f"EXPLAIN {lookup}"), {"key": DATASET_INDEPENDENT_KEY} - ).scalars() + act_as(session, managed_v2_roles.runtime) + lookup = select(col(Report.id)).where( + col(Report.dataset_independent_key) == DATASET_INDEPENDENT_KEY ) + found_report_ids = set(session.execute(lookup).scalars()) + # SET LOCAL enable_seqscan = off: set_config's true keeps it to the + # transaction. + session.execute(select(func.set_config("enable_seqscan", "off", true()))) + plan = query_plan(session, lookup) + assert found_report_ids == stored_report_ids assert None not in stored_report_ids assert "using ix_reports_dataset_independent_key on reports" in plan @@ -392,7 +501,7 @@ def test_the_public_api_finds_reports_by_the_shared_key_alone( ], ) def test_a_malformed_or_incomplete_key_is_refused( - connection: Connection, + session: Session, public_api_rows: PublicApiRows, table: str, key_columns: dict[str, object], @@ -408,35 +517,31 @@ def test_a_malformed_or_incomplete_key_is_refused( "label": "Report", "country": "us", "tax_benefit_model_id": public_api_rows.model_id, - "inputs": "{}", + "inputs": {}, } ) columns |= {"id": uuid4(), "year": 2026, **key_columns} - with refused(connection, IntegrityError, match="violates check constraint"): - insert_row(connection, table, **columns) + with refused(session, IntegrityError, match="violates check constraint"): + add_row(session, KEYED_MODELS[table], **columns) def test_a_simulation_has_one_unfailed_unforced_run_per_version_set( - connection: Connection, managed_v2_roles, public_api_rows: PublicApiRows + session: Session, managed_v2_roles: ManagedV2Roles, public_api_rows: PublicApiRows ) -> None: - simulation_id = _simulation(connection, public_api_rows, NATIONAL_KEY) - _act_as(connection, managed_v2_roles.simulation_service) + simulation_id = _simulation(session, public_api_rows, NATIONAL_KEY) + act_as(session, managed_v2_roles.simulation_service) - first_run = _simulation_run(connection, public_api_rows, simulation_id) - joined = _simulation_run(connection, public_api_rows, simulation_id) - forced_run = _simulation_run( - connection, public_api_rows, simulation_id, forced=True - ) + first_run = _simulation_run(session, public_api_rows, simulation_id) + joined = _simulation_run(session, public_api_rows, simulation_id) + forced_run = _simulation_run(session, public_api_rows, simulation_id, forced=True) second_forced_run = _simulation_run( - connection, public_api_rows, simulation_id, forced=True + session, public_api_rows, simulation_id, forced=True ) newer_versions_run = _simulation_run( - connection, public_api_rows, simulation_id, versions=NEWER_VERSIONS - ) - other_year_run = _simulation_run( - connection, public_api_rows, simulation_id, year=2027 + session, public_api_rows, simulation_id, versions=NEWER_VERSIONS ) + other_year_run = _simulation_run(session, public_api_rows, simulation_id, year=2027) assert first_run is not None assert joined is None @@ -444,54 +549,53 @@ def test_a_simulation_has_one_unfailed_unforced_run_per_version_set( assert other_year_run is not None # Today's plain INSERT of a second run on the same versions is refused. _refused( - connection, - "INSERT INTO simulation_runs (id, simulation_id, year, " - "tax_benefit_model_version_id, country_package_version, " - "policyengine_version, status) VALUES (:id, :simulation_id, 2026, " - ":version_id, :country_package_version, :policyengine_version, 'pending')", + session, + insert(SimulationRun).values( + id=uuid4(), + simulation_id=simulation_id, + year=2026, + tax_benefit_model_version_id=public_api_rows.version_id, + status="pending", + **RUN_VERSIONS, + ), match="uq_simulation_runs_unfailed_unforced_versions", - id=uuid4(), - simulation_id=simulation_id, - version_id=public_api_rows.version_id, - **RUN_VERSIONS, ) # A failed run never counts: the next request creates a new run. - _act_as(connection, managed_v2_roles.modal_worker) - _fail(connection, "simulation_runs", first_run) - _act_as(connection, managed_v2_roles.simulation_service) - after_failure = _simulation_run(connection, public_api_rows, simulation_id) + act_as(session, managed_v2_roles.modal_worker) + _fail(session, SimulationRun, first_run) + act_as(session, managed_v2_roles.simulation_service) + after_failure = _simulation_run(session, public_api_rows, simulation_id) assert after_failure not in {None, first_run} # The failed run can't count again while the new one hasn't failed. - _act_as(connection, managed_v2_roles.modal_worker) + act_as(session, managed_v2_roles.modal_worker) _refused( - connection, - "UPDATE simulation_runs SET status = 'running' WHERE id = :id", + session, + _update_row(SimulationRun, first_run, status="running"), match="uq_simulation_runs_unfailed_unforced_versions", - id=first_run, ) def test_a_report_has_one_unfailed_unforced_run_per_version_set_outside_windows( - connection: Connection, managed_v2_roles, public_api_rows: PublicApiRows + session: Session, managed_v2_roles: ManagedV2Roles, public_api_rows: PublicApiRows ) -> None: - simulation_id = _simulation(connection, public_api_rows, NATIONAL_KEY) - report_id = _report(connection, public_api_rows) - _act_as(connection, managed_v2_roles.simulation_service) - baseline_run_id = _simulation_run(connection, public_api_rows, simulation_id) + simulation_id = _simulation(session, public_api_rows, NATIONAL_KEY) + report_id = _report(session, public_api_rows) + act_as(session, managed_v2_roles.simulation_service) + baseline_run_id = _simulation_run(session, public_api_rows, simulation_id) assert baseline_run_id is not None - first_run = _report_run(connection, report_id, baseline_run_id) - joined = _report_run(connection, report_id, baseline_run_id) - forced_run = _report_run(connection, report_id, baseline_run_id, forced=True) + first_run = _report_run(session, report_id, baseline_run_id) + joined = _report_run(session, report_id, baseline_run_id) + forced_run = _report_run(session, report_id, baseline_run_id, forced=True) newer_versions_run = _report_run( - connection, report_id, baseline_run_id, versions=NEWER_VERSIONS + session, report_id, baseline_run_id, versions=NEWER_VERSIONS ) # Each window run names a report run per year on the same versions. for window_run_id in (uuid4(), uuid4()): - insert_row( - connection, - "budget_window_runs", + add_row( + session, + BudgetWindowRun, id=window_run_id, report_id=report_id, tax_benefit_model_version_id=public_api_rows.version_id, @@ -499,9 +603,9 @@ def test_a_report_has_one_unfailed_unforced_run_per_version_set_outside_windows( recalculate=False, status="pending", ) - insert_row( - connection, - "report_runs", + add_row( + session, + ReportRun, id=uuid4(), report_id=report_id, budget_window_run_id=window_run_id, @@ -515,33 +619,33 @@ def test_a_report_has_one_unfailed_unforced_run_per_version_set_outside_windows( assert first_run is not None assert joined is None assert None not in {forced_run, newer_versions_run} - _act_as(connection, managed_v2_roles.modal_worker) - _fail(connection, "report_runs", first_run) - _act_as(connection, managed_v2_roles.simulation_service) - assert _report_run(connection, report_id, baseline_run_id) not in { + act_as(session, managed_v2_roles.modal_worker) + _fail(session, ReportRun, first_run) + act_as(session, managed_v2_roles.simulation_service) + assert _report_run(session, report_id, baseline_run_id) not in { None, first_run, } def test_a_budget_window_has_one_unfailed_unrecalculated_run_per_version_set( - connection: Connection, managed_v2_roles, public_api_rows: PublicApiRows + session: Session, managed_v2_roles: ManagedV2Roles, public_api_rows: PublicApiRows ) -> None: """``recalculate`` is a window run's forced marker.""" - report_id = _report(connection, public_api_rows) - _act_as(connection, managed_v2_roles.simulation_service) + report_id = _report(session, public_api_rows) + act_as(session, managed_v2_roles.simulation_service) def window_run( *, policyengine_version: str = "4.0.0", recalculate: bool = False ) -> UUID | None: return _inserted_id( - connection, - FIND_OR_CREATE_WINDOW_RUN, - id=uuid4(), - report_id=report_id, - version_id=public_api_rows.version_id, - policyengine_version=policyengine_version, - recalculate=recalculate, + session, + _find_or_create_window_run( + public_api_rows, + report_id, + policyengine_version=policyengine_version, + recalculate=recalculate, + ), ) first_run = window_run() @@ -552,49 +656,48 @@ def window_run( assert first_run is not None assert joined is None assert None not in {recalculated, newer_versions_run} - _act_as(connection, managed_v2_roles.modal_worker) - _fail(connection, "budget_window_runs", first_run) - _act_as(connection, managed_v2_roles.simulation_service) + act_as(session, managed_v2_roles.modal_worker) + _fail(session, BudgetWindowRun, first_run) + act_as(session, managed_v2_roles.simulation_service) assert window_run() not in {None, first_run} _refused( - connection, - "UPDATE budget_window_runs SET policyengine_version = '4.9.9' WHERE id = :id", + session, + _update_row(BudgetWindowRun, first_run, policyengine_version="4.9.9"), ProgrammingError, match="permission denied", - id=first_run, ) def test_the_simulation_service_writes_shared_rows_without_per_user_columns( - connection: Connection, managed_v2_roles, public_api_rows: PublicApiRows + session: Session, managed_v2_roles: ManagedV2Roles, public_api_rows: PublicApiRows ) -> None: """A report without a label, and runs without a trigger, are stored as such.""" - simulation_id = _simulation(connection, public_api_rows, NATIONAL_KEY) - _act_as(connection, managed_v2_roles.simulation_service) - baseline_run_id = _simulation_run(connection, public_api_rows, simulation_id) + simulation_id = _simulation(session, public_api_rows, NATIONAL_KEY) + act_as(session, managed_v2_roles.simulation_service) + baseline_run_id = _simulation_run(session, public_api_rows, simulation_id) report_id, report_run_id, window_run_id = uuid4(), uuid4(), uuid4() - insert_row( - connection, - "reports", + add_row( + session, + Report, id=report_id, country="us", tax_benefit_model_id=public_api_rows.model_id, year=2026, - inputs="{}", + inputs={}, ) - insert_row( - connection, - "report_runs", + add_row( + session, + ReportRun, id=report_run_id, report_id=report_id, baseline_simulation_run_id=baseline_run_id, status="pending", **RUN_VERSIONS, ) - insert_row( - connection, - "budget_window_runs", + add_row( + session, + BudgetWindowRun, id=window_run_id, report_id=report_id, tax_benefit_model_version_id=public_api_rows.version_id, @@ -602,142 +705,108 @@ def test_the_simulation_service_writes_shared_rows_without_per_user_columns( status="pending", ) - _act_as(connection, managed_v2_roles.runtime) - stored = connection.execute( - text( - "SELECT reports.label, report_runs.trigger, budget_window_runs.trigger " - "FROM reports JOIN report_runs ON report_runs.report_id = reports.id " - "JOIN budget_window_runs ON budget_window_runs.report_id = reports.id " - "WHERE reports.id = :report_id" - ), - {"report_id": report_id}, + 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) ).one() assert tuple(stored) == (None, None, None) def test_no_simulation_role_changes_a_rows_key_or_a_runs_forced_marker( - connection: Connection, managed_v2_roles, public_api_rows: PublicApiRows + session: Session, managed_v2_roles: ManagedV2Roles, public_api_rows: PublicApiRows ) -> None: - simulation_id = _simulation(connection, public_api_rows, NATIONAL_KEY) - report_id = _report(connection, public_api_rows) - _act_as(connection, managed_v2_roles.simulation_service) - run_id = _simulation_run(connection, public_api_rows, simulation_id) + simulation_id = _simulation(session, public_api_rows, NATIONAL_KEY) + report_id = _report(session, public_api_rows) + act_as(session, managed_v2_roles.simulation_service) + run_id = _simulation_run(session, public_api_rows, simulation_id) assert run_id is not None - report_run_id = _report_run(connection, report_id, run_id) + report_run_id = _report_run(session, report_id, run_id) for role in ( managed_v2_roles.simulation_service, managed_v2_roles.modal_worker, ): - _act_as(connection, role) - for statement, row_id in ( - ( - "UPDATE simulations SET definition_key = NULL WHERE id = :id", - simulation_id, - ), - ("UPDATE reports SET key_version = 1 WHERE id = :id", report_id), - ("UPDATE simulation_runs SET forced = true WHERE id = :id", run_id), - ("UPDATE report_runs SET forced = true WHERE id = :id", report_run_id), + act_as(session, role) + for statement in ( + _update_row(Simulation, simulation_id, definition_key=None), + _update_row(Report, report_id, key_version=1), + _update_row(SimulationRun, run_id, forced=True), + _update_row(ReportRun, report_run_id, forced=True), ): - _refused( - connection, - statement, - ProgrammingError, - match="permission denied", - id=row_id, - ) + _refused(session, statement, ProgrammingError, match="permission denied") def test_the_public_api_records_each_users_request_for_a_report_run( - connection: Connection, managed_v2_roles, public_api_rows: PublicApiRows + session: Session, managed_v2_roles: ManagedV2Roles, public_api_rows: PublicApiRows ) -> None: - simulation_id = _simulation(connection, public_api_rows, NATIONAL_KEY) - report_id = _report(connection, public_api_rows) - first_user, second_user, third_user = (_user(connection) for _ in range(3)) - _act_as(connection, managed_v2_roles.simulation_service) - baseline_run_id = _simulation_run(connection, public_api_rows, simulation_id) - report_run_id = _report_run(connection, report_id, baseline_run_id) - _act_as(connection, managed_v2_roles.runtime) + simulation_id = _simulation(session, public_api_rows, NATIONAL_KEY) + report_id = _report(session, public_api_rows) + first_user, second_user, third_user = (_user(session) for _ in range(3)) + act_as(session, managed_v2_roles.simulation_service) + baseline_run_id = _simulation_run(session, public_api_rows, simulation_id) + report_run_id = _report_run(session, report_id, baseline_run_id) + act_as(session, managed_v2_roles.runtime) first_record, second_record = uuid4(), uuid4() - connection.execute( - text(RECORD_REQUEST), - { - "id": first_record, - "user_id": first_user, - "report_run_id": report_run_id, - "trigger": "initial", - }, + session.execute( + _record_request(first_user, report_run_id, "initial", record_id=first_record) ) # A second user who joins the same run gets a record of their own. - connection.execute( - text(RECORD_REQUEST), - { - "id": second_record, - "user_id": second_user, - "report_run_id": report_run_id, - "trigger": "manual", - }, - ) - requesters = connection.execute( - text( - "SELECT user_id FROM user_report_run_associations " - "WHERE report_run_id = :report_run_id ORDER BY trigger" - ), - {"report_run_id": report_run_id}, + session.execute( + _record_request(second_user, report_run_id, "manual", record_id=second_record) + ) + requesters = session.execute( + select(col(UserReportRunAssociation.user_id)) + .where(col(UserReportRunAssociation.report_run_id) == report_run_id) + .order_by(col(UserReportRunAssociation.trigger)) ).scalars() assert list(requesters) == [first_user, second_user] _refused( - connection, - RECORD_REQUEST, + session, + _record_request(first_user, report_run_id, "manual"), match="uq_user_report_run_associations_user_id_report_run_id", - id=uuid4(), - user_id=first_user, - report_run_id=report_run_id, - trigger="manual", ) # A system re-run is nobody's request. _refused( - connection, - RECORD_REQUEST, + session, + _record_request(third_user, report_run_id, "system"), match="ck_user_report_run_associations_trigger", - id=uuid4(), - user_id=third_user, - report_run_id=report_run_id, - trigger="system", ) _refused( - connection, - "UPDATE user_report_run_associations SET requested_at = now() WHERE id = :id", + session, + _update_row(UserReportRunAssociation, first_record, requested_at=func.now()), ProgrammingError, match="permission denied", - id=first_record, ) - deleted = connection.execute( - text("DELETE FROM user_report_run_associations WHERE id = :id RETURNING id"), - {"id": second_record}, + deleted = session.execute( + delete(UserReportRunAssociation) + .where(col(UserReportRunAssociation.id) == second_record) + .returning(col(UserReportRunAssociation.id)) ).scalar_one() assert deleted == second_record for role in (managed_v2_roles.simulation_service, managed_v2_roles.modal_worker): - _act_as(connection, role) + act_as(session, role) _refused( - connection, - "SELECT count(*) FROM user_report_run_associations", + session, + select(func.count()).select_from(UserReportRunAssociation), ProgrammingError, match="permission denied", ) # A run a user asked for stays; the user's records go with the user. - _act_as_owner(connection) + act_as_owner(session) _refused( - connection, - "DELETE FROM report_runs WHERE id = :id", + session, + delete(ReportRun).where(col(ReportRun.id) == report_run_id), match="fk_user_report_run_associations_report_run_id_report_runs", - id=report_run_id, ) - connection.execute(text("DELETE FROM users WHERE id = :id"), {"id": first_user}) - remaining = connection.execute( - text("SELECT count(*) FROM user_report_run_associations") + session.execute(delete(User).where(col(User.id) == first_user)) + remaining = session.execute( + select(func.count()).select_from(UserReportRunAssociation) ).scalar_one() assert remaining == 0 diff --git a/tests/integration/test_v2_simulation_role_privileges.py b/tests/integration/test_v2_simulation_role_privileges.py index e64be932a..5dd0abfeb 100644 --- a/tests/integration/test_v2_simulation_role_privileges.py +++ b/tests/integration/test_v2_simulation_role_privileges.py @@ -7,82 +7,130 @@ role holds only its declared privileges (``policyengine_api/data/v2/privileges.py``), so a statement outside them fails here as it would in staging and production. + +Every statement runs through one Session of the database's owner, which +``act_as`` switches to a role for the rest of its transaction. An ORM +``update`` also sets ``updated_at`` on the tables that have it, which every +role here that updates those tables may do. """ from __future__ import annotations -from typing import TYPE_CHECKING -from uuid import uuid4 +from typing import TYPE_CHECKING, Any +from uuid import UUID, uuid4 import pytest from alembic import command from alembic.config import Config -from sqlalchemy import create_engine, text +from sqlalchemy import bindparam, delete, false, func, insert, inspect, select, update +from sqlalchemy.dialects import postgresql from sqlalchemy.exc import ProgrammingError -from sqlalchemy.pool import NullPool +from sqlmodel import col from policyengine_api.constants import REPO -from policyengine_api.data.v2.models import V2_METADATA +from policyengine_api.data.v2.models import ( + BudgetWindowRun, + CliffImpact, + Household, + HouseholdJob, + LaborSupplyDecileResponse, + ParameterValue, + Policy, + Poverty, + Report, + ReportRun, + Simulation, + SimulationRun, + SimulationStatus, + WithheldAreaCode, +) from policyengine_api.data.v2.privileges import ( CATALOG_WRITER_ROLE, ColumnPrivilege, TablePrivilege, declared_privileges, ) +from tests.fixtures.database_sessions import act_as from tests.integration.simulation_rows import ( RUN_VERSIONS, PublicApiRows, + add_row, insert_public_api_rows, - insert_row, refused, ) if TYPE_CHECKING: from collections.abc import Iterator - from sqlalchemy import Connection + from sqlalchemy import Executable, Update + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + from tests.integration.conftest import ManagedV2Roles @pytest.fixture -def connection(disposable_v2_database_url, managed_v2_roles) -> Iterator[Connection]: - """Yield a connection at head whose writes are rolled back after the test. +def session( + v2_owner_sessions: sessionmaker[Session], managed_v2_roles: ManagedV2Roles +) -> Iterator[Session]: + """Yield a Session at head whose writes are rolled back after the test. - It connects as the disposable database's superuser; ``_act_as`` switches it - to one managed role for the rest of the transaction. + It acts as the disposable database's owner (superuser); ``act_as`` + switches it to one managed role for the rest of the transaction. """ command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - try: - with engine.connect() as database_connection: - transaction = database_connection.begin() - try: - yield database_connection - finally: - transaction.rollback() - finally: - engine.dispose() + with v2_owner_sessions() as owner_session: + try: + yield owner_session + finally: + owner_session.rollback() @pytest.fixture -def public_api_rows(connection: Connection) -> PublicApiRows: - """Store, as the superuser, the Public API's rows the simulation rows name.""" - return insert_public_api_rows(connection) +def public_api_rows(session: Session) -> PublicApiRows: + """Store, as the owner, API v1's rows the simulation rows name.""" + return insert_public_api_rows(session) + +def _refused(session: Session, statement: Executable) -> None: + """Expect a permission error from ``statement``.""" + with refused(session, ProgrammingError, match="permission denied"): + session.execute(statement) -def _act_as(connection: Connection, role: str) -> None: - quoted_role = connection.dialect.identifier_preparer.quote(role) - connection.execute(text(f"SET LOCAL ROLE {quoted_role}")) +def _update_row(model: type[Any], row_id: object, **values: object) -> Update: + """Build an UPDATE of the model's row with ID ``row_id``, setting ``values``.""" + return update(model).where(model.id == row_id).values(**values) -def _refused(connection: Connection, statement: str, **values: object) -> None: - """Expect a permission error from ``statement``.""" - with refused(connection, ProgrammingError, match="permission denied"): - connection.execute(text(statement), values) + +def _update_from_status( + session: Session, + model: type[Any], + row_id: object, + current_status: str, + **values: object, +) -> object: + """Update the row while its status is ``current_status``, as the services do. + + Return its ID, from the statement's RETURNING, which expects exactly the + one row. + """ + return session.execute( + update(model) + .where(model.id == row_id, model.status == current_status) + .values(**values) + .returning(model.id) + ).scalar_one() + + +def _row_count(model: type[Any], *conditions: Any) -> Executable: + """Build a count of the model's rows that meet ``conditions``.""" + return select(func.count()).select_from(model).where(*conditions) def _create_simulation_rows( - connection: Connection, public_api_rows: PublicApiRows -) -> dict[str, object]: + session: Session, public_api_rows: PublicApiRows +) -> dict[str, UUID]: """Create what the simulation API creates for one economy report run.""" ids = { name: uuid4() @@ -95,18 +143,18 @@ def _create_simulation_rows( "household_job", ) } - insert_row( - connection, - "simulations", + add_row( + session, + Simulation, id=ids["simulation"], simulation_type="economy", dataset_id=public_api_rows.dataset_id, tax_benefit_model_version_id=public_api_rows.version_id, year=2026, ) - insert_row( - connection, - "simulation_runs", + add_row( + session, + SimulationRun, id=ids["run"], simulation_id=ids["simulation"], tax_benefit_model_version_id=public_api_rows.version_id, @@ -114,20 +162,20 @@ def _create_simulation_rows( status="pending", **RUN_VERSIONS, ) - insert_row( - connection, - "reports", + add_row( + session, + Report, id=ids["report"], label="Report", country="us", tax_benefit_model_id=public_api_rows.model_id, year=2026, budget_window_size=1, - inputs="{}", + inputs={}, ) - insert_row( - connection, - "budget_window_runs", + add_row( + session, + BudgetWindowRun, id=ids["budget_window_run"], report_id=ids["report"], tax_benefit_model_version_id=public_api_rows.version_id, @@ -135,9 +183,9 @@ def _create_simulation_rows( recalculate=False, status="pending", ) - insert_row( - connection, - "report_runs", + add_row( + session, + ReportRun, id=ids["report_run"], report_id=ids["report"], budget_window_run_id=ids["budget_window_run"], @@ -147,14 +195,14 @@ def _create_simulation_rows( trigger="initial", **RUN_VERSIONS, ) - insert_row( - connection, - "household_jobs", + add_row( + session, + HouseholdJob, id=ids["household_job"], country="us", household_id=public_api_rows.household_id, year=2026, - request_data="{}", + request_data={}, tax_benefit_model_version_id=public_api_rows.version_id, status="pending", **RUN_VERSIONS, @@ -163,183 +211,180 @@ def _create_simulation_rows( def test_the_simulation_service_creates_rows_and_records_only_its_calls( - connection: Connection, managed_v2_roles, public_api_rows: PublicApiRows + session: Session, managed_v2_roles: ManagedV2Roles, public_api_rows: PublicApiRows ) -> None: - _act_as(connection, managed_v2_roles.simulation_service) + act_as(session, managed_v2_roles.simulation_service) - ids = _create_simulation_rows(connection, public_api_rows) - run_count = connection.execute( - text("SELECT count(*) FROM simulation_runs WHERE id = :id"), {"id": ids["run"]} + ids = _create_simulation_rows(session, public_api_rows) + run_count = session.execute( + _row_count(SimulationRun, col(SimulationRun.id) == ids["run"]) ).scalar_one() - connection.execute(text("SELECT count(*) FROM policies")).scalar_one() + session.execute(_row_count(Policy)).scalar_one() assert run_count == 1 # The service records a Modal call's ID once Modal accepts the call, and # fails the run when Modal refuses it, while the run is still pending. - recorded = connection.execute( - text( - "UPDATE report_runs SET modal_call_id = 'fc-accepted', " - "updated_at = now() WHERE id = :id AND status = 'pending' " - "AND modal_call_id IS NULL RETURNING id" - ), - {"id": ids["report_run"]}, - ).scalar_one() - failed = connection.execute( - text( - "UPDATE household_jobs SET status = 'failed', error_message = 'refused', " - "completed_at = now(), updated_at = now() " - "WHERE id = :id AND status = 'pending' RETURNING id" - ), - {"id": ids["household_job"]}, + recorded = session.execute( + update(ReportRun) + .where( + col(ReportRun.id) == ids["report_run"], + col(ReportRun.status) == "pending", + col(ReportRun.modal_call_id).is_(None), + ) + .values(modal_call_id="fc-accepted", updated_at=func.now()) + .returning(col(ReportRun.id)) ).scalar_one() + failed = _update_from_status( + session, + HouseholdJob, + ids["household_job"], + "pending", + status="failed", + error_message="refused", + completed_at=func.now(), + updated_at=func.now(), + ) assert (recorded, failed) == (ids["report_run"], ids["household_job"]) for statement in ( - "UPDATE simulation_runs SET started_at = now() WHERE id = :id", - "UPDATE simulation_runs SET output_uri = 'gs://bucket/run' WHERE id = :id", - "UPDATE simulation_runs SET year = 2027 WHERE id = :id", + _update_row(SimulationRun, ids["run"], started_at=func.now()), + _update_row(SimulationRun, ids["run"], output_uri="gs://bucket/run"), + _update_row(SimulationRun, ids["run"], year=2027), + _update_row(ReportRun, ids["report_run"], baseline_cliff_gap=1.0), + insert(Poverty).values( + id=uuid4(), + simulation_run_id=ids["run"], + poverty_type="spm", + entity="person", + ), + delete(Simulation).where(col(Simulation.id) == ids["simulation"]), + insert(LaborSupplyDecileResponse).values( + id=uuid4(), report_run_id=ids["report_run"], decile=1 + ), + update(Policy).values(content_hash=col(Policy.content_hash)), ): - _refused(connection, statement, id=ids["run"]) - _refused( - connection, - "UPDATE report_runs SET baseline_cliff_gap = 1.0 WHERE id = :id", - id=ids["report_run"], - ) - _refused( - connection, - "INSERT INTO poverty (id, simulation_run_id, poverty_type, entity) " - "VALUES (:id, :run_id, 'spm', 'person')", - id=uuid4(), - run_id=ids["run"], - ) - _refused(connection, "DELETE FROM simulations WHERE id = :id", id=ids["simulation"]) - _refused( - connection, - "INSERT INTO labor_supply_decile_responses (id, report_run_id, decile) " - "VALUES (:id, :report_run_id, 1)", - id=uuid4(), - report_run_id=ids["report_run"], - ) - _refused(connection, "UPDATE policies SET content_hash = content_hash") + _refused(session, statement) def test_modal_workers_write_their_run_status_and_results_only( - connection: Connection, managed_v2_roles, public_api_rows: PublicApiRows + session: Session, managed_v2_roles: ManagedV2Roles, public_api_rows: PublicApiRows ) -> None: - _act_as(connection, managed_v2_roles.simulation_service) - ids = _create_simulation_rows(connection, public_api_rows) - _act_as(connection, managed_v2_roles.modal_worker) - - updated = connection.execute( - text( - "UPDATE simulation_runs SET status = 'succeeded', completed_at = now() " - "WHERE id = :id AND status = 'pending' RETURNING id" - ), - {"id": ids["run"]}, - ).scalar_one() - insert_row( - connection, - "poverty", + act_as(session, managed_v2_roles.simulation_service) + ids = _create_simulation_rows(session, public_api_rows) + act_as(session, managed_v2_roles.modal_worker) + + updated = _update_from_status( + session, + SimulationRun, + ids["run"], + "pending", + status="succeeded", + completed_at=func.now(), + ) + add_row( + session, + Poverty, id=uuid4(), simulation_run_id=ids["run"], poverty_type="spm", entity="person", rate=0.1, ) - connection.execute( - text( - "UPDATE report_runs SET status = 'running', started_at = now(), " - "modal_call_id = 'fc-coordinator', baseline_cliff_gap = 1.0, " - "baseline_cliff_share = 0.1, reform_cliff_gap = 2.0, " - "reform_cliff_share = 0.2, data_version = '1.0.0', " - "spm_provenance = CAST('{}' AS jsonb), updated_at = now() " - "WHERE id = :id" - ), - {"id": ids["report_run"]}, + session.execute( + _update_row( + ReportRun, + ids["report_run"], + status="running", + started_at=func.now(), + modal_call_id="fc-coordinator", + baseline_cliff_gap=1.0, + baseline_cliff_share=0.1, + reform_cliff_gap=2.0, + reform_cliff_share=0.2, + data_version="1.0.0", + spm_provenance={}, + updated_at=func.now(), + ) ) - insert_row( - connection, - "labor_supply_decile_responses", + add_row( + session, + LaborSupplyDecileResponse, id=uuid4(), report_run_id=ids["report_run"], decile=1, average_income_effect=-1.0, ) - finished_job = connection.execute( - text( - "UPDATE household_jobs SET status = 'succeeded', result = '{}', " - "completed_at = now() WHERE id = :id AND status = 'pending' " - "RETURNING id" - ), - {"id": ids["household_job"]}, - ).scalar_one() - connection.execute(text("SELECT count(*) FROM parameter_values")).scalar_one() + finished_job = _update_from_status( + session, + HouseholdJob, + ids["household_job"], + "pending", + status="succeeded", + result={}, + completed_at=func.now(), + ) + session.execute(_row_count(ParameterValue)).scalar_one() assert updated == ids["run"] assert finished_job == ids["household_job"] - _refused( - connection, - "INSERT INTO simulations (id, simulation_type, dataset_id, " - "tax_benefit_model_version_id) " - "VALUES (:id, 'economy', :dataset_id, :version_id)", - id=uuid4(), - dataset_id=uuid4(), - version_id=uuid4(), - ) - _refused( - connection, "DELETE FROM poverty WHERE simulation_run_id = :id", id=ids["run"] - ) - _refused( - connection, - "INSERT INTO budget_window_runs (id, report_id, " - "tax_benefit_model_version_id, trigger, recalculate, status) " - "VALUES (:id, :report_id, :version_id, 'manual', true, 'pending')", - id=uuid4(), - report_id=ids["report"], - version_id=public_api_rows.version_id, - ) - _refused( - connection, - "UPDATE poverty SET rate = 0 WHERE simulation_run_id = :id", - id=ids["run"], - ) - _refused(connection, "UPDATE households SET content_hash = content_hash") + for statement in ( + insert(Simulation).values( + id=uuid4(), + simulation_type="economy", + dataset_id=uuid4(), + tax_benefit_model_version_id=uuid4(), + ), + delete(Poverty).where(col(Poverty.simulation_run_id) == ids["run"]), + insert(BudgetWindowRun).values( + id=uuid4(), + report_id=ids["report"], + tax_benefit_model_version_id=public_api_rows.version_id, + trigger="manual", + recalculate=True, + status="pending", + ), + update(Poverty) + .where(col(Poverty.simulation_run_id) == ids["run"]) + .values(rate=0), + update(Household).values(content_hash=col(Household.content_hash)), + ): + _refused(session, statement) # What a run is stays as the simulation service wrote it. - for statement, run_key in ( - ("UPDATE simulation_runs SET year = 2027 WHERE id = :id", "run"), - ( - "UPDATE simulation_runs SET simulation_id = simulation_id WHERE id = :id", - "run", + for statement in ( + _update_row(SimulationRun, ids["run"], year=2027), + _update_row( + SimulationRun, ids["run"], simulation_id=col(SimulationRun.simulation_id) ), - ( - "UPDATE report_runs SET baseline_simulation_run_id = " - "baseline_simulation_run_id WHERE id = :id", - "report_run", + _update_row( + ReportRun, + ids["report_run"], + baseline_simulation_run_id=col(ReportRun.baseline_simulation_run_id), ), - ("UPDATE report_runs SET markdown = 'edited' WHERE id = :id", "report_run"), - ( - "UPDATE household_jobs SET household_id = household_id WHERE id = :id", - "household_job", + _update_row(ReportRun, ids["report_run"], markdown="edited"), + _update_row( + HouseholdJob, + ids["household_job"], + household_id=col(HouseholdJob.household_id), ), ): - _refused(connection, statement, id=ids[run_key]) + _refused(session, statement) def test_modal_workers_insert_withheld_area_codes_that_the_public_api_reads( - connection: Connection, managed_v2_roles, public_api_rows: PublicApiRows + session: Session, managed_v2_roles: ManagedV2Roles, public_api_rows: PublicApiRows ) -> None: - """The workers insert and read the rows, the Public API only reads them. + """The workers insert and read the rows, API v1 only reads them. The simulation service, the Stage 12 role and the catalog writer can't read them. """ - _act_as(connection, managed_v2_roles.simulation_service) - ids = _create_simulation_rows(connection, public_api_rows) - _act_as(connection, managed_v2_roles.modal_worker) + act_as(session, managed_v2_roles.simulation_service) + ids = _create_simulation_rows(session, public_api_rows) + act_as(session, managed_v2_roles.modal_worker) withheld_code_id = uuid4() - insert_row( - connection, - "withheld_area_codes", + add_row( + session, + WithheldAreaCode, id=withheld_code_id, report_run_id=ids["report_run"], baseline_simulation_run_id=ids["run"], @@ -348,81 +393,86 @@ def test_modal_workers_insert_withheld_area_codes_that_the_public_api_reads( code="E14001063", ) assert ( - connection.execute( - text("SELECT count(*) FROM withheld_area_codes WHERE report_run_id = :id"), - {"id": ids["report_run"]}, + session.execute( + _row_count( + WithheldAreaCode, + col(WithheldAreaCode.report_run_id) == ids["report_run"], + ) ).scalar_one() == 1 ) # Once written, a withheld code is never changed or removed by the workers. + _refused(session, _update_row(WithheldAreaCode, withheld_code_id, code="E14001064")) _refused( - connection, - "UPDATE withheld_area_codes SET code = 'E14001064' WHERE id = :id", - id=withheld_code_id, + session, + delete(WithheldAreaCode).where(col(WithheldAreaCode.id) == withheld_code_id), ) - _refused( - connection, - "DELETE FROM withheld_area_codes WHERE id = :id", - id=withheld_code_id, - ) - _act_as(connection, managed_v2_roles.runtime) + act_as(session, managed_v2_roles.runtime) assert ( - connection.execute( - text("SELECT code FROM withheld_area_codes WHERE id = :id"), - {"id": withheld_code_id}, + session.execute( + select(col(WithheldAreaCode.code)).where( + col(WithheldAreaCode.id) == withheld_code_id + ) ).scalar_one() == "E14001063" ) _refused( - connection, - "INSERT INTO withheld_area_codes (id, report_run_id, " - "baseline_simulation_run_id, reform_simulation_run_id, area_type, code) " - "VALUES (:id, :report_run_id, :run_id, :run_id, 'constituency', 'E14001064')", - id=uuid4(), - report_run_id=ids["report_run"], - run_id=ids["run"], + session, + insert(WithheldAreaCode).values( + id=uuid4(), + report_run_id=ids["report_run"], + baseline_simulation_run_id=ids["run"], + reform_simulation_run_id=ids["run"], + area_type="constituency", + code="E14001064", + ), ) for role in ( managed_v2_roles.simulation_service, managed_v2_roles.stage12, CATALOG_WRITER_ROLE, ): - _act_as(connection, role) - _refused(connection, "SELECT count(*) FROM withheld_area_codes") + act_as(session, role) + _refused(session, _row_count(WithheldAreaCode)) def test_the_simulation_service_fails_a_window_whose_first_calls_modal_refuses( - connection: Connection, managed_v2_roles, public_api_rows: PublicApiRows + session: Session, managed_v2_roles: ManagedV2Roles, public_api_rows: PublicApiRows ) -> None: """The service fails a budget-window run when Modal refuses its first years. It never sets when the window started, which the Modal workers record, and never changes what the window is. """ - _act_as(connection, managed_v2_roles.simulation_service) - ids = _create_simulation_rows(connection, public_api_rows) - - failed_window = connection.execute( - text( - "UPDATE budget_window_runs SET status = 'failed', " - "error_message = 'refused', completed_at = now(), updated_at = now() " - "WHERE id = :id AND status = 'pending' RETURNING id" - ), - {"id": ids["budget_window_run"]}, - ).scalar_one() + act_as(session, managed_v2_roles.simulation_service) + ids = _create_simulation_rows(session, public_api_rows) + window_id = ids["budget_window_run"] + + failed_window = _update_from_status( + session, + BudgetWindowRun, + window_id, + "pending", + status="failed", + error_message="refused", + completed_at=func.now(), + updated_at=func.now(), + ) - assert failed_window == ids["budget_window_run"] + assert failed_window == window_id for statement in ( - "UPDATE budget_window_runs SET started_at = now() WHERE id = :id", - "UPDATE budget_window_runs SET recalculate = true WHERE id = :id", - "UPDATE budget_window_runs SET report_id = report_id WHERE id = :id", + _update_row(BudgetWindowRun, window_id, started_at=func.now()), + _update_row(BudgetWindowRun, window_id, recalculate=True), + _update_row( + BudgetWindowRun, window_id, report_id=col(BudgetWindowRun.report_id) + ), ): - _refused(connection, statement, id=ids["budget_window_run"]) + _refused(session, statement) def test_modal_workers_start_finish_and_fail_budget_windows( - connection: Connection, managed_v2_roles, public_api_rows: PublicApiRows + session: Session, managed_v2_roles: ManagedV2Roles, public_api_rows: PublicApiRows ) -> None: """The Modal workers write a budget-window run's status and times. @@ -430,12 +480,13 @@ def test_modal_workers_start_finish_and_fail_budget_windows( own year finishes; the last year to finish marks the window succeeded, and a failed year fails it. """ - _act_as(connection, managed_v2_roles.simulation_service) - ids = _create_simulation_rows(connection, public_api_rows) + act_as(session, managed_v2_roles.simulation_service) + ids = _create_simulation_rows(session, public_api_rows) + window_id = ids["budget_window_run"] failing_window_id = uuid4() - insert_row( - connection, - "budget_window_runs", + add_row( + session, + BudgetWindowRun, id=failing_window_id, report_id=ids["report"], tax_benefit_model_version_id=public_api_rows.version_id, @@ -443,54 +494,60 @@ def test_modal_workers_start_finish_and_fail_budget_windows( recalculate=True, status="pending", ) - _act_as(connection, managed_v2_roles.modal_worker) + act_as(session, managed_v2_roles.modal_worker) started_windows = [ - connection.execute( - text( - "UPDATE budget_window_runs SET status = 'running', " - "started_at = now(), updated_at = now() " - "WHERE id = :id AND status = 'pending' RETURNING id" - ), - {"id": window_id}, - ).scalar_one() - for window_id in (ids["budget_window_run"], failing_window_id) + _update_from_status( + session, + BudgetWindowRun, + started_window_id, + "pending", + status="running", + started_at=func.now(), + updated_at=func.now(), + ) + for started_window_id in (window_id, failing_window_id) ] - succeeded_window = connection.execute( - text( - "UPDATE budget_window_runs SET status = 'succeeded', " - "completed_at = now(), updated_at = now() " - "WHERE id = :id AND status = 'running' RETURNING id" - ), - {"id": ids["budget_window_run"]}, - ).scalar_one() - failed_window = connection.execute( - text( - "UPDATE budget_window_runs SET status = 'failed', " - "error_message = 'the 2027 report run failed', completed_at = now(), " - "updated_at = now() WHERE id = :id AND status = 'running' RETURNING id" - ), - {"id": failing_window_id}, - ).scalar_one() - - assert started_windows == [ids["budget_window_run"], failing_window_id] - assert (succeeded_window, failed_window) == ( - ids["budget_window_run"], + succeeded_window = _update_from_status( + session, + BudgetWindowRun, + window_id, + "running", + status="succeeded", + completed_at=func.now(), + updated_at=func.now(), + ) + failed_window = _update_from_status( + session, + BudgetWindowRun, failing_window_id, + "running", + status="failed", + error_message="the 2027 report run failed", + completed_at=func.now(), + updated_at=func.now(), ) + + assert started_windows == [window_id, failing_window_id] + assert (succeeded_window, failed_window) == (window_id, failing_window_id) for statement in ( - "UPDATE budget_window_runs SET trigger = 'manual' WHERE id = :id", - "UPDATE budget_window_runs SET recalculate = false WHERE id = :id", - "UPDATE budget_window_runs SET tax_benefit_model_version_id = " - "tax_benefit_model_version_id WHERE id = :id", + _update_row(BudgetWindowRun, window_id, trigger="manual"), + _update_row(BudgetWindowRun, window_id, recalculate=False), + _update_row( + BudgetWindowRun, + window_id, + tax_benefit_model_version_id=col( + BudgetWindowRun.tax_benefit_model_version_id + ), + ), ): - _refused(connection, statement, id=ids["budget_window_run"]) + _refused(session, statement) @pytest.mark.parametrize("role_kind", ["simulation_service", "modal_worker"]) def test_each_simulation_role_locks_a_budget_window_run_row( - connection: Connection, - managed_v2_roles, + session: Session, + managed_v2_roles: ManagedV2Roles, public_api_rows: PublicApiRows, role_kind: str, ) -> None: @@ -501,234 +558,263 @@ def test_each_simulation_role_locks_a_budget_window_run_row( ``budget_window_runs`` alone: neither role may update ``reports``, so a lock on every joined table is refused. """ - _act_as(connection, managed_v2_roles.simulation_service) - ids = _create_simulation_rows(connection, public_api_rows) - _act_as(connection, getattr(managed_v2_roles, role_kind)) - - locked_window = connection.execute( - text("SELECT id FROM budget_window_runs WHERE id = :id FOR UPDATE"), - {"id": ids["budget_window_run"]}, + act_as(session, managed_v2_roles.simulation_service) + ids = _create_simulation_rows(session, public_api_rows) + act_as(session, getattr(managed_v2_roles, role_kind)) + is_the_window = col(BudgetWindowRun.id) == ids["budget_window_run"] + report_of_the_window = col(Report.id) == col(BudgetWindowRun.report_id) + + locked_window = session.execute( + select(col(BudgetWindowRun.id)).where(is_the_window).with_for_update() ).scalar_one() - locked_over_join = connection.execute( - text( - "SELECT budget_window_runs.id, reports.budget_window_size " - "FROM budget_window_runs JOIN reports " - "ON reports.id = budget_window_runs.report_id " - "WHERE budget_window_runs.id = :id FOR UPDATE OF budget_window_runs" - ), - {"id": ids["budget_window_run"]}, + locked_over_join = session.execute( + select(col(BudgetWindowRun.id), col(Report.budget_window_size)) + .join(Report, report_of_the_window) + .where(is_the_window) + .with_for_update(of=BudgetWindowRun) ).one() assert locked_window == ids["budget_window_run"] assert tuple(locked_over_join) == (ids["budget_window_run"], 1) _refused( - connection, - "SELECT budget_window_runs.id FROM budget_window_runs JOIN reports " - "ON reports.id = budget_window_runs.report_id " - "WHERE budget_window_runs.id = :id FOR UPDATE", - id=ids["budget_window_run"], + session, + select(col(BudgetWindowRun.id)) + .join(Report, report_of_the_window) + .where(is_the_window) + .with_for_update(), ) def test_the_public_api_reads_runs_and_results_but_writes_neither( - connection: Connection, managed_v2_roles + session: Session, managed_v2_roles: ManagedV2Roles ) -> None: - _act_as(connection, managed_v2_roles.runtime) + act_as(session, managed_v2_roles.runtime) - for table in ("simulation_runs", "report_runs", "poverty"): - connection.execute(text(f"SELECT count(*) FROM {table}")).scalar_one() + for model in (SimulationRun, ReportRun, Poverty): + session.execute(_row_count(model)).scalar_one() _refused( - connection, - "INSERT INTO report_runs (id, report_id, baseline_simulation_run_id, " - "country_package_version, policyengine_version, status, trigger) " - "VALUES (:id, :report_id, :run_id, '1.0.0', '4.0.0', 'pending', 'initial')", - id=uuid4(), - report_id=uuid4(), - run_id=uuid4(), + session, + insert(ReportRun).values( + id=uuid4(), + report_id=uuid4(), + baseline_simulation_run_id=uuid4(), + country_package_version="1.0.0", + policyengine_version="4.0.0", + status="pending", + trigger="initial", + ), ) @pytest.mark.parametrize("role_kind", ["simulation_service", "modal_worker"]) def test_each_simulation_role_updates_exactly_its_declared_columns( - connection: Connection, managed_v2_roles, role_kind: str + session: Session, managed_v2_roles: ManagedV2Roles, role_kind: str ) -> None: - """Every column of the run tables is updatable exactly when it is declared.""" + """Every column of the run tables is updatable exactly when it is declared. + + Setting a column other than ``updated_at`` also sets ``updated_at``, which + both roles may update on each of these tables. + """ role = getattr(managed_v2_roles, role_kind) declared = declared_privileges(managed_v2_roles.deployment_environment)[role] - _act_as(connection, role) - - for table in ( - "simulation_runs", - "report_runs", - "household_jobs", - "budget_window_runs", - "cliff_impacts", + act_as(session, role) + + for model in ( + SimulationRun, + ReportRun, + HouseholdJob, + BudgetWindowRun, + CliffImpact, ): updatable = { column - for privilege in declared[table] + for privilege in declared[model.__tablename__] if isinstance(privilege, ColumnPrivilege) and privilege.privilege is TablePrivilege.UPDATE for column in privilege.columns } - for column in V2_METADATA.tables[table].c: + for column_attribute in inspect(model).column_attrs: + column = getattr(model, column_attribute.key) # The privilege is checked when the statement starts, so no row is # needed. - statement = f"UPDATE {table} SET {column.name} = {column.name} WHERE false" - if column.name in updatable: - connection.execute(text(statement)) + statement = update(model).where(false()).values({column: column}) + if column_attribute.key in updatable: + session.execute(statement) else: - _refused(connection, statement) + _refused(session, statement) -# What the simulation service inserts to start a run's cliff calculation, -# unless one that hasn't failed exists. Naming the partial unique index's -# conflict target needs SELECT as well as INSERT. -START_CLIFF_CALCULATION = ( - "INSERT INTO cliff_impacts (id, simulation_run_id, status) " - "VALUES (:id, :simulation_run_id, 'pending') " - "ON CONFLICT (simulation_run_id) WHERE status <> 'failed' DO NOTHING " - "RETURNING id" -) - +def _start_cliff_calculation(session: Session, run_id: object) -> UUID | None: + """Start the run's cliff calculation, unless one that hasn't failed exists. -def _start_cliff_calculation(connection: Connection, run_id: object) -> object: - return connection.execute( - text(START_CLIFF_CALCULATION), {"id": uuid4(), "simulation_run_id": run_id} + This is what the simulation service inserts; return the new calculation's + ID, or None. Naming the partial unique index's conflict target needs SELECT + as well as INSERT. Its condition is sent as a literal, as in the index, so + PostgreSQL can match the index however often the statement runs. + """ + unfailed = col(CliffImpact.status) != bindparam( + "failed_status", SimulationStatus.FAILED, literal_execute=True + ) + return session.execute( + postgresql.insert(CliffImpact) + .values(id=uuid4(), simulation_run_id=run_id, status="pending") + .on_conflict_do_nothing( + index_elements=[col(CliffImpact.simulation_run_id)], + index_where=unfailed, + ) + .returning(col(CliffImpact.id)) ).scalar_one_or_none() def test_the_simulation_service_starts_cliff_calculations_and_records_calls( - connection: Connection, managed_v2_roles, public_api_rows: PublicApiRows + session: Session, managed_v2_roles: ManagedV2Roles, public_api_rows: PublicApiRows ) -> None: """The service inserts a run's calculation once, and records or fails its call. It never claims a calculation, writes its numbers, changes the run it calculates or deletes it. """ - _act_as(connection, managed_v2_roles.simulation_service) - ids = _create_simulation_rows(connection, public_api_rows) - - calculation_id = _start_cliff_calculation(connection, ids["run"]) - joined_calculation = _start_cliff_calculation(connection, ids["run"]) - recorded = connection.execute( - text( - "UPDATE cliff_impacts SET modal_call_id = 'fc-cliffs', " - "updated_at = now() WHERE id = :id AND status = 'pending' " - "AND modal_call_id IS NULL RETURNING id" - ), - {"id": calculation_id}, - ).scalar_one() - failed = connection.execute( - text( - "UPDATE cliff_impacts SET status = 'failed', " - "error_message = 'modal_refused: refused', completed_at = now(), " - "updated_at = now() WHERE id = :id AND status = 'pending' RETURNING id" - ), - {"id": calculation_id}, + act_as(session, managed_v2_roles.simulation_service) + ids = _create_simulation_rows(session, public_api_rows) + + calculation_id = _start_cliff_calculation(session, ids["run"]) + joined_calculation = _start_cliff_calculation(session, ids["run"]) + recorded = session.execute( + update(CliffImpact) + .where( + col(CliffImpact.id) == calculation_id, + col(CliffImpact.status) == "pending", + col(CliffImpact.modal_call_id).is_(None), + ) + .values(modal_call_id="fc-cliffs", updated_at=func.now()) + .returning(col(CliffImpact.id)) ).scalar_one() + failed = _update_from_status( + session, + CliffImpact, + calculation_id, + "pending", + status="failed", + error_message="modal_refused: refused", + completed_at=func.now(), + updated_at=func.now(), + ) assert calculation_id is not None assert joined_calculation is None assert recorded == failed == calculation_id for statement in ( - "UPDATE cliff_impacts SET started_at = now() WHERE id = :id", - "UPDATE cliff_impacts SET cliff_gap = 1.0 WHERE id = :id", - "UPDATE cliff_impacts SET simulation_run_id = simulation_run_id WHERE id = :id", - "DELETE FROM cliff_impacts WHERE id = :id", + _update_row(CliffImpact, calculation_id, started_at=func.now()), + _update_row(CliffImpact, calculation_id, cliff_gap=1.0), + _update_row( + CliffImpact, + calculation_id, + simulation_run_id=col(CliffImpact.simulation_run_id), + ), + delete(CliffImpact).where(col(CliffImpact.id) == calculation_id), ): - _refused(connection, statement, id=calculation_id) + _refused(session, statement) def test_modal_workers_claim_cliff_calculations_and_write_their_results( - connection: Connection, managed_v2_roles, public_api_rows: PublicApiRows + session: Session, managed_v2_roles: ManagedV2Roles, public_api_rows: PublicApiRows ) -> None: """A worker claims a pending calculation under its call and finishes it. It never inserts a calculation, changes the run it calculates or deletes one. """ - _act_as(connection, managed_v2_roles.simulation_service) - ids = _create_simulation_rows(connection, public_api_rows) - calculation_id = _start_cliff_calculation(connection, ids["run"]) - _act_as(connection, managed_v2_roles.modal_worker) - - claimed = connection.execute( - text( - "UPDATE cliff_impacts SET status = 'running', started_at = now(), " - "modal_call_id = 'fc-cliffs', updated_at = now() " - "WHERE id = :id AND status = 'pending' RETURNING id" - ), - {"id": calculation_id}, - ).scalar_one() - succeeded = connection.execute( - text( - "UPDATE cliff_impacts SET status = 'succeeded', cliff_gap = 1.5e9, " - "cliff_share = 0.04, completed_at = now(), updated_at = now() " - "WHERE id = :id AND status = 'running' RETURNING id" - ), - {"id": calculation_id}, - ).scalar_one() + act_as(session, managed_v2_roles.simulation_service) + ids = _create_simulation_rows(session, public_api_rows) + calculation_id = _start_cliff_calculation(session, ids["run"]) + act_as(session, managed_v2_roles.modal_worker) + + claimed = _update_from_status( + session, + CliffImpact, + calculation_id, + "pending", + status="running", + started_at=func.now(), + modal_call_id="fc-cliffs", + updated_at=func.now(), + ) + succeeded = _update_from_status( + session, + CliffImpact, + calculation_id, + "running", + status="succeeded", + cliff_gap=1.5e9, + cliff_share=0.04, + completed_at=func.now(), + updated_at=func.now(), + ) assert claimed == succeeded == calculation_id - _refused( - connection, - "INSERT INTO cliff_impacts (id, simulation_run_id, status) " - "VALUES (:id, :run_id, 'pending')", - id=uuid4(), - run_id=ids["run"], - ) for statement in ( - "UPDATE cliff_impacts SET simulation_run_id = simulation_run_id WHERE id = :id", - "DELETE FROM cliff_impacts WHERE id = :id", + insert(CliffImpact).values( + id=uuid4(), simulation_run_id=ids["run"], status="pending" + ), + _update_row( + CliffImpact, + calculation_id, + simulation_run_id=col(CliffImpact.simulation_run_id), + ), + delete(CliffImpact).where(col(CliffImpact.id) == calculation_id), ): - _refused(connection, statement, id=calculation_id) + _refused(session, statement) def test_api_v1_reads_cliff_results_and_other_roles_cannot( - connection: Connection, managed_v2_roles, public_api_rows: PublicApiRows + session: Session, managed_v2_roles: ManagedV2Roles, public_api_rows: PublicApiRows ) -> None: """API v1 reads a report run's two cliff results and writes none. The catalog writer and the Stage 12 role can't read them. """ - _act_as(connection, managed_v2_roles.simulation_service) - ids = _create_simulation_rows(connection, public_api_rows) - calculation_id = _start_cliff_calculation(connection, ids["run"]) - _act_as(connection, managed_v2_roles.modal_worker) - connection.execute( - text( - "UPDATE cliff_impacts SET status = 'succeeded', cliff_gap = 1.5e9, " - "cliff_share = 0.04, completed_at = now() WHERE id = :id" - ), - {"id": calculation_id}, + act_as(session, managed_v2_roles.simulation_service) + ids = _create_simulation_rows(session, public_api_rows) + calculation_id = _start_cliff_calculation(session, ids["run"]) + act_as(session, managed_v2_roles.modal_worker) + session.execute( + _update_row( + CliffImpact, + calculation_id, + status="succeeded", + cliff_gap=1.5e9, + cliff_share=0.04, + completed_at=func.now(), + ) ) - _act_as(connection, managed_v2_roles.runtime) - - results = connection.execute( - text( - "SELECT cliff_impacts.cliff_gap, cliff_impacts.cliff_share " - "FROM report_runs JOIN cliff_impacts ON cliff_impacts.simulation_run_id " - "IN (report_runs.baseline_simulation_run_id, " - "report_runs.reform_simulation_run_id) " - "WHERE report_runs.id = :id AND cliff_impacts.status = 'succeeded'" - ), - {"id": ids["report_run"]}, + act_as(session, managed_v2_roles.runtime) + + results = session.execute( + select(col(CliffImpact.cliff_gap), col(CliffImpact.cliff_share)) + .select_from(ReportRun) + .join( + CliffImpact, + col(CliffImpact.simulation_run_id).in_( + [ + col(ReportRun.baseline_simulation_run_id), + col(ReportRun.reform_simulation_run_id), + ] + ), + ) + .where( + col(ReportRun.id) == ids["report_run"], + col(CliffImpact.status) == "succeeded", + ) ).all() assert [tuple(result) for result in results] == [(1.5e9, 0.04)] _refused( - connection, - "INSERT INTO cliff_impacts (id, simulation_run_id, status) " - "VALUES (:id, :run_id, 'pending')", - id=uuid4(), - run_id=ids["run"], - ) - _refused( - connection, - "UPDATE cliff_impacts SET cliff_gap = 0 WHERE id = :id", - id=calculation_id, + session, + insert(CliffImpact).values( + id=uuid4(), simulation_run_id=ids["run"], status="pending" + ), ) + _refused(session, _update_row(CliffImpact, calculation_id, cliff_gap=0)) for role in (managed_v2_roles.stage12, CATALOG_WRITER_ROLE): - _act_as(connection, role) - _refused(connection, "SELECT count(*) FROM cliff_impacts") + act_as(session, role) + _refused(session, _row_count(CliffImpact)) diff --git a/tests/integration/test_v2_stage12_comparison_persistence.py b/tests/integration/test_v2_stage12_comparison_persistence.py index bbd75a4d2..569243e67 100644 --- a/tests/integration/test_v2_stage12_comparison_persistence.py +++ b/tests/integration/test_v2_stage12_comparison_persistence.py @@ -14,10 +14,8 @@ from uuid import uuid4 import pytest -from sqlalchemy import create_engine, delete, func, select +from sqlalchemy import delete, func, select from sqlalchemy.exc import ProgrammingError -from sqlalchemy.orm import sessionmaker -from sqlmodel import Session from policyengine_api.data.v2.models import ( Stage12ComparisonReport, @@ -41,6 +39,9 @@ if TYPE_CHECKING: from collections.abc import Iterator + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + from policyengine_api.services.v2.comparison_runs.types import ( ComparisonReportRecord, ComparisonSimulationRecord, @@ -49,31 +50,29 @@ @pytest.fixture def stage12_sessions( - disposable_v2_database_url, managed_v2_roles, v2_engine_as_role + managed_v2_roles, + v2_sessions_as_role, + v2_owner_sessions: sessionmaker[Session], ) -> Iterator[sessionmaker[Session]]: """Open sessions as the Stage 12 role; remove this test's rows as the superuser.""" - stage12_engine = v2_engine_as_role(managed_v2_roles.stage12) - cleanup_engine = create_engine(disposable_v2_database_url) - factory = sessionmaker(stage12_engine, class_=Session, expire_on_commit=False) + factory = v2_sessions_as_role(managed_v2_roles.stage12) factory.kw["info"] = {"evaluation_ids": []} try: yield factory finally: evaluation_ids = factory.kw["info"]["evaluation_ids"] if evaluation_ids: - with cleanup_engine.begin() as connection: - connection.execute( + with v2_owner_sessions.begin() as session: + session.execute( delete(Stage12ComparisonSimulation).where( Stage12ComparisonSimulation.evaluation_id.in_(evaluation_ids) ) ) - connection.execute( + session.execute( delete(Stage12ComparisonReport).where( Stage12ComparisonReport.evaluation_id.in_(evaluation_ids) ) ) - stage12_engine.dispose() - cleanup_engine.dispose() def _new_report(stage12_sessions) -> ComparisonReportRecord: diff --git a/tests/integration/test_v2_user_budget_window_runs.py b/tests/integration/test_v2_user_budget_window_runs.py index 19f691bf6..b8000ecc6 100644 --- a/tests/integration/test_v2_user_budget_window_runs.py +++ b/tests/integration/test_v2_user_budget_window_runs.py @@ -10,18 +10,17 @@ from __future__ import annotations from datetime import timedelta -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING from uuid import UUID, uuid4 import pytest from alembic import command from alembic.config import Config -from sqlalchemy import create_engine, text -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import NullPool -from sqlmodel import Session +from sqlalchemy import delete, select +from sqlmodel import col from policyengine_api.constants import REPO +from policyengine_api.data.v2.models import ReportRun, User from tests.integration.stored_report_rows import ( STARTED_AT, RunSettings, @@ -40,9 +39,10 @@ ) if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator - from sqlalchemy import Engine + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session from tests.integration.stored_report_rows import CatalogRows @@ -50,56 +50,57 @@ @pytest.fixture -def owner_engine(disposable_v2_database_url: str) -> Iterator[Engine]: +def owner_sessions(v2_owner_sessions: sessionmaker[Session]) -> sessionmaker[Session]: command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - yield engine - engine.dispose() + return v2_owner_sessions @pytest.fixture -def catalog(owner_engine: Engine) -> Iterator[CatalogRows]: - with owner_engine.begin() as connection: - stored = store_catalog(connection, "us") +def catalog(owner_sessions: sessionmaker[Session]) -> Iterator[CatalogRows]: + with owner_sessions.begin() as session: + stored = store_catalog(session, "us") yield stored - with owner_engine.begin() as connection: - delete_catalog(connection, stored) + with owner_sessions.begin() as session: + delete_catalog(session, stored) @pytest.fixture -def runtime_sessions(managed_v2_roles, v2_engine_as_role) -> Iterator[Any]: - engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - yield sessionmaker(engine, class_=Session) - engine.dispose() +def runtime_sessions( + managed_v2_roles, v2_sessions_as_role: Callable[[str], sessionmaker[Session]] +) -> sessionmaker[Session]: + return v2_sessions_as_role(managed_v2_roles.runtime) @pytest.fixture -def browser_id(owner_engine: Engine) -> Iterator[UUID]: +def browser_id(owner_sessions: sessionmaker[Session]) -> Iterator[UUID]: """Name a signed-out browser, and delete its user and records after.""" browser = uuid4() yield browser - with owner_engine.begin() as connection: - connection.execute(text("DELETE FROM users WHERE id = :id"), {"id": browser}) + with owner_sessions.begin() as session: + session.execute(delete(User).where(col(User.id) == browser)) -def window_run_years(engine: Engine, window_run_id: UUID) -> set[UUID]: - with engine.begin() as connection: +def window_run_years( + owner_sessions: sessionmaker[Session], window_run_id: UUID +) -> set[UUID]: + with owner_sessions.begin() as session: return set( - connection.execute( - text("SELECT id FROM report_runs WHERE budget_window_run_id = :id"), - {"id": window_run_id}, + session.execute( + select(col(ReportRun.id)).where( + col(ReportRun.budget_window_run_id) == window_run_id + ) ).scalars() ) def test_a_budget_window_create_records_each_years_report_run( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], browser_id: UUID, ) -> None: client = client_for( - runtime_sessions, JoiningSimulationService(owner_engine, catalog) + runtime_sessions, JoiningSimulationService(owner_sessions, catalog) ) response = client.post( @@ -110,9 +111,9 @@ def test_a_budget_window_create_records_each_years_report_run( assert response.status_code == 201, response.text window_run_id = UUID(response.json()["result"]["item"]["run"]["id"]) - records = stored_records(owner_engine, [browser_id]) + records = stored_records(owner_sessions, [browser_id]) assert {record.report_run_id for record in records} == window_run_years( - owner_engine, window_run_id + owner_sessions, window_run_id ) assert len(records) == len(WINDOW_YEARS) assert {record.trigger for record in records} == {"initial"} @@ -120,20 +121,20 @@ def test_a_budget_window_create_records_each_years_report_run( def test_a_budget_window_rerun_records_each_year_of_the_window_run_it_joined( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], browser_id: UUID, ) -> None: - with owner_engine.begin() as connection: + with owner_sessions.begin() as session: joined = store_window( - connection, + session, catalog, years=WINDOW_YEARS, settings=RunSettings(versions=CURRENT_VERSIONS, status="running"), ) newer = store_window( - connection, + session, catalog, years=WINDOW_YEARS, settings=RunSettings( @@ -144,7 +145,7 @@ def test_a_budget_window_rerun_records_each_year_of_the_window_run_it_joined( report=joined.report, ) simulation_service = JoiningSimulationService( - owner_engine, + owner_sessions, catalog, joined_run=JoinedRun( report_id=joined.report.report_id, @@ -161,28 +162,28 @@ def test_a_budget_window_rerun_records_each_year_of_the_window_run_it_joined( assert response.status_code == 201, response.text assert response.json()["result"]["item"]["run"]["id"] == str(joined.window_run_id) - records = stored_records(owner_engine, [browser_id]) + records = stored_records(owner_sessions, [browser_id]) assert {record.report_run_id for record in records} == set(joined.year_run_ids) assert not {record.report_run_id for record in records} & set(newer.year_run_ids) assert {record.trigger for record in records} == {"manual"} def test_a_window_rerun_whose_answer_names_no_window_run_points_to_the_run_list( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], browser_id: UUID, ) -> None: - with owner_engine.begin() as connection: + with owner_sessions.begin() as session: window = store_window( - connection, + session, catalog, years=WINDOW_YEARS, settings=RunSettings(versions=CURRENT_VERSIONS, status="pending"), ) # An answer naming the first year's report run but no budget-window run. simulation_service = JoiningSimulationService( - owner_engine, + owner_sessions, catalog, joined_run=JoinedRun( report_id=window.report.report_id, report_run_id=window.year_run_ids[0] @@ -201,4 +202,4 @@ def test_a_window_rerun_whose_answer_names_no_window_run_points_to_the_run_list( assert ( f"/v2/reports/{window.report.report_id}/runs?country_id=us" in body["message"] ) - assert stored_records(owner_engine, [browser_id]) == [] + assert stored_records(owner_sessions, [browser_id]) == [] diff --git a/tests/integration/test_v2_user_identity_persistence.py b/tests/integration/test_v2_user_identity_persistence.py index f129ee086..254a56ddd 100644 --- a/tests/integration/test_v2_user_identity_persistence.py +++ b/tests/integration/test_v2_user_identity_persistence.py @@ -9,26 +9,20 @@ from __future__ import annotations -import os import time from concurrent.futures import ThreadPoolExecutor -from dataclasses import dataclass +from dataclasses import dataclass, replace from threading import Barrier from typing import TYPE_CHECKING from uuid import UUID, uuid4 import pytest from pydantic import ValidationError -from sqlalchemy import create_engine, delete, func, select, update +from sqlalchemy import delete, func, select, update +from sqlalchemy.engine import make_url from sqlalchemy.exc import IntegrityError -from sqlalchemy.orm import sessionmaker -from sqlmodel import Session from policyengine_api.data.v2 import user_association_migration_qualification -from policyengine_api.data.v2.migration_target import ( - V2_ALEMBIC_DISPOSABLE_TEST, - load_v2_alembic_settings, -) from policyengine_api.data.v2.models import ( LegacyUserMapping, User, @@ -42,6 +36,7 @@ V2_MIGRATION_DATABASE_URL, V2_SUPABASE_ENVIRONMENT, V2_SUPABASE_PROJECT_REF, + PostgresConnectionSettings, ) from policyengine_api.services.v2.identity.services import ( convert_unauthenticated_user_in_session, @@ -91,7 +86,14 @@ from tests.unit.v2.user_service_support import default_legacy_references if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator + from contextlib import AbstractContextManager + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + from policyengine_api.data.v2.settings import V2DatabaseSettings + from tests.integration.conftest import ManagedV2Roles # Long enough for a write that is not blocked by a held row lock to finish. LOCK_WAIT_SECONDS = 1.0 @@ -103,54 +105,38 @@ ) -def _disposable_url() -> str: - database_url = os.environ.get(V2_MIGRATION_DATABASE_URL, "") - if not database_url: - pytest.skip(f"{V2_MIGRATION_DATABASE_URL} is not set") - settings = load_v2_alembic_settings( - { - V2_MIGRATION_DATABASE_URL: database_url, - V2_ALEMBIC_DISPOSABLE_TEST: os.environ.get(V2_ALEMBIC_DISPOSABLE_TEST, ""), - } - ) - if not settings.disposable_test: - pytest.fail("identity persistence tests require disposable-test mode") - return settings.url.render_as_string(hide_password=False) - - @pytest.fixture -def sessions(managed_v2_roles, v2_engine_as_role) -> Iterator[sessionmaker[Session]]: - """Open sessions as the Public API's runtime role; clean up as the superuser. +def sessions( + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], + v2_owner_sessions: sessionmaker[Session], +) -> Iterator[sessionmaker[Session]]: + """Open sessions as API v1's runtime role; clean up as the database's owner. Running the services as ``policyengine_v2_runtime`` proves its declared privileges cover them (rule - ``api.v2.runtime-privileges-tested-as-runtime-role``). + ``api.v2.runtime-privileges-tested-as-runtime-role``). The factory is this + test's own, and each of its Sessions opens its own connection. """ - runtime_engine = v2_engine_as_role( - managed_v2_roles.runtime, pool_size=10, max_overflow=10 - ) - cleanup_engine = create_engine(_disposable_url()) - factory = sessionmaker(runtime_engine, class_=Session, expire_on_commit=False) + factory = v2_sessions_as_role(managed_v2_roles.runtime) issuer = f"https://stage12a-{uuid4().hex[:12]}.example.test/" factory.kw["info"] = {"issuer": issuer, "browser_user_ids": []} try: yield factory finally: - with cleanup_engine.begin() as connection: + with v2_owner_sessions.begin() as session: owned = select(UserIdentity.user_id).where(UserIdentity.issuer == issuer) user_ids = [ - *connection.execute(owned).scalars(), + *session.scalars(owned), *factory.kw["info"]["browser_user_ids"], ] if user_ids: - connection.execute( + session.execute( delete(LegacyUserMapping).where( LegacyUserMapping.user_id.in_(user_ids) ) ) - connection.execute(delete(User).where(User.id.in_(user_ids))) - runtime_engine.dispose() - cleanup_engine.dispose() + session.execute(delete(User).where(User.id.in_(user_ids))) def _principal(sessions, subject: str) -> UserPrincipal: @@ -244,27 +230,25 @@ def _save_policy(services: Services, principal) -> UUID: ).id -def _set_stored_user_type(user_id: UUID, user_type: str) -> None: - """Change a user's type as the superuser; the runtime role never changes one.""" - engine = create_engine(_disposable_url()) - try: - with engine.begin() as connection: - connection.execute( - update(User).where(User.id == user_id).values(user_type=user_type) - ) - finally: - engine.dispose() +def _set_stored_user_type( + v2_owner_sessions: sessionmaker[Session], user_id: UUID, user_type: str +) -> None: + """Change a user's type as the database's owner; the runtime role never does.""" + with v2_owner_sessions.begin() as session: + session.execute( + update(User).where(User.id == user_id).values(user_type=user_type) + ) @pytest.mark.parametrize("user_type", ["author", "admin"]) def test_an_author_or_admin_keeps_its_type_at_sign_in_and_upgrade( - sessions, user_type: str + sessions, v2_owner_sessions: sessionmaker[Session], user_type: str ) -> None: signed_in = _principal(sessions, f"google-oauth2|{user_type}") browser = _browser(sessions) services = _services(sessions) account_id = services.accounts.get_account(principal=signed_in, country_id="us").id - _set_stored_user_type(account_id, user_type) + _set_stored_user_type(v2_owner_sessions, account_id, user_type) _save_policy(services, browser) again = services.accounts.get_account(principal=signed_in, country_id="uk") @@ -763,10 +747,12 @@ def delete_user(self, subject: str) -> None: @pytest.mark.usefixtures("sessions") -def test_qualification_reads_counts_in_a_read_only_transaction() -> None: - disposable_url = _disposable_url() - # The settings loader requires a persistent-looking target; the engine - # builder substitutes the disposable database, which is all that is read. +def test_qualification_reads_counts_in_a_read_only_transaction( + disposable_v2_database_url: str, +) -> None: + # The settings loader requires a persistent-looking target. The + # qualification's own Session factories then open the disposable database + # in its place, which is all that is read. environ = { V2_MIGRATION_DATABASE_URL: ( "postgresql+psycopg://migration:unused@db.abcdefghijklmnopqrst." @@ -776,15 +762,28 @@ def test_qualification_reads_counts_in_a_read_only_transaction() -> None: V2_SUPABASE_ENVIRONMENT: "test", } qualification = user_association_migration_qualification - observed_read_only: list[object] = [] + observed_read_only: list[bool] = [] - def pending_checker(connection) -> bool: - observed_read_only.append(connection.connection.dbapi_connection.read_only) - return qualification.user_association_migration_is_pending(connection) + def pending_checker(session: Session) -> bool: + transaction_read_only = session.execute( + select(func.current_setting("transaction_read_only")) + ).scalar_one() + observed_read_only.append(transaction_read_only == "on") + return qualification.user_association_migration_is_pending(session) + + def disposable_qualification_sessions( + settings: V2DatabaseSettings, + ) -> AbstractContextManager[sessionmaker[Session]]: + disposable_connection = PostgresConnectionSettings( + make_url(disposable_v2_database_url) + ) + return qualification.open_qualification_sessions( + replace(settings, connection=disposable_connection) + ) evidence = qualification.qualify_user_association_migration( environ, - engine_builder=lambda _settings: create_engine(disposable_url), + session_factories=disposable_qualification_sessions, pending_checker=pending_checker, ) diff --git a/tests/integration/test_v2_user_policy_mirroring.py b/tests/integration/test_v2_user_policy_mirroring.py index a321f7946..f58142eee 100644 --- a/tests/integration/test_v2_user_policy_mirroring.py +++ b/tests/integration/test_v2_user_policy_mirroring.py @@ -2,21 +2,15 @@ from __future__ import annotations -import os from concurrent.futures import ThreadPoolExecutor from threading import Barrier +from typing import TYPE_CHECKING from uuid import UUID, uuid4 import pytest -from sqlalchemy import create_engine, delete, func, select -from sqlalchemy.orm import sessionmaker -from sqlmodel import Session +from sqlalchemy import delete, func, select from policyengine_api.constants import COUNTRY_PACKAGE_VERSIONS, POLICYENGINE_VERSION -from policyengine_api.data.v2.migration_target import ( - V2_ALEMBIC_DISPOSABLE_TEST, - load_v2_alembic_settings, -) from policyengine_api.data.v2.models import ( LegacyPolicyMapping, LegacyUserMapping, @@ -29,7 +23,6 @@ User, UserPolicy, ) -from policyengine_api.data.v2.settings import V2_MIGRATION_DATABASE_URL from policyengine_api.services.v2.policies.types import LegacyPolicySnapshot from policyengine_api.services.v2.user_policies.services import ( mirror_legacy_user_policy_in_session, @@ -40,27 +33,13 @@ ) from policyengine_api.services.v2.user_policies.types import LegacyUserPolicySnapshot - -def _disposable_url() -> str: - database_url = os.environ.get(V2_MIGRATION_DATABASE_URL, "") - if not database_url: - pytest.skip(f"{V2_MIGRATION_DATABASE_URL} is not set") - settings = load_v2_alembic_settings( - { - V2_MIGRATION_DATABASE_URL: database_url, - V2_ALEMBIC_DISPOSABLE_TEST: os.environ.get( - V2_ALEMBIC_DISPOSABLE_TEST, - "", - ), - } - ) - if not settings.disposable_test: - pytest.fail("saved-policy mirror tests require disposable-test mode") - return settings.url.render_as_string(hide_password=False) +if TYPE_CHECKING: + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session -def _seed_catalog(sessions): - with sessions.begin() as session: +def _seed_catalog(v2_owner_sessions: sessionmaker[Session]): + with v2_owner_sessions.begin() as session: model = TaxBenefitModel(name="policyengine-us") version = TaxBenefitModelVersion( model=model, @@ -111,21 +90,17 @@ def _saved(*, legacy_id: int, reform_id: int, reform_label="Reform", **changes): return LegacyUserPolicySnapshot.model_validate(values) -def _cleanup(engine, model_id) -> None: +def _cleanup(v2_owner_sessions: sessionmaker[Session], model_id) -> None: if model_id is None: return - with engine.begin() as connection: + with v2_owner_sessions.begin() as session: legacy_user_ids = ("auth0|one", "legacy-user-two") - user_ids = ( - connection.execute( - select(LegacyUserMapping.user_id).where( - LegacyUserMapping.legacy_user_id.in_(legacy_user_ids) - ) + user_ids = session.scalars( + select(LegacyUserMapping.user_id).where( + LegacyUserMapping.legacy_user_id.in_(legacy_user_ids) ) - .scalars() - .all() - ) - connection.execute( + ).all() + session.execute( delete(LegacyUserMapping).where( LegacyUserMapping.legacy_user_id.in_(legacy_user_ids) ) @@ -134,51 +109,45 @@ def _cleanup(engine, model_id) -> None: association_ids = select(UserPolicy.id).where( UserPolicy.policy_id.in_(policy_ids) ) - connection.execute( + session.execute( delete(LegacyUserPolicyMapping).where( LegacyUserPolicyMapping.user_policy_id.in_(association_ids) ) ) - connection.execute( - delete(UserPolicy).where(UserPolicy.policy_id.in_(policy_ids)) - ) + session.execute(delete(UserPolicy).where(UserPolicy.policy_id.in_(policy_ids))) if user_ids: - connection.execute(delete(User).where(User.id.in_(user_ids))) - connection.execute( + session.execute(delete(User).where(User.id.in_(user_ids))) + session.execute( delete(LegacyPolicyMapping).where( LegacyPolicyMapping.policy_id.in_(policy_ids) ) ) - connection.execute( + session.execute( delete(ParameterValue).where(ParameterValue.policy_id.in_(policy_ids)) ) - connection.execute( - delete(Policy).where(Policy.tax_benefit_model_id == model_id) - ) + session.execute(delete(Policy).where(Policy.tax_benefit_model_id == model_id)) version_ids = select(TaxBenefitModelVersion.id).where( TaxBenefitModelVersion.model_id == model_id ) - connection.execute( + session.execute( delete(Parameter).where( Parameter.tax_benefit_model_version_id.in_(version_ids) ) ) - connection.execute( + session.execute( delete(TaxBenefitModelVersion).where( TaxBenefitModelVersion.model_id == model_id ) ) - connection.execute( - delete(TaxBenefitModel).where(TaxBenefitModel.id == model_id) - ) + session.execute(delete(TaxBenefitModel).where(TaxBenefitModel.id == model_id)) -def test_saved_rows_share_policy_and_reuse_only_the_same_mapped_user() -> None: - engine = create_engine(_disposable_url()) - sessions = sessionmaker(engine, class_=Session, expire_on_commit=False) +def test_saved_rows_share_policy_and_reuse_only_the_same_mapped_user( + v2_owner_sessions: sessionmaker[Session], +) -> None: model_id = None try: - model_id, parameter_name = _seed_catalog(sessions) + model_id, parameter_name = _seed_catalog(v2_owner_sessions) first_reform = _reform(parameter_name, legacy_id=101, source_hash="first") second_reform = _reform(parameter_name, legacy_id=102, source_hash="second") first_saved = _saved(legacy_id=201, reform_id=101) @@ -194,7 +163,7 @@ def test_saved_rows_share_policy_and_reuse_only_the_same_mapped_user() -> None: user_id="legacy-user-two", ) - with sessions.begin() as session: + with v2_owner_sessions.begin() as session: first = mirror_legacy_user_policy_in_session( session, first_saved, @@ -213,7 +182,7 @@ def test_saved_rows_share_policy_and_reuse_only_the_same_mapped_user() -> None: first_reform, source_revision=1, ) - with sessions.begin() as session: + with v2_owner_sessions.begin() as session: retry = mirror_legacy_user_policy_in_session( session, first_saved, @@ -226,7 +195,7 @@ def test_saved_rows_share_policy_and_reuse_only_the_same_mapped_user() -> None: assert third.policy_id == first.policy_id assert retry.association_id == first.association_id assert retry.association_created is False - with sessions() as session: + with v2_owner_sessions() as session: associations = session.scalars( select(UserPolicy).order_by(UserPolicy.created_at, UserPolicy.id) ).all() @@ -261,18 +230,17 @@ def test_saved_rows_share_policy_and_reuse_only_the_same_mapped_user() -> None: == 3 ) finally: - _cleanup(engine, model_id) - engine.dispose() + _cleanup(v2_owner_sessions, model_id) -def test_concurrent_first_use_resolves_one_legacy_user_mapping() -> None: - engine = create_engine(_disposable_url()) - sessions = sessionmaker(engine, class_=Session, expire_on_commit=False) +def test_concurrent_first_use_resolves_one_legacy_user_mapping( + v2_owner_sessions: sessionmaker[Session], +) -> None: legacy_user_id = f"phase10-concurrent-{uuid4()}" barrier = Barrier(2) def resolve() -> UUID: - with sessions.begin() as session: + with v2_owner_sessions.begin() as session: barrier.wait() return resolve_legacy_user_id( session, @@ -285,7 +253,7 @@ def resolve() -> UUID: user_ids = list(executor.map(lambda _index: resolve(), range(2))) assert user_ids[0] == user_ids[1] - with sessions() as session: + with v2_owner_sessions() as session: mappings = session.scalars( select(LegacyUserMapping).where( LegacyUserMapping.legacy_user_id == legacy_user_id @@ -294,7 +262,7 @@ def resolve() -> UUID: assert len(mappings) == 1 assert session.get(User, user_ids[0]) is not None finally: - with sessions.begin() as session: + with v2_owner_sessions.begin() as session: mapping = session.get(LegacyUserMapping, legacy_user_id) if mapping is not None: user_id = mapping.user_id @@ -303,18 +271,17 @@ def resolve() -> UUID: user = session.get(User, user_id) if user is not None: session.delete(user) - engine.dispose() -def test_label_and_v1_only_updates_advance_the_complete_row_fingerprint() -> None: - engine = create_engine(_disposable_url()) - sessions = sessionmaker(engine, class_=Session, expire_on_commit=False) +def test_label_and_v1_only_updates_advance_the_complete_row_fingerprint( + v2_owner_sessions: sessionmaker[Session], +) -> None: model_id = None try: - model_id, parameter_name = _seed_catalog(sessions) + model_id, parameter_name = _seed_catalog(v2_owner_sessions) reform = _reform(parameter_name, legacy_id=301, source_hash="reform") original = _saved(legacy_id=401, reform_id=301) - with sessions.begin() as session: + with v2_owner_sessions.begin() as session: created = mirror_legacy_user_policy_in_session( session, original, @@ -325,10 +292,10 @@ def test_label_and_v1_only_updates_advance_the_complete_row_fingerprint() -> Non renamed = original.model_copy( update={"reform_label": "Renamed", "updated_date": 3} ) - with sessions.begin() as session: + with v2_owner_sessions.begin() as session: association = session.get(UserPolicy, created.association_id) association.description = "Native description" - with sessions.begin() as session: + with v2_owner_sessions.begin() as session: rename_result = mirror_legacy_user_policy_in_session( session, renamed, @@ -336,7 +303,7 @@ def test_label_and_v1_only_updates_advance_the_complete_row_fingerprint() -> Non source_revision=2, changed_fields=frozenset({"reform_label", "updated_date"}), ) - with sessions() as session: + with v2_owner_sessions() as session: after_rename = session.get(UserPolicy, created.association_id) mapping = session.scalar( select(LegacyUserPolicyMapping).where( @@ -348,15 +315,15 @@ def test_label_and_v1_only_updates_advance_the_complete_row_fingerprint() -> Non assert mapping.fingerprint_sha256 == fingerprint_legacy_user_policy(renamed) v1_only = renamed.model_copy(update={"year": "2027", "updated_date": 4}) - with sessions.begin() as session: + with v2_owner_sessions.begin() as session: association = session.get(UserPolicy, created.association_id) association.name = "Native name" - with sessions() as session: + with v2_owner_sessions() as session: native_timestamp = session.get( UserPolicy, created.association_id, ).updated_at - with sessions.begin() as session: + with v2_owner_sessions.begin() as session: v1_only_result = mirror_legacy_user_policy_in_session( session, v1_only, @@ -364,7 +331,7 @@ def test_label_and_v1_only_updates_advance_the_complete_row_fingerprint() -> Non source_revision=3, changed_fields=frozenset({"year", "updated_date"}), ) - with sessions() as session: + with v2_owner_sessions() as session: association = session.get(UserPolicy, created.association_id) mapping = session.scalar( select(LegacyUserPolicyMapping).where( @@ -379,21 +346,20 @@ def test_label_and_v1_only_updates_advance_the_complete_row_fingerprint() -> Non assert association.updated_at == native_timestamp assert mapping.fingerprint_sha256 == fingerprint_legacy_user_policy(v1_only) finally: - _cleanup(engine, model_id) - engine.dispose() + _cleanup(v2_owner_sessions, model_id) -def test_complete_transaction_rolls_back_and_native_delete_is_isolated() -> None: - engine = create_engine(_disposable_url()) - sessions = sessionmaker(engine, class_=Session, expire_on_commit=False) +def test_complete_transaction_rolls_back_and_native_delete_is_isolated( + v2_owner_sessions: sessionmaker[Session], +) -> None: model_id = None try: - model_id, parameter_name = _seed_catalog(sessions) + model_id, parameter_name = _seed_catalog(v2_owner_sessions) reform = _reform(parameter_name, legacy_id=501, source_hash="rollback") saved = _saved(legacy_id=601, reform_id=501) def mirror_then_fail() -> None: - with sessions.begin() as session: + with v2_owner_sessions.begin() as session: mirror_legacy_user_policy_in_session( session, saved, @@ -406,7 +372,7 @@ def mirror_then_fail() -> None: with pytest.raises(RuntimeError, match="forced rollback"): mirror_then_fail() - with sessions() as session: + with v2_owner_sessions() as session: assert session.scalar(select(func.count()).select_from(Policy)) == 0 assert session.scalar(select(func.count()).select_from(UserPolicy)) == 0 assert session.scalar(select(func.count()).select_from(User)) == 0 @@ -424,18 +390,18 @@ def mirror_then_fail() -> None: == 0 ) - with sessions.begin() as session: + with v2_owner_sessions.begin() as session: created = mirror_legacy_user_policy_in_session( session, saved, reform, source_revision=1, ) - with sessions.begin() as session: + with v2_owner_sessions.begin() as session: association = session.get(UserPolicy, created.association_id) session.delete(association) - with sessions() as session: + with v2_owner_sessions() as session: assert session.get(UserPolicy, created.association_id) is None assert ( session.scalar( @@ -457,5 +423,4 @@ def mirror_then_fail() -> None: == 1 ) finally: - _cleanup(engine, model_id) - engine.dispose() + _cleanup(v2_owner_sessions, model_id) diff --git a/tests/integration/test_v2_user_report_run_requesters.py b/tests/integration/test_v2_user_report_run_requesters.py index 996ea480e..297691225 100644 --- a/tests/integration/test_v2_user_report_run_requesters.py +++ b/tests/integration/test_v2_user_report_run_requesters.py @@ -9,18 +9,17 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING from uuid import UUID, uuid4 import pytest from alembic import command from alembic.config import Config -from sqlalchemy import create_engine, text -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import NullPool -from sqlmodel import Session +from sqlalchemy import delete, select +from sqlmodel import col from policyengine_api.constants import REPO +from policyengine_api.data.v2.models import User, UserIdentity from policyengine_api.services.v2.identity.services import ( convert_unauthenticated_user_in_session, resolve_principal_user_in_session, @@ -29,6 +28,7 @@ AccountConversionOutcome, UserPrincipal, ) +from tests.integration.simulation_rows import add_row from tests.integration.stored_report_rows import delete_catalog, store_catalog from tests.integration.user_report_run_support import ( JoiningSimulationService, @@ -39,9 +39,10 @@ ) if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator - from sqlalchemy import Engine + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session from tests.integration.stored_report_rows import CatalogRows @@ -49,65 +50,59 @@ @pytest.fixture -def owner_engine(disposable_v2_database_url: str) -> Iterator[Engine]: +def owner_sessions(v2_owner_sessions: sessionmaker[Session]) -> sessionmaker[Session]: command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - yield engine - engine.dispose() + return v2_owner_sessions @pytest.fixture -def catalog(owner_engine: Engine) -> Iterator[CatalogRows]: - with owner_engine.begin() as connection: - stored = store_catalog(connection, "us") +def catalog(owner_sessions: sessionmaker[Session]) -> Iterator[CatalogRows]: + with owner_sessions.begin() as session: + stored = store_catalog(session, "us") yield stored - with owner_engine.begin() as connection: - delete_catalog(connection, stored) + with owner_sessions.begin() as session: + delete_catalog(session, stored) @pytest.fixture -def runtime_sessions(managed_v2_roles, v2_engine_as_role) -> Iterator[Any]: - engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - yield sessionmaker(engine, class_=Session) - engine.dispose() +def runtime_sessions( + managed_v2_roles, v2_sessions_as_role: Callable[[str], sessionmaker[Session]] +) -> sessionmaker[Session]: + return v2_sessions_as_role(managed_v2_roles.runtime) @pytest.fixture -def user_ids(owner_engine: Engine) -> Iterator[list[UUID]]: +def user_ids(owner_sessions: sessionmaker[Session]) -> Iterator[list[UUID]]: """Collect the users a test makes, and delete them and their records after.""" collected: list[UUID] = [] yield collected - with owner_engine.begin() as connection: - connection.execute( - text("DELETE FROM users WHERE id = ANY(:ids)"), {"ids": collected} - ) + with owner_sessions.begin() as session: + session.execute(delete(User).where(col(User.id).in_(collected))) -def store_browser_user(engine: Engine, browser_id: UUID) -> None: - with engine.begin() as connection: - connection.execute( - text("INSERT INTO users (id, user_type) VALUES (:id, 'unauthenticated')"), - {"id": browser_id}, - ) +def store_browser_user(owner_sessions: sessionmaker[Session], browser_id: UUID) -> None: + with owner_sessions.begin() as session: + add_row(session, User, id=browser_id, user_type="unauthenticated") -def user_type(engine: Engine, user_id: UUID) -> str | None: - with engine.begin() as connection: - return connection.execute( - text("SELECT user_type FROM users WHERE id = :id"), {"id": user_id} +def user_type(owner_sessions: sessionmaker[Session], user_id: UUID) -> str | None: + with owner_sessions.begin() as session: + stored_type: str | None = session.execute( + select(col(User.user_type)).where(col(User.id) == user_id) ).scalar_one_or_none() + return stored_type def test_a_signed_in_users_request_provisions_and_records_that_user( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], user_ids: list[UUID], ) -> None: signed_in = UserPrincipal(issuer=ISSUER, subject=f"auth0|{uuid4()}") client = client_for( runtime_sessions, - JoiningSimulationService(owner_engine, catalog), + JoiningSimulationService(owner_sessions, catalog), requester=signed_in, ) @@ -116,28 +111,27 @@ def test_a_signed_in_users_request_provisions_and_records_that_user( ) assert response.status_code == 201, response.text - with owner_engine.begin() as connection: - signed_in_user_id = connection.execute( - text( - "SELECT user_id FROM user_identities WHERE issuer = :issuer AND " - "subject = :subject" - ), - {"issuer": ISSUER, "subject": signed_in.subject}, + with owner_sessions.begin() as session: + signed_in_user_id = session.execute( + select(col(UserIdentity.user_id)).where( + col(UserIdentity.issuer) == ISSUER, + col(UserIdentity.subject) == signed_in.subject, + ) ).scalar_one() user_ids.append(signed_in_user_id) - (record,) = stored_records(owner_engine, [signed_in_user_id]) + (record,) = stored_records(owner_sessions, [signed_in_user_id]) assert str(record.report_run_id) == response.json()["result"]["item"]["run"]["id"] - assert user_type(owner_engine, signed_in_user_id) == "standard" + assert user_type(owner_sessions, signed_in_user_id) == "standard" def test_a_browser_merged_while_the_service_is_asked_is_not_recorded_again( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], user_ids: list[UUID], ) -> None: browser_id = uuid4() - store_browser_user(owner_engine, browser_id) + store_browser_user(owner_sessions, browser_id) account = UserPrincipal(issuer=ISSUER, subject=f"auth0|{uuid4()}") with runtime_sessions.begin() as session: account_id = resolve_principal_user_in_session( @@ -158,7 +152,7 @@ def sign_in_and_merge() -> None: ) simulation_service = JoiningSimulationService( - owner_engine, catalog, during_call=sign_in_and_merge + owner_sessions, catalog, during_call=sign_in_and_merge ) response = client_for(runtime_sessions, simulation_service).post( @@ -173,18 +167,18 @@ def sign_in_and_merge() -> None: assert body["report_id"] == str(catalog.report_ids[-1]) assert UUID(body["run_id"]) # The browser's user stays merged away, and nobody holds the record. - assert user_type(owner_engine, browser_id) is None - assert stored_records(owner_engine, [browser_id, account_id]) == [] + assert user_type(owner_sessions, browser_id) is None + assert stored_records(owner_sessions, [browser_id, account_id]) == [] def test_a_browser_converted_while_the_service_is_asked_is_recorded_as_itself( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], user_ids: list[UUID], ) -> None: browser_id = uuid4() - store_browser_user(owner_engine, browser_id) + store_browser_user(owner_sessions, browser_id) user_ids.append(browser_id) new_account = UserPrincipal(issuer=ISSUER, subject=f"auth0|{uuid4()}") outcomes: list[AccountConversionOutcome] = [] @@ -201,7 +195,7 @@ def sign_in_and_convert() -> None: ) simulation_service = JoiningSimulationService( - owner_engine, catalog, during_call=sign_in_and_convert + owner_sessions, catalog, during_call=sign_in_and_convert ) response = client_for(runtime_sessions, simulation_service).post( @@ -212,6 +206,6 @@ def sign_in_and_convert() -> None: assert outcomes == [AccountConversionOutcome.CONVERTED] assert response.status_code == 201, response.text - (record,) = stored_records(owner_engine, [browser_id]) + (record,) = stored_records(owner_sessions, [browser_id]) assert str(record.report_run_id) == response.json()["result"]["item"]["run"]["id"] - assert user_type(owner_engine, browser_id) == "standard" + assert user_type(owner_sessions, browser_id) == "standard" diff --git a/tests/integration/test_v2_user_report_runs.py b/tests/integration/test_v2_user_report_runs.py index abbaa0759..097c4d1c6 100644 --- a/tests/integration/test_v2_user_report_runs.py +++ b/tests/integration/test_v2_user_report_runs.py @@ -12,18 +12,17 @@ from __future__ import annotations from datetime import UTC, datetime, timedelta -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING from uuid import UUID, uuid4 import pytest from alembic import command from alembic.config import Config -from sqlalchemy import create_engine, text -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import NullPool -from sqlmodel import Session +from sqlalchemy import delete, func, select +from sqlmodel import col from policyengine_api.constants import REPO +from policyengine_api.data.v2.models import ReportRun, User, UserReportRunAssociation from policyengine_api.libs.user_auth import UNAUTHENTICATED_USER_HEADER from policyengine_api.services.v2.identity.services import ( convert_unauthenticated_user_in_session, @@ -42,6 +41,7 @@ UserReportCreateFields, UserReportUpdateInput, ) +from tests.integration.simulation_rows import add_row from tests.integration.stored_report_rows import ( STARTED_AT, BudgetWindowYear, @@ -73,46 +73,47 @@ from tests.unit.v2.user_service_support import default_legacy_references if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator - from sqlalchemy import Engine + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session from tests.integration.stored_report_rows import CatalogRows @pytest.fixture -def owner_engine(disposable_v2_database_url: str) -> Iterator[Engine]: +def owner_sessions(v2_owner_sessions: sessionmaker[Session]) -> sessionmaker[Session]: command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - yield engine - engine.dispose() + return v2_owner_sessions @pytest.fixture -def catalog(owner_engine: Engine) -> Iterator[CatalogRows]: - with owner_engine.begin() as connection: - stored = store_catalog(connection, "us") +def catalog(owner_sessions: sessionmaker[Session]) -> Iterator[CatalogRows]: + with owner_sessions.begin() as session: + stored = store_catalog(session, "us") yield stored - with owner_engine.begin() as connection: - delete_catalog(connection, stored) + with owner_sessions.begin() as session: + delete_catalog(session, stored) @pytest.fixture -def runtime_sessions(managed_v2_roles, v2_engine_as_role) -> Iterator[Any]: - engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - yield sessionmaker(engine, class_=Session) - engine.dispose() +def runtime_sessions( + managed_v2_roles, v2_sessions_as_role: Callable[[str], sessionmaker[Session]] +) -> sessionmaker[Session]: + return v2_sessions_as_role(managed_v2_roles.runtime) def test_a_create_that_joins_a_run_answers_that_run_not_the_reports_newest( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - with owner_engine.begin() as connection: + with owner_sessions.begin() as session: report, joined_run_id, _forced_run_id = store_joined_and_newer_forced_run( - connection, catalog, joined_status="succeeded" + session, catalog, joined_status="succeeded" ) simulation_service = JoiningSimulationService( - owner_engine, + owner_sessions, catalog, joined_run=JoinedRun(report_id=report.report_id, report_run_id=joined_run_id), ) @@ -129,14 +130,16 @@ def test_a_create_that_joins_a_run_answers_that_run_not_the_reports_newest( def test_a_rerun_while_a_run_is_under_way_answers_201_with_that_run( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - with owner_engine.begin() as connection: + with owner_sessions.begin() as session: report, joined_run_id, _forced_run_id = store_joined_and_newer_forced_run( - connection, catalog, joined_status="pending" + session, catalog, joined_status="pending" ) simulation_service = JoiningSimulationService( - owner_engine, + owner_sessions, catalog, joined_run=JoinedRun(report_id=report.report_id, report_run_id=joined_run_id), ) @@ -152,10 +155,12 @@ def test_a_rerun_while_a_run_is_under_way_answers_201_with_that_run( def test_a_budget_window_rerun_answers_the_window_run_it_joined( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - with owner_engine.begin() as connection: - window = store_report(connection, catalog, budget_window_size=2) + with owner_sessions.begin() as session: + window = store_report(session, catalog, budget_window_size=2) window_run_ids = [] first_year_run_ids = [] for days_later in (0, 1): @@ -165,15 +170,13 @@ def test_a_budget_window_rerun_answers_the_window_run_it_joined( created_at=STARTED_AT + timedelta(days=days_later), forced=days_later == 1, ) - window_run_id = store_budget_window_run( - connection, catalog, window, settings - ) + window_run_id = store_budget_window_run(session, catalog, window, settings) window_run_ids.append(window_run_id) for year in WINDOW_YEARS: year_run = store_report_run( - connection, + session, catalog, - store_year_simulations(connection, catalog, window, year), + store_year_simulations(session, catalog, window, year), RunSettings( versions=CURRENT_VERSIONS, status="pending", @@ -192,7 +195,7 @@ def test_a_budget_window_rerun_answers_the_window_run_it_joined( budget_window_run_id=window_run_ids[0], ) simulation_service = JoiningSimulationService( - owner_engine, catalog, joined_run=joined + owner_sessions, catalog, joined_run=joined ) response = client_for(runtime_sessions, simulation_service).post( @@ -206,23 +209,21 @@ def test_a_budget_window_rerun_answers_the_window_run_it_joined( @pytest.fixture -def browsers(owner_engine: Engine) -> Iterator[list[UUID]]: +def browsers(owner_sessions: sessionmaker[Session]) -> Iterator[list[UUID]]: """Name signed-out browsers' users, and delete them and their records after.""" browser_ids = [uuid4() for _ in range(2)] yield browser_ids - with owner_engine.begin() as connection: - connection.execute( - text("DELETE FROM users WHERE id = ANY(:ids)"), {"ids": browser_ids} - ) + with owner_sessions.begin() as session: + session.execute(delete(User).where(col(User.id).in_(browser_ids))) def test_a_create_with_a_signed_out_browsers_credential_records_its_run( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], browsers: list[UUID], ) -> None: - simulation_service = JoiningSimulationService(owner_engine, catalog) + simulation_service = JoiningSimulationService(owner_sessions, catalog) asked_at = datetime.now(UTC) response = client_for(runtime_sessions, simulation_service).post( @@ -233,7 +234,7 @@ def test_a_create_with_a_signed_out_browsers_credential_records_its_run( assert response.status_code == 201, response.text run_id = UUID(response.json()["result"]["item"]["run"]["id"]) - (record,) = stored_records(owner_engine, browsers) + (record,) = stored_records(owner_sessions, browsers) assert (record.user_id, record.report_run_id, record.trigger) == ( browsers[0], run_id, @@ -243,17 +244,17 @@ def test_a_create_with_a_signed_out_browsers_credential_records_its_run( def test_two_users_who_join_one_run_each_record_it( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], browsers: list[UUID], ) -> None: - with owner_engine.begin() as connection: + with owner_sessions.begin() as session: report, joined_run_id, _forced_run_id = store_joined_and_newer_forced_run( - connection, catalog, joined_status="pending" + session, catalog, joined_status="pending" ) simulation_service = JoiningSimulationService( - owner_engine, + owner_sessions, catalog, joined_run=JoinedRun(report_id=report.report_id, report_run_id=joined_run_id), ) @@ -269,7 +270,7 @@ def test_two_users_who_join_one_run_each_record_it( ] assert [answer.status_code for answer in answers] == [201, 201] - records = stored_records(owner_engine, browsers) + records = stored_records(owner_sessions, browsers) assert {(record.user_id, record.report_run_id) for record in records} == { (browsers[0], joined_run_id), (browsers[1], joined_run_id), @@ -277,17 +278,17 @@ def test_two_users_who_join_one_run_each_record_it( def test_a_user_asking_again_for_a_run_they_have_keeps_their_first_record( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], browsers: list[UUID], ) -> None: - with owner_engine.begin() as connection: + with owner_sessions.begin() as session: report, joined_run_id, _forced_run_id = store_joined_and_newer_forced_run( - connection, catalog, joined_status="pending" + session, catalog, joined_status="pending" ) simulation_service = JoiningSimulationService( - owner_engine, + owner_sessions, catalog, joined_run=JoinedRun(report_id=report.report_id, report_run_id=joined_run_id), ) @@ -297,7 +298,7 @@ def test_a_user_asking_again_for_a_run_they_have_keeps_their_first_record( json=report_body(catalog.policy_id), headers=as_browser(browsers[0]), ) - (first_record,) = stored_records(owner_engine, browsers) + (first_record,) = stored_records(owner_sessions, browsers) again = client.post( f"/v2/reports/{report.report_id}/runs?country_id=us", @@ -306,19 +307,19 @@ def test_a_user_asking_again_for_a_run_they_have_keeps_their_first_record( ) assert (first.status_code, again.status_code) == (201, 201) - assert stored_records(owner_engine, browsers) == [first_record] + assert stored_records(owner_sessions, browsers) == [first_record] assert first_record.trigger == "initial" def test_a_rerun_records_a_manual_request_for_the_run_it_ended_on( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], browsers: list[UUID], ) -> None: - with owner_engine.begin() as connection: - report = store_report(connection, catalog) - simulation_service = JoiningSimulationService(owner_engine, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) + simulation_service = JoiningSimulationService(owner_sessions, catalog) response = client_for(runtime_sessions, simulation_service).post( f"/v2/reports/{report.report_id}/runs?country_id=us", @@ -328,50 +329,50 @@ def test_a_rerun_records_a_manual_request_for_the_run_it_ended_on( assert response.status_code == 201, response.text run_id = UUID(response.json()["result"]["item"]["run"]["id"]) - (record,) = stored_records(owner_engine, browsers) + (record,) = stored_records(owner_sessions, browsers) assert (record.report_run_id, record.trigger) == (run_id, "manual") (rerun,) = simulation_service.reruns assert rerun.force is False def test_a_request_without_a_user_credential_records_nothing( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - simulation_service = JoiningSimulationService(owner_engine, catalog) + simulation_service = JoiningSimulationService(owner_sessions, catalog) response = client_for(runtime_sessions, simulation_service).post( "/v2/reports?country_id=us", json=report_body(catalog.policy_id) ) assert response.status_code == 201, response.text - run_id = response.json()["result"]["item"]["run"]["id"] - with owner_engine.begin() as connection: - recorded = connection.execute( - text( - "SELECT count(*) FROM user_report_run_associations WHERE " - "report_run_id = :id" - ), - {"id": run_id}, + run_id = UUID(response.json()["result"]["item"]["run"]["id"]) + with owner_sessions.begin() as session: + recorded = session.execute( + select(func.count()) + .select_from(UserReportRunAssociation) + .where(col(UserReportRunAssociation.report_run_id) == run_id) ).scalar_one() assert recorded == 0 def test_a_browser_credential_naming_a_signed_in_user_is_refused_before_asking( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], browsers: list[UUID], ) -> None: signed_in_user_id = browsers[0] - with owner_engine.begin() as connection: - connection.execute( - text( - "INSERT INTO users (id, user_type, primary_country) VALUES " - "(:id, 'standard', 'us')" - ), - {"id": signed_in_user_id}, + with owner_sessions.begin() as session: + add_row( + session, + User, + id=signed_in_user_id, + user_type="standard", + primary_country="us", ) - simulation_service = JoiningSimulationService(owner_engine, catalog) + simulation_service = JoiningSimulationService(owner_sessions, catalog) response = client_for(runtime_sessions, simulation_service).post( "/v2/reports?country_id=us", @@ -382,13 +383,15 @@ def test_a_browser_credential_naming_a_signed_in_user_is_refused_before_asking( assert response.status_code == 401, response.text assert response.headers["WWW-Authenticate"] == "Bearer" assert simulation_service.reports == [] - assert stored_records(owner_engine, browsers) == [] + assert stored_records(owner_sessions, browsers) == [] def test_a_malformed_browser_credential_is_refused_before_asking( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - simulation_service = JoiningSimulationService(owner_engine, catalog) + simulation_service = JoiningSimulationService(owner_sessions, catalog) response = client_for(runtime_sessions, simulation_service).post( "/v2/reports?country_id=us", @@ -401,28 +404,28 @@ def test_a_malformed_browser_credential_is_refused_before_asking( def test_a_saved_reports_last_run_at_is_its_owners_newest_request( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], browsers: list[UUID], ) -> None: # An admin, who may force a re-run, so each re-run is a new run. owner, owner_id = store_signed_in_user( - runtime_sessions, owner_engine, user_type="admin" + runtime_sessions, owner_sessions, user_type="admin" ) browsers.append(owner_id) other_user_id = browsers[0] - with owner_engine.begin() as connection: - report = store_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) saved_report_id = store_saved_report( - owner_engine, user_id=owner_id, report_id=report.report_id + owner_sessions, user_id=owner_id, report_id=report.report_id ) others_saved_report_id = store_saved_report( - owner_engine, user_id=other_user_id, report_id=report.report_id + owner_sessions, user_id=other_user_id, report_id=report.report_id ) client = client_for( runtime_sessions, - JoiningSimulationService(owner_engine, catalog), + JoiningSimulationService(owner_sessions, catalog), requester=owner, ) @@ -434,19 +437,19 @@ def test_a_saved_reports_last_run_at_is_its_owners_newest_request( assert response.status_code == 201, response.text newest_request = max( - record.requested_at for record in stored_records(owner_engine, [owner_id]) + record.requested_at for record in stored_records(owner_sessions, [owner_id]) ) - assert saved_report_last_run_at(owner_engine, saved_report_id) == newest_request - assert saved_report_last_run_at(owner_engine, others_saved_report_id) is None + assert saved_report_last_run_at(owner_sessions, saved_report_id) == newest_request + assert saved_report_last_run_at(owner_sessions, others_saved_report_id) is None def test_a_run_whose_record_cannot_be_written_answers_503_naming_it( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], browsers: list[UUID], ) -> None: - simulation_service = JoiningSimulationService(owner_engine, catalog) + simulation_service = JoiningSimulationService(owner_sessions, catalog) response = client_for( runtime_sessions, @@ -461,33 +464,32 @@ def test_a_run_whose_record_cannot_be_written_answers_503_naming_it( assert response.status_code == 503, response.text body = response.json() report_id = catalog.report_ids[-1] - with owner_engine.begin() as connection: - run_id = connection.execute( - text("SELECT id FROM report_runs WHERE report_id = :id"), - {"id": report_id}, + with owner_sessions.begin() as session: + run_id = session.execute( + select(col(ReportRun.id)).where(col(ReportRun.report_id) == report_id) ).scalar_one() assert body["report_id"] == str(report_id) assert body["run_id"] == str(run_id) assert f"run_id={run_id}" in body["message"] - assert stored_records(owner_engine, browsers) == [] + assert stored_records(owner_sessions, browsers) == [] def test_a_sign_in_merge_moves_the_browsers_run_records_into_the_account( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], browsers: list[UUID], ) -> None: browser_id = browsers[0] - with owner_engine.begin() as connection: + with owner_sessions.begin() as session: alone_report, alone_run_id, _ = store_joined_and_newer_forced_run( - connection, catalog, joined_status="pending" + session, catalog, joined_status="pending" ) shared_report, shared_run_id, _ = store_joined_and_newer_forced_run( - connection, catalog, joined_status="pending" + session, catalog, joined_status="pending" ) accounts_own_report, accounts_own_run_id, _ = store_joined_and_newer_forced_run( - connection, catalog, joined_status="pending" + session, catalog, joined_status="pending" ) account = UserPrincipal(issuer="https://users.example.test/", subject="auth0|merge") with runtime_sessions.begin() as session: @@ -498,35 +500,31 @@ def test_a_sign_in_merge_moves_the_browsers_run_records_into_the_account( account_asked_at = datetime(2026, 1, 1, tzinfo=UTC) # Later than any request the browser makes in this test. account_asked_for_its_own_at = datetime(2030, 1, 1, tzinfo=UTC) - with owner_engine.begin() as connection: + with owner_sessions.begin() as session: for run_id, requested_at in ( (shared_run_id, account_asked_at), (accounts_own_run_id, account_asked_for_its_own_at), ): - connection.execute( - text( - "INSERT INTO user_report_run_associations (id, user_id, " - "report_run_id, requested_at, trigger) VALUES (:id, " - ":user_id, :run_id, :requested_at, 'initial')" - ), - { - "id": uuid4(), - "user_id": account_id, - "run_id": run_id, - "requested_at": requested_at, - }, + add_row( + session, + UserReportRunAssociation, + id=uuid4(), + user_id=account_id, + report_run_id=run_id, + requested_at=requested_at, + trigger="initial", ) account_saved_report_id = store_saved_report( - owner_engine, user_id=account_id, report_id=alone_report.report_id + owner_sessions, user_id=account_id, report_id=alone_report.report_id ) browser_saved_report_id = store_saved_report( - owner_engine, user_id=browser_id, report_id=shared_report.report_id + owner_sessions, user_id=browser_id, report_id=shared_report.report_id ) # The browser saved a report it never asked to run, but the account did. browsers_unrun_saved_report_id = store_saved_report( - owner_engine, user_id=browser_id, report_id=accounts_own_report.report_id + owner_sessions, user_id=browser_id, report_id=accounts_own_report.report_id ) - simulation_service = JoiningSimulationService(owner_engine, catalog) + simulation_service = JoiningSimulationService(owner_sessions, catalog) client = client_for(runtime_sessions, simulation_service) for report, run_id in ( (alone_report, alone_run_id), @@ -543,7 +541,7 @@ def test_a_sign_in_merge_moves_the_browsers_run_records_into_the_account( assert response.status_code == 201, response.text browser_asked_at = { record.report_run_id: record.requested_at - for record in stored_records(owner_engine, [browser_id]) + for record in stored_records(owner_sessions, [browser_id]) } with runtime_sessions.begin() as session: @@ -555,7 +553,7 @@ def test_a_sign_in_merge_moves_the_browsers_run_records_into_the_account( ) assert conversion.outcome is AccountConversionOutcome.MERGED - records = stored_records(owner_engine, [account_id, browser_id]) + records = stored_records(owner_sessions, [account_id, browser_id]) # A run the account had already asked for keeps the account's record. assert { (record.user_id, record.report_run_id, record.requested_at) @@ -571,40 +569,40 @@ def test_a_sign_in_merge_moves_the_browsers_run_records_into_the_account( # moved in, and the browser's moved saved reports take the account's # records, whatever time they held before. assert ( - saved_report_last_run_at(owner_engine, account_saved_report_id) + saved_report_last_run_at(owner_sessions, account_saved_report_id) == browser_asked_at[alone_run_id] ) assert ( - saved_report_last_run_at(owner_engine, browser_saved_report_id) + saved_report_last_run_at(owner_sessions, browser_saved_report_id) == account_asked_at ) assert ( - saved_report_last_run_at(owner_engine, browsers_unrun_saved_report_id) + saved_report_last_run_at(owner_sessions, browsers_unrun_saved_report_id) == account_asked_for_its_own_at ) def test_saving_or_repointing_a_report_takes_its_owners_newest_request( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], browsers: list[UUID], ) -> None: owner_id = browsers[0] owner = UnauthenticatedPrincipal(user_id=owner_id) - with owner_engine.begin() as connection: - first_report = store_report(connection, catalog) - second_report = store_report(connection, catalog) - never_run_report = store_report(connection, catalog) + with owner_sessions.begin() as session: + first_report = store_report(session, catalog) + second_report = store_report(session, catalog) + never_run_report = store_report(session, catalog) client = client_for( - runtime_sessions, JoiningSimulationService(owner_engine, catalog) + runtime_sessions, JoiningSimulationService(owner_sessions, catalog) ) saved_reports = V2UserReportService( UserReportDatabaseSession(runtime_sessions), default_legacy_references() ) callers_time = datetime(2020, 1, 1, tzinfo=UTC) rerun_as_browser(client, first_report.report_id, owner_id) - first_request = newest_request(owner_engine, owner_id) + first_request = newest_request(owner_sessions, owner_id) saved = saved_reports.create_user_report( principal=owner, @@ -623,7 +621,7 @@ def test_saving_or_repointing_a_report_takes_its_owners_newest_request( ), ) rerun_as_browser(client, second_report.report_id, owner_id) - second_request = newest_request(owner_engine, owner_id) + second_request = newest_request(owner_sessions, owner_id) repointed = saved_reports.patch_user_report( principal=owner, country_id="us", @@ -652,17 +650,17 @@ def test_saving_or_repointing_a_report_takes_its_owners_newest_request( @pytest.mark.parametrize("request_kind", ["create", "rerun"]) def test_a_run_that_cannot_be_read_back_is_named_in_the_502( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], request_kind: str, ) -> None: - with owner_engine.begin() as connection: - report = store_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) # The answer names a run the report doesn't have, so reading it back fails. unreadable_run_id = uuid4() simulation_service = JoiningSimulationService( - owner_engine, + owner_sessions, catalog, joined_run=JoinedRun( report_id=report.report_id, report_run_id=unreadable_run_id diff --git a/tests/integration/test_v2_user_report_views.py b/tests/integration/test_v2_user_report_views.py index 9d47fc198..0c85b67e0 100644 --- a/tests/integration/test_v2_user_report_views.py +++ b/tests/integration/test_v2_user_report_views.py @@ -17,12 +17,15 @@ import pytest from alembic import command from alembic.config import Config -from sqlalchemy import create_engine, text -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import NullPool -from sqlmodel import Session +from sqlalchemy import delete, update +from sqlmodel import col from policyengine_api.constants import REPO +from policyengine_api.data.v2.models import ( + BudgetWindowRun, + User, + UserReportAssociation, +) from policyengine_api.libs.user_auth import UNAUTHENTICATED_USER_HEADER from tests.fixtures.economy_results import us_economy_result from tests.integration.stored_report_rows import ( @@ -44,9 +47,10 @@ ) if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator - from sqlalchemy import Connection, Engine + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session from tests.integration.stored_report_rows import CatalogRows, StoredReport @@ -54,42 +58,38 @@ @pytest.fixture -def owner_engine(disposable_v2_database_url: str) -> Iterator[Engine]: +def owner_sessions(v2_owner_sessions: sessionmaker[Session]) -> sessionmaker[Session]: command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") - engine = create_engine(disposable_v2_database_url, poolclass=NullPool) - yield engine - engine.dispose() + return v2_owner_sessions @pytest.fixture -def catalog(owner_engine: Engine) -> Iterator[CatalogRows]: - with owner_engine.begin() as connection: - stored = store_catalog(connection, "us") +def catalog(owner_sessions: sessionmaker[Session]) -> Iterator[CatalogRows]: + with owner_sessions.begin() as session: + stored = store_catalog(session, "us") yield stored - with owner_engine.begin() as connection: - delete_catalog(connection, stored) + with owner_sessions.begin() as session: + delete_catalog(session, stored) @pytest.fixture -def runtime_sessions(managed_v2_roles, v2_engine_as_role) -> Iterator[Any]: - engine = v2_engine_as_role(managed_v2_roles.runtime, poolclass=NullPool) - yield sessionmaker(engine, class_=Session) - engine.dispose() +def runtime_sessions( + managed_v2_roles, v2_sessions_as_role: Callable[[str], sessionmaker[Session]] +) -> sessionmaker[Session]: + return v2_sessions_as_role(managed_v2_roles.runtime) @pytest.fixture -def browsers(owner_engine: Engine) -> Iterator[list[UUID]]: +def browsers(owner_sessions: sessionmaker[Session]) -> Iterator[list[UUID]]: """Name signed-out browsers' users, and delete them and their records after.""" browser_ids = [uuid4() for _ in range(2)] yield browser_ids - with owner_engine.begin() as connection: - connection.execute( - text("DELETE FROM users WHERE id = ANY(:ids)"), {"ids": browser_ids} - ) + with owner_sessions.begin() as session: + session.execute(delete(User).where(col(User.id).in_(browser_ids))) def store_run( # noqa: PLR0913 # each run differs in a keyword-only setting - connection: Connection, + session: Session, catalog: CatalogRows, report: StoredReport, *, @@ -100,7 +100,7 @@ def store_run( # noqa: PLR0913 # each run differs in a keyword-only setting ) -> UUID: """Store a run of the report, with its result once it succeeded.""" return store_report_run( - connection, + session, catalog, report, RunSettings( @@ -120,41 +120,43 @@ def read_item(client: Any, report_id: UUID, headers: dict[str, str] | None = Non def test_without_a_record_the_newest_succeeded_unforced_run_is_read( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - with owner_engine.begin() as connection: - report = store_report(connection, catalog) - store_run(connection, catalog, report, days_later=0, status="failed") + with owner_sessions.begin() as session: + report = store_report(session, catalog) + store_run(session, catalog, report, days_later=0, status="failed") succeeded = store_run( - connection, catalog, report, days_later=1, status="succeeded" + session, catalog, report, days_later=1, status="succeeded" ) store_run( - connection, catalog, report, days_later=2, status="succeeded", forced=True + session, catalog, report, days_later=2, status="succeeded", forced=True ) store_run( - connection, + session, catalog, report, days_later=3, status="pending", versions=NEWER_VERSIONS, ) - only_forced = store_report(connection, catalog) + only_forced = store_report(session, catalog) store_run( - connection, + session, catalog, only_forced, days_later=0, status="succeeded", forced=True, ) - unsucceeded = store_report(connection, catalog) - store_run(connection, catalog, unsucceeded, days_later=0, status="failed") + unsucceeded = store_report(session, catalog) + store_run(session, catalog, unsucceeded, days_later=0, status="failed") newest_unforced = store_run( - connection, catalog, unsucceeded, days_later=1, status="pending" + session, catalog, unsucceeded, days_later=1, status="pending" ) client = client_for( - runtime_sessions, JoiningSimulationService(owner_engine, catalog) + runtime_sessions, JoiningSimulationService(owner_sessions, catalog) ) item = read_item(client, report.report_id) @@ -177,19 +179,19 @@ def test_without_a_record_the_newest_succeeded_unforced_run_is_read( def test_a_user_reads_their_own_newest_recorded_run( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], browsers: list[UUID], ) -> None: asker, other_user = browsers - with owner_engine.begin() as connection: - report = store_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) first_asked = store_run( - connection, catalog, report, days_later=0, status="succeeded" + session, catalog, report, days_later=0, status="succeeded" ) newest_asked = store_run( - connection, + session, catalog, report, days_later=1, @@ -197,14 +199,14 @@ def test_a_user_reads_their_own_newest_recorded_run( versions=NEWER_VERSIONS, ) newest_succeeded = store_run( - connection, + session, catalog, report, days_later=2, status="succeeded", versions={**CURRENT_VERSIONS, "policyengine_version": "4.4.0"}, ) - simulation_service = JoiningSimulationService(owner_engine, catalog) + simulation_service = JoiningSimulationService(owner_sessions, catalog) client = client_for(runtime_sessions, simulation_service) for run_id in (first_asked, newest_asked): simulation_service.joined_run = JoinedRun( @@ -236,21 +238,21 @@ def test_a_user_reads_their_own_newest_recorded_run( def test_a_user_reads_the_window_run_of_their_newest_recorded_year( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], browsers: list[UUID], ) -> None: asker = browsers[0] - with owner_engine.begin() as connection: + with owner_sessions.begin() as session: asked = store_window( - connection, + session, catalog, years=(2026, 2027), settings=RunSettings(versions=CURRENT_VERSIONS, status="running"), ) store_window( - connection, + session, catalog, years=(2026, 2027), settings=RunSettings( @@ -261,7 +263,7 @@ def test_a_user_reads_the_window_run_of_their_newest_recorded_year( report=asked.report, ) simulation_service = JoiningSimulationService( - owner_engine, + owner_sessions, catalog, joined_run=JoinedRun( report_id=asked.report.report_id, @@ -285,25 +287,23 @@ def test_a_user_reads_the_window_run_of_their_newest_recorded_year( def test_a_reports_label_and_description_are_the_users_saved_reports( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], browsers: list[UUID], ) -> None: saver, other_user = browsers - with owner_engine.begin() as connection: - report = store_report(connection, catalog) - store_saved_report(owner_engine, user_id=saver, report_id=report.report_id) - with owner_engine.begin() as connection: - connection.execute( - text( - "UPDATE user_report_associations SET description = 'Mine' " - "WHERE user_id = :user_id" - ), - {"user_id": saver}, + with owner_sessions.begin() as session: + report = store_report(session, catalog) + store_saved_report(owner_sessions, user_id=saver, report_id=report.report_id) + with owner_sessions.begin() as session: + session.execute( + update(UserReportAssociation) + .where(col(UserReportAssociation.user_id) == saver) + .values(description="Mine") ) client = client_for( - runtime_sessions, JoiningSimulationService(owner_engine, catalog) + runtime_sessions, JoiningSimulationService(owner_sessions, catalog) ) savers_item = read_item(client, report.report_id, as_browser(saver)) @@ -321,20 +321,20 @@ def test_a_reports_label_and_description_are_the_users_saved_reports( def test_a_search_by_key_reads_each_report_as_the_user_sees_it( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], browsers: list[UUID], ) -> None: saver, _ = browsers dataset_independent_key = "b" * 64 - with owner_engine.begin() as connection: + with owner_sessions.begin() as session: report = store_report( - connection, catalog, dataset_independent_key=dataset_independent_key + session, catalog, dataset_independent_key=dataset_independent_key ) - store_saved_report(owner_engine, user_id=saver, report_id=report.report_id) + store_saved_report(owner_sessions, user_id=saver, report_id=report.report_id) client = client_for( - runtime_sessions, JoiningSimulationService(owner_engine, catalog) + runtime_sessions, JoiningSimulationService(owner_sessions, catalog) ) search = ( f"/v2/reports?country_id=us&dataset_independent_key={dataset_independent_key}" @@ -354,12 +354,14 @@ def test_a_search_by_key_reads_each_report_as_the_user_sees_it( def test_a_malformed_browser_credential_on_a_read_is_refused( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - with owner_engine.begin() as connection: - report = store_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) client = client_for( - runtime_sessions, JoiningSimulationService(owner_engine, catalog) + runtime_sessions, JoiningSimulationService(owner_sessions, catalog) ) read = client.get( @@ -375,27 +377,27 @@ def test_a_malformed_browser_credential_on_a_read_is_refused( def test_the_newest_request_wins_whichever_run_was_created_last( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], browsers: list[UUID], ) -> None: asker = browsers[0] - with owner_engine.begin() as connection: - report = store_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) # Not succeeded, so neither the default run nor the newest run. created_first = store_run( - connection, catalog, report, days_later=0, status="pending" + session, catalog, report, days_later=0, status="pending" ) created_last = store_run( - connection, + session, catalog, report, days_later=1, status="succeeded", versions=NEWER_VERSIONS, ) - simulation_service = JoiningSimulationService(owner_engine, catalog) + simulation_service = JoiningSimulationService(owner_sessions, catalog) client = client_for(runtime_sessions, simulation_service) # Asked for the run created last first, then the one created first. for run_id in (created_last, created_first): @@ -415,17 +417,19 @@ def test_the_newest_request_wins_whichever_run_was_created_last( def test_a_recalculated_window_run_is_never_the_default( - owner_engine: Engine, catalog: CatalogRows, runtime_sessions: Any + owner_sessions: sessionmaker[Session], + catalog: CatalogRows, + runtime_sessions: sessionmaker[Session], ) -> None: - with owner_engine.begin() as connection: + with owner_sessions.begin() as session: unrecalculated = store_window( - connection, + session, catalog, years=(2026, 2027), settings=RunSettings(versions=CURRENT_VERSIONS, status="pending"), ) recalculated = store_window( - connection, + session, catalog, years=(2026, 2027), settings=RunSettings( @@ -435,12 +439,13 @@ def test_a_recalculated_window_run_is_never_the_default( ), report=unrecalculated.report, ) - connection.execute( - text("UPDATE budget_window_runs SET recalculate = true WHERE id = :id"), - {"id": recalculated.window_run_id}, + session.execute( + update(BudgetWindowRun) + .where(col(BudgetWindowRun.id) == recalculated.window_run_id) + .values(recalculate=True) ) client = client_for( - runtime_sessions, JoiningSimulationService(owner_engine, catalog) + runtime_sessions, JoiningSimulationService(owner_sessions, catalog) ) item = read_item(client, unrecalculated.report.report_id) @@ -449,34 +454,32 @@ def test_a_recalculated_window_run_is_never_the_default( def test_of_two_saved_reports_of_one_report_the_one_saved_last_names_it( - owner_engine: Engine, + owner_sessions: sessionmaker[Session], catalog: CatalogRows, - runtime_sessions: Any, + runtime_sessions: sessionmaker[Session], browsers: list[UUID], ) -> None: saver = browsers[0] - with owner_engine.begin() as connection: - report = store_report(connection, catalog) + with owner_sessions.begin() as session: + report = store_report(session, catalog) first_saved = store_saved_report( - owner_engine, user_id=saver, report_id=report.report_id + owner_sessions, user_id=saver, report_id=report.report_id ) last_saved = store_saved_report( - owner_engine, user_id=saver, report_id=report.report_id + owner_sessions, user_id=saver, report_id=report.report_id ) - with owner_engine.begin() as connection: + with owner_sessions.begin() as session: for saved_report_id, name, saved_at in ( (first_saved, "First name", STARTED_AT), (last_saved, "Last name", STARTED_AT + timedelta(days=1)), ): - connection.execute( - text( - "UPDATE user_report_associations SET name = :name, " - "created_at = :saved_at WHERE id = :id" - ), - {"name": name, "saved_at": saved_at, "id": saved_report_id}, + session.execute( + update(UserReportAssociation) + .where(col(UserReportAssociation.id) == saved_report_id) + .values(name=name, created_at=saved_at) ) client = client_for( - runtime_sessions, JoiningSimulationService(owner_engine, catalog) + runtime_sessions, JoiningSimulationService(owner_sessions, catalog) ) item = read_item(client, report.report_id, as_browser(saver)) diff --git a/tests/integration/test_v2_user_type_persistence.py b/tests/integration/test_v2_user_type_persistence.py index 9ae69ce0b..109e8b65d 100644 --- a/tests/integration/test_v2_user_type_persistence.py +++ b/tests/integration/test_v2_user_type_persistence.py @@ -12,20 +12,13 @@ from __future__ import annotations -import os import threading from typing import TYPE_CHECKING from uuid import UUID, uuid4 import pytest -from sqlalchemy import create_engine, delete, or_, select, update -from sqlalchemy.orm import sessionmaker -from sqlmodel import Session +from sqlalchemy import delete, or_, select, update -from policyengine_api.data.v2.migration_target import ( - V2_ALEMBIC_DISPOSABLE_TEST, - load_v2_alembic_settings, -) from policyengine_api.data.v2.models import ( LegacyUserMapping, User, @@ -34,7 +27,6 @@ UserType, UserTypeChange, ) -from policyengine_api.data.v2.settings import V2_MIGRATION_DATABASE_URL from policyengine_api.libs.auth0_management import ( Auth0UserIdSearch, Auth0UserProfile, @@ -84,49 +76,40 @@ ) if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator -# Long enough for a change or deletion not blocked by the held lock to finish. -LOCK_WAIT_SECONDS = 1.0 + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + from tests.integration.conftest import ManagedV2Roles -def _disposable_url() -> str: - database_url = os.environ.get(V2_MIGRATION_DATABASE_URL, "") - if not database_url: - pytest.skip(f"{V2_MIGRATION_DATABASE_URL} is not set") - settings = load_v2_alembic_settings( - { - V2_MIGRATION_DATABASE_URL: database_url, - V2_ALEMBIC_DISPOSABLE_TEST: os.environ.get(V2_ALEMBIC_DISPOSABLE_TEST, ""), - } - ) - if not settings.disposable_test: - pytest.fail("user type persistence tests require disposable-test mode") - return settings.url.render_as_string(hide_password=False) +# Long enough for a change or deletion not blocked by the held lock to finish. +LOCK_WAIT_SECONDS = 1.0 @pytest.fixture -def sessions(managed_v2_roles, v2_engine_as_role) -> Iterator[sessionmaker[Session]]: - """Open sessions as the Public API's runtime role; clean up as the superuser. +def sessions( + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], + v2_owner_sessions: sessionmaker[Session], +) -> Iterator[sessionmaker[Session]]: + """Open sessions as API v1's runtime role; clean up as the database's owner. The database may hold other tests' admins, so each test starts with none - and puts them back afterwards. + and puts them back afterwards. The factory is this test's own, and each + of its Sessions opens its own connection. """ - runtime_engine = v2_engine_as_role( - managed_v2_roles.runtime, pool_size=5, max_overflow=5 - ) - cleanup_engine = create_engine(_disposable_url()) - factory = sessionmaker(runtime_engine, class_=Session, expire_on_commit=False) + factory = v2_sessions_as_role(managed_v2_roles.runtime) issuer = f"https://user-types-{uuid4().hex[:12]}.example.test/" factory.kw["info"] = {"issuer": issuer} - with cleanup_engine.begin() as connection: + with v2_owner_sessions.begin() as session: other_admins = list( - connection.execute( + session.scalars( select(User.id).where(User.user_type == UserType.ADMIN.value) - ).scalars() + ) ) if other_admins: - connection.execute( + session.execute( update(User) .where(User.id.in_(other_admins)) .values(user_type=UserType.STANDARD.value) @@ -134,11 +117,11 @@ def sessions(managed_v2_roles, v2_engine_as_role) -> Iterator[sessionmaker[Sessi try: yield factory finally: - with cleanup_engine.begin() as connection: + with v2_owner_sessions.begin() as session: owned = select(UserIdentity.user_id).where(UserIdentity.issuer == issuer) - user_ids = list(connection.execute(owned).scalars()) + user_ids = list(session.scalars(owned)) if user_ids: - connection.execute( + session.execute( delete(UserInvitation).where( or_( UserInvitation.invited_by_user_id.in_(user_ids), @@ -146,20 +129,18 @@ def sessions(managed_v2_roles, v2_engine_as_role) -> Iterator[sessionmaker[Sessi ) ) ) - connection.execute( + session.execute( delete(LegacyUserMapping).where( LegacyUserMapping.user_id.in_(user_ids) ) ) - connection.execute(delete(User).where(User.id.in_(user_ids))) + session.execute(delete(User).where(User.id.in_(user_ids))) if other_admins: - connection.execute( + session.execute( update(User) .where(User.id.in_(other_admins)) .values(user_type=UserType.ADMIN.value) ) - runtime_engine.dispose() - cleanup_engine.dispose() def _principal(sessions, name: str) -> UserPrincipal: @@ -178,15 +159,13 @@ def _user_types(sessions) -> V2UserTypeService: return V2UserTypeService(UserTypeDatabaseSession(sessions)) -def _store_type_as_superuser(user_id: UUID, user_type: UserType) -> None: - engine = create_engine(_disposable_url()) - try: - with engine.begin() as connection: - connection.execute( - update(User).where(User.id == user_id).values(user_type=user_type.value) - ) - finally: - engine.dispose() +def _store_type_as_superuser( + v2_owner_sessions: sessionmaker[Session], user_id: UUID, user_type: UserType +) -> None: + with v2_owner_sessions.begin() as session: + session.execute( + update(User).where(User.id == user_id).values(user_type=user_type.value) + ) def _stored_types(sessions, user_ids: list[UUID]) -> list[str]: @@ -203,13 +182,15 @@ def _history(sessions, user_id: UUID) -> list[UserTypeChange]: ) -def test_the_runtime_role_changes_types_and_records_them(sessions) -> None: +def test_the_runtime_role_changes_types_and_records_them( + sessions, v2_owner_sessions: sessionmaker[Session] +) -> None: alice = _principal(sessions, "alice") bob = _principal(sessions, "bob") accounts = _accounts(sessions) alice_id = accounts.get_account(principal=alice, country_id="us").id bob_id = accounts.get_account(principal=bob, country_id="uk").id - _store_type_as_superuser(alice_id, UserType.ADMIN) + _store_type_as_superuser(v2_owner_sessions, alice_id, UserType.ADMIN) user_types = _user_types(sessions) promoted = user_types.change_user_type( @@ -278,7 +259,9 @@ def read_user_profile( return self.profile if user_id == self.profile.user_id else None -def test_the_runtime_role_finds_users_by_their_auth0_email(sessions) -> None: +def test_the_runtime_role_finds_users_by_their_auth0_email( + sessions, v2_owner_sessions: sessionmaker[Session] +) -> None: alice = _principal(sessions, "alice") accounts = _accounts(sessions) alice_id = accounts.get_account(principal=alice, country_id="us").id @@ -288,7 +271,7 @@ def test_the_runtime_role_finds_users_by_their_auth0_email(sessions) -> None: issuer=sessions.kw["info"]["issuer"], subject="google-oauth2|carol" ) carol_id = accounts.get_account(principal=carol, country_id="uk").id - _store_type_as_superuser(alice_id, UserType.ADMIN) + _store_type_as_superuser(v2_owner_sessions, alice_id, UserType.ADMIN) auth0 = StandInAuth0( Auth0UserProfile( user_id=carol.subject, @@ -319,7 +302,7 @@ def test_the_runtime_role_finds_users_by_their_auth0_email(sessions) -> None: def test_a_change_waits_for_another_and_never_demotes_the_last_admin( - sessions, + sessions, v2_owner_sessions: sessionmaker[Session] ) -> None: """Alice demotes Bob while Bob's demotion of Alice waits for the lock.""" alice = _principal(sessions, "alice") @@ -328,7 +311,7 @@ def test_a_change_waits_for_another_and_never_demotes_the_last_admin( alice_id = accounts.get_account(principal=alice, country_id="us").id bob_id = accounts.get_account(principal=bob, country_id="us").id for user_id in (alice_id, bob_id): - _store_type_as_superuser(user_id, UserType.ADMIN) + _store_type_as_superuser(v2_owner_sessions, user_id, UserType.ADMIN) outcomes: dict[str, object] = {} finished = threading.Event() @@ -366,7 +349,9 @@ def bob_demotes_alice() -> None: assert _stored_types(sessions, [alice_id, bob_id]) == ["admin", "standard"] -def test_deleting_accounts_removes_or_keeps_their_recorded_changes(sessions) -> None: +def test_deleting_accounts_removes_or_keeps_their_recorded_changes( + sessions, v2_owner_sessions: sessionmaker[Session] +) -> None: alice = _principal(sessions, "alice") bob = _principal(sessions, "bob") carol = _principal(sessions, "carol") @@ -374,7 +359,7 @@ def test_deleting_accounts_removes_or_keeps_their_recorded_changes(sessions) -> alice_id = accounts.get_account(principal=alice, country_id="us").id bob_id = accounts.get_account(principal=bob, country_id="us").id carol_id = accounts.get_account(principal=carol, country_id="us").id - _store_type_as_superuser(carol_id, UserType.ADMIN) + _store_type_as_superuser(v2_owner_sessions, carol_id, UserType.ADMIN) user_types = _user_types(sessions) for user_id in (alice_id, bob_id): user_types.change_user_type( @@ -431,7 +416,7 @@ def _admin_ids(sessions) -> list[UUID]: def test_a_deletion_waits_for_a_promotion_and_never_removes_the_last_admin( - sessions, + sessions, v2_owner_sessions: sessionmaker[Session] ) -> None: """Olivia, standard, deletes her account while Xavier makes her the only admin.""" olivia = _principal(sessions, "olivia") @@ -439,7 +424,7 @@ def test_a_deletion_waits_for_a_promotion_and_never_removes_the_last_admin( accounts = _accounts(sessions) olivia_id = accounts.get_account(principal=olivia, country_id="us").id xavier_id = accounts.get_account(principal=xavier, country_id="us").id - _store_type_as_superuser(xavier_id, UserType.ADMIN) + _store_type_as_superuser(v2_owner_sessions, xavier_id, UserType.ADMIN) outcomes: dict[str, object] = {} held = sessions() @@ -466,7 +451,7 @@ def test_a_deletion_waits_for_a_promotion_and_never_removes_the_last_admin( def test_a_deletion_after_a_demotion_is_allowed_while_another_admin_remains( - sessions, + sessions, v2_owner_sessions: sessionmaker[Session] ) -> None: """Xavier demotes Olivia while her deletion waits; she is then deleted.""" olivia = _principal(sessions, "olivia") @@ -475,7 +460,7 @@ def test_a_deletion_after_a_demotion_is_allowed_while_another_admin_remains( olivia_id = accounts.get_account(principal=olivia, country_id="us").id xavier_id = accounts.get_account(principal=xavier, country_id="us").id for user_id in (olivia_id, xavier_id): - _store_type_as_superuser(user_id, UserType.ADMIN) + _store_type_as_superuser(v2_owner_sessions, user_id, UserType.ADMIN) outcomes: dict[str, object] = {} held = sessions() @@ -497,7 +482,9 @@ def test_a_deletion_after_a_demotion_is_allowed_while_another_admin_remains( assert _admin_ids(sessions) == [xavier_id] -def test_a_change_from_a_type_changed_while_it_waited_is_refused(sessions) -> None: +def test_a_change_from_a_type_changed_while_it_waited_is_refused( + sessions, v2_owner_sessions: sessionmaker[Session] +) -> None: """Carol read Bob as standard; Alice makes him an author while Carol waits.""" alice = _principal(sessions, "alice") carol = _principal(sessions, "carol") @@ -507,7 +494,7 @@ def test_a_change_from_a_type_changed_while_it_waited_is_refused(sessions) -> No carol_id = accounts.get_account(principal=carol, country_id="us").id bob_id = accounts.get_account(principal=bob, country_id="us").id for user_id in (alice_id, carol_id): - _store_type_as_superuser(user_id, UserType.ADMIN) + _store_type_as_superuser(v2_owner_sessions, user_id, UserType.ADMIN) outcomes: dict[str, object] = {} finished = threading.Event() @@ -579,13 +566,15 @@ def _sent_token(postmark: RecordingPostmark) -> str: return postmark.sent[-1]["model"]["accept_url"].split("#token=", 1)[1] -def test_the_runtime_role_invites_accepts_and_dismisses(sessions) -> None: +def test_the_runtime_role_invites_accepts_and_dismisses( + sessions, v2_owner_sessions: sessionmaker[Session] +) -> None: alice = _principal(sessions, "alice") bob = _principal(sessions, "bob") accounts = _accounts(sessions) alice_id = accounts.get_account(principal=alice, country_id="us").id bob_id = accounts.get_account(principal=bob, country_id="us").id - _store_type_as_superuser(alice_id, UserType.ADMIN) + _store_type_as_superuser(v2_owner_sessions, alice_id, UserType.ADMIN) postmark = RecordingPostmark() auth0 = StandInAuth0( Auth0UserProfile( @@ -640,7 +629,7 @@ def test_the_runtime_role_invites_accepts_and_dismisses(sessions) -> None: def test_an_acceptance_waits_for_its_inviters_demotion_and_is_refused( - sessions, + sessions, v2_owner_sessions: sessionmaker[Session] ) -> None: """Carol demotes Alice while Bob's acceptance of Alice's invitation waits.""" alice = _principal(sessions, "alice") @@ -651,7 +640,7 @@ def test_an_acceptance_waits_for_its_inviters_demotion_and_is_refused( bob_id = accounts.get_account(principal=bob, country_id="us").id carol_id = accounts.get_account(principal=carol, country_id="us").id for user_id in (alice_id, carol_id): - _store_type_as_superuser(user_id, UserType.ADMIN) + _store_type_as_superuser(v2_owner_sessions, user_id, UserType.ADMIN) postmark = RecordingPostmark() auth0 = StandInAuth0( Auth0UserProfile( @@ -701,14 +690,16 @@ def bob_accepts() -> None: assert _stored_types(sessions, [bob_id]) == ["standard"] -def test_deleting_an_account_deletes_the_invitations_it_accepted(sessions) -> None: +def test_deleting_an_account_deletes_the_invitations_it_accepted( + sessions, v2_owner_sessions: sessionmaker[Session] +) -> None: """The runtime role holds no DELETE on invitations; the foreign key cascades.""" alice = _principal(sessions, "alice") bob = _principal(sessions, "bob") accounts = _accounts(sessions) alice_id = accounts.get_account(principal=alice, country_id="us").id accounts.get_account(principal=bob, country_id="us") - _store_type_as_superuser(alice_id, UserType.ADMIN) + _store_type_as_superuser(v2_owner_sessions, alice_id, UserType.ADMIN) postmark = RecordingPostmark() auth0 = StandInAuth0( Auth0UserProfile( @@ -767,14 +758,14 @@ def delete_user_account() -> None: def test_the_runtime_role_deletes_another_users_account_for_an_admin( - sessions, + sessions, v2_owner_sessions: sessionmaker[Session] ) -> None: alice = _principal(sessions, "alice") bob = _principal(sessions, "bob") accounts = _accounts(sessions) alice_id = accounts.get_account(principal=alice, country_id="us").id bob_id = accounts.get_account(principal=bob, country_id="us").id - _store_type_as_superuser(alice_id, UserType.ADMIN) + _store_type_as_superuser(v2_owner_sessions, alice_id, UserType.ADMIN) _user_types(sessions).change_user_type( principal=alice, user_id=bob_id, @@ -802,7 +793,7 @@ def test_the_runtime_role_deletes_another_users_account_for_an_admin( def test_an_admins_own_deletion_waits_for_a_demotion_and_keeps_the_last_admin( - sessions, + sessions, v2_owner_sessions: sessionmaker[Session] ) -> None: """Alice deletes her own account while a change demotes Bob, the other admin.""" alice = _principal(sessions, "alice") @@ -811,7 +802,7 @@ def test_an_admins_own_deletion_waits_for_a_demotion_and_keeps_the_last_admin( alice_id = accounts.get_account(principal=alice, country_id="us").id bob_id = accounts.get_account(principal=bob, country_id="us").id for user_id in (alice_id, bob_id): - _store_type_as_superuser(user_id, UserType.ADMIN) + _store_type_as_superuser(v2_owner_sessions, user_id, UserType.ADMIN) outcomes: dict[str, object] = {} held = sessions() @@ -837,7 +828,9 @@ def test_an_admins_own_deletion_waits_for_a_demotion_and_keeps_the_last_admin( assert _admin_ids(sessions) == [alice_id] -def test_two_admins_deleting_each_other_at_once_leave_one_admin(sessions) -> None: +def test_two_admins_deleting_each_other_at_once_leave_one_admin( + sessions, v2_owner_sessions: sessionmaker[Session] +) -> None: """Bob deletes Alice while Alice's deletion of Bob holds the lock.""" alice = _principal(sessions, "alice") bob = _principal(sessions, "bob") @@ -845,7 +838,7 @@ def test_two_admins_deleting_each_other_at_once_leave_one_admin(sessions) -> Non alice_id = accounts.get_account(principal=alice, country_id="us").id bob_id = accounts.get_account(principal=bob, country_id="us").id for user_id in (alice_id, bob_id): - _store_type_as_superuser(user_id, UserType.ADMIN) + _store_type_as_superuser(v2_owner_sessions, user_id, UserType.ADMIN) outcomes: dict[str, object] = {} held = sessions() diff --git a/tests/unit/data/fake_driver_connections.py b/tests/unit/data/fake_driver_connections.py new file mode 100644 index 000000000..ae9d1ff44 --- /dev/null +++ b/tests/unit/data/fake_driver_connections.py @@ -0,0 +1,93 @@ +"""A stand-in for pymysql's connections, for the v1 pool event tests. + +``SocketCarryingConnection`` is an in-memory SQLite connection that, like +pymysql's, keeps a socket in ``_sock`` and drops it (``_sock = None``) when the +connection breaks, before the error is raised. The error builders return the +driver errors pymysql raises for a lost connection. This module is the fake +database driver beneath SQLAlchemy, so it uses only ``sqlite3`` and +``socket``. +""" + +from __future__ import annotations + +import errno +import socket +import sqlite3 + + +class SocketCarryingConnection(sqlite3.Connection): + """A SQLite connection that keeps a socket in ``_sock``, as pymysql's does.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self._sock.bind(("127.0.0.1", 0)) + self.socket_fields = { + "database_connection.fd": self._sock.fileno(), + "database_connection.local_port": self._sock.getsockname()[1], + } + + def break_like_pymysql(self, error=None): + """Lose the connection: drop the socket, as pymysql's _force_close does. + + With ``error``, the next ping raises it instead of finding a closed + SQLite database. + """ + self._sock.close() + self._sock = None + self.ping_error = error + super().close() + + def cursor(self, *args, **kwargs): + if getattr(self, "ping_error", None) is not None: + raise self.ping_error + return super().cursor(*args, **kwargs) + + def close(self): + if self._sock is not None: + self._sock.close() + self._sock = None + super().close() + + +def open_socket_carrying_connection() -> SocketCarryingConnection: + """Open a new in-memory SQLite database on a socket-carrying connection.""" + return sqlite3.connect( + ":memory:", + factory=SocketCarryingConnection, + check_same_thread=False, + ) + + +class LostConnectionError(Exception): + """A driver error whose first argument is the driver's error code.""" + + +class OperationalError(sqlite3.OperationalError): + """Shaped like pymysql.err.OperationalError: (code, message) arguments. + + It subclasses SQLite's error so that SQLAlchemy's SQLite dialect treats it + as a DBAPI error, as the MySQL dialect treats pymysql's. + """ + + +def pymysql_lost_connection_error(): + """Return OperationalError(2013, ...) caused by a ConnectionResetError. + + This is how pymysql raises a lost connection: its socket read fails, and + _read_bytes raises OperationalError(CR_SERVER_LOST, ...) from the OSError. + """ + os_error = ConnectionResetError(errno.ECONNRESET, "Connection reset by peer") + driver_error = OperationalError( + 2013, "Lost connection to MySQL server during query" + ) + driver_error.__cause__ = os_error + return driver_error + + +def lost_connection_error(): + """Return a driver error caused by a ConnectionResetError, as pymysql raises it.""" + os_error = ConnectionResetError(errno.ECONNRESET, "Connection reset by peer") + driver_error = LostConnectionError(2013, "Lost connection to MySQL server") + driver_error.__cause__ = os_error + return driver_error diff --git a/tests/unit/data/orm_access_support.py b/tests/unit/data/orm_access_support.py index 5eef73896..6b4fcce30 100644 --- a/tests/unit/data/orm_access_support.py +++ b/tests/unit/data/orm_access_support.py @@ -124,6 +124,10 @@ "policyengine_api/data/orm_pool_events.py", "policyengine_api/data/v2/database.py", "tests/fixtures/database_sessions.py", + # The tests of orm_pool_events drive the pool it listens to: they + # invalidate, detach and recycle connections and hold two at once, + # which no Session offers. Their statements still run in Sessions. + "tests/unit/data/test_orm_pool_events.py", } ) ENGINE_NAMES = frozenset( diff --git a/tests/unit/data/test_alembic_baseline.py b/tests/unit/data/test_alembic_baseline.py index 937b3c2f7..5a28406a3 100644 --- a/tests/unit/data/test_alembic_baseline.py +++ b/tests/unit/data/test_alembic_baseline.py @@ -9,6 +9,11 @@ from policyengine_api.data.v1_models import V1Base +def _mapped_table_names() -> set[str]: + """Return the tables of the v1 mapped classes.""" + return {mapper.class_.__tablename__ for mapper in V1Base.registry.mappers} + + def _mysql_offline_config() -> tuple[Config, StringIO]: output = StringIO() config = Config(str(REPO / "alembic-v1.ini"), output_buffer=output) @@ -41,7 +46,7 @@ def test_baseline_renders_the_v1_schema_for_mysql_without_connecting(): command.upgrade(config, "head", sql=True) rendered_sql = output.getvalue() - for table_name in V1Base.metadata.tables: + for table_name in _mapped_table_names(): assert f"CREATE TABLE {table_name}" in rendered_sql assert "CREATE TABLE alembic_version" in rendered_sql @@ -62,5 +67,5 @@ def test_baseline_renders_a_complete_mysql_downgrade_without_connecting(): command.downgrade(config, "head:base", sql=True) rendered_sql = output.getvalue() - for table_name in V1Base.metadata.tables: + for table_name in _mapped_table_names(): assert f"DROP TABLE {table_name}" in rendered_sql diff --git a/tests/unit/data/test_database_access_boundaries.py b/tests/unit/data/test_database_access_boundaries.py index e63ef04f7..7d7a6ddd5 100644 --- a/tests/unit/data/test_database_access_boundaries.py +++ b/tests/unit/data/test_database_access_boundaries.py @@ -20,16 +20,24 @@ import re from functools import cache from pathlib import Path -from typing import TYPE_CHECKING, NamedTuple +from typing import TYPE_CHECKING, NamedTuple, cast +from sqlalchemy import create_mock_engine from sqlalchemy.dialects import postgresql -from sqlalchemy.schema import CreateTable -from policyengine_api.data.v2.catalog.publication_staging import STAGING_METADATA +from policyengine_api.data.v2.catalog.publication_staging import ( + create_staging_tables, + table_name, +) +from policyengine_api.data.v2.catalog.publication_staging_base import STAGING_MODELS from scripts.rules.file_length import is_excluded from scripts.rules.load import load_registry if TYPE_CHECKING: + from sqlalchemy.engine.mock import MockConnection + from sqlalchemy.sql.ddl import ExecutableDDLElement + from sqlmodel import Session + from scripts.rules.model import RuleException PROJECT_ROOT = Path(__file__).parents[3] @@ -498,18 +506,47 @@ def test_non_test_code_changes_schema_only_through_alembic() -> None: ) +class _DdlRecordingSession: + """Stands in for the publishing Session, on a connection that records DDL. + + SQLAlchemy's mock engine compiles each statement it is given and runs none, + so no database is needed. + """ + + def __init__(self) -> None: + self.statements: list[str] = [] + self.recorder = create_mock_engine("postgresql+psycopg://", self._record) + + def _record(self, statement: ExecutableDDLElement, *_arguments: object) -> None: + self.statements.append( + str(statement.compile(dialect=postgresql.dialect())).strip() + ) + + def connection(self) -> MockConnection: + return self.recorder + + def test_publication_staging_tables_are_temporary_and_dropped_at_commit() -> None: - assert STAGING_METADATA.tables, "STAGING_METADATA declares no staging tables" - for table in STAGING_METADATA.tables.values(): - create_statement = str( - CreateTable(table).compile(dialect=postgresql.dialect()) - ).strip() - assert create_statement.startswith(f"CREATE TEMPORARY TABLE {table.name} "), ( - f"staging table {table.name} must be TEMPORARY" + session = _DdlRecordingSession() + + create_staging_tables(cast("Session", session)) + + assert session.statements, "create_staging_tables creates no staging tables" + created = set() + for create_statement in session.statements: + created_table = re.match( + r"CREATE (?:TEMPORARY )?TABLE (\w+) ", create_statement + ) + assert created_table is not None, create_statement + name = created_table.group(1) + assert create_statement.startswith(f"CREATE TEMPORARY TABLE {name} "), ( + f"staging table {name} must be TEMPORARY" ) assert create_statement.endswith("ON COMMIT DROP"), ( - f"staging table {table.name} must be dropped at commit" + f"staging table {name} must be dropped at commit" ) + created.add(name) + assert created == {table_name(model) for model in STAGING_MODELS} def test_rule_proof_sqlalchemy_and_alembic_only() -> None: diff --git a/tests/unit/data/test_orm_pool_events.py b/tests/unit/data/test_orm_pool_events.py index ded0622e7..2d44d7e35 100644 --- a/tests/unit/data/test_orm_pool_events.py +++ b/tests/unit/data/test_orm_pool_events.py @@ -2,20 +2,29 @@ The engines here are real SQLAlchemy engines with pre-ping, over in-memory SQLite connections that, like pymysql's, keep a socket in ``_sock`` and drop -it (``_sock = None``) when the connection breaks, before the error is raised. +it (``_sock = None``) when the connection breaks, before the error is raised +(``fake_driver_connections``). The tests drive the pool directly, invalidating, +detaching and recycling its connections, which no Session can do, so this is +one of rule api.data.orm-only's session-factory modules; its statements still +run through Sessions. """ import errno import logging -import socket -import sqlite3 from types import SimpleNamespace import pytest -from sqlalchemy import create_engine, event, exc +from sqlalchemy import create_engine, event, exc, literal, select +from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column from sqlalchemy.pool import QueuePool from policyengine_api.data import orm_pool_events +from tests.unit.data.fake_driver_connections import ( + OperationalError, + lost_connection_error, + open_socket_carrying_connection, + pymysql_lost_connection_error, +) ENGINE_FIELD = {"database_pool.engine": "v1_cloud_sql"} @@ -37,73 +46,21 @@ def names(self): return [name for name, _severity, _attributes in self.events] -class SocketCarryingConnection(sqlite3.Connection): - """A SQLite connection that keeps a socket in ``_sock``, as pymysql's does.""" +class _MissingTableBase(DeclarativeBase): + """The declarative base of a table no test database has.""" - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self._sock.bind(("127.0.0.1", 0)) - self.socket_fields = { - "database_connection.fd": self._sock.fileno(), - "database_connection.local_port": self._sock.getsockname()[1], - } - def break_like_pymysql(self, error=None): - """Lose the connection: drop the socket, as pymysql's _force_close does. +class MissingRow(_MissingTableBase): + """A row of a table that doesn't exist, so selecting it fails.""" - With ``error``, the next ping raises it instead of finding a closed - SQLite database. - """ - self._sock.close() - self._sock = None - self.ping_error = error - super().close() + __tablename__ = "a_missing_table" + id: Mapped[int] = mapped_column(primary_key=True) - def cursor(self, *args, **kwargs): - if getattr(self, "ping_error", None) is not None: - raise self.ping_error - return super().cursor(*args, **kwargs) - def close(self): - if self._sock is not None: - self._sock.close() - self._sock = None - super().close() - - -class LostConnectionError(Exception): - """A driver error whose first argument is the driver's error code.""" - - -class OperationalError(sqlite3.OperationalError): - """Shaped like pymysql.err.OperationalError: (code, message) arguments. - - It subclasses SQLite's error so that SQLAlchemy's SQLite dialect treats it - as a DBAPI error, as the MySQL dialect treats pymysql's. - """ - - -def pymysql_lost_connection_error(): - """Return OperationalError(2013, ...) caused by a ConnectionResetError. - - This is how pymysql raises a lost connection: its socket read fails, and - _read_bytes raises OperationalError(CR_SERVER_LOST, ...) from the OSError. - """ - os_error = ConnectionResetError(errno.ECONNRESET, "Connection reset by peer") - driver_error = OperationalError( - 2013, "Lost connection to MySQL server during query" - ) - driver_error.__cause__ = os_error - return driver_error - - -def lost_connection_error(): - """Return a driver error caused by a ConnectionResetError, as pymysql raises it.""" - os_error = ConnectionResetError(errno.ECONNRESET, "Connection reset by peer") - driver_error = LostConnectionError(2013, "Lost connection to MySQL server") - driver_error.__cause__ = os_error - return driver_error +def _select_one(engine): + """Check a connection out of the pool, pinging it, and select 1 in a Session.""" + with Session(engine) as session: + return session.execute(select(literal(1))).scalar_one() @pytest.fixture @@ -139,11 +96,7 @@ def engine_factory(connector_logger): def build(**pool_options): def open_connection(): - connection = sqlite3.connect( - ":memory:", - factory=SocketCarryingConnection, - check_same_thread=False, - ) + connection = open_socket_carrying_connection() connections.append(connection) return connection @@ -165,13 +118,11 @@ def open_connection(): def test_failed_pre_ping_records_its_cause_and_the_lost_socket(runtime, engine_factory): engine, connections = engine_factory(pool_size=1, max_overflow=0) - with engine.connect() as connection: - connection.exec_driver_sql("select 1") + _select_one(engine) [first] = connections first.break_like_pymysql() - with engine.connect() as connection: - connection.exec_driver_sql("select 1") + _select_one(engine) assert runtime.names() == [ "database_pool.connect", @@ -220,13 +171,11 @@ def test_failed_pre_ping_records_the_driver_code_and_errno( or sqlite_is_disconnect(error, *arguments) ), ) - with engine.connect() as connection: - connection.exec_driver_sql("select 1") + _select_one(engine) [first] = connections first.break_like_pymysql(pymysql_lost_connection_error()) - with engine.connect() as connection: - connection.exec_driver_sql("select 1") + _select_one(engine) assert runtime.names() == [ "database_pool.connect", @@ -338,8 +287,8 @@ def test_closes_are_recorded_with_the_saved_socket(runtime, engine_factory): def test_statement_errors_are_recorded_without_their_message(runtime, engine_factory): engine, _connections = engine_factory(pool_size=1, max_overflow=0) - with engine.connect() as connection, pytest.raises(exc.OperationalError): - connection.exec_driver_sql("select * from a_missing_table") + with Session(engine) as session, pytest.raises(exc.OperationalError): + session.execute(select(MissingRow)) [error] = [event for event in runtime.events if event[0] == "database_pool.error"] assert error[1:] == ( @@ -446,12 +395,10 @@ def failing_runtime(): monkeypatch.setattr(orm_pool_events, "get_runtime", failing_runtime) engine, connections = engine_factory(pool_size=1, max_overflow=0) - with engine.connect() as connection: - connection.exec_driver_sql("select 1") + _select_one(engine) connections[0].break_like_pymysql() - with engine.connect() as connection: - assert connection.exec_driver_sql("select 1").scalar() == 1 + assert _select_one(engine) == 1 logging.getLogger(orm_pool_events.CONNECTOR_REFRESH_LOGGER).debug("refresh") diff --git a/tests/unit/data/test_orm_sessions.py b/tests/unit/data/test_orm_sessions.py index 036788077..161896dff 100644 --- a/tests/unit/data/test_orm_sessions.py +++ b/tests/unit/data/test_orm_sessions.py @@ -1,68 +1,93 @@ +from unittest.mock import Mock + import pytest -from sqlalchemy import create_engine, text +from sqlalchemy import select from sqlalchemy.orm import Session +from sqlalchemy.pool import NullPool import policyengine_api.data.orm as orm_module -from policyengine_api.data.orm import ( - build_session_factory, - get_v1_session_factory, -) +from policyengine_api.data.orm import get_v1_session_factory +from policyengine_api.data.v1_models import Household +from tests.fixtures.database_sessions import serve_v1_sessions, sqlite_v1_sessions -def test_session_factory_creates_distinct_sessions_bound_to_one_engine(): - engine = create_engine("sqlite+pysqlite:///:memory:") - factory = build_session_factory(engine) - - first = factory() - second = factory() - try: - assert isinstance(first, Session) - assert isinstance(second, Session) - assert first is not second - assert first.get_bind() is engine - assert second.get_bind() is engine - assert first.expire_on_commit is False - finally: - first.close() - second.close() +def _household(household_hash: str) -> Household: + return Household( + country_id="us", + api_version="1.0.0", + household_json={}, + household_hash=household_hash, + ) -def test_session_factory_begin_commits_and_rolls_back(): - engine = create_engine("sqlite+pysqlite:///:memory:") - factory = build_session_factory(engine) - with engine.begin() as connection: - connection.execute(text("CREATE TABLE item (id INTEGER PRIMARY KEY)")) +def _stored_household_hashes(session: Session) -> list[str]: + return list( + session.scalars(select(Household.household_hash).order_by(Household.id)) + ) + - with factory.begin() as session: - session.execute(text("INSERT INTO item (id) VALUES (1)")) +def test_session_factory_creates_distinct_sessions_bound_to_one_engine(): + with sqlite_v1_sessions() as factory: + first = factory() + second = factory() + try: + assert isinstance(first, Session) + assert isinstance(second, Session) + assert first is not second + assert first.expire_on_commit is False + # A row one session commits is the other's: both reach one database. + first.add(_household("shared")) + first.commit() + assert _stored_household_hashes(second) == ["shared"] + finally: + first.close() + second.close() - def insert_then_fail() -> None: + +def test_session_factory_begin_commits_and_rolls_back(): + with sqlite_v1_sessions() as factory: with factory.begin() as session: - session.execute(text("INSERT INTO item (id) VALUES (2)")) - msg = "stop" - raise RuntimeError(msg) + session.add(_household("committed")) + + def insert_then_fail() -> None: + with factory.begin() as session: + session.add(_household("rolled back")) + session.flush() + msg = "stop" + raise RuntimeError(msg) - with pytest.raises(RuntimeError, match="stop"): - insert_then_fail() + with pytest.raises(RuntimeError, match="stop"): + insert_then_fail() - with factory() as session: - assert session.scalars(text("SELECT id FROM item ORDER BY id")).all() == [1] + with factory() as session: + assert _stored_household_hashes(session) == ["committed"] def test_runtime_factory_is_cached_and_has_no_local_selector(monkeypatch): - remote_engine = create_engine("sqlite+pysqlite:///:memory:") + with sqlite_v1_sessions() as remote_sessions: + serve_v1_sessions(monkeypatch, remote_sessions) + try: + remote = get_v1_session_factory() - monkeypatch.setattr( - orm_module, - "get_v1_engine", - lambda: remote_engine, - ) - orm_module.clear_v1_session_factories() + assert remote is get_v1_session_factory() + # The factory opens the served engine's database, not one of its own. + with remote_sessions.begin() as session: + session.add(_household("served")) + with remote() as session: + assert _stored_household_hashes(session) == ["served"] + finally: + orm_module.clear_v1_session_factories() + + +def test_unpooled_sessions_keep_no_pool_and_dispose_of_their_engine(monkeypatch): + engine = Mock() + engine_factory = Mock(return_value=engine) + monkeypatch.setattr(orm_module, "create_engine", engine_factory) + url = "mysql+pymysql://migrator:password@127.0.0.1:3307/policyengine" - try: - remote = get_v1_session_factory() + with orm_module.unpooled_v1_sessions(url) as sessions: + assert sessions.kw["expire_on_commit"] is False + engine.dispose.assert_not_called() - assert remote is get_v1_session_factory() - assert remote.kw["bind"] is remote_engine - finally: - orm_module.clear_v1_session_factories() + engine_factory.assert_called_once_with(url, poolclass=NullPool) + engine.dispose.assert_called_once_with() diff --git a/tests/unit/data/test_v1_database_migration.py b/tests/unit/data/test_v1_database_migration.py index 36dac5702..fd694e640 100644 --- a/tests/unit/data/test_v1_database_migration.py +++ b/tests/unit/data/test_v1_database_migration.py @@ -1,9 +1,9 @@ from __future__ import annotations -from contextlib import nullcontext +from contextlib import contextmanager, nullcontext +from types import SimpleNamespace import pytest -from sqlalchemy import Column, Integer, MetaData, String, Table, text from sqlalchemy.engine import URL import scripts.v1_database_migration as migration @@ -115,13 +115,9 @@ def test_database_state_is_head_only_when_all_script_heads_are_applied(): def test_metadata_difference_descriptions_are_stable_and_do_not_include_data(): - metadata = MetaData() - question = Table( - "question", - metadata, - Column("question_id", Integer, primary_key=True), - Column("question", String(255)), - ) + # Alembic names an extra table by the table it reflected, of which only the + # name is described. + question = SimpleNamespace(name="question") assert describe_metadata_difference(("remove_table", question)) == ( "extra_table:question" @@ -151,7 +147,7 @@ def test_metadata_difference_descriptions_are_stable_and_do_not_include_data(): "reform_impact", "dataset", {}, - text("'default'"), + "'default'", None, ) ] @@ -170,30 +166,29 @@ def test_metadata_difference_rejects_unknown_shapes_without_repr_leakage(): assert secret not in str(error.value) -def test_upgrade_cli_commits_the_externally_supplied_connection(monkeypatch): - connection = object() +def test_upgrade_cli_commits_the_session_it_supplies(monkeypatch): + session = object() + opened_urls = [] - class FakeEngine: + class FakeSessions: def begin(self): - return nullcontext(connection) + return nullcontext(session) - def connect(self): + def __call__(self): msg = "upgrade must use a committing transaction" raise AssertionError(msg) - def dispose(self): - pass + @contextmanager + def unpooled_v1_sessions(url): + opened_urls.append(url) + yield FakeSessions() calls = [] - monkeypatch.setattr( - migration, "create_engine", lambda *_args, **_kwargs: FakeEngine() - ) + monkeypatch.setattr(migration, "unpooled_v1_sessions", unpooled_v1_sessions) monkeypatch.setattr( migration, "upgrade_database", - lambda supplied_connection, **kwargs: calls.append( - (supplied_connection, kwargs) - ), + lambda supplied_session, **kwargs: calls.append((supplied_session, kwargs)), ) monkeypatch.setenv("ALEMBIC_DATABASE_URL", "mysql+pymysql://unused") @@ -208,9 +203,10 @@ def dispose(self): ) == 0 ) + assert opened_urls == ["mysql+pymysql://unused"] assert calls == [ ( - connection, + session, { "backup_id": "verified-backup", }, @@ -220,17 +216,17 @@ def dispose(self): @pytest.mark.parametrize("state", [DatabaseState.UNVERSIONED, DatabaseState.INVALID]) def test_upgrade_refuses_databases_without_valid_revision_history(monkeypatch, state): - class FakeConnection: + class FakeSession: def scalar(self, *_args, **_kwargs): return 1 def execute(self, *args, **kwargs): pass - monkeypatch.setattr(migration, "database_state", lambda _connection: state) + monkeypatch.setattr(migration, "database_state", lambda _session: state) with pytest.raises(RuntimeError, match="no valid Alembic revision"): - upgrade_database(FakeConnection(), backup_id="verified-backup") + upgrade_database(FakeSession(), backup_id="verified-backup") @pytest.mark.parametrize( diff --git a/tests/unit/data/test_v1_models.py b/tests/unit/data/test_v1_models.py index da5476fe7..c2374d2b3 100644 --- a/tests/unit/data/test_v1_models.py +++ b/tests/unit/data/test_v1_models.py @@ -1,7 +1,23 @@ -from sqlalchemy.dialects import mysql -from sqlalchemy.schema import CreateTable +"""Guards on the v1 models' schema, read through their mappers. -from policyengine_api.data.v1_models import V1Base +The tables are read through each mapped class's mapper, and their MySQL DDL is +rendered by creating the schema on SQLAlchemy's mock engine, which compiles the +statements and connects to no database. +""" + +import re + +from sqlalchemy import create_mock_engine, inspect + +from policyengine_api.data.v1_models import ( + ComputedHousehold, + LegacyReportOutputAlias, + Policy, + UserPolicy, + UserPolicyMirrorEvent, + UserProfile, + V1Base, +) EXPECTED_TABLES = { "analysis", @@ -22,45 +38,63 @@ } +def _mapped_table_names() -> set[str]: + return {mapper.class_.__tablename__ for mapper in V1Base.registry.mappers} + + +def _mysql_create_table_statements() -> dict[str, str]: + """Return each v1 table's CREATE TABLE statement compiled for MySQL.""" + statements: dict[str, str] = {} + + def record(ddl: object, *_parameters: object, **_options: object) -> None: + compiled = str(ddl.compile(dialect=ddl_recorder.dialect)) + if match := re.match(r"\s*CREATE TABLE (\w+)", compiled): + statements[match.group(1)] = compiled + + ddl_recorder = create_mock_engine("mysql://", record) + V1Base.metadata.create_all(ddl_recorder, checkfirst=False) + return statements + + def test_v1_metadata_contains_every_legacy_table(): - assert set(V1Base.metadata.tables) == EXPECTED_TABLES + assert _mapped_table_names() == EXPECTED_TABLES def test_tracer_table_is_absent_after_sqlite_cache_removal(): - assert "tracers" not in V1Base.metadata.tables + assert "tracers" not in _mapped_table_names() def test_v1_metadata_compiles_for_the_production_mysql_dialect(): - for table in V1Base.metadata.sorted_tables: - assert str(CreateTable(table).compile(dialect=mysql.dialect())) + statements = _mysql_create_table_statements() + + assert set(statements) == EXPECTED_TABLES + assert all(statements.values()) def test_v1_composite_and_unique_keys_match_legacy_contract(): - policy = V1Base.metadata.tables["policy"] - assert policy.c.id.autoincrement is True - assert [column.name for column in policy.primary_key.columns] == [ + policy = inspect(Policy) + assert policy.columns["id"].autoincrement is True + assert [column.name for column in policy.primary_key] == [ "id", "country_id", "policy_hash", ] - computed = V1Base.metadata.tables["computed_household"] - assert [column.name for column in computed.primary_key.columns] == [ + computed = inspect(ComputedHousehold) + assert [column.name for column in computed.primary_key] == [ "household_id", "policy_id", "country_id", ] - assert V1Base.metadata.tables["user_profiles"].c.auth0_id.unique - assert V1Base.metadata.tables["user_policies"].c.mirror_revision.default.arg == 0 - mirror_events = V1Base.metadata.tables["user_policy_mirror_events"] - assert mirror_events.c.id.autoincrement is True - assert { - tuple(column.name for column in constraint.columns) - for constraint in mirror_events.constraints - if constraint.__class__.__name__ == "UniqueConstraint" - } == {("country_id", "legacy_user_policy_id", "source_revision")} + assert inspect(UserProfile).columns["auth0_id"].unique + assert inspect(UserPolicy).columns["mirror_revision"].default.arg == 0 + assert inspect(UserPolicyMirrorEvent).columns["id"].autoincrement is True + mirror_events_table = _mysql_create_table_statements()["user_policy_mirror_events"] + assert re.findall(r"UNIQUE \(([^)]*)\)", mirror_events_table) == [ + "country_id, legacy_user_policy_id, source_revision" + ] assert ( - V1Base.metadata.tables[ - "legacy_report_output_aliases" - ].c.legacy_report_output_id.autoincrement + inspect(LegacyReportOutputAlias) + .columns["legacy_report_output_id"] + .autoincrement is False ) diff --git a/tests/unit/services/test_simulation_service.py b/tests/unit/services/test_simulation_service.py index 1880ed1e7..a50811b8b 100644 --- a/tests/unit/services/test_simulation_service.py +++ b/tests/unit/services/test_simulation_service.py @@ -8,6 +8,7 @@ SimulationCreateResult, SimulationService, ) +from tests.fixtures.database_sessions import recorded_statements @pytest.fixture @@ -276,24 +277,14 @@ def test_creating_a_simulation_never_locks_a_household_row( unrelated household inserts into that range. What serializes a repeated create is the locking read of `simulations` itself, which is still taken. """ - from sqlalchemy import event - - statements = [] - engine = orm_session_factory.kw["bind"] - - @event.listens_for(engine, "before_cursor_execute", named=True) - def record(**event_arguments): - statements.append(" ".join(event_arguments["statement"].split()).lower()) - - try: + with recorded_statements(orm_session_factory) as sent_statements: result = service.get_or_create_simulation( country_id="us", population_id=population_id, population_type="household", policy_id=1, ) - finally: - event.remove(engine, "before_cursor_execute", record) + statements = [" ".join(statement.split()).lower() for statement in sent_statements] assert result.created is True selects = [item for item in statements if item.startswith("select")] diff --git a/tests/unit/test_household_event_command.py b/tests/unit/test_household_event_command.py index f73b951b9..4aa8b8b11 100644 --- a/tests/unit/test_household_event_command.py +++ b/tests/unit/test_household_event_command.py @@ -2,13 +2,12 @@ from __future__ import annotations +from contextlib import ExitStack, contextmanager from unittest.mock import Mock from uuid import UUID import pytest -from sqlalchemy import Engine from sqlalchemy.engine import URL -from sqlalchemy.pool import NullPool from policyengine_api.services.v2.households.types import ( LegacyHouseholdPersistenceResult, @@ -131,15 +130,16 @@ def test_command_uses_selected_cloud_sql_proxy(monkeypatch, capsys) -> None: mapping_created=True, ) ) - engine = Mock(spec=Engine) event_service = Mock() + closed: list[str] = [] + + def proxy_event_service(_environ, cleanup: ExitStack) -> Mock: + cleanup.callback(closed.append, "proxy sessions") + return event_service + monkeypatch.setattr(command, "process_household_event_after_commit", process) monkeypatch.setattr(command.logger, "log_struct", Mock()) - monkeypatch.setattr( - command, - "_proxy_event_service", - Mock(return_value=(event_service, engine)), - ) + monkeypatch.setattr(command, "_proxy_event_service", proxy_event_service) status = command.main( [ @@ -160,7 +160,7 @@ def test_command_uses_selected_cloud_sql_proxy(monkeypatch, capsys) -> None: event_service=event_service, require_pending=True, ) - engine.dispose.assert_called_once_with() + assert closed == ["proxy sessions"] def test_command_redacts_processing_failure_and_records_error( @@ -354,11 +354,14 @@ def test_audit_failure_does_not_change_the_command_result( @pytest.mark.parametrize("raw_port", ["", " "]) def test_proxy_is_not_used_without_a_port(raw_port: str) -> None: - assert command._proxy_event_service({"POLICYENGINE_DB_PROXY_PORT": raw_port}) == ( - None, - None, - ) - assert command._proxy_event_service({}) == (None, None) + with ExitStack() as cleanup: + assert ( + command._proxy_event_service( + {"POLICYENGINE_DB_PROXY_PORT": raw_port}, cleanup + ) + is None + ) + assert command._proxy_event_service({}, cleanup) is None @pytest.mark.parametrize( @@ -371,14 +374,18 @@ def test_proxy_is_not_used_without_a_port(raw_port: str) -> None: ], ) def test_proxy_port_must_be_a_valid_tcp_port(raw_port: str, message: str) -> None: - with pytest.raises( - command.HouseholdEventCommandConfigurationError, match=f"^{message}$" + with ( + pytest.raises( + command.HouseholdEventCommandConfigurationError, match=f"^{message}$" + ), + ExitStack() as cleanup, ): command._proxy_event_service( { "POLICYENGINE_DB_PROXY_PORT": raw_port, "POLICYENGINE_DB_PASSWORD": PROXY_PASSWORD, - } + }, + cleanup, ) @@ -386,42 +393,51 @@ def test_proxy_port_must_be_a_valid_tcp_port(raw_port: str, message: str) -> Non def test_proxy_connects_as_the_migration_user( monkeypatch: pytest.MonkeyPatch, raw_port: str, port: int ) -> None: - engine = Mock(spec=Engine) - create_engine = Mock(return_value=engine) session_factory = Mock() - build_session_factory = Mock(return_value=session_factory) + opened_urls: list[URL] = [] + closed: list[URL] = [] + + @contextmanager + def unpooled_v1_sessions(url: URL): + opened_urls.append(url) + yield session_factory + closed.append(url) + household_service = Mock() - monkeypatch.setattr(command, "create_engine", create_engine) - monkeypatch.setattr(command, "build_session_factory", build_session_factory) + monkeypatch.setattr(command, "unpooled_v1_sessions", unpooled_v1_sessions) monkeypatch.setattr(command, "HouseholdService", household_service) - service, returned_engine = command._proxy_event_service( - { - "POLICYENGINE_DB_PROXY_PORT": raw_port, - "POLICYENGINE_DB_PASSWORD": PROXY_PASSWORD, - } - ) + with ExitStack() as cleanup: + service = command._proxy_event_service( + { + "POLICYENGINE_DB_PROXY_PORT": raw_port, + "POLICYENGINE_DB_PASSWORD": PROXY_PASSWORD, + }, + cleanup, + ) + assert closed == [] - assert returned_engine is engine assert service is household_service.return_value household_service.assert_called_once_with(session_factory) - build_session_factory.assert_called_once_with(engine) - create_engine.assert_called_once_with( - URL.create( - "mysql+pymysql", - username="policyengine_schema_migrator", - password=PROXY_PASSWORD, - host="127.0.0.1", - port=port, - database="policyengine", - ), - poolclass=NullPool, + expected_url = URL.create( + "mysql+pymysql", + username="policyengine_schema_migrator", + password=PROXY_PASSWORD, + host="127.0.0.1", + port=port, + database="policyengine", ) + assert opened_urls == [expected_url] + # Closing the command's cleanup closes the factories, disposing of the engine. + assert closed == [expected_url] def test_proxy_requires_the_database_password() -> None: - with pytest.raises( - command.HouseholdEventCommandConfigurationError, - match=r"^POLICYENGINE_DB_PASSWORD is required$", + with ( + pytest.raises( + command.HouseholdEventCommandConfigurationError, + match=r"^POLICYENGINE_DB_PASSWORD is required$", + ), + ExitStack() as cleanup, ): - command._proxy_event_service({"POLICYENGINE_DB_PROXY_PORT": "3307"}) + command._proxy_event_service({"POLICYENGINE_DB_PROXY_PORT": "3307"}, cleanup) diff --git a/tests/unit/v2/qualification_sessions.py b/tests/unit/v2/qualification_sessions.py new file mode 100644 index 000000000..6d7fc59f7 --- /dev/null +++ b/tests/unit/v2/qualification_sessions.py @@ -0,0 +1,100 @@ +"""Stand-ins for the read-only Sessions the v2 migration qualification commands open. + +Each command opens Session factories with ``session_factories(settings)``, reads +its counts in one Session, and closes it without committing, which rolls the +READ ONLY transaction back. ``QualificationSessions`` is such a +``session_factories``, handing out one ``CountingSession``. +``serve_read_only_sessions`` stands in for ``unpooled_v2_read_only_sessions``, +the commands' default, to check that they open it for the configured URL. +""" + +from __future__ import annotations + +from contextlib import contextmanager +from types import SimpleNamespace +from typing import TYPE_CHECKING, Self + +from policyengine_api.data.v2 import database +from policyengine_api.data.v2.models import V2_TABLE_NAMES + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Iterator + + import pytest + + +class CountingSession: + """A Session that answers each count with the next of ``counts``.""" + + def __init__(self, counts: Iterable[int]) -> None: + self._counts = iter(counts) + self.statements: list[str] = [] + self.committed = False + self.closed = False + + def __enter__(self) -> Self: + return self + + def __exit__(self, *_exception: object) -> None: + # Session.close, which rolls back a transaction that wasn't committed. + self.closed = True + + def scalar(self, statement: object) -> int: + self.statements.append(str(statement)) + return next(self._counts) + + def commit(self) -> None: + self.committed = True + + @property + def rolled_back(self) -> bool: + """Whether the session closed without committing its transaction.""" + return self.closed and not self.committed + + +class QualificationSessions: + """Session factories that hand out ``session``, recording their settings.""" + + def __init__(self, session: CountingSession) -> None: + self.session = session + self.opened_with: list[object] = [] + self.closed = False + + @contextmanager + def __call__(self, settings: object) -> Iterator[Callable[[], CountingSession]]: + self.opened_with.append(settings) + try: + yield lambda: self.session + finally: + # The engine is disposed of when the factories close. + self.closed = True + + +def serve_public_tables( + monkeypatch: pytest.MonkeyPatch, + public_tables: Iterable[str] = V2_TABLE_NAMES, +) -> None: + """Make every v2 schema Inspector list ``public_tables``.""" + tables = sorted(public_tables) + monkeypatch.setattr( + database, + "v2_schema_inspector", + lambda _session: SimpleNamespace(get_table_names=lambda schema: tables), + ) + + +def serve_read_only_sessions( + monkeypatch: pytest.MonkeyPatch, sessions: QualificationSessions +) -> list[object]: + """Stand in ``sessions`` for ``unpooled_v2_read_only_sessions``. + + Return the list of URLs it is opened for. + """ + urls: list[object] = [] + + def read_only_sessions(url: object) -> object: + urls.append(url) + return sessions(url) + + monkeypatch.setattr(database, "unpooled_v2_read_only_sessions", read_only_sessions) + return urls diff --git a/tests/unit/v2/test_admin_user_deletion.py b/tests/unit/v2/test_admin_user_deletion.py index 6a6776c18..77b8c309f 100644 --- a/tests/unit/v2/test_admin_user_deletion.py +++ b/tests/unit/v2/test_admin_user_deletion.py @@ -12,7 +12,6 @@ import pytest import sqlalchemy as sa from sqlalchemy.exc import OperationalError -from sqlalchemy.orm import sessionmaker from sqlmodel import Session, select from policyengine_api import observability @@ -618,23 +617,24 @@ def test_a_failed_commit_records_no_deletion_and_deletes_no_auth0_user( ) -> None: _sign_in(store, ALICE, UserType.ADMIN) bob_id = _sign_in(store, BOB) - refusing_sessions = sessionmaker( - store.sessions.kw["bind"], class_=Session, expire_on_commit=False - ) - @sa.event.listens_for(refusing_sessions, "before_commit") def refuse_commit(_session: Session) -> None: msg = "COMMIT" raise OperationalError(msg, {}, Exception("the connection was lost")) auth0_users = RecordingAuth0Users() accounts = V2AccountService( - AccountDatabaseSession(refusing_sessions), + AccountDatabaseSession(store.sessions), auth0_user_deleter_factory=lambda: auth0_users, ) - with pytest.raises(OperationalError): - accounts.delete_user_account_as_admin(principal=ALICE, user_id=bob_id) + # Every commit of the store's sessions fails until the deletion returns. + sa.event.listen(store.sessions, "before_commit", refuse_commit) + try: + with pytest.raises(OperationalError): + accounts.delete_user_account_as_admin(principal=ALICE, user_id=bob_id) + finally: + sa.event.remove(store.sessions, "before_commit", refuse_commit) assert _user_type_of(store, bob_id) == "standard" assert auth0_users.preparations == 1 diff --git a/tests/unit/v2/test_alembic_v2.py b/tests/unit/v2/test_alembic_v2.py index 4192da91e..7d4242af3 100644 --- a/tests/unit/v2/test_alembic_v2.py +++ b/tests/unit/v2/test_alembic_v2.py @@ -23,10 +23,10 @@ V2AlembicSettings, V2MigrationTargetError, load_v2_alembic_settings, - qualify_v2_connection, + qualify_v2_target, validate_v2_head_schema, ) -from policyengine_api.data.v2.models import V2_METADATA +from policyengine_api.data.v2.models import V2_METADATA, V2_TABLE_NAMES from policyengine_api.data.v2.settings import ( V2_MIGRATION_DATABASE_URL, V2_SUPABASE_ENVIRONMENT, @@ -35,7 +35,6 @@ PROJECT_REF = "abcdefghijklmnopqrst" TARGET_ENVIRONMENT = "test-foundation" -V2_TABLE_NAMES = frozenset(table.name for table in V2_METADATA.tables.values()) POOLER_URL = ( "postgresql+psycopg://policyengine_v2_migrator." f"{PROJECT_REF}:test-password@aws-0-us-east-2.pooler.supabase.com:5432/" @@ -249,25 +248,27 @@ def test_alembic_rejects_unknown_missing_and_divergent_history(tmp_path: Path) - divergent_script.get_revision("bbbbbbbbbbbb") -def _persistent_connection( +def _persistent_session( monkeypatch: pytest.MonkeyPatch, *, public_tables: set[str], ): - import policyengine_api.data.v2.migration_target as module + from policyengine_api.data.v2 import database - connection = MagicMock() - connection.dialect.name = "postgresql" - connection.execute.side_effect = [ + session = MagicMock() + session.execute.side_effect = [ SimpleNamespace(one=lambda: ("postgres", MIGRATION_ROLE)), SimpleNamespace(scalar_one=lambda: True), ] monkeypatch.setattr( - module, - "inspect", - lambda _: SimpleNamespace(get_table_names=lambda schema: list(public_tables)), + database, + "v2_schema_inspector", + lambda _session: SimpleNamespace( + dialect=SimpleNamespace(name="postgresql"), + get_table_names=lambda schema: list(public_tables), + ), ) - return connection + return session def test_persistent_first_use_requires_configured_successful_freshness_audit( @@ -296,8 +297,8 @@ def test_persistent_first_use_requires_configured_successful_freshness_audit( ) with pytest.raises(V2MigrationTargetError, match="freshness audit"): - qualify_v2_connection( - _persistent_connection(monkeypatch, public_tables=set()), + qualify_v2_target( + _persistent_session(monkeypatch, public_tables=set()), settings, ) @@ -314,8 +315,8 @@ def test_persistent_target_rejects_unstamped_nonfresh_inventory( ) with pytest.raises(V2MigrationTargetError): - qualify_v2_connection( - _persistent_connection( + qualify_v2_target( + _persistent_session( monkeypatch, public_tables={"unreviewed_predecessor"}, ), @@ -334,8 +335,8 @@ def test_persistent_target_allows_stamped_previous_revision_inventory( } ) - qualify_v2_connection( - _persistent_connection( + qualify_v2_target( + _persistent_session( monkeypatch, public_tables={"alembic_version", "reports"}, ), @@ -354,24 +355,24 @@ def test_v2_head_rejects_schema_divergent_from_metadata( monkeypatch: pytest.MonkeyPatch, public_tables: set[str], ) -> None: - connection = _persistent_connection( + session = _persistent_session( monkeypatch, public_tables=public_tables, ) with pytest.raises(V2MigrationTargetError, match="v2 head schema"): - validate_v2_head_schema(connection, V2_METADATA) + validate_v2_head_schema(session, V2_TABLE_NAMES) def test_v2_head_accepts_schema_matching_metadata( monkeypatch: pytest.MonkeyPatch, ) -> None: - connection = _persistent_connection( + session = _persistent_session( monkeypatch, public_tables={"alembic_version", *V2_TABLE_NAMES}, ) - validate_v2_head_schema(connection, V2_METADATA) + validate_v2_head_schema(session, V2_TABLE_NAMES) def test_v2_environment_contains_no_reset_adopt_or_restamp_path() -> None: @@ -389,4 +390,4 @@ def test_v2_environment_commits_after_persistent_target_qualification() -> None: assert "with engine.connect() as connection:" not in env_source assert "current_heads != previous_heads" in env_source assert "current_heads == script_heads" in env_source - assert "validate_v2_head_schema(connection, target_metadata)" in env_source + assert "validate_v2_head_schema(session, V2_TABLE_NAMES)" in env_source diff --git a/tests/unit/v2/test_alembic_v2_revisions.py b/tests/unit/v2/test_alembic_v2_revisions.py index 6e8bd8fa6..0f0c7fe36 100644 --- a/tests/unit/v2/test_alembic_v2_revisions.py +++ b/tests/unit/v2/test_alembic_v2_revisions.py @@ -10,12 +10,16 @@ from alembic.config import Config from alembic.script import ScriptDirectory +from sqlalchemy import inspect from policyengine_api.constants import REPO from policyengine_api.data.v2.migration_target import V2_ALEMBIC_HEAD_REVISION -from policyengine_api.data.v2.models import V2_METADATA +from policyengine_api.data.v2.models import User -V2_TABLE_NAMES = frozenset(table.name for table in V2_METADATA.tables.values()) +# Every v2 table, by the mapped classes on the v2 models' registry. +V2_TABLE_NAMES = frozenset( + mapper.class_.__tablename__ for mapper in inspect(User).registry.mappers +) POST_BASELINE_TABLE_NAMES = frozenset( diff --git a/tests/unit/v2/test_catalog_initialization.py b/tests/unit/v2/test_catalog_initialization.py index ad5bc4f95..0978d6fdb 100644 --- a/tests/unit/v2/test_catalog_initialization.py +++ b/tests/unit/v2/test_catalog_initialization.py @@ -4,8 +4,10 @@ import ast import json +from contextlib import contextmanager from dataclasses import replace from pathlib import Path +from typing import TYPE_CHECKING import pytest @@ -27,6 +29,9 @@ normalized_catalog, ) +if TYPE_CHECKING: + from collections.abc import Iterator + ENVIRONMENT = { V2_DATA_WRITE_DATABASE_URL: ( "postgresql+psycopg://data-writer:test-password@db." @@ -40,12 +45,22 @@ } -class FakeEngine: +class FakeSessions: + """Stands in for the Session factories of one initialization attempt. + + ``closed`` records that the context ``sessions_builder`` opened has ended, + as ``unpooled_v2_sessions`` then disposes of its engine. + """ + def __init__(self) -> None: - self.disposed = False + self.closed = False - def dispose(self) -> None: - self.disposed = True + @contextmanager + def opened(self) -> Iterator[FakeSessions]: + try: + yield self + finally: + self.closed = True def _evidence() -> PublicationEvidence: @@ -60,23 +75,23 @@ def _evidence() -> PublicationEvidence: ) -def test_initialization_uses_only_data_write_settings_and_disposes_engine() -> None: - engine = FakeEngine() +def test_initialization_uses_only_data_write_settings_and_closes_sessions() -> None: + sessions = FakeSessions() observed = {} def build(settings): observed["username"] = settings.connection.url.username - return engine + return sessions.opened() - def publish(selected_engine, catalog): - observed["engine"] = selected_engine + def publish(selected_sessions, catalog): + observed["sessions"] = selected_sessions observed["version"] = catalog.policyengine_version return _evidence() - def verify(selected_engine, catalog, environ): - assert "engine" not in observed + def verify(selected_sessions, catalog, environ): + assert "sessions" not in observed observed["verified"] = ( - selected_engine, + selected_sessions, catalog.policyengine_version, environ, ) @@ -85,15 +100,16 @@ def verify(selected_engine, catalog, environ): recorded=(("us", "1.450.0", True),) ) - def record_spm(selected_engine, catalog, environ): - assert "engine" in observed - observed["spm"] = (selected_engine, catalog.policyengine_version, environ) + def record_spm(selected_sessions, catalog, environ): + assert "sessions" in observed + assert not sessions.closed + observed["spm"] = (selected_sessions, catalog.policyengine_version, environ) return recording result = initialization.initialize_catalog( ENVIRONMENT, extractor=normalized_catalog, - engine_builder=build, + sessions_builder=build, steps=initialization.PublicationSteps( verify_region_data=verify, publish=publish, @@ -104,22 +120,22 @@ def record_spm(selected_engine, catalog, environ): assert result == replace(_evidence(), spm_availability=recording) assert observed == { "username": "data-writer", - "verified": (engine, POLICYENGINE_VERSION, ENVIRONMENT), - "engine": engine, + "verified": (sessions, POLICYENGINE_VERSION, ENVIRONMENT), + "sessions": sessions, "version": POLICYENGINE_VERSION, - "spm": (engine, POLICYENGINE_VERSION, ENVIRONMENT), + "spm": (sessions, POLICYENGINE_VERSION, ENVIRONMENT), } - assert engine.disposed + assert sessions.closed -def test_region_data_failure_publishes_nothing_and_disposes_engine() -> None: - engine = FakeEngine() +def test_region_data_failure_publishes_nothing_and_closes_sessions() -> None: + sessions = FakeSessions() - def reject(_engine, _catalog, _environ): + def reject(_sessions, _catalog, _environ): msg = "the certified dataset d has no household column c" raise RegionDataVerificationError(msg) - def refuse_publication(_engine, _catalog): + def refuse_publication(_sessions, _catalog): msg = "publication must not start" raise AssertionError(msg) @@ -127,12 +143,12 @@ def refuse_publication(_engine, _catalog): initialization.initialize_catalog( ENVIRONMENT, extractor=normalized_catalog, - engine_builder=lambda _settings: engine, + sessions_builder=lambda _settings: sessions.opened(), steps=initialization.PublicationSteps( verify_region_data=reject, publish=refuse_publication ), ) - assert engine.disposed + assert sessions.closed def test_installed_verification_reads_artifacts_with_the_hugging_face_token( @@ -190,12 +206,12 @@ def refuse(*_args, **_kwargs): def test_default_verification_checks_only_countries_not_yet_published( monkeypatch: pytest.MonkeyPatch, ) -> None: - engine = FakeEngine() + sessions = FakeSessions() catalog = normalized_catalog() observed = {} - def find_unpublished(selected_engine, selected_catalog): - observed["found"] = (selected_engine, selected_catalog) + def find_unpublished(selected_sessions, selected_catalog): + observed["found"] = (selected_sessions, selected_catalog) return ("uk",) def verify(selected_catalog, countries, environ): @@ -204,10 +220,10 @@ def verify(selected_catalog, countries, environ): monkeypatch.setattr(initialization, "unpublished_countries", find_unpublished) monkeypatch.setattr(initialization, "verify_installed_region_data", verify) - initialization.verify_unpublished_region_data(engine, catalog, ENVIRONMENT) + initialization.verify_unpublished_region_data(sessions, catalog, ENVIRONMENT) assert observed == { - "found": (engine, catalog), + "found": (sessions, catalog), "verified": (catalog, ("uk",), ENVIRONMENT), } @@ -231,20 +247,20 @@ def fail(): assert "which 1 uk region filters on" in failure.err -def test_extraction_failure_opens_no_engine() -> None: +def test_extraction_failure_opens_no_sessions() -> None: def fail_extraction(): msg = "extraction failed" raise RuntimeError(msg) - def reject_engine(_settings): - msg = "engine must not be built" + def reject_sessions(_settings): + msg = "no Session factory may be built" raise AssertionError(msg) with pytest.raises(RuntimeError, match="extraction failed"): initialization.initialize_catalog( ENVIRONMENT, extractor=fail_extraction, - engine_builder=reject_engine, + sessions_builder=reject_sessions, ) diff --git a/tests/unit/v2/test_catalog_metadata_fields.py b/tests/unit/v2/test_catalog_metadata_fields.py index da26bd602..d47f1d5cb 100644 --- a/tests/unit/v2/test_catalog_metadata_fields.py +++ b/tests/unit/v2/test_catalog_metadata_fields.py @@ -460,9 +460,11 @@ def test_an_empty_basic_input_list_is_stored_empty() -> None: def _variable_column_length(field_name: str) -> int: + from sqlalchemy import inspect + from policyengine_api.data.v2.models import Variable - return Variable.__table__.c[field_name].type.length + return inspect(Variable).columns[field_name].type.length def test_variable_text_limits_are_the_variable_column_lengths() -> None: diff --git a/tests/unit/v2/test_catalog_publication.py b/tests/unit/v2/test_catalog_publication.py index b537ca5cc..b154afab6 100644 --- a/tests/unit/v2/test_catalog_publication.py +++ b/tests/unit/v2/test_catalog_publication.py @@ -14,34 +14,30 @@ from alembic.config import Config from alembic.script import ScriptDirectory from sqlalchemy.dialects import postgresql -from sqlalchemy.schema import CreateTable +from sqlalchemy.orm import registry from sqlalchemy.sql.elements import TextClause +from sqlmodel import Field, SQLModel +from policyengine_api.data.v2 import database from policyengine_api.data.v2.catalog import ( publication, publication_inserts, publication_reconciliation, publication_staging, - publication_tables, publication_types, ) from policyengine_api.data.v2.catalog.publication_parameter_tree import ( catalog_parameter_tree, ) +from policyengine_api.data.v2.catalog.publication_staging_base import ( + STAGING_MODELS, + TEMPORARY_UNTIL_COMMIT, + StagingBase, +) from policyengine_api.data.v2.catalog.publication_types import ( CatalogPublicationError, ) from policyengine_api.data.v2.migration_target import V2_ALEMBIC_HEAD_REVISION -from policyengine_api.data.v2.models import ( - Dataset, - Parameter, - ParameterNode, - ParameterValue, - Region, - TaxBenefitModel, - TaxBenefitModelVersion, - Variable, -) from tests.fixtures.v2_catalog import normalized_catalog REPO = Path(__file__).parents[3] @@ -86,6 +82,8 @@ def cursor(self) -> FakeCursor: class FakeConnection: + """Stands in for the SQLAlchemy Connection a Session holds.""" + def __init__(self) -> None: self.connection = type( "ConnectionProxy", @@ -94,6 +92,16 @@ def __init__(self) -> None: )() +class FakeSession: + """Stands in for the publishing Session, which hands out its Connection.""" + + def __init__(self) -> None: + self.held_connection = FakeConnection() + + def connection(self) -> FakeConnection: + return self.held_connection + + def test_expected_publication_revision_is_the_alembic_head() -> None: config = Config(str(REPO / "alembic-v2.ini"), output_buffer=StringIO()) script = ScriptDirectory.from_config(config) @@ -101,29 +109,19 @@ def test_expected_publication_revision_is_the_alembic_head() -> None: assert script.get_current_head() == V2_ALEMBIC_HEAD_REVISION -class _ScalarResult: - def __init__(self, value=None, values=()): - self.value = value - self.values = values +class _RevisionSession: + """Stands in for a Session that reads the stored revisions.""" - def scalar_one(self): - return self.value + def __init__(self, revisions=()): + self.revisions = revisions - def scalars(self): - return iter(self.values) - - -class _RevisionConnection: - def __init__(self, *, dialect: str, revisions=()): - self.dialect = type("Dialect", (), {"name": dialect})() - self.result = _ScalarResult(values=revisions) - - def execute(self, _statement): - return self.result + def scalars(self, _statement): + return iter(self.revisions) class _Inspector: - def __init__(self, *, table_exists: bool): + def __init__(self, *, dialect: str = "postgresql", table_exists: bool = True): + self.dialect = type("Dialect", (), {"name": dialect})() self.table_exists = table_exists def has_table(self, table_name: str) -> bool: @@ -132,48 +130,53 @@ def has_table(self, table_name: str) -> bool: def test_revision_check_rejects_non_postgres_missing_and_wrong_revisions() -> None: - with pytest.raises(publication.CatalogPublicationError, match="PostgreSQL"): - publication._verify_expected_revision(_RevisionConnection(dialect="sqlite")) - with ( patch.object( - publication.sa, "inspect", return_value=_Inspector(table_exists=False) + database, "v2_schema_inspector", return_value=_Inspector(dialect="sqlite") ), - pytest.raises(publication.CatalogPublicationError, match="table is absent"), + pytest.raises(publication.CatalogPublicationError, match="PostgreSQL"), ): - publication._verify_expected_revision(_RevisionConnection(dialect="postgresql")) + publication._verify_expected_revision(_RevisionSession()) with ( patch.object( - publication.sa, "inspect", return_value=_Inspector(table_exists=True) + database, + "v2_schema_inspector", + return_value=_Inspector(table_exists=False), ), + pytest.raises(publication.CatalogPublicationError, match="table is absent"), + ): + publication._verify_expected_revision(_RevisionSession()) + + with ( + patch.object(database, "v2_schema_inspector", return_value=_Inspector()), pytest.raises(publication.CatalogPublicationError, match="expected"), ): publication._verify_expected_revision( - _RevisionConnection( - dialect="postgresql", - revisions=("wrong-revision",), - ) + _RevisionSession(revisions=("wrong-revision",)) ) +class _CopyBase(SQLModel, registry=registry()): + """A declarative base of its own, so the test's table is on no real one.""" + + +class _CopiedRow(_CopyBase, table=True): + """A table COPY writes into.""" + + __tablename__ = "stage_catalog_models" + + id: int = Field(primary_key=True) + name: str + + def test_copy_streams_rows_through_psycopg_without_an_orm_write() -> None: - connection = FakeConnection() + session = FakeSession() rows = ((index, f"row-{index}") for index in range(3)) - copy_table = sa.Table( - "stage_catalog_models", - sa.MetaData(), - sa.Column("id", sa.Integer), - sa.Column("name", sa.Text), - ) - count = publication_staging.copy_rows( - connection, - table=copy_table, - rows=rows, - ) + count = publication_staging.copy_rows(session, model=_CopiedRow, rows=rows) - cursor = connection.connection.driver_connection.selected_cursor + cursor = session.held_connection.connection.driver_connection.selected_cursor assert count == 3 assert cursor.statement.as_string() == ( 'COPY "stage_catalog_models" ("id", "name") FROM STDIN' @@ -187,32 +190,17 @@ def test_copy_streams_rows_through_psycopg_without_an_orm_write() -> None: def test_publication_uses_mapped_tables_and_sqlalchemy_statements() -> None: dialect = postgresql.dialect() - assert ( - Dataset.__table__, - TaxBenefitModel.__table__, - TaxBenefitModelVersion.__table__, - Parameter.__table__, - ParameterNode.__table__, - ParameterValue.__table__, - Region.__table__, - Variable.__table__, - ) == ( - publication_tables.DATASETS, - publication_tables.MODELS, - publication_tables.MODEL_VERSIONS, - publication_tables.PARAMETERS, - publication_tables.PARAMETER_NODES, - publication_tables.PARAMETER_VALUES, - publication_tables.REGIONS, - publication_tables.VARIABLES, - ) - staging_ddl = tuple( - str(CreateTable(table).compile(dialect=dialect)) - for table in publication_staging.STAGING_TABLES + # The staging tables are mapped classes on their own registry, apart from + # the v2 models that Alembic compares, and each is TEMPORARY, dropped at + # commit (test_database_access_boundaries checks the DDL publication sends). + staging_registry = StagingBase._sa_registry + assert {mapper.class_ for mapper in staging_registry.mappers} == set(STAGING_MODELS) + assert StagingBase.metadata is not SQLModel.metadata + assert {mapper.class_ for mapper in SQLModel._sa_registry.mappers}.isdisjoint( + STAGING_MODELS ) assert all( - "CREATE TEMPORARY TABLE" in statement and "ON COMMIT DROP" in statement - for statement in staging_ddl + model.__table_args__ == TEMPORARY_UNTIL_COMMIT for model in STAGING_MODELS ) inserts = publication_inserts.SET_BASED_INSERT_STATEMENTS @@ -267,18 +255,18 @@ class Result: def scalar_one(self): return None - class Connection: + class RecordingSession: statement = None def execute(self, statement): self.statement = statement return Result() - connection = Connection() - publication._acquire_publication_lock(connection) - assert not isinstance(connection.statement, TextClause) + session = RecordingSession() + publication._acquire_publication_lock(session) + assert not isinstance(session.statement, TextClause) compiled_lock = str( - connection.statement.compile( + session.statement.compile( dialect=dialect, compile_kwargs={"literal_binds": True}, ) @@ -478,7 +466,7 @@ def _kept_region_records( monkeypatch.setattr( publication, "count_region_differences", - lambda _connection, _country: differences, + lambda _session, _country: differences, ) monkeypatch.setattr(publication, "count_stored_regions", lambda *_args: 4) # An earlier test's Alembic logging setup may have disabled existing loggers. @@ -548,7 +536,7 @@ def _time_period_update_records( monkeypatch.setattr( publication, "update_stored_time_periods", - lambda _connection, _country: update, + lambda _session, _country: update, ) # An earlier test's Alembic logging setup may have disabled existing loggers. monkeypatch.setattr(publication.LOGGER, "disabled", False) diff --git a/tests/unit/v2/test_catalog_spm_availability.py b/tests/unit/v2/test_catalog_spm_availability.py index 89254a874..dcdc8e86c 100644 --- a/tests/unit/v2/test_catalog_spm_availability.py +++ b/tests/unit/v2/test_catalog_spm_availability.py @@ -139,7 +139,7 @@ def _store_unrecorded(monkeypatch: pytest.MonkeyPatch, *model_names: str) -> Non monkeypatch.setattr( spm_availability, "read_unrecorded_versions", - lambda _connection, versions: { + lambda _session, versions: { (model_name, version) for model_name, version in versions if model_name in model_names @@ -147,8 +147,8 @@ def _store_unrecorded(monkeypatch: pytest.MonkeyPatch, *model_names: str) -> Non ) -class RecordingEngine: - """An engine whose transactions are only counted.""" +class RecordingSessions: + """Session factories whose transactions are only counted.""" def __init__(self) -> None: """Start with no transaction.""" @@ -156,9 +156,9 @@ def __init__(self) -> None: @contextmanager def begin(self) -> Iterator[str]: - """Count one transaction and hand out a placeholder connection.""" + """Count one transaction and hand out a placeholder Session.""" self.transactions += 1 - yield "connection" + yield "session" def test_publication_records_only_what_is_known( @@ -166,7 +166,7 @@ def test_publication_records_only_what_is_known( ) -> None: recorded: list[tuple[str, dict]] = [] - def record(_connection, *, model_name, version, availability) -> bool: + def record(_session, *, model_name, version, availability) -> bool: recorded.append((model_name, dict(availability))) return True @@ -175,7 +175,7 @@ def record(_connection, *, model_name, version, availability) -> bool: not_served = {"policyengine": {"latest": "6.11.0", "6.11.0": "app"}} recording = spm_availability.record_published_spm_availability( - RecordingEngine(), + RecordingSessions(), _catalog("uk", "us"), {"SIMULATION_ENTRYPOINT_URL": "https://simulation.example"}, fetch_versions=lambda _url: not_served, @@ -198,12 +198,12 @@ def test_a_version_recorded_by_an_earlier_publication_is_not_listed( monkeypatch.setattr( spm_availability, "record_spm_availability", - lambda _connection, *, model_name, version, availability: False, + lambda _session, *, model_name, version, availability: False, ) _store_unrecorded(monkeypatch) recording = spm_availability.record_published_spm_availability( - RecordingEngine(), + RecordingSessions(), _catalog("us"), {"SIMULATION_ENTRYPOINT_URL": "https://simulation.example"}, fetch_versions=lambda _url: versions, @@ -262,7 +262,7 @@ def test_an_unreadable_versions_answer_lists_only_versions_still_unrecorded( monkeypatch.setattr( spm_availability, "record_spm_availability", - lambda _connection, *, model_name, version, availability: recorded.append( + lambda _session, *, model_name, version, availability: recorded.append( model_name ), ) @@ -274,7 +274,7 @@ def unreadable(_url: str) -> object: raise CatalogPublicationError(msg) recording = spm_availability.record_published_spm_availability( - RecordingEngine(), + RecordingSessions(), _catalog("uk", "us"), {"SIMULATION_ENTRYPOINT_URL": "https://simulation.example"}, fetch_versions=unreadable, @@ -309,7 +309,7 @@ def unreadable(_url: str) -> object: with caplog.at_level("WARNING", logger=spm_availability.LOGGER.name): spm_availability.record_published_spm_availability( - RecordingEngine(), + RecordingSessions(), _catalog("uk", "us"), {"SIMULATION_ENTRYPOINT_URL": "https://simulation.example"}, fetch_versions=unreadable, diff --git a/tests/unit/v2/test_catalog_staging_rows.py b/tests/unit/v2/test_catalog_staging_rows.py index e8b6f0bd4..ad23cb02c 100644 --- a/tests/unit/v2/test_catalog_staging_rows.py +++ b/tests/unit/v2/test_catalog_staging_rows.py @@ -8,9 +8,13 @@ from psycopg.types.json import Jsonb from policyengine_api.data.v2.catalog.publication_staging import ( - STAGE_CATALOG_VARIABLES, - STAGING_TABLES, _catalog_rows, + column_names, + table_name, +) +from policyengine_api.data.v2.catalog.publication_staging_base import ( + STAGING_MODELS, + StagedVariable, ) from policyengine_api.data.v2.catalog.records import EnumValueRecord from tests.fixtures.v2_catalog import normalized_catalog @@ -27,7 +31,7 @@ def test_catalog_rows_stream_every_staging_table_lazily_in_table_order() -> None rows_by_table = _catalog_rows(country) - assert list(rows_by_table) == list(STAGING_TABLES) + assert list(rows_by_table) == list(STAGING_MODELS) assert all(inspect.isgenerator(rows) for rows in rows_by_table.values()) @@ -37,8 +41,8 @@ def test_catalog_rows_project_every_record_field_in_column_order() -> None: parameter_names = {parameter.id: parameter.name for parameter in country.parameters} rows = { - table.name: [_plain(row) for row in table_rows] - for table, table_rows in _catalog_rows(country).items() + table_name(model): [_plain(row) for row in table_rows] + for model, table_rows in _catalog_rows(country).items() } assert rows["stage_catalog_models"] == [ @@ -157,9 +161,9 @@ def test_enum_values_are_staged_as_value_and_label_objects_in_order() -> None: ) country = replace(country, variables=(variable,)) - (row,) = (_plain(row) for row in _catalog_rows(country)[STAGE_CATALOG_VARIABLES]) + (row,) = (_plain(row) for row in _catalog_rows(country)[StagedVariable]) - staged_column_names = [column.name for column in STAGE_CATALOG_VARIABLES.columns] + staged_column_names = column_names(StagedVariable) assert row[staged_column_names.index("enum_values")] == ( "jsonb", [{"value": "SINGLE", "label": "Single"}, {"value": "JOINT", "label": 2}], diff --git a/tests/unit/v2/test_cliff_impact_models.py b/tests/unit/v2/test_cliff_impact_models.py index c2009d4bd..c2377dd5c 100644 --- a/tests/unit/v2/test_cliff_impact_models.py +++ b/tests/unit/v2/test_cliff_impact_models.py @@ -6,6 +6,10 @@ start one calculation; a failed calculation never counts, and the next request starts another. The result inherits its run's versions, and is linked to the run, not to any report. + +Columns are read from the model's mapper, constraints and indexes from SQLite's +copy of the schema, and the partial index from the model's declaration +(tests/unit/v2/v2_schema_reading.py). """ from collections.abc import Iterator @@ -18,11 +22,16 @@ from sqlalchemy.orm import Session from policyengine_api.data.v2.models import ( - V2_METADATA, CliffImpact, SimulationRun, SimulationStatus, ) +from tests.fixtures.database_sessions import sqlite_v2_sessions +from tests.unit.v2.v2_schema_reading import ( + declared_index, + model_columns, + stored_v2_table, +) CLIFF_IMPACT_COLUMNS = frozenset( { @@ -43,56 +52,40 @@ FINISHED_STATUSES = frozenset({SimulationStatus.SUCCEEDED, SimulationStatus.FAILED}) -def _cliff_impacts() -> sa.Table: - return V2_METADATA.tables["cliff_impacts"] - - -def _checks() -> dict[str, str]: - return { - str(constraint.name): str(constraint.sqltext) - for constraint in _cliff_impacts().constraints - if isinstance(constraint, sa.CheckConstraint) - } - - -def _indexes() -> dict[str, sa.Index]: - return {str(index.name): index for index in _cliff_impacts().indexes} - - def test_cliff_impacts_hold_one_calculation_of_a_simulation_run() -> None: """The run it calculates, the calculation's state and the two numbers.""" - cliff_impacts = _cliff_impacts() + cliff_impacts = model_columns(CliffImpact) - assert set(cliff_impacts.c.keys()) == CLIFF_IMPACT_COLUMNS - assert not cliff_impacts.c.simulation_run_id.nullable - (run_key,) = cliff_impacts.c.simulation_run_id.foreign_keys - assert run_key.target_fullname == "simulation_runs.id" + assert set(cliff_impacts.keys()) == CLIFF_IMPACT_COLUMNS + assert not cliff_impacts.simulation_run_id.nullable + run_key = stored_v2_table("cliff_impacts").foreign_key("simulation_run_id") + assert run_key.target == "simulation_runs.id" # The result is part of its run, as poverty and inequality rows are. assert run_key.ondelete == "CASCADE" - status = cliff_impacts.c.status + status = cliff_impacts.status assert not status.nullable assert isinstance(status.type, sa.Enum) # A cliff calculation has a simulation run's states, in the same type. assert status.type.name == "v2_simulation_status" assert status.type.enums == ["pending", "running", "succeeded", "failed"] - assert cliff_impacts.c.modal_call_id.type.length == 255 + assert cliff_impacts.modal_call_id.type.length == 255 for timestamp in ("started_at", "completed_at"): - assert cliff_impacts.c[timestamp].nullable - assert cliff_impacts.c[timestamp].type.timezone + assert cliff_impacts[timestamp].nullable + assert cliff_impacts[timestamp].type.timezone for number in ("cliff_gap", "cliff_share"): - assert cliff_impacts.c[number].nullable - assert isinstance(cliff_impacts.c[number].type, sa.Float) + assert cliff_impacts[number].nullable + assert isinstance(cliff_impacts[number].type, sa.Float) # No version of its own: it inherits its run's. assert { "tax_benefit_model_version_id", "country_package_version", "policyengine_version", "report_run_id", - }.isdisjoint(cliff_impacts.c.keys()) + }.isdisjoint(cliff_impacts.keys()) def test_only_a_succeeded_cliff_calculation_has_a_result() -> None: - assert _checks() == { + assert stored_v2_table("cliff_impacts").checks == { "ck_cliff_impacts_finished_completion": ( "status NOT IN ('succeeded', 'failed') OR completed_at IS NOT NULL" ), @@ -105,8 +98,7 @@ def test_only_a_succeeded_cliff_calculation_has_a_result() -> None: def test_a_simulation_run_has_one_cliff_calculation_that_has_not_failed() -> None: """The partial unique index the simulation service names on conflict.""" - indexes = _indexes() - unfailed = indexes["uq_cliff_impacts_unfailed"] + unfailed = declared_index(CliffImpact, "uq_cliff_impacts_unfailed") assert unfailed.unique assert tuple(column.name for column in unfailed.columns) == ("simulation_run_id",) @@ -117,8 +109,8 @@ def test_a_simulation_run_has_one_cliff_calculation_that_has_not_failed() -> Non # The run's key, for its cascade and for reads that include failed rows, # and the stuck-run sweep's search by state and age. assert { - name: tuple(column.name for column in index.columns) - for name, index in indexes.items() + name: index.columns + for name, index in stored_v2_table("cliff_impacts").indexes.items() if not index.unique } == { "ix_cliff_impacts_simulation_run_id": ("simulation_run_id",), @@ -129,7 +121,7 @@ def test_a_simulation_run_has_one_cliff_calculation_that_has_not_failed() -> Non def test_a_simulation_runs_cliff_calculations_go_with_it() -> None: relationship = sa.inspect(SimulationRun).relationships["cliff_impacts"] - assert relationship.mapper.local_table is _cliff_impacts() + assert relationship.mapper.class_ is CliffImpact assert "delete" in relationship.cascade assert sa.inspect(CliffImpact).relationships["simulation_run"].mapper.class_ is ( SimulationRun @@ -138,11 +130,8 @@ def test_a_simulation_runs_cliff_calculations_go_with_it() -> None: @pytest.fixture def sqlite_session() -> Iterator[Session]: - engine = sa.create_engine("sqlite://") - V2_METADATA.create_all(engine) - with Session(engine) as session: + with sqlite_v2_sessions() as sessions, sessions(expire_on_commit=True) as session: yield session - engine.dispose() def _cliff_calculation( diff --git a/tests/unit/v2/test_country_service.py b/tests/unit/v2/test_country_service.py index 253278599..4e12397de 100644 --- a/tests/unit/v2/test_country_service.py +++ b/tests/unit/v2/test_country_service.py @@ -2,11 +2,11 @@ from __future__ import annotations +from typing import TYPE_CHECKING + import pytest -from sqlalchemy.orm import sessionmaker -from sqlmodel import Session, create_engine -from policyengine_api.data.v2.models import V2_METADATA, Country +from policyengine_api.data.v2.models import Country from policyengine_api.services.v2.countries.database_session import ( CountryDatabaseSession, ) @@ -16,13 +16,26 @@ CountryListMismatchError, ) from policyengine_api.supported_countries import SUPPORTED_COUNTRY_IDS +from tests.fixtures.database_sessions import sqlite_v2_sessions from tests.fixtures.v2_countries import add_listed_countries +if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + +@pytest.fixture +def sessions() -> Iterator[sessionmaker[Session]]: + """Return Session factories of an empty in-memory SQLite v2 database.""" + with sqlite_v2_sessions() as v2_sessions: + yield v2_sessions -def _service_with_countries(*extra_countries: Country) -> V2CountryService: - engine = create_engine("sqlite://") - V2_METADATA.create_all(engine) - sessions = sessionmaker(engine, class_=Session) + +def _service_with_countries( + sessions: sessionmaker[Session], *extra_countries: Country +) -> V2CountryService: with sessions() as session: add_listed_countries(session) session.add_all(extra_countries) @@ -30,9 +43,11 @@ def _service_with_countries(*extra_countries: Country) -> V2CountryService: return V2CountryService(CountryDatabaseSession(sessions)) -def test_countries_are_listed_by_id_with_their_capability_flags() -> None: +def test_countries_are_listed_by_id_with_their_capability_flags( + sessions: sessionmaker[Session], +) -> None: service = _service_with_countries( - Country(id="be", household_enabled=True, society_wide_enabled=False) + sessions, Country(id="be", household_enabled=True, society_wide_enabled=False) ) countries = service.list_countries() @@ -44,25 +59,27 @@ def test_countries_are_listed_by_id_with_their_capability_flags() -> None: ] -def test_an_empty_countries_table_lists_no_countries() -> None: - engine = create_engine("sqlite://") - V2_METADATA.create_all(engine) - service = V2CountryService( - CountryDatabaseSession(sessionmaker(engine, class_=Session)) - ) +def test_an_empty_countries_table_lists_no_countries( + sessions: sessionmaker[Session], +) -> None: + service = V2CountryService(CountryDatabaseSession(sessions)) assert service.list_countries() == [] -def test_rows_for_exactly_the_listed_countries_pass_verification() -> None: - service = _service_with_countries() +def test_rows_for_exactly_the_listed_countries_pass_verification( + sessions: sessionmaker[Session], +) -> None: + service = _service_with_countries(sessions) service.verify_countries_match_code_list(SUPPORTED_COUNTRY_IDS) -def test_a_row_for_an_unlisted_country_fails_verification() -> None: +def test_a_row_for_an_unlisted_country_fails_verification( + sessions: sessionmaker[Session], +) -> None: service = _service_with_countries( - Country(id="ca", household_enabled=True, society_wide_enabled=False) + sessions, Country(id="ca", household_enabled=True, society_wide_enabled=False) ) with pytest.raises(CountryListMismatchError) as raised: @@ -72,12 +89,10 @@ def test_a_row_for_an_unlisted_country_fails_verification() -> None: assert raised.value.listed_without_row == () -def test_an_empty_countries_table_fails_verification() -> None: - engine = create_engine("sqlite://") - V2_METADATA.create_all(engine) - service = V2CountryService( - CountryDatabaseSession(sessionmaker(engine, class_=Session)) - ) +def test_an_empty_countries_table_fails_verification( + sessions: sessionmaker[Session], +) -> None: + service = V2CountryService(CountryDatabaseSession(sessions)) with pytest.raises(CountryListMismatchError) as raised: service.verify_countries_match_code_list(SUPPORTED_COUNTRY_IDS) diff --git a/tests/unit/v2/test_database.py b/tests/unit/v2/test_database.py index fbfa92c72..3b9678309 100644 --- a/tests/unit/v2/test_database.py +++ b/tests/unit/v2/test_database.py @@ -4,11 +4,10 @@ from pathlib import Path import pytest -from sqlalchemy.pool import StaticPool -from sqlmodel import Session, create_engine, select +from sqlmodel import Session, select from policyengine_api.data.v2 import database -from policyengine_api.data.v2.models import V2_METADATA, TaxBenefitModel +from policyengine_api.data.v2.models import TaxBenefitModel from policyengine_api.data.v2.settings import ( V2_MIGRATION_DATABASE_URL, V2_RUNTIME_DATABASE_URL, @@ -18,6 +17,7 @@ load_v2_migration_database_settings, load_v2_runtime_database_settings, ) +from tests.fixtures.database_sessions import sqlite_v2_sessions def _environment(*, username: str = "runtime") -> dict[str, str]: @@ -45,8 +45,8 @@ def _clear_v2_database_state() -> Iterator[None]: def test_engine_construction_is_lazy_and_reused_without_connecting() -> None: settings = load_v2_runtime_database_settings(_environment()) - first = database.get_v2_engine(settings) - second = database.get_v2_engine(settings) + first = database._v2_engine(settings) + second = database._v2_engine(settings) assert first is second assert first.url.drivername == "postgresql+psycopg" @@ -67,7 +67,7 @@ def capture_create_engine(url: object, **options: object) -> object: monkeypatch.setattr(database, "create_engine", capture_create_engine) - engine = database.build_v2_engine(settings) + engine = database._build_v2_engine(settings) assert engine is expected_engine assert captured["url"] is settings.connection.url @@ -87,16 +87,16 @@ def test_session_factory_builds_sqlmodel_sessions() -> None: with factory() as session: assert isinstance(session, Session) - assert session.bind is database.get_v2_engine(settings) + assert session.bind is database._v2_engine(settings) def test_process_engine_cannot_silently_change_target() -> None: first = load_v2_runtime_database_settings(_environment(username="runtime")) second = load_v2_runtime_database_settings(_environment(username="other-runtime")) - database.get_v2_engine(first) + database._v2_engine(first) with pytest.raises(V2ConfigurationError, match="different explicit target"): - database.get_v2_engine(second) + database._v2_engine(second) def test_migration_credentials_are_not_selected_as_runtime_fallback( @@ -110,7 +110,7 @@ def test_migration_credentials_are_not_selected_as_runtime_fallback( monkeypatch.delenv(V2_RUNTIME_DATABASE_URL, raising=False) with pytest.raises(V2ConfigurationError, match=V2_RUNTIME_DATABASE_URL): - database.get_v2_engine() + database._v2_engine() assert migration.connection.url.username == "migrator" @@ -119,12 +119,12 @@ def test_forked_process_state_builds_a_new_engine( monkeypatch: pytest.MonkeyPatch, ) -> None: settings = load_v2_runtime_database_settings(_environment()) - parent_engine = database.get_v2_engine(settings) + parent_engine = database._v2_engine(settings) parent_pid = database._engine_state.engine_pid assert parent_pid is not None monkeypatch.setattr(database.os, "getpid", lambda: parent_pid + 1) - child_engine = database.get_v2_engine(settings) + child_engine = database._v2_engine(settings) assert child_engine is not parent_engine assert database._engine_state.engine_pid == parent_pid + 1 @@ -134,10 +134,10 @@ def test_read_sessions_share_the_runtime_pool_without_transactions() -> None: settings = load_v2_runtime_database_settings(_environment()) read_factory = database.get_v2_read_session_factory(settings) - runtime_engine = database.get_v2_engine(settings) + runtime_engine = database._v2_engine(settings) with read_factory() as session: - bind = session.get_bind() + bind = session.bind assert bind.get_execution_options()["isolation_level"] == "AUTOCOMMIT" assert bind.pool is runtime_engine.pool assert database.get_v2_read_session_factory(settings) is read_factory @@ -154,20 +154,16 @@ def test_read_session_factory_is_rebuilt_with_the_engine() -> None: def test_read_sessions_refuse_to_write_rows() -> None: - engine = create_engine( - "sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool - ) - V2_METADATA.create_all(engine) - read_factory = database.build_v2_read_session_factory(engine) + with sqlite_v2_sessions() as sessions: + read_factory = database.build_v2_read_session_factory(sessions) - with read_factory() as session: - session.add(TaxBenefitModel(name="policyengine-test")) - with pytest.raises(database.ReadOnlySessionError): - session.flush() + with read_factory() as session: + session.add(TaxBenefitModel(name="policyengine-test")) + with pytest.raises(database.ReadOnlySessionError): + session.flush() - with Session(engine) as session: - assert session.exec(select(TaxBenefitModel)).all() == [] - engine.dispose() + with sessions() as session: + assert session.exec(select(TaxBenefitModel)).all() == [] def test_only_the_metadata_reader_opens_read_sessions() -> None: diff --git a/tests/unit/v2/test_dynamic_catalog.py b/tests/unit/v2/test_dynamic_catalog.py index b53267f43..abfc175e7 100644 --- a/tests/unit/v2/test_dynamic_catalog.py +++ b/tests/unit/v2/test_dynamic_catalog.py @@ -11,17 +11,14 @@ from uuid import UUID import pytest -import sqlalchemy as sa from pydantic import ValidationError from sqlalchemy.exc import OperationalError, SQLAlchemyError -from sqlalchemy.orm import sessionmaker -from sqlmodel import Session, create_engine from policyengine_api.data.v2.catalog.catalog_selection_validation import ( MetadataCatalogUnavailableError, ) from policyengine_api.data.v2.models import ( - V2_METADATA, + Dynamic, Parameter, TaxBenefitModel, TaxBenefitModelVersion, @@ -50,10 +47,18 @@ PolicyCatalogValidationError, PolicySetsDynamicParametersError, ) +from tests.fixtures.database_sessions import ( + drop_registry_tables, + drop_tables, + sqlite_v2_sessions, +) if TYPE_CHECKING: from collections.abc import Iterator + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + INCOME_ELASTICITY = "gov.simulation.labor_supply_responses.elasticities.income" MARGINAL_TAX_RATE_DELTA = "simulation.marginal_tax_rate_delta" TAX_RATE = "gov.irs.income.rate" @@ -79,16 +84,21 @@ def __init__(self, session: Session) -> None: session.commit() +# The registry every v2 model is mapped on, SQLModel's own. +V2_REGISTRY = TaxBenefitModel._sa_registry + + +@pytest.fixture +def sessions() -> Iterator[sessionmaker[Session]]: + """Return Session factories of an in-memory SQLite copy of the v2 schema.""" + with sqlite_v2_sessions() as v2_sessions: + yield v2_sessions + + @pytest.fixture -def session() -> Iterator[Session]: - engine = create_engine("sqlite://") - V2_METADATA.create_all(engine) - database_session = Session(engine) - try: +def session(sessions: sessionmaker[Session]) -> Iterator[Session]: + with sessions() as database_session: yield database_session - finally: - database_session.close() - engine.dispose() @pytest.fixture @@ -230,45 +240,45 @@ def test_a_policy_without_dynamic_parameters_is_still_bound( ] -def test_a_dynamic_storage_that_cannot_be_read_is_a_storage_error() -> None: +def test_a_dynamic_storage_that_cannot_be_read_is_a_storage_error( + sessions: sessionmaker[Session], +) -> None: # A database without the v2 tables fails every read with OperationalError. # A create's first read is the catalog query, which reports its own error. - engine = create_engine("sqlite://") + with sessions.begin() as session: + drop_registry_tables(session, V2_REGISTRY) service = V2DynamicService( - DynamicDatabaseSession(sessionmaker(engine, class_=Session)), + DynamicDatabaseSession(sessions), running_policyengine_version=RUNNING_VERSION, ) - try: - with pytest.raises(DynamicStorageError) as failure: - service.get_dynamic(country_id="us", dynamic_id=UUID(int=3)) - with pytest.raises(MetadataCatalogUnavailableError): - service.create_dynamic( - NativeDynamicCreationInput( - country_id="us", - tax_benefit_model_id=UUID(int=1), - parameter_values=[ - { - "parameter_id": UUID(int=2), - "value": 0.25, - "start_date": "2026-01-01T00:00:00Z", - } - ], - ) + + with pytest.raises(DynamicStorageError) as failure: + service.get_dynamic(country_id="us", dynamic_id=UUID(int=3)) + with pytest.raises(MetadataCatalogUnavailableError): + service.create_dynamic( + NativeDynamicCreationInput( + country_id="us", + tax_benefit_model_id=UUID(int=1), + parameter_values=[ + { + "parameter_id": UUID(int=2), + "value": 0.25, + "start_date": "2026-01-01T00:00:00Z", + } + ], ) - finally: - engine.dispose() + ) assert isinstance(failure.value.__cause__, OperationalError) def test_a_dynamic_that_cannot_be_written_is_a_storage_error( - session: Session, catalog: Catalog + sessions: sessionmaker[Session], catalog: Catalog ) -> None: - engine = session.get_bind() - with engine.begin() as connection: - connection.execute(sa.text("DROP TABLE dynamics")) + with sessions.begin() as session: + drop_tables(session, Dynamic) service = V2DynamicService( - DynamicDatabaseSession(sessionmaker(engine, class_=Session)), + DynamicDatabaseSession(sessions), running_policyengine_version=RUNNING_VERSION, ) diff --git a/tests/unit/v2/test_dynamic_table_models.py b/tests/unit/v2/test_dynamic_table_models.py index ac6fd180c..544b2f70c 100644 --- a/tests/unit/v2/test_dynamic_table_models.py +++ b/tests/unit/v2/test_dynamic_table_models.py @@ -2,15 +2,16 @@ import subprocess import sys +from collections.abc import Iterator +from contextlib import contextmanager from datetime import UTC, datetime import pytest -import sqlalchemy as sa from sqlalchemy.exc import IntegrityError -from sqlmodel import Session, create_engine +from sqlalchemy.orm import sessionmaker +from sqlmodel import Session from policyengine_api.data.v2.models import ( - V2_METADATA, Dynamic, LegacyPolicyMapping, Parameter, @@ -19,24 +20,23 @@ TaxBenefitModel, TaxBenefitModelVersion, ) +from tests.fixtures.database_sessions import sqlite_v2_sessions from tests.fixtures.v2_countries import add_listed_countries +from tests.unit.v2.v2_schema_reading import ( + declared_index, + model_columns, + stored_v2_table, +) START_DATE = datetime(2026, 1, 1, tzinfo=UTC) -def _sqlite_engine_with_foreign_keys() -> sa.Engine: - engine = create_engine("sqlite://") - - @sa.event.listens_for(engine, "connect") - def enable_foreign_keys(dbapi_connection, _connection_record) -> None: - cursor = dbapi_connection.cursor() - cursor.execute("PRAGMA foreign_keys=ON") - cursor.close() - - V2_METADATA.create_all(engine) - with Session(engine) as session: - add_listed_countries(session) - return engine +@contextmanager +def _sqlite_sessions_with_foreign_keys() -> Iterator[sessionmaker[Session]]: + with sqlite_v2_sessions(foreign_keys=True) as sessions: + with sessions(expire_on_commit=True) as session: + add_listed_countries(session) + yield sessions def _catalog() -> tuple[TaxBenefitModel, TaxBenefitModelVersion, Parameter]: @@ -68,12 +68,13 @@ def _dynamic( def test_dynamics_have_policies_columns_and_no_name_or_description() -> None: - dynamics = V2_METADATA.tables["dynamics"] - policies = V2_METADATA.tables["policies"] + dynamics = model_columns("dynamics") + policies = model_columns("policies") + stored_dynamics = stored_v2_table("dynamics") - assert set(dynamics.c.keys()) == set(policies.c.keys()) - assert "name" not in dynamics.c - assert "description" not in dynamics.c + assert set(dynamics.keys()) == set(policies.keys()) + assert "name" not in dynamics + assert "description" not in dynamics for column_name in ( "country_id", "tax_benefit_model_id", @@ -81,45 +82,28 @@ def test_dynamics_have_policies_columns_and_no_name_or_description() -> None: "canonicalization_version", "content_hash", ): - assert not dynamics.c[column_name].nullable - foreign_keys = { - foreign_key.parent.name: (foreign_key.column.table.name, foreign_key.ondelete) - for foreign_key in dynamics.foreign_keys - } - assert foreign_keys == { + assert not dynamics[column_name].nullable + assert stored_dynamics.references_by_column == { "country_id": ("countries", "RESTRICT"), "tax_benefit_model_id": ("tax_benefit_models", "RESTRICT"), "tax_benefit_model_version_id": ("tax_benefit_model_versions", "RESTRICT"), } - unique_column_sets = { - constraint.name: tuple(column.name for column in constraint.columns) - for constraint in dynamics.constraints - if isinstance(constraint, sa.UniqueConstraint) - } - assert unique_column_sets == { + assert stored_dynamics.unique_constraints == { "uq_dynamics_id_country": ("id", "country_id"), "uq_dynamics_canonicalization_content_hash": ( "canonicalization_version", "content_hash", ), } - check_names = { - constraint.name - for constraint in dynamics.constraints - if isinstance(constraint, sa.CheckConstraint) - } - assert check_names == { + assert set(stored_dynamics.checks) == { "ck_dynamics_canonicalization_version", "ck_dynamics_content_hash_length", } def test_a_dynamic_s_values_are_unique_per_parameter_and_start_date() -> None: - parameter_values = V2_METADATA.tables["parameter_values"] - index = next( - index - for index in parameter_values.indexes - if index.name == "uq_parameter_values_dynamic_parameter_start_date" + index = declared_index( + ParameterValue, "uq_parameter_values_dynamic_parameter_start_date" ) assert index.unique @@ -135,37 +119,26 @@ def test_a_dynamic_s_values_are_unique_per_parameter_and_start_date() -> None: def test_legacy_policy_mappings_name_an_optional_dynamic_of_their_country() -> None: - mappings = V2_METADATA.tables["legacy_policy_mappings"] - - assert mappings.c.dynamic_id.nullable - (dynamic_key,) = ( - constraint - for constraint in mappings.constraints - if isinstance(constraint, sa.ForeignKeyConstraint) - and constraint.referred_table.name == "dynamics" - ) + mappings = stored_v2_table("legacy_policy_mappings") + + assert model_columns("legacy_policy_mappings").dynamic_id.nullable + (dynamic_key,) = mappings.foreign_keys_to("dynamics") assert dynamic_key.name == "fk_legacy_policy_mappings_dynamic_country" - assert [column.name for column in dynamic_key.columns] == [ - "dynamic_id", - "country_id", - ] - assert [element.target_fullname for element in dynamic_key.elements] == [ - "dynamics.id", - "dynamics.country_id", - ] + assert dynamic_key.columns == ("dynamic_id", "country_id") + assert dynamic_key.targets == ("dynamics.id", "dynamics.country_id") assert dynamic_key.ondelete == "RESTRICT" - assert any( - index.name == "ix_legacy_policy_mappings_dynamic" - and [column.name for column in index.columns] == ["dynamic_id"] - for index in mappings.indexes + assert mappings.index_columns.get("ix_legacy_policy_mappings_dynamic") == ( + "dynamic_id", ) def test_identical_dynamic_content_is_stored_once() -> None: - engine = _sqlite_engine_with_foreign_keys() model, version, parameter = _catalog() - with Session(engine) as session: + with ( + _sqlite_sessions_with_foreign_keys() as sessions, + sessions(expire_on_commit=True) as session, + ): session.add_all([model, version, parameter]) session.commit() session.add(_dynamic(model, version)) @@ -177,14 +150,14 @@ def test_identical_dynamic_content_is_stored_once() -> None: session.add(_dynamic(model, version, content_hash="e" * 64)) session.commit() - engine.dispose() - def test_a_dynamic_sets_one_value_per_parameter_and_start_date() -> None: - engine = _sqlite_engine_with_foreign_keys() model, version, parameter = _catalog() - with Session(engine) as session: + with ( + _sqlite_sessions_with_foreign_keys() as sessions, + sessions(expire_on_commit=True) as session, + ): session.add_all([model, version, parameter]) session.commit() dynamic = _dynamic(model, version) @@ -202,14 +175,14 @@ def test_a_dynamic_sets_one_value_per_parameter_and_start_date() -> None: with pytest.raises(IntegrityError, match="UNIQUE constraint failed"): session.commit() - engine.dispose() - def test_a_mapping_cannot_name_another_country_s_dynamic() -> None: - engine = _sqlite_engine_with_foreign_keys() model, version, _parameter = _catalog() - with Session(engine) as session: + with ( + _sqlite_sessions_with_foreign_keys() as sessions, + sessions(expire_on_commit=True) as session, + ): policy = Policy( country_id="uk", tax_benefit_model_id=model.id, @@ -234,8 +207,6 @@ def test_a_mapping_cannot_name_another_country_s_dynamic() -> None: with pytest.raises(IntegrityError, match="FOREIGN KEY constraint failed"): session.commit() - engine.dispose() - def test_the_v2_mappers_configure_without_relationship_warnings() -> None: # A fresh interpreter, since a process configures its mappers only once @@ -260,10 +231,12 @@ def test_the_v2_mappers_configure_without_relationship_warnings() -> None: def test_a_dynamic_is_stored_in_one_flush_with_its_new_catalog_version() -> None: - engine = _sqlite_engine_with_foreign_keys() model, version, parameter = _catalog() - with Session(engine) as session: + with ( + _sqlite_sessions_with_foreign_keys() as sessions, + sessions(expire_on_commit=True) as session, + ): dynamic = Dynamic( country_id="us", tax_benefit_model=model, @@ -278,5 +251,3 @@ def test_a_dynamic_is_stored_in_one_flush_with_its_new_catalog_version() -> None assert stored is not None assert stored.tax_benefit_model_version_id == version.id assert stored in version.dynamics - - engine.dispose() diff --git a/tests/unit/v2/test_household_calculation_database_routes.py b/tests/unit/v2/test_household_calculation_database_routes.py index 29d56801d..ad30ba9df 100644 --- a/tests/unit/v2/test_household_calculation_database_routes.py +++ b/tests/unit/v2/test_household_calculation_database_routes.py @@ -9,20 +9,16 @@ import json from datetime import UTC, datetime +from typing import TYPE_CHECKING from uuid import UUID, uuid4 import httpx import pytest from fastapi.testclient import TestClient from flask import Flask -from sqlalchemy import text -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import StaticPool -from sqlmodel import Session, create_engine from policyengine_api.asgi_factory import create_asgi_app from policyengine_api.data.v2.models import ( - V2_METADATA, Country, Household, Parameter, @@ -59,9 +55,16 @@ PolicyDatabaseSession, ) from policyengine_api.services.v2.policies.services import V2PolicyService +from tests.fixtures.database_sessions import drop_tables, sqlite_v2_sessions from tests.fixtures.household_calculation_documents import JOB_ID from tests.unit.v2.household_calculation_support import FakeSimulation +if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + RUNNING_VERSION = "6.10.0" EARLIER_VERSION = "6.9.0" KEPT_PARAMETER = "gov.example.rate" @@ -71,17 +74,11 @@ @pytest.fixture -def engine(): - # One connection shared by every thread, so the route's worker thread - # reads the same in-memory database. - database_engine = create_engine( - "sqlite://", - connect_args={"check_same_thread": False}, - poolclass=StaticPool, - ) - V2_METADATA.create_all(database_engine) - yield database_engine - database_engine.dispose() +def sessions() -> Iterator[sessionmaker[Session]]: + # Every Session shares one connection, so the route's worker thread reads + # the same in-memory database. + with sqlite_v2_sessions() as session_factory: + yield session_factory def _catalog_version( @@ -126,9 +123,9 @@ def _policy(session: Session, parameters: dict[str, Parameter], hash_seed: str): @pytest.fixture -def stored(engine) -> dict[str, object]: +def stored(sessions) -> dict[str, object]: """Store the US, a household, and a policy on each of two catalog versions.""" - with Session(engine, expire_on_commit=False) as session: + with sessions() as session: session.add(Country(id="us", household_enabled=True, society_wide_enabled=True)) model = TaxBenefitModel(name="policyengine-us") earlier = _catalog_version( @@ -158,9 +155,7 @@ def simulation() -> FakeSimulation: @pytest.fixture -def client(engine, simulation) -> TestClient: - sessions = sessionmaker(engine, class_=Session, expire_on_commit=False) - +def client(sessions, simulation) -> TestClient: def service() -> V2HouseholdCalculationService: return V2HouseholdCalculationService( countries=V2CountryService(CountryDatabaseSession(sessions)), @@ -234,11 +229,11 @@ def test_an_unknown_household_is_not_found_in_the_database( def test_a_catalog_that_cannot_be_queried_answers_503( - engine, client, stored, simulation + sessions, client, stored, simulation ) -> None: # The policy check's catalog query reads this table; nothing else does. - with engine.begin() as connection: - connection.execute(text("DROP TABLE tax_benefit_model_versions")) + with sessions.begin() as session: + drop_tables(session, TaxBenefitModelVersion) response = client.post(CALCULATIONS, json=_body(stored, "running_policy")) @@ -292,9 +287,8 @@ def simulation_recorder(monkeypatch) -> SimulationRecorder: @pytest.fixture -def client_with_simulation_client(engine, simulation_recorder) -> TestClient: +def client_with_simulation_client(sessions, simulation_recorder) -> TestClient: """Serve the route with the real simulation client over a recording transport.""" - sessions = sessionmaker(engine, class_=Session, expire_on_commit=False) transport = httpx.MockTransport(simulation_recorder.answer) def service() -> V2HouseholdCalculationService: diff --git a/tests/unit/v2/test_household_migration_qualification.py b/tests/unit/v2/test_household_migration_qualification.py index 38199cdc9..08f4fa281 100644 --- a/tests/unit/v2/test_household_migration_qualification.py +++ b/tests/unit/v2/test_household_migration_qualification.py @@ -2,9 +2,6 @@ from __future__ import annotations -from contextlib import contextmanager -from typing import TYPE_CHECKING - import pytest from policyengine_api.data.v2 import household_migration_qualification as qualification @@ -12,10 +9,14 @@ V2_MIGRATION_DATABASE_URL, V2_SUPABASE_ENVIRONMENT, V2_SUPABASE_PROJECT_REF, + load_v2_migration_database_settings, +) +from tests.unit.v2.qualification_sessions import ( + CountingSession, + QualificationSessions, + serve_public_tables, + serve_read_only_sessions, ) - -if TYPE_CHECKING: - from collections.abc import Iterator ENVIRONMENT = { V2_MIGRATION_DATABASE_URL: ( @@ -27,51 +28,23 @@ } -class FakeTransaction: - def __init__(self) -> None: - self.rolled_back = False - - def rollback(self) -> None: - self.rolled_back = True - - -class FakeConnection: - def __init__(self, counts: tuple[int, int, int, int, int]) -> None: - self._counts = iter(counts) - self.transaction = FakeTransaction() - self.statements: list[str] = [] - - def begin(self) -> FakeTransaction: - return self.transaction - - def exec_driver_sql(self, statement: str) -> None: - self.statements.append(statement) - - def scalar(self, _statement: object) -> int: - return next(self._counts) +@pytest.fixture(autouse=True) +def _every_household_table_exists(monkeypatch: pytest.MonkeyPatch) -> None: + serve_public_tables(monkeypatch) -class FakeEngine: - def __init__(self, connection: FakeConnection) -> None: - self.connection = connection - self.disposed = False +def _configured_url() -> object: + return load_v2_migration_database_settings(ENVIRONMENT).connection.url - @contextmanager - def connect(self) -> Iterator[FakeConnection]: - yield self.connection - def dispose(self) -> None: - self.disposed = True - - -def test_empty_target_is_qualified_in_a_rolled_back_read_only_transaction() -> None: - connection = FakeConnection((0, 0, 0, 0, 0)) - engine = FakeEngine(connection) +def test_empty_target_is_qualified_in_a_rolled_back_read_only_transaction( + monkeypatch: pytest.MonkeyPatch, +) -> None: + session = CountingSession((0, 0, 0, 0, 0)) + sessions = QualificationSessions(session) + read_only_urls = serve_read_only_sessions(monkeypatch, sessions) - evidence = qualification.qualify_household_migration_target( - ENVIRONMENT, - engine_builder=lambda _settings: engine, - ) + evidence = qualification.qualify_household_migration_target(ENVIRONMENT) assert evidence.as_dict() == { "outcome": "ok", @@ -86,41 +59,44 @@ def test_empty_target_is_qualified_in_a_rolled_back_read_only_transaction() -> N "household_jobs": 0, }, } - assert connection.statements == ["SET TRANSACTION READ ONLY"] - assert connection.transaction.rolled_back - assert engine.disposed + assert read_only_urls == [_configured_url()] + assert session.rolled_back + assert sessions.closed def test_applied_household_revision_skips_row_qualification() -> None: - connection = FakeConnection((1, 2, 3, 4, 5)) - engine = FakeEngine(connection) + session = CountingSession((1, 2, 3, 4, 5)) + sessions = QualificationSessions(session) evidence = qualification.qualify_household_migration_if_pending( ENVIRONMENT, - engine_builder=lambda _settings: engine, - pending_checker=lambda _connection: False, + session_factories=sessions, + pending_checker=lambda _session: False, ) assert evidence.required is False assert evidence.counts == qualification.HouseholdDataCounts(0, 0, 0, 0, 0) - assert connection.transaction.rolled_back - assert engine.disposed + assert session.rolled_back + assert sessions.closed -def test_pending_household_revision_runs_row_qualification() -> None: - connection = FakeConnection((0, 0, 0, 0, 0)) - engine = FakeEngine(connection) +def test_pending_household_revision_runs_row_qualification( + monkeypatch: pytest.MonkeyPatch, +) -> None: + session = CountingSession((0, 0, 0, 0, 0)) + sessions = QualificationSessions(session) + read_only_urls = serve_read_only_sessions(monkeypatch, sessions) evidence = qualification.qualify_household_migration_if_pending( ENVIRONMENT, - engine_builder=lambda _settings: engine, - pending_checker=lambda _connection: True, + pending_checker=lambda _session: True, ) assert evidence.required is True - assert connection.statements == ["SET TRANSACTION READ ONLY"] - assert connection.transaction.rolled_back - assert engine.disposed + assert read_only_urls == [_configured_url()] + assert len(session.statements) == 5 + assert session.rolled_back + assert sessions.closed @pytest.mark.parametrize( @@ -137,8 +113,8 @@ def test_pending_household_revision_runs_row_qualification() -> None: def test_retained_household_data_stops_without_committing( counts: tuple[int, int, int, int, int], ) -> None: - connection = FakeConnection(counts) - engine = FakeEngine(connection) + session = CountingSession(counts) + sessions = QualificationSessions(session) with pytest.raises( qualification.RetainedHouseholdDataError, @@ -146,12 +122,12 @@ def test_retained_household_data_stops_without_committing( ) as raised: qualification.qualify_household_migration_target( ENVIRONMENT, - engine_builder=lambda _settings: engine, + session_factories=sessions, ) assert raised.value.counts == qualification.HouseholdDataCounts(*counts) - assert connection.transaction.rolled_back - assert engine.disposed + assert session.rolled_back + assert sessions.closed def test_main_redacts_unexpected_errors( diff --git a/tests/unit/v2/test_household_models.py b/tests/unit/v2/test_household_models.py index bef59c843..e91f04822 100644 --- a/tests/unit/v2/test_household_models.py +++ b/tests/unit/v2/test_household_models.py @@ -2,38 +2,45 @@ from __future__ import annotations +from contextlib import contextmanager from datetime import datetime +from typing import TYPE_CHECKING import pytest import sqlalchemy as sa from sqlalchemy.dialects import postgresql from sqlalchemy.exc import IntegrityError -from sqlmodel import Session, create_engine, select +from sqlmodel import select from policyengine_api.data.v1_models import HouseholdMirrorEvent from policyengine_api.data.v2.models import ( - V2_METADATA, Household, LegacyHouseholdMapping, User, UserHouseholdAssociation, ) +from tests.fixtures.database_sessions import sqlite_v1_sessions, sqlite_v2_sessions from tests.fixtures.v2_countries import add_listed_countries +from tests.unit.v2.v2_schema_reading import ( + model_columns, + stored_v1_schema, + stored_v2_table, +) +if TYPE_CHECKING: + from collections.abc import Iterator -def _engine(): - engine = create_engine("sqlite://") + from sqlmodel import Session - @sa.event.listens_for(engine, "connect") - def enable_foreign_keys(dbapi_connection, _connection_record) -> None: - cursor = dbapi_connection.cursor() - cursor.execute("PRAGMA foreign_keys=ON") - cursor.close() - V2_METADATA.create_all(engine) - with Session(engine) as session: - add_listed_countries(session) - return engine +@contextmanager +def _session() -> Iterator[Session]: + """Yield a Session of a SQLite v2 schema that enforces foreign keys.""" + with sqlite_v2_sessions(foreign_keys=True) as sessions: + with sessions(expire_on_commit=True) as session: + add_listed_countries(session) + with sessions(expire_on_commit=True) as session: + yield session def _household( @@ -52,9 +59,10 @@ def _household( def test_household_schema_uses_jsonb_and_versioned_content_identity() -> None: - households = V2_METADATA.tables["households"] + households = model_columns("households") + stored_households = stored_v2_table("households") - assert {"country", "year", "label"}.isdisjoint(households.c.keys()) + assert {"country", "year", "label"}.isdisjoint(households.keys()) assert { "country_id", "default_year", @@ -63,49 +71,34 @@ def test_household_schema_uses_jsonb_and_versioned_content_identity() -> None: "content_hash", "created_at", "updated_at", - }.issubset(households.c.keys()) - assert households.c.default_year.nullable + }.issubset(households.keys()) + assert households.default_year.nullable assert isinstance( - households.c.household_data.type.dialect_impl(postgresql.dialect()), + households.household_data.type.dialect_impl(postgresql.dialect()), postgresql.JSONB, ) - unique_columns = { - tuple(column.name for column in constraint.columns) - for constraint in households.constraints - if isinstance(constraint, sa.UniqueConstraint) - } + unique_columns = stored_households.unique_column_sets assert ("id", "country_id") in unique_columns assert ("canonicalization_version", "content_hash") in unique_columns - assert "ix_households_country_default_year_created_id" in { - index.name for index in households.indexes - } + assert "ix_households_country_default_year_created_id" in ( + stored_households.indexes + ) def test_user_household_is_an_independent_country_scoped_association() -> None: - associations = V2_METADATA.tables["user_household_associations"] - - assert {"country", "label"}.isdisjoint(associations.c.keys()) - assert {"country_id", "name", "description"}.issubset(associations.c.keys()) - unique_columns = { - tuple(column.name for column in constraint.columns) - for constraint in associations.constraints - if isinstance(constraint, sa.UniqueConstraint) - } + associations = model_columns("user_household_associations") + stored_associations = stored_v2_table("user_household_associations") + + assert {"country", "label"}.isdisjoint(associations.keys()) + assert {"country_id", "name", "description"}.issubset(associations.keys()) + unique_columns = stored_associations.unique_column_sets assert ("user_id", "household_id") not in unique_columns assert ("id", "country_id") in unique_columns - household_country = next( - constraint - for constraint in associations.foreign_key_constraints - if constraint.name == "fk_user_household_associations_household_country" + household_country = stored_associations.foreign_key_named( + "fk_user_household_associations_household_country" ) - assert [column.name for column in household_country.columns] == [ - "household_id", - "country_id", - ] - assert [element.target_fullname for element in household_country.elements] == [ - "households.id", - "households.country_id", - ] + assert household_country.columns == ("household_id", "country_id") + assert household_country.targets == ("households.id", "households.country_id") assert household_country.ondelete == "RESTRICT" assert ( sa.inspect(UserHouseholdAssociation).relationships["user"].back_populates @@ -114,26 +107,24 @@ def test_user_household_is_an_independent_country_scoped_association() -> None: def test_legacy_household_mapping_is_many_to_one_by_destination() -> None: - mappings = V2_METADATA.tables["legacy_household_mappings"] + columns = model_columns("legacy_household_mappings") + mappings = stored_v2_table("legacy_household_mappings") - unique_columns = { - tuple(column.name for column in constraint.columns) - for constraint in mappings.constraints - if isinstance(constraint, sa.UniqueConstraint) - } + unique_columns = mappings.unique_column_sets assert ("country_id", "legacy_household_id") in unique_columns assert ("household_id",) not in unique_columns - assert mappings.c.source_api_version.type.length == 255 - assert mappings.c.fingerprint_sha256.type.length == 64 - household_country = next(iter(mappings.foreign_key_constraints)) + assert columns.source_api_version.type.length == 255 + assert columns.fingerprint_sha256.type.length == 64 + household_country = mappings.foreign_keys[0] assert household_country.name == "fk_legacy_household_mappings_household_country" assert household_country.ondelete == "RESTRICT" def test_v1_household_event_contains_one_create_snapshot_without_revision() -> None: - event = HouseholdMirrorEvent.__table__ + event = model_columns(HouseholdMirrorEvent) + stored_event = stored_v1_schema()[HouseholdMirrorEvent.__tablename__] - assert {"source_revision", "event_type"}.isdisjoint(event.c.keys()) + assert {"source_revision", "event_type"}.isdisjoint(event.keys()) assert { "country_id", "legacy_household_id", @@ -142,109 +133,88 @@ def test_v1_household_event_contains_one_create_snapshot_without_revision() -> N "source_fingerprint_sha256", "created_at", "processed_at", - }.issubset(event.c.keys()) - unique_columns = { - tuple(column.name for column in constraint.columns) - for constraint in event.constraints - if isinstance(constraint, sa.UniqueConstraint) - } - assert ("country_id", "legacy_household_id") in unique_columns - assert "ix_household_mirror_events_pending_age" in { - index.name for index in event.indexes - } + }.issubset(event.keys()) + assert ("country_id", "legacy_household_id") in stored_event.unique_column_sets + assert "ix_household_mirror_events_pending_age" in stored_event.indexes def test_household_hash_uniqueness_and_legacy_null_year() -> None: - engine = _engine() - try: - with Session(engine) as session: - legacy = _household(default_year=None) - duplicate = _household(default_year=2026) - session.add_all([legacy, duplicate]) - with pytest.raises(IntegrityError): - session.commit() - finally: - engine.dispose() + with _session() as session: + legacy = _household(default_year=None) + duplicate = _household(default_year=2026) + session.add_all([legacy, duplicate]) + with pytest.raises(IntegrityError): + session.commit() def test_association_duplicates_are_allowed_but_country_must_match() -> None: - engine = _engine() - try: - with Session(engine) as session: - household = _household(content_hash="b" * 64) - user = User(primary_country="us") - session.add_all([household, user]) - session.commit() - first = UserHouseholdAssociation( - country_id="us", - user_id=user.id, - household_id=household.id, - name="First", - ) - second = UserHouseholdAssociation( - country_id="us", + with _session() as session: + household = _household(content_hash="b" * 64) + user = User(primary_country="us") + session.add_all([household, user]) + session.commit() + first = UserHouseholdAssociation( + country_id="us", + user_id=user.id, + household_id=household.id, + name="First", + ) + second = UserHouseholdAssociation( + country_id="us", + user_id=user.id, + household_id=household.id, + name="Second", + ) + session.add_all([first, second]) + session.commit() + assert first.id != second.id + + session.add( + UserHouseholdAssociation( + country_id="uk", user_id=user.id, household_id=household.id, - name="Second", ) - session.add_all([first, second]) + ) + with pytest.raises(IntegrityError): session.commit() - assert first.id != second.id - - session.add( - UserHouseholdAssociation( - country_id="uk", - user_id=user.id, - household_id=household.id, - ) - ) - with pytest.raises(IntegrityError): - session.commit() - finally: - engine.dispose() def test_legacy_mappings_allow_many_sources_and_restrict_household_deletion() -> None: - engine = _engine() - try: - with Session(engine) as session: - household = _household(content_hash="c" * 64) - session.add(household) - session.commit() - session.add_all( - [ - LegacyHouseholdMapping( - country_id="us", - legacy_household_id=101, - household_id=household.id, - source_api_version="1.0.0", - fingerprint_version=1, - fingerprint_sha256="1" * 64, - ), - LegacyHouseholdMapping( - country_id="us", - legacy_household_id=102, - household_id=household.id, - source_api_version="1.0.0", - fingerprint_version=1, - fingerprint_sha256="2" * 64, - ), - ] - ) + with _session() as session: + household = _household(content_hash="c" * 64) + session.add(household) + session.commit() + session.add_all( + [ + LegacyHouseholdMapping( + country_id="us", + legacy_household_id=101, + household_id=household.id, + source_api_version="1.0.0", + fingerprint_version=1, + fingerprint_sha256="1" * 64, + ), + LegacyHouseholdMapping( + country_id="us", + legacy_household_id=102, + household_id=household.id, + source_api_version="1.0.0", + fingerprint_version=1, + fingerprint_sha256="2" * 64, + ), + ] + ) + session.commit() + assert len(household.legacy_mappings) == 2 + + session.delete(household) + with pytest.raises(IntegrityError): session.commit() - assert len(household.legacy_mappings) == 2 - - session.delete(household) - with pytest.raises(IntegrityError): - session.commit() - finally: - engine.dispose() def test_v1_event_identity_is_unique_and_failed_transaction_rolls_back() -> None: - engine = create_engine("sqlite://") - HouseholdMirrorEvent.__table__.create(engine) - try: + with sqlite_v1_sessions() as sessions: payload = { "country_id": "us", "legacy_household_id": 100, @@ -253,7 +223,7 @@ def test_v1_event_identity_is_unique_and_failed_transaction_rolls_back() -> None "household_json": {"people": {}}, "household_hash": "source-hash", } - with Session(engine) as session: + with sessions(expire_on_commit=True) as session: session.add_all( [ HouseholdMirrorEvent( @@ -275,19 +245,13 @@ def test_v1_event_identity_is_unique_and_failed_transaction_rolls_back() -> None with pytest.raises(IntegrityError): session.commit() session.rollback() - assert session.exec(select(HouseholdMirrorEvent)).all() == [] - finally: - engine.dispose() + assert session.scalars(select(HouseholdMirrorEvent)).all() == [] def test_household_timestamps_are_database_compatible() -> None: - engine = _engine() - try: - with Session(engine) as session: - household = _household(content_hash="d" * 64) - session.add(household) - session.commit() - assert isinstance(household.created_at, datetime) - assert isinstance(household.updated_at, datetime) - finally: - engine.dispose() + with _session() as session: + household = _household(content_hash="d" * 64) + session.add(household) + session.commit() + assert isinstance(household.created_at, datetime) + assert isinstance(household.updated_at, datetime) diff --git a/tests/unit/v2/test_household_query.py b/tests/unit/v2/test_household_query.py index ccfa5d730..14a3c5426 100644 --- a/tests/unit/v2/test_household_query.py +++ b/tests/unit/v2/test_household_query.py @@ -2,23 +2,31 @@ from __future__ import annotations +from contextlib import contextmanager from datetime import UTC, datetime, timedelta +from typing import TYPE_CHECKING from uuid import UUID import pytest -from sqlmodel import Session, create_engine -from policyengine_api.data.v2.models import V2_METADATA, Household +from policyengine_api.data.v2.models import Household from policyengine_api.services.v2.households.services import ( read_complete_household, read_household_page, ) from policyengine_api.services.v2.households.validators import HouseholdNotFoundError +from tests.fixtures.database_sessions import sqlite_v2_sessions +if TYPE_CHECKING: + from collections.abc import Iterator -def _stored_households(): - engine = create_engine("sqlite://") - V2_METADATA.create_all(engine) + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + + +@contextmanager +def _stored_households() -> Iterator[tuple[sessionmaker[Session], UUID, UUID, UUID]]: + """Yield Session factories of a database storing three households, and their IDs.""" created = datetime(2026, 1, 1, tzinfo=UTC) first_id = UUID("00000000-0000-0000-0000-000000000010") second_id = UUID("00000000-0000-0000-0000-000000000020") @@ -53,31 +61,28 @@ def _stored_households(): created_at=created + timedelta(seconds=2), updated_at=created + timedelta(seconds=2), ) - with Session(engine) as session: - session.add_all([first, second, other]) - session.commit() - return engine, first_id, second_id, other_id + with sqlite_v2_sessions() as sessions: + with sessions(expire_on_commit=True) as session: + session.add_all([first, second, other]) + session.commit() + yield sessions, first_id, second_id, other_id def test_detail_is_complete_and_uses_country_as_resource_identity() -> None: - engine, first_id, _second_id, _other_id = _stored_households() - try: - with Session(engine) as session: - item = read_complete_household( - session, country_id="us", household_id=first_id - ) - assert item.household_data == {"people": [], "household": []} - assert item.default_year == 2026 - with pytest.raises(HouseholdNotFoundError): - read_complete_household(session, country_id="uk", household_id=first_id) - finally: - engine.dispose() + with ( + _stored_households() as (sessions, first_id, _second_id, _other_id), + sessions(expire_on_commit=True) as session, + ): + item = read_complete_household(session, country_id="us", household_id=first_id) + assert item.household_data == {"people": [], "household": []} + assert item.default_year == 2026 + with pytest.raises(HouseholdNotFoundError): + read_complete_household(session, country_id="uk", household_id=first_id) def test_collection_orders_paginates_and_filters_exact_default_year() -> None: - engine, first_id, second_id, _other_id = _stored_households() - try: - with Session(engine) as session: + with _stored_households() as (sessions, first_id, second_id, _other_id): + with sessions(expire_on_commit=True) as session: first_page = read_household_page( session, country_id="us", @@ -105,5 +110,3 @@ def test_collection_orders_paginates_and_filters_exact_default_year() -> None: assert [item.id for item in second_page.items] == [second_id] assert second_page.has_more is False assert [item.id for item in filtered.items] == [first_id] - finally: - engine.dispose() diff --git a/tests/unit/v2/test_household_report_reads.py b/tests/unit/v2/test_household_report_reads.py index 14ec4b7ef..0c078ec3c 100644 --- a/tests/unit/v2/test_household_report_reads.py +++ b/tests/unit/v2/test_household_report_reads.py @@ -14,12 +14,8 @@ from uuid import UUID, uuid4 import pytest -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import StaticPool -from sqlmodel import Session, create_engine from policyengine_api.data.v2.models import ( - V2_METADATA, Household, Policy, Report, @@ -60,11 +56,13 @@ CreatedReportUnreadableError, StoredReportNotFoundError, ) +from tests.fixtures.database_sessions import sqlite_v2_sessions if TYPE_CHECKING: from collections.abc import Iterator - from sqlalchemy import Engine + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session STORED_AT = datetime(2026, 11, 13, 9, tzinfo=UTC) CURRENT_VERSIONS = PackageVersions( @@ -119,20 +117,9 @@ def current_versions(country_id: str) -> PackageVersions: @pytest.fixture -def engine() -> Iterator[Engine]: - database_engine = create_engine( - "sqlite://", - connect_args={"check_same_thread": False}, - poolclass=StaticPool, - ) - V2_METADATA.create_all(database_engine) - yield database_engine - database_engine.dispose() - - -@pytest.fixture -def sessions(engine: Engine) -> sessionmaker[Session]: - return sessionmaker(engine, class_=Session, expire_on_commit=False) +def sessions() -> Iterator[sessionmaker[Session]]: + with sqlite_v2_sessions() as session_factory: + yield session_factory @pytest.fixture diff --git a/tests/unit/v2/test_legacy_reference_service.py b/tests/unit/v2/test_legacy_reference_service.py index f2d0cf54e..2b46a9d60 100644 --- a/tests/unit/v2/test_legacy_reference_service.py +++ b/tests/unit/v2/test_legacy_reference_service.py @@ -3,8 +3,6 @@ from __future__ import annotations import pytest -import sqlalchemy as sa -from sqlalchemy.orm import Session, sessionmaker from policyengine_api.data.v1_models import ( Household, @@ -23,83 +21,69 @@ from policyengine_api.services.v2.legacy_refs.validators import ( LegacyReferenceNotFoundError, ) +from tests.fixtures.database_sessions import recorded_statements, sqlite_v1_sessions @pytest.fixture def v1_sessions(): - engine = sa.create_engine("sqlite://") - # SQLite cannot autoincrement inside v1's composite policy key, so the - # physical test tables come from detached copies without that option. - sqlite_metadata = sa.MetaData() - for model in (Policy, Household, Simulation, ReportOutput): - copy = model.__table__.to_metadata(sqlite_metadata) - copy.c.id.autoincrement = False - sqlite_metadata.create_all(engine) - sessions = sessionmaker(engine, class_=Session, expire_on_commit=False) - with sessions.begin() as session: - session.add_all( - [ - Policy( - id=1, - country_id="us", - api_version="1", - policy_json={}, - policy_hash="a", - ), - Policy( - id=2, - country_id="uk", - api_version="1", - policy_json={}, - policy_hash="b", - ), - Household( - id=10, - country_id="us", - api_version="1", - household_json={}, - household_hash="h", - ), - Simulation( - id=613, - country_id="us", - api_version="1", - population_id="us", - population_type="geography", - policy_id=1, - ), - ReportOutput( - id=615, - country_id="us", - simulation_1_id=613, - api_version="1", - ), - ] - ) - yield sessions - engine.dispose() + with sqlite_v1_sessions() as sessions: + with sessions.begin() as session: + session.add_all( + [ + Policy( + id=1, + country_id="us", + api_version="1", + policy_json={}, + policy_hash="a", + ), + Policy( + id=2, + country_id="uk", + api_version="1", + policy_json={}, + policy_hash="b", + ), + Household( + id=10, + country_id="us", + api_version="1", + household_json={}, + household_hash="h", + ), + Simulation( + id=613, + country_id="us", + api_version="1", + population_id="us", + population_type="geography", + policy_id=1, + ), + ReportOutput( + id=615, + country_id="us", + simulation_1_id=613, + api_version="1", + ), + ] + ) + yield sessions def test_existing_ids_are_country_scoped_and_batched(v1_sessions, monkeypatch) -> None: monkeypatch.setattr(reads, "READ_BATCH_SIZE", 1) - statements: list[str] = [] - engine = v1_sessions.kw["bind"] - - def record(_conn, _cursor, statement, _parameters, _context, _many) -> None: - statements.append(statement) - - sa.event.listen(engine, "before_cursor_execute", record) service = V1LegacyReferenceService(LegacyReferenceDatabaseSession(v1_sessions)) - existing = service.existing_ids( - country_id="us", - requested={ - LegacyRecordKind.POLICY: [1, 2, 3], - LegacyRecordKind.HOUSEHOLD: [10], - LegacyRecordKind.SIMULATION: [613, 613], - LegacyRecordKind.REPORT: [], - }, - ) + with recorded_statements(v1_sessions) as statements: + existing = service.existing_ids( + country_id="us", + requested={ + LegacyRecordKind.POLICY: [1, 2, 3], + LegacyRecordKind.HOUSEHOLD: [10], + LegacyRecordKind.SIMULATION: [613, 613], + LegacyRecordKind.REPORT: [], + }, + ) assert existing == { LegacyRecordKind.POLICY: frozenset({1}), diff --git a/tests/unit/v2/test_metadata_service.py b/tests/unit/v2/test_metadata_service.py index 44ae5b956..9632e5612 100644 --- a/tests/unit/v2/test_metadata_service.py +++ b/tests/unit/v2/test_metadata_service.py @@ -8,7 +8,6 @@ from uuid import uuid4 import pytest -from sqlalchemy import event from sqlmodel import Session, select from policyengine_api.data.v2.catalog.catalog_selection_validation import ( @@ -48,6 +47,7 @@ MetadataResourceNotFoundError, ParameterSearchFileUnavailableError, ) +from tests.fixtures import database_sessions from tests.fixtures.v2_catalog import POLICYENGINE_VERSION, normalized_catalog from tests.fixtures.v2_metadata_service_helpers import ( add_country_version, @@ -79,17 +79,10 @@ def test_resource_collection_uses_bounded_pagination_without_counting( ) ) catalog_session.commit() - statements: list[str] = [] - - def record_statement(_connection, _cursor, statement, *_args) -> None: - statements.append(statement.lower()) - - bind = catalog_session.get_bind() - event.listen(bind, "before_cursor_execute", record_statement) - try: - result = catalog_service(catalog_session).list_variables("us", limit=1) - finally: - event.remove(bind, "before_cursor_execute", record_statement) + result, statements = recorded_statements( + catalog_session, + lambda: catalog_service(catalog_session).list_variables("us", limit=1), + ) assert [item.name for item in result.items] == ["employment_income"] assert result.policyengine_version == POLICYENGINE_VERSION @@ -110,22 +103,15 @@ def test_resource_collection_rejects_out_of_range_pages_before_querying( offset: int, limit: int, ) -> None: - statements: list[str] = [] - - def record_statement(_connection, _cursor, statement, *_args) -> None: - statements.append(statement) - - bind = catalog_session.get_bind() - event.listen(bind, "before_cursor_execute", record_statement) - try: - with pytest.raises(InvalidMetadataPageError): - catalog_service(catalog_session).list_variables( - "us", - offset=offset, - limit=limit, - ) - finally: - event.remove(bind, "before_cursor_execute", record_statement) + with ( + database_sessions.recorded_statements(catalog_session) as statements, + pytest.raises(InvalidMetadataPageError), + ): + catalog_service(catalog_session).list_variables( + "us", + offset=offset, + limit=limit, + ) assert statements == [] @@ -133,17 +119,9 @@ def record_statement(_connection, _cursor, statement, *_args) -> None: def test_parameter_collection_does_not_query_or_embed_values( catalog_session: Session, ) -> None: - statements: list[str] = [] - - def record_statement(_connection, _cursor, statement, *_args) -> None: - statements.append(statement.lower()) - - bind = catalog_session.get_bind() - event.listen(bind, "before_cursor_execute", record_statement) - try: - result = catalog_service(catalog_session).list_parameters("us") - finally: - event.remove(bind, "before_cursor_execute", record_statement) + result, statements = recorded_statements( + catalog_session, lambda: catalog_service(catalog_session).list_parameters("us") + ) assert [item.name for item in result.items] == ["gov.example.rate"] assert "values" not in result.items[0].model_dump() @@ -327,17 +305,10 @@ def test_dataset_collection_excludes_outputs_and_storage_references( def test_economy_options_read_only_regions_and_the_national_dataset( catalog_session: Session, ) -> None: - statements: list[str] = [] - - def record_statement(_connection, _cursor, statement, *_args) -> None: - statements.append(statement.lower()) - - bind = catalog_session.get_bind() - event.listen(bind, "before_cursor_execute", record_statement) - try: - result = catalog_service(catalog_session).get_economy_options("us") - finally: - event.remove(bind, "before_cursor_execute", record_statement) + result, statements = recorded_statements( + catalog_session, + lambda: catalog_service(catalog_session).get_economy_options("us"), + ) assert len(statements) == 3 assert all("variables" not in statement for statement in statements) diff --git a/tests/unit/v2/test_metadata_validation.py b/tests/unit/v2/test_metadata_validation.py index ad9e0724d..4a767e90f 100644 --- a/tests/unit/v2/test_metadata_validation.py +++ b/tests/unit/v2/test_metadata_validation.py @@ -8,11 +8,19 @@ V2MetadataValidationError, validate_v2_metadata_table_names, ) -from policyengine_api.data.v2.models import V2_METADATA +from policyengine_api.data.v2.models import TaxBenefitModel + +# The registry every v2 model is mapped on, SQLModel's own. +V2_REGISTRY = TaxBenefitModel._sa_registry + + +def _v2_table_names() -> set[str]: + """Return the name of every table a v2 model maps.""" + return {mapper.class_.__tablename__ for mapper in V2_REGISTRY.mappers} def test_current_metadata_contains_no_rejected_tables() -> None: - validate_v2_metadata_table_names(V2_METADATA.tables) + validate_v2_metadata_table_names(_v2_table_names()) @pytest.mark.parametrize( @@ -21,23 +29,23 @@ def test_current_metadata_contains_no_rejected_tables() -> None: ) def test_known_rejected_tables_are_identified(table_name: str) -> None: with pytest.raises(V2MetadataValidationError, match=table_name): - validate_v2_metadata_table_names({*V2_METADATA.tables, table_name}) + validate_v2_metadata_table_names({*_v2_table_names(), table_name}) def test_rejection_sets_do_not_block_current_metadata() -> None: - table_names = set(V2_METADATA.tables) + table_names = _v2_table_names() assert table_names.isdisjoint(PROHIBITED_V2_TABLES) assert table_names.isdisjoint(V1_ONLY_TABLES) def test_new_table_name_requires_no_allowlist_update() -> None: - validate_v2_metadata_table_names({*V2_METADATA.tables, "future_domain_table"}) + validate_v2_metadata_table_names({*_v2_table_names(), "future_domain_table"}) @pytest.mark.parametrize("table_name", ["simulations", "simulation_runs"]) def test_names_shared_with_v1_are_accepted(table_name: str) -> None: """v2 reuses these v1 table names for its own tables, in its own database.""" - assert table_name in V2_METADATA.tables + assert table_name in _v2_table_names() assert table_name not in V1_ONLY_TABLES - validate_v2_metadata_table_names({*V2_METADATA.tables, table_name}) + validate_v2_metadata_table_names({*_v2_table_names(), table_name}) diff --git a/tests/unit/v2/test_model_persistence.py b/tests/unit/v2/test_model_persistence.py index cdecc7844..e492687d1 100644 --- a/tests/unit/v2/test_model_persistence.py +++ b/tests/unit/v2/test_model_persistence.py @@ -1,15 +1,17 @@ """Canonical SQLModel persistence and bounded SQLAlchemy escape-hatch tests.""" +from collections.abc import Iterator +from contextlib import contextmanager from datetime import UTC, datetime, timedelta from pathlib import Path +from uuid import UUID import pytest import sqlalchemy as sa from sqlalchemy.exc import IntegrityError -from sqlmodel import Session, create_engine, select +from sqlmodel import Session, select from policyengine_api.data.v2.models import ( - V2_METADATA, Country, Dynamic, Household, @@ -26,22 +28,18 @@ UserPolicy, ) from policyengine_api.data.v2.models.base import DIRECT_SQLALCHEMY_EXCEPTIONS +from tests.fixtures.database_sessions import sqlite_v2_sessions from tests.fixtures.v2_countries import add_listed_countries -def _relational_sqlite_engine(): - engine = create_engine("sqlite://") - - @sa.event.listens_for(engine, "connect") - def enable_foreign_keys(dbapi_connection, _connection_record) -> None: - cursor = dbapi_connection.cursor() - cursor.execute("PRAGMA foreign_keys=ON") - cursor.close() - - V2_METADATA.create_all(engine) - with Session(engine) as session: - add_listed_countries(session) - return engine +@contextmanager +def _relational_sqlite_session() -> Iterator[Session]: + """Yield a Session of a SQLite v2 schema that enforces foreign keys.""" + with sqlite_v2_sessions(foreign_keys=True) as sessions: + with sessions(expire_on_commit=True) as session: + add_listed_countries(session) + with sessions(expire_on_commit=True) as session: + yield session def _policy_graph(*, content_hash: str = "a" * 64): @@ -69,8 +67,6 @@ def _policy_graph(*, content_hash: str = "a" * 64): def test_ordinary_persistence_uses_sqlmodel_session_select_and_exec() -> None: # SQLite exists only as an injected, in-memory unit-test fixture. Runtime # v2 settings reject it and application code never selects it. - engine = create_engine("sqlite://") - V2_METADATA.create_all(engine) model = TaxBenefitModel(name="test-country", description="Test model") version = TaxBenefitModelVersion( model=model, @@ -79,7 +75,7 @@ def test_ordinary_persistence_uses_sqlmodel_session_select_and_exec() -> None: metadata_time_periods=[2026], ) - with Session(engine) as session: + with sqlite_v2_sessions() as sessions, sessions(expire_on_commit=True) as session: session.add(version) session.commit() statement = select(TaxBenefitModelVersion).where( @@ -90,8 +86,6 @@ def test_ordinary_persistence_uses_sqlmodel_session_select_and_exec() -> None: assert stored.model.name == "test-country" assert stored.id == version.id - engine.dispose() - def test_direct_sqlalchemy_categories_are_complete_and_documented() -> None: assert set(DIRECT_SQLALCHEMY_EXCEPTIONS) == { @@ -106,9 +100,8 @@ def test_direct_sqlalchemy_categories_are_complete_and_documented() -> None: def test_user_primary_country_must_be_a_listed_country() -> None: - engine = _relational_sqlite_engine() - with Session(engine) as session: + with _relational_sqlite_session() as session: user = User( first_name="Ada", last_name="Lovelace", @@ -128,18 +121,15 @@ def test_user_primary_country_must_be_a_listed_country() -> None: with pytest.raises(IntegrityError): session.commit() - engine.dispose() - def test_a_country_row_lets_records_use_a_household_only_country() -> None: - engine = _relational_sqlite_engine() household_only_country = Country( id="be", household_enabled=True, society_wide_enabled=False, ) - with Session(engine) as session: + with _relational_sqlite_session() as session: session.add(User(primary_country="be")) with pytest.raises(IntegrityError): session.commit() @@ -168,13 +158,10 @@ def test_a_country_row_lets_records_use_a_household_only_country() -> None: stored_country = session.exec(select(UserHouseholdAssociation.country_id)).one() assert stored_country == "be" - engine.dispose() - def test_a_listed_country_cannot_be_deleted_while_records_use_it() -> None: - engine = _relational_sqlite_engine() - with Session(engine) as session: + with _relational_sqlite_session() as session: session.add(User(primary_country="uk")) session.commit() @@ -182,57 +169,50 @@ def test_a_listed_country_cannot_be_deleted_while_records_use_it() -> None: with pytest.raises(IntegrityError): session.commit() - engine.dispose() - def test_a_society_wide_country_must_also_be_household_capable() -> None: - engine = _relational_sqlite_engine() - with Session(engine) as session: + with _relational_sqlite_session() as session: session.add( Country(id="be", household_enabled=False, society_wide_enabled=True) ) with pytest.raises(IntegrityError): session.commit() - engine.dispose() - def test_only_unauthenticated_users_may_omit_a_primary_country() -> None: - engine = create_engine("sqlite://") - V2_METADATA.create_all(engine) - - with Session(engine) as session: - session.add(User(user_type="unauthenticated")) - session.commit() - for invalid in ( - User(), - User(user_type="standard"), - User(user_type="guest", primary_country="us"), - ): - with Session(engine) as session: - session.add(invalid) - with pytest.raises(IntegrityError): - session.commit() - with engine.begin() as connection: - # Writers that predate user_type rely on its server default. - connection.execute( - sa.text( - "INSERT INTO users (id, created_at, primary_country) " - "VALUES ('00000000000000000000000000000001', CURRENT_TIMESTAMP, 'us')" + with sqlite_v2_sessions() as sessions: + with sessions(expire_on_commit=True) as session: + session.add(User(user_type="unauthenticated")) + session.commit() + for invalid in ( + User(), + User(user_type="standard"), + User(user_type="guest", primary_country="us"), + ): + with sessions(expire_on_commit=True) as session: + session.add(invalid) + with pytest.raises(IntegrityError): + session.commit() + with sessions.begin() as session: + # Writers that predate user_type rely on its server default: the + # INSERT names only these columns, leaving out every default. + session.execute( + sa.insert(User).from_select( + ["id", "created_at", "primary_country"], + sa.select( + sa.literal(UUID(int=1), sa.Uuid), + sa.func.current_timestamp(), + sa.literal("us"), + ), + include_defaults=False, + ) ) - ) - stored_types = connection.execute( - sa.text("SELECT user_type FROM users ORDER BY user_type") - ).scalars() - assert list(stored_types) == ["standard", "unauthenticated"] - - engine.dispose() + stored_types = session.exec(select(User.user_type).order_by(User.user_type)) + assert list(stored_types) == ["standard", "unauthenticated"] def test_canonical_parameter_values_are_unique_by_parameter_and_start_date() -> None: - engine = create_engine("sqlite://") - V2_METADATA.create_all(engine) model = TaxBenefitModel(name="canonical-values") version = TaxBenefitModelVersion( model=model, @@ -246,7 +226,7 @@ def test_canonical_parameter_values_are_unique_by_parameter_and_start_date() -> ) start_date = datetime(2026, 1, 1, tzinfo=UTC) - with Session(engine) as session: + with sqlite_v2_sessions() as sessions, sessions(expire_on_commit=True) as session: session.add_all( [ ParameterValue( @@ -264,11 +244,8 @@ def test_canonical_parameter_values_are_unique_by_parameter_and_start_date() -> with pytest.raises(IntegrityError): session.commit() - engine.dispose() - def test_policy_content_hash_is_unique_per_canonicalization_version() -> None: - engine = _relational_sqlite_engine() model, version, _parameter, policy = _policy_graph() duplicate = Policy( country_id="us", @@ -278,16 +255,13 @@ def test_policy_content_hash_is_unique_per_canonicalization_version() -> None: content_hash=policy.content_hash, ) - with Session(engine) as session: + with _relational_sqlite_session() as session: session.add_all([policy, duplicate]) with pytest.raises(IntegrityError): session.commit() - engine.dispose() - def test_policy_parameter_value_owner_period_and_identity_constraints() -> None: - engine = _relational_sqlite_engine() model, version, parameter, policy = _policy_graph(content_hash="b" * 64) dynamic = Dynamic( country_id="us", @@ -298,7 +272,7 @@ def test_policy_parameter_value_owner_period_and_identity_constraints() -> None: ) start = datetime(2026, 1, 1, tzinfo=UTC) - with Session(engine) as session: + with _relational_sqlite_session() as session: session.add_all([parameter, policy]) session.commit() session.add(dynamic) @@ -347,15 +321,12 @@ def test_policy_parameter_value_owner_period_and_identity_constraints() -> None: with pytest.raises(IntegrityError): session.commit() - engine.dispose() - def test_user_policy_allows_duplicates_but_requires_policy_country() -> None: - engine = _relational_sqlite_engine() _model, _version, _parameter, policy = _policy_graph(content_hash="c" * 64) user = User(primary_country="us") - with Session(engine) as session: + with _relational_sqlite_session() as session: session.add_all([policy, user]) session.commit() first = UserPolicy( @@ -385,14 +356,11 @@ def test_user_policy_allows_duplicates_but_requires_policy_country() -> None: with pytest.raises(IntegrityError): session.commit() - engine.dispose() - def test_legacy_policy_mapping_allows_many_sources_for_one_policy() -> None: - engine = _relational_sqlite_engine() _model, _version, _parameter, policy = _policy_graph(content_hash="d" * 64) - with Session(engine) as session: + with _relational_sqlite_session() as session: session.add(policy) session.commit() session.add_all( @@ -426,15 +394,12 @@ def test_legacy_policy_mapping_allows_many_sources_for_one_policy() -> None: with pytest.raises(IntegrityError): session.commit() - engine.dispose() - def test_legacy_user_policy_mapping_destination_is_unique_and_cascades() -> None: - engine = _relational_sqlite_engine() _model, _version, _parameter, policy = _policy_graph(content_hash="e" * 64) user = User(primary_country="us") - with Session(engine) as session: + with _relational_sqlite_session() as session: association = UserPolicy( country_id="us", user=user, @@ -477,13 +442,10 @@ def test_legacy_user_policy_mapping_destination_is_unique_and_cascades() -> None stored_policy = session.get(Policy, policy.id) assert stored_policy is not None - engine.dispose() - def test_legacy_user_mapping_is_one_to_one_and_profile_fields_are_optional() -> None: - engine = _relational_sqlite_engine() - with Session(engine) as session: + with _relational_sqlite_session() as session: user = User(primary_country="us") session.add(user) session.commit() @@ -509,8 +471,6 @@ def test_legacy_user_mapping_is_one_to_one_and_profile_fields_are_optional() -> with pytest.raises(IntegrityError): session.commit() - engine.dispose() - def test_v2_models_do_not_create_a_parallel_sqlalchemy_orm_layer() -> None: models_directory = ( diff --git a/tests/unit/v2/test_models.py b/tests/unit/v2/test_models.py index d1316ecba..3d87687ed 100644 --- a/tests/unit/v2/test_models.py +++ b/tests/unit/v2/test_models.py @@ -1,4 +1,8 @@ -"""Structural contract tests for the complete reviewed v2 SQLModel schema.""" +"""Structural contract tests for the complete reviewed v2 SQLModel schema. + +Columns are read from the models' mappers, and keys, constraints and indexes +from SQLite's copy of the schema (tests/unit/v2/v2_schema_reading.py). +""" from typing import Literal from uuid import uuid4 @@ -6,7 +10,6 @@ import sqlalchemy as sa from sqlalchemy.dialects import postgresql from sqlalchemy.orm import configure_mappers -from sqlalchemy.schema import CreateTable from sqlmodel.sql.sqltypes import AutoString from policyengine_api.data.v1_models import V1Base @@ -35,6 +38,14 @@ UserSimulationAssociation, UserType, ) +from tests.fixtures.database_sessions import v2_schema_statements +from tests.unit.v2.v2_schema_reading import ( + declared_index, + model_columns, + stored_v2_schema, + stored_v2_table, + v2_mappers, +) # Every column that names the country a record belongs to. Each references the # countries table instead of checking a fixed list of country IDs. @@ -93,42 +104,36 @@ def test_domain_models_are_grouped_into_topic_scoped_modules() -> None: } == expected_modules -def _v2_mappers(): - configure_mappers() - return tuple( - mapper - for mapper in sa.inspect(User).registry.mappers - if mapper.local_table is not None and mapper.local_table.metadata is V2_METADATA - ) - - def test_every_metadata_table_has_one_mapped_model() -> None: - metadata_table_names = set(V2_METADATA.tables) - model_table_names = {mapper.local_table.name for mapper in _v2_mappers()} + # SQLite's copy holds every table of V2_METADATA: create_all made it. + metadata_table_names = set(stored_v2_schema()) + model_table_names = {mapper.class_.__tablename__ for mapper in v2_mappers()} assert V2_METADATA is not V1Base.metadata assert model_table_names == metadata_table_names - assert len(_v2_mappers()) == len(metadata_table_names) + assert len(v2_mappers()) == len(metadata_table_names) def test_every_table_has_named_primary_foreign_and_relational_constraints() -> None: - for table in V2_METADATA.tables.values(): - assert table.primary_key.columns - assert table.primary_key.name - for constraint in table.constraints: - assert constraint.name, f"unnamed constraint on {table.name}" - for index in table.indexes: - assert index.name, f"unnamed index on {table.name}" + tables = stored_v2_schema() + + for table in tables.values(): + assert table.primary_key + assert table.primary_key_name + for constraint_name in table.constraint_names: + assert constraint_name, f"unnamed constraint on {table.name}" + for index_name in table.indexes: + assert index_name, f"unnamed index on {table.name}" for foreign_key in table.foreign_keys: - assert foreign_key.constraint.name + assert foreign_key.name assert foreign_key.ondelete in {"CASCADE", "RESTRICT", "SET NULL"} - assert foreign_key.column.table.name in V2_METADATA.tables + assert foreign_key.referred_table in tables def test_every_declared_relationship_has_a_complete_back_populates_pair() -> None: configure_mappers() - for mapper in _v2_mappers(): + for mapper in v2_mappers(): for relationship in mapper.relationships: assert relationship.back_populates, ( f"{mapper.class_.__name__}.{relationship.key} lacks back_populates" @@ -157,10 +162,9 @@ def test_user_owned_associations_have_relational_integrity() -> None: ) for model, table_name, user_collection in associations: - user_id = V2_METADATA.tables[table_name].c.user_id - foreign_keys = list(user_id.foreign_keys) + foreign_keys = stored_v2_table(table_name).foreign_keys_of("user_id") assert len(foreign_keys) == 1 - assert foreign_keys[0].target_fullname == "users.id" + assert foreign_keys[0].target == "users.id" assert foreign_keys[0].ondelete == "CASCADE" association_user = sa.inspect(model).relationships["user"] @@ -169,9 +173,10 @@ def test_user_owned_associations_have_relational_integrity() -> None: def test_policy_content_identity_and_catalog_columns_are_explicit() -> None: - policies = V2_METADATA.tables["policies"] + columns = model_columns("policies") + policies = stored_v2_table("policies") - assert {"name", "description"}.isdisjoint(policies.c.keys()) + assert {"name", "description"}.isdisjoint(columns.keys()) assert { "country_id", "tax_benefit_model_id", @@ -180,73 +185,50 @@ def test_policy_content_identity_and_catalog_columns_are_explicit() -> None: "content_hash", "created_at", "updated_at", - }.issubset(policies.c.keys()) - assert policies.c.country_id.type.length == 2 - assert policies.c.content_hash.type.length == 64 - unique_columns = { - tuple(column.name for column in constraint.columns) - for constraint in policies.constraints - if isinstance(constraint, sa.UniqueConstraint) - } - assert ("id", "country_id") in unique_columns - assert ("canonicalization_version", "content_hash") in unique_columns + }.issubset(columns.keys()) + assert columns.country_id.type.length == 2 + assert columns.content_hash.type.length == 64 + assert ("id", "country_id") in policies.unique_column_sets + assert ("canonicalization_version", "content_hash") in policies.unique_column_sets assert { "ix_policies_country_model", "ix_policies_country_model_version", - } <= {index.name for index in policies.indexes} + } <= set(policies.indexes) def test_policy_parameter_values_use_jsonb_and_enforce_period_identity() -> None: - values = V2_METADATA.tables["parameter_values"] + columns = model_columns("parameter_values") + values = stored_v2_table("parameter_values") - postgres_type = values.c.value_json.type.dialect_impl(postgresql.dialect()) + postgres_type = columns.value_json.type.dialect_impl(postgresql.dialect()) assert isinstance(postgres_type, postgresql.JSONB) assert { "ck_parameter_values_single_owner", "ck_parameter_values_effective_period", - } <= {constraint.name for constraint in values.constraints} - unique_columns = { - tuple(column.name for column in constraint.columns) - for constraint in values.constraints - if isinstance(constraint, sa.UniqueConstraint) - } - assert ("policy_id", "parameter_id", "start_date") in unique_columns + } <= values.constraint_names + assert ("policy_id", "parameter_id", "start_date") in values.unique_column_sets assert sa.inspect(ParameterValue).relationships["policy"].back_populates == ( "parameter_values" ) def test_user_policy_is_an_independent_country_scoped_association() -> None: - associations = V2_METADATA.tables["user_policies"] + columns = model_columns("user_policies") + associations = stored_v2_table("user_policies") - assert isinstance(associations.c.user_id.type, sa.Uuid) - user_foreign_key = next(iter(associations.c.user_id.foreign_keys)) - assert user_foreign_key.target_fullname == "users.id" + assert isinstance(columns.user_id.type, sa.Uuid) + user_foreign_key = associations.foreign_keys_of("user_id")[0] + assert user_foreign_key.target == "users.id" assert user_foreign_key.ondelete == "CASCADE" - assert {"country", "label"}.isdisjoint(associations.c.keys()) - assert {"country_id", "name", "description"}.issubset(associations.c.keys()) - assert associations.c.name.nullable - assert associations.c.description.nullable - unique_columns = { - tuple(column.name for column in constraint.columns) - for constraint in associations.constraints - if isinstance(constraint, sa.UniqueConstraint) - } - assert ("user_id", "policy_id") not in unique_columns - assert ("id", "country_id") in unique_columns - policy_country = next( - constraint - for constraint in associations.foreign_key_constraints - if constraint.name == "fk_user_policies_policy_country" - ) - assert [column.name for column in policy_country.columns] == [ - "policy_id", - "country_id", - ] - assert [element.target_fullname for element in policy_country.elements] == [ - "policies.id", - "policies.country_id", - ] + assert {"country", "label"}.isdisjoint(columns.keys()) + assert {"country_id", "name", "description"}.issubset(columns.keys()) + assert columns.name.nullable + assert columns.description.nullable + assert ("user_id", "policy_id") not in associations.unique_column_sets + assert ("id", "country_id") in associations.unique_column_sets + policy_country = associations.foreign_key_named("fk_user_policies_policy_country") + assert policy_country.columns == ("policy_id", "country_id") + assert policy_country.targets == ("policies.id", "policies.country_id") assert policy_country.ondelete == "RESTRICT" assert sa.inspect(UserPolicy).relationships["user"].back_populates == ( "policy_associations" @@ -254,60 +236,47 @@ def test_user_policy_is_an_independent_country_scoped_association() -> None: def test_legacy_user_mapping_is_one_to_one() -> None: - mappings = V2_METADATA.tables["legacy_user_mappings"] - - assert mappings.primary_key.columns.keys() == ["legacy_user_id"] - assert mappings.c.legacy_user_id.type.length == 255 - assert mappings.c.created_at.type.timezone - unique_columns = { - tuple(column.name for column in constraint.columns) - for constraint in mappings.constraints - if isinstance(constraint, sa.UniqueConstraint) - } - assert ("user_id",) in unique_columns - user_foreign_key = next(iter(mappings.c.user_id.foreign_keys)) - assert user_foreign_key.target_fullname == "users.id" + columns = model_columns("legacy_user_mappings") + mappings = stored_v2_table("legacy_user_mappings") + + assert mappings.primary_key == ("legacy_user_id",) + assert columns.legacy_user_id.type.length == 255 + assert columns.created_at.type.timezone + assert ("user_id",) in mappings.unique_column_sets + user_foreign_key = mappings.foreign_keys_of("user_id")[0] + assert user_foreign_key.target == "users.id" assert user_foreign_key.ondelete == "RESTRICT" def test_legacy_policy_mapping_is_many_to_one_by_destination() -> None: - mappings = V2_METADATA.tables["legacy_policy_mappings"] - - unique_columns = { - tuple(column.name for column in constraint.columns) - for constraint in mappings.constraints - if isinstance(constraint, sa.UniqueConstraint) - } - assert ("country_id", "legacy_policy_id") in unique_columns - assert ("policy_id",) not in unique_columns - assert mappings.c.source_policy_hash.type.length == 255 - foreign_keys = { - constraint.name: constraint for constraint in mappings.foreign_key_constraints - } - assert foreign_keys["fk_legacy_policy_mappings_policy_country"].ondelete == ( - "RESTRICT" + columns = model_columns("legacy_policy_mappings") + mappings = stored_v2_table("legacy_policy_mappings") + + assert ("country_id", "legacy_policy_id") in mappings.unique_column_sets + assert ("policy_id",) not in mappings.unique_column_sets + assert columns.source_policy_hash.type.length == 255 + policy_country = mappings.foreign_key_named( + "fk_legacy_policy_mappings_policy_country" ) - assert foreign_keys["fk_legacy_policy_mappings_dynamic_country"].ondelete == ( - "RESTRICT" + assert policy_country.ondelete == "RESTRICT" + dynamic_country = mappings.foreign_key_named( + "fk_legacy_policy_mappings_dynamic_country" ) + assert dynamic_country.ondelete == "RESTRICT" def test_legacy_user_policy_mapping_is_one_to_one_by_destination() -> None: - mappings = V2_METADATA.tables["legacy_user_policy_mappings"] - - unique_columns = { - tuple(column.name for column in constraint.columns) - for constraint in mappings.constraints - if isinstance(constraint, sa.UniqueConstraint) - } - assert ("country_id", "legacy_user_policy_id") in unique_columns - assert ("user_policy_id",) in unique_columns - assert mappings.c.fingerprint_sha256.type.length == 64 - assert mappings.c.last_applied_source_revision.server_default.arg == "0" - assert "ck_legacy_user_policy_mappings_source_revision" in { - constraint.name for constraint in mappings.constraints - } - association_country = next(iter(mappings.foreign_key_constraints)) + columns = model_columns("legacy_user_policy_mappings") + mappings = stored_v2_table("legacy_user_policy_mappings") + + assert ("country_id", "legacy_user_policy_id") in mappings.unique_column_sets + assert ("user_policy_id",) in mappings.unique_column_sets + assert columns.fingerprint_sha256.type.length == 64 + assert columns.last_applied_source_revision.server_default.arg == "0" + assert "ck_legacy_user_policy_mappings_source_revision" in ( + mappings.constraint_names + ) + association_country = mappings.foreign_keys[0] assert ( association_country.name == "fk_legacy_user_policy_mappings_association_country" ) @@ -317,8 +286,8 @@ def test_legacy_user_policy_mapping_is_one_to_one_by_destination() -> None: def test_all_datetime_columns_are_timezone_aware() -> None: datetime_columns = [ column - for table in V2_METADATA.tables.values() - for column in table.columns + for mapper in v2_mappers() + for column in mapper.columns if isinstance(column.type, sa.DateTime) ] @@ -327,10 +296,10 @@ def test_all_datetime_columns_are_timezone_aware() -> None: def test_report_definition_and_run_columns_are_separated() -> None: - report = V2_METADATA.tables["reports"] - report_run = V2_METADATA.tables["report_runs"] + report = model_columns("reports") + report_run = model_columns("report_runs") - assert report.c.type.nullable + assert report.type.nullable assert { "country", "type", @@ -343,7 +312,7 @@ def test_report_definition_and_run_columns_are_separated() -> None: "region_id", "year", "inputs", - }.issubset(report.c.keys()) + }.issubset(report.keys()) assert { "country_package_version", "policyengine_version", @@ -354,36 +323,31 @@ def test_report_definition_and_run_columns_are_separated() -> None: "completed_at", "error_message", "markdown", - }.issubset(report_run.c.keys()) + }.issubset(report_run.keys()) assert { "country_package_version", "policyengine_version", "status", "error_message", "markdown", - }.isdisjoint(report.c.keys()) - assert not report_run.c.country_package_version.nullable - assert not report_run.c.policyengine_version.nullable - assert isinstance(report_run.c.idempotency_key.type, sa.Uuid) - assert report_run.c.idempotency_key.type.as_uuid + }.isdisjoint(report.keys()) + assert not report_run.country_package_version.nullable + assert not report_run.policyengine_version.nullable + assert isinstance(report_run.idempotency_key.type, sa.Uuid) + assert report_run.idempotency_key.type.as_uuid def test_standard_users_require_a_supported_primary_country() -> None: - users = V2_METADATA.tables["users"] + users = model_columns("users") # Nullable only for unauthenticated users; a check requires it otherwise. - assert users.c.primary_country.nullable - assert users.c.first_name.nullable - assert users.c.last_name.nullable - assert users.c.email.nullable - assert users.c.primary_country.type.length == 2 - checks = { - constraint.name: str(constraint.sqltext) - for constraint in users.constraints - if isinstance(constraint, sa.CheckConstraint) - } + assert users.primary_country.nullable + assert users.first_name.nullable + assert users.last_name.nullable + assert users.email.nullable + assert users.primary_country.type.length == 2 # The countries table, not a check, lists the countries a user may choose. - assert checks == { + assert stored_v2_table("users").checks == { "ck_users_user_type_allowed": ( "user_type IN ('unauthenticated', 'standard', 'author', 'admin')" ), @@ -394,13 +358,13 @@ def test_standard_users_require_a_supported_primary_country() -> None: def test_user_type_defaults_to_standard_for_every_writer() -> None: - users = V2_METADATA.tables["users"] + users = model_columns("users") - assert not users.c.user_type.nullable - assert users.c.user_type.type.length == 16 + assert not users.user_type.nullable + assert users.user_type.type.length == 16 # The server default covers inserts by Public API revisions that predate # the column; the Python default covers this revision's ORM inserts. - assert users.c.user_type.server_default.arg == "standard" + assert users.user_type.server_default.arg == "standard" assert User().user_type == "standard" assert [member.value for member in UserType] == [ "unauthenticated", @@ -411,73 +375,65 @@ def test_user_type_defaults_to_standard_for_every_writer() -> None: def test_regions_have_one_same_model_version_default_logical_dataset() -> None: - regions = V2_METADATA.tables["regions"] - datasets = V2_METADATA.tables["datasets"] - - assert "region_datasets" not in V2_METADATA.tables - assert not regions.c.default_dataset_id.nullable - assert regions.c.default_dataset_id.index - default_constraint = next( - constraint - for constraint in regions.foreign_key_constraints - if constraint.name == "fk_regions_default_dataset_model_version" + regions = model_columns("regions") + datasets = model_columns("datasets") + stored_regions = stored_v2_table("regions") + stored_datasets = stored_v2_table("datasets") + + assert "region_datasets" not in stored_v2_schema() + assert not regions.default_dataset_id.nullable + assert regions.default_dataset_id.index + default_constraint = stored_regions.foreign_key_named( + "fk_regions_default_dataset_model_version" ) - assert [element.parent.name for element in default_constraint.elements] == [ + assert default_constraint.columns == ( "default_dataset_id", "tax_benefit_model_version_id", - ] - assert [element.target_fullname for element in default_constraint.elements] == [ + ) + assert default_constraint.targets == ( "datasets.id", "datasets.tax_benefit_model_version_id", - ] + ) assert default_constraint.ondelete == "RESTRICT" - unique_column_sets = { - tuple(column.name for column in constraint.columns) - for constraint in datasets.constraints - if isinstance(constraint, sa.UniqueConstraint) - } + unique_column_sets = stored_datasets.unique_column_sets assert ("tax_benefit_model_version_id", "name") in unique_column_sets assert ("id", "tax_benefit_model_version_id") in unique_column_sets - assert "tax_benefit_model_id" not in datasets.c - assert "tax_benefit_model_id" not in regions.c - assert not datasets.c.tax_benefit_model_version_id.nullable - assert not regions.c.tax_benefit_model_version_id.nullable - assert datasets.c.storage_path.nullable - assert "ck_datasets_output_storage_path" in { - constraint.name for constraint in datasets.constraints - } + assert "tax_benefit_model_id" not in datasets + assert "tax_benefit_model_id" not in regions + assert not datasets.tax_benefit_model_version_id.nullable + assert not regions.tax_benefit_model_version_id.nullable + assert datasets.storage_path.nullable + assert "ck_datasets_output_storage_path" in stored_datasets.constraint_names def test_reports_and_simulations_snapshot_selected_datasets() -> None: - reports = V2_METADATA.tables["reports"] - simulations = V2_METADATA.tables["simulations"] - - for table in (reports, simulations): - dataset_foreign_key = next(iter(table.c.dataset_id.foreign_keys)) - assert dataset_foreign_key.target_fullname == "datasets.id" + for table_name in ("reports", "simulations"): + table = stored_v2_table(table_name) + dataset_foreign_key = table.foreign_keys_of("dataset_id")[0] + assert dataset_foreign_key.target == "datasets.id" assert dataset_foreign_key.ondelete in {"RESTRICT", "SET NULL"} def test_stage9_adds_no_dataset_version_relationship_to_run_tables() -> None: for table_name in ("simulations", "reports", "report_runs"): - assert "dataset_version_id" not in V2_METADATA.tables[table_name].c + assert "dataset_version_id" not in model_columns(table_name) def test_run_outputs_reference_report_runs_not_base_reports() -> None: for table_name in RUN_OUTPUT_TABLES: - table = V2_METADATA.tables[table_name] - assert "report_run_id" in table.c - assert not table.c.report_run_id.nullable - assert "report_id" not in table.c - foreign_key = next(iter(table.c.report_run_id.foreign_keys)) - assert foreign_key.target_fullname == "report_runs.id" + columns = model_columns(table_name) + assert "report_run_id" in columns + assert not columns.report_run_id.nullable + assert "report_id" not in columns + foreign_key = stored_v2_table(table_name).foreign_keys_of("report_run_id")[0] + assert foreign_key.target == "report_runs.id" assert foreign_key.ondelete == "CASCADE" def test_uk_area_impacts_store_no_map_coordinates() -> None: for table_name in ("constituency_impacts", "local_authority_impacts"): - assert {"x", "y"}.isdisjoint(V2_METADATA.tables[table_name].c.keys()) + assert {"x", "y"}.isdisjoint(model_columns(table_name).keys()) def test_report_reruns_deduplicate_requests_and_keep_failed_or_forced_runs() -> None: @@ -487,12 +443,8 @@ def test_report_reruns_deduplicate_requests_and_keep_failed_or_forced_runs() -> constraint covers the versions; ``test_shared_report_models.py`` checks the partial unique index that does. """ - report_runs = V2_METADATA.tables["report_runs"] - unique_column_sets = { - tuple(column.name for column in constraint.columns) - for constraint in report_runs.constraints - if isinstance(constraint, sa.UniqueConstraint) - } + report_runs = stored_v2_table("report_runs") + unique_column_sets = report_runs.unique_column_sets assert ("report_id", "idempotency_key") in unique_column_sets assert ( @@ -503,18 +455,17 @@ def test_report_reruns_deduplicate_requests_and_keep_failed_or_forced_runs() -> assert { "ix_report_runs_current_output", "uq_report_runs_unfailed_unforced_versions", - } <= {index.name for index in report_runs.indexes} + } <= set(report_runs.indexes) def test_named_checks_and_required_indexes_cover_core_invariants() -> None: + tables = stored_v2_schema().values() constraint_names = { - constraint.name - for table in V2_METADATA.tables.values() - for constraint in table.constraints - } - index_names = { - index.name for table in V2_METADATA.tables.values() for index in table.indexes + constraint_name + for table in tables + for constraint_name in table.constraint_names } + index_names = {index_name for table in tables for index_name in table.indexes} assert { "ck_regions_required_filter_values", @@ -536,8 +487,8 @@ def test_named_checks_and_required_indexes_cover_core_invariants() -> None: def test_stage9_uses_policyengine_version_as_its_only_catalog_release_identity() -> ( None ): - model_version = V2_METADATA.tables[TaxBenefitModelVersion.__tablename__] - dataset_version = V2_METADATA.tables[DatasetVersion.__tablename__] + model_version = model_columns(TaxBenefitModelVersion) + dataset_version = model_columns(DatasetVersion) forbidden_columns = { "policyengine_version", "core_version", @@ -547,29 +498,24 @@ def test_stage9_uses_policyengine_version_as_its_only_catalog_release_identity() "catalog_fingerprint", } - assert set(model_version.c) >= { - model_version.c.model_id, - model_version.c.version, - model_version.c.current_law_id, - model_version.c.metadata_time_periods, + assert set(model_version) >= { + model_version.model_id, + model_version.version, + model_version.current_law_id, + model_version.metadata_time_periods, } - assert forbidden_columns.isdisjoint(model_version.c.keys()) - assert forbidden_columns.isdisjoint(dataset_version.c.keys()) + assert forbidden_columns.isdisjoint(model_version.keys()) + assert forbidden_columns.isdisjoint(dataset_version.keys()) - unique_column_sets = { - tuple(column.name for column in constraint.columns) - for constraint in model_version.constraints - if isinstance(constraint, sa.UniqueConstraint) - } + unique_column_sets = stored_v2_table( + TaxBenefitModelVersion.__tablename__ + ).unique_column_sets assert ("model_id", "version") in unique_column_sets def test_canonical_parameter_values_have_a_postgres_partial_unique_index() -> None: - parameter_values = V2_METADATA.tables["parameter_values"] - index = next( - index - for index in parameter_values.indexes - if index.name == "uq_parameter_values_canonical_parameter_start_date" + index = declared_index( + ParameterValue, "uq_parameter_values_canonical_parameter_start_date" ) assert index.unique @@ -582,37 +528,32 @@ def test_canonical_parameter_values_have_a_postgres_partial_unique_index() -> No def test_complete_metadata_compiles_for_postgres_without_mutation() -> None: - dialect = postgresql.dialect() - statements = [ - str(CreateTable(table).compile(dialect=dialect)) - for table in V2_METADATA.sorted_tables + statement + for statement in v2_schema_statements("postgresql") + if statement.lstrip().startswith("CREATE TABLE") ] - assert len(statements) == len(V2_METADATA.tables) - assert all("CREATE TABLE" in statement for statement in statements) + # One CREATE TABLE for each table of V2_METADATA, which SQLite's copy holds. + assert len(statements) == len(stored_v2_schema()) def test_user_identity_maps_one_issuer_subject_to_one_user() -> None: - identities = V2_METADATA.tables["user_identities"] + identities = model_columns("user_identities") + stored_identities = stored_v2_table("user_identities") - unique_columns = { - constraint.name: tuple(column.name for column in constraint.columns) - for constraint in identities.constraints - if isinstance(constraint, sa.UniqueConstraint) - } - assert unique_columns == { + assert stored_identities.unique_constraints == { "uq_user_identities_issuer_subject": ("issuer", "subject") } - assert isinstance(identities.c.issuer.type, sa.Text) - assert isinstance(identities.c.subject.type, sa.Text) - assert identities.c.email.nullable - assert identities.c.email.type.length == 320 - assert not identities.c.last_seen_at.nullable - user_foreign_key = next(iter(identities.c.user_id.foreign_keys)) - assert user_foreign_key.target_fullname == "users.id" + assert isinstance(identities.issuer.type, sa.Text) + assert isinstance(identities.subject.type, sa.Text) + assert identities.email.nullable + assert identities.email.type.length == 320 + assert not identities.last_seen_at.nullable + user_foreign_key = stored_identities.foreign_keys_of("user_id")[0] + assert user_foreign_key.target == "users.id" assert user_foreign_key.ondelete == "CASCADE" - assert "ix_user_identities_user_id" in {index.name for index in identities.indexes} + assert "ix_user_identities_user_id" in stored_identities.indexes assert sa.inspect(User).relationships["identities"].back_populates == "user" @@ -623,25 +564,21 @@ def test_associations_are_v1_anchored_without_client_refs() -> None: ("user_simulation_associations", "simulation"), ("user_report_associations", "report"), ): - table = V2_METADATA.tables[table_name] - assert table.c[f"{reference}_id"].nullable - assert table.c[f"legacy_{reference}_id"].nullable - assert isinstance(table.c[f"legacy_{reference}_id"].type, sa.BigInteger) - assert "client_ref" not in table.c - assert not table.c.country_id.nullable - assert table.c.country_id.type.length == 2 - constraints = {constraint.name: constraint for constraint in table.constraints} - reference_check = constraints[f"ck_{table_name}_{reference}_ref"] - assert str(reference_check.sqltext) == ( + columns = model_columns(table_name) + table = stored_v2_table(table_name) + assert columns[f"{reference}_id"].nullable + assert columns[f"legacy_{reference}_id"].nullable + assert isinstance(columns[f"legacy_{reference}_id"].type, sa.BigInteger) + assert "client_ref" not in columns + assert not columns.country_id.nullable + assert columns.country_id.type.length == 2 + reference_check = table.checks[f"ck_{table_name}_{reference}_ref"] + assert reference_check == ( f"{reference}_id IS NOT NULL OR legacy_{reference}_id IS NOT NULL" ) # No uniqueness involves the owner, so a merge at sign-in can move # any association to another user unchanged. - assert { - tuple(column.name for column in constraint.columns) - for constraint in table.constraints - if isinstance(constraint, sa.UniqueConstraint) - } == {("id", "country_id")} + assert table.unique_column_sets == {("id", "country_id")} def test_saved_simulations_and_reports_name_stored_v2_rows() -> None: @@ -651,32 +588,37 @@ def test_saved_simulations_and_reports_name_stored_v2_rows() -> None: ``reports``, with ``RESTRICT``: a saved item can't name a row that doesn't exist, and a simulation or report a saved item names can't be deleted. """ - simulations = V2_METADATA.tables["user_simulation_associations"] - reports = V2_METADATA.tables["user_report_associations"] + simulations = stored_v2_table("user_simulation_associations") + reports = stored_v2_table("user_report_associations") + report_columns = model_columns("user_report_associations") # The retired columns stay, nullable, for the previous Public API revision. - for table in (simulations, reports): - assert table.c.country.nullable - assert table.c.label.nullable - assert { - foreign_key.target_fullname for foreign_key in simulations.foreign_keys - } == {"users.id", "countries.id", "simulations.id"} - assert {foreign_key.target_fullname for foreign_key in reports.foreign_keys} == { + for table_name in ("user_simulation_associations", "user_report_associations"): + columns = model_columns(table_name) + assert columns.country.nullable + assert columns.label.nullable + assert {foreign_key.target for foreign_key in simulations.foreign_key_columns} == { + "users.id", + "countries.id", + "simulations.id", + } + assert {foreign_key.target for foreign_key in reports.foreign_key_columns} == { "users.id", "user_policies.id", "countries.id", "reports.id", } - (simulation_key,) = simulations.c.simulation_id.foreign_keys - assert simulation_key.target_fullname == "simulations.id" + simulation_key = simulations.foreign_key("simulation_id") + assert simulation_key.target == "simulations.id" assert simulation_key.ondelete == "RESTRICT" - (report_key,) = reports.c.report_id.foreign_keys - assert report_key.target_fullname == "reports.id" + report_key = reports.foreign_key("report_id") + assert report_key.target == "reports.id" assert report_key.ondelete == "RESTRICT" - user_policy_key = next(iter(reports.c.user_policy_id.foreign_keys)) + user_policy_key = reports.foreign_keys_of("user_policy_id")[0] assert user_policy_key.ondelete == "SET NULL" for column_name in ("provisions", "validation"): - postgres_type = reports.c[column_name].type.dialect_impl(postgresql.dialect()) + column_type = report_columns[column_name].type + postgres_type = column_type.dialect_impl(postgresql.dialect()) assert isinstance(postgres_type, postgresql.JSONB) assert set(sa.inspect(UserSimulationAssociation).relationships.keys()) == {"user"} assert set(sa.inspect(UserReportAssociation).relationships.keys()) == {"user"} @@ -684,39 +626,33 @@ def test_saved_simulations_and_reports_name_stored_v2_rows() -> None: def test_user_policy_records_v3_reform_fields() -> None: - policies = V2_METADATA.tables["user_policies"] + policies = model_columns("user_policies") - assert policies.c.baseline.type.length == 16 - baseline_check = next( - constraint - for constraint in policies.constraints - if constraint.name == "ck_user_policies_baseline" - ) - assert "current-law" in str(baseline_check.sqltext) - assert "current-policy" in str(baseline_check.sqltext) - postgres_type = policies.c.provenance.type.dialect_impl(postgresql.dialect()) + assert policies.baseline.type.length == 16 + baseline_check = stored_v2_table("user_policies").checks[ + "ck_user_policies_baseline" + ] + assert "current-law" in baseline_check + assert "current-policy" in baseline_check + postgres_type = policies.provenance.type.dialect_impl(postgresql.dialect()) assert isinstance(postgres_type, postgresql.JSONB) def test_countries_record_household_and_society_wide_capability() -> None: - countries = V2_METADATA.tables["countries"] + countries = model_columns("countries") + stored_countries = stored_v2_table("countries") - assert countries.c.keys() == ["id", "household_enabled", "society_wide_enabled"] - assert countries.primary_key.columns.keys() == ["id"] - assert countries.primary_key.name == "pk_countries" - assert countries.c.id.type.length == 2 + assert countries.keys() == ["id", "household_enabled", "society_wide_enabled"] + assert stored_countries.primary_key == ("id",) + assert stored_countries.primary_key_name == "pk_countries" + assert countries.id.type.length == 2 for flag_name in ("household_enabled", "society_wide_enabled"): - assert isinstance(countries.c[flag_name].type, sa.Boolean) - assert not countries.c[flag_name].nullable - assert countries.c[flag_name].server_default is None - checks = { - constraint.name: str(constraint.sqltext) - for constraint in countries.constraints - if isinstance(constraint, sa.CheckConstraint) - } + assert isinstance(countries[flag_name].type, sa.Boolean) + assert not countries[flag_name].nullable + assert countries[flag_name].server_default is None # Society-wide reports need household calculations, so a society-wide # country is always household capable too. - assert checks == { + assert stored_countries.checks == { "ck_countries_society_wide_requires_household": ( "household_enabled OR NOT society_wide_enabled" ), @@ -727,23 +663,22 @@ def test_country_columns_reference_the_countries_table_instead_of_a_fixed_list() None ): for table_name, column_name in COUNTRY_REFERENCE_COLUMNS: - table = V2_METADATA.tables[table_name] + table = stored_v2_table(table_name) country_keys = [ foreign_key - for foreign_key in table.c[column_name].foreign_keys - if foreign_key.column.table.name == "countries" + for foreign_key in table.foreign_keys_of(column_name) + if foreign_key.referred_table == "countries" ] assert len(country_keys) == 1, table_name - assert country_keys[0].target_fullname == "countries.id" + assert country_keys[0].target == "countries.id" assert country_keys[0].ondelete == "RESTRICT" - assert country_keys[0].constraint.name == ( + assert country_keys[0].constraint_name == ( f"fk_{table_name}_{column_name}_countries" ) fixed_country_checks = [ - constraint.name - for constraint in table.constraints - if isinstance(constraint, sa.CheckConstraint) - and "'us', 'uk'" in str(constraint.sqltext) + check_name + for check_name, condition in table.checks.items() + if "'us', 'uk'" in condition ] assert fixed_country_checks == [], table_name @@ -757,18 +692,16 @@ def test_v1_copy_mappings_keep_their_us_and_uk_checks() -> None: "legacy_policy_mappings", "legacy_user_policy_mappings", ): - table = V2_METADATA.tables[table_name] - assert f"ck_{table_name}_country" in { - constraint.name for constraint in table.constraints - } + table = stored_v2_table(table_name) + assert f"ck_{table_name}_country" in table.constraint_names assert "countries.id" not in { - foreign_key.target_fullname for foreign_key in table.foreign_keys + foreign_key.target for foreign_key in table.foreign_key_columns } def test_spm_availability_is_nullable_for_versions_not_yet_recorded() -> None: """Publication records it after the catalog, so a version may lack it.""" - column = V2_METADATA.tables["tax_benefit_model_versions"].c["spm_availability"] + column = model_columns("tax_benefit_model_versions")["spm_availability"] assert column.nullable assert column.server_default is None @@ -805,22 +738,22 @@ def test_catalog_format_2_columns_are_nullable_for_earlier_versions() -> None: } for table_name, columns in expected_columns.items(): - table = V2_METADATA.tables[table_name] + mapped_columns = model_columns(table_name) for column_name, column_type in columns.items(): - column = table.c[column_name] + column = mapped_columns[column_name] assert column.nullable, f"{table_name}.{column_name}" assert column.server_default is None, f"{table_name}.{column_name}" assert isinstance(column.type, column_type), f"{table_name}.{column_name}" - variables = V2_METADATA.tables["variables"] + variables = model_columns("variables") for column_name in ( "module_name", "adds_parameter_path", "subtracts_parameter_path", ): - assert variables.c[column_name].type.length == 512 - assert variables.c["unit"].type.length == 128 - assert variables.c["definition_period"].type.length == 32 + assert variables[column_name].type.length == 512 + assert variables["unit"].type.length == 128 + assert variables["definition_period"].type.length == 32 def test_catalog_format_2_json_columns_have_typed_shapes() -> None: @@ -857,9 +790,10 @@ def test_parameter_tree_children_have_one_row_per_path_in_listing_order() -> Non unique index (version, parent path, position); a parameter row references its parameter, and both references are removed with their rows. """ - table = V2_METADATA.tables["parameter_tree_children"] + columns = model_columns("parameter_tree_children") + table = stored_v2_table("parameter_tree_children") - assert {column.name for column in table.columns} == { + assert set(columns.keys()) == { "id", "created_at", "tax_benefit_model_version_id", @@ -876,8 +810,8 @@ def test_parameter_tree_children_have_one_row_per_path_in_listing_order() -> Non "household", } for column_name in ("parent_path", "path", "label"): - assert table.c[column_name].type.length == 512 - assert not table.c[column_name].nullable + assert columns[column_name].type.length == 512 + assert not columns[column_name].nullable for column_name in ( "child_count", "reform_position", @@ -886,16 +820,11 @@ def test_parameter_tree_children_have_one_row_per_path_in_listing_order() -> Non "economy", "household", ): - assert table.c[column_name].nullable - unique_constraints = { - tuple(column.name for column in constraint.columns) - for constraint in table.constraints - if isinstance(constraint, sa.UniqueConstraint) - } - assert ("tax_benefit_model_version_id", "path") in unique_constraints + assert columns[column_name].nullable + assert ("tax_benefit_model_version_id", "path") in table.unique_column_sets indexes = { - index.name: (tuple(column.name for column in index.columns), index.unique) - for index in table.indexes + index_name: (index.columns, index.unique) + for index_name, index in table.indexes.items() } assert indexes["ix_parameter_tree_children_listing"] == ( ("tax_benefit_model_version_id", "parent_path", "position"), @@ -909,20 +838,11 @@ def test_parameter_tree_children_have_one_row_per_path_in_listing_order() -> Non ("parameter_id",), False, ) - foreign_keys = { - foreign_key.parent.name: (foreign_key.column.table.name, foreign_key.ondelete) - for foreign_key in table.foreign_keys - } - assert foreign_keys == { + assert table.references_by_column == { "tax_benefit_model_version_id": ("tax_benefit_model_versions", "CASCADE"), "parameter_id": ("parameters", "CASCADE"), } - checks = { - constraint.name - for constraint in table.constraints - if isinstance(constraint, sa.CheckConstraint) - } - assert checks == { + assert set(table.checks) == { "ck_parameter_tree_children_child_type", "ck_parameter_tree_children_parameter_reference", } @@ -933,7 +853,7 @@ def test_parameter_tree_child_type_is_typed_with_its_two_values() -> None: annotation = ParameterTreeChild.model_fields["child_type"].annotation assert annotation == Literal["node", "parameter"] - column = V2_METADATA.tables["parameter_tree_children"].c["child_type"] + column = model_columns("parameter_tree_children")["child_type"] assert isinstance(column.type, AutoString) assert column.type.length == 16 @@ -944,9 +864,10 @@ def test_parameter_search_files_hold_one_compressed_file_per_version() -> None: The row holds the gzip-compressed JSON, its file format, the SHA-256 of the uncompressed JSON (the response's ETag) and both sizes. """ - table = V2_METADATA.tables["parameter_search_files"] + columns = model_columns("parameter_search_files") + table = stored_v2_table("parameter_search_files") - assert {column.name for column in table.columns} == { + assert set(columns.keys()) == { "id", "created_at", "tax_benefit_model_version_id", @@ -956,26 +877,17 @@ def test_parameter_search_files_hold_one_compressed_file_per_version() -> None: "uncompressed_size", "compressed_size", } - for column in table.columns: + for column in columns: assert not column.nullable, column.name - assert isinstance(table.c["compressed_content"].type, sa.LargeBinary) - assert table.c["content_sha256"].type.length == 64 - unique_constraints = { - constraint.name: tuple(column.name for column in constraint.columns) - for constraint in table.constraints - if isinstance(constraint, sa.UniqueConstraint) - } - assert unique_constraints == { + assert isinstance(columns["compressed_content"].type, sa.LargeBinary) + assert columns["content_sha256"].type.length == 64 + assert table.unique_constraints == { "uq_parameter_search_files_model_version_format": ( "tax_benefit_model_version_id", "file_format", ) } - foreign_keys = { - foreign_key.parent.name: (foreign_key.column.table.name, foreign_key.ondelete) - for foreign_key in table.foreign_keys - } - assert foreign_keys == { + assert table.references_by_column == { "tax_benefit_model_version_id": ("tax_benefit_model_versions", "CASCADE"), } @@ -987,9 +899,7 @@ def test_catalog_pruning_marker_is_a_nullable_timezone_aware_timestamp() -> None and search file are stored, and holds the time pruning removed them. It has no default, so a version is published unpruned. """ - column = V2_METADATA.tables["tax_benefit_model_versions"].c[ - "catalog_values_pruned_at" - ] + column = model_columns("tax_benefit_model_versions")["catalog_values_pruned_at"] assert column.nullable assert column.server_default is None @@ -1012,9 +922,7 @@ def test_catalog_publication_time_is_a_nullable_timezone_aware_timestamp() -> No keeps the most recently published versions. It is null for a version no publication has recorded since the column was added, and has no default. """ - column = V2_METADATA.tables["tax_benefit_model_versions"].c[ - "catalog_last_published_at" - ] + column = model_columns("tax_benefit_model_versions")["catalog_last_published_at"] assert column.nullable assert column.server_default is None @@ -1024,9 +932,10 @@ def test_catalog_publication_time_is_a_nullable_timezone_aware_timestamp() -> No def test_user_type_changes_record_each_change_of_a_signed_in_users_type() -> None: - changes = V2_METADATA.tables["user_type_changes"] + changes = model_columns("user_type_changes") + stored_changes = stored_v2_table("user_type_changes") - assert {column.name for column in changes.columns} == { + assert set(changes.keys()) == { "id", "created_at", "user_id", @@ -1036,28 +945,19 @@ def test_user_type_changes_record_each_change_of_a_signed_in_users_type() -> Non "source", "dismissed_at", } - assert not changes.c.user_id.nullable - assert changes.c.changed_by_user_id.nullable + assert not changes.user_id.nullable + assert changes.changed_by_user_id.nullable # Set when the user dismisses the app's notice of the change. - assert changes.c.dismissed_at.nullable - assert isinstance(changes.c.dismissed_at.type, sa.DateTime) - assert changes.c.dismissed_at.type.timezone is True - foreign_keys = { - key.parent.name: (key.column.table.name, key.ondelete) - for key in changes.foreign_keys - } + assert changes.dismissed_at.nullable + assert isinstance(changes.dismissed_at.type, sa.DateTime) + assert changes.dismissed_at.type.timezone is True # A user's history goes with the user; an admin's deletion keeps the change. - assert foreign_keys == { + assert stored_changes.references_by_column == { "user_id": ("users", "CASCADE"), "changed_by_user_id": ("users", "SET NULL"), } - checks = { - constraint.name: str(constraint.sqltext) - for constraint in changes.constraints - if isinstance(constraint, sa.CheckConstraint) - } signed_in_types = "('standard', 'author', 'admin')" - assert checks == { + assert stored_changes.checks == { "ck_user_type_changes_previous_user_type": ( f"previous_user_type IN {signed_in_types}" ), @@ -1070,15 +970,17 @@ def test_user_type_changes_record_each_change_of_a_signed_in_users_type() -> Non ), } # The admin's index serves the SET NULL that each user deletion runs. - assert { - tuple(column.name for column in index.columns) for index in changes.indexes - } == {("user_id", "created_at"), ("changed_by_user_id",)} + assert set(stored_changes.index_columns.values()) == { + ("user_id", "created_at"), + ("changed_by_user_id",), + } def test_user_invitations_hold_each_invitation_and_only_its_token_hash() -> None: - invitations = V2_METADATA.tables["user_invitations"] + invitations = model_columns("user_invitations") + stored_invitations = stored_v2_table("user_invitations") - assert {column.name for column in invitations.columns} == { + assert set(invitations.keys()) == { "id", "created_at", "email", @@ -1093,45 +995,30 @@ def test_user_invitations_hold_each_invitation_and_only_its_token_hash() -> None "revoked_at", } required = {"id", "created_at", "email", "user_type", "token_hash", "expires_at"} - assert { - column.name for column in invitations.columns if not column.nullable - } == required + assert {column.name for column in invitations if not column.nullable} == required for name in ("expires_at", "last_sent_at", "accepted_at", "revoked_at"): - column_type = invitations.c[name].type + column_type = invitations[name].type assert isinstance(column_type, sa.DateTime), name assert column_type.timezone is True, name - assert invitations.c.email.type.length == 320 + assert invitations.email.type.length == 320 # A SHA-256 digest in hexadecimal; the token itself is never stored. - assert invitations.c.token_hash.type.length == 64 - assert invitations.c.last_send_error.type.length == 64 - foreign_keys = { - key.parent.name: (key.column.table.name, key.ondelete) - for key in invitations.foreign_keys - } + assert invitations.token_hash.type.length == 64 + assert invitations.last_send_error.type.length == 64 # Deleting the inviting admin keeps the invitation; deleting the user who # accepted it deletes it, so the address, theirs, goes with the account. - assert foreign_keys == { + assert stored_invitations.references_by_column == { "invited_by_user_id": ("users", "SET NULL"), "accepted_by_user_id": ("users", "CASCADE"), } - checks = { - constraint.name: str(constraint.sqltext) - for constraint in invitations.constraints - if isinstance(constraint, sa.CheckConstraint) - } - assert checks == { + assert stored_invitations.checks == { "ck_user_invitations_user_type": "user_type IN ('author', 'admin')", "ck_user_invitations_accepted_or_revoked": ( "accepted_at IS NULL OR revoked_at IS NULL" ), } - unique = { - tuple(column.name for column in constraint.columns) - for constraint in invitations.constraints - if isinstance(constraint, sa.UniqueConstraint) - } - assert unique == {("token_hash",)} + assert stored_invitations.unique_column_sets == {("token_hash",)} # The users' indexes serve what each user deletion runs on them. - assert { - tuple(column.name for column in index.columns) for index in invitations.indexes - } == {("invited_by_user_id",), ("accepted_by_user_id",)} + assert set(stored_invitations.index_columns.values()) == { + ("invited_by_user_id",), + ("accepted_by_user_id",), + } diff --git a/tests/unit/v2/test_pending_revisions.py b/tests/unit/v2/test_pending_revisions.py new file mode 100644 index 000000000..67698dcbc --- /dev/null +++ b/tests/unit/v2/test_pending_revisions.py @@ -0,0 +1,19 @@ +"""Tests for the check of whether a v2 Alembic revision is still to be applied.""" + +from __future__ import annotations + +from policyengine_api.data.v2.household_migration_qualification import ( + HOUSEHOLD_MIGRATION_REVISION, +) +from policyengine_api.data.v2.pending_revisions import v2_revision_is_pending +from tests.fixtures.database_sessions import sqlite_v2_sessions + + +def test_every_revision_is_pending_for_a_database_alembic_never_stamped() -> None: + with sqlite_v2_sessions() as sessions, sessions() as session: + assert v2_revision_is_pending(session, HOUSEHOLD_MIGRATION_REVISION) + + +def test_a_revision_outside_the_v2_chain_is_never_pending() -> None: + with sqlite_v2_sessions() as sessions, sessions() as session: + assert not v2_revision_is_pending(session, "000000000000") diff --git a/tests/unit/v2/test_policy_catalog.py b/tests/unit/v2/test_policy_catalog.py index 87bffb464..a225f2e2c 100644 --- a/tests/unit/v2/test_policy_catalog.py +++ b/tests/unit/v2/test_policy_catalog.py @@ -2,16 +2,16 @@ from __future__ import annotations +from dataclasses import dataclass +from typing import TYPE_CHECKING from uuid import uuid4 import pytest -from sqlmodel import Session, create_engine from policyengine_api.data.v2.catalog.catalog_selection_validation import ( MetadataCatalogVersionNotFoundError, ) from policyengine_api.data.v2.models import ( - V2_METADATA, Parameter, TaxBenefitModel, TaxBenefitModelVersion, @@ -23,36 +23,61 @@ from policyengine_api.services.v2.policies.validators import ( PolicyCatalogValidationError, ) +from tests.fixtures.database_sessions import sqlite_v2_sessions +if TYPE_CHECKING: + from collections.abc import Iterator -def _catalog_session(): - engine = create_engine("sqlite://") - V2_METADATA.create_all(engine) - session = Session(engine) - us_model = TaxBenefitModel(name="policyengine-us") - current = TaxBenefitModelVersion( - model=us_model, - version="5.2.0", - current_law_id=1, - metadata_time_periods=[2026], - ) - previous = TaxBenefitModelVersion( - model=us_model, - version="5.1.0", - current_law_id=2, - metadata_time_periods=[2025], - ) - current_parameter = Parameter( - name="gov.example.rate", - tax_benefit_model_version=current, - ) - previous_parameter = Parameter( - name="gov.example.old_rate", - tax_benefit_model_version=previous, - ) - session.add_all([current_parameter, previous_parameter]) - session.commit() - return engine, session, us_model, current, current_parameter, previous_parameter + from sqlmodel import Session + + +@dataclass(frozen=True) +class StoredCatalog: + """A US model's two stored versions, each with one parameter. + + ``session`` is open on the in-memory SQLite database that holds them. + """ + + session: Session + model: TaxBenefitModel + version: TaxBenefitModelVersion + parameter: Parameter + previous_parameter: Parameter + + +@pytest.fixture +def stored_catalog() -> Iterator[StoredCatalog]: + with sqlite_v2_sessions() as sessions, sessions() as session: + us_model = TaxBenefitModel(name="policyengine-us") + current = TaxBenefitModelVersion( + model=us_model, + version="5.2.0", + current_law_id=1, + metadata_time_periods=[2026], + ) + previous = TaxBenefitModelVersion( + model=us_model, + version="5.1.0", + current_law_id=2, + metadata_time_periods=[2025], + ) + current_parameter = Parameter( + name="gov.example.rate", + tax_benefit_model_version=current, + ) + previous_parameter = Parameter( + name="gov.example.old_rate", + tax_benefit_model_version=previous, + ) + session.add_all([current_parameter, previous_parameter]) + session.commit() + yield StoredCatalog( + session=session, + model=us_model, + version=current, + parameter=current_parameter, + previous_parameter=previous_parameter, + ) def _command(model_id, parameter_id=None, *, country_id="us"): @@ -72,83 +97,66 @@ def _command(model_id, parameter_id=None, *, country_id="us"): ) -def test_resolver_binds_model_version_and_all_parameter_ids() -> None: - engine, session, model, version, parameter, _previous = _catalog_session() - try: - resolved = resolve_policy_creation_input( - session, - _command(model.id, parameter.id), +def test_resolver_binds_model_version_and_all_parameter_ids( + stored_catalog: StoredCatalog, +) -> None: + resolved = resolve_policy_creation_input( + stored_catalog.session, + _command(stored_catalog.model.id, stored_catalog.parameter.id), + policyengine_version="5.2.0", + running_policyengine_version="different-running-version", + ) + + assert resolved.country_id == "us" + assert resolved.tax_benefit_model_id == stored_catalog.model.id + assert resolved.tax_benefit_model_version_id == stored_catalog.version.id + assert resolved.policyengine_version == "5.2.0" + assert resolved.parameter_values[0].parameter_id == stored_catalog.parameter.id + + +def test_omitted_version_selects_the_running_catalog( + stored_catalog: StoredCatalog, +) -> None: + resolved = resolve_policy_creation_input( + stored_catalog.session, + _command(stored_catalog.model.id), + running_policyengine_version="5.2.0", + ) + assert resolved.tax_benefit_model_version_id == stored_catalog.version.id + + +def test_wrong_stable_model_is_rejected(stored_catalog: StoredCatalog) -> None: + with pytest.raises(PolicyCatalogValidationError, match="selected country"): + resolve_policy_creation_input( + stored_catalog.session, + _command(uuid4(), stored_catalog.parameter.id), policyengine_version="5.2.0", - running_policyengine_version="different-running-version", ) - assert resolved.country_id == "us" - assert resolved.tax_benefit_model_id == model.id - assert resolved.tax_benefit_model_version_id == version.id - assert resolved.policyengine_version == "5.2.0" - assert resolved.parameter_values[0].parameter_id == parameter.id - finally: - session.close() - engine.dispose() - - -def test_omitted_version_selects_the_running_catalog() -> None: - engine, session, model, version, _parameter, _previous = _catalog_session() - try: - resolved = resolve_policy_creation_input( - session, - _command(model.id), - running_policyengine_version="5.2.0", + +def test_parameter_from_another_model_version_is_rejected( + stored_catalog: StoredCatalog, +) -> None: + with pytest.raises(PolicyCatalogValidationError, match="every parameter_id"): + resolve_policy_creation_input( + stored_catalog.session, + _command(stored_catalog.model.id, stored_catalog.previous_parameter.id), + policyengine_version="5.2.0", + ) + + +def test_absent_or_unsupported_catalog_never_falls_back( + stored_catalog: StoredCatalog, +) -> None: + with pytest.raises(MetadataCatalogVersionNotFoundError): + resolve_policy_creation_input( + stored_catalog.session, + _command(stored_catalog.model.id), + policyengine_version="4.0.0", + ) + with pytest.raises(MetadataCatalogVersionNotFoundError): + resolve_policy_creation_input( + stored_catalog.session, + _command(stored_catalog.model.id, country_id="uk"), + policyengine_version="5.2.0", ) - assert resolved.tax_benefit_model_version_id == version.id - finally: - session.close() - engine.dispose() - - -def test_wrong_stable_model_is_rejected() -> None: - engine, session, _model, _version, parameter, _previous = _catalog_session() - try: - with pytest.raises(PolicyCatalogValidationError, match="selected country"): - resolve_policy_creation_input( - session, - _command(uuid4(), parameter.id), - policyengine_version="5.2.0", - ) - finally: - session.close() - engine.dispose() - - -def test_parameter_from_another_model_version_is_rejected() -> None: - engine, session, model, _version, _parameter, previous = _catalog_session() - try: - with pytest.raises(PolicyCatalogValidationError, match="every parameter_id"): - resolve_policy_creation_input( - session, - _command(model.id, previous.id), - policyengine_version="5.2.0", - ) - finally: - session.close() - engine.dispose() - - -def test_absent_or_unsupported_catalog_never_falls_back() -> None: - engine, session, model, _version, _parameter, _previous = _catalog_session() - try: - with pytest.raises(MetadataCatalogVersionNotFoundError): - resolve_policy_creation_input( - session, - _command(model.id), - policyengine_version="4.0.0", - ) - with pytest.raises(MetadataCatalogVersionNotFoundError): - resolve_policy_creation_input( - session, - _command(model.id, country_id="uk"), - policyengine_version="5.2.0", - ) - finally: - session.close() - engine.dispose() diff --git a/tests/unit/v2/test_policy_legacy_copy.py b/tests/unit/v2/test_policy_legacy_copy.py index 7bf5b903a..0947c039a 100644 --- a/tests/unit/v2/test_policy_legacy_copy.py +++ b/tests/unit/v2/test_policy_legacy_copy.py @@ -8,13 +8,12 @@ from dataclasses import asdict, dataclass, field from datetime import UTC, datetime +from typing import TYPE_CHECKING from uuid import UUID import pytest -from sqlmodel import Session, create_engine from policyengine_api.data.v2.models import ( - V2_METADATA, LegacyPolicyMapping, Parameter, TaxBenefitModel, @@ -37,6 +36,10 @@ LegacyPolicyMappingIntegrityError, LegacyPolicyTranslationError, ) +from tests.fixtures.database_sessions import sqlite_v2_sessions + +if TYPE_CHECKING: + from sqlmodel import Session RUNNING_POLICYENGINE_VERSION = "6.7.5" COPIED_POLICY_ID = UUID("00000000-0000-0000-0000-000000000042") @@ -81,14 +84,8 @@ def record_mapping(_session, mapping): @pytest.fixture def catalog_session(): - engine = create_engine("sqlite://") - V2_METADATA.create_all(engine) - session = Session(engine) - try: + with sqlite_v2_sessions() as sessions, sessions(expire_on_commit=True) as session: yield session - finally: - session.close() - engine.dispose() def _add_running_catalog( diff --git a/tests/unit/v2/test_policy_legacy_translation.py b/tests/unit/v2/test_policy_legacy_translation.py index d4d2d2d69..d9577c71a 100644 --- a/tests/unit/v2/test_policy_legacy_translation.py +++ b/tests/unit/v2/test_policy_legacy_translation.py @@ -3,18 +3,17 @@ from __future__ import annotations import json +from contextlib import contextmanager from datetime import UTC, datetime +from typing import TYPE_CHECKING import pytest from pydantic import ValidationError -from sqlalchemy.orm import sessionmaker -from sqlmodel import Session, create_engine from policyengine_api.data.v2.catalog.catalog_selection_validation import ( MetadataCatalogNotPublishedError, ) from policyengine_api.data.v2.models import ( - V2_METADATA, Parameter, TaxBenefitModel, TaxBenefitModelVersion, @@ -42,13 +41,27 @@ LegacyPolicyTranslationError, parameters_missing_from_model, ) -from tests.fixtures.local_v1_database import create_test_v1_schema +from tests.fixtures.database_sessions import sqlite_v1_sessions, sqlite_v2_sessions +if TYPE_CHECKING: + from collections.abc import Iterator -def _session_and_catalog(): - engine = create_engine("sqlite://") - V2_METADATA.create_all(engine) - session = Session(engine) + from sqlmodel import Session + + +@contextmanager +def _session_and_catalog() -> Iterator[ + tuple[Session, TaxBenefitModel, TaxBenefitModelVersion, Parameter, Parameter] +]: + """Yield a Session of a catalog version with two parameters, and the catalog.""" + with sqlite_v2_sessions() as sessions, sessions(expire_on_commit=True) as session: + yield (session, *_store_catalog(session)) + + +def _store_catalog( + session: Session, +) -> tuple[TaxBenefitModel, TaxBenefitModelVersion, Parameter, Parameter]: + """Store a model's catalog version with two parameters; return them.""" model = TaxBenefitModel(name="policyengine-us") version = TaxBenefitModelVersion( model=model, @@ -66,7 +79,7 @@ def _session_and_catalog(): ) session.add_all([first, second]) session.commit() - return engine, session, model, version, first, second + return model, version, first, second def _snapshot(**changes) -> LegacyPolicySnapshot: @@ -125,8 +138,7 @@ def test_year_day_and_explicit_range_periods_are_inclusive_utc() -> None: def test_translation_resolves_paths_and_excludes_legacy_identity_and_label() -> None: - engine, session, model, version, first, second = _session_and_catalog() - try: + with _session_and_catalog() as (session, model, version, first, second): translated = _translate(session, _snapshot()) assert translated.tax_benefit_model_id == model.id @@ -137,20 +149,13 @@ def test_translation_resolves_paths_and_excludes_legacy_identity_and_label() -> } assert "label" not in type(translated).model_fields assert "legacy_policy_id" not in type(translated).model_fields - finally: - session.close() - engine.dispose() def test_label_does_not_change_translated_core_content() -> None: - engine, session, _model, _version, _first, _second = _session_and_catalog() - try: + with _session_and_catalog() as (session, _model, _version, _first, _second): first = _translate(session, _snapshot(label="First")) second = _translate(session, _snapshot(label="Second", legacy_policy_id=43)) assert first == second - finally: - session.close() - engine.dispose() @pytest.mark.parametrize( @@ -179,19 +184,19 @@ def serialize_stored_json(value): ) ) - v1_engine = create_engine("sqlite://", json_serializer=serialize_stored_json) - create_test_v1_schema(v1_engine) - service = PolicyService(sessionmaker(v1_engine, expire_on_commit=False)) monkeypatch.setattr( "policyengine_api.services.policy_service.COUNTRY_PACKAGE_VERSIONS", {"us": "1.0.0"}, ) - engine, session, _model, _version, _first, _second = _session_and_catalog() request = { "gov.example.rate": {"2026-01-01.2100-12-31": request_value}, "gov.example.amount": {"2026": 100}, } - try: + with ( + sqlite_v1_sessions(json_serializer=serialize_stored_json) as v1_sessions, + _session_and_catalog() as (session, _model, _version, _first, _second), + ): + service = PolicyService(v1_sessions) first = service.set_policy( "us", "First label", request, prepare_for_mirroring=True ) @@ -237,10 +242,6 @@ def unavailable_mirror(): for result in (first, retry, equivalent) ) assert request["gov.example.rate"]["2026-01-01.2100-12-31"] == request_value - finally: - session.close() - engine.dispose() - v1_engine.dispose() @pytest.mark.parametrize( @@ -292,33 +293,25 @@ def test_untranslatable_policy_fails_with_a_fixed_reason( policy_json: dict[str, object], reason: LegacyPolicyTranslationReason, ) -> None: - engine, session, _model, _version, _first, _second = _session_and_catalog() - try: + with _session_and_catalog() as (session, _model, _version, _first, _second): with pytest.raises(LegacyPolicyTranslationError) as failure: _translate(session, _snapshot(policy_json=policy_json)) assert failure.value.reason is reason - finally: - session.close() - engine.dispose() def test_policy_with_more_values_than_v2_accepts_fails_as_too_many_values() -> None: - engine, session, _model, _version, _first, _second = _session_and_catalog() # One more dated value than a v2 policy may hold, with no repeated dates. too_many_periods = { f"{2026 + offset}-01-01.{2026 + offset}-12-31": offset for offset in range(MAXIMUM_POLICY_PARAMETER_VALUES + 1) } - try: + with _session_and_catalog() as (session, _model, _version, _first, _second): with pytest.raises(LegacyPolicyTranslationError) as failure: _translate( session, _snapshot(policy_json={"gov.example.rate": too_many_periods}), ) assert failure.value.reason is LegacyPolicyTranslationReason.TOO_MANY_VALUES - finally: - session.close() - engine.dispose() def test_parameters_missing_from_model_lists_each_absent_name_once_in_order() -> None: @@ -341,8 +334,7 @@ def test_parameters_missing_from_model_lists_each_absent_name_once_in_order() -> def test_policy_saved_under_another_country_package_translates_to_running_catalog( saved_api_version: str, ) -> None: - engine, session, _model, version, first, second = _session_and_catalog() - try: + with _session_and_catalog() as (session, _model, version, first, second): translated = _translate(session, _snapshot(api_version=saved_api_version)) assert translated.tax_benefit_model_version_id == version.id @@ -351,9 +343,6 @@ def test_policy_saved_under_another_country_package_translates_to_running_catalo second.id, } assert translated == _translate(session, _snapshot()) - finally: - session.close() - engine.dispose() @pytest.mark.parametrize( @@ -377,16 +366,14 @@ def test_reverse_legacy_range_is_rejected() -> None: def test_unknown_policyengine_version_never_falls_back() -> None: - engine, session, _model, _version, _first, _second = _session_and_catalog() - try: - with pytest.raises( + with ( + _session_and_catalog() as (session, _model, _version, _first, _second), + pytest.raises( MetadataCatalogNotPublishedError, match=r"running PolicyEngine\.py" - ): - _translate( - session, - _snapshot(), - running_policyengine_version="4.0.0", - ) - finally: - session.close() - engine.dispose() + ), + ): + _translate( + session, + _snapshot(), + running_policyengine_version="4.0.0", + ) diff --git a/tests/unit/v2/test_policy_migration_qualification.py b/tests/unit/v2/test_policy_migration_qualification.py index 54a711ef4..c9507d6b0 100644 --- a/tests/unit/v2/test_policy_migration_qualification.py +++ b/tests/unit/v2/test_policy_migration_qualification.py @@ -2,9 +2,6 @@ from __future__ import annotations -from contextlib import contextmanager -from typing import TYPE_CHECKING - import pytest from policyengine_api.data.v2 import policy_migration_qualification as qualification @@ -12,10 +9,14 @@ V2_MIGRATION_DATABASE_URL, V2_SUPABASE_ENVIRONMENT, V2_SUPABASE_PROJECT_REF, + load_v2_migration_database_settings, +) +from tests.unit.v2.qualification_sessions import ( + CountingSession, + QualificationSessions, + serve_public_tables, + serve_read_only_sessions, ) - -if TYPE_CHECKING: - from collections.abc import Iterator ENVIRONMENT = { V2_MIGRATION_DATABASE_URL: ( @@ -27,51 +28,23 @@ } -class FakeTransaction: - def __init__(self) -> None: - self.rolled_back = False - - def rollback(self) -> None: - self.rolled_back = True - - -class FakeConnection: - def __init__(self, counts: tuple[int, int, int]) -> None: - self._counts = iter(counts) - self.transaction = FakeTransaction() - self.statements: list[str] = [] - - def begin(self) -> FakeTransaction: - return self.transaction - - def exec_driver_sql(self, statement: str) -> None: - self.statements.append(statement) - - def scalar(self, _statement: object) -> int: - return next(self._counts) - +@pytest.fixture(autouse=True) +def _every_policy_table_exists(monkeypatch: pytest.MonkeyPatch) -> None: + serve_public_tables(monkeypatch) -class FakeEngine: - def __init__(self, connection: FakeConnection) -> None: - self.connection = connection - self.disposed = False - @contextmanager - def connect(self) -> Iterator[FakeConnection]: - yield self.connection +def _configured_url() -> object: + return load_v2_migration_database_settings(ENVIRONMENT).connection.url - def dispose(self) -> None: - self.disposed = True +def test_empty_target_is_qualified_in_a_rolled_back_read_only_transaction( + monkeypatch: pytest.MonkeyPatch, +) -> None: + session = CountingSession((0, 0, 0)) + sessions = QualificationSessions(session) + read_only_urls = serve_read_only_sessions(monkeypatch, sessions) -def test_empty_target_is_qualified_in_a_rolled_back_read_only_transaction() -> None: - connection = FakeConnection((0, 0, 0)) - engine = FakeEngine(connection) - - evidence = qualification.qualify_policy_migration_target( - ENVIRONMENT, - engine_builder=lambda _settings: engine, - ) + evidence = qualification.qualify_policy_migration_target(ENVIRONMENT) assert evidence.as_dict() == { "outcome": "ok", @@ -84,19 +57,21 @@ def test_empty_target_is_qualified_in_a_rolled_back_read_only_transaction() -> N "user_policies": 0, }, } - assert connection.statements == ["SET TRANSACTION READ ONLY"] - assert connection.transaction.rolled_back - assert engine.disposed + assert read_only_urls == [_configured_url()] + assert session.rolled_back + assert sessions.closed -def test_applied_policy_revision_skips_predecessor_row_qualification() -> None: - connection = FakeConnection((1, 2, 3)) - engine = FakeEngine(connection) +def test_applied_policy_revision_skips_predecessor_row_qualification( + monkeypatch: pytest.MonkeyPatch, +) -> None: + session = CountingSession((1, 2, 3)) + sessions = QualificationSessions(session) + read_only_urls = serve_read_only_sessions(monkeypatch, sessions) evidence = qualification.qualify_policy_migration_if_pending( ENVIRONMENT, - engine_builder=lambda _settings: engine, - pending_checker=lambda _connection: False, + pending_checker=lambda _session: False, ) assert evidence.as_dict() == { @@ -110,25 +85,29 @@ def test_applied_policy_revision_skips_predecessor_row_qualification() -> None: "user_policies": 0, }, } - assert connection.statements == ["SET TRANSACTION READ ONLY"] - assert connection.transaction.rolled_back - assert engine.disposed + assert read_only_urls == [_configured_url()] + assert session.statements == [] + assert session.rolled_back + assert sessions.closed -def test_pending_policy_revision_runs_predecessor_row_qualification() -> None: - connection = FakeConnection((0, 0, 0)) - engine = FakeEngine(connection) +def test_pending_policy_revision_runs_predecessor_row_qualification( + monkeypatch: pytest.MonkeyPatch, +) -> None: + session = CountingSession((0, 0, 0)) + sessions = QualificationSessions(session) + read_only_urls = serve_read_only_sessions(monkeypatch, sessions) evidence = qualification.qualify_policy_migration_if_pending( ENVIRONMENT, - engine_builder=lambda _settings: engine, - pending_checker=lambda _connection: True, + pending_checker=lambda _session: True, ) assert evidence.required is True - assert connection.statements == ["SET TRANSACTION READ ONLY"] - assert connection.transaction.rolled_back - assert engine.disposed + assert read_only_urls == [_configured_url()] + assert len(session.statements) == 3 + assert session.rolled_back + assert sessions.closed @pytest.mark.parametrize( @@ -143,8 +122,8 @@ def test_pending_policy_revision_runs_predecessor_row_qualification() -> None: def test_retained_policy_data_stops_without_committing( counts: tuple[int, int, int], ) -> None: - connection = FakeConnection(counts) - engine = FakeEngine(connection) + session = CountingSession(counts) + sessions = QualificationSessions(session) with pytest.raises( qualification.RetainedPolicyDataError, @@ -152,12 +131,12 @@ def test_retained_policy_data_stops_without_committing( ) as raised: qualification.qualify_policy_migration_target( ENVIRONMENT, - engine_builder=lambda _settings: engine, + session_factories=sessions, ) assert raised.value.counts == qualification.PolicyDataCounts(*counts) - assert connection.transaction.rolled_back - assert engine.disposed + assert session.rolled_back + assert sessions.closed def test_main_redacts_unexpected_errors( diff --git a/tests/unit/v2/test_policy_missing_parameters.py b/tests/unit/v2/test_policy_missing_parameters.py index ebf41c08d..38dd40a7d 100644 --- a/tests/unit/v2/test_policy_missing_parameters.py +++ b/tests/unit/v2/test_policy_missing_parameters.py @@ -4,17 +4,15 @@ from collections import deque from datetime import UTC, datetime +from typing import TYPE_CHECKING from uuid import uuid4 import pytest -from sqlalchemy.orm import sessionmaker -from sqlmodel import Session, create_engine from policyengine_api.data.v2.catalog.catalog_selection_validation import ( MetadataCatalogUnavailableError, ) from policyengine_api.data.v2.models import ( - V2_METADATA, Parameter, ParameterValue, Policy, @@ -36,8 +34,15 @@ PolicyCreationResult, PolicyRead, ) +from tests.fixtures.database_sessions import sqlite_v2_sessions from tests.fixtures.recording_session import RecordingSession +if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + RUNNING_VERSION = "5.2.0" EARLIER_VERSION = "5.1.0" KEPT_PARAMETER = "gov.example.rate" @@ -45,21 +50,20 @@ @pytest.fixture -def engine(): - database_engine = create_engine("sqlite://") - V2_METADATA.create_all(database_engine) - yield database_engine - database_engine.dispose() +def sessions() -> Iterator[sessionmaker[Session]]: + with sqlite_v2_sessions() as session_factory: + yield session_factory @pytest.fixture -def session(engine): - with Session(engine) as database_session: +def session(sessions): + with sessions(expire_on_commit=True) as database_session: yield database_session -def _service(engine, running_policyengine_version: str = RUNNING_VERSION): - sessions = sessionmaker(engine, class_=Session, expire_on_commit=False) +def _service( + sessions: sessionmaker[Session], running_policyengine_version: str = RUNNING_VERSION +) -> V2PolicyService: return V2PolicyService( PolicyDatabaseSession(sessions), running_policyengine_version=running_policyengine_version, @@ -133,9 +137,9 @@ def stored_policies(session: Session) -> dict[str, Policy]: def test_policy_on_an_earlier_catalog_names_the_parameters_the_running_one_lacks( - engine, stored_policies: dict[str, Policy] + sessions, stored_policies: dict[str, Policy] ) -> None: - policy = _service(engine).get_policy( + policy = _service(sessions).get_policy( country_id="us", policy_id=stored_policies["earlier"].id ) @@ -143,9 +147,9 @@ def test_policy_on_an_earlier_catalog_names_the_parameters_the_running_one_lacks def test_policy_on_the_running_catalog_lacks_nothing( - engine, stored_policies: dict[str, Policy] + sessions, stored_policies: dict[str, Policy] ) -> None: - policy = _service(engine).get_policy( + policy = _service(sessions).get_policy( country_id="us", policy_id=stored_policies["running"].id ) @@ -153,9 +157,9 @@ def test_policy_on_the_running_catalog_lacks_nothing( def test_page_reports_each_policy_against_the_running_catalog( - engine, stored_policies: dict[str, Policy] + sessions, stored_policies: dict[str, Policy] ) -> None: - page = _service(engine).list_policies(country_id="us", offset=0, limit=10) + page = _service(sessions).list_policies(country_id="us", offset=0, limit=10) assert {item.id: item.missing_parameters for item in page.items} == { stored_policies["earlier"].id: (REMOVED_PARAMETER,), @@ -164,10 +168,10 @@ def test_page_reports_each_policy_against_the_running_catalog( def test_without_a_running_catalog_nothing_is_reported( - engine, stored_policies: dict[str, Policy] + sessions, stored_policies: dict[str, Policy] ) -> None: # The running PolicyEngine.py release has no published catalog yet. - policy = _service(engine, running_policyengine_version="9.9.9").get_policy( + policy = _service(sessions, running_policyengine_version="9.9.9").get_policy( country_id="us", policy_id=stored_policies["earlier"].id ) @@ -198,7 +202,7 @@ def test_parameter_names_are_read_in_batches_of_bounded_size() -> None: def test_catalog_that_cannot_be_queried_fails_the_read( - engine, stored_policies: dict[str, Policy], monkeypatch + sessions, stored_policies: dict[str, Policy], monkeypatch ) -> None: def unreadable_catalog(*_args, **_kwargs): msg = "the v2 metadata catalog cannot be queried" @@ -207,13 +211,13 @@ def unreadable_catalog(*_args, **_kwargs): monkeypatch.setattr(policy_services, "read_policy_catalog", unreadable_catalog) with pytest.raises(MetadataCatalogUnavailableError): - _service(engine).get_policy( + _service(sessions).get_policy( country_id="us", policy_id=stored_policies["earlier"].id ) def test_created_policy_on_an_earlier_catalog_names_what_the_running_one_lacks( - engine, stored_policies: dict[str, Policy], monkeypatch + sessions, stored_policies: dict[str, Policy], monkeypatch ) -> None: # Creation is replaced by the stored policy (its inserts need PostgreSQL); # the read and check after it are the service's own. @@ -231,7 +235,7 @@ def test_created_policy_on_an_earlier_catalog_names_what_the_running_one_lacks( ), ) - creation = _service(engine).create_policy( + creation = _service(sessions).create_policy( NativePolicyCreationInput( country_id="us", tax_benefit_model_id=stored.tax_benefit_model_id, @@ -244,11 +248,11 @@ def test_created_policy_on_an_earlier_catalog_names_what_the_running_one_lacks( def test_only_a_checked_read_carries_missing_parameters( - engine, stored_policies: dict[str, Policy] + sessions, stored_policies: dict[str, Policy] ) -> None: # A read that skipped the check cannot be mistaken for "catalog not # published": only the checked type has the field. - policy = _service(engine).get_policy( + policy = _service(sessions).get_policy( country_id="us", policy_id=stored_policies["running"].id ) diff --git a/tests/unit/v2/test_policy_query.py b/tests/unit/v2/test_policy_query.py index 4fa5b129b..5c898c068 100644 --- a/tests/unit/v2/test_policy_query.py +++ b/tests/unit/v2/test_policy_query.py @@ -2,14 +2,14 @@ from __future__ import annotations +from contextlib import contextmanager from datetime import UTC, datetime, timedelta +from typing import TYPE_CHECKING from uuid import UUID import pytest -from sqlmodel import Session, create_engine from policyengine_api.data.v2.models import ( - V2_METADATA, Parameter, ParameterValue, Policy, @@ -23,12 +23,25 @@ from policyengine_api.services.v2.policies.validators import ( PolicyNotFoundError, ) +from tests.fixtures.database_sessions import sqlite_v2_sessions +if TYPE_CHECKING: + from collections.abc import Iterator -def _stored_policies(): - engine = create_engine("sqlite://") - V2_METADATA.create_all(engine) - session = Session(engine) + from sqlmodel import Session + + +@contextmanager +def _stored_policies() -> Iterator[ + tuple[Session, TaxBenefitModel, Policy, Policy, Policy] +]: + """Yield a Session of a database storing three policies, the model and them.""" + with sqlite_v2_sessions() as sessions, sessions(expire_on_commit=True) as session: + yield (session, *_store_policies(session)) + + +def _store_policies(session: Session) -> tuple[TaxBenefitModel, Policy, Policy, Policy]: + """Store a model's two US policies and a UK policy; return the model and them.""" model = TaxBenefitModel(name="policyengine-us") version = TaxBenefitModelVersion( model=model, @@ -98,12 +111,11 @@ def _stored_policies(): ] ) session.commit() - return engine, session, model, first, second, other_country + return model, first, second, other_country def test_detail_joins_parameter_names_and_orders_complete_values() -> None: - engine, session, _model, first, _second, _other = _stored_policies() - try: + with _stored_policies() as (session, _model, first, _second, _other): result = read_complete_policy(session, country_id="us", policy_id=first.id) assert result.id == first.id @@ -114,24 +126,18 @@ def test_detail_joins_parameter_names_and_orders_complete_values() -> None: "gov.zeta", ] assert [value.value for value in result.parameter_values] == [0, 1, 2] - finally: - session.close() - engine.dispose() def test_detail_uses_country_as_part_of_resource_identity() -> None: - engine, session, _model, first, _second, _other = _stored_policies() - try: - with pytest.raises(PolicyNotFoundError): - read_complete_policy(session, country_id="uk", policy_id=first.id) - finally: - session.close() - engine.dispose() + with ( + _stored_policies() as (session, _model, first, _second, _other), + pytest.raises(PolicyNotFoundError), + ): + read_complete_policy(session, country_id="uk", policy_id=first.id) def test_empty_policy_has_an_empty_nested_collection() -> None: - engine, session, _model, _first, second, _other = _stored_policies() - try: + with _stored_policies() as (session, _model, _first, second, _other): assert ( read_complete_policy( session, @@ -140,14 +146,10 @@ def test_empty_policy_has_an_empty_nested_collection() -> None: ).parameter_values == () ) - finally: - session.close() - engine.dispose() def test_collection_filters_orders_paginates_and_returns_complete_items() -> None: - engine, session, model, first, second, _other = _stored_policies() - try: + with _stored_policies() as (session, model, first, second, _other): first_page = read_policy_page( session, country_id="us", @@ -170,14 +172,10 @@ def test_collection_filters_orders_paginates_and_returns_complete_items() -> Non assert [item.id for item in second_page.items] == [second.id] assert second_page.has_more is False assert all(item.country_id == "us" for item in first_page.items) - finally: - session.close() - engine.dispose() def test_model_filter_is_exact() -> None: - engine, session, _model, _first, _second, _other = _stored_policies() - try: + with _stored_policies() as (session, _model, _first, _second, _other): result = read_policy_page( session, country_id="us", @@ -187,6 +185,3 @@ def test_model_filter_is_exact() -> None: ) assert result.items == () assert result.has_more is False - finally: - session.close() - engine.dispose() diff --git a/tests/unit/v2/test_privilege_manifest.py b/tests/unit/v2/test_privilege_manifest.py index a24da1d61..b792f3599 100644 --- a/tests/unit/v2/test_privilege_manifest.py +++ b/tests/unit/v2/test_privilege_manifest.py @@ -14,7 +14,7 @@ from policyengine_api.data.v2.catalog.publication_statistics import ( CATALOG_STATISTICS_TABLES, ) -from policyengine_api.data.v2.models import V2_METADATA +from policyengine_api.data.v2.models import V2_REGISTRY, V2_TABLE_NAMES from policyengine_api.data.v2.privilege_requirements import ( required_privileges, undeclared_requirements, @@ -219,30 +219,36 @@ def _missing(relative_path: str, role: str) -> list[str]: ) declared = declared_privileges(TEST_ENVIRONMENT)[role] return [ - f"{missing.connector}: {missing.privilege} on {missing.table} " + f"{missing.connector}: {missing.privilege} on {missing.table_name} " f"({missing.reason})" for missing in undeclared_requirements(requirements, declared) ] -def test_every_v2_table_has_an_entry_for_every_managed_role() -> None: - metadata_tables = {table.name for table in V2_METADATA.tables.values()} +def _column_keys_by_table() -> dict[str, set[str]]: + """Return the keys of each v2 table's columns, read through its mapper.""" + return { + mapper.class_.__tablename__: {column.key for column in mapper.columns} + for mapper in V2_REGISTRY.mappers + } - assert set(TABLE_ACCESS) == metadata_tables | {"alembic_version"} + +def test_every_v2_table_has_an_entry_for_every_managed_role() -> None: + assert set(TABLE_ACCESS) == V2_TABLE_NAMES | {"alembic_version"} for role, privileges_by_table in declared_privileges(TEST_ENVIRONMENT).items(): assert set(privileges_by_table) == set(TABLE_ACCESS), role def test_v2_schema_has_no_sequences_the_manifest_would_need_to_cover() -> None: sequence_columns = [ - f"{table.name}.{column.name}" - for table in V2_METADATA.tables.values() - for column in table.columns + f"{mapper.class_.__tablename__}.{column.name}" + for mapper in V2_REGISTRY.mappers + for column in mapper.columns if isinstance(column.default, sa.Sequence) or column.identity is not None or ( column.primary_key - and len(table.primary_key.columns) == 1 + and len(mapper.primary_key) == 1 and isinstance(column.type, sa.Integer) and column.autoincrement is not False ) @@ -330,6 +336,7 @@ def test_modal_workers_write_only_run_status_and_results() -> None: def test_column_privileges_name_their_tables_columns_alone() -> None: """A whole-table privilege would override the same privilege's column list.""" + column_keys_by_table = _column_keys_by_table() for role, privileges_by_table in declared_privileges(TEST_ENVIRONMENT).items(): for table, privileges in privileges_by_table.items(): column_privileges = [ @@ -341,7 +348,7 @@ def test_column_privileges_name_their_tables_columns_alone() -> None: assert len(kinds) == len(set(kinds)), (role, table) for privilege in column_privileges: assert privilege.columns, (role, table) - assert privilege.columns <= set(V2_METADATA.tables[table].c.keys()), ( + assert privilege.columns <= column_keys_by_table[table], ( role, table, ) @@ -397,7 +404,7 @@ def test_rule_proof_runtime_privileges_declared() -> None: good = required_privileges(PROOF_FIXTURES / "reads_good.py", table_by_model) assert [ - (missing.table, missing.privilege) + (missing.table_name, missing.privilege) for missing in undeclared_requirements(bad, runtime_before_3977) ] == [("legacy_policy_mappings", TablePrivilege.SELECT)] assert undeclared_requirements(good, runtime_before_3977) == [] diff --git a/tests/unit/v2/test_privilege_reconciliation.py b/tests/unit/v2/test_privilege_reconciliation.py index b7d731682..dd18675b0 100644 --- a/tests/unit/v2/test_privilege_reconciliation.py +++ b/tests/unit/v2/test_privilege_reconciliation.py @@ -575,7 +575,7 @@ def test_rule_proof_deployed_privileges_match() -> None: } -def _engine_never_built(_settings: object) -> object: +def _sessions_never_opened(_settings: object) -> object: msg = "the command must stop before connecting" raise AssertionError(msg) @@ -588,7 +588,7 @@ def test_creating_roles_is_refused_for_a_persistent_database() -> None: "apply", create_roles=True, environ=PERSISTENT_ENVIRONMENT, - engine_builder=_engine_never_built, + session_factories=_sessions_never_opened, ) @@ -600,7 +600,7 @@ def test_a_persistent_database_needs_staging_or_production(environment: str) -> privilege_reconciliation.run( "verify", environ=PERSISTENT_ENVIRONMENT | {"DEPLOYMENT_ENVIRONMENT": environment}, - engine_builder=_engine_never_built, + session_factories=_sessions_never_opened, ) diff --git a/tests/unit/v2/test_privilege_requirements.py b/tests/unit/v2/test_privilege_requirements.py index 76ba0b5eb..ca861ff36 100644 --- a/tests/unit/v2/test_privilege_requirements.py +++ b/tests/unit/v2/test_privilege_requirements.py @@ -33,7 +33,7 @@ def _connector(directory: Path, name: str, source: str) -> Path: def _needed(path: Path) -> set[tuple[str, TablePrivilege]]: return { - (requirement.table, requirement.privilege) + (requirement.table_name, requirement.privilege) for requirement in required_privileges(path, TABLE_BY_MODEL) } @@ -126,7 +126,7 @@ def read_user(session, user_id): assert ( RequiredPrivilege( - table="legacy_policy_mappings", + table_name="legacy_policy_mappings", privilege=TablePrivilege.UPDATE, connector="reads.py", reason="read_mapping locks rows with with_for_update", diff --git a/tests/unit/v2/test_publication_statistics.py b/tests/unit/v2/test_publication_statistics.py index 5f8601ba3..ce8b4fb81 100644 --- a/tests/unit/v2/test_publication_statistics.py +++ b/tests/unit/v2/test_publication_statistics.py @@ -12,8 +12,8 @@ ) -class EngineThatCannotConnect: - """Stands in for an engine whose connection fails before any statement.""" +class SessionsThatCannotConnect: + """Stands in for Session factories whose connection fails before any statement.""" def begin(self) -> None: msg = "postgresql://writer:hunter2@db.example.internal refused the connection" @@ -21,7 +21,7 @@ def begin(self) -> None: def test_a_failure_that_is_not_a_database_error_is_named_by_its_class() -> None: - refresh = analyze_catalog_tables(EngineThatCannotConnect()) + refresh = analyze_catalog_tables(SessionsThatCannotConnect()) assert refresh.analyzed == () assert refresh.failure_type == "builtins.RuntimeError" diff --git a/tests/unit/v2/test_report_run_creation.py b/tests/unit/v2/test_report_run_creation.py index ac0959f9b..9b62e08cf 100644 --- a/tests/unit/v2/test_report_run_creation.py +++ b/tests/unit/v2/test_report_run_creation.py @@ -3,15 +3,14 @@ from __future__ import annotations from contextlib import contextmanager +from typing import TYPE_CHECKING from uuid import UUID, uuid4 import pytest from sqlalchemy.exc import IntegrityError -from sqlalchemy.pool import StaticPool -from sqlmodel import Session, create_engine, select +from sqlmodel import Session, select from policyengine_api.data.v2.models import ( - V2_METADATA, Report, ReportRun, ReportRunStatus, @@ -25,6 +24,12 @@ ReportRunSimulationRuns, create_report_run, ) +from tests.fixtures.database_sessions import sqlite_v2_sessions + +if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlalchemy.orm import sessionmaker # The simulation runs each report run compares. SQLite doesn't enforce foreign # keys, so these tests store no simulation run rows for them. @@ -34,15 +39,9 @@ @pytest.fixture -def engine(): - test_engine = create_engine( - "sqlite://", - connect_args={"check_same_thread": False}, - poolclass=StaticPool, - ) - V2_METADATA.create_all(test_engine) - yield test_engine - test_engine.dispose() +def sessions() -> Iterator[sessionmaker[Session]]: + with sqlite_v2_sessions() as session_factory: + yield session_factory def _create_report(session: Session) -> Report: @@ -60,9 +59,9 @@ def _create_report(session: Session) -> Report: return report -def test_unknown_report_is_rejected_before_any_validation(engine) -> None: +def test_unknown_report_is_rejected_before_any_validation(sessions) -> None: with ( - Session(engine) as session, + sessions(expire_on_commit=True) as session, pytest.raises(ReportNotFoundError, match="does not exist"), ): create_report_run( @@ -79,8 +78,8 @@ def test_unknown_report_is_rejected_before_any_validation(engine) -> None: ) -def test_manual_run_without_a_key_is_rejected_before_version_checks(engine) -> None: - with Session(engine) as session: +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( @@ -105,11 +104,11 @@ def test_manual_run_without_a_key_is_rejected_before_version_checks(engine) -> N [("", "4.5.6"), ("1.2.3", "")], ) def test_empty_package_versions_are_rejected( - engine, + sessions, country_package_version: str, policyengine_version: str, ) -> None: - with Session(engine) as session: + with sessions(expire_on_commit=True) as session: report = _create_report(session) with pytest.raises( @@ -129,8 +128,8 @@ def test_empty_package_versions_are_rejected( ) -def test_run_without_a_key_is_inserted_without_a_savepoint(engine) -> None: - with Session(engine) as session: +def test_run_without_a_key_is_inserted_without_a_savepoint(sessions) -> None: + with sessions(expire_on_commit=True) as session: report = _create_report(session) run = create_report_run( @@ -159,7 +158,7 @@ def test_run_without_a_key_is_inserted_without_a_savepoint(engine) -> None: def test_conflict_without_a_matching_keyed_run_reraises( - engine, + sessions, monkeypatch, ) -> None: conflict = IntegrityError("insert", {}, Exception("unrelated constraint")) @@ -169,7 +168,7 @@ def failing_savepoint(): raise conflict yield - with Session(engine) as session: + with sessions(expire_on_commit=True) as session: report = _create_report(session) monkeypatch.setattr(session, "begin_nested", failing_savepoint) diff --git a/tests/unit/v2/test_report_runs.py b/tests/unit/v2/test_report_runs.py index 44558041b..0073e420d 100644 --- a/tests/unit/v2/test_report_runs.py +++ b/tests/unit/v2/test_report_runs.py @@ -1,19 +1,18 @@ """Report definition, rerun, idempotency, worker, and selector tests.""" import threading +from collections.abc import Iterator from concurrent.futures import ThreadPoolExecutor from datetime import UTC, datetime, timedelta from pathlib import Path from uuid import UUID, uuid4 import pytest -import sqlalchemy as sa from sqlalchemy.exc import IntegrityError -from sqlalchemy.pool import StaticPool -from sqlmodel import Session, create_engine, select +from sqlalchemy.orm import sessionmaker +from sqlmodel import Session, select from policyengine_api.data.v2.models import ( - V2_METADATA, AggregateOutput, AggregateType, Dataset, @@ -39,6 +38,11 @@ select_current_report_run, set_report_type, ) +from tests.fixtures.database_sessions import ( + sqlite_v2_file_sessions, + sqlite_v2_sessions, +) +from tests.unit.v2.v2_schema_reading import model_columns DEPLOYED_COUNTRY_VERSIONS = {"us": "1.2.3"} DEPLOYED_POLICYENGINE_VERSION = "4.5.6" @@ -51,15 +55,9 @@ @pytest.fixture -def engine(): - test_engine = create_engine( - "sqlite://", - connect_args={"check_same_thread": False}, - poolclass=StaticPool, - ) - V2_METADATA.create_all(test_engine) - yield test_engine - test_engine.dispose() +def sessions() -> Iterator[sessionmaker[Session]]: + with sqlite_v2_sessions() as session_factory: + yield session_factory def _create_report(session: Session, *, report_type: str | None = None) -> Report: @@ -123,20 +121,20 @@ def _create_forced_run(session: Session, report: Report) -> ReportRun: def test_untyped_and_typed_report_definitions_store_no_execution_versions( - engine, + sessions, ) -> None: - with Session(engine) as session: + with sessions(expire_on_commit=True) as session: untyped = _create_report(session) typed = _create_report(session, report_type="marginal_tax_rate") assert untyped.type is None assert typed.type == "marginal_tax_rate" - assert "country_package_version" not in Report.__table__.c - assert "policyengine_version" not in Report.__table__.c + assert "country_package_version" not in model_columns(Report) + assert "policyengine_version" not in model_columns(Report) -def test_report_type_can_change_before_first_run_but_not_after(engine) -> None: - with Session(engine) as session: +def test_report_type_can_change_before_first_run_but_not_after(sessions) -> None: + with sessions(expire_on_commit=True) as session: report = _create_report(session) set_report_type( session, @@ -160,9 +158,9 @@ def test_report_type_can_change_before_first_run_but_not_after(engine) -> None: def test_new_manual_keys_create_a_same_version_run_once_the_last_one_failed( - engine, + sessions, ) -> None: - with Session(engine) as session: + with sessions(expire_on_commit=True) as session: report = _create_report(session) first = _create_run(session, report) # A report has one unfailed, unforced run per version set. @@ -179,8 +177,8 @@ 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(engine) -> None: - with Session(engine) as session: +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"): @@ -198,8 +196,8 @@ def test_manual_rerun_requires_an_idempotency_key(engine) -> None: ) -def test_idempotency_key_round_trips_as_a_python_uuid(engine) -> None: - with Session(engine) as session: +def test_idempotency_key_round_trips_as_a_python_uuid(sessions) -> None: + with sessions(expire_on_commit=True) as session: report = _create_report(session) request_key = uuid4() run = _create_run(session, report, key=request_key) @@ -210,8 +208,8 @@ def test_idempotency_key_round_trips_as_a_python_uuid(engine) -> None: assert isinstance(run.idempotency_key, UUID) -def test_transport_retry_returns_the_existing_report_scoped_run(engine) -> None: - with Session(engine) as session: +def test_transport_retry_returns_the_existing_report_scoped_run(sessions) -> None: + with sessions(expire_on_commit=True) as session: report = _create_report(session) request_key = uuid4() first = _create_run(session, report, key=request_key) @@ -221,25 +219,19 @@ def test_transport_retry_returns_the_existing_report_scoped_run(engine) -> None: assert len(session.exec(select(ReportRun)).all()) == 1 -def test_concurrent_idempotent_requests_resolve_to_one_run(tmp_path: Path) -> None: - sqlite_path = tmp_path / "report-rerun-concurrency.db" - test_engine = create_engine( - f"sqlite:///{sqlite_path}", - connect_args={"check_same_thread": False, "timeout": 10}, - ) - - # BEGIN IMMEDIATE gives this explicit SQLite-only test fixture the same - # serialization point that SELECT FOR UPDATE provides in Postgres. - @sa.event.listens_for(test_engine, "connect") - def _set_sqlite_transaction_mode(dbapi_connection, _record) -> None: - dbapi_connection.isolation_level = None +@pytest.fixture +def file_sessions(tmp_path: Path) -> Iterator[sessionmaker[Session]]: + # Each transaction begins with BEGIN IMMEDIATE, which gives this explicit + # SQLite-only test fixture the same serialization point that SELECT FOR + # UPDATE provides in Postgres. + with sqlite_v2_file_sessions(tmp_path / "report-rerun-concurrency.db") as sessions: + yield sessions - @sa.event.listens_for(test_engine, "begin") - def _begin_immediate(connection) -> None: - connection.exec_driver_sql("BEGIN IMMEDIATE") - V2_METADATA.create_all(test_engine) - with Session(test_engine) as session: +def test_concurrent_idempotent_requests_resolve_to_one_run( + file_sessions: sessionmaker[Session], +) -> None: + with file_sessions(expire_on_commit=True) as session: report_id = _create_report(session).id session.commit() @@ -247,7 +239,7 @@ def _begin_immediate(connection) -> None: request_key = uuid4() def request_rerun() -> UUID: - with Session(test_engine) as session: + with file_sessions(expire_on_commit=True) as session: barrier.wait() run = create_report_run( session, @@ -269,16 +261,15 @@ def request_rerun() -> UUID: with ThreadPoolExecutor(max_workers=2) as executor: run_ids = set(executor.map(lambda _: request_rerun(), range(2))) - with Session(test_engine) as session: + with file_sessions(expire_on_commit=True) as session: assert len(run_ids) == 1 assert len(session.exec(select(ReportRun)).all()) == 1 - test_engine.dispose() def test_worker_retry_resumes_the_same_run_and_terminal_runs_stay_terminal( - engine, + sessions, ) -> None: - with Session(engine) as session: + with sessions(expire_on_commit=True) as session: report = _create_report(session) run = _create_run(session, report) started = begin_report_run(session, report_run_id=run.id, started_at=NOW) @@ -294,8 +285,8 @@ def test_worker_retry_resumes_the_same_run_and_terminal_runs_stay_terminal( begin_report_run(session, report_run_id=run.id) -def test_outputs_from_repeated_runs_are_preserved(engine) -> None: - with Session(engine) as session: +def test_outputs_from_repeated_runs_are_preserved(sessions) -> None: + with sessions(expire_on_commit=True) as session: report = _create_report(session) version = TaxBenefitModelVersion( model_id=report.tax_benefit_model_id, @@ -349,8 +340,8 @@ def test_outputs_from_repeated_runs_are_preserved(engine) -> None: assert outputs[0].report_run_id != outputs[1].report_run_id -def test_selector_uses_versions_success_completion_time_and_stable_id(engine) -> None: - with Session(engine) as session: +def test_selector_uses_versions_success_completion_time_and_stable_id(sessions) -> None: + with sessions(expire_on_commit=True) as session: report = _create_report(session) # Runs 1 and 4 share run 2's versions, so each is a forced re-run. candidates = [ @@ -406,8 +397,8 @@ def test_selector_uses_versions_success_completion_time_and_stable_id(engine) -> assert current.id == UUID(int=2) -def test_pending_and_failed_reruns_do_not_displace_success(engine) -> None: - with Session(engine) as session: +def test_pending_and_failed_reruns_do_not_displace_success(sessions) -> None: + with sessions(expire_on_commit=True) as session: report = _create_report(session) successful = _create_run(session, report) complete_report_run(session, report_run_id=successful.id, completed_at=NOW) @@ -432,8 +423,8 @@ def test_pending_and_failed_reruns_do_not_displace_success(engine) -> None: assert current.id == successful.id -def test_new_successful_rerun_becomes_current_without_cache_state(engine) -> None: - with Session(engine) as session: +def test_new_successful_rerun_becomes_current_without_cache_state(sessions) -> None: + with sessions(expire_on_commit=True) as session: report = _create_report(session) first = _create_run(session, report) complete_report_run(session, report_run_id=first.id, completed_at=NOW) @@ -458,8 +449,8 @@ def test_new_successful_rerun_becomes_current_without_cache_state(engine) -> Non assert len(session.exec(select(ReportRun)).all()) == 2 -def test_selector_returns_none_without_a_matching_success(engine) -> None: - with Session(engine) as session: +def test_selector_returns_none_without_a_matching_success(sessions) -> None: + with sessions(expire_on_commit=True) as session: report = _create_report(session) mismatched = _create_run( session, diff --git a/tests/unit/v2/test_shared_report_models.py b/tests/unit/v2/test_shared_report_models.py index 3312b02ad..367c777cd 100644 --- a/tests/unit/v2/test_shared_report_models.py +++ b/tests/unit/v2/test_shared_report_models.py @@ -5,9 +5,13 @@ The database enforces both: one row per key, and at most one unfailed, unforced run per definition and version set. Each user's request is recorded in ``user_report_run_associations``. + +Columns are read from the models' mappers, constraints from SQLite's copy of +the schema, and partial indexes from the models' declarations +(tests/unit/v2/v2_schema_reading.py). """ -from collections.abc import Iterator +from collections.abc import Iterator, Mapping from datetime import UTC, datetime from uuid import UUID, uuid4 @@ -17,7 +21,6 @@ from sqlalchemy.orm import Session from policyengine_api.data.v2.models import ( - V2_METADATA, BudgetWindowRun, ReportRun, ReportRunStatus, @@ -28,32 +31,27 @@ from policyengine_api.services.v2.stored_reports import ( transformations as stored_report_transformations, ) +from tests.fixtures.database_sessions import sqlite_v2_sessions +from tests.unit.v2.v2_schema_reading import ( + declared_index, + model_columns, + stored_v2_table, + v2_model, +) UNFAILED_UNFORCED = "status <> 'failed' AND NOT forced" -def _checks(table_name: str) -> dict[str, str]: - return { - constraint.name: str(constraint.sqltext) - for constraint in V2_METADATA.tables[table_name].constraints - if isinstance(constraint, sa.CheckConstraint) - } +def _checks(table_name: str) -> Mapping[str | None, str]: + return stored_v2_table(table_name).checks -def _unique_constraints(table_name: str) -> dict[str, tuple[str, ...]]: - return { - str(constraint.name): tuple(column.name for column in constraint.columns) - for constraint in V2_METADATA.tables[table_name].constraints - if isinstance(constraint, sa.UniqueConstraint) - } +def _unique_constraints(table_name: str) -> Mapping[str | None, tuple[str, ...]]: + return stored_v2_table(table_name).unique_constraints def _index(table_name: str, index_name: str) -> sa.Index: - return next( - index - for index in V2_METADATA.tables[table_name].indexes - if index.name == index_name - ) + return declared_index(v2_model(table_name), index_name) @pytest.mark.parametrize("table_name", ["simulations", "reports"]) @@ -61,12 +59,12 @@ def test_simulations_and_reports_are_found_by_an_optional_unique_key( table_name: str, ) -> None: """Existing rows stay unkeyed; a keyed row is unique on its key and version.""" - table = V2_METADATA.tables[table_name] + columns = model_columns(table_name) - assert table.c.key_version.nullable - assert isinstance(table.c.key_version.type, sa.Integer) - assert table.c.definition_key.nullable - assert table.c.definition_key.type.length == 64 + assert columns.key_version.nullable + assert isinstance(columns.key_version.type, sa.Integer) + assert columns.definition_key.nullable + assert columns.definition_key.type.length == 64 assert _unique_constraints(table_name)[ f"uq_{table_name}_key_version_definition_key" ] == ("key_version", "definition_key") @@ -85,11 +83,11 @@ def test_a_keyed_simulation_names_its_key_version() -> None: def test_a_keyed_report_also_has_the_key_shared_across_datasets() -> None: """A national report and its local-area report share dataset_independent_key.""" - reports = V2_METADATA.tables["reports"] + reports = model_columns("reports") checks = _checks("reports") - assert reports.c.dataset_independent_key.nullable - assert reports.c.dataset_independent_key.type.length == 64 + assert reports.dataset_independent_key.nullable + assert reports.dataset_independent_key.type.length == 64 assert checks["ck_reports_dataset_independent_key"] == ( "length(dataset_independent_key) = 64 " "AND ltrim(dataset_independent_key, '0123456789abcdef') = ''" @@ -110,7 +108,7 @@ def test_a_keyed_report_also_has_the_key_shared_across_datasets() -> None: @pytest.mark.parametrize("table_name", ["simulation_runs", "report_runs"]) def test_runs_record_whether_a_re_run_forced_them(table_name: str) -> None: """Every existing run, and every run the service writes without it, is unforced.""" - forced = V2_METADATA.tables[table_name].c.forced + forced = model_columns(table_name).forced assert isinstance(forced.type, sa.Boolean) assert not forced.nullable @@ -158,13 +156,13 @@ def test_a_report_has_one_unfailed_unrecalculated_window_run_per_version_set() - The version stays optional, since window runs written before it have none, and an unversioned run is never joined. """ - windows = V2_METADATA.tables["budget_window_runs"] + windows = model_columns("budget_window_runs") index = _index( "budget_window_runs", "uq_budget_window_runs_unfailed_unforced_versions" ) - assert windows.c.policyengine_version.nullable - assert windows.c.policyengine_version.type.length == 128 + assert windows.policyengine_version.nullable + assert windows.policyengine_version.type.length == 128 assert index.unique assert tuple(column.name for column in index.columns) == ( "report_id", @@ -233,16 +231,17 @@ def test_per_user_columns_of_shared_rows_need_no_value( They go in a later revision; until then they are nullable, with no default, so a row written without one holds none. """ - column = V2_METADATA.tables[table_name].c[column_name] + column = model_columns(table_name)[column_name] assert column.nullable assert column.server_default is None def test_user_report_run_associations_record_each_users_request_for_a_run() -> None: - records = V2_METADATA.tables["user_report_run_associations"] + records = model_columns("user_report_run_associations") + stored_records = stored_v2_table("user_report_run_associations") - assert {column.name for column in records.columns} == { + assert set(records.keys()) == { "id", "created_at", "user_id", @@ -251,16 +250,12 @@ def test_user_report_run_associations_record_each_users_request_for_a_run() -> N "trigger", } for column_name in ("user_id", "report_run_id", "requested_at", "trigger"): - assert not records.c[column_name].nullable, column_name - assert records.c.requested_at.type.timezone - assert records.c.requested_at.server_default is None - assert records.c.trigger.type.name == "v2_report_run_trigger" - foreign_keys = { - key.parent.name: (key.column.table.name, key.ondelete) - for key in records.foreign_keys - } + assert not records[column_name].nullable, column_name + assert records.requested_at.type.timezone + assert records.requested_at.server_default is None + assert records.trigger.type.name == "v2_report_run_trigger" # A user's records go with the user; a run a user asked for stays. - assert foreign_keys == { + assert stored_records.references_by_column == { "user_id": ("users", "CASCADE"), "report_run_id": ("report_runs", "RESTRICT"), } @@ -270,9 +265,7 @@ def test_user_report_run_associations_record_each_users_request_for_a_run() -> N "report_run_id", ) } - assert { - tuple(column.name for column in index.columns) for index in records.indexes - } == {("report_run_id",)} + assert set(stored_records.index_columns.values()) == {("report_run_id",)} # A user creates a report or runs it again; a system re-run asks for no user. assert _checks("user_report_run_associations") == { "ck_user_report_run_associations_trigger": "trigger IN ('initial', 'manual')" @@ -281,11 +274,8 @@ def test_user_report_run_associations_record_each_users_request_for_a_run() -> N @pytest.fixture def sqlite_session() -> Iterator[Session]: - engine = sa.create_engine("sqlite://") - V2_METADATA.create_all(engine) - with Session(engine) as session: + with sqlite_v2_sessions() as sessions, sessions(expire_on_commit=True) as session: yield session - engine.dispose() VALID_KEY = "4bb1299756cb0a89" * 4 diff --git a/tests/unit/v2/test_simulation_run_models.py b/tests/unit/v2/test_simulation_run_models.py index d3282dcb6..94222c6cf 100644 --- a/tests/unit/v2/test_simulation_run_models.py +++ b/tests/unit/v2/test_simulation_run_models.py @@ -4,20 +4,30 @@ records the catalog and PolicyEngine.py versions it used. A report run names its baseline and reform simulation runs, results are keyed by run, and a household job calculates one household for one year under one policy. + +Columns are read from the models' mappers, and keys, constraints and indexes +from SQLite's copy of the schema (tests/unit/v2/v2_schema_reading.py). """ import sqlalchemy as sa from sqlalchemy.dialects import postgresql -from sqlalchemy.schema import CreateTable from policyengine_api.data.v2.models import ( - V2_METADATA, BudgetWindowRun, LaborSupplyDecileResponse, LaborSupplyResponse, ReportRun, SimulationRun, ) +from tests.fixtures.database_sessions import v2_schema_statements +from tests.unit.v2.v2_schema_reading import ( + StoredForeignKeyColumn, + model_columns, + stored_v2_schema, + stored_v2_table, + v2_mappers, + v2_model, +) RUN_STATUSES = ["pending", "running", "succeeded", "failed"] # The baseline's and reform's cliff gap and share, stored together or not at all. @@ -115,36 +125,33 @@ } -def _foreign_key(table: sa.Table, column_name: str) -> sa.ForeignKey: - (foreign_key,) = table.c[column_name].foreign_keys - return foreign_key +def _foreign_key(table_name: str, column_name: str) -> StoredForeignKeyColumn: + return stored_v2_table(table_name).foreign_key(column_name) -def _check_names(table: sa.Table) -> set[str]: - return { - constraint.name - for constraint in table.constraints - if isinstance(constraint, sa.CheckConstraint) - } +def _check_names(table_name: str) -> set[str | None]: + return set(stored_v2_table(table_name).checks) -def _unique_column_sets(table: sa.Table) -> set[tuple[str, ...]]: - return { - tuple(column.name for column in constraint.columns) - for constraint in table.constraints - if isinstance(constraint, sa.UniqueConstraint) - } +def _unique_column_sets(table_name: str) -> set[tuple[str, ...]]: + return stored_v2_table(table_name).unique_column_sets -def _indexes(table: sa.Table) -> dict[str, tuple[str, ...]]: - return { - index.name: tuple(column.name for column in index.columns) - for index in table.indexes - } +def _indexes(table_name: str) -> dict[str | None, tuple[str | None, ...]]: + return stored_v2_table(table_name).index_columns + + +def _create_table_statement(table_name: str) -> str: + """Return the CREATE TABLE statement the v2 schema sends PostgreSQL.""" + return next( + statement + for statement in v2_schema_statements("postgresql") + if statement.lstrip().startswith(f"CREATE TABLE {table_name} (") + ) def test_simulations_keep_only_what_to_calculate() -> None: - simulations = V2_METADATA.tables["simulations"] + simulations = model_columns("simulations") assert { "status", @@ -153,7 +160,7 @@ def test_simulations_keep_only_what_to_calculate() -> None: "completed_at", "household_result", "output_dataset_id", - }.isdisjoint(simulations.c.keys()) + }.isdisjoint(simulations.keys()) assert { "simulation_type", "dataset_id", @@ -166,12 +173,12 @@ def test_simulations_keep_only_what_to_calculate() -> None: "filter_value", "filter_strategy", "year", - } <= set(simulations.c.keys()) - assert "ix_simulations_status_created_at" not in _indexes(simulations) + } <= set(simulations.keys()) + assert "ix_simulations_status_created_at" not in _indexes("simulations") def test_each_simulation_run_records_its_versions_status_and_output() -> None: - simulation_runs = V2_METADATA.tables["simulation_runs"] + simulation_runs = model_columns("simulation_runs") required = { "simulation_id", @@ -195,44 +202,41 @@ def test_each_simulation_run_records_its_versions_status_and_output() -> None: "output_uri", "output_sha256", } - assert set(simulation_runs.c.keys()) == {"id"} | required | optional - assert all(not simulation_runs.c[name].nullable for name in required) - assert all(simulation_runs.c[name].nullable for name in optional) - assert simulation_runs.c.status.type.name == "v2_simulation_status" - assert list(simulation_runs.c.status.type.enums) == RUN_STATUSES - assert simulation_runs.c.modal_call_id.type.length == 255 - assert simulation_runs.c.output_uri.type.length == 2048 - assert simulation_runs.c.output_sha256.type.length == 64 - assert simulation_runs.c.country_package_version.type.length == 128 - assert simulation_runs.c.policyengine_version.type.length == 128 - - simulation_key = _foreign_key(simulation_runs, "simulation_id") - assert simulation_key.target_fullname == "simulations.id" + assert set(simulation_runs.keys()) == {"id"} | required | optional + assert all(not simulation_runs[name].nullable for name in required) + assert all(simulation_runs[name].nullable for name in optional) + assert simulation_runs.status.type.name == "v2_simulation_status" + assert list(simulation_runs.status.type.enums) == RUN_STATUSES + assert simulation_runs.modal_call_id.type.length == 255 + assert simulation_runs.output_uri.type.length == 2048 + assert simulation_runs.output_sha256.type.length == 64 + assert simulation_runs.country_package_version.type.length == 128 + assert simulation_runs.policyengine_version.type.length == 128 + + simulation_key = _foreign_key("simulation_runs", "simulation_id") + assert simulation_key.target == "simulations.id" assert simulation_key.ondelete == "CASCADE" - assert {key.target_fullname for key in simulation_runs.foreign_keys} == { + stored_keys = stored_v2_table("simulation_runs").foreign_key_columns + assert {key.target for key in stored_keys} == { "simulations.id", "tax_benefit_model_versions.id", "datasets.id", "regions.id", } - assert "ck_simulation_runs_year" in _check_names(simulation_runs) + assert "ck_simulation_runs_year" in _check_names("simulation_runs") assert SimulationRun.__module__.endswith(".simulations") def test_run_tables_require_a_completion_time_and_index_running_runs() -> None: - simulation_runs = V2_METADATA.tables["simulation_runs"] - report_runs = V2_METADATA.tables["report_runs"] - household_jobs = V2_METADATA.tables["household_jobs"] - assert { "ck_simulation_runs_terminal_completion", "ck_simulation_runs_output_pair", "ck_simulation_runs_output_sha256_length", - } <= _check_names(simulation_runs) - assert "ck_household_jobs_terminal_completion" in _check_names(household_jobs) + } <= _check_names("simulation_runs") + assert "ck_household_jobs_terminal_completion" in _check_names("household_jobs") # A simulation has a run per year, so its newest successful run is found # per year. - assert _indexes(simulation_runs) == { + assert _indexes("simulation_runs") == { "ix_simulation_runs_current_output": ( "simulation_id", "year", @@ -256,75 +260,75 @@ def test_run_tables_require_a_completion_time_and_index_running_runs() -> None: "policyengine_version", ), } - assert _indexes(report_runs)["ix_report_runs_status_started_at"] == ( + assert _indexes("report_runs")["ix_report_runs_status_started_at"] == ( "status", "started_at", ) def test_report_runs_record_their_modal_call() -> None: - report_runs = V2_METADATA.tables["report_runs"] + report_runs = model_columns("report_runs") - assert report_runs.c.modal_call_id.nullable - assert report_runs.c.modal_call_id.type.length == 255 - assert "report_run_comparisons" not in V2_METADATA.tables + assert report_runs.modal_call_id.nullable + assert report_runs.modal_call_id.type.length == 255 + assert "report_run_comparisons" not in stored_v2_schema() def test_report_runs_record_cliff_impact_spm_receipt_and_data_version() -> None: """The comparison parts with no result table are typed, except the receipt.""" - report_runs = V2_METADATA.tables["report_runs"] + report_runs = model_columns("report_runs") for column_name in CLIFF_IMPACT_COLUMNS: - assert report_runs.c[column_name].nullable, column_name - assert isinstance(report_runs.c[column_name].type, sa.Float), column_name - assert "ck_report_runs_cliff_impact_complete" in _check_names(report_runs) - assert report_runs.c.spm_provenance.nullable - spm_type = report_runs.c.spm_provenance.type + assert report_runs[column_name].nullable, column_name + assert isinstance(report_runs[column_name].type, sa.Float), column_name + assert "ck_report_runs_cliff_impact_complete" in _check_names("report_runs") + assert report_runs.spm_provenance.nullable + spm_type = report_runs.spm_provenance.type assert isinstance(spm_type.dialect_impl(postgresql.dialect()), postgresql.JSONB) - assert report_runs.c.data_version.nullable - assert report_runs.c.data_version.type.length == 128 - assert {"labor_supply_result", "cliff_impact_result"}.isdisjoint( - report_runs.c.keys() - ) + assert report_runs.data_version.nullable + assert report_runs.data_version.type.length == 128 + assert {"labor_supply_result", "cliff_impact_result"}.isdisjoint(report_runs.keys()) def test_labor_supply_responses_have_one_typed_row_per_report_run() -> None: - responses = V2_METADATA.tables["labor_supply_responses"] + responses = model_columns("labor_supply_responses") - assert set(responses.c.keys()) == { + assert set(responses.keys()) == { "id", "created_at", "report_run_id", *LABOR_SUPPLY_RESPONSE_COLUMNS, } for column_name in LABOR_SUPPLY_RESPONSE_COLUMNS: - assert not responses.c[column_name].nullable, column_name - assert isinstance(responses.c[column_name].type, sa.Float), column_name - report_run_key = _foreign_key(responses, "report_run_id") - assert report_run_key.target_fullname == "report_runs.id" + assert not responses[column_name].nullable, column_name + assert isinstance(responses[column_name].type, sa.Float), column_name + report_run_key = _foreign_key("labor_supply_responses", "report_run_id") + assert report_run_key.target == "report_runs.id" assert report_run_key.ondelete == "CASCADE" - assert _unique_column_sets(responses) == {("report_run_id",)} + assert _unique_column_sets("labor_supply_responses") == {("report_run_id",)} def test_labor_supply_decile_responses_have_one_row_per_decile() -> None: - deciles = V2_METADATA.tables["labor_supply_decile_responses"] + deciles = model_columns("labor_supply_decile_responses") - assert set(deciles.c.keys()) == { + assert set(deciles.keys()) == { "id", "created_at", "report_run_id", "decile", *LABOR_SUPPLY_DECILE_COLUMNS, } - assert not deciles.c.decile.nullable + assert not deciles.decile.nullable # .py reports a relative response only for deciles above zero. for column_name in LABOR_SUPPLY_DECILE_COLUMNS: - assert deciles.c[column_name].nullable, column_name - assert isinstance(deciles.c[column_name].type, sa.Float), column_name - report_run_key = _foreign_key(deciles, "report_run_id") - assert report_run_key.target_fullname == "report_runs.id" + assert deciles[column_name].nullable, column_name + assert isinstance(deciles[column_name].type, sa.Float), column_name + report_run_key = _foreign_key("labor_supply_decile_responses", "report_run_id") + assert report_run_key.target == "report_runs.id" assert report_run_key.ondelete == "CASCADE" - assert _unique_column_sets(deciles) == {("report_run_id", "decile")} + assert _unique_column_sets("labor_supply_decile_responses") == { + ("report_run_id", "decile") + } def test_report_run_relationships_name_labor_supply_rows() -> None: @@ -342,22 +346,22 @@ def test_report_run_relationships_name_labor_supply_rows() -> None: def test_uk_area_impacts_record_disclosure_control() -> None: for table_name in ("constituency_impacts", "local_authority_impacts"): - table = V2_METADATA.tables[table_name] - assert table.c.disclosure_tier.nullable - assert table.c.disclosure_tier.type.length == 16 + columns = model_columns(table_name) + assert columns.disclosure_tier.nullable + assert columns.disclosure_tier.type.length == 16 for change in ("average", "relative"): for bound in ("lower", "upper"): - column = table.c[f"{change}_household_income_change_{bound}"] + column = columns[f"{change}_household_income_change_{bound}"] assert column.nullable assert isinstance(column.type, sa.Float) - assert f"ck_{table_name}_disclosure_tier" in _check_names(table) + assert f"ck_{table_name}_disclosure_tier" in _check_names(table_name) def test_withheld_area_codes_list_each_area_a_report_run_held_back() -> None: """One row per UK area that disclosure control withheld from a report run.""" - withheld = V2_METADATA.tables["withheld_area_codes"] + withheld = model_columns("withheld_area_codes") - assert set(withheld.c.keys()) == { + assert set(withheld.keys()) == { "id", "created_at", "report_run_id", @@ -366,18 +370,14 @@ def test_withheld_area_codes_list_each_area_a_report_run_held_back() -> None: "area_type", "code", } - area_type = withheld.c.area_type + area_type = withheld.area_type assert not area_type.nullable assert isinstance(area_type.type, sa.Enum) assert area_type.type.name == "v2_uk_area_type" assert area_type.type.enums == ["constituency", "local_authority"] - assert not withheld.c.code.nullable - assert withheld.c.code.type.length == 64 - assert { - constraint.name: tuple(column.name for column in constraint.columns) - for constraint in withheld.constraints - if isinstance(constraint, sa.UniqueConstraint) - } == { + assert not withheld.code.nullable + assert withheld.code.type.length == 64 + assert stored_v2_table("withheld_area_codes").unique_constraints == { "uq_withheld_area_codes_run_type_code": ( "report_run_id", "area_type", @@ -385,31 +385,29 @@ def test_withheld_area_codes_list_each_area_a_report_run_held_back() -> None: ) } relationship = sa.inspect(ReportRun).relationships["withheld_area_codes"] - assert relationship.mapper.local_table is withheld + assert relationship.mapper.class_ is v2_model("withheld_area_codes") assert "delete" in relationship.cascade def test_congressional_district_impacts_record_winner_and_loser_shares() -> None: - districts = V2_METADATA.tables["congressional_district_impacts"] + districts = model_columns("congressional_district_impacts") for column_name in ( "winner_percentage", "loser_percentage", "no_change_percentage", ): - assert not districts.c[column_name].nullable - assert isinstance(districts.c[column_name].type, sa.Float) + assert not districts[column_name].nullable + assert isinstance(districts[column_name].type, sa.Float) def test_detailed_budget_rows_need_neither_an_entity_nor_a_tax_flag() -> None: """The economy output names each program's totals, not its entity or kind.""" - program_statistics = V2_METADATA.tables["program_statistics"] + program_statistics = model_columns("program_statistics") - assert program_statistics.c.entity.nullable - assert program_statistics.c.is_tax.nullable - statement = str( - CreateTable(program_statistics).compile(dialect=postgresql.dialect()) - ) + assert program_statistics.entity.nullable + assert program_statistics.is_tax.nullable + statement = _create_table_statement("program_statistics") assert ( "CONSTRAINT uq_program_statistics_run_program_entity UNIQUE NULLS NOT " "DISTINCT (report_run_id, program_name, entity)" @@ -418,35 +416,35 @@ def test_detailed_budget_rows_need_neither_an_entity_nor_a_tax_flag() -> None: def test_report_runs_name_their_baseline_and_reform_simulation_runs() -> None: """A report run compares one pair; a household report may have no reform.""" - report_runs = V2_METADATA.tables["report_runs"] + report_runs = model_columns("report_runs") - assert not report_runs.c.baseline_simulation_run_id.nullable - assert report_runs.c.reform_simulation_run_id.nullable + assert not report_runs.baseline_simulation_run_id.nullable + assert report_runs.reform_simulation_run_id.nullable for column_name in ("baseline_simulation_run_id", "reform_simulation_run_id"): - run_key = _foreign_key(report_runs, column_name) - assert run_key.target_fullname == "simulation_runs.id" + run_key = _foreign_key("report_runs", column_name) + assert run_key.target == "simulation_runs.id" assert run_key.ondelete == "RESTRICT" - assert (column_name,) in _indexes(report_runs).values() - assert "report_run_simulation_runs" not in V2_METADATA.tables + assert (column_name,) in _indexes("report_runs").values() + assert "report_run_simulation_runs" not in stored_v2_schema() enum_type_names = { column.type.name - for table in V2_METADATA.tables.values() - for column in table.columns + for mapper in v2_mappers() + for column in mapper.columns if isinstance(column.type, sa.Enum) } assert "v2_simulation_role" not in enum_type_names def test_budget_window_reports_name_how_many_years_they_compare() -> None: - reports = V2_METADATA.tables["reports"] + reports = model_columns("reports") - assert reports.c.budget_window_size.nullable - assert isinstance(reports.c.budget_window_size.type, sa.Integer) - assert "ck_reports_budget_window_size" in _check_names(reports) + assert reports.budget_window_size.nullable + assert isinstance(reports.budget_window_size.type, sa.Integer) + assert "ck_reports_budget_window_size" in _check_names("reports") def test_budget_window_runs_record_each_calculation_of_a_window() -> None: - windows = V2_METADATA.tables["budget_window_runs"] + windows = model_columns("budget_window_runs") required = { "report_id", @@ -463,21 +461,25 @@ def test_budget_window_runs_record_each_calculation_of_a_window() -> None: "policyengine_version", "trigger", } - assert set(windows.c.keys()) == {"id"} | required | optional - assert all(not windows.c[name].nullable for name in required) - assert all(windows.c[name].nullable for name in optional) + 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. - assert windows.c.status.type.name == "v2_report_run_status" - assert windows.c.trigger.type.name == "v2_report_run_trigger" - report_key = _foreign_key(windows, "report_id") - assert report_key.target_fullname == "reports.id" + 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" - version_key = _foreign_key(windows, "tax_benefit_model_version_id") - assert version_key.target_fullname == "tax_benefit_model_versions.id" + version_key = _foreign_key("budget_window_runs", "tax_benefit_model_version_id") + assert version_key.target == "tax_benefit_model_versions.id" assert version_key.ondelete == "RESTRICT" - assert ("id", "report_id") in _unique_column_sets(windows) - assert "ck_budget_window_runs_terminal_completion" in _check_names(windows) - assert _indexes(windows)["ix_budget_window_runs_report_id_created_at"] == ( + assert ("id", "report_id") in _unique_column_sets("budget_window_runs") + assert "ck_budget_window_runs_terminal_completion" in _check_names( + "budget_window_runs" + ) + assert _indexes("budget_window_runs")[ + "ix_budget_window_runs_report_id_created_at" + ] == ( "report_id", "created_at", ) @@ -485,34 +487,27 @@ def test_budget_window_runs_record_each_calculation_of_a_window() -> None: def test_report_runs_hold_one_year_of_a_budget_window_run() -> None: - report_runs = V2_METADATA.tables["report_runs"] - - assert report_runs.c.budget_window_run_id.nullable - assert report_runs.c.year.nullable - (window_key,) = ( - constraint - for constraint in report_runs.foreign_key_constraints - if constraint.referred_table.name == "budget_window_runs" - ) + report_runs = model_columns("report_runs") + + assert report_runs.budget_window_run_id.nullable + assert report_runs.year.nullable + (window_key,) = stored_v2_table("report_runs").foreign_keys_to("budget_window_runs") # A year's report run belongs to a window run of the same report, which # owns it as the report owns its runs. - assert [column.name for column in window_key.columns] == [ - "budget_window_run_id", - "report_id", - ] - assert [element.target_fullname for element in window_key.elements] == [ + assert window_key.columns == ("budget_window_run_id", "report_id") + assert window_key.targets == ( "budget_window_runs.id", "budget_window_runs.report_id", - ] + ) assert window_key.ondelete == "CASCADE" - assert ("budget_window_run_id", "year") in _unique_column_sets(report_runs) + assert ("budget_window_run_id", "year") in _unique_column_sets("report_runs") assert {"ck_report_runs_year", "ck_report_runs_budget_window_year"} <= ( - _check_names(report_runs) + _check_names("report_runs") ) def test_household_jobs_calculate_one_household_year_and_policy() -> None: - household_jobs = V2_METADATA.tables["household_jobs"] + household_jobs = model_columns("household_jobs") for column_name in ( "household_id", @@ -523,33 +518,31 @@ def test_household_jobs_calculate_one_household_year_and_policy() -> None: "request_data", "updated_at", ): - assert not household_jobs.c[column_name].nullable, column_name + assert not household_jobs[column_name].nullable, column_name for column_name in ("policy_id", "dynamic_id", "modal_call_id"): - assert household_jobs.c[column_name].nullable, column_name - assert household_jobs.c.modal_call_id.type.length == 255 - assert "ck_household_jobs_year" in _check_names(household_jobs) - assert "ix_household_jobs_household_id" in _indexes(household_jobs) - assert _foreign_key(household_jobs, "household_id").target_fullname == ( - "households.id" + assert household_jobs[column_name].nullable, column_name + assert household_jobs.modal_call_id.type.length == 255 + assert "ck_household_jobs_year" in _check_names("household_jobs") + assert "ix_household_jobs_household_id" in _indexes("household_jobs") + assert _foreign_key("household_jobs", "household_id").target == "households.id" + assert _foreign_key("household_jobs", "tax_benefit_model_version_id").target == ( + "tax_benefit_model_versions.id" ) - assert _foreign_key( - household_jobs, "tax_benefit_model_version_id" - ).target_fullname == ("tax_benefit_model_versions.id") def test_per_simulation_results_belong_to_one_simulation_run() -> None: for table_name in PER_SIMULATION_RESULT_TABLES: - table = V2_METADATA.tables[table_name] - assert {"report_run_id", "simulation_id"}.isdisjoint(table.c.keys()) - assert not table.c.simulation_run_id.nullable - simulation_run_key = _foreign_key(table, "simulation_run_id") - assert simulation_run_key.target_fullname == "simulation_runs.id" + columns = model_columns(table_name) + assert {"report_run_id", "simulation_id"}.isdisjoint(columns.keys()) + assert not columns.simulation_run_id.nullable + simulation_run_key = _foreign_key(table_name, "simulation_run_id") + assert simulation_run_key.target == "simulation_runs.id" assert simulation_run_key.ondelete == "CASCADE" - assert _unique_column_sets(V2_METADATA.tables["inequality"]) == { + assert _unique_column_sets("inequality") == { ("simulation_run_id", "income_variable", "entity") } - assert _unique_column_sets(V2_METADATA.tables["poverty"]) == { + assert _unique_column_sets("poverty") == { ( "simulation_run_id", "poverty_type", @@ -561,9 +554,7 @@ def test_per_simulation_results_belong_to_one_simulation_run() -> None: def test_poverty_rows_without_a_filter_variable_are_unique_per_run() -> None: - statement = str( - CreateTable(V2_METADATA.tables["poverty"]).compile(dialect=postgresql.dialect()) - ) + statement = _create_table_statement("poverty") assert ( "CONSTRAINT uq_poverty_simulation_run_measure UNIQUE NULLS NOT DISTINCT " @@ -573,21 +564,21 @@ def test_poverty_rows_without_a_filter_variable_are_unique_per_run() -> None: def test_comparison_results_name_the_two_simulation_runs_they_compare() -> None: for table_name in COMPARISON_RESULT_TABLES: - table = V2_METADATA.tables[table_name] + columns = model_columns(table_name) assert {"baseline_simulation_id", "reform_simulation_id"}.isdisjoint( - table.c.keys() + columns.keys() ), table_name - report_run_key = _foreign_key(table, "report_run_id") - assert report_run_key.target_fullname == "report_runs.id" + report_run_key = _foreign_key(table_name, "report_run_id") + assert report_run_key.target == "report_runs.id" assert report_run_key.ondelete == "CASCADE" for column_name in ("baseline_simulation_run_id", "reform_simulation_run_id"): - assert not table.c[column_name].nullable - run_key = _foreign_key(table, column_name) - assert run_key.target_fullname == "simulation_runs.id", table_name + assert not columns[column_name].nullable + run_key = _foreign_key(table_name, column_name) + assert run_key.target == "simulation_runs.id", table_name assert run_key.ondelete == "RESTRICT" # A report run compares one pair of simulation runs, so each row is # unique within its report run. - (unique_columns,) = _unique_column_sets(table) + (unique_columns,) = _unique_column_sets(table_name) assert unique_columns[0] == "report_run_id", table_name assert {"baseline_simulation_run_id", "reform_simulation_run_id"}.isdisjoint( unique_columns @@ -596,64 +587,56 @@ def test_comparison_results_name_the_two_simulation_runs_they_compare() -> None: def test_custom_totals_keep_their_simulation_references() -> None: """``aggregates`` and ``change_aggregates`` stay unchanged until they return.""" - aggregates = V2_METADATA.tables["aggregates"] - change_aggregates = V2_METADATA.tables["change_aggregates"] - - assert _foreign_key(aggregates, "simulation_id").target_fullname == ( - "simulations.id" - ) + assert _foreign_key("aggregates", "simulation_id").target == "simulations.id" for column_name in ("baseline_simulation_id", "reform_simulation_id"): - assert _foreign_key(change_aggregates, column_name).target_fullname == ( + assert _foreign_key("change_aggregates", column_name).target == ( "simulations.id" ) - for table in (aggregates, change_aggregates): - assert _foreign_key(table, "report_run_id").target_fullname == ( - "report_runs.id" - ) + for table_name in ("aggregates", "change_aggregates"): + assert _foreign_key(table_name, "report_run_id").target == "report_runs.id" def test_simulation_tables_keep_foreign_keys_to_the_rows_they_name() -> None: """Each service writes only its own tables; the keys between them stay.""" + tables = stored_v2_schema() public_api_keys = { - (table.name, key.parent.name): (key.column.table.name, key.ondelete) - for table in V2_METADATA.tables.values() + (table.name, key.column): (key.referred_table, key.ondelete) + for table in tables.values() if table.name in SIMULATION_SIDE_TABLES - for key in table.foreign_keys - if key.column.table.name not in SIMULATION_SIDE_TABLES + for key in table.foreign_key_columns + if key.referred_table not in SIMULATION_SIDE_TABLES } assert public_api_keys == PUBLIC_API_FOREIGN_KEYS - assert set(V2_METADATA.tables) >= SIMULATION_SIDE_TABLES + assert set(tables) >= SIMULATION_SIDE_TABLES def test_reports_index_their_owner_for_account_deletion() -> None: """Deleting a user clears ``reports.user_id``, which an index finds.""" - reports = V2_METADATA.tables["reports"] - - assert ("user_id",) in _indexes(reports).values() + assert ("user_id",) in _indexes("reports").values() def test_the_catalog_versions_runs_and_jobs_use_are_indexed() -> None: for table_name in ("simulation_runs", "household_jobs"): - table = V2_METADATA.tables[table_name] - assert ("tax_benefit_model_version_id",) in _indexes(table).values(), table_name + indexed_columns = _indexes(table_name).values() + assert ("tax_benefit_model_version_id",) in indexed_columns, table_name def test_poverty_rows_name_the_group_their_filter_selects() -> None: """One filter variable selects several groups (``age``: child, adult, senior).""" - poverty = V2_METADATA.tables["poverty"] + poverty = model_columns("poverty") - assert poverty.c.filter_group.nullable - assert poverty.c.filter_group.type.length == 64 + assert poverty.filter_group.nullable + assert poverty.filter_group.type.length == 64 def test_decile_rows_name_the_variable_that_groups_them() -> None: """Wealth deciles of income changes share the income variable and entity.""" - decile_impacts = V2_METADATA.tables["decile_impacts"] + decile_impacts = model_columns("decile_impacts") - assert decile_impacts.c.decile_variable.nullable - assert decile_impacts.c.decile_variable.type.length == 512 - statement = str(CreateTable(decile_impacts).compile(dialect=postgresql.dialect())) + assert decile_impacts.decile_variable.nullable + assert decile_impacts.decile_variable.type.length == 512 + statement = _create_table_statement("decile_impacts") assert ( "CONSTRAINT uq_decile_impacts_run_measure UNIQUE NULLS NOT DISTINCT " "(report_run_id, income_variable, decile_variable, entity, decile, quantiles)" diff --git a/tests/unit/v2/test_simulation_submission_database_routes.py b/tests/unit/v2/test_simulation_submission_database_routes.py index b9041099b..f6ba5f624 100644 --- a/tests/unit/v2/test_simulation_submission_database_routes.py +++ b/tests/unit/v2/test_simulation_submission_database_routes.py @@ -13,13 +13,8 @@ from uuid import UUID, uuid4 import pytest -from sqlalchemy import text -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import StaticPool -from sqlmodel import Session, create_engine from policyengine_api.data.v2.models import ( - V2_METADATA, Country, Dynamic, Parameter, @@ -63,13 +58,15 @@ from policyengine_api.services.v2.stored_simulations.services import ( V2StoredSimulationService, ) +from tests.fixtures.database_sessions import drop_tables, sqlite_v2_sessions from tests.unit.v2.stored_report_support import CURRENT_VERSIONS, report_route_client if TYPE_CHECKING: from collections.abc import Iterator from fastapi.testclient import TestClient - from sqlalchemy import Engine + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session RUNNING_VERSION = "6.10.0" EARLIER_VERSION = "6.9.0" @@ -102,17 +99,11 @@ def submit_simulation( @pytest.fixture -def engine() -> Iterator[Engine]: - # One connection shared by every thread, so the route's worker thread - # reads the same in-memory database. - database_engine = create_engine( - "sqlite://", - connect_args={"check_same_thread": False}, - poolclass=StaticPool, - ) - V2_METADATA.create_all(database_engine) - yield database_engine - database_engine.dispose() +def sessions() -> Iterator[sessionmaker[Session]]: + # Every Session shares one connection, so the route's worker thread reads + # the same in-memory database. + with sqlite_v2_sessions() as session_factory: + yield session_factory def store_catalog_version( @@ -161,7 +152,7 @@ def store_policy( @pytest.fixture -def stored_policy_ids(engine: Engine) -> dict[str, UUID]: +def stored_policy_ids(sessions: sessionmaker[Session]) -> dict[str, UUID]: """Store the US with two catalog versions and three policies. ``outdated_policy`` sets a parameter the running catalog version removed; @@ -169,7 +160,7 @@ def stored_policy_ids(engine: Engine) -> dict[str, UUID]: parameter the running version still has; ``running_policy`` was made on the running version. """ - with Session(engine, expire_on_commit=False) as session: + with sessions() as session: session.add(Country(id="us", household_enabled=True, society_wide_enabled=True)) model = TaxBenefitModel(name="policyengine-us") earlier = store_catalog_version( @@ -221,14 +212,14 @@ def store_dynamic( @pytest.fixture -def stored_dynamic_ids(engine: Engine) -> dict[str, UUID]: +def stored_dynamic_ids(sessions: sessionmaker[Session]) -> dict[str, UUID]: """Store the US with two catalog versions, the UK with one, and three dynamics. ``outdated_dynamic`` sets an assumption the running US catalog version removed, ``running_dynamic`` was made on the running US version, and ``uk_dynamic`` is the UK's. """ - with Session(engine, expire_on_commit=False) as session: + with sessions() as session: session.add_all( [ Country(id="us", household_enabled=True, society_wide_enabled=True), @@ -265,9 +256,8 @@ def simulation_service() -> RecordingSimulationService: @pytest.fixture def submissions( - engine: Engine, simulation_service: RecordingSimulationService + sessions: sessionmaker[Session], simulation_service: RecordingSimulationService ) -> SimulationSubmissionService: - sessions = sessionmaker(engine, class_=Session, expire_on_commit=False) return SimulationSubmissionService( countries=V2CountryService(CountryDatabaseSession(sessions)), households=V2HouseholdService(HouseholdDatabaseSession(sessions)), @@ -284,8 +274,9 @@ def submissions( @pytest.fixture -def client(engine: Engine, submissions: SimulationSubmissionService) -> TestClient: - sessions = sessionmaker(engine, class_=Session, expire_on_commit=False) +def client( + sessions: sessionmaker[Session], submissions: SimulationSubmissionService +) -> TestClient: return report_route_client( reports=V2StoredReportService( StoredReportDatabaseSession(sessions), @@ -389,7 +380,7 @@ def test_policies_whose_parameters_all_exist_in_the_running_catalog_are_sent( @pytest.mark.parametrize("record", ["report", "simulation"]) def test_a_catalog_that_cannot_be_queried_answers_503( - engine: Engine, + sessions: sessionmaker[Session], client: TestClient, stored_policy_ids: dict[str, UUID], simulation_service: RecordingSimulationService, @@ -397,8 +388,8 @@ def test_a_catalog_that_cannot_be_queried_answers_503( ) -> None: running_policy_id = stored_policy_ids["running_policy"] # The policy check's catalog query reads this table; nothing else does. - with engine.begin() as connection: - connection.execute(text("DROP TABLE tax_benefit_model_versions")) + with sessions.begin() as session: + drop_tables(session, TaxBenefitModelVersion) if record == "report": response = client.post( diff --git a/tests/unit/v2/test_stage12_comparison_isolation.py b/tests/unit/v2/test_stage12_comparison_isolation.py index 1bfa8c729..8113b4b4c 100644 --- a/tests/unit/v2/test_stage12_comparison_isolation.py +++ b/tests/unit/v2/test_stage12_comparison_isolation.py @@ -2,7 +2,7 @@ from pathlib import Path -from policyengine_api.data.v2.models import V2_METADATA +from tests.unit.v2.v2_schema_reading import v2_mappers REPO_ROOT = Path(__file__).resolve().parents[3] LEGACY_COMPARISON_TABLES = { @@ -34,12 +34,13 @@ def test_normal_routes_and_services_do_not_read_comparison_tables() -> None: def test_production_tables_have_no_comparison_table_dependency() -> None: - for table_name, table in V2_METADATA.tables.items(): + for mapper in v2_mappers(): + table_name = mapper.class_.__tablename__ if table_name in LEGACY_COMPARISON_TABLES: continue targets = { foreign_key.target_fullname - for column in table.columns + for column in mapper.columns for foreign_key in column.foreign_keys } assert not any( diff --git a/tests/unit/v2/test_stage12_comparison_models.py b/tests/unit/v2/test_stage12_comparison_models.py index 3637bee7a..ebd9c7693 100644 --- a/tests/unit/v2/test_stage12_comparison_models.py +++ b/tests/unit/v2/test_stage12_comparison_models.py @@ -2,15 +2,15 @@ from __future__ import annotations +from contextlib import contextmanager from datetime import UTC, datetime, timedelta +from typing import TYPE_CHECKING from uuid import UUID import sqlalchemy as sa from sqlalchemy.exc import IntegrityError -from sqlmodel import Session, create_engine from policyengine_api.data.v2.models import ( - V2_METADATA, Stage12AggregationStatus, Stage12ComparisonReport, Stage12ComparisonSimulation, @@ -24,6 +24,13 @@ ResultComparisonStatus, ) from policyengine_api.services.v2.simulations.types import SimulationRole +from tests.fixtures.database_sessions import sqlite_v2_sessions +from tests.unit.v2.v2_schema_reading import stored_v2_table + +if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlmodel import Session NOW = datetime(2026, 9, 14, tzinfo=UTC) EVALUATION_ID = UUID("00000000-0000-4000-8000-000000000001") @@ -31,17 +38,14 @@ DIGEST_B = "b" * 64 -def _engine(): - engine = create_engine("sqlite://") - - @sa.event.listens_for(engine, "connect") - def enable_foreign_keys(dbapi_connection, _connection_record) -> None: - cursor = dbapi_connection.cursor() - cursor.execute("PRAGMA foreign_keys=ON") - cursor.close() - - V2_METADATA.create_all(engine) - return engine +@contextmanager +def _session() -> Iterator[Session]: + """Yield a Session of a SQLite v2 schema that enforces foreign keys.""" + with ( + sqlite_v2_sessions(foreign_keys=True) as sessions, + sessions(expire_on_commit=True) as session, + ): + yield session def _report(**changes: object) -> Stage12ComparisonReport: @@ -91,8 +95,8 @@ def _simulation(**changes: object) -> Stage12ComparisonSimulation: def test_comparison_tables_have_only_the_temporary_parent_child_relationship() -> None: - report_table = V2_METADATA.tables["stage12_evaluation_reports"] - simulation_table = V2_METADATA.tables["stage12_evaluation_simulations"] + report_table = stored_v2_table("stage12_evaluation_reports") + simulation_table = stored_v2_table("stage12_evaluation_simulations") assert set(sa.inspect(Stage12ComparisonReport).relationships.keys()) == { "simulations" @@ -102,7 +106,7 @@ def test_comparison_tables_have_only_the_temporary_parent_child_relationship() - } assert not report_table.foreign_keys assert { - foreign_key.target_fullname for foreign_key in simulation_table.foreign_keys + foreign_key.target for foreign_key in simulation_table.foreign_key_columns } == {"stage12_evaluation_reports.evaluation_id"} assert { "household_jobs", @@ -131,8 +135,7 @@ def test_contract_and_table_enum_values_cannot_drift() -> None: def test_parent_identity_is_unique_for_worker_and_manifest() -> None: - engine = _engine() - with Session(engine) as session: + with _session() as session: session.add(_report()) session.commit() session.add(_report(evaluation_id=None)) @@ -143,12 +146,10 @@ def test_parent_identity_is_unique_for_worker_and_manifest() -> None: else: msg = "duplicate parent identity was accepted" raise AssertionError(msg) - engine.dispose() def test_child_identity_is_unique_within_a_parent() -> None: - engine = _engine() - with Session(engine) as session: + with _session() as session: session.add(_report()) session.add(_simulation()) session.commit() @@ -160,12 +161,10 @@ def test_child_identity_is_unique_within_a_parent() -> None: else: msg = "duplicate child identity was accepted" raise AssertionError(msg) - engine.dispose() def test_distinct_child_roles_can_complete_independently() -> None: - engine = _engine() - with Session(engine) as session: + with _session() as session: report = _report() baseline = _simulation( status=Stage12RunStatus.SUCCEEDED, @@ -188,12 +187,10 @@ def test_distinct_child_roles_can_complete_independently() -> None: assert baseline.status is Stage12RunStatus.SUCCEEDED assert reform.status is Stage12RunStatus.PENDING - engine.dispose() def test_database_rejects_success_without_complete_output_metadata() -> None: - engine = _engine() - with Session(engine) as session: + with _session() as session: session.add( _report( status=Stage12RunStatus.SUCCEEDED, @@ -208,12 +205,10 @@ def test_database_rejects_success_without_complete_output_metadata() -> None: else: msg = "successful report without output was accepted" raise AssertionError(msg) - engine.dispose() def test_database_rejects_failed_state_without_bounded_error_code() -> None: - engine = _engine() - with Session(engine) as session: + with _session() as session: session.add(_report(status=Stage12RunStatus.FAILED)) try: session.commit() @@ -222,12 +217,10 @@ def test_database_rejects_failed_state_without_bounded_error_code() -> None: else: msg = "failed report without error code was accepted" raise AssertionError(msg) - engine.dispose() def test_database_accepts_complete_comparison_receipt() -> None: - engine = _engine() - with Session(engine) as session: + with _session() as session: report = _report( comparison_status=Stage12ResultComparisonStatus.MATCHED, comparison_output_uri="gs://private-stage12/reports/comparison.json", @@ -238,4 +231,3 @@ def test_database_accepts_complete_comparison_receipt() -> None: session.add(report) session.commit() assert report.comparison_status is Stage12ResultComparisonStatus.MATCHED - engine.dispose() diff --git a/tests/unit/v2/test_user_association_migration_qualification.py b/tests/unit/v2/test_user_association_migration_qualification.py index 463a073f9..3f2dbf712 100644 --- a/tests/unit/v2/test_user_association_migration_qualification.py +++ b/tests/unit/v2/test_user_association_migration_qualification.py @@ -3,8 +3,6 @@ from __future__ import annotations import json -from contextlib import contextmanager -from typing import TYPE_CHECKING import pytest from alembic.config import Config @@ -18,10 +16,14 @@ V2_MIGRATION_DATABASE_URL, V2_SUPABASE_ENVIRONMENT, V2_SUPABASE_PROJECT_REF, + load_v2_migration_database_settings, +) +from tests.unit.v2.qualification_sessions import ( + CountingSession, + QualificationSessions, + serve_public_tables, + serve_read_only_sessions, ) - -if TYPE_CHECKING: - from collections.abc import Iterator ENVIRONMENT = { V2_MIGRATION_DATABASE_URL: ( @@ -33,59 +35,28 @@ } -class FakeTransaction: - def __init__(self) -> None: - self.rolled_back = False - - def rollback(self) -> None: - self.rolled_back = True - - -class FakeConnection: - def __init__(self, counts: tuple[int, int, int, int]) -> None: - self._counts = iter(counts) - self.transaction = FakeTransaction() - self.options: list[dict[str, object]] = [] - self.statements: list[str] = [] - - def execution_options(self, **options: object) -> FakeConnection: - self.options.append(options) - return self - - def begin(self) -> FakeTransaction: - return self.transaction +@pytest.fixture(autouse=True) +def _every_association_table_exists(monkeypatch: pytest.MonkeyPatch) -> None: + serve_public_tables(monkeypatch) - def scalar(self, statement: object) -> int: - self.statements.append(str(statement)) - return next(self._counts) - -class FakeEngine: - def __init__(self, connection: FakeConnection) -> None: - self.connection = connection - self.disposed = False - - @contextmanager - def connect(self) -> Iterator[FakeConnection]: - yield self.connection - - def dispose(self) -> None: - self.disposed = True - - -def _qualify(counts, *, pending: bool): - connection = FakeConnection(counts) - engine = FakeEngine(connection) +def _qualify(counts, *, pending: bool, monkeypatch: pytest.MonkeyPatch): + session = CountingSession(counts) + sessions = QualificationSessions(session) + read_only_urls = serve_read_only_sessions(monkeypatch, sessions) evidence = qualification.qualify_user_association_migration( ENVIRONMENT, - engine_builder=lambda _settings: engine, - pending_checker=lambda _connection: pending, + pending_checker=lambda _session: pending, ) - return evidence, connection, engine + return evidence, session, sessions, read_only_urls -def test_counts_are_reported_from_a_read_only_rolled_back_transaction() -> None: - evidence, connection, engine = _qualify((3, 2, 0, 0), pending=True) +def test_counts_are_reported_from_a_read_only_rolled_back_transaction( + monkeypatch: pytest.MonkeyPatch, +) -> None: + evidence, session, sessions, read_only_urls = _qualify( + (3, 2, 0, 0), pending=True, monkeypatch=monkeypatch + ) assert evidence.as_dict() == { "outcome": "ok", @@ -101,26 +72,33 @@ def test_counts_are_reported_from_a_read_only_rolled_back_transaction() -> None: "user_report_associations": 0, }, } - assert connection.options == [{"postgresql_readonly": True}] - assert connection.transaction.rolled_back - assert engine.disposed - assert len(connection.statements) == 4 - assert all("count(*)" in statement for statement in connection.statements) + configured = load_v2_migration_database_settings(ENVIRONMENT) + assert read_only_urls == [configured.connection.url] + assert session.rolled_back + assert sessions.closed + assert len(session.statements) == 4 + assert all("count(*)" in statement for statement in session.statements) -def test_retained_dormant_rows_stop_a_pending_reshape() -> None: +def test_retained_dormant_rows_stop_a_pending_reshape( + monkeypatch: pytest.MonkeyPatch, +) -> None: with pytest.raises(qualification.RetainedDormantAssociationError) as error: - _qualify((0, 0, 1, 2), pending=True) + _qualify((0, 0, 1, 2), pending=True, monkeypatch=monkeypatch) assert error.value.counts.dormant_total == 3 -def test_applied_reshape_reports_rows_without_failing() -> None: - evidence, connection, _engine = _qualify((0, 0, 5, 7), pending=False) +def test_applied_reshape_reports_rows_without_failing( + monkeypatch: pytest.MonkeyPatch, +) -> None: + evidence, session, _sessions, _read_only_urls = _qualify( + (0, 0, 5, 7), pending=False, monkeypatch=monkeypatch + ) assert evidence.as_dict()["dormant_tables_empty"] is False assert evidence.as_dict()["migration_pending"] is False - assert connection.transaction.rolled_back + assert session.rolled_back def test_revision_constant_names_a_revision_in_the_v2_chain() -> None: diff --git a/tests/unit/v2/test_user_types.py b/tests/unit/v2/test_user_types.py index 9529d1ab8..372003895 100644 --- a/tests/unit/v2/test_user_types.py +++ b/tests/unit/v2/test_user_types.py @@ -6,7 +6,6 @@ import pytest from sqlalchemy.exc import IntegrityError -from sqlmodel import Session from policyengine_api.data.v2.models import User, UserType from policyengine_api.fastapi_routes.v2.me.response_models import MeItem @@ -111,11 +110,11 @@ def test_users_store_each_signed_in_type_and_refuse_unknown_types( with store.sessions.begin() as session: for user_type in SIGNED_IN_TYPES_ABOVE_STANDARD: session.add(User(user_type=user_type.value, primary_country="us")) - with Session(store.sessions.kw["bind"]) as session: + with store.sessions() as session: session.add(User(user_type="editor", primary_country="us")) with pytest.raises(IntegrityError): session.commit() - with Session(store.sessions.kw["bind"]) as session: + with store.sessions() as session: # Every signed-in type still needs a primary country. session.add(User(user_type=UserType.AUTHOR.value)) with pytest.raises(IntegrityError): diff --git a/tests/unit/v2/v2_schema_reading.py b/tests/unit/v2/v2_schema_reading.py new file mode 100644 index 000000000..e6f31896a --- /dev/null +++ b/tests/unit/v2/v2_schema_reading.py @@ -0,0 +1,272 @@ +"""Read what the v2 models declare through the ORM, for the structural tests. + +Rule api.data.orm-only keeps tests away from Core ``Table`` objects, so the +structural tests read the schema two ways: + +- A model's columns come from its mapper (``model_columns``): the columns the + model declares, with their types, defaults and nullability. +- Each table's keys, constraints and indexes come from an in-memory SQLite copy + of the schema (``stored_v2_schema``), read with SQLAlchemy's Inspector, which + reads what the database holds. SQLite keeps every name, column list, delete + rule, check condition and index the models declare. + +What only PostgreSQL receives, such as a partial index's PostgreSQL condition, +is read from the model's ``__table_args__`` (``declared_index``). +""" + +from __future__ import annotations + +from dataclasses import dataclass +from functools import cache +from typing import TYPE_CHECKING, Any + +import sqlalchemy as sa +from sqlalchemy.orm import configure_mappers + +from policyengine_api.data.v2.models import User +from tests.fixtures.database_sessions import ( + schema_inspector, + sqlite_v1_sessions, + sqlite_v2_sessions, +) + +if TYPE_CHECKING: + from collections.abc import Mapping + + from sqlalchemy.engine import Inspector + from sqlalchemy.engine.interfaces import ReflectedForeignKeyConstraint + from sqlalchemy.orm import Mapper, Session + from sqlalchemy.sql.base import ReadOnlyColumnCollection + + +@dataclass(frozen=True) +class StoredForeignKeyColumn: + """One column of a stored foreign key, and the column it refers to.""" + + column: str + referred_table: str + referred_column: str + ondelete: str | None + constraint_name: str | None + + @property + def target(self) -> str: + """Return the referred column as ``table.column``.""" + return f"{self.referred_table}.{self.referred_column}" + + +@dataclass(frozen=True) +class StoredForeignKey: + """A stored foreign key: its name, columns, referred columns and delete rule.""" + + name: str | None + columns: tuple[str, ...] + referred_table: str + referred_columns: tuple[str, ...] + ondelete: str | None + + @property + def targets(self) -> tuple[str, ...]: + """Return the referred columns, each as ``table.column``.""" + return tuple( + f"{self.referred_table}.{column}" for column in self.referred_columns + ) + + @property + def column_references(self) -> tuple[StoredForeignKeyColumn, ...]: + """Return each of the key's columns with the column it refers to.""" + return tuple( + StoredForeignKeyColumn( + column=column, + referred_table=self.referred_table, + referred_column=referred_column, + ondelete=self.ondelete, + constraint_name=self.name, + ) + for column, referred_column in zip( + self.columns, self.referred_columns, strict=True + ) + ) + + +@dataclass(frozen=True) +class StoredIndex: + """A stored index: its name, columns and whether it is unique.""" + + name: str | None + columns: tuple[str | None, ...] + unique: bool + + +@dataclass(frozen=True) +class StoredTable: + """A table as the database stores it: its keys, constraints and indexes.""" + + name: str + primary_key_name: str | None + primary_key: tuple[str, ...] + foreign_keys: tuple[StoredForeignKey, ...] + unique_constraints: Mapping[str | None, tuple[str, ...]] + checks: Mapping[str | None, str] + indexes: Mapping[str | None, StoredIndex] + + @property + def constraint_names(self) -> set[str | None]: + """Return the names of the primary, foreign, unique and check constraints.""" + return { + self.primary_key_name, + *(foreign_key.name for foreign_key in self.foreign_keys), + *self.unique_constraints, + *self.checks, + } + + @property + def unique_column_sets(self) -> set[tuple[str, ...]]: + """Return each unique constraint's columns.""" + return set(self.unique_constraints.values()) + + @property + def index_columns(self) -> dict[str | None, tuple[str | None, ...]]: + """Return each index's columns, by the index's name.""" + return {name: index.columns for name, index in self.indexes.items()} + + @property + def foreign_key_columns(self) -> tuple[StoredForeignKeyColumn, ...]: + """Return every column of every foreign key with the column it refers to.""" + return tuple( + reference + for foreign_key in self.foreign_keys + for reference in foreign_key.column_references + ) + + @property + def references_by_column(self) -> dict[str, tuple[str, str | None]]: + """Return each foreign key column's referred table and delete rule.""" + return { + reference.column: (reference.referred_table, reference.ondelete) + for reference in self.foreign_key_columns + } + + def foreign_keys_of(self, column_name: str) -> tuple[StoredForeignKeyColumn, ...]: + """Return the references from ``column_name``, one per foreign key it is in.""" + return tuple( + reference + for reference in self.foreign_key_columns + if reference.column == column_name + ) + + def foreign_key(self, column_name: str) -> StoredForeignKeyColumn: + """Return the one reference from ``column_name``.""" + (reference,) = self.foreign_keys_of(column_name) + return reference + + def foreign_key_named(self, name: str) -> StoredForeignKey: + """Return the foreign key called ``name``.""" + return next( + foreign_key for foreign_key in self.foreign_keys if foreign_key.name == name + ) + + def foreign_keys_to(self, table_name: str) -> tuple[StoredForeignKey, ...]: + """Return the foreign keys that refer to ``table_name``.""" + return tuple( + foreign_key + for foreign_key in self.foreign_keys + if foreign_key.referred_table == table_name + ) + + +def _stored_foreign_key(reflected: ReflectedForeignKeyConstraint) -> StoredForeignKey: + return StoredForeignKey( + name=reflected["name"], + columns=tuple(reflected["constrained_columns"]), + referred_table=reflected["referred_table"], + referred_columns=tuple(reflected["referred_columns"]), + ondelete=reflected.get("options", {}).get("ondelete"), + ) + + +def _stored_table(inspector: Inspector, table_name: str) -> StoredTable: + primary_key = inspector.get_pk_constraint(table_name) + return StoredTable( + name=table_name, + primary_key_name=primary_key["name"], + primary_key=tuple(primary_key["constrained_columns"]), + foreign_keys=tuple( + _stored_foreign_key(foreign_key) + for foreign_key in inspector.get_foreign_keys(table_name) + ), + unique_constraints={ + constraint["name"]: tuple(constraint["column_names"]) + for constraint in inspector.get_unique_constraints(table_name) + }, + checks={ + constraint["name"]: constraint["sqltext"] + for constraint in inspector.get_check_constraints(table_name) + }, + indexes={ + index["name"]: StoredIndex( + name=index["name"], + columns=tuple(index["column_names"]), + unique=bool(index["unique"]), + ) + for index in inspector.get_indexes(table_name) + }, + ) + + +def _stored_tables(session: Session) -> dict[str, StoredTable]: + inspector = schema_inspector(session) + return { + table_name: _stored_table(inspector, table_name) + for table_name in inspector.get_table_names() + } + + +@cache +def stored_v2_schema() -> Mapping[str, StoredTable]: + """Return every table of an in-memory SQLite copy of the v2 schema, by name.""" + with sqlite_v2_sessions() as sessions, sessions() as session: + return _stored_tables(session) + + +def stored_v2_table(table_name: str) -> StoredTable: + """Return the v2 table called ``table_name`` as SQLite stores it.""" + return stored_v2_schema()[table_name] + + +@cache +def stored_v1_schema() -> Mapping[str, StoredTable]: + """Return every table of an in-memory SQLite copy of API v1's schema, by name.""" + with sqlite_v1_sessions() as sessions, sessions() as session: + return _stored_tables(session) + + +def v2_mappers() -> tuple[Mapper[Any], ...]: + """Return the mapper of every v2 model, once every mapper is configured.""" + configure_mappers() + return tuple(sa.inspect(User).registry.mappers) + + +def v2_model(table_name: str) -> type[Any]: + """Return the v2 model that maps the table called ``table_name``.""" + return next( + mapper.class_ + for mapper in v2_mappers() + if mapper.class_.__tablename__ == table_name + ) + + +def model_columns(model: type[Any] | str) -> ReadOnlyColumnCollection[str, Any]: + """Return the columns a model's mapper maps, by name; a name means its v2 model.""" + mapped_class = v2_model(model) if isinstance(model, str) else model + mapper: Mapper[Any] = sa.inspect(mapped_class) + return mapper.columns + + +def declared_index(model: type[Any], index_name: str) -> sa.Index: + """Return the index called ``index_name`` in the model's ``__table_args__``.""" + return next( + argument + for argument in model.__table_args__ + if isinstance(argument, sa.Index) and argument.name == index_name + ) From 77659002d669cd0e6973b884037ca14e2564e0bb Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:04:50 +0400 Subject: [PATCH 14/20] Test review round 1's findings in the ORM rule and conversion (failing) - The checker reports a statement's constant arguments, so an exception for SQLite's foreign-key PRAGMA allows no other statement; findings name their enclosing function, and exceptions can be narrowed to one; DDL(...) is raw SQL; exec_driver_sql, get_bind, raw_connection, connection() and database drivers' connect calls are reported in modules that import neither SQLAlchemy nor SQLModel. The rules loader reads an exception's function. - query_plan explains statements with an IN list, a literal parameter and a JSON parameter. - The metadata catalog fixture reads a row changed after its commit. - Importing the v1 schema migration script loads no .env file, the v2 schema inspector reads a plain SQLAlchemy Session, and read-only Sessions make every transaction READ ONLY. Co-Authored-By: Claude Opus 5.5 --- scripts/rules/tests/test_load.py | 71 +++- tests/fixtures/v2_metadata_service.py | 13 +- tests/integration/test_database_sessions.py | 43 ++- tests/unit/data/test_orm_access_support.py | 316 +++++++++++++++++- tests/unit/data/test_v1_database_migration.py | 66 ++++ tests/unit/v2/test_database.py | 36 +- .../unit/v2/test_metadata_service_fixture.py | 48 +++ 7 files changed, 568 insertions(+), 25 deletions(-) create mode 100644 tests/unit/v2/test_metadata_service_fixture.py diff --git a/scripts/rules/tests/test_load.py b/scripts/rules/tests/test_load.py index 7224fca20..6346e8601 100644 --- a/scripts/rules/tests/test_load.py +++ b/scripts/rules/tests/test_load.py @@ -123,8 +123,8 @@ def test_every_problem_is_reported_in_order(self) -> None: "Fix: write [[rule.exception]].", "[ex.layers.malformed] schema: unknown key 'extra' in " "ex.layers.malformed.exception. Fix: remove it or use one of " - "['category', 'expires', 'issue', 'match', 'path', 'reason', " - "'removal'].", + "['category', 'expires', 'function', 'issue', 'match', 'path', " + "'reason', 'removal'].", f"{MALFORMED}.exception.expires must be a date. " "Fix: write it as YYYY-MM-DD.", f"{MALFORMED}.downgrade needs a 'reason'. " @@ -191,5 +191,72 @@ def test_single_tables_stand_for_one_entry_lists(self) -> None: ) +NARROWED_EXCEPTION = { + "path": "pkg/store.py", + "reason": "GRANT has no ORM form", + "match": "text(statement)", + "category": "no-orm-form", + "function": "Reconciler.apply", +} + + +class ExceptionFunctionTest(unittest.TestCase): + """An exception's ``function`` narrows it to findings inside that function.""" + + def _parsed_exceptions( + self, exception: dict[str, object] + ) -> tuple[list[str], tuple[RuleException, ...]]: + raw = tomllib.loads(REGISTRY) + rule = {**SINGLE_TABLES_RULE, "exception": exception} + del rule["baseline"] + raw["rule"] = [rule] + registry, violations = parse(raw) + assert registry is not None + parsed = registry.rule("ex.layers.single-tables") + assert parsed is not None + return [str(violation) for violation in violations], parsed.exceptions + + def test_an_exception_reads_the_function_it_is_narrowed_to(self) -> None: + violations, exceptions = self._parsed_exceptions(NARROWED_EXCEPTION) + + self.assertEqual(violations, []) + self.assertEqual( + exceptions, + ( + RuleException( + path="pkg/store.py", + reason="GRANT has no ORM form", + match="text(statement)", + category="no-orm-form", + function="Reconciler.apply", + ), + ), + ) + + def test_an_exception_without_a_function_reads_none(self) -> None: + exception = { + key: value for key, value in NARROWED_EXCEPTION.items() if key != "function" + } + + violations, exceptions = self._parsed_exceptions(exception) + + self.assertEqual(violations, []) + self.assertIsNone(exceptions[0].function) + + def test_a_function_must_be_a_non_empty_string(self) -> None: + violations, _exceptions = self._parsed_exceptions( + {**NARROWED_EXCEPTION, "function": ""} + ) + + self.assertEqual( + violations, + [ + "[ex.layers.single-tables] schema: " + "ex.layers.single-tables.exception.function must be a non-empty " + "string. Fix: set function." + ], + ) + + if __name__ == "__main__": unittest.main() diff --git a/tests/fixtures/v2_metadata_service.py b/tests/fixtures/v2_metadata_service.py index f8cb46c21..a69943645 100644 --- a/tests/fixtures/v2_metadata_service.py +++ b/tests/fixtures/v2_metadata_service.py @@ -13,15 +13,22 @@ if TYPE_CHECKING: from collections.abc import Iterator + from sqlalchemy.orm import sessionmaker from sqlmodel import Session @pytest.fixture -def catalog_session() -> Iterator[Session]: +def catalog_sessions() -> Iterator[sessionmaker[Session]]: + """Return Session factories of a database holding the US and UK catalogs.""" with sqlite_v2_sessions() as sessions: with sessions.begin() as session: for country in normalized_catalog().countries: insert_country(session, country, include_model=True) + yield sessions - with sessions() as session: - yield session + +@pytest.fixture +def catalog_session(catalog_sessions: sessionmaker[Session]) -> Iterator[Session]: + """Return a Session of the catalog database, closed after the test.""" + with catalog_sessions() as session: + yield session diff --git a/tests/integration/test_database_sessions.py b/tests/integration/test_database_sessions.py index 48b4f2272..dd269c09e 100644 --- a/tests/integration/test_database_sessions.py +++ b/tests/integration/test_database_sessions.py @@ -11,7 +11,7 @@ from uuid import uuid4 import pytest -from sqlalchemy import delete, func, select +from sqlalchemy import bindparam, delete, func, select from sqlalchemy.exc import DBAPIError from sqlmodel import col @@ -23,7 +23,9 @@ ) from policyengine_api.data.v2.models import ( Country, + Household, Region, + Report, TaxBenefitModel, TaxBenefitModelVersion, ) @@ -35,6 +37,7 @@ drop_role, grant, grant_declared_v2_privileges, + query_plan, schema_inspector, truncate, ) @@ -191,6 +194,44 @@ def test_the_schema_inspector_reads_a_session_or_its_factory( assert set(from_factory) == set(tables) +def test_query_plan_explains_a_statement_with_an_in_list( + owner_session: Session, +) -> None: + """``in_()`` sends its list as one expanding parameter, rendered at execution.""" + lookup = select(col(Report.id)).where(col(Report.id).in_([uuid4(), uuid4()])) + + plan = query_plan(owner_session, lookup) + + assert "on reports" in plan + + +def test_query_plan_explains_a_statement_with_a_literal_parameter( + owner_session: Session, +) -> None: + """A ``literal_execute`` parameter is written into the SQL when it runs.""" + lookup = select(col(Report.id)).where( + col(Report.year) == bindparam("year", 2026, literal_execute=True) + ) + + plan = query_plan(owner_session, lookup) + + assert "on reports" in plan + assert "2026" in plan + + +def test_query_plan_explains_a_statement_with_a_json_parameter( + owner_session: Session, +) -> None: + """A JSON parameter is sent as its JSON text, as the column's type sends it.""" + lookup = select(col(Household.id)).where( + col(Household.household_data) == {"people": {"you": {}}} + ) + + plan = query_plan(owner_session, lookup) + + assert "on households" in plan + + def test_declared_privileges_are_granted_again_without_error( disposable_v2_database_url: str, managed_v2_roles: ManagedV2Roles ) -> None: diff --git a/tests/unit/data/test_orm_access_support.py b/tests/unit/data/test_orm_access_support.py index c5ab8de5d..9422d968e 100644 --- a/tests/unit/data/test_orm_access_support.py +++ b/tests/unit/data/test_orm_access_support.py @@ -549,8 +549,134 @@ def test_a_statement_on_a_session_is_not_reported(call: str) -> None: assert _checks({STORE: source}, STORE) == [] -def test_a_connection_outside_sqlalchemy_is_not_reported() -> None: - assert _checks({ROUTES: "value = connection.execute(statement)"}, ROUTES) == [] +@pytest.mark.parametrize( + ("call", "summary"), + [ + ( + "sqlite_connection.execute('PRAGMA foreign_keys = ON')", + "sqlite_connection.execute('PRAGMA foreign_keys = ON')", + ), + ( + "connection.execute('SELECT 1', parameters)", + "connection.execute('SELECT 1', ...)", + ), + ("conn.scalar('SELECT 1')", "conn.scalar('SELECT 1')"), + ("connection.execute(statement, parameters)", "connection.execute(...)"), + ("connection.execute(statement, timeout=5)", "connection.execute(...)"), + ], +) +def test_a_statement_outside_a_session_reports_its_constant_arguments( + call: str, summary: str +) -> None: + """A constant statement is reported, so an exception can name that statement.""" + source = f"import sqlalchemy\n\nvalue = {call}" + + assert _checks({STORE: source}, STORE) == [(CORE_CONNECTION, summary)] + + +def test_an_exception_for_one_constant_statement_allows_no_other() -> None: + source = """ + import sqlalchemy + + sqlite_connection.execute("PRAGMA foreign_keys = ON") + sqlite_connection.execute("DELETE FROM reports") + """ + findings = orm_access_findings({STORE: dedent(source)}) + exceptions = [ + _construct_exception( + STORE, "sqlite_connection.execute('PRAGMA foreign_keys = ON')" + ) + ] + + assert [ + finding.source for finding in undeclared_findings(findings, exceptions) + ] == ["sqlite_connection.execute('DELETE FROM reports')"] + + +@pytest.mark.parametrize( + ("call", "expected"), + [ + ( + "session.connection().exec_driver_sql('DELETE FROM reports')", + [ + ( + RAW_SQL, + "session.connection().exec_driver_sql('DELETE FROM reports')", + ), + (CORE_CONNECTION, "session.connection()"), + ], + ), + ("session.get_bind()", [(CORE_CONNECTION, "session.get_bind()")]), + ("engine.raw_connection()", [(CORE_CONNECTION, "engine.raw_connection()")]), + ( + "database.exec_driver_sql('SELECT 1')", + [(RAW_SQL, "database.exec_driver_sql('SELECT 1')")], + ), + ], +) +def test_connections_and_driver_sql_are_reported_without_a_sqlalchemy_import( + call: str, expected: list[tuple[str, str]] +) -> None: + """These method names mean SQLAlchemy whatever the module imports.""" + assert _checks({ROUTES: f"value = {call}"}, ROUTES) == expected + + +@pytest.mark.parametrize( + "call", + [ + "connection.execute(statement)", + "connection.scalars(statement)", + "socket.connect()", + "connect(url)", + "driver.cursor()", + "cache_engine.begin()", + ], +) +def test_ambiguous_method_names_are_not_reported_outside_sqlalchemy(call: str) -> None: + """Other libraries share these names, so they count only beside sqlalchemy.""" + assert _checks({ROUTES: f"value = {call}"}, ROUTES) == [] + + +@pytest.mark.parametrize( + ("imports", "call", "summary"), + [ + ("import psycopg", "psycopg.connect(url)", "psycopg.connect(url)"), + ("import psycopg2", "psycopg2.connect(url)", "psycopg2.connect(url)"), + ("import pymysql", "pymysql.connect(host='localhost')", "pymysql.connect(...)"), + ( + "import sqlite3", + "sqlite3.connect(':memory:')", + "sqlite3.connect(':memory:')", + ), + ( + "import mysql.connector", + "mysql.connector.connect(user='root')", + "mysql.connector.connect(...)", + ), + ("import psycopg as pg", "pg.connect(url)", "pg.connect(url)"), + ("from psycopg import connect", "connect(url)", "connect(url)"), + ( + "from mysql import connector", + "connector.connect(user='root')", + "connector.connect(...)", + ), + ], +) +def test_a_database_drivers_connect_is_reported_outside_a_session_factory_module( + imports: str, call: str, summary: str +) -> None: + source = f"{imports}\n\ndriver_connection = {call}\n" + + assert _checks({ROUTES: source}, ROUTES) == [(CORE_CONNECTION, summary)] + assert _checks({SESSION_FACTORY: source}, SESSION_FACTORY) == [] + + +def test_a_statement_on_a_driver_connection_is_reported_where_it_connects() -> None: + source = "import psycopg\n\npsycopg.connect(url).execute('DELETE FROM reports')\n" + + assert _checks({ROUTES: source}, ROUTES) == [ + (CORE_CONNECTION, "psycopg.connect(url)") + ] def test_a_session_factory_module_hands_out_no_engine_or_connection() -> None: @@ -607,11 +733,18 @@ def test_only_a_session_factory_module_reads_a_session_factorys_engine() -> None ("sa.literal_column('count(*)')", "sa.literal_column('count(*)')"), ("session.exec_driver_sql('SELECT 1')", "session.exec_driver_sql('SELECT 1')"), ("driver_connection.cursor()", "driver_connection.cursor()"), + ("sa.DDL('DROP TABLE reports')", "sa.DDL('DROP TABLE reports')"), + ( + "sa.schema.DDL('ALTER TABLE reports ADD note text')", + "sa.schema.DDL('ALTER TABLE reports ADD note text')", + ), + ("DDL('DROP TABLE reports')", "DDL('DROP TABLE reports')"), ], ) def test_raw_sql_is_reported(source: str, summary: str) -> None: store = f""" import sqlalchemy as sa + from sqlalchemy.schema import DDL statement = {source} """ @@ -972,14 +1105,98 @@ def test_a_name_assigned_a_mapped_class_or_its_table_name_is_not_a_table() -> No assert _checks({STORE: store}, STORE) == [] -def _finding(file: str, source: str, line: int = 1) -> Finding: - return Finding(file, line, RAW_SQL, source) +def _finding( + file: str, source: str, line: int = 1, *, function: str | None = None +) -> Finding: + if function is None: + return Finding(file, line, RAW_SQL, source) + return Finding(file, line, RAW_SQL, source, function=function) -def _construct_exception(path: str, match: str | None) -> RuleException: +def _construct_exception( + path: str, match: str | None, *, function: str | None = None +) -> RuleException: + if function is None: + return RuleException( + path=path, reason="no ORM form", match=match, category=NO_ORM_FORM + ) return RuleException( - path=path, reason="no ORM form", match=match, category=NO_ORM_FORM + path=path, + reason="no ORM form", + match=match, + category=NO_ORM_FORM, + function=function, + ) + + +def test_each_finding_names_the_function_it_is_in() -> None: + source = """ + import sqlalchemy as sa + + module_statement = sa.text("SELECT 1") + + def reconcile(): + return sa.text("SELECT 2") + + class Reconciler: + class_statement = sa.text("SELECT 3") + + def apply(self): + def build(): + return sa.text("SELECT 4") + + return sa.text("SELECT 5") + + async def read(): + return sa.text("SELECT 6") + """ + + findings = orm_access_findings({STORE: dedent(source)}) + + assert [(finding.source, finding.function) for finding in findings] == [ + ("sa.text('SELECT 1')", None), + ("sa.text('SELECT 2')", "reconcile"), + ("sa.text('SELECT 3')", "Reconciler"), + ("sa.text('SELECT 4')", "Reconciler.apply.build"), + ("sa.text('SELECT 5')", "Reconciler.apply"), + ("sa.text('SELECT 6')", "read"), + ] + + +def test_a_finding_in_a_function_names_it_when_described() -> None: + in_function = _finding(STORE, "text(statement)", line=3, function="apply_grants") + + assert str(in_function) == f"{STORE}:3: raw SQL: text(statement) in apply_grants" + assert str(_finding(STORE, "text(statement)", line=3)) == ( + f"{STORE}:3: raw SQL: text(statement)" + ) + + +def test_an_exception_with_a_function_allows_findings_only_in_that_function() -> None: + granting = _finding(STORE, "text(statement)", line=3, function="apply_grants") + reading = _finding(STORE, "text(statement)", line=9, function="read_roles") + module_level = _finding(STORE, "text(statement)", line=12) + exceptions = [ + _construct_exception(STORE, "text(statement)", function="apply_grants") + ] + + assert undeclared_findings([granting, reading, module_level], exceptions) == [ + reading, + module_level, + ] + + +def test_an_exception_with_a_function_is_unused_without_a_finding_there() -> None: + findings = [_finding(STORE, "text(statement)", function="read_roles")] + in_its_function = _construct_exception( + STORE, "text(statement)", function="read_roles" ) + elsewhere = _construct_exception(STORE, "text(statement)", function="apply_grants") + anywhere_in_the_module = _construct_exception(STORE, "text(statement)") + + assert unused_exceptions( + findings, [in_its_function, elsewhere, anywhere_in_the_module] + ) == [elsewhere] def test_an_exception_allows_every_finding_with_its_file_and_source() -> None: @@ -1032,11 +1249,12 @@ def test_a_path_exception_takes_its_files_out_of_the_check(tmp_path: Path) -> No def test_exception_problems_name_each_unusable_exception(tmp_path: Path) -> None: (tmp_path / "migrations").mkdir() (tmp_path / "migrations" / "env.py").write_text("", encoding="utf-8") - (tmp_path / "store.py").write_text("", encoding="utf-8") + (tmp_path / "tests").mkdir() + (tmp_path / "tests" / "store.py").write_text("", encoding="utf-8") exceptions = [ - _construct_exception("store.py", "text('SELECT 1')"), - _construct_exception("store.py", None), - _construct_exception("missing.py", "text('SELECT 1')"), + _construct_exception("tests/store.py", "text('SELECT 1')"), + _construct_exception("tests/store.py", None), + _construct_exception("tests/missing.py", "text('SELECT 1')"), RuleException( path="migrations/*.py", reason="revisions", category=MIGRATION_REVISION ), @@ -1049,19 +1267,81 @@ def test_exception_problems_name_each_unusable_exception(tmp_path: Path) -> None RuleException( path="scripts/*.py", reason="scripts", category=MIGRATION_REVISION ), - RuleException(path="store.py", reason="no category"), - RuleException(path="store.py", reason="driver", category="driver-access"), + RuleException(path="tests/store.py", reason="no category"), + RuleException(path="tests/store.py", reason="driver", category="driver-access"), ] assert exception_problems( - exceptions, ["migrations/env.py", "store.py"], tmp_path + exceptions, ["migrations/env.py", "tests/store.py"], tmp_path ) == [ - "exception for store.py names no construct: set match to the finding's source", - "exception for missing.py must name one existing file", + "exception for tests/store.py names no construct: set match to the " + "finding's source", + "exception for tests/missing.py must name one existing file", "exception for migrations/*.py skips whole files, so it takes no match", "exception for scripts/*.py matches no file the rule test reads: remove it", - "exception for store.py has unknown category None: use one of " - "['no-orm-form', 'migration-revision']", - "exception for store.py has unknown category 'driver-access': use one of " + "exception for tests/store.py has unknown category None: use one of " "['no-orm-form', 'migration-revision']", + "exception for tests/store.py has unknown category 'driver-access': use " + "one of ['no-orm-form', 'migration-revision']", + ] + + +def test_exceptions_outside_tests_or_naming_no_sql_text_need_a_function( + tmp_path: Path, +) -> None: + """Production entries, and entries whose match holds no SQL, name a function. + + An entry whose match is a bare call, a call on variables or an attribute + read would otherwise allow every such call in the module. + """ + for file in ("policyengine_api/store.py", "scripts/migrate.py", "tests/rows.py"): + (tmp_path / file).parent.mkdir(parents=True, exist_ok=True) + (tmp_path / file).write_text("", encoding="utf-8") + store, script, rows = ( + "policyengine_api/store.py", + "scripts/migrate.py", + "tests/rows.py", + ) + exceptions = [ + _construct_exception(store, "sa.text(f'ANALYZE {tables}')"), + _construct_exception(store, "text(statement)", function="apply_grants"), + _construct_exception(script, "session.connection()"), + _construct_exception(rows, "text(statement)"), + _construct_exception(rows, "session.get_bind()"), + _construct_exception(rows, "mapper.local_table"), + _construct_exception(rows, "session.get_bind()", function="Rows.dialect"), + _construct_exception(rows, "text(f'TRUNCATE {tables} CASCADE')"), + _construct_exception( + rows, "sqlite_connection.execute('PRAGMA foreign_keys = ON')" + ), + ] + + assert exception_problems(exceptions, [], tmp_path) == [ + f"exception for {store} (sa.text(f'ANALYZE {{tables}}')) needs a " + "function: set function to the enclosing function of its finding", + f"exception for {script} (session.connection()) needs a function: set " + "function to the enclosing function of its finding", + f"exception for {rows} (text(statement)) needs a function: set function " + "to the enclosing function of its finding", + f"exception for {rows} (session.get_bind()) needs a function: set " + "function to the enclosing function of its finding", + f"exception for {rows} (mapper.local_table) needs a function: set " + "function to the enclosing function of its finding", + ] + + +def test_a_path_exception_takes_no_function(tmp_path: Path) -> None: + (tmp_path / "migrations").mkdir() + (tmp_path / "migrations" / "env.py").write_text("", encoding="utf-8") + exceptions = [ + RuleException( + path="migrations/*.py", + reason="revisions", + category=MIGRATION_REVISION, + function="run_migrations_online", + ) + ] + + assert exception_problems(exceptions, ["migrations/env.py"], tmp_path) == [ + "exception for migrations/*.py skips whole files, so it takes no function" ] diff --git a/tests/unit/data/test_v1_database_migration.py b/tests/unit/data/test_v1_database_migration.py index fd694e640..9ea5329d8 100644 --- a/tests/unit/data/test_v1_database_migration.py +++ b/tests/unit/data/test_v1_database_migration.py @@ -1,12 +1,18 @@ from __future__ import annotations +import json +import os +import subprocess +import sys from contextlib import contextmanager, nullcontext from types import SimpleNamespace +from typing import TYPE_CHECKING import pytest from sqlalchemy.engine import URL import scripts.v1_database_migration as migration +from policyengine_api.constants import REPO from scripts.v1_database_migration import ( DatabaseState, build_database_url, @@ -15,9 +21,69 @@ upgrade_database, ) +if TYPE_CHECKING: + from pathlib import Path + # Fake credentials; the first holds characters that URLs must escape. FAKE_PASSWORD_WITH_URL_CHARACTERS = "p@ss:/word" FAKE_PASSWORD = "p@ssword" +# The database URLs .github/scripts/migrate_v1_cloud_sql.sh unsets before it +# runs the script, so only the credentials it fetched reach the database. +UNSET_DATABASE_URL_NAMES = ("ALEMBIC_DATABASE_URL", "STAGE7_EXISTING_DATABASE_URL") +# Imports the script, then prints the named variables as JSON on its last line. +IMPORT_SCRIPT_AND_REPORT_VARIABLES = """ +import json +import os +import sys + +import scripts.v1_database_migration + +print(json.dumps({name: os.environ.get(name) for name in sys.argv[1:]})) +""" +SUBPROCESS_TIMEOUT_SECONDS = 120 + + +def test_importing_the_script_loads_no_dotenv_file(tmp_path: Path) -> None: + """A .env file can't give the script back a database URL the deploy unset. + + Run through ``python -c``, python-dotenv searches for ``.env`` from the + working directory, so a default ``load_dotenv()`` anywhere in the script's + imports would find the file written here. + """ + (tmp_path / ".env").write_text( + "".join( + f"{name}=mysql+pymysql://from-dotenv@127.0.0.1:3307/policyengine\n" + for name in UNSET_DATABASE_URL_NAMES + ), + encoding="utf-8", + ) + environment = { + name: value + for name, value in os.environ.items() + if name not in UNSET_DATABASE_URL_NAMES + } + environment["PYTHONPATH"] = os.pathsep.join( + [str(REPO), *filter(None, [os.environ.get("PYTHONPATH")])] + ) + + completed = subprocess.run( + [ + sys.executable, + "-c", + IMPORT_SCRIPT_AND_REPORT_VARIABLES, + *UNSET_DATABASE_URL_NAMES, + ], + cwd=tmp_path, + env=environment, + capture_output=True, + text=True, + check=False, + timeout=SUBPROCESS_TIMEOUT_SECONDS, + ) + + assert completed.returncode == 0, completed.stderr + reported_variables = json.loads(completed.stdout.splitlines()[-1]) + assert reported_variables == dict.fromkeys(UNSET_DATABASE_URL_NAMES) def test_database_url_uses_sqlalchemy_url_without_stringifying_credentials(): diff --git a/tests/unit/v2/test_database.py b/tests/unit/v2/test_database.py index 3b9678309..fcea49791 100644 --- a/tests/unit/v2/test_database.py +++ b/tests/unit/v2/test_database.py @@ -4,8 +4,10 @@ from pathlib import Path import pytest +from sqlalchemy.orm import Session as OrmSession from sqlmodel import Session, select +from policyengine_api.data.v1_models import Policy from policyengine_api.data.v2 import database from policyengine_api.data.v2.models import TaxBenefitModel from policyengine_api.data.v2.settings import ( @@ -17,7 +19,12 @@ load_v2_migration_database_settings, load_v2_runtime_database_settings, ) -from tests.fixtures.database_sessions import sqlite_v2_sessions +from tests.fixtures.database_sessions import sqlite_v1_sessions, sqlite_v2_sessions + +# A PostgreSQL URL no test connects to: building an engine opens no connection. +UNCONNECTED_POSTGRES_URL = ( + "postgresql+psycopg://reader:test-password@127.0.0.1:5432/policyengine" +) def _environment(*, username: str = "runtime") -> dict[str, str]: @@ -166,6 +173,33 @@ def test_read_sessions_refuse_to_write_rows() -> None: assert session.exec(select(TaxBenefitModel)).all() == [] +def test_unpooled_read_only_sessions_make_every_transaction_read_only() -> None: + """Every Session's engine has SQLAlchemy's ``postgresql_readonly`` option. + + With it, psycopg begins each of the engine's transactions READ ONLY, so + PostgreSQL refuses any write the qualification commands might send. + """ + with ( + database.unpooled_v2_read_only_sessions(UNCONNECTED_POSTGRES_URL) as sessions, + sessions() as session, + ): + bind = session.bind + assert bind is not None + assert bind.get_execution_options().get("postgresql_readonly") is True + + +def test_schema_inspector_reads_a_plain_sqlalchemy_session_in_its_transaction() -> None: + """A Session that isn't SQLModel's is read as a Session, not as a factory.""" + with sqlite_v1_sessions() as sessions, sessions() as session: + assert isinstance(session, OrmSession) + assert not isinstance(session, Session) + + inspector = database.v2_schema_inspector(session) + + assert Policy.__tablename__ in inspector.get_table_names() + assert session.in_transaction() + + def test_only_the_metadata_reader_opens_read_sessions() -> None: package = Path(database.__file__).parents[2] users = sorted( diff --git a/tests/unit/v2/test_metadata_service_fixture.py b/tests/unit/v2/test_metadata_service_fixture.py new file mode 100644 index 000000000..aa7e5d5e5 --- /dev/null +++ b/tests/unit/v2/test_metadata_service_fixture.py @@ -0,0 +1,48 @@ +"""Tests of the metadata service tests' catalog database fixture. + +The fixture is in tests/fixtures/v2_metadata_service.py. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from sqlalchemy import update +from sqlmodel import col + +from policyengine_api.data.v2.models import TaxBenefitModelVersion +from tests.fixtures.v2_metadata_service_helpers import ( + catalog_service, + stored_model_version, +) + +if TYPE_CHECKING: + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + +pytest_plugins = ("tests.fixtures.v2_metadata_service",) + +CHANGED_DESCRIPTION = "Changed by another session after the commit" + + +def test_the_catalog_session_reads_a_row_changed_after_its_commit( + catalog_sessions: sessionmaker[Session], catalog_session: Session +) -> None: + """A commit expires the session's rows, so its next read sees stored values. + + The test keeps the loaded model version, so the session's identity map + still holds it when the service reads the version again. + """ + model_version = stored_model_version(catalog_session, "policyengine-us") + model_version_id = model_version.id + catalog_session.commit() + with catalog_sessions.begin() as other_session: + other_session.execute( + update(TaxBenefitModelVersion) + .where(col(TaxBenefitModelVersion.id) == model_version_id) + .values(description=CHANGED_DESCRIPTION) + ) + + read = catalog_service(catalog_session).get_model_version("us", model_version_id) + + assert read.item.description == CHANGED_DESCRIPTION From e6b195a66f30bb15ac4a587342dd3435f5502ef7 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:26:18 +0400 Subject: [PATCH 15/20] Fix review round 1's findings in the ORM rule and conversion - The checker reports a statement's constant arguments and each finding's enclosing function, and no-orm-form exceptions can name that function, so each exception allows only the statement its reason gives; production entries and entries that name only a variable must name their function. DDL(...) is raw SQL, and exec_driver_sql, get_bind, raw_connection, connection() and database drivers' connect calls are reported whatever a module imports. The rules loader and renderer read and show the function. - query_plan compiles for the session's dialect, expands IN lists and literal parameters, and processes each bind, so it explains what the session runs. - The metadata catalog fixtures expire rows on commit again, and serve_v1_sessions restores API v1's cached Session factory after the test. - API v1's Session factories for one-off commands move to policyengine_api/data/v1_sessions.py, so importing the v1 schema migration script loads no .env file, Cloud SQL connector or observability runtime, as before the conversion. v2_schema_inspector reads any SQLAlchemy Session. - Role privilege refusals send only the columns they test, through test-local mapped classes without onupdate or Python defaults, so a wrong column grant makes them fail again. - New integration tests run qualify_v2_target's persistent path as non-owner roles and check privilege reconciliation's reads of default privileges, sequence, view and materialized-view grants; CI runs them. - Duplicated test helpers are shared, two catalog fixtures expire on commit, test docstrings say API v1, and the docs describe the narrowed exceptions. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/v2-integration-check.yml | 4 +- docs/engineering/skills/alembic-migrations.md | 151 ++++++--- docs/engineering/skills/rules-registry.md | 2 +- docs/generated/rules.md | 32 +- migrations/v2/env.py | 6 +- policyengine_api/data/orm.py | 47 +-- policyengine_api/data/v1_sessions.py | 54 +++ policyengine_api/data/v2/database.py | 50 ++- rules/registry.toml | 78 ++++- scripts/process_v1_household_mirror_event.py | 2 +- scripts/rules/load.py | 12 +- scripts/rules/model.py | 5 +- scripts/rules/render.py | 5 +- scripts/rules/tests/test_load.py | 6 +- scripts/rules/tests/test_render.py | 50 +++ scripts/rules/v2_layer_checks.py | 6 +- scripts/v1_database_migration.py | 2 +- tests/fixtures/database_sessions.py | 98 ++++-- tests/fixtures/integration/alembic_v2.py | 16 +- tests/fixtures/v2_metadata_service.py | 8 +- tests/integration/alembic_version_rows.py | 13 +- .../integration/catalog_privilege_objects.py | 159 +++++++++ .../catalog_publication_support.py | 41 ++- tests/integration/privilege_statements.py | 187 +++++++++++ .../test_alembic_mysql_lifecycle.py | 2 +- .../test_alembic_v2_cliff_impacts.py | 13 +- .../integration/test_alembic_v2_lifecycle.py | 43 +-- .../test_alembic_v2_simulation_runs.py | 16 +- tests/integration/test_database_sessions.py | 2 +- .../test_v1_schema_metadata_compatibility.py | 2 +- .../test_v2_budget_window_report_creation.py | 2 +- .../test_v2_budget_window_report_reads.py | 2 +- .../test_v2_catalog_publication.py | 33 +- .../test_v2_catalog_publication_pruning.py | 26 +- tests/integration/test_v2_country_routes.py | 8 +- .../test_v2_forced_report_reruns.py | 2 +- .../test_v2_household_calculation_reads.py | 15 +- .../integration/test_v2_household_reports.py | 6 +- tests/integration/test_v2_metadata_routes.py | 36 +- .../test_v2_migration_target_persistent.py | 161 +++++++++ .../test_v2_privilege_reconciliation.py | 118 ++++++- tests/integration/test_v2_report_creation.py | 2 +- tests/integration/test_v2_report_reads.py | 2 +- .../test_v2_report_reads_by_run.py | 2 +- tests/integration/test_v2_report_runs.py | 4 +- .../integration/test_v2_shared_report_rows.py | 47 ++- .../test_v2_simulation_role_privileges.py | 114 ++++--- .../test_v2_stage12_comparison_persistence.py | 9 +- .../test_v2_user_budget_window_runs.py | 6 +- .../test_v2_user_identity_persistence.py | 4 +- .../test_v2_user_report_run_requesters.py | 6 +- tests/integration/test_v2_user_report_runs.py | 6 +- .../integration/test_v2_user_report_views.py | 6 +- tests/unit/data/fake_driver_connections.py | 46 ++- tests/unit/data/orm_access_support.py | 314 +++++++++++++----- tests/unit/data/test_database_sessions.py | 9 + tests/unit/data/test_orm_access_support.py | 6 - tests/unit/data/test_orm_only.py | 20 +- tests/unit/data/test_orm_pool_events.py | 4 +- tests/unit/data/test_orm_sessions.py | 17 - tests/unit/data/test_v1_sessions.py | 37 +++ tests/unit/test_alembic_workflows.py | 16 + tests/unit/v2/test_alembic_v2_revisions.py | 11 +- tests/unit/v2/test_database.py | 28 +- tests/unit/v2/test_dynamic_catalog.py | 7 +- tests/unit/v2/test_metadata_validation.py | 22 +- tests/unit/v2/test_models.py | 4 +- tests/unit/v2/test_policy_catalog.py | 5 +- tests/unit/v2/test_policy_legacy_copy.py | 4 +- tests/unit/v2/test_privilege_manifest.py | 2 +- tests/unit/v2/test_simulation_run_models.py | 4 +- 71 files changed, 1717 insertions(+), 568 deletions(-) create mode 100644 policyengine_api/data/v1_sessions.py create mode 100644 tests/integration/catalog_privilege_objects.py create mode 100644 tests/integration/privilege_statements.py create mode 100644 tests/integration/test_v2_migration_target_persistent.py create mode 100644 tests/unit/data/test_v1_sessions.py diff --git a/.github/workflows/v2-integration-check.yml b/.github/workflows/v2-integration-check.yml index 018370d8b..7ddd676db 100644 --- a/.github/workflows/v2-integration-check.yml +++ b/.github/workflows/v2-integration-check.yml @@ -79,8 +79,8 @@ jobs: run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_policy_persistence.py tests/integration/test_v2_dynamic_persistence.py tests/integration/test_v1_policy_dual_write.py tests/integration/test_mysql_policy_dual_write.py tests/integration/test_v2_user_policy_mirroring.py tests/integration/test_v1_user_policy_dual_write.py - name: Test signed-in identity provisioning, user associations, saved detailed-save records and user types run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_user_identity_persistence.py tests/integration/test_v2_user_type_persistence.py tests/integration/test_v2_saved_detailed_save_records.py tests/integration/test_v2_saved_budget_window_reports.py - - name: Test comparison-run persistence, the simulation API's roles, shared reports and runs, privilege reconciliation as the managed roles, and the tests' database sessions - run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_stage12_comparison_persistence.py tests/integration/test_v2_simulation_role_privileges.py tests/integration/test_v2_shared_report_rows.py tests/integration/test_v2_privilege_reconciliation.py tests/integration/test_database_sessions.py + - name: Test comparison-run persistence, the simulation API's roles, shared reports and runs, privilege reconciliation as the managed roles, the v2 migration target checks as roles that don't own the database, and the tests' database sessions + run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_stage12_comparison_persistence.py tests/integration/test_v2_simulation_role_privileges.py tests/integration/test_v2_shared_report_rows.py tests/integration/test_v2_privilege_reconciliation.py tests/integration/test_v2_migration_target_persistent.py tests/integration/test_database_sessions.py - name: Test v2 household persistence, immediate v1 copying, household calculation reads and household reports run: uv run --frozen --extra dev coverage run -a --branch -m pytest -q tests/integration/test_v2_household_persistence.py tests/integration/test_v1_household_dual_write.py tests/integration/test_mysql_household_spm_dual_write.py tests/integration/test_v2_household_calculation_reads.py tests/integration/test_v2_household_reports.py - name: Test the row counts v1 ORM updates report on MySQL diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 8f32a44a3..28c80452b 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -193,16 +193,27 @@ SQLAlchemy's `text`. They report four kinds of finding: - **Core engine or connection**: importing `Engine`, `create_engine` or `Connection` outside a session-factory module; opening a Connection there (`connect()`, `connection()`, `get_bind()`, or `begin()` on an engine); - `raw_connection()` in any module; `execute()` on anything not named as a - session, and `scalar()`, `scalars()`, `stream()` or `stream_scalars()` on a - name such as `connection`; listening for pool, engine or dialect events - (`connect`, `checkout`, `before_cursor_execute`, `handle_error` and the - rest) outside a session-factory module; and a public function of a - session-factory module that returns an `Engine` or `Connection`. -- **raw SQL**: `text()`, `literal_column()`, `exec_driver_sql()` and + calling a database driver's `connect` there (`psycopg`, `psycopg2`, + `pymysql`, `sqlite3` or `mysql.connector`); `raw_connection()` in any + module; `execute()` on anything not named as a session, and `scalar()`, + `scalars()`, `stream()` or `stream_scalars()` on a name such as + `connection`; listening for pool, engine or dialect events (`connect`, + `checkout`, `before_cursor_execute`, `handle_error` and the rest) outside a + session-factory module; and a public function of a session-factory module + that returns an `Engine` or `Connection`. +- **raw SQL**: `text()`, `literal_column()`, `DDL()`, `exec_driver_sql()` and `cursor()`, apart from `text()` given as a server default, a partial index's condition or a check constraint's condition. +`connection()`, `get_bind()`, `raw_connection()` and `exec_driver_sql()` are +SQLAlchemy's names, so they count in every module, as does a driver's +`connect`. The names other libraries share, such as `execute()`, `connect()`, +`begin()` and `cursor()`, count only in a module that imports `sqlalchemy` or +`sqlmodel`. A statement run outside a session is reported with its constant +arguments, as `sqlite_connection.execute('PRAGMA foreign_keys = ON')`, and +every finding records the innermost class or function whose body holds it, +such as `Reconciler.apply`. + `test_every_table_is_mapped_by_a_class` imports `policyengine_api.data` and the test modules that write rows, and reports every table they hold that no mapped class maps, including tables built in ways the source checks can't see. @@ -210,16 +221,24 @@ mapped class maps, including tables built in ways the source checks can't see. Two kinds of module have a role of their own: - **Session-factory modules** are the only modules that may create or hold an - Engine, open a Connection or attach pool events: - `policyengine_api/data/orm.py` (with `policyengine_api/data/orm_pool_events.py`, - whose listeners record the v1 pool's events), - `policyengine_api/data/v2/database.py`, and - `tests/fixtures/database_sessions.py` for the tests, with - `tests/unit/data/test_orm_pool_events.py`, whose tests drive the pool - `orm_pool_events.py` listens to (they invalidate, detach and recycle - connections and hold two at once, which no Session offers; their statements - still run in Sessions). They hand out Session - factories, never an Engine or a Connection. When a module needs its own + Engine, open a Connection, call a database driver's `connect` or attach pool + events: + - `policyengine_api/data/orm.py`, API v1's runtime factory, with + `policyengine_api/data/orm_pool_events.py`, whose listeners record the v1 + pool's events; + - `policyengine_api/data/v1_sessions.py`, API v1's Session factories for + commands that run once. Unlike `orm.py`, importing it loads no `.env` + file, Cloud SQL connector or pool listeners; + - `policyengine_api/data/v2/database.py`; + - `tests/fixtures/database_sessions.py` for the tests; + - `tests/unit/data/test_orm_pool_events.py`, whose tests drive the pool + `orm_pool_events.py` listens to (they invalidate, detach and recycle + connections and hold two at once, which no Session offers; their + statements still run in Sessions), and + `tests/unit/data/fake_driver_connections.py`, the fake database driver + beneath those tests' engine, which opens its in-memory SQLite connections. + + They hand out Session factories, never an Engine or a Connection. When a module needs its own engine settings, such as `NullPool`, a deploy-time role or a separate URL, the session-factory module gets a function that returns a Session factory with them. @@ -237,8 +256,8 @@ session-factory modules: | Function | What it gives | | --- | --- | -| `orm.unpooled_v1_sessions(url)` | A context manager yielding API v1 Session factories for the database at `url`, on an engine with no pool, disposed of on exit. For the household mirror command and the v1 schema migration. | -| `orm.v1_schema_inspector(source)` | SQLAlchemy's `Inspector` of the database a v1 Session (inside its transaction) or Session factory uses. | +| `v1_sessions.unpooled_v1_sessions(url)` | A context manager yielding API v1 Session factories for the database at `url`, on an engine with no pool, disposed of on exit. For the household mirror command and the v1 schema migration. Importing `v1_sessions` loads no `.env` file, so a command's environment is the one its caller gives it. | +| `v1_sessions.v1_schema_inspector(source)` | SQLAlchemy's `Inspector` of the database a v1 Session (inside its transaction) or Session factory uses. | | `v2.database.unpooled_v2_sessions(url)` | The same for API v2, given `V2DatabaseSettings.connection.url` or `V2AlembicSettings.url`: catalog initialization and privilege reconciliation. | | `v2.database.unpooled_v2_read_only_sessions(url)` | The same, with every transaction `READ ONLY` (`postgresql_readonly`): the migration qualification commands. | | `v2.database.v2_schema_inspector(source)` | SQLAlchemy's `Inspector` of the database a v2 Session or Session factory uses, as the migration target checks need. | @@ -253,17 +272,17 @@ integration fixtures built on it (`tests/integration/conftest.py`): | `v1_sessions(url)`; fixture `v1_sessions` | API v1's Session factories of the disposable MySQL database. | | `sqlite_v2_sessions(foreign_keys=False)` | Session factories of a new in-memory SQLite copy of the v2 schema, whose savepoints behave as on PostgreSQL (Python 3.12's sqlite3 `autocommit=False`); with `foreign_keys`, SQLite enforces the foreign keys. | | `sqlite_v1_sessions(json_serializer=None)` | API v1's Session factories of a new in-memory SQLite copy of its schema, with SQLite numbering policies. | -| `serve_v1_sessions(monkeypatch, sessions)` | Makes `orm.get_v1_session_factory()` open `sessions`' connections for the test. | +| `serve_v1_sessions(monkeypatch, sessions)` | Makes `orm.get_v1_session_factory()` open `sessions`' connections for the test; the factory it builds is forgotten after the test. | | `v1_cloud_sql_sessions(monkeypatch, url)` | API v1's own Session factory, its Cloud SQL engine built as in production but connected to the local MySQL server at `url`. | | `sqlite_v2_file_sessions(path)` | Session factories of a SQLite file copy of the v2 schema, one connection per Session, every transaction starting with `BEGIN IMMEDIATE`, for concurrency tests. | | `single_connection_v2_sessions(url)` | The owner's Session factories on a pool of exactly one connection, so every Session gets the same pooled connection back. | -| `act_as(session, role)`, `act_as_owner(session)` | Act as `role`, or as the database's owner again, until the transaction ends. | +| `act_as(session, role)`, `act_as_owner(session)` | Act as `role` (`SET LOCAL ROLE`), or as the user the session logged in as, the database's owner (`SET LOCAL ROLE NONE`), until the transaction ends. | | `schema_inspector(source)` | SQLAlchemy's `Inspector` of the database a Session or Session factory uses. | | `recorded_statements(source)` | A context manager yielding the list of SQL statements sent through a Session or Session factory inside it. | | `recorded_driver_connection_states(source)` | A context manager yielding, for each statement, which driver connection it ran on, its autocommit mode and whether it was inside a transaction. | -| `query_plan(session, statement)` | PostgreSQL's plan (`EXPLAIN`) of an ORM statement, its rows joined. | +| `query_plan(session, statement)` | PostgreSQL's plan (`EXPLAIN`) of an ORM statement, its rows joined, compiled for the session's dialect and sent as executing it would send it: `in_()` lists, `literal_execute` values and processed parameters such as JSON. | | `v2_schema_statements(dialect_name)` | The v2 schema's CREATE statements, compiled for a dialect, with no database. | -| `delete_all_rows(session, registry)` | Deletes every row of every table a registry's mapped classes map, such as `V1Base.registry`. | +| `delete_all_rows(session, registry)` | Deletes every row of every table a registry's mapped classes map, in no set order, so for a registry whose tables have no foreign keys between them, such as `V1Base.registry`. | | `truncate(session, *models)` | `TRUNCATE ... CASCADE` of the models' tables. | | `drop_tables(session, *models)` | `DROP TABLE` of the models' tables, so a later query on them fails with the database's own error. | | `create_registry_tables(session, registry)`, `drop_registry_tables(session, registry)` | Create a registry's tables (failing if one exists), or drop those that exist, in the Session's transaction, for tables a test declares itself. | @@ -296,8 +315,11 @@ and `refused(session, ...)`. select from `information_schema` or `pg_catalog` with SQL text. - **Roles in tests**: `act_as(session, role)` and `act_as_owner(session)` set the `role` setting with `set_config` inside the session's transaction, as - `SET LOCAL ROLE` and `RESET ROLE` do; or a role's Session factory - (`v2_sessions_as_role`), whose connections start as the role. Setup rows + `SET LOCAL ROLE role` and `SET LOCAL ROLE NONE` do. `NONE` acts as the user + the session logged in as, the database's owner, even on a role's + connection, where `RESET ROLE` would return to the role it started with. Or + use a role's Session factory (`v2_sessions_as_role`), whose connections + start as the role. Setup rows stay in the same rolled-back transaction where a test relies on that. - **Refusals**: `refused(session, ...)` runs the statements inside it in `session.begin_nested()` and expects the error. @@ -319,14 +341,23 @@ The rule's exceptions are its `[[rule.exception]]` entries in - **`no-orm-form`**: one construct in one module that SQLAlchemy's ORM has no form for. `path` names the module, and `match` is the finding's source exactly as the check reports it, the text after its kind, such as - `text(f'DROP ROLE {quoted_role}')`. The entry allows every finding in that - module with that source. -- **`migration-revision`**: a path pattern the rule test doesn't read. + `text(f'DROP ROLE {quoted_role}')`. `function` names the class or function + whose body holds it, as the finding reports it after `in`, such as + `apply_declared_privileges` or `Reconciler.apply`. With `function`, the + entry allows that source only there; without it, anywhere in the module. + Every entry outside `tests/` gives its `function`, and so does any entry + whose `match` holds no SQL text, such as `text(statement)`, + `session.connection()` or an attribute read, which would otherwise allow + every such call in its module. Two sites in different functions take an + entry each. +- **`migration-revision`**: a path pattern the rule test doesn't read. It + takes no `match` and no `function`. The rule test fails on a finding no entry names, on an entry that names no finding, and on an entry with an unknown category, a `no-orm-form` entry -without a `match` or an existing file, or a `migration-revision` entry that -names no file. Only statements SQLAlchemy can't express get an entry: `GRANT` +without a `match`, an existing file or a `function` it needs, or a +`migration-revision` entry that names no file or gives a `match` or +`function`. Only statements SQLAlchemy can't express get an entry: `GRANT` and `REVOKE`, `CREATE`, `ALTER` and `DROP ROLE` (with `DROP OWNED BY`), `DROP TABLE`, `TRUNCATE`, `COPY`, `EXPLAIN`, `ANALYZE`, Alembic's need for a Connection, and connection settings no SQL function sets, such as SQLite's @@ -340,38 +371,54 @@ modules as possible. The entries: (`api.data.sqlalchemy-and-alembic-only`), so the rule test doesn't read them. 2. **The rule's own check for unmapped tables** (`no-orm-form`, two - entries), in `tests/unit/data/orm_access_support.py`: it reads which - table each mapped class maps (`mapper.local_table`) and the tables a - declarative base's metadata holds (`class_registry.metadata.tables`). It - runs no statement. + entries), in `tests/unit/data/orm_access_support.py`'s + `_unmapped_findings`: it reads which table each mapped class maps + (`mapper.local_table`) and the tables a declarative base's metadata holds + (`class_registry.metadata.tables`). It runs no statement. 3. **The tests' statements with no ORM form** (`no-orm-form`, nine entries), in `tests/fixtures/database_sessions.py`: SQLite's `PRAGMA foreign_keys` on each new in-memory connection; `BEGIN IMMEDIATE` on the concurrency test's SQLite file; `TRUNCATE ... CASCADE` for cleanup; `DROP TABLE`, so a - route's catalog query fails with the database's own error; `EXPLAIN`, to - read the plan of an ORM statement; and `CREATE ROLE`, `DROP OWNED BY`, - `DROP ROLE` and `GRANT` for the privilege tests' temporary roles. -4. **Catalog publication** (`no-orm-form`, three entries). + route's catalog query fails with the database's own error and the MySQL + lifecycle test finds a revision's table missing; `EXPLAIN`, to read the + plan of an ORM statement (`query_plan` sends it with `exec_driver_sql`, + because `text()` reads only `:name` parameters and the psycopg dialect + writes `%(name)s::TYPE`); and `CREATE ROLE`, `DROP OWNED BY`, `DROP ROLE` + and `GRANT` for the privilege tests' temporary roles. +4. **Catalog publication** (`no-orm-form`, four entries). `publication_staging.py` takes the Connection the publishing Session holds - (`session.connection()`) to create the `TEMPORARY` staging tables with - `MetaData.create_all` and to stream rows with `COPY ... FROM STDIN`, on a - cursor of the psycopg connection beneath it (`driver_connection.cursor()`). - `publication_statistics.py` runs one `ANALYZE` of the catalog tables a - publication wrote, after it commits. + (`session.connection()`) in `create_staging_tables`, to create the + `TEMPORARY` staging tables with `MetaData.create_all`, and in `copy_rows`, + to stream rows with `COPY ... FROM STDIN` on a cursor of the psycopg + connection beneath it (`driver_connection.cursor()`). + `publication_statistics.py`'s `analyze_catalog_tables` runs one `ANALYZE` + of the catalog tables a publication wrote, after it commits. 5. **Privilege reconciliation** (`no-orm-form`, two entries), in `privilege_reconciliation.py`: `CREATE ROLE ... NOLOGIN` for missing - managed roles, only in the disposable test database, and the `GRANT` and - `REVOKE` statements `privilege_plans` builds, with identifiers checked by + managed roles in `create_missing_roles`, only in the disposable test + database, and, in `apply_declared_privileges`, the `GRANT` and `REVOKE` + statements `privilege_plans` builds, with identifiers checked by `safe_identifier` and quoted by the session's dialect. -6. **Alembic's Connection** (`no-orm-form`, two entries). Alembic's +6. **Alembic's Connection** (`no-orm-form`, four entries). Alembic's `MigrationContext`, `compare_metadata` and `command.upgrade` take a - Connection, so `pending_revisions.py` (the migration qualification - commands' pending-revision check) and `scripts/v1_database_migration.py` - give them the Connection their Session holds, inside its transaction. + Connection, so `pending_revisions.py`'s `v2_revision_is_pending` (the + migration qualification commands' pending-revision check) and + `scripts/v1_database_migration.py`'s `_config`, `database_state` and + `metadata_differences` give them the Connection their Session holds, + inside its transaction. 7. **The dialect's name** (`no-orm-form`), in - `services/v2/user_types/database_connectors/reads.py`: - `session.get_bind()` reads it to skip PostgreSQL's advisory lock on the - SQLite test databases. It runs no statement on the engine. + `services/v2/user_types/database_connectors/reads.py`'s + `acquire_user_type_change_lock`: `session.get_bind()` reads it to skip + PostgreSQL's advisory lock on the SQLite test databases. It runs no + statement on the engine. +8. **The privilege reconciliation tests' objects** (`no-orm-form`, three + entries), in `tests/integration/catalog_privilege_objects.py`: `GRANT` on + a schema or a sequence in `grant_on_schema_object`, which the shared + `grant` (tables, views and materialized views) doesn't cover; `ALTER + DEFAULT PRIVILEGES` in `alter_default_privileges`, for a default ACL; and + `CREATE VIEW` and `CREATE MATERIALIZED VIEW` in `create_view`, which + SQLAlchemy has no construct for. The reconciliation's catalog reads are + tested on those grants. A new exception is a rule change: add a `[[rule.exception]]` entry to the rule in `rules/registry.toml`, explain here why the ORM can't express the diff --git a/docs/engineering/skills/rules-registry.md b/docs/engineering/skills/rules-registry.md index b3a65c0de..3f2329e1d 100644 --- a/docs/engineering/skills/rules-registry.md +++ b/docs/engineering/skills/rules-registry.md @@ -60,7 +60,7 @@ gap is visible, rather than leaving it out. | `[[rule.ci]]` | `workflow`, `job`, and an `invocation` string that must appear in that job's `run:` text (or its reusable-workflow `uses:`), or in a command of a Makefile target the job runs with `make `, following the targets' prerequisites and the `$(MAKE)` calls in their recipes (`scripts/rules/makefile.py`). | | `[rule.proof]` | Optional; see "Proof". | | `[rule.baseline]` | Only for `ratcheted` rules: `file` listing tolerated violations, and their `count`. | -| `[[rule.exception]]` | Carve-out: `path`, `reason`, and `expires`; or, for rules whose guard reads them, `match` (one site), `removal`, `issue` and `category` ([dependencies.md](dependencies.md#exceptions); for `api.data.sqlalchemy-and-alembic-only`, `match` is the exact construct and `category` is `driver-access`, `schema-change` or `migration-revision`: [alembic-migrations.md](alembic-migrations.md#declared-exceptions); for `api.data.orm-only`, `match` is the finding's source and `category` is `no-orm-form` or `migration-revision`: [alembic-migrations.md](alembic-migrations.md#orm-only-exceptions)). | +| `[[rule.exception]]` | Carve-out: `path`, `reason`, and `expires`; or, for rules whose guard reads them, `match` (one site), `function`, `removal`, `issue` and `category` ([dependencies.md](dependencies.md#exceptions); for `api.data.sqlalchemy-and-alembic-only`, `match` is the exact construct and `category` is `driver-access`, `schema-change` or `migration-revision`: [alembic-migrations.md](alembic-migrations.md#declared-exceptions); for `api.data.orm-only`, `match` is the finding's source, `function` the class or function whose body holds it, and `category` is `no-orm-form` or `migration-revision`; a `no-orm-form` entry allows every site with that source in its module, or only in its `function` when it gives one: [alembic-migrations.md](alembic-migrations.md#orm-only-exceptions)). | | `[rule.downgrade]` | Required `reason` when a rule moves from enforced/ratcheted to advisory/doc-only. | `blocking` is derived, never declared: a rule blocks merges when its status is diff --git a/docs/generated/rules.md b/docs/generated/rules.md index 6ff876860..cbd57bf55 100644 --- a/docs/generated/rules.md +++ b/docs/generated/rules.md @@ -72,25 +72,31 @@ Every rule that governs `policyengine-api` is listed here with how it is enforce ### Exceptions and review dates - `api.data.orm-only`: exception for `migrations/**/*.py` allowed as a migration-revision (migrations/ holds the Alembic environments and the revisions Alembic generates. The environments run Alembic's migration context on a Connection, and the revisions are where schema changes belong (api.data.sqlalchemy-and-alembic-only), so the rule test doesn't read them.) -- `api.data.orm-only`: exception for `policyengine_api/data/v2/catalog/publication_staging.py` (`driver_connection.cursor()`) allowed as a no-orm-form (COPY ... FROM STDIN has no SQLAlchemy form. Publication runs it through psycopg's Cursor.copy, on a cursor of the driver connection beneath the publishing Session's Connection.) -- `api.data.orm-only`: exception for `policyengine_api/data/v2/catalog/publication_staging.py` (`session.connection()`) allowed as a no-orm-form (Catalog publication creates its TEMPORARY staging tables with MetaData.create_all, which takes a Connection, and streams rows with COPY ... FROM STDIN through the psycopg connection beneath the Connection. Both run on the Connection the publishing Session holds, in its transaction.) -- `api.data.orm-only`: exception for `policyengine_api/data/v2/catalog/publication_statistics.py` (`sa.text(f'ANALYZE {tables}')`) allowed as a no-orm-form (ANALYZE has no ORM form. After a publication commits, one ANALYZE refreshes the planner statistics of the catalog tables it wrote.) -- `api.data.orm-only`: exception for `policyengine_api/data/v2/pending_revisions.py` (`session.connection()`) allowed as a no-orm-form (Alembic's MigrationContext reads the database's current heads from its version table through a Connection. The migration qualification commands give it the Connection their Session holds, so the read runs inside the Session's READ ONLY transaction.) -- `api.data.orm-only`: exception for `policyengine_api/data/v2/privilege_reconciliation.py` (`text(f'CREATE ROLE {quote(safe_identifier(role))} NOLOGIN')`) allowed as a no-orm-form (CREATE ROLE has no SQLAlchemy form. reconcile_v2_privileges.py apply --create-missing-roles creates each missing managed role as NOLOGIN, only in the disposable test database, in the reconciliation's one transaction. The role name is checked by safe_identifier and quoted by the session's dialect.) -- `api.data.orm-only`: exception for `policyengine_api/data/v2/privilege_reconciliation.py` (`text(statement)`) allowed as a no-orm-form (GRANT and REVOKE have no SQLAlchemy form. apply runs the REVOKEs and GRANTs that privilege_plans' revoke_statements and grant_statements build from the declared privileges, with identifiers checked by safe_identifier and quoted by the session's dialect, in the reconciliation's one transaction.) -- `api.data.orm-only`: exception for `policyengine_api/services/v2/user_types/database_connectors/reads.py` (`session.get_bind()`) allowed as a no-orm-form (Reads the dialect's name, to skip PostgreSQL's advisory lock on the SQLite test databases, which have none. It runs no statement on the engine.) -- `api.data.orm-only`: exception for `scripts/v1_database_migration.py` (`session.connection()`) allowed as a no-orm-form (Alembic's MigrationContext, compare_metadata and command.upgrade take a Connection. The v1 schema migration gives them the Connection its Session holds, so the version reads, the schema comparison and the upgrade run in the Session's transaction, under the MySQL named lock the Session took.) +- `api.data.orm-only`: exception for `policyengine_api/data/v2/catalog/publication_staging.py` (`driver_connection.cursor()` in `copy_rows`) allowed as a no-orm-form (COPY ... FROM STDIN has no SQLAlchemy form. Publication runs it through psycopg's Cursor.copy, on a cursor of the driver connection beneath the publishing Session's Connection.) +- `api.data.orm-only`: exception for `policyengine_api/data/v2/catalog/publication_staging.py` (`session.connection()` in `copy_rows`) allowed as a no-orm-form (Catalog publication streams rows with COPY ... FROM STDIN through the psycopg connection beneath the Connection the publishing Session holds, in its transaction.) +- `api.data.orm-only`: exception for `policyengine_api/data/v2/catalog/publication_staging.py` (`session.connection()` in `create_staging_tables`) allowed as a no-orm-form (Catalog publication creates its TEMPORARY staging tables with MetaData.create_all, which takes a Connection: the Connection the publishing Session holds, in its transaction.) +- `api.data.orm-only`: exception for `policyengine_api/data/v2/catalog/publication_statistics.py` (`sa.text(f'ANALYZE {tables}')` in `analyze_catalog_tables`) allowed as a no-orm-form (ANALYZE has no ORM form. After a publication commits, one ANALYZE refreshes the planner statistics of the catalog tables it wrote.) +- `api.data.orm-only`: exception for `policyengine_api/data/v2/pending_revisions.py` (`session.connection()` in `v2_revision_is_pending`) allowed as a no-orm-form (Alembic's MigrationContext reads the database's current heads from its version table through a Connection. The migration qualification commands give it the Connection their Session holds, so the read runs inside the Session's READ ONLY transaction.) +- `api.data.orm-only`: exception for `policyengine_api/data/v2/privilege_reconciliation.py` (`text(f'CREATE ROLE {quote(safe_identifier(role))} NOLOGIN')` in `create_missing_roles`) allowed as a no-orm-form (CREATE ROLE has no SQLAlchemy form. reconcile_v2_privileges.py apply --create-missing-roles creates each missing managed role as NOLOGIN, only in the disposable test database, in the reconciliation's one transaction. The role name is checked by safe_identifier and quoted by the session's dialect.) +- `api.data.orm-only`: exception for `policyengine_api/data/v2/privilege_reconciliation.py` (`text(statement)` in `apply_declared_privileges`) allowed as a no-orm-form (GRANT and REVOKE have no SQLAlchemy form. apply runs the REVOKEs and GRANTs that privilege_plans' revoke_statements and grant_statements build from the declared privileges, with identifiers checked by safe_identifier and quoted by the session's dialect, in the reconciliation's one transaction.) +- `api.data.orm-only`: exception for `policyengine_api/services/v2/user_types/database_connectors/reads.py` (`session.get_bind()` in `acquire_user_type_change_lock`) allowed as a no-orm-form (Reads the dialect's name, to skip PostgreSQL's advisory lock on the SQLite test databases, which have none. It runs no statement on the engine.) +- `api.data.orm-only`: exception for `scripts/v1_database_migration.py` (`session.connection()` in `_config`) allowed as a no-orm-form (Alembic's command.upgrade takes a Connection, through the Alembic config's connection attribute. The v1 schema migration gives it the Connection its Session holds, so the upgrade runs in the Session's transaction, under the MySQL named lock the Session took.) +- `api.data.orm-only`: exception for `scripts/v1_database_migration.py` (`session.connection()` in `database_state`) allowed as a no-orm-form (Alembic's MigrationContext reads the database's current heads from its version table through a Connection. The v1 schema migration gives it the Connection its Session holds, so the read runs in the Session's transaction, under the MySQL named lock the Session took.) +- `api.data.orm-only`: exception for `scripts/v1_database_migration.py` (`session.connection()` in `metadata_differences`) allowed as a no-orm-form (Alembic's compare_metadata compares the schema through a MigrationContext on a Connection. The v1 schema migration gives it the Connection its Session holds, so the comparison runs in the Session's transaction, under the MySQL named lock the Session took.) - `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`connection.exec_driver_sql('BEGIN IMMEDIATE')`) allowed as a no-orm-form (SQLite takes its write lock at the start of a transaction only with BEGIN IMMEDIATE, a transaction mode SQLAlchemy's SQLite dialect has no setting for. A concurrency test's file database starts every transaction that way, as SELECT ... FOR UPDATE makes writers wait on PostgreSQL.) -- `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`sqlite_connection.execute(...)`) allowed as a no-orm-form (SQLite enforces foreign keys only once a connection sets PRAGMA foreign_keys, a connection setting SQLAlchemy has no API for. The in-memory SQLite test databases set it on each connection before its first transaction.) +- `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`session.connection().exec_driver_sql(f'EXPLAIN {expanded.statement}', ...)` in `query_plan`) allowed as a no-orm-form (EXPLAIN has no SQLAlchemy form. A test that checks an index serves a lookup reads PostgreSQL's plan for the ORM statement that does the lookup, compiled for the session's dialect with its in_() lists and literal_execute values written out and its parameters processed by their types. text() can't take that SQL: the psycopg dialect writes each parameter as %(name)s with a cast such as ::JSONB, and text() reads only :name parameters. So the plan is read on the Session's own Connection, in its transaction and as its role.) +- `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`sqlite_connection.execute('PRAGMA foreign_keys = ON')`) allowed as a no-orm-form (SQLite enforces foreign keys only once a connection sets PRAGMA foreign_keys, a connection setting SQLAlchemy has no API for. The in-memory SQLite test databases set it on each connection before its first transaction.) - `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`text(f'CREATE ROLE {quoted_role} NOLOGIN')`) allowed as a no-orm-form (Roles have no ORM form. Privilege tests create a temporary role that can't log in.) - `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`text(f'DROP OWNED BY {quoted_role}')`) allowed as a no-orm-form (Roles have no ORM form. Privilege tests drop what a temporary role owns and was granted, so the role can be dropped.) - `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`text(f'DROP ROLE {quoted_role}')`) allowed as a no-orm-form (Roles have no ORM form. Privilege tests drop the temporary roles they create.) -- `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`text(f'DROP TABLE {tables}')`) allowed as a no-orm-form (Dropping a table has no ORM form. Route tests drop a catalog table so the route's real catalog query fails with the database's own error.) -- `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`text(f'EXPLAIN {compiled}')`) allowed as a no-orm-form (EXPLAIN has no SQLAlchemy form. A test that checks an index serves a lookup reads PostgreSQL's plan for the ORM statement that does the lookup.) +- `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`text(f'DROP TABLE {tables}')`) allowed as a no-orm-form (Dropping a table has no ORM form. Route tests drop a catalog table so the route's real catalog query fails with the database's own error, and the MySQL lifecycle test drops a table a revision creates, to check the migration notices it is missing.) - `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`text(f'GRANT {privileges} ON TABLE {table} TO {quoted_role}')`) allowed as a no-orm-form (Grants have no ORM form. Privilege tests grant a temporary role privileges the manifest doesn't declare, to check that verification reports them.) - `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`text(f'TRUNCATE {tables} CASCADE')`) allowed as a no-orm-form (TRUNCATE has no ORM form. Test cleanup empties a table and every table that refers to it at once, as the catalog tests do after publishing.) -- `api.data.orm-only`: exception for `tests/unit/data/orm_access_support.py` (`class_registry.metadata.tables`) allowed as a no-orm-form (The rule's check for tables without a mapped class reads the tables a declarative base's metadata holds, to find those no class maps. It runs no statement.) -- `api.data.orm-only`: exception for `tests/unit/data/orm_access_support.py` (`mapper.local_table`) allowed as a no-orm-form (The rule's check for tables without a mapped class reads which table each mapped class maps. It runs no statement.) +- `api.data.orm-only`: exception for `tests/integration/catalog_privilege_objects.py` (`text(f"CREATE {view_kind} {qualified_view} AS SELECT 1 AS id, 'label'::text AS label")` in `create_view`) allowed as a no-orm-form (CREATE VIEW and CREATE MATERIALIZED VIEW have no SQLAlchemy construct. The v2 schema has only tables, so the privilege reconciliation tests create a view and a materialized view of one row, to check the reconciliation reads the grants on them.) +- `api.data.orm-only`: exception for `tests/integration/catalog_privilege_objects.py` (`text(f'ALTER DEFAULT PRIVILEGES FOR ROLE {creator} IN SCHEMA {SCHEMA} GRANT {_privileges(privileges)} ON {object_type} TO {grantee}')` in `alter_default_privileges`) allowed as a no-orm-form (ALTER DEFAULT PRIVILEGES has no ORM form. The privilege reconciliation tests set a default ACL on the tables and sequences a role creates, PUBLIC's included, to check the reconciliation reads the default privileges.) +- `api.data.orm-only`: exception for `tests/integration/catalog_privilege_objects.py` (`text(f'GRANT {_privileges(privileges)} ON {on_object} TO {grantee}')` in `grant_on_schema_object`) allowed as a no-orm-form (Grants have no ORM form. The privilege reconciliation tests grant a role privileges on a schema or a sequence, which the shared grant helper, for tables, views and materialized views, doesn't cover, to check the reconciliation reads those grants.) +- `api.data.orm-only`: exception for `tests/unit/data/orm_access_support.py` (`class_registry.metadata.tables` in `_unmapped_findings`) allowed as a no-orm-form (The rule's check for tables without a mapped class reads the tables a declarative base's metadata holds, to find those no class maps. It runs no statement.) +- `api.data.orm-only`: exception for `tests/unit/data/orm_access_support.py` (`mapper.local_table` in `_unmapped_findings`) allowed as a no-orm-form (The rule's check for tables without a mapped class reads which table each mapped class maps. It runs no statement.) - `api.data.sqlalchemy-and-alembic-only`: exception for `migrations/*/versions/*.py` allowed as a migration-revision (Alembic generates the revisions, and they are where schema changes belong, so the check doesn't scan them. Ruff skips the same files (extend-exclude in pyproject.toml).) - `api.data.sqlalchemy-and-alembic-only`: exception for `policyengine_api/data/orm_pool_events.py` (`attribute ._sock`) allowed as a driver-access (The v1 pool's diagnostics read the file descriptor and local port of pymysql's socket from the driver connection a SQLAlchemy pool event passes them, because SQLAlchemy has no API for a connection's socket. They never read or write through the socket or the driver connection, and import no driver.) - `api.data.sqlalchemy-and-alembic-only`: exception for `policyengine_api/data/v2/catalog/publication_staging.py` (`attribute .driver_connection`) allowed as a driver-access (Catalog publication runs COPY through the psycopg connection beneath a SQLAlchemy Connection that SQLAlchemy opened and still manages, so the transaction stays SQLAlchemy's.) diff --git a/migrations/v2/env.py b/migrations/v2/env.py index 20ff3e93e..d81f8cb64 100644 --- a/migrations/v2/env.py +++ b/migrations/v2/env.py @@ -43,8 +43,10 @@ def _include_application_object( def _configure(connection: Connection) -> None: - # Each Session joins the connection's transaction, and closing it leaves - # that transaction to the environment. + # Inside run_migrations_online's engine.begin(), each Session joins that + # transaction, and closing it leaves the transaction to the environment. + # On a connection passed in with no transaction open, a Session begins + # its own, and closing it rolls that transaction back. with Session(bind=connection) as session: qualify_v2_target(session, settings) context.configure( diff --git a/policyengine_api/data/orm.py b/policyengine_api/data/orm.py index f6a382c9a..5d5948638 100644 --- a/policyengine_api/data/orm.py +++ b/policyengine_api/data/orm.py @@ -1,26 +1,27 @@ -"""Canonical SQLAlchemy engine and Session configuration for API v1.""" +"""Canonical SQLAlchemy engine and Session configuration for API v1. + +Importing this module loads a ``.env`` file. Commands that must run with only +the environment they are given take their Session factories from +``policyengine_api.data.v1_sessions``, which has no import side effects. +""" from __future__ import annotations import atexit import os -from contextlib import contextmanager from dataclasses import dataclass from typing import TYPE_CHECKING from dotenv import load_dotenv from google.cloud.sql.connector import Connector, IPTypes -from sqlalchemy import Engine, create_engine, inspect -from sqlalchemy.orm import Session, sessionmaker -from sqlalchemy.pool import NullPool +from sqlalchemy import Engine, create_engine from policyengine_api.data.orm_pool_events import record_pool_events +from policyengine_api.data.v1_sessions import build_session_factory if TYPE_CHECKING: - from collections.abc import Iterator - - from sqlalchemy.engine import URL, Inspector from sqlalchemy.engine.interfaces import DBAPIConnection + from sqlalchemy.orm import Session, sessionmaker load_dotenv() @@ -70,36 +71,6 @@ def get_remote_database_config() -> dict[str, str]: } -def build_session_factory(engine: Engine) -> sessionmaker[Session]: - """Return SQLAlchemy's standard configurable Session factory.""" - return sessionmaker(bind=engine, class_=Session, expire_on_commit=False) - - -@contextmanager -def unpooled_v1_sessions(url: str | URL) -> Iterator[sessionmaker[Session]]: - """Yield v1 Session factories for one command's work on the database at ``url``. - - For commands and scripts that run once, such as the household mirror - command and the v1 schema migration. Their engine keeps no connection - pool, so no connection outlives its Session, and is disposed of on exit. - """ - engine = create_engine(url, poolclass=NullPool) - try: - yield build_session_factory(engine) - finally: - engine.dispose() - - -def v1_schema_inspector(source: Session | sessionmaker[Session]) -> Inspector: - """Return SQLAlchemy's Inspector of the v1 database a Session or factory uses. - - A Session's Inspector reads the schema inside the Session's transaction. - """ - bind = source.connection() if isinstance(source, Session) else source.kw["bind"] - inspector: Inspector = inspect(bind) - return inspector - - def _build_remote_engine() -> Engine: config = get_remote_database_config() connector = Connector( diff --git a/policyengine_api/data/v1_sessions.py b/policyengine_api/data/v1_sessions.py new file mode 100644 index 000000000..e378a67d9 --- /dev/null +++ b/policyengine_api/data/v1_sessions.py @@ -0,0 +1,54 @@ +"""API v1's Session factories for commands that run once. + +A session-factory module of rule api.data.orm-only. Importing it has no side +effects. ``policyengine_api.data.orm``, the application's module, loads a +``.env`` file when imported and imports the Cloud SQL connector and the pool's +event listeners. A command such as the v1 schema migration runs only with the +environment its deploy script sets, so it takes its Session factories from +here. ``orm`` builds its own factories with ``build_session_factory``. +""" + +from __future__ import annotations + +from contextlib import contextmanager +from typing import TYPE_CHECKING + +from sqlalchemy import create_engine, inspect +from sqlalchemy.orm import Session, sessionmaker +from sqlalchemy.pool import NullPool + +if TYPE_CHECKING: + from collections.abc import Iterator + + from sqlalchemy import Engine + from sqlalchemy.engine import URL, Inspector + + +def build_session_factory(engine: Engine) -> sessionmaker[Session]: + """Return SQLAlchemy's standard configurable Session factory.""" + return sessionmaker(bind=engine, class_=Session, expire_on_commit=False) + + +@contextmanager +def unpooled_v1_sessions(url: str | URL) -> Iterator[sessionmaker[Session]]: + """Yield v1 Session factories for one command's work on the database at ``url``. + + For commands and scripts that run once, such as the household mirror + command and the v1 schema migration. Their engine keeps no connection + pool, so no connection outlives its Session, and is disposed of on exit. + """ + engine = create_engine(url, poolclass=NullPool) + try: + yield build_session_factory(engine) + finally: + engine.dispose() + + +def v1_schema_inspector(source: Session | sessionmaker[Session]) -> Inspector: + """Return SQLAlchemy's Inspector of the v1 database a Session or factory uses. + + A Session's Inspector reads the schema inside the Session's transaction. + """ + bind = source.connection() if isinstance(source, Session) else source.kw["bind"] + inspector: Inspector = inspect(bind) + return inspector diff --git a/policyengine_api/data/v2/database.py b/policyengine_api/data/v2/database.py index 01a14fc58..cb9a0296a 100644 --- a/policyengine_api/data/v2/database.py +++ b/policyengine_api/data/v2/database.py @@ -7,9 +7,10 @@ from contextlib import contextmanager from dataclasses import dataclass from threading import Lock -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any from sqlalchemy import event, inspect +from sqlalchemy.orm import Session as OrmSession from sqlalchemy.orm import sessionmaker from sqlalchemy.pool import NullPool from sqlmodel import Session, create_engine @@ -21,7 +22,7 @@ ) if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator from sqlalchemy import Engine from sqlalchemy.engine import URL, Inspector @@ -133,6 +134,22 @@ def _read_session_factory(engine: Engine) -> sessionmaker[Session]: return factory +@contextmanager +def _unpooled_sessions( + url: str | URL, build_factory: Callable[[Engine], sessionmaker[Session]] +) -> Iterator[sessionmaker[Session]]: + """Yield ``build_factory``'s Session factories on a new engine for ``url``. + + The engine keeps no connection pool, so no connection outlives its + Session, and is disposed of on exit. + """ + engine = create_engine(url, poolclass=NullPool) + try: + yield build_factory(engine) + finally: + engine.dispose() + + @contextmanager def unpooled_v2_sessions(url: str | URL) -> Iterator[sessionmaker[Session]]: """Yield v2 Session factories for one command's work on the database at ``url``. @@ -142,11 +159,12 @@ def unpooled_v2_sessions(url: str | URL) -> Iterator[sessionmaker[Session]]: ``V2AlembicSettings.url``. Their engine keeps no connection pool, so no connection outlives its Session, and is disposed of on exit. """ - engine = create_engine(url, poolclass=NullPool) - try: - yield build_v2_session_factory(engine) - finally: - engine.dispose() + with _unpooled_sessions(url, build_v2_session_factory) as sessions: + yield sessions + + +def _build_read_only_session_factory(engine: Engine) -> sessionmaker[Session]: + return build_v2_session_factory(engine.execution_options(postgresql_readonly=True)) @contextmanager @@ -158,22 +176,18 @@ def unpooled_v2_read_only_sessions(url: str | URL) -> Iterator[sessionmaker[Sess through SQLAlchemy's ``postgresql_readonly`` option). Like ``unpooled_v2_sessions``, the engine keeps no pool. """ - engine = create_engine(url, poolclass=NullPool) - try: - yield build_v2_session_factory( - engine.execution_options(postgresql_readonly=True) - ) - finally: - engine.dispose() + with _unpooled_sessions(url, _build_read_only_session_factory) as sessions: + yield sessions -def v2_schema_inspector(source: Session | sessionmaker[Session]) -> Inspector: +def v2_schema_inspector(source: OrmSession | sessionmaker[Any]) -> Inspector: """Return SQLAlchemy's Inspector of the v2 database a Session or factory uses. - A Session's Inspector reads the schema inside the Session's transaction, - as the migration target checks need. + Any SQLAlchemy ORM Session counts as a Session, SQLModel's included. A + Session's Inspector reads the schema inside the Session's transaction, as + the migration target checks need. """ - bind = source.connection() if isinstance(source, Session) else source.kw["bind"] + bind = source.connection() if isinstance(source, OrmSession) else source.kw["bind"] inspector: Inspector = inspect(bind) return inspector diff --git a/rules/registry.toml b/rules/registry.toml index 701299723..cb24c8559 100644 --- a/rules/registry.toml +++ b/rules/registry.toml @@ -642,11 +642,14 @@ invocation = "make test" bad_fixture = "rules/fixtures/api.data.orm-only/bad_simulation_rows.py" good_fixture = "rules/fixtures/api.data.orm-only/good_simulation_rows.py" test = "tests/unit/data/test_orm_only.py::test_rule_proof_orm_only" -# Each exception names a module and, in match, the source of the one finding -# there that SQLAlchemy's ORM has no form for (category no-orm-form), or a path -# pattern the rule test doesn't read (category migration-revision). The rule -# test fails on a finding no exception names and on an exception that names -# nothing. +# Each exception names a module, in match the source of a finding there that +# SQLAlchemy's ORM has no form for and, in function, the function it is in +# (category no-orm-form), or a path pattern the rule test doesn't read +# (category migration-revision). Without a function, an entry allows its source +# anywhere in the module. Every entry outside tests/, and every entry whose +# match holds no SQL text (a bare call, a call on variables or an attribute +# read), names its function. The rule test fails on a finding no exception +# names and on an exception that names nothing. [[rule.exception]] path = "migrations/**/*.py" category = "migration-revision" @@ -655,74 +658,106 @@ reason = "migrations/ holds the Alembic environments and the revisions Alembic g [[rule.exception]] path = "tests/unit/data/orm_access_support.py" match = "mapper.local_table" +function = "_unmapped_findings" category = "no-orm-form" reason = "The rule's check for tables without a mapped class reads which table each mapped class maps. It runs no statement." [[rule.exception]] path = "tests/unit/data/orm_access_support.py" match = "class_registry.metadata.tables" +function = "_unmapped_findings" category = "no-orm-form" reason = "The rule's check for tables without a mapped class reads the tables a declarative base's metadata holds, to find those no class maps. It runs no statement." [[rule.exception]] path = "policyengine_api/data/v2/catalog/publication_staging.py" match = "session.connection()" +function = "create_staging_tables" category = "no-orm-form" -reason = "Catalog publication creates its TEMPORARY staging tables with MetaData.create_all, which takes a Connection, and streams rows with COPY ... FROM STDIN through the psycopg connection beneath the Connection. Both run on the Connection the publishing Session holds, in its transaction." +reason = "Catalog publication creates its TEMPORARY staging tables with MetaData.create_all, which takes a Connection: the Connection the publishing Session holds, in its transaction." + +[[rule.exception]] +path = "policyengine_api/data/v2/catalog/publication_staging.py" +match = "session.connection()" +function = "copy_rows" +category = "no-orm-form" +reason = "Catalog publication streams rows with COPY ... FROM STDIN through the psycopg connection beneath the Connection the publishing Session holds, in its transaction." [[rule.exception]] path = "policyengine_api/data/v2/catalog/publication_staging.py" match = "driver_connection.cursor()" +function = "copy_rows" category = "no-orm-form" reason = "COPY ... FROM STDIN has no SQLAlchemy form. Publication runs it through psycopg's Cursor.copy, on a cursor of the driver connection beneath the publishing Session's Connection." [[rule.exception]] path = "policyengine_api/data/v2/catalog/publication_statistics.py" match = "sa.text(f'ANALYZE {tables}')" +function = "analyze_catalog_tables" category = "no-orm-form" reason = "ANALYZE has no ORM form. After a publication commits, one ANALYZE refreshes the planner statistics of the catalog tables it wrote." [[rule.exception]] path = "policyengine_api/data/v2/privilege_reconciliation.py" match = "text(f'CREATE ROLE {quote(safe_identifier(role))} NOLOGIN')" +function = "create_missing_roles" category = "no-orm-form" reason = "CREATE ROLE has no SQLAlchemy form. reconcile_v2_privileges.py apply --create-missing-roles creates each missing managed role as NOLOGIN, only in the disposable test database, in the reconciliation's one transaction. The role name is checked by safe_identifier and quoted by the session's dialect." [[rule.exception]] path = "policyengine_api/data/v2/privilege_reconciliation.py" match = "text(statement)" +function = "apply_declared_privileges" category = "no-orm-form" reason = "GRANT and REVOKE have no SQLAlchemy form. apply runs the REVOKEs and GRANTs that privilege_plans' revoke_statements and grant_statements build from the declared privileges, with identifiers checked by safe_identifier and quoted by the session's dialect, in the reconciliation's one transaction." [[rule.exception]] path = "policyengine_api/data/v2/pending_revisions.py" match = "session.connection()" +function = "v2_revision_is_pending" category = "no-orm-form" reason = "Alembic's MigrationContext reads the database's current heads from its version table through a Connection. The migration qualification commands give it the Connection their Session holds, so the read runs inside the Session's READ ONLY transaction." [[rule.exception]] path = "scripts/v1_database_migration.py" match = "session.connection()" +function = "_config" +category = "no-orm-form" +reason = "Alembic's command.upgrade takes a Connection, through the Alembic config's connection attribute. The v1 schema migration gives it the Connection its Session holds, so the upgrade runs in the Session's transaction, under the MySQL named lock the Session took." + +[[rule.exception]] +path = "scripts/v1_database_migration.py" +match = "session.connection()" +function = "database_state" +category = "no-orm-form" +reason = "Alembic's MigrationContext reads the database's current heads from its version table through a Connection. The v1 schema migration gives it the Connection its Session holds, so the read runs in the Session's transaction, under the MySQL named lock the Session took." + +[[rule.exception]] +path = "scripts/v1_database_migration.py" +match = "session.connection()" +function = "metadata_differences" category = "no-orm-form" -reason = "Alembic's MigrationContext, compare_metadata and command.upgrade take a Connection. The v1 schema migration gives them the Connection its Session holds, so the version reads, the schema comparison and the upgrade run in the Session's transaction, under the MySQL named lock the Session took." +reason = "Alembic's compare_metadata compares the schema through a MigrationContext on a Connection. The v1 schema migration gives it the Connection its Session holds, so the comparison runs in the Session's transaction, under the MySQL named lock the Session took." [[rule.exception]] path = "policyengine_api/services/v2/user_types/database_connectors/reads.py" match = "session.get_bind()" +function = "acquire_user_type_change_lock" category = "no-orm-form" reason = "Reads the dialect's name, to skip PostgreSQL's advisory lock on the SQLite test databases, which have none. It runs no statement on the engine." [[rule.exception]] path = "tests/fixtures/database_sessions.py" -match = "sqlite_connection.execute(...)" +match = "sqlite_connection.execute('PRAGMA foreign_keys = ON')" category = "no-orm-form" reason = "SQLite enforces foreign keys only once a connection sets PRAGMA foreign_keys, a connection setting SQLAlchemy has no API for. The in-memory SQLite test databases set it on each connection before its first transaction." [[rule.exception]] path = "tests/fixtures/database_sessions.py" -match = "text(f'EXPLAIN {compiled}')" +match = "session.connection().exec_driver_sql(f'EXPLAIN {expanded.statement}', ...)" +function = "query_plan" category = "no-orm-form" -reason = "EXPLAIN has no SQLAlchemy form. A test that checks an index serves a lookup reads PostgreSQL's plan for the ORM statement that does the lookup." +reason = "EXPLAIN has no SQLAlchemy form. A test that checks an index serves a lookup reads PostgreSQL's plan for the ORM statement that does the lookup, compiled for the session's dialect with its in_() lists and literal_execute values written out and its parameters processed by their types. text() can't take that SQL: the psycopg dialect writes each parameter as %(name)s with a cast such as ::JSONB, and text() reads only :name parameters. So the plan is read on the Session's own Connection, in its transaction and as its role." [[rule.exception]] path = "tests/fixtures/database_sessions.py" @@ -734,7 +769,7 @@ reason = "SQLite takes its write lock at the start of a transaction only with BE path = "tests/fixtures/database_sessions.py" match = "text(f'DROP TABLE {tables}')" category = "no-orm-form" -reason = "Dropping a table has no ORM form. Route tests drop a catalog table so the route's real catalog query fails with the database's own error." +reason = "Dropping a table has no ORM form. Route tests drop a catalog table so the route's real catalog query fails with the database's own error, and the MySQL lifecycle test drops a table a revision creates, to check the migration notices it is missing." [[rule.exception]] path = "tests/fixtures/database_sessions.py" @@ -766,6 +801,27 @@ match = "text(f'GRANT {privileges} ON TABLE {table} TO {quoted_role}')" category = "no-orm-form" reason = "Grants have no ORM form. Privilege tests grant a temporary role privileges the manifest doesn't declare, to check that verification reports them." +[[rule.exception]] +path = "tests/integration/catalog_privilege_objects.py" +match = "text(f'GRANT {_privileges(privileges)} ON {on_object} TO {grantee}')" +function = "grant_on_schema_object" +category = "no-orm-form" +reason = "Grants have no ORM form. The privilege reconciliation tests grant a role privileges on a schema or a sequence, which the shared grant helper, for tables, views and materialized views, doesn't cover, to check the reconciliation reads those grants." + +[[rule.exception]] +path = "tests/integration/catalog_privilege_objects.py" +match = "text(f'ALTER DEFAULT PRIVILEGES FOR ROLE {creator} IN SCHEMA {SCHEMA} GRANT {_privileges(privileges)} ON {object_type} TO {grantee}')" +function = "alter_default_privileges" +category = "no-orm-form" +reason = "ALTER DEFAULT PRIVILEGES has no ORM form. The privilege reconciliation tests set a default ACL on the tables and sequences a role creates, PUBLIC's included, to check the reconciliation reads the default privileges." + +[[rule.exception]] +path = "tests/integration/catalog_privilege_objects.py" +match = "text(f\"CREATE {view_kind} {qualified_view} AS SELECT 1 AS id, 'label'::text AS label\")" +function = "create_view" +category = "no-orm-form" +reason = "CREATE VIEW and CREATE MATERIALIZED VIEW have no SQLAlchemy construct. The v2 schema has only tables, so the privilege reconciliation tests create a view and a materialized view of one row, to check the reconciliation reads the grants on them." + [[rule]] id = "api.legacy.removed-layers-stay-removed" category = "runtime-layers" diff --git a/scripts/process_v1_household_mirror_event.py b/scripts/process_v1_household_mirror_event.py index 45dbe3ef7..828ef3912 100755 --- a/scripts/process_v1_household_mirror_event.py +++ b/scripts/process_v1_household_mirror_event.py @@ -12,7 +12,7 @@ from sqlalchemy.engine import URL -from policyengine_api.data.orm import unpooled_v1_sessions +from policyengine_api.data.v1_sessions import unpooled_v1_sessions from policyengine_api.gcp_logging import logger from policyengine_api.services.household_mirroring import ( process_household_event_after_commit, diff --git a/scripts/rules/load.py b/scripts/rules/load.py index f47a755dd..2604f7685 100644 --- a/scripts/rules/load.py +++ b/scripts/rules/load.py @@ -296,7 +296,16 @@ def _baseline( return None -_EXCEPTION_KEYS = {"path", "reason", "expires", "match", "category", "removal", "issue"} +_EXCEPTION_KEYS = { + "path", + "reason", + "expires", + "match", + "function", + "category", + "removal", + "issue", +} def _optional_string( @@ -340,6 +349,7 @@ def _exception( category, removal, issue, + _optional_string(collector, rule_id, entry, "function", where), ) diff --git a/scripts/rules/model.py b/scripts/rules/model.py index b1f9afc96..a8e1aab28 100644 --- a/scripts/rules/model.py +++ b/scripts/rules/model.py @@ -205,7 +205,9 @@ class RuleException: """A carve-out of ``path`` from a rule; the guard fails once ``expires`` passes. ``match`` narrows the carve-out to one site in the file (a command or call - containing that text). An exception ends either on its ``expires`` review + containing that text). ``function`` narrows it further to that function, as + ``name`` or ``Class.method``, for a rule whose checker records the function + each finding is in. An exception ends either on its ``expires`` review date, tracked by ``issue``, or when its ``removal`` condition holds. ``category`` names a kind of exception a rule allows as a class, such as ``pinned-tool`` for the locked-installs rules. @@ -218,6 +220,7 @@ class RuleException: category: str | None = None removal: str | None = None issue: int | None = None + function: str | None = None @dataclass(frozen=True) diff --git a/scripts/rules/render.py b/scripts/rules/render.py index 01a017ab5..c9c2cd3ef 100644 --- a/scripts/rules/render.py +++ b/scripts/rules/render.py @@ -293,7 +293,10 @@ def _exception_summary(exception: RuleException) -> str: """Describe where an exception applies, why, and when it ends.""" site = f"`{exception.path}`" if exception.match is not None: - site += f" (`{exception.match}`)" + site += f" (`{exception.match}`" + if exception.function is not None: + site += f" in `{exception.function}`" + site += ")" if exception.category is not None: ends = f"allowed as a {exception.category}" elif exception.removal is not None: diff --git a/scripts/rules/tests/test_load.py b/scripts/rules/tests/test_load.py index 6346e8601..185af1238 100644 --- a/scripts/rules/tests/test_load.py +++ b/scripts/rules/tests/test_load.py @@ -5,6 +5,7 @@ import tomllib import unittest from datetime import date +from typing import TYPE_CHECKING from scripts.rules.load import parse from scripts.rules.model import ( @@ -20,6 +21,9 @@ ) from scripts.rules.tests.support import REGISTRY +if TYPE_CHECKING: + from collections.abc import Mapping + BOUNDARY_NODE = "tests/unit/test_boundaries.py::test_routes_have_no_sql" KNOWN_RULE_KEYS = ( "['autofix', 'baseline', 'category', 'ci', 'downgrade', 'enforcer', " @@ -204,7 +208,7 @@ class ExceptionFunctionTest(unittest.TestCase): """An exception's ``function`` narrows it to findings inside that function.""" def _parsed_exceptions( - self, exception: dict[str, object] + self, exception: Mapping[str, object] ) -> tuple[list[str], tuple[RuleException, ...]]: raw = tomllib.loads(REGISTRY) rule = {**SINGLE_TABLES_RULE, "exception": exception} diff --git a/scripts/rules/tests/test_render.py b/scripts/rules/tests/test_render.py index dbed7c2dc..fd2a6098b 100644 --- a/scripts/rules/tests/test_render.py +++ b/scripts/rules/tests/test_render.py @@ -3,6 +3,7 @@ from __future__ import annotations import unittest +from dataclasses import replace from scripts.rules.model import ( Category, @@ -12,6 +13,7 @@ Kind, Registry, Rule, + RuleException, Status, Tier, ) @@ -207,5 +209,53 @@ def test_large_graphs_are_split_into_chunks_of_rules(self) -> None: ) +class ExceptionSummaryTest(unittest.TestCase): + def _exception_lines(self, exceptions: tuple[RuleException, ...]) -> list[str]: + rule = make_rule("ex.checks.orm-only", Enforcer(Kind.NONE)) + registry = Registry( + schema_version=1, + repo="example", + categories=(Category("checks", "Checks"),), + discovery=Discovery(), + rules=(replace(rule, exceptions=exceptions),), + ) + return [ + line + for line in render_rules_md(registry).splitlines() + if line.startswith("- `ex.checks.orm-only`: exception") + ] + + def test_an_exception_names_its_match_and_function(self) -> None: + lines = self._exception_lines( + ( + RuleException( + path="pkg/store.py", + reason="GRANT has no ORM form", + match="text(statement)", + category="no-orm-form", + function="apply_declared_privileges", + ), + RuleException( + path="pkg/rows.py", + reason="TRUNCATE has no ORM form", + match="text('TRUNCATE reports')", + category="no-orm-form", + ), + ) + ) + + self.assertEqual( + lines, + [ + "- `ex.checks.orm-only`: exception for `pkg/rows.py` " + "(`text('TRUNCATE reports')`) allowed as a no-orm-form " + "(TRUNCATE has no ORM form)", + "- `ex.checks.orm-only`: exception for `pkg/store.py` " + "(`text(statement)` in `apply_declared_privileges`) allowed as a " + "no-orm-form (GRANT has no ORM form)", + ], + ) + + if __name__ == "__main__": unittest.main() diff --git a/scripts/rules/v2_layer_checks.py b/scripts/rules/v2_layer_checks.py index 5791eceb1..eb75320c4 100644 --- a/scripts/rules/v2_layer_checks.py +++ b/scripts/rules/v2_layer_checks.py @@ -36,7 +36,11 @@ ) SQL_PACKAGES = ("sqlalchemy", "sqlmodel") -DATABASE_PACKAGES = ("policyengine_api.data.orm", "policyengine_api.data.v2.database") +DATABASE_PACKAGES = ( + "policyengine_api.data.orm", + "policyengine_api.data.v1_sessions", + "policyengine_api.data.v2.database", +) SESSION_TYPES = ("sqlmodel.Session", "sqlalchemy.orm.Session") SQL_EXCEPTIONS = "sqlalchemy.exc" # What a service may import from SQLAlchemy or SQLModel: the session type, for diff --git a/scripts/v1_database_migration.py b/scripts/v1_database_migration.py index a646cc8c2..dbb73ad91 100644 --- a/scripts/v1_database_migration.py +++ b/scripts/v1_database_migration.py @@ -22,8 +22,8 @@ from sqlalchemy.engine import URL from policyengine_api.constants import REPO -from policyengine_api.data.orm import unpooled_v1_sessions, v1_schema_inspector from policyengine_api.data.v1_models import V1Base +from policyengine_api.data.v1_sessions import unpooled_v1_sessions, v1_schema_inspector if TYPE_CHECKING: from sqlalchemy.orm import Session diff --git a/tests/fixtures/database_sessions.py b/tests/fixtures/database_sessions.py index b7cb79835..9a91f44b7 100644 --- a/tests/fixtures/database_sessions.py +++ b/tests/fixtures/database_sessions.py @@ -8,12 +8,12 @@ how to write each kind of statement, under "Database statements through the ORM". -The statements here that the ORM can't express (``TRUNCATE``, ``CREATE ROLE``, -``DROP OWNED BY``, ``DROP ROLE``, ``GRANT`` and SQLite's ``foreign_keys`` -setting) are each a ``no-orm-form`` exception of the rule in -rules/registry.toml. Roles and settings inside a transaction need none: -``act_as`` and ``act_as_owner`` call Postgres's ``set_config``, which is what -``SET LOCAL ROLE`` does. +The statements here that the ORM can't express (``TRUNCATE``, ``DROP TABLE``, +``EXPLAIN``, ``CREATE ROLE``, ``DROP OWNED BY``, ``DROP ROLE``, ``GRANT``, +SQLite's ``foreign_keys`` setting and ``BEGIN IMMEDIATE``) are each a +``no-orm-form`` exception of the rule in rules/registry.toml. Roles and +settings inside a transaction need none: ``act_as`` and ``act_as_owner`` call +Postgres's ``set_config``, which is what ``SET LOCAL ROLE`` does. """ from __future__ import annotations @@ -40,14 +40,14 @@ text, true, ) -from sqlalchemy.dialects import postgresql from sqlalchemy.engine import make_url from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, sessionmaker from sqlalchemy.orm import Session as OrmSession from sqlalchemy.pool import NullPool, StaticPool +from sqlalchemy.sql.compiler import SQLCompiler -from policyengine_api.data.orm import build_session_factory from policyengine_api.data.v1_models import Policy, V1Base +from policyengine_api.data.v1_sessions import build_session_factory from policyengine_api.data.v2.database import build_v2_session_factory from policyengine_api.data.v2.models import V2_METADATA from policyengine_api.data.v2.privilege_reconciliation import ( @@ -63,6 +63,7 @@ from sqlalchemy.engine import URL, Connection, Inspector from sqlalchemy.orm import registry from sqlalchemy.sql import ClauseElement + from sqlalchemy.sql.compiler import ExpandedState from sqlmodel import Session from policyengine_api.data.v2.privilege_plans import ReconciliationPlan @@ -70,7 +71,8 @@ # A role name SET ROLE and a connection's startup options take as it is. PLAIN_ROLE_NAME = re.compile(r"[a-z_][a-z0-9_]*") -# The role that means "no role": the session acts as the user it logged in as. +# The role that means "no role" (SET ROLE NONE): the session acts as the user it +# logged in as, whatever role its connection started with. NO_ROLE = "none" IN_MEMORY_SQLITE_URL = "sqlite://" @@ -119,8 +121,9 @@ def v2_role_sessions(database_url: str, role: str) -> Iterator[sessionmaker[Sess Each connection starts with ``role`` as its role (PostgreSQL's ``role`` startup option), so every statement is checked against that role's privileges, as in staging and production. ``act_as_owner`` would still - switch a transaction to the database's owner, so a test acting as a role - uses these factories, or ``act_as`` on the owner's. + switch a transaction to the user the connection logged in as, the + database's owner, so a test acting as a role uses these factories, or + ``act_as`` on the owner's. """ engine = create_engine( database_url, @@ -288,13 +291,15 @@ def serve_v1_sessions( """Make API v1's own Session factory open ``sessions``' connections. ``policyengine_api.data.orm.get_v1_session_factory`` then builds its - factory on ``sessions``' engine; ``monkeypatch`` undoes it after the test. + factory on ``sessions``' engine and keeps it. ``monkeypatch`` restores + both the engine and the kept factory after the test, so the factory the + test built doesn't outlive it. """ from policyengine_api.data import orm engine = sessions.kw["bind"] monkeypatch.setattr(orm, "_v1_engine", lambda: engine) - orm.clear_v1_session_factories() + monkeypatch.setattr(orm._cloud_sql_state, "session_factory", None) class _LocalMySqlConnector: @@ -369,36 +374,71 @@ def act_as(session: OrmSession, role: str) -> None: def act_as_owner(session: OrmSession) -> None: - """Act as the database's owner again, for the rest of the transaction.""" + """Act as the user the session logged in as, for the rest of the transaction. + + It sets the role to ``none`` (``SET LOCAL ROLE NONE``), not back to the + connection's starting role as ``RESET ROLE`` would. Every test connection + logs in as the database's owner, so even a role's Session acts as the + owner afterwards. + """ _set_transaction_role(session, NO_ROLE) def schema_inspector(source: OrmSession | sessionmaker[Any]) -> Inspector: """Return SQLAlchemy's Inspector of the database a Session or factory uses. - A Session's Inspector reads the schema inside its transaction. Anything - else, such as the Engine a test not yet moved to Sessions holds, is - inspected as it is. + A Session's Inspector reads the schema inside its transaction; a factory's + reads it on a connection of its own. """ - bind: Any = source - if isinstance(source, OrmSession): - bind = source.connection() - elif isinstance(source, sessionmaker): - bind = source.kw["bind"] + bind = source.connection() if isinstance(source, OrmSession) else source.kw["bind"] inspector: Inspector = inspect(bind) return inspector +def _parameters_as_sent( + compiled: SQLCompiler, expanded: ExpandedState +) -> dict[str, Any]: + """Return a statement's parameters as executing it would send them. + + Each value goes through its type's bind processor for the dialect, as a + JSON value becomes the driver's JSON. ``expanded`` gives the processors of + the parameters an ``in_()`` list expands into. + """ + dialect = compiled.dialect + processors = { + compiled.escaped_bind_names.get(name, name): processor + for name, bind in compiled.binds.items() + if (processor := bind.type.dialect_impl(dialect).bind_processor(dialect)) + } + processors.update(expanded.processors) + return { + name: processors[name](value) if name in processors else value + for name, value in expanded.parameters.items() + } + + def query_plan(session: OrmSession, statement: ClauseElement) -> str: """Return PostgreSQL's plan for an ORM statement (EXPLAIN), its rows joined. A test that checks an index serves a lookup reads the plan of the ORM statement that does the lookup, in the session's transaction and as the - session's role. + session's role. The statement is compiled for the session's own dialect + and sent as executing it would send it: an ``in_()`` list and a + ``literal_execute`` value are written into the SQL, and each parameter + goes through its type's bind processor, such as JSON's. """ - # The named paramstyle gives text() the :name parameters it parses. - compiled = statement.compile(dialect=postgresql.dialect(paramstyle="named")) - plan_rows = session.execute(text(f"EXPLAIN {compiled}"), compiled.params).scalars() + compiled = statement.compile(dialect=session.get_bind().dialect) + if not isinstance(compiled, SQLCompiler): + msg = f"EXPLAIN needs a SQL statement, not {type(statement).__name__}" + raise TypeError(msg) + expanded = compiled.construct_expanded_state() + plan_rows = ( + session.connection() + .exec_driver_sql( + f"EXPLAIN {expanded.statement}", _parameters_as_sent(compiled, expanded) + ) + .scalars() + ) return "\n".join(plan_rows) @@ -464,7 +504,11 @@ def record(connection: Any, *_arguments: object) -> None: def delete_all_rows(session: OrmSession, mapped_classes: registry) -> None: - """Delete every row of every table the registry's mapped classes map.""" + """Delete every row of every table the registry's mapped classes map. + + It deletes the tables in no set order, so it suits a registry whose + tables have no foreign keys between them, such as API v1's. + """ for mapper in mapped_classes.mappers: session.execute(delete(mapper.class_)) diff --git a/tests/fixtures/integration/alembic_v2.py b/tests/fixtures/integration/alembic_v2.py index 8f55bf235..b15cd1d7d 100644 --- a/tests/fixtures/integration/alembic_v2.py +++ b/tests/fixtures/integration/alembic_v2.py @@ -1,22 +1,30 @@ """The disposable Postgres target and Alembic config of the v2 lifecycle tests.""" -from typing import Any +from __future__ import annotations + +from typing import TYPE_CHECKING, Any from alembic.config import Config -from sqlalchemy.engine.interfaces import ReflectedColumn from policyengine_api.constants import REPO from tests.fixtures.database_sessions import schema_inspector +if TYPE_CHECKING: + from sqlalchemy.engine.interfaces import ReflectedColumn + from sqlalchemy.orm import Session, sessionmaker + def alembic_v2_config() -> Config: return Config(str(REPO / "alembic-v2.ini")) -def table_columns(source: Any, table_name: str) -> dict[str, ReflectedColumn]: +def table_columns( + source: Session | sessionmaker[Any], table_name: str +) -> dict[str, ReflectedColumn]: """Return a public table's columns by name, as the database describes them. - ``source`` is a Session or a Session factory (see ``schema_inspector``). + ``source`` is a Session, read inside its transaction, or a Session factory + (see ``schema_inspector``). """ return { column["name"]: column diff --git a/tests/fixtures/v2_metadata_service.py b/tests/fixtures/v2_metadata_service.py index a69943645..9c1126a35 100644 --- a/tests/fixtures/v2_metadata_service.py +++ b/tests/fixtures/v2_metadata_service.py @@ -29,6 +29,10 @@ def catalog_sessions() -> Iterator[sessionmaker[Session]]: @pytest.fixture def catalog_session(catalog_sessions: sessionmaker[Session]) -> Iterator[Session]: - """Return a Session of the catalog database, closed after the test.""" - with catalog_sessions() as session: + """Return a Session of the catalog database, closed after the test. + + A commit expires its rows, as a plain SQLModel ``Session`` does, so a read + after a commit sees the stored values, not the ones the Session held. + """ + with catalog_sessions(expire_on_commit=True) as session: yield session diff --git a/tests/integration/alembic_version_rows.py b/tests/integration/alembic_version_rows.py index aa09b0c4e..87a266a86 100644 --- a/tests/integration/alembic_version_rows.py +++ b/tests/integration/alembic_version_rows.py @@ -14,7 +14,11 @@ from sqlalchemy import select from sqlmodel import col -from policyengine_api.data.v2.alembic_revision import AlembicRevision +from policyengine_api.data.v2.alembic_revision import ( + ALEMBIC_REVISION_TABLE, + AlembicRevision, +) +from tests.fixtures.database_sessions import schema_inspector if TYPE_CHECKING: from sqlalchemy.orm import sessionmaker @@ -23,10 +27,13 @@ def current_revision(sessions: sessionmaker[Any]) -> str | None: """Return the revision the database is at, or None if it records none. - It fails, as Alembic's ``MigrationContext.get_current_revision`` does, when - the database records more than one revision. + As Alembic's ``MigrationContext.get_current_revision`` does, a database + with no ``alembic_version`` table, or an empty one, is at no revision, and + one that records more than one revision fails. """ with sessions() as session: + if not schema_inspector(session).has_table(ALEMBIC_REVISION_TABLE): + return None revision: str | None = session.scalars( select(col(AlembicRevision.version_num)) ).one_or_none() diff --git a/tests/integration/catalog_privilege_objects.py b/tests/integration/catalog_privilege_objects.py new file mode 100644 index 000000000..278b1dddc --- /dev/null +++ b/tests/integration/catalog_privilege_objects.py @@ -0,0 +1,159 @@ +"""PostgreSQL objects and grants that the v2 privilege reconciliation reads. + +The reconciliation reads grants on tables, views, materialized views and +sequences, grants on their columns, and default privileges (set by ``ALTER +DEFAULT PRIVILEGES``). The v2 schema has only tables, so tests make the rest +here: a view and a materialized view, mapped by ``PrivilegeTestView`` and +``PrivilegeTestMaterializedView`` so that the shared ``grant`` grants on them, +and sequences. The ORM has no form for these statements, so each helper that +writes SQL text is a ``no-orm-form`` exception of rule api.data.orm-only in +rules/registry.toml: + +- ``grant_on_schema_object``: GRANT on a schema or a sequence, which the shared + ``grant`` (tables, views and materialized views) doesn't cover; +- ``alter_default_privileges``: ALTER DEFAULT PRIVILEGES; +- ``create_view``: CREATE VIEW and CREATE MATERIALIZED VIEW, which SQLAlchemy + has no construct for. + +A test creates the objects as a temporary role, given CREATE on the schema. +``drop_role`` (``DROP OWNED BY``) then drops them, with the role's default +privileges. +""" + +from __future__ import annotations + +import re +from typing import TYPE_CHECKING, Literal + +from sqlalchemy import Sequence, text +from sqlalchemy.orm import registry +from sqlalchemy.schema import CreateSequence +from sqlmodel import Field, SQLModel + +from tests.fixtures.database_sessions import schema_inspector + +if TYPE_CHECKING: + from sqlalchemy.orm import Session + +SCHEMA = "public" +# The grantee that stands for every role, as GRANT and aclexplode name it. +PUBLIC_GRANTEE = "PUBLIC" +# A name the helpers write into a statement: lowercase letters, digits and _. +PLAIN_NAME = re.compile(r"[a-z_][a-z0-9_]*") +# A privilege list such as "SELECT", "USAGE, SELECT" or "CREATE". +PRIVILEGE_LIST = re.compile(r"[A-Z]+(?:, [A-Z]+)*") + +SchemaObjectKind = Literal["SCHEMA", "SEQUENCE"] +DefaultObjectType = Literal["TABLES", "SEQUENCES"] + + +class _PrivilegeTestRelation(SQLModel, registry=registry()): + """The base of the test views' classes, on a registry of their own.""" + + +class PrivilegeTestView(_PrivilegeTestRelation, table=True): + """The view ``create_view`` creates, of one row.""" + + __tablename__ = "privilege_test_view" + id: int = Field(primary_key=True) + label: str + + +class PrivilegeTestMaterializedView(_PrivilegeTestRelation, table=True): + """The materialized view ``create_view`` creates, of one row.""" + + __tablename__ = "privilege_test_materialized_view" + id: int = Field(primary_key=True) + label: str + + +def _plain(name: str) -> str: + if not PLAIN_NAME.fullmatch(name): + msg = f"names here are lowercase letters, digits and _: {name!r}" + raise ValueError(msg) + return name + + +def _quoted(session: Session, name: str) -> str: + quote = schema_inspector(session).dialect.identifier_preparer.quote + quoted: str = quote(_plain(name)) + return quoted + + +def _grantee(session: Session, role: str) -> str: + return PUBLIC_GRANTEE if role == PUBLIC_GRANTEE else _quoted(session, role) + + +def _privileges(privileges: str) -> str: + if not PRIVILEGE_LIST.fullmatch(privileges): + msg = f"not a privilege list: {privileges!r}" + raise ValueError(msg) + return privileges + + +def grant_on_schema_object( + session: Session, + privileges: str, + *, + object_kind: SchemaObjectKind, + name: str, + to: str, +) -> None: + """Grant ``privileges`` on a schema, or a sequence in ``public``, to a role. + + ``to`` may be ``PUBLIC_GRANTEE``. For tables and views, use the shared + ``grant``. + """ + if object_kind == "SCHEMA": + on_object = f"SCHEMA {_quoted(session, name)}" + else: + on_object = f"SEQUENCE {SCHEMA}.{_quoted(session, name)}" + grantee = _grantee(session, to) + session.execute( + text(f"GRANT {_privileges(privileges)} ON {on_object} TO {grantee}") + ) + + +def alter_default_privileges( + session: Session, + *, + creating_role: str, + privileges: str, + object_type: DefaultObjectType, + to: str, +) -> None: + """Give ``to`` the privileges on what ``creating_role`` creates in ``public``. + + ``to`` may be ``PUBLIC_GRANTEE``. + """ + creator = _quoted(session, creating_role) + grantee = _grantee(session, to) + session.execute( + text( + f"ALTER DEFAULT PRIVILEGES FOR ROLE {creator} IN SCHEMA {SCHEMA} " + f"GRANT {_privileges(privileges)} ON {object_type} TO {grantee}" + ) + ) + + +def create_view( + session: Session, + view: type[PrivilegeTestView | PrivilegeTestMaterializedView], +) -> None: + """Create a test view of one row, ``id`` 1 and ``label`` text. + + ``PrivilegeTestMaterializedView`` is created as a materialized view. + """ + view_kind = "MATERIALIZED VIEW" if view is PrivilegeTestMaterializedView else "VIEW" + qualified_view = f"{SCHEMA}.{_quoted(session, view.__tablename__)}" + session.execute( + text( + f"CREATE {view_kind} {qualified_view} " + "AS SELECT 1 AS id, 'label'::text AS label" + ) + ) + + +def create_sequence(session: Session, name: str) -> None: + """Create the sequence ``public.``.""" + session.execute(CreateSequence(Sequence(_plain(name), schema=SCHEMA))) diff --git a/tests/integration/catalog_publication_support.py b/tests/integration/catalog_publication_support.py index 1c9459f29..f9a534e5e 100644 --- a/tests/integration/catalog_publication_support.py +++ b/tests/integration/catalog_publication_support.py @@ -4,6 +4,8 @@ empties its catalog before and after a test. ``row_counts`` and ``stored_identifiers`` read tables through their mapped classes, so a test can check that a publication added, kept or removed exactly the rows it should. +``clear_format_2_fields`` makes stored versions look as if published before +catalog format 2. """ from __future__ import annotations @@ -14,7 +16,7 @@ from alembic import command from alembic.config import Config -from sqlalchemy import func, select +from sqlalchemy import func, null, select, update from sqlmodel import col from policyengine_api.data.v2.models import ( @@ -32,6 +34,7 @@ if TYPE_CHECKING: from collections.abc import Iterator, Mapping + from sqlalchemy import ColumnElement, Update from sqlalchemy.orm import sessionmaker from sqlmodel import Session @@ -95,3 +98,39 @@ def stored_identifiers( ) for table_name, model in models.items() } + + +def clear_version_format_2_fields(*conditions: ColumnElement[bool]) -> Update: + """Build an UPDATE of the versions that meet ``conditions``, or of every one. + + It clears their catalog format 2 fields, so they look as if published + before format 2. The JSON columns get SQL NULL (``null()``), not JSON's + null. + """ + return ( + update(TaxBenefitModelVersion) + .where(*conditions) + .values(catalog_format=None, entities=null(), basic_inputs=null()) + ) + + +def clear_format_2_fields(session: Session) -> None: + """Make every stored version look as if published before catalog format 2. + + Clears the versions' format 2 fields, and those of their variables and + parameters, in the Session's transaction. + """ + session.execute(clear_version_format_2_fields()) + session.execute( + update(Variable).values( + is_input_variable=None, + hidden_input=None, + module_name=None, + adds_parameter_path=None, + subtracts_parameter_path=None, + enum_values=null(), + unit=None, + definition_period=None, + ) + ) + session.execute(update(Parameter).values(economy=None, household=None)) diff --git a/tests/integration/privilege_statements.py b/tests/integration/privilege_statements.py new file mode 100644 index 000000000..1aa39ef88 --- /dev/null +++ b/tests/integration/privilege_statements.py @@ -0,0 +1,187 @@ +"""Statements the v2 privilege tests send, built to name exactly their columns. + +An ORM ``update`` of a v2 model also sets ``updated_at`` (its ``onupdate``), +and an ORM ``insert`` also writes the model's Python-side defaults, such as +``created_at``. A role that may not write those columns is refused because of +them, whatever it may do with the column a test names. A refusal sent through +a model therefore proves the role is refused the named column only where the +role may write ``updated_at`` and the defaults. + +The classes here map only the columns the refusal tests name, on a registry +of their own, with no ``onupdate`` and no defaults. A statement through one +of them sends exactly the columns it names, so a refusal fails only for those +columns. Each class maps one table, with the columns of every test that +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. +""" + +# No ``from __future__ import annotations``: SQLAlchemy reads the classes' +# ``Mapped`` annotations when it maps them, so their names stay imported at +# runtime. +from typing import Any +from uuid import UUID + +from sqlalchemy import ColumnElement, Update, bindparam, update +from sqlalchemy.orm import Mapped, class_mapper, mapped_column, registry +from sqlalchemy.types import TypeEngine +from sqlmodel import SQLModel + +from policyengine_api.data.v2.models import ( + BudgetWindowRun, + CliffImpact, + ReportRun, + Simulation, + WithheldAreaCode, +) + + +def _type_of(model: type[SQLModel], column_name: str) -> TypeEngine[Any]: + """Return a copy of the type the model gives a column, such as its enum type.""" + column_type: TypeEngine[Any] = class_mapper(model).columns[column_name].type + return column_type.copy() + + +named_column_tables = registry() + + +@named_column_tables.mapped +class SimulationColumns: + """A simulation's key, and the columns of a new economy simulation.""" + + __tablename__ = "simulations" + + id: Mapped[UUID] = mapped_column(primary_key=True) + definition_key: Mapped[str | None] + simulation_type: Mapped[str] = mapped_column( + _type_of(Simulation, "simulation_type") + ) + dataset_id: Mapped[UUID | None] + tax_benefit_model_version_id: Mapped[UUID] + + +@named_column_tables.mapped +class ReportColumns: + """A report's key version.""" + + __tablename__ = "reports" + + id: Mapped[UUID] = mapped_column(primary_key=True) + key_version: Mapped[int | None] + + +@named_column_tables.mapped +class PolicyColumns: + """A policy's content hash.""" + + __tablename__ = "policies" + + id: Mapped[UUID] = mapped_column(primary_key=True) + content_hash: Mapped[str] + + +@named_column_tables.mapped +class HouseholdColumns: + """A household's content hash.""" + + __tablename__ = "households" + + id: Mapped[UUID] = mapped_column(primary_key=True) + content_hash: Mapped[str] + + +@named_column_tables.mapped +class CliffImpactColumns: + """A new cliff calculation's columns, and its cliff gap.""" + + __tablename__ = "cliff_impacts" + + id: Mapped[UUID] = mapped_column(primary_key=True) + simulation_run_id: Mapped[UUID] + status: Mapped[str] = mapped_column(_type_of(CliffImpact, "status")) + cliff_gap: Mapped[float | None] + + +@named_column_tables.mapped +class PovertyColumns: + """A new poverty result's columns, without its values.""" + + __tablename__ = "poverty" + + id: Mapped[UUID] = mapped_column(primary_key=True) + simulation_run_id: Mapped[UUID] + poverty_type: Mapped[str] + entity: Mapped[str] + + +@named_column_tables.mapped +class LaborSupplyDecileResponseColumns: + """A new labour supply decile result's columns, without its values.""" + + __tablename__ = "labor_supply_decile_responses" + + id: Mapped[UUID] = mapped_column(primary_key=True) + report_run_id: Mapped[UUID] + decile: Mapped[int] + + +@named_column_tables.mapped +class BudgetWindowRunColumns: + """A new budget-window run's columns.""" + + __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")) + recalculate: Mapped[bool] + status: Mapped[str] = mapped_column(_type_of(BudgetWindowRun, "status")) + + +@named_column_tables.mapped +class ReportRunColumns: + """A new report run's columns.""" + + __tablename__ = "report_runs" + + id: Mapped[UUID] = mapped_column(primary_key=True) + report_id: Mapped[UUID] + baseline_simulation_run_id: Mapped[UUID] + 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")) + + +@named_column_tables.mapped +class WithheldAreaCodeColumns: + """A new withheld area code's columns.""" + + __tablename__ = "withheld_area_codes" + + id: Mapped[UUID] = mapped_column(primary_key=True) + report_run_id: Mapped[UUID] + baseline_simulation_run_id: Mapped[UUID] + reform_simulation_run_id: Mapped[UUID] + area_type: Mapped[str] = mapped_column(_type_of(WithheldAreaCode, "area_type")) + code: Mapped[str] + + +def update_row(model: type[Any], row_id: object, **values: object) -> Update: + """Build an UPDATE of the model's row with ID ``row_id``, setting ``values``.""" + return update(model).where(model.id == row_id).values(**values) + + +def unfailed(status: Any, failed_status: str) -> ColumnElement[bool]: + """Return ``status <> 'failed'``, with the failed status written as a literal. + + PostgreSQL matches an ``ON CONFLICT`` condition to a partial unique index's + condition when it plans the statement. Once psycopg prepares a statement, + after five runs on one connection, PostgreSQL plans it without its + parameters' values, so a status sent as a parameter matches no index and + the INSERT fails. + """ + condition: ColumnElement[bool] = status != bindparam( + "failed_status", failed_status, literal_execute=True + ) + return condition diff --git a/tests/integration/test_alembic_mysql_lifecycle.py b/tests/integration/test_alembic_mysql_lifecycle.py index d58833d23..12fc0b1f4 100644 --- a/tests/integration/test_alembic_mysql_lifecycle.py +++ b/tests/integration/test_alembic_mysql_lifecycle.py @@ -11,12 +11,12 @@ from sqlalchemy.orm import Mapped, mapped_column, registry from policyengine_api.constants import REPO -from policyengine_api.data.orm import v1_schema_inspector from policyengine_api.data.v1_models import ( Household, HouseholdMirrorEvent, Policy, ) +from policyengine_api.data.v1_sessions import v1_schema_inspector from policyengine_api.services.household_service import HouseholdService from policyengine_api.services.policy_service import PolicyService from scripts.v1_database_migration import ( diff --git a/tests/integration/test_alembic_v2_cliff_impacts.py b/tests/integration/test_alembic_v2_cliff_impacts.py index 3eb18f8a4..b488d3684 100644 --- a/tests/integration/test_alembic_v2_cliff_impacts.py +++ b/tests/integration/test_alembic_v2_cliff_impacts.py @@ -15,7 +15,7 @@ import pytest from alembic import command -from sqlalchemy import delete, func, literal, select, update +from sqlalchemy import delete, func, select, update from sqlalchemy.dialects import postgresql from sqlalchemy.dialects.postgresql.base import PGInspector from sqlalchemy.exc import IntegrityError @@ -29,6 +29,7 @@ ) from tests.fixtures.database_sessions import schema_inspector from tests.fixtures.integration.alembic_v2 import alembic_v2_config, table_columns +from tests.integration.privilege_statements import unfailed from tests.integration.simulation_rows import ( RUN_VERSIONS, add_row, @@ -248,19 +249,15 @@ def _start_cliff_calculation(session: Session, run_id: UUID) -> UUID | None: This is what a request starting a run's cliff calculation inserts (INSERT ... ON CONFLICT DO NOTHING RETURNING id): the conflict target - names the partial unique index's whole condition, ``status <> 'failed'``. - The status is written into the statement as a literal: PostgreSQL matches - the condition to the index when it plans the statement, so a parameter - there fails once psycopg prepares the statement, after five runs on one - connection, and PostgreSQL plans it without the parameter's value. + names the partial unique index's whole condition, ``status <> 'failed'``, + with the status written into the statement as a literal (``unfailed``). """ - failed_status = literal(SimulationStatus.FAILED, literal_execute=True) start_calculation = ( postgresql.insert(CliffImpact) .values(id=uuid4(), simulation_run_id=run_id, status=SimulationStatus.PENDING) .on_conflict_do_nothing( index_elements=["simulation_run_id"], - index_where=col(CliffImpact.status) != failed_status, + index_where=unfailed(col(CliffImpact.status), SimulationStatus.FAILED), ) .returning(col(CliffImpact.id)) ) diff --git a/tests/integration/test_alembic_v2_lifecycle.py b/tests/integration/test_alembic_v2_lifecycle.py index beacbbab5..494c4a170 100644 --- a/tests/integration/test_alembic_v2_lifecycle.py +++ b/tests/integration/test_alembic_v2_lifecycle.py @@ -24,13 +24,13 @@ from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column from sqlmodel import col -from sqlmodel.main import default_registry from policyengine_api.data.v2.migration_target import ( V2_ALEMBIC_HEAD_REVISION, V2MigrationTargetError, ) from policyengine_api.data.v2.models import ( + V2_TABLE_NAMES, Country, Household, Report, @@ -54,6 +54,7 @@ ALEMBIC_VERSION_TABLE, assert_revision_serves_previous_revision, ) +from tests.integration.alembic_version_rows import current_revision from tests.integration.simulation_rows import ( RUN_VERSIONS, PublicApiRows, @@ -79,10 +80,6 @@ # The catalog format 2 revision, the parent of the area impact coordinate removal. CATALOG_FORMAT_2_REVISION = "f5c1d9b4685b" AREA_IMPACT_COORDINATE_REVISION = "e86f19a6c4da" -# Every table the v2 models map, which are the tables of V2_METADATA. -V2_TABLE_NAMES = frozenset( - mapper.class_.__tablename__ for mapper in default_registry.mappers -) AREA_IMPACT_TABLES = ("constituency_impacts", "local_authority_impacts") MAP_COORDINATE_COLUMNS = ("x", "y") @@ -95,18 +92,6 @@ def _existing_enum(type_name: str) -> postgresql.ENUM: return postgresql.ENUM(name=type_name, create_type=False) -class AlembicVersionBase(DeclarativeBase): - """The declarative base of Alembic's version table.""" - - -class AlembicVersion(AlembicVersionBase): - """The row in which Alembic records the database's revision.""" - - __tablename__ = ALEMBIC_VERSION_TABLE - - version_num: Mapped[str] = mapped_column(sa.String(32), primary_key=True) - - class BaselineBase(DeclarativeBase): """The declarative base of tables as the baseline revision created them.""" @@ -262,22 +247,6 @@ class UnreviewedRuntimeTable(UnreviewedTableBase): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=False) -def _current_revision(sessions: sessionmaker[Session]) -> str | None: - """Return the revision Alembic records, or ``None`` when it records none. - - As Alembic's ``MigrationContext.get_current_revision`` does, a database - with no version table, or an empty one, is at no revision. - """ - if ALEMBIC_VERSION_TABLE not in schema_inspector(sessions).get_table_names( - schema="public" - ): - return None - with sessions() as session: - revisions = session.scalars(select(AlembicVersion.version_num)).all() - assert len(revisions) <= 1, revisions - return revisions[0] if revisions else None - - def _assert_head(sessions: sessionmaker[Session]) -> None: """Check the database is at head with exactly the v2 tables and its indexes. @@ -287,7 +256,7 @@ def _assert_head(sessions: sessionmaker[Session]) -> None: assert set(schema_inspector(sessions).get_table_names(schema="public")) == ( V2_TABLE_NAMES | {ALEMBIC_VERSION_TABLE} ) - assert _current_revision(sessions) == V2_ALEMBIC_HEAD_REVISION + assert current_revision(sessions) == V2_ALEMBIC_HEAD_REVISION with sessions() as session: model_count = session.scalar( select(func.count()) @@ -455,7 +424,7 @@ def _upgrade_and_assert_head(config: Config, sessions: sessionmaker[Session]) -> def _assert_revision(sessions: sessionmaker[Session], revision: str) -> None: - assert _current_revision(sessions) == revision + assert current_revision(sessions) == revision def _enum_type_names(sessions: sessionmaker[Session]) -> set[str]: @@ -472,7 +441,7 @@ def _assert_revision_without_enum_types( ``enum_name_pattern`` is a regular expression the whole name must match. """ - assert _current_revision(sessions) == revision + assert current_revision(sessions) == revision matching_enum_types = sorted( type_name for type_name in _enum_type_names(sessions) @@ -817,7 +786,7 @@ def test_upgrade_to_head_validates_the_resulting_schema_against_metadata( ): command.upgrade(config, "head") - assert _current_revision(v2_owner_sessions) is None + assert current_revision(v2_owner_sessions) is None finally: with v2_owner_sessions.begin() as session: drop_registry_tables(session, UnreviewedTableBase.registry) diff --git a/tests/integration/test_alembic_v2_simulation_runs.py b/tests/integration/test_alembic_v2_simulation_runs.py index 48004685f..c1a7db391 100644 --- a/tests/integration/test_alembic_v2_simulation_runs.py +++ b/tests/integration/test_alembic_v2_simulation_runs.py @@ -5,12 +5,12 @@ reform simulation runs; keys every result table by run; types a report run's cliff impact and labour supply; adds the budget-window tables; gives household jobs one household, one year and one policy; and adds the economy output's -fields that had no column. The foreign keys from those tables to the Public -API's tables stay, and the new columns that name the Public API's rows get -keys too. It changes no other table. The previous Public API revision keeps -working while it is deployed: its roles can't read or write any table it -changes, except the catalog writer, which counts the rows of simulations, -reports and report_runs. +fields that had no column. The foreign keys from those tables to API v1's +tables stay, and the new columns that name API v1's rows get keys too. It +changes no other table. The previous API v1 revision keeps working while it +is deployed: its roles can't read or write any table it changes, except the +catalog writer, which counts the rows of simulations, reports and +report_runs. """ from __future__ import annotations @@ -87,7 +87,7 @@ "simulations", } ) -# The tables the simulation service and its Modal workers write; the Public API +# The tables the simulation service and its Modal workers write; API v1 # writes every other table. withheld_area_codes and cliff_impacts came in later # revisions. SIMULATION_SIDE_TABLES = ( @@ -95,7 +95,7 @@ | NEW_TABLES | {"aggregates", "change_aggregates", "withheld_area_codes", "cliff_impacts"} ) -# The foreign keys from the simulation service's tables to the Public API's +# The foreign keys from the simulation service's tables to API v1's # rows, with their delete rules. PUBLIC_API_FOREIGN_KEYS = { ("simulations", "dataset_id"): ("datasets", "RESTRICT"), diff --git a/tests/integration/test_database_sessions.py b/tests/integration/test_database_sessions.py index dd269c09e..c4b41f3cb 100644 --- a/tests/integration/test_database_sessions.py +++ b/tests/integration/test_database_sessions.py @@ -15,7 +15,7 @@ from sqlalchemy.exc import DBAPIError from sqlmodel import col -from policyengine_api.data.orm import unpooled_v1_sessions, v1_schema_inspector +from policyengine_api.data.v1_sessions import unpooled_v1_sessions, v1_schema_inspector from policyengine_api.data.v2.database import ( unpooled_v2_read_only_sessions, unpooled_v2_sessions, diff --git a/tests/integration/test_v1_schema_metadata_compatibility.py b/tests/integration/test_v1_schema_metadata_compatibility.py index 10ede04df..7cc783fc1 100644 --- a/tests/integration/test_v1_schema_metadata_compatibility.py +++ b/tests/integration/test_v1_schema_metadata_compatibility.py @@ -4,7 +4,7 @@ import pytest -from policyengine_api.data.orm import unpooled_v1_sessions +from policyengine_api.data.v1_sessions import unpooled_v1_sessions from scripts.v1_database_migration import metadata_differences diff --git a/tests/integration/test_v2_budget_window_report_creation.py b/tests/integration/test_v2_budget_window_report_creation.py index cf62a1d16..b359c92b7 100644 --- a/tests/integration/test_v2_budget_window_report_creation.py +++ b/tests/integration/test_v2_budget_window_report_creation.py @@ -4,7 +4,7 @@ simulation service creates for a budget window (the report with its first year's simulations, its budget-window run, and a pending report run per year under that year's simulations) and answers with the report's and -window run's IDs. The routes run as the Public API's runtime +window run's IDs. The routes run as API v1's runtime role, checking the country and policies and reading the window back. """ diff --git a/tests/integration/test_v2_budget_window_report_reads.py b/tests/integration/test_v2_budget_window_report_reads.py index 01be7baf1..3f3ed6b01 100644 --- a/tests/integration/test_v2_budget_window_report_reads.py +++ b/tests/integration/test_v2_budget_window_report_reads.py @@ -2,7 +2,7 @@ A budget window's calculation is a ``budget_window_runs`` row, and each year of it a report run naming that row and its year, as the simulation service -creates them. The routes run as the Public API's runtime role, so the tests +creates them. The routes run as API v1's runtime role, so the tests prove the role's declared privileges cover every read (rule ``api.v2.runtime-privileges-tested-as-runtime-role``). """ diff --git a/tests/integration/test_v2_catalog_publication.py b/tests/integration/test_v2_catalog_publication.py index c2e5c9e5d..bd424c34f 100644 --- a/tests/integration/test_v2_catalog_publication.py +++ b/tests/integration/test_v2_catalog_publication.py @@ -59,6 +59,7 @@ value_shape_catalog, ) from tests.integration.catalog_publication_support import ( + clear_format_2_fields, emptied_catalog, row_counts, stored_identifiers, @@ -671,32 +672,6 @@ def _format_2_values(sessions: sessionmaker[Session]) -> dict[str, object]: } -def _clear_format_2_fields(sessions: sessionmaker[Session]) -> None: - """Make every stored version look as if published before catalog format 2. - - The JSON columns get SQL NULL (``sa.null()``), not JSON's null. - """ - with sessions.begin() as session: - session.execute( - sa.update(TaxBenefitModelVersion).values( - catalog_format=None, entities=sa.null(), basic_inputs=sa.null() - ) - ) - session.execute( - sa.update(Variable).values( - is_input_variable=None, - hidden_input=None, - module_name=None, - adds_parameter_path=None, - subtracts_parameter_path=None, - enum_values=sa.null(), - unit=None, - definition_period=None, - ) - ) - session.execute(sa.update(Parameter).values(economy=None, household=None)) - - def test_publication_stores_catalog_format_2_fields( publication_sessions: sessionmaker[Session], ) -> None: @@ -730,7 +705,8 @@ def test_version_stored_before_format_2_keeps_its_fields_empty_on_republish( ) -> None: catalog = normalized_catalog() publish_catalog(publication_sessions, catalog) - _clear_format_2_fields(publication_sessions) + with publication_sessions.begin() as session: + clear_format_2_fields(session) before_ids = _identifiers(publication_sessions) result = publish_catalog(publication_sessions, catalog) @@ -1070,7 +1046,8 @@ def test_an_installed_version_stored_before_format_2_gets_no_tree( catalog = normalized_catalog() current_version = catalog.country("us").model_version.version publish_catalog(publication_sessions, catalog) - _clear_format_2_fields(publication_sessions) + with publication_sessions.begin() as session: + clear_format_2_fields(session) _delete_tree(publication_sessions, current_version) evidence = publish_catalog(publication_sessions, catalog) diff --git a/tests/integration/test_v2_catalog_publication_pruning.py b/tests/integration/test_v2_catalog_publication_pruning.py index bbb620e7d..51106d9ef 100644 --- a/tests/integration/test_v2_catalog_publication_pruning.py +++ b/tests/integration/test_v2_catalog_publication_pruning.py @@ -64,7 +64,10 @@ ) from policyengine_api.services.v2.metadata.services import V2MetadataService from tests.fixtures.v2_catalog import normalized_catalog -from tests.integration.catalog_publication_support import emptied_catalog +from tests.integration.catalog_publication_support import ( + clear_version_format_2_fields, + emptied_catalog, +) if TYPE_CHECKING: from collections.abc import Callable, Iterator @@ -72,6 +75,8 @@ from sqlalchemy.orm import sessionmaker from sqlmodel import Session + from tests.integration.conftest import ManagedV2Roles + OLD_VERSION = "5.0.1" # The earlier of the two other versions pruning keeps, with the previous one. EARLIER_KEPT_VERSION = "5.0.2" @@ -378,7 +383,7 @@ def _fixture_pruned(country_id: str, version: str) -> PrunedCatalogVersion: def test_publication_prunes_versions_older_than_the_kept_ones_as_the_writer( publication_sessions: sessionmaker[Session], - managed_v2_roles, + managed_v2_roles: ManagedV2Roles, v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> None: """Pruning deletes exactly the old version's current-law data, as the writer. @@ -438,7 +443,7 @@ def test_publication_prunes_versions_older_than_the_kept_ones_as_the_writer( def test_republishing_a_pruned_version_restores_what_its_publication_wrote( publication_sessions: sessionmaker[Session], - managed_v2_roles, + managed_v2_roles: ManagedV2Roles, v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> None: """A rollback that installs a pruned version restores its rows and marker. @@ -668,10 +673,10 @@ def _pruned_message(country_id: str, version: str) -> str: def test_routes_answer_404_for_a_pruned_version_and_serve_its_kept_rows( publication_sessions: sessionmaker[Session], - managed_v2_roles, + managed_v2_roles: ManagedV2Roles, v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> None: - """Read as the Public API's runtime role, with its declared privileges.""" + """Read as API v1's runtime role, with its declared privileges.""" for version in ( OLD_VERSION, EARLIER_KEPT_VERSION, @@ -742,7 +747,7 @@ def test_routes_answer_404_for_a_pruned_version_and_serve_its_kept_rows( def test_a_process_that_selected_a_version_before_its_pruning_answers_404( publication_sessions: sessionmaker[Session], - managed_v2_roles, + managed_v2_roles: ManagedV2Roles, v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> None: """The production reader keeps selections and whole-version responses. @@ -808,7 +813,7 @@ def test_a_process_that_selected_a_version_before_its_pruning_answers_404( def test_a_process_that_selected_a_pruned_version_serves_it_once_restored( publication_sessions: sessionmaker[Session], - managed_v2_roles, + managed_v2_roles: ManagedV2Roles, v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> None: """A selection kept while the version was pruned doesn't outlive restoration. @@ -1271,11 +1276,10 @@ def test_restoring_a_version_stored_before_catalog_format_2_writes_values_only( with publication_sessions.begin() as session: for model_name in MODEL_NAMES: version_id = _version_id(publication_sessions, model_name, OLD_VERSION) - # The JSON columns get SQL NULL (sa.null()), not JSON's null. session.execute( - sa.update(TaxBenefitModelVersion) - .where(col(TaxBenefitModelVersion.id) == version_id) - .values(catalog_format=None, entities=sa.null(), basic_inputs=sa.null()) + clear_version_format_2_fields( + col(TaxBenefitModelVersion.id) == version_id + ) ) _delete_tree_and_search_file(session, version_id) before = { diff --git a/tests/integration/test_v2_country_routes.py b/tests/integration/test_v2_country_routes.py index 1b9d35932..588ad0dfa 100644 --- a/tests/integration/test_v2_country_routes.py +++ b/tests/integration/test_v2_country_routes.py @@ -1,6 +1,6 @@ """Serve and check the v2 countries from a migrated disposable Postgres database. -The route and the startup check run as the Public API's runtime role, so the +The route and the startup check run as API v1's runtime role, so the tests prove the role's declared privileges cover them (rule ``api.v2.runtime-privileges-tested-as-runtime-role``). """ @@ -42,9 +42,11 @@ from sqlalchemy.orm import sessionmaker from sqlmodel import Session + from tests.integration.conftest import ManagedV2Roles + def test_postgres_countries_list_the_rows_the_revision_inserted( - managed_v2_roles, + managed_v2_roles: ManagedV2Roles, v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> None: command.upgrade(Config(str(REPO / "alembic-v2.ini")), "head") @@ -81,7 +83,7 @@ def test_postgres_countries_list_the_rows_the_revision_inserted( def test_postgres_countries_match_the_code_list_as_the_runtime_role( - managed_v2_roles, + managed_v2_roles: ManagedV2Roles, v2_sessions_as_role: Callable[[str], sessionmaker[Session]], v2_owner_sessions: sessionmaker[Session], ) -> None: diff --git a/tests/integration/test_v2_forced_report_reruns.py b/tests/integration/test_v2_forced_report_reruns.py index b1a4abf2a..c0718140b 100644 --- a/tests/integration/test_v2_forced_report_reruns.py +++ b/tests/integration/test_v2_forced_report_reruns.py @@ -4,7 +4,7 @@ from an admin user and refuses it, before the simulation service is asked, from anyone else: 401 without a user credential, 403 for a signed-out browser or a user below admin. An unforced re-run needs no credential. The -routes run as the Public API's runtime role. +routes run as API v1's runtime role. """ from __future__ import annotations diff --git a/tests/integration/test_v2_household_calculation_reads.py b/tests/integration/test_v2_household_calculation_reads.py index 7550d02a1..7540aaf15 100644 --- a/tests/integration/test_v2_household_calculation_reads.py +++ b/tests/integration/test_v2_household_calculation_reads.py @@ -1,7 +1,7 @@ -"""Read household calculations from ``household_jobs`` as the Public API's runtime role. +"""Read household calculations from ``household_jobs`` as API v1's runtime role. The simulation service inserts the jobs and its Modal workers record their -results; the Public API only reads them, through the household calculation +results; API v1 only reads them, through the household calculation service, as ``policyengine_v2_runtime``. Its declared privileges must cover the read, so a statement they don't allow fails here as it would in staging and production (rule ``api.v2.runtime-privileges-tested-as-runtime-role``). @@ -63,11 +63,13 @@ ) if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator from sqlalchemy.orm import sessionmaker from sqlmodel import Session + from tests.integration.conftest import ManagedV2Roles + COMPLETED_AT = datetime(2026, 11, 10, 12, 0, 9, tzinfo=UTC) @@ -106,7 +108,7 @@ def _insert_job( @pytest.fixture def stored_jobs( - v2_owner_sessions: sessionmaker[Session], managed_v2_roles + v2_owner_sessions: sessionmaker[Session], managed_v2_roles: ManagedV2Roles ) -> Iterator[StoredJobs]: """Commit, as the superuser, one job of each outcome; delete them afterwards. @@ -168,7 +170,10 @@ def _no_simulation_service(): @pytest.fixture -def runtime_service(managed_v2_roles, v2_sessions_as_role): +def runtime_service( + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], +) -> V2HouseholdCalculationService: """Return the household calculation service, reading as the runtime role.""" sessions = v2_sessions_as_role(managed_v2_roles.runtime) return V2HouseholdCalculationService( diff --git a/tests/integration/test_v2_household_reports.py b/tests/integration/test_v2_household_reports.py index 60928fa18..76dd5320f 100644 --- a/tests/integration/test_v2_household_reports.py +++ b/tests/integration/test_v2_household_reports.py @@ -1,6 +1,6 @@ """Create, read and list household reports through /v2/reports on migrated PostgreSQL. -The routes run as the Public API's runtime role, so the tests prove its +The routes run as API v1's runtime role, so the tests prove its declared privileges cover every read: the countries row, the stored household and policies the checks read, and the reports, simulations, runs and calculated households the reads return (rule @@ -80,6 +80,7 @@ from policyengine_api.services.v2.simulation_service.types import ( HouseholdReportCreationInput, ) + from tests.integration.conftest import ManagedV2Roles from tests.integration.stored_report_rows import CatalogRows CURRENT_VERSIONS = {"country_package_version": "1.5.0", "policyengine_version": "4.2.0"} @@ -335,7 +336,8 @@ def household_only_uk(owner_sessions: sessionmaker[Session]) -> Iterator[Catalog @pytest.fixture def runtime_sessions( - managed_v2_roles, v2_sessions_as_role: Callable[[str], sessionmaker[Session]] + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> sessionmaker[Session]: return v2_sessions_as_role(managed_v2_roles.runtime) diff --git a/tests/integration/test_v2_metadata_routes.py b/tests/integration/test_v2_metadata_routes.py index 2c3387f64..4dcec4c9d 100644 --- a/tests/integration/test_v2_metadata_routes.py +++ b/tests/integration/test_v2_metadata_routes.py @@ -51,7 +51,11 @@ region_references, source_models, ) -from tests.integration.catalog_publication_support import emptied_catalog, row_counts +from tests.integration.catalog_publication_support import ( + clear_format_2_fields, + emptied_catalog, + row_counts, +) if TYPE_CHECKING: from collections.abc import Callable, Iterator @@ -59,6 +63,8 @@ from sqlalchemy.orm import sessionmaker from sqlmodel import Session + from tests.integration.conftest import ManagedV2Roles + # The catalog tables whose rows the read-only routes must leave as they are. COUNTED_MODELS = { "variables": Variable, @@ -833,10 +839,10 @@ def test_postgres_parameter_tree_nests_schedules_and_filters_reform_changes( def test_postgres_parameter_tree_reads_as_the_runtime_role( published_sessions: sessionmaker[Session], - managed_v2_roles, + managed_v2_roles: ManagedV2Roles, v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> None: - """The Public API's runtime role can read the tree with its declared privileges.""" + """API v1's runtime role can read the tree with its declared privileges.""" runtime_sessions = v2_sessions_as_role(managed_v2_roles.runtime) with runtime_sessions() as session: result = V2MetadataService( @@ -997,26 +1003,8 @@ def test_postgres_a_version_stored_before_format_2_returns_the_tree_503( Its parameter tree request returns 503 with the message naming it. """ - # The JSON columns get SQL NULL (sa.null()), not JSON's null. with published_sessions.begin() as session: - session.execute( - sa.update(TaxBenefitModelVersion).values( - catalog_format=None, entities=sa.null(), basic_inputs=sa.null() - ) - ) - session.execute( - sa.update(Variable).values( - is_input_variable=None, - hidden_input=None, - module_name=None, - adds_parameter_path=None, - subtracts_parameter_path=None, - enum_values=sa.null(), - unit=None, - definition_period=None, - ) - ) - session.execute(sa.update(Parameter).values(economy=None, household=None)) + clear_format_2_fields(session) session.execute(sa.delete(ParameterTreeChild)) evidence = publish_catalog(published_sessions, normalized_catalog()) @@ -1090,10 +1078,10 @@ def test_postgres_search_file_of_a_version_without_one_is_unavailable( def test_postgres_search_file_reads_as_the_runtime_role( published_sessions: sessionmaker[Session], - managed_v2_roles, + managed_v2_roles: ManagedV2Roles, v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> None: - """The Public API's runtime role reads the file with its declared privileges.""" + """API v1's runtime role reads the file with its declared privileges.""" runtime_sessions = v2_sessions_as_role(managed_v2_roles.runtime) with runtime_sessions() as session: service = V2MetadataService( diff --git a/tests/integration/test_v2_migration_target_persistent.py b/tests/integration/test_v2_migration_target_persistent.py new file mode 100644 index 000000000..c5d8efed2 --- /dev/null +++ b/tests/integration/test_v2_migration_target_persistent.py @@ -0,0 +1,161 @@ +"""PostgreSQL tests of the target checks v2 Alembic runs on a persistent database. + +In staging and production, ``qualify_v2_target`` runs before Alembic or the +privilege reconciliation changes anything. It reads the live database's name +and the role the statements run as, and whether that role may CREATE in +schema ``public``, and refuses a target that doesn't match the configured one. +These tests run that non-disposable path on the disposable database, as +temporary roles that don't own it, with a configured target that names the +disposable database and one of the roles. +""" + +from __future__ import annotations + +from datetime import date +from typing import TYPE_CHECKING +from uuid import uuid4 + +import pytest +from sqlalchemy.engine import make_url + +from policyengine_api.data.v2.migration_target import ( + ConfiguredSupabaseTarget, + V2AlembicSettings, + V2MigrationTargetError, + qualify_v2_target, +) +from tests.fixtures.database_sessions import create_role, drop_role +from tests.integration.catalog_privilege_objects import SCHEMA, grant_on_schema_object + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + + from sqlalchemy.orm import sessionmaker + from sqlmodel import Session + +# A configured target's identity outside the live checks, which never read it. +TARGET_ENVIRONMENT = "persistent-path-test" +TARGET_PROJECT_REF = "abcdefghijklmnopqrst" +FRESHNESS_AUDITED_ON = date(2026, 11, 24) + + +@pytest.fixture +def temporary_role( + v2_owner_sessions: sessionmaker[Session], +) -> Iterator[Callable[..., str]]: + """Return a builder of NOLOGIN roles, with or without CREATE on ``public``. + + The roles are dropped after the test. + """ + created_roles: list[str] = [] + + def create_temporary_role(*, can_create_in_public: bool) -> str: + role = f"policyengine_migration_target_test_{uuid4().hex[:12]}" + with v2_owner_sessions.begin() as session: + create_role(session, role) + if can_create_in_public: + grant_on_schema_object( + session, "CREATE", object_kind="SCHEMA", name=SCHEMA, to=role + ) + created_roles.append(role) + return role + + try: + yield create_temporary_role + finally: + with v2_owner_sessions.begin() as session: + for role in created_roles: + drop_role(session, role) + + +def _persistent_settings( + database_url: str, *, migration_role: str, database_name: str | None = None +) -> V2AlembicSettings: + """Return non-disposable settings whose target names a database and role. + + The database is the one ``database_url`` names, unless ``database_name`` + names another. + """ + url = make_url(database_url) + if database_name is None: + assert url.database is not None + database_name = url.database + return V2AlembicSettings( + url=url, + disposable_test=False, + target=ConfiguredSupabaseTarget( + environment=TARGET_ENVIRONMENT, + project_ref=TARGET_PROJECT_REF, + database_name=database_name, + migration_role=migration_role, + freshness_audited_on=FRESHNESS_AUDITED_ON, + freshness_audit_passed=True, + ), + ) + + +def _qualify_as(sessions: sessionmaker[Session], settings: V2AlembicSettings) -> None: + with sessions() as session: + qualify_v2_target(session, settings) + + +def test_the_configured_role_that_can_create_in_public_qualifies( + disposable_v2_database_url: str, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], + temporary_role: Callable[..., str], +) -> None: + role = temporary_role(can_create_in_public=True) + settings = _persistent_settings( + disposable_v2_database_url, + migration_role=role, + ) + + _qualify_as(v2_sessions_as_role(role), settings) + + +def test_a_role_other_than_the_configured_one_is_refused( + disposable_v2_database_url: str, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], + temporary_role: Callable[..., str], +) -> None: + """Both roles may CREATE in ``public``; only the configured one may migrate.""" + configured_role = temporary_role(can_create_in_public=True) + other_role = temporary_role(can_create_in_public=True) + settings = _persistent_settings( + disposable_v2_database_url, + migration_role=configured_role, + ) + + with pytest.raises(V2MigrationTargetError, match="identity does not match"): + _qualify_as(v2_sessions_as_role(other_role), settings) + + +def test_the_configured_role_without_create_in_public_is_refused( + disposable_v2_database_url: str, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], + temporary_role: Callable[..., str], +) -> None: + role = temporary_role(can_create_in_public=False) + settings = _persistent_settings( + disposable_v2_database_url, + migration_role=role, + ) + + with pytest.raises(V2MigrationTargetError, match="lacks public schema CREATE"): + _qualify_as(v2_sessions_as_role(role), settings) + + +def test_a_database_other_than_the_configured_one_is_refused( + disposable_v2_database_url: str, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], + temporary_role: Callable[..., str], +) -> None: + role = temporary_role(can_create_in_public=True) + settings = _persistent_settings( + disposable_v2_database_url, + database_name="postgres", + migration_role=role, + ) + + with pytest.raises(V2MigrationTargetError, match="identity does not match"): + _qualify_as(v2_sessions_as_role(role), settings) diff --git a/tests/integration/test_v2_privilege_reconciliation.py b/tests/integration/test_v2_privilege_reconciliation.py index af5f9be95..dfaaaf215 100644 --- a/tests/integration/test_v2_privilege_reconciliation.py +++ b/tests/integration/test_v2_privilege_reconciliation.py @@ -19,16 +19,30 @@ from policyengine_api.data.v2.models import Region from policyengine_api.data.v2.privilege_reconciliation import ( DEPLOYMENT_ENVIRONMENT, + DefaultPrivilege, PrivilegeEntry, apply_declared_privileges, check_declared_privileges, check_table_wide_overrides, + read_default_privileges, + read_granted_column_privileges, + read_granted_privileges, run, skipped_roles, ) from policyengine_api.data.v2.privileges import READ, TablePrivilege, update_columns from policyengine_api.data.v2.settings import V2_MIGRATION_DATABASE_URL -from tests.fixtures.database_sessions import create_role, drop_role, grant +from tests.fixtures.database_sessions import act_as, create_role, drop_role, grant +from tests.integration.catalog_privilege_objects import ( + PUBLIC_GRANTEE, + SCHEMA, + PrivilegeTestMaterializedView, + PrivilegeTestView, + alter_default_privileges, + create_sequence, + create_view, + grant_on_schema_object, +) if TYPE_CHECKING: from collections.abc import Callable, Iterator @@ -360,3 +374,105 @@ def test_verify_fails_once_a_role_awaiting_creation_exists_without_its_privilege f"`{absent_role}`" ) in summary assert summary.count("## v2 table privileges") == 1 + + +def test_default_privileges_are_read_for_tables_and_sequences_including_public( + v2_owner_sessions: sessionmaker[Session], + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], + temporary_role: Callable[[], str], +) -> None: + """Each default privilege is read with its creating role, schema and grantee. + + A default privilege given to PUBLIC names no grantee role, so it is read + only for its creating role. + """ + creator = temporary_role() + reader = temporary_role() + with v2_owner_sessions.begin() as session: + alter_default_privileges( + session, + creating_role=creator, + privileges="SELECT", + object_type="TABLES", + to=reader, + ) + alter_default_privileges( + session, + creating_role=creator, + privileges="USAGE", + object_type="SEQUENCES", + to=PUBLIC_GRANTEE, + ) + + with v2_sessions_as_role(creator)() as session: + for_both_roles = read_default_privileges(session, [creator, reader]) + for_the_reader = read_default_privileges(session, [reader]) + + readers_tables = DefaultPrivilege( + creating_role=creator, + schema=SCHEMA, + object_type="tables", + grantee=reader, + privileges=("SELECT",), + ) + assert for_both_roles == [ + DefaultPrivilege( + creating_role=creator, + schema=SCHEMA, + object_type="sequences", + grantee=PUBLIC_GRANTEE, + privileges=("USAGE",), + ), + readers_tables, + ] + assert for_the_reader == [readers_tables] + + +def test_grants_on_sequences_views_and_materialized_views_are_read( + v2_owner_sessions: sessionmaker[Session], + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], + temporary_role: Callable[[], str], +) -> None: + """The reads return each grant a role holds, on whole relations and columns. + + A temporary role creates the objects and reads the grants, as the migration + role owns the tables and runs the reconciliation. + """ + creator = temporary_role() + reader = temporary_role() + sequence = f"privilege_test_sequence_{uuid4().hex[:12]}" + view = PrivilegeTestView.__tablename__ + materialized_view = PrivilegeTestMaterializedView.__tablename__ + with v2_owner_sessions.begin() as session: + grant_on_schema_object( + session, "CREATE", object_kind="SCHEMA", name=SCHEMA, to=creator + ) + act_as(session, creator) + create_sequence(session, sequence) + create_view(session, PrivilegeTestView) + create_view(session, PrivilegeTestMaterializedView) + grant_on_schema_object( + session, "USAGE, SELECT", object_kind="SEQUENCE", name=sequence, to=reader + ) + grant(session, "SELECT", on=PrivilegeTestView, to=reader) + grant(session, "UPDATE (label)", on=PrivilegeTestView, to=reader) + grant(session, "SELECT", on=PrivilegeTestMaterializedView, to=reader) + grant(session, "SELECT (label)", on=PrivilegeTestMaterializedView, to=reader) + + with v2_sessions_as_role(creator)() as session: + granted = read_granted_privileges(session, [reader]) + granted_columns = read_granted_column_privileges(session, [reader]) + + assert granted == { + reader: { + sequence: {"SELECT", "USAGE"}, + view: {"SELECT"}, + materialized_view: {"SELECT"}, + } + } + assert granted_columns == { + reader: { + view: {"label": {"UPDATE"}}, + materialized_view: {"label": {"SELECT"}}, + } + } diff --git a/tests/integration/test_v2_report_creation.py b/tests/integration/test_v2_report_creation.py index a4aa33544..6e17b696e 100644 --- a/tests/integration/test_v2_report_creation.py +++ b/tests/integration/test_v2_report_creation.py @@ -2,7 +2,7 @@ A stand-in for the simulation service's client stores the rows the simulation service would create and answers with their IDs; the routes run -as the Public API's runtime role, checking the country and policies and +as API v1's runtime role, checking the country and policies and reading the created records back. """ diff --git a/tests/integration/test_v2_report_reads.py b/tests/integration/test_v2_report_reads.py index 2456d6fd9..daaef53d2 100644 --- a/tests/integration/test_v2_report_reads.py +++ b/tests/integration/test_v2_report_reads.py @@ -1,6 +1,6 @@ """Read v2 reports, their results and simulations from migrated PostgreSQL. -The routes run as the Public API's runtime role, so the tests prove the +The routes run as API v1's runtime role, so the tests prove the role's declared privileges cover every read (rule ``api.v2.runtime-privileges-tested-as-runtime-role``). The rows are stored as the simulation service and its Modal workers store them, committed, and diff --git a/tests/integration/test_v2_report_reads_by_run.py b/tests/integration/test_v2_report_reads_by_run.py index 2e0c4d00b..771a5a6e2 100644 --- a/tests/integration/test_v2_report_reads_by_run.py +++ b/tests/integration/test_v2_report_reads_by_run.py @@ -3,7 +3,7 @@ ``GET /v2/reports/{report_id}?run_id=`` answers that run of the report, its status, versions and result, whichever run is the newest: a report run of an economy or household report, or a budget-window run of a budget window. The -routes run as the Public API's runtime role. +routes run as API v1's runtime role. """ from __future__ import annotations diff --git a/tests/integration/test_v2_report_runs.py b/tests/integration/test_v2_report_runs.py index 57ab7a523..e4c4146d4 100644 --- a/tests/integration/test_v2_report_runs.py +++ b/tests/integration/test_v2_report_runs.py @@ -2,7 +2,7 @@ A stand-in for the simulation service's client stores the new run the simulation service would create and records what it was asked; the routes -run as the Public API's runtime role, reading the report, checking its +run as API v1's runtime role, reading the report, checking its country and policies, and reading the report and its runs back. """ @@ -613,7 +613,7 @@ def test_a_report_whose_reform_simulation_is_gone_is_left_to_the_service_to_refu catalog: CatalogRows, runtime_sessions: sessionmaker[Session], ) -> None: - # The Public API checks the policies that remain and asks the simulation + # API v1 checks the policies that remain and asks the simulation # service, which refuses a report missing a simulation. with owner_sessions.begin() as session: report = store_report(session, catalog) diff --git a/tests/integration/test_v2_shared_report_rows.py b/tests/integration/test_v2_shared_report_rows.py index c3c6e9a3a..5c309f116 100644 --- a/tests/integration/test_v2_shared_report_rows.py +++ b/tests/integration/test_v2_shared_report_rows.py @@ -3,7 +3,7 @@ The simulation service finds each simulation and report by its key, and joins a run on the same versions that hasn't failed, with ``INSERT ... ON CONFLICT DO NOTHING`` against the indexes the shared-report revision adds; a forced -re-run is an extra run that nothing joins. The Public API records each user's +re-run is an extra run that nothing joins. API v1 records each user's request for a report run. Each statement runs as the role that runs it in staging and production, holding only its declared privileges (``policyengine_api/data/v2/privileges.py``). @@ -25,14 +25,12 @@ from alembic.config import Config from sqlalchemy import ( and_, - bindparam, delete, func, insert, not_, select, true, - update, ) from sqlalchemy.dialects import postgresql from sqlalchemy.exc import IntegrityError, ProgrammingError @@ -51,6 +49,12 @@ UserReportRunAssociation, ) from tests.fixtures.database_sessions import act_as, act_as_owner, query_plan +from tests.integration.privilege_statements import ( + ReportColumns, + SimulationColumns, + unfailed, + update_row, +) from tests.integration.simulation_rows import ( RUN_VERSIONS, PublicApiRows, @@ -62,7 +66,7 @@ if TYPE_CHECKING: from collections.abc import Iterator - from sqlalchemy import Executable, Update + from sqlalchemy import Executable from sqlalchemy.orm import sessionmaker from sqlmodel import Session @@ -80,11 +84,6 @@ } -def _unfailed(status: Any, failed_status: str) -> Any: - """Return ``status <> 'failed'``, with the failed status sent as a literal.""" - return status != bindparam("failed_status", failed_status, literal_execute=True) - - # What the simulation service will send: a new row, or nothing when one with # the same key, or an unfailed unforced run on the same versions, exists. def _find_or_create_simulation(public_api_rows: PublicApiRows, key: str) -> Executable: @@ -155,7 +154,7 @@ def _find_or_create_simulation_run( col(SimulationRun.policyengine_version), ], index_where=and_( - _unfailed(col(SimulationRun.status), SimulationStatus.FAILED), + unfailed(col(SimulationRun.status), SimulationStatus.FAILED), not_(col(SimulationRun.forced)), ), ) @@ -189,7 +188,7 @@ def _find_or_create_report_run( ], index_where=and_( col(ReportRun.budget_window_run_id).is_(None), - _unfailed(col(ReportRun.status), ReportRunStatus.FAILED), + unfailed(col(ReportRun.status), ReportRunStatus.FAILED), not_(col(ReportRun.forced)), ), ) @@ -222,7 +221,7 @@ def _find_or_create_window_run( col(BudgetWindowRun.policyengine_version), ], index_where=and_( - _unfailed(col(BudgetWindowRun.status), ReportRunStatus.FAILED), + unfailed(col(BudgetWindowRun.status), ReportRunStatus.FAILED), not_(col(BudgetWindowRun.recalculate)), ), ) @@ -285,11 +284,6 @@ def _refused( session.execute(statement) -def _update_row(model: type[Any], row_id: object, **values: object) -> Update: - """Build an UPDATE of the model's row with ID ``row_id``, setting ``values``.""" - return update(model).where(model.id == row_id).values(**values) - - def _simulation( session: Session, public_api_rows: PublicApiRows, key: str | None = None ) -> UUID: @@ -361,7 +355,7 @@ def _report_run( def _fail(session: Session, model: type[Any], run_id: UUID | None) -> None: session.execute( - _update_row( + update_row( model, run_id, status="failed", @@ -571,7 +565,7 @@ def test_a_simulation_has_one_unfailed_unforced_run_per_version_set( act_as(session, managed_v2_roles.modal_worker) _refused( session, - _update_row(SimulationRun, first_run, status="running"), + update_row(SimulationRun, first_run, status="running"), match="uq_simulation_runs_unfailed_unforced_versions", ) @@ -662,7 +656,7 @@ def window_run( assert window_run() not in {None, first_run} _refused( session, - _update_row(BudgetWindowRun, first_run, policyengine_version="4.9.9"), + update_row(BudgetWindowRun, first_run, policyengine_version="4.9.9"), ProgrammingError, match="permission denied", ) @@ -731,11 +725,14 @@ def test_no_simulation_role_changes_a_rows_key_or_a_runs_forced_marker( managed_v2_roles.modal_worker, ): act_as(session, role) + # The keys' UPDATEs set only the key column: neither role may update + # ``updated_at`` on simulations or reports, which the models' UPDATE + # also sets. Both roles may update it on the run tables. for statement in ( - _update_row(Simulation, simulation_id, definition_key=None), - _update_row(Report, report_id, key_version=1), - _update_row(SimulationRun, run_id, forced=True), - _update_row(ReportRun, report_run_id, forced=True), + update_row(SimulationColumns, simulation_id, definition_key=None), + update_row(ReportColumns, report_id, key_version=1), + update_row(SimulationRun, run_id, forced=True), + update_row(ReportRun, report_run_id, forced=True), ): _refused(session, statement, ProgrammingError, match="permission denied") @@ -778,7 +775,7 @@ def test_the_public_api_records_each_users_request_for_a_report_run( ) _refused( session, - _update_row(UserReportRunAssociation, first_record, requested_at=func.now()), + update_row(UserReportRunAssociation, first_record, requested_at=func.now()), ProgrammingError, match="permission denied", ) diff --git a/tests/integration/test_v2_simulation_role_privileges.py b/tests/integration/test_v2_simulation_role_privileges.py index 5dd0abfeb..12d52bd1a 100644 --- a/tests/integration/test_v2_simulation_role_privileges.py +++ b/tests/integration/test_v2_simulation_role_privileges.py @@ -3,15 +3,21 @@ The simulation service creates simulations, reports, their runs, budget-window runs, household jobs and simulation runs' cliff calculations; its Modal workers write their runs' and cliff calculations' status and results and -their budget-window runs' status; API v1 reads them. Each -role holds only its declared privileges -(``policyengine_api/data/v2/privileges.py``), so a statement outside them -fails here as it would in staging and production. +their budget-window runs' status; API v1 reads them. Each role holds only its +declared privileges (``policyengine_api/data/v2/privileges.py``), so a +statement outside them fails here as it would in staging and production. Every statement runs through one Session of the database's owner, which -``act_as`` switches to a role for the rest of its transaction. An ORM -``update`` also sets ``updated_at`` on the tables that have it, which every -role here that updates those tables may do. +``act_as`` switches to a role for the rest of its transaction. A refused +statement sends only the columns it names, so the database refuses it for +those columns. A model's ORM ``update`` also sets ``updated_at``, and its ORM +``insert`` also writes Python-side defaults such as ``created_at``, so refused +inserts, and refused updates of tables where the role may not update +``updated_at``, go through ``tests.integration.privilege_statements``' classes, +which map only the columns they name. The other refused updates use the +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``. """ from __future__ import annotations @@ -22,7 +28,7 @@ import pytest from alembic import command from alembic.config import Config -from sqlalchemy import bindparam, delete, false, func, insert, inspect, select, update +from sqlalchemy import delete, false, func, insert, inspect, select, update from sqlalchemy.dialects import postgresql from sqlalchemy.exc import ProgrammingError from sqlmodel import col @@ -31,7 +37,6 @@ from policyengine_api.data.v2.models import ( BudgetWindowRun, CliffImpact, - Household, HouseholdJob, LaborSupplyDecileResponse, ParameterValue, @@ -51,6 +56,19 @@ declared_privileges, ) from tests.fixtures.database_sessions import act_as +from tests.integration.privilege_statements import ( + BudgetWindowRunColumns, + CliffImpactColumns, + HouseholdColumns, + LaborSupplyDecileResponseColumns, + PolicyColumns, + PovertyColumns, + ReportRunColumns, + SimulationColumns, + WithheldAreaCodeColumns, + unfailed, + update_row, +) from tests.integration.simulation_rows import ( RUN_VERSIONS, PublicApiRows, @@ -62,7 +80,7 @@ if TYPE_CHECKING: from collections.abc import Iterator - from sqlalchemy import Executable, Update + from sqlalchemy import Executable from sqlalchemy.orm import sessionmaker from sqlmodel import Session @@ -98,11 +116,6 @@ def _refused(session: Session, statement: Executable) -> None: session.execute(statement) -def _update_row(model: type[Any], row_id: object, **values: object) -> Update: - """Build an UPDATE of the model's row with ID ``row_id``, setting ``values``.""" - return update(model).where(model.id == row_id).values(**values) - - def _update_from_status( session: Session, model: type[Any], @@ -246,21 +259,21 @@ def test_the_simulation_service_creates_rows_and_records_only_its_calls( ) assert (recorded, failed) == (ids["report_run"], ids["household_job"]) for statement in ( - _update_row(SimulationRun, ids["run"], started_at=func.now()), - _update_row(SimulationRun, ids["run"], output_uri="gs://bucket/run"), - _update_row(SimulationRun, ids["run"], year=2027), - _update_row(ReportRun, ids["report_run"], baseline_cliff_gap=1.0), - insert(Poverty).values( + update_row(SimulationRun, ids["run"], started_at=func.now()), + update_row(SimulationRun, ids["run"], output_uri="gs://bucket/run"), + update_row(SimulationRun, ids["run"], year=2027), + update_row(ReportRun, ids["report_run"], baseline_cliff_gap=1.0), + insert(PovertyColumns).values( id=uuid4(), simulation_run_id=ids["run"], poverty_type="spm", entity="person", ), delete(Simulation).where(col(Simulation.id) == ids["simulation"]), - insert(LaborSupplyDecileResponse).values( + insert(LaborSupplyDecileResponseColumns).values( id=uuid4(), report_run_id=ids["report_run"], decile=1 ), - update(Policy).values(content_hash=col(Policy.content_hash)), + update(PolicyColumns).values(content_hash=PolicyColumns.content_hash), ): _refused(session, statement) @@ -290,7 +303,7 @@ def test_modal_workers_write_their_run_status_and_results_only( rate=0.1, ) session.execute( - _update_row( + update_row( ReportRun, ids["report_run"], status="running", @@ -327,14 +340,14 @@ def test_modal_workers_write_their_run_status_and_results_only( assert updated == ids["run"] assert finished_job == ids["household_job"] for statement in ( - insert(Simulation).values( + insert(SimulationColumns).values( id=uuid4(), simulation_type="economy", dataset_id=uuid4(), tax_benefit_model_version_id=uuid4(), ), delete(Poverty).where(col(Poverty.simulation_run_id) == ids["run"]), - insert(BudgetWindowRun).values( + insert(BudgetWindowRunColumns).values( id=uuid4(), report_id=ids["report"], tax_benefit_model_version_id=public_api_rows.version_id, @@ -345,22 +358,22 @@ def test_modal_workers_write_their_run_status_and_results_only( update(Poverty) .where(col(Poverty.simulation_run_id) == ids["run"]) .values(rate=0), - update(Household).values(content_hash=col(Household.content_hash)), + update(HouseholdColumns).values(content_hash=HouseholdColumns.content_hash), ): _refused(session, statement) # What a run is stays as the simulation service wrote it. for statement in ( - _update_row(SimulationRun, ids["run"], year=2027), - _update_row( + update_row(SimulationRun, ids["run"], year=2027), + update_row( SimulationRun, ids["run"], simulation_id=col(SimulationRun.simulation_id) ), - _update_row( + update_row( ReportRun, ids["report_run"], baseline_simulation_run_id=col(ReportRun.baseline_simulation_run_id), ), - _update_row(ReportRun, ids["report_run"], markdown="edited"), - _update_row( + update_row(ReportRun, ids["report_run"], markdown="edited"), + update_row( HouseholdJob, ids["household_job"], household_id=col(HouseholdJob.household_id), @@ -403,7 +416,7 @@ def test_modal_workers_insert_withheld_area_codes_that_the_public_api_reads( ) # Once written, a withheld code is never changed or removed by the workers. - _refused(session, _update_row(WithheldAreaCode, withheld_code_id, code="E14001064")) + _refused(session, update_row(WithheldAreaCode, withheld_code_id, code="E14001064")) _refused( session, delete(WithheldAreaCode).where(col(WithheldAreaCode.id) == withheld_code_id), @@ -419,7 +432,7 @@ def test_modal_workers_insert_withheld_area_codes_that_the_public_api_reads( ) _refused( session, - insert(WithheldAreaCode).values( + insert(WithheldAreaCodeColumns).values( id=uuid4(), report_run_id=ids["report_run"], baseline_simulation_run_id=ids["run"], @@ -462,9 +475,9 @@ def test_the_simulation_service_fails_a_window_whose_first_calls_modal_refuses( assert failed_window == window_id for statement in ( - _update_row(BudgetWindowRun, window_id, started_at=func.now()), - _update_row(BudgetWindowRun, window_id, recalculate=True), - _update_row( + update_row(BudgetWindowRun, window_id, started_at=func.now()), + update_row(BudgetWindowRun, window_id, recalculate=True), + update_row( BudgetWindowRun, window_id, report_id=col(BudgetWindowRun.report_id) ), ): @@ -531,9 +544,9 @@ 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(BudgetWindowRun, window_id, recalculate=False), - _update_row( + update_row(BudgetWindowRun, window_id, trigger="manual"), + update_row(BudgetWindowRun, window_id, recalculate=False), + update_row( BudgetWindowRun, window_id, tax_benefit_model_version_id=col( @@ -594,7 +607,7 @@ def test_the_public_api_reads_runs_and_results_but_writes_neither( session.execute(_row_count(model)).scalar_one() _refused( session, - insert(ReportRun).values( + insert(ReportRunColumns).values( id=uuid4(), report_id=uuid4(), baseline_simulation_run_id=uuid4(), @@ -652,15 +665,12 @@ def _start_cliff_calculation(session: Session, run_id: object) -> UUID | None: as well as INSERT. Its condition is sent as a literal, as in the index, so PostgreSQL can match the index however often the statement runs. """ - unfailed = col(CliffImpact.status) != bindparam( - "failed_status", SimulationStatus.FAILED, literal_execute=True - ) return session.execute( postgresql.insert(CliffImpact) .values(id=uuid4(), simulation_run_id=run_id, status="pending") .on_conflict_do_nothing( index_elements=[col(CliffImpact.simulation_run_id)], - index_where=unfailed, + index_where=unfailed(col(CliffImpact.status), SimulationStatus.FAILED), ) .returning(col(CliffImpact.id)) ).scalar_one_or_none() @@ -704,9 +714,9 @@ def test_the_simulation_service_starts_cliff_calculations_and_records_calls( assert joined_calculation is None assert recorded == failed == calculation_id for statement in ( - _update_row(CliffImpact, calculation_id, started_at=func.now()), - _update_row(CliffImpact, calculation_id, cliff_gap=1.0), - _update_row( + update_row(CliffImpact, calculation_id, started_at=func.now()), + update_row(CliffImpact, calculation_id, cliff_gap=1.0), + update_row( CliffImpact, calculation_id, simulation_run_id=col(CliffImpact.simulation_run_id), @@ -753,10 +763,10 @@ def test_modal_workers_claim_cliff_calculations_and_write_their_results( assert claimed == succeeded == calculation_id for statement in ( - insert(CliffImpact).values( + insert(CliffImpactColumns).values( id=uuid4(), simulation_run_id=ids["run"], status="pending" ), - _update_row( + update_row( CliffImpact, calculation_id, simulation_run_id=col(CliffImpact.simulation_run_id), @@ -778,7 +788,7 @@ def test_api_v1_reads_cliff_results_and_other_roles_cannot( calculation_id = _start_cliff_calculation(session, ids["run"]) act_as(session, managed_v2_roles.modal_worker) session.execute( - _update_row( + update_row( CliffImpact, calculation_id, status="succeeded", @@ -810,11 +820,11 @@ def test_api_v1_reads_cliff_results_and_other_roles_cannot( assert [tuple(result) for result in results] == [(1.5e9, 0.04)] _refused( session, - insert(CliffImpact).values( + insert(CliffImpactColumns).values( id=uuid4(), simulation_run_id=ids["run"], status="pending" ), ) - _refused(session, _update_row(CliffImpact, calculation_id, cliff_gap=0)) + _refused(session, update_row(CliffImpactColumns, calculation_id, cliff_gap=0)) for role in (managed_v2_roles.stage12, CATALOG_WRITER_ROLE): act_as(session, role) _refused(session, _row_count(CliffImpact)) diff --git a/tests/integration/test_v2_stage12_comparison_persistence.py b/tests/integration/test_v2_stage12_comparison_persistence.py index 569243e67..257467630 100644 --- a/tests/integration/test_v2_stage12_comparison_persistence.py +++ b/tests/integration/test_v2_stage12_comparison_persistence.py @@ -37,7 +37,7 @@ ) if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator from sqlalchemy.orm import sessionmaker from sqlmodel import Session @@ -46,12 +46,13 @@ ComparisonReportRecord, ComparisonSimulationRecord, ) + from tests.integration.conftest import ManagedV2Roles @pytest.fixture def stage12_sessions( - managed_v2_roles, - v2_sessions_as_role, + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], v2_owner_sessions: sessionmaker[Session], ) -> Iterator[sessionmaker[Session]]: """Open sessions as the Stage 12 role; remove this test's rows as the superuser.""" @@ -101,7 +102,7 @@ def _baseline_simulation(report: ComparisonReportRecord) -> ComparisonSimulation def test_stage12_sessions_act_as_the_stage12_role( - stage12_sessions, managed_v2_roles + stage12_sessions: sessionmaker[Session], managed_v2_roles: ManagedV2Roles ) -> None: with stage12_sessions() as session: current_role = session.execute(select(func.current_user())).scalar_one() diff --git a/tests/integration/test_v2_user_budget_window_runs.py b/tests/integration/test_v2_user_budget_window_runs.py index b8000ecc6..8714b202c 100644 --- a/tests/integration/test_v2_user_budget_window_runs.py +++ b/tests/integration/test_v2_user_budget_window_runs.py @@ -2,7 +2,7 @@ A budget window's run is a budget-window run with a report run per year; a request for one records each year's report run for the user, with one -``requested_at``. The routes run as the Public API's runtime role, through +``requested_at``. The routes run as API v1's runtime role, through a stand-in for the simulation service that answers a window run it names or one it stores. """ @@ -44,6 +44,7 @@ from sqlalchemy.orm import sessionmaker from sqlmodel import Session + from tests.integration.conftest import ManagedV2Roles from tests.integration.stored_report_rows import CatalogRows WINDOW_YEARS = (2026, 2027, 2028) @@ -66,7 +67,8 @@ def catalog(owner_sessions: sessionmaker[Session]) -> Iterator[CatalogRows]: @pytest.fixture def runtime_sessions( - managed_v2_roles, v2_sessions_as_role: Callable[[str], sessionmaker[Session]] + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> sessionmaker[Session]: return v2_sessions_as_role(managed_v2_roles.runtime) diff --git a/tests/integration/test_v2_user_identity_persistence.py b/tests/integration/test_v2_user_identity_persistence.py index 254a56ddd..27fa76e79 100644 --- a/tests/integration/test_v2_user_identity_persistence.py +++ b/tests/integration/test_v2_user_identity_persistence.py @@ -270,7 +270,9 @@ def test_an_author_or_admin_keeps_its_type_at_sign_in_and_upgrade( assert stored.user_type == user_type -def test_sessions_act_as_the_runtime_role(sessions, managed_v2_roles) -> None: +def test_sessions_act_as_the_runtime_role( + sessions: sessionmaker[Session], managed_v2_roles: ManagedV2Roles +) -> None: with sessions() as session: current_role = session.execute(select(func.current_user())).scalar_one() diff --git a/tests/integration/test_v2_user_report_run_requesters.py b/tests/integration/test_v2_user_report_run_requesters.py index 297691225..1cc5adc61 100644 --- a/tests/integration/test_v2_user_report_run_requesters.py +++ b/tests/integration/test_v2_user_report_run_requesters.py @@ -4,7 +4,7 @@ browser's user may be merged into an account, or converted into one in place, while the simulation service is asked: the run is then recorded for the user the check found, or not at all, never for a new user re-created -with the browser's ID. The routes run as the Public API's runtime role. +with the browser's ID. The routes run as API v1's runtime role. """ from __future__ import annotations @@ -44,6 +44,7 @@ from sqlalchemy.orm import sessionmaker from sqlmodel import Session + from tests.integration.conftest import ManagedV2Roles from tests.integration.stored_report_rows import CatalogRows ISSUER = "https://users.example.test/" @@ -66,7 +67,8 @@ def catalog(owner_sessions: sessionmaker[Session]) -> Iterator[CatalogRows]: @pytest.fixture def runtime_sessions( - managed_v2_roles, v2_sessions_as_role: Callable[[str], sessionmaker[Session]] + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> sessionmaker[Session]: return v2_sessions_as_role(managed_v2_roles.runtime) diff --git a/tests/integration/test_v2_user_report_runs.py b/tests/integration/test_v2_user_report_runs.py index 097c4d1c6..53da81948 100644 --- a/tests/integration/test_v2_user_report_runs.py +++ b/tests/integration/test_v2_user_report_runs.py @@ -5,7 +5,7 @@ run, and a re-run while a run is pending or running answers that run rather than 409. A stand-in for the simulation service's client answers so: with a run it names (``joined_run``), or else with a new pending run it stores. The -routes run as the Public API's runtime role and read the report back with +routes run as API v1's runtime role and read the report back with the run the answer names, whichever run is the report's newest. """ @@ -78,6 +78,7 @@ from sqlalchemy.orm import sessionmaker from sqlmodel import Session + from tests.integration.conftest import ManagedV2Roles from tests.integration.stored_report_rows import CatalogRows @@ -98,7 +99,8 @@ def catalog(owner_sessions: sessionmaker[Session]) -> Iterator[CatalogRows]: @pytest.fixture def runtime_sessions( - managed_v2_roles, v2_sessions_as_role: Callable[[str], sessionmaker[Session]] + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> sessionmaker[Session]: return v2_sessions_as_role(managed_v2_roles.runtime) diff --git a/tests/integration/test_v2_user_report_views.py b/tests/integration/test_v2_user_report_views.py index 0c85b67e0..160286125 100644 --- a/tests/integration/test_v2_user_report_views.py +++ b/tests/integration/test_v2_user_report_views.py @@ -5,7 +5,7 @@ wasn't forced, else its newest run that wasn't forced; a forced run is never the default. A report's label and description are the requesting user's saved report's name and description, and null without one. The routes run as -the Public API's runtime role. +API v1's runtime role. """ from __future__ import annotations @@ -52,6 +52,7 @@ from sqlalchemy.orm import sessionmaker from sqlmodel import Session + from tests.integration.conftest import ManagedV2Roles from tests.integration.stored_report_rows import CatalogRows, StoredReport NEWER_VERSIONS = {**CURRENT_VERSIONS, "policyengine_version": "4.3.0"} @@ -74,7 +75,8 @@ def catalog(owner_sessions: sessionmaker[Session]) -> Iterator[CatalogRows]: @pytest.fixture def runtime_sessions( - managed_v2_roles, v2_sessions_as_role: Callable[[str], sessionmaker[Session]] + managed_v2_roles: ManagedV2Roles, + v2_sessions_as_role: Callable[[str], sessionmaker[Session]], ) -> sessionmaker[Session]: return v2_sessions_as_role(managed_v2_roles.runtime) diff --git a/tests/unit/data/fake_driver_connections.py b/tests/unit/data/fake_driver_connections.py index ae9d1ff44..a534e00f0 100644 --- a/tests/unit/data/fake_driver_connections.py +++ b/tests/unit/data/fake_driver_connections.py @@ -13,37 +13,61 @@ import errno import socket import sqlite3 +from typing import TYPE_CHECKING, Any, TypeVar, overload + +if TYPE_CHECKING: + from collections.abc import Callable + +CursorType = TypeVar("CursorType", bound=sqlite3.Cursor) class SocketCarryingConnection(sqlite3.Connection): """A SQLite connection that keeps a socket in ``_sock``, as pymysql's does.""" - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self._sock: socket.socket | None = socket.socket( + socket.AF_INET, socket.SOCK_STREAM + ) self._sock.bind(("127.0.0.1", 0)) - self.socket_fields = { + self.ping_error: Exception | None = None + self.socket_fields: dict[str, int] = { "database_connection.fd": self._sock.fileno(), "database_connection.local_port": self._sock.getsockname()[1], } - def break_like_pymysql(self, error=None): + def break_like_pymysql(self, error: Exception | None = None) -> None: """Lose the connection: drop the socket, as pymysql's _force_close does. With ``error``, the next ping raises it instead of finding a closed SQLite database. """ - self._sock.close() + if self._sock is not None: + self._sock.close() self._sock = None self.ping_error = error super().close() - def cursor(self, *args, **kwargs): - if getattr(self, "ping_error", None) is not None: + @overload + def cursor(self, factory: None = None) -> sqlite3.Cursor: ... + + @overload + def cursor( + self, factory: Callable[[sqlite3.Connection], CursorType] + ) -> CursorType: ... + + def cursor( + self, factory: Callable[[sqlite3.Connection], sqlite3.Cursor] | None = None + ) -> sqlite3.Cursor: + """Raise the error ``break_like_pymysql`` was given, else open a cursor.""" + if self.ping_error is not None: raise self.ping_error - return super().cursor(*args, **kwargs) + if factory is None: + return super().cursor() + return super().cursor(factory) - def close(self): + def close(self) -> None: + """Close the socket, then the SQLite connection.""" if self._sock is not None: self._sock.close() self._sock = None @@ -71,7 +95,7 @@ class OperationalError(sqlite3.OperationalError): """ -def pymysql_lost_connection_error(): +def pymysql_lost_connection_error() -> OperationalError: """Return OperationalError(2013, ...) caused by a ConnectionResetError. This is how pymysql raises a lost connection: its socket read fails, and @@ -85,7 +109,7 @@ def pymysql_lost_connection_error(): return driver_error -def lost_connection_error(): +def lost_connection_error() -> LostConnectionError: """Return a driver error caused by a ConnectionResetError, as pymysql raises it.""" os_error = ConnectionResetError(errno.ECONNRESET, "Connection reset by peer") driver_error = LostConnectionError(2013, "Lost connection to MySQL server") diff --git a/tests/unit/data/orm_access_support.py b/tests/unit/data/orm_access_support.py index 6b4fcce30..637c25021 100644 --- a/tests/unit/data/orm_access_support.py +++ b/tests/unit/data/orm_access_support.py @@ -28,12 +28,15 @@ the named ``DECLARATIVE_BASE_MODULES``, rather than files matched by name. - A session-factory module may also import ``Connection``, open a Connection (``connect()``, ``connection()``, ``get_bind()`` and ``begin()`` on an - engine) and attach listeners for pool, engine or dialect events, which no - other module may do. ``raw_connection()`` hands out the driver's connection, - not SQLAlchemy's, and is reported in every module. -- A finding is allowed when a ``no-orm-form`` exception names its file and, - in ``match``, its ``source``; a ``migration-revision`` exception names a - path pattern the rule test doesn't read. + engine), call a database driver's ``connect`` and attach listeners for pool, + engine or dialect events, which no other module may do. + ``raw_connection()`` hands out the driver's connection, not SQLAlchemy's, + and is reported in every module. +- A finding is allowed when a ``no-orm-form`` exception names its file, in + ``match`` its ``source`` and, when the exception gives one, in ``function`` + the function it is in; a ``migration-revision`` exception names a path + pattern the rule test doesn't read. Each finding records the innermost + class or function whose body holds it. The source checks look for Core rather than for the ORM, so any statement on mapped classes passes. Each file is checked on its own, through its own imports: @@ -48,13 +51,17 @@ A public function of a session-factory module may not return an Engine or Connection, and only a session-factory module may read ``factory.kw["bind"]``. -The rules that go by a method or attribute name alone apply only in modules that +A statement run outside a session is reported with its constant arguments, as +in ``connection.execute('PRAGMA foreign_keys = ON')``, so an exception can name +that one statement. ``.connection()``, ``.get_bind()``, ``.raw_connection()`` +and ``.exec_driver_sql()`` are SQLAlchemy's names and count in every module, as +does a call of ``connect`` from psycopg, psycopg2, pymysql, sqlite3 or +mysql.connector, followed through the module's imports. The rules that go by a +method or attribute name other libraries share apply only in modules that import sqlalchemy or sqlmodel: any ``.table`` read, ``kw["bind"]``, ``.execute()`` on anything not named as a session, ``.scalar()``, ``.scalars()``, ``.stream()`` and ``.stream_scalars()`` on a name such as -``connection``, and the ``.connect()``, ``.connection()``, -``.raw_connection()``, ``.get_bind()``, ``.begin()``, ``.cursor()`` and -``.exec_driver_sql()`` calls. +``connection``, and the ``.connect()``, ``.begin()`` and ``.cursor()`` calls. The checks guard against ordinary Core use, not against deliberate evasion. They don't see imports made through ``importlib`` or ``__import__``, engines or @@ -65,10 +72,11 @@ quoted name inside an annotation such as ``Optional["Table"]``, ``Table`` under another local name such as ``Jobs = Table``, names from ``from sqlalchemy import *``, a ``.table`` read in a module that doesn't import sqlalchemy or sqlmodel, a -Session's ``bind`` attribute, or an event listener whose target and event name -aren't its first two positional arguments, the name a string literal. ``.tables`` -of a MetaData isn't reported when the name holding it doesn't end in -``metadata`` and wasn't assigned ``MetaData(...)``. +statement run on an open driver connection in such a module, a Session's +``bind`` attribute, or an event listener whose target and event name aren't its +first two positional arguments, the name a string literal. ``.tables`` of a +MetaData isn't reported when the name holding it doesn't end in ``metadata`` +and wasn't assigned ``MetaData(...)``. """ from __future__ import annotations @@ -122,12 +130,18 @@ { "policyengine_api/data/orm.py", "policyengine_api/data/orm_pool_events.py", + # API v1's Session factories for commands that run once; unlike orm.py, + # importing it loads no .env file, Cloud SQL connector or pool listeners. + "policyengine_api/data/v1_sessions.py", "policyengine_api/data/v2/database.py", "tests/fixtures/database_sessions.py", # The tests of orm_pool_events drive the pool it listens to: they # invalidate, detach and recycle connections and hold two at once, # which no Session offers. Their statements still run in Sessions. "tests/unit/data/test_orm_pool_events.py", + # The pool event tests' fake database driver: it opens the in-memory + # SQLite connections, shaped like pymysql's, that their engine pools. + "tests/unit/data/fake_driver_connections.py", } ) ENGINE_NAMES = frozenset( @@ -144,13 +158,28 @@ ENGINE_TYPES = frozenset({"AsyncEngine", "Engine"}) # A name such as engine or simulation_engine, but not policyengine. ENGINE_NAME_PATTERN = re.compile(r"(?:^|_)engine$", re.IGNORECASE) -# Calls that open a Connection: on anything, and begin() on an engine. Only a -# session-factory module may make them. -CONNECTION_METHODS = frozenset({"connect", "connection", "get_bind"}) +# Calls that open a Connection, which only a session-factory module may make. +# connection() and get_bind() are SQLAlchemy's names, so they count in every +# module; connect() and begin() on an engine count only beside sqlalchemy, +# because other libraries share those names. +SESSION_CONNECTION_METHODS = frozenset({"connection", "get_bind"}) +CONNECT_METHOD = "connect" ENGINE_TRANSACTION_METHOD = "begin" # The call that hands out the driver's connection beneath SQLAlchemy's, which # no module may make. DRIVER_CONNECTION_METHODS = frozenset({"raw_connection"}) +# The database drivers, and the functions of theirs that open a connection, +# which only a session-factory module may call. +DATABASE_DRIVER_MODULES = ( + "mysql.connector", + "psycopg", + "psycopg2", + "pymysql", + "sqlite3", +) +DRIVER_CONNECT_FUNCTIONS = frozenset( + f"{driver}.connect" for driver in DATABASE_DRIVER_MODULES +) # execute runs only on a name such as session or store_session, which finds a # connection passed around without a Connection annotation. A Result has scalar # and scalars too, so the others are reported only on a name such as connection. @@ -223,8 +252,11 @@ # module that imports sqlalchemy or sqlmodel, any .table is reported. COLUMN_TABLE_ATTRIBUTE = "table" METADATA_SUFFIX = "metadata" -RAW_SQL_FUNCTIONS = frozenset({"TextClause", "literal_column", "text"}) -RAW_SQL_METHODS = frozenset({"cursor", "exec_driver_sql"}) +RAW_SQL_FUNCTIONS = frozenset({"DDL", "TextClause", "literal_column", "text"}) +# exec_driver_sql is SQLAlchemy's name, so it counts in every module; a cursor +# counts only beside sqlalchemy, because every DB-API driver has one. +DRIVER_SQL_METHOD = "exec_driver_sql" +CURSOR_METHOD = "cursor" # A model's schema details given as SQL text: a server default and a partial # index's condition, by keyword, and a check constraint's condition. SCHEMA_DETAIL_KEYWORDS = frozenset( @@ -239,67 +271,87 @@ UNMAPPED_TABLE = "table without a mapped class" # The rule's [[rule.exception]] categories: one construct in one module that -# SQLAlchemy's ORM has no form for, named by the module's path and, in match, -# the finding's source; and a path pattern the rule test doesn't read at all. +# SQLAlchemy's ORM has no form for, named by the module's path, in match the +# finding's source and, in function, the function it is in; and a path pattern +# the rule test doesn't read at all. NO_ORM_FORM = "no-orm-form" MIGRATION_REVISION = "migration-revision" EXCEPTION_CATEGORIES = (NO_ORM_FORM, MIGRATION_REVISION) +# Outside the tests, every no-orm-form exception names its function. +TEST_DIRECTORY = "tests/" +SCOPE_NODES = (ast.AsyncFunctionDef, ast.ClassDef, ast.FunctionDef) @dataclass(frozen=True) class Finding: - """One place where code reaches the database without the ORM.""" + """One place where code reaches the database without the ORM. + + ``function`` is the dotted name of the innermost class or function whose + body holds it, as in ``Reconciler.apply``, or ``None`` at module level. + """ file: str line: int check: str source: str + function: str | None = None def __str__(self) -> str: - """Describe the finding as ``file:line: check: source``.""" - return f"{self.file}:{self.line}: {self.check}: {self.source}" + """Describe the finding as ``file:line: check: source in function``.""" + described = f"{self.file}:{self.line}: {self.check}: {self.source}" + if self.function is None: + return described + return f"{described} in {self.function}" def _matches_module(module_name: str, parent_module: str) -> bool: return module_name == parent_module or module_name.startswith(f"{parent_module}.") -def _orm_library(module_name: str) -> str | None: - """Return the ORM library ``module_name`` belongs to, or ``None``.""" +def _library_of(module_name: str, libraries: Iterable[str]) -> str | None: + """Return the one of ``libraries`` that ``module_name`` belongs to, or ``None``.""" return next( - ( - library - for library in ORM_LIBRARY_MODULES - if _matches_module(module_name, library) - ), + (library for library in libraries if _matches_module(module_name, library)), None, ) -def _orm_library_imports(tree: ast.Module) -> dict[str, str]: - """Map each name imported from sqlalchemy or sqlmodel to its dotted name.""" +def _orm_library(module_name: str) -> str | None: + """Return the ORM library ``module_name`` belongs to, or ``None``.""" + return _library_of(module_name, ORM_LIBRARY_MODULES) + + +def _library_imports(tree: ast.Module, libraries: Iterable[str]) -> dict[str, str]: + """Map each name the module imports from ``libraries`` to its dotted name. + + ``import mysql.connector`` binds ``mysql``, and ``from mysql import + connector`` binds ``connector`` as ``mysql.connector``. + """ + libraries = tuple(libraries) imported: dict[str, str] = {} for node in ast.walk(tree): if isinstance(node, ast.Import): for alias in node.names: - library = _orm_library(alias.name) - if library is None: + if _library_of(alias.name, libraries) is None: continue if alias.asname: imported[alias.asname] = alias.name else: - imported[library] = library - elif ( - isinstance(node, ast.ImportFrom) - and not node.level - and node.module is not None - and _orm_library(node.module) is not None - ): + top_level = alias.name.split(".", 1)[0] + imported[top_level] = top_level + elif isinstance(node, ast.ImportFrom) and not node.level and node.module: for alias in node.names: - imported[alias.asname or alias.name] = f"{node.module}.{alias.name}" + qualified = f"{node.module}.{alias.name}" + if _library_of(qualified, libraries) is not None: + imported[alias.asname or alias.name] = qualified return imported +def _orm_library_imports(tree: ast.Module) -> dict[str, str]: + """Map each name imported from sqlalchemy or sqlmodel to its dotted name.""" + return _library_imports(tree, ORM_LIBRARY_MODULES) + + def _qualified_name(node: ast.expr, imported: Mapping[str, str]) -> str | None: if isinstance(node, ast.Name): return imported.get(node.id) @@ -359,11 +411,12 @@ def _last_name(node: ast.expr) -> str: @dataclass class _Module: - """One scanned file and the names it imports from sqlalchemy or sqlmodel.""" + """One scanned file and the names it imports from the ORM and the drivers.""" file: str tree: ast.Module imported: dict[str, str] + driver_imported: dict[str, str] @property def uses_sqlalchemy(self) -> bool: @@ -449,6 +502,20 @@ def _call_summary(call: ast.Call) -> str: return f"{ast.unparse(call.func)}({', '.join(parts)})" +def _statement_summary(call: ast.Call) -> str: + """Summarize a statement call, its constant arguments written out. + + Any other argument, and any keyword, is ``...``, with a run of them written + once: ``connection.execute('SELECT 1', ...)`` or ``connection.execute(...)``. + """ + parts: list[str] = [] + for argument in [*call.args, *call.keywords]: + part = ast.unparse(argument) if isinstance(argument, ast.Constant) else "..." + if part != "..." or not parts or parts[-1] != "...": + parts.append(part) + return f"{ast.unparse(call.func)}({', '.join(parts)})" + + def _schema_detail_calls(tree: ast.Module, imported: Mapping[str, str]) -> set[int]: """Return the calls given as a default or as an index's or check's condition.""" details = { @@ -540,28 +607,47 @@ def _attribute_findings( def _runs_raw_sql(node: ast.Call, function: str, context: _ModuleContext) -> bool: if function in RAW_SQL_FUNCTIONS: return id(node) not in context.schema_details + if not isinstance(node.func, ast.Attribute): + return False + if node.func.attr == DRIVER_SQL_METHOD: + return True + return context.module.uses_sqlalchemy and node.func.attr == CURSOR_METHOD + + +def _connects_a_driver(node: ast.Call, context: _ModuleContext) -> bool: + """Whether a call opens a database driver's connection outside a factory.""" return ( - context.module.uses_sqlalchemy - and isinstance(node.func, ast.Attribute) - and node.func.attr in RAW_SQL_METHODS + not context.module.is_session_factory + and _qualified_name(node.func, context.module.driver_imported) + in DRIVER_CONNECT_FUNCTIONS + ) + + +def _opens_engine_connection(method: ast.Attribute, context: _ModuleContext) -> bool: + """Whether ``connect()``, or ``begin()`` on an engine, opens a Connection. + + Other libraries share these names, so they count only beside sqlalchemy. + """ + if not context.module.uses_sqlalchemy: + return False + if method.attr == CONNECT_METHOD: + return True + receiver = _last_name(method.value) + return method.attr == ENGINE_TRANSACTION_METHOD and ( + receiver in context.engine_names or bool(ENGINE_NAME_PATTERN.search(receiver)) ) def _opens_connection(node: ast.Call, context: _ModuleContext) -> bool: """Whether a call opens a Connection where it may not, or a driver connection.""" - if not context.module.uses_sqlalchemy or not isinstance(node.func, ast.Attribute): + if not isinstance(node.func, ast.Attribute): return False if node.func.attr in DRIVER_CONNECTION_METHODS: return True if context.module.is_session_factory: return False - if node.func.attr in CONNECTION_METHODS: - return True - if node.func.attr != ENGINE_TRANSACTION_METHOD: - return False - receiver = _last_name(node.func.value) - return receiver in context.engine_names or bool( - ENGINE_NAME_PATTERN.search(receiver) + return node.func.attr in SESSION_CONNECTION_METHODS or _opens_engine_connection( + node.func, context ) @@ -612,12 +698,12 @@ def _call_findings( yield CORE_TABLE_DECLARATION, _call_summary(node) elif _runs_raw_sql(node, function, context): yield RAW_SQL, _call_summary(node) - elif _opens_connection(node, context): + elif _connects_a_driver(node, context) or _opens_connection(node, context): yield CORE_CONNECTION, _call_summary(node) elif listener := _database_event_listener(node, function, context): yield CORE_CONNECTION, listener elif _runs_outside_a_session(node, context): - yield CORE_CONNECTION, f"{ast.unparse(node.func)}(...)" + yield CORE_CONNECTION, _statement_summary(node) def _annotation_text(annotation: ast.expr) -> str: @@ -755,6 +841,31 @@ def _module_context(module: _Module) -> _ModuleContext: ) +def _enclosing_scopes(tree: ast.Module) -> dict[int, str]: + """Map each node in a class's or function's body to that scope's dotted name. + + The innermost scope counts, named as Python's ``__qualname__`` names it + without ````: ``Reconciler.apply.build``. A definition's own + decorators, parameters and annotations belong to the scope around it. + """ + scopes: dict[int, str] = {} + pending: list[tuple[ast.AST, str | None]] = [(tree, None)] + while pending: + node, scope = pending.pop() + if scope is not None: + scopes[id(node)] = scope + if not isinstance(node, SCOPE_NODES): + pending.extend((child, scope) for child in ast.iter_child_nodes(node)) + continue + inner = node.name if scope is None else f"{scope}.{node.name}" + body = {id(statement) for statement in node.body} + pending.extend( + (child, inner if id(child) in body else scope) + for child in ast.iter_child_nodes(node) + ) + return scopes + + def orm_access_findings(sources: Mapping[str, str]) -> list[Finding]: """Return every place the sources reach the database without the ORM. @@ -763,10 +874,22 @@ def orm_access_findings(sources: Mapping[str, str]) -> list[Finding]: findings: list[Finding] = [] for file, source in sorted(sources.items()): tree = ast.parse(source, filename=file) - module = _Module(file=file, tree=tree, imported=_orm_library_imports(tree)) + module = _Module( + file=file, + tree=tree, + imported=_orm_library_imports(tree), + driver_imported=_library_imports(tree, DATABASE_DRIVER_MODULES), + ) context = _module_context(module) + scopes = _enclosing_scopes(tree) findings.extend( - Finding(file, getattr(node, "lineno", 0), check, finding_source) + Finding( + file, + getattr(node, "lineno", 0), + check, + finding_source, + function=scopes.get(id(node)), + ) for node in ast.walk(tree) for check, finding_source in _node_findings(node, context) ) @@ -873,31 +996,30 @@ def unmapped_tables_in_packages( return _unmapped_findings(placed_modules) -def _declared_constructs( - exceptions: Iterable[RuleException], -) -> frozenset[tuple[str, str]]: - """Return the (file, source) pairs the no-orm-form exceptions allow.""" - return frozenset( - (exception.path, exception.match) - for exception in exceptions - if exception.category == NO_ORM_FORM and exception.match is not None +def _names_finding(exception: RuleException, finding: Finding) -> bool: + """Whether a no-orm-form exception allows ``finding``. + + Its ``path`` is the finding's file and its ``match`` the finding's + ``source``, exactly. With a ``function``, the finding is in that function + too; without one, the exception allows the source anywhere in the file. + """ + return ( + exception.category == NO_ORM_FORM + and exception.match is not None + and (exception.path, exception.match) == (finding.file, finding.source) + and exception.function in (None, finding.function) ) def undeclared_findings( findings: Iterable[Finding], exceptions: Iterable[RuleException] ) -> list[Finding]: - """Return the findings that no no-orm-form exception names. - - An exception names a finding when its ``path`` is the finding's file and its - ``match`` is the finding's ``source``, exactly; it then allows every finding - in that file with that source. - """ - declared = _declared_constructs(exceptions) + """Return the findings that no no-orm-form exception names.""" + exceptions = list(exceptions) return [ finding for finding in findings - if (finding.file, finding.source) not in declared + if not any(_names_finding(exception, finding) for exception in exceptions) ] @@ -905,12 +1027,12 @@ def unused_exceptions( findings: Iterable[Finding], exceptions: Iterable[RuleException] ) -> list[RuleException]: """Return each no-orm-form exception that names no finding.""" - found = {(finding.file, finding.source) for finding in findings} + findings = list(findings) return [ exception for exception in exceptions if exception.category == NO_ORM_FORM - and (exception.path, exception.match) not in found + and not any(_names_finding(exception, finding) for finding in findings) ] @@ -927,6 +1049,35 @@ def unscanned_files( ) +def _names_sql_text(match: str) -> bool: + """Whether ``match`` is a call whose first argument is a string or f-string. + + Such a match names one statement, as ``text(f'TRUNCATE {tables}')`` does. A + bare call, a call on variables and an attribute read name none. + """ + try: + expression = ast.parse(match, mode="eval").body + except SyntaxError: + return False + if not isinstance(expression, ast.Call) or not expression.args: + return False + statement = expression.args[0] + return isinstance(statement, ast.JoinedStr) or ( + isinstance(statement, ast.Constant) and isinstance(statement.value, str) + ) + + +def _needs_function(exception: RuleException, match: str) -> bool: + """Whether a no-orm-form exception must name the function it allows. + + Every exception outside the tests does, and so does one whose match names + no statement, which would otherwise allow every such call in its module. + """ + return exception.function is None and ( + not exception.path.startswith(TEST_DIRECTORY) or not _names_sql_text(match) + ) + + def _construct_exception_problem( exception: RuleException, repository_root: Path ) -> str | None: @@ -936,6 +1087,11 @@ def _construct_exception_problem( return f"{where} names no construct: set match to the finding's source" if not (repository_root / exception.path).is_file(): return f"{where} must name one existing file" + if _needs_function(exception, exception.match): + return ( + f"{where} ({exception.match}) needs a function: set function to the " + "enclosing function of its finding" + ) return None @@ -946,6 +1102,8 @@ def _path_exception_problem( where = f"exception for {exception.path}" if exception.match is not None: return f"{where} skips whole files, so it takes no match" + if exception.function is not None: + return f"{where} skips whole files, so it takes no function" if not unscanned_files([exception], repository_root) & read_files: return f"{where} matches no file the rule test reads: remove it" return None @@ -970,7 +1128,7 @@ def exception_problems( read_files: Iterable[str], repository_root: Path, ) -> list[str]: - """Describe each exception with an unknown category, or no module or construct. + """Describe each exception with an unknown category, module, construct or function. ``read_files`` are the repository-relative files the rule test reads before the migration-revision exceptions take theirs out. diff --git a/tests/unit/data/test_database_sessions.py b/tests/unit/data/test_database_sessions.py index 8cf3b0778..67b900e77 100644 --- a/tests/unit/data/test_database_sessions.py +++ b/tests/unit/data/test_database_sessions.py @@ -26,6 +26,7 @@ sqlite_v2_sessions, v2_role_sessions, ) +from tests.integration.alembic_version_rows import current_revision if TYPE_CHECKING: from sqlalchemy.orm import Session, sessionmaker @@ -156,6 +157,14 @@ def test_the_schema_inspector_reads_a_session_or_its_factory() -> None: assert from_session == from_factory +def test_a_database_without_a_version_table_is_at_no_revision() -> None: + """As Alembic's MigrationContext.get_current_revision reads it.""" + with sqlite_v2_sessions() as sessions: + revision = current_revision(sessions) + + assert revision is None + + def test_recorded_statements_are_the_sql_sent_inside() -> None: with sqlite_v2_sessions() as sessions, sessions() as session: session.scalars(select(col(TaxBenefitModel.name))).all() diff --git a/tests/unit/data/test_orm_access_support.py b/tests/unit/data/test_orm_access_support.py index 9422d968e..f3735e0b5 100644 --- a/tests/unit/data/test_orm_access_support.py +++ b/tests/unit/data/test_orm_access_support.py @@ -1108,18 +1108,12 @@ def test_a_name_assigned_a_mapped_class_or_its_table_name_is_not_a_table() -> No def _finding( file: str, source: str, line: int = 1, *, function: str | None = None ) -> Finding: - if function is None: - return Finding(file, line, RAW_SQL, source) return Finding(file, line, RAW_SQL, source, function=function) def _construct_exception( path: str, match: str | None, *, function: str | None = None ) -> RuleException: - if function is None: - return RuleException( - path=path, reason="no ORM form", match=match, category=NO_ORM_FORM - ) return RuleException( path=path, reason="no ORM form", diff --git a/tests/unit/data/test_orm_only.py b/tests/unit/data/test_orm_only.py index 0029a3cc8..204b5a082 100644 --- a/tests/unit/data/test_orm_only.py +++ b/tests/unit/data/test_orm_only.py @@ -7,9 +7,10 @@ write each kind of statement. The checks live in orm_access_support.py. A finding fails unless one of the rule's ``no-orm-form`` [[rule.exception]] -entries names its module and, in ``match``, its source, and an entry that names -no finding fails too. The rule's ``migration-revision`` entry takes -``migrations/`` out of the check. +entries names its module, in ``match`` its source and, when the entry gives +one, in ``function`` the function it is in. An entry that names no finding +fails too. The rule's ``migration-revision`` entry takes ``migrations/`` out of +the check. """ from __future__ import annotations @@ -42,7 +43,7 @@ import pytest - from scripts.rules.model import Rule + from scripts.rules.model import Rule, RuleException PROJECT_ROOT = Path(__file__).parents[3] RULE_ID = "api.data.orm-only" @@ -66,6 +67,12 @@ ) +def _declared_site(exception: RuleException) -> str: + """Describe what an exception names: its file, its match and its function.""" + site = f"{exception.path}: {exception.match}" + return site if exception.function is None else f"{site} in {exception.function}" + + @cache def _rule() -> Rule: registry, violations = load_registry(PROJECT_ROOT) @@ -129,8 +136,7 @@ def test_database_code_uses_only_the_orm() -> None: problems = [str(finding) for finding in undeclared_findings(findings, exceptions)] problems.extend( - f"declared exception names no finding, remove it: {exception.path}: " - f"{exception.match}" + f"declared exception names no finding, remove it: {_declared_site(exception)}" for exception in unused_exceptions(findings, exceptions) ) @@ -157,7 +163,7 @@ def test_orm_only_exceptions_match_a_finding_and_name_a_category() -> None: problems = exception_problems(exceptions, _read_files(), PROJECT_ROOT) problems.extend( - f"exception for {exception.path} names no finding: {exception.match}" + f"exception names no finding: {_declared_site(exception)}" for exception in unused_exceptions(_repository_findings(), exceptions) ) diff --git a/tests/unit/data/test_orm_pool_events.py b/tests/unit/data/test_orm_pool_events.py index 2d44d7e35..faf1150bb 100644 --- a/tests/unit/data/test_orm_pool_events.py +++ b/tests/unit/data/test_orm_pool_events.py @@ -14,7 +14,7 @@ from types import SimpleNamespace import pytest -from sqlalchemy import create_engine, event, exc, literal, select +from sqlalchemy import Engine, create_engine, event, exc, literal, select from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column from sqlalchemy.pool import QueuePool @@ -57,7 +57,7 @@ class MissingRow(_MissingTableBase): id: Mapped[int] = mapped_column(primary_key=True) -def _select_one(engine): +def _select_one(engine: Engine) -> int: """Check a connection out of the pool, pinging it, and select 1 in a Session.""" with Session(engine) as session: return session.execute(select(literal(1))).scalar_one() diff --git a/tests/unit/data/test_orm_sessions.py b/tests/unit/data/test_orm_sessions.py index 161896dff..692802dc9 100644 --- a/tests/unit/data/test_orm_sessions.py +++ b/tests/unit/data/test_orm_sessions.py @@ -1,9 +1,6 @@ -from unittest.mock import Mock - import pytest from sqlalchemy import select from sqlalchemy.orm import Session -from sqlalchemy.pool import NullPool import policyengine_api.data.orm as orm_module from policyengine_api.data.orm import get_v1_session_factory @@ -77,17 +74,3 @@ def test_runtime_factory_is_cached_and_has_no_local_selector(monkeypatch): assert _stored_household_hashes(session) == ["served"] finally: orm_module.clear_v1_session_factories() - - -def test_unpooled_sessions_keep_no_pool_and_dispose_of_their_engine(monkeypatch): - engine = Mock() - engine_factory = Mock(return_value=engine) - monkeypatch.setattr(orm_module, "create_engine", engine_factory) - url = "mysql+pymysql://migrator:password@127.0.0.1:3307/policyengine" - - with orm_module.unpooled_v1_sessions(url) as sessions: - assert sessions.kw["expire_on_commit"] is False - engine.dispose.assert_not_called() - - engine_factory.assert_called_once_with(url, poolclass=NullPool) - engine.dispose.assert_called_once_with() diff --git a/tests/unit/data/test_v1_sessions.py b/tests/unit/data/test_v1_sessions.py new file mode 100644 index 000000000..242b5bab1 --- /dev/null +++ b/tests/unit/data/test_v1_sessions.py @@ -0,0 +1,37 @@ +"""Tests of API v1's Session factories for commands that run once.""" + +from unittest.mock import Mock + +import pytest +from sqlalchemy.pool import NullPool + +from policyengine_api.data import v1_sessions +from policyengine_api.data.v1_models import Policy +from tests.fixtures.database_sessions import sqlite_v1_sessions + + +def test_unpooled_sessions_keep_no_pool_and_dispose_of_their_engine( + monkeypatch: pytest.MonkeyPatch, +) -> None: + engine = Mock() + engine_factory = Mock(return_value=engine) + monkeypatch.setattr(v1_sessions, "create_engine", engine_factory) + url = "mysql+pymysql://migrator:password@127.0.0.1:3307/policyengine" + + with v1_sessions.unpooled_v1_sessions(url) as sessions: + assert sessions.kw["expire_on_commit"] is False + engine.dispose.assert_not_called() + + engine_factory.assert_called_once_with(url, poolclass=NullPool) + engine.dispose.assert_called_once_with() + + +def test_schema_inspector_reads_a_factory_and_a_session_in_its_transaction() -> None: + with sqlite_v1_sessions() as sessions: + factory_tables = v1_sessions.v1_schema_inspector(sessions).get_table_names() + with sessions() as session: + session_tables = v1_sessions.v1_schema_inspector(session).get_table_names() + assert session.in_transaction() + + assert Policy.__tablename__ in factory_tables + assert session_tables == factory_tables diff --git a/tests/unit/test_alembic_workflows.py b/tests/unit/test_alembic_workflows.py index b1f49c857..9ac642958 100644 --- a/tests/unit/test_alembic_workflows.py +++ b/tests/unit/test_alembic_workflows.py @@ -266,6 +266,22 @@ def test_reusable_v2_integration_check_runs_the_dynamic_persistence_tests(): assert "test_alembic_v2_dynamics.py" not in workflow +def test_reusable_v2_integration_check_runs_the_persistent_migration_target_tests() -> ( + None +): + """The persistent target checks run after the managed roles get their privileges. + + They act as temporary roles through ``v2_sessions_as_role``, as the other + tests in their step act as roles. + """ + workflow = _workflow("v2-integration-check.yml") + + privileges_applied = workflow.index("reconcile_v2_privileges.py apply") + assert privileges_applied < workflow.index( + "tests/integration/test_v2_migration_target_persistent.py" + ) + + def test_reusable_v2_integration_check_uses_disposable_databases_and_coverage(): workflow = _workflow("v2-integration-check.yml") diff --git a/tests/unit/v2/test_alembic_v2_revisions.py b/tests/unit/v2/test_alembic_v2_revisions.py index 0f0c7fe36..6231fa35e 100644 --- a/tests/unit/v2/test_alembic_v2_revisions.py +++ b/tests/unit/v2/test_alembic_v2_revisions.py @@ -10,17 +10,10 @@ from alembic.config import Config from alembic.script import ScriptDirectory -from sqlalchemy import inspect from policyengine_api.constants import REPO from policyengine_api.data.v2.migration_target import V2_ALEMBIC_HEAD_REVISION -from policyengine_api.data.v2.models import User - -# Every v2 table, by the mapped classes on the v2 models' registry. -V2_TABLE_NAMES = frozenset( - mapper.class_.__tablename__ for mapper in inspect(User).registry.mappers -) - +from policyengine_api.data.v2.models import V2_TABLE_NAMES POST_BASELINE_TABLE_NAMES = frozenset( { @@ -407,7 +400,7 @@ def test_stage_12a_user_identity_and_association_revision_is_generated() -> None assert "Post-generation" not in revision assert "op.execute(" not in revision assert "op.bulk_insert(" not in revision - # The previous Public API revision still maps the retired country and label + # The previous API v1 revision still maps the retired country and label # columns, so the upgrade relaxes them instead of dropping anything. upgrade = revision[ revision.index("def upgrade()") : revision.index("def downgrade()") diff --git a/tests/unit/v2/test_database.py b/tests/unit/v2/test_database.py index fcea49791..8bae7f470 100644 --- a/tests/unit/v2/test_database.py +++ b/tests/unit/v2/test_database.py @@ -1,10 +1,14 @@ """Tests for lazy process-owned v2 engine and SQLModel Session factories.""" -from collections.abc import Iterator +from collections.abc import Callable, Iterator +from contextlib import AbstractContextManager from pathlib import Path +from unittest.mock import Mock import pytest from sqlalchemy.orm import Session as OrmSession +from sqlalchemy.orm import sessionmaker +from sqlalchemy.pool import NullPool from sqlmodel import Session, select from policyengine_api.data.v1_models import Policy @@ -173,6 +177,28 @@ def test_read_sessions_refuse_to_write_rows() -> None: assert session.exec(select(TaxBenefitModel)).all() == [] +@pytest.mark.parametrize( + "unpooled_sessions", + [database.unpooled_v2_sessions, database.unpooled_v2_read_only_sessions], + ids=["read-write", "read-only"], +) +def test_unpooled_sessions_keep_no_pool_and_dispose_of_their_engine( + monkeypatch: pytest.MonkeyPatch, + unpooled_sessions: Callable[[str], AbstractContextManager[sessionmaker[Session]]], +) -> None: + engine = Mock() + engine_factory = Mock(return_value=engine) + monkeypatch.setattr(database, "create_engine", engine_factory) + + with unpooled_sessions(UNCONNECTED_POSTGRES_URL) as sessions: + assert sessions.kw["expire_on_commit"] is False + assert issubclass(sessions.class_, Session) + engine.dispose.assert_not_called() + + engine_factory.assert_called_once_with(UNCONNECTED_POSTGRES_URL, poolclass=NullPool) + engine.dispose.assert_called_once_with() + + def test_unpooled_read_only_sessions_make_every_transaction_read_only() -> None: """Every Session's engine has SQLAlchemy's ``postgresql_readonly`` option. diff --git a/tests/unit/v2/test_dynamic_catalog.py b/tests/unit/v2/test_dynamic_catalog.py index abfc175e7..4ceda392c 100644 --- a/tests/unit/v2/test_dynamic_catalog.py +++ b/tests/unit/v2/test_dynamic_catalog.py @@ -18,6 +18,7 @@ MetadataCatalogUnavailableError, ) from policyengine_api.data.v2.models import ( + V2_REGISTRY, Dynamic, Parameter, TaxBenefitModel, @@ -84,10 +85,6 @@ def __init__(self, session: Session) -> None: session.commit() -# The registry every v2 model is mapped on, SQLModel's own. -V2_REGISTRY = TaxBenefitModel._sa_registry - - @pytest.fixture def sessions() -> Iterator[sessionmaker[Session]]: """Return Session factories of an in-memory SQLite copy of the v2 schema.""" @@ -97,7 +94,7 @@ def sessions() -> Iterator[sessionmaker[Session]]: @pytest.fixture def session(sessions: sessionmaker[Session]) -> Iterator[Session]: - with sessions() as database_session: + with sessions(expire_on_commit=True) as database_session: yield database_session diff --git a/tests/unit/v2/test_metadata_validation.py b/tests/unit/v2/test_metadata_validation.py index 4a767e90f..c084cd86e 100644 --- a/tests/unit/v2/test_metadata_validation.py +++ b/tests/unit/v2/test_metadata_validation.py @@ -8,19 +8,11 @@ V2MetadataValidationError, validate_v2_metadata_table_names, ) -from policyengine_api.data.v2.models import TaxBenefitModel - -# The registry every v2 model is mapped on, SQLModel's own. -V2_REGISTRY = TaxBenefitModel._sa_registry - - -def _v2_table_names() -> set[str]: - """Return the name of every table a v2 model maps.""" - return {mapper.class_.__tablename__ for mapper in V2_REGISTRY.mappers} +from policyengine_api.data.v2.models import V2_TABLE_NAMES def test_current_metadata_contains_no_rejected_tables() -> None: - validate_v2_metadata_table_names(_v2_table_names()) + validate_v2_metadata_table_names(V2_TABLE_NAMES) @pytest.mark.parametrize( @@ -29,23 +21,23 @@ def test_current_metadata_contains_no_rejected_tables() -> None: ) def test_known_rejected_tables_are_identified(table_name: str) -> None: with pytest.raises(V2MetadataValidationError, match=table_name): - validate_v2_metadata_table_names({*_v2_table_names(), table_name}) + validate_v2_metadata_table_names({*V2_TABLE_NAMES, table_name}) def test_rejection_sets_do_not_block_current_metadata() -> None: - table_names = _v2_table_names() + table_names = V2_TABLE_NAMES assert table_names.isdisjoint(PROHIBITED_V2_TABLES) assert table_names.isdisjoint(V1_ONLY_TABLES) def test_new_table_name_requires_no_allowlist_update() -> None: - validate_v2_metadata_table_names({*_v2_table_names(), "future_domain_table"}) + validate_v2_metadata_table_names({*V2_TABLE_NAMES, "future_domain_table"}) @pytest.mark.parametrize("table_name", ["simulations", "simulation_runs"]) def test_names_shared_with_v1_are_accepted(table_name: str) -> None: """v2 reuses these v1 table names for its own tables, in its own database.""" - assert table_name in _v2_table_names() + assert table_name in V2_TABLE_NAMES assert table_name not in V1_ONLY_TABLES - validate_v2_metadata_table_names({*_v2_table_names(), table_name}) + validate_v2_metadata_table_names({*V2_TABLE_NAMES, table_name}) diff --git a/tests/unit/v2/test_models.py b/tests/unit/v2/test_models.py index 3d87687ed..d3d9c7c59 100644 --- a/tests/unit/v2/test_models.py +++ b/tests/unit/v2/test_models.py @@ -362,7 +362,7 @@ def test_user_type_defaults_to_standard_for_every_writer() -> None: assert not users.user_type.nullable assert users.user_type.type.length == 16 - # The server default covers inserts by Public API revisions that predate + # The server default covers inserts by API v1 revisions that predate # the column; the Python default covers this revision's ORM inserts. assert users.user_type.server_default.arg == "standard" assert User().user_type == "standard" @@ -592,7 +592,7 @@ def test_saved_simulations_and_reports_name_stored_v2_rows() -> None: reports = stored_v2_table("user_report_associations") report_columns = model_columns("user_report_associations") - # The retired columns stay, nullable, for the previous Public API revision. + # The retired columns stay, nullable, for the previous API v1 revision. for table_name in ("user_simulation_associations", "user_report_associations"): columns = model_columns(table_name) assert columns.country.nullable diff --git a/tests/unit/v2/test_policy_catalog.py b/tests/unit/v2/test_policy_catalog.py index a225f2e2c..362b31ac9 100644 --- a/tests/unit/v2/test_policy_catalog.py +++ b/tests/unit/v2/test_policy_catalog.py @@ -47,7 +47,10 @@ class StoredCatalog: @pytest.fixture def stored_catalog() -> Iterator[StoredCatalog]: - with sqlite_v2_sessions() as sessions, sessions() as session: + with ( + sqlite_v2_sessions() as sessions, + sessions(expire_on_commit=True) as session, + ): us_model = TaxBenefitModel(name="policyengine-us") current = TaxBenefitModelVersion( model=us_model, diff --git a/tests/unit/v2/test_policy_legacy_copy.py b/tests/unit/v2/test_policy_legacy_copy.py index 0947c039a..22192d38d 100644 --- a/tests/unit/v2/test_policy_legacy_copy.py +++ b/tests/unit/v2/test_policy_legacy_copy.py @@ -146,7 +146,7 @@ class ReusedProductionPolicy: # The two production copies that failed after dual-write was turned on: each # POST matched an existing v1 row saved under a country package release many -# versions older than the one the Public API ran (us 2.2.1, uk 2.130.1). +# versions older than the one API v1 ran (us 2.2.1, uk 2.130.1). PRODUCTION_REUSED_POLICIES = [ pytest.param( ReusedProductionPolicy("us", 96567, "1.633.2", "gov.dol.minimum_wage", 9), @@ -208,7 +208,7 @@ def test_policy_with_a_country_package_the_api_does_not_run_is_copied( catalog_session: Session, recorded_writes: RecordedCopyWrites, ) -> None: - # The copy binds content to the running catalog, as the Public API binds an + # The copy binds content to the running catalog, as API v1 binds an # old policy to the running country package when it simulates one. _add_running_catalog( catalog_session, country_id="us", parameter_names=["gov.example.rate"] diff --git a/tests/unit/v2/test_privilege_manifest.py b/tests/unit/v2/test_privilege_manifest.py index b792f3599..1a5432acf 100644 --- a/tests/unit/v2/test_privilege_manifest.py +++ b/tests/unit/v2/test_privilege_manifest.py @@ -481,7 +481,7 @@ def test_the_public_api_revokes_and_accepts_invitations_but_never_deletes_them() def test_the_public_api_records_each_users_report_run_requests() -> None: - """The Public API writes a user's record of each report run they asked for. + """API v1 writes a user's record of each report run they asked for. It reads, adds and deletes them, but never changes one: a later request for the same run is the same record. No other role reads them. diff --git a/tests/unit/v2/test_simulation_run_models.py b/tests/unit/v2/test_simulation_run_models.py index 94222c6cf..abe87c52d 100644 --- a/tests/unit/v2/test_simulation_run_models.py +++ b/tests/unit/v2/test_simulation_run_models.py @@ -68,7 +68,7 @@ "program_statistics", "withheld_area_codes", ) -# The tables the simulation service and its Modal workers write. The Public API +# The tables the simulation service and its Modal workers write. API v1 # writes every other table. SIMULATION_SIDE_TABLES = frozenset( { @@ -86,7 +86,7 @@ *COMPARISON_RESULT_TABLES, } ) -# The foreign keys from the simulation service's tables to the Public API's rows, +# The foreign keys from the simulation service's tables to API v1's rows, # with their delete rules. Each service writes only its own tables, and # PostgreSQL checks every row named on insert. PUBLIC_API_FOREIGN_KEYS = { From 6bcd4ea9751bc42e3ef36d638461f935fc77f6a5 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:49:37 +0400 Subject: [PATCH 16/20] Test review round 2's findings in the ORM rule's checker (failing) - An exception counts as naming SQL text only for a raw SQL construct or a statement method whose first argument holds literal SQL, so entries such as sqlite3.connect(':memory:') or text(f'{statement}') must name their function. - An entry can name module level as its function (), so a finding at module level outside tests can be declared. - Opening a driver connection another way (psycopg.Connection.connect, pymysql.Connect, sqlite3.Connection(...) and the like) is reported outside session-factory modules. Co-Authored-By: Claude Opus 5.5 --- tests/unit/data/orm_access_examples.py | 11 + tests/unit/data/test_orm_access_support.py | 355 +++++------------- tests/unit/data/test_orm_only_exceptions.py | 379 ++++++++++++++++++++ 3 files changed, 474 insertions(+), 271 deletions(-) create mode 100644 tests/unit/data/orm_access_examples.py create mode 100644 tests/unit/data/test_orm_only_exceptions.py diff --git a/tests/unit/data/orm_access_examples.py b/tests/unit/data/orm_access_examples.py new file mode 100644 index 000000000..d6341c130 --- /dev/null +++ b/tests/unit/data/orm_access_examples.py @@ -0,0 +1,11 @@ +"""Example file names the tests of rule api.data.orm-only's checks scan. + +Each names the kind of module the checks treat it as: an ordinary store, a +session-factory module, a declarative-base module, routes and models. +""" + +STORE = "policyengine_api/data/v2/example_store.py" +SESSION_FACTORY = "policyengine_api/data/v2/database.py" +DECLARATIVE_BASE = "policyengine_api/data/v1_models.py" +ROUTES = "policyengine_api/routes/example_routes.py" +MODELS = "policyengine_api/data/v2/example_models.py" diff --git a/tests/unit/data/test_orm_access_support.py b/tests/unit/data/test_orm_access_support.py index f3735e0b5..43e46a4f1 100644 --- a/tests/unit/data/test_orm_access_support.py +++ b/tests/unit/data/test_orm_access_support.py @@ -1,9 +1,10 @@ -"""Unit tests for the checks behind rule api.data.orm-only. +"""Unit tests for the checks behind rule api.data.orm-only: what they report. Ported from policyengine-sim-api's tests of the checker behind sim.persistence.orm-only, with tests added for this repository's changes: SQLModel's names, the named session-factory and declarative-base modules, event -listeners, and the rule's exceptions. +listeners and database drivers. test_orm_only_exceptions.py tests the rule's +exceptions and the function each finding records. """ from __future__ import annotations @@ -15,32 +16,25 @@ import pytest -from scripts.rules.model import RuleException +from tests.unit.data.orm_access_examples import ( + DECLARATIVE_BASE, + MODELS, + ROUTES, + SESSION_FACTORY, + STORE, +) from tests.unit.data.orm_access_support import ( CORE_CONNECTION, CORE_TABLE_ACCESS, CORE_TABLE_DECLARATION, DECLARATIVE_BASE_MODULES, - MIGRATION_REVISION, - NO_ORM_FORM, RAW_SQL, SESSION_FACTORY_MODULES, UNMAPPED_TABLE, - Finding, - exception_problems, orm_access_findings, - undeclared_findings, unmapped_table_findings, - unscanned_files, - unused_exceptions, ) -STORE = "policyengine_api/data/v2/example_store.py" -SESSION_FACTORY = "policyengine_api/data/v2/database.py" -DECLARATIVE_BASE = "policyengine_api/data/v1_models.py" -ROUTES = "policyengine_api/routes/example_routes.py" -MODELS = "policyengine_api/data/v2/example_models.py" - def _checks(sources: dict[str, str], file: str) -> list[tuple[str, str]]: """Return the (check, source) findings in ``file``.""" @@ -574,25 +568,6 @@ def test_a_statement_outside_a_session_reports_its_constant_arguments( assert _checks({STORE: source}, STORE) == [(CORE_CONNECTION, summary)] -def test_an_exception_for_one_constant_statement_allows_no_other() -> None: - source = """ - import sqlalchemy - - sqlite_connection.execute("PRAGMA foreign_keys = ON") - sqlite_connection.execute("DELETE FROM reports") - """ - findings = orm_access_findings({STORE: dedent(source)}) - exceptions = [ - _construct_exception( - STORE, "sqlite_connection.execute('PRAGMA foreign_keys = ON')" - ) - ] - - assert [ - finding.source for finding in undeclared_findings(findings, exceptions) - ] == ["sqlite_connection.execute('DELETE FROM reports')"] - - @pytest.mark.parametrize( ("call", "expected"), [ @@ -679,6 +654,80 @@ def test_a_statement_on_a_driver_connection_is_reported_where_it_connects() -> N ] +@pytest.mark.parametrize( + ("imports", "call", "summary"), + [ + ( + "import psycopg", + "psycopg.Connection.connect(url)", + "psycopg.Connection.connect(url)", + ), + ( + "import psycopg", + "psycopg.AsyncConnection.connect(url)", + "psycopg.AsyncConnection.connect(url)", + ), + ( + "from psycopg import Connection", + "Connection.connect(url)", + "Connection.connect(url)", + ), + ( + "from psycopg.connection import Connection", + "Connection.connect(url)", + "Connection.connect(url)", + ), + ("import pymysql", "pymysql.Connect(host='localhost')", "pymysql.Connect(...)"), + ( + "import pymysql", + "pymysql.connections.Connection(host='localhost')", + "pymysql.connections.Connection(...)", + ), + ( + "from pymysql.connections import Connection", + "Connection(host='localhost')", + "Connection(...)", + ), + ( + "import sqlite3", + "sqlite3.Connection(':memory:')", + "sqlite3.Connection(':memory:')", + ), + ( + "import mysql.connector", + "mysql.connector.Connect(user='root')", + "mysql.connector.Connect(...)", + ), + ], +) +def test_a_driver_connection_opened_another_way_is_reported( + imports: str, call: str, summary: str +) -> None: + """A driver's connection class, or its connect, opens a connection too.""" + source = f"{imports}\n\ndriver_connection = {call}\n" + + assert _checks({ROUTES: source}, ROUTES) == [(CORE_CONNECTION, summary)] + assert _checks({SESSION_FACTORY: source}, SESSION_FACTORY) == [] + + +@pytest.mark.parametrize( + "source", + [ + "def check(value: sqlite3.Connection) -> bool:\n" + " return isinstance(value, sqlite3.Connection)", + "class RecordingConnection(sqlite3.Connection):\n pass", + "error = psycopg.OperationalError('connection lost')", + "rows = psycopg.Cursor", + ], +) +def test_naming_a_drivers_connection_class_without_calling_it_is_not_reported( + source: str, +) -> None: + module = f"import psycopg\nimport sqlite3\n\n{source}\n" + + assert _checks({ROUTES: module}, ROUTES) == [] + + def test_a_session_factory_module_hands_out_no_engine_or_connection() -> None: source = """ from sqlalchemy import Connection, Engine, create_engine @@ -1103,239 +1152,3 @@ def test_a_name_assigned_a_mapped_class_or_its_table_name_is_not_a_table() -> No """ assert _checks({STORE: store}, STORE) == [] - - -def _finding( - file: str, source: str, line: int = 1, *, function: str | None = None -) -> Finding: - return Finding(file, line, RAW_SQL, source, function=function) - - -def _construct_exception( - path: str, match: str | None, *, function: str | None = None -) -> RuleException: - return RuleException( - path=path, - reason="no ORM form", - match=match, - category=NO_ORM_FORM, - function=function, - ) - - -def test_each_finding_names_the_function_it_is_in() -> None: - source = """ - import sqlalchemy as sa - - module_statement = sa.text("SELECT 1") - - def reconcile(): - return sa.text("SELECT 2") - - class Reconciler: - class_statement = sa.text("SELECT 3") - - def apply(self): - def build(): - return sa.text("SELECT 4") - - return sa.text("SELECT 5") - - async def read(): - return sa.text("SELECT 6") - """ - - findings = orm_access_findings({STORE: dedent(source)}) - - assert [(finding.source, finding.function) for finding in findings] == [ - ("sa.text('SELECT 1')", None), - ("sa.text('SELECT 2')", "reconcile"), - ("sa.text('SELECT 3')", "Reconciler"), - ("sa.text('SELECT 4')", "Reconciler.apply.build"), - ("sa.text('SELECT 5')", "Reconciler.apply"), - ("sa.text('SELECT 6')", "read"), - ] - - -def test_a_finding_in_a_function_names_it_when_described() -> None: - in_function = _finding(STORE, "text(statement)", line=3, function="apply_grants") - - assert str(in_function) == f"{STORE}:3: raw SQL: text(statement) in apply_grants" - assert str(_finding(STORE, "text(statement)", line=3)) == ( - f"{STORE}:3: raw SQL: text(statement)" - ) - - -def test_an_exception_with_a_function_allows_findings_only_in_that_function() -> None: - granting = _finding(STORE, "text(statement)", line=3, function="apply_grants") - reading = _finding(STORE, "text(statement)", line=9, function="read_roles") - module_level = _finding(STORE, "text(statement)", line=12) - exceptions = [ - _construct_exception(STORE, "text(statement)", function="apply_grants") - ] - - assert undeclared_findings([granting, reading, module_level], exceptions) == [ - reading, - module_level, - ] - - -def test_an_exception_with_a_function_is_unused_without_a_finding_there() -> None: - findings = [_finding(STORE, "text(statement)", function="read_roles")] - in_its_function = _construct_exception( - STORE, "text(statement)", function="read_roles" - ) - elsewhere = _construct_exception(STORE, "text(statement)", function="apply_grants") - anywhere_in_the_module = _construct_exception(STORE, "text(statement)") - - assert unused_exceptions( - findings, [in_its_function, elsewhere, anywhere_in_the_module] - ) == [elsewhere] - - -def test_an_exception_allows_every_finding_with_its_file_and_source() -> None: - set_role = "text(f'SET ROLE {role}')" - findings = [ - _finding(STORE, set_role, line=3), - _finding(STORE, set_role, line=9), - _finding(STORE, "text('RESET ROLE')", line=12), - _finding(SESSION_FACTORY, set_role, line=4), - ] - exceptions = [_construct_exception(STORE, set_role)] - - assert undeclared_findings(findings, exceptions) == [ - _finding(STORE, "text('RESET ROLE')", line=12), - _finding(SESSION_FACTORY, set_role, line=4), - ] - - -def test_an_exception_that_names_no_finding_is_unused() -> None: - findings = [_finding(STORE, "text('RESET ROLE')")] - used = _construct_exception(STORE, "text('RESET ROLE')") - other_file = _construct_exception(SESSION_FACTORY, "text('RESET ROLE')") - other_source = _construct_exception(STORE, "text('SET ROLE owner')") - path_exception = RuleException( - path="migrations/**/*.py", reason="revisions", category=MIGRATION_REVISION - ) - - assert unused_exceptions( - findings, [used, other_file, other_source, path_exception] - ) == [other_file, other_source] - - -def test_a_path_exception_takes_its_files_out_of_the_check(tmp_path: Path) -> None: - for file in ("migrations/v2/env.py", "migrations/v2/versions/one.py", "app.py"): - (tmp_path / file).parent.mkdir(parents=True, exist_ok=True) - (tmp_path / file).write_text("", encoding="utf-8") - exceptions = [ - RuleException( - path="migrations/**/*.py", reason="revisions", category=MIGRATION_REVISION - ), - _construct_exception("app.py", "text('SELECT 1')"), - ] - - assert unscanned_files(exceptions, tmp_path) == { - "migrations/v2/env.py", - "migrations/v2/versions/one.py", - } - - -def test_exception_problems_name_each_unusable_exception(tmp_path: Path) -> None: - (tmp_path / "migrations").mkdir() - (tmp_path / "migrations" / "env.py").write_text("", encoding="utf-8") - (tmp_path / "tests").mkdir() - (tmp_path / "tests" / "store.py").write_text("", encoding="utf-8") - exceptions = [ - _construct_exception("tests/store.py", "text('SELECT 1')"), - _construct_exception("tests/store.py", None), - _construct_exception("tests/missing.py", "text('SELECT 1')"), - RuleException( - path="migrations/*.py", reason="revisions", category=MIGRATION_REVISION - ), - RuleException( - path="migrations/*.py", - reason="revisions", - match="text('SELECT 1')", - category=MIGRATION_REVISION, - ), - RuleException( - path="scripts/*.py", reason="scripts", category=MIGRATION_REVISION - ), - RuleException(path="tests/store.py", reason="no category"), - RuleException(path="tests/store.py", reason="driver", category="driver-access"), - ] - - assert exception_problems( - exceptions, ["migrations/env.py", "tests/store.py"], tmp_path - ) == [ - "exception for tests/store.py names no construct: set match to the " - "finding's source", - "exception for tests/missing.py must name one existing file", - "exception for migrations/*.py skips whole files, so it takes no match", - "exception for scripts/*.py matches no file the rule test reads: remove it", - "exception for tests/store.py has unknown category None: use one of " - "['no-orm-form', 'migration-revision']", - "exception for tests/store.py has unknown category 'driver-access': use " - "one of ['no-orm-form', 'migration-revision']", - ] - - -def test_exceptions_outside_tests_or_naming_no_sql_text_need_a_function( - tmp_path: Path, -) -> None: - """Production entries, and entries whose match holds no SQL, name a function. - - An entry whose match is a bare call, a call on variables or an attribute - read would otherwise allow every such call in the module. - """ - for file in ("policyengine_api/store.py", "scripts/migrate.py", "tests/rows.py"): - (tmp_path / file).parent.mkdir(parents=True, exist_ok=True) - (tmp_path / file).write_text("", encoding="utf-8") - store, script, rows = ( - "policyengine_api/store.py", - "scripts/migrate.py", - "tests/rows.py", - ) - exceptions = [ - _construct_exception(store, "sa.text(f'ANALYZE {tables}')"), - _construct_exception(store, "text(statement)", function="apply_grants"), - _construct_exception(script, "session.connection()"), - _construct_exception(rows, "text(statement)"), - _construct_exception(rows, "session.get_bind()"), - _construct_exception(rows, "mapper.local_table"), - _construct_exception(rows, "session.get_bind()", function="Rows.dialect"), - _construct_exception(rows, "text(f'TRUNCATE {tables} CASCADE')"), - _construct_exception( - rows, "sqlite_connection.execute('PRAGMA foreign_keys = ON')" - ), - ] - - assert exception_problems(exceptions, [], tmp_path) == [ - f"exception for {store} (sa.text(f'ANALYZE {{tables}}')) needs a " - "function: set function to the enclosing function of its finding", - f"exception for {script} (session.connection()) needs a function: set " - "function to the enclosing function of its finding", - f"exception for {rows} (text(statement)) needs a function: set function " - "to the enclosing function of its finding", - f"exception for {rows} (session.get_bind()) needs a function: set " - "function to the enclosing function of its finding", - f"exception for {rows} (mapper.local_table) needs a function: set " - "function to the enclosing function of its finding", - ] - - -def test_a_path_exception_takes_no_function(tmp_path: Path) -> None: - (tmp_path / "migrations").mkdir() - (tmp_path / "migrations" / "env.py").write_text("", encoding="utf-8") - exceptions = [ - RuleException( - path="migrations/*.py", - reason="revisions", - category=MIGRATION_REVISION, - function="run_migrations_online", - ) - ] - - assert exception_problems(exceptions, ["migrations/env.py"], tmp_path) == [ - "exception for migrations/*.py skips whole files, so it takes no function" - ] diff --git a/tests/unit/data/test_orm_only_exceptions.py b/tests/unit/data/test_orm_only_exceptions.py new file mode 100644 index 000000000..1870fb19b --- /dev/null +++ b/tests/unit/data/test_orm_only_exceptions.py @@ -0,0 +1,379 @@ +"""Unit tests for rule api.data.orm-only's exceptions. + +They test how a ``no-orm-form`` exception names findings, by file, source and +function, the ```` marker, which entries need a function, the +``migration-revision`` path exceptions, the problems ``exception_problems`` +reports, and the function each finding records. test_orm_access_support.py +tests what the checks report. +""" + +from __future__ import annotations + +from textwrap import dedent +from typing import TYPE_CHECKING + +import pytest + +from scripts.rules.model import RuleException +from tests.unit.data.orm_access_examples import SESSION_FACTORY, STORE +from tests.unit.data.orm_access_support import ( + MIGRATION_REVISION, + NO_ORM_FORM, + RAW_SQL, + Finding, + exception_problems, + orm_access_findings, + undeclared_findings, + unscanned_files, + unused_exceptions, +) + +if TYPE_CHECKING: + from pathlib import Path + + +def _finding( + file: str, source: str, line: int = 1, *, function: str | None = None +) -> Finding: + return Finding(file, line, RAW_SQL, source, function=function) + + +def _construct_exception( + path: str, match: str | None, *, function: str | None = None +) -> RuleException: + return RuleException( + path=path, + reason="no ORM form", + match=match, + category=NO_ORM_FORM, + function=function, + ) + + +def test_each_finding_names_the_function_it_is_in() -> None: + source = """ + import sqlalchemy as sa + + module_statement = sa.text("SELECT 1") + + def reconcile(): + return sa.text("SELECT 2") + + class Reconciler: + class_statement = sa.text("SELECT 3") + + def apply(self): + def build(): + return sa.text("SELECT 4") + + return sa.text("SELECT 5") + + async def read(): + return sa.text("SELECT 6") + """ + + findings = orm_access_findings({STORE: dedent(source)}) + + assert [(finding.source, finding.function) for finding in findings] == [ + ("sa.text('SELECT 1')", None), + ("sa.text('SELECT 2')", "reconcile"), + ("sa.text('SELECT 3')", "Reconciler"), + ("sa.text('SELECT 4')", "Reconciler.apply.build"), + ("sa.text('SELECT 5')", "Reconciler.apply"), + ("sa.text('SELECT 6')", "read"), + ] + + +def test_a_finding_in_a_function_names_it_when_described() -> None: + in_function = _finding(STORE, "text(statement)", line=3, function="apply_grants") + + assert str(in_function) == f"{STORE}:3: raw SQL: text(statement) in apply_grants" + assert str(_finding(STORE, "text(statement)", line=3)) == ( + f"{STORE}:3: raw SQL: text(statement)" + ) + + +def test_an_exception_with_a_function_allows_findings_only_in_that_function() -> None: + granting = _finding(STORE, "text(statement)", line=3, function="apply_grants") + reading = _finding(STORE, "text(statement)", line=9, function="read_roles") + module_level = _finding(STORE, "text(statement)", line=12) + exceptions = [ + _construct_exception(STORE, "text(statement)", function="apply_grants") + ] + + assert undeclared_findings([granting, reading, module_level], exceptions) == [ + reading, + module_level, + ] + + +def test_an_exception_with_a_function_is_unused_without_a_finding_there() -> None: + findings = [_finding(STORE, "text(statement)", function="read_roles")] + in_its_function = _construct_exception( + STORE, "text(statement)", function="read_roles" + ) + elsewhere = _construct_exception(STORE, "text(statement)", function="apply_grants") + anywhere_in_the_module = _construct_exception(STORE, "text(statement)") + + assert unused_exceptions( + findings, [in_its_function, elsewhere, anywhere_in_the_module] + ) == [elsewhere] + + +def test_an_exception_allows_every_finding_with_its_file_and_source() -> None: + set_role = "text(f'SET ROLE {role}')" + findings = [ + _finding(STORE, set_role, line=3), + _finding(STORE, set_role, line=9), + _finding(STORE, "text('RESET ROLE')", line=12), + _finding(SESSION_FACTORY, set_role, line=4), + ] + exceptions = [_construct_exception(STORE, set_role)] + + assert undeclared_findings(findings, exceptions) == [ + _finding(STORE, "text('RESET ROLE')", line=12), + _finding(SESSION_FACTORY, set_role, line=4), + ] + + +def test_an_exception_that_names_no_finding_is_unused() -> None: + findings = [_finding(STORE, "text('RESET ROLE')")] + used = _construct_exception(STORE, "text('RESET ROLE')") + other_file = _construct_exception(SESSION_FACTORY, "text('RESET ROLE')") + other_source = _construct_exception(STORE, "text('SET ROLE owner')") + path_exception = RuleException( + path="migrations/**/*.py", reason="revisions", category=MIGRATION_REVISION + ) + + assert unused_exceptions( + findings, [used, other_file, other_source, path_exception] + ) == [other_file, other_source] + + +def test_a_path_exception_takes_its_files_out_of_the_check(tmp_path: Path) -> None: + for file in ("migrations/v2/env.py", "migrations/v2/versions/one.py", "app.py"): + (tmp_path / file).parent.mkdir(parents=True, exist_ok=True) + (tmp_path / file).write_text("", encoding="utf-8") + exceptions = [ + RuleException( + path="migrations/**/*.py", reason="revisions", category=MIGRATION_REVISION + ), + _construct_exception("app.py", "text('SELECT 1')"), + ] + + assert unscanned_files(exceptions, tmp_path) == { + "migrations/v2/env.py", + "migrations/v2/versions/one.py", + } + + +def test_exception_problems_name_each_unusable_exception(tmp_path: Path) -> None: + (tmp_path / "migrations").mkdir() + (tmp_path / "migrations" / "env.py").write_text("", encoding="utf-8") + (tmp_path / "tests").mkdir() + (tmp_path / "tests" / "store.py").write_text("", encoding="utf-8") + exceptions = [ + _construct_exception("tests/store.py", "text('SELECT 1')"), + _construct_exception("tests/store.py", None), + _construct_exception("tests/missing.py", "text('SELECT 1')"), + RuleException( + path="migrations/*.py", reason="revisions", category=MIGRATION_REVISION + ), + RuleException( + path="migrations/*.py", + reason="revisions", + match="text('SELECT 1')", + category=MIGRATION_REVISION, + ), + RuleException( + path="scripts/*.py", reason="scripts", category=MIGRATION_REVISION + ), + RuleException(path="tests/store.py", reason="no category"), + RuleException(path="tests/store.py", reason="driver", category="driver-access"), + ] + + assert exception_problems( + exceptions, ["migrations/env.py", "tests/store.py"], tmp_path + ) == [ + "exception for tests/store.py names no construct: set match to the " + "finding's source", + "exception for tests/missing.py must name one existing file", + "exception for migrations/*.py skips whole files, so it takes no match", + "exception for scripts/*.py matches no file the rule test reads: remove it", + "exception for tests/store.py has unknown category None: use one of " + "['no-orm-form', 'migration-revision']", + "exception for tests/store.py has unknown category 'driver-access': use " + "one of ['no-orm-form', 'migration-revision']", + ] + + +def _needs_function_problem(path: str, match: str) -> str: + return ( + f"exception for {path} ({match}) needs a function: set function to the " + "enclosing function of its finding, or to for a finding at " + "module level" + ) + + +def test_exceptions_outside_tests_or_naming_no_sql_text_need_a_function( + tmp_path: Path, +) -> None: + """Production entries, and entries whose match holds no SQL, name a function. + + An entry whose match is a bare call, a call on variables or an attribute + read would otherwise allow every such call in the module. + """ + for file in ("policyengine_api/store.py", "scripts/migrate.py", "tests/rows.py"): + (tmp_path / file).parent.mkdir(parents=True, exist_ok=True) + (tmp_path / file).write_text("", encoding="utf-8") + store, script, rows = ( + "policyengine_api/store.py", + "scripts/migrate.py", + "tests/rows.py", + ) + exceptions = [ + _construct_exception(store, "sa.text(f'ANALYZE {tables}')"), + _construct_exception(store, "text(statement)", function="apply_grants"), + _construct_exception(script, "session.connection()"), + _construct_exception(rows, "text(statement)"), + _construct_exception(rows, "session.get_bind()"), + _construct_exception(rows, "mapper.local_table"), + _construct_exception(rows, "session.get_bind()", function="Rows.dialect"), + _construct_exception(rows, "text(f'TRUNCATE {tables} CASCADE')"), + _construct_exception( + rows, "sqlite_connection.execute('PRAGMA foreign_keys = ON')" + ), + ] + + assert exception_problems(exceptions, [], tmp_path) == [ + _needs_function_problem(store, "sa.text(f'ANALYZE {tables}')"), + _needs_function_problem(script, "session.connection()"), + _needs_function_problem(rows, "text(statement)"), + _needs_function_problem(rows, "session.get_bind()"), + _needs_function_problem(rows, "mapper.local_table"), + ] + + +@pytest.mark.parametrize( + "match", + [ + "sqlite3.connect(':memory:')", + "psycopg.connect('postgresql://localhost/policyengine')", + "sa.Column('id', ...)", + "Table('household_jobs', ...)", + "event.listen(engine, 'connect')", + "text(f'{statement}')", + "text(f'{statement} {parameters}')", + "connection.execute(f'{statement}')", + "text('')", + ], +) +def test_a_test_entry_naming_no_sql_statement_needs_a_function( + tmp_path: Path, match: str +) -> None: + """Only raw SQL text, or a statement method given SQL, names one statement. + + A string given to anything else, or an f-string of names alone, names no + statement, so the entry would allow the call wherever its module makes it. + """ + (tmp_path / "tests").mkdir() + (tmp_path / "tests" / "rows.py").write_text("", encoding="utf-8") + exceptions = [_construct_exception("tests/rows.py", match)] + + assert exception_problems(exceptions, [], tmp_path) == [ + _needs_function_problem("tests/rows.py", match) + ] + + +@pytest.mark.parametrize( + "match", + [ + "text('TRUNCATE reports')", + "sa.text(f'TRUNCATE {tables} CASCADE')", + "sa.TextClause('SELECT 1')", + "sa.literal_column('count(*)')", + "DDL('DROP TABLE reports')", + "sqlite_connection.execute('PRAGMA foreign_keys = ON')", + "connection.exec_driver_sql('BEGIN IMMEDIATE')", + "session.connection().exec_driver_sql(f'EXPLAIN {expanded.statement}', ...)", + "conn.scalar('SELECT 1')", + ], +) +def test_a_test_entry_naming_one_sql_statement_needs_no_function( + tmp_path: Path, match: str +) -> None: + (tmp_path / "tests").mkdir() + (tmp_path / "tests" / "rows.py").write_text("", encoding="utf-8") + exceptions = [_construct_exception("tests/rows.py", match)] + + assert exception_problems(exceptions, [], tmp_path) == [] + + +def test_a_module_level_exception_allows_findings_only_at_module_level() -> None: + """``function = ""`` names the module's own top-level statements.""" + module_level = _finding(STORE, "text('ANALYZE reports')", line=3) + in_function = _finding(STORE, "text('ANALYZE reports')", line=9, function="analyze") + exceptions = [ + _construct_exception(STORE, "text('ANALYZE reports')", function="") + ] + + assert undeclared_findings([module_level, in_function], exceptions) == [in_function] + + +def test_a_module_level_exception_is_unused_without_a_module_level_finding() -> None: + findings = [_finding(STORE, "text('ANALYZE reports')", function="analyze")] + module_level = _construct_exception( + STORE, "text('ANALYZE reports')", function="" + ) + + assert unused_exceptions(findings, [module_level]) == [module_level] + + +def test_a_production_entry_may_name_module_level_as_its_function( + tmp_path: Path, +) -> None: + (tmp_path / "policyengine_api").mkdir() + (tmp_path / "policyengine_api" / "store.py").write_text("", encoding="utf-8") + exceptions = [ + _construct_exception( + "policyengine_api/store.py", "text(statement)", function="" + ) + ] + + assert exception_problems(exceptions, [], tmp_path) == [] + + +def test_a_path_exception_takes_no_function(tmp_path: Path) -> None: + (tmp_path / "migrations").mkdir() + (tmp_path / "migrations" / "env.py").write_text("", encoding="utf-8") + exceptions = [ + RuleException( + path="migrations/*.py", + reason="revisions", + category=MIGRATION_REVISION, + function="run_migrations_online", + ) + ] + + assert exception_problems(exceptions, ["migrations/env.py"], tmp_path) == [ + "exception for migrations/*.py skips whole files, so it takes no function" + ] + + +def test_an_exception_for_one_constant_statement_allows_no_other() -> None: + source = """ + import sqlalchemy + + sqlite_connection.execute("PRAGMA foreign_keys = ON") + sqlite_connection.execute("DELETE FROM reports") + """ + findings = orm_access_findings({STORE: dedent(source)}) + exceptions = [ + _construct_exception( + STORE, "sqlite_connection.execute('PRAGMA foreign_keys = ON')" + ) + ] + + assert [ + finding.source for finding in undeclared_findings(findings, exceptions) + ] == ["sqlite_connection.execute('DELETE FROM reports')"] From f642b35b6f31cc79bf5b1021949ec9ab2ec2bbea Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:56:48 +0400 Subject: [PATCH 17/20] Fix review round 2's findings in the ORM rule's checker - An exception counts as naming SQL text only for a raw SQL construct or a statement method whose first argument holds literal SQL; every other entry names its function. function = "" declares a finding at module level. A call that opens a connection through psycopg, psycopg2, pymysql, sqlite3 or mysql.connector, by connect, Connect, Connection or AsyncConnection, is reported outside session-factory modules. - The rules loader accepts an exception's function only on api.data.orm-only, and renders it only there; the v2 layer checks are tested to treat v1_sessions as database code. - The migrations skill, the rules-registry skill, the v2 Alembic environment's docstring, the privilege test helpers' docs and the integration conftest describe what the code does. Co-Authored-By: Claude Opus 5.5 --- docs/engineering/skills/alembic-migrations.md | 49 ++++---- docs/engineering/skills/rules-registry.md | 2 +- docs/generated/rules.md | 2 +- migrations/v2/env.py | 15 +-- rules/registry.toml | 17 +-- scripts/rules/load.py | 14 ++- scripts/rules/render.py | 12 +- scripts/rules/tests/test_load.py | 32 +++++- scripts/rules/tests/test_render.py | 44 ++++++-- scripts/rules/tests/test_v2_layers.py | 33 ++++++ .../integration/catalog_privilege_objects.py | 9 +- tests/integration/conftest.py | 15 +-- tests/unit/data/orm_access_support.py | 106 +++++++++++++----- 13 files changed, 251 insertions(+), 99 deletions(-) diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 28c80452b..3a73b5c6e 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -193,9 +193,11 @@ SQLAlchemy's `text`. They report four kinds of finding: - **Core engine or connection**: importing `Engine`, `create_engine` or `Connection` outside a session-factory module; opening a Connection there (`connect()`, `connection()`, `get_bind()`, or `begin()` on an engine); - calling a database driver's `connect` there (`psycopg`, `psycopg2`, - `pymysql`, `sqlite3` or `mysql.connector`); `raw_connection()` in any - module; `execute()` on anything not named as a session, and `scalar()`, + opening a database driver's connection there (a call into `psycopg`, + `psycopg2`, `pymysql`, `sqlite3` or `mysql.connector` whose last name is + `connect`, `Connect`, `Connection` or `AsyncConnection`, as in + `psycopg.connect(url)` or `sqlite3.Connection(':memory:')`); + `raw_connection()` in any module; `execute()` on anything not named as a session, and `scalar()`, `scalars()`, `stream()` or `stream_scalars()` on a name such as `connection`; listening for pool, engine or dialect events (`connect`, `checkout`, `before_cursor_execute`, `handle_error` and the rest) outside a @@ -205,11 +207,12 @@ SQLAlchemy's `text`. They report four kinds of finding: `cursor()`, apart from `text()` given as a server default, a partial index's condition or a check constraint's condition. -`connection()`, `get_bind()`, `raw_connection()` and `exec_driver_sql()` are -SQLAlchemy's names, so they count in every module, as does a driver's -`connect`. The names other libraries share, such as `execute()`, `connect()`, -`begin()` and `cursor()`, count only in a module that imports `sqlalchemy` or -`sqlmodel`. A statement run outside a session is reported with its constant +`connection()`, `get_bind()` and a driver's connection are reported in every +module outside the session-factory modules, whatever the module imports, and +`raw_connection()` and `exec_driver_sql()` in every module, session-factory +modules included. The names other libraries share, such as `execute()`, +`connect()`, `begin()` and `cursor()`, count only in a module that imports +`sqlalchemy` or `sqlmodel`. A statement run outside a session is reported with its constant arguments, as `sqlite_connection.execute('PRAGMA foreign_keys = ON')`, and every finding records the innermost class or function whose body holds it, such as `Reconciler.apply`. @@ -221,7 +224,7 @@ mapped class maps, including tables built in ways the source checks can't see. Two kinds of module have a role of their own: - **Session-factory modules** are the only modules that may create or hold an - Engine, open a Connection, call a database driver's `connect` or attach pool + Engine, open a Connection or a database driver's connection, or attach pool events: - `policyengine_api/data/orm.py`, API v1's runtime factory, with `policyengine_api/data/orm_pool_events.py`, whose listeners record the v1 @@ -256,7 +259,7 @@ session-factory modules: | Function | What it gives | | --- | --- | -| `v1_sessions.unpooled_v1_sessions(url)` | A context manager yielding API v1 Session factories for the database at `url`, on an engine with no pool, disposed of on exit. For the household mirror command and the v1 schema migration. Importing `v1_sessions` loads no `.env` file, so a command's environment is the one its caller gives it. | +| `v1_sessions.unpooled_v1_sessions(url)` | A context manager yielding API v1 Session factories for the database at `url`, on an engine with no pool, disposed of on exit. For the household mirror command and the v1 schema migration. Importing `v1_sessions` loads no `.env` file, so the v1 schema migration's environment is the one its caller gives it (`test_importing_the_script_loads_no_dotenv_file`). The household mirror command still imports `orm` through its services, and `orm` loads `.env`. | | `v1_sessions.v1_schema_inspector(source)` | SQLAlchemy's `Inspector` of the database a v1 Session (inside its transaction) or Session factory uses. | | `v2.database.unpooled_v2_sessions(url)` | The same for API v2, given `V2DatabaseSettings.connection.url` or `V2AlembicSettings.url`: catalog initialization and privilege reconciliation. | | `v2.database.unpooled_v2_read_only_sessions(url)` | The same, with every transaction `READ ONLY` (`postgresql_readonly`): the migration qualification commands. | @@ -343,13 +346,20 @@ The rule's exceptions are its `[[rule.exception]]` entries in exactly as the check reports it, the text after its kind, such as `text(f'DROP ROLE {quoted_role}')`. `function` names the class or function whose body holds it, as the finding reports it after `in`, such as - `apply_declared_privileges` or `Reconciler.apply`. With `function`, the - entry allows that source only there; without it, anywhere in the module. - Every entry outside `tests/` gives its `function`, and so does any entry - whose `match` holds no SQL text, such as `text(statement)`, - `session.connection()` or an attribute read, which would otherwise allow - every such call in its module. Two sites in different functions take an - entry each. + `apply_declared_privileges` or `Reconciler.apply`; `` names a + finding at module level, which the finding reports with no `in`. With + `function`, the entry allows that source only there; without it, anywhere + in the module. Every entry outside `tests/` gives its `function`. So does + every entry whose `match` doesn't name one SQL statement, which would + otherwise allow every such call in its module. A `match` names one + statement only when it is a raw SQL construct (`text`, `TextClause`, + `literal_column`, `DDL`) or a statement method (`execute`, + `exec_driver_sql`, `scalar` and the like) whose first argument is a string + or f-string with SQL of its own, as `text(f'TRUNCATE {tables} CASCADE')`. + `text(statement)`, `text(f'{statement}')`, `session.connection()`, + `sqlite3.connect(':memory:')` and an attribute read name none. Two sites in + different functions take an entry each. Only this rule's entries may give + `function`: the rules loader refuses it on any other rule's. - **`migration-revision`**: a path pattern the rule test doesn't read. It takes no `match` and no `function`. @@ -358,8 +368,9 @@ finding, and on an entry with an unknown category, a `no-orm-form` entry without a `match`, an existing file or a `function` it needs, or a `migration-revision` entry that names no file or gives a `match` or `function`. Only statements SQLAlchemy can't express get an entry: `GRANT` -and `REVOKE`, `CREATE`, `ALTER` and `DROP ROLE` (with `DROP OWNED BY`), -`DROP TABLE`, `TRUNCATE`, `COPY`, `EXPLAIN`, `ANALYZE`, Alembic's need for a +and `REVOKE`, `ALTER DEFAULT PRIVILEGES`, `CREATE`, `ALTER` and `DROP ROLE` +(with `DROP OWNED BY`), `CREATE VIEW` and `CREATE MATERIALIZED VIEW`, `DROP +TABLE`, `TRUNCATE`, `COPY`, `EXPLAIN`, `ANALYZE`, Alembic's need for a Connection, and connection settings no SQL function sets, such as SQLite's `foreign_keys` and `BEGIN IMMEDIATE`. Roles and Postgres settings inside a transaction need none: `set_config` sets them. Keep the entries in as few diff --git a/docs/engineering/skills/rules-registry.md b/docs/engineering/skills/rules-registry.md index 3f2329e1d..fe6a1e6fe 100644 --- a/docs/engineering/skills/rules-registry.md +++ b/docs/engineering/skills/rules-registry.md @@ -60,7 +60,7 @@ gap is visible, rather than leaving it out. | `[[rule.ci]]` | `workflow`, `job`, and an `invocation` string that must appear in that job's `run:` text (or its reusable-workflow `uses:`), or in a command of a Makefile target the job runs with `make `, following the targets' prerequisites and the `$(MAKE)` calls in their recipes (`scripts/rules/makefile.py`). | | `[rule.proof]` | Optional; see "Proof". | | `[rule.baseline]` | Only for `ratcheted` rules: `file` listing tolerated violations, and their `count`. | -| `[[rule.exception]]` | Carve-out: `path`, `reason`, and `expires`; or, for rules whose guard reads them, `match` (one site), `function`, `removal`, `issue` and `category` ([dependencies.md](dependencies.md#exceptions); for `api.data.sqlalchemy-and-alembic-only`, `match` is the exact construct and `category` is `driver-access`, `schema-change` or `migration-revision`: [alembic-migrations.md](alembic-migrations.md#declared-exceptions); for `api.data.orm-only`, `match` is the finding's source, `function` the class or function whose body holds it, and `category` is `no-orm-form` or `migration-revision`; a `no-orm-form` entry allows every site with that source in its module, or only in its `function` when it gives one: [alembic-migrations.md](alembic-migrations.md#orm-only-exceptions)). | +| `[[rule.exception]]` | Carve-out: `path`, `reason`, and `expires`; or, for rules whose guard reads them, `match` (one site), `removal`, `issue` and `category`, and `function` for `api.data.orm-only` alone, which the loader refuses on any other rule ([dependencies.md](dependencies.md#exceptions); for `api.data.sqlalchemy-and-alembic-only`, `match` is the exact construct and `category` is `driver-access`, `schema-change` or `migration-revision`: [alembic-migrations.md](alembic-migrations.md#declared-exceptions); for `api.data.orm-only`, `match` is the finding's source, `function` the class or function whose body holds it, or `` for module level, and `category` is `no-orm-form` or `migration-revision`; a `no-orm-form` entry allows every site with that source in its module, or only in its `function` when it gives one: [alembic-migrations.md](alembic-migrations.md#orm-only-exceptions)). | | `[rule.downgrade]` | Required `reason` when a rule moves from enforced/ratcheted to advisory/doc-only. | `blocking` is derived, never declared: a rule blocks merges when its status is diff --git a/docs/generated/rules.md b/docs/generated/rules.md index cbd57bf55..c8e65778c 100644 --- a/docs/generated/rules.md +++ b/docs/generated/rules.md @@ -94,7 +94,7 @@ Every rule that governs `policyengine-api` is listed here with how it is enforce - `api.data.orm-only`: exception for `tests/fixtures/database_sessions.py` (`text(f'TRUNCATE {tables} CASCADE')`) allowed as a no-orm-form (TRUNCATE has no ORM form. Test cleanup empties a table and every table that refers to it at once, as the catalog tests do after publishing.) - `api.data.orm-only`: exception for `tests/integration/catalog_privilege_objects.py` (`text(f"CREATE {view_kind} {qualified_view} AS SELECT 1 AS id, 'label'::text AS label")` in `create_view`) allowed as a no-orm-form (CREATE VIEW and CREATE MATERIALIZED VIEW have no SQLAlchemy construct. The v2 schema has only tables, so the privilege reconciliation tests create a view and a materialized view of one row, to check the reconciliation reads the grants on them.) - `api.data.orm-only`: exception for `tests/integration/catalog_privilege_objects.py` (`text(f'ALTER DEFAULT PRIVILEGES FOR ROLE {creator} IN SCHEMA {SCHEMA} GRANT {_privileges(privileges)} ON {object_type} TO {grantee}')` in `alter_default_privileges`) allowed as a no-orm-form (ALTER DEFAULT PRIVILEGES has no ORM form. The privilege reconciliation tests set a default ACL on the tables and sequences a role creates, PUBLIC's included, to check the reconciliation reads the default privileges.) -- `api.data.orm-only`: exception for `tests/integration/catalog_privilege_objects.py` (`text(f'GRANT {_privileges(privileges)} ON {on_object} TO {grantee}')` in `grant_on_schema_object`) allowed as a no-orm-form (Grants have no ORM form. The privilege reconciliation tests grant a role privileges on a schema or a sequence, which the shared grant helper, for tables, views and materialized views, doesn't cover, to check the reconciliation reads those grants.) +- `api.data.orm-only`: exception for `tests/integration/catalog_privilege_objects.py` (`text(f'GRANT {_privileges(privileges)} ON {on_object} TO {grantee}')` in `grant_on_schema_object`) allowed as a no-orm-form (Grants have no ORM form. The privilege reconciliation tests grant a role privileges on a schema or a sequence, which the shared grant helper, for tables, views and materialized views, doesn't cover, to check the reconciliation reads those grants. test_v2_migration_target_persistent grants a migration role CREATE on the public schema, so the persistent target's privilege check meets a role with that privilege and one without.) - `api.data.orm-only`: exception for `tests/unit/data/orm_access_support.py` (`class_registry.metadata.tables` in `_unmapped_findings`) allowed as a no-orm-form (The rule's check for tables without a mapped class reads the tables a declarative base's metadata holds, to find those no class maps. It runs no statement.) - `api.data.orm-only`: exception for `tests/unit/data/orm_access_support.py` (`mapper.local_table` in `_unmapped_findings`) allowed as a no-orm-form (The rule's check for tables without a mapped class reads which table each mapped class maps. It runs no statement.) - `api.data.sqlalchemy-and-alembic-only`: exception for `migrations/*/versions/*.py` allowed as a migration-revision (Alembic generates the revisions, and they are where schema changes belong, so the check doesn't scan them. Ruff skips the same files (extend-exclude in pyproject.toml).) diff --git a/migrations/v2/env.py b/migrations/v2/env.py index d81f8cb64..8dfbf2ee6 100644 --- a/migrations/v2/env.py +++ b/migrations/v2/env.py @@ -82,8 +82,9 @@ def run_migrations_offline() -> None: def run_migrations_online() -> None: """Migrate the caller's connection, or else a new engine in one transaction. - The new engine's transaction commits, so the target qualification's reads - cannot leave the completed migration to be rolled back. + On a new engine, the target qualification, the migration and the head + schema check share one transaction, which commits only when all of them + succeed: a failed ``validate_v2_head_schema`` rolls the migration back. """ provided_connection = config.attributes.get("connection") if provided_connection is not None: @@ -92,11 +93,11 @@ def run_migrations_online() -> None: engine = create_engine(settings.url, poolclass=pool.NullPool) try: - # Persistent target qualification performs live reads before Alembic - # enters its migration transaction. SQLAlchemy 2.x autobegins on - # those reads, so the environment must own a committing transaction; - # otherwise a standalone command closes the connection and silently - # rolls the completed migration back. + # engine.begin() opens the one transaction the qualification's reads, + # the migration and validate_v2_head_schema all run in. Alembic's + # begin_transaction joins it rather than committing on its own, so the + # migration commits only when the head schema check passes; when the + # check raises, engine.begin() rolls the migration back. with engine.begin() as connection: _configure(connection) finally: diff --git a/rules/registry.toml b/rules/registry.toml index cb24c8559..a1f839888 100644 --- a/rules/registry.toml +++ b/rules/registry.toml @@ -643,13 +643,14 @@ bad_fixture = "rules/fixtures/api.data.orm-only/bad_simulation_rows.py" good_fixture = "rules/fixtures/api.data.orm-only/good_simulation_rows.py" test = "tests/unit/data/test_orm_only.py::test_rule_proof_orm_only" # Each exception names a module, in match the source of a finding there that -# SQLAlchemy's ORM has no form for and, in function, the function it is in -# (category no-orm-form), or a path pattern the rule test doesn't read -# (category migration-revision). Without a function, an entry allows its source -# anywhere in the module. Every entry outside tests/, and every entry whose -# match holds no SQL text (a bare call, a call on variables or an attribute -# read), names its function. The rule test fails on a finding no exception -# names and on an exception that names nothing. +# SQLAlchemy's ORM has no form for and, in function, the function it is in, or +# "" for module level (category no-orm-form), or a path pattern the +# rule test doesn't read (category migration-revision). Without a function, an +# entry allows its source anywhere in the module. Every entry outside tests/ +# names its function, and so does every entry whose match isn't raw SQL text +# or a statement method given SQL of its own, such as a bare call, a call on +# variables, a driver's connect or an attribute read. The rule test fails on a +# finding no exception names and on an exception that names nothing. [[rule.exception]] path = "migrations/**/*.py" category = "migration-revision" @@ -806,7 +807,7 @@ path = "tests/integration/catalog_privilege_objects.py" match = "text(f'GRANT {_privileges(privileges)} ON {on_object} TO {grantee}')" function = "grant_on_schema_object" category = "no-orm-form" -reason = "Grants have no ORM form. The privilege reconciliation tests grant a role privileges on a schema or a sequence, which the shared grant helper, for tables, views and materialized views, doesn't cover, to check the reconciliation reads those grants." +reason = "Grants have no ORM form. The privilege reconciliation tests grant a role privileges on a schema or a sequence, which the shared grant helper, for tables, views and materialized views, doesn't cover, to check the reconciliation reads those grants. test_v2_migration_target_persistent grants a migration role CREATE on the public schema, so the persistent target's privilege check meets a role with that privilege and one without." [[rule.exception]] path = "tests/integration/catalog_privilege_objects.py" diff --git a/scripts/rules/load.py b/scripts/rules/load.py index 2604f7685..9c4ae2fa9 100644 --- a/scripts/rules/load.py +++ b/scripts/rules/load.py @@ -296,6 +296,9 @@ def _baseline( return None +# The rules whose checkers read an exception's function. Only their exceptions +# may give one; on any other rule's, it would narrow nothing. +FUNCTION_EXCEPTION_RULES = frozenset({"api.data.orm-only"}) _EXCEPTION_KEYS = { "path", "reason", @@ -335,6 +338,15 @@ def _exception( expires = ( collector.day(rule_id, entry.get("expires"), f"{where}.expires") or date.max ) + function = _optional_string(collector, rule_id, entry, "function", where) + if function is not None and rule_id not in FUNCTION_EXCEPTION_RULES: + collector.add( + rule_id, + f"{where}.function is read only for " + f"{', '.join(sorted(FUNCTION_EXCEPTION_RULES))}", + "remove function", + ) + function = None issue = entry.get("issue") if issue is not None and (not isinstance(issue, int) or isinstance(issue, bool)): collector.add( @@ -349,7 +361,7 @@ def _exception( category, removal, issue, - _optional_string(collector, rule_id, entry, "function", where), + function, ) diff --git a/scripts/rules/render.py b/scripts/rules/render.py index c9c2cd3ef..de58b3189 100644 --- a/scripts/rules/render.py +++ b/scripts/rules/render.py @@ -9,6 +9,7 @@ import re from pathlib import Path +from scripts.rules.load import FUNCTION_EXCEPTION_RULES from scripts.rules.model import Kind, Registry, Rule, RuleException, Status, Tier RULES_MD = Path("docs/generated/rules.md") @@ -193,7 +194,7 @@ def section(title: str, items: list[str]) -> None: ], ) dated = [f"- `{r.id}`: review by {r.review_by}" for r in rules if r.review_by] + [ - f"- `{r.id}`: {_exception_summary(e)}" for r in rules for e in r.exceptions + f"- `{r.id}`: {_exception_summary(r, e)}" for r in rules for e in r.exceptions ] section("Exceptions and review dates", sorted(dated)) @@ -289,12 +290,15 @@ def write_outputs(registry: Registry, root: Path) -> list[Path]: return [rules_md, agents] -def _exception_summary(exception: RuleException) -> str: - """Describe where an exception applies, why, and when it ends.""" +def _exception_summary(rule: Rule, exception: RuleException) -> str: + """Describe where an exception applies, why, and when it ends. + + Its function is shown only for a rule whose checker reads it. + """ site = f"`{exception.path}`" if exception.match is not None: site += f" (`{exception.match}`" - if exception.function is not None: + if exception.function is not None and rule.id in FUNCTION_EXCEPTION_RULES: site += f" in `{exception.function}`" site += ")" if exception.category is not None: diff --git a/scripts/rules/tests/test_load.py b/scripts/rules/tests/test_load.py index 185af1238..2cec80b38 100644 --- a/scripts/rules/tests/test_load.py +++ b/scripts/rules/tests/test_load.py @@ -204,19 +204,25 @@ def test_single_tables_stand_for_one_entry_lists(self) -> None: } +ORM_ONLY_RULE = "api.data.orm-only" + + class ExceptionFunctionTest(unittest.TestCase): - """An exception's ``function`` narrows it to findings inside that function.""" + """An exception's ``function`` narrows it to findings inside that function. + + Only the rules whose checkers read it, api.data.orm-only's, may give one. + """ def _parsed_exceptions( - self, exception: Mapping[str, object] + self, exception: Mapping[str, object], rule_id: str = ORM_ONLY_RULE ) -> tuple[list[str], tuple[RuleException, ...]]: raw = tomllib.loads(REGISTRY) - rule = {**SINGLE_TABLES_RULE, "exception": exception} + rule = {**SINGLE_TABLES_RULE, "id": rule_id, "exception": exception} del rule["baseline"] raw["rule"] = [rule] registry, violations = parse(raw) assert registry is not None - parsed = registry.rule("ex.layers.single-tables") + parsed = registry.rule(rule_id) assert parsed is not None return [str(violation) for violation in violations], parsed.exceptions @@ -252,14 +258,28 @@ def test_a_function_must_be_a_non_empty_string(self) -> None: {**NARROWED_EXCEPTION, "function": ""} ) + self.assertEqual( + violations, + [ + f"[{ORM_ONLY_RULE}] schema: {ORM_ONLY_RULE}.exception.function " + "must be a non-empty string. Fix: set function." + ], + ) + + def test_another_rules_exception_may_not_give_a_function(self) -> None: + violations, exceptions = self._parsed_exceptions( + NARROWED_EXCEPTION, rule_id="ex.layers.single-tables" + ) + self.assertEqual( violations, [ "[ex.layers.single-tables] schema: " - "ex.layers.single-tables.exception.function must be a non-empty " - "string. Fix: set function." + "ex.layers.single-tables.exception.function is read only for " + f"{ORM_ONLY_RULE}. Fix: remove function." ], ) + self.assertIsNone(exceptions[0].function) if __name__ == "__main__": diff --git a/scripts/rules/tests/test_render.py b/scripts/rules/tests/test_render.py index fd2a6098b..2c7bbb0c7 100644 --- a/scripts/rules/tests/test_render.py +++ b/scripts/rules/tests/test_render.py @@ -209,9 +209,21 @@ def test_large_graphs_are_split_into_chunks_of_rules(self) -> None: ) +ORM_ONLY_RULE = "api.data.orm-only" +NARROWED_EXCEPTION = RuleException( + path="pkg/store.py", + reason="GRANT has no ORM form", + match="text(statement)", + category="no-orm-form", + function="apply_declared_privileges", +) + + class ExceptionSummaryTest(unittest.TestCase): - def _exception_lines(self, exceptions: tuple[RuleException, ...]) -> list[str]: - rule = make_rule("ex.checks.orm-only", Enforcer(Kind.NONE)) + def _exception_lines( + self, exceptions: tuple[RuleException, ...], rule_id: str = ORM_ONLY_RULE + ) -> list[str]: + rule = make_rule(rule_id, Enforcer(Kind.NONE)) registry = Registry( schema_version=1, repo="example", @@ -222,19 +234,13 @@ def _exception_lines(self, exceptions: tuple[RuleException, ...]) -> list[str]: return [ line for line in render_rules_md(registry).splitlines() - if line.startswith("- `ex.checks.orm-only`: exception") + if line.startswith(f"- `{rule_id}`: exception") ] def test_an_exception_names_its_match_and_function(self) -> None: lines = self._exception_lines( ( - RuleException( - path="pkg/store.py", - reason="GRANT has no ORM form", - match="text(statement)", - category="no-orm-form", - function="apply_declared_privileges", - ), + NARROWED_EXCEPTION, RuleException( path="pkg/rows.py", reason="TRUNCATE has no ORM form", @@ -247,15 +253,29 @@ def test_an_exception_names_its_match_and_function(self) -> None: self.assertEqual( lines, [ - "- `ex.checks.orm-only`: exception for `pkg/rows.py` " + f"- `{ORM_ONLY_RULE}`: exception for `pkg/rows.py` " "(`text('TRUNCATE reports')`) allowed as a no-orm-form " "(TRUNCATE has no ORM form)", - "- `ex.checks.orm-only`: exception for `pkg/store.py` " + f"- `{ORM_ONLY_RULE}`: exception for `pkg/store.py` " "(`text(statement)` in `apply_declared_privileges`) allowed as a " "no-orm-form (GRANT has no ORM form)", ], ) + def test_another_rules_exception_shows_no_function(self) -> None: + lines = self._exception_lines( + (NARROWED_EXCEPTION,), rule_id="ex.checks.driver-access" + ) + + self.assertEqual( + lines, + [ + "- `ex.checks.driver-access`: exception for `pkg/store.py` " + "(`text(statement)`) allowed as a no-orm-form " + "(GRANT has no ORM form)", + ], + ) + if __name__ == "__main__": unittest.main() diff --git a/scripts/rules/tests/test_v2_layers.py b/scripts/rules/tests/test_v2_layers.py index 5299d11f4..20d1b9dc0 100644 --- a/scripts/rules/tests/test_v2_layers.py +++ b/scripts/rules/tests/test_v2_layers.py @@ -327,6 +327,39 @@ def read(): }, ) + def test_api_v1s_command_session_factories_are_database_code(self) -> None: + """``v1_sessions`` is a database package, as ``orm`` is.""" + route_source = """ + from policyengine_api.data.v1_sessions import unpooled_v1_sessions + + + def route(url): + with unpooled_v1_sessions(url) as sessions: + return sessions + """ + connector_source = """ + from policyengine_api.data import v1_sessions + + + def read(url): + return v1_sessions.unpooled_v1_sessions(url) + """ + + self.assertEqual( + _findings({ROUTE: route_source}, ROUTES_RULE), + { + f"{ROUTE} calls unpooled_v1_sessions", + f"{ROUTE} imports policyengine_api.data.v1_sessions", + }, + ) + self.assertEqual( + _findings({CONNECTOR: connector_source}, CONNECTORS_RULE), + { + f"{CONNECTOR} calls unpooled_v1_sessions", + f"{CONNECTOR} imports policyengine_api.data.v1_sessions", + }, + ) + def test_services_import_only_the_session_type_and_errors_from_sql_packages( self, ) -> None: diff --git a/tests/integration/catalog_privilege_objects.py b/tests/integration/catalog_privilege_objects.py index 278b1dddc..b93093682 100644 --- a/tests/integration/catalog_privilege_objects.py +++ b/tests/integration/catalog_privilege_objects.py @@ -5,9 +5,12 @@ DEFAULT PRIVILEGES``). The v2 schema has only tables, so tests make the rest here: a view and a materialized view, mapped by ``PrivilegeTestView`` and ``PrivilegeTestMaterializedView`` so that the shared ``grant`` grants on them, -and sequences. The ORM has no form for these statements, so each helper that -writes SQL text is a ``no-orm-form`` exception of rule api.data.orm-only in -rules/registry.toml: +and sequences. test_v2_privilege_reconciliation.py uses all of it. +test_v2_migration_target_persistent.py uses ``grant_on_schema_object`` to give +a migration role CREATE on ``public``, so the persistent target's privilege +check meets a role with that privilege and one without. The ORM has no form +for these statements, so each helper that writes SQL text is a +``no-orm-form`` exception of rule api.data.orm-only in rules/registry.toml: - ``grant_on_schema_object``: GRANT on a schema or a sequence, which the shared ``grant`` (tables, views and materialized views) doesn't cover; diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 59c5c9da8..0237b1d5d 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -181,8 +181,8 @@ def api_base_url() -> str: @pytest.fixture -def api_client(api_base_url: str): - """Call the deployed Public API with the CI server credential on every request. +def api_client(api_base_url: str) -> Iterator[httpx.Client]: + """Call the deployed API v1 with the CI server credential on every request. The client is ``deployed_api_client``'s (``tests/integration/deployed_api_credentials.py``). The test fails, rather @@ -197,8 +197,8 @@ def api_client(api_base_url: str): @pytest.fixture -def uncredentialed_api_client(api_base_url: str): - """Call the deployed Public API without any credential, as an outside caller.""" +def uncredentialed_api_client(api_base_url: str) -> Iterator[httpx.Client]: + """Call the deployed API v1 without any credential, as an outside caller.""" with httpx.Client( base_url=api_base_url, timeout=90.0, @@ -229,7 +229,8 @@ def _poll_live_endpoint( route_name: str, ) -> dict: deadline = time.monotonic() + INTEGRATION_TIMEOUT_SECONDS - last_response = None + # The last error, response summary or payload, for the timeout's message. + last_response: object = None while True: try: @@ -254,7 +255,7 @@ def _poll_live_endpoint( request=error.request, response=error.response, ) from error - payload = response.json() + payload: dict = response.json() if payload["status"] != "computing": return payload @@ -271,7 +272,7 @@ def _poll_live_endpoint( @pytest.fixture -def poll_live_endpoint(): +def poll_live_endpoint() -> Callable[..., dict]: return _poll_live_endpoint diff --git a/tests/unit/data/orm_access_support.py b/tests/unit/data/orm_access_support.py index 637c25021..1be43ef18 100644 --- a/tests/unit/data/orm_access_support.py +++ b/tests/unit/data/orm_access_support.py @@ -28,15 +28,16 @@ the named ``DECLARATIVE_BASE_MODULES``, rather than files matched by name. - A session-factory module may also import ``Connection``, open a Connection (``connect()``, ``connection()``, ``get_bind()`` and ``begin()`` on an - engine), call a database driver's ``connect`` and attach listeners for pool, - engine or dialect events, which no other module may do. + engine), open a database driver's connection and attach listeners for + pool, engine or dialect events, which no other module may do. ``raw_connection()`` hands out the driver's connection, not SQLAlchemy's, and is reported in every module. - A finding is allowed when a ``no-orm-form`` exception names its file, in ``match`` its ``source`` and, when the exception gives one, in ``function`` - the function it is in; a ``migration-revision`` exception names a path - pattern the rule test doesn't read. Each finding records the innermost - class or function whose body holds it. + the function it is in, or ```` for module level; a + ``migration-revision`` exception names a path pattern the rule test doesn't + read. Each finding records the innermost class or function whose body holds + it. The source checks look for Core rather than for the ORM, so any statement on mapped classes passes. Each file is checked on its own, through its own imports: @@ -54,9 +55,11 @@ class or function whose body holds it. A statement run outside a session is reported with its constant arguments, as in ``connection.execute('PRAGMA foreign_keys = ON')``, so an exception can name that one statement. ``.connection()``, ``.get_bind()``, ``.raw_connection()`` -and ``.exec_driver_sql()`` are SQLAlchemy's names and count in every module, as -does a call of ``connect`` from psycopg, psycopg2, pymysql, sqlite3 or -mysql.connector, followed through the module's imports. The rules that go by a +and ``.exec_driver_sql()`` are SQLAlchemy's names and count whatever a module +imports, as does opening a connection of psycopg, psycopg2, pymysql, sqlite3 or +mysql.connector: a call into one of them, followed through the module's +imports, whose last name is ``connect``, ``Connect``, ``Connection`` or +``AsyncConnection``. The rules that go by a method or attribute name other libraries share apply only in modules that import sqlalchemy or sqlmodel: any ``.table`` read, ``kw["bind"]``, ``.execute()`` on anything not named as a session, ``.scalar()``, @@ -168,8 +171,10 @@ class or function whose body holds it. # The call that hands out the driver's connection beneath SQLAlchemy's, which # no module may make. DRIVER_CONNECTION_METHODS = frozenset({"raw_connection"}) -# The database drivers, and the functions of theirs that open a connection, -# which only a session-factory module may call. +# The database drivers, and the last names of their calls that open a +# connection: a connect function or method, as in psycopg.connect or +# psycopg.Connection.connect, or a connection class, as in sqlite3.Connection. +# Only a session-factory module may make them. DATABASE_DRIVER_MODULES = ( "mysql.connector", "psycopg", @@ -177,8 +182,8 @@ class or function whose body holds it. "pymysql", "sqlite3", ) -DRIVER_CONNECT_FUNCTIONS = frozenset( - f"{driver}.connect" for driver in DATABASE_DRIVER_MODULES +DRIVER_CONNECT_NAMES = frozenset( + {"AsyncConnection", "Connect", "Connection", "connect"} ) # execute runs only on a name such as session or store_session, which finds a # connection passed around without a Connection annotation. A Result has scalar @@ -277,8 +282,18 @@ class or function whose body holds it. NO_ORM_FORM = "no-orm-form" MIGRATION_REVISION = "migration-revision" EXCEPTION_CATEGORIES = (NO_ORM_FORM, MIGRATION_REVISION) -# Outside the tests, every no-orm-form exception names its function. +# Outside the tests, every no-orm-form exception names its function, or +# MODULE_LEVEL for a finding in no class or function. TEST_DIRECTORY = "tests/" +MODULE_LEVEL = "" +# The calls whose first argument is SQL: the raw SQL constructs and the methods +# that run a statement. An exception naming one, given SQL of its own, names +# one statement, so it needs no function in a test module. +SQL_TEXT_CALLS = RAW_SQL_FUNCTIONS | { + DRIVER_SQL_METHOD, + EXECUTE_METHOD, + *CONNECTION_STATEMENT_METHODS, +} SCOPE_NODES = (ast.AsyncFunctionDef, ast.ClassDef, ast.FunctionDef) @@ -615,11 +630,18 @@ def _runs_raw_sql(node: ast.Call, function: str, context: _ModuleContext) -> boo def _connects_a_driver(node: ast.Call, context: _ModuleContext) -> bool: - """Whether a call opens a database driver's connection outside a factory.""" + """Whether a call opens a database driver's connection outside a factory. + + The call is into a driver module, followed through the module's imports, + and its last name is a connect function or a connection class. + """ + if context.module.is_session_factory: + return False + qualified = _qualified_name(node.func, context.module.driver_imported) return ( - not context.module.is_session_factory - and _qualified_name(node.func, context.module.driver_imported) - in DRIVER_CONNECT_FUNCTIONS + qualified is not None + and _library_of(qualified, DATABASE_DRIVER_MODULES) is not None + and qualified.rsplit(".", 1)[-1] in DRIVER_CONNECT_NAMES ) @@ -844,9 +866,12 @@ def _module_context(module: _Module) -> _ModuleContext: def _enclosing_scopes(tree: ast.Module) -> dict[int, str]: """Map each node in a class's or function's body to that scope's dotted name. - The innermost scope counts, named as Python's ``__qualname__`` names it - without ````: ``Reconciler.apply.build``. A definition's own - decorators, parameters and annotations belong to the scope around it. + The innermost class or function counts, its name joined to the names of + the classes and functions around it: ``Reconciler.apply.build``. A lambda + counts as the function it is in, and two definitions with one name in one + scope, such as a property's getter and setter, share that name. A + definition's own decorators, parameters and annotations belong to the + scope around it. """ scopes: dict[int, str] = {} pending: list[tuple[ast.AST, str | None]] = [(tree, None)] @@ -1001,13 +1026,14 @@ def _names_finding(exception: RuleException, finding: Finding) -> bool: Its ``path`` is the finding's file and its ``match`` the finding's ``source``, exactly. With a ``function``, the finding is in that function - too; without one, the exception allows the source anywhere in the file. + too, or at module level for ``MODULE_LEVEL``; without one, the exception + allows the source anywhere in the file. """ return ( exception.category == NO_ORM_FORM and exception.match is not None and (exception.path, exception.match) == (finding.file, finding.source) - and exception.function in (None, finding.function) + and exception.function in (None, finding.function or MODULE_LEVEL) ) @@ -1049,21 +1075,40 @@ def unscanned_files( ) +def _holds_literal_sql(argument: ast.expr) -> bool: + """Whether a string or f-string argument has SQL of its own, not only names. + + ``'TRUNCATE reports'`` and ``f'TRUNCATE {tables}'`` do; ``''``, + ``f'{statement}'`` and ``f'{statement} {parameters}'`` don't. + """ + if isinstance(argument, ast.Constant): + return isinstance(argument.value, str) and bool(argument.value.strip()) + return isinstance(argument, ast.JoinedStr) and any( + _holds_literal_sql(part) + for part in argument.values + if isinstance(part, ast.Constant) + ) + + def _names_sql_text(match: str) -> bool: - """Whether ``match`` is a call whose first argument is a string or f-string. + """Whether ``match`` is raw SQL, or a statement method, given SQL of its own. - Such a match names one statement, as ``text(f'TRUNCATE {tables}')`` does. A + Such a match names one statement: a raw SQL construct (``text``, + ``TextClause``, ``literal_column``, ``DDL``) or a statement method + (``execute``, ``exec_driver_sql``, ``scalar`` and the like) whose first + argument holds literal SQL, as ``text(f'TRUNCATE {tables}')`` does. A + string given to anything else, such as ``sqlite3.connect(':memory:')``, a bare call, a call on variables and an attribute read name none. """ try: expression = ast.parse(match, mode="eval").body except SyntaxError: return False - if not isinstance(expression, ast.Call) or not expression.args: - return False - statement = expression.args[0] - return isinstance(statement, ast.JoinedStr) or ( - isinstance(statement, ast.Constant) and isinstance(statement.value, str) + return ( + isinstance(expression, ast.Call) + and bool(expression.args) + and _last_name(expression.func) in SQL_TEXT_CALLS + and _holds_literal_sql(expression.args[0]) ) @@ -1090,7 +1135,8 @@ def _construct_exception_problem( if _needs_function(exception, exception.match): return ( f"{where} ({exception.match}) needs a function: set function to the " - "enclosing function of its finding" + f"enclosing function of its finding, or to {MODULE_LEVEL} for a " + "finding at module level" ) return None From 69f03810368570138e935a46187b951f473fa2a2 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:06:41 +0400 Subject: [PATCH 18/20] Test review round 3's findings in the ORM rule's checker (failing) - A test exception counts as naming one SQL statement only when its literal text holds a statement keyword outside SQL comments, so text(f'{statement};'), text(f'{statement} -- cleanup') or literal_column('count(*)') must name their function. - Calling any driver class whose name ends with Connection, such as mysql.connector's MySQLConnection or psycopg2's RealDictConnection, is reported outside session-factory modules. Co-Authored-By: Claude Opus 5.5 --- tests/unit/data/test_orm_access_support.py | 59 ++++++++++++++++++++- tests/unit/data/test_orm_only_exceptions.py | 15 +++++- 2 files changed, 72 insertions(+), 2 deletions(-) diff --git a/tests/unit/data/test_orm_access_support.py b/tests/unit/data/test_orm_access_support.py index 43e46a4f1..4c77fcc36 100644 --- a/tests/unit/data/test_orm_access_support.py +++ b/tests/unit/data/test_orm_access_support.py @@ -718,16 +718,73 @@ def test_a_driver_connection_opened_another_way_is_reported( "class RecordingConnection(sqlite3.Connection):\n pass", "error = psycopg.OperationalError('connection lost')", "rows = psycopg.Cursor", + "connection_class = psycopg2.extras.RealDictConnection", + "value = psycopg2.extras.Json({'people': {}})", + "statement = psycopg.sql.Identifier('reports')", ], ) def test_naming_a_drivers_connection_class_without_calling_it_is_not_reported( source: str, ) -> None: - module = f"import psycopg\nimport sqlite3\n\n{source}\n" + """Only a call of a connect function or connection class opens one.""" + module = f"import psycopg\nimport psycopg2.extras\nimport sqlite3\n\n{source}\n" assert _checks({ROUTES: module}, ROUTES) == [] +@pytest.mark.parametrize( + ("imports", "call", "summary"), + [ + ( + "from mysql.connector import connection", + "connection.MySQLConnection(user='root')", + "connection.MySQLConnection(...)", + ), + ( + "import mysql.connector", + "mysql.connector.MySQLConnection(user='root')", + "mysql.connector.MySQLConnection(...)", + ), + ( + "from mysql.connector.connection_cext import CMySQLConnection", + "CMySQLConnection(user='root')", + "CMySQLConnection(...)", + ), + ( + "import psycopg2.extras", + "psycopg2.extras.RealDictConnection(dsn)", + "psycopg2.extras.RealDictConnection(dsn)", + ), + ( + "from psycopg2.extras import LoggingConnection", + "LoggingConnection(dsn)", + "LoggingConnection(dsn)", + ), + ], +) +def test_a_drivers_other_connection_classes_are_reported( + imports: str, call: str, summary: str +) -> None: + """A call of any driver class whose name ends with Connection opens one.""" + source = f"{imports}\n\ndriver_connection = {call}\n" + + assert _checks({ROUTES: source}, ROUTES) == [(CORE_CONNECTION, summary)] + assert _checks({SESSION_FACTORY: source}, SESSION_FACTORY) == [] + + +def test_a_name_shadowing_an_imported_driver_is_followed_as_the_driver() -> None: + """The checks read a module's imports, not each scope's names. + + A parameter named ``sqlite3`` in a module that imports ``sqlite3`` is + still taken for the driver, so its ``connect()`` is reported. + """ + source = ( + "import sqlite3\n\ndef open_store(sqlite3):\n return sqlite3.connect()\n" + ) + + assert _checks({ROUTES: source}, ROUTES) == [(CORE_CONNECTION, "sqlite3.connect()")] + + def test_a_session_factory_module_hands_out_no_engine_or_connection() -> None: source = """ from sqlalchemy import Connection, Engine, create_engine diff --git a/tests/unit/data/test_orm_only_exceptions.py b/tests/unit/data/test_orm_only_exceptions.py index 1870fb19b..e9ac7c31d 100644 --- a/tests/unit/data/test_orm_only_exceptions.py +++ b/tests/unit/data/test_orm_only_exceptions.py @@ -266,6 +266,15 @@ def test_exceptions_outside_tests_or_naming_no_sql_text_need_a_function( "text(f'{statement} {parameters}')", "connection.execute(f'{statement}')", "text('')", + "text(f'{statement};')", + "text(f'({statement})')", + "text(f'{schema}.{table}')", + "text(f'{statement} -- cleanup')", + "text(f'{statement} /* cleanup */')", + "text('-- SELECT 1')", + "text(f'{column} = :value')", + "text(f'{table}_selection')", + "sa.literal_column('count(*)')", ], ) def test_a_test_entry_naming_no_sql_statement_needs_a_function( @@ -291,12 +300,16 @@ def test_a_test_entry_naming_no_sql_statement_needs_a_function( "text('TRUNCATE reports')", "sa.text(f'TRUNCATE {tables} CASCADE')", "sa.TextClause('SELECT 1')", - "sa.literal_column('count(*)')", "DDL('DROP TABLE reports')", "sqlite_connection.execute('PRAGMA foreign_keys = ON')", "connection.exec_driver_sql('BEGIN IMMEDIATE')", "session.connection().exec_driver_sql(f'EXPLAIN {expanded.statement}', ...)", "conn.scalar('SELECT 1')", + "text('select 1')", + "text(f'SELECT * FROM {table} -- read every row')", + "text('/* statistics */ VACUUM reports')", + "text(f'WITH recent AS ({query}) SELECT 1')", + "text(f'DROP OWNED BY {quoted_role}')", ], ) def test_a_test_entry_naming_one_sql_statement_needs_no_function( From 4b2bbfa25b42adb656fe4df28fab380c55f20a06 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:09:51 +0400 Subject: [PATCH 19/20] Fix review round 3's findings in the ORM rule's checker - A test exception names one SQL statement only when its literal text, with SQL comments removed, holds a statement keyword as a whole word; text built of punctuation, names or a comment around interpolated values names none. - A call into a database driver package is reported outside session-factory modules when its last name is connect or Connect or ends with Connection, which covers MySQLConnection, CMySQLConnection and RealDictConnection. - The v2 Alembic environment's comment says the head schema check runs only when a migration reaches the script heads. Co-Authored-By: Claude Opus 5.5 --- docs/engineering/skills/alembic-migrations.md | 20 +++-- migrations/v2/env.py | 17 ++-- tests/unit/data/orm_access_support.py | 83 +++++++++++++------ 3 files changed, 83 insertions(+), 37 deletions(-) diff --git a/docs/engineering/skills/alembic-migrations.md b/docs/engineering/skills/alembic-migrations.md index 3a73b5c6e..433b0963d 100644 --- a/docs/engineering/skills/alembic-migrations.md +++ b/docs/engineering/skills/alembic-migrations.md @@ -195,8 +195,10 @@ SQLAlchemy's `text`. They report four kinds of finding: (`connect()`, `connection()`, `get_bind()`, or `begin()` on an engine); opening a database driver's connection there (a call into `psycopg`, `psycopg2`, `pymysql`, `sqlite3` or `mysql.connector` whose last name is - `connect`, `Connect`, `Connection` or `AsyncConnection`, as in - `psycopg.connect(url)` or `sqlite3.Connection(':memory:')`); + `connect` or `Connect`, or ends with `Connection`, as in + `psycopg.connect(url)`, `sqlite3.Connection(':memory:')` or + `psycopg2.extras.RealDictConnection(dsn)`; naming a connection class + without calling it isn't reported); `raw_connection()` in any module; `execute()` on anything not named as a session, and `scalar()`, `scalars()`, `stream()` or `stream_scalars()` on a name such as `connection`; listening for pool, engine or dialect events (`connect`, @@ -355,9 +357,17 @@ The rule's exceptions are its `[[rule.exception]]` entries in statement only when it is a raw SQL construct (`text`, `TextClause`, `literal_column`, `DDL`) or a statement method (`execute`, `exec_driver_sql`, `scalar` and the like) whose first argument is a string - or f-string with SQL of its own, as `text(f'TRUNCATE {tables} CASCADE')`. - `text(statement)`, `text(f'{statement}')`, `session.connection()`, - `sqlite3.connect(':memory:')` and an attribute read name none. Two sites in + or f-string whose literal text, less its SQL comments (`--` to the end of + a line, and `/* ... */`), holds a statement keyword as a whole word, in any + case: `SELECT`, `INSERT`, `UPDATE`, `DELETE`, `TRUNCATE`, `CREATE`, + `DROP`, `ALTER`, `GRANT`, `REVOKE`, `EXPLAIN`, `ANALYZE`, `BEGIN`, + `COMMIT`, `ROLLBACK`, `SAVEPOINT`, `PRAGMA`, `SET`, `RESET`, `SHOW`, + `WITH`, `COPY`, `LOCK`, `VACUUM`, `COMMENT`, `DO` or `CALL`, as + `text(f'TRUNCATE {tables} CASCADE')` does. `text(statement)`, + `text(f'{statement};')`, `text(f'{schema}.{table}')`, + `text(f'{statement} -- cleanup')`, `literal_column('count(*)')`, + `session.connection()`, `sqlite3.connect(':memory:')` and an attribute read + name none. Two sites in different functions take an entry each. Only this rule's entries may give `function`: the rules loader refuses it on any other rule's. - **`migration-revision`**: a path pattern the rule test doesn't read. It diff --git a/migrations/v2/env.py b/migrations/v2/env.py index 8dfbf2ee6..3188ac968 100644 --- a/migrations/v2/env.py +++ b/migrations/v2/env.py @@ -82,9 +82,10 @@ def run_migrations_offline() -> None: def run_migrations_online() -> None: """Migrate the caller's connection, or else a new engine in one transaction. - On a new engine, the target qualification, the migration and the head - schema check share one transaction, which commits only when all of them - succeed: a failed ``validate_v2_head_schema`` rolls the migration back. + On a new engine, the target qualification, the migration and, when the + migration reaches the script heads, the head schema check share one + transaction, which commits only when all of them succeed: a failed + ``validate_v2_head_schema`` rolls the migration back. """ provided_connection = config.attributes.get("connection") if provided_connection is not None: @@ -94,10 +95,12 @@ def run_migrations_online() -> None: engine = create_engine(settings.url, poolclass=pool.NullPool) try: # engine.begin() opens the one transaction the qualification's reads, - # the migration and validate_v2_head_schema all run in. Alembic's - # begin_transaction joins it rather than committing on its own, so the - # migration commits only when the head schema check passes; when the - # check raises, engine.begin() rolls the migration back. + # the migration and validate_v2_head_schema run in. Alembic's + # begin_transaction joins it rather than committing on its own. + # _configure runs the head schema check only when the migration moved + # the database to the script heads: then the migration commits only + # when the check passes, and engine.begin() rolls it back when the + # check raises. Any other migration commits once it completes. with engine.begin() as connection: _configure(connection) finally: diff --git a/tests/unit/data/orm_access_support.py b/tests/unit/data/orm_access_support.py index 1be43ef18..9d12e14db 100644 --- a/tests/unit/data/orm_access_support.py +++ b/tests/unit/data/orm_access_support.py @@ -58,8 +58,10 @@ and ``.exec_driver_sql()`` are SQLAlchemy's names and count whatever a module imports, as does opening a connection of psycopg, psycopg2, pymysql, sqlite3 or mysql.connector: a call into one of them, followed through the module's -imports, whose last name is ``connect``, ``Connect``, ``Connection`` or -``AsyncConnection``. The rules that go by a +imports, whose last name is ``connect`` or ``Connect``, or ends with +``Connection``. An exception in a test module needs no ``function`` when its +match is raw SQL text, or a statement method, whose first argument holds a +statement keyword outside its SQL comments. The rules that go by a method or attribute name other libraries share apply only in modules that import sqlalchemy or sqlmodel: any ``.table`` read, ``kw["bind"]``, ``.execute()`` on anything not named as a session, ``.scalar()``, @@ -79,7 +81,9 @@ ``bind`` attribute, or an event listener whose target and event name aren't its first two positional arguments, the name a string literal. ``.tables`` of a MetaData isn't reported when the name holding it doesn't end in ``metadata`` -and wasn't assigned ``MetaData(...)``. +and wasn't assigned ``MetaData(...)``. Imports are read for the whole module, +not for each scope, so a local name that shadows one, such as a parameter +named ``sqlite3``, is still taken for the import. """ from __future__ import annotations @@ -171,9 +175,10 @@ # The call that hands out the driver's connection beneath SQLAlchemy's, which # no module may make. DRIVER_CONNECTION_METHODS = frozenset({"raw_connection"}) -# The database drivers, and the last names of their calls that open a -# connection: a connect function or method, as in psycopg.connect or -# psycopg.Connection.connect, or a connection class, as in sqlite3.Connection. +# The database drivers, and how their calls that open a connection end: a +# connect function or method, as in psycopg.connect or +# psycopg.Connection.connect, or a connection class, whose name ends with +# Connection, as in sqlite3.Connection or psycopg2.extras.RealDictConnection. # Only a session-factory module may make them. DATABASE_DRIVER_MODULES = ( "mysql.connector", @@ -182,9 +187,8 @@ "pymysql", "sqlite3", ) -DRIVER_CONNECT_NAMES = frozenset( - {"AsyncConnection", "Connect", "Connection", "connect"} -) +DRIVER_CONNECT_FUNCTIONS = frozenset({"Connect", "connect"}) +DRIVER_CONNECTION_CLASS_SUFFIX = "Connection" # execute runs only on a name such as session or store_session, which finds a # connection passed around without a Connection annotation. A Result has scalar # and scalars too, so the others are reported only on a name such as connection. @@ -286,6 +290,15 @@ # MODULE_LEVEL for a finding in no class or function. TEST_DIRECTORY = "tests/" MODULE_LEVEL = "" +# What makes a literal SQL of its own: a statement keyword as a whole word, +# outside a SQL comment (-- to the end of a line, or /* ... */). +SQL_STATEMENT_KEYWORD = re.compile( + r"\b(?:ALTER|ANALYZE|BEGIN|CALL|COMMENT|COMMIT|COPY|CREATE|DELETE|DO|DROP" + r"|EXPLAIN|GRANT|INSERT|LOCK|PRAGMA|RESET|REVOKE|ROLLBACK|SAVEPOINT|SELECT" + r"|SET|SHOW|TRUNCATE|UPDATE|VACUUM|WITH)\b", + re.IGNORECASE, +) +SQL_COMMENT = re.compile(r"--[^\n]*|/\*.*?\*/", re.DOTALL) # The calls whose first argument is SQL: the raw SQL constructs and the methods # that run a statement. An exception naming one, given SQL of its own, names # one statement, so it needs no function in a test module. @@ -633,15 +646,17 @@ def _connects_a_driver(node: ast.Call, context: _ModuleContext) -> bool: """Whether a call opens a database driver's connection outside a factory. The call is into a driver module, followed through the module's imports, - and its last name is a connect function or a connection class. + and its last name is ``connect`` or ``Connect``, or ends with + ``Connection``, as a connection class's does. """ if context.module.is_session_factory: return False qualified = _qualified_name(node.func, context.module.driver_imported) - return ( - qualified is not None - and _library_of(qualified, DATABASE_DRIVER_MODULES) is not None - and qualified.rsplit(".", 1)[-1] in DRIVER_CONNECT_NAMES + if qualified is None or _library_of(qualified, DATABASE_DRIVER_MODULES) is None: + return False + last_name = qualified.rsplit(".", 1)[-1] + return last_name in DRIVER_CONNECT_FUNCTIONS or last_name.endswith( + DRIVER_CONNECTION_CLASS_SUFFIX ) @@ -1075,30 +1090,48 @@ def unscanned_files( ) -def _holds_literal_sql(argument: ast.expr) -> bool: - """Whether a string or f-string argument has SQL of its own, not only names. +def _literal_text(argument: ast.expr) -> str | None: + """Return a string argument's text, an f-string's with each value a space. - ``'TRUNCATE reports'`` and ``f'TRUNCATE {tables}'`` do; ``''``, - ``f'{statement}'`` and ``f'{statement} {parameters}'`` don't. + Return ``None`` for any other argument. """ if isinstance(argument, ast.Constant): - return isinstance(argument.value, str) and bool(argument.value.strip()) - return isinstance(argument, ast.JoinedStr) and any( - _holds_literal_sql(part) + return argument.value if isinstance(argument.value, str) else None + if not isinstance(argument, ast.JoinedStr): + return None + return "".join( + part.value + if isinstance(part, ast.Constant) and isinstance(part.value, str) + else " " for part in argument.values - if isinstance(part, ast.Constant) ) +def _holds_literal_sql(argument: ast.expr) -> bool: + """Whether a string or f-string argument names a SQL statement of its own. + + Its literal text, less its SQL comments, holds a statement keyword as a + whole word: ``'TRUNCATE reports'`` and ``f'TRUNCATE {tables}'`` do; + ``f'{statement};'``, ``f'{schema}.{table}'``, ``'-- SELECT 1'`` and + ``'count(*)'`` don't. + """ + literal = _literal_text(argument) + if literal is None: + return False + return bool(SQL_STATEMENT_KEYWORD.search(SQL_COMMENT.sub(" ", literal))) + + def _names_sql_text(match: str) -> bool: """Whether ``match`` is raw SQL, or a statement method, given SQL of its own. Such a match names one statement: a raw SQL construct (``text``, ``TextClause``, ``literal_column``, ``DDL``) or a statement method (``execute``, ``exec_driver_sql``, ``scalar`` and the like) whose first - argument holds literal SQL, as ``text(f'TRUNCATE {tables}')`` does. A - string given to anything else, such as ``sqlite3.connect(':memory:')``, a - bare call, a call on variables and an attribute read name none. + argument holds a statement keyword outside its comments, as + ``text(f'TRUNCATE {tables}')`` does. A string given to anything else, such + as ``sqlite3.connect(':memory:')``, an expression such as + ``literal_column('count(*)')``, a bare call, a call on variables and an + attribute read name none. """ try: expression = ast.parse(match, mode="eval").body From 41d63f31483a5736f5406b56edc5f1ddf0b0f5e0 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:10:38 +0400 Subject: [PATCH 20/20] Add a changelog fragment for running every database statement through the ORM Co-Authored-By: Claude Opus 5.5 --- changelog.d/v2-orm-only-database-statements.changed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/v2-orm-only-database-statements.changed.md diff --git a/changelog.d/v2-orm-only-database-statements.changed.md b/changelog.d/v2-orm-only-database-statements.changed.md new file mode 100644 index 000000000..88c979daf --- /dev/null +++ b/changelog.d/v2-orm-only-database-statements.changed.md @@ -0,0 +1 @@ +API v1 runs every database statement through SQLAlchemy's ORM, in its production code, scripts and tests, and rule api.data.orm-only enforces it; the few statements SQLAlchemy can't express, such as GRANT and COPY, are named exceptions. Commands, their arguments and their environment variables are unchanged.