diff --git a/changelog.d/us-compatibility-engineering-pilot.added.md b/changelog.d/us-compatibility-engineering-pilot.added.md new file mode 100644 index 0000000000..2e362e1fdf --- /dev/null +++ b/changelog.d/us-compatibility-engineering-pilot.added.md @@ -0,0 +1 @@ +Add a US compatibility engineering pilot that retains at most 32 complete source households and their original weights, with a distinct partial receipt and existing runtime, parent and reviewed-column checks. diff --git a/docs/agent-guide.md b/docs/agent-guide.md index bfc2f08f6c..a8d00f9fee 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -514,6 +514,8 @@ what the tested engine reads or ignores must have an entry in `RECERTIFICATION_COLUMN_CHANGES`. It takes `--compatibility-wheel` and no `--parent-h5`. National parents only for now. See [the recertification runbook](us-compatibility-recertification.md). +For a source-preserving probe of at most 32 complete households, use the +[US compatibility engineering pilot](us-compatibility-engineering-pilot.md). Three US release seams refuse a stored column that is lowercase snake_case, not a variable of the engine the release is certified against, and not in the diff --git a/docs/us-compatibility-engineering-pilot.md b/docs/us-compatibility-engineering-pilot.md new file mode 100644 index 0000000000..d1bd3e371c --- /dev/null +++ b/docs/us-compatibility-engineering-pilot.md @@ -0,0 +1,48 @@ +# US compatibility engineering pilot + +Run `tools/probe_us_compatibility_recertification.py` to check native construction and household scoring on at most 32 complete source households. The tool keeps the original source weights and writes a partial engineering receipt. It supplies no population estimate or compatibility certification. + +## Inputs and invocation + +Prepare a pending ordinary compatibility-recertification candidate as the [recertification runbook](us-compatibility-recertification.md) describes. This pilot accepts only a schema 1 calibration parent and the existing 2024 scoring period. It rejects source-enrichment parents and passed candidates. + +Use the task's authenticated US environment and the three original official wheel files for its installed country model, Core and SPM calculator. The ordinary `scoring_runtime` check verifies the installed trees against those wheels and queries PyPI for the matching public wheel digests before the pilot loads the country engine. + +From the checkout root, run: + +```bash +uv run --no-sync python tools/probe_us_compatibility_recertification.py \ + --release-dir /absolute/candidate/microcosm-us-2024-national \ + --artifact-root /absolute/candidate/artifacts \ + --compatibility-wheel /absolute/wheels/policyengine_us-VERSION-py3-none-any.whl \ + --compatibility-wheel /absolute/wheels/policyengine_core-VERSION-py3-none-any.whl \ + --compatibility-wheel /absolute/wheels/spm_calculator-VERSION-py3-none-any.whl \ + --max-households 32 \ + --output /absolute/evidence/engineering-pilot.json +``` + +Replace the placeholder versions and paths with the task's actual authenticated artifacts. Create the output directory first, outside the release and artifact directories. The command refuses an existing output, including a symlink. The script creates a fresh bytecode cache before it imports Microcosm when the process lacks one; the existing bytecode checks still govern every run. + +Follow the applicable resource reservation and heavy-run rules before launching this command. Use one process, retain the configured numerical-thread limits, and record the native exit, wall time and peak memory beside the receipt. Full membership scans and model construction can still consume substantial memory; the household bound limits retained source rows, not a measured memory ceiling. + +## Source preservation + +The pilot first runs the ordinary candidate validator, which authenticates the carried parent manifests, release files and root artifacts. It then scans the household IDs and compact person memberships in chunks and selects the first source households in stored row order. This deterministic selection supplies an engineering fixture, not a statistical sample. + +The reader rejects duplicate or dangling IDs, incomplete selected households and group units that cross the selection boundary. It retains every selected person's referenced tax, SPM, family and marital unit, with the source row order, column order, values and dtypes. It neither rescales weights nor rewrites the H5. The reader requires all six entity tables, an explicit 2024 period and a supported table codec. + +The existing reviewed-column register governs every newly read or ignored model-named column. A known reviewed change can coexist with a raw stored-input refusal. The receipt records both `reviewed_changes_accepted` and the unchanged raw `h5_verdict`, including its `passed`, `refused` and failure fields. An unreviewed change or a direction mismatch stops the pilot. The tool adds no aliases, replacement care costs or register exceptions. + +## Native calculation and receipt + +The pilot constructs a native single-year dataset, then calls the public `extend_single_year_dataset(..., end_year=2024)` function. That base-year branch makes a one-year container without uprating the source inputs. The pilot checks every selected column before native construction and after scoring. + +One genuine native `Microsimulation` uses the parent's SPM configuration. The existing `_BatchFrames` and `_BatchScorer` calculate only metrics whose definitions declare household batching, with their original source weights. The receipt lists all excluded metrics. The guard refuses any known population or state aggregate cache after construction and before and after each metric, including branch caches. This check covers the existing aggregate-variable list; it does not establish universal separability across every model path. + +The tool verifies loaded module bytes, isolated bytecode, carried input hashes and selected input fingerprints before writing an exclusive JSON file. Nonfinite totals stop the run. Its receipt uses kind `compatibility_recertification_engineering_pilot`, records `population_estimate: false` and `compatibility_certification: "not_attested"`, and includes aggregate outcomes without raw household IDs or records. + +The ordinary score consumer still requires full household and state passes, the complete metric set and its existing runtime and source bindings. It rejects this pilot receipt. Qualification still needs the ordinary baseline, tested and withheld-input scores, drift and claim checks, publisher and consumer checks, and any wrapper or scientific-adapter work. A successful pilot supplies no default-dataset promotion, historical-law qualification or study-adoption decision. + +## Tests + +`engine_free/us/test_compatibility_recertification_pilot.py` checks selection closure, source preservation, limits, refusal order, reviewed-column accounting and ordinary-score rejection with pure synthetic fixtures. The `engine_workflow/us` module runs one tiny synthetic H5 through the real native constructor and scorer. That workflow uses explicit test-local parent, runtime and bytecode metadata stubs; it authenticates no real release. Both modules use existing registered test categories and add no CI job. diff --git a/packages/microcosm-data/tests/engine_free/us/test_compatibility_recertification_pilot.py b/packages/microcosm-data/tests/engine_free/us/test_compatibility_recertification_pilot.py new file mode 100644 index 0000000000..fba97eb81f --- /dev/null +++ b/packages/microcosm-data/tests/engine_free/us/test_compatibility_recertification_pilot.py @@ -0,0 +1,465 @@ +"""Pure pilot contracts. Every fixture contains synthetic MOCK inputs only.""" + +from __future__ import annotations + +import copy +import os +import subprocess +import sys +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.data import compatibility_recertification as recert +from test_support.microcosm_data.compatibility_recertification_pilot import ( + membership_inputs, + mock_tables, +) +from test_support.paths import paths_for +from tools import build_us_compatibility_recertification as scorer_tool +from tools import probe_us_compatibility_recertification as pilot + + +def test_direct_cli_outside_checkout_reaches_missing_wheel_refusal(tmp_path): + script = ( + paths_for("microcosm-data").repository + / "tools" + / "probe_us_compatibility_recertification.py" + ) + wheel = tmp_path / "NONEXISTENT_WHEEL.whl" + output = tmp_path / "MUST_NOT_BE_CREATED.json" + env = os.environ.copy() + for key in ("PYTHONPATH", "PYTHONHOME"): + env.pop(key, None) + run = subprocess.run( + [ + sys.executable, + "-B", + str(script), + "--release-dir", + str(tmp_path / "NONEXISTENT_RELEASE"), + "--artifact-root", + str(tmp_path / "NONEXISTENT_ARTIFACTS"), + "--output", + str(output), + "--compatibility-wheel", + str(wheel), + "--max-households", + "1", + ], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + timeout=60, + check=False, + ) + assert run.returncode == 2, run.stderr + assert "Engineering pilot refused:" in run.stderr + assert str(wheel) in run.stderr + assert not any( + message in run.stderr + for message in ("ModuleNotFoundError", "ImportError", "Traceback") + ) + assert run.stdout == "" + assert not output.exists() + + +@pytest.mark.parametrize("value", [False, True, 0, -1, 33, 1.0, "2", None]) +def test_invalid_limit_refuses_before_runtime_or_inputs(value, tmp_path, monkeypatch): + monkeypatch.setattr( + scorer_tool, "scoring_runtime", lambda *_: pytest.fail("runtime reached") + ) + with pytest.raises(pilot.EngineeringPilotError, match="integer from 1 to 32"): + pilot.probe_candidate( + release_dir=tmp_path / "absent", + artifact_root=tmp_path / "absent2", + output=tmp_path / "result.json", + compatibility_wheels=(), + max_households=value, + ) + + +@settings(max_examples=35, deadline=None) +@given( + sizes=st.lists(st.integers(1, 4), min_size=1, max_size=40), + limit=st.integers(1, 32), + reverse=st.booleans(), + unsigned=st.booleans(), +) +def test_selection_preserves_complete_source_rows_and_weights( + sizes, limit, reverse, unsigned +): + tables = mock_tables( + tuple(sizes), + id_dtype="uint64" if unsigned else "int64", + offset=2**53 + 17 if unsigned else 100, + ) + if reverse: + for entity in ("tax_unit", "spm_unit", "family", "marital_unit"): + tables[entity] = tables[entity].iloc[::-1].reset_index(drop=True) + before = pilot._frame_inventory(tables) + memberships, groups = membership_inputs(tables) + selected, masks = pilot._select_rows( + groups["household"], memberships, groups, max_households=limit + ) + count = min(limit, len(sizes)) + np.testing.assert_array_equal(selected, groups["household"][:count]) + assert selected.dtype == groups["household"].dtype + # Independent positional reference: each fixture household owns its next size rows. + people = set(tables["person"].person_id.iloc[: sum(sizes[:count])]) + for entity, frame in tables.items(): + if entity == "person": + expected = frame.person_id.isin(people) + else: + members = tables["person"].loc[ + tables["person"].person_id.isin(people), f"person_{entity}_id" + ] + expected = frame[f"{entity}_id"].isin(set(members)) + pd.testing.assert_frame_equal(frame.loc[masks[entity]], frame.loc[expected]) + assert len(masks[entity]) == len(frame) + assert pilot._frame_inventory(tables) == before + np.testing.assert_array_equal( + tables["household"].loc[masks["household"], "household_weight"], + tables["household"].household_weight.iloc[:count], + ) + + +@pytest.mark.parametrize( + "damage", + [ + "shared_unit", + "dangling_household", + "missing_group", + "duplicate_person", + "duplicate_group", + "orphan_household", + "float_id", + ], +) +def test_membership_damage_refuses_without_selecting_partial_households(damage): + tables = mock_tables((2, 2, 1)) + if damage == "shared_unit": + tables["person"].loc[2, "person_tax_unit_id"] = tables[ + "tax_unit" + ].tax_unit_id.iloc[0] + elif damage == "dangling_household": + tables["person"].loc[0, "person_household_id"] = 999999 + elif damage == "missing_group": + tables["tax_unit"] = tables["tax_unit"].iloc[1:] + elif damage == "duplicate_person": + tables["person"].loc[1, "person_id"] = tables["person"].person_id.iloc[0] + elif damage == "duplicate_group": + tables["family"].loc[1, "family_id"] = tables["family"].family_id.iloc[0] + elif damage == "orphan_household": + tables["person"] = tables["person"].iloc[2:] + elif damage == "float_id": + tables["household"]["household_id"] = tables["household"].household_id.astype( + float + ) + memberships, groups = membership_inputs(tables) + with pytest.raises(pilot.EngineeringPilotError): + pilot._select_rows(groups["household"], memberships, groups, max_households=1) + + +def test_boundary_members_outside_the_selection_refuse(): + tables = mock_tables((2, 1, 1)) + # The last person's family reaches the first household even though that row lies outside the selection. + tables["person"].loc[3, "person_family_id"] = tables[ + "person" + ].person_family_id.iloc[0] + memberships, groups = membership_inputs(tables) + with pytest.raises(pilot.EngineeringPilotError, match="another household"): + pilot._select_rows(groups["household"], memberships, groups, max_households=1) + + +def test_fingerprints_preserve_dtype_order_categories_and_object_types(): + source = pd.DataFrame( + { + "x": np.asarray([0.0, -0.0]), + "c": pd.Categorical( + ["a", "b"], categories=["a", "b", "unused"], ordered=True + ), + } + ) + digest = pilot._frame_inventory({"person": source}) + changes = [ + source.iloc[::-1].reset_index(drop=True), + source[["c", "x"]], + source.assign(x=source.x.astype("float32")), + source.assign(c=source.c.cat.reorder_categories(["b", "a", "unused"])), + source.assign(c=source.c.cat.as_unordered()), + ] + assert all( + pilot._frame_inventory({"person": changed}) != digest for changed in changes + ) + assert pilot._array_digest(np.asarray([1], dtype=object)) != pilot._array_digest( + np.asarray([True], dtype=object) + ) + assert pilot._array_digest( + np.asarray([b"one"], dtype=object) + ) != pilot._array_digest(np.asarray(["one"], dtype=object)) + with pytest.raises(pilot.EngineeringPilotError, match="unsupported stored scalar"): + pilot._array_digest(np.asarray([object()], dtype=object)) + + +def test_known_reviewed_changes_keep_raw_refusal_false_and_untouched(): + changes = { + recert.CHANGE_IGNORED: [ + {"column": "first_home_mortgage_interest", "tables": ["tax_unit"]} + ], + recert.CHANGE_READ: [{"column": "tax_unit_role_input", "tables": ["person"]}], + } + raw = { + "passed": False, + "refused": ["first_home_mortgage_interest"], + "failures": ["MOCK raw refusal"], + "register_sha256": "MOCK", + } + before = copy.deepcopy((changes, raw)) + result = pilot._reviewed_columns(changes, raw) + assert result == { + "reviewed_changes_accepted": True, + "changes": changes, + "raw_verdict": raw, + } + assert result["raw_verdict"]["passed"] is False + assert (changes, raw) == before + + +@pytest.mark.parametrize( + "column,direction", + [ + ("unreviewed_input", recert.CHANGE_IGNORED), + ("first_home_mortgage_interest", recert.CHANGE_READ), + ], +) +def test_unreviewed_or_wrong_direction_refuses(column, direction): + with pytest.raises(pilot.EngineeringPilotError): + pilot._reviewed_columns( + {direction: [{"column": column, "tables": ["person"]}]}, {"passed": False} + ) + + +def test_aggregate_guard_checks_all_branches_and_refuses_existing_cache(monkeypatch): + seen = [] + simulation = SimpleNamespace() + + def known(sim, variables, **kwargs): + seen.append((sim, variables, kwargs)) + return {("medicaid_slcsp_state_denominator", "2024")} + + monkeypatch.setattr(recert, "engine_known_periods", known) + with pytest.raises( + pilot.EngineeringPilotError, match="population/state aggregates" + ): + pilot._aggregate_guard(simulation) + assert seen == [ + ( + simulation, + recert.POPULATION_AGGREGATE_VARIABLES, + {"walk_branches": True, "skip_unknown": True}, + ) + ] + + +@pytest.mark.parametrize("damage", ["existing", "symlink", "input_root"]) +def test_output_refuses_before_runtime(damage, tmp_path, monkeypatch): + root = tmp_path / "inputs" + root.mkdir() + output = tmp_path / "result.json" + if damage == "existing": + output.write_text("KEEP") + elif damage == "symlink": + output.symlink_to(tmp_path / "absent") + else: + output = root / "result.json" + monkeypatch.setattr( + scorer_tool, "scoring_runtime", lambda *_: pytest.fail("runtime reached") + ) + with pytest.raises((ValueError, OSError)): + pilot.probe_candidate( + release_dir=root, artifact_root=root, output=output, compatibility_wheels=() + ) + if damage == "existing": + assert output.read_text() == "KEEP" + + +def test_runtime_authentication_precedes_candidate_reader(tmp_path, monkeypatch): + def refuse(_): + raise ValueError("MOCK authentic-runtime refusal") + + monkeypatch.setattr(scorer_tool, "scoring_runtime", refuse) + monkeypatch.setattr( + recert, + "validate_recertification_candidate", + lambda *_a, **_kw: pytest.fail("candidate read before auth"), + ) + with pytest.raises(ValueError, match="authentic-runtime refusal"): + pilot.probe_candidate( + release_dir=tmp_path / "release", + artifact_root=tmp_path / "artifacts", + output=tmp_path / "result.json", + compatibility_wheels=(), + ) + + +@pytest.mark.parametrize( + "field,value", + [ + ("schema_version", True), + ("schema_version", 2), + ("parent", {"release_type": "source_enrichment"}), + ("compatibility", {"status": "passed"}), + ], +) +def test_unsupported_parent_context_refuses_before_payload( + field, value, tmp_path, monkeypatch +): + report = { + "schema_version": 1, + "parent": {"release_type": "calibration"}, + "compatibility": {"status": "pending"}, + } + report[field] = value + monkeypatch.setattr( + scorer_tool, "scoring_runtime", lambda _: {"MOCK_METADATA_ONLY": True} + ) + monkeypatch.setattr(recert, "require_trusted_bytecode", lambda: None) + monkeypatch.setattr( + recert, "validate_recertification_candidate", lambda *_a, **_kw: report + ) + monkeypatch.setattr( + pilot, "_input_files", lambda *_: pytest.fail("payload reached") + ) + with pytest.raises( + pilot.EngineeringPilotError, match="pending schema1 calibration" + ): + pilot.probe_candidate( + release_dir=tmp_path / "release", + artifact_root=tmp_path / "artifacts", + output=tmp_path / "result.json", + compatibility_wheels=(), + ) + + +def test_exclusive_receipt_rejects_overwrite_and_nonfinite(tmp_path): + output = tmp_path / "result.json" + pilot._write_receipt(output, {"kind": pilot.PILOT_KIND}) + with pytest.raises(FileExistsError): + pilot._write_receipt(output, {"kind": "wrong"}) + with pytest.raises(ValueError): + pilot._write_receipt(tmp_path / "bad.json", {"value": float("nan")}) + + +def test_partial_engineering_receipt_cannot_satisfy_ordinary_fullscore_consumer(): + document = { + "schema_version": 1, + "kind": pilot.PILOT_KIND, + "population_estimate": False, + "selection": {"actual_households": 2}, + "measurement": {"household_metrics": {}}, + } + failures = recert._score_document_failures( + document, + dataset_sha256="a" * 64, + definitions={"metrics": []}, + label="MOCK pilot", + diagnostics_sha256="b" * 64, + spm={"geography_kind": "county"}, + expected_households=3, + ) + assert any("both their household and their state passes" in f for f in failures) + assert any(recert.SCORES_KIND in f for f in failures) + + +class _MockStore: + """In-memory HDFStore transport; no H5 library or file access.""" + + def __init__(self, tables, *, period=2024, codec=False): + self.tables = tables + self.period = period + self.codec = codec + self.reads = [] + + def __enter__(self): + return self + + def __exit__(self, *_): + return False + + def keys(self): + return ["/" + key for key in (*self.tables, "_time_period")] + + def __getitem__(self, key): + assert key == "_time_period" + return pd.Series([self.period]) + + def get_storer(self, key): + attrs = SimpleNamespace( + _microcosm_frame_table_codec="MOCK_UNSUPPORTED" if self.codec else None + ) + return SimpleNamespace( + attrs=attrs, + nrows=len(self.tables[key]), + table=SimpleNamespace(rowsize=1024), + ) + + def select(self, key, *, start, stop): + self.reads.append((key, start, stop)) + return self.tables[key].iloc[start:stop].copy() + + +def test_chunk_reader_preserves_scattered_group_rows_without_full_entity_reads( + tmp_path, monkeypatch +): + from tools import sample_us_export_households as sampler + + tables = mock_tables((2, 3, 1, 2, 1)) + for entity in ("tax_unit", "spm_unit", "family", "marital_unit"): + tables[entity] = tables[entity].iloc[::-1].reset_index(drop=True) + transport = _MockStore(tables) + monkeypatch.setattr(pd, "HDFStore", lambda *_a, **_kw: transport) + # Small test-local chunk geometry exercises the real shared reader across boundaries. + monkeypatch.setattr(sampler, "MINIMUM_CHUNK_ROWS", 2) + monkeypatch.setattr(pilot, "_CHUNK_BYTES", 1) + selected, year = pilot._read_selected_tables( + tmp_path / "MOCK.h5", max_households=2, expected_period=2024 + ) + assert year == 2024 + memberships, groups = membership_inputs(tables) + _, masks = pilot._select_rows( + groups["household"], memberships, groups, max_households=2 + ) + for entity, frame in selected.items(): + pd.testing.assert_frame_equal( + frame, tables[entity].loc[masks[entity]].reset_index(drop=True) + ) + assert transport.reads + assert all(stop - start <= 2 for _, start, stop in transport.reads) + assert any(start >= 2 for _, start, _ in transport.reads) + + +@pytest.mark.parametrize("period", [2023, True, "2024", 2024.0]) +def test_period_refuses_before_row_reads(period, tmp_path, monkeypatch): + transport = _MockStore(mock_tables(), period=period) + monkeypatch.setattr(pd, "HDFStore", lambda *_a, **_kw: transport) + with pytest.raises(pilot.EngineeringPilotError, match="period|year"): + pilot._read_selected_tables( + tmp_path / "MOCK.h5", max_households=2, expected_period=2024 + ) + assert not transport.reads + + +def test_unsupported_frame_codec_refuses_before_row_reads(tmp_path, monkeypatch): + transport = _MockStore(mock_tables(), codec=True) + monkeypatch.setattr(pd, "HDFStore", lambda *_a, **_kw: transport) + with pytest.raises(ValueError, match="codec"): + pilot._read_selected_tables( + tmp_path / "MOCK.h5", max_households=2, expected_period=2024 + ) + assert not transport.reads diff --git a/packages/microcosm-data/tests/engine_workflow/us/test_compatibility_recertification_pilot.py b/packages/microcosm-data/tests/engine_workflow/us/test_compatibility_recertification_pilot.py new file mode 100644 index 0000000000..2a4cce2f17 --- /dev/null +++ b/packages/microcosm-data/tests/engine_workflow/us/test_compatibility_recertification_pilot.py @@ -0,0 +1,153 @@ +"""One tiny MOCK H5 workflow with the real US constructor and batch scorer. + +Test-local runtime, parent and bytecode proof stubs do not authenticate a +release. The real model handles only two complete synthetic households. +""" + +from __future__ import annotations + +import json +import math + +import pandas as pd + +from microcosm.data import compatibility_recertification as recert +from test_support.microcosm_data.compatibility_recertification_pilot import ( + mock_tables, + write_mock_h5, +) +from tools import build_us_compatibility_recertification as scorer_tool +from tools import probe_us_compatibility_recertification as pilot + + +def test_tiny_mock_h5_retains_source_rows_through_real_native_scoring( + tmp_path, monkeypatch +): + import policyengine_us + + tables = mock_tables((2, 1, 3)) + artifact_root = tmp_path / "artifacts" + release_dir = tmp_path / "MOCK_RELEASE_NOT_QUALIFIED" + artifact_root.mkdir() + release_dir.mkdir() + h5 = artifact_root / "mock_synthetic.h5" + write_mock_h5(h5, tables) + initial_h5 = recert.sha256_file(h5) + spm = {"geography_kind": "county"} + (release_dir / "calibration_diagnostics.json").write_text( + json.dumps({"build": {"post_export_scoring": {"spm": spm}}}) + ) + report = { + "schema_version": 1, + "dataset": {"filename": h5.name, "sha256": initial_h5}, + "parent": { + "release_type": "calibration", + "root_artifacts": {}, + "MOCK_METADATA_ONLY": True, + }, + "compatibility": {"status": "pending"}, + } + (release_dir / recert.REPORT_FILE).write_text(json.dumps(report)) + # These stubs exist only in this test. No real parent/runtime claim follows. + monkeypatch.setattr( + recert, "validate_recertification_candidate", lambda *_a, **_kw: report + ) + monkeypatch.setattr( + scorer_tool, "scoring_runtime", lambda _: {"MOCK_METADATA_ONLY": True} + ) + monkeypatch.setattr(recert, "require_trusted_bytecode", lambda: None) + monkeypatch.setattr(recert, "verify_loaded_modules", lambda: 0) + monkeypatch.setattr( + recert, + "bytecode_isolation_status", + lambda: {"isolated": True, "MOCK_METADATA_ONLY": True}, + ) + monkeypatch.setattr( + scorer_tool, "_producer_identity", lambda: {"MOCK_METADATA_ONLY": True} + ) + metric = { + "metric_id": "mock_income_tax", + "batching": recert.BATCHING_HOUSEHOLD, + "entity": "tax_unit", + "variables": ["income_tax"], + "combine": "sum", + "itemizers_only": False, + "statistic": recert.STATISTIC_SUM, + "source_variable": "income_tax", + } + state_metric = { + **metric, + "metric_id": "mock_state_excluded", + "batching": recert.BATCHING_STATE, + } + monkeypatch.setattr( + recert, + "drift_metric_definitions", + lambda _: {"metrics": [metric, state_metric]}, + ) + expected = {} + person_mask = tables["person"].person_household_id.isin( + tables["household"].household_id.iloc[:2] + ) + expected["person"] = tables["person"].loc[person_mask].reset_index(drop=True) + for entity, frame in tables.items(): + if entity != "person": + ids = expected["person"][f"person_{entity}_id"] + expected[entity] = frame.loc[ + frame[f"{entity}_id"].isin(set(ids)) + ].reset_index(drop=True) + events = [] + native_constructor = policyengine_us.Microsimulation + + def constructor(**kwargs): + events.append("constructor") + assert kwargs["spm"] == spm + assert kwargs["dataset"].years == [2024] + for entity, frame in expected.items(): + pd.testing.assert_frame_equal( + getattr(kwargs["dataset"].get_year(2024), entity).reset_index( + drop=True + ), + frame, + ) + return native_constructor(**kwargs) + + monkeypatch.setattr(policyengine_us, "Microsimulation", constructor) + native_guard = pilot._aggregate_guard + + def guard(simulation): + events.append("guard") + native_guard(simulation) + + monkeypatch.setattr(pilot, "_aggregate_guard", guard) + native_total = scorer_tool._BatchScorer.total + + def total(self, metric): + events.append("total") + return native_total(self, metric) + + monkeypatch.setattr(scorer_tool._BatchScorer, "total", total) + output = tmp_path / "engineering-only.json" + result = pilot.probe_candidate( + release_dir=release_dir, + artifact_root=artifact_root, + output=output, + compatibility_wheels=(), + max_households=2, + ) + assert events == ["constructor", "guard", "guard", "guard", "total", "guard"] + assert result["kind"] == pilot.PILOT_KIND + assert result["population_estimate"] is False + assert result["compatibility_certification"] == "not_attested" + assert result["selection"]["actual_households"] == 2 + assert result["selection"]["raw_source_input_inventory"] == pilot._frame_inventory( + expected + ) + assert result["measurement"]["excluded_metric_ids"] == ["mock_state_excluded"] + assert list(result["measurement"]["household_metrics"]) == ["mock_income_tax"] + assert math.isfinite( + result["measurement"]["household_metrics"]["mock_income_tax"]["value"] + ) + assert result["runtime"]["packages"] == {"MOCK_METADATA_ONLY": True} + assert recert.sha256_file(h5) == initial_h5 + assert json.loads(output.read_text()) == result diff --git a/test_support/microcosm_data/compatibility_recertification_pilot.py b/test_support/microcosm_data/compatibility_recertification_pilot.py new file mode 100644 index 0000000000..4f0db12ce9 --- /dev/null +++ b/test_support/microcosm_data/compatibility_recertification_pilot.py @@ -0,0 +1,91 @@ +"""Public MOCK fixtures; no real records or runtime qualification evidence.""" + +from __future__ import annotations + +import numpy as np +import pandas as pd + + +def mock_tables(sizes=(2, 1, 3), *, id_dtype="int64", offset=100): + """Independent positional fixture with sparse IDs and unequal source weights.""" + dtype = np.dtype(id_dtype) + household_ids = np.asarray( + [offset + 11 * i for i in range(len(sizes))], dtype=dtype + ) + people = [] + person_id = offset + 1000 + for position, (household, size) in enumerate( + zip(household_ids, sizes, strict=True) + ): + for member in range(size): + people.append( + { + "person_id": person_id, + "person_household_id": household, + "person_tax_unit_id": int(household) + 100, + "person_spm_unit_id": int(household) + 200, + "person_family_id": int(household) + 300, + "person_marital_unit_id": person_id + 400, + "age": 40.0 if member == 0 else 10.0, + "employment_income": 45_000.0 + 1000 * position + if member == 0 + else 0.0, + "tax_unit_role_input": "HEAD" if member == 0 else "DEPENDENT", + } + ) + person_id += 7 + person = pd.DataFrame(people) + for column in person: + if column.endswith("_id"): + person[column] = person[column].astype(dtype) + tables = { + "person": person, + "household": pd.DataFrame( + { + "household_id": household_ids, + "household_weight": np.asarray( + [0.0 if i == 0 else i + 0.25 for i in range(len(sizes))] + ), + "state_fips": np.asarray( + [6 if i % 2 == 0 else 36 for i in range(len(sizes))], dtype="int32" + ), + "county_fips": np.asarray( + [6037 if i % 2 == 0 else 36061 for i in range(len(sizes))], + dtype="int32", + ), + } + ), + } + for entity, increment in (("tax_unit", 100), ("spm_unit", 200), ("family", 300)): + tables[entity] = pd.DataFrame( + { + f"{entity}_id": np.asarray( + [int(h) + increment for h in household_ids], dtype=dtype + ) + } + ) + tables["tax_unit"]["filing_status_input"] = "SINGLE" + tables["marital_unit"] = pd.DataFrame( + {"marital_unit_id": (person.person_id + 400).astype(dtype)} + ) + return tables + + +def membership_inputs(tables): + """Expose only the membership projection and original group-ID arrays.""" + columns = [c for c in tables["person"] if c.endswith("_id")] + memberships = tables["person"].loc[:, columns].copy() + groups = { + entity: frame[f"{entity}_id"].to_numpy() + for entity, frame in tables.items() + if entity != "person" + } + return memberships, groups + + +def write_mock_h5(path, tables, *, year=2024): + """Write synthetic six-table data for the engine-workflow category only.""" + with pd.HDFStore(path, "w") as store: + store.put("_time_period", pd.Series([year]), format="table") + for entity, frame in tables.items(): + store.put(entity, frame, format="table", data_columns=True) diff --git a/tools/probe_us_compatibility_recertification.py b/tools/probe_us_compatibility_recertification.py new file mode 100644 index 0000000000..13663ed2ce --- /dev/null +++ b/tools/probe_us_compatibility_recertification.py @@ -0,0 +1,522 @@ +#!/usr/bin/env python3 +"""Probe at most 32 complete source households without certifying a release. + +This engineering tool preserves selected source rows and their weights. It +does not draw a statistical sample, write a dataset, run a state pass, or +produce a compatibility_recertification_scores document. +""" + +from __future__ import annotations + +import argparse +import gc +import hashlib +import json +import math +import os +import platform +import struct +import sys +import tempfile +import time +from collections.abc import Mapping, Sequence +from pathlib import Path + +# Match the ordinary recertifier: isolate bytecode before Microcosm imports. +if __name__ == "__main__" and sys.pycache_prefix is None: + sys.pycache_prefix = tempfile.mkdtemp(prefix="recertification-pilot-pycache-") + +# Direct scripts put tools/ on sys.path; resolve sibling tools from this checkout. +if __name__ == "__main__": + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from microcosm.data import compatibility_recertification as recert # noqa: E402 + +MAX_HOUSEHOLDS = 32 +PILOT_KIND = "compatibility_recertification_engineering_pilot" +PILOT_SCHEMA_VERSION = 1 +_CHUNK_BYTES = 8 * 2**20 + + +class EngineeringPilotError(ValueError): + """The bounded engineering contract cannot hold for these inputs.""" + + +def _validate_limit(max_households: int) -> None: + if type(max_households) is not int or not 1 <= max_households <= MAX_HOUSEHOLDS: + raise EngineeringPilotError("max_households must be an integer from 1 to 32") + + +def _ids(values, label: str): + import numpy as np + + result = np.asarray(values) + if result.ndim != 1 or result.dtype.kind not in "iu": + raise EngineeringPilotError(f"{label} must retain an integer ID dtype") + if len(np.unique(result)) != len(result): + raise EngineeringPilotError(f"{label} contains duplicate IDs") + return result + + +def _select_rows(household_ids, memberships, group_ids, *, max_households: int): + """Return source-position masks, retaining every selected group's members.""" + import numpy as np + + from tools import sample_us_export_households as sampler + + _validate_limit(max_households) + households = _ids(household_ids, "household_id") + if not len(households): + raise EngineeringPilotError("the source has no households") + _ids(memberships["person_id"].to_numpy(), "person_id") + selected = households[:max_households].copy() + person_household = memberships["person_household_id"].to_numpy() + if person_household.dtype.kind not in "iu": + raise EngineeringPilotError("person_household_id must retain an integer dtype") + if not np.isin(person_household, households).all(): + raise EngineeringPilotError("person memberships reference a missing household") + person_mask = np.isin(person_household, selected) + if not np.isin(selected, person_household[person_mask]).all(): + raise EngineeringPilotError("a selected household has no person members") + try: + sampler.assert_units_nest_in_households(memberships.loc[person_mask]) + except ValueError: + raise EngineeringPilotError( + "selected group units do not nest within whole households" + ) from None + for entity in sampler.US_GROUP_ENTITIES: + entity_ids = _ids(group_ids[entity], f"{entity}_id") + members = memberships[f"person_{entity}_id"].to_numpy() + if members.dtype.kind not in "iu": + raise EngineeringPilotError(f"person_{entity}_id has a noninteger dtype") + if not np.isin(members, entity_ids).all(): + raise EngineeringPilotError( + f"person memberships reference a missing {entity}" + ) + wanted = np.unique(members[person_mask]) + if not np.isin(wanted, entity_ids).all(): + raise EngineeringPilotError( + f"selected {entity} memberships lack a group row" + ) + if entity != "household" and np.isin(members[~person_mask], wanted).any(): + raise EngineeringPilotError( + f"a selected {entity} reaches another household" + ) + masks = sampler.entity_row_masks(memberships, group_ids, selected) + if any(not mask.any() for mask in masks.values()): + raise EngineeringPilotError("selected households lack a required entity table") + return selected, masks + + +def _field(digest, value: bytes) -> None: + digest.update(len(value).to_bytes(8, "big")) + digest.update(value) + + +def _scalar_bytes(value) -> bytes: + """Distinguish stored scalar types; never hash object-array pointers.""" + import numpy as np + import pandas as pd + + if value is None: + return b"none" + if value is pd.NA: + return b"pandas.NA" + if value is pd.NaT: + return b"pandas.NaT" + if isinstance(value, np.generic): + return b"numpy:" + value.dtype.str.encode() + b":" + value.tobytes() + if isinstance(value, bytes): + return b"bytes:" + value + if isinstance(value, str): + return b"str:" + value.encode("utf-8") + if isinstance(value, bool): + return b"bool:1" if value else b"bool:0" + if isinstance(value, int): + return b"int:" + str(value).encode("ascii") + if isinstance(value, float): + return b"float64:" + struct.pack("!d", value) + if isinstance(value, (pd.Timestamp, pd.Timedelta)): + return type(value).__name__.encode() + b":" + value.isoformat().encode() + raise EngineeringPilotError( + f"unsupported stored scalar type {type(value).__name__}" + ) + + +def _array_digest(values) -> str: + import numpy as np + + array = np.asarray(values) + digest = hashlib.sha256() + _field(digest, array.dtype.str.encode()) + _field(digest, json.dumps(array.shape).encode()) + if array.dtype.hasobject: + for value in array.flat: + _field(digest, _scalar_bytes(value)) + else: + _field(digest, np.ascontiguousarray(array).tobytes()) + return digest.hexdigest() + + +def _frame_inventory(tables: Mapping) -> dict: + """Hash column order, dtypes and values, including categorical metadata.""" + import pandas as pd + + inventory = {} + for entity, frame in tables.items(): + if not frame.columns.is_unique or any(not isinstance(c, str) for c in frame): + raise EngineeringPilotError(f"{entity} has duplicate or nontext columns") + columns = [] + for column in frame: + series = frame[column] + metadata = {"name": column, "dtype": repr(series.dtype)} + if isinstance(series.dtype, pd.CategoricalDtype): + metadata["categories_sha256"] = _array_digest(series.cat.categories) + metadata["ordered"] = series.cat.ordered + columns.append( + {**metadata, "values_sha256": _array_digest(series.to_numpy())} + ) + inventory[entity] = {"rows": len(frame), "columns": columns} + return inventory + + +def _read_selected_tables(h5: Path, *, max_households: int, expected_period: int): + """Scan compact memberships, then retain only complete selected source rows.""" + import pandas as pd + + from tools import sample_us_export_households as sampler + + with pd.HDFStore(str(h5), mode="r") as store: + keys = {key.strip("/") for key in store.keys()} + if set(sampler.US_ENTITIES) - keys or sampler.TIME_PERIOD_KEY not in keys: + raise EngineeringPilotError( + "source lacks entity tables or explicit time period" + ) + period = store[sampler.TIME_PERIOD_KEY] + if len(period) != 1 or type(period.iloc[0]) is bool: + raise EngineeringPilotError("source time period must contain one integer") + import numpy as np + + if not isinstance(period.iloc[0], (int, np.integer)): + raise EngineeringPilotError( + "source time period must retain an integer dtype" + ) + source_year = int(period.iloc[0]) + if source_year != expected_period: + raise EngineeringPilotError("source year differs from the scoring period") + memberships = sampler.read_table_rows( + store, + "person", + columns=("person_id", *sampler.PERSON_MEMBERSHIP_COLUMNS), + chunk_bytes=_CHUNK_BYTES, + ) + group_ids = { + entity: sampler.read_table_rows( + store, + entity, + columns=(sampler.id_column(entity),), + chunk_bytes=_CHUNK_BYTES, + )[sampler.id_column(entity)].to_numpy() + for entity in sampler.US_GROUP_ENTITIES + } + selected, masks = _select_rows( + group_ids["household"], + memberships, + group_ids, + max_households=max_households, + ) + tables = { + entity: sampler.read_table_rows( + store, entity, row_mask=masks[entity], chunk_bytes=_CHUNK_BYTES + ) + for entity in sampler.US_ENTITIES + } + if not tables["household"]["household_id"].to_numpy().tolist() == selected.tolist(): + raise EngineeringPilotError("selection changed source household order") + return tables, source_year + + +def _reviewed_columns(changes: Mapping, raw_verdict: Mapping) -> dict: + """Accept only the existing reviewed-change authority; retain the raw verdict.""" + failures = recert.reviewed_column_change_failures(changes) + if failures: + raise EngineeringPilotError(" ".join(failures)) + # A raw verdict may refuse explicitly reviewed retired columns. It stays + # false here: neither this receipt nor the reviewed-change check relabels it. + return { + "reviewed_changes_accepted": True, + "changes": changes, + "raw_verdict": raw_verdict, + } + + +def _aggregate_guard(simulation) -> None: + known = recert.engine_known_periods( + simulation, + recert.POPULATION_AGGREGATE_VARIABLES, + walk_branches=True, + skip_unknown=True, + ) + if known: + names = sorted({name for name, _ in known}) + raise EngineeringPilotError( + f"incomplete-support engine computed population/state aggregates: {names}" + ) + + +def _check_output(output: Path, release_dir: Path, artifact_root: Path) -> None: + if os.path.lexists(output): + raise FileExistsError(f"{output} exists; refusing to overwrite it") + if not output.parent.is_dir() or output.parent.is_symlink(): + raise EngineeringPilotError( + "output parent must be an existing regular directory" + ) + resolved = output.resolve() + for root in (release_dir.resolve(), artifact_root.resolve()): + if resolved.is_relative_to(root): + raise EngineeringPilotError( + "output must lie outside the input release/artifacts" + ) + + +def _input_files(release_dir: Path, artifact_root: Path, report: Mapping) -> dict: + """Bind carried metadata and every declared parent artifact without rewriting it.""" + paths = {f"release/{path.name}": path for path in release_dir.iterdir()} + for name in report["parent"]["root_artifacts"]: + child = recert.child_artifact_path(report["parent"], release_dir.name, name) + paths[f"artifacts/{child}"] = artifact_root / child + result = {} + for name, path in sorted(paths.items()): + if path.is_symlink() or not path.is_file(): + raise EngineeringPilotError( + "input evidence must use regular nonsymlink files" + ) + result[name] = recert.sha256_file(path) + return result + + +def _write_receipt(output: Path, document: Mapping) -> None: + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) + fd = os.open(output, flags, 0o600) + try: + with os.fdopen(fd, "w") as stream: + json.dump(document, stream, indent=2, sort_keys=True, allow_nan=False) + stream.write("\n") + except BaseException: + # Do not remove an independently replaced path while handling a failure. + # An incomplete exclusive output remains evidence and cannot be reused. + raise + + +def probe_candidate( + *, + release_dir: Path, + artifact_root: Path, + output: Path, + compatibility_wheels: Sequence[Path], + max_households: int = MAX_HOUSEHOLDS, +) -> dict: + """Run one native source-preserving household probe; grant no compatibility.""" + _validate_limit(max_households) + release_dir, artifact_root, output = map(Path, (release_dir, artifact_root, output)) + _check_output(output, release_dir, artifact_root) + started = time.perf_counter() + from tools import build_us_compatibility_recertification as scorer_tool + + runtime = scorer_tool.scoring_runtime(tuple(compatibility_wheels)) + recert.require_trusted_bytecode() + report = recert.validate_recertification_candidate( + release_dir, artifact_root=artifact_root, require_compatibility=False + ) + if ( + type(report.get("schema_version")) is not int + or report.get("schema_version") != 1 + or report.get("parent", {}).get("release_type") != "calibration" + or report.get("compatibility", {}).get("status") != "pending" + ): + raise EngineeringPilotError( + "pilot requires a pending schema1 calibration parent" + ) + input_files = _input_files(release_dir, artifact_root, report) + pilot_source_sha256 = recert.sha256_file(__file__) + filename = report["dataset"]["filename"] + if not isinstance(filename, str) or Path(filename).name != filename: + raise EngineeringPilotError("source filename must be a bare filename") + h5 = artifact_root / filename + if h5.is_symlink() or not h5.is_file(): + raise EngineeringPilotError("source H5 must be a regular nonsymlink file") + source_sha256 = recert.sha256_file(h5) + if source_sha256 != report["dataset"]["sha256"]: + raise EngineeringPilotError("source H5 differs from the admitted candidate") + diagnostics_path = release_dir / "calibration_diagnostics.json" + diagnostics_sha256 = recert.sha256_file(diagnostics_path) + diagnostics = json.loads(diagnostics_path.read_text()) + spm = ((diagnostics.get("build") or {}).get("post_export_scoring") or {}).get("spm") + if not isinstance(spm, dict): + raise EngineeringPilotError("parent diagnostics lack their SPM selection") + definitions = recert.drift_metric_definitions(diagnostics) + metrics = [ + m for m in definitions["metrics"] if m["batching"] == recert.BATCHING_HOUSEHOLD + ] + if not metrics or len({m["metric_id"] for m in metrics}) != len(metrics): + raise EngineeringPilotError("household metric set is empty or repeats an ID") + excluded = [m["metric_id"] for m in definitions["metrics"] if m not in metrics] + + from microcosm.data import stored_inputs + + stored_tables = stored_inputs.h5_stored_tables(h5) + if set(stored_tables) != set(recert._ENTITIES): + raise EngineeringPilotError("source must contain exactly the six entity tables") + engine = stored_inputs.installed_us_engine() + changes = recert.stored_column_changes( + stored_tables, + engine_variables=engine.variables, + stored_input_register=stored_inputs.US_STORED_NON_VARIABLE_COLUMNS, + ) + columns = _reviewed_columns(changes, stored_inputs.h5_verdict(h5, engine=engine)) + selected, year = _read_selected_tables( + h5, max_households=max_households, expected_period=recert.SCORING_PERIOD + ) + source_inputs = _frame_inventory(selected) + if set(selected) != set(recert._ENTITIES): + raise EngineeringPilotError("selection must retain the six source entities") + + from policyengine_us import Microsimulation + from policyengine_us.data import USSingleYearDataset, extend_single_year_dataset + + dataset = extend_single_year_dataset( + USSingleYearDataset(**selected, time_period=year), end_year=year + ) + if dataset.years != [year]: + raise EngineeringPilotError("source-year container generated another period") + source_year_dataset = dataset.get_year(year) + dataset_tables = { + entity: getattr(source_year_dataset, entity) for entity in recert._ENTITIES + } + if _frame_inventory(dataset_tables) != source_inputs: + raise EngineeringPilotError("one-year dataset changed selected source inputs") + frames = scorer_tool._BatchFrames(source_year_dataset, withheld=[]) + ids = selected["household"]["household_id"].to_numpy() + batch = frames.batch(ids) + if _frame_inventory(batch) != source_inputs: + raise EngineeringPilotError("batch construction changed source rows or dtypes") + if not 1 <= len(ids) <= max_households <= MAX_HOUSEHOLDS: + raise EngineeringPilotError("selection exceeded the household bound") + simulation = Microsimulation(dataset=dataset, spm=dict(spm)) + scorer = None + totals = {} + try: + _aggregate_guard(simulation) + scorer = scorer_tool._BatchScorer(simulation, batch) + _aggregate_guard(simulation) + for metric in metrics: + _aggregate_guard(simulation) + value = scorer.total(metric) + _aggregate_guard(simulation) + if not math.isfinite(value): + raise EngineeringPilotError("a household metric is not finite") + totals[metric["metric_id"]] = {"value": value} + if any( + _frame_inventory(tables) != source_inputs + for tables in (selected, dataset_tables, batch) + ): + raise EngineeringPilotError( + "native construction/scoring changed source inputs" + ) + finally: + del scorer + del simulation + gc.collect() + recert.verify_loaded_modules() + bytecode = recert.bytecode_isolation_status() + if bytecode.get("isolated") is not True: + raise EngineeringPilotError("native modules ran from untrusted bytecode") + if recert.sha256_file(h5) != source_sha256: + raise EngineeringPilotError("source H5 changed during the pilot") + if recert.sha256_file(diagnostics_path) != diagnostics_sha256: + raise EngineeringPilotError("parent diagnostics changed during the pilot") + if _input_files(release_dir, artifact_root, report) != input_files: + raise EngineeringPilotError("carried input evidence changed during the pilot") + if recert.sha256_file(__file__) != pilot_source_sha256: + raise EngineeringPilotError("pilot source changed during execution") + producer = scorer_tool._producer_identity() + document = { + "schema_version": PILOT_SCHEMA_VERSION, + "kind": PILOT_KIND, + "scope": "bounded complete-household constructor/scorer engineering only", + "population_estimate": False, + "compatibility_certification": "not_attested", + "source": { + "dataset": report["dataset"], + "parent": report["parent"], + "diagnostics_sha256": diagnostics_sha256, + "input_files_sha256": input_files, + }, + "selection": { + "method": "first source households in stored row order; complete membership closure", + "requested_max_households": max_households, + "actual_households": len(ids), + "household_id_order_sha256": _array_digest(ids), + "raw_source_input_inventory": source_inputs, + "weights": "original source household weights, without rescaling", + "source_period": year, + }, + "runtime": {"python": platform.python_version(), "packages": runtime}, + "source_columns": columns, + "measurement": { + "method": "one native whole-household engineering probe; no state pass", + "spm": spm, + "metric_definitions_sha256": recert.canonical_sha256(definitions), + "excluded_metric_ids": excluded, + "household_metrics": totals, + }, + "bytecode": {"isolated": True}, + "producer": producer, + "pilot_source_sha256": pilot_source_sha256, + "elapsed_seconds": time.perf_counter() - started, + "untested": [ + "full population/state passes", + "baseline/withheld comparison and drift", + "certification/claim/publication", + "wrapper/bundle admission", + "historical-law/scientific adapter and study adoption", + ], + } + _write_receipt(output, document) + return document + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--release-dir", type=Path, required=True) + parser.add_argument("--artifact-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--max-households", type=int, default=MAX_HOUSEHOLDS) + parser.add_argument( + "--compatibility-wheel", type=Path, action="append", required=True + ) + args = parser.parse_args(argv) + try: + document = probe_candidate( + release_dir=args.release_dir, + artifact_root=args.artifact_root, + output=args.output, + compatibility_wheels=tuple(args.compatibility_wheel), + max_households=args.max_households, + ) + except (ValueError, OSError, RuntimeError) as exc: + print(f"Engineering pilot refused: {exc}", file=sys.stderr) + return 2 + print( + json.dumps( + { + "kind": document["kind"], + "households": document["selection"]["actual_households"], + } + ) + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())