diff --git a/changelog.d/1263-us-acs-local-artifact-writer-binding.changed.md b/changelog.d/1263-us-acs-local-artifact-writer-binding.changed.md new file mode 100644 index 0000000000..60fbdd84bf --- /dev/null +++ b/changelog.d/1263-us-acs-local-artifact-writer-binding.changed.md @@ -0,0 +1 @@ +The ACS local-area release's package stage now refuses to give a build an ID that names code other than the code that wrote its calibrated artifact. Calibrate reads its code identity when the stage starts and records it in `consumer_export.json`; it refuses to write the artifact if the checkout's commit or dirty state changed before the write. Package requires the same commit, and counts a writer record that does not say its tree was clean as dirty. The interim WIC limitation now states exactly whom the assumption covers, and its receipt records how many people were allowed to lack a decision. diff --git a/docs/us-modal-stage-runbook.md b/docs/us-modal-stage-runbook.md index 4df67d7e21..c9834db0f0 100644 --- a/docs/us-modal-stage-runbook.md +++ b/docs/us-modal-stage-runbook.md @@ -533,6 +533,16 @@ one stage of a run at a time, because two concurrent stages would race on the same state directory. The attempt ledger enforces this, best effort (see "Preemption and restarts"). +For `us-acs-local-release`, run package at the commit calibrate ran at. +Calibrate records the code that wrote the calibrated H5 in +`consumer_export.json`: it reads the commit when the stage starts, reads it +again just before it writes the H5, and refuses to write if the commit or +the tree's dirty state changed in between. The build's ID names the +packaging code, so package refuses to give a build an ID that names any +other commit (microcosm#1263). A commit landing between the two stages means +re-running calibrate, qa and finalize at the new commit, or packaging at the +old one. + For a gated or private Hub input, set `MICROCOSM_MODAL_HF_SECRET` to the name of a Modal secret that holds `HF_TOKEN`, for example `huggingface-token` in the `policyengine` workspace. Otherwise no secret is attached. Only the diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/retired_stored_inputs.py b/packages/microcosm-build/src/microcosm/build/us_runtime/retired_stored_inputs.py index 203d5dbb21..be0de764f6 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/retired_stored_inputs.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/retired_stored_inputs.py @@ -37,7 +37,6 @@ from collections.abc import Collection from dataclasses import dataclass -from numbers import Real from typing import Any import numpy as np @@ -179,6 +178,7 @@ def _live_wic( "stored_decisions_kept": int(present.sum()), "stored_decisions_true": int(decisions[present].sum()), "people_assumed_true": int(assumed.sum()), + "people_allowed_without_decision": int(allowed.sum()), "rule": ACS_WIC_ASSUMPTION, "status": "interim", "flip_condition": ACS_WIC_FLIP_CONDITION, @@ -186,16 +186,15 @@ def _live_wic( def _booleans(values: pd.Series) -> np.ndarray: - """Stored decisions as Booleans: bools, or real numbers equal to 0 or 1.""" + """Stored decisions as Booleans: bools, or int or float numbers equal to 0 or 1.""" out = np.empty(len(values), dtype=bool) for position, value in enumerate(values.to_numpy(dtype=object)): if isinstance(value, (bool, np.bool_)): out[position] = bool(value) - elif ( - isinstance(value, Real) - and not isinstance(value, (bool, np.bool_)) - and value in (0, 1) + elif isinstance(value, (int, float, np.integer, np.floating)) and value in ( + 0, + 1, ): out[position] = bool(value) else: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py index a1e174d50f..d801358c6e 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py @@ -2,18 +2,23 @@ from __future__ import annotations +import functools import importlib.util import inspect import json import os import re import shlex +import subprocess +import sys from pathlib import Path from types import SimpleNamespace import numpy as np import pandas as pd import pytest +from hypothesis import given, settings +from hypothesis import strategies as st from microcosm.build.gates import GateResult from microcosm.build.us_runtime import spm_measurement_gate @@ -156,6 +161,16 @@ def _spm_measurement_gate_passes(monkeypatch): ) +def _writer_code(module) -> dict: + """This checkout's code identity, as the calibrate stage records it.""" + + return module._repo_code_identity(allow_dirty=True) + + +#: A code identity as the calibrate stage reads it when it starts. +_STARTED_CODE = {"sha": "a" * 9, "commit": "a" * 40, "dirty": False, "branch": "main"} + + def _load_tool_module(): root = _TEST_PATHS.repository path = root / "tools" / "build_us_acs_local_release.py" @@ -801,6 +816,7 @@ def limitation(consumer_export): "from": "would_claim_wic", "to": "takes_up_wic_if_eligible", "people_assumed_true": 12, + "people_allowed_without_decision": 20, "flip_condition": "Drop it once microcosm#1156 lands.", } } @@ -809,6 +825,16 @@ def limitation(consumer_export): assert entry["status"] == "reviewed_interim_assumption" assert entry["column"] == "takes_up_wic_if_eligible" assert entry["people_assumed_true"] == 12 + # The text claims only what the rule did: the people without a decision. + assert ( + "every person without one (12, all on the ACS spine, of 20" in entry["reason"] + ) + # A receipt from before the count existed renders no count it lacks. + older = json.loads(json.dumps(applied)) + del older["live_stored_inputs"]["wic"]["people_allowed_without_decision"] + older_reason = limitation(older)["reason"] + assert "None" not in older_reason + assert "every person without one (12, all on the ACS spine) is set" in older_reason assert entry["treatment"] == "Drop it once microcosm#1156 lands." assert entry["calibration_blocker"] is False assert limitation(None) is None @@ -869,6 +895,260 @@ def test_only_acs_spine_people_may_lack_a_wic_decision() -> None: ) +@pytest.mark.parametrize( + "spine", + [np.nan, None, b"acs_2024_1yr", "ACS_2024_1YR"], + ids=["nan", "none", "bytes", "other-label"], +) +def test_an_unreadable_spine_tag_refuses_rather_than_fills(spine) -> None: + """A person whose tag is not exactly the ACS spine may not lack one.""" + + module = _load_tool_module() + frame = _spine_frame(["acs_2024_1yr", spine], [None, None]) + + with pytest.raises(SystemExit, match="did not allow"): + module._with_live_stored_inputs(frame) + + +def test_a_person_table_without_the_spine_tag_is_refused() -> None: + from microcosm.frame import Frame + + module = _load_tool_module() + frame = _spine_frame(["acs_2024_1yr"], [None]) + tables = {entity: frame.table(entity) for entity in frame.entities} + tables["person"] = tables["person"].drop(columns="person_spine") + untagged = Frame( + tables, + frame.schema, + {entity: frame.weights_for(entity) for entity in frame.weighted_entities}, + ) + + with pytest.raises(SystemExit, match="person_spine"): + module._with_live_stored_inputs(untagged) + + +@pytest.mark.parametrize( + ("written_by", "allow_dirty", "match"), + [ + (None, True, "records no code identity"), + ({"sha": "abc1234"}, True, "records no code identity"), + ({"commit": ""}, True, "records no code identity"), + ({"commit": "0" * 40, "dirty": False}, True, "written by code 0000000"), + ({"commit": "a" * 40, "dirty": True}, False, "dirty tree"), + ( + {"commit": "a" * 40}, + False, + r"does not say the tree was clean \(dirty=None\)", + ), + ({"commit": "a" * 40, "dirty": None}, False, "does not say the tree was clean"), + ({"commit": "a" * 40, "dirty": 0}, False, r"does not say .*\(dirty=0\)"), + ], + ids=[ + "absent", + "short-sha-only", + "empty", + "other-commit", + "dirty-writer", + "no-dirty-key", + "dirty-null", + "dirty-zero", + ], +) +def test_package_gives_a_build_an_id_only_for_the_code_that_wrote_it( + written_by, allow_dirty, match +) -> None: + """The build's ID names the packaging code, so that code must have + written the calibrated bytes (reviews of microcosm#1309 and #1311).""" + + module = _load_tool_module() + code = {"sha": "aaaaaaaaa", "commit": "a" * 40, "dirty": False, "branch": "main"} + export = {} if written_by is None else {"code": written_by} + + with pytest.raises(SystemExit, match=match) as refused: + module._require_artifact_written_by(export, code, allow_dirty=allow_dirty) + # Since microcosm#1571 the release is fixed and the build's ID names the + # code, so no refusal speaks of naming a release. + assert "release" not in str(refused.value) + assert "build's ID" in str(refused.value) + + # The abbreviated sha may differ in length between checkouts; only the + # full commit is compared. + assert ( + module._require_artifact_written_by( + {"code": {"sha": "aaaaaaa", "commit": "a" * 40, "dirty": False}}, + code, + allow_dirty=False, + ) + is False + ) + assert ( + module._require_artifact_written_by( + {"code": {"commit": "a" * 40, "dirty": True}}, code, allow_dirty=True + ) + is True + ) + # A record that does not say it was clean marks the build dirty. + assert ( + module._require_artifact_written_by( + {"code": {"commit": "a" * 40}}, code, allow_dirty=True + ) + is True + ) + + +def test_the_writer_binding_speaks_of_the_build_not_the_release() -> None: + """Since microcosm#1571 a build's ID names the code and the release's ID + does not; the binding's docstring and the runbook say so.""" + + module = _load_tool_module() + doc = inspect.getdoc(module._require_artifact_written_by) + + assert "build's ID names the packaging code" in doc + assert "release" not in doc + + runbook = _TEST_PATHS.repository / "docs" / "us-modal-stage-runbook.md" + text = runbook.read_text() + start = text.index("For `us-acs-local-release`, run package at the commit") + paragraph = " ".join(text[start : text.index("\n\n", start)].split()) + assert "The build's ID names the packaging code" in paragraph + assert "name a release" not in paragraph + + +@functools.cache +def _tool_module_once(): + """One load of the tool, for tests that patch nothing on it.""" + + return _load_tool_module() + + +@pytest.mark.parametrize( + ("writer_commit", "packaging_commit"), + [(1, 1), (True, 1), (["a" * 40], ["a" * 40])], + ids=["equal-integers", "true-equals-one", "equal-lists"], +) +def test_a_commit_that_is_not_a_string_names_no_code( + writer_commit, packaging_commit +) -> None: + """Equal values bind a build to its writer only when they are commit + strings: ``True == 1`` binds nothing.""" + + module = _tool_module_once() + code = { + "sha": "aaaaaaa", + "commit": packaging_commit, + "dirty": False, + "branch": "main", + } + export = {"code": {"commit": writer_commit, "dirty": False}} + + with pytest.raises(SystemExit, match="records no code identity"): + module._require_artifact_written_by(export, code, allow_dirty=True) + + +_HEX = "0123456789abcdef" +#: What a writer record may hold for its tree's state; ``False`` is the only +#: one that says the tree was clean, and it is drawn more often. +_DIRTY_VALUES = st.sampled_from([False, False, False, True, None, 0, 1, "false", ""]) + + +def _packaging_commits(): + """A packaging identity's commit: a full commit, or anything else.""" + + return st.one_of( + st.text(_HEX, min_size=40, max_size=40), + st.text(_HEX, min_size=40, max_size=40), + st.text(_HEX, max_size=40), + st.text(max_size=8), + st.none(), + st.booleans(), + st.integers(), + ) + + +def _records_naming(commit): + """A ``consumer_export.json`` whose writer record names ``commit``.""" + + record = st.fixed_dictionaries( + {"commit": st.just(commit)}, + optional={"dirty": _DIRTY_VALUES, "sha": st.just("abc1234")}, + ) + return st.fixed_dictionaries({"code": record}) + + +def _other_records(commit): + """Any other ``consumer_export.json``, with near misses of ``commit``.""" + + near = [commit, 1, True] + if isinstance(commit, str): + near += [commit.upper(), commit[:7], f"{commit} "] + commits = st.one_of( + st.sampled_from(near), + st.text(_HEX, max_size=40), + st.none(), + st.integers(), + ) + records = st.one_of( + st.fixed_dictionaries({"commit": commits}, optional={"dirty": _DIRTY_VALUES}), + st.fixed_dictionaries( + {}, optional={"sha": st.just("abc1234"), "dirty": _DIRTY_VALUES} + ), + st.none(), + st.text(max_size=5), + st.lists(st.just(commit), max_size=2), + ) + return st.one_of(st.just({}), st.fixed_dictionaries({"code": records})) + + +@settings(max_examples=200, deadline=None, database=None) +@given(data=st.data()) +def test_the_writer_binding_returns_only_for_its_own_clean_or_allowed_writer( + data, +) -> None: + """For any writer record and any packaging identity, package goes on only + when the two commits are equal, non-empty strings and the writer said it + was clean or dirt is allowed; otherwise it refuses. It reads a writer as + clean only for an explicit ``dirty: false``. + """ + + module = _tool_module_once() + commit = data.draw(_packaging_commits()) + code = { + "sha": "abc1234", + "commit": commit, + "dirty": data.draw(st.booleans()), + "branch": "main", + } + # Half the records name the packaging commit, so the dirty rule is reached. + records = _records_naming if data.draw(st.booleans()) else _other_records + export = data.draw(records(commit)) + allow_dirty = data.draw(st.booleans()) + + written_by = export.get("code") + writer_commit = written_by.get("commit") if isinstance(written_by, dict) else None + same_commit = ( + isinstance(writer_commit, str) + and writer_commit != "" + and writer_commit == commit + ) + said_clean = same_commit and written_by.get("dirty") is False + if same_commit and (said_clean or allow_dirty): + writer_dirty = module._require_artifact_written_by( + export, code, allow_dirty=allow_dirty + ) + assert writer_dirty is (not said_clean) + else: + with pytest.raises(SystemExit): + module._require_artifact_written_by(export, code, allow_dirty=allow_dirty) + + +def test_the_recorded_code_identity_carries_the_full_commit() -> None: + module = _load_tool_module() + code = module._repo_code_identity(allow_dirty=True) + + assert len(code["commit"]) == 40 + assert code["commit"].startswith(code["sha"]) + + def test_parse_args_enforces_stage_requirements(tmp_path: Path) -> None: module = _load_tool_module() base = [ @@ -1908,6 +2188,7 @@ def test_consumer_export_refuses_a_pre_ssi_disability_staging_before_loading_it( np.ones(1), {"acs_local_take_up": _TAKE_UP_RECEIPT}, {}, + code=_STARTED_CODE, ) @@ -2084,6 +2365,7 @@ def test_consumer_export_refuses_a_pre_anchor_staging_before_loading_it( np.ones(1), {"acs_local_take_up": _TAKE_UP_RECEIPT}, {}, + code=_STARTED_CODE, ) @@ -2300,6 +2582,7 @@ def test_consumer_export_refuses_a_checkpoint_without_the_ssi_medicaid_assignmen np.ones(1), {"acs_local_take_up": _TAKE_UP_RECEIPT}, {}, + code=_STARTED_CODE, ) @@ -2615,6 +2898,7 @@ def test_consumer_export_refuses_a_pre_1021_staging_before_loading_it( np.ones(1), {"acs_local_take_up": _TAKE_UP_RECEIPT}, {}, + code=_STARTED_CODE, ) @@ -2755,7 +3039,10 @@ def _package_evidence_args(module, tmp_path: Path, monkeypatch, *, hours_report) "artifact_sha256": artifact_sha, "per_spine": {}, }, - "consumer_export.json": {"staging_sha256": module._sha256(staging)}, + "consumer_export.json": { + "staging_sha256": module._sha256(staging), + "code": _writer_code(module), + }, "held_back_columns.json": {"total": 0}, "reviewed_null_fills.json": {"columns_filled": 0, "fills": []}, "materialize_rss.json": { @@ -4695,7 +4982,10 @@ def test_the_district_ess_gate_ships_in_both_manifests( "artifact_sha256": artifact_sha, "per_spine": {}, }, - "consumer_export.json": {"staging_sha256": artifact_sha}, + "consumer_export.json": { + "staging_sha256": artifact_sha, + "code": _writer_code(module), + }, "consumer_reviewed_null_fills.json": {"columns_filled": 0, "fills": []}, } for name, value in evidence.items(): @@ -4744,7 +5034,10 @@ def test_finalize_report_round_trips_into_package(tmp_path, monkeypatch) -> None "artifact_sha256": artifact_sha, "per_spine": {}, }, - "consumer_export.json": {"staging_sha256": artifact_sha}, + "consumer_export.json": { + "staging_sha256": artifact_sha, + "code": _writer_code(module), + }, "consumer_reviewed_null_fills.json": {"columns_filled": 0, "fills": []}, } for name, value in evidence.items(): @@ -4815,6 +5108,7 @@ def test_a_sparse_era_calibration_is_bound_through_finalize_and_package( "run_identity_sha256": stamp, "out_h5_sha256": artifact_sha, "weights_sha256": "w", + "code": _writer_code(module), } qa = { "plain_consumption": True, @@ -4998,7 +5292,10 @@ def _package_args_with_hours( "artifact_sha256": artifact_sha, "per_spine": {}, }, - "consumer_export.json": {"staging_sha256": artifact_sha}, + "consumer_export.json": { + "staging_sha256": artifact_sha, + "code": _writer_code(module), + }, "consumer_reviewed_null_fills.json": {"columns_filled": 0, "fills": []}, } for name, value in evidence.items(): @@ -5185,6 +5482,44 @@ def test_package_refuses_historical_staging_with_incomplete_work_experience( assert not (args.out / module.ARTIFACT_FILENAME).exists() +def _set_writer(args, **changes) -> None: + path = args.checkpoint_dir / "consumer_export.json" + export = json.loads(path.read_text()) + export["code"] = {**export["code"], **changes} + path.write_text(json.dumps(export)) + + +@requires_pytables +def test_package_refuses_another_writer_before_any_release_dir(tmp_path, monkeypatch): + """The writer binding runs before the release directory exists.""" + + module = _load_tool_module() + args = _package_args_with_hours(module, tmp_path, monkeypatch, gate_state="passed") + _set_writer(args, commit="0" * 40) + + with pytest.raises(SystemExit, match="written by code 0000000"): + module.do_package(args) + assert not (args.out / "releases").exists() + + +@requires_pytables +def test_a_dirty_writer_marks_the_build_dirty(tmp_path, monkeypatch): + """A clean packaging tree cannot hide a dirty writer (review of #1311).""" + + module = _load_tool_module() + # A clean packaging tree, whatever this checkout's state, so only the + # writer's flag can make the build dirty. + clean = {**module._repo_code_identity(allow_dirty=True), "dirty": False} + monkeypatch.setattr(module, "_repo_code_identity", lambda allow_dirty: dict(clean)) + args = _package_args_with_hours(module, tmp_path, monkeypatch, gate_state="passed") + _set_writer(args, dirty=True) + + release_dir = Path(module.do_package(args)["release_dir"]) + + build = json.loads((release_dir / "build_manifest.json").read_text()) + assert build["build_dirty"] is True + + @requires_pytables def test_package_records_the_stored_input_gate_bound_to_the_packaged_bytes( tmp_path, monkeypatch @@ -6577,6 +6912,244 @@ def test_do_calibrate_stamps_and_records_the_penalty_settings( assert calls == [] +def _calibrate_through_the_write(module, tmp_path: Path, monkeypatch, reads: list): + """Drive ``do_calibrate`` through a tiny real solve into the real write. + + The write's heavy collaborators (staging load, take-up, projection, + reviewed-null fill, live inputs, the lean checkpoint and the H5 writer) + are stubbed. The git reader answers from ``reads`` in order and raises an + exception it finds there. Returns the args and the ordered events: each + ``git`` read, the ``solve``, ``prepare`` when the last collaborator before + the H5 has run, and the ``write`` of the H5. + """ + + import types + + from scipy import sparse + + import microcosm.calibrate as calibrate_package + from microcosm.calibrate import TargetSpec + + events: list[str] = [] + answers = iter(reads) + + def git_reader(allow_dirty): + # Calibrate records a dirty tree; it never refuses one itself. + assert allow_dirty is True + events.append("git") + answer = next(answers) + if isinstance(answer, BaseException): + raise answer + return dict(answer) + + monkeypatch.setattr(module, "_repo_code_identity", git_reader) + frame, design, targets = _tiny_calibration_surface() + identity = { + "staging_sha256": "s", + "target_roles_sha256": "r", + "acs_local_take_up": _TAKE_UP_RECEIPT, + } + monkeypatch.setattr(module, "_verify_run_identity", lambda args: identity) + income = TargetSpec( + name="income", + entity="household", + measure="income", + value=next(iter(targets)).value, + source="fixture", + family="irs_soi", + metadata={ + "measure_mode": "sum", + "source_measure_id": "adjusted_gross_income_amount", + "ledger_measure_unit": "usd", + "ledger_geography_level": "state", + "state_fips": "06", + }, + ) + monkeypatch.setattr( + module, + "load_checkpoint_surface", + lambda *a, **k: ( + frame, + design, + SimpleNamespace(specs=(income,)), + [{"name": "income", "role": "train"}], + sparse.csr_array((1, len(design)), dtype=np.float32), + ), + ) + monkeypatch.setattr( + module.cd_surface, "calibration_target_set", lambda *a, **k: targets + ) + monkeypatch.setattr( + module, + "calibration_evidence", + lambda **kwargs: {"cd_holdout": {"n_targets": 0}, "n_holdout_targets": 0}, + ) + monkeypatch.setattr( + calibrate_package, + "write_calibration_diagnostics", + lambda *a, **k: SimpleNamespace( + status="available", schema_version=8, sha256="diagnostics" + ), + ) + solve = module.calibrate_surface + + def recording_solve(*a, **k): + events.append("solve") + return solve(*a, **k) + + monkeypatch.setattr(module, "calibrate_surface", recording_solve) + + monkeypatch.setattr(module, "_load_staging_frame", lambda path: frame) + monkeypatch.setattr(module, "_require_local_hours", lambda *a: None) + monkeypatch.setattr(module, "_require_acs_self_employment_identity", lambda f: None) + monkeypatch.setattr( + module, + "_with_local_take_up", + lambda f, seed: (f, {"assigned_sha256": _TAKE_UP_RECEIPT["assigned_sha256"]}), + ) + monkeypatch.setattr(module, "_with_recorded_ssi_medicaid_take_up", lambda f, *a: f) + monkeypatch.setattr(module, "project_input_only", lambda f, **k: (f, {})) + monkeypatch.setattr(module, "fill_reviewed_nulls", lambda *a, **k: ([], None)) + + def live_stored_inputs(f): + events.append("prepare") + return SimpleNamespace(frame=f, provenance={}) + + monkeypatch.setattr(module, "_with_live_stored_inputs", live_stored_inputs) + + class LeanCheckpoint: + def __init__(self, path, mode): + assert Path(path).name == "target_frame_lean.h5" + + def __enter__(self): + return {"household": frame.table("household")} + + def __exit__(self, *exc): + return False + + monkeypatch.setattr(pd, "HDFStore", LeanCheckpoint) + + def write_dataset(calibrated, path, **kwargs): + events.append("write") + path.write_bytes(b"calibrated") + + builder = types.ModuleType("build_us_acs_multispine_base") + builder._write_dataset = write_dataset + monkeypatch.setitem(sys.modules, "build_us_acs_multispine_base", builder) + + args = module._parse_args( + _calibrate_stage_argv(tmp_path, "--epochs", "2", "--epoch-batch", "2") + ) + args.checkpoint_dir.mkdir() + module._staging_summary_path(args).write_text( + json.dumps(_staging_receipt_anchor_summary()) + ) + identity["acs_local_ssi_medicaid_take_up"] = _ssi_medicaid_receipt( + module, args.checkpoint_dir + ) + return args, events + + +def test_calibrate_records_the_code_it_read_when_it_started( + tmp_path: Path, monkeypatch +) -> None: + """consumer_export.json names the code read before the solve, and the + checkout is read again just before the H5 (review of microcosm#1311).""" + + module = _load_tool_module() + # Only the branch moved, which names no code: the write goes on, and the + # record keeps what the stage read when it started. + renamed = {**_STARTED_CODE, "branch": "renamed"} + resumed = {**_STARTED_CODE, "sha": "c" * 9, "commit": "c" * 40} + args, events = _calibrate_through_the_write( + module, tmp_path, monkeypatch, [_STARTED_CODE, renamed, resumed, resumed] + ) + + module.do_calibrate(args) + + export_path = args.checkpoint_dir / "consumer_export.json" + export = json.loads(export_path.read_text()) + assert export["code"] == _STARTED_CODE + assert export["out_h5_sha256"] == module._sha256(args.out_h5) + # The second read comes after everything that prepares the artifact. + assert events == ["git", "solve", "prepare", "git", "write"] + + # A resumed run with nothing left to solve only writes the artifact + # again, and records the code that writes it this time. + events.clear() + args.resume = True + module.do_calibrate(args) + + assert json.loads(export_path.read_text())["code"] == resumed + assert events == ["git", "prepare", "git", "write"] + + +@pytest.mark.parametrize( + ("started", "at_write", "refusal"), + [ + ( + _STARTED_CODE, + {**_STARTED_CODE, "sha": "b" * 9, "commit": "b" * 40}, + r"started at a{40} \(dirty=False\) and is now at b{40} \(dirty=False\)", + ), + ( + _STARTED_CODE, + {**_STARTED_CODE, "dirty": True}, + r"started at a{40} \(dirty=False\) and is now at a{40} \(dirty=True\)", + ), + ( + {**_STARTED_CODE, "dirty": True}, + _STARTED_CODE, + r"started at a{40} \(dirty=True\) and is now at a{40} \(dirty=False\)", + ), + ( + _STARTED_CODE, + subprocess.CalledProcessError(128, ["git", "rev-parse", "HEAD"]), + None, + ), + ], + ids=["moved", "dirtied", "cleaned", "git-fails"], +) +def test_calibrate_writes_nothing_from_a_checkout_that_changed( + tmp_path: Path, monkeypatch, started, at_write, refusal +) -> None: + """A checkout whose commit or dirty state changes during the solve, or a + git that fails at the write, stops the stage before any byte of the H5 or + of consumer_export.json exists (review of #1311).""" + + module = _load_tool_module() + args, events = _calibrate_through_the_write( + module, tmp_path, monkeypatch, [started, at_write] + ) + + if refusal is None: + with pytest.raises(subprocess.CalledProcessError): + module.do_calibrate(args) + else: + with pytest.raises(SystemExit, match=refusal): + module.do_calibrate(args) + assert events == ["git", "solve", "prepare", "git"] + assert not args.out_h5.exists() + assert not (args.checkpoint_dir / "consumer_export.json").exists() + + +def test_calibrate_reads_the_code_before_it_solves(tmp_path: Path, monkeypatch) -> None: + """A git that fails at the start fails the stage before hours of solving.""" + + module = _load_tool_module() + args, events = _calibrate_through_the_write( + module, + tmp_path, + monkeypatch, + [subprocess.CalledProcessError(128, ["git", "rev-parse", "HEAD"])], + ) + + with pytest.raises(subprocess.CalledProcessError): + module.do_calibrate(args) + assert events == ["git"] + assert not (args.checkpoint_dir / "weights_latest.npz").exists() + + def test_a_stamp_from_before_the_penalty_settings_reads_as_the_historical_solve( tmp_path: Path, ) -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_retired_stored_inputs.py b/packages/microcosm-build/tests/engine_free/us/test_us_retired_stored_inputs.py index 62fdd90cdb..e05bacfdab 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_retired_stored_inputs.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_retired_stored_inputs.py @@ -1,8 +1,10 @@ """Moving the donor's retired stored inputs to the live ones (microcosm#1263). Every frame here is invented. The engine is a variable-name set, so no -policyengine-us is imported; ``test_us_retired_stored_inputs_engine`` checks -the names against the installed engine. +policyengine-us is imported. The installed engine's side of the premise (the +live input is a Person Boolean defaulting to True, and neither retired name is +defined) is pinned by +``packages/microcosm-data/tests/engine_contract/us/test_stored_inputs.py``. """ from __future__ import annotations @@ -32,13 +34,11 @@ def _remedy(frame, engine=ENGINE, allowed=None): - """The rule with the release tool's mask: the ACS people may lack one.""" + """The rule with the release tool's mask: the ACS-spine people may lack one.""" if allowed is None: - channels = frame.table("person")["person_support_channel"].map( - lambda value: value.decode() if isinstance(value, bytes) else value - ) - allowed = channels.eq(ACS_CHANNEL).to_numpy(dtype=bool) + spine = frame.table("person")["person_spine"] + allowed = spine.eq(ACS_CHANNEL).fillna(False).to_numpy(dtype=bool) return with_live_stored_inputs( frame, engine_variables=engine, may_lack_decision=allowed ) @@ -50,6 +50,9 @@ def _frame(channels, decisions=None, part_b=None) -> Frame: frame = acs_frame([[(20, 40.0)] for _ in channels]) person = frame.table("person").copy() person["person_support_channel"] = channels + person["person_spine"] = [ + ACS_CHANNEL if channel == ACS_CHANNEL else "asec_puf" for channel in channels + ] if decisions is not None: person[RETIRED_WIC_INPUT] = pd.Series(decisions, dtype=object) if part_b is not None: @@ -80,6 +83,7 @@ def test_donor_decisions_are_kept_and_acs_gaps_take_wic_up(): assert wic["stored_decisions_kept"] == 2 assert wic["stored_decisions_true"] == 1 assert wic["people_assumed_true"] == 2 + assert wic["people_allowed_without_decision"] == 2 assert wic["status"] == "interim" assert "microcosm#1156" in wic["flip_condition"] @@ -166,6 +170,58 @@ def test_it_refuses_rather_than_guessing(channels, decisions, match): _remedy(_frame(channels, decisions)) +@pytest.mark.parametrize( + ("stored", "expected"), + [ + (pd.array([True, False, None], dtype="boolean"), [True, False, True]), + (np.array([True, False, True]), [True, False, True]), + (np.array([1.0, 0.0, np.nan]), [True, False, True]), + (pd.Series([True, False, None], dtype=object), [True, False, True]), + (pd.array([1, 0, None], dtype="Int64"), [True, False, True]), + (pd.array([1.0, 0.0, None], dtype="Float64"), [True, False, True]), + (np.array([1, 0, 1], dtype=np.int8), [True, False, True]), + (np.array([1, 0, 1], dtype=np.uint8), [True, False, True]), + ], + ids=[ + "pandas-boolean-NA", + "numpy-bool", + "float-0-1-nan", + "object", + "nullable-Int64-NA", + "nullable-Float64-NA", + "int8", + "uint8", + ], +) +def test_every_stored_boolean_dtype_reads_alike(stored, expected): + frame = _frame(["asec", "puf_tax_detail", ACS_CHANNEL]) + tables = {entity: frame.table(entity) for entity in frame.entities} + tables["person"] = tables["person"].assign(**{RETIRED_WIC_INPUT: stored}) + typed = Frame( + tables, + frame.schema, + {entity: frame.weights_for(entity) for entity in frame.weighted_entities}, + ) + + person = _remedy(typed).frame.table("person") + + assert person[LIVE_WIC_INPUT].dtype == bool + assert person[LIVE_WIC_INPUT].tolist() == expected + + +@pytest.mark.parametrize("value", ["fraction", "decimal", "complex"]) +def test_only_bools_and_real_zero_or_one_are_decisions(value): + """Bools and int/float 0/1 only. policyengine.py's reader refuses a + Fraction and a Decimal too; this rule is stricter about complex.""" + + from decimal import Decimal + from fractions import Fraction + + stored = {"fraction": Fraction(1), "decimal": Decimal(1), "complex": 1 + 0j} + with pytest.raises(ValueError, match="not a Boolean"): + _remedy(_frame(["asec"], [stored[value]])) + + def test_zero_one_numbers_are_read_as_decisions(): frame = _frame(["asec", "asec", "asec"], [1, 0.0, np.float64(1.0)]) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py index ef2c108d37..520851fffd 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py @@ -379,6 +379,11 @@ "release_gate_preflight.py", "release_input_coverage.py", "release_target_parity.py", + # Consumer-artifact remedy for two retired stored inputs (microcosm#1263): + # renames the WIC draw (keeping stored decisions and defaulting missing + # ones to True) and drops a dead column. It reads no provenance column; + # the release tool passes the people who may lack a decision. + "retired_stored_inputs.py", "scf_auto_loans.py", # SCF 2025 federal student loan inputs (microcosm#1073); a donor-model # stage shaped like scf_auto_loans. @@ -417,10 +422,6 @@ "spm_universe_source.py", # Reviewed held-out SSI/Social Security diagnostic; no population treatment. "ssi_social_security_holdout.py", - # Consumer-artifact remedy for two retired stored inputs (microcosm#1263): - # renames the WIC draw and drops a dead column. It reads no provenance - # column; the release tool passes the people who may lack a decision. - "retired_stored_inputs.py", "stacked_spine.py", # Provenance owner (#578 revision); see owners list. # Bake-off arm accounting, split mirror and ESS; evaluates support mixes, # never transforms a population. diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index b4d75bf3d2..813ab16c6e 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -2753,6 +2753,10 @@ def calibration_evidence( def do_calibrate(args) -> None: + # The checkout's code identity as this stage starts, before it loads or + # solves anything. The write reads it again and refuses if the commit or + # the dirty state changed in between (review of #1311). + code = _repo_code_identity(allow_dirty=True) from microcosm.calibrate import write_calibration_diagnostics identity = _verify_run_identity(args) @@ -2848,7 +2852,11 @@ def do_calibrate(args) -> None: "weights_latest.npz to recalibrate)." ) _write_calibrated_artifact( - args, np.asarray(warm, dtype=np.float64), identity, settings + args, + np.asarray(warm, dtype=np.float64), + identity, + settings, + code=code, ) county_surface.write_reports( args.checkpoint_dir, previous, identity=identity @@ -2954,7 +2962,11 @@ def save(weights: np.ndarray, epochs_done: int) -> None: } county_surface.write_reports(args.checkpoint_dir, summary, identity=identity) _write_calibrated_artifact( - args, np.asarray(result.weights, dtype=np.float64), identity, settings + args, + np.asarray(result.weights, dtype=np.float64), + identity, + settings, + code=code, ) holdout = summary["cd_holdout"] @@ -3086,7 +3098,7 @@ def _with_live_stored_inputs(frame): def _write_calibrated_artifact( - args, weights: np.ndarray, identity: dict, settings: dict + args, weights: np.ndarray, identity: dict, settings: dict, *, code: dict ) -> None: """Write the consumer-ready calibrated H5 with verified attachment. @@ -3097,7 +3109,10 @@ def _write_calibrated_artifact( fill — so a plain ``USSingleYearDataset``/``Microsimulation`` consumer loads the published file directly. The nullable staging H5 remains the archival nullable truth; every fill is recorded in the run's consumer - manifest. + manifest. ``code`` is the code identity the calibrate stage read when it + started; ``consumer_export.json`` records it, and this function writes + neither that file nor the H5 unless the checkout still has that commit + and dirty state just before the H5. """ if args.out_h5 is None: @@ -3172,6 +3187,8 @@ def _write_calibrated_artifact( projected.strata, mass_log=projected.mass_log, ) + # The last moment before any byte of the artifact exists. + _require_unchanged_code(code) _write_dataset( calibrated, Path(args.out_h5), @@ -3197,6 +3214,10 @@ def _write_calibrated_artifact( "assignment_file": ssi_medicaid["assignment_file"], }, "live_stored_inputs": live_inputs.provenance, + # The code that wrote these bytes, as read when the stage + # started. The build's ID names the packaging code, so + # package refuses any other writer. + "code": code, "note": ( "The engine-pass contract (input-schema projection + " "reviewed-null default fill) is applied to the published " @@ -3571,6 +3592,53 @@ def do_qa(args) -> None: ) +def _require_artifact_written_by( + consumer_export: dict, code: dict, *, allow_dirty: bool +) -> bool: + """Refuse to give a build an ID that names code other than its writer. + + The calibrate stage writes the published bytes and records its code in + ``consumer_export.json``; the build's ID names the packaging code. They + must be the same commit, so the build's ID names the code that produced + the artifact. A checkpoint that records no writer is refused, not + trusted. A writer record that does not say ``dirty: false`` counts as + dirty, so it needs ``allow_dirty``. + + Returns whether the writer's tree counts as dirty, so the build can + record it even when packaging runs from a clean tree. + """ + + written_by = consumer_export.get("code") + commit = written_by.get("commit") if isinstance(written_by, dict) else None + # A commit is a non-empty string; anything else names no code. + if not isinstance(commit, str) or not commit: + raise SystemExit( + "consumer_export.json records no code identity for the calibrated " + "H5, so the build's ID cannot be shown to name the code that wrote " + "it. Re-run --stage calibrate (then qa and finalize) with the " + "current tool." + ) + # Full commits: the abbreviated sha's length depends on the checkout (a + # shallow clone abbreviates shorter), so it cannot be compared. + if written_by["commit"] != code["commit"]: + raise SystemExit( + f"The calibrated H5 was written by code {written_by['commit']}, but " + f"packaging runs {code['commit']}, and the build's ID names the " + "packaging code. Package with the code that wrote the artifact, or " + "re-run --stage calibrate (then qa and finalize) with this code." + ) + # Only a record that says its tree was clean reads as clean. + writer_dirty = written_by.get("dirty") is not False + if writer_dirty and not allow_dirty: + raise SystemExit( + "The calibrated H5 was written from a dirty tree, or its record " + f"does not say the tree was clean (dirty={written_by.get('dirty')!r}); " + "a build's ID names a committed code vintage. Re-run --stage " + "calibrate from a clean tree, or pass --allow-dirty." + ) + return writer_dirty + + def _repo_code_identity(allow_dirty: bool) -> dict[str, object]: def _git(*parts: str) -> str: return subprocess.check_output( @@ -3578,6 +3646,7 @@ def _git(*parts: str) -> str: ).strip() sha = _git("rev-parse", "--short", "HEAD") + commit = _git("rev-parse", "HEAD") dirty = bool(_git("status", "--porcelain")) if dirty and not allow_dirty: raise SystemExit( @@ -3585,7 +3654,34 @@ def _git(*parts: str) -> str: "committed code vintage. Commit first or pass --allow-dirty " "(the manifest will record dirty=true)." ) - return {"sha": sha, "dirty": dirty, "branch": _git("branch", "--show-current")} + return { + "sha": sha, + "commit": commit, + "dirty": dirty, + "branch": _git("branch", "--show-current"), + } + + +def _require_unchanged_code(started: dict) -> None: + """Refuse to write the calibrated artifact from a checkout that moved. + + ``consumer_export.json`` records the code identity the calibrate stage + read when it started. A solve can run for hours, so just before calibrate + writes the H5 the checkout must still be at that commit and in that dirty + state; otherwise the record would name code other than the code that ran. + The branch's name may change: it names no code. + """ + + now = _repo_code_identity(allow_dirty=True) + if (now["commit"], now["dirty"]) != (started["commit"], started["dirty"]): + raise SystemExit( + "The checkout changed while calibrate ran: it started at " + f"{started['commit']} (dirty={started['dirty']}) and is now at " + f"{now['commit']} (dirty={now['dirty']}). Refusing to write the " + "calibrated H5 and consumer_export.json, whose record would name " + "code other than the code that ran. Re-run --stage calibrate from " + "a checkout that does not change during the run." + ) def _ess_concentration_limitation(diagnostics: dict) -> dict: @@ -3719,6 +3815,9 @@ def _acs_wic_takeup_limitation(consumer_export: dict | None) -> dict | None: assumed = wic.get("people_assumed_true") if not assumed: return None + # A receipt written before the count existed states no count. + allowed = wic.get("people_allowed_without_decision") + of_allowed = "" if allowed is None else f", of {allowed} ACS-spine people" return { "id": "acs_wic_takeup_assumed_interim", "status": "reviewed_interim_assumption", @@ -3731,8 +3830,9 @@ def _acs_wic_takeup_limitation(consumer_export: dict | None) -> dict | None: "people, and the donor stores its decisions under the retired " f"input name {wic.get('from')!r}, which the installed " "policyengine-us ignores. The consumer artifact stores them as " - f"{wic.get('to')!r}: every donor decision is kept, and every ACS " - "person is set to take WIC up when eligible. That is the engine's " + f"{wic.get('to')!r}: every stored decision is kept, and every " + f"person without one ({assumed}, all on the ACS spine{of_allowed}) " + "is set to take WIC up when eligible. That is the engine's " "default and the assumption policyengine.py applies to the same " "cells today; it is a modelling assumption, not observed " "participation." @@ -5440,6 +5540,8 @@ def do_finalize(args) -> None: "filled_columns", "total_values_filled", "staging_sha256", + "live_stored_inputs", + "code", ) } if consumer_export @@ -5818,6 +5920,9 @@ def do_package(args) -> dict: ) code = _repo_code_identity(args.allow_dirty) + writer_dirty = _require_artifact_written_by( + consumer_export, code, allow_dirty=args.allow_dirty + ) timestamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ") # The build's ID; it names the build within the local-area release. build_id = f"{RELEASE_ID_PREFIX}-{code['sha']}-{timestamp}" @@ -6037,7 +6142,9 @@ def _version(package: str) -> str: build_manifest = { "build_id": build_id, "build_sha": code["sha"], - "build_dirty": code["dirty"], + # Dirty if either the packaging tree or the tree that wrote the + # artifact was. + "build_dirty": bool(code["dirty"]) or writer_dirty, "created_at": datetime.now(UTC).isoformat(), "code": {"branch": code["branch"], "repo": "microcosm"}, "runtime": {