diff --git a/changelog.d/us-post-export-scorer-closed-on-error.changed.md b/changelog.d/us-post-export-scorer-closed-on-error.changed.md new file mode 100644 index 0000000000..b258acd834 --- /dev/null +++ b/changelog.d/us-post-export-scorer-closed-on-error.changed.md @@ -0,0 +1 @@ +US certification closes the post-export scorer when any error stops it during scoring, before the error leaves certification: when the reform-coverage smoke fails at the certified tier (or with an evidence-tier failure no owner matches), when a stage raises, or on a SIGTERM. A pooled scorer then kills the workers still running a unit (such as reform validation's first units, which start before the smoke's result is decided) instead of leaving them to run until the process exits, tells idle workers to exit, and removes the batch files. An ordinary error from closing is printed and the first error raised; an interrupt while closing is raised instead. A failed smoke that certification goes on past (the allow option, or an evidence failure with an owner) cancels nothing. diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index dd4a86a9a1..6b564f4603 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -560,6 +560,24 @@ one Microsimulation over the whole file. the shared pass's values is still served. Each of these is a `WorkerPoolError` and stops certification, the held-out reports included, where the serial scorer, which has no memory cap, may have finished. + - The smoke's reform units are the first reform units in the second run, + after the shared baseline pass, so its result is known before reform + validation's units are due. Workers still run ahead of the stages, by up + to twice the worker count of units: with two or more workers, reform + validation's first units start while the smoke's last are running, and + with one, its first unit is handed out as the smoke's last result comes + back, before the smoke's result is decided. Any error that stops + certification during scoring (the smoke's refusal at the certified tier, + an evidence-tier failure with no owner, a stage's own error, a SIGTERM) + closes the scorer before the error leaves certification: workers still + running a unit are killed at once, idle workers are told to exit and + killed if they have not within 10 seconds, and the batch files are + removed. An ordinary error from closing is printed and the first error + raised; an interrupt while closing (Ctrl-C, or a first SIGTERM) is raised + instead, and batch files a failed close left are removed when the process + exits. A failed smoke that certification goes on past (the allow option, + or an evidence failure with an owner) cancels nothing. The serial scorer + is closed the same way. - Each stage then runs as in the serial path and builds its own reforms (the smoke records each list edit's resolved lists from its own). Its baseline is served its recorded plan, and each reformed simulation its recorded diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py index e451d93c58..1ae13c15b9 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py @@ -15,22 +15,32 @@ behavioral-response parameter; - the merged baseline pass's failure to fall back to each consumer's own pass, as the serial scorer does, a changed batch file to stop scoring, and a - request the dry run did not record to be refused. + request the dry run did not record to be refused; +- certification (``_certify_us_build``) to close the scorer when an error + stops it during scoring (tracker task 1.4 · 8): the reform-coverage check's + reform units run first, and its refusal, or any stage's error, kills the + units still running and removes the batch files, while a failed check that + certification goes on past cancels nothing. """ # The ``builder`` fixture is imported, and each test takes it by name. # ruff: noqa: F401, F811 from __future__ import annotations +import argparse +import dataclasses import json +import multiprocessing import os import sys +import time import types from collections import defaultdict from pathlib import Path import pytest +from microcosm.build.termination import BuildTerminatedError from microcosm.build.us_runtime.post_export_requests import ( RECORDS_REQUESTS_ONLY, ParameterChangesReform, @@ -51,6 +61,7 @@ MEMORY_ON_HOUSEHOLDS, SLOW, WAIT_FOR, + WAIT_FOR_OTHER_REFORMS, FakeMicrosimulation, build_fake_parameter_reform, build_fake_reform, @@ -95,6 +106,7 @@ def pooled_reforms(monkeypatch, builder): MEMORY_KEYS, SLOW, WAIT_FOR, + WAIT_FOR_OTHER_REFORMS, FAIL_ON_HOUSEHOLDS, MEMORY_ON_HOUSEHOLDS, ): @@ -131,10 +143,11 @@ def load_frame(path, *, expected_sha256=None): return load_frame -def _serial_scorer(builder, plan, directory: Path): +def _serial_scorer(builder, plan, directory: Path, *, batch_parent=None): return builder._HouseholdBatchedPostExportScorer( _written_h5(directory), maximum_microsim_batch_size=BATCH_SIZE, + batch_parent=batch_parent, expected_n_households=N_HOUSEHOLDS, microsimulation_cls=FakeMicrosimulation, dataset_from_frame=identity_dataset, @@ -143,10 +156,13 @@ def _serial_scorer(builder, plan, directory: Path): ) -def _pooled_scorer(builder, plan, directory: Path, workers: int, **settings): +def _pooled_scorer( + builder, plan, directory: Path, workers: int, *, batch_parent=None, **settings +): return builder._PooledPostExportScorer( _written_h5(directory), maximum_microsim_batch_size=BATCH_SIZE, + batch_parent=batch_parent, expected_n_households=N_HOUSEHOLDS, consumer_requests=plan.consumer_requests, pooling=_pooling(builder, workers, **settings), @@ -1314,3 +1330,601 @@ def run(scorer): assert serial["second"] == "RuntimeError: fixture engine refuses snap" monkeypatch.setenv(MEMORY_ON_HOUSEHOLDS, json.dumps({"snap": [7]})) assert run(_pooled_scorer(builder, plan, tmp_path / "pooled", 2)) == serial + + +# --------------------------------------------------------------------------- +# Certification stops the pool when scoring stops it (tracker task 1.4 · 8) +# --------------------------------------------------------------------------- + + +class _ScoringFinishedError(Exception): + """Raised in place of the population-structure holdout, which certification + writes after it has closed the scorer, so a test ends there.""" + + +def _use_probes(monkeypatch, *, passing: bool): + """Three of the shipped reform-coverage probes, each made to pass or to + fail on the fake engine, in place of the shipped set: the plan's dry run, + the check in the certifying process and the workers' units all use them.""" + probes = tuple( + dataclasses.replace( + probe, + expected_sign="either", + min_abs_effect=1e-6 if passing else 1e18, + ) + for probe in smoke_module.us_release_reform_coverage_probes()[:3] + ) + monkeypatch.setattr( + smoke_module, "us_release_reform_coverage_probes", lambda: probes + ) + return probes + + +def _record_for_certification(builder, plan, fit, tmp_path: Path, **settings): + """What ``_certify_us_build`` reads of a build record, for the fixture plan. + + The record's options are the build's: every stage on, the fixture's + batching, and ``settings`` on top. Everything the manifests alone read is + empty, since these tests end before the manifests. + """ + artifact_root = tmp_path / "build" / "artifacts" + artifact_root.mkdir(parents=True) + options = {name: False for name in builder.US_BUILD_RECORD_SETTINGS} + options.update(maximum_microsim_batch_size=BATCH_SIZE, **settings) + + def empty(): + return defaultdict(lambda: None) + + return types.SimpleNamespace( + certify_args=lambda *, evidence_release: argparse.Namespace( + **options, evidence_release=evidence_release + ), + artifact_root=artifact_root, + release_root=tmp_path / "build", + dataset_key=builder.DATASET_KEY, + dataset_filename=builder.DATASET_FILENAME, + calibration_key=builder.CALIBRATION_KEY, + calibration_filename=builder.CALIBRATION_FILENAME, + terminal_gate_failures=(), + timing={}, + calibration_result=lambda: fit, + registry_summary=lambda: TargetRegistry((), country="us"), + post_export_scoring_plan=lambda args, *, result: plan, + manifest_inputs=defaultdict(lambda: None, release_gate_failures=[]), + gates=empty, + diagnostics_outcome=lambda release_dir: None, + source_coverage=empty(), + take_up=empty(), + ) + + +def _certification(builder, tmp_path: Path, *, evidence_release: bool, owners=()): + release_dir = tmp_path / "release" + release_dir.mkdir() + return builder._Certification( + evidence_release=evidence_release, + owner_patterns=owners, + owners_file=None, + owners_file_sha256=None, + release_dir=release_dir, + build="fixture-release", + commit="c" * 40, + changed_since_build=(), + ) + + +def _certify_with(builder, monkeypatch, make_scorer, record, certification, opened): + """Run ``_certify_us_build`` with ``make_scorer(batch_parent)`` as the + scorer it opens, in the batch parent certification passes (the scorer + holds the fixture frame). Each scorer opened is added to ``opened``.""" + + def open_scorer(plan, dataset_path, *, batch_parent=None, pooling=None): + opened.append(make_scorer(batch_parent)) + return opened[-1] + + monkeypatch.setattr(builder, "_open_post_export_scorer", open_scorer) + builder._certify_us_build(record, certification=certification, telemetry=None) + + +def _close_opened(builder, opened) -> None: + for scorer in opened: + builder._close_post_export_scorer(scorer) + + +def _child_processes() -> set[int]: + """The process IDs of this process's live ``multiprocessing`` children.""" + return {process.pid for process in multiprocessing.active_children()} + + +def _engine_events(log: Path) -> list[dict]: + """The engine log so far; a line a worker is still writing is skipped.""" + events = [] + for path in sorted(log.glob("*.jsonl")): + for text in path.read_text().splitlines(): + try: + events.append({"pid": int(path.stem), **json.loads(text)}) + except ValueError: + continue + return events + + +@pytest.mark.parametrize( + ("evidence_release", "refusal"), + [ + (False, "Release gates failed: Reform coverage smoke failed"), + (True, "Evidence release refused"), + ], + ids=["certified", "evidence_unowned"], +) +def test_a_failed_check_that_stops_certification_stops_the_pools_workers( + builder, + pooled_reforms, + tmp_path, + monkeypatch, + evidence_release, + refusal, +) -> None: + """The reform-coverage check's reform units are the first reform units the + pool runs, after the merged baseline pass. When the check fails and that + stops certification (the certified tier, or a failure no evidence owner + matches), certification closes the scorer before its refusal leaves + ``_certify_us_build``: the reform-validation unit a worker had already + started is killed at once, not left to run until the process exits, and + the scorer's batch files and the batch parent it made are removed.""" + probes = _use_probes(monkeypatch, passing=False) + probe_ids = [probe.id for probe in probes] + plan, fit = _release_plan(builder) + log = tmp_path / "engine-log" + log.mkdir() + monkeypatch.setenv(ENGINE_LOG, str(log)) + # Every reform other than the check's waits for a file nobody writes, so + # reform validation's first unit is still running when the check fails. + monkeypatch.setenv( + WAIT_FOR_OTHER_REFORMS, + json.dumps({"file": str(tmp_path / "never-written"), "except": probe_ids}), + ) + checked_gate = builder.us_reform_coverage_smoke_gate + decided: list[float] = [] + + def gate_once_reform_validation_started(**arguments): + # The pool hands reform validation's first unit to the worker as the + # check's last result comes back; wait until the worker has built + # that unit's first engine before the check's result is returned. + result = checked_gate(**arguments) + deadline = time.monotonic() + 60 + while not any( + event["event"] == "construct" and event["reform"] not in (None, *probe_ids) + for event in _engine_events(log) + ): + assert time.monotonic() < deadline, "reform validation never started" + time.sleep(0.05) + decided.append(time.monotonic()) + return result + + # After the plan's dry run, which runs the check on a recording seam. + monkeypatch.setattr( + builder, "us_reform_coverage_smoke_gate", gate_once_reform_validation_started + ) + children_before = _child_processes() + opened: list = [] + try: + with pytest.raises(RuntimeError, match=refusal): + _certify_with( + builder, + monkeypatch, + lambda batch_parent: _pooled_scorer( + builder, plan, tmp_path / "scoring", 1, batch_parent=batch_parent + ), + _record_for_certification(builder, plan, fit, tmp_path), + _certification(builder, tmp_path, evidence_release=evidence_release), + opened, + ) + # The busy worker was killed: the pool waits 10 seconds for a worker + # it has told to stop, and the unit it ran waits two minutes. + assert time.monotonic() - decided[0] < 8.0 + assert _child_processes() - children_before == set() + [scorer] = opened + assert not scorer.batch_directory.exists() + assert not ( + tmp_path / "build" / builder.US_POST_EXPORT_BATCH_DIRECTORY + ).exists() + + # One worker ran every unit, in the order the pool handed them out: + # the merged baseline pass, the check's reformed simulations, then + # reform validation's first, which never finished. + events = _engine_events(log) + assert len({event["pid"] for event in events}) == 1 + built = [event["reform"] for event in events if event["event"] == "construct"] + first_reform = next( + index for index, reform in enumerate(built) if reform is not None + ) + assert first_reform > 0 + assert None not in built[first_reform:] + started = [ + reform + for index, reform in enumerate(built[first_reform:], start=first_reform) + if built[index - 1] != reform + ] + assert started[: len(probes)] == probe_ids + assert len(started) == len(probes) + 1 + execution = scorer.execution_record() + assert execution["report"]["units_completed"] == ( + execution["units"]["baseline"] + len(probes) + ) + release_dir = tmp_path / "release" + assert (release_dir / "reform_coverage_smoke.json").exists() + assert not (release_dir / "reform_validation.json").exists() + finally: + _close_opened(builder, opened) + + +@pytest.mark.parametrize( + ("pooled", "error_type"), + [ + (True, RuntimeError), + (False, RuntimeError), + (True, BuildTerminatedError), + ], + ids=["pooled", "serial", "pooled_sigterm"], +) +def test_any_error_during_scoring_closes_the_scorer( + builder, + pooled_reforms, + tmp_path, + monkeypatch, + pooled, + error_type, +) -> None: + """An error in any post-export stage, not only the check's refusal, stops + certification with the scorer closed: no worker is left running and the + batch files are removed. That includes a SIGTERM, which certification + raises as ``BuildTerminatedError`` (a ``KeyboardInterrupt``, not an + ``Exception``). The serial scorer is closed the same way.""" + _use_probes(monkeypatch, passing=True) + plan, fit = _release_plan(builder) + error = error_type("the demographics writer broke") + + def make_scorer(batch_parent): + if pooled: + return _pooled_scorer( + builder, plan, tmp_path / "scoring", 1, batch_parent=batch_parent + ) + return _serial_scorer( + builder, plan, tmp_path / "scoring", batch_parent=batch_parent + ) + + def broken_demographics(**arguments): + raise error + + monkeypatch.setattr(builder, "_write_demographics", broken_demographics) + children_before = _child_processes() + opened: list = [] + try: + with pytest.raises(type(error)) as raised: + _certify_with( + builder, + monkeypatch, + make_scorer, + _record_for_certification(builder, plan, fit, tmp_path), + _certification(builder, tmp_path, evidence_release=False), + opened, + ) + assert raised.value is error + assert (tmp_path / "release" / "reform_validation.json").exists() + [scorer] = opened + assert not scorer.batch_directory.exists() + assert not ( + tmp_path / "build" / builder.US_POST_EXPORT_BATCH_DIRECTORY + ).exists() + assert _child_processes() - children_before == set() + finally: + _close_opened(builder, opened) + + +class _UnprintableError(Exception): + def __str__(self) -> str: + raise ValueError("this error cannot be printed") + + +@pytest.mark.parametrize( + ("close_error_type", "close_error_arguments", "printed"), + [ + ( + OSError, + ("the batch directory is gone",), + "OSError: the batch directory is gone", + ), + (_UnprintableError, (), "_UnprintableError"), + ], + ids=["ordinary", "unprintable"], +) +def test_an_error_closing_the_scorer_does_not_replace_the_one_that_stopped_it( + builder, + pooled_reforms, + tmp_path, + monkeypatch, + capsys, + close_error_type, + close_error_arguments, + printed, +) -> None: + """If closing the scorer after an error raises an ``Exception`` too, + certification prints that second error, even one that cannot be turned + into text, and raises the first, the check's refusal.""" + _use_probes(monkeypatch, passing=False) + plan, fit = _release_plan(builder) + + def failing_close(): + raise close_error_type(*close_error_arguments) + + def make_scorer(batch_parent): + scorer = _serial_scorer( + builder, plan, tmp_path / "scoring", batch_parent=batch_parent + ) + monkeypatch.setattr(scorer, "close", failing_close) + return scorer + + opened: list = [] + try: + with pytest.raises(RuntimeError, match="Release gates failed"): + _certify_with( + builder, + monkeypatch, + make_scorer, + _record_for_certification(builder, plan, fit, tmp_path), + _certification(builder, tmp_path, evidence_release=False), + opened, + ) + assert printed in capsys.readouterr().err + finally: + for scorer in opened: + type(scorer).close(scorer) + + +class _BrokenStream: + """A standard error stream whose reader has gone.""" + + def write(self, text): + raise BrokenPipeError("standard error is closed") + + def flush(self): + raise BrokenPipeError("standard error is closed") + + +def test_a_warning_that_cannot_be_written_does_not_replace_the_error( + builder, + pooled_reforms, + tmp_path, + monkeypatch, +) -> None: + """If closing the scorer after an error raises, and the warning about it + cannot be written either (standard error's reader has gone), the error + that stopped certification is still the one raised.""" + _use_probes(monkeypatch, passing=False) + plan, fit = _release_plan(builder) + + def failing_close(): + raise OSError("the batch directory is gone") + + def make_scorer(batch_parent): + scorer = _serial_scorer( + builder, plan, tmp_path / "scoring", batch_parent=batch_parent + ) + monkeypatch.setattr(scorer, "close", failing_close) + return scorer + + opened: list = [] + try: + with monkeypatch.context() as broken: + broken.setattr(sys, "stderr", _BrokenStream()) + with pytest.raises(RuntimeError, match="Release gates failed"): + _certify_with( + builder, + monkeypatch, + make_scorer, + _record_for_certification(builder, plan, fit, tmp_path), + _certification(builder, tmp_path, evidence_release=False), + opened, + ) + finally: + for scorer in opened: + type(scorer).close(scorer) + + +def test_an_interrupt_while_closing_the_scorer_is_raised( + builder, + pooled_reforms, + tmp_path, + monkeypatch, +) -> None: + """An interrupt while closing the scorer after an error (Ctrl-C, or a + first SIGTERM) is raised in place of that error, which it carries as its + context: certification then ends as an interrupted run.""" + _use_probes(monkeypatch, passing=False) + plan, fit = _release_plan(builder) + + def interrupted_close(): + raise BuildTerminatedError() + + def make_scorer(batch_parent): + scorer = _serial_scorer( + builder, plan, tmp_path / "scoring", batch_parent=batch_parent + ) + monkeypatch.setattr(scorer, "close", interrupted_close) + return scorer + + opened: list = [] + try: + with pytest.raises(BuildTerminatedError) as raised: + _certify_with( + builder, + monkeypatch, + make_scorer, + _record_for_certification(builder, plan, fit, tmp_path), + _certification(builder, tmp_path, evidence_release=False), + opened, + ) + assert isinstance(raised.value.__context__, RuntimeError) + assert "Release gates failed" in str(raised.value.__context__) + finally: + for scorer in opened: + type(scorer).close(scorer) + + +def test_a_stage_error_kills_the_units_still_running( + builder, + pooled_reforms, + tmp_path, + monkeypatch, +) -> None: + """A stage's own error while workers are still running its later units + stops certification with those units killed at once: here reform + validation fails as it builds its second reform, while the worker runs + that reformed simulation's unit.""" + probes = _use_probes(monkeypatch, passing=True) + plan, fit = _release_plan(builder) + validation = plan.consumer_requests["reform_validation"] + assert len(validation.simulations) >= 2 + first_validation = build_fake_reform( + validation.reforms[validation.simulations[0]] + ).label + held = [probe.id for probe in probes] + [first_validation] + log = tmp_path / "engine-log" + log.mkdir() + monkeypatch.setenv(ENGINE_LOG, str(log)) + # Every reform after reform validation's first waits for a file nobody + # writes, so its second unit is still running when the stage fails. + monkeypatch.setenv( + WAIT_FOR_OTHER_REFORMS, + json.dumps({"file": str(tmp_path / "never-written"), "except": held}), + ) + built: list[object] = [] + failed: list[float] = [] + + def failing_on_the_second(build): + def build_reform(*arguments, **options): + built.append(build) + if len(built) < 2: + return build(*arguments, **options) + # Wait until the worker has started the second unit's engine. + deadline = time.monotonic() + 60 + while not any( + event["event"] == "construct" and event["reform"] not in (None, *held) + for event in _engine_events(log) + ): + assert time.monotonic() < deadline, "the second unit never started" + time.sleep(0.05) + failed.append(time.monotonic()) + raise RuntimeError("reform validation broke") + + return build_reform + + # Reform validation builds a spec's reform or a parameter reform. + monkeypatch.setattr( + ReformValidationSpec, + "build_reform", + failing_on_the_second(ReformValidationSpec.build_reform), + ) + monkeypatch.setattr( + reform_validation_module, + "_build_parameter_reform", + failing_on_the_second(reform_validation_module._build_parameter_reform), + ) + children_before = _child_processes() + opened: list = [] + try: + with pytest.raises(RuntimeError, match="reform validation broke"): + _certify_with( + builder, + monkeypatch, + lambda batch_parent: _pooled_scorer( + builder, plan, tmp_path / "scoring", 1, batch_parent=batch_parent + ), + _record_for_certification(builder, plan, fit, tmp_path), + _certification(builder, tmp_path, evidence_release=False), + opened, + ) + # The busy worker was killed: the pool waits 10 seconds for a worker + # it has told to stop, and the unit it ran waits two minutes. + assert time.monotonic() - failed[0] < 8.0 + assert _child_processes() - children_before == set() + [scorer] = opened + assert not scorer.batch_directory.exists() + assert not ( + tmp_path / "build" / builder.US_POST_EXPORT_BATCH_DIRECTORY + ).exists() + execution = scorer.execution_record() + assert execution["report"]["units_completed"] == ( + execution["units"]["baseline"] + len(probes) + 1 + ) + assert not (tmp_path / "release" / "reform_validation.json").exists() + finally: + _close_opened(builder, opened) + + +@pytest.mark.parametrize( + ("evidence_release", "settings", "owners"), + [ + (False, {"allow_reform_coverage_smoke_failures": True}, ()), + (True, {}, (("Reform coverage smoke failed", "PolicyEngine/microcosm#368"),)), + ], + ids=["allowed", "evidence_owned"], +) +def test_a_failed_check_that_does_not_stop_certification_cancels_nothing( + builder, + pooled_reforms, + tmp_path, + monkeypatch, + evidence_release, + settings, + owners, +) -> None: + """A failed check that certification goes on past (the allow option, or an + evidence-tier failure with an owner) cancels nothing: every later stage + is scored in the pool and writes its file.""" + _use_probes(monkeypatch, passing=False) + plan, fit = _release_plan(builder) + + def finished(**arguments): + raise _ScoringFinishedError + + monkeypatch.setattr(builder, "_write_population_structure_holdout", finished) + opened: list = [] + try: + with pytest.raises(_ScoringFinishedError): + _certify_with( + builder, + monkeypatch, + lambda batch_parent: _pooled_scorer( + builder, plan, tmp_path / "scoring", 1, batch_parent=batch_parent + ), + _record_for_certification(builder, plan, fit, tmp_path, **settings), + _certification( + builder, + tmp_path, + evidence_release=evidence_release, + owners=owners, + ), + opened, + ) + release_dir = tmp_path / "release" + assert {path.name for path in release_dir.iterdir()} == { + "demographics.json", + "reform_coverage_smoke.json", + "reform_validation.json", + "us_medicare_irmaa_holdout.json", + "us_ssi_social_security_holdout.json", + } + smoke = json.loads((release_dir / "reform_coverage_smoke.json").read_text()) + assert smoke["reform_coverage_smoke"]["passed"] is False + assert smoke["enforced"] is not settings.get( + "allow_reform_coverage_smoke_failures", False + ) + # One worker ran every unit once: none was killed and run again. + [scorer] = opened + report = scorer.execution_record()["report"] + assert report["pools"] == 1 + assert report["worker_starts"] == 1 + assert report["failed_attempts"] == [] + finally: + _close_opened(builder, opened) diff --git a/test_support/microcosm_build/us_post_export_pool.py b/test_support/microcosm_build/us_post_export_pool.py index 910d3f89cd..9601c0d144 100644 --- a/test_support/microcosm_build/us_post_export_pool.py +++ b/test_support/microcosm_build/us_post_export_pool.py @@ -23,6 +23,10 @@ before it computes that variable; - :data:`WAIT_FOR`: JSON mapping a variable to a file each engine waits for (two minutes at most) before it computes that variable; +- :data:`WAIT_FOR_OTHER_REFORMS`: JSON ``{"file": path, "except": [labels]}``; + an engine whose reform's label is not listed waits for the file (two minutes + at most) before each variable it computes, so a test can keep one stage's + reformed simulations running while another stage's finish; - :data:`FAIL_ON_HOUSEHOLDS` and :data:`MEMORY_ON_HOUSEHOLDS`: JSON mapping a variable to household ids; an engine whose batch holds one of them raises ``RuntimeError`` or ``MemoryError`` for that variable. @@ -63,6 +67,7 @@ MEMORY_KEYS = "MICROCOSM_TEST_POST_EXPORT_MEMORY_KEYS" SLOW = "MICROCOSM_TEST_POST_EXPORT_SLOW" WAIT_FOR = "MICROCOSM_TEST_POST_EXPORT_WAIT_FOR" +WAIT_FOR_OTHER_REFORMS = "MICROCOSM_TEST_POST_EXPORT_WAIT_FOR_OTHER_REFORMS" FAIL_ON_HOUSEHOLDS = "MICROCOSM_TEST_POST_EXPORT_FAIL_ON_HOUSEHOLDS" MEMORY_ON_HOUSEHOLDS = "MICROCOSM_TEST_POST_EXPORT_MEMORY_ON_HOUSEHOLDS" @@ -135,6 +140,13 @@ def get_known_periods(self): return sorted(self._periods) +def _wait_for_file(path: str) -> None: + """Wait until ``path`` exists, two minutes at most.""" + deadline = time.monotonic() + 120 + while not Path(path).exists() and time.monotonic() < deadline: + time.sleep(0.1) + + #: This process's engines, to count those not yet released at a construction. _ENGINES: list = [] @@ -207,9 +219,11 @@ def calculate(self, variable, period, map_to=None): time.sleep(float(delay)) awaited = json.loads(os.environ.get(WAIT_FOR) or "{}").get(variable) if awaited: - deadline = time.monotonic() + 120 - while not Path(awaited).exists() and time.monotonic() < deadline: - time.sleep(0.1) + _wait_for_file(awaited) + held = json.loads(os.environ.get(WAIT_FOR_OTHER_REFORMS) or "{}") + reform = self.policy_reform + if held and reform is not None and reform.label not in held["except"]: + _wait_for_file(held["file"]) households = set( int(value) for value in frame.table("household")["household_id"] ) @@ -221,7 +235,6 @@ def calculate(self, variable, period, map_to=None): for computed in (variable, *computes.get(variable, ())): self.known.setdefault(computed, set()).add(period) native = _native_entity(variable) - reform = self.policy_reform delta = 0.0 if reform is None else reform.delta values = _native_values(frame, variable, period, delta) target = map_to or native diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index f76f657837..a48469ca74 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -6604,6 +6604,38 @@ def _close_post_export_scorer( return scorer.dataset_sha256 +def _close_post_export_scorer_after_error( + scorer: _HouseholdBatchedPostExportScorer | None, +) -> None: + """Close the scorer after an error that stops certification. + + A pooled scorer kills the workers still running a unit and tells idle + ones to exit (killing any that has not within 10 seconds); every scorer + removes its batch files. An ``Exception`` from closing is printed, not + raised (nor is one from printing it), so the error that stopped + certification is the one raised. An interrupt while closing (Ctrl-C, or + a first SIGTERM) is raised instead, with that error as its context; + batch files a failed close left are removed when the process exits. + """ + try: + _close_post_export_scorer(scorer) + except Exception as close_error: + try: + detail = f"{type(close_error).__name__}: {close_error}" + except Exception: + # Its text cannot be made; its class still names it. + detail = type(close_error).__name__ + try: + print( + "warning: could not close the post-export scorer after an " + f"error: {detail}", + file=sys.stderr, + ) + except Exception: + # Standard error is gone too; the first error is still raised. + pass + + class _PostExportConsumer: """One consumer's simulate seam over a scored baseline plan.""" @@ -21312,163 +21344,182 @@ def _certify_us_build( batch_parent=record.release_root / US_POST_EXPORT_BATCH_DIRECTORY, pooling=post_export_pooling, ) - # microcosm#368: reform-coverage smoke on the WRITTEN release H5. The column - # gate above proves the required keys exist and carry signal; this is the - # end-to-end backstop: each pinned probe (first: SSI asset limits at - # $10k/$20k) mechanically binds through named input leaves and must move - # its budget measure. A ~$0 score on a bound reform means those leaves are - # absent or degenerate — the release aborts before any manifest or - # contract file certifies the artifact. Runs on both dense and sparse - # default paths (both reach this line). Until the asset stage is restored - # (Deliverable 2) the SSI probe fails by design; that is the gate working. - if not args.skip_reform_coverage_smoke: - if telemetry is not None: - telemetry.stage( + # Any error from here until the scorer closes stops certification. Close + # the scorer first, so a pooled scorer's workers stop at once, the units + # they had started included, instead of running until the process exits, + # and its batch files are removed; then raise the error (tracker task + # 1.4 · 8). The reform-coverage smoke's units are the first reform units + # the pool runs, so its refusal stops the reform-validation units that + # had already started. + try: + # microcosm#368: reform-coverage smoke on the WRITTEN release H5. The column + # gate above proves the required keys exist and carry signal; this is the + # end-to-end backstop: each pinned probe (first: SSI asset limits at + # $10k/$20k) mechanically binds through named input leaves and must move + # its budget measure. A ~$0 score on a bound reform means those leaves are + # absent or degenerate — the release aborts before any manifest or + # contract file certifies the artifact. Runs on both dense and sparse + # default paths (both reach this line). Until the asset stage is restored + # (Deliverable 2) the SSI probe fails by design; that is the gate working. + if not args.skip_reform_coverage_smoke: + if telemetry is not None: + telemetry.stage( + "reform_coverage_smoke", + message="Scoring pinned bound-reform probes on the written H5.", + ) + smoke_scoring = post_export_scorer.open_consumer( "reform_coverage_smoke", - message="Scoring pinned bound-reform probes on the written H5.", + post_export_scoring_plan.baseline_plan("reform_coverage_smoke"), + planned_reform_passes=post_export_scoring_plan.planned_reform_passes( + "reform_coverage_smoke" + ), ) - smoke_scoring = post_export_scorer.open_consumer( - "reform_coverage_smoke", - post_export_scoring_plan.baseline_plan("reform_coverage_smoke"), - planned_reform_passes=post_export_scoring_plan.planned_reform_passes( - "reform_coverage_smoke" - ), - ) - reform_coverage_smoke_gate = us_reform_coverage_smoke_gate( - simulate=smoke_scoring.simulate, - period=PERIOD, - ) - smoke_scoring_record = post_export_scorer.finish_consumer(smoke_scoring) - reform_coverage_smoke_path = release_dir / "reform_coverage_smoke.json" - reform_coverage_smoke_path.write_text( - json.dumps( - { - "schema_version": 1, - "enforced": not args.allow_reform_coverage_smoke_failures, - "reform_coverage_smoke": { - "passed": reform_coverage_smoke_gate.passed, - "failures": list(reform_coverage_smoke_gate.failures), - "details": dict(reform_coverage_smoke_gate.details), + reform_coverage_smoke_gate = us_reform_coverage_smoke_gate( + simulate=smoke_scoring.simulate, + period=PERIOD, + ) + smoke_scoring_record = post_export_scorer.finish_consumer(smoke_scoring) + reform_coverage_smoke_path = release_dir / "reform_coverage_smoke.json" + reform_coverage_smoke_path.write_text( + json.dumps( + { + "schema_version": 1, + "enforced": not args.allow_reform_coverage_smoke_failures, + "reform_coverage_smoke": { + "passed": reform_coverage_smoke_gate.passed, + "failures": list(reform_coverage_smoke_gate.failures), + "details": dict(reform_coverage_smoke_gate.details), + }, + "post_export_scoring": smoke_scoring_record, }, - "post_export_scoring": smoke_scoring_record, - }, - indent=2, - sort_keys=True, + indent=2, + sort_keys=True, + ) + + "\n" ) - + "\n" - ) - # The smoke's record is written; free its reform results before reform - # validation runs. Its baseline values stay with the scorer only while - # a consumer still to be served planned them. - del smoke_scoring - if telemetry is not None: - telemetry.attach_artifact( - "reform_coverage_smoke", reform_coverage_smoke_path + # The smoke's record is written; free its reform results before reform + # validation runs. Its baseline values stay with the scorer only while + # a consumer still to be served planned them. + del smoke_scoring + if telemetry is not None: + telemetry.attach_artifact( + "reform_coverage_smoke", reform_coverage_smoke_path + ) + if ( + not reform_coverage_smoke_gate.passed + and not args.allow_reform_coverage_smoke_failures + ): + if telemetry is not None: + telemetry.stage( + "reform_coverage_smoke", + status="failed", + message="Reform-coverage smoke gate failed.", + failures=list(reform_coverage_smoke_gate.failures), + ) + smoke_failures = [ + f"Reform coverage smoke failed: {failure}" + for failure in reform_coverage_smoke_gate.failures + ] + if not args.evidence_release: + raise RuntimeError( + "Release gates failed: " + "; ".join(smoke_failures) + ) + # Evidence tier: the smoke verdict joins the recorded terminal + # set (owner-checked immediately, so an unowned failure aborts + # before further export work). + terminal_gate_failures.extend(smoke_failures) + _evidence_known_failures( + terminal_gate_failures, evidence_failure_owner_patterns + ) + if not args.skip_reform_validation: + if telemetry is not None: + telemetry.stage( + "reform_validation", + message="Writing reform validation diagnostics.", + ) + _write_reform_validation( + release_dir=release_dir, + dataset_path=dataset_path, + result=result, + registry=registry, + release_id=release_id, + simulate_out_of_sample=not args.skip_out_of_sample_reforms, + post_export_scorer=post_export_scorer, + baseline_plan=( + None + if args.skip_out_of_sample_reforms + else post_export_scoring_plan.baseline_plan("reform_validation") + ), + planned_reform_passes=post_export_scoring_plan.planned_reform_passes( + "reform_validation" + ), ) - if ( - not reform_coverage_smoke_gate.passed - and not args.allow_reform_coverage_smoke_failures - ): + if telemetry is not None: + telemetry.attach_artifact( + "reform_validation", + release_dir / "reform_validation.json", + ) + + if not args.skip_demographics: if telemetry is not None: telemetry.stage( - "reform_coverage_smoke", - status="failed", - message="Reform-coverage smoke gate failed.", - failures=list(reform_coverage_smoke_gate.failures), + "demographics", message="Writing demographics diagnostics." ) - smoke_failures = [ - f"Reform coverage smoke failed: {failure}" - for failure in reform_coverage_smoke_gate.failures - ] - if not args.evidence_release: - raise RuntimeError("Release gates failed: " + "; ".join(smoke_failures)) - # Evidence tier: the smoke verdict joins the recorded terminal - # set (owner-checked immediately, so an unowned failure aborts - # before further export work). - terminal_gate_failures.extend(smoke_failures) - _evidence_known_failures( - terminal_gate_failures, evidence_failure_owner_patterns + _write_demographics( + release_dir=release_dir, + dataset_path=dataset_path, + release_id=release_id, + post_export_scorer=post_export_scorer, + baseline_plan=post_export_scoring_plan.baseline_plan("demographics"), ) - if not args.skip_reform_validation: + if telemetry is not None: + telemetry.attach_artifact( + "demographics", release_dir / "demographics.json" + ) if telemetry is not None: telemetry.stage( - "reform_validation", - message="Writing reform validation diagnostics.", + "ssi_social_security_holdout", + message="Writing held-out SSI/Social Security receipt overlap.", ) - _write_reform_validation( + _write_ssi_social_security_holdout( release_dir=release_dir, dataset_path=dataset_path, - result=result, - registry=registry, release_id=release_id, - simulate_out_of_sample=not args.skip_out_of_sample_reforms, post_export_scorer=post_export_scorer, - baseline_plan=( - None - if args.skip_out_of_sample_reforms - else post_export_scoring_plan.baseline_plan("reform_validation") - ), - planned_reform_passes=post_export_scoring_plan.planned_reform_passes( - "reform_validation" + baseline_plan=post_export_scoring_plan.baseline_plan( + "ssi_social_security_holdout" ), ) if telemetry is not None: telemetry.attach_artifact( - "reform_validation", - release_dir / "reform_validation.json", + "us_ssi_social_security_holdout", + release_dir / "us_ssi_social_security_holdout.json", ) - - if not args.skip_demographics: - if telemetry is not None: - telemetry.stage("demographics", message="Writing demographics diagnostics.") - _write_demographics( + telemetry.stage( + "medicare_irmaa_holdout", + message="Writing held-out Medicare IRMAA payers and premiums.", + ) + _write_medicare_irmaa_holdout( release_dir=release_dir, dataset_path=dataset_path, release_id=release_id, post_export_scorer=post_export_scorer, - baseline_plan=post_export_scoring_plan.baseline_plan("demographics"), + baseline_plan=post_export_scoring_plan.baseline_plan( + "medicare_irmaa_holdout" + ), ) if telemetry is not None: - telemetry.attach_artifact("demographics", release_dir / "demographics.json") - if telemetry is not None: - telemetry.stage( - "ssi_social_security_holdout", - message="Writing held-out SSI/Social Security receipt overlap.", - ) - _write_ssi_social_security_holdout( - release_dir=release_dir, - dataset_path=dataset_path, - release_id=release_id, - post_export_scorer=post_export_scorer, - baseline_plan=post_export_scoring_plan.baseline_plan( - "ssi_social_security_holdout" - ), - ) - if telemetry is not None: - telemetry.attach_artifact( - "us_ssi_social_security_holdout", - release_dir / "us_ssi_social_security_holdout.json", - ) - telemetry.stage( - "medicare_irmaa_holdout", - message="Writing held-out Medicare IRMAA payers and premiums.", - ) - _write_medicare_irmaa_holdout( - release_dir=release_dir, - dataset_path=dataset_path, - release_id=release_id, - post_export_scorer=post_export_scorer, - baseline_plan=post_export_scoring_plan.baseline_plan("medicare_irmaa_holdout"), - ) - if telemetry is not None: - telemetry.attach_artifact( - "us_medicare_irmaa_holdout", - release_dir / "us_medicare_irmaa_holdout.json", - ) - # Every post-export engine stage has run; remove the scorer's batch files. - # The manifest must pin the bytes those stages scored, and both manifests - # carry how they were scored (Route A remediation PR-3). - post_export_scoring = _post_export_scoring_manifest_block(post_export_scorer) + telemetry.attach_artifact( + "us_medicare_irmaa_holdout", + release_dir / "us_medicare_irmaa_holdout.json", + ) + # Every post-export engine stage has run; remove the scorer's batch files. + # The manifest must pin the bytes those stages scored, and both manifests + # carry how they were scored (Route A remediation PR-3). + post_export_scoring = _post_export_scoring_manifest_block(post_export_scorer) + except BaseException: + _close_post_export_scorer_after_error(post_export_scorer) + raise scored_dataset_sha256 = _close_post_export_scorer(post_export_scorer) post_export_scorer = None # Reads the written H5 without an engine, after the scorer has closed,