diff --git a/changelog.d/1146.added.md b/changelog.d/1146.added.md new file mode 100644 index 000000000..5fc99e1b4 --- /dev/null +++ b/changelog.d/1146.added.md @@ -0,0 +1 @@ +The v2 app's US workers, `SimulationSegmentWorkerUS` and `SimulationWorkerUS`, now run one warm-up calculation before Modal takes their memory snapshot, so a container restored from the snapshot starts with the year's parameter values built. The warm-up calculates the reform side of the first region group the v2 cache precomputes (Hawaii, Iowa and Wisconsin) for 2026, under a raised Child Tax Credit base amount, only in a container Modal takes a snapshot from. It reads no Modal Secret, opens no connection, sends no telemetry, doesn't count as a worker call and leaves nothing for later calls; a failure only logs a warning. Containers that take a snapshot start later by about one segment's calculation. The UK worker doesn't warm up yet. diff --git a/docs/engineering/skills/observability.md b/docs/engineering/skills/observability.md index bde990d9a..150124310 100644 --- a/docs/engineering/skills/observability.md +++ b/docs/engineering/skills/observability.md @@ -300,7 +300,11 @@ How a call tells them apart, in Modal 1.6.4: the one serving the call. Neither the restore nor the snapshot hook runs inside a call, so no span -measures them. Modal's container records (its `TaskGetInfo` call) give the +measures them. That includes the warm-up calculation that the versioned app's +workers and the v2 app's US workers run in the hook of a container Modal +snapshots (`src/modal/snapshot_warm_up.py`, `src/modal/v2_snapshot_warm_up.py`): +it opens no span or operation and takes no call number, so the container's +first call is still number 1. Modal's container records (its `TaskGetInfo` call) give the times each container was queued and became ready (`enqueued_at` and `started_at`), which include scheduling as well as the restore. A call's spans show the setup still left in it: diff --git a/projects/policyengine-simulation-executor/src/modal/v2_app.py b/projects/policyengine-simulation-executor/src/modal/v2_app.py index ca6eef835..149d761bb 100644 --- a/projects/policyengine-simulation-executor/src/modal/v2_app.py +++ b/projects/policyengine-simulation-executor/src/modal/v2_app.py @@ -42,8 +42,6 @@ from policyengine_simulation_executor.stage12_timeouts import ( COORDINATOR_TIMEOUT_SECONDS, HOUSEHOLD_FUNCTION_TIMEOUT_SECONDS, - UK_SIMULATION_TIMEOUT_SECONDS, - US_SIMULATION_TIMEOUT_SECONDS, ) from policyengine_simulation_observability.observability import ( init_process_observability, @@ -77,6 +75,12 @@ uk_worker_image, us_worker_image, ) +from src.modal.v2_snapshot_warm_up import warm_up_first_us_calculation +from src.modal.v2_worker_resources import ( + SEGMENT_WORKER_RESOURCES, + UK_SIMULATION_WORKER_RESOURCES, + US_SIMULATION_WORKER_RESOURCES, +) import modal @@ -187,34 +191,22 @@ def validate_worker_uk() -> dict: # code from before the classes: an entry service revision (the stable one # during a deploy, or one a rollback routes traffic back to), and a coordinator # or US worker call running while this app is redeployed in place. Both run the -# same calculation. +# same calculation. Their CPU, memory, time and container limits are in +# src/modal/v2_worker_resources.py. _SEGMENT_WORKER_OPTIONS: dict[str, Any] = { + **SEGMENT_WORKER_RESOURCES, "image": us_worker_image, - "cpu": 8.0, - "memory": 32768, - "timeout": 3600, - "retries": 0, - # Every segment of every US simulation call that may run at once: a - # segment queued behind this limit counts against its caller's wait. - "max_containers": 1000, "secrets": worker_secrets, } _US_SIMULATION_WORKER_OPTIONS: dict[str, Any] = { + **US_SIMULATION_WORKER_RESOURCES, "image": us_worker_image, - "cpu": 8.0, - "memory": 32768, - "timeout": US_SIMULATION_TIMEOUT_SECONDS, - "retries": 0, - # Both simulations of every coordinator call that may run at once. The - # simulation runs and cliff calculations the simulation service starts - # directly share the same containers. - "max_containers": 50, "secrets": report_run_writer_secrets, } _UK_SIMULATION_WORKER_OPTIONS: dict[str, Any] = { - **_US_SIMULATION_WORKER_OPTIONS, + **UK_SIMULATION_WORKER_RESOURCES, "image": uk_worker_image, - "timeout": UK_SIMULATION_TIMEOUT_SECONDS, + "secrets": report_run_writer_secrets, } @@ -386,9 +378,11 @@ class _V2CountryModelsLoadedBeforeSnapshot: Modal runs ``snap=True`` hooks in every container that isn't restored, and takes the memory snapshot from such a container when it starts it with snapshots enabled; every container restored from the snapshot starts with - the loaded models in memory. ``snap=False`` hooks run after each restore. - Observability is configured per call instead, after the restore, so each - restored container reports its own process identity. + the loaded models in memory. The US workers' hook also runs one warm-up + calculation in a container Modal snapshots (``v2_snapshot_warm_up``). + ``snap=False`` hooks run after each restore. Observability is configured + per call instead, after the restore, so each restored container reports + its own process identity. """ # The image's own country: a failed import of one country's models can't @@ -398,10 +392,11 @@ class _V2CountryModelsLoadedBeforeSnapshot: @modal.enter(snap=True) def load_country_models(self) -> None: - """Load the class's country models, and for the US the SPM capability.""" + """Load the country models, and for the US the SPM capability and a warm-up.""" with contextlib.suppress(Exception): _CONTAINER_CALLS.record_snapshot_hook() preload_country_models(self.snapshot_countries) + warm_up_first_us_calculation(self.snapshot_countries) @modal.enter(snap=False) def reseed_random_after_restore(self) -> None: diff --git a/projects/policyengine-simulation-executor/src/modal/v2_snapshot_warm_up.py b/projects/policyengine-simulation-executor/src/modal/v2_snapshot_warm_up.py new file mode 100644 index 000000000..9b61e6cc3 --- /dev/null +++ b/projects/policyengine-simulation-executor/src/modal/v2_snapshot_warm_up.py @@ -0,0 +1,319 @@ +"""Run one calculation before Modal takes the v2 US workers' memory snapshot. + +A process's first calculation for a year does work that its later +calculations for that year reuse: mostly building the US parameter values at +the calculation date and the SPM threshold amounts, about 20 s of the first +calculation when profiled on Modal ``testing`` (2026-11-25, in the +run_simulation app). A later request can reuse only what the packages keep +for the whole process, such as the module-level parameter tree that every +simulation's baseline branch shares (``share_spm_policy`` in policyengine-us), +spm-calculator's threshold tables and the modules the calculation imports; a +request's reform builds its own parameter tree. The v2 workers' snapshot hook +otherwise only loads the models. So ``SimulationSegmentWorkerUS`` and +``SimulationWorkerUS`` in ``src/modal/v2_app.py`` run +:func:`warm_up_first_us_calculation` in their ``@modal.enter(snap=True)`` +hook, after the preload, and every container restored from the snapshot +starts with that work done for the warm-up year. +The run_simulation app's workers run the same kind of warm-up, which made +restored containers' first calculation 11 to 16 s faster on Modal +``testing``, with identical results; this one hasn't been measured. + +The warm-up calculates one segment as a segmented national run's child +receives it: the reform side of the first region group whose current-law +baseline the v2 cache precomputes, for the first precompute year, under a +small reform. A v2 segment calculates one simulation, so a reform segment +always calculates, and never loads or computes the precomputed current-law +baseline, whatever the cache holds. (Its own calculation still reads +current-law values through its baseline branch, which is what builds the +module-level parameter values a later call reuses.) It runs only where it is +safe before a snapshot, and only where Modal takes one: + +- **Only in a US worker container Modal snapshots.** Modal runs the hook in + every container that isn't restored, and takes a snapshot only where its + worker set ``MODAL_ENABLE_SNAP_RESTORE`` to ``1``. Elsewhere the warm-up + would delay the container's first call by about as long as a calculation. + The UK worker's hook calls it too, and it does nothing there: the UK image + holds no prebuilt UK year file, so a UK warm-up would build its dataset + before the snapshot. +- **No connection and no Secret.** It runs only when the US models were + preloaded, since importing them again could fetch the data release + manifest again, and when the image's prebuilt folder holds the group's + year file in a form .py reuses, looked up as a run looks it up, so nothing + is downloaded or built from source. The calculation runs inside + ``skip_gcp_credential_setup``, so the v2 calculation's Google Cloud + credential setup reads no Modal Secret and writes no credentials file. + (The preload before it already reads the Hugging Face token and fetches + the data release manifest, as ``country_model_preload`` says.) +- **No telemetry.** It configures no observability and calculates with no + runtime, so it writes no operation record or span, and the container's + first call is still number 1 (``ContainerCalls`` in + ``src/modal/container_calls.py``). +- **Nothing left for a request.** It removes the simulation it added to + .py's in-process cache and the output file it saved in the prebuilt + folder, and the memory warnings .py's cache marked as given + (``_removing_what_the_calculation_leaves``), so a later call finds the + image's files as it would without the warm-up. It then collects garbage, + also after a failure. What stays is what the packages keep for the whole + process. +- **Never fatal.** A failure or skip logs a warning, and the container + starts as it would without the warm-up. The executor modules it uses are + looked up when it runs, not when ``v2_app.py`` imports this module, so a + move or rename in them costs only the warm-up. + +The run_simulation app's warm-up (``src/modal/snapshot_warm_up.py``) does the +same for that app's workers. This module shares no code with it, since that +app is to be removed while this one stays. +""" + +from __future__ import annotations + +import contextlib +import gc +import logging +import os +import sys +import time +from pathlib import Path +from typing import TYPE_CHECKING + +from src.modal.country_model_preload import COUNTRY_MODEL_MODULES + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator + + from policyengine_simulation_contract.stage12_execution import ( + PlannedSimulationExecutionInput, + ) + from policyengine_simulation_executor.stage12_runtime.segment_contracts import ( + Stage12SegmentInput, + ) + +logger = logging.getLogger(__name__) + +# Modal's worker sets this to "1" in the containers it takes a snapshot from +# or restores (``run_function`` in modal/_container_entrypoint.py, Modal +# 1.6.4). Restored containers don't run the snapshot hook. +SNAPSHOT_FLAG_ENV_NAME = "MODAL_ENABLE_SNAP_RESTORE" +WARM_UP_COUNTRY = "us" +# The reform makes the warm-up calculate a reform simulation, as a request +# does: the Child Tax Credit's base amount, raised to $2,500. +WARM_UP_REFORM_PARAMETER = "gov.irs.credits.ctc.amount.base[0].amount" +WARM_UP_REFORM_VALUE = 2500 + + +class _WarmUpUnsafeError(Exception): + """The warm-up can't run safely before the snapshot; the message says why.""" + + +def warm_up_first_us_calculation(countries: Iterable[str]) -> None: + """Run the warm-up calculation in a US worker container Modal snapshots. + + ``countries`` are the worker class's ``snapshot_countries``. Does nothing + for a worker without the US, or in a container Modal takes no snapshot + from. Nothing here may stop a container from starting: a failure or skip + logs a warning, and each container's first calculation then does its + one-time work itself, as before. + """ + if WARM_UP_COUNTRY not in tuple(countries): + return + if os.environ.get(SNAPSHOT_FLAG_ENV_NAME) != "1": + return + try: + _calculate_unless_unsafe() + except _WarmUpUnsafeError as unsafe: + logger.warning( + "Warm-up calculation skipped, so each restored container's first " + "calculation does its one-time work itself: %s", + unsafe, + ) + except Exception: # noqa: BLE001 # the warm-up only makes first calls faster + logger.warning( + "Warm-up calculation failed; each restored container's first " + "calculation does its one-time work itself", + exc_info=True, + ) + finally: + # Free what the calculation allocated before Modal takes the snapshot. + # policyengine-core's simulation objects refer to each other, so only + # a collection frees them, and after a failure only once the handled + # exception, whose traceback holds the calculation's frames, is gone. + gc.collect() + + +def warm_up_segment_input() -> Stage12SegmentInput: + """Return the warm-up's segment: a precomputed group's reform, first year. + + The group is the first whose current-law baseline the v2 cache + precomputes for the country's first precompute year, which is also a + segmented national run's first segment. Its simulation is the + precompute's planned reform side for that group, given the warm-up's + reform and planned again as a report run's reform child with that policy + is planned. + """ + from policyengine_simulation_contract.stage12_execution import ( # noqa: PLC0415 # imported here so a move of the planning code costs only the warm-up, never the app's import + SimulationExecutionInput, + ) + from policyengine_simulation_executor.stage12_cache import ( # noqa: PLC0415 # as above + precompute_planning, + ) + from policyengine_simulation_executor.stage12_cache.cache_levels import ( # noqa: PLC0415 # as above + cache_baseline_levels, + ) + from policyengine_simulation_executor.stage12_runtime import ( # noqa: PLC0415 # as above + output_planning, + ) + from policyengine_simulation_executor.stage12_runtime.segment_contracts import ( # noqa: PLC0415 # as above + Stage12SegmentInput, + ) + + baseline_levels = cache_baseline_levels(WARM_UP_COUNTRY) + if not baseline_levels: + msg = f"the v2 cache precomputes no {WARM_UP_COUNTRY} baseline" + raise _WarmUpUnsafeError(msg) + prebuilt = precompute_planning.country_prebuilt(WARM_UP_COUNTRY) + year = prebuilt.years[0] + first_target = prebuilt.handlers[baseline_levels[0]].baseline_targets(year)[0] + group = tuple(first_target.request["region_group"]) + template = precompute_planning.scoped_planned_simulation(year, group, reform=True) + reform = SimulationExecutionInput.model_validate( + { + **template.model_dump(mode="json", exclude={"output_plan"}), + "policy": { + WARM_UP_REFORM_PARAMETER: { + f"{year}-01-01.2100-12-31": WARM_UP_REFORM_VALUE + } + }, + } + ) + planned = output_planning.plan_simulation_input( + reform, output_planning.resolve_simulation_output_plan(reform) + ) + return Stage12SegmentInput(simulation=planned, segment_index=0, region_codes=group) + + +def _calculate_unless_unsafe() -> None: + """Run the warm-up calculation; raise ``_WarmUpUnsafeError`` when it isn't safe.""" + not_preloaded = [ + module_name + for module_name in COUNTRY_MODEL_MODULES[WARM_UP_COUNTRY] + if module_name not in sys.modules + ] + if not_preloaded: + msg = f"the preload didn't import {', '.join(not_preloaded)}" + raise _WarmUpUnsafeError(msg) + from policyengine_simulation_executor import ( # noqa: PLC0415 # resolved per call so tests can replace calculate_segment; loaded in the worker container, not at deploy time + stage12_runtime, + ) + from policyengine_simulation_executor.gcp_credentials import ( # noqa: PLC0415 # as above + skip_gcp_credential_setup, + ) + + segment = warm_up_segment_input() + prebuilt_folder = _prebuilt_folder_with_year_file(segment) + started = time.monotonic() + with ( + skip_gcp_credential_setup(), + _removing_what_the_calculation_leaves(prebuilt_folder), + ): + # Sent as the fan-out sends a segment to its worker. + stage12_runtime.calculate_segment( + segment.model_dump(mode="python"), runtime=None + ) + logger.info( + "Warm-up calculation of the reform for region group %s in %s finished in %.1fs", + "+".join(segment.region_codes), + segment.simulation.year, + time.monotonic() - started, + ) + + +def _scoped_simulation(segment: Stage12SegmentInput) -> PlannedSimulationExecutionInput: + """Return the segment's simulation as ``calculate_segment`` scopes it.""" + options = { + key: value + for key, value in segment.simulation.options.items() + if key != "segmented" + } + options["region_group"] = list(segment.region_codes) + return segment.simulation.model_copy(update={"options": options}) + + +def _prebuilt_folder_with_year_file(segment: Stage12SegmentInput) -> Path: + """Return the prebuilt folder holding the segment's year file. + + Looked up as ``calculate_simulation_frames`` looks it up for the scoped + segment: the region and dataset resolution, then the image's + prebuilt-folder lookup, which finds no folder for a year file the image + lacks or .py wouldn't reuse. Raises ``_WarmUpUnsafeError`` then: the + calculation would build the year file from its source, which it may + download. + """ + from policyengine_simulation_executor.simulation_runtime import ( # noqa: PLC0415 # resolved per call so tests can patch simulation_runtime + _country_module, + _prebuilt_folder, + _resolve_dataset_selection, + resolve_region, + ) + from policyengine_simulation_executor.stage12_runtime.local_area_datasets import ( # noqa: PLC0415 # see warm_up_segment_input + dataset_region, + local_area_dataset_name, + ) + from policyengine_simulation_executor.stage12_runtime.worker_inputs import ( # noqa: PLC0415 # as above + simulation_runtime_params, + ) + + simulation = _scoped_simulation(segment) + country = simulation.geography.country + params = simulation_runtime_params(simulation) + region = resolve_region( + country_module=_country_module(country), country=country, params=params + ) + selection = _resolve_dataset_selection( + params, + region_resolution=dataset_region(region, local_area_dataset_name(simulation)), + ) + prebuilt = _prebuilt_folder(country, region, selection, simulation.year) + if prebuilt is None: + msg = ( + "the image holds no prebuilt year file .py would reuse for region " + f"group {'+'.join(segment.region_codes)} in {simulation.year}" + ) + raise _WarmUpUnsafeError(msg) + return Path(prebuilt.folder) + + +@contextlib.contextmanager +def _removing_what_the_calculation_leaves(output_folder: Path) -> Iterator[None]: + """Remove what a calculation adds to .py's cache and the folder, even if it fails. + + .py's ``Simulation.ensure()`` caches the reform in the process under a new + random ID and saves its output beside the year file it loaded, in + ``output_folder``, as ``.h5``. Left there, both would go into + the snapshot, taking memory and disk in every restored container. Adding + to the cache also marks each memory threshold the process has passed + (8, 16 and 32 GB) as warned about, once per process; the marks the + calculation added are removed too, so a restored container's own calls + warn when they pass a threshold. + """ + from policyengine.core import ( # noqa: PLC0415 # resolved per call so tests can patch policyengine's cache module + cache as policyengine_cache, + ) + from policyengine.core.simulation import ( # noqa: PLC0415 # resolved per call so tests can patch policyengine's simulation cache + _cache as simulation_cache, + ) + + cached_before = set(simulation_cache._cache) # noqa: SLF001 # policyengine's LRUCache has no public listing or remove + warned_before = set(policyengine_cache._warned_thresholds) # noqa: SLF001 # policyengine's cache has no public way to reset one warning + outputs_before = set(output_folder.glob("*.h5")) + try: + yield + finally: + for storage_id in [ + storage_id + for storage_id in simulation_cache._cache # noqa: SLF001 # as above + if storage_id not in cached_before + ]: + simulation_cache._cache.pop(storage_id, None) # noqa: SLF001 # as above + policyengine_cache._warned_thresholds.intersection_update(warned_before) # noqa: SLF001 # as above + for output in set(output_folder.glob("*.h5")) - outputs_before: + output.unlink(missing_ok=True) diff --git a/projects/policyengine-simulation-executor/src/modal/v2_worker_resources.py b/projects/policyengine-simulation-executor/src/modal/v2_worker_resources.py new file mode 100644 index 000000000..bdad7d770 --- /dev/null +++ b/projects/policyengine-simulation-executor/src/modal/v2_worker_resources.py @@ -0,0 +1,39 @@ +"""CPU, memory, time and container limits of the v2 app's simulation workers. + +``src/modal/v2_app.py`` gives each simulation worker class, and the plain +function of the same name kept for callers on older code, these settings +together with its image and secrets. +""" + +from __future__ import annotations + +from typing import Any + +from policyengine_simulation_executor.stage12_timeouts import ( + UK_SIMULATION_TIMEOUT_SECONDS, + US_SIMULATION_TIMEOUT_SECONDS, +) + +SEGMENT_WORKER_RESOURCES: dict[str, Any] = { + "cpu": 8.0, + "memory": 32768, + "timeout": 3600, + "retries": 0, + # Every segment of every US simulation call that may run at once: a + # segment queued behind this limit counts against its caller's wait. + "max_containers": 1000, +} +US_SIMULATION_WORKER_RESOURCES: dict[str, Any] = { + "cpu": 8.0, + "memory": 32768, + "timeout": US_SIMULATION_TIMEOUT_SECONDS, + "retries": 0, + # Both simulations of every coordinator call that may run at once. The + # simulation runs and cliff calculations the simulation service starts + # directly share the same containers. + "max_containers": 50, +} +UK_SIMULATION_WORKER_RESOURCES: dict[str, Any] = { + **US_SIMULATION_WORKER_RESOURCES, + "timeout": UK_SIMULATION_TIMEOUT_SECONDS, +} diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/gcp_credentials.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/gcp_credentials.py index b4989df5e..c37009620 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/gcp_credentials.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/gcp_credentials.py @@ -7,6 +7,7 @@ import logging import os import tempfile +from contextvars import ContextVar from typing import TYPE_CHECKING from policyengine_simulation_observability.stages import ANNUAL_IMPACT_STAGES, Stage @@ -21,6 +22,11 @@ # Credential-adjacent environment values are cut to this many characters. _ENV_VALUE_PREVIEW_CHARS = 50 +# True inside ``skip_gcp_credential_setup``: ``setup_gcp_credentials`` then +# reads and writes nothing. +_CREDENTIAL_SETUP_SKIPPED: ContextVar[bool] = ContextVar( + "gcp_credential_setup_skipped", default=False +) def _normalize_credentials_blob(creds_json: str) -> str: @@ -42,6 +48,23 @@ def _normalize_credentials_blob(creds_json: str) -> str: return creds_json +@contextlib.contextmanager +def skip_gcp_credential_setup() -> Iterator[None]: + """Make ``setup_gcp_credentials`` read and write nothing inside this block. + + The v2 workers' snapshot warm-up (``src/modal/v2_snapshot_warm_up.py``) + calculates from files in the image only, and nothing may read a Modal + Secret before Modal takes the snapshot: a value read then would be the + snapshot's in every restored container. The setup works as usual again + after the block, also when the block raises. + """ + token = _CREDENTIAL_SETUP_SKIPPED.set(True) + try: + yield + finally: + _CREDENTIAL_SETUP_SKIPPED.reset(token) + + @contextlib.contextmanager def setup_gcp_credentials( runtime: ObservabilityRuntime | None = None, @@ -54,8 +77,12 @@ def setup_gcp_credentials( on exit. This runs as a context manager to guarantee cleanup even if the caller raises mid-simulation; the previous fire-and-forget ``tempfile.mkstemp`` path leaked credential material on disk every - time a container served a request. + time a container served a request. Inside ``skip_gcp_credential_setup`` + it reads no environment variable, writes no file and opens no span. """ + if _CREDENTIAL_SETUP_SKIPPED.get(): + yield + return previous = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS") creds_file = None with contextlib.ExitStack() as credentials_file_stack: diff --git a/projects/policyengine-simulation-executor/tests/environment_reads.py b/projects/policyengine-simulation-executor/tests/environment_reads.py new file mode 100644 index 000000000..11b101ffc --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/environment_reads.py @@ -0,0 +1,58 @@ +"""Record which environment variables code reads, for the snapshot warm-up tests. + +Nothing may read a Modal Secret before Modal takes a worker's memory snapshot, +so the run_simulation and v2 warm-up tests replace ``os.environ`` with +``EnvironmentReadRecorder`` and compare the names read with +``SECRET_ENVIRONMENT_NAMES``. +""" + +from __future__ import annotations + +from collections.abc import Iterator, MutableMapping + +# Modal Secrets the workers have, under every name the code reads them by: +# Google Cloud credentials and the Hugging Face token, and for the v2 workers +# the runtime Secret (``stage12-evaluation-runtime``: database and buckets) +# and the Modal worker role's database Secret. +SECRET_ENVIRONMENT_NAMES = { + "GOOGLE_APPLICATION_CREDENTIALS_JSON", + "GCP_CREDENTIALS_JSON", + "GOOGLE_CREDENTIALS", + "SERVICE_ACCOUNT_JSON", + "HUGGING_FACE_TOKEN", + "HF_TOKEN", + "HUGGINGFACE_HUB_TOKEN", + "STAGE12_DATABASE_URL", + "STAGE12_ARTIFACT_BUCKET", + "STAGE12_CACHE_BUCKET", + "V2_SIMULATION_OUTPUT_BUCKET", + "MODAL_WORKER_DATABASE_URL", +} + + +class EnvironmentReadRecorder(MutableMapping): + """Wraps ``os.environ`` and records the name of every variable read.""" + + def __init__(self, environment: MutableMapping) -> None: + self.environment = environment + self.names_read: set[str] = set() + + def __getitem__(self, name: str) -> str: + self.names_read.add(name) + return self.environment[name] + + def __setitem__(self, name: str, value: str) -> None: + self.environment[name] = value + + def __delitem__(self, name: str) -> None: + del self.environment[name] + + def __iter__(self) -> Iterator[str]: + # Listing the variables reads them all, as the credential setup's + # log of Google-related variables does. + for name in list(self.environment): + self.names_read.add(name) + yield name + + def __len__(self) -> int: + return len(self.environment) diff --git a/projects/policyengine-simulation-executor/tests/test_gcp_credentials.py b/projects/policyengine-simulation-executor/tests/test_gcp_credentials.py index 1b143f04e..e2c265cef 100644 --- a/projects/policyengine-simulation-executor/tests/test_gcp_credentials.py +++ b/projects/policyengine-simulation-executor/tests/test_gcp_credentials.py @@ -7,8 +7,11 @@ from pathlib import Path import pytest +from environment_reads import EnvironmentReadRecorder +from policyengine_simulation_executor import gcp_credentials from policyengine_simulation_executor.gcp_credentials import ( _normalize_credentials_blob, + skip_gcp_credential_setup, ) from policyengine_simulation_executor.simulation_runtime import setup_gcp_credentials @@ -86,3 +89,54 @@ def test_normalize_credentials_blob_unwraps_double_escaped(): def test_normalize_credentials_blob_reraises_on_unparseable(): with pytest.raises(json.JSONDecodeError): _normalize_credentials_blob("not even close to json") + + +def test_skipped_credential_setup_reads_no_variable_and_writes_no_file( + monkeypatch, observability_runtime +): + # The v2 snapshot warm-up calculates from the image's files only, and + # nothing before the snapshot may read a Secret. + monkeypatch.setenv( + "GOOGLE_APPLICATION_CREDENTIALS_JSON", json.dumps({"type": "service_account"}) + ) + monkeypatch.delenv("GOOGLE_APPLICATION_CREDENTIALS", raising=False) + + def refuse_temporary_file(*_args, **_kwargs): + msg = "a skipped credential setup must write no credentials file" + raise AssertionError(msg) + + monkeypatch.setattr( + gcp_credentials.tempfile, "NamedTemporaryFile", refuse_temporary_file + ) + environment = EnvironmentReadRecorder(os.environ) + monkeypatch.setattr(os, "environ", environment) + + with skip_gcp_credential_setup(), setup_gcp_credentials(observability_runtime): + names_read_inside = set(environment.names_read) + credentials_path_inside = environment.environment.get( + "GOOGLE_APPLICATION_CREDENTIALS" + ) + + assert names_read_inside == set() + assert credentials_path_inside is None + assert environment.names_read == set() + + +def test_credential_setup_writes_credentials_again_after_a_skipped_block( + monkeypatch, observability_runtime +): + monkeypatch.setenv( + "GOOGLE_APPLICATION_CREDENTIALS_JSON", json.dumps({"type": "service_account"}) + ) + monkeypatch.delenv("GOOGLE_APPLICATION_CREDENTIALS", raising=False) + + def fail_inside_skipped_block() -> None: + with skip_gcp_credential_setup(): + msg = "warm-up failed" + raise RuntimeError(msg) + + with pytest.raises(RuntimeError, match="warm-up failed"): + fail_inside_skipped_block() + + with setup_gcp_credentials(observability_runtime): + assert os.environ.get("GOOGLE_APPLICATION_CREDENTIALS") is not None diff --git a/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py b/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py index cff0780a0..27ad2b358 100644 --- a/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py +++ b/projects/policyengine-simulation-executor/tests/test_snapshot_warm_up.py @@ -15,13 +15,13 @@ import logging import os import sys -from collections.abc import Iterator, MutableMapping from types import ModuleType, SimpleNamespace from typing import TYPE_CHECKING from uuid import uuid4 import pytest from conftest import NoOpObservabilityRuntime +from environment_reads import SECRET_ENVIRONMENT_NAMES, EnvironmentReadRecorder from fixtures.fake_modal import install_fake_modal from policyengine_observability.runtime import ObservabilityRuntime from policyengine_simulation_executor import precompute_planning, simulation_runtime @@ -53,17 +53,6 @@ "_emit_microdata": True, } US_MODEL_MODULES = ("policyengine_us", "policyengine.tax_benefit_models.us") -# Modal Secrets the workers have: Google Cloud credentials and the Hugging -# Face token, under every name the code reads them by. -SECRET_ENVIRONMENT_NAMES = { - "GOOGLE_APPLICATION_CREDENTIALS_JSON", - "GCP_CREDENTIALS_JSON", - "GOOGLE_CREDENTIALS", - "SERVICE_ACCOUNT_JSON", - "HUGGING_FACE_TOKEN", - "HF_TOKEN", - "HUGGINGFACE_HUB_TOKEN", -} class _PolicyEngineLikeCalculation: @@ -112,34 +101,6 @@ def shutdown(self) -> None: return None -class _EnvironmentReadRecorder(MutableMapping): - """Wraps ``os.environ`` and records the name of every variable read.""" - - def __init__(self, environment: MutableMapping) -> None: - self.environment = environment - self.names_read: set[str] = set() - - def __getitem__(self, name: str) -> str: - self.names_read.add(name) - return self.environment[name] - - def __setitem__(self, name: str, value: str) -> None: - self.environment[name] = value - - def __delitem__(self, name: str) -> None: - del self.environment[name] - - def __iter__(self) -> Iterator[str]: - # Listing the variables reads them all, as the credential setup's - # log of Google-related variables does. - for name in list(self.environment): - self.names_read.add(name) - yield name - - def __len__(self) -> int: - return len(self.environment) - - @pytest.fixture def warm_up_module(): return importlib.import_module("src.modal.snapshot_warm_up") @@ -384,7 +345,7 @@ def refuse(*_args, **_kwargs): # Records the warm-up's own reads, the real group target's included. The # calculation and the lookups that need the model are replaced here, so # what they read is checked by reading their code instead. - environment = _EnvironmentReadRecorder(os.environ) + environment = EnvironmentReadRecorder(os.environ) monkeypatch.setattr(os, "environ", environment) with caplog.at_level(logging.WARNING, logger=warm_up_module.__name__): diff --git a/projects/policyengine-simulation-executor/tests/test_v2_container_start.py b/projects/policyengine-simulation-executor/tests/test_v2_container_start.py index d80b83d23..016af622c 100644 --- a/projects/policyengine-simulation-executor/tests/test_v2_container_start.py +++ b/projects/policyengine-simulation-executor/tests/test_v2_container_start.py @@ -94,8 +94,10 @@ def v2_app(monkeypatch): sys.modules.pop("src.modal.v2_images", None) sys.modules.pop("src.modal.v2_app", None) app = importlib.import_module("src.modal.v2_app") - # The real preload imports the country's models. + # The real preload imports the country's models, and the real warm-up + # calculates a region group (tests/test_v2_snapshot_warm_up.py). monkeypatch.setattr(app, "preload_country_models", lambda _countries: None) + monkeypatch.setattr(app, "warm_up_first_us_calculation", lambda _countries: None) monkeypatch.setattr(app.modal, "current_function_call_id", lambda: "fc-call") _replace_worker_jobs(monkeypatch, lambda: WORKER_RESULT) yield app diff --git a/projects/policyengine-simulation-executor/tests/test_v2_snapshot_warm_up.py b/projects/policyengine-simulation-executor/tests/test_v2_snapshot_warm_up.py new file mode 100644 index 000000000..28a1a6929 --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_v2_snapshot_warm_up.py @@ -0,0 +1,842 @@ +"""The warm-up calculation the v2 US workers run before their memory snapshot. + +A process's first calculation for a year does one-time work that later +calculations reuse. The v2 US workers' snapshot hook calculates one segment +of a region group whose current-law baseline the v2 cache precomputes, for +the first precompute year, under a small reform, so containers restored from +the snapshot start with that work done. These tests replace the segment +calculation with a fake that touches .py's in-process simulation cache and +the prebuilt folder as a real one does, and replace the planning and the +region, dataset and prebuilt-folder lookups, which need the US model. One +test runs the real v2 calculation up to its dataset load. +""" + +from __future__ import annotations + +import gc +import importlib +import logging +import os +import socket +import sys +import weakref +from types import ModuleType, SimpleNamespace +from typing import TYPE_CHECKING +from uuid import uuid4 + +import pytest +from conftest import NoOpObservabilityRuntime +from environment_reads import SECRET_ENVIRONMENT_NAMES, EnvironmentReadRecorder +from fixtures.fake_modal import install_fake_modal +from policyengine_observability.runtime import ObservabilityRuntime +from policyengine_simulation_contract.stage12_execution import ( + EntityOutputPlan, + PlannedSimulationExecutionInput, + ReportAggregate, + ReportOutputRequirements, + SimulationRole, + Stage12OutputPlan, +) +from policyengine_simulation_executor import simulation_runtime, stage12_runtime +from policyengine_simulation_executor.stage12_cache import levels +from policyengine_simulation_executor.stage12_cache import ( + precompute_planning as v2_precompute_planning, +) +from policyengine_simulation_executor.stage12_cache.cache_levels import ( + cache_baseline_levels, +) +from policyengine_simulation_executor.stage12_cache.partition import US_REGION_GROUPS +from policyengine_simulation_executor.stage12_runtime import output_planning +from policyengine_simulation_executor.stage12_runtime.segment_contracts import ( + Stage12SegmentInput, +) +from stage12_runtime_support import bundle_provenance, planned_simulation + +if TYPE_CHECKING: + from pathlib import Path + + from policyengine.core.cache import LRUCache + +# The default dataset's prebuilt folder and its 2026 year file, as the +# precompute names them. +PREBUILT_FOLDER = "prebuilt/us/populace_us_2024/all" +PREBUILT_YEAR_FILENAME = "populace_us_2024_year_2026.h5" +SNAPSHOT_TASK_ID = "ta-01SNAPSHOTTING" +US_MODEL_MODULES = ("policyengine_us", "policyengine.tax_benefit_models.us") +# The run_simulation app's own modules, which the v2 app must not need: that +# app is to be removed while the v2 app stays. +RUN_SIMULATION_APP_MODULES = ( + "src.modal.app", + "src.modal.snapshot_warm_up", + "src.modal.segmented_national", + "src.modal.precompute_app", + "src.modal._image_setup", +) +CREDENTIALS_JSON = '{"type": "service_account", "project_id": "warm-up-test"}' +# The plan the reform's stored plan resolves to here, unlike the template's. +REFORM_OUTPUT_PLAN = Stage12OutputPlan( + country="us", + requirements=ReportOutputRequirements( + aggregates=tuple(ReportAggregate), + include_cliff_impacts=False, + labor_supply_response_active=False, + ), + entities=( + EntityOutputPlan( + entity="household", + materialized_variables=( + "household_id", + "household_net_income", + "household_tax", + ), + ), + EntityOutputPlan( + entity="person", + materialized_variables=("age", "household_id", "person_id"), + ), + ), +) +# A segment the container calculates after its snapshot hook: another region +# group's reform, as a segmented national run's child receives it. +LATER_SEGMENT = {"simulation": {"role": "reform"}, "segment_index": 3} + + +class _SegmentResult: + """Stands in for a segment's artifact descriptor.""" + + def __init__(self, result: dict) -> None: + self.result = result + + def model_dump(self, *, mode: str) -> dict: + assert mode == "python" + return self.result + + +class _PolicyEngineLikeSegmentCalculation: + """Stands in for ``calculate_segment``, leaving what a real calculation leaves. + + A real calculation sets up Google Cloud credentials first. Its reform's + ``ensure()`` then adds the reform to .py's in-process cache under a new + random ID, and saves its output beside the year file, in the prebuilt + folder. Each call returns what it found in the cache and that folder + before it calculated, which a real call's result depends on. + """ + + def __init__(self, cache: LRUCache, output_folder: Path) -> None: + self.cache = cache + self.output_folder = output_folder + self.payloads: list[dict] = [] + self.runtimes: list[object] = [] + self.credential_paths: list[str | None] = [] + + def __call__(self, payload: dict, *, runtime=None) -> _SegmentResult: + self.payloads.append(payload) + self.runtimes.append(runtime) + with simulation_runtime.setup_gcp_credentials(): + self.credential_paths.append( + os.environ.get("GOOGLE_APPLICATION_CREDENTIALS") + ) + state_seen = { + "cached_simulations": sorted(self.cache._cache), + "output_folder_files": sorted( + path.name for path in self.output_folder.iterdir() + ), + } + reform_storage_id = str(uuid4()) + self.cache.add(reform_storage_id, SimpleNamespace(role="reform")) + (self.output_folder / f"{reform_storage_id}.h5").write_bytes(b"reform output") + return _SegmentResult({"state_seen": state_seen}) + + +class _RecordingRuntime(NoOpObservabilityRuntime): + """A worker call's runtime that keeps the attributes set on its operation.""" + + def __init__(self) -> None: + self.attributes: dict[str, object] = {} + + def set_context(self, **attributes: object) -> None: + self.attributes.update(attributes) + + def shutdown(self) -> None: + return None + + +class _StoppedAfterDatasetLoadError(Exception): + """Raised by a stubbed dataset load, to stop a real calculation there.""" + + +@pytest.fixture +def warm_up_module(): + return importlib.import_module("src.modal.v2_snapshot_warm_up") + + +@pytest.fixture +def snapshotted_container(monkeypatch): + """Act as a container Modal snapshots, with the US models preloaded.""" + monkeypatch.setenv("MODAL_ENABLE_SNAP_RESTORE", "1") + monkeypatch.setenv("MODAL_TASK_ID", SNAPSHOT_TASK_ID) + for module_name in US_MODEL_MODULES: + monkeypatch.setitem( + sys.modules, + module_name, + sys.modules.get(module_name) or ModuleType(module_name), + ) + + +@pytest.fixture +def planning(monkeypatch): + """Plan the warm-up's segment without the US model, recording each step. + + The template is the precompute's planned reform side for the group, as + ``scoped_planned_simulation`` returns it: no policy, and the group in its + options. Returns what was planned. + """ + planned = SimpleNamespace(templates=[], resolved_for=[]) + + def scoped_planned_simulation(year, group, *, reform=False, country="us"): + planned.templates.append( + {"year": year, "group": tuple(group), "reform": reform, "country": country} + ) + role = SimulationRole.REFORM if reform else SimulationRole.BASELINE + return PlannedSimulationExecutionInput.model_validate( + { + **planned_simulation(role).model_dump(mode="json"), + "policy": {}, + "year": year, + "options": {"region_group": list(group)}, + } + ) + + def resolve_simulation_output_plan(simulation, **_options): + planned.resolved_for.append(simulation) + return REFORM_OUTPUT_PLAN + + monkeypatch.setattr( + v2_precompute_planning, "scoped_planned_simulation", scoped_planned_simulation + ) + monkeypatch.setattr( + output_planning, + "resolve_simulation_output_plan", + resolve_simulation_output_plan, + ) + return planned + + +@pytest.fixture +def prebuilt_image(tmp_path, monkeypatch): + """Create the image's prebuilt folder, and answer a run's lookups as in the image. + + The region and dataset resolution and ``levels.prebuilt_dataset_folder``, + which the warm-up's check and the calculation both call, record what they + are asked. The folder lookup answers as the real one does: the folder + when it holds the year file, and None otherwise, which is also its answer + for a year file .py wouldn't reuse. + """ + data_folder = tmp_path / "data" + prebuilt_folder = data_folder / PREBUILT_FOLDER + prebuilt_folder.mkdir(parents=True) + (prebuilt_folder / PREBUILT_YEAR_FILENAME).write_bytes(b"prebuilt year file") + monkeypatch.setenv("POLICYENGINE_DATA_FOLDER", str(data_folder)) + group_region = SimpleNamespace( + code="region_group/state/hi+state/ia+state/wi", + scoping_strategy="group row filter", + state_code=None, + dataset_reference=None, + ) + # The dataset the template's provenance names, so a real calculation's + # provenance check passes. + named_dataset = bundle_provenance().dataset + default_dataset = simulation_runtime.DatasetSelection( + named_dataset.identity, named_dataset.uri, is_default=True + ) + image = SimpleNamespace( + data_folder=data_folder, + prebuilt_folder=prebuilt_folder, + group_region=group_region, + default_dataset=default_dataset, + regions_resolved=[], + dataset_selections=[], + folder_lookups=[], + ) + + def resolve_region(*, country_module, country, params): + image.regions_resolved.append((country, dict(params))) + return group_region + + def resolve_dataset_selection(params, *, region_resolution): + image.dataset_selections.append((dict(params), region_resolution)) + return default_dataset + + def prebuilt_folder_lookup(run, data_folder): + image.folder_lookups.append((run, data_folder)) + if not (prebuilt_folder / PREBUILT_YEAR_FILENAME).is_file(): + return None + return levels.PrebuiltFolder(folder=str(prebuilt_folder), dataset_source=None) + + monkeypatch.setattr(simulation_runtime, "_country_module", lambda country: country) + monkeypatch.setattr(simulation_runtime, "resolve_region", resolve_region) + monkeypatch.setattr( + simulation_runtime, "_resolve_dataset_selection", resolve_dataset_selection + ) + monkeypatch.setattr(levels, "prebuilt_dataset_folder", prebuilt_folder_lookup) + return image + + +@pytest.fixture +def simulation_cache(monkeypatch): + """Start .py's in-process simulation cache empty, as in a new container.""" + from policyengine.core import simulation as policyengine_simulation + from policyengine.core.cache import LRUCache + + cache = LRUCache(max_size=100) + monkeypatch.setattr(policyengine_simulation, "_cache", cache) + return cache + + +@pytest.fixture +def calculation(monkeypatch, simulation_cache, prebuilt_image, planning): + """Replace the segment calculation with a .py-like fake.""" + fake_calculation = _PolicyEngineLikeSegmentCalculation( + simulation_cache, prebuilt_image.prebuilt_folder + ) + monkeypatch.setattr(stage12_runtime, "calculate_segment", fake_calculation) + return fake_calculation + + +@pytest.fixture +def credentials_in_environment(monkeypatch): + """Give the container the Google Cloud credentials Secret, as Modal does.""" + monkeypatch.delenv("GOOGLE_APPLICATION_CREDENTIALS", raising=False) + monkeypatch.setenv("GOOGLE_APPLICATION_CREDENTIALS_JSON", CREDENTIALS_JSON) + + +@pytest.fixture +def v2_app(monkeypatch): + """Import the v2 app afresh, as a new container does, without the real preload.""" + install_fake_modal(monkeypatch) + sys.modules.pop("src.modal.v2_images", None) + sys.modules.pop("src.modal.v2_app", None) + app = importlib.import_module("src.modal.v2_app") + monkeypatch.setattr(app, "preload_country_models", lambda _countries: None) + monkeypatch.setattr(app.modal, "current_function_call_id", lambda: "fc-call") + yield app + sys.modules.pop("src.modal.v2_images", None) + sys.modules.pop("src.modal.v2_app", None) + + +def _first_precompute_year() -> int: + prebuilt = levels.prebuilt_for("us") + assert prebuilt is not None + return prebuilt.years[0] + + +def _first_precomputed_group() -> tuple[str, ...]: + """Return the first region group whose baseline the v2 cache precomputes.""" + prebuilt = levels.prebuilt_for("us") + assert prebuilt is not None + [baseline_level] = cache_baseline_levels("us") + [first_target, *_other_targets] = prebuilt.handlers[ + baseline_level + ].baseline_targets(_first_precompute_year()) + return tuple(first_target.request["region_group"]) + + +def _restore_initial_state(cache: LRUCache, folder: Path, files_before: set) -> None: + """Put the cache and the folder back as they were when the container started.""" + cache.clear() + for path in folder.iterdir(): + if path.name not in files_before: + path.unlink() + + +def test_the_v2_snapshot_hook_runs_the_warm_up_after_the_preload_in_every_worker( + v2_app, monkeypatch +): + steps: list[tuple[str, tuple[str, ...]]] = [] + monkeypatch.setattr( + v2_app, + "preload_country_models", + lambda countries: steps.append(("preload", tuple(countries))), + ) + monkeypatch.setattr( + v2_app, + "warm_up_first_us_calculation", + lambda countries: steps.append(("warm-up", tuple(countries))), + ) + + for worker_class_name in ( + "SimulationSegmentWorkerUS", + "SimulationWorkerUS", + "SimulationWorkerUK", + ): + worker = getattr(v2_app, worker_class_name)() + worker.load_country_models() + # Restored containers run only the snapshot=False hook. + worker.reseed_random_after_restore() + + assert steps == [ + ("preload", ("us",)), + ("warm-up", ("us",)), + ("preload", ("us",)), + ("warm-up", ("us",)), + ("preload", ("uk",)), + ("warm-up", ("uk",)), + ] + + +@pytest.mark.usefixtures("snapshotted_container") +def test_only_the_us_workers_calculate_a_warm_up(warm_up_module, calculation): + # The UK image holds no prebuilt UK year file yet, so a UK warm-up would + # build its dataset before the snapshot. + warm_up_module.warm_up_first_us_calculation(("uk",)) + + assert calculation.payloads == [] + + warm_up_module.warm_up_first_us_calculation(("us",)) + + assert len(calculation.payloads) == 1 + + +@pytest.mark.usefixtures("prebuilt_image") +@pytest.mark.parametrize("snapshot_flag", [None, "0", ""]) +def test_a_container_modal_takes_no_snapshot_from_skips_the_warm_up( + warm_up_module, calculation, monkeypatch, snapshot_flag +): + # Modal runs the snapshot hook in every container that isn't restored, + # but takes a snapshot only where its worker set this flag. Elsewhere the + # warm-up would delay the first call by more than it saves. + if snapshot_flag is None: + monkeypatch.delenv("MODAL_ENABLE_SNAP_RESTORE", raising=False) + else: + monkeypatch.setenv("MODAL_ENABLE_SNAP_RESTORE", snapshot_flag) + for module_name in US_MODEL_MODULES: + monkeypatch.setitem( + sys.modules, + module_name, + sys.modules.get(module_name) or ModuleType(module_name), + ) + + warm_up_module.warm_up_first_us_calculation(("us",)) + + assert calculation.payloads == [] + + +@pytest.mark.usefixtures("snapshotted_container") +def test_the_warm_up_calculates_one_reform_segment_of_the_first_precomputed_group( + warm_up_module, calculation, planning, prebuilt_image, caplog +): + with caplog.at_level(logging.WARNING, logger=warm_up_module.__name__): + warm_up_module.warm_up_first_us_calculation(("us",)) + + assert caplog.records == [] + [payload] = calculation.payloads + segment = Stage12SegmentInput.model_validate(payload) + first_year = _first_precompute_year() + first_group = _first_precomputed_group() + # A segmented national run's first child: the first of the 20 groups. + assert first_group == US_REGION_GROUPS[0] + assert segment.segment_index == 0 + assert segment.region_codes == first_group + # The reform side, under a small reform, so it calculates rather than + # loading a precomputed baseline. + assert segment.simulation.role is SimulationRole.REFORM + assert segment.simulation.year == first_year + assert segment.simulation.policy == { + warm_up_module.WARM_UP_REFORM_PARAMETER: { + f"{first_year}-01-01.2100-12-31": warm_up_module.WARM_UP_REFORM_VALUE + } + } + # Planned from the precompute's own reform side for the group, then + # given the plan a report run's reform child with this policy stores. + assert planning.templates == [ + {"year": first_year, "group": first_group, "reform": True, "country": "us"} + ] + [resolved_for] = planning.resolved_for + assert resolved_for.role is SimulationRole.REFORM + assert resolved_for.policy == segment.simulation.policy + assert segment.simulation.output_plan == REFORM_OUTPUT_PLAN + # Its year file is looked up as a run of the segment looks it up. + [(country, params)] = prebuilt_image.regions_resolved + assert country == "us" + assert params["region_group"] == list(first_group) + assert params["time_period"] == str(first_year) + [(run, data_folder)] = prebuilt_image.folder_lookups + assert (run.country, run.region, run.dataset, run.year) == ( + "us", + prebuilt_image.group_region, + prebuilt_image.default_dataset, + first_year, + ) + assert data_folder == str(prebuilt_image.data_folder) + # No runtime, so no span or operation record. + assert calculation.runtimes == [None] + + +@pytest.mark.usefixtures("snapshotted_container") +def test_the_warm_up_skips_with_a_warning_unless_the_image_holds_the_year_file( + warm_up_module, calculation, prebuilt_image, caplog +): + # Without a usable prebuilt year file the dataset would be built from its + # source, which may download it. + (prebuilt_image.prebuilt_folder / PREBUILT_YEAR_FILENAME).unlink() + + with caplog.at_level(logging.WARNING, logger=warm_up_module.__name__): + warm_up_module.warm_up_first_us_calculation(("us",)) + + assert calculation.payloads == [] + assert "Warm-up calculation skipped" in caplog.text + assert "prebuilt year file" in caplog.text + + +@pytest.mark.usefixtures("prebuilt_image") +def test_the_warm_up_skips_with_a_warning_when_the_us_models_were_not_preloaded( + warm_up_module, calculation, monkeypatch, caplog +): + # Importing them again could fetch the data release manifest again. + monkeypatch.setenv("MODAL_ENABLE_SNAP_RESTORE", "1") + for module_name in US_MODEL_MODULES: + monkeypatch.delitem(sys.modules, module_name, raising=False) + + with caplog.at_level(logging.WARNING, logger=warm_up_module.__name__): + warm_up_module.warm_up_first_us_calculation(("us",)) + + assert calculation.payloads == [] + assert "Warm-up calculation skipped" in caplog.text + assert "policyengine.tax_benefit_models.us" in caplog.text + + +@pytest.mark.usefixtures( + "snapshotted_container", "planning", "credentials_in_environment" +) +def test_the_real_v2_calculation_reads_no_secret_and_writes_no_credentials( + warm_up_module, prebuilt_image, monkeypatch, caplog +): + from policyengine_simulation_executor.stage12_runtime import ( + simulation as v2_simulation, + ) + + dataset_loads: list[dict[str, str | None]] = [] + + def load_dataset(_params, *, selection, country_module, data_folder=None): + dataset_loads.append( + { + "credentials_path": os.environ.get("GOOGLE_APPLICATION_CREDENTIALS"), + "data_folder": data_folder, + } + ) + raise _StoppedAfterDatasetLoadError + + connection_attempts: list[object] = [] + + def refuse_connection(_socket, address): + connection_attempts.append(address) + msg = "nothing may connect before the snapshot" + raise OSError(msg) + + monkeypatch.setattr(v2_simulation, "_require_installed_bundle", lambda _input: None) + monkeypatch.setattr(simulation_runtime, "_load_dataset", load_dataset) + monkeypatch.setattr(socket.socket, "connect", refuse_connection) + monkeypatch.setattr(socket.socket, "connect_ex", refuse_connection) + environment = EnvironmentReadRecorder(os.environ) + monkeypatch.setattr(os, "environ", environment) + + with caplog.at_level(logging.WARNING, logger=warm_up_module.__name__): + warm_up_module.warm_up_first_us_calculation(("us",)) + + # The real calculate_segment and calculate_simulation_frames ran up to + # the dataset load, from the image's prebuilt folder, with no credential + # file, no Secret read and no connection. + assert dataset_loads == [ + {"credentials_path": None, "data_folder": str(prebuilt_image.prebuilt_folder)} + ] + assert environment.names_read.isdisjoint(SECRET_ENVIRONMENT_NAMES) + assert "GOOGLE_APPLICATION_CREDENTIALS" not in environment.environment + assert connection_attempts == [] + assert "Warm-up calculation failed" in caplog.text + # The warm-up's check asked exactly what the calculation then asked, so + # the folder it found is the one the calculation reads. + warm_up_region, calculation_region = prebuilt_image.regions_resolved + assert warm_up_region == calculation_region + warm_up_selection, calculation_selection = prebuilt_image.dataset_selections + assert warm_up_selection == calculation_selection + warm_up_lookup, calculation_lookup = prebuilt_image.folder_lookups + assert warm_up_lookup == calculation_lookup + + +@pytest.mark.usefixtures("snapshotted_container", "credentials_in_environment") +def test_the_warm_up_sets_up_no_credentials_and_calls_still_do( + warm_up_module, calculation, monkeypatch +): + def failing_calculation(payload, **options): + calculation(payload, **options) + msg = "the reform parameter is not in this model version" + raise ValueError(msg) + + monkeypatch.setattr(stage12_runtime, "calculate_segment", failing_calculation) + + warm_up_module.warm_up_first_us_calculation(("us",)) + + assert calculation.credential_paths == [None] + # A worker call after the warm-up, even a failed one, writes them. + with simulation_runtime.setup_gcp_credentials(): + assert os.environ.get("GOOGLE_APPLICATION_CREDENTIALS") is not None + + +@pytest.mark.usefixtures("snapshotted_container") +def test_the_warm_up_sends_no_telemetry_and_the_first_call_is_still_number_1( + v2_app, calculation, monkeypatch, caplog +): + # Recorded as well as raised, since the warm-up turns an exception into + # a warning. + refusals: list[str] = [] + + def refuse_observability(*_args, **_kwargs): + # A runtime configured before the snapshot would be shared by every + # restored container, and would export the warm-up's records. + refusals.append("observability configured") + msg = "the warm-up must not configure observability" + raise AssertionError(msg) + + monkeypatch.setattr(v2_app, "init_process_observability", refuse_observability) + monkeypatch.setattr(ObservabilityRuntime, "__init__", refuse_observability) + + worker = v2_app.SimulationSegmentWorkerUS() + with caplog.at_level(logging.WARNING, logger="src.modal.v2_snapshot_warm_up"): + worker.load_country_models() + + assert refusals == [] + assert caplog.records == [] + assert calculation.runtimes == [None] + + call_runtime = _RecordingRuntime() + monkeypatch.setattr( + v2_app, "init_process_observability", lambda **_identity: call_runtime + ) + + worker.run_single_simulation_segment_us(dict(LATER_SEGMENT)) + + assert call_runtime.attributes["container_start"] == "took_snapshot" + assert call_runtime.attributes["container_call_number"] == 1 + + +@pytest.mark.usefixtures("snapshotted_container") +def test_a_failed_warm_up_only_logs_a_warning_and_removes_what_it_left( + warm_up_module, calculation, monkeypatch, caplog +): + files_before = {path.name for path in calculation.output_folder.iterdir()} + + def failing_calculation(payload, **options): + calculation(payload, **options) + msg = "the reform parameter is not in this model version" + raise ValueError(msg) + + monkeypatch.setattr(stage12_runtime, "calculate_segment", failing_calculation) + + with caplog.at_level(logging.WARNING, logger=warm_up_module.__name__): + warm_up_module.warm_up_first_us_calculation(("us",)) + + assert "the reform parameter is not in this model version" in caplog.text + assert len(calculation.cache) == 0 + assert {path.name for path in calculation.output_folder.iterdir()} == files_before + + +@pytest.mark.usefixtures("snapshotted_container", "prebuilt_image") +def test_a_failure_before_the_calculation_only_logs_a_warning( + warm_up_module, calculation, monkeypatch, caplog +): + def unreadable_bundle(*_args, **_kwargs): + msg = "the bundle receipt is unreadable" + raise OSError(msg) + + monkeypatch.setattr( + v2_precompute_planning, "scoped_planned_simulation", unreadable_bundle + ) + + with caplog.at_level(logging.WARNING, logger=warm_up_module.__name__): + warm_up_module.warm_up_first_us_calculation(("us",)) + + assert calculation.payloads == [] + assert "the bundle receipt is unreadable" in caplog.text + + +@pytest.mark.usefixtures("snapshotted_container") +def test_the_v2_app_imports_and_starts_when_the_warm_up_cannot_import_its_helpers( + monkeypatch, caplog +): + # A change elsewhere can move or rename what the warm-up imports. That + # must cost only the warm-up, never the import of the app. + install_fake_modal(monkeypatch) + monkeypatch.delattr(v2_precompute_planning, "scoped_planned_simulation") + for module_name in ( + "src.modal.v2_snapshot_warm_up", + "src.modal.v2_images", + "src.modal.v2_app", + ): + monkeypatch.delitem(sys.modules, module_name, raising=False) + + app = importlib.import_module("src.modal.v2_app") + monkeypatch.setattr(app, "preload_country_models", lambda _countries: None) + with caplog.at_level(logging.WARNING, logger="src.modal.v2_snapshot_warm_up"): + app.SimulationSegmentWorkerUS().load_country_models() + + assert "Warm-up calculation failed" in caplog.text + for module_name in ("src.modal.v2_images", "src.modal.v2_app"): + sys.modules.pop(module_name, None) + + +@pytest.mark.usefixtures("snapshotted_container") +def test_a_failed_warm_up_never_stops_the_container_starting( + v2_app, calculation, monkeypatch +): + attempts: list[str] = [] + + def failing_calculation(_payload, **_options): + attempts.append("calculated") + msg = "out of memory" + raise MemoryError(msg) + + monkeypatch.setattr(stage12_runtime, "calculate_segment", failing_calculation) + + worker = v2_app.SimulationSegmentWorkerUS() + worker.load_country_models() + + assert attempts == ["calculated"] + monkeypatch.setattr(stage12_runtime, "calculate_segment", calculation) + monkeypatch.setattr( + v2_app, + "init_process_observability", + lambda **_identity: _RecordingRuntime(), + ) + assert worker.run_single_simulation_segment_us(dict(LATER_SEGMENT)) == { + "state_seen": { + "cached_simulations": [], + "output_folder_files": [PREBUILT_YEAR_FILENAME], + } + } + + +@pytest.mark.usefixtures("snapshotted_container") +def test_a_call_after_the_warm_up_finds_no_simulation_or_file_the_warm_up_added( + warm_up_module, calculation, simulation_cache, prebuilt_image +): + prebuilt_folder = prebuilt_image.prebuilt_folder + files_before = {path.name for path in prebuilt_folder.iterdir()} + without_warm_up = calculation(dict(LATER_SEGMENT)).result + _restore_initial_state(simulation_cache, prebuilt_folder, files_before) + + warm_up_module.warm_up_first_us_calculation(("us",)) + after_warm_up = calculation(dict(LATER_SEGMENT)).result + + # The call finds no simulation the warm-up cached and no file it saved, + # so it calculates from the image's files as it would without one. + assert len(calculation.payloads) == 3 + assert after_warm_up == without_warm_up + + +@pytest.mark.usefixtures("snapshotted_container") +def test_the_v2_app_and_its_warm_up_need_no_module_of_the_run_simulation_app( + calculation, monkeypatch +): + install_fake_modal(monkeypatch) + for run_simulation_module in RUN_SIMULATION_APP_MODULES: + # Importing a module set to None raises ImportError. + monkeypatch.setitem(sys.modules, run_simulation_module, None) + for module_name in ( + "src.modal.v2_snapshot_warm_up", + "src.modal.v2_images", + "src.modal.v2_app", + ): + monkeypatch.delitem(sys.modules, module_name, raising=False) + + app = importlib.import_module("src.modal.v2_app") + monkeypatch.setattr(app, "preload_country_models", lambda _countries: None) + app.SimulationSegmentWorkerUS().load_country_models() + + assert len(calculation.payloads) == 1 + for module_name in ("src.modal.v2_images", "src.modal.v2_app"): + sys.modules.pop(module_name, None) + + +def test_the_warm_up_reform_changes_a_parameter_of_the_installed_us_model( + warm_up_module, +): + # policyengine-us's own parameter tree, about 12 s to load; .py's US model + # would also read the data release manifest from Hugging Face. + from policyengine_us.system import system + + period_start = f"{_first_precompute_year()}-01-01" + current_law_value = system.parameters.get_child( + warm_up_module.WARM_UP_REFORM_PARAMETER + )(period_start) + + # A reform equal to current law would calculate current law again. + assert current_law_value != warm_up_module.WARM_UP_REFORM_VALUE + + +class _CyclicCalculationObject: + """Refers to itself, as policyengine-core's simulation objects do.""" + + def __init__(self) -> None: + self.itself = self + + +@pytest.mark.usefixtures("snapshotted_container") +def test_a_failed_warm_up_frees_its_calculation_before_the_snapshot( + warm_up_module, calculation, monkeypatch +): + # Left allocated, a failed calculation's objects would go into the + # snapshot, and every restored container would start with them. + calculation_objects: list[weakref.ref] = [] + warnings: list[str] = [] + + def failing_calculation(_payload, **_options): + microsimulation = _CyclicCalculationObject() + calculation_objects.append(weakref.ref(microsimulation)) + msg = "the planned column household_tax is missing" + raise ValueError(msg) + + def record_warning(message, *args, **_options): + # Only the message: a log record keeps the traceback, and with it + # the failed calculation's frames. + warnings.append(message % args) + + monkeypatch.setattr(stage12_runtime, "calculate_segment", failing_calculation) + monkeypatch.setattr(warm_up_module.logger, "warning", record_warning) + # Only the warm-up's own collection may free the objects. + automatic_collection_was_on = gc.isenabled() + gc.disable() + try: + warm_up_module.warm_up_first_us_calculation(("us",)) + finally: + if automatic_collection_was_on: + gc.enable() + + [calculation_object] = calculation_objects + assert calculation_object() is None + [warning] = warnings + assert "Warm-up calculation failed" in warning + + +@pytest.mark.usefixtures("snapshotted_container") +def test_the_warm_up_leaves_no_memory_warning_marked_as_given( + warm_up_module, calculation, monkeypatch +): + from policyengine.core import cache as policyengine_cache + + # .py's cache warns once per process when its memory passes 8, 16 and + # 32 GB, and remembers each warning given. + warnings_given: set[int] = set() + monkeypatch.setattr(policyengine_cache, "_warned_thresholds", warnings_given) + nine_gigabytes = SimpleNamespace(rss=9 * 1024**3) + monkeypatch.setattr( + policyengine_cache.psutil, + "Process", + lambda: SimpleNamespace(memory_info=lambda: nine_gigabytes), + ) + + warm_up_module.warm_up_first_us_calculation(("us",)) + + # The warm-up's calculation passed 8 GB, but a restored container's own + # calls must still get the warning when they pass it. + assert len(calculation.payloads) == 1 + assert warnings_given == set()