From 137367f218565eef6371f20f34add8e04717f73e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:01:48 +0400 Subject: [PATCH 1/8] Add failing tests for closing the post-export scorer when scoring stops certification MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tracker task 1.4 · 8. Certification closes the post-export scorer only once every stage has finished, so when the reform-coverage check fails at the certified tier (or with a failure no evidence owner matches), or any stage raises, the pool's workers keep running the units they had started until the process exits. The new tests run _certify_us_build on the fixture plan with the fake engine, and require: - a failed check that stops certification to leave no pool worker running and no batch files when the refusal leaves _certify_us_build, with the check's reform units run first and the reform-validation unit already started killed rather than finished (certified tier, and evidence tier with an unowned failure); - any other error during scoring to close the scorer too, pooled or serial; - an error from closing the scorer to be printed, with the original error raised. Two pins pass already: a failed check that certification goes on past (the allow option, or an evidence failure with an owner) cancels nothing, and every later stage writes its file. The fake engine gains WAIT_FOR_OTHER_REFORMS, which holds every reformed simulation but the listed ones. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_post_export_pooled_scoring.py | 316 ++++++++++++++++++ .../microcosm_build/us_post_export_pool.py | 21 +- 2 files changed, 333 insertions(+), 4 deletions(-) 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..1768444fcf 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 @@ -22,7 +22,10 @@ # ruff: noqa: F401, F811 from __future__ import annotations +import argparse +import dataclasses import json +import multiprocessing import os import sys import types @@ -51,6 +54,7 @@ MEMORY_ON_HOUSEHOLDS, SLOW, WAIT_FOR, + WAIT_FOR_OTHER_REFORMS, FakeMicrosimulation, build_fake_parameter_reform, build_fake_reform, @@ -95,6 +99,7 @@ def pooled_reforms(monkeypatch, builder): MEMORY_KEYS, SLOW, WAIT_FOR, + WAIT_FOR_OTHER_REFORMS, FAIL_ON_HOUSEHOLDS, MEMORY_ON_HOUSEHOLDS, ): @@ -1314,3 +1319,314 @@ 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, scorer, record, certification) -> None: + """Run ``_certify_us_build`` on ``scorer`` (which holds the fixture frame).""" + monkeypatch.setattr( + builder, "_open_post_export_scorer", lambda *args, **options: scorer + ) + builder._certify_us_build(record, certification=certification, telemetry=None) + + +def _live_workers(events) -> list[int]: + """The processes in the engine log that are still running.""" + logged = {event["pid"] for event in events} + return [ + process.pid + for process in multiprocessing.active_children() + if process.pid in logged + ] + + +@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, not left to run until the process exits, and the + scorer's batch files are removed.""" + probes = _use_probes(monkeypatch, passing=False) + 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. + monkeypatch.setenv( + WAIT_FOR_OTHER_REFORMS, + json.dumps( + { + "file": str(tmp_path / "never-written"), + "except": [probe.id for probe in probes], + } + ), + ) + scorer = _pooled_scorer(builder, plan, tmp_path / "scoring", 1) + try: + with pytest.raises(RuntimeError, match=refusal): + _certify_with( + builder, + monkeypatch, + scorer, + _record_for_certification(builder, plan, fit, tmp_path), + _certification(builder, tmp_path, evidence_release=evidence_release), + ) + events = engine_log(log) + assert _live_workers(events) == [] + assert not scorer.batch_directory.exists() + + # One worker ran every unit, in the order the pool handed them out. + assert len({event["pid"] for event in events}) == 1 + reforms = [ + event["reform"] + for event in events + if event["event"] == "construct" and event["reform"] is not None + ] + started = [ + reform + for index, reform in enumerate(reforms) + if index == 0 or reforms[index - 1] != reform + ] + assert started[: len(probes)] == [probe.id for probe in probes] + # One reformed simulation of reform validation had started, and never + # finished. + 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: + builder._close_post_export_scorer(scorer) + + +@pytest.mark.parametrize("pooled", [True, False], ids=["pooled", "serial"]) +def test_any_error_during_scoring_closes_the_scorer( + builder, + pooled_reforms, + tmp_path, + monkeypatch, + pooled, +) -> 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. The serial scorer is closed the same way.""" + _use_probes(monkeypatch, passing=True) + plan, fit = _release_plan(builder) + log = tmp_path / "engine-log" + log.mkdir() + monkeypatch.setenv(ENGINE_LOG, str(log)) + scorer = ( + _pooled_scorer(builder, plan, tmp_path / "scoring", 1) + if pooled + else _serial_scorer(builder, plan, tmp_path / "scoring") + ) + + def broken_demographics(**arguments): + raise RuntimeError("the demographics writer broke") + + monkeypatch.setattr(builder, "_write_demographics", broken_demographics) + try: + with pytest.raises(RuntimeError, match="the demographics writer broke"): + _certify_with( + builder, + monkeypatch, + scorer, + _record_for_certification(builder, plan, fit, tmp_path), + _certification(builder, tmp_path, evidence_release=False), + ) + assert (tmp_path / "release" / "reform_validation.json").exists() + assert not scorer.batch_directory.exists() + if pooled: + assert _live_workers(engine_log(log)) == [] + finally: + builder._close_post_export_scorer(scorer) + + +def test_an_error_closing_the_scorer_does_not_replace_the_one_that_stopped_it( + builder, + pooled_reforms, + tmp_path, + monkeypatch, + capsys, +) -> None: + """If closing the scorer after an error raises too, certification prints + that second error and raises the first, the check's refusal.""" + _use_probes(monkeypatch, passing=False) + plan, fit = _release_plan(builder) + scorer = _serial_scorer(builder, plan, tmp_path / "scoring") + + def failing_close(): + raise OSError("the batch directory is gone") + + monkeypatch.setattr(scorer, "close", failing_close) + try: + with pytest.raises(RuntimeError, match="Release gates failed"): + _certify_with( + builder, + monkeypatch, + scorer, + _record_for_certification(builder, plan, fit, tmp_path), + _certification(builder, tmp_path, evidence_release=False), + ) + assert "OSError: the batch directory is gone" in capsys.readouterr().err + finally: + type(scorer).close(scorer) + + +@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) + scorer = _pooled_scorer(builder, plan, tmp_path / "scoring", 1) + + def finished(**arguments): + raise _ScoringFinishedError + + monkeypatch.setattr(builder, "_write_population_structure_holdout", finished) + try: + with pytest.raises(_ScoringFinishedError): + _certify_with( + builder, + monkeypatch, + scorer, + _record_for_certification(builder, plan, fit, tmp_path, **settings), + _certification( + builder, + tmp_path, + evidence_release=evidence_release, + owners=owners, + ), + ) + 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 + ) + finally: + builder._close_post_export_scorer(scorer) diff --git a/test_support/microcosm_build/us_post_export_pool.py b/test_support/microcosm_build/us_post_export_pool.py index 910d3f89cd..95fec3d48a 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 it computes anything, 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 From 8b2ca2f2f575c75a5eecf13fdf74b0285b879f8b Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:05:09 +0400 Subject: [PATCH 2/8] Close the post-export scorer when an error stops certification during scoring MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tracker task 1.4 · 8 ("Schedule the reform-coverage passes first and cancel the rest when that check fails"). Pooled scoring already hands out the reform-coverage smoke's reform units before any other stage's, after the merged baseline pass. Certification now closes the scorer when any error stops it between opening the scorer and taking its manifest block, then raises that error: - the smoke's refusal at the certified tier, or an evidence-tier smoke failure that matches no owner; - any stage's own error, a unit that failed on every attempt, or a SIGTERM (BuildTerminatedError). A pooled scorer's workers then stop at once: those still running a unit, such as reform validation's first units, which start while the smoke's last are running, are killed rather than left to run until the process exits. Every scorer removes its batch files. An error from closing is printed and the first error is the one raised (_close_post_export_scorer_after_error). A failed smoke that certification goes on past (the allow option, or an evidence failure with an owner) cancels nothing. The check itself, its record and the serial scorer's outputs are unchanged. The diff re-indents the scoring stages inside the new try block; view it with whitespace ignored. Co-Authored-By: Claude Opus 5.5 --- ...t-export-scorer-closed-on-error.changed.md | 1 + docs/us-release-build-rule.md | 12 + tools/build_us_fiscal_refresh_release.py | 299 ++++++++++-------- 3 files changed, 182 insertions(+), 130 deletions(-) create mode 100644 changelog.d/us-post-export-scorer-closed-on-error.changed.md 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..a8f2d88dee --- /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 is raised: 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's workers then stop at once, those still running a unit (reform validation's first units, which start while the smoke's last are running) are killed instead of running until the process exits, and the batch files are removed. An error from closing is printed, and the first error is the one raised. 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..1662af3dc2 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -560,6 +560,18 @@ 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, 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, + so reform validation's first units start while the smoke's last are + running. 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 is + raised: the workers stop at once, those still running a unit are killed, + and the batch files are removed. An error from closing is printed and the + first error raised. 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/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index f76f657837..5101fc3657 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -6604,6 +6604,26 @@ 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 stops its workers, killing those still running a unit, + and every scorer removes its batch files. An error from closing is + printed, not raised, so the error that stopped certification is the one + raised. + """ + try: + _close_post_export_scorer(scorer) + except Exception as close_error: + print( + "warning: could not close the post-export scorer after an error: " + f"{type(close_error).__name__}: {close_error}", + file=sys.stderr, + ) + + class _PostExportConsumer: """One consumer's simulate seam over a scored baseline plan.""" @@ -21312,163 +21332,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, From 1cc8b3a05fc007aeedadfc144acbd8bb62f43ddf Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:30:30 +0400 Subject: [PATCH 3/8] Fix review round 1's test findings for closing the post-export scorer Review round 1 (two adversarial reviewers) found no fault in the change and these in its tests: - The stop test raced with its worker: the pool hands reform validation's first unit to the worker as the check's last result comes back, and the close could kill the worker before it logged that unit's first engine. The test now waits, after the check runs, until the worker has built it, so the kill always lands on a started unit. - Nothing raised an interrupt. test_any_error_during_scoring_closes_the_scorer gains a pooled case where the stage raises BuildTerminatedError (a KeyboardInterrupt, as certification raises a SIGTERM), so a handler narrowed to Exception would fail it. - "Killed at once" was not separated from a close that waits: the stop test now requires the refusal within 8 seconds of the check's result, below the pool's 10-second wait for a worker told to stop, while the started unit waits two minutes. - Live workers were found only among processes that wrote to the engine log; the tests now require no new multiprocessing child at all. - The opener stub dropped certification's batch parent; the scorers are now built in it, and the tests require the parent the scorer made to be removed too. - The stop test now also checks that the merged baseline pass's engines were all built before any reform's. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_post_export_pooled_scoring.py | 212 ++++++++++++------ 1 file changed, 148 insertions(+), 64 deletions(-) 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 1768444fcf..a794d21928 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 @@ -28,12 +28,14 @@ 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, @@ -136,10 +138,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, @@ -148,10 +151,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), @@ -1402,22 +1408,39 @@ def _certification(builder, tmp_path: Path, *, evidence_release: bool, owners=() ) -def _certify_with(builder, monkeypatch, scorer, record, certification) -> None: - """Run ``_certify_us_build`` on ``scorer`` (which holds the fixture frame).""" - monkeypatch.setattr( - builder, "_open_post_export_scorer", lambda *args, **options: scorer - ) +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 _live_workers(events) -> list[int]: - """The processes in the engine log that are still running.""" - logged = {event["pid"] for event in events} - return [ - process.pid - for process in multiprocessing.active_children() - if process.pid in logged - ] +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( @@ -1441,52 +1464,83 @@ def test_a_failed_check_that_stops_certification_stops_the_pools_workers( 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, not left to run until the process exits, and the - scorer's batch files are removed.""" + 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. + # 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.id for probe in probes], - } - ), + 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 ) - scorer = _pooled_scorer(builder, plan, tmp_path / "scoring", 1) + children_before = _child_processes() + opened: list = [] try: with pytest.raises(RuntimeError, match=refusal): _certify_with( builder, monkeypatch, - scorer, + 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, ) - events = engine_log(log) - assert _live_workers(events) == [] + # 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() - - # One worker ran every unit, in the order the pool handed them out. + 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 - reforms = [ - event["reform"] - for event in events - if event["event"] == "construct" and event["reform"] is not None - ] + 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(reforms) - if index == 0 or reforms[index - 1] != reform + for index, reform in enumerate(built[first_reform:], start=first_reform) + if built[index - 1] != reform ] - assert started[: len(probes)] == [probe.id for probe in probes] - # One reformed simulation of reform validation had started, and never - # finished. + assert started[: len(probes)] == probe_ids assert len(started) == len(probes) + 1 execution = scorer.execution_record() assert execution["report"]["units_completed"] == ( @@ -1496,50 +1550,69 @@ def test_a_failed_check_that_stops_certification_stops_the_pools_workers( assert (release_dir / "reform_coverage_smoke.json").exists() assert not (release_dir / "reform_validation.json").exists() finally: - builder._close_post_export_scorer(scorer) + _close_opened(builder, opened) -@pytest.mark.parametrize("pooled", [True, False], ids=["pooled", "serial"]) +@pytest.mark.parametrize( + ("pooled", "error"), + [ + (True, RuntimeError("the demographics writer broke")), + (False, RuntimeError("the demographics writer broke")), + (True, BuildTerminatedError()), + ], + ids=["pooled", "serial", "pooled_sigterm"], +) def test_any_error_during_scoring_closes_the_scorer( builder, pooled_reforms, tmp_path, monkeypatch, pooled, + error, ) -> 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. The serial scorer is closed the same way.""" + 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) - log = tmp_path / "engine-log" - log.mkdir() - monkeypatch.setenv(ENGINE_LOG, str(log)) - scorer = ( - _pooled_scorer(builder, plan, tmp_path / "scoring", 1) - if pooled - else _serial_scorer(builder, plan, tmp_path / "scoring") - ) + + 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 RuntimeError("the demographics writer broke") + raise error monkeypatch.setattr(builder, "_write_demographics", broken_demographics) + children_before = _child_processes() + opened: list = [] try: - with pytest.raises(RuntimeError, match="the demographics writer broke"): + with pytest.raises(type(error)) as raised: _certify_with( builder, monkeypatch, - scorer, + 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() - if pooled: - assert _live_workers(engine_log(log)) == [] + assert not ( + tmp_path / "build" / builder.US_POST_EXPORT_BATCH_DIRECTORY + ).exists() + assert _child_processes() - children_before == set() finally: - builder._close_post_export_scorer(scorer) + _close_opened(builder, opened) def test_an_error_closing_the_scorer_does_not_replace_the_one_that_stopped_it( @@ -1553,24 +1626,32 @@ def test_an_error_closing_the_scorer_does_not_replace_the_one_that_stopped_it( that second error and raises the first, the check's refusal.""" _use_probes(monkeypatch, passing=False) plan, fit = _release_plan(builder) - scorer = _serial_scorer(builder, plan, tmp_path / "scoring") def failing_close(): raise OSError("the batch directory is gone") - monkeypatch.setattr(scorer, "close", failing_close) + 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, - scorer, + make_scorer, _record_for_certification(builder, plan, fit, tmp_path), _certification(builder, tmp_path, evidence_release=False), + opened, ) assert "OSError: the batch directory is gone" in capsys.readouterr().err finally: - type(scorer).close(scorer) + for scorer in opened: + type(scorer).close(scorer) @pytest.mark.parametrize( @@ -1595,18 +1676,20 @@ def test_a_failed_check_that_does_not_stop_certification_cancels_nothing( is scored in the pool and writes its file.""" _use_probes(monkeypatch, passing=False) plan, fit = _release_plan(builder) - scorer = _pooled_scorer(builder, plan, tmp_path / "scoring", 1) def finished(**arguments): raise _ScoringFinishedError monkeypatch.setattr(builder, "_write_population_structure_holdout", finished) + opened: list = [] try: with pytest.raises(_ScoringFinishedError): _certify_with( builder, monkeypatch, - scorer, + 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, @@ -1614,6 +1697,7 @@ def finished(**arguments): evidence_release=evidence_release, owners=owners, ), + opened, ) release_dir = tmp_path / "release" assert {path.name for path in release_dir.iterdir()} == { @@ -1629,4 +1713,4 @@ def finished(**arguments): "allow_reform_coverage_smoke_failures", False ) finally: - builder._close_post_export_scorer(scorer) + _close_opened(builder, opened) From 9197dbb33a5652a64a3c4679f94117ff1bcaca18 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:30:30 +0400 Subject: [PATCH 4/8] Describe closing the post-export scorer as it happens (review round 1) Review round 1 found the wording loose. The docstring of _close_post_export_scorer_after_error, the release-build doc and the changelog fragment now say that: - only workers running a unit are killed at once; idle workers are told to exit and killed after 10 seconds if they have not; - with one worker, reform validation's first unit is handed out as the smoke's last result comes back, before the smoke's result is decided; - an Exception from closing is printed and the first error raised, but an interrupt while closing (Ctrl-C, or a first SIGTERM) is raised instead; - batch files a failed close left are removed when the process exits. No code changes. Co-Authored-By: Claude Opus 5.5 --- ...t-export-scorer-closed-on-error.changed.md | 2 +- docs/us-release-build-rule.md | 30 +++++++++++-------- tools/build_us_fiscal_refresh_release.py | 11 ++++--- 3 files changed, 26 insertions(+), 17 deletions(-) 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 index a8f2d88dee..37062e91b1 100644 --- a/changelog.d/us-post-export-scorer-closed-on-error.changed.md +++ b/changelog.d/us-post-export-scorer-closed-on-error.changed.md @@ -1 +1 @@ -US certification closes the post-export scorer when any error stops it during scoring, before the error is raised: 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's workers then stop at once, those still running a unit (reform validation's first units, which start while the smoke's last are running) are killed instead of running until the process exits, and the batch files are removed. An error from closing is printed, and the first error is the one raised. A failed smoke that certification goes on past (the allow option, or an evidence failure with an owner) cancels nothing. +US certification closes the post-export scorer when any error stops it during scoring, before the error is raised: 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 1662af3dc2..63036e4ed6 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -560,18 +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, 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, - so reform validation's first units start while the smoke's last are - running. 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 is - raised: the workers stop at once, those still running a unit are killed, - and the batch files are removed. An error from closing is printed and the - first error raised. 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. + - 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 is raised: 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/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 5101fc3657..6d976b85a1 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -6609,10 +6609,13 @@ def _close_post_export_scorer_after_error( ) -> None: """Close the scorer after an error that stops certification. - A pooled scorer stops its workers, killing those still running a unit, - and every scorer removes its batch files. An error from closing is - printed, not raised, so the error that stopped certification is the one - raised. + 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, 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) From d3e44e9563434e9105ac780d5b81565e612250ed Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:56:32 +0400 Subject: [PATCH 5/8] Add failing tests for review round 2 of closing the post-export scorer Review round 2 found nothing serious in the change. From its findings: - An error from closing whose text cannot be made (its __str__ raises) replaces the error that stopped certification, because the warning formats it unguarded. New case test_an_error_closing_the_scorer_does_not_replace_the_one_that_stopped_it [unprintable] fails until the warning is guarded. - These pass already and pin documented behaviour: - test_an_interrupt_while_closing_the_scorer_is_raised: an interrupt while closing is raised, with the first error as its context; - test_a_stage_error_kills_the_units_still_running: reform validation failing while the worker runs its next unit kills that unit at once. - test_a_failed_check_that_does_not_stop_certification_cancels_nothing passed even when the busy worker was killed and its unit run again in a fresh one (the reviewer showed this). It now also requires one pool, one worker start and no failed attempts. - The tests build their exceptions inside the test, not at collection, so no exception and its traceback outlives its test. - Wording: WAIT_FOR_OTHER_REFORMS waits before each variable an engine computes; the module docstring lists the closing tests. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_post_export_pooled_scoring.py | 181 +++++++++++++++++- .../microcosm_build/us_post_export_pool.py | 2 +- 2 files changed, 172 insertions(+), 11 deletions(-) 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 a794d21928..1e3b60fc6a 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,7 +15,12 @@ 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. @@ -1554,11 +1559,11 @@ def gate_once_reform_validation_started(**arguments): @pytest.mark.parametrize( - ("pooled", "error"), + ("pooled", "error_type"), [ - (True, RuntimeError("the demographics writer broke")), - (False, RuntimeError("the demographics writer broke")), - (True, BuildTerminatedError()), + (True, RuntimeError), + (False, RuntimeError), + (True, BuildTerminatedError), ], ids=["pooled", "serial", "pooled_sigterm"], ) @@ -1568,7 +1573,7 @@ def test_any_error_during_scoring_closes_the_scorer( tmp_path, monkeypatch, pooled, - error, + 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 @@ -1577,6 +1582,7 @@ def test_any_error_during_scoring_closes_the_scorer( ``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: @@ -1615,20 +1621,41 @@ def broken_demographics(**arguments): _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 too, certification prints - that second error and raises the first, the check's refusal.""" + """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 OSError("the batch directory is gone") + raise close_error_type(*close_error_arguments) def make_scorer(batch_parent): scorer = _serial_scorer( @@ -1648,12 +1675,140 @@ def make_scorer(batch_parent): _certification(builder, tmp_path, evidence_release=False), opened, ) - assert "OSError: the batch directory is gone" in capsys.readouterr().err + assert printed in capsys.readouterr().err + 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() + 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"), [ @@ -1712,5 +1867,11 @@ def finished(**arguments): 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 95fec3d48a..9601c0d144 100644 --- a/test_support/microcosm_build/us_post_export_pool.py +++ b/test_support/microcosm_build/us_post_export_pool.py @@ -25,7 +25,7 @@ (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 it computes anything, so a test can keep one stage's + 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 From c274b4b7920b894e9610a60a104de094e4771845 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:57:54 +0400 Subject: [PATCH 6/8] Fix review round 2 of closing the post-export scorer - _close_post_export_scorer_after_error guards making the warning's text: an error from closing whose __str__ raises is printed by its class name, and the error that stopped certification is still the one raised. - The release-build doc and the changelog fragment say the scorer is closed before the error leaves certification (it has already been raised by then). Co-Authored-By: Claude Opus 5.5 --- ...st-export-scorer-closed-on-error.changed.md | 2 +- docs/us-release-build-rule.md | 18 +++++++++--------- tools/build_us_fiscal_refresh_release.py | 8 ++++++-- 3 files changed, 16 insertions(+), 12 deletions(-) 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 index 37062e91b1..b258acd834 100644 --- a/changelog.d/us-post-export-scorer-closed-on-error.changed.md +++ b/changelog.d/us-post-export-scorer-closed-on-error.changed.md @@ -1 +1 @@ -US certification closes the post-export scorer when any error stops it during scoring, before the error is raised: 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. +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 63036e4ed6..6b564f4603 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -569,15 +569,15 @@ one Microsimulation over the whole file. 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 is raised: 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. + 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/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 6d976b85a1..56489c6588 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -6620,9 +6620,13 @@ def _close_post_export_scorer_after_error( 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__ print( - "warning: could not close the post-export scorer after an error: " - f"{type(close_error).__name__}: {close_error}", + f"warning: could not close the post-export scorer after an error: {detail}", file=sys.stderr, ) From ee457193e11ccb3d3b591498e60ec8195fa12b94 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:10:20 +0400 Subject: [PATCH 7/8] Add failing tests for review round 3 of closing the post-export scorer Review round 3 found nothing serious. From its findings: - When closing the scorer after an error raises, and writing the warning to standard error fails too (a broken pipe), the write's error replaces the one that stopped certification. New test_a_warning_that_cannot_be_written_does_not_replace_the_error fails until the write is guarded. - test_a_stage_error_kills_the_units_still_running also requires the batch parent the scorer made to be removed, as the neighbouring tests do. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_post_export_pooled_scoring.py | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) 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 1e3b60fc6a..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 @@ -1681,6 +1681,56 @@ def make_scorer(batch_parent): 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, @@ -1800,6 +1850,9 @@ def build_reform(*arguments, **options): 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 From f50914c84c77075500daf10b2228acd50769bed6 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:11:32 +0400 Subject: [PATCH 8/8] Fix review round 3 of closing the post-export scorer _close_post_export_scorer_after_error no longer lets a failed write of its warning (standard error's reader gone) replace the error that stopped certification: the print is guarded, and the first error is raised. Co-Authored-By: Claude Opus 5.5 --- tools/build_us_fiscal_refresh_release.py | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 56489c6588..a48469ca74 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -6612,10 +6612,10 @@ def _close_post_export_scorer_after_error( 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, 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. + 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) @@ -6625,10 +6625,15 @@ def _close_post_export_scorer_after_error( except Exception: # Its text cannot be made; its class still names it. detail = type(close_error).__name__ - print( - f"warning: could not close the post-export scorer after an error: {detail}", - file=sys.stderr, - ) + 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: