diff --git a/changelog.d/definition-key-audit.changed.md b/changelog.d/definition-key-audit.changed.md new file mode 100644 index 000000000..ffca7cbea --- /dev/null +++ b/changelog.d/definition-key-audit.changed.md @@ -0,0 +1 @@ +Add tests for simulation and report definition keys, UUID request spelling, and run reuse with SPM request variants. diff --git a/libs/policyengine-simulation-persistence/tests/test_definition_keys.py b/libs/policyengine-simulation-persistence/tests/test_definition_keys.py index 3382a3851..d5e6666f8 100644 --- a/libs/policyengine-simulation-persistence/tests/test_definition_keys.py +++ b/libs/policyengine-simulation-persistence/tests/test_definition_keys.py @@ -3,7 +3,11 @@ from __future__ import annotations import hashlib -from dataclasses import replace +import json +from dataclasses import fields, replace +from datetime import datetime +from decimal import Decimal +from random import Random from typing import Any from uuid import UUID @@ -329,3 +333,267 @@ def test_a_household_reports_sides_are_the_simulations_it_names() -> None: same_policy.simulation("baseline").definition_key == same_policy.simulation("reform").definition_key ) + + +SEEDS = range(16) + + +def _generated_definitions(seed): + rng = Random(seed) # noqa: S311 # reproducible synthetic test values + + def new_id(): + return UUID(int=rng.getrandbits(128)) + + baseline = SimulationChoice(new_id(), None if seed % 3 == 0 else new_id()) + reform = SimulationChoice(None if seed % 5 == 0 else new_id(), new_id()) + country = ("us", "uk")[seed % 2] + year = rng.randrange(2000, 2100) + spm = {"label": "café", "values": [rng.randrange(100), 1.5, True, None]} + for _ in range(seed % 4 + 1): + spm = {"layers": [spm, {"first": False, "last": "東京"}], "count": seed} + economy = EconomyReportDefinition( + country=country, + baseline=baseline, + reform=reform, + dataset_name=f"dataset-{seed}", + region_code=f"{country}/region-{seed}", + year=year, + budget_window_size=3 if seed % 2 else None, + spm=spm, + ) + household = HouseholdReportDefinition( + country=country, + baseline=baseline, + reform=None if seed % 4 == 0 else reform, + household_id=new_id(), + year=year, + ) + return ( + economy, + _direct_economy_simulation(economy, baseline, year), + household, + _direct_household_simulation(household, baseline), + ) + + +def _direct_economy_simulation(report, choice, year): + return EconomySimulationDefinition( + report.country, + choice, + report.dataset_name, + report.region_code, + year, + report.spm, + ) + + +def _direct_household_simulation(report, choice): + return HouseholdSimulationDefinition( + report.country, choice, report.household_id, report.year + ) + + +def _keys(record): + if isinstance(record, (EconomyReportDefinition, HouseholdReportDefinition)): + return record.definition_key, record.dataset_independent_key + return (record.definition_key,) + + +def _reverse_objects(value): + if isinstance(value, dict): + return {name: _reverse_objects(value[name]) for name in reversed(value)} + if isinstance(value, list): + return [_reverse_objects(item) for item in value] + return value + + +@pytest.mark.parametrize("seed", SEEDS) +def test_generated_keys_ignore_nested_object_order(seed): + for original in _generated_definitions(seed): + if isinstance(original, (EconomySimulationDefinition, EconomyReportDefinition)): + reordered = replace(original, spm=_reverse_objects(original.spm)) + assert _keys(original) == _keys(reordered) + + +def _other_id(value): + return UUID(int=1) if value is None else UUID(int=value.int ^ 1) + + +def _field_changes(record): + replacements = { + "country": "us" if record.country == "uk" else "uk", + "year": record.year + 1, + "spm": None, + "budget_window_size": 2, + } + for field in fields(record): + name = field.name + value = getattr(record, name) + if name in {"choice", "baseline", "reform"}: + if value is None: + yield name, SimulationChoice(UUID(int=1), None) + else: + yield name, replace(value, policy_id=_other_id(value.policy_id)) + yield name, replace(value, dynamic_id=_other_id(value.dynamic_id)) + if name == "reform" and isinstance(record, HouseholdReportDefinition): + yield name, None + elif name == "household_id": + yield name, _other_id(value) + elif name in {"dataset_name", "region_code"}: + yield name, value + "-other" + else: + yield name, replacements[name] + + +@pytest.mark.parametrize("seed", SEEDS) +def test_generated_keys_change_with_each_field_except_the_ignored_dataset(seed): + for original in _generated_definitions(seed): + for name, value in _field_changes(original): + changed = replace(original, **{name: value}) + assert changed.definition_key != original.definition_key, ( + seed, + changed, + name, + ) + if isinstance( + original, (EconomyReportDefinition, HouseholdReportDefinition) + ): + same = ( + changed.dataset_independent_key == original.dataset_independent_key + ) + assert same == (name == "dataset_name"), (seed, changed, name) + assert _keys(changed) == _reference_keys(changed) + + +@pytest.mark.parametrize("seed", SEEDS) +def test_generated_keys_separate_record_kinds_and_populations(seed): + keys = [key for record in _generated_definitions(seed) for key in _keys(record)] + assert len(set(keys)) == len(keys) == 6 + + +@pytest.mark.parametrize("seed", SEEDS) +def test_generated_report_sides_have_the_keys_of_direct_simulations(seed): + economy, _, household, _ = _generated_definitions(seed) + for side in ("baseline", "reform"): + choice = getattr(economy, side) + assert ( + economy.simulation(side).definition_key + == _direct_economy_simulation(economy, choice, economy.year).definition_key + ) + year = economy.year + 1 + assert economy.simulation(side, year=year).definition_key == ( + _direct_economy_simulation(economy, choice, year).definition_key + ) + for side in household.sides: + assert household.simulation(side).definition_key == ( + _direct_household_simulation( + household, getattr(household, side) + ).definition_key + ) + + +def _reference_side(choice): + if choice is None: + return None + return { + "policy_id": None if choice.policy_id is None else str(choice.policy_id), + "dynamic_id": None if choice.dynamic_id is None else str(choice.dynamic_id), + } + + +def _reference_keys(record): + # Build from definition fields and the v1 spec, without calling production + # key-object or JSON helpers. + economy = isinstance(record, (EconomyReportDefinition, EconomySimulationDefinition)) + report = isinstance(record, (EconomyReportDefinition, HouseholdReportDefinition)) + kind = "economy" if economy else "household" + payload = {"key_version": 1, "country": record.country, "year": record.year} + + if report: + payload.update( + record="report", + report_type=kind, + baseline=_reference_side(record.baseline), + reform=_reference_side(record.reform), + budget_window_size=record.budget_window_size if economy else None, + ) + else: + payload.update( + record="simulation", + simulation_type=kind, + filter=None, + **_reference_side(record.choice), + ) + if economy: + payload.update( + dataset=record.dataset_name, region=record.region_code, spm=record.spm + ) + else: + payload["household_id"] = str(record.household_id) + + def digest(value): + encoded = json.dumps( + value, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=False, + allow_nan=False, + ) + return hashlib.sha256(encoded.encode("utf-8")).hexdigest() + + key = digest(payload) + if not report: + return (key,) + payload.pop("dataset", None) + payload["record"] = "report_dataset_independent" + return key, digest(payload) + + +@pytest.mark.parametrize("seed", SEEDS) +def test_generated_keys_agree_with_the_independent_v1_digest(seed): + for record in _generated_definitions(seed): + assert _keys(record) == _reference_keys(record) + + +@pytest.mark.parametrize( + "spm", + [ + None, + {}, + {"scenario": None}, + {"forecast_content_sha256": None}, + {"geography_kind": "national"}, + {"geography_kind": "national", "geography_id": None}, + ], + ids=["omitted", "empty", "scenario", "forecast-hash", "national", "national-id"], +) +def test_v1_keys_preserve_the_original_spm_representations(spm): + report = _report_n( + country="us", region_code="us", dataset_name="test-dataset", spm=spm + ) + assert _keys(report) == _reference_keys(report) + for side in ("baseline", "reform"): + direct = _direct_economy_simulation(report, getattr(report, side), report.year) + assert _keys(report.simulation(side)) == _reference_keys(direct) + + +@pytest.mark.parametrize("depth", range(5)) +@pytest.mark.parametrize( + ("value", "error"), + [ + (float("nan"), ValueError), + (float("inf"), ValueError), + (-float("inf"), ValueError), + ({1, 2}, TypeError), + (b"bytes", TypeError), + (Decimal("1.25"), TypeError), + (datetime(2026, 1, 1), TypeError), + ], + ids=["nan", "inf", "negative-inf", "set", "bytes", "decimal", "datetime"], +) +def test_generated_nesting_rejects_unsupported_json_values(value, error, depth): + definition = {"value": value} + for _ in range(depth): + definition = {"items": [None, definition]} + with pytest.raises(error): + canonical_json(definition) diff --git a/projects/policyengine-simulation-entry/tests/economy_reuse_fakes.py b/projects/policyengine-simulation-entry/tests/economy_reuse_fakes.py new file mode 100644 index 000000000..1a3145b00 --- /dev/null +++ b/projects/policyengine-simulation-entry/tests/economy_reuse_fakes.py @@ -0,0 +1,102 @@ +"""An in-memory session for sequential keyed economy submissions.""" + +from __future__ import annotations + +from collections import defaultdict +from contextlib import nullcontext +from types import SimpleNamespace +from unittest.mock import Mock + +from economy_service_fakes import FakeStore +from policyengine_simulation_persistence import EconomyRunStore +from sqlalchemy.dialects.postgresql import Insert +from sqlalchemy.sql import Select, operators +from sqlalchemy.sql.elements import ( + BinaryExpression, + BindParameter, + BooleanClauseList, + Grouping, +) + +_SQL_CONSTANTS = {"false": False, "true": True, "null": None} + + +def _matches(clause, row): + if isinstance(clause, Grouping): + return _matches(clause.element, row) + if isinstance(clause, BooleanClauseList): + matches = (_matches(part, row) for part in clause.clauses) + if clause.operator is operators.and_: + return all(matches) + if clause.operator is operators.or_: + return any(matches) + elif isinstance(clause, BinaryExpression): + left = row[clause.left.key] + right = ( + clause.right.value + if isinstance(clause.right, BindParameter) + else _SQL_CONSTANTS[str(clause.right).lower()] + ) + if clause.operator is operators.is_: + return left is right + if clause.operator in (operators.eq, operators.ne): + return clause.operator(left, right) + if clause.operator is operators.in_op: + return left in right + msg = f"Unsupported test selection: {clause}" + raise NotImplementedError(msg) + + +class _ReuseSession: + """Run the INSERT conflict and SELECT predicates for sequential pending rows. + + Concurrency, failed runs and database constraints belong to the marked + PostgreSQL tests. + """ + + def __init__(self): + self.rows = defaultdict(list) + + def begin_nested(self): + snapshot = {name: rows.copy() for name, rows in self.rows.items()} + return Mock(rollback=lambda: self._restore(snapshot)) + + def _restore(self, snapshot): + self.rows.clear() + self.rows.update(snapshot) + + def execute(self, statement): + if isinstance(statement, Insert): + rows = self.rows[statement.table.name] + columns = statement._post_values_clause.inferred_target_elements + values = {"forced": False, **statement.compile().params} + matched = any( + all(row[column] == values[column] for column in columns) for row in rows + ) + if matched: + return Mock(one_or_none=lambda: None) + rows.append(values) + return Mock(one_or_none=lambda: SimpleNamespace(**values)) + if isinstance(statement, Select): + (table,) = statement.get_final_froms() + matched = [ + SimpleNamespace(**row) + for row in self.rows[table.name] + if _matches(statement.whereclause, row) + ] + if len(matched) <= 1: + return Mock(one_or_none=lambda: next(iter(matched), None)) + msg = f"Unsupported test query or result: {statement}" + raise NotImplementedError(msg) + + +class ReusingEconomyStore(FakeStore): + """Use the real persistence lookups for writes, with catalog and Modal faked.""" + + def __init__(self): + super().__init__() + session = _ReuseSession() + self.persistence = EconomyRunStore(lambda: nullcontext(session)) + + def find_or_create_report(self, report): + return self.persistence.find_or_create_report(report) diff --git a/projects/policyengine-simulation-entry/tests/test_economy_report_reuse.py b/projects/policyengine-simulation-entry/tests/test_economy_report_reuse.py new file mode 100644 index 000000000..6a907d509 --- /dev/null +++ b/projects/policyengine-simulation-entry/tests/test_economy_report_reuse.py @@ -0,0 +1,109 @@ +"""Report submission reuse with real persistence lookups and an in-memory session.""" + +from __future__ import annotations + +import asyncio + +import pytest +from economy_reuse_fakes import ReusingEconomyStore +from economy_service_fakes import REPORT_BODY, FakeCaller, service +from policyengine_simulation_entry.economy_api_models import EconomyReportRequest + +_SIDES = ("baseline", "reform") +_OTHER_POLICY_ID = "a0000000-0000-4000-8000-000000000001" +_NULL_SELECTIONS = [ + pytest.param({}, "scenario", id="scenario"), + pytest.param({}, "forecast_content_sha256", id="forecast-hash"), + pytest.param({"geography_kind": "national"}, "geography_id", id="national-id"), +] + + +def _submit_twice(first_selection, second_selection, **second_choices): + caller = FakeCaller() + submissions = service(ReusingEconomyStore(), caller=caller) + body = {name: value for name, value in REPORT_BODY.items() if name != "spm"} + body["include_cliffs"] = False + + async def submit(selection, **choices): + fields = {} if selection is None else {"spm": selection} + return await submissions.submit_report( + EconomyReportRequest.model_validate(body | fields | choices), + request_id="test-reuse", + observability_context=None, + ) + + async def both(): + return await submit(first_selection), await submit( + second_selection, **second_choices + ) + + first, second = asyncio.run(both()) + return first, second, caller + + +def _simulation_runs(report): + return report.baseline_simulation_run_id, report.reform_simulation_run_id + + +def test_identical_report_requests_reuse_their_runs(): + first, second, caller = _submit_twice({}, {}) + assert _simulation_runs(first) == _simulation_runs(second) + assert first.report_run_id == second.report_run_id + assert len(caller.report_runs) == 1 + + +def _unchanged_side_runs(first_selection, second_selection, side): + # An existing report run returns its saved side IDs. Give the other + # side a new policy to exercise simulation-run lookup independently. + other = "reform" if side == "baseline" else "baseline" + first, second, _ = _submit_twice( + first_selection, second_selection, **{other: {"policy_id": _OTHER_POLICY_ID}} + ) + if first.report_run_id == second.report_run_id: + pytest.fail("Changing the other policy must produce a different report run") + field = f"{side}_simulation_run_id" + return getattr(first, field), getattr(second, field) + + +@pytest.mark.parametrize("side", _SIDES) +def test_distinct_reports_reuse_the_simulation_run_of_an_unchanged_side(side): + first, second = _unchanged_side_runs({}, {}, side) + assert first == second + + +@pytest.mark.parametrize("side", _SIDES) +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="Omission and an empty SPM selection can split simulation-run reuse", +) +def test_omitted_and_empty_spm_reuse_the_same_simulation_runs(side): + first, second = _unchanged_side_runs(None, {}, side) + assert first == second + + +@pytest.mark.parametrize("side", _SIDES) +@pytest.mark.parametrize(("selection", "null_field"), _NULL_SELECTIONS) +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="Omission and a null default selector can split simulation-run reuse", +) +def test_null_spm_default_selectors_reuse_the_same_simulation_runs( + selection, null_field, side +): + first, second = _unchanged_side_runs( + selection, {**selection, null_field: None}, side + ) + assert first == second + + +@pytest.mark.parametrize(("selection", "null_field"), _NULL_SELECTIONS) +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="Omission and a null default selector can split report-run reuse", +) +def test_null_spm_default_selectors_reuse_the_same_report_run(selection, null_field): + first, second, _ = _submit_twice(selection, {**selection, null_field: None}) + assert first.report_run_id == second.report_run_id diff --git a/projects/policyengine-simulation-entry/tests/test_economy_submissions.py b/projects/policyengine-simulation-entry/tests/test_economy_submissions.py index cbb85cccc..d76a9f644 100644 --- a/projects/policyengine-simulation-entry/tests/test_economy_submissions.py +++ b/projects/policyengine-simulation-entry/tests/test_economy_submissions.py @@ -291,6 +291,49 @@ def test_a_report_without_spm_settings_stores_none() -> None: assert payload.reform.options == {} +def test_economy_report_keys_ignore_request_uuid_case(): + store = FakeStore() + submissions = service(store) + for transform in (str.lower, str.upper): + _submit_report( + submissions, + report_request( + include_cliffs=False, + reform={ + "policy_id": transform(str(POLICY_ID)), + "dynamic_id": transform(str(DYNAMIC_ID)), + }, + ), + ) + + lower, upper = (report.definition for report in store.reports) + assert (lower.definition_key, lower.dataset_independent_key) == ( + upper.definition_key, + upper.dataset_independent_key, + ) + for side in ("baseline", "reform"): + assert ( + lower.simulation(side).definition_key + == upper.simulation(side).definition_key + ) + + +def test_standalone_simulation_key_ignores_request_uuid_case(): + store = FakeStore() + submissions = service(store) + for transform in (str.lower, str.upper): + _submit_simulation( + submissions, + simulation_request( + policy_id=transform(str(POLICY_ID)), + dynamic_id=transform(str(DYNAMIC_ID)), + ), + ) + + lower, upper = (simulation.definition for simulation in store.simulations) + assert lower.definition_key == upper.definition_key + + def _started_cliff_calculations(caller: FakeCaller) -> dict[UUID, UUID]: """Return each cliff calculation the service started, by its simulation run.""" started: dict[UUID, UUID] = {} diff --git a/projects/policyengine-simulation-entry/tests/test_household_report_submissions.py b/projects/policyengine-simulation-entry/tests/test_household_report_submissions.py index 4f1ad058a..1285c0f1b 100644 --- a/projects/policyengine-simulation-entry/tests/test_household_report_submissions.py +++ b/projects/policyengine-simulation-entry/tests/test_household_report_submissions.py @@ -227,6 +227,33 @@ def test_each_sides_dynamic_is_read_keyed_and_applied_with_its_policy(): ) +def test_household_report_keys_ignore_request_uuid_case(): + store = FakeHouseholdReportStore() + service = household_report_service(store) + for transform in (str.lower, str.upper): + _submit( + service, + household_report_request( + household_id=transform(str(HOUSEHOLD_ID)), + reform={ + "policy_id": transform(str(POLICY_ID)), + "dynamic_id": transform(str(DYNAMIC_ID)), + }, + ), + ) + + lower, upper = (report.definition for report in store.keyed_reports) + assert (lower.definition_key, lower.dataset_independent_key) == ( + upper.definition_key, + upper.dataset_independent_key, + ) + for side in ("baseline", "reform"): + assert ( + lower.simulation(side).definition_key + == upper.simulation(side).definition_key + ) + + def test_a_report_with_a_dynamic_keys_apart_from_one_without(): store = FakeHouseholdReportStore() service = household_report_service(store)