From ec54674926c32115fdc1038e3c05ef1e059e126f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:00:50 +0400 Subject: [PATCH 1/6] Add tests for production's household containers that fail before the change Production's v2 household functions are to keep one container running per country, with extra containers stopped after ten idle minutes; staging keeps none. The tests cover reading those settings at deploy time, the deploy workflow passing each environment's values, and a script, run once the v2 default has moved, that sets the minimum to 0 on every other deployed v2 app's household functions. Placeholder modules let the tests fail on their assertions; the next commit implements them. Co-Authored-By: Claude Opus 5.5 --- ..._deployment_assets_household_containers.py | 225 ++++++ .../lower_replaced_household_containers.py | 47 ++ .../src/modal/v2_household_scaling.py | 22 + ...est_lower_replaced_household_containers.py | 725 ++++++++++++++++++ .../tests/test_v2_household_scaling.py | 174 +++++ 5 files changed, 1193 insertions(+) create mode 100644 projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py create mode 100644 projects/policyengine-simulation-executor/src/modal/utils/lower_replaced_household_containers.py create mode 100644 projects/policyengine-simulation-executor/src/modal/v2_household_scaling.py create mode 100644 projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py create mode 100644 projects/policyengine-simulation-executor/tests/test_v2_household_scaling.py diff --git a/projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py b/projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py new file mode 100644 index 000000000..789ab694c --- /dev/null +++ b/projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py @@ -0,0 +1,225 @@ +"""Deployment wiring for the containers the v2 household functions keep running. + +Each deploy gives ``modal deploy`` of the v2 app its environment's minimum +container count and idle window for the household functions: production +keeps one container per country, with extra containers stopped after ten +idle minutes; staging keeps none, with Modal's 60 seconds. Every .py +version's v2 app stays deployed, so once the v2 default has moved, a job of +its own sets the minimum to 0 on every other v2 app's household functions. +""" + +from __future__ import annotations + +import pytest +import yaml +from test_deployment_assets_support import ( + REUSABLE_DEPLOY_WORKFLOW, + WORKFLOWS_DIRECTORY, + evaluate_github_expression, + step_shell, + workflow_jobs, +) + +MIN_CONTAINERS_INPUT = "household_function_min_containers" +SCALEDOWN_WINDOW_INPUT = "household_function_scaledown_window_seconds" +V2_DEPLOY_STEP = "Deploy the additional versioned v2 Modal application" +DEFAULT_JOB = "publish_stage12_v2_default" +LOWERING_JOB = "lower_replaced_household_containers" +LOWERING_STEP = "Stop keeping household containers in replaced v2 apps" +LOWERING_MODULE = "src.modal.utils.lower_replaced_household_containers" +EXECUTOR_DIRECTORY = "projects/policyengine-simulation-executor" + + +def _jobs() -> dict: + return workflow_jobs(REUSABLE_DEPLOY_WORKFLOW) + + +def _step(job: dict, name: str) -> dict: + matching = [step for step in job["steps"] if step.get("name") == name] + assert len(matching) == 1, name + return matching[0] + + +def _lowering_job() -> dict: + jobs = _jobs() + assert LOWERING_JOB in jobs + return jobs[LOWERING_JOB] + + +def _reusable_inputs() -> dict: + workflow = yaml.safe_load(REUSABLE_DEPLOY_WORKFLOW.read_text(encoding="utf-8")) + # PyYAML reads the ``on`` key as True. + return workflow[True]["workflow_call"]["inputs"] + + +def _reusable_deploy_calls() -> dict[tuple[str, str], dict]: + """Return each job that calls the reusable deploy, by workflow file and job.""" + calls = {} + for path in sorted(WORKFLOWS_DIRECTORY.glob("*.yml")): + jobs = yaml.safe_load(path.read_text(encoding="utf-8")).get("jobs") or {} + for job_id, job in jobs.items(): + if job.get("uses") == "./.github/workflows/simulation-deploy.reusable.yml": + calls[(path.name, job_id)] = job + return calls + + +@pytest.mark.parametrize("input_name", [MIN_CONTAINERS_INPUT, SCALEDOWN_WINDOW_INPUT]) +def test_the_reusable_deploy_requires_both_household_settings(input_name): + inputs = _reusable_inputs() + + assert input_name in inputs + assert inputs[input_name]["required"] is True + assert inputs[input_name]["type"] == "number" + assert "default" not in inputs[input_name] + + +@pytest.mark.parametrize( + ("workflow", "job_id", "modal_environment", "minimum", "window"), + [ + ("simulation-deploy.yml", "beta", "staging", 0, 60), + ("simulation-deploy.yml", "prod", "main", 1, 600), + ("stage12-deploy.yml", "deploy-stage12-staging", "staging", 0, 60), + ("stage12-deploy.yml", "deploy-stage12-production", "main", 1, 600), + ], +) +def test_each_deploy_sets_its_environments_household_settings( + workflow, job_id, modal_environment, minimum, window +): + settings = _reusable_deploy_calls()[(workflow, job_id)]["with"] + + assert settings["modal_environment"] == modal_environment + assert settings.get(MIN_CONTAINERS_INPUT) == minimum + assert settings.get(SCALEDOWN_WINDOW_INPUT) == window + + +def test_every_call_of_the_reusable_deploy_is_covered(): + """A new caller must be added to the table above with its own values.""" + assert set(_reusable_deploy_calls()) == { + ("simulation-deploy.yml", "beta"), + ("simulation-deploy.yml", "prod"), + ("stage12-deploy.yml", "deploy-stage12-staging"), + ("stage12-deploy.yml", "deploy-stage12-production"), + } + + +def test_the_v2_deploy_passes_the_settings_to_modal_deploy(): + deploy = _step(_jobs()["deploy_stage12_v2"], V2_DEPLOY_STEP) + + assert "modal deploy" in deploy["run"] + assert "src/modal/v2_app.py" in deploy["run"] + assert deploy["env"].get("HOUSEHOLD_FUNCTION_MIN_CONTAINERS") == ( + f"${{{{ inputs.{MIN_CONTAINERS_INPUT} }}}}" + ) + assert deploy["env"].get("HOUSEHOLD_FUNCTION_SCALEDOWN_WINDOW_SECONDS") == ( + f"${{{{ inputs.{SCALEDOWN_WINDOW_INPUT} }}}}" + ) + + +def test_the_settings_reach_no_other_step(): + for job_id, job in _jobs().items(): + for step in job.get("steps", []): + if step.get("name") == V2_DEPLOY_STEP: + continue + environment = step.get("env") or {} + assert "HOUSEHOLD_FUNCTION_MIN_CONTAINERS" not in environment, job_id + assert "HOUSEHOLD_FUNCTION_SCALEDOWN_WINDOW_SECONDS" not in environment, ( + job_id + ) + + +def test_the_lowering_job_waits_for_the_default_move(): + job = _lowering_job() + + assert job["name"] == LOWERING_STEP + assert job["needs"] == [DEFAULT_JOB] + assert job["environment"] == "${{ inputs.release_environment }}" + assert job["runs-on"] == "ubuntu-latest" + assert job["defaults"]["run"]["shell"] == "bash" + + +def _context(*, default_result="success", deploy_stage12=True, cancelled=False): + return { + "inputs": {"deploy_stage12_v2": deploy_stage12}, + "needs": {DEFAULT_JOB: {"result": default_result}}, + "cancelled": cancelled, + } + + +@pytest.mark.parametrize( + ("context", "runs"), + [ + (_context(), True), + (_context(default_result="failure"), False), + (_context(default_result="skipped"), False), + (_context(default_result="cancelled"), False), + (_context(deploy_stage12=False), False), + (_context(deploy_stage12=False, default_result="skipped"), False), + (_context(cancelled=True), False), + ], + ids=[ + "default-moved", + "default-job-failed", + "default-job-skipped", + "default-job-cancelled", + "stage12-input-off", + "stage12-not-requested", + "run-cancelled", + ], +) +def test_the_lowering_job_runs_only_after_a_successful_default_move(context, runs): + job = _lowering_job() + + assert bool(evaluate_github_expression(job["if"], context, job_if=True)) is runs + + +def test_the_lowering_step_runs_the_script_in_the_deploys_modal_environment(): + job = _lowering_job() + step = _step(job, LOWERING_STEP) + + assert step["run"] == ( + f"uv run --frozen python -m {LOWERING_MODULE} " + '--environment "${{ inputs.modal_environment }}" ' + "--manifest-name simulation-api-v2-version-manifest" + ) + assert step["working-directory"] == EXECUTOR_DIRECTORY + # Only Modal's tokens: the script reads the manifest and changes the + # functions in the Modal environment it is given. + assert step["env"] == { + "MODAL_TOKEN_ID": "${{ secrets.MODAL_TOKEN_ID }}", + "MODAL_TOKEN_SECRET": "${{ secrets.MODAL_TOKEN_SECRET }}", + } + assert "if" not in step + assert "continue-on-error" not in step + assert "continue-on-error" not in job + + +def test_the_lowering_job_installs_the_executors_locked_dependencies_first(): + job = _lowering_job() + names = [step.get("name") for step in job["steps"]] + install = _step(job, "Install the household container script's dependencies") + + assert install["run"] == "uv sync --frozen" + assert install["working-directory"] == EXECUTOR_DIRECTORY + assert names.index(install["name"]) < names.index(LOWERING_STEP) + setup_uv = next( + step + for step in job["steps"] + if str(step.get("uses", "")).startswith("astral-sh/setup-uv@") + ) + assert setup_uv["with"]["version"] == "0.13.6" + assert job["steps"][-1]["name"] == LOWERING_STEP + + +def test_only_the_lowering_job_runs_the_script(): + """A failed lowering never puts the previous v2 default back.""" + jobs = _jobs() + + for job_id, job in jobs.items(): + if job_id == LOWERING_JOB: + continue + for step in job.get("steps", []): + assert LOWERING_MODULE not in step_shell(step), job_id + restore = _step( + jobs[DEFAULT_JOB], "Put the v2 default back after a failed or cancelled step" + ) + assert jobs[DEFAULT_JOB]["steps"][-1] is restore diff --git a/projects/policyengine-simulation-executor/src/modal/utils/lower_replaced_household_containers.py b/projects/policyengine-simulation-executor/src/modal/utils/lower_replaced_household_containers.py new file mode 100644 index 000000000..d32a97a34 --- /dev/null +++ b/projects/policyengine-simulation-executor/src/modal/utils/lower_replaced_household_containers.py @@ -0,0 +1,47 @@ +"""Stop keeping household containers running in replaced v2 apps. + +Placeholder: nothing is lowered yet. +""" + +from __future__ import annotations + +import modal + +HOUSEHOLD_FUNCTION_NAMES: tuple[str, ...] = () + + +class HouseholdContainerLoweringError(RuntimeError): + """The manifest or the application list could not be read.""" + + +def list_applications(environment: str, *, run: object = None) -> str: + """Return no applications yet.""" + del environment, run + return "" + + +def modal_function( + application_name: str, function_name: str, environment: str +) -> object: + """Look up nothing yet.""" + del application_name, function_name, environment + + +def open_manifest(manifest_name: str, environment: str) -> object: + """Open nothing yet.""" + del manifest_name, environment + + +def lower_replaced_household_containers(**kwargs: object) -> int: + """Lower nothing yet.""" + del kwargs + return 0 + + +def main(argv: list[str] | None = None, **kwargs: object) -> int: + """Lower nothing yet.""" + del argv, kwargs + return 0 + + +__all__ = ["modal"] diff --git a/projects/policyengine-simulation-executor/src/modal/v2_household_scaling.py b/projects/policyengine-simulation-executor/src/modal/v2_household_scaling.py new file mode 100644 index 000000000..f51324023 --- /dev/null +++ b/projects/policyengine-simulation-executor/src/modal/v2_household_scaling.py @@ -0,0 +1,22 @@ +"""How many containers each v2 household function keeps running. + +Placeholder: the deploy's settings are not read yet. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Mapping + +MIN_CONTAINERS_VARIABLE = "HOUSEHOLD_FUNCTION_MIN_CONTAINERS" +SCALEDOWN_WINDOW_VARIABLE = "HOUSEHOLD_FUNCTION_SCALEDOWN_WINDOW_SECONDS" + + +def household_function_scaling( + environ: Mapping[str, str], *, max_containers: int +) -> dict[str, int]: + """Return no settings yet.""" + del environ, max_containers + return {} diff --git a/projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py b/projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py new file mode 100644 index 000000000..038382758 --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py @@ -0,0 +1,725 @@ +"""Tests for the script that stops replaced v2 apps' household containers. + +A production deploy keeps one container running for each household function +of the v2 app it deploys, and every .py version's app stays deployed. Once +the deploy has moved the v2 manifest's default, the script sets the minimum +to 0 on the household functions of every other deployed v2 app in the +environment. Each test runs it against a manifest store held in memory, the +JSON ``modal app list --json`` prints, and fake Modal functions that record +each ``update_autoscaler`` call, so no test reaches Modal. +""" + +from __future__ import annotations + +import json +import subprocess +import sys +from datetime import UTC, datetime +from types import SimpleNamespace + +import pytest +from policyengine_simulation_contract.stage12_bundle import ( + Stage12BundleManifest, + Stage12CountryBundle, + Stage12Dataset, +) +from policyengine_simulation_contract.stage12_manifest import ( + V2_VERSION_MANIFEST_NAME, + V2CountryWorker, + V2WorkerValidation, + V2WorkerVersion, + add_v2_worker, + move_v2_default, + v2_application_name, + write_v2_manifest, +) +from src.modal.utils import lower_replaced_household_containers as lowering + +CORE_PACKAGE_VERSION = "3.33.3" +BUNDLE_MANIFEST_SHA256 = "b" * 64 +HOUSEHOLD_FUNCTIONS = ("calculate_household_us", "calculate_household_uk") +OLDEST = "6.19.0" +OLDER = "6.20.4" +NEWEST = "6.21.0" +# A version whose application name has letters, so a listing can differ from +# it in letter case only. +PRERELEASE = "6.22.0rc1" + + +class NotFoundError(Exception): + """Stands in for ``modal.exception.NotFoundError``. + + Under pytest, ``modal`` resolves to this project's ``src/modal``, so the + tests give the script a stand-in ``modal`` with this error class. + """ + + +@pytest.fixture(autouse=True) +def stand_in_modal(monkeypatch): + """Give the script a ``modal`` whose lookups each test sets.""" + monkeypatch.setattr( + lowering, + "modal", + SimpleNamespace( + exception=SimpleNamespace(NotFoundError=NotFoundError), + Function=SimpleNamespace(from_name=None), + Dict=SimpleNamespace(from_name=None), + ), + ) + + +def _country_bundle(country: str) -> Stage12CountryBundle: + package = f"policyengine-{country}" + dataset = f"populace_{country}_2024" + revision = f"{dataset}-revision" + return Stage12CountryBundle( + country=country, + country_package_name=package, + country_package_version="2.1.0", + country_package_requirement=f"{package}==2.1.0", + data_package_name="populace-data", + data_package_version="0.1.0", + data_release_version=revision, + data_artifact_revision=revision, + default_dataset=dataset, + default_dataset_uri=f"hf://policyengine/data/{dataset}.h5@{revision}", + datasets=( + Stage12Dataset( + identity=dataset, + uri=f"hf://policyengine/data/{dataset}.h5@{revision}", + artifact_revision=revision, + sha256="a" * 64, + repo_type="dataset", + ), + ), + ) + + +def _worker(policyengine_version: str) -> V2WorkerVersion: + """Return a validated worker with household functions for both countries.""" + application_name = v2_application_name(policyengine_version) + return V2WorkerVersion( + application_name=application_name, + report_coordinator_callable="coordinate_report", + countries=tuple( + V2CountryWorker( + country=country, + economy_capable=True, + single_simulation_callable=f"run_single_simulation_{country}", + household_callable=f"calculate_household_{country}", + ) + for country in ("us", "uk") + ), + bundle=Stage12BundleManifest( + policyengine_version=policyengine_version, + policyengine_requirement=f"policyengine=={policyengine_version}", + core_package_version=CORE_PACKAGE_VERSION, + core_package_requirement=f"policyengine-core=={CORE_PACKAGE_VERSION}", + countries=tuple(_country_bundle(country) for country in ("us", "uk")), + ), + bundle_manifest_sha256=BUNDLE_MANIFEST_SHA256, + validation=V2WorkerValidation( + validated=True, + application_name=application_name, + bundle_manifest_sha256=BUNDLE_MANIFEST_SHA256, + validated_at=datetime(2026, 11, 10, tzinfo=UTC), + validation_invocation_id="validation-1", + country_validation_invocation_ids={ + country: f"validation-{country}" for country in ("us", "uk") + }, + household_validation_invocation_ids={ + country: f"household-validation-{country}" for country in ("us", "uk") + }, + ), + ) + + +def _manifest_store(*, versions: tuple[str, ...], default: str) -> dict[str, object]: + """Return a store whose manifest names ``versions``, ``default`` the default.""" + manifest = None + for version in versions: + manifest = add_v2_worker(current=manifest, worker=_worker(version)) + store: dict[str, object] = {} + write_v2_manifest( + store=store, manifest=move_v2_default(current=manifest, version=default) + ) + return store + + +def _app(name: str, state: str = "deployed") -> dict[str, object]: + """Return one entry as ``modal app list --json`` prints it.""" + return { + "app_id": f"ap-{name or 'unnamed'}", + "description": name, + "state": state, + "tasks": "0", + "created_at": "2026-12-03 10:00:00+00:00", + "stopped_at": None, + } + + +def _app_list(*entries: dict[str, object]) -> str: + return json.dumps(list(entries), indent=2) + + +class FakeModal: + """The manifest Dict, ``modal app list`` and Modal functions, recording each use.""" + + def __init__( + self, + *, + store: dict[str, object] | None, + app_list: str, + missing: frozenset[tuple[str, str]] = frozenset(), + missing_at_lookup: frozenset[tuple[str, str]] = frozenset(), + failing: frozenset[tuple[str, str]] = frozenset(), + ) -> None: + self.store = store + self.app_list = app_list + self.missing = missing + self.missing_at_lookup = missing_at_lookup + self.failing = failing + self.manifests_opened: list[tuple[str, str]] = [] + self.app_lists: list[str] = [] + self.lookups: list[tuple[str, str, str]] = [] + self.updates: list[tuple[str, str, str, dict[str, object]]] = [] + + def open_manifest(self, manifest_name: str, environment: str): + self.manifests_opened.append((manifest_name, environment)) + if self.store is None: + msg = "the manifest Dict could not be read" + raise RuntimeError(msg) + return self.store + + def list_apps(self, environment: str) -> str: + self.app_lists.append(environment) + return self.app_list + + def lookup(self, application_name: str, function_name: str, environment: str): + self.lookups.append((application_name, function_name, environment)) + if (application_name, function_name) in self.missing_at_lookup: + msg = f"Function '{application_name}.{function_name}' not found" + raise NotFoundError(msg) + + def update_autoscaler(**settings: object) -> None: + self.updates.append( + (application_name, function_name, environment, settings) + ) + if (application_name, function_name) in self.missing: + msg = f"Function '{application_name}.{function_name}' not found" + raise NotFoundError(msg) + if (application_name, function_name) in self.failing: + msg = "the autoscaler update was refused" + raise RuntimeError(msg) + + return SimpleNamespace(update_autoscaler=update_autoscaler) + + def lowered(self) -> list[tuple[str, str]]: + """Return each function whose update set the minimum to 0 and succeeded.""" + return [ + (application_name, function_name) + for application_name, function_name, _environment, settings in self.updates + if settings == {"min_containers": 0} + and (application_name, function_name) not in self.missing | self.failing + ] + + +def _run(fake: FakeModal, environment: str = "main", **overrides) -> int: + return lowering.lower_replaced_household_containers( + environment=environment, + manifest_name=overrides.pop("manifest_name", V2_VERSION_MANIFEST_NAME), + open_manifest=fake.open_manifest, + list_apps=fake.list_apps, + lookup=fake.lookup, + **overrides, + ) + + +def _both_functions(*versions: str) -> list[tuple[str, str]]: + return [ + (v2_application_name(version), function_name) + for version in versions + for function_name in HOUSEHOLD_FUNCTIONS + ] + + +def test_the_household_functions_are_both_countries(): + assert lowering.HOUSEHOLD_FUNCTION_NAMES == HOUSEHOLD_FUNCTIONS + + +def test_every_replaced_v2_app_stops_keeping_household_containers(capsys): + fake = FakeModal( + store=_manifest_store(versions=(OLDEST, OLDER, NEWEST), default=NEWEST), + app_list=_app_list( + _app(v2_application_name(NEWEST)), + _app(v2_application_name(OLDER)), + _app(v2_application_name(OLDEST)), + ), + ) + + assert _run(fake) == 0 + + # Only the minimum changes, to 0, in the deploy's Modal environment; + # oldest first, so a run's output reads the same each time. + assert fake.updates == [ + (application_name, function_name, "main", {"min_containers": 0}) + for application_name, function_name in _both_functions(OLDEST, OLDER) + ] + output = capsys.readouterr().out + assert f"kept: {v2_application_name(NEWEST)}, the v2 default" in output + for application_name, function_name in _both_functions(OLDEST, OLDER): + assert f"lowered: {application_name}.{function_name}" in output + + +DEFAULT_APPLICATION = v2_application_name(PRERELEASE) + + +@pytest.mark.parametrize( + "default_names", + [ + [DEFAULT_APPLICATION], + [DEFAULT_APPLICATION, DEFAULT_APPLICATION], + [DEFAULT_APPLICATION.replace("rc1", "RC1")], + [DEFAULT_APPLICATION, DEFAULT_APPLICATION.replace("rc1", "Rc1")], + ], + ids=["listed-once", "listed-twice", "other-letter-case", "both-letter-cases"], +) +def test_the_default_app_is_never_lowered(default_names): + fake = FakeModal( + store=_manifest_store(versions=(OLDER, PRERELEASE), default=PRERELEASE), + app_list=_app_list( + *(_app(name) for name in default_names), _app(v2_application_name(OLDER)) + ), + ) + + assert _run(fake) == 0 + + assert fake.lowered() == _both_functions(OLDER) + assert not [ + lookup + for lookup in fake.lookups + if lookup[0].casefold() == DEFAULT_APPLICATION.casefold() + ] + + +def test_the_default_is_read_from_the_stored_manifest(): + """An older default, as a deploy of an older version leaves it, is kept.""" + fake = FakeModal( + store=_manifest_store(versions=(OLDER, NEWEST), default=OLDER), + app_list=_app_list( + _app(v2_application_name(NEWEST)), _app(v2_application_name(OLDER)) + ), + ) + + assert _run(fake) == 0 + + assert fake.lowered() == _both_functions(NEWEST) + assert fake.manifests_opened == [(V2_VERSION_MANIFEST_NAME, "main")] + + +def test_a_v2_app_the_manifest_does_not_name_is_lowered(): + """An app whose deploy failed before the manifest named it keeps nothing.""" + fake = FakeModal( + store=_manifest_store(versions=(OLDER,), default=OLDER), + app_list=_app_list( + _app(v2_application_name(OLDER)), _app(v2_application_name(NEWEST)) + ), + ) + + assert _run(fake) == 0 + + assert fake.lowered() == _both_functions(NEWEST) + + +@pytest.mark.parametrize( + "application_name", + [ + "policyengine-simulation-py6-20-4", + "policyengine-simulation-run-sweep", + "policyengine-simulation-runtime-estimates", + "policyengine-simulation-v2-image-smoke", + "policyengine-stage12-cache-precompute", + "policyengine-simulation-executor-smoke", + "policyengine-simulation-v2-py", + "policyengine-simulation-v2-py-6-20-4", + "policyengine-simulation-v2-py6.20.4", + "copy-of-policyengine-simulation-v2-py6-20-4", + "", + ], +) +def test_only_v2_worker_apps_are_touched(application_name): + fake = FakeModal( + store=_manifest_store(versions=(OLDER, NEWEST), default=NEWEST), + app_list=_app_list( + _app(v2_application_name(NEWEST)), + _app(application_name), + _app(v2_application_name(OLDER)), + ), + ) + + assert _run(fake) == 0 + + # The replaced v2 app beside it is still lowered. + assert fake.lowered() == _both_functions(OLDER) + assert {lookup[0] for lookup in fake.lookups} == {v2_application_name(OLDER)} + + +@pytest.mark.parametrize( + "state", + [ + "stopped", + "stopping...", + "ephemeral", + "ephemeral (detached)", + "initializing...", + "disabled", + "unknown", + ], +) +def test_only_deployed_apps_are_lowered(state): + fake = FakeModal( + store=_manifest_store(versions=(NEWEST,), default=NEWEST), + app_list=_app_list( + _app(v2_application_name(NEWEST)), + _app(v2_application_name(OLDER), state=state), + _app(v2_application_name(OLDEST)), + ), + ) + + assert _run(fake) == 0 + + assert fake.lowered() == _both_functions(OLDEST) + + +def test_an_app_listed_as_stopped_and_deployed_is_lowered_once(): + fake = FakeModal( + store=_manifest_store(versions=(NEWEST,), default=NEWEST), + app_list=_app_list( + _app(v2_application_name(NEWEST)), + _app(v2_application_name(OLDER), state="stopped"), + _app(v2_application_name(OLDER)), + _app(v2_application_name(OLDER)), + ), + ) + + assert _run(fake) == 0 + + assert fake.lowered() == _both_functions(OLDER) + + +@pytest.mark.parametrize("environment", ["main", "staging"]) +def test_the_run_reads_and_changes_only_its_own_modal_environment(environment): + fake = FakeModal( + store=_manifest_store(versions=(OLDER, NEWEST), default=NEWEST), + app_list=_app_list( + _app(v2_application_name(NEWEST)), _app(v2_application_name(OLDER)) + ), + ) + + assert _run(fake, environment=environment) == 0 + + assert fake.manifests_opened == [(V2_VERSION_MANIFEST_NAME, environment)] + assert fake.app_lists == [environment] + assert {lookup[2] for lookup in fake.lookups} == {environment} + assert {update[2] for update in fake.updates} == {environment} + + +def test_with_no_replaced_app_nothing_changes(capsys): + fake = FakeModal( + store=_manifest_store(versions=(NEWEST,), default=NEWEST), + app_list=_app_list(_app(v2_application_name(NEWEST))), + ) + + assert _run(fake) == 0 + + assert fake.lookups == [] + assert "no replaced v2 app is deployed" in capsys.readouterr().out + + +@pytest.mark.parametrize("where", ["lookup", "update"]) +def test_an_app_without_household_functions_is_skipped(where, capsys): + """Apps deployed before the household functions existed have none to lower.""" + oldest_functions = frozenset(_both_functions(OLDEST)) + fake = FakeModal( + store=_manifest_store(versions=(OLDEST, OLDER, NEWEST), default=NEWEST), + app_list=_app_list( + _app(v2_application_name(NEWEST)), + _app(v2_application_name(OLDER)), + _app(v2_application_name(OLDEST)), + ), + missing=oldest_functions if where == "update" else frozenset(), + missing_at_lookup=oldest_functions if where == "lookup" else frozenset(), + ) + + assert _run(fake) == 0 + + assert fake.lowered() == _both_functions(OLDER) + output = capsys.readouterr().out + for application_name, function_name in _both_functions(OLDEST): + assert f"no such function: {application_name}.{function_name}" in output + + +def test_a_failed_update_fails_the_run_after_every_other_function_is_tried(capsys): + failed = (v2_application_name(OLDEST), "calculate_household_us") + fake = FakeModal( + store=_manifest_store(versions=(OLDEST, OLDER, NEWEST), default=NEWEST), + app_list=_app_list( + _app(v2_application_name(NEWEST)), + _app(v2_application_name(OLDER)), + _app(v2_application_name(OLDEST)), + ), + failing=frozenset({failed}), + ) + + assert _run(fake) == 1 + + # Every other function is still lowered. + assert fake.lowered() == [ + function for function in _both_functions(OLDEST, OLDER) if function != failed + ] + output = capsys.readouterr().out + assert ( + f"failed: {failed[0]}.{failed[1]}: " + "RuntimeError: the autoscaler update was refused" + ) in output + assert ( + f"1 household function still keeps its containers: {failed[0]}.{failed[1]}" + ) in output + + +@pytest.mark.parametrize( + "store", + [ + None, + {}, + {"active-schema-2-with-local-area-reports": {"schema_version": "not one"}}, + ], + ids=["unreadable", "never-published", "invalid"], +) +def test_without_a_valid_manifest_nothing_is_listed_or_lowered(store): + fake = FakeModal( + store=store, + app_list=_app_list( + _app(v2_application_name(NEWEST)), _app(v2_application_name(OLDER)) + ), + ) + + with pytest.raises(lowering.HouseholdContainerLoweringError): + _run(fake) + + assert fake.app_lists == [] + assert fake.lookups == [] + + +@pytest.mark.parametrize( + "app_list", + [ + "", + "Apps in environment 'main'", + json.dumps({"description": "policyengine-simulation-v2-py6-20-4"}), + json.dumps([["policyengine-simulation-v2-py6-20-4", "deployed"]]), + json.dumps([{"state": "deployed"}]), + json.dumps([{"description": "policyengine-simulation-v2-py6-20-4"}]), + json.dumps([{"description": None, "state": "deployed"}]), + ], + ids=[ + "empty", + "not-json", + "not-a-list", + "entry-not-an-object", + "no-name", + "no-state", + "name-not-text", + ], +) +def test_an_unreadable_app_list_lowers_nothing(app_list): + fake = FakeModal( + store=_manifest_store(versions=(OLDER, NEWEST), default=NEWEST), + app_list=app_list, + ) + + with pytest.raises(lowering.HouseholdContainerLoweringError): + _run(fake) + + assert fake.lookups == [] + + +@pytest.mark.parametrize( + "manifest_name", ["", "simulation-api-routing-state"], ids=["empty", "v1"] +) +def test_the_v1_routing_state_is_never_read_as_the_manifest(manifest_name): + fake = FakeModal( + store=_manifest_store(versions=(NEWEST,), default=NEWEST), + app_list=_app_list(_app(v2_application_name(NEWEST))), + ) + + with pytest.raises(ValueError, match="manifest"): + _run(fake, manifest_name=manifest_name) + + assert fake.manifests_opened == [] + assert fake.lookups == [] + + +class FakeCompletedProcess: + def __init__(self, returncode: int, stdout: str = "", stderr: str = "") -> None: + self.returncode = returncode + self.stdout = stdout + self.stderr = stderr + + +def test_the_app_list_comes_from_modal_app_list_as_json(monkeypatch): + monkeypatch.setenv("FORCE_COLOR", "1") + monkeypatch.setenv("TTY_COMPATIBLE", "1") + monkeypatch.setenv("MODAL_TOKEN_ID", "token-id") + calls: list[tuple[list[str], dict[str, object]]] = [] + + def run(command: list[str], **options: object) -> FakeCompletedProcess: + calls.append((command, options)) + return FakeCompletedProcess(0, stdout="[]\n") + + assert lowering.list_applications("staging", run=run) == "[]\n" + + ((command, options),) = calls + # The Modal client this interpreter runs, so the same release as the + # autoscaler updates. + # Isolated (-I), so neither the working directory nor PYTHONPATH can put + # this project's src/modal in place of the Modal client. + assert command == [ + sys.executable, + "-I", + "-m", + "modal", + "app", + "list", + "--env", + "staging", + "--json", + ] + assert options["capture_output"] is True + assert options["text"] is True + assert options["check"] is False + # Plain JSON, without colour codes, whatever the runner's settings; the + # Modal credentials still reach the command. + environment = options["env"] + assert isinstance(environment, dict) + assert environment["NO_COLOR"] == "1" + assert "FORCE_COLOR" not in environment + assert "TTY_COMPATIBLE" not in environment + assert environment["MODAL_TOKEN_ID"] == "token-id" + + +def test_a_failed_modal_app_list_is_an_error(): + def run(command: list[str], **options: object) -> FakeCompletedProcess: + return FakeCompletedProcess(1, stdout="", stderr="Token missing\n") + + with pytest.raises( + lowering.HouseholdContainerLoweringError, + match=r"modal app list exited with status 1: Token missing", + ): + lowering.list_applications("main", run=run) + + +def test_the_real_app_list_command_is_runnable(): + """``python -I -m modal`` runs this environment's Modal client.""" + completed = subprocess.run( + [sys.executable, "-I", "-m", "modal", "app", "list", "--help"], + capture_output=True, + text=True, + check=False, + ) + + assert completed.returncode == 0, completed.stderr + assert "--json" in completed.stdout + assert "--env" in completed.stdout + + +def test_modal_functions_are_looked_up_in_the_given_environment(monkeypatch): + looked_up: list[tuple[tuple[object, ...], dict[str, object]]] = [] + + def from_name(*args: object, **kwargs: object) -> str: + looked_up.append((args, kwargs)) + return "function" + + monkeypatch.setattr(lowering.modal.Function, "from_name", from_name) + + assert ( + lowering.modal_function( + "policyengine-simulation-v2-py6-20-4", "calculate_household_us", "main" + ) + == "function" + ) + assert looked_up == [ + ( + ("policyengine-simulation-v2-py6-20-4", "calculate_household_us"), + {"environment_name": "main"}, + ) + ] + + +def test_the_manifest_is_opened_without_creating_it(monkeypatch): + opened: list[tuple[tuple[object, ...], dict[str, object]]] = [] + + def from_name(*args: object, **kwargs: object) -> dict[str, object]: + opened.append((args, kwargs)) + return {} + + monkeypatch.setattr(lowering.modal.Dict, "from_name", from_name) + + assert lowering.open_manifest(V2_VERSION_MANIFEST_NAME, "main") == {} + assert opened == [ + ( + (V2_VERSION_MANIFEST_NAME,), + {"environment_name": "main", "create_if_missing": False}, + ) + ] + + +def test_main_runs_with_the_arguments_the_workflow_passes(): + fake = FakeModal( + store=_manifest_store(versions=(OLDER, NEWEST), default=NEWEST), + app_list=_app_list( + _app(v2_application_name(NEWEST)), _app(v2_application_name(OLDER)) + ), + ) + + result = lowering.main( + ["--environment", "main", "--manifest-name", V2_VERSION_MANIFEST_NAME], + open_manifest=fake.open_manifest, + list_apps=fake.list_apps, + lookup=fake.lookup, + ) + + assert result == 0 + assert fake.lowered() == _both_functions(OLDER) + + +@pytest.mark.parametrize( + "arguments", + [ + [], + ["--environment", "main"], + ["--manifest-name", V2_VERSION_MANIFEST_NAME], + ["--environment", "", "--manifest-name", V2_VERSION_MANIFEST_NAME], + ["--environment", " ", "--manifest-name", V2_VERSION_MANIFEST_NAME], + ], + ids=[ + "nothing", + "no-manifest-name", + "no-environment", + "empty-environment", + "blank-environment", + ], +) +def test_main_refuses_a_missing_environment_or_manifest_name(arguments): + fake = FakeModal(store=None, app_list="[]") + + with pytest.raises(SystemExit) as exited: + lowering.main( + arguments, + open_manifest=fake.open_manifest, + list_apps=fake.list_apps, + lookup=fake.lookup, + ) + + assert exited.value.code == 2 + assert fake.manifests_opened == [] diff --git a/projects/policyengine-simulation-executor/tests/test_v2_household_scaling.py b/projects/policyengine-simulation-executor/tests/test_v2_household_scaling.py new file mode 100644 index 000000000..656d3e853 --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_v2_household_scaling.py @@ -0,0 +1,174 @@ +"""Tests for the containers each v2 household function keeps running. + +The deploy passes each environment's minimum container count and idle +window to ``modal deploy`` of ``src/modal/v2_app.py`` as environment +variables: production keeps one container per country running, with +extra containers stopped after ten idle minutes; staging keeps none, with +Modal's 60 seconds. Without them, as inside a Modal container, the +household functions keep none and use Modal's idle window. +""" + +from __future__ import annotations + +import importlib +import sys + +import pytest +from fixtures.fake_modal import install_fake_modal +from src.modal import v2_household_scaling as scaling + +MIN_CONTAINERS = "HOUSEHOLD_FUNCTION_MIN_CONTAINERS" +SCALEDOWN_WINDOW = "HOUSEHOLD_FUNCTION_SCALEDOWN_WINDOW_SECONDS" +HOUSEHOLD_FUNCTIONS = ("calculate_household_us", "calculate_household_uk") +OTHER_FUNCTIONS = ("validate_worker_us", "validate_worker_uk", "coordinate_report") + + +def _scaling(**environment: str) -> dict[str, int]: + return scaling.household_function_scaling(environment, max_containers=20) + + +def test_the_variable_names_are_the_ones_the_deploy_sets(): + assert scaling.MIN_CONTAINERS_VARIABLE == MIN_CONTAINERS + assert scaling.SCALEDOWN_WINDOW_VARIABLE == SCALEDOWN_WINDOW + + +@pytest.mark.parametrize( + "environment", + [{}, {MIN_CONTAINERS: "", SCALEDOWN_WINDOW: ""}], + ids=["unset", "empty"], +) +def test_without_settings_no_container_is_kept(environment): + assert scaling.household_function_scaling(environment, max_containers=20) == { + "min_containers": 0 + } + + +def test_production_keeps_one_container_and_a_ten_minute_window(): + assert _scaling(**{MIN_CONTAINERS: "1", SCALEDOWN_WINDOW: "600"}) == { + "min_containers": 1, + "scaledown_window": 600, + } + + +def test_staging_keeps_no_container_and_modals_sixty_seconds(): + assert _scaling(**{MIN_CONTAINERS: "0", SCALEDOWN_WINDOW: "60"}) == { + "min_containers": 0, + "scaledown_window": 60, + } + + +@pytest.mark.parametrize( + ("minimum", "window", "expected"), + [ + ("20", "2", {"min_containers": 20, "scaledown_window": 2}), + ("0", "3600", {"min_containers": 0, "scaledown_window": 3600}), + ], + ids=["most-containers-shortest-window", "longest-window"], +) +def test_the_limits_are_inclusive(minimum, window, expected): + assert _scaling(**{MIN_CONTAINERS: minimum, SCALEDOWN_WINDOW: window}) == expected + + +@pytest.mark.parametrize( + "minimum", + ["-1", "1.5", "one", " 1", "1 ", "+1", "0x1", "٢", "21", "1000"], +) +def test_an_invalid_minimum_stops_the_deploy(minimum): + with pytest.raises(ValueError, match=MIN_CONTAINERS): + _scaling(**{MIN_CONTAINERS: minimum}) + + +@pytest.mark.parametrize( + "window", ["0", "1", "3601", "-60", "600s", "ten", "60.0", " 600", "٦٠٠"] +) +def test_an_invalid_idle_window_stops_the_deploy(window): + with pytest.raises(ValueError, match=SCALEDOWN_WINDOW): + _scaling(**{MIN_CONTAINERS: "1", SCALEDOWN_WINDOW: window}) + + +def test_the_minimum_may_not_exceed_the_functions_container_limit(): + with pytest.raises(ValueError, match="at most 3"): + scaling.household_function_scaling({MIN_CONTAINERS: "4"}, max_containers=3) + + assert scaling.household_function_scaling( + {MIN_CONTAINERS: "3"}, max_containers=3 + ) == {"min_containers": 3} + + +def _load_v2_app(monkeypatch): + install_fake_modal(monkeypatch) + sys.modules.pop("src.modal.v2_images", None) + sys.modules.pop("src.modal.v2_app", None) + return importlib.import_module("src.modal.v2_app") + + +@pytest.fixture +def without_household_settings(monkeypatch): + monkeypatch.delenv(MIN_CONTAINERS, raising=False) + monkeypatch.delenv(SCALEDOWN_WINDOW, raising=False) + yield + # Later tests import the module without these settings. + sys.modules.pop("src.modal.v2_app", None) + + +def test_a_production_deploy_keeps_a_household_container_for_each_country( + monkeypatch, without_household_settings +): + monkeypatch.setenv(MIN_CONTAINERS, "1") + monkeypatch.setenv(SCALEDOWN_WINDOW, "600") + + module = _load_v2_app(monkeypatch) + functions = dict(module.app.function_calls) + + for function_name in HOUSEHOLD_FUNCTIONS: + assert functions[function_name].get("min_containers") == 1 + assert functions[function_name].get("scaledown_window") == 600 + # Unchanged: extra containers still stop at 20. + assert functions[function_name]["max_containers"] == 20 + assert getattr(module, "HOUSEHOLD_FUNCTION_SCALING", None) == { + "min_containers": 1, + "scaledown_window": 600, + } + + +def test_the_settings_apply_only_to_the_household_functions( + monkeypatch, without_household_settings +): + monkeypatch.setenv(MIN_CONTAINERS, "1") + monkeypatch.setenv(SCALEDOWN_WINDOW, "600") + + module = _load_v2_app(monkeypatch) + functions = dict(module.app.function_calls) + + for function_name in OTHER_FUNCTIONS: + assert "min_containers" not in functions[function_name] + assert "scaledown_window" not in functions[function_name] + for _class_name, options in module.app.cls_calls: + assert "min_containers" not in options + assert "scaledown_window" not in options + + +def test_without_the_settings_the_household_functions_keep_no_container( + monkeypatch, without_household_settings +): + """As in a Modal container, or a deploy that sets neither.""" + module = _load_v2_app(monkeypatch) + functions = dict(module.app.function_calls) + + for function_name in HOUSEHOLD_FUNCTIONS: + assert functions[function_name].get("min_containers") == 0 + assert "scaledown_window" not in functions[function_name] + + +@pytest.mark.parametrize( + ("variable", "value"), + [(MIN_CONTAINERS, "one"), (MIN_CONTAINERS, "21"), (SCALEDOWN_WINDOW, "1")], +) +def test_an_invalid_setting_stops_the_v2_app_deploy( + monkeypatch, without_household_settings, variable, value +): + monkeypatch.setenv(MIN_CONTAINERS, "1") + monkeypatch.setenv(variable, value) + + with pytest.raises(ValueError, match=variable): + _load_v2_app(monkeypatch) From 6e5932bdf7de20d84b45eb874871d755a6618c30 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:08:09 +0400 Subject: [PATCH 2/6] Keep a household container per country running in production Each caller of the reusable deploy now sets the API v2 household functions' minimum container count and idle window for its environment: one container and 600 seconds in production, none and Modal's 60 seconds in staging. The v2 app reads them from the environment when it is deployed (src/modal/v2_household_scaling.py), and an invalid value stops the deploy. Every .py version's v2 app stays deployed, and the simulation service calls only the default worker's household functions. So after the Stage 12 v2 default moves, the new job lower_replaced_household_containers runs src/modal/utils/lower_replaced_household_containers.py, which sets the minimum to 0 on the household functions of every other deployed v2 app in the Modal environment. It is its own job, so a failure there never puts the previous default back. Registers the tests under the new rule sim.deploy.household-containers-follow-the-default, documents the job in the executor README and the entry's DEPLOYMENT.md, and adds a changelog fragment. Co-Authored-By: Claude Opus 5.5 --- .../workflows/simulation-deploy.reusable.yml | 59 +++ .github/workflows/simulation-deploy.yml | 9 + .github/workflows/stage12-deploy.yml | 9 + AGENTS.md | 2 +- .../v2-household-containers.changed.md | 1 + docs/generated/rules.md | 39 +- .../DEPLOYMENT.md | 10 + .../README.md | 52 +++ .../lower_replaced_household_containers.py | 339 ++++++++++++++++-- .../src/modal/v2_app.py | 9 + .../src/modal/v2_household_scaling.py | 74 +++- rules/registry.toml | 62 ++++ 12 files changed, 624 insertions(+), 41 deletions(-) create mode 100644 changelog.d/v2-household-containers.changed.md diff --git a/.github/workflows/simulation-deploy.reusable.yml b/.github/workflows/simulation-deploy.reusable.yml index 900b2cb0a..de30ed8d9 100644 --- a/.github/workflows/simulation-deploy.reusable.yml +++ b/.github/workflows/simulation-deploy.reusable.yml @@ -29,6 +29,14 @@ on: entrypoint_max_instances: required: true type: number + household_function_min_containers: + required: true + type: number + description: "Containers each v2 household function keeps running" + household_function_scaledown_window_seconds: + required: true + type: number + description: "Seconds an extra v2 household container stays idle before Modal stops it" promote_entrypoint: required: true type: boolean @@ -645,6 +653,11 @@ jobs: OBSERVABILITY_GOOGLE_SERVICE_ACCOUNT_EMAIL: ${{ vars.OBSERVABILITY_GOOGLE_SERVICE_ACCOUNT_EMAIL }} OTEL_EXPORTER_OTLP_ENDPOINT: ${{ vars.OBSERVABILITY_OTLP_ENDPOINT }} POLICYENGINE_OTEL_GOOGLE_AUDIENCE: ${{ vars.OBSERVABILITY_OTLP_GOOGLE_AUDIENCE }} + # The containers each household function keeps running, and how + # long extra ones stay idle, read when the app is deployed + # (src/modal/v2_household_scaling.py). + HOUSEHOLD_FUNCTION_MIN_CONTAINERS: ${{ inputs.household_function_min_containers }} + HOUSEHOLD_FUNCTION_SCALEDOWN_WINDOW_SECONDS: ${{ inputs.household_function_scaledown_window_seconds }} run: uv run --frozen modal deploy --env="${{ inputs.modal_environment }}" src/modal/v2_app.py - name: Validate installed bundles, secrets, datasets, and calculations @@ -1236,6 +1249,52 @@ jobs: MODAL_ENVIRONMENT: ${{ inputs.modal_environment }} run: ../../.github/scripts/stage12-v2-default-restore.sh + lower_replaced_household_containers: + name: Stop keeping household containers in replaced v2 apps + # Each .py version's v2 app stays deployed, and a deploy gives its + # household functions the environment's minimum container count, one in + # production. The simulation service calls only the v2 default's, so once + # the default has moved, this sets the minimum to 0 on every other + # deployed v2 app's household functions. Its own job, after the default + # job succeeded, so a failed run puts back no Stage 12 default. A failure + # fails this workflow call, so in the beta deployment it skips the + # production deployment, as a failed runtime estimates deploy does. + if: >- + ${{ + !cancelled() && + inputs.deploy_stage12_v2 && + needs.publish_stage12_v2_default.result == 'success' + }} + needs: [publish_stage12_v2_default] + runs-on: ubuntu-latest + defaults: + run: + shell: bash + environment: ${{ inputs.release_environment }} + steps: + - uses: actions/checkout@v6 + + - uses: actions/setup-python@v6 + with: + python-version: "3.13" + + - uses: astral-sh/setup-uv@v8.1.0 + with: + version: "0.13.6" + + - name: Install the household container script's dependencies + working-directory: projects/policyengine-simulation-executor + run: uv sync --frozen + + # Reads the default from the environment's v2 manifest and lists the + # environment's apps with modal app list; only Modal's tokens. + - name: Stop keeping household containers in replaced v2 apps + working-directory: projects/policyengine-simulation-executor + env: + MODAL_TOKEN_ID: ${{ secrets.MODAL_TOKEN_ID }} + MODAL_TOKEN_SECRET: ${{ secrets.MODAL_TOKEN_SECRET }} + run: uv run --frozen python -m src.modal.utils.lower_replaced_household_containers --environment "${{ inputs.modal_environment }}" --manifest-name simulation-api-v2-version-manifest + deploy_runtime_estimates: name: Deploy the scheduled runtime estimates app after every check # An unversioned app, one per Modal environment, whose daily schedule diff --git a/.github/workflows/simulation-deploy.yml b/.github/workflows/simulation-deploy.yml index a4f33808f..e8d55f57f 100644 --- a/.github/workflows/simulation-deploy.yml +++ b/.github/workflows/simulation-deploy.yml @@ -99,6 +99,10 @@ jobs: entrypoint_revision_prefix: s- entrypoint_min_instances: 0 entrypoint_max_instances: 2 + # Staging keeps no household container running, with Modal's + # 60-second idle window. + household_function_min_containers: 0 + household_function_scaledown_window_seconds: 60 # Staging's stable URL must serve the revision this deployment tested, # because staging callers such as the Public API's staging service use # that URL. Only a run from main promotes: a manual run from another @@ -127,6 +131,11 @@ jobs: entrypoint_revision_prefix: p- entrypoint_min_instances: 1 entrypoint_max_instances: 20 + # One household container per country stays running, so a + # calculation after idle doesn't wait for one to start; extra + # containers stop after ten idle minutes. + household_function_min_containers: 1 + household_function_scaledown_window_seconds: 600 promote_entrypoint: true run_full_integration: false deploy_existing_stack: true diff --git a/.github/workflows/stage12-deploy.yml b/.github/workflows/stage12-deploy.yml index a5b252e3f..62142d7c7 100644 --- a/.github/workflows/stage12-deploy.yml +++ b/.github/workflows/stage12-deploy.yml @@ -53,6 +53,10 @@ jobs: entrypoint_revision_prefix: s- entrypoint_min_instances: 0 entrypoint_max_instances: 2 + # Staging keeps no household container running, with Modal's + # 60-second idle window. + household_function_min_containers: 0 + household_function_scaledown_window_seconds: 60 # Like the main deployment, promote the tested staging revision, and # only from main. Rule: sim.deploy.staging-promotes-tested-revision. promote_entrypoint: ${{ github.ref == 'refs/heads/main' }} @@ -79,6 +83,11 @@ jobs: entrypoint_revision_prefix: p- entrypoint_min_instances: 1 entrypoint_max_instances: 20 + # One household container per country stays running, so a + # calculation after idle doesn't wait for one to start; extra + # containers stop after ten idle minutes. + household_function_min_containers: 1 + household_function_scaledown_window_seconds: 600 promote_entrypoint: true run_full_integration: false deploy_existing_stack: false diff --git a/AGENTS.md b/AGENTS.md index fcf7ad614..27054987a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -140,7 +140,7 @@ To add or change a rule, read `docs/engineering/skills/rules-registry.md`. ### Deployment pipeline -- Checked: `sim.deploy.container-context-minimal`, `sim.deploy.docker-images-build`, `sim.deploy.gcloud-without-terraform`, `sim.deploy.latest-moves-after-checks`, `sim.deploy.modal-image-smoke`, `sim.deploy.numerical-sentinel-gate`, `sim.deploy.permission-enforcement-wired`, `sim.deploy.promotion-order-explicit`, `sim.deploy.release-commit-deploys-once`, `sim.deploy.release-identity-smoke`, `sim.deploy.revision-tags-valid`, `sim.deploy.routing-publication-journaled`, `sim.deploy.shell-scripts-valid`, `sim.deploy.smoke-tests-strict`, `sim.deploy.stage12-default-moves-after-checks`, `sim.deploy.stage12-manifest-read-daily`, `sim.deploy.staging-promotes-tested-revision`, `sim.deploy.traffic-changes-exact`, `sim.deploy.workflow-shell-safety` +- Checked: `sim.deploy.container-context-minimal`, `sim.deploy.docker-images-build`, `sim.deploy.gcloud-without-terraform`, `sim.deploy.household-containers-follow-the-default`, `sim.deploy.latest-moves-after-checks`, `sim.deploy.modal-image-smoke`, `sim.deploy.numerical-sentinel-gate`, `sim.deploy.permission-enforcement-wired`, `sim.deploy.promotion-order-explicit`, `sim.deploy.release-commit-deploys-once`, `sim.deploy.release-identity-smoke`, `sim.deploy.revision-tags-valid`, `sim.deploy.routing-publication-journaled`, `sim.deploy.shell-scripts-valid`, `sim.deploy.smoke-tests-strict`, `sim.deploy.stage12-default-moves-after-checks`, `sim.deploy.stage12-manifest-read-daily`, `sim.deploy.staging-promotes-tested-revision`, `sim.deploy.traffic-changes-exact`, `sim.deploy.workflow-shell-safety` - `sim.deploy.image-smoke-covers-every-image-lib`: The image smoke path filter includes every library mounted into a Modal image, so a change to any of them runs the smoke. (doc-only, not checked: follow it yourself) ### API contracts and integration diff --git a/changelog.d/v2-household-containers.changed.md b/changelog.d/v2-household-containers.changed.md new file mode 100644 index 000000000..7c2200386 --- /dev/null +++ b/changelog.d/v2-household-containers.changed.md @@ -0,0 +1 @@ +In production, the API v2 simulation app's household calculation functions (`calculate_household_us` and `calculate_household_uk`) keep one container running at all times, so a household calculation after a quiet period doesn't wait for a container to start, and extra containers stop after ten idle minutes instead of one; staging keeps none, as before. After each deploy moves the v2 default, a new deploy job sets the minimum to 0 on the household functions of every other deployed v2 app, so only the default's containers keep running (about $92 a month per container at list price). diff --git a/docs/generated/rules.md b/docs/generated/rules.md index 4e43f8679..58aaf5787 100644 --- a/docs/generated/rules.md +++ b/docs/generated/rules.md @@ -8,11 +8,11 @@ Every rule that governs `policyengine-sim-api` is listed here with how it is enf | Tier | enforced | ratcheted | advisory | doc-only | Total | | --- | ---: | ---: | ---: | ---: | ---: | -| mechanical | 66 | 0 | 0 | 14 | 80 | +| mechanical | 67 | 0 | 0 | 14 | 81 | | metric | 1 | 0 | 0 | 0 | 1 | | judgment | 0 | 0 | 0 | 0 | 0 | -**Blocking:** 67 of 81 rules. +**Blocking:** 68 of 82 rules. ## Gaps @@ -43,6 +43,7 @@ Every rule that governs `policyengine-sim-api` is listed here with how it is enf - `sim.contracts.full-integration-beta-only` - `sim.contracts.gateway-openapi-golden` - `sim.deploy.gcloud-without-terraform` +- `sim.deploy.household-containers-follow-the-default` - `sim.deploy.latest-moves-after-checks` - `sim.deploy.numerical-sentinel-gate` - `sim.deploy.permission-enforcement-wired` @@ -173,6 +174,7 @@ flowchart LR | `sim.deploy.container-context-minimal` | Container builds exclude local environments and unrelated projects but include every local library the entrypoint installs, and the entrypoint container builds for the requested target platform. | mechanical | enforced | yes | pytest `projects/policyengine-simulation-entry/tests/test_deployment_assets_cloud_run.py`, `projects/policyengine-simulation-entry/tests/test_deployment_assets_traffic.py` | `pr.yml:test` | yes | | `sim.deploy.docker-images-build` | The simulation entry and executor Docker images build. | mechanical | enforced | yes | CI job `docker-build` | `pr.yml:docker-build` | — | | `sim.deploy.gcloud-without-terraform` | Deployment uses the gcloud-based workflow, not Terraform. | mechanical | enforced | yes | pytest `projects/policyengine-simulation-entry/tests/test_deployment_assets.py` | `pr.yml:test` | **unproven** | +| `sim.deploy.household-containers-follow-the-default` | Every caller of the reusable deploy sets the minimum container count and idle window of the API v2 household functions for its environment (one container and 600 seconds in production, none and 60 seconds in staging), which the v2 app reads when it is deployed; after the Stage 12 v2 default moves, a job of its own sets the minimum to 0 on the household functions of every other deployed v2 app, so a failure there never puts the previous default back. | mechanical | enforced | yes | pytest `projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py`, `projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py`, `projects/policyengine-simulation-executor/tests/test_v2_household_scaling.py` | `pr.yml:test` | **unproven** | | `sim.deploy.image-smoke-covers-every-image-lib` | The image smoke path filter includes every library mounted into a Modal image, so a change to any of them runs the smoke. | mechanical | doc-only | no | nothing | — | — | | `sim.deploy.latest-moves-after-checks` | A deployment publishes its release's routes before its checks without moving latest (unless no release is latest yet), and moves latest only after every check and the Cloud Run promotion pass, then checks that unpinned requests reach the release and puts latest back if a later step fails; no job that runs after the routes job is upstream of it, so rerunning jobs that failed after it never republishes the routes. | mechanical | enforced | yes | pytest `projects/policyengine-simulation-entry/tests/test_deployment_assets_latest.py` | `pr.yml:test` | **unproven** | | `sim.deploy.modal-image-smoke` | App entrypoints import inside the real Modal images before merge, whenever a library baked into an image changes. | mechanical | enforced | yes | CI job `image-smoke` | `pr-image-smoke.yml:image-smoke` | — | @@ -201,6 +203,8 @@ flowchart LR j_CI_pr_yml_docker_build["CI pr.yml:docker-build"] r_sim_deploy_gcloud_without_terraform("sim.deploy.gcloud-without-terraform (enforced)") e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_py["pytest projects/policyengine-simulation-entry/tests/test_deployment_assets.py"] + r_sim_deploy_household_containers_follow_the_default("sim.deploy.household-containers-follow-the-default (enforced)") + e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_household_containers_py__projects_policyengine_simulation_executor_tests_test_lower_replaced_household_containers_py__projects_policyengine_simulation_executor_tests_test_v2_household_scaling_py["pytest projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py, projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py, projects/policyengine-simulation-executor/tests/test_v2_household_scaling.py"] r_sim_deploy_image_smoke_covers_every_image_lib("sim.deploy.image-smoke-covers-every-image-lib (doc-only)") gap_unenforced>"not enforced"] r_sim_deploy_latest_moves_after_checks("sim.deploy.latest-moves-after-checks (enforced)") @@ -222,22 +226,14 @@ flowchart LR r_sim_deploy_routing_publication_journaled("sim.deploy.routing-publication-journaled (enforced)") e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_release_gates_py__projects_policyengine_simulation_entry_tests_test_deployment_assets_routing_py__projects_policyengine_simulation_entry_tests_test_routing_and_sentinel_scripts_py["pytest projects/policyengine-simulation-entry/tests/test_deployment_assets_release_gates.py, projects/policyengine-simulation-entry/tests/test_deployment_assets_routing.py, projects/policyengine-simulation-entry/tests/test_routing_and_sentinel_scripts.py"] r_sim_deploy_shell_scripts_valid("sim.deploy.shell-scripts-valid (enforced)") - r_sim_deploy_smoke_tests_strict("sim.deploy.smoke-tests-strict (enforced)") - e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_py__projects_policyengine_simulation_entry_tests_test_simulation_database_deployment_py["pytest projects/policyengine-simulation-entry/tests/test_deployment_assets.py, projects/policyengine-simulation-entry/tests/test_simulation_database_deployment.py"] - r_sim_deploy_stage12_default_moves_after_checks("sim.deploy.stage12-default-moves-after-checks (enforced)") - e_pytest_libs_policyengine_simulation_contract_tests_test_stage12_manifest_default_py__projects_policyengine_simulation_entry_tests_test_deployment_assets_stage12_default_py__projects_policyengine_simulation_entry_tests_test_stage12_default_scripts_py__projects_policyengine_simulation_executor_tests_test_update_v2_version_manifest_default_py["pytest libs/policyengine-simulation-contract/tests/test_stage12_manifest_default.py, projects/policyengine-simulation-entry/tests/test_deployment_assets_stage12_default.py, projects/policyengine-simulation-entry/tests/test_stage12_default_scripts.py, projects/policyengine-simulation-executor/tests/test_update_v2_version_manifest_default.py"] - r_sim_deploy_stage12_manifest_read_daily("sim.deploy.stage12-manifest-read-daily (enforced)") - e_pytest_libs_policyengine_simulation_contract_tests_test_stage12_manifest_default_py__projects_policyengine_simulation_entry_tests_test_deployment_assets_stage12_refresh_py__projects_policyengine_simulation_executor_tests_test_update_v2_version_manifest_default_py__projects_policyengine_simulation_executor_tests_test_update_v2_version_manifest_expiry_py["pytest libs/policyengine-simulation-contract/tests/test_stage12_manifest_default.py, projects/policyengine-simulation-entry/tests/test_deployment_assets_stage12_refresh.py, projects/policyengine-simulation-executor/tests/test_update_v2_version_manifest_default.py, projects/policyengine-simulation-executor/tests/test_update_v2_version_manifest_expiry.py"] - r_sim_deploy_staging_promotes_tested_revision("sim.deploy.staging-promotes-tested-revision (enforced)") - r_sim_deploy_traffic_changes_exact("sim.deploy.traffic-changes-exact (enforced)") - e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_traffic_py["pytest projects/policyengine-simulation-entry/tests/test_deployment_assets_traffic.py"] - r_sim_deploy_workflow_shell_safety("sim.deploy.workflow-shell-safety (enforced)") r_sim_deploy_container_context_minimal --> e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_cloud_run_py__projects_policyengine_simulation_entry_tests_test_deployment_assets_traffic_py e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_cloud_run_py__projects_policyengine_simulation_entry_tests_test_deployment_assets_traffic_py --> j_CI_pr_yml_test r_sim_deploy_docker_images_build --> e_CI_job_docker_build e_CI_job_docker_build --> j_CI_pr_yml_docker_build r_sim_deploy_gcloud_without_terraform --> e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_py e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_py --> j_CI_pr_yml_test + r_sim_deploy_household_containers_follow_the_default --> e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_household_containers_py__projects_policyengine_simulation_executor_tests_test_lower_replaced_household_containers_py__projects_policyengine_simulation_executor_tests_test_v2_household_scaling_py + e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_household_containers_py__projects_policyengine_simulation_executor_tests_test_lower_replaced_household_containers_py__projects_policyengine_simulation_executor_tests_test_v2_household_scaling_py --> j_CI_pr_yml_test r_sim_deploy_image_smoke_covers_every_image_lib -.-> gap_unenforced r_sim_deploy_latest_moves_after_checks --> e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_latest_py e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_latest_py --> j_CI_pr_yml_test @@ -257,6 +253,23 @@ flowchart LR r_sim_deploy_routing_publication_journaled --> e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_release_gates_py__projects_policyengine_simulation_entry_tests_test_deployment_assets_routing_py__projects_policyengine_simulation_entry_tests_test_routing_and_sentinel_scripts_py e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_release_gates_py__projects_policyengine_simulation_entry_tests_test_deployment_assets_routing_py__projects_policyengine_simulation_entry_tests_test_routing_and_sentinel_scripts_py --> j_CI_pr_yml_test r_sim_deploy_shell_scripts_valid --> e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_py +``` + +```mermaid +flowchart LR + r_sim_deploy_smoke_tests_strict("sim.deploy.smoke-tests-strict (enforced)") + e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_py__projects_policyengine_simulation_entry_tests_test_simulation_database_deployment_py["pytest projects/policyengine-simulation-entry/tests/test_deployment_assets.py, projects/policyengine-simulation-entry/tests/test_simulation_database_deployment.py"] + j_CI_pr_yml_test["CI pr.yml:test"] + r_sim_deploy_stage12_default_moves_after_checks("sim.deploy.stage12-default-moves-after-checks (enforced)") + e_pytest_libs_policyengine_simulation_contract_tests_test_stage12_manifest_default_py__projects_policyengine_simulation_entry_tests_test_deployment_assets_stage12_default_py__projects_policyengine_simulation_entry_tests_test_stage12_default_scripts_py__projects_policyengine_simulation_executor_tests_test_update_v2_version_manifest_default_py["pytest libs/policyengine-simulation-contract/tests/test_stage12_manifest_default.py, projects/policyengine-simulation-entry/tests/test_deployment_assets_stage12_default.py, projects/policyengine-simulation-entry/tests/test_stage12_default_scripts.py, projects/policyengine-simulation-executor/tests/test_update_v2_version_manifest_default.py"] + r_sim_deploy_stage12_manifest_read_daily("sim.deploy.stage12-manifest-read-daily (enforced)") + e_pytest_libs_policyengine_simulation_contract_tests_test_stage12_manifest_default_py__projects_policyengine_simulation_entry_tests_test_deployment_assets_stage12_refresh_py__projects_policyengine_simulation_executor_tests_test_update_v2_version_manifest_default_py__projects_policyengine_simulation_executor_tests_test_update_v2_version_manifest_expiry_py["pytest libs/policyengine-simulation-contract/tests/test_stage12_manifest_default.py, projects/policyengine-simulation-entry/tests/test_deployment_assets_stage12_refresh.py, projects/policyengine-simulation-executor/tests/test_update_v2_version_manifest_default.py, projects/policyengine-simulation-executor/tests/test_update_v2_version_manifest_expiry.py"] + r_sim_deploy_staging_promotes_tested_revision("sim.deploy.staging-promotes-tested-revision (enforced)") + e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_promotion_py["pytest projects/policyengine-simulation-entry/tests/test_deployment_assets_promotion.py"] + r_sim_deploy_traffic_changes_exact("sim.deploy.traffic-changes-exact (enforced)") + e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_traffic_py["pytest projects/policyengine-simulation-entry/tests/test_deployment_assets_traffic.py"] + r_sim_deploy_workflow_shell_safety("sim.deploy.workflow-shell-safety (enforced)") + e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_cloud_run_py["pytest projects/policyengine-simulation-entry/tests/test_deployment_assets_cloud_run.py"] r_sim_deploy_smoke_tests_strict --> e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_py__projects_policyengine_simulation_entry_tests_test_simulation_database_deployment_py e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_py__projects_policyengine_simulation_entry_tests_test_simulation_database_deployment_py --> j_CI_pr_yml_test r_sim_deploy_stage12_default_moves_after_checks --> e_pytest_libs_policyengine_simulation_contract_tests_test_stage12_manifest_default_py__projects_policyengine_simulation_entry_tests_test_deployment_assets_stage12_default_py__projects_policyengine_simulation_entry_tests_test_stage12_default_scripts_py__projects_policyengine_simulation_executor_tests_test_update_v2_version_manifest_default_py @@ -264,9 +277,11 @@ flowchart LR r_sim_deploy_stage12_manifest_read_daily --> e_pytest_libs_policyengine_simulation_contract_tests_test_stage12_manifest_default_py__projects_policyengine_simulation_entry_tests_test_deployment_assets_stage12_refresh_py__projects_policyengine_simulation_executor_tests_test_update_v2_version_manifest_default_py__projects_policyengine_simulation_executor_tests_test_update_v2_version_manifest_expiry_py e_pytest_libs_policyengine_simulation_contract_tests_test_stage12_manifest_default_py__projects_policyengine_simulation_entry_tests_test_deployment_assets_stage12_refresh_py__projects_policyengine_simulation_executor_tests_test_update_v2_version_manifest_default_py__projects_policyengine_simulation_executor_tests_test_update_v2_version_manifest_expiry_py --> j_CI_pr_yml_test r_sim_deploy_staging_promotes_tested_revision --> e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_promotion_py + e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_promotion_py --> j_CI_pr_yml_test r_sim_deploy_traffic_changes_exact --> e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_traffic_py e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_traffic_py --> j_CI_pr_yml_test r_sim_deploy_workflow_shell_safety --> e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_cloud_run_py + e_pytest_projects_policyengine_simulation_entry_tests_test_deployment_assets_cloud_run_py --> j_CI_pr_yml_test ``` ## API contracts and integration diff --git a/projects/policyengine-simulation-entry/DEPLOYMENT.md b/projects/policyengine-simulation-entry/DEPLOYMENT.md index 620c80858..27c192dff 100644 --- a/projects/policyengine-simulation-entry/DEPLOYMENT.md +++ b/projects/policyengine-simulation-entry/DEPLOYMENT.md @@ -102,6 +102,16 @@ Without the database URL or the Modal environment the routes answer 503 release's household functions serve calculations once `publish_stage12_v2_default` has moved the default to its worker. +In production, each household function keeps one container running, and +stops extra containers after ten idle minutes; staging keeps none, with +Modal's 60 seconds. Each caller of the reusable deploy sets these with the +`household_function_min_containers` and +`household_function_scaledown_window_seconds` inputs. After the default +moves, `lower_replaced_household_containers` sets the minimum to 0 on every +other deployed v2 app's household functions, so only the default's +containers keep running. The executor's README describes the job and the +cases it leaves to the next deployment. + ### The staging household check Every staging deployment runs `staging_household_check` after the v2 diff --git a/projects/policyengine-simulation-executor/README.md b/projects/policyengine-simulation-executor/README.md index 509871840..d3f4d3409 100644 --- a/projects/policyengine-simulation-executor/README.md +++ b/projects/policyengine-simulation-executor/README.md @@ -293,6 +293,58 @@ jobs" finds the default already on the release, writes nothing and succeeds, unless the write stopped part-way: then the rerun's move refuses the keys, and an operator repairs them by hand. +### Household containers + +The v2 app's household functions (`calculate_household_us` and +`calculate_household_uk`) take their minimum container count and idle window +from the deploy, which passes the reusable deploy workflow's +`household_function_min_containers` and +`household_function_scaledown_window_seconds` inputs to `modal deploy` as +`HOUSEHOLD_FUNCTION_MIN_CONTAINERS` and +`HOUSEHOLD_FUNCTION_SCALEDOWN_WINDOW_SECONDS` +(`src/modal/v2_household_scaling.py`). Production keeps one container per +function running, so a household calculation after a quiet period doesn't wait +for a container to start, and stops extra containers after 600 idle seconds; +staging keeps none, with Modal's 60 seconds. Without the variables, the +functions keep none and use Modal's idle window; an invalid value stops the +deploy. At list price, a 2-core, 4 GiB container running all month costs about +$92. + +Every policyengine.py version's v2 app stays deployed, and the simulation +service calls only the default worker's household functions. So after +`publish_stage12_v2_default` succeeds, the job +`lower_replaced_household_containers` runs +`src/modal/utils/lower_replaced_household_containers.py`: it reads the +default from the manifest, lists the Modal environment's apps with +`modal app list --json`, and sets the minimum to 0 (`update_autoscaler`) on +the household functions of every other deployed v2 worker app, including one +whose deploy failed before the manifest named it. It leaves the idle window, +the container limit and every other app as they are. A failed update fails +the job, after every other function has been tried, and so the deployment; +the default stays where it moved. A later `modal deploy` of a lowered app +gives its functions the deploy's minimum again. + +Two cases leave containers running until the next deployment whose default +job succeeds: + +- **A deployment that fails after deploying its v2 app**, before or during + the default move, keeps that app's household containers, because the + lowering runs only after a successful move. +- **A default an operator moves by hand**, with `--restore-plan` or a + publication, leaves the new default's functions at the lowered minimum, 0, + and the app it replaced at the deploy's minimum. To change one function's + minimum until + its app's next deploy, with Modal credentials for the workspace, run + `modal.Function.from_name("", "", + environment_name="").update_autoscaler(min_containers=)` + from Python in `projects/policyengine-simulation-executor`. + +To lower the replaced apps by hand, from +`projects/policyengine-simulation-executor`, run +`uv run --frozen python -m src.modal.utils.lower_replaced_household_containers +--environment --manifest-name +simulation-api-v2-version-manifest`. + ## Baseline artifact pipeline (precompute → store → image fetch) The precompute app fills a content-addressed GCS store for one country diff --git a/projects/policyengine-simulation-executor/src/modal/utils/lower_replaced_household_containers.py b/projects/policyengine-simulation-executor/src/modal/utils/lower_replaced_household_containers.py index d32a97a34..fae6059e1 100644 --- a/projects/policyengine-simulation-executor/src/modal/utils/lower_replaced_household_containers.py +++ b/projects/policyengine-simulation-executor/src/modal/utils/lower_replaced_household_containers.py @@ -1,47 +1,342 @@ """Stop keeping household containers running in replaced v2 apps. -Placeholder: nothing is lowered yet. +The simulation service sends household calculations only to the household +functions of the v2 version manifest's default worker. A deploy of +``src/modal/v2_app.py`` gives each household function its environment's +minimum container count (``src/modal/v2_household_scaling.py``; one in +production), and every .py version's v2 app stays deployed. So once a deploy +has moved the default, the deploy workflow runs this, which sets the minimum +to 0 on the household functions of every other deployed v2 app in the +environment, through Modal's ``update_autoscaler``. A later ``modal deploy`` +of such an app gives its functions the deploy's minimum again. + +- **The app it keeps** is the default worker's, read from the manifest as + stored. No app whose name matches it, ignoring letter case, is changed. +- **The apps it changes** are those ``modal app list --json`` lists as + deployed under a v2 worker app's name (``policyengine-simulation-v2-py`` + and a version), including any whose deploy failed before the manifest + named it. The v1 apps and every other app are left alone. +- **Only the minimum changes**: an app's idle window and container limit + stay as deployed. + +Exit status 0 when every household function of those apps was lowered, or +doesn't exist (an app from before the household functions); 1 when any +update failed, after every other function was tried. When the manifest or +the app list can't be read, it raises before changing anything. """ from __future__ import annotations +import argparse +import json +import os +import re +import subprocess +import sys +from dataclasses import dataclass +from typing import TYPE_CHECKING, Literal, Protocol + import modal +from policyengine_simulation_contract.household_execution import ( + household_callable_name, +) +from policyengine_simulation_contract.stage12_bundle import SUPPORTED_COUNTRIES +from policyengine_simulation_contract.stage12_manifest import ( + V1_ROUTING_STATE_NAME, + V2_APPLICATION_PREFIX, + V2ManifestStore, + assert_separate_manifest_names, + read_v2_manifest, +) + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Sequence -HOUSEHOLD_FUNCTION_NAMES: tuple[str, ...] = () +HOUSEHOLD_FUNCTION_NAMES: tuple[str, ...] = tuple( + household_callable_name(country) for country in SUPPORTED_COUNTRIES +) +# The minimum a replaced app's household functions keep. +REPLACED_MIN_CONTAINERS = 0 +# The state ``modal app list --json`` gives an app that is deployed. +DEPLOYED_STATE = "deployed" +# A v2 worker app's name: the prefix and a version with its dots and plus +# signs turned into hyphens, as v2_application_name makes it. +_V2_WORKER_APPLICATION = re.compile( + re.escape(V2_APPLICATION_PREFIX) + r"[A-Za-z0-9][A-Za-z0-9_-]*" +) +# Settings that would make the Modal client print colour codes into the JSON. +_COLOUR_VARIABLES = ("FORCE_COLOR", "TTY_COMPATIBLE") class HouseholdContainerLoweringError(RuntimeError): - """The manifest or the application list could not be read.""" + """The manifest or the app list could not be opened or read; nothing changed.""" + + +class AutoscaledFunction(Protocol): + """A deployed Modal function whose autoscaler settings can be changed.""" + + def update_autoscaler(self, *, min_containers: int) -> object: + """Change the function's minimum container count until its next deploy.""" + ... + + +class FunctionLookup(Protocol): + """Find a deployed function by app, function and Modal environment.""" + + def __call__( + self, application_name: str, function_name: str, environment: str + ) -> AutoscaledFunction: + """Return the function; Modal raises NotFoundError when it is used.""" + ... + + +@dataclass(frozen=True) +class LoweringOutcome: + """What happened to one household function of one replaced app.""" + + application_name: str + function_name: str + result: Literal["lowered", "no such function", "failed"] + detail: str = "" + + def line(self) -> str: + """Return the outcome as one line of the run's output.""" + line = f"{self.result}: {self.application_name}.{self.function_name}" + return f"{line}: {self.detail}" if self.detail else line + +def default_application_name(store: V2ManifestStore) -> str: + """Return the name of the app the manifest's default worker runs in. -def list_applications(environment: str, *, run: object = None) -> str: - """Return no applications yet.""" - del environment, run - return "" + Raises HouseholdContainerLoweringError when the manifest can't be read, + isn't valid, or hasn't been published. + """ + try: + manifest = read_v2_manifest(store) + except Exception as error: + msg = f"the v2 version manifest could not be read: {error}" + raise HouseholdContainerLoweringError(msg) from error + if manifest is None: + msg = "the v2 version manifest has not been published" + raise HouseholdContainerLoweringError(msg) + return manifest.versions[manifest.default_version].application_name + + +def replaced_v2_applications(app_list: str, *, default_application: str) -> list[str]: + """Return each deployed v2 worker app in ``app_list`` but the default's. + + ``app_list`` is what ``modal app list --json`` prints. The names come + sorted, each once. Raises HouseholdContainerLoweringError when it isn't a + JSON list of objects that each have a text name and state. + """ + try: + entries = json.loads(app_list) + except json.JSONDecodeError as error: + msg = "modal app list did not print JSON" + raise HouseholdContainerLoweringError(msg) from error + if not isinstance(entries, list): + msg = "modal app list did not print a JSON list" + raise HouseholdContainerLoweringError(msg) + replaced: set[str] = set() + for entry in entries: + if not ( + isinstance(entry, dict) + and isinstance(entry.get("description"), str) + and isinstance(entry.get("state"), str) + ): + msg = f"modal app list printed an entry without a name and state: {entry!r}" + raise HouseholdContainerLoweringError(msg) + name = entry["description"] + if ( + entry["state"] == DEPLOYED_STATE + and _V2_WORKER_APPLICATION.fullmatch(name) + and name.casefold() != default_application.casefold() + ): + replaced.add(name) + return sorted(replaced) + + +def lower_household_functions( + applications: Iterable[str], *, environment: str, lookup: FunctionLookup +) -> list[LoweringOutcome]: + """Set the minimum to 0 on each household function of ``applications``. + + Every function is tried, whatever happened to the ones before it. + """ + return [ + _lower(application_name, function_name, environment, lookup) + for application_name in applications + for function_name in HOUSEHOLD_FUNCTION_NAMES + ] + + +def _lower( + application_name: str, function_name: str, environment: str, lookup: FunctionLookup +) -> LoweringOutcome: + try: + lookup(application_name, function_name, environment).update_autoscaler( + min_containers=REPLACED_MIN_CONTAINERS + ) + except modal.exception.NotFoundError: + return LoweringOutcome(application_name, function_name, "no such function") + # Each failure is reported, and the other functions are still lowered. + except Exception as error: # noqa: BLE001 + return LoweringOutcome( + application_name, + function_name, + "failed", + f"{type(error).__name__}: {error}", + ) + return LoweringOutcome(application_name, function_name, "lowered") + + +def list_applications( + environment: str, + *, + run: Callable[..., subprocess.CompletedProcess[str]] = (subprocess.run), +) -> str: + """Return what ``modal app list --json`` prints for ``environment``. + + It runs the Modal client of this interpreter, isolated (``-I``), so + neither the working directory nor PYTHONPATH can put this project's + ``src/modal`` in its place, and without colour codes. Raises + HouseholdContainerLoweringError when the command fails. + """ + command_environment = { + name: value + for name, value in os.environ.items() + if name not in _COLOUR_VARIABLES + } + command_environment["NO_COLOR"] = "1" + completed = run( + [ + sys.executable, + "-I", + "-m", + "modal", + "app", + "list", + "--env", + environment, + "--json", + ], + capture_output=True, + text=True, + check=False, + env=command_environment, + ) + if completed.returncode != 0: + msg = ( + f"modal app list exited with status {completed.returncode}: " + f"{completed.stderr.strip()}" + ) + raise HouseholdContainerLoweringError(msg) + return completed.stdout def modal_function( application_name: str, function_name: str, environment: str -) -> object: - """Look up nothing yet.""" - del application_name, function_name, environment +) -> AutoscaledFunction: + """Return the deployed Modal function, found when it is first used.""" + return modal.Function.from_name( + application_name, function_name, environment_name=environment + ) + + +def open_manifest(manifest_name: str, environment: str) -> V2ManifestStore: + """Return the manifest's Modal Dict, which must already exist.""" + return modal.Dict.from_name( + manifest_name, environment_name=environment, create_if_missing=False + ) + +def lower_replaced_household_containers( # noqa: PLR0913 # each Modal access is passed in for the tests + *, + environment: str, + manifest_name: str, + open_manifest: Callable[[str, str], V2ManifestStore], + list_apps: Callable[[str], str], + lookup: FunctionLookup, + report: Callable[[str], object] = print, +) -> int: + """Lower every replaced v2 app's household functions; return the exit status. -def open_manifest(manifest_name: str, environment: str) -> object: - """Open nothing yet.""" - del manifest_name, environment + Reads the default before listing the apps, and changes nothing unless + both could be read. Raises ValueError for a manifest name that is empty + or names the v1 routing state. + """ + assert_separate_manifest_names(v1_name=V1_ROUTING_STATE_NAME, v2_name=manifest_name) + try: + store = open_manifest(manifest_name, environment) + except Exception as error: + msg = f"the v2 version manifest could not be opened: {error}" + raise HouseholdContainerLoweringError(msg) from error + default_application = default_application_name(store) + applications = replaced_v2_applications( + list_apps(environment), default_application=default_application + ) + report(f"kept: {default_application}, the v2 default") + if not applications: + report("no replaced v2 app is deployed") + return 0 + outcomes = lower_household_functions( + applications, environment=environment, lookup=lookup + ) + for outcome in outcomes: + report(outcome.line()) + failed = [outcome for outcome in outcomes if outcome.result == "failed"] + if not failed: + return 0 + names = ", ".join( + f"{outcome.application_name}.{outcome.function_name}" for outcome in failed + ) + if len(failed) == 1: + report(f"1 household function still keeps its containers: {names}") + else: + report( + f"{len(failed)} household functions still keep their containers: {names}" + ) + return 1 -def lower_replaced_household_containers(**kwargs: object) -> int: - """Lower nothing yet.""" - del kwargs - return 0 +def _argument_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description=( + "Set the minimum container count to 0 on the household functions " + "of every deployed v2 app but the v2 default's." + ) + ) + parser.add_argument( + "--environment", required=True, help="The Modal environment, such as main." + ) + parser.add_argument( + "--manifest-name", + required=True, + help="The v2 version manifest's Modal Dict.", + ) + return parser -def main(argv: list[str] | None = None, **kwargs: object) -> int: - """Lower nothing yet.""" - del argv, kwargs - return 0 +def main( + argv: Sequence[str] | None = None, + *, + open_manifest: Callable[[str, str], V2ManifestStore] = open_manifest, + list_apps: Callable[[str], str] = list_applications, + lookup: FunctionLookup = modal_function, +) -> int: + """Run with the command line's environment and manifest; return the exit status.""" + parser = _argument_parser() + args = parser.parse_args(argv) + if not args.environment.strip(): + parser.error("--environment must name a Modal environment") + return lower_replaced_household_containers( + environment=args.environment, + manifest_name=args.manifest_name, + open_manifest=open_manifest, + list_apps=list_apps, + lookup=lookup, + ) -__all__ = ["modal"] +if __name__ == "__main__": + sys.exit(main()) diff --git a/projects/policyengine-simulation-executor/src/modal/v2_app.py b/projects/policyengine-simulation-executor/src/modal/v2_app.py index 3435af165..422459a16 100644 --- a/projects/policyengine-simulation-executor/src/modal/v2_app.py +++ b/projects/policyengine-simulation-executor/src/modal/v2_app.py @@ -59,6 +59,7 @@ from src.modal.container_calls import ContainerCalls from src.modal.country_model_preload import preload_country_models from src.modal.interrupted_inputs import stop_fetching_inputs_after_interruption +from src.modal.v2_household_scaling import household_function_scaling from src.modal.v2_images import ( BUNDLE_VALUES, RESOLVED_BUNDLE, @@ -578,6 +579,12 @@ def coordinate_report( HOUSEHOLD_FUNCTION_CPU = 2.0 HOUSEHOLD_FUNCTION_MEMORY_MIB = (4096, 16384) HOUSEHOLD_FUNCTION_MAX_CONTAINERS = 20 +# The containers each household function keeps running, and how long extra +# ones stay idle, from the deploy's settings for its environment +# (src/modal/v2_household_scaling.py): one per country in production. +HOUSEHOLD_FUNCTION_SCALING = household_function_scaling( + os.environ, max_containers=HOUSEHOLD_FUNCTION_MAX_CONTAINERS +) def _run_household_calculation( @@ -696,6 +703,7 @@ def calculate() -> HouseholdExecutionResult | HouseholdExecutionFailure: timeout=HOUSEHOLD_FUNCTION_TIMEOUT_SECONDS, retries=0, max_containers=HOUSEHOLD_FUNCTION_MAX_CONTAINERS, + **HOUSEHOLD_FUNCTION_SCALING, secrets=[modal_worker_database_secret], ) def calculate_household_us( @@ -727,6 +735,7 @@ def calculate_household_us( timeout=HOUSEHOLD_FUNCTION_TIMEOUT_SECONDS, retries=0, max_containers=HOUSEHOLD_FUNCTION_MAX_CONTAINERS, + **HOUSEHOLD_FUNCTION_SCALING, secrets=[modal_worker_database_secret], ) def calculate_household_uk( diff --git a/projects/policyengine-simulation-executor/src/modal/v2_household_scaling.py b/projects/policyengine-simulation-executor/src/modal/v2_household_scaling.py index f51324023..33af8ad5d 100644 --- a/projects/policyengine-simulation-executor/src/modal/v2_household_scaling.py +++ b/projects/policyengine-simulation-executor/src/modal/v2_household_scaling.py @@ -1,22 +1,84 @@ """How many containers each v2 household function keeps running. -Placeholder: the deploy's settings are not read yet. +The deploy passes its environment's values to ``modal deploy`` of +``src/modal/v2_app.py`` as two environment variables, from the reusable +deploy workflow's ``household_function_min_containers`` and +``household_function_scaledown_window_seconds`` inputs: production keeps one +container per country running, so a calculation after idle doesn't wait for +one to start, and stops extra containers after ten idle minutes; staging +keeps none, with Modal's 60 seconds. The app gives both household functions +these settings when it is deployed. + +Without the variables, as inside a Modal container or in a deploy that sets +neither, the functions keep no container and use Modal's idle window. An +invalid value raises ValueError, so the deploy stops. + +Every .py version's v2 app stays deployed, so once the v2 default has moved, +``src/modal/utils/lower_replaced_household_containers.py`` sets the minimum to +0 on every other app's household functions. """ from __future__ import annotations -from typing import TYPE_CHECKING +import re +from typing import TYPE_CHECKING, NotRequired, TypedDict if TYPE_CHECKING: from collections.abc import Mapping MIN_CONTAINERS_VARIABLE = "HOUSEHOLD_FUNCTION_MIN_CONTAINERS" SCALEDOWN_WINDOW_VARIABLE = "HOUSEHOLD_FUNCTION_SCALEDOWN_WINDOW_SECONDS" +# The idle windows Modal accepts, in seconds. +SCALEDOWN_WINDOW_RANGE = (2, 3600) +_WHOLE_NUMBER = re.compile(r"[0-9]+") + + +class HouseholdFunctionScaling(TypedDict): + """The keyword arguments the household functions' declarations add.""" + + min_containers: int + scaledown_window: NotRequired[int] + + +def _whole_number(variable: str, value: str) -> int: + """Return ``value`` as a whole number, or raise ValueError naming ``variable``.""" + # Only ASCII digits: int() would also accept signs, spaces, underscores + # and other scripts' digits. + if not _WHOLE_NUMBER.fullmatch(value): + msg = f"{variable} must be a whole number of 0 or more, not {value!r}" + raise ValueError(msg) + return int(value) def household_function_scaling( environ: Mapping[str, str], *, max_containers: int -) -> dict[str, int]: - """Return no settings yet.""" - del environ, max_containers - return {} +) -> HouseholdFunctionScaling: + """Return the household functions' Modal autoscaler settings from ``environ``. + + ``min_containers`` is always present, 0 when its variable is unset or + empty; ``scaledown_window`` only when its variable is set. Raises + ValueError for a minimum that is not a whole number from 0 to + ``max_containers``, or an idle window outside Modal's 2 to 3600 seconds. + """ + settings: HouseholdFunctionScaling = {"min_containers": 0} + minimum = environ.get(MIN_CONTAINERS_VARIABLE, "") + if minimum: + settings["min_containers"] = _whole_number(MIN_CONTAINERS_VARIABLE, minimum) + if settings["min_containers"] > max_containers: + msg = ( + f"{MIN_CONTAINERS_VARIABLE} must be at most {max_containers}, " + "the household functions' container limit" + ) + raise ValueError(msg) + window = environ.get(SCALEDOWN_WINDOW_VARIABLE, "") + if window: + seconds = _whole_number(SCALEDOWN_WINDOW_VARIABLE, window) + shortest, longest = SCALEDOWN_WINDOW_RANGE + if not shortest <= seconds <= longest: + msg = ( + f"{SCALEDOWN_WINDOW_VARIABLE} must be from {shortest} to " + f"{longest} seconds, not {seconds}" + ) + raise ValueError(msg) + settings["scaledown_window"] = seconds + return settings diff --git a/rules/registry.toml b/rules/registry.toml index 27c5beb7b..7ee0e9327 100644 --- a/rules/registry.toml +++ b/rules/registry.toml @@ -806,6 +806,68 @@ workflow = ".github/workflows/pr.yml" job = "test" invocation = "uv run --frozen pytest tests/" +[[rule]] +id = "sim.deploy.household-containers-follow-the-default" +category = "deployment" +statement = "Every caller of the reusable deploy sets the minimum container count and idle window of the API v2 household functions for its environment (one container and 600 seconds in production, none and 60 seconds in staging), which the v2 app reads when it is deployed; after the Stage 12 v2 default moves, a job of its own sets the minimum to 0 on the household functions of every other deployed v2 app, so a failure there never puts the previous default back." +rationale = "projects/policyengine-simulation-executor/README.md#household-containers" +scope = [".github/workflows/simulation-deploy.reusable.yml", ".github/workflows/simulation-deploy.yml", ".github/workflows/stage12-deploy.yml", "projects/policyengine-simulation-executor/src/modal/v2_household_scaling.py", "projects/policyengine-simulation-executor/src/modal/utils/lower_replaced_household_containers.py"] +tier = "mechanical" +status = "enforced" +autofix = false +[rule.enforcer] +kind = "pytest" +nodes = [ + "projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py::test_the_reusable_deploy_requires_both_household_settings", + "projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py::test_each_deploy_sets_its_environments_household_settings", + "projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py::test_every_call_of_the_reusable_deploy_is_covered", + "projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py::test_the_v2_deploy_passes_the_settings_to_modal_deploy", + "projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py::test_the_settings_reach_no_other_step", + "projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py::test_the_lowering_job_waits_for_the_default_move", + "projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py::test_the_lowering_job_runs_only_after_a_successful_default_move", + "projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py::test_the_lowering_step_runs_the_script_in_the_deploys_modal_environment", + "projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py::test_the_lowering_job_installs_the_executors_locked_dependencies_first", + "projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py::test_only_the_lowering_job_runs_the_script", + "projects/policyengine-simulation-executor/tests/test_v2_household_scaling.py::test_the_variable_names_are_the_ones_the_deploy_sets", + "projects/policyengine-simulation-executor/tests/test_v2_household_scaling.py::test_without_settings_no_container_is_kept", + "projects/policyengine-simulation-executor/tests/test_v2_household_scaling.py::test_production_keeps_one_container_and_a_ten_minute_window", + "projects/policyengine-simulation-executor/tests/test_v2_household_scaling.py::test_staging_keeps_no_container_and_modals_sixty_seconds", + "projects/policyengine-simulation-executor/tests/test_v2_household_scaling.py::test_the_limits_are_inclusive", + "projects/policyengine-simulation-executor/tests/test_v2_household_scaling.py::test_an_invalid_minimum_stops_the_deploy", + "projects/policyengine-simulation-executor/tests/test_v2_household_scaling.py::test_an_invalid_idle_window_stops_the_deploy", + "projects/policyengine-simulation-executor/tests/test_v2_household_scaling.py::test_the_minimum_may_not_exceed_the_functions_container_limit", + "projects/policyengine-simulation-executor/tests/test_v2_household_scaling.py::test_a_production_deploy_keeps_a_household_container_for_each_country", + "projects/policyengine-simulation-executor/tests/test_v2_household_scaling.py::test_the_settings_apply_only_to_the_household_functions", + "projects/policyengine-simulation-executor/tests/test_v2_household_scaling.py::test_without_the_settings_the_household_functions_keep_no_container", + "projects/policyengine-simulation-executor/tests/test_v2_household_scaling.py::test_an_invalid_setting_stops_the_v2_app_deploy", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_the_household_functions_are_both_countries", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_every_replaced_v2_app_stops_keeping_household_containers", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_the_default_app_is_never_lowered", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_the_default_is_read_from_the_stored_manifest", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_a_v2_app_the_manifest_does_not_name_is_lowered", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_only_v2_worker_apps_are_touched", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_only_deployed_apps_are_lowered", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_an_app_listed_as_stopped_and_deployed_is_lowered_once", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_the_run_reads_and_changes_only_its_own_modal_environment", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_with_no_replaced_app_nothing_changes", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_an_app_without_household_functions_is_skipped", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_a_failed_update_fails_the_run_after_every_other_function_is_tried", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_without_a_valid_manifest_nothing_is_listed_or_lowered", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_an_unreadable_app_list_lowers_nothing", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_the_v1_routing_state_is_never_read_as_the_manifest", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_the_app_list_comes_from_modal_app_list_as_json", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_a_failed_modal_app_list_is_an_error", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_the_real_app_list_command_is_runnable", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_modal_functions_are_looked_up_in_the_given_environment", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_the_manifest_is_opened_without_creating_it", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_main_runs_with_the_arguments_the_workflow_passes", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_main_refuses_a_missing_environment_or_manifest_name", +] +[[rule.ci]] +workflow = ".github/workflows/pr.yml" +job = "test" +invocation = "uv run --frozen pytest tests/" + [[rule]] id = "sim.deploy.release-commit-deploys-once" category = "deployment" From 64f1ec5ab0cb53b1ac35aa24d5d9235ec5e8702b Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:26:59 +0400 Subject: [PATCH 3/6] Add tests for review round 1's findings that fail before the fixes The household container script must set the v2 default's household functions to the environment's minimum, so a default that an earlier run set to 0 gets its containers back; use Function.autoscaler.update, since the locked Modal client deprecates update_autoscaler; fail a function whose reported minimum isn't the one requested; and refuse to change anything when modal app list doesn't list the default's app as deployed. The workflow passes the deploy's minimum as --default-min-containers. The script takes the new argument as a placeholder, unused, so the tests fail on what it does rather than on its signature. Co-Authored-By: Claude Opus 5.5 --- ..._deployment_assets_household_containers.py | 9 +- .../lower_replaced_household_containers.py | 4 + ...est_lower_replaced_household_containers.py | 299 ++++++++++++++++-- 3 files changed, 280 insertions(+), 32 deletions(-) diff --git a/projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py b/projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py index 789ab694c..21ad81b41 100644 --- a/projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py +++ b/projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py @@ -5,7 +5,8 @@ keeps one container per country, with extra containers stopped after ten idle minutes; staging keeps none, with Modal's 60 seconds. Every .py version's v2 app stays deployed, so once the v2 default has moved, a job of -its own sets the minimum to 0 on every other v2 app's household functions. +its own sets the default's household functions to the environment's minimum +again and every other v2 app's to 0. """ from __future__ import annotations @@ -25,7 +26,7 @@ V2_DEPLOY_STEP = "Deploy the additional versioned v2 Modal application" DEFAULT_JOB = "publish_stage12_v2_default" LOWERING_JOB = "lower_replaced_household_containers" -LOWERING_STEP = "Stop keeping household containers in replaced v2 apps" +LOWERING_STEP = "Keep household containers running only in the v2 default's app" LOWERING_MODULE = "src.modal.utils.lower_replaced_household_containers" EXECUTOR_DIRECTORY = "projects/policyengine-simulation-executor" @@ -176,10 +177,12 @@ def test_the_lowering_step_runs_the_script_in_the_deploys_modal_environment(): job = _lowering_job() step = _step(job, LOWERING_STEP) + # The default's functions get the minimum the deploy gave the v2 app. assert step["run"] == ( f"uv run --frozen python -m {LOWERING_MODULE} " '--environment "${{ inputs.modal_environment }}" ' - "--manifest-name simulation-api-v2-version-manifest" + "--manifest-name simulation-api-v2-version-manifest " + f'--default-min-containers "${{{{ inputs.{MIN_CONTAINERS_INPUT} }}}}"' ) assert step["working-directory"] == EXECUTOR_DIRECTORY # Only Modal's tokens: the script reads the manifest and changes the diff --git a/projects/policyengine-simulation-executor/src/modal/utils/lower_replaced_household_containers.py b/projects/policyengine-simulation-executor/src/modal/utils/lower_replaced_household_containers.py index fae6059e1..b28350622 100644 --- a/projects/policyengine-simulation-executor/src/modal/utils/lower_replaced_household_containers.py +++ b/projects/policyengine-simulation-executor/src/modal/utils/lower_replaced_household_containers.py @@ -254,6 +254,7 @@ def lower_replaced_household_containers( # noqa: PLR0913 # each Modal access i *, environment: str, manifest_name: str, + default_min_containers: int, # noqa: ARG001 # placeholder until the change open_manifest: Callable[[str, str], V2ManifestStore], list_apps: Callable[[str], str], lookup: FunctionLookup, @@ -314,6 +315,8 @@ def _argument_parser() -> argparse.ArgumentParser: required=True, help="The v2 version manifest's Modal Dict.", ) + # Placeholder until the change. + parser.add_argument("--default-min-containers", type=int, required=True) return parser @@ -332,6 +335,7 @@ def main( return lower_replaced_household_containers( environment=args.environment, manifest_name=args.manifest_name, + default_min_containers=args.default_min_containers, open_manifest=open_manifest, list_apps=list_apps, lookup=lookup, diff --git a/projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py b/projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py index 038382758..98c6826cf 100644 --- a/projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py +++ b/projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py @@ -1,12 +1,14 @@ -"""Tests for the script that stops replaced v2 apps' household containers. +"""Tests for the script that keeps household containers only in the v2 default. A production deploy keeps one container running for each household function of the v2 app it deploys, and every .py version's app stays deployed. Once -the deploy has moved the v2 manifest's default, the script sets the minimum -to 0 on the household functions of every other deployed v2 app in the -environment. Each test runs it against a manifest store held in memory, the -JSON ``modal app list --json`` prints, and fake Modal functions that record -each ``update_autoscaler`` call, so no test reaches Modal. +the deploy has moved the v2 manifest's default, the script sets the default's +household functions to the environment's minimum, in case an earlier run set +them to 0, and the minimum to 0 on the household functions of every other +deployed v2 app in the environment. Each test runs it against a manifest +store held in memory, the JSON ``modal app list --json`` prints, and fake +Modal functions that record each ``autoscaler.update`` call, so no test +reaches Modal. """ from __future__ import annotations @@ -165,7 +167,7 @@ def _app_list(*entries: dict[str, object]) -> str: class FakeModal: """The manifest Dict, ``modal app list`` and Modal functions, recording each use.""" - def __init__( + def __init__( # noqa: PLR0913 # one keyword for each Modal answer a test sets self, *, store: dict[str, object] | None, @@ -173,16 +175,22 @@ def __init__( missing: frozenset[tuple[str, str]] = frozenset(), missing_at_lookup: frozenset[tuple[str, str]] = frozenset(), failing: frozenset[tuple[str, str]] = frozenset(), + returned_minimums: dict[tuple[str, str], int | None] | None = None, ) -> None: self.store = store self.app_list = app_list self.missing = missing self.missing_at_lookup = missing_at_lookup self.failing = failing + # The minimum Modal reports after an update, where it isn't the one + # requested. + self.returned_minimums = returned_minimums or {} self.manifests_opened: list[tuple[str, str]] = [] self.app_lists: list[str] = [] self.lookups: list[tuple[str, str, str]] = [] self.updates: list[tuple[str, str, str, dict[str, object]]] = [] + # Each update Modal accepted: the function and the minimum it reported. + self.applied: list[tuple[str, str, int | None]] = [] def open_manifest(self, manifest_name: str, environment: str): self.manifests_opened.append((manifest_name, environment)) @@ -201,26 +209,45 @@ def lookup(self, application_name: str, function_name: str, environment: str): msg = f"Function '{application_name}.{function_name}' not found" raise NotFoundError(msg) - def update_autoscaler(**settings: object) -> None: + def update(**settings: object) -> SimpleNamespace: + """Stand in for ``Function.autoscaler.update``.""" self.updates.append( (application_name, function_name, environment, settings) ) - if (application_name, function_name) in self.missing: + function = (application_name, function_name) + if function in self.missing: msg = f"Function '{application_name}.{function_name}' not found" raise NotFoundError(msg) - if (application_name, function_name) in self.failing: + if function in self.failing: msg = "the autoscaler update was refused" raise RuntimeError(msg) + minimum = self.returned_minimums.get(function, settings["min_containers"]) + self.applied.append((application_name, function_name, minimum)) + # Modal's FunctionAutoscalerSettings after the update. + return SimpleNamespace( + min_containers=minimum, + max_containers=20, + scaledown_window=600, + buffer_containers=None, + ) - return SimpleNamespace(update_autoscaler=update_autoscaler) + # Only the current API: the deprecated update_autoscaler is absent. + return SimpleNamespace(autoscaler=SimpleNamespace(update=update)) def lowered(self) -> list[tuple[str, str]]: - """Return each function whose update set the minimum to 0 and succeeded.""" + """Return each function whose update Modal reports left a minimum of 0.""" return [ (application_name, function_name) - for application_name, function_name, _environment, settings in self.updates - if settings == {"min_containers": 0} - and (application_name, function_name) not in self.missing | self.failing + for application_name, function_name, minimum in self.applied + if not minimum + ] + + def set_on(self, application_name: str) -> list[tuple[str, dict[str, object]]]: + """Return each update requested for ``application_name``'s functions.""" + return [ + (function_name, settings) + for name, function_name, _environment, settings in self.updates + if name == application_name ] @@ -228,6 +255,8 @@ def _run(fake: FakeModal, environment: str = "main", **overrides) -> int: return lowering.lower_replaced_household_containers( environment=environment, manifest_name=overrides.pop("manifest_name", V2_VERSION_MANIFEST_NAME), + # Production's minimum unless a test gives another. + default_min_containers=overrides.pop("default_min_containers", 1), open_manifest=fake.open_manifest, list_apps=fake.list_apps, lookup=fake.lookup, @@ -259,18 +288,65 @@ def test_every_replaced_v2_app_stops_keeping_household_containers(capsys): assert _run(fake) == 0 - # Only the minimum changes, to 0, in the deploy's Modal environment; - # oldest first, so a run's output reads the same each time. + # Only the minimum changes, in the deploy's Modal environment: first the + # default's functions, to the environment's minimum, then each replaced + # app's, to 0, oldest first, so a run's output reads the same each time. assert fake.updates == [ + (application_name, function_name, "main", {"min_containers": 1}) + for application_name, function_name in _both_functions(NEWEST) + ] + [ (application_name, function_name, "main", {"min_containers": 0}) for application_name, function_name in _both_functions(OLDEST, OLDER) ] output = capsys.readouterr().out - assert f"kept: {v2_application_name(NEWEST)}, the v2 default" in output + assert f"the v2 default: {v2_application_name(NEWEST)}" in output + for application_name, function_name in _both_functions(NEWEST): + assert f"set: {application_name}.{function_name}: minimum 1" in output for application_name, function_name in _both_functions(OLDEST, OLDER): assert f"lowered: {application_name}.{function_name}" in output +def test_a_default_an_earlier_run_lowered_gets_its_containers_back(): + """Re-running a deployment's failed jobs can make a lowered app the default. + + A later deployment's run set that app's functions to 0, and the rerun + doesn't deploy it again, so the script sets them back. + """ + fake = FakeModal( + store=_manifest_store(versions=(OLDER, NEWEST), default=NEWEST), + app_list=_app_list( + _app(v2_application_name(OLDER)), _app(v2_application_name(NEWEST)) + ), + ) + + assert _run(fake) == 0 + + assert fake.set_on(v2_application_name(NEWEST)) == [ + (function_name, {"min_containers": 1}) for function_name in HOUSEHOLD_FUNCTIONS + ] + assert [ + (application_name, function_name) + for application_name, function_name, minimum in fake.applied + if minimum == 1 + ] == _both_functions(NEWEST) + + +def test_staging_sets_the_default_to_its_own_minimum(): + fake = FakeModal( + store=_manifest_store(versions=(OLDER, NEWEST), default=NEWEST), + app_list=_app_list( + _app(v2_application_name(NEWEST)), _app(v2_application_name(OLDER)) + ), + ) + + assert _run(fake, environment="staging", default_min_containers=0) == 0 + + assert fake.set_on(v2_application_name(NEWEST)) == [ + (function_name, {"min_containers": 0}) for function_name in HOUSEHOLD_FUNCTIONS + ] + assert fake.lowered() == _both_functions(NEWEST, OLDER) + + DEFAULT_APPLICATION = v2_application_name(PRERELEASE) @@ -295,10 +371,18 @@ def test_the_default_app_is_never_lowered(default_names): assert _run(fake) == 0 assert fake.lowered() == _both_functions(OLDER) - assert not [ + # The default's functions get only the environment's minimum, under the + # name the manifest gives its app. + assert [ lookup for lookup in fake.lookups if lookup[0].casefold() == DEFAULT_APPLICATION.casefold() + ] == [ + (DEFAULT_APPLICATION, function_name, "main") + for function_name in HOUSEHOLD_FUNCTIONS + ] + assert fake.set_on(DEFAULT_APPLICATION) == [ + (function_name, {"min_containers": 1}) for function_name in HOUSEHOLD_FUNCTIONS ] @@ -361,7 +445,10 @@ def test_only_v2_worker_apps_are_touched(application_name): # The replaced v2 app beside it is still lowered. assert fake.lowered() == _both_functions(OLDER) - assert {lookup[0] for lookup in fake.lookups} == {v2_application_name(OLDER)} + assert {lookup[0] for lookup in fake.lookups} == { + v2_application_name(NEWEST), + v2_application_name(OLDER), + } @pytest.mark.parametrize( @@ -424,7 +511,7 @@ def test_the_run_reads_and_changes_only_its_own_modal_environment(environment): assert {update[2] for update in fake.updates} == {environment} -def test_with_no_replaced_app_nothing_changes(capsys): +def test_with_no_replaced_app_only_the_default_is_set(capsys): fake = FakeModal( store=_manifest_store(versions=(NEWEST,), default=NEWEST), app_list=_app_list(_app(v2_application_name(NEWEST))), @@ -432,7 +519,10 @@ def test_with_no_replaced_app_nothing_changes(capsys): assert _run(fake) == 0 - assert fake.lookups == [] + assert fake.updates == [ + (v2_application_name(NEWEST), function_name, "main", {"min_containers": 1}) + for function_name in HOUSEHOLD_FUNCTIONS + ] assert "no replaced v2 app is deployed" in capsys.readouterr().out @@ -482,9 +572,99 @@ def test_a_failed_update_fails_the_run_after_every_other_function_is_tried(capsy f"failed: {failed[0]}.{failed[1]}: " "RuntimeError: the autoscaler update was refused" ) in output + assert f"1 household function was not changed: {failed[0]}.{failed[1]}" in output + + +@pytest.mark.parametrize("where", ["lookup", "update"]) +def test_a_default_without_household_functions_fails_the_run(where, capsys): + """The simulation service calls the default's household functions.""" + default_functions = frozenset(_both_functions(NEWEST)) + fake = FakeModal( + store=_manifest_store(versions=(OLDER, NEWEST), default=NEWEST), + app_list=_app_list( + _app(v2_application_name(NEWEST)), _app(v2_application_name(OLDER)) + ), + missing=default_functions if where == "update" else frozenset(), + missing_at_lookup=default_functions if where == "lookup" else frozenset(), + ) + + assert _run(fake) == 1 + + # The replaced app is still lowered. + assert fake.lowered() == _both_functions(OLDER) + output = capsys.readouterr().out + for application_name, function_name in _both_functions(NEWEST): + assert ( + f"failed: {application_name}.{function_name}: NotFoundError: " + f"Function '{application_name}.{function_name}' not found" + ) in output + assert "2 household functions were not changed: " in output + + +def test_a_failed_update_of_the_default_fails_the_run(capsys): + failed = (v2_application_name(NEWEST), "calculate_household_uk") + fake = FakeModal( + store=_manifest_store(versions=(OLDER, NEWEST), default=NEWEST), + app_list=_app_list( + _app(v2_application_name(NEWEST)), _app(v2_application_name(OLDER)) + ), + failing=frozenset({failed}), + ) + + assert _run(fake) == 1 + + assert fake.lowered() == _both_functions(OLDER) + assert f"1 household function was not changed: {failed[0]}.{failed[1]}" in ( + capsys.readouterr().out + ) + + +@pytest.mark.parametrize( + ("function", "returned", "requested"), + [ + ((v2_application_name(OLDER), "calculate_household_us"), 1, 0), + ((v2_application_name(NEWEST), "calculate_household_uk"), 0, 1), + ((v2_application_name(NEWEST), "calculate_household_us"), None, 1), + ], + ids=["replaced-still-kept", "default-left-at-0", "default-without-minimum"], +) +def test_an_update_modal_reports_as_not_applied_fails_the_run( + function, returned, requested, capsys +): + fake = FakeModal( + store=_manifest_store(versions=(OLDER, NEWEST), default=NEWEST), + app_list=_app_list( + _app(v2_application_name(NEWEST)), _app(v2_application_name(OLDER)) + ), + returned_minimums={function: returned}, + ) + + assert _run(fake) == 1 + + output = capsys.readouterr().out assert ( - f"1 household function still keeps its containers: {failed[0]}.{failed[1]}" + f"failed: {function[0]}.{function[1]}: Modal reports a minimum of " + f"{returned or 0}, not {requested}" ) in output + assert f"1 household function was not changed: {function[0]}.{function[1]}" in ( + output + ) + + +def test_modal_reporting_no_minimum_after_lowering_counts_as_0(): + """Modal's settings give None for a minimum it holds as unset, which is 0.""" + function = (v2_application_name(OLDER), "calculate_household_uk") + fake = FakeModal( + store=_manifest_store(versions=(OLDER, NEWEST), default=NEWEST), + app_list=_app_list( + _app(v2_application_name(NEWEST)), _app(v2_application_name(OLDER)) + ), + returned_minimums={function: None}, + ) + + assert _run(fake) == 0 + + assert fake.lowered() == _both_functions(OLDER) @pytest.mark.parametrize( @@ -544,6 +724,34 @@ def test_an_unreadable_app_list_lowers_nothing(app_list): assert fake.lookups == [] +@pytest.mark.parametrize( + "default_entries", + [ + [], + [_app(v2_application_name(NEWEST), state="stopped")], + # A state text other than the one this client prints, as a change of + # the client's output would give. + [_app(v2_application_name(NEWEST), state="Deployed")], + [_app(v2_application_name(NEWEST), state="deployed (v2)")], + ], + ids=["not-listed", "listed-as-stopped", "other-letter-case", "other-text"], +) +def test_without_the_default_listed_as_deployed_nothing_changes(default_entries): + """The default's app is deployed, so a list without it can't be trusted.""" + fake = FakeModal( + store=_manifest_store(versions=(OLDER, NEWEST), default=NEWEST), + app_list=_app_list(*default_entries, _app(v2_application_name(OLDER))), + ) + + with pytest.raises( + lowering.HouseholdContainerLoweringError, + match=f"does not list the v2 default's app {v2_application_name(NEWEST)}", + ): + _run(fake) + + assert fake.lookups == [] + + @pytest.mark.parametrize( "manifest_name", ["", "simulation-api-routing-state"], ids=["empty", "v1"] ) @@ -683,24 +891,49 @@ def test_main_runs_with_the_arguments_the_workflow_passes(): ) result = lowering.main( - ["--environment", "main", "--manifest-name", V2_VERSION_MANIFEST_NAME], + [ + "--environment", + "main", + "--manifest-name", + V2_VERSION_MANIFEST_NAME, + "--default-min-containers", + "1", + ], open_manifest=fake.open_manifest, list_apps=fake.list_apps, lookup=fake.lookup, ) assert result == 0 + assert fake.set_on(v2_application_name(NEWEST)) == [ + (function_name, {"min_containers": 1}) for function_name in HOUSEHOLD_FUNCTIONS + ] assert fake.lowered() == _both_functions(OLDER) +MANIFEST_ARGUMENTS = ["--manifest-name", V2_VERSION_MANIFEST_NAME] +MINIMUM_ARGUMENTS = ["--default-min-containers", "1"] + + @pytest.mark.parametrize( "arguments", [ [], - ["--environment", "main"], - ["--manifest-name", V2_VERSION_MANIFEST_NAME], - ["--environment", "", "--manifest-name", V2_VERSION_MANIFEST_NAME], - ["--environment", " ", "--manifest-name", V2_VERSION_MANIFEST_NAME], + ["--environment", "main", *MINIMUM_ARGUMENTS], + [*MANIFEST_ARGUMENTS, *MINIMUM_ARGUMENTS], + ["--environment", "", *MANIFEST_ARGUMENTS, *MINIMUM_ARGUMENTS], + ["--environment", " ", *MANIFEST_ARGUMENTS, *MINIMUM_ARGUMENTS], + ["--environment", "main", *MANIFEST_ARGUMENTS], + *( + [ + "--environment", + "main", + *MANIFEST_ARGUMENTS, + "--default-min-containers", + value, + ] + for value in ("", "-1", "one", " 1", "1.0", "+1", "٢") + ), ], ids=[ "nothing", @@ -708,9 +941,17 @@ def test_main_runs_with_the_arguments_the_workflow_passes(): "no-environment", "empty-environment", "blank-environment", + "no-default-minimum", + "empty-minimum", + "negative-minimum", + "minimum-not-a-number", + "minimum-with-a-space", + "minimum-not-whole", + "minimum-with-a-sign", + "minimum-in-other-digits", ], ) -def test_main_refuses_a_missing_environment_or_manifest_name(arguments): +def test_main_refuses_missing_or_invalid_arguments(arguments): fake = FakeModal(store=None, app_list="[]") with pytest.raises(SystemExit) as exited: From 41ff818a1e195c855955d85146bafe5d4c39b1b5 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:29:28 +0400 Subject: [PATCH 4/6] Set the v2 default's household minimum and check each update Review round 1 found that nothing gave a new default back its household containers once an earlier run had set them to 0, as "Re-run failed jobs" on an older deployment can leave it. The job now passes the deploy's minimum as --default-min-containers, and the script sets the default's household functions to it before lowering every other v2 app's. The script also uses Function.autoscaler.update, which the locked Modal client recommends over the deprecated update_autoscaler; fails a function whose reported minimum isn't the one requested; and changes nothing when modal app list doesn't list the default's app as deployed, so a change of the client's output can't make it lower nothing while reporting success. The job's name and comment, the rule's statement, scope and tests, the docs and the changelog fragment follow. Co-Authored-By: Claude Opus 5.5 --- .../workflows/simulation-deploy.reusable.yml | 21 +- .../v2-household-containers.changed.md | 2 +- docs/generated/rules.md | 2 +- .../DEPLOYMENT.md | 8 +- .../README.md | 55 ++-- .../lower_replaced_household_containers.py | 238 +++++++++++++----- rules/registry.toml | 15 +- 7 files changed, 240 insertions(+), 101 deletions(-) diff --git a/.github/workflows/simulation-deploy.reusable.yml b/.github/workflows/simulation-deploy.reusable.yml index de30ed8d9..770c8bb7e 100644 --- a/.github/workflows/simulation-deploy.reusable.yml +++ b/.github/workflows/simulation-deploy.reusable.yml @@ -1250,15 +1250,19 @@ jobs: run: ../../.github/scripts/stage12-v2-default-restore.sh lower_replaced_household_containers: - name: Stop keeping household containers in replaced v2 apps + name: Keep household containers running only in the v2 default's app # Each .py version's v2 app stays deployed, and a deploy gives its # household functions the environment's minimum container count, one in # production. The simulation service calls only the v2 default's, so once - # the default has moved, this sets the minimum to 0 on every other - # deployed v2 app's household functions. Its own job, after the default - # job succeeded, so a failed run puts back no Stage 12 default. A failure + # the default has moved, this sets the default's household functions to + # that minimum (an earlier run may have set them to 0, and a rerun of + # failed jobs can make them the default without deploying them) and every + # other deployed v2 app's to 0. Its own job, after the default job + # succeeded, so a failed run puts back no Stage 12 default. A failure # fails this workflow call, so in the beta deployment it skips the - # production deployment, as a failed runtime estimates deploy does. + # production deployment and the client publishing, as a failed runtime + # estimates deploy does; in the production deployment it fails the run, + # which also stops the client publishing. if: >- ${{ !cancelled() && @@ -1287,13 +1291,14 @@ jobs: run: uv sync --frozen # Reads the default from the environment's v2 manifest and lists the - # environment's apps with modal app list; only Modal's tokens. - - name: Stop keeping household containers in replaced v2 apps + # environment's apps with modal app list; only Modal's tokens. The + # default's functions get the minimum the v2 deploy step gave the app. + - name: Keep household containers running only in the v2 default's app working-directory: projects/policyengine-simulation-executor env: MODAL_TOKEN_ID: ${{ secrets.MODAL_TOKEN_ID }} MODAL_TOKEN_SECRET: ${{ secrets.MODAL_TOKEN_SECRET }} - run: uv run --frozen python -m src.modal.utils.lower_replaced_household_containers --environment "${{ inputs.modal_environment }}" --manifest-name simulation-api-v2-version-manifest + run: uv run --frozen python -m src.modal.utils.lower_replaced_household_containers --environment "${{ inputs.modal_environment }}" --manifest-name simulation-api-v2-version-manifest --default-min-containers "${{ inputs.household_function_min_containers }}" deploy_runtime_estimates: name: Deploy the scheduled runtime estimates app after every check diff --git a/changelog.d/v2-household-containers.changed.md b/changelog.d/v2-household-containers.changed.md index 7c2200386..d9651bde2 100644 --- a/changelog.d/v2-household-containers.changed.md +++ b/changelog.d/v2-household-containers.changed.md @@ -1 +1 @@ -In production, the API v2 simulation app's household calculation functions (`calculate_household_us` and `calculate_household_uk`) keep one container running at all times, so a household calculation after a quiet period doesn't wait for a container to start, and extra containers stop after ten idle minutes instead of one; staging keeps none, as before. After each deploy moves the v2 default, a new deploy job sets the minimum to 0 on the household functions of every other deployed v2 app, so only the default's containers keep running (about $92 a month per container at list price). +In production, the API v2 simulation app's household calculation functions (`calculate_household_us` and `calculate_household_uk`) keep one container running at all times, so a household calculation after a quiet period doesn't wait for a container to start, and extra containers stop after ten idle minutes instead of one; staging keeps none, as before. After each deploy moves the v2 default, a new deploy job sets the default's household functions to that minimum and every other deployed v2 app's to 0, so only the default's containers keep running (about $92 a month per container at list price). diff --git a/docs/generated/rules.md b/docs/generated/rules.md index 58aaf5787..86be5a955 100644 --- a/docs/generated/rules.md +++ b/docs/generated/rules.md @@ -174,7 +174,7 @@ flowchart LR | `sim.deploy.container-context-minimal` | Container builds exclude local environments and unrelated projects but include every local library the entrypoint installs, and the entrypoint container builds for the requested target platform. | mechanical | enforced | yes | pytest `projects/policyengine-simulation-entry/tests/test_deployment_assets_cloud_run.py`, `projects/policyengine-simulation-entry/tests/test_deployment_assets_traffic.py` | `pr.yml:test` | yes | | `sim.deploy.docker-images-build` | The simulation entry and executor Docker images build. | mechanical | enforced | yes | CI job `docker-build` | `pr.yml:docker-build` | — | | `sim.deploy.gcloud-without-terraform` | Deployment uses the gcloud-based workflow, not Terraform. | mechanical | enforced | yes | pytest `projects/policyengine-simulation-entry/tests/test_deployment_assets.py` | `pr.yml:test` | **unproven** | -| `sim.deploy.household-containers-follow-the-default` | Every caller of the reusable deploy sets the minimum container count and idle window of the API v2 household functions for its environment (one container and 600 seconds in production, none and 60 seconds in staging), which the v2 app reads when it is deployed; after the Stage 12 v2 default moves, a job of its own sets the minimum to 0 on the household functions of every other deployed v2 app, so a failure there never puts the previous default back. | mechanical | enforced | yes | pytest `projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py`, `projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py`, `projects/policyengine-simulation-executor/tests/test_v2_household_scaling.py` | `pr.yml:test` | **unproven** | +| `sim.deploy.household-containers-follow-the-default` | Every caller of the reusable deploy sets the minimum container count and idle window of the API v2 household functions for its environment (one container and 600 seconds in production, none and 60 seconds in staging), which the v2 app reads when it is deployed; after the Stage 12 v2 default moves, a job of its own sets the default's household functions to that minimum and every other deployed v2 app's to 0, so a failure there never puts the previous default back. | mechanical | enforced | yes | pytest `projects/policyengine-simulation-entry/tests/test_deployment_assets_household_containers.py`, `projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py`, `projects/policyengine-simulation-executor/tests/test_v2_household_scaling.py` | `pr.yml:test` | **unproven** | | `sim.deploy.image-smoke-covers-every-image-lib` | The image smoke path filter includes every library mounted into a Modal image, so a change to any of them runs the smoke. | mechanical | doc-only | no | nothing | — | — | | `sim.deploy.latest-moves-after-checks` | A deployment publishes its release's routes before its checks without moving latest (unless no release is latest yet), and moves latest only after every check and the Cloud Run promotion pass, then checks that unpinned requests reach the release and puts latest back if a later step fails; no job that runs after the routes job is upstream of it, so rerunning jobs that failed after it never republishes the routes. | mechanical | enforced | yes | pytest `projects/policyengine-simulation-entry/tests/test_deployment_assets_latest.py` | `pr.yml:test` | **unproven** | | `sim.deploy.modal-image-smoke` | App entrypoints import inside the real Modal images before merge, whenever a library baked into an image changes. | mechanical | enforced | yes | CI job `image-smoke` | `pr-image-smoke.yml:image-smoke` | — | diff --git a/projects/policyengine-simulation-entry/DEPLOYMENT.md b/projects/policyengine-simulation-entry/DEPLOYMENT.md index 27c192dff..1dbab0676 100644 --- a/projects/policyengine-simulation-entry/DEPLOYMENT.md +++ b/projects/policyengine-simulation-entry/DEPLOYMENT.md @@ -107,10 +107,10 @@ stops extra containers after ten idle minutes; staging keeps none, with Modal's 60 seconds. Each caller of the reusable deploy sets these with the `household_function_min_containers` and `household_function_scaledown_window_seconds` inputs. After the default -moves, `lower_replaced_household_containers` sets the minimum to 0 on every -other deployed v2 app's household functions, so only the default's -containers keep running. The executor's README describes the job and the -cases it leaves to the next deployment. +moves, `lower_replaced_household_containers` sets the default's household +functions to that minimum and every other deployed v2 app's to 0, so only +the default's containers keep running. The executor's README describes the +job and the cases it leaves to the next deployment. ### The staging household check diff --git a/projects/policyengine-simulation-executor/README.md b/projects/policyengine-simulation-executor/README.md index d3f4d3409..f6fcedd70 100644 --- a/projects/policyengine-simulation-executor/README.md +++ b/projects/policyengine-simulation-executor/README.md @@ -314,36 +314,45 @@ Every policyengine.py version's v2 app stays deployed, and the simulation service calls only the default worker's household functions. So after `publish_stage12_v2_default` succeeds, the job `lower_replaced_household_containers` runs -`src/modal/utils/lower_replaced_household_containers.py`: it reads the -default from the manifest, lists the Modal environment's apps with -`modal app list --json`, and sets the minimum to 0 (`update_autoscaler`) on -the household functions of every other deployed v2 worker app, including one -whose deploy failed before the manifest named it. It leaves the idle window, -the container limit and every other app as they are. A failed update fails -the job, after every other function has been tried, and so the deployment; -the default stays where it moved. A later `modal deploy` of a lowered app -gives its functions the deploy's minimum again. - -Two cases leave containers running until the next deployment whose default +`src/modal/utils/lower_replaced_household_containers.py`, which changes only +minimums, through Modal's `Function.autoscaler.update`: + +1. It reads the default from the manifest and lists the Modal environment's + apps with `modal app list --json`. If the list doesn't show the default's + app as deployed, it can't be trusted, and nothing changes. +2. It sets the default's household functions to the environment's minimum, + the same input the v2 deploy step uses. An earlier run may have set them + to 0 while the app wasn't the default, and "Re-run failed jobs" on an + older deployment can make that app the default again without deploying + it. +3. It sets the minimum to 0 on the household functions of every other + deployed v2 worker app, including one whose deploy failed before the + manifest named it. + +It leaves the idle window, the container limit and every other app as they +are. A failed update, a default without household functions, or a minimum +Modal reports other than the one requested fails the job, after every other +function has been tried, and so the deployment; the default stays where it +moved. A later `modal deploy` of an app gives its functions the deploy's +minimum again. + +Two cases leave the minimums wrong until the next deployment whose default job succeeds: - **A deployment that fails after deploying its v2 app**, before or during - the default move, keeps that app's household containers, because the - lowering runs only after a successful move. + the default move, keeps that app's household containers, because the job + runs only after a successful move. - **A default an operator moves by hand**, with `--restore-plan` or a - publication, leaves the new default's functions at the lowered minimum, 0, - and the app it replaced at the deploy's minimum. To change one function's - minimum until - its app's next deploy, with Modal credentials for the workspace, run - `modal.Function.from_name("", "", - environment_name="").update_autoscaler(min_containers=)` - from Python in `projects/policyengine-simulation-executor`. - -To lower the replaced apps by hand, from + publication, keeps the minimums the last run gave: 0 on the new default's + functions, and the deploy's minimum on the app it replaced. To put them + right before the next deployment, run the script by hand. + +To run it by hand, with Modal credentials for the workspace, from `projects/policyengine-simulation-executor`, run `uv run --frozen python -m src.modal.utils.lower_replaced_household_containers --environment --manifest-name -simulation-api-v2-version-manifest`. +simulation-api-v2-version-manifest --default-min-containers `, with the +environment's minimum: 1 for `main`, 0 for `staging`. ## Baseline artifact pipeline (precompute → store → image fetch) diff --git a/projects/policyengine-simulation-executor/src/modal/utils/lower_replaced_household_containers.py b/projects/policyengine-simulation-executor/src/modal/utils/lower_replaced_household_containers.py index b28350622..77e0d9cf6 100644 --- a/projects/policyengine-simulation-executor/src/modal/utils/lower_replaced_household_containers.py +++ b/projects/policyengine-simulation-executor/src/modal/utils/lower_replaced_household_containers.py @@ -1,28 +1,40 @@ -"""Stop keeping household containers running in replaced v2 apps. +"""Keep household containers running only in the v2 default's app. The simulation service sends household calculations only to the household functions of the v2 version manifest's default worker. A deploy of ``src/modal/v2_app.py`` gives each household function its environment's minimum container count (``src/modal/v2_household_scaling.py``; one in production), and every .py version's v2 app stays deployed. So once a deploy -has moved the default, the deploy workflow runs this, which sets the minimum -to 0 on the household functions of every other deployed v2 app in the -environment, through Modal's ``update_autoscaler``. A later ``modal deploy`` -of such an app gives its functions the deploy's minimum again. - -- **The app it keeps** is the default worker's, read from the manifest as - stored. No app whose name matches it, ignoring letter case, is changed. -- **The apps it changes** are those ``modal app list --json`` lists as +has moved the default, the deploy workflow runs this, which, through Modal's +``Function.autoscaler.update``: + +1. sets the default's household functions to the environment's minimum + (``--default-min-containers``), since an earlier run may have set them to + 0 while the app wasn't the default, and a rerun of a deployment's failed + jobs can make it the default without deploying it again; +2. sets the minimum to 0 on the household functions of every other deployed + v2 app in the environment. + +A later ``modal deploy`` of an app gives its functions the deploy's minimum +again. + +- **The default** is the default worker's app, read from the manifest as + stored. ``modal app list`` must list it as deployed, or the list can't be + trusted (another format, or another environment's), and nothing changes. + No other app whose name matches it, ignoring letter case, is lowered. +- **The apps it lowers** are those ``modal app list --json`` lists as deployed under a v2 worker app's name (``policyengine-simulation-v2-py`` and a version), including any whose deploy failed before the manifest named it. The v1 apps and every other app are left alone. - **Only the minimum changes**: an app's idle window and container limit - stay as deployed. - -Exit status 0 when every household function of those apps was lowered, or -doesn't exist (an app from before the household functions); 1 when any -update failed, after every other function was tried. When the manifest or -the app list can't be read, it raises before changing anything. + stay as deployed. An update counts only when the settings Modal returns + hold the minimum requested. + +Exit status 0 when every change was made, a replaced app without household +functions (an app from before them) included; 1 when any update failed, a +default's function was missing, or Modal reported another minimum, after +every other function was tried. When the manifest or the app list can't be +read, it raises before changing anything. """ from __future__ import annotations @@ -57,6 +69,7 @@ ) # The minimum a replaced app's household functions keep. REPLACED_MIN_CONTAINERS = 0 +_WHOLE_NUMBER = re.compile(r"[0-9]+") # The state ``modal app list --json`` gives an app that is deployed. DEPLOYED_STATE = "deployed" # A v2 worker app's name: the prefix and a version with its dots and plus @@ -72,11 +85,29 @@ class HouseholdContainerLoweringError(RuntimeError): """The manifest or the app list could not be opened or read; nothing changed.""" +class AutoscalerSettings(Protocol): + """A function's autoscaler settings, as Modal returns them after an update.""" + + @property + def min_containers(self) -> int | None: + """The minimum container count; None when Modal holds none, which is 0.""" + ... + + +class FunctionAutoscaler(Protocol): + """A deployed function's autoscaler, ``Function.autoscaler`` in Modal.""" + + def update(self, *, min_containers: int) -> AutoscalerSettings: + """Change the minimum container count until the app's next deploy.""" + ... + + class AutoscaledFunction(Protocol): """A deployed Modal function whose autoscaler settings can be changed.""" - def update_autoscaler(self, *, min_containers: int) -> object: - """Change the function's minimum container count until its next deploy.""" + @property + def autoscaler(self) -> FunctionAutoscaler: + """The function's autoscaler.""" ... @@ -91,12 +122,23 @@ def __call__( @dataclass(frozen=True) -class LoweringOutcome: - """What happened to one household function of one replaced app.""" +class MinimumChange: + """A minimum container count to give one household function.""" + + application_name: str + function_name: str + min_containers: int + # The default's functions must exist: the simulation service calls them. + of_default: bool + + +@dataclass(frozen=True) +class MinimumOutcome: + """What happened to one household function's minimum.""" application_name: str function_name: str - result: Literal["lowered", "no such function", "failed"] + result: Literal["set", "lowered", "no such function", "failed"] detail: str = "" def line(self) -> str: @@ -127,7 +169,8 @@ def replaced_v2_applications(app_list: str, *, default_application: str) -> list ``app_list`` is what ``modal app list --json`` prints. The names come sorted, each once. Raises HouseholdContainerLoweringError when it isn't a - JSON list of objects that each have a text name and state. + JSON list of objects that each have a text name and state, or doesn't + list the default's app as deployed. """ try: entries = json.loads(app_list) @@ -138,6 +181,7 @@ def replaced_v2_applications(app_list: str, *, default_application: str) -> list msg = "modal app list did not print a JSON list" raise HouseholdContainerLoweringError(msg) replaced: set[str] = set() + default_listed = False for entry in entries: if not ( isinstance(entry, dict) @@ -147,47 +191,99 @@ def replaced_v2_applications(app_list: str, *, default_application: str) -> list msg = f"modal app list printed an entry without a name and state: {entry!r}" raise HouseholdContainerLoweringError(msg) name = entry["description"] - if ( - entry["state"] == DEPLOYED_STATE - and _V2_WORKER_APPLICATION.fullmatch(name) - and name.casefold() != default_application.casefold() - ): + if entry["state"] != DEPLOYED_STATE: + continue + if name.casefold() == default_application.casefold(): + default_listed = True + elif _V2_WORKER_APPLICATION.fullmatch(name): replaced.add(name) + if not default_listed: + msg = ( + f"modal app list does not list the v2 default's app " + f"{default_application} as deployed, so the list can't be trusted" + ) + raise HouseholdContainerLoweringError(msg) return sorted(replaced) -def lower_household_functions( - applications: Iterable[str], *, environment: str, lookup: FunctionLookup -) -> list[LoweringOutcome]: - """Set the minimum to 0 on each household function of ``applications``. +def planned_changes( + default_application: str, + replaced_applications: Iterable[str], + *, + default_min_containers: int, +) -> list[MinimumChange]: + """Return the default's functions at ``default_min_containers``, then the rest at 0. - Every function is tried, whatever happened to the ones before it. + The default comes first, so its containers start before any other app's + stop. """ return [ - _lower(application_name, function_name, environment, lookup) - for application_name in applications + MinimumChange( + default_application, function_name, default_min_containers, of_default=True + ) for function_name in HOUSEHOLD_FUNCTION_NAMES + ] + [ + MinimumChange( + application_name, + function_name, + REPLACED_MIN_CONTAINERS, + of_default=False, + ) + for application_name in replaced_applications + for function_name in HOUSEHOLD_FUNCTION_NAMES + ] + + +def apply_changes( + changes: Iterable[MinimumChange], *, environment: str, lookup: FunctionLookup +) -> list[MinimumOutcome]: + """Make each change; every one is tried, whatever happened to those before it.""" + return [ + _apply(change, environment=environment, lookup=lookup) for change in changes ] -def _lower( - application_name: str, function_name: str, environment: str, lookup: FunctionLookup -) -> LoweringOutcome: +def _apply( + change: MinimumChange, *, environment: str, lookup: FunctionLookup +) -> MinimumOutcome: + application_name, function_name = change.application_name, change.function_name try: - lookup(application_name, function_name, environment).update_autoscaler( - min_containers=REPLACED_MIN_CONTAINERS - ) - except modal.exception.NotFoundError: - return LoweringOutcome(application_name, function_name, "no such function") - # Each failure is reported, and the other functions are still lowered. + settings = lookup( + application_name, function_name, environment + ).autoscaler.update(min_containers=change.min_containers) + except modal.exception.NotFoundError as error: + if change.of_default: + return MinimumOutcome( + application_name, + function_name, + "failed", + f"{type(error).__name__}: {error}", + ) + return MinimumOutcome(application_name, function_name, "no such function") + # Each failure is reported, and the other functions are still changed. except Exception as error: # noqa: BLE001 - return LoweringOutcome( + return MinimumOutcome( application_name, function_name, "failed", f"{type(error).__name__}: {error}", ) - return LoweringOutcome(application_name, function_name, "lowered") + reported = settings.min_containers or 0 + if reported != change.min_containers: + return MinimumOutcome( + application_name, + function_name, + "failed", + f"Modal reports a minimum of {reported}, not {change.min_containers}", + ) + if change.of_default: + return MinimumOutcome( + application_name, + function_name, + "set", + f"minimum {change.min_containers}", + ) + return MinimumOutcome(application_name, function_name, "lowered") def list_applications( @@ -237,7 +333,11 @@ def list_applications( def modal_function( application_name: str, function_name: str, environment: str ) -> AutoscaledFunction: - """Return the deployed Modal function, found when it is first used.""" + """Return the deployed Modal function, found when it is first used. + + Its ``autoscaler.update`` raises NotFoundError for a missing app or + function. + """ return modal.Function.from_name( application_name, function_name, environment_name=environment ) @@ -254,18 +354,21 @@ def lower_replaced_household_containers( # noqa: PLR0913 # each Modal access i *, environment: str, manifest_name: str, - default_min_containers: int, # noqa: ARG001 # placeholder until the change + default_min_containers: int, open_manifest: Callable[[str, str], V2ManifestStore], list_apps: Callable[[str], str], lookup: FunctionLookup, report: Callable[[str], object] = print, ) -> int: - """Lower every replaced v2 app's household functions; return the exit status. + """Set the default's household functions, lower the rest; return the exit status. Reads the default before listing the apps, and changes nothing unless both could be read. Raises ValueError for a manifest name that is empty - or names the v1 routing state. + or names the v1 routing state, or a negative ``default_min_containers``. """ + if default_min_containers < 0: + msg = f"the default's minimum must be 0 or more, not {default_min_containers}" + raise ValueError(msg) assert_separate_manifest_names(v1_name=V1_ROUTING_STATE_NAME, v2_name=manifest_name) try: store = open_manifest(manifest_name, environment) @@ -276,12 +379,17 @@ def lower_replaced_household_containers( # noqa: PLR0913 # each Modal access i applications = replaced_v2_applications( list_apps(environment), default_application=default_application ) - report(f"kept: {default_application}, the v2 default") + report(f"the v2 default: {default_application}") if not applications: report("no replaced v2 app is deployed") - return 0 - outcomes = lower_household_functions( - applications, environment=environment, lookup=lookup + outcomes = apply_changes( + planned_changes( + default_application, + applications, + default_min_containers=default_min_containers, + ), + environment=environment, + lookup=lookup, ) for outcome in outcomes: report(outcome.line()) @@ -292,19 +400,17 @@ def lower_replaced_household_containers( # noqa: PLR0913 # each Modal access i f"{outcome.application_name}.{outcome.function_name}" for outcome in failed ) if len(failed) == 1: - report(f"1 household function still keeps its containers: {names}") + report(f"1 household function was not changed: {names}") else: - report( - f"{len(failed)} household functions still keep their containers: {names}" - ) + report(f"{len(failed)} household functions were not changed: {names}") return 1 def _argument_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description=( - "Set the minimum container count to 0 on the household functions " - "of every deployed v2 app but the v2 default's." + "Set the v2 default's household functions to the environment's " + "minimum container count, and every other deployed v2 app's to 0." ) ) parser.add_argument( @@ -315,11 +421,23 @@ def _argument_parser() -> argparse.ArgumentParser: required=True, help="The v2 version manifest's Modal Dict.", ) - # Placeholder until the change. - parser.add_argument("--default-min-containers", type=int, required=True) + parser.add_argument( + "--default-min-containers", + required=True, + type=_container_count, + help="The minimum the deploy gave the v2 app's household functions.", + ) return parser +def _container_count(value: str) -> int: + """Return ``value`` as a whole number of containers, in ASCII digits only.""" + if not _WHOLE_NUMBER.fullmatch(value): + msg = f"must be a whole number of 0 or more, not {value!r}" + raise argparse.ArgumentTypeError(msg) + return int(value) + + def main( argv: Sequence[str] | None = None, *, diff --git a/rules/registry.toml b/rules/registry.toml index 7ee0e9327..02f1d6560 100644 --- a/rules/registry.toml +++ b/rules/registry.toml @@ -809,9 +809,9 @@ invocation = "uv run --frozen pytest tests/" [[rule]] id = "sim.deploy.household-containers-follow-the-default" category = "deployment" -statement = "Every caller of the reusable deploy sets the minimum container count and idle window of the API v2 household functions for its environment (one container and 600 seconds in production, none and 60 seconds in staging), which the v2 app reads when it is deployed; after the Stage 12 v2 default moves, a job of its own sets the minimum to 0 on the household functions of every other deployed v2 app, so a failure there never puts the previous default back." +statement = "Every caller of the reusable deploy sets the minimum container count and idle window of the API v2 household functions for its environment (one container and 600 seconds in production, none and 60 seconds in staging), which the v2 app reads when it is deployed; after the Stage 12 v2 default moves, a job of its own sets the default's household functions to that minimum and every other deployed v2 app's to 0, so a failure there never puts the previous default back." rationale = "projects/policyengine-simulation-executor/README.md#household-containers" -scope = [".github/workflows/simulation-deploy.reusable.yml", ".github/workflows/simulation-deploy.yml", ".github/workflows/stage12-deploy.yml", "projects/policyengine-simulation-executor/src/modal/v2_household_scaling.py", "projects/policyengine-simulation-executor/src/modal/utils/lower_replaced_household_containers.py"] +scope = [".github/workflows/simulation-deploy.reusable.yml", ".github/workflows/simulation-deploy.yml", ".github/workflows/stage12-deploy.yml", "projects/policyengine-simulation-executor/src/modal/v2_app.py", "projects/policyengine-simulation-executor/src/modal/v2_household_scaling.py", "projects/policyengine-simulation-executor/src/modal/utils/lower_replaced_household_containers.py"] tier = "mechanical" status = "enforced" autofix = false @@ -842,6 +842,8 @@ nodes = [ "projects/policyengine-simulation-executor/tests/test_v2_household_scaling.py::test_an_invalid_setting_stops_the_v2_app_deploy", "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_the_household_functions_are_both_countries", "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_every_replaced_v2_app_stops_keeping_household_containers", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_a_default_an_earlier_run_lowered_gets_its_containers_back", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_staging_sets_the_default_to_its_own_minimum", "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_the_default_app_is_never_lowered", "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_the_default_is_read_from_the_stored_manifest", "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_a_v2_app_the_manifest_does_not_name_is_lowered", @@ -849,11 +851,16 @@ nodes = [ "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_only_deployed_apps_are_lowered", "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_an_app_listed_as_stopped_and_deployed_is_lowered_once", "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_the_run_reads_and_changes_only_its_own_modal_environment", - "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_with_no_replaced_app_nothing_changes", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_with_no_replaced_app_only_the_default_is_set", "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_an_app_without_household_functions_is_skipped", "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_a_failed_update_fails_the_run_after_every_other_function_is_tried", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_a_default_without_household_functions_fails_the_run", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_a_failed_update_of_the_default_fails_the_run", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_an_update_modal_reports_as_not_applied_fails_the_run", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_modal_reporting_no_minimum_after_lowering_counts_as_0", "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_without_a_valid_manifest_nothing_is_listed_or_lowered", "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_an_unreadable_app_list_lowers_nothing", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_without_the_default_listed_as_deployed_nothing_changes", "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_the_v1_routing_state_is_never_read_as_the_manifest", "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_the_app_list_comes_from_modal_app_list_as_json", "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_a_failed_modal_app_list_is_an_error", @@ -861,7 +868,7 @@ nodes = [ "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_modal_functions_are_looked_up_in_the_given_environment", "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_the_manifest_is_opened_without_creating_it", "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_main_runs_with_the_arguments_the_workflow_passes", - "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_main_refuses_a_missing_environment_or_manifest_name", + "projects/policyengine-simulation-executor/tests/test_lower_replaced_household_containers.py::test_main_refuses_missing_or_invalid_arguments", ] [[rule.ci]] workflow = ".github/workflows/pr.yml" From d56120b00136543bf9e3be420e1c1c85fce953d7 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:44:31 +0400 Subject: [PATCH 5/6] Describe every case that leaves household minimums wrong Review round 2 found the executor README naming two cases that leave the household minimums wrong until the next deployment, missing a run cancelled after the default moved and a failed run of the job, and the settings module's docstring describing the script from before it set the default's minimum. Wording only. Co-Authored-By: Claude Opus 5.5 --- projects/policyengine-simulation-executor/README.md | 10 ++++++---- .../src/modal/v2_household_scaling.py | 5 +++-- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/projects/policyengine-simulation-executor/README.md b/projects/policyengine-simulation-executor/README.md index f6fcedd70..a67875461 100644 --- a/projects/policyengine-simulation-executor/README.md +++ b/projects/policyengine-simulation-executor/README.md @@ -336,16 +336,18 @@ function has been tried, and so the deployment; the default stays where it moved. A later `modal deploy` of an app gives its functions the deploy's minimum again. -Two cases leave the minimums wrong until the next deployment whose default -job succeeds: +Three cases leave the minimums wrong until the next deployment whose default +job succeeds, or until someone runs the script by hand (below): - **A deployment that fails after deploying its v2 app**, before or during the default move, keeps that app's household containers, because the job runs only after a successful move. +- **A run cancelled after the default moved, or a failed run of this job**, + leaves the previous default's household containers running, and possibly + the new default's functions at 0. - **A default an operator moves by hand**, with `--restore-plan` or a publication, keeps the minimums the last run gave: 0 on the new default's - functions, and the deploy's minimum on the app it replaced. To put them - right before the next deployment, run the script by hand. + functions, and the deploy's minimum on the app it replaced. To run it by hand, with Modal credentials for the workspace, from `projects/policyengine-simulation-executor`, run diff --git a/projects/policyengine-simulation-executor/src/modal/v2_household_scaling.py b/projects/policyengine-simulation-executor/src/modal/v2_household_scaling.py index 33af8ad5d..14a6cfd3f 100644 --- a/projects/policyengine-simulation-executor/src/modal/v2_household_scaling.py +++ b/projects/policyengine-simulation-executor/src/modal/v2_household_scaling.py @@ -14,8 +14,9 @@ invalid value raises ValueError, so the deploy stops. Every .py version's v2 app stays deployed, so once the v2 default has moved, -``src/modal/utils/lower_replaced_household_containers.py`` sets the minimum to -0 on every other app's household functions. +``src/modal/utils/lower_replaced_household_containers.py`` sets the default's +household functions to the environment's minimum again and every other +app's to 0. """ from __future__ import annotations From 63edbad1ac79c2192575802767b692aa872c1222 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:51:24 +0400 Subject: [PATCH 6/6] Count the household container job among the release-environment jobs The new job that keeps household containers only in the v2 default's app declares the release environment, as every job but stage12_v2_ready does, so the reusable workflow has 19 such jobs. Co-Authored-By: Claude Opus 5.5 --- .../tests/test_deployment_assets.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/projects/policyengine-simulation-entry/tests/test_deployment_assets.py b/projects/policyengine-simulation-entry/tests/test_deployment_assets.py index decec58fa..5d7e8ce61 100644 --- a/projects/policyengine-simulation-entry/tests/test_deployment_assets.py +++ b/projects/policyengine-simulation-entry/tests/test_deployment_assets.py @@ -216,7 +216,7 @@ def _assert_deployment_environment_settings(reusable_workflow: str) -> None: # Every job but stage12_v2_ready declares the release environment. # The job that moves latest after the checks reads the prod # environment's custom-hostname variable. - reusable_workflow.count("environment: ${{ inputs.release_environment }}") == 18 + reusable_workflow.count("environment: ${{ inputs.release_environment }}") == 19 ) assert "APP_ENVIRONMENT: ${{ inputs.deployment_environment }}" in reusable_workflow assert "STAGE12_ENABLED_VALUE: ${{ vars.STAGE12_ENABLED }}" in reusable_workflow