From d0a827e529bcdec02e2831097827b62991f766fb Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 19 Nov 2026 22:49:19 +0000 Subject: [PATCH 1/6] Let transport CREATE take an optional donor-decoding profile CREATE accepts a `donor_profile` parameter: a canonical JSON document that names a versioned decoding profile for the populace-us donor and states each of its choices. The first profile, populace-us-cps-asec version 1, stages household tenure, legal marital status and full-time study from the donor's raw answers and SPM units, refuses a document written for other donor bytes, and records its counts in CREATE's receipt. No graph selects a profile here. A graph that sets none keeps its CREATE frame and receipt bytes, which frozen fixtures captured at the base commit pin. Seven kernel refs move once: transport.create@1 and @2, currency@1, quantile_map@1 and @2, support_bounds@1 and boundary@1. Co-Authored-By: Claude Opus 5.5 --- changelog.d/donor-decoding-profile.added.md | 3 + docs/concept-schema-transport-adr.md | 31 + .../build/transport/population_kernels.py | 27 +- .../test_transport_create_donor_profile.py | 520 +++++++ .../transport_create_baseline/composed.json | 1 + .../transport_create_baseline/nz_toy.json | 1 + .../transport_create_baseline/provenance.json | 25 + .../transport_create_baseline/toy.json | 1 + .../toy_profile_columns.json | 1 + .../transport_create_baseline/toy_v2.json | 1 + .../src/microcosm/frame/transport.py | 657 +++++++- .../shared/test_transport_donor_profile.py | 1342 +++++++++++++++++ .../transport_create_baseline.py | 318 ++++ 13 files changed, 2922 insertions(+), 6 deletions(-) create mode 100644 changelog.d/donor-decoding-profile.added.md create mode 100644 packages/microcosm-build/tests/engine_free/shared/test_transport_create_donor_profile.py create mode 100644 packages/microcosm-build/tests/fixtures/transport_create_baseline/composed.json create mode 100644 packages/microcosm-build/tests/fixtures/transport_create_baseline/nz_toy.json create mode 100644 packages/microcosm-build/tests/fixtures/transport_create_baseline/provenance.json create mode 100644 packages/microcosm-build/tests/fixtures/transport_create_baseline/toy.json create mode 100644 packages/microcosm-build/tests/fixtures/transport_create_baseline/toy_profile_columns.json create mode 100644 packages/microcosm-build/tests/fixtures/transport_create_baseline/toy_v2.json create mode 100644 packages/microcosm-frame/tests/engine_free/shared/test_transport_donor_profile.py create mode 100644 test_support/microcosm_build/transport_create_baseline.py diff --git a/changelog.d/donor-decoding-profile.added.md b/changelog.d/donor-decoding-profile.added.md new file mode 100644 index 0000000000..fe9e1e2cf1 --- /dev/null +++ b/changelog.d/donor-decoding-profile.added.md @@ -0,0 +1,3 @@ +Transport CREATE (`transport.create@1` and `@2`) accepts an optional `donor_profile` parameter: a canonical JSON document that selects a versioned donor-decoding profile and states each of its choices. The first profile, `populace-us-cps-asec` version 1, stages household tenure, legal marital status and full-time study from the donor's raw survey answers and SPM units, refuses a document written for other donor bytes, and records its counts in CREATE's receipt. No graph selects a profile in this change, and a graph that sets none keeps its CREATE frame and receipt bytes. + +The change edits `microcosm/frame/transport.py` and `microcosm/build/transport/population_kernels.py`, so seven kernel refs move once: `transport.create@1`, `transport.create@2`, `transport.currency@1`, `transport.quantile_map@1`, `transport.quantile_map@2`, `transport.support_bounds@1` and `transport.boundary@1`. Their implementation hashes change, so the node records of these kernels and of every node downstream of them re-key, and those nodes run again. A stored CREATE inventory stops matching, because its store key includes CREATE's implementation hash (`transport/cli.py`). Stored support-bounds evidence is refused, not rebuilt: it records its producer's implementation hash, and the battery's header check refuses evidence whose hash differs from this build's (`transport/evidence_contract.py`). `gates.battery@1` does not move, and no committed digest moves. diff --git a/docs/concept-schema-transport-adr.md b/docs/concept-schema-transport-adr.md index 877b6b9406..57cdd23611 100644 --- a/docs/concept-schema-transport-adr.md +++ b/docs/concept-schema-transport-adr.md @@ -417,6 +417,37 @@ These hold for every input and are tested (Hypothesis properties unless noted): nonmissing ages in completed years, from 0 through 130. `DonorBank.dropped_parent_cycle_edges` exposes the number of dropped edges. Longer cycles and other inconsistent relationships still fail validation. +- A graph selects a donor-decoding profile through CREATE's optional + `donor_profile` parameter. The value is a canonical JSON document with the + fields `format` (`microcosm.donor-profile/1`), `profile`, `version`, + `donor_sha256` and `choices`. `parse_donor_profile` refuses an unknown or + missing field and any choice outside the closed sets in + `DONOR_PROFILE_CHOICES`, and a profile has no defaults: the document states + every choice. The one profile, `populace-us-cps-asec` version 1, stages + household `tenure` from `tenure_type`, `H_TENURE` and the SPM units' + tenure and housing assistance, person `legal_marital_status` from + `A_MARITL`, and person `enrolled_full_time` from `A_ENRLW` and `A_FTPT`. + The reader refuses a document whose `donor_sha256` names other bytes + before it opens the file. It checks the raw codes and the SPM joins before + decoding, and it reconciles rent and mortgage costs with the staged tenure + before concept validation. CREATE's receipt records the document's digest, + its choices and the staging counts under `donor_profile`. A graph that sets + no profile reads what it read before (the person and household tables and + the `_time_period` series) and never the `spm_unit` table, and its CREATE + frame and receipt keep the bytes captured at the commit before this change. + No graph selects a profile when the parameter lands. The parameter still + moves seven kernel refs once, because it edits the reader's module and + CREATE's module: `transport.create@1` and `@2`, `transport.currency@1`, + `transport.quantile_map@1` and `@2`, `transport.support_bounds@1` and + `transport.boundary@1`. The node records of these kernels and of every node + downstream of them re-key. A stored CREATE inventory stops matching, + because its store key includes CREATE's implementation hash. The battery + refuses stored support-bounds evidence that records the old implementation + hash; it does not rebuild it. `gates.battery@1` does not move, and no + committed digest moves. A choice value the closed sets do not offer needs a + further edit to the reader's module, which moves every one of these refs + again except `transport.boundary@1`, whose hash reads CREATE's module but + not the reader's. - The consuming builder supplies the destination frame declaration after transport. New Zealand's group bindings now execute on benefit units built from the concept pointers. Belgium's 39 `person_role` bindings on `Child` diff --git a/packages/microcosm-build/src/microcosm/build/transport/population_kernels.py b/packages/microcosm-build/src/microcosm/build/transport/population_kernels.py index f8d24121fd..00f8257322 100644 --- a/packages/microcosm-build/src/microcosm/build/transport/population_kernels.py +++ b/packages/microcosm-build/src/microcosm/build/transport/population_kernels.py @@ -12,6 +12,14 @@ (``donor_pin_sha256``, ``unit_rule_sha256``, ``mass_reference_sha256``, ``currency_sha256`` and ``bands_sha256``) is checked for format only: it moves the node key and authenticates nothing. + +An optional ``donor_profile`` carries a donor-decoding profile document +(``microcosm.frame.transport.parse_donor_profile``). The reader refuses a +document whose own ``donor_sha256`` differs from this kernel's +``donor_sha256`` parameter and stages the profile's concepts; the receipt's +``donor_profile`` key records what it staged. +Without the parameter, CREATE reads the donor and writes its frame and +receipt as before. """ from __future__ import annotations @@ -41,6 +49,7 @@ from microcosm.frame.transport import ( currency_bridge, derive_transport_seed, + parse_donor_profile, quantile_map, read_populace_us_donor, ) @@ -141,6 +150,7 @@ class TransportCreateKernel(KernelBase): "seed_stream", } ) + _optional = frozenset({"facts_sha256", "chronicle_feed_pin", "donor_profile"}) def implementation_hash(self) -> str: return source_hash( @@ -164,10 +174,13 @@ def implementation_hash(self) -> str: def run(self, context: KernelContext) -> KernelResult: require_params( - context, - self.ref, - required=self._required, - optional=frozenset({"facts_sha256", "chronicle_feed_pin"}), + context, self.ref, required=self._required, optional=self._optional + ) + # Parsed once, before any source is read; the reader stages it. + profile = ( + parse_donor_profile(string_param(context, self.ref, "donor_profile")) + if "donor_profile" in context.params + else None ) donor_source = string_param(context, self.ref, "donor_source") facts_source = string_param(context, self.ref, "facts_source") @@ -218,6 +231,7 @@ def run(self, context: KernelContext) -> KernelResult: context.sources[donor_source], sha256=sha256_param(context, self.ref, "donor_sha256"), size=context.params["donor_size"], + profile=profile, ) tables, dropped = split_for_transport(donor.tables) # pandas 3's inferred text dtype spells itself "str"; graph columns @@ -313,6 +327,11 @@ def run(self, context: KernelContext) -> KernelResult: else diagnostics, "mass_reference": registry.specs[0].name, "facts": dict(surface.facts), + **( + {} + if donor.donor_profile is None + else {"donor_profile": donor.donor_profile} + ), }, ) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_transport_create_donor_profile.py b/packages/microcosm-build/tests/engine_free/shared/test_transport_create_donor_profile.py new file mode 100644 index 0000000000..8ecc9f8968 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_transport_create_donor_profile.py @@ -0,0 +1,520 @@ +"""CREATE's optional ``donor_profile``: unchanged without it, recorded with it. + +The frozen baseline was captured at the base commit, before CREATE accepted +a profile: with no profile set, CREATE's frame and receipt and the donor +codec's frame keep those exact canonical bytes on the toy donors and the +composed toy graphs. With a profile, CREATE stages the profile's concepts, +records them in its receipt, and equals each oracle reading the donor through +the same parsed profile. Synthetic donors only. +""" + +from __future__ import annotations + +import ast +import json +import re +from functools import partial +from hashlib import sha256 +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +import microcosm.build.transport.codecs as codecs_module +import microcosm.build.transport.population_kernels as population_kernels_module +import test_support.microcosm_build.transport_nz_toy as nz_toy_module +import test_support.microcosm_build.transport_population as population_module +from microcosm.build.transport.codecs import load_populace_us_h5 +from microcosm.build.transport.population_kernels import ( + TRANSPORT_CREATE, + TRANSPORT_CREATE_DECLARED, +) +from microcosm.frame.transport import ( + DONOR_PROFILE_FORMAT, + parse_donor_profile, + read_populace_us_donor, +) +from microcosm.frame.unit_construction import MultiUnitRule +from microcosm.graph import ( + ContentStore, + Graph, + Node, + Owned, + SourceRef, + StructuralDelta, + compile_graph, + run_graph, +) +from microcosm.graph.canonical import canonical_json +from test_support.microcosm_build.transport_create_baseline import ( + SCENARIOS, + add_profile_columns, + frame_document, + run_create, + scenario_bytes, +) +from test_support.microcosm_build.transport_graph import canonical_text +from test_support.microcosm_build.transport_population import ( + ENTITIES, + UNIT_RULE, + create_params, + digest, + direct_population, + donor_pin, + population_registry, + write_population_sources, +) +from test_support.paths import paths_for + +BASELINE = paths_for("microcosm-build").tests / "fixtures/transport_create_baseline" +BASE_COMMIT = "cfd5a2a5ea8fbaa0269f434d10c50eb389eabc83" +CHOICES = { + "assisted_renter_tenure": "rented_public_authority", + "blank_full_time_study": "read_false", + "housing_cost_contradicting_tenure": "tenure_wins", +} +STAGED = { + "person": {"legal_marital_status", "enrolled_full_time"}, + "household": {"tenure"}, +} + + +def _profile_text(donor, **choices) -> str: + """The document as composition hands it to CREATE: canonical JSON text.""" + return canonical_json( + { + "format": DONOR_PROFILE_FORMAT, + "profile": "populace-us-cps-asec", + "version": 1, + "donor_sha256": donor_pin(donor)["sha256"], + "choices": {**CHOICES, **choices}, + } + ).decode("utf-8") + + +def _sources(root, **kwargs): + return write_population_sources(root, edit_tables=add_profile_columns, **kwargs) + + +def _paths(sources): + return {"donor": sources.donor, "facts": sources.facts} + + +def _create_document(kernel, result) -> bytes: + return canonical_json( + { + "kernel": kernel, + "frame": frame_document(result.frame), + "receipt": result.receipt, + } + ) + + +# --- The frozen baseline ---------------------------------------------------- + + +@pytest.mark.parametrize("scenario", SCENARIOS) +def test_without_a_profile_create_and_the_codec_keep_the_frozen_base_bytes( + tmp_path, scenario +): + expected = (BASELINE / f"{scenario}.json").read_bytes() + actual = scenario_bytes(tmp_path, scenario) + if actual != expected: + frozen, now = json.loads(expected), json.loads(actual) + differ = [ + part + for part in ("create", "codec") + if canonical_json(frozen[part]) != canonical_json(now[part]) + ] + pytest.fail(f"{scenario}: {differ} differ from the frozen base bytes.") + + +def test_the_frozen_baseline_names_its_base_commit_and_file_digests(): + provenance = json.loads((BASELINE / "provenance.json").read_text()) + assert provenance["base_commit"] == BASE_COMMIT + # The recorded digest is the capture module in this tree, so an edit to + # it must show again that it reproduces the files at the base commit. + capture = paths_for("microcosm-build").repository / provenance["capture_module"] + recorded = provenance["capture_module_sha256"] + assert sha256(capture.read_bytes()).hexdigest() == recorded + assert set(provenance["files"]) == {f"{name}.json" for name in SCENARIOS} + for name, value in provenance["files"].items(): + assert sha256((BASELINE / name).read_bytes()).hexdigest() == value + assert {path.name for path in BASELINE.iterdir()} == { + "provenance.json", + *provenance["files"], + } + + +# --- One donor file, one CREATE with a profile and one without -------------- + + +@pytest.mark.parametrize( + "order", [("plain", "profiled"), ("profiled", "plain")], ids="-then-".join +) +def test_two_single_create_runs_on_one_donor_file_profiled_and_not(tmp_path, order): + """A graph that sets no profile (Belgium's case) keeps the frozen base + bytes on the very file another graph's CREATE reads with a profile, in + either order. The donor codec, read right after the profiled run, keeps + its frozen base bytes too.""" + sources = _sources(tmp_path / "toy_profile_columns", time_period=2024) + params = create_params(sources) + text = _profile_text(sources.donor) + frozen = json.loads((BASELINE / "toy_profile_columns.json").read_bytes()) + runs = {} + for run in order: + runs[run] = run_create( + TRANSPORT_CREATE.ref, + params if run == "plain" else {**params, "donor_profile": text}, + _paths(sources), + ) + if run == "profiled": + codec = frame_document(load_populace_us_h5(sources.donor)) + assert canonical_json(codec) == canonical_json(frozen["codec"]) + plain, profiled = runs["plain"], runs["profiled"] + assert _create_document(TRANSPORT_CREATE.ref, plain) == canonical_json( + frozen["create"] + ) + for entity in ENTITIES: + before = plain.frame.table(entity) + after = profiled.frame.table(entity) + added = STAGED.get(entity, set()) + assert set(after.columns) == set(before.columns) | added + assert [name for name in after if name not in added] == list(before) + changed = {"rent", "mortgage_interest"} if entity == "household" else set() + for column in before.columns: + if column not in changed: + pd.testing.assert_series_equal(after[column], before[column]) + household = profiled.frame.table("household") + assert household["rent"].tolist() == [0.0, 0.0] + assert household["mortgage_interest"].tolist() == [12.0, 0.0] + assert household["tenure"].tolist() == [ + "owned_with_mortgage", + "rented_public_authority", + ] + np.testing.assert_array_equal( + profiled.frame.weights_for("household").values, + plain.frame.weights_for("household").values, + ) + assert dict(profiled.frame.metadata) == dict(plain.frame.metadata) + assert set(profiled.receipt) == set(plain.receipt) | {"donor_profile"} + for key, value in plain.receipt.items(): + assert profiled.receipt[key] == value, key + record = profiled.receipt["donor_profile"] + assert record["document_sha256"] == sha256(text.encode("utf-8")).hexdigest() + assert (record["profile"], record["version"]) == ("populace-us-cps-asec", 1) + assert record["choices"] == CHOICES + assert record["full_time_study"]["read_false_by_source_year"] == {"2024": 1} + assert record["reconciliation"]["rent"]["contradicting_households"] == 1 + assert record["reconciliation"]["mortgage_principal"] == {"column": "absent"} + assert record["tenure"]["rented_public_authority"]["households"] == 1 + # The record is part of a canonical receipt. + canonical_json(profiled.receipt) + + +def test_both_create_versions_stage_the_same_profile(tmp_path): + assert TRANSPORT_CREATE_DECLARED.run.__func__ is TRANSPORT_CREATE.run.__func__ + sources = _sources(tmp_path) + text = _profile_text(sources.donor, assisted_renter_tenure="rented_private") + params = {**create_params(sources), "donor_profile": text} + declaration = MultiUnitRule.from_benefit_unit(UNIT_RULE).to_dict() + versioned = { + **params, + "unit_rule": canonical_text(declaration), + "unit_rule_sha256": digest(declaration), + } + first = run_create(TRANSPORT_CREATE.ref, params, _paths(sources)) + second = run_create(TRANSPORT_CREATE_DECLARED.ref, versioned, _paths(sources)) + for entity, columns in STAGED.items(): + for column in columns: + pd.testing.assert_series_equal( + first.frame.table(entity)[column], second.frame.table(entity)[column] + ) + assert first.frame.table("household")["tenure"].tolist()[1] == "rented_private" + assert first.receipt["donor_profile"] == second.receipt["donor_profile"] + + +def test_a_profiled_create_runs_under_the_executor_with_declared_columns(tmp_path): + sources = _sources(tmp_path / "sources") + params = {**create_params(sources), "donor_profile": _profile_text(sources.donor)} + frame = run_create(TRANSPORT_CREATE.ref, params, _paths(sources)).frame + structural = { + "person": {"person_id", "person_household_id", "person_family_id"}, + "household": {"household_id"}, + "family": {"family_id"}, + } + node = Node( + "toy.create", + TRANSPORT_CREATE.ref, + sources=("donor", "facts"), + structural=StructuralDelta.CREATE, + params=params, + outputs=tuple( + Owned(entity, column, str(frame.table(entity)[column].dtype)) + for entity in ENTITIES + for column in frame.table(entity) + if column not in structural[entity] + ), + ) + declared = {(item.entity, item.column): item.dtype for item in node.outputs} + assert declared["household", "tenure"] == "string" + assert declared["person", "legal_marital_status"] == "string" + assert declared["person", "enrolled_full_time"] == "bool" + graph = Graph( + "single-create", + ( + SourceRef("donor", "populace-us-h5-v1"), + SourceRef("facts", "ledger-consumer-artifact-v1"), + ), + (node,), + ) + manifest = run_graph( + compile_graph(graph), + sources=_paths(sources), + store=ContentStore(tmp_path / "store"), + kernels=population_registry(), + ) + population = manifest.population("toy.create") + for entity in ENTITIES: + pd.testing.assert_frame_equal(population.table(entity), frame.table(entity)) + receipt = manifest.nodes["toy.create"].receipt + assert receipt["donor_profile"]["choices"] == CHOICES + + +# --- Oracles read through the same parsed profile --------------------------- + + +def test_a_profiled_create_equals_the_population_oracle(tmp_path, monkeypatch): + sources = _sources(tmp_path) + text = _profile_text(sources.donor) + monkeypatch.setattr( + population_module, + "read_populace_us_donor", + partial(read_populace_us_donor, profile=parse_donor_profile(text)), + ) + expected, dropped = direct_population(sources) + result = run_create( + TRANSPORT_CREATE.ref, + {**create_params(sources), "donor_profile": text}, + _paths(sources), + ) + assert canonical_json(result.receipt["dropped_columns"]) == canonical_json(dropped) + for entity in ENTITIES: + table = result.frame.table(entity) + assert STAGED.get(entity, set()) <= set(table.columns) + pd.testing.assert_frame_equal(table, expected.table(entity)) + np.testing.assert_array_equal( + result.frame.weights_for("household").values, + expected.weights_for("household").values, + ) + pd.testing.assert_series_equal(result.frame.strata, expected.strata) + + +def _toy_profile_columns(tables): + """Profile answers for the forty-household toy donor: one SPM unit per + household, every household tenure label, assisted and unassisted renters, + every marital code and blank enrollment answers.""" + nz_toy_module.synthetic_households(tables) + person, household = tables["person"], tables["household"] + n = len(household) + labels = ["OWNED_WITH_MORTGAGE", "RENTED", "NONE"] + household["tenure_type"] = [labels[h % 3] for h in range(n)] + household["H_TENURE"] = [h % 3 + 1 for h in range(n)] + person["person_spm_unit_id"] = person["person_household_id"] * 10 + person["A_MARITL"] = [i % 7 + 1 for i in range(len(person))] + person["A_ENRLW"] = [[1.0, 2.0, 0.0, np.nan][i % 4] for i in range(len(person))] + person["A_FTPT"] = [[1.0, 1.0, 2.0, np.nan][i % 5 % 4] for i in range(len(person))] + tables["spm_unit"] = pd.DataFrame( + { + "spm_unit_id": household["household_id"] * 10, + "spm_unit_tenure_type": [ + ["OWNER_WITH_MORTGAGE", "RENTER", "OWNER_WITHOUT_MORTGAGE"][h % 3] + if h % 3 != 0 + else ["OWNER_WITH_MORTGAGE", "OWNER_WITHOUT_MORTGAGE"][h % 2] + for h in range(n) + ], + "receives_housing_assistance": [h % 4 == 1 for h in range(n)], + } + ) + + +def test_a_profiled_create_equals_the_nz_toy_oracle(tmp_path, monkeypatch): + sources = write_population_sources( + tmp_path, mass=120, edit_tables=_toy_profile_columns, time_period=2024 + ) + text = _profile_text(sources.donor) + monkeypatch.setattr( + nz_toy_module, + "read_populace_us_donor", + partial(read_populace_us_donor, profile=parse_donor_profile(text)), + ) + expected = nz_toy_module._synthetic_frame(sources) + rule = nz_toy_module.UNIT_RULE.to_dict() + params = { + **create_params(sources, seed_stream="synthetic:composed:takeup"), + "unit_rule": canonical_text(rule), + "unit_rule_sha256": digest(rule), + "donor_profile": text, + } + result = run_create(TRANSPORT_CREATE.ref, params, _paths(sources)) + tenure = result.frame.table("household")["tenure"] + assert set(tenure) == { + "owned_with_mortgage", + "owned_outright", + "rented_private", + "rented_public_authority", + "rent_free", + } + for entity in ENTITIES: + pd.testing.assert_frame_equal( + result.frame.table(entity), expected.table(entity) + ) + np.testing.assert_allclose( + result.frame.weights_for("household").values, + expected.weights_for("household").values, + rtol=1e-12, + ) + blanks = result.receipt["donor_profile"]["full_time_study"] + assert sum(blanks["read_false_by_source_year"].values()) > 0 + + +def test_the_codec_path_reads_through_the_same_profile(tmp_path, monkeypatch): + sources = _sources(tmp_path) + profile = parse_donor_profile(_profile_text(sources.donor)) + direct = read_populace_us_donor( + sources.donor, **donor_pin(sources.donor), profile=profile + ) + monkeypatch.setattr( + codecs_module, + "read_populace_us_donor", + partial(read_populace_us_donor, profile=profile), + ) + frame = load_populace_us_h5(sources.donor) + for entity, table in direct.tables.items(): + pd.testing.assert_frame_equal(frame.table(entity), table) + assert "tenure" in frame.table("household") + np.testing.assert_array_equal(frame.weights_for("household").values, direct.weights) + + +# --- Refusals ---------------------------------------------------------------- + + +def test_create_param_sets_are_pinned(): + required = { + "donor_source", + "facts_source", + "donor_sha256", + "donor_size", + "donor_pin_sha256", + "unit_rule", + "unit_rule_sha256", + "mass_reference", + "mass_reference_sha256", + "country", + "concept_schema_sha256", + "seed_stream", + } + optional = {"facts_sha256", "chronicle_feed_pin", "donor_profile"} + for kernel in (TRANSPORT_CREATE, TRANSPORT_CREATE_DECLARED): + assert kernel._required == required + assert kernel._optional == optional + + +@pytest.mark.parametrize("kernel", [TRANSPORT_CREATE, TRANSPORT_CREATE_DECLARED]) +@pytest.mark.parametrize( + "name", ["donor_profiles", "donor_profile_sha256", "target_references"] +) +def test_an_unknown_create_param_refuses(tmp_path, kernel, name): + sources = write_population_sources(tmp_path) + params = {**create_params(sources), name: "x"} + with pytest.raises(ValueError, match=rf"unknown parameter\(s\): \['{name}'\]"): + run_create(kernel.ref, params, _paths(sources)) + + +@pytest.mark.parametrize( + ("value", "error", "message"), + [ + (1, TypeError, "non-empty string"), + ("", TypeError, "non-empty string"), + ("{", ValueError, "is not JSON"), + ('{"profile":"x"}', ValueError, "lacks field"), + ("populace-us-cps-asec@1", ValueError, "is not JSON"), + ], +) +def test_a_malformed_profile_refuses_before_any_source_is_read( + tmp_path, value, error, message +): + sources = write_population_sources(tmp_path / "sources") + params = {**create_params(sources), "donor_profile": value} + absent = {"donor": tmp_path / "absent-donor", "facts": tmp_path / "absent-facts"} + with pytest.raises(error, match=message): + run_create(TRANSPORT_CREATE.ref, params, absent) + + +@pytest.mark.parametrize( + ("edit", "message"), + [ + (lambda d: d.update(profile="populace-us-cps-asec-nz"), "Unknown donor"), + (lambda d: d.update(version=2), "Unknown donor profile"), + (lambda d: d.update(format="microcosm.donor-profile/0"), "format"), + (lambda d: d.update(country="nz"), "unknown field"), + (lambda d: d["choices"].update(rent="x"), "declares no choice field"), + (lambda d: d["choices"].pop("blank_full_time_study"), "requires choice"), + ( + lambda d: d["choices"].update(assisted_renter_tenure="rent_free"), + "must be one of", + ), + ], +) +def test_an_unknown_profile_field_or_value_refuses_before_any_source_is_read( + tmp_path, edit, message +): + sources = write_population_sources(tmp_path / "sources") + document = json.loads(_profile_text(sources.donor)) + edit(document) + params = {**create_params(sources), "donor_profile": canonical_text(document)} + absent = {"donor": tmp_path / "absent-donor", "facts": tmp_path / "absent-facts"} + with pytest.raises(ValueError, match=message): + run_create(TRANSPORT_CREATE.ref, params, absent) + + +def test_a_non_canonical_profile_refuses(tmp_path): + sources = _sources(tmp_path) + document = json.loads(_profile_text(sources.donor)) + params = {**create_params(sources), "donor_profile": json.dumps(document)} + with pytest.raises(ValueError, match="must be canonical JSON"): + run_create(TRANSPORT_CREATE.ref, params, _paths(sources)) + + +def test_a_profile_naming_another_donor_refuses(tmp_path): + sources = _sources(tmp_path) + document = json.loads(_profile_text(sources.donor)) + document["donor_sha256"] = "0" * 64 + params = {**create_params(sources), "donor_profile": canonical_text(document)} + with pytest.raises(ValueError, match="names donor bytes other than"): + run_create(TRANSPORT_CREATE.ref, params, _paths(sources)) + + +def test_a_profile_on_a_donor_without_profile_answers_refuses(tmp_path): + sources = write_population_sources(tmp_path) + params = {**create_params(sources), "donor_profile": _profile_text(sources.donor)} + with pytest.raises(ValueError, match="needs the donor's spm_unit table"): + run_create(TRANSPORT_CREATE.ref, params, _paths(sources)) + + +# --- Ruling term 7 ----------------------------------------------------------- + + +def test_create_names_no_country_node_id_or_donor_digest(): + """CREATE selects a profile only through its param: its module holds no + country name, node id or donor digest literal.""" + source = Path(population_kernels_module.__file__).read_text() + strings = [ + node.value + for node in ast.walk(ast.parse(source)) + if isinstance(node, ast.Constant) and isinstance(node.value, str) + ] + assert not [s for s in strings if re.search(r"[0-9a-f]{64}", s)] + assert not [s for s in strings if re.search(r"(?i)zealand|belgi", s)] + assert not [s for s in strings if re.search(r"\b(nz|be|uk|us)\.[a-z_]", s)] diff --git a/packages/microcosm-build/tests/fixtures/transport_create_baseline/composed.json b/packages/microcosm-build/tests/fixtures/transport_create_baseline/composed.json new file mode 100644 index 0000000000..04c15a0270 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/transport_create_baseline/composed.json @@ -0,0 +1 @@ +{"codec":{"links":[],"mass_log":[],"metadata":{"mapping":[["content_basis","transport"],["donor_country","us"],["currency","USD"],["source_person_ids",{"tuple":["0000000000000000000001","0000000000000000000002","0000000000000000000003","0000000000000000000004","0000000000000000000005","0000000000000000000006"]}],["dropped_parent_cycle_edges",0]]},"schema":{"group_entities":["household"],"links":[],"person_entity":"person"},"strata":{"dtype":"dtype('O')","index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5]},"name":"stratum","values":["us:asec","us:asec","us:asec","us:puf_tax_detail","us:puf_tax_detail","us:puf_tax_detail"]},"tables":[["person",{"columns":[{"dtype":"dtype('int64')","name":"person_id","values":[9007199254741001,9007199254741002,9007199254741003,9007199254741004,9007199254741005,9007199254741006]},{"dtype":"dtype('int64')","name":"person_household_id","values":[101,101,101,202,202,202]},{"dtype":"dtype('int64')","name":"age","values":[40,38,10,45,42,12]},{"dtype":"","name":"sex","values":["male","female","male","male","female","female"]},{"dtype":"dtype('float64')","name":"employment_income","values":[0.0,10.0,20.0,30.0,40.0,50.0]},{"dtype":"dtype('float64')","name":"interest_income","values":[3.0,5.0,0.0,7.0,0.0,0.0]},{"dtype":"Int64Dtype()","name":"partner_person_id","values":[9007199254741002,9007199254741001,null,9007199254741005,9007199254741004,null]},{"dtype":"Int64Dtype()","name":"parent_1_person_id","values":[null,null,9007199254741001,null,null,9007199254741005]},{"dtype":"Int64Dtype()","name":"parent_2_person_id","values":[null,null,9007199254741002,null,null,null]},{"dtype":"dtype('float64')","name":"liquid_financial_assets","values":[60.0,0.0,0.0,180.0,0.0,0.0]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5]}}],["household",{"columns":[{"dtype":"dtype('int64')","name":"household_id","values":[101,202]},{"dtype":"Int64Dtype()","name":"reference_person_id","values":[9007199254741001,9007199254741004]},{"dtype":"dtype('float64')","name":"rent","values":[25.0,0.0]},{"dtype":")>","name":"source_household_id","values":["[[\"int\",\"2024\"],[\"int\",\"101\"]]","[[\"int\",\"2024\"],[\"int\",\"202\"]]"]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1]}}]],"weights":[["household","design",{"dtype":"dtype('float64')","index":{"dtype":"dtype('int64')","name":null,"values":[0,1]},"name":null,"values":[1.0,3.0]}]]},"create":{"frame":{"links":[],"mass_log":[],"metadata":{"mapping":[["content_basis","transport"],["donor_country","us"],["country","nz"],["donor_currency","USD"],["donor_time_period",null]]},"schema":{"group_entities":["household","family"],"links":[],"person_entity":"person"},"strata":{"dtype":"dtype('O')","index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5]},"name":"stratum","values":["us:asec","us:asec","us:asec","us:puf_tax_detail","us:puf_tax_detail","us:puf_tax_detail"]},"tables":[["person",{"columns":[{"dtype":"dtype('int64')","name":"person_id","values":[9007199254741001,9007199254741002,9007199254741003,9007199254741004,9007199254741005,9007199254741006]},{"dtype":"dtype('int64')","name":"person_household_id","values":[101,101,101,202,202,202]},{"dtype":"dtype('int64')","name":"age","values":[40,38,10,45,42,12]},{"dtype":")>","name":"sex","values":["male","female","male","male","female","female"]},{"dtype":"dtype('float64')","name":"employment_income","values":[0.0,10.0,20.0,30.0,40.0,50.0]},{"dtype":"dtype('float64')","name":"interest_income","values":[3.0,5.0,0.0,7.0,0.0,0.0]},{"dtype":"Int64Dtype()","name":"partner_person_id","values":[9007199254741002,9007199254741001,null,9007199254741005,9007199254741004,null]},{"dtype":"Int64Dtype()","name":"parent_1_person_id","values":[null,null,9007199254741001,null,null,9007199254741005]},{"dtype":"Int64Dtype()","name":"parent_2_person_id","values":[null,null,9007199254741002,null,null,null]},{"dtype":"dtype('float64')","name":"liquid_financial_assets","values":[60.0,0.0,0.0,180.0,0.0,0.0]},{"dtype":"dtype('int64')","name":"person_family_id","values":[9007199254741001,9007199254741001,9007199254741001,9007199254741004,9007199254741004,9007199254741004]},{"dtype":"dtype('float64')","name":"take_up_seed","values":[0.13877306688181723,0.5101799079557797,0.842189694141747,0.5021092355421002,0.9080986015148532,0.4057529812445503]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5]}}],["household",{"columns":[{"dtype":"dtype('int64')","name":"household_id","values":[101,202]},{"dtype":"Int64Dtype()","name":"reference_person_id","values":[9007199254741001,9007199254741004]},{"dtype":"dtype('float64')","name":"rent","values":[25.0,0.0]},{"dtype":")>","name":"source_household_id","values":["[[\"int\",\"2024\"],[\"int\",\"101\"]]","[[\"int\",\"2024\"],[\"int\",\"202\"]]"]},{"dtype":")>","name":"donor_support_stratum","values":["us:asec","us:puf_tax_detail"]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1]}}],["family",{"columns":[{"dtype":"dtype('int64')","name":"family_id","values":[9007199254741001,9007199254741004]},{"dtype":"dtype('int64')","name":"family_household_id","values":[101,202]},{"dtype":"dtype('int64')","name":"family_head_person_id","values":[9007199254741001,9007199254741004]},{"dtype":")>","name":"family_source_household_id","values":["[[\"int\",\"2024\"],[\"int\",\"101\"]]","[[\"int\",\"2024\"],[\"int\",\"202\"]]"]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1]}}]],"weights":[["household","design",{"dtype":"dtype('float64')","index":{"dtype":"dtype('int64')","name":null,"values":[0,1]},"name":null,"values":[10.0,30.0]}]]},"kernel":"transport.create@1","receipt":{"content_basis":"transport","country":"nz","design_scale":10.0,"destination_mass":120.0,"donor_country":"us","donor_mass":12.0,"donor_time_period":null,"dropped_columns":{"household":[],"person":[]},"dropped_parent_cycle_edges":0,"facts":{"facts_sha256":"bb6b1a1c00219043c8250cfe265eb08f3b727c16408cfc456ea9274e2c0e54f0","manifest_sha256":null,"n_facts":9},"mass_reference":"toy_population","n_households":2,"n_persons":6,"n_units":2,"unit_construction":{"children_with_reference_person":0,"dependent_teen_parents":0,"hours_independent_children":0,"independent_teen_parents":0,"non_partnered_coparent_households":0,"parentless_reference_person_heads":0,"younger_independent_teen_parents":0}}},"scenario":"composed"} \ No newline at end of file diff --git a/packages/microcosm-build/tests/fixtures/transport_create_baseline/nz_toy.json b/packages/microcosm-build/tests/fixtures/transport_create_baseline/nz_toy.json new file mode 100644 index 0000000000..885cf00b10 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/transport_create_baseline/nz_toy.json @@ -0,0 +1 @@ +{"codec":{"links":[],"mass_log":[],"metadata":{"mapping":[["content_basis","transport"],["donor_country","us"],["currency","USD"],["source_person_ids",{"tuple":["synthetic-10000","synthetic-10001","synthetic-10002","synthetic-10003","synthetic-10004","synthetic-10005","synthetic-10006","synthetic-10007","synthetic-10008","synthetic-10009","synthetic-10010","synthetic-10011","synthetic-10012","synthetic-10013","synthetic-10014","synthetic-10015","synthetic-10016","synthetic-10017","synthetic-10018","synthetic-10019","synthetic-10020","synthetic-10021","synthetic-10022","synthetic-10023","synthetic-10024","synthetic-10025","synthetic-10026","synthetic-10027","synthetic-10028","synthetic-10029","synthetic-10030","synthetic-10031","synthetic-10032","synthetic-10033","synthetic-10034","synthetic-10035","synthetic-10036","synthetic-10037","synthetic-10038","synthetic-10039","synthetic-10040","synthetic-10041","synthetic-10042","synthetic-10043","synthetic-10044","synthetic-10045","synthetic-10046","synthetic-10047","synthetic-10048","synthetic-10049","synthetic-10050","synthetic-10051","synthetic-10052","synthetic-10053","synthetic-10054","synthetic-10055","synthetic-10056","synthetic-10057","synthetic-10058","synthetic-10059","synthetic-10060","synthetic-10061","synthetic-10062","synthetic-10063","synthetic-10064","synthetic-10065","synthetic-10066","synthetic-10067","synthetic-10068","synthetic-10069","synthetic-10070","synthetic-10071","synthetic-10072","synthetic-10073","synthetic-10074","synthetic-10075","synthetic-10076","synthetic-10077","synthetic-10078","synthetic-10079","synthetic-10080","synthetic-10081","synthetic-10082","synthetic-10083","synthetic-10084","synthetic-10085","synthetic-10086","synthetic-10087","synthetic-10088","synthetic-10089","synthetic-10090","synthetic-10091","synthetic-10092","synthetic-10093","synthetic-10094","synthetic-10095","synthetic-10096","synthetic-10097","synthetic-10098","synthetic-10099","synthetic-10100","synthetic-10101","synthetic-10102","synthetic-10103","synthetic-10104","synthetic-10105","synthetic-10106","synthetic-10107","synthetic-10108","synthetic-10109","synthetic-10110","synthetic-10111","synthetic-10112","synthetic-10113","synthetic-10114","synthetic-10115","synthetic-10116","synthetic-10117","synthetic-10118","synthetic-10119"]}],["dropped_parent_cycle_edges",0]]},"schema":{"group_entities":["household"],"links":[],"person_entity":"person"},"strata":{"dtype":"dtype('O')","index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119]},"name":"stratum","values":["us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec"]},"tables":[["person",{"columns":[{"dtype":"dtype('int64')","name":"person_id","values":[10000,10001,10002,10003,10004,10005,10006,10007,10008,10009,10010,10011,10012,10013,10014,10015,10016,10017,10018,10019,10020,10021,10022,10023,10024,10025,10026,10027,10028,10029,10030,10031,10032,10033,10034,10035,10036,10037,10038,10039,10040,10041,10042,10043,10044,10045,10046,10047,10048,10049,10050,10051,10052,10053,10054,10055,10056,10057,10058,10059,10060,10061,10062,10063,10064,10065,10066,10067,10068,10069,10070,10071,10072,10073,10074,10075,10076,10077,10078,10079,10080,10081,10082,10083,10084,10085,10086,10087,10088,10089,10090,10091,10092,10093,10094,10095,10096,10097,10098,10099,10100,10101,10102,10103,10104,10105,10106,10107,10108,10109,10110,10111,10112,10113,10114,10115,10116,10117,10118,10119]},{"dtype":"dtype('int64')","name":"person_household_id","values":[1000,1000,1000,1001,1001,1001,1002,1002,1002,1003,1003,1003,1004,1004,1004,1005,1005,1005,1006,1006,1006,1007,1007,1007,1008,1008,1008,1009,1009,1009,1010,1010,1010,1011,1011,1011,1012,1012,1012,1013,1013,1013,1014,1014,1014,1015,1015,1015,1016,1016,1016,1017,1017,1017,1018,1018,1018,1019,1019,1019,1020,1020,1020,1021,1021,1021,1022,1022,1022,1023,1023,1023,1024,1024,1024,1025,1025,1025,1026,1026,1026,1027,1027,1027,1028,1028,1028,1029,1029,1029,1030,1030,1030,1031,1031,1031,1032,1032,1032,1033,1033,1033,1034,1034,1034,1035,1035,1035,1036,1036,1036,1037,1037,1037,1038,1038,1038,1039,1039,1039]},{"dtype":"dtype('int64')","name":"age","values":[18,40,15,19,41,16,20,16,1,21,15,1,22,44,16,23,45,17,24,46,15,25,47,16,26,48,17,27,49,15,28,50,16,29,51,17,30,52,15,31,53,16,32,54,17,33,55,15,34,56,16,35,57,17,36,58,15,37,59,16,38,60,17,39,61,15,40,62,16,18,63,17,19,64,15,20,40,16,21,41,17,22,42,15,23,43,16,24,44,17,65,70,16,66,71,16,67,72,16,68,73,16,69,74,16,70,75,16,71,76,16,72,77,16,73,78,16,74,79,16]},{"dtype":"","name":"sex","values":["male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male"]},{"dtype":"dtype('float64')","name":"employment_income","values":[10.0,11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0,20.0,21.0,22.0,23.0,24.0,25.0,26.0,27.0,28.0,29.0,30.0,31.0,32.0,33.0,34.0,35.0,36.0,37.0,38.0,39.0,40.0,41.0,42.0,43.0,44.0,45.0,46.0,47.0,48.0,49.0,50.0,51.0,52.0,53.0,54.0,55.0,56.0,57.0,58.0,59.0,60.0,61.0,62.0,63.0,64.0,65.0,66.0,67.0,68.0,69.0,70.0,71.0,72.0,73.0,74.0,75.0,76.0,77.0,78.0,79.0,80.0,81.0,82.0,83.0,84.0,85.0,86.0,87.0,88.0,89.0,90.0,91.0,92.0,93.0,94.0,95.0,96.0,97.0,98.0,99.0,100.0,101.0,102.0,103.0,104.0,105.0,106.0,107.0,108.0,109.0,110.0,111.0,112.0,113.0,114.0,115.0,116.0,117.0,118.0,119.0,120.0,121.0,122.0,123.0,124.0,125.0,126.0,127.0,128.0,129.0]},{"dtype":"dtype('float64')","name":"farm_self_employment_income","values":[0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0]},{"dtype":"dtype('float64')","name":"interest_income","values":[1.0,2.0,3.0,2.0,3.0,4.0,3.0,4.0,5.0,4.0,5.0,6.0,5.0,6.0,7.0,6.0,7.0,8.0,7.0,8.0,9.0,8.0,9.0,10.0,9.0,10.0,11.0,10.0,11.0,12.0,11.0,12.0,13.0,12.0,13.0,14.0,13.0,14.0,15.0,14.0,15.0,16.0,15.0,16.0,17.0,16.0,17.0,18.0,17.0,18.0,19.0,18.0,19.0,20.0,19.0,20.0,21.0,20.0,21.0,22.0,21.0,22.0,23.0,22.0,23.0,24.0,23.0,24.0,25.0,24.0,25.0,26.0,25.0,26.0,27.0,26.0,27.0,28.0,27.0,28.0,29.0,28.0,29.0,30.0,29.0,30.0,31.0,30.0,31.0,32.0,31.0,32.0,33.0,32.0,33.0,34.0,33.0,34.0,35.0,34.0,35.0,36.0,35.0,36.0,37.0,36.0,37.0,38.0,37.0,38.0,39.0,38.0,39.0,40.0,39.0,40.0,41.0,40.0,41.0,42.0]},{"dtype":"dtype('float64')","name":"rental_income","values":[-120.5,0.0,0.0,1.0,1.0,1.0,2.0,2.0,2.0,3.0,3.0,3.0,4.0,4.0,4.0,5.0,5.0,5.0,6.0,6.0,6.0,7.0,7.0,7.0,8.0,8.0,8.0,9.0,9.0,9.0,10.0,10.0,10.0,11.0,11.0,11.0,12.0,12.0,12.0,13.0,13.0,13.0,14.0,14.0,14.0,15.0,15.0,15.0,16.0,16.0,16.0,17.0,17.0,17.0,18.0,18.0,18.0,19.0,19.0,19.0,20.0,20.0,20.0,21.0,21.0,21.0,22.0,22.0,22.0,23.0,23.0,23.0,24.0,24.0,24.0,25.0,25.0,25.0,26.0,26.0,26.0,27.0,27.0,27.0,28.0,28.0,28.0,29.0,29.0,29.0,30.0,30.0,30.0,31.0,31.0,31.0,32.0,32.0,32.0,33.0,33.0,33.0,34.0,34.0,34.0,35.0,35.0,35.0,36.0,36.0,36.0,37.0,37.0,37.0,38.0,38.0,38.0,39.0,39.0,39.0]},{"dtype":"Int64Dtype()","name":"partner_person_id","values":[10001,10000,null,10004,10003,null,null,null,null,null,null,null,null,null,null,10016,10015,null,10019,10018,null,10022,10021,null,10025,10024,null,10028,10027,null,10031,10030,null,10034,10033,null,10037,10036,null,10040,10039,null,10043,10042,null,10046,10045,null,10049,10048,null,10052,10051,null,10055,10054,null,10058,10057,null,10061,10060,null,10064,10063,null,10067,10066,null,10070,10069,null,10073,10072,null,10076,10075,null,10079,10078,null,10082,10081,null,10085,10084,null,10088,10087,null,10091,10090,null,10094,10093,null,10097,10096,null,10100,10099,null,10103,10102,null,10106,10105,null,10109,10108,null,10112,10111,null,10115,10114,null,10118,10117,null]},{"dtype":"Int64Dtype()","name":"parent_1_person_id","values":[null,null,10000,null,null,10003,null,10006,10007,null,10009,10010,null,null,10012,null,null,null,null,null,10018,null,null,10021,null,null,10024,null,null,10027,null,null,10030,null,null,10033,null,null,10036,null,null,10039,null,null,10042,null,null,10045,null,null,10048,null,null,10051,null,null,10054,null,null,10057,null,null,10060,null,null,10063,null,null,10066,null,null,10069,null,null,10072,null,null,10075,null,null,10078,null,null,10081,null,null,10084,null,null,10087,null,null,10090,null,null,10093,null,null,10096,null,null,10099,null,null,10102,null,null,10105,null,null,10108,null,null,10111,null,null,10114,null,null,10117]},{"dtype":"Int64Dtype()","name":"parent_2_person_id","values":[null,null,10001,null,null,10004,null,null,null,null,null,null,null,null,10013,null,null,null,null,null,10019,null,null,10022,null,null,10025,null,null,10028,null,null,10031,null,null,10034,null,null,10037,null,null,10040,null,null,10043,null,null,10046,null,null,10049,null,null,10052,null,null,10055,null,null,10058,null,null,10061,null,null,10064,null,null,10067,null,null,10070,null,null,10073,null,null,10076,null,null,10079,null,null,10082,null,null,10085,null,null,10088,null,null,10091,null,null,10094,null,null,10097,null,null,10100,null,null,10103,null,null,10106,null,null,10109,null,null,10112,null,null,10115,null,null,10118]},{"dtype":"dtype('float64')","name":"liquid_financial_assets","values":[50.0,1.0,2.0,52.0,3.0,4.0,54.0,5.0,6.0,56.0,7.0,8.0,58.0,9.0,10.0,60.0,11.0,12.0,62.0,13.0,14.0,64.0,15.0,16.0,66.0,17.0,18.0,68.0,19.0,20.0,70.0,21.0,22.0,72.0,23.0,24.0,74.0,25.0,26.0,76.0,27.0,28.0,78.0,29.0,30.0,80.0,31.0,32.0,82.0,33.0,34.0,84.0,35.0,36.0,86.0,37.0,38.0,88.0,39.0,40.0,90.0,41.0,42.0,92.0,43.0,44.0,94.0,45.0,46.0,96.0,47.0,48.0,98.0,49.0,50.0,100.0,51.0,52.0,102.0,53.0,54.0,104.0,55.0,56.0,106.0,57.0,58.0,108.0,59.0,60.0,110.0,61.0,62.0,112.0,63.0,64.0,114.0,65.0,66.0,116.0,67.0,68.0,118.0,69.0,70.0,120.0,71.0,72.0,122.0,73.0,74.0,124.0,75.0,76.0,126.0,77.0,78.0,128.0,79.0,80.0]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119]}}],["household",{"columns":[{"dtype":"dtype('int64')","name":"household_id","values":[1000,1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013,1014,1015,1016,1017,1018,1019,1020,1021,1022,1023,1024,1025,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,1037,1038,1039]},{"dtype":"Int64Dtype()","name":"reference_person_id","values":[10000,10003,10006,10009,10012,10015,10018,10021,10024,10027,10030,10033,10036,10039,10042,10045,10048,10051,10054,10057,10060,10063,10066,10069,10072,10075,10078,10081,10084,10087,10090,10093,10096,10099,10102,10105,10108,10111,10114,10117]},{"dtype":"dtype('float64')","name":"rent","values":[100.0,101.0,102.0,103.0,104.0,105.0,106.0,107.0,108.0,109.0,110.0,111.0,112.0,113.0,114.0,115.0,116.0,117.0,118.0,119.0,120.0,121.0,122.0,123.0,124.0,125.0,126.0,127.0,128.0,129.0,130.0,131.0,132.0,133.0,134.0,135.0,136.0,137.0,138.0,139.0]},{"dtype":")>","name":"source_household_id","values":["[[\"int\",\"2024\"],[\"int\",\"1000\"]]","[[\"int\",\"2024\"],[\"int\",\"1000\"]]","[[\"int\",\"2024\"],[\"int\",\"1002\"]]","[[\"int\",\"2024\"],[\"int\",\"1003\"]]","[[\"int\",\"2024\"],[\"int\",\"1004\"]]","[[\"int\",\"2024\"],[\"int\",\"1005\"]]","[[\"int\",\"2024\"],[\"int\",\"1006\"]]","[[\"int\",\"2024\"],[\"int\",\"1007\"]]","[[\"int\",\"2024\"],[\"int\",\"1008\"]]","[[\"int\",\"2024\"],[\"int\",\"1009\"]]","[[\"int\",\"2024\"],[\"int\",\"1010\"]]","[[\"int\",\"2024\"],[\"int\",\"1011\"]]","[[\"int\",\"2024\"],[\"int\",\"1012\"]]","[[\"int\",\"2024\"],[\"int\",\"1013\"]]","[[\"int\",\"2024\"],[\"int\",\"1014\"]]","[[\"int\",\"2024\"],[\"int\",\"1015\"]]","[[\"int\",\"2024\"],[\"int\",\"1016\"]]","[[\"int\",\"2024\"],[\"int\",\"1017\"]]","[[\"int\",\"2024\"],[\"int\",\"1018\"]]","[[\"int\",\"2024\"],[\"int\",\"1019\"]]","[[\"int\",\"2024\"],[\"int\",\"1020\"]]","[[\"int\",\"2024\"],[\"int\",\"1021\"]]","[[\"int\",\"2024\"],[\"int\",\"1022\"]]","[[\"int\",\"2024\"],[\"int\",\"1023\"]]","[[\"int\",\"2024\"],[\"int\",\"1024\"]]","[[\"int\",\"2024\"],[\"int\",\"1025\"]]","[[\"int\",\"2024\"],[\"int\",\"1026\"]]","[[\"int\",\"2024\"],[\"int\",\"1027\"]]","[[\"int\",\"2024\"],[\"int\",\"1028\"]]","[[\"int\",\"2024\"],[\"int\",\"1029\"]]","[[\"int\",\"2024\"],[\"int\",\"1030\"]]","[[\"int\",\"2024\"],[\"int\",\"1031\"]]","[[\"int\",\"2024\"],[\"int\",\"1032\"]]","[[\"int\",\"2024\"],[\"int\",\"1033\"]]","[[\"int\",\"2024\"],[\"int\",\"1034\"]]","[[\"int\",\"2024\"],[\"int\",\"1035\"]]","[[\"int\",\"2024\"],[\"int\",\"1036\"]]","[[\"int\",\"2024\"],[\"int\",\"1037\"]]","[[\"int\",\"2024\"],[\"int\",\"1038\"]]","[[\"int\",\"2024\"],[\"int\",\"1039\"]]"]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39]}}]],"weights":[["household","design",{"dtype":"dtype('float64')","index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39]},"name":null,"values":[0.5,0.5,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0]}]]},"create":{"frame":{"links":[],"mass_log":[],"metadata":{"mapping":[["content_basis","transport"],["donor_country","us"],["country","nz"],["donor_currency","USD"],["donor_time_period",2024]]},"schema":{"group_entities":["household","family"],"links":[],"person_entity":"person"},"strata":{"dtype":"dtype('O')","index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119]},"name":"stratum","values":["us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec"]},"tables":[["person",{"columns":[{"dtype":"dtype('int64')","name":"person_id","values":[10000,10001,10002,10003,10004,10005,10006,10007,10008,10009,10010,10011,10012,10013,10014,10015,10016,10017,10018,10019,10020,10021,10022,10023,10024,10025,10026,10027,10028,10029,10030,10031,10032,10033,10034,10035,10036,10037,10038,10039,10040,10041,10042,10043,10044,10045,10046,10047,10048,10049,10050,10051,10052,10053,10054,10055,10056,10057,10058,10059,10060,10061,10062,10063,10064,10065,10066,10067,10068,10069,10070,10071,10072,10073,10074,10075,10076,10077,10078,10079,10080,10081,10082,10083,10084,10085,10086,10087,10088,10089,10090,10091,10092,10093,10094,10095,10096,10097,10098,10099,10100,10101,10102,10103,10104,10105,10106,10107,10108,10109,10110,10111,10112,10113,10114,10115,10116,10117,10118,10119]},{"dtype":"dtype('int64')","name":"person_household_id","values":[1000,1000,1000,1001,1001,1001,1002,1002,1002,1003,1003,1003,1004,1004,1004,1005,1005,1005,1006,1006,1006,1007,1007,1007,1008,1008,1008,1009,1009,1009,1010,1010,1010,1011,1011,1011,1012,1012,1012,1013,1013,1013,1014,1014,1014,1015,1015,1015,1016,1016,1016,1017,1017,1017,1018,1018,1018,1019,1019,1019,1020,1020,1020,1021,1021,1021,1022,1022,1022,1023,1023,1023,1024,1024,1024,1025,1025,1025,1026,1026,1026,1027,1027,1027,1028,1028,1028,1029,1029,1029,1030,1030,1030,1031,1031,1031,1032,1032,1032,1033,1033,1033,1034,1034,1034,1035,1035,1035,1036,1036,1036,1037,1037,1037,1038,1038,1038,1039,1039,1039]},{"dtype":"dtype('int64')","name":"age","values":[18,40,15,19,41,16,20,16,1,21,15,1,22,44,16,23,45,17,24,46,15,25,47,16,26,48,17,27,49,15,28,50,16,29,51,17,30,52,15,31,53,16,32,54,17,33,55,15,34,56,16,35,57,17,36,58,15,37,59,16,38,60,17,39,61,15,40,62,16,18,63,17,19,64,15,20,40,16,21,41,17,22,42,15,23,43,16,24,44,17,65,70,16,66,71,16,67,72,16,68,73,16,69,74,16,70,75,16,71,76,16,72,77,16,73,78,16,74,79,16]},{"dtype":")>","name":"sex","values":["male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male","male","female","male"]},{"dtype":"dtype('float64')","name":"employment_income","values":[10.0,11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0,20.0,21.0,22.0,23.0,24.0,25.0,26.0,27.0,28.0,29.0,30.0,31.0,32.0,33.0,34.0,35.0,36.0,37.0,38.0,39.0,40.0,41.0,42.0,43.0,44.0,45.0,46.0,47.0,48.0,49.0,50.0,51.0,52.0,53.0,54.0,55.0,56.0,57.0,58.0,59.0,60.0,61.0,62.0,63.0,64.0,65.0,66.0,67.0,68.0,69.0,70.0,71.0,72.0,73.0,74.0,75.0,76.0,77.0,78.0,79.0,80.0,81.0,82.0,83.0,84.0,85.0,86.0,87.0,88.0,89.0,90.0,91.0,92.0,93.0,94.0,95.0,96.0,97.0,98.0,99.0,100.0,101.0,102.0,103.0,104.0,105.0,106.0,107.0,108.0,109.0,110.0,111.0,112.0,113.0,114.0,115.0,116.0,117.0,118.0,119.0,120.0,121.0,122.0,123.0,124.0,125.0,126.0,127.0,128.0,129.0]},{"dtype":"dtype('float64')","name":"farm_self_employment_income","values":[0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0,0.0,1.0,2.0]},{"dtype":"dtype('float64')","name":"interest_income","values":[1.0,2.0,3.0,2.0,3.0,4.0,3.0,4.0,5.0,4.0,5.0,6.0,5.0,6.0,7.0,6.0,7.0,8.0,7.0,8.0,9.0,8.0,9.0,10.0,9.0,10.0,11.0,10.0,11.0,12.0,11.0,12.0,13.0,12.0,13.0,14.0,13.0,14.0,15.0,14.0,15.0,16.0,15.0,16.0,17.0,16.0,17.0,18.0,17.0,18.0,19.0,18.0,19.0,20.0,19.0,20.0,21.0,20.0,21.0,22.0,21.0,22.0,23.0,22.0,23.0,24.0,23.0,24.0,25.0,24.0,25.0,26.0,25.0,26.0,27.0,26.0,27.0,28.0,27.0,28.0,29.0,28.0,29.0,30.0,29.0,30.0,31.0,30.0,31.0,32.0,31.0,32.0,33.0,32.0,33.0,34.0,33.0,34.0,35.0,34.0,35.0,36.0,35.0,36.0,37.0,36.0,37.0,38.0,37.0,38.0,39.0,38.0,39.0,40.0,39.0,40.0,41.0,40.0,41.0,42.0]},{"dtype":"dtype('float64')","name":"rental_income","values":[-120.5,0.0,0.0,1.0,1.0,1.0,2.0,2.0,2.0,3.0,3.0,3.0,4.0,4.0,4.0,5.0,5.0,5.0,6.0,6.0,6.0,7.0,7.0,7.0,8.0,8.0,8.0,9.0,9.0,9.0,10.0,10.0,10.0,11.0,11.0,11.0,12.0,12.0,12.0,13.0,13.0,13.0,14.0,14.0,14.0,15.0,15.0,15.0,16.0,16.0,16.0,17.0,17.0,17.0,18.0,18.0,18.0,19.0,19.0,19.0,20.0,20.0,20.0,21.0,21.0,21.0,22.0,22.0,22.0,23.0,23.0,23.0,24.0,24.0,24.0,25.0,25.0,25.0,26.0,26.0,26.0,27.0,27.0,27.0,28.0,28.0,28.0,29.0,29.0,29.0,30.0,30.0,30.0,31.0,31.0,31.0,32.0,32.0,32.0,33.0,33.0,33.0,34.0,34.0,34.0,35.0,35.0,35.0,36.0,36.0,36.0,37.0,37.0,37.0,38.0,38.0,38.0,39.0,39.0,39.0]},{"dtype":"Int64Dtype()","name":"partner_person_id","values":[10001,10000,null,10004,10003,null,null,null,null,null,null,null,null,null,null,10016,10015,null,10019,10018,null,10022,10021,null,10025,10024,null,10028,10027,null,10031,10030,null,10034,10033,null,10037,10036,null,10040,10039,null,10043,10042,null,10046,10045,null,10049,10048,null,10052,10051,null,10055,10054,null,10058,10057,null,10061,10060,null,10064,10063,null,10067,10066,null,10070,10069,null,10073,10072,null,10076,10075,null,10079,10078,null,10082,10081,null,10085,10084,null,10088,10087,null,10091,10090,null,10094,10093,null,10097,10096,null,10100,10099,null,10103,10102,null,10106,10105,null,10109,10108,null,10112,10111,null,10115,10114,null,10118,10117,null]},{"dtype":"Int64Dtype()","name":"parent_1_person_id","values":[null,null,10000,null,null,10003,null,10006,10007,null,10009,10010,null,null,10012,null,null,null,null,null,10018,null,null,10021,null,null,10024,null,null,10027,null,null,10030,null,null,10033,null,null,10036,null,null,10039,null,null,10042,null,null,10045,null,null,10048,null,null,10051,null,null,10054,null,null,10057,null,null,10060,null,null,10063,null,null,10066,null,null,10069,null,null,10072,null,null,10075,null,null,10078,null,null,10081,null,null,10084,null,null,10087,null,null,10090,null,null,10093,null,null,10096,null,null,10099,null,null,10102,null,null,10105,null,null,10108,null,null,10111,null,null,10114,null,null,10117]},{"dtype":"Int64Dtype()","name":"parent_2_person_id","values":[null,null,10001,null,null,10004,null,null,null,null,null,null,null,null,10013,null,null,null,null,null,10019,null,null,10022,null,null,10025,null,null,10028,null,null,10031,null,null,10034,null,null,10037,null,null,10040,null,null,10043,null,null,10046,null,null,10049,null,null,10052,null,null,10055,null,null,10058,null,null,10061,null,null,10064,null,null,10067,null,null,10070,null,null,10073,null,null,10076,null,null,10079,null,null,10082,null,null,10085,null,null,10088,null,null,10091,null,null,10094,null,null,10097,null,null,10100,null,null,10103,null,null,10106,null,null,10109,null,null,10112,null,null,10115,null,null,10118]},{"dtype":"dtype('float64')","name":"liquid_financial_assets","values":[50.0,1.0,2.0,52.0,3.0,4.0,54.0,5.0,6.0,56.0,7.0,8.0,58.0,9.0,10.0,60.0,11.0,12.0,62.0,13.0,14.0,64.0,15.0,16.0,66.0,17.0,18.0,68.0,19.0,20.0,70.0,21.0,22.0,72.0,23.0,24.0,74.0,25.0,26.0,76.0,27.0,28.0,78.0,29.0,30.0,80.0,31.0,32.0,82.0,33.0,34.0,84.0,35.0,36.0,86.0,37.0,38.0,88.0,39.0,40.0,90.0,41.0,42.0,92.0,43.0,44.0,94.0,45.0,46.0,96.0,47.0,48.0,98.0,49.0,50.0,100.0,51.0,52.0,102.0,53.0,54.0,104.0,55.0,56.0,106.0,57.0,58.0,108.0,59.0,60.0,110.0,61.0,62.0,112.0,63.0,64.0,114.0,65.0,66.0,116.0,67.0,68.0,118.0,69.0,70.0,120.0,71.0,72.0,122.0,73.0,74.0,124.0,75.0,76.0,126.0,77.0,78.0,128.0,79.0,80.0]},{"dtype":"dtype('int64')","name":"person_family_id","values":[10000,10000,10000,10003,10003,10003,10006,10007,10007,10009,10009,10009,10012,10013,10012,10015,10015,10015,10018,10018,10018,10021,10021,10021,10024,10024,10024,10027,10027,10027,10030,10030,10030,10033,10033,10033,10036,10036,10036,10039,10039,10039,10042,10042,10042,10045,10045,10045,10048,10048,10048,10051,10051,10051,10054,10054,10054,10057,10057,10057,10060,10060,10060,10063,10063,10063,10066,10066,10066,10069,10069,10069,10072,10072,10072,10075,10075,10075,10078,10078,10078,10081,10081,10081,10084,10084,10084,10087,10087,10087,10090,10090,10090,10093,10093,10093,10096,10096,10096,10099,10099,10099,10102,10102,10102,10105,10105,10105,10108,10108,10108,10111,10111,10111,10114,10114,10114,10117,10117,10117]},{"dtype":"dtype('float64')","name":"take_up_seed","values":[0.5228738146203967,0.3254267870941906,0.5920323428797988,0.6515379650559883,0.20709180639030833,0.8983428888819011,0.7854482971319909,0.33286893873439294,0.6060182947838615,0.9786306221025811,0.08681511007495668,0.12619488938161416,0.7816655689315657,0.7106164600492729,0.6934814082211563,0.8562343867967207,0.4179787505684026,0.3407740126424157,0.7884018325660817,0.5143478651779133,0.46721831682472226,0.5802881030449999,0.0007719634921157237,0.13587448801096713,0.46217087398017587,0.4554289812567859,0.353418918092277,0.08732761402719713,0.0850562307470446,0.6049057310564376,0.06397810732974052,0.8281005635214812,0.20726770568584674,0.1763362140526451,0.4750475452580354,0.9251958284948569,0.4631995036925234,0.3687157498574417,0.32031963841849265,0.7707756482015623,0.007637497925983561,0.9965960214637929,0.5249893545938941,0.3223935084648396,0.9411234444151718,0.24536406201175986,0.6743778132499219,0.15192490716433238,0.07339496610246776,0.9605455016463181,0.742395750591199,0.2990082228661667,0.88952813197154,0.18953902928381117,0.0064875046487774535,0.09031820497007426,0.8585207239635266,0.8744557719449193,0.9640893980379401,0.9923664545586341,0.2536355652580675,0.7715960515794078,0.02921725996975799,0.6522806966045969,0.8231682829794985,0.4473857410214026,0.38785686741291836,0.44231981218674243,0.0650380881134549,0.2813219234623803,0.46753923052979907,0.8588200731627477,0.9913114694482162,0.38284055377533366,0.3826358350460315,0.7694135519286658,0.9645432078328021,0.7836144775810547,0.7972048459481378,0.05103878883017632,0.8543492601276581,0.4880791490664629,0.9942277430342606,0.8830433408417017,0.5882309409297268,0.8613283397219732,0.9133244675458445,0.8526347799908333,0.08512272637283591,0.40259340080120676,0.18846001660963818,0.8586433048424416,0.9923420496851347,0.43344819310918237,0.080276503198357,0.43302657861655913,0.5019137427660254,0.8709665931128354,0.5698566466100312,0.6759583357064674,0.8597382730657402,0.2537673029748654,0.16851173370870154,0.4048287114330985,0.8145860085617888,0.6169438660174555,0.8956320136793827,0.5385336419947201,0.5733957107162002,0.5262849772303289,0.3413441100771535,0.2786340059320124,0.17213258941294274,0.5942353019568833,0.1559358202828407,0.05916383483241483,0.407095450909847,0.5150052318745881,0.5700353027064688,0.7924822684821269]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119]}}],["household",{"columns":[{"dtype":"dtype('int64')","name":"household_id","values":[1000,1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013,1014,1015,1016,1017,1018,1019,1020,1021,1022,1023,1024,1025,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,1037,1038,1039]},{"dtype":"Int64Dtype()","name":"reference_person_id","values":[10000,10003,10006,10009,10012,10015,10018,10021,10024,10027,10030,10033,10036,10039,10042,10045,10048,10051,10054,10057,10060,10063,10066,10069,10072,10075,10078,10081,10084,10087,10090,10093,10096,10099,10102,10105,10108,10111,10114,10117]},{"dtype":"dtype('float64')","name":"rent","values":[100.0,101.0,102.0,103.0,104.0,105.0,106.0,107.0,108.0,109.0,110.0,111.0,112.0,113.0,114.0,115.0,116.0,117.0,118.0,119.0,120.0,121.0,122.0,123.0,124.0,125.0,126.0,127.0,128.0,129.0,130.0,131.0,132.0,133.0,134.0,135.0,136.0,137.0,138.0,139.0]},{"dtype":")>","name":"source_household_id","values":["[[\"int\",\"2024\"],[\"int\",\"1000\"]]","[[\"int\",\"2024\"],[\"int\",\"1000\"]]","[[\"int\",\"2024\"],[\"int\",\"1002\"]]","[[\"int\",\"2024\"],[\"int\",\"1003\"]]","[[\"int\",\"2024\"],[\"int\",\"1004\"]]","[[\"int\",\"2024\"],[\"int\",\"1005\"]]","[[\"int\",\"2024\"],[\"int\",\"1006\"]]","[[\"int\",\"2024\"],[\"int\",\"1007\"]]","[[\"int\",\"2024\"],[\"int\",\"1008\"]]","[[\"int\",\"2024\"],[\"int\",\"1009\"]]","[[\"int\",\"2024\"],[\"int\",\"1010\"]]","[[\"int\",\"2024\"],[\"int\",\"1011\"]]","[[\"int\",\"2024\"],[\"int\",\"1012\"]]","[[\"int\",\"2024\"],[\"int\",\"1013\"]]","[[\"int\",\"2024\"],[\"int\",\"1014\"]]","[[\"int\",\"2024\"],[\"int\",\"1015\"]]","[[\"int\",\"2024\"],[\"int\",\"1016\"]]","[[\"int\",\"2024\"],[\"int\",\"1017\"]]","[[\"int\",\"2024\"],[\"int\",\"1018\"]]","[[\"int\",\"2024\"],[\"int\",\"1019\"]]","[[\"int\",\"2024\"],[\"int\",\"1020\"]]","[[\"int\",\"2024\"],[\"int\",\"1021\"]]","[[\"int\",\"2024\"],[\"int\",\"1022\"]]","[[\"int\",\"2024\"],[\"int\",\"1023\"]]","[[\"int\",\"2024\"],[\"int\",\"1024\"]]","[[\"int\",\"2024\"],[\"int\",\"1025\"]]","[[\"int\",\"2024\"],[\"int\",\"1026\"]]","[[\"int\",\"2024\"],[\"int\",\"1027\"]]","[[\"int\",\"2024\"],[\"int\",\"1028\"]]","[[\"int\",\"2024\"],[\"int\",\"1029\"]]","[[\"int\",\"2024\"],[\"int\",\"1030\"]]","[[\"int\",\"2024\"],[\"int\",\"1031\"]]","[[\"int\",\"2024\"],[\"int\",\"1032\"]]","[[\"int\",\"2024\"],[\"int\",\"1033\"]]","[[\"int\",\"2024\"],[\"int\",\"1034\"]]","[[\"int\",\"2024\"],[\"int\",\"1035\"]]","[[\"int\",\"2024\"],[\"int\",\"1036\"]]","[[\"int\",\"2024\"],[\"int\",\"1037\"]]","[[\"int\",\"2024\"],[\"int\",\"1038\"]]","[[\"int\",\"2024\"],[\"int\",\"1039\"]]"]},{"dtype":")>","name":"donor_support_stratum","values":["us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec","us:asec"]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39]}}],["family",{"columns":[{"dtype":"dtype('int64')","name":"family_id","values":[10000,10003,10006,10007,10009,10012,10013,10015,10018,10021,10024,10027,10030,10033,10036,10039,10042,10045,10048,10051,10054,10057,10060,10063,10066,10069,10072,10075,10078,10081,10084,10087,10090,10093,10096,10099,10102,10105,10108,10111,10114,10117]},{"dtype":"dtype('int64')","name":"family_household_id","values":[1000,1001,1002,1002,1003,1004,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013,1014,1015,1016,1017,1018,1019,1020,1021,1022,1023,1024,1025,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,1037,1038,1039]},{"dtype":"dtype('int64')","name":"family_head_person_id","values":[10000,10003,10006,10007,10009,10012,10013,10015,10018,10021,10024,10027,10030,10033,10036,10039,10042,10045,10048,10051,10054,10057,10060,10063,10066,10069,10072,10075,10078,10081,10084,10087,10090,10093,10096,10099,10102,10105,10108,10111,10114,10117]},{"dtype":")>","name":"family_source_household_id","values":["[[\"int\",\"2024\"],[\"int\",\"1000\"]]","[[\"int\",\"2024\"],[\"int\",\"1000\"]]","[[\"int\",\"2024\"],[\"int\",\"1002\"]]","[[\"int\",\"2024\"],[\"int\",\"1002\"]]","[[\"int\",\"2024\"],[\"int\",\"1003\"]]","[[\"int\",\"2024\"],[\"int\",\"1004\"]]","[[\"int\",\"2024\"],[\"int\",\"1004\"]]","[[\"int\",\"2024\"],[\"int\",\"1005\"]]","[[\"int\",\"2024\"],[\"int\",\"1006\"]]","[[\"int\",\"2024\"],[\"int\",\"1007\"]]","[[\"int\",\"2024\"],[\"int\",\"1008\"]]","[[\"int\",\"2024\"],[\"int\",\"1009\"]]","[[\"int\",\"2024\"],[\"int\",\"1010\"]]","[[\"int\",\"2024\"],[\"int\",\"1011\"]]","[[\"int\",\"2024\"],[\"int\",\"1012\"]]","[[\"int\",\"2024\"],[\"int\",\"1013\"]]","[[\"int\",\"2024\"],[\"int\",\"1014\"]]","[[\"int\",\"2024\"],[\"int\",\"1015\"]]","[[\"int\",\"2024\"],[\"int\",\"1016\"]]","[[\"int\",\"2024\"],[\"int\",\"1017\"]]","[[\"int\",\"2024\"],[\"int\",\"1018\"]]","[[\"int\",\"2024\"],[\"int\",\"1019\"]]","[[\"int\",\"2024\"],[\"int\",\"1020\"]]","[[\"int\",\"2024\"],[\"int\",\"1021\"]]","[[\"int\",\"2024\"],[\"int\",\"1022\"]]","[[\"int\",\"2024\"],[\"int\",\"1023\"]]","[[\"int\",\"2024\"],[\"int\",\"1024\"]]","[[\"int\",\"2024\"],[\"int\",\"1025\"]]","[[\"int\",\"2024\"],[\"int\",\"1026\"]]","[[\"int\",\"2024\"],[\"int\",\"1027\"]]","[[\"int\",\"2024\"],[\"int\",\"1028\"]]","[[\"int\",\"2024\"],[\"int\",\"1029\"]]","[[\"int\",\"2024\"],[\"int\",\"1030\"]]","[[\"int\",\"2024\"],[\"int\",\"1031\"]]","[[\"int\",\"2024\"],[\"int\",\"1032\"]]","[[\"int\",\"2024\"],[\"int\",\"1033\"]]","[[\"int\",\"2024\"],[\"int\",\"1034\"]]","[[\"int\",\"2024\"],[\"int\",\"1035\"]]","[[\"int\",\"2024\"],[\"int\",\"1036\"]]","[[\"int\",\"2024\"],[\"int\",\"1037\"]]","[[\"int\",\"2024\"],[\"int\",\"1038\"]]","[[\"int\",\"2024\"],[\"int\",\"1039\"]]"]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41]}}]],"weights":[["household","design",{"dtype":"dtype('float64')","index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39]},"name":null,"values":[0.5128205128205128,0.5128205128205128,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255,1.0256410256410255]}]]},"kernel":"transport.create@1","receipt":{"content_basis":"transport","country":"nz","design_scale":1.0256410256410255,"destination_mass":120.0,"donor_country":"us","donor_mass":117.0,"donor_time_period":2024,"dropped_columns":{"household":[],"person":[]},"dropped_parent_cycle_edges":0,"facts":{"facts_sha256":"91f26203f2ca8259c2996cd3caba06cc32fb7560842d078ac7dee7273e710a62","manifest_sha256":"7cfca8ce75e62e412639c95d5df4b281af2ffb65119a01a023b864238c9d6874","n_facts":41},"mass_reference":"toy_population","n_households":40,"n_persons":120,"n_units":42,"unit_construction":{"children_with_reference_person":1,"dependent_teen_parents":1,"hours_independent_children":0,"independent_teen_parents":1,"non_partnered_coparent_households":1,"parentless_reference_person_heads":0,"younger_independent_teen_parents":0}}},"scenario":"nz_toy"} \ No newline at end of file diff --git a/packages/microcosm-build/tests/fixtures/transport_create_baseline/provenance.json b/packages/microcosm-build/tests/fixtures/transport_create_baseline/provenance.json new file mode 100644 index 0000000000..86d5a0d21c --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/transport_create_baseline/provenance.json @@ -0,0 +1,25 @@ +{ + "base_commit": "cfd5a2a5ea8fbaa0269f434d10c50eb389eabc83", + "capture_command": "python -m test_support.microcosm_build.transport_create_baseline packages/microcosm-build/tests/fixtures/transport_create_baseline", + "capture_module": "test_support/microcosm_build/transport_create_baseline.py", + "capture_module_sha256": "0743de62aa8208dbc00fc57a7e1bc43ad0e7f4d8a24786bc88ca31b489e300a0", + "captured": "2026-11-19", + "environment": { + "numpy": "2.4.6", + "pandas": "3.0.3", + "pyarrow": "25.0.0", + "python": "3.14.7", + "tables": "3.11.1" + }, + "files": { + "composed.json": "035cc4971383991e4f0fc3237b23a6e2d99ec892f2a35844ef54feeea3be6581", + "nz_toy.json": "474296d58ea31837ffce71934191ed83703037b19c7def1bc0162d813221340d", + "toy.json": "af27c7572740cb6f3ce30135e546865aeb6e999ca311d2b50fe4710c69d797f9", + "toy_profile_columns.json": "bb38c33be9586c4589c7ee9dc03183101fceee92a1ca936e6c76df18976cff23", + "toy_v2.json": "22e91f0a2ae09425fa27eb4059cf9b56910bade3c1616ea89424f98e6105c162" + }, + "kind": "transport_create_no_profile_baseline", + "reproduction": "The capture module with this SHA-256, run with the base commit's microcosm/frame/transport.py and microcosm/build/transport/population_kernels.py in place of the edited ones, writes every file listed here byte for byte.", + "schema_version": 1, + "scope": "Captured on the unedited base commit, before CREATE accepted a donor_profile. Each file holds the canonical bytes of transport.create's frame and receipt on its declared params and sources, and of the populace-us-h5-v1 codec's frame, for one toy donor or composed toy graph. No file holds real donor data." +} diff --git a/packages/microcosm-build/tests/fixtures/transport_create_baseline/toy.json b/packages/microcosm-build/tests/fixtures/transport_create_baseline/toy.json new file mode 100644 index 0000000000..a41cb76105 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/transport_create_baseline/toy.json @@ -0,0 +1 @@ +{"codec":{"links":[],"mass_log":[],"metadata":{"mapping":[["content_basis","transport"],["donor_country","us"],["currency","USD"],["source_person_ids",{"tuple":["0000000000000000000001","0000000000000000000002","0000000000000000000003","0000000000000000000004","0000000000000000000005","0000000000000000000006"]}],["dropped_parent_cycle_edges",0]]},"schema":{"group_entities":["household"],"links":[],"person_entity":"person"},"strata":{"dtype":"dtype('O')","index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5]},"name":"stratum","values":["us:asec","us:asec","us:asec","us:puf_tax_detail","us:puf_tax_detail","us:puf_tax_detail"]},"tables":[["person",{"columns":[{"dtype":"dtype('int64')","name":"person_id","values":[9007199254741001,9007199254741002,9007199254741003,9007199254741004,9007199254741005,9007199254741006]},{"dtype":"dtype('int64')","name":"person_household_id","values":[101,101,101,202,202,202]},{"dtype":"dtype('int64')","name":"age","values":[40,38,10,45,42,12]},{"dtype":"","name":"sex","values":["male","female","male","male","female","female"]},{"dtype":"dtype('float64')","name":"employment_income","values":[0.0,10.0,20.0,30.0,40.0,50.0]},{"dtype":"dtype('float64')","name":"interest_income","values":[3.0,5.0,0.0,7.0,0.0,0.0]},{"dtype":"Int64Dtype()","name":"partner_person_id","values":[9007199254741002,9007199254741001,null,9007199254741005,9007199254741004,null]},{"dtype":"Int64Dtype()","name":"parent_1_person_id","values":[null,null,9007199254741001,null,null,9007199254741005]},{"dtype":"Int64Dtype()","name":"parent_2_person_id","values":[null,null,9007199254741002,null,null,null]},{"dtype":"dtype('float64')","name":"liquid_financial_assets","values":[60.0,0.0,0.0,180.0,0.0,0.0]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5]}}],["household",{"columns":[{"dtype":"dtype('int64')","name":"household_id","values":[101,202]},{"dtype":"Int64Dtype()","name":"reference_person_id","values":[9007199254741001,9007199254741004]},{"dtype":"dtype('float64')","name":"rent","values":[25.0,0.0]},{"dtype":")>","name":"source_household_id","values":["[[\"int\",\"2024\"],[\"int\",\"101\"]]","[[\"int\",\"2024\"],[\"int\",\"202\"]]"]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1]}}]],"weights":[["household","design",{"dtype":"dtype('float64')","index":{"dtype":"dtype('int64')","name":null,"values":[0,1]},"name":null,"values":[1.0,3.0]}]]},"create":{"frame":{"links":[],"mass_log":[],"metadata":{"mapping":[["content_basis","transport"],["donor_country","us"],["country","xx"],["donor_currency","USD"],["donor_time_period",null]]},"schema":{"group_entities":["household","family"],"links":[],"person_entity":"person"},"strata":{"dtype":"dtype('O')","index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5]},"name":"stratum","values":["us:asec","us:asec","us:asec","us:puf_tax_detail","us:puf_tax_detail","us:puf_tax_detail"]},"tables":[["person",{"columns":[{"dtype":"dtype('int64')","name":"person_id","values":[9007199254741001,9007199254741002,9007199254741003,9007199254741004,9007199254741005,9007199254741006]},{"dtype":"dtype('int64')","name":"person_household_id","values":[101,101,101,202,202,202]},{"dtype":"dtype('int64')","name":"age","values":[40,38,10,45,42,12]},{"dtype":")>","name":"sex","values":["male","female","male","male","female","female"]},{"dtype":"dtype('float64')","name":"employment_income","values":[0.0,10.0,20.0,30.0,40.0,50.0]},{"dtype":"dtype('float64')","name":"interest_income","values":[3.0,5.0,0.0,7.0,0.0,0.0]},{"dtype":"Int64Dtype()","name":"partner_person_id","values":[9007199254741002,9007199254741001,null,9007199254741005,9007199254741004,null]},{"dtype":"Int64Dtype()","name":"parent_1_person_id","values":[null,null,9007199254741001,null,null,9007199254741005]},{"dtype":"Int64Dtype()","name":"parent_2_person_id","values":[null,null,9007199254741002,null,null,null]},{"dtype":"dtype('float64')","name":"liquid_financial_assets","values":[60.0,0.0,0.0,180.0,0.0,0.0]},{"dtype":"dtype('int64')","name":"person_family_id","values":[9007199254741001,9007199254741001,9007199254741001,9007199254741004,9007199254741004,9007199254741004]},{"dtype":"dtype('float64')","name":"take_up_seed","values":[0.13479855962228915,0.814136316266239,0.30432980533210985,0.17633266258664693,0.5877081982295528,0.910367081750198]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5]}}],["household",{"columns":[{"dtype":"dtype('int64')","name":"household_id","values":[101,202]},{"dtype":"Int64Dtype()","name":"reference_person_id","values":[9007199254741001,9007199254741004]},{"dtype":"dtype('float64')","name":"rent","values":[25.0,0.0]},{"dtype":")>","name":"source_household_id","values":["[[\"int\",\"2024\"],[\"int\",\"101\"]]","[[\"int\",\"2024\"],[\"int\",\"202\"]]"]},{"dtype":")>","name":"donor_support_stratum","values":["us:asec","us:puf_tax_detail"]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1]}}],["family",{"columns":[{"dtype":"dtype('int64')","name":"family_id","values":[9007199254741001,9007199254741004]},{"dtype":"dtype('int64')","name":"family_household_id","values":[101,202]},{"dtype":"dtype('int64')","name":"family_head_person_id","values":[9007199254741001,9007199254741004]},{"dtype":")>","name":"family_source_household_id","values":["[[\"int\",\"2024\"],[\"int\",\"101\"]]","[[\"int\",\"2024\"],[\"int\",\"202\"]]"]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1]}}]],"weights":[["household","design",{"dtype":"dtype('float64')","index":{"dtype":"dtype('int64')","name":null,"values":[0,1]},"name":null,"values":[10.0,30.0]}]]},"kernel":"transport.create@1","receipt":{"content_basis":"transport","country":"xx","design_scale":10.0,"destination_mass":120.0,"donor_country":"us","donor_mass":12.0,"donor_time_period":null,"dropped_columns":{"household":[],"person":[]},"dropped_parent_cycle_edges":0,"facts":{"facts_sha256":"0e969d00a40dbf6e3650a80c5e88ac3b97f3010fd80990f6aedcff6c8fa7a973","manifest_sha256":null,"n_facts":1},"mass_reference":"toy_population","n_households":2,"n_persons":6,"n_units":2,"unit_construction":{"children_with_reference_person":0,"dependent_teen_parents":0,"hours_independent_children":0,"independent_teen_parents":0,"non_partnered_coparent_households":0,"parentless_reference_person_heads":0,"younger_independent_teen_parents":0}}},"scenario":"toy"} \ No newline at end of file diff --git a/packages/microcosm-build/tests/fixtures/transport_create_baseline/toy_profile_columns.json b/packages/microcosm-build/tests/fixtures/transport_create_baseline/toy_profile_columns.json new file mode 100644 index 0000000000..088c7df79f --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/transport_create_baseline/toy_profile_columns.json @@ -0,0 +1 @@ +{"codec":{"links":[],"mass_log":[],"metadata":{"mapping":[["content_basis","transport"],["donor_country","us"],["currency","USD"],["source_person_ids",{"tuple":["0000000000000000000001","0000000000000000000002","0000000000000000000003","0000000000000000000004","0000000000000000000005","0000000000000000000006"]}],["dropped_parent_cycle_edges",0]]},"schema":{"group_entities":["household"],"links":[],"person_entity":"person"},"strata":{"dtype":"dtype('O')","index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5]},"name":"stratum","values":["us:asec","us:asec","us:asec","us:puf_tax_detail","us:puf_tax_detail","us:puf_tax_detail"]},"tables":[["person",{"columns":[{"dtype":"dtype('int64')","name":"person_id","values":[9007199254741001,9007199254741002,9007199254741003,9007199254741004,9007199254741005,9007199254741006]},{"dtype":"dtype('int64')","name":"person_household_id","values":[101,101,101,202,202,202]},{"dtype":"dtype('int64')","name":"age","values":[40,38,10,45,42,12]},{"dtype":"","name":"sex","values":["male","female","male","male","female","female"]},{"dtype":"dtype('float64')","name":"employment_income","values":[0.0,10.0,20.0,30.0,40.0,50.0]},{"dtype":"dtype('float64')","name":"interest_income","values":[3.0,5.0,0.0,7.0,0.0,0.0]},{"dtype":"Int64Dtype()","name":"partner_person_id","values":[9007199254741002,9007199254741001,null,9007199254741005,9007199254741004,null]},{"dtype":"Int64Dtype()","name":"parent_1_person_id","values":[null,null,9007199254741001,null,null,9007199254741005]},{"dtype":"Int64Dtype()","name":"parent_2_person_id","values":[null,null,9007199254741002,null,null,null]},{"dtype":"dtype('float64')","name":"liquid_financial_assets","values":[60.0,0.0,0.0,180.0,0.0,0.0]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5]}}],["household",{"columns":[{"dtype":"dtype('int64')","name":"household_id","values":[101,202]},{"dtype":"Int64Dtype()","name":"reference_person_id","values":[9007199254741001,9007199254741004]},{"dtype":"dtype('float64')","name":"rent","values":[25.0,0.0]},{"dtype":"dtype('float64')","name":"mortgage_interest","values":[12.0,7.0]},{"dtype":")>","name":"source_household_id","values":["[[\"int\",\"2024\"],[\"int\",\"101\"]]","[[\"int\",\"2024\"],[\"int\",\"202\"]]"]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1]}}]],"weights":[["household","design",{"dtype":"dtype('float64')","index":{"dtype":"dtype('int64')","name":null,"values":[0,1]},"name":null,"values":[1.0,3.0]}]]},"create":{"frame":{"links":[],"mass_log":[],"metadata":{"mapping":[["content_basis","transport"],["donor_country","us"],["country","xx"],["donor_currency","USD"],["donor_time_period",2024]]},"schema":{"group_entities":["household","family"],"links":[],"person_entity":"person"},"strata":{"dtype":"dtype('O')","index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5]},"name":"stratum","values":["us:asec","us:asec","us:asec","us:puf_tax_detail","us:puf_tax_detail","us:puf_tax_detail"]},"tables":[["person",{"columns":[{"dtype":"dtype('int64')","name":"person_id","values":[9007199254741001,9007199254741002,9007199254741003,9007199254741004,9007199254741005,9007199254741006]},{"dtype":"dtype('int64')","name":"person_household_id","values":[101,101,101,202,202,202]},{"dtype":"dtype('int64')","name":"age","values":[40,38,10,45,42,12]},{"dtype":")>","name":"sex","values":["male","female","male","male","female","female"]},{"dtype":"dtype('float64')","name":"employment_income","values":[0.0,10.0,20.0,30.0,40.0,50.0]},{"dtype":"dtype('float64')","name":"interest_income","values":[3.0,5.0,0.0,7.0,0.0,0.0]},{"dtype":"Int64Dtype()","name":"partner_person_id","values":[9007199254741002,9007199254741001,null,9007199254741005,9007199254741004,null]},{"dtype":"Int64Dtype()","name":"parent_1_person_id","values":[null,null,9007199254741001,null,null,9007199254741005]},{"dtype":"Int64Dtype()","name":"parent_2_person_id","values":[null,null,9007199254741002,null,null,null]},{"dtype":"dtype('float64')","name":"liquid_financial_assets","values":[60.0,0.0,0.0,180.0,0.0,0.0]},{"dtype":"dtype('int64')","name":"person_family_id","values":[9007199254741001,9007199254741001,9007199254741001,9007199254741004,9007199254741004,9007199254741004]},{"dtype":"dtype('float64')","name":"take_up_seed","values":[0.13479855962228915,0.814136316266239,0.30432980533210985,0.17633266258664693,0.5877081982295528,0.910367081750198]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5]}}],["household",{"columns":[{"dtype":"dtype('int64')","name":"household_id","values":[101,202]},{"dtype":"Int64Dtype()","name":"reference_person_id","values":[9007199254741001,9007199254741004]},{"dtype":"dtype('float64')","name":"rent","values":[25.0,0.0]},{"dtype":"dtype('float64')","name":"mortgage_interest","values":[12.0,7.0]},{"dtype":")>","name":"source_household_id","values":["[[\"int\",\"2024\"],[\"int\",\"101\"]]","[[\"int\",\"2024\"],[\"int\",\"202\"]]"]},{"dtype":")>","name":"donor_support_stratum","values":["us:asec","us:puf_tax_detail"]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1]}}],["family",{"columns":[{"dtype":"dtype('int64')","name":"family_id","values":[9007199254741001,9007199254741004]},{"dtype":"dtype('int64')","name":"family_household_id","values":[101,202]},{"dtype":"dtype('int64')","name":"family_head_person_id","values":[9007199254741001,9007199254741004]},{"dtype":")>","name":"family_source_household_id","values":["[[\"int\",\"2024\"],[\"int\",\"101\"]]","[[\"int\",\"2024\"],[\"int\",\"202\"]]"]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1]}}]],"weights":[["household","design",{"dtype":"dtype('float64')","index":{"dtype":"dtype('int64')","name":null,"values":[0,1]},"name":null,"values":[10.0,30.0]}]]},"kernel":"transport.create@1","receipt":{"content_basis":"transport","country":"xx","design_scale":10.0,"destination_mass":120.0,"donor_country":"us","donor_mass":12.0,"donor_time_period":2024,"dropped_columns":{"household":[],"person":[]},"dropped_parent_cycle_edges":0,"facts":{"facts_sha256":"0e969d00a40dbf6e3650a80c5e88ac3b97f3010fd80990f6aedcff6c8fa7a973","manifest_sha256":null,"n_facts":1},"mass_reference":"toy_population","n_households":2,"n_persons":6,"n_units":2,"unit_construction":{"children_with_reference_person":0,"dependent_teen_parents":0,"hours_independent_children":0,"independent_teen_parents":0,"non_partnered_coparent_households":0,"parentless_reference_person_heads":0,"younger_independent_teen_parents":0}}},"scenario":"toy_profile_columns"} \ No newline at end of file diff --git a/packages/microcosm-build/tests/fixtures/transport_create_baseline/toy_v2.json b/packages/microcosm-build/tests/fixtures/transport_create_baseline/toy_v2.json new file mode 100644 index 0000000000..595edebe68 --- /dev/null +++ b/packages/microcosm-build/tests/fixtures/transport_create_baseline/toy_v2.json @@ -0,0 +1 @@ +{"codec":null,"create":{"frame":{"links":[],"mass_log":[],"metadata":{"mapping":[["content_basis","transport"],["donor_country","us"],["country","xx"],["donor_currency","USD"],["donor_time_period",null]]},"schema":{"group_entities":["household","family"],"links":[],"person_entity":"person"},"strata":{"dtype":"dtype('O')","index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5]},"name":"stratum","values":["us:asec","us:asec","us:asec","us:puf_tax_detail","us:puf_tax_detail","us:puf_tax_detail"]},"tables":[["person",{"columns":[{"dtype":"dtype('int64')","name":"person_id","values":[9007199254741001,9007199254741002,9007199254741003,9007199254741004,9007199254741005,9007199254741006]},{"dtype":"dtype('int64')","name":"person_household_id","values":[101,101,101,202,202,202]},{"dtype":"dtype('int64')","name":"age","values":[40,38,10,45,42,12]},{"dtype":")>","name":"sex","values":["male","female","male","male","female","female"]},{"dtype":"dtype('float64')","name":"employment_income","values":[0.0,10.0,20.0,30.0,40.0,50.0]},{"dtype":"dtype('float64')","name":"interest_income","values":[3.0,5.0,0.0,7.0,0.0,0.0]},{"dtype":"Int64Dtype()","name":"partner_person_id","values":[9007199254741002,9007199254741001,null,9007199254741005,9007199254741004,null]},{"dtype":"Int64Dtype()","name":"parent_1_person_id","values":[null,null,9007199254741001,null,null,9007199254741005]},{"dtype":"Int64Dtype()","name":"parent_2_person_id","values":[null,null,9007199254741002,null,null,null]},{"dtype":"dtype('float64')","name":"liquid_financial_assets","values":[60.0,0.0,0.0,180.0,0.0,0.0]},{"dtype":"dtype('int64')","name":"person_family_id","values":[9007199254741001,9007199254741001,9007199254741001,9007199254741004,9007199254741004,9007199254741004]},{"dtype":"dtype('float64')","name":"take_up_seed","values":[0.13479855962228915,0.814136316266239,0.30432980533210985,0.17633266258664693,0.5877081982295528,0.910367081750198]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1,2,3,4,5]}}],["household",{"columns":[{"dtype":"dtype('int64')","name":"household_id","values":[101,202]},{"dtype":"Int64Dtype()","name":"reference_person_id","values":[9007199254741001,9007199254741004]},{"dtype":"dtype('float64')","name":"rent","values":[25.0,0.0]},{"dtype":")>","name":"source_household_id","values":["[[\"int\",\"2024\"],[\"int\",\"101\"]]","[[\"int\",\"2024\"],[\"int\",\"202\"]]"]},{"dtype":")>","name":"donor_support_stratum","values":["us:asec","us:puf_tax_detail"]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1]}}],["family",{"columns":[{"dtype":"dtype('int64')","name":"family_id","values":[9007199254741001,9007199254741004]},{"dtype":"dtype('int64')","name":"family_household_id","values":[101,202]},{"dtype":"dtype('int64')","name":"family_head_person_id","values":[9007199254741001,9007199254741004]},{"dtype":")>","name":"family_source_household_id","values":["[[\"int\",\"2024\"],[\"int\",\"101\"]]","[[\"int\",\"2024\"],[\"int\",\"202\"]]"]}],"columns_name":null,"index":{"dtype":"dtype('int64')","name":null,"values":[0,1]}}]],"weights":[["household","design",{"dtype":"dtype('float64')","index":{"dtype":"dtype('int64')","name":null,"values":[0,1]},"name":null,"values":[10.0,30.0]}]]},"kernel":"transport.create@2","receipt":{"content_basis":"transport","country":"xx","design_scale":10.0,"destination_mass":120.0,"donor_country":"us","donor_mass":12.0,"donor_time_period":null,"dropped_columns":{"household":[],"person":[]},"dropped_parent_cycle_edges":0,"facts":{"facts_sha256":"0e969d00a40dbf6e3650a80c5e88ac3b97f3010fd80990f6aedcff6c8fa7a973","manifest_sha256":null,"n_facts":1},"mass_reference":"toy_population","n_households":2,"n_persons":6,"n_units":2,"unit_construction":{"children_with_reference_person":0,"dependent_teen_parents":0,"hours_independent_children":0,"independent_teen_parents":0,"non_partnered_coparent_households":0,"parentless_reference_person_heads":0,"younger_independent_teen_parents":0}}},"scenario":"toy_v2"} \ No newline at end of file diff --git a/packages/microcosm-frame/src/microcosm/frame/transport.py b/packages/microcosm-frame/src/microcosm/frame/transport.py index e55fa54746..ebfa013be1 100644 --- a/packages/microcosm-frame/src/microcosm/frame/transport.py +++ b/packages/microcosm-frame/src/microcosm/frame/transport.py @@ -4,6 +4,7 @@ from collections.abc import Mapping, Sequence from dataclasses import dataclass from hashlib import blake2b, file_digest +from hashlib import sha256 as _sha256 from math import fsum from pathlib import Path from types import MappingProxyType @@ -17,9 +18,12 @@ ) from microcosm.frame.concepts import ( HOUSEHOLD_ID_COLUMN, + MARITAL_STATUS_DOMAIN, PERSON_HOUSEHOLD_ID_COLUMN, PERSON_ID_COLUMN, + RENTED_TENURES, SOURCE_HOUSEHOLD_ID_COLUMN, + TENURE_DOMAIN, ContentBasis, Unit, concept_for_column, @@ -29,9 +33,13 @@ from microcosm.frame.scaling import apply_scale __all__ = [ + "DONOR_PROFILE_CHOICES", + "DONOR_PROFILE_FORMAT", "DonorBank", + "DonorProfile", "currency_bridge", "derive_transport_seed", + "parse_donor_profile", "quantile_map", "read_populace_us_donor", ] @@ -474,6 +482,8 @@ class DonorBank: merges clones across support channels and distinguishes source vintages. ``time_period`` is the donor file's recorded model ``_time_period`` year, or ``None`` when absent. It does not authenticate the amounts' money basis. + ``donor_profile`` records what a :class:`DonorProfile` staged, or is + ``None`` when the caller named no profile. """ tables: Mapping[str, pd.DataFrame] @@ -485,6 +495,7 @@ class DonorBank: currency: str = "USD" dropped_parent_cycle_edges: int = 0 time_period: int | None = None + donor_profile: Mapping[str, object] | None = None #: Line numbers and pointers are validated as float64 (pointer columns can hold @@ -728,6 +739,613 @@ def pointer(present: np.ndarray, rows: np.ndarray) -> pd.arrays.IntegerArray: } +# --- Donor-decoding profiles ------------------------------------------------- +# +# The concept mapping cannot invert the donor's tenure, marital status or +# enrollment inputs, so the reader decodes none of them. A donor profile, +# named for a donor family, stages them from the donor's raw survey answers +# between the authenticated read and validation. A graph selects one through +# a profile document; without one the reader is unchanged. + +#: The profile document's format tag. +DONOR_PROFILE_FORMAT = "microcosm.donor-profile/1" + +#: Every declared profile, by name and version, with each choice field it +#: declares and that field's closed value set. These are the only values a +#: profile document may carry; a new value is a new shared release. +#: +#: ``populace-us-cps-asec`` version 1 reads a populace-us donor's CPS ASEC +#: answers: +#: +#: - ``assisted_renter_tenure``: the tenure of a renting household any of +#: whose SPM units receives housing assistance. The donor has no landlord +#: signal, so ``rented_public_authority`` is a recorded stand-in for a +#: public landlord; ``rented_private`` treats assisted renters like the rest. +#: - ``blank_full_time_study``: what a blank ``A_ENRLW`` or ``A_FTPT`` answer +#: means. ``refuse`` refuses the donor; ``read_false`` reads the person as +#: not studying full time and counts the blanks by source year. The +#: document's ``donor_sha256`` ties the choice to the one donor it names. +#: - ``housing_cost_contradicting_tenure``: rent outside the rented tenures, +#: or mortgage interest or principal outside ``owned_with_mortgage``. +#: ``tenure_wins`` sets the amount to zero and records the counts and +#: amounts; ``refuse`` refuses the donor with the counts. +DONOR_PROFILE_CHOICES: Mapping[tuple[str, int], Mapping[str, tuple[str, ...]]] = ( + MappingProxyType( + { + ("populace-us-cps-asec", 1): MappingProxyType( + { + "assisted_renter_tenure": ( + "rented_public_authority", + "rented_private", + ), + "blank_full_time_study": ("refuse", "read_false"), + "housing_cost_contradicting_tenure": ("tenure_wins", "refuse"), + } + ), + } + ) +) + +_DONOR_PROFILE_FIELDS = frozenset( + {"format", "profile", "version", "donor_sha256", "choices"} +) + + +def _is_sha256(value: object) -> bool: + return ( + isinstance(value, str) + and len(value) == 64 + and all(c in "0123456789abcdef" for c in value) + ) + + +@dataclass(frozen=True) +class DonorProfile: + """A validated donor-decoding profile document. + + Build one with :func:`parse_donor_profile`. ``choices`` maps each choice + field the profile declares in :data:`DONOR_PROFILE_CHOICES` to one of its + values. ``canonical_text`` is the document's canonical JSON spelling and + ``sha256`` its SHA-256. + """ + + name: str + version: int + donor_sha256: str + choices: Mapping[str, str] + + def __post_init__(self) -> None: + if not isinstance(self.name, str) or type(self.version) is not int: + raise ValueError("A donor profile names a string profile and int version.") + declared = DONOR_PROFILE_CHOICES.get((self.name, self.version)) + if declared is None: + raise ValueError( + f"Unknown donor profile {self.name!r} version {self.version!r}; " + f"declared: {sorted(DONOR_PROFILE_CHOICES)}." + ) + if not _is_sha256(self.donor_sha256): + raise ValueError( + "A donor profile's donor_sha256 must be 64 lowercase hexadecimal " + "characters." + ) + if not isinstance(self.choices, Mapping): + raise ValueError("A donor profile's choices must be an object.") + unknown = sorted(set(self.choices) - set(declared)) + if unknown: + raise ValueError( + f"Donor profile {self.name!r} version {self.version} declares no " + f"choice field(s) {unknown}." + ) + missing = sorted(set(declared) - set(self.choices)) + if missing: + raise ValueError( + f"Donor profile {self.name!r} version {self.version} requires " + f"choice field(s) {missing}." + ) + for field, value in self.choices.items(): + if not isinstance(value, str) or value not in declared[field]: + raise ValueError( + f"Donor profile choice {field!r} must be one of " + f"{list(declared[field])}, not {value!r}." + ) + object.__setattr__( + self, "choices", MappingProxyType(dict(sorted(self.choices.items()))) + ) + + @property + def canonical_text(self) -> str: + """The document's canonical JSON: sorted keys, no whitespace.""" + return json.dumps( + { + "choices": dict(self.choices), + "donor_sha256": self.donor_sha256, + "format": DONOR_PROFILE_FORMAT, + "profile": self.name, + "version": self.version, + }, + ensure_ascii=False, + allow_nan=False, + sort_keys=True, + separators=(",", ":"), + ) + + @property + def sha256(self) -> str: + """SHA-256 of :attr:`canonical_text`, the text a graph param carries.""" + return _sha256(self.canonical_text.encode("utf-8")).hexdigest() + + +def _unique_object(pairs: list[tuple[str, object]]) -> dict[str, object]: + keys = [key for key, _ in pairs] + if len(set(keys)) != len(keys): + raise ValueError("A donor profile document repeats a key.") + return dict(pairs) + + +def _refuse_constant(token: str) -> object: + raise ValueError(f"A donor profile document cannot hold {token}.") + + +def parse_donor_profile(text: str) -> DonorProfile: + """Parse and validate a donor profile document, given as canonical JSON. + + The document is an object with exactly ``format`` (equal to + :data:`DONOR_PROFILE_FORMAT`), ``profile``, ``version``, ``donor_sha256`` + and ``choices``. An unknown format, profile, version, field, choice field + or value refuses, as does a missing field. The text must be the + document's canonical spelling, the one composition hands CREATE, so one + document has one spelling, one node key and one SHA-256. + """ + if not isinstance(text, str): + raise TypeError("A donor profile document must be JSON text.") + try: + document = json.loads( + text, object_pairs_hook=_unique_object, parse_constant=_refuse_constant + ) + except json.JSONDecodeError as error: + raise ValueError(f"A donor profile document is not JSON: {error}.") from error + if not isinstance(document, dict): + raise ValueError("A donor profile document must be a JSON object.") + unknown = sorted(set(document) - _DONOR_PROFILE_FIELDS) + if unknown: + raise ValueError(f"A donor profile document has unknown field(s) {unknown}.") + missing = sorted(_DONOR_PROFILE_FIELDS - set(document)) + if missing: + raise ValueError(f"A donor profile document lacks field(s) {missing}.") + if document["format"] != DONOR_PROFILE_FORMAT: + raise ValueError( + f"Unknown donor profile format {document['format']!r}; expected " + f"{DONOR_PROFILE_FORMAT!r}." + ) + profile = DonorProfile( + name=document["profile"], + version=document["version"], + donor_sha256=document["donor_sha256"], + choices=document["choices"], + ) + if text != profile.canonical_text: + raise ValueError( + "A donor profile document must be canonical JSON (sorted keys, no " + "whitespace), so equal documents give equal node keys." + ) + return profile + + +#: The household ``tenure_type`` labels the populace-us exporter writes, each +#: with the CPS ASEC ``H_TENURE`` answer it carries: 1 owned or being bought +#: (the exporter labels every owner ``OWNED_WITH_MORTGAGE``), 2 rented, 3 +#: occupied without payment of rent. Any other label refuses. +_HOUSEHOLD_TENURE_CODES = MappingProxyType( + {"OWNED_WITH_MORTGAGE": 1, "RENTED": 2, "NONE": 3} +) +_OWNER, _RENTER, _RENT_FREE = 1, 2, 3 +#: The SPM unit tenure labels; the two owner labels give the mortgage status. +_SPM_TENURES = frozenset({"OWNER_WITH_MORTGAGE", "OWNER_WITHOUT_MORTGAGE", "RENTER"}) +_SPM_OWNER_TENURE = MappingProxyType( + { + "OWNER_WITH_MORTGAGE": "owned_with_mortgage", + "OWNER_WITHOUT_MORTGAGE": "owned_outright", + } +) +#: CPS ASEC ``A_MARITL`` codes as this profile reads them: 1, 2 and 3 are the +#: married categories (read as ``married`` without distinguishing them), 4 +#: widowed, 5 divorced, 6 separated and 7 never married. Any other code +#: refuses. The US build's own recodes read 4 as a surviving spouse and 6 as +#: separated. +_A_MARITL = MappingProxyType( + { + 1: "married", + 2: "married", + 3: "married", + 4: "widowed", + 5: "divorced", + 6: "separated", + 7: "never_married", + } +) +#: CPS ASEC ``A_ENRLW`` (enrolled last week) and ``A_FTPT`` (full or part +#: time): 0 not in universe, 1 yes or full time, 2 no or part time. +_ENROLLMENT_CODES = frozenset({0, 1, 2}) +#: The raw columns the profile reads, by donor table. +_PROFILE_COLUMNS = MappingProxyType( + { + "person": ("person_spm_unit_id", "A_MARITL", "A_ENRLW", "A_FTPT"), + "household": ("tenure_type", "H_TENURE"), + "spm_unit": ( + "spm_unit_id", + "spm_unit_tenure_type", + "receives_housing_assistance", + ), + } +) +#: The concepts the profile writes, by concept table. +_PROFILE_CONCEPTS = MappingProxyType( + { + "person": ("legal_marital_status", "enrolled_full_time"), + "household": ("tenure",), + } +) +#: The housing costs reconciled with tenure, with the tenures that may pay +#: each one. +_TENURE_COSTS = ( + ("rent", RENTED_TENURES), + ("mortgage_interest", ("owned_with_mortgage",)), + ("mortgage_principal", ("owned_with_mortgage",)), +) + + +def _profile_codes( + values: pd.Series, allowed: frozenset[int], *, missing_ok: bool = False +) -> tuple[np.ndarray, np.ndarray]: + """Whole-number survey codes, checked before any comparison reads them. + + Returns the codes, with -1 where blank, and the blank mask. A blank + refuses unless ``missing_ok``; every other value must be a finite whole + number in ``allowed``. + """ + if pd.api.types.is_bool_dtype(values.dtype) or not pd.api.types.is_numeric_dtype( + values.dtype + ): + raise ValueError(f"Donor {values.name} must hold numeric survey codes.") + numbers = values.to_numpy(dtype=np.float64, na_value=np.nan) + blank = np.isnan(numbers) + if blank.any() and not missing_ok: + raise ValueError( + f"Donor {values.name} has {int(blank.sum())} blank values, which this " + "donor profile refuses." + ) + present = numbers[~blank] + if ( + not np.isfinite(present).all() + or np.any(present != np.floor(present)) + or not np.isin(present, sorted(allowed)).all() + ): + raise ValueError(f"Donor {values.name} holds codes outside {sorted(allowed)}.") + codes = np.full(len(numbers), -1, dtype=np.int64) + codes[~blank] = present.astype(np.int64) + return codes, blank + + +def _profile_labels(values: pd.Series, allowed) -> np.ndarray: + """Survey labels as an object array; a blank or unknown label refuses.""" + labels = values.to_numpy(dtype=object, na_value=None) + unknown = { + repr(value) + for value in labels.tolist() + if not isinstance(value, str) or value not in allowed + } + if unknown: + raise ValueError( + f"Donor {values.name} holds labels outside {sorted(allowed)}: " + f"{sorted(unknown)[:5]}." + ) + return labels + + +def _profile_ids(values: pd.Series) -> np.ndarray: + """Non-null integer ids as int64, never through floats.""" + if values.dtype.kind not in "iu" or values.isna().any(): + raise ValueError(f"Donor {values.name} must hold non-null integer ids.") + if (values > np.iinfo(np.int64).max).any(): + raise ValueError(f"Donor {values.name} must fit int64.") + return values.to_numpy(dtype=np.int64) + + +def _by_source_year(person: pd.DataFrame, mask: np.ndarray) -> dict[str, int]: + """Counts of ``mask`` for each donor source year, zeros included.""" + if "source_year" not in person: + return {"unrecorded": int(mask.sum())} + counts = ( + pd.Series(mask.astype(np.int64)) + .groupby(person["source_year"].to_numpy(), dropna=False, sort=True) + .sum() + ) + return {str(year): int(count) for year, count in counts.items()} + + +def _donor_spm_unit(store: pd.HDFStore, profile: DonorProfile) -> pd.DataFrame: + if "/spm_unit" not in store.keys(): + raise ValueError( + f"Donor profile {profile.name!r} needs the donor's spm_unit table." + ) + return read_frame_table(store, "spm_unit") + + +def _stage_donor_profile( + profile: DonorProfile, + person: pd.DataFrame, + household: pd.DataFrame, + spm_unit: pd.DataFrame, +) -> dict: + """Stage a profile's concepts from the raw donor tables, keyed by raw id. + + Every raw label, code and id is checked before any comparison reads it, + and every SPM join is checked before any household takes a tenure. A + household the joins cannot reach refuses; it never falls through to a + default tenure. + """ + raw = {"person": person, "household": household, "spm_unit": spm_unit} + absent = sorted( + f"{table}.{column}" + for table, columns in _PROFILE_COLUMNS.items() + for column in columns + if column not in raw[table] + ) + if absent: + raise ValueError( + f"Donor profile {profile.name!r} needs donor columns {absent}." + ) + choices = profile.choices + # Raw labels, codes and ids first. + tenure_type = _profile_labels(household["tenure_type"], _HOUSEHOLD_TENURE_CODES) + h_tenure, _ = _profile_codes( + household["H_TENURE"], frozenset(_HOUSEHOLD_TENURE_CODES.values()) + ) + spm_tenure = _profile_labels(spm_unit["spm_unit_tenure_type"], _SPM_TENURES) + assistance = spm_unit["receives_housing_assistance"] + if not pd.api.types.is_bool_dtype(assistance.dtype) or assistance.isna().any(): + raise ValueError( + "Donor receives_housing_assistance must be boolean with no nulls." + ) + assisted_unit = assistance.to_numpy(dtype=bool) + marital, _ = _profile_codes(person["A_MARITL"], frozenset(_A_MARITL)) + read_false = choices["blank_full_time_study"] == "read_false" + enrolled, enrolled_blank = _profile_codes( + person["A_ENRLW"], _ENROLLMENT_CODES, missing_ok=True + ) + full_time, full_time_blank = _profile_codes( + person["A_FTPT"], _ENROLLMENT_CODES, missing_ok=True + ) + blank = enrolled_blank | full_time_blank + if blank.any() and not read_false: + raise ValueError( + "Donor A_ENRLW or A_FTPT is blank for persons by source year " + f"{_by_source_year(person, blank)}, which this donor profile refuses." + ) + unit_ids = pd.Index(_profile_ids(spm_unit["spm_unit_id"])) + member_ids = _profile_ids(person["person_spm_unit_id"]) + person_ids = _profile_ids(person[PERSON_ID_COLUMN]) + household_ids = _profile_ids(household[HOUSEHOLD_ID_COLUMN]) + # The two tenure answers must agree before either decides anything. + code_of_label = np.asarray( + [_HOUSEHOLD_TENURE_CODES[label] for label in tenure_type.tolist()], + dtype=np.int64, + ) + disagree = h_tenure != code_of_label + if disagree.any(): + raise ValueError( + f"Donor tenure_type disagrees with H_TENURE in {int(disagree.sum())} " + "households." + ) + # Checked SPM joins. + if not unit_ids.is_unique: + raise ValueError("Donor SPM unit ids must be unique.") + unit_of_person = unit_ids.get_indexer(member_ids) + if np.any(unit_of_person < 0): + raise ValueError( + f"{int((unit_of_person < 0).sum())} donor persons belong to no known " + "SPM unit." + ) + households = pd.Index(household_ids) + household_of_person = households.get_indexer( + _profile_ids(person[PERSON_HOUSEHOLD_ID_COLUMN]) + ) + if np.any(household_of_person < 0): + raise ValueError("Every donor person must belong to a known household.") + pairs = pd.DataFrame( + {"unit": unit_of_person, "household": household_of_person} + ).drop_duplicates() + spanning = pairs["unit"].duplicated() + if spanning.any(): + raise ValueError( + f"{int(pairs.loc[spanning, 'unit'].nunique())} donor SPM units span " + "more than one household." + ) + unit_household = np.full(len(unit_ids), -1, dtype=np.int64) + unit_household[pairs["unit"].to_numpy()] = pairs["household"].to_numpy() + # A unit with no member reaches no household and stages nothing; it is + # counted, not refused. + reached = unit_household >= 0 + by_household = pd.DataFrame( + { + "household": unit_household[reached], + "tenure": spm_tenure[reached], + "assisted": assisted_unit[reached], + } + ).groupby("household") + split = by_household["tenure"].nunique() > 1 + if split.any(): + raise ValueError( + f"{int(split.sum())} donor households have SPM units that disagree " + "on tenure." + ) + rows = np.arange(len(households)) + spm_household = by_household["tenure"].first().reindex(rows) + assisted_household = by_household["assisted"].any().reindex(rows) + if spm_household.isna().any() or assisted_household.isna().any(): + raise ValueError( + f"{int(spm_household.isna().sum())} donor households have no SPM unit." + ) + spm_household = spm_household.to_numpy(dtype=object) + assisted = assisted_household.to_numpy(dtype=bool) + owner, renter, rent_free = ( + h_tenure == code for code in (_OWNER, _RENTER, _RENT_FREE) + ) + unknown_mortgage = owner & (spm_household == "RENTER") + if unknown_mortgage.any(): + raise ValueError( + f"{int(unknown_mortgage.sum())} donor owner households have SPM renter " + "tenure, so their mortgage status is unknown." + ) + tenure = np.full(len(households), None, dtype=object) + tenure[rent_free] = "rent_free" + tenure[renter & assisted] = choices["assisted_renter_tenure"] + tenure[renter & ~assisted] = "rented_private" + for label, value in _SPM_OWNER_TENURE.items(): + tenure[owner & (spm_household == label)] = value + if any(value is None for value in tenure.tolist()): + raise ValueError("Donor profile left a household without a tenure.") + statuses = np.asarray([_A_MARITL[code] for code in marital.tolist()], dtype=object) + return { + "profile": profile, + "household_ids": household_ids, + "person_ids": person_ids, + "tenure": tenure, + "legal_marital_status": statuses, + "enrolled_full_time": (enrolled == 1) & (full_time == 1), + "record": { + "household_tenure_type": { + label: int((code_of_label == code).sum()) + for label, code in _HOUSEHOLD_TENURE_CODES.items() + }, + "spm_units": { + "units": len(unit_ids), + "units_without_members": int((~reached).sum()), + "assistance_rule": "any_spm_unit_in_household", + "households_with_mixed_assistance": int( + (by_household["assisted"].nunique() > 1).sum() + ), + "assisted_renter_households": int((renter & assisted).sum()), + "assisted_other_households": int((~renter & assisted).sum()), + "rent_free_households_with_spm_owner_tenure": int( + (rent_free & (spm_household != "RENTER")).sum() + ), + "renter_households_with_spm_owner_tenure": int( + (renter & (spm_household != "RENTER")).sum() + ), + }, + "full_time_study": { + "enrolled_full_time": int(((enrolled == 1) & (full_time == 1)).sum()), + "blank_a_enrlw_by_source_year": _by_source_year(person, enrolled_blank), + "blank_a_ftpt_by_source_year": _by_source_year(person, full_time_blank), + "read_false_by_source_year": _by_source_year(person, blank), + }, + "legal_marital_status": { + value: int((statuses == value).sum()) for value in MARITAL_STATUS_DOMAIN + }, + }, + } + + +def _aligned_rows( + raw_ids: np.ndarray, decoded_ids: pd.Series, entity: str +) -> np.ndarray: + """Each decoded row's position among the raw rows, refusing any mismatch.""" + rows = pd.Index(raw_ids).get_indexer(decoded_ids.to_numpy(dtype=np.int64)) + if len(rows) != len(raw_ids) or np.any(rows < 0): + raise ValueError( + f"Decoded {entity} rows do not match the donor's {entity} rows." + ) + return rows + + +def _attach_donor_profile( + staged: dict, tables: Mapping[str, pd.DataFrame], weights: np.ndarray +) -> dict: + """Write the staged concepts, reconcile housing costs, and return the record. + + ``weights`` are the donor design weights in raw household order. The + record's amounts are donor currency; weighted figures use those weights. + """ + profile: DonorProfile = staged["profile"] + present = sorted( + f"{entity}.{column}" + for entity, columns in _PROFILE_CONCEPTS.items() + for column in columns + if column in tables[entity] + ) + if present: + raise ValueError( + f"Donor profile {profile.name!r} would overwrite decoded concepts " + f"{present}." + ) + household_table = tables["household"] + person_table = tables["person"] + household_rows = _aligned_rows( + staged["household_ids"], household_table[HOUSEHOLD_ID_COLUMN], "household" + ) + person_rows = _aligned_rows( + staged["person_ids"], person_table[PERSON_ID_COLUMN], "person" + ) + tenure = staged["tenure"][household_rows] + household_weights = np.asarray(weights, dtype=np.float64)[household_rows] + refuse = profile.choices["housing_cost_contradicting_tenure"] == "refuse" + reconciliation: dict[str, dict] = {} + contradicted: dict[str, int] = {} + reconciled: dict[str, np.ndarray] = {} + for column, payers in _TENURE_COSTS: + if column not in household_table: + reconciliation[column] = {"column": "absent"} + continue + amounts = household_table[column].to_numpy(dtype=np.float64, copy=True) + if not np.isfinite(amounts).all(): + raise ValueError(f"Donor {column} must be finite before reconciliation.") + contradicting = ~np.isin(tenure, payers) & (amounts != 0) + count = int(contradicting.sum()) + reconciliation[column] = { + "column": "present", + "contradicting_households": count, + "contradicting_amount": fsum(amounts[contradicting].tolist()), + "contradicting_weighted_amount": fsum( + (amounts * household_weights)[contradicting].tolist() + ), + "total_amount": fsum(amounts.tolist()), + "weighted_total_amount": fsum((amounts * household_weights).tolist()), + "zeroed": bool(count) and not refuse, + } + if count: + contradicted[column] = count + amounts[contradicting] = 0.0 + reconciled[column] = amounts + if contradicted and refuse: + raise ValueError( + f"Donor housing costs contradict the staged tenure in households " + f"{contradicted}, which this donor profile refuses." + ) + for column, amounts in reconciled.items(): + household_table[column] = amounts + # Object arrays of labels, as decode writes its text concepts. + household_table["tenure"] = tenure + person_table["legal_marital_status"] = staged["legal_marital_status"][person_rows] + person_table["enrolled_full_time"] = staged["enrolled_full_time"][person_rows] + return { + "profile": profile.name, + "version": profile.version, + "document_sha256": profile.sha256, + "donor_sha256": profile.donor_sha256, + "choices": dict(profile.choices), + "tenure": { + value: { + "households": int((tenure == value).sum()), + "weight": fsum(household_weights[tenure == value].tolist()), + } + for value in TENURE_DOMAIN + }, + **staged["record"], + "reconciliation": reconciliation, + } + + def _drop_two_person_parent_cycles(person: pd.DataFrame) -> int: """Repair reciprocal parent edges only after other concepts validate. @@ -801,7 +1419,13 @@ def _donor_time_period(store: pd.HDFStore) -> int | None: return int(value) -def read_populace_us_donor(path: str | Path, *, sha256: str, size: int) -> DonorBank: +def read_populace_us_donor( + path: str | Path, + *, + sha256: str, + size: int, + profile: DonorProfile | None = None, +) -> DonorBank: """Authenticate a local donor H5, then decode its person/household inputs. Size and SHA-256 are mandatory and verified before any HDF parsing. The @@ -843,6 +1467,15 @@ def read_populace_us_donor(path: str | Path, *, sha256: str, size: int) -> Donor US donor and unchanged source-currency amounts and design weights. The exporter's ``_time_period`` (a one-row integer series) is returned as ``time_period``; a file without it reads as ``None``. + + ``profile``, a :class:`DonorProfile` from :func:`parse_donor_profile`, + must name this donor's ``sha256``; any other refuses before the file is + opened. Only then does the reader also read the donor's ``spm_unit`` + table, stage the profile's concepts from the raw survey answers, and + reconcile housing costs with tenure before validation, which it never + relaxes. The bank's ``donor_profile`` records the choices and counts. + Without a profile, the reader reads and returns exactly what it did + before profiles existed. """ path = Path(path) if isinstance(size, bool) or not isinstance(size, int) or size < 0: @@ -853,6 +1486,14 @@ def read_populace_us_donor(path: str | Path, *, sha256: str, size: int) -> Donor or any(c not in "0123456789abcdef" for c in sha256) ): raise ValueError("Donor SHA-256 must be 64 lowercase hexadecimal characters.") + if profile is not None: + if not isinstance(profile, DonorProfile): + raise TypeError("A donor profile must be a parsed DonorProfile.") + if profile.donor_sha256 != sha256: + raise ValueError( + f"Donor profile {profile.name!r} version {profile.version} names " + "donor bytes other than this donor's SHA-256." + ) with path.open("rb") as source: if path.stat().st_size != size: raise ValueError("Donor size mismatch.") @@ -864,15 +1505,26 @@ def read_populace_us_donor(path: str | Path, *, sha256: str, size: int) -> Donor for entity in ("person", "household") } time_period = _donor_time_period(store) + spm_unit = None if profile is None else _donor_spm_unit(store, profile) staged = _donor_extras(raw["person"], raw["household"]) + profiled = ( + None + if profile is None + else _stage_donor_profile(profile, raw["person"], raw["household"], spm_unit) + ) tables = POLICYENGINE_US_CONCEPT_MAPPING.decode(raw) - del raw + del raw, spm_unit for name, values in staged["pointers"].items(): tables["person"][name] = values tables["person"]["liquid_financial_assets"] = staged["liquid_financial_assets"] tables["household"]["reference_person_id"] = staged["reference_person_id"] if staged["source_household_ids"] is not None: tables["household"][SOURCE_HOUSEHOLD_ID_COLUMN] = staged["source_household_ids"] + record = ( + None + if profiled is None + else _attach_donor_profile(profiled, tables, staged["weights"]) + ) violations = validate_concept_tables(tables) dropped = 0 if violations and all(v.code == "parent_cycle" for v in violations): @@ -889,6 +1541,7 @@ def read_populace_us_donor(path: str | Path, *, sha256: str, size: int) -> Donor staged["source_person_ids"], dropped_parent_cycle_edges=dropped, time_period=time_period, + donor_profile=record, ) diff --git a/packages/microcosm-frame/tests/engine_free/shared/test_transport_donor_profile.py b/packages/microcosm-frame/tests/engine_free/shared/test_transport_donor_profile.py new file mode 100644 index 0000000000..62a548e475 --- /dev/null +++ b/packages/microcosm-frame/tests/engine_free/shared/test_transport_donor_profile.py @@ -0,0 +1,1342 @@ +"""Donor-decoding profiles: the closed document and the reader's staging. + +A synthetic donor carries the raw survey answers a profile reads. Without a +profile the reader reads exactly what it did before; with one it stages +tenure, marital status and full-time study, reconciles housing costs with +tenure, and records what it did. The property tests drive the staging +against an independent oracle. No test opens a real donor. +""" + +import ast +import itertools +import json +import re +from hashlib import sha256 +from math import fsum +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest +from hypothesis import HealthCheck, given, settings +from hypothesis import strategies as st + +import microcosm.frame.transport as transport_module +from microcosm.frame.concepts import ( + MARITAL_STATUS_DOMAIN, + RENTED_TENURES, + TENURE_DOMAIN, + validate_concept_tables, +) +from microcosm.frame.transport import ( + DONOR_PROFILE_CHOICES, + DONOR_PROFILE_FORMAT, + DonorProfile, + parse_donor_profile, + read_populace_us_donor, +) +from test_support.paths import paths_for + +FIXTURE = paths_for("microcosm-frame").tests / "fixtures/transport/synthetic_donor.json" +PROPERTY = settings( + max_examples=60, + deadline=None, + database=None, + suppress_health_check=[HealthCheck.too_slow], +) +NAME, VERSION = "populace-us-cps-asec", 1 +OFFERED = { + "assisted_renter_tenure": ("rented_public_authority", "rented_private"), + "blank_full_time_study": ("refuse", "read_false"), + "housing_cost_contradicting_tenure": ("tenure_wins", "refuse"), +} +CHOICES = { + "assisted_renter_tenure": "rented_public_authority", + "blank_full_time_study": "read_false", + "housing_cost_contradicting_tenure": "tenure_wins", +} +STAGED = { + "person": ("legal_marital_status", "enrolled_full_time"), + "household": ("tenure",), +} +#: The codes the oracle reads, written out independently of the module. The +#: official 2025 CPS ASEC data dictionary, printed page 6C-3 +#: (https://www2.census.gov/programs-surveys/cps/datasets/2025/march/asec2025_ddl_pub_full.pdf), +#: maps codes 1 to 3 to married, 4 widowed, 5 divorced, 6 separated and 7 +#: never married. +A_MARITL = { + 1: "married", + 2: "married", + 3: "married", + 4: "widowed", + 5: "divorced", + 6: "separated", + 7: "never_married", +} + + +def _canonical(document: dict) -> str: + return json.dumps( + document, ensure_ascii=False, sort_keys=True, separators=(",", ":") + ) + + +def _document(donor_sha256: str, **choices) -> dict: + return { + "format": DONOR_PROFILE_FORMAT, + "profile": NAME, + "version": VERSION, + "donor_sha256": donor_sha256, + "choices": {**CHOICES, **choices}, + } + + +def _profile(donor_sha256: str, **choices) -> DonorProfile: + return parse_donor_profile(_canonical(_document(donor_sha256, **choices))) + + +def _raw_tables() -> dict[str, pd.DataFrame]: + """The synthetic donor plus the raw columns a profile reads. + + Household 101 owns with a mortgage and carries rent; household 202 rents, + with one assisted and one unassisted SPM unit, and carries mortgage + interest. Person 4 (source year 2024) has blank enrollment answers. + """ + document = json.loads(FIXTURE.read_text()) + tables = {name: pd.DataFrame(rows) for name, rows in document["tables"].items()} + person = tables["person"] + person["home_mortgage_interest"] = [12.0, 0.0, 0.0, 7.0, 0.0, 0.0] + person["person_spm_unit_id"] = [11, 11, 11, 21, 22, 22] + person["A_MARITL"] = [1, 1, 7, 1, 1, 7] + person["A_ENRLW"] = [2.0, 1.0, 1.0, np.nan, 0.0, 1.0] + person["A_FTPT"] = [0.0, 1.0, 1.0, np.nan, 0.0, 2.0] + household = tables["household"] + household["tenure_type"] = ["OWNED_WITH_MORTGAGE", "RENTED"] + household["H_TENURE"] = [1, 2] + tables["spm_unit"] = pd.DataFrame( + { + "spm_unit_id": [11, 21, 22], + "spm_unit_tenure_type": ["OWNER_WITH_MORTGAGE", "RENTER", "RENTER"], + "receives_housing_assistance": [False, False, True], + } + ) + return tables + + +def _write(path: Path, tables: dict[str, pd.DataFrame]) -> dict: + with pd.HDFStore(path, mode="w") as store: + for name, table in tables.items(): + store.put(name, table, format="table") + return { + "sha256": sha256(path.read_bytes()).hexdigest(), + "size": path.stat().st_size, + } + + +def _read(tmp_path, tables=None, **choices): + path = tmp_path / "donor.h5" + pin = _write(path, _raw_tables() if tables is None else tables) + return read_populace_us_donor( + path, **pin, profile=_profile(pin["sha256"], **choices) + ) + + +# --- The document ----------------------------------------------------------- + + +def test_the_value_sets_live_in_one_place_and_name_the_donor_family(): + assert DONOR_PROFILE_FORMAT == "microcosm.donor-profile/1" + assert {key: dict(value) for key, value in DONOR_PROFILE_CHOICES.items()} == { + (NAME, VERSION): OFFERED + } + # Every tenure a choice can write is a schema tenure. + assert set(OFFERED["assisted_renter_tenure"]) <= set(TENURE_DOMAIN) + + +def test_the_document_parses_once_into_its_canonical_text_and_digest(): + text = _canonical(_document("a" * 64)) + profile = parse_donor_profile(text) + assert (profile.name, profile.version, profile.donor_sha256) == ( + NAME, + VERSION, + "a" * 64, + ) + assert dict(profile.choices) == CHOICES + assert profile.canonical_text == text + assert profile.sha256 == sha256(text.encode("utf-8")).hexdigest() + assert parse_donor_profile(text) == profile + # The document carries no target_references key, which composition trims. + assert "target_references" not in json.loads(text) + + +@pytest.mark.parametrize( + "values", list(itertools.product(*OFFERED.values())), ids=lambda v: "-".join(v) +) +def test_every_offered_choice_value_parses(values): + choices = dict(zip(OFFERED, values, strict=True)) + profile = _profile("b" * 64, **choices) + assert dict(profile.choices) == choices + + +def _without(document, *path): + document = json.loads(json.dumps(document)) + target = document + for key in path[:-1]: + target = target[key] + del target[path[-1]] + return document + + +def _with(document, value, *path): + document = json.loads(json.dumps(document)) + target = document + for key in path[:-1]: + target = target[key] + target[path[-1]] = value + return document + + +BASE = _document("c" * 64) + + +@pytest.mark.parametrize( + ("document", "message"), + [ + ([BASE], "must be a JSON object"), + ("text", "must be a JSON object"), + (_with(BASE, "x", "target_references"), r"unknown field\(s\) \['target_"), + (_with(BASE, "nz", "country"), r"unknown field\(s\) \['country'\]"), + (_with(BASE, "d" * 64, "donor_profile_sha256"), "unknown field"), + (_without(BASE, "format"), r"lacks field\(s\) \['format'\]"), + (_without(BASE, "profile"), r"lacks field\(s\) \['profile'\]"), + (_without(BASE, "version"), r"lacks field\(s\) \['version'\]"), + (_without(BASE, "donor_sha256"), r"lacks field\(s\) \['donor_sha256'\]"), + (_without(BASE, "choices"), r"lacks field\(s\) \['choices'\]"), + ( + _with(BASE, "microcosm.donor-profile/2", "format"), + "Unknown donor profile format", + ), + (_with(BASE, "populace-us", "profile"), "Unknown donor profile"), + (_with(BASE, 2, "version"), "Unknown donor profile"), + (_with(BASE, "1", "version"), "int version"), + (_with(BASE, True, "version"), "int version"), + (_with(BASE, 1.0, "version"), "int version"), + (_with(BASE, "C" * 64, "donor_sha256"), "64 lowercase hexadecimal"), + (_with(BASE, "c" * 63, "donor_sha256"), "64 lowercase hexadecimal"), + (_with(BASE, None, "donor_sha256"), "64 lowercase hexadecimal"), + (_with(BASE, [], "choices"), "choices must be an object"), + (_with(BASE, "x", "choices", "rent_rule"), r"declares no choice field\(s\)"), + ( + _without(BASE, "choices", "blank_full_time_study"), + r"requires choice field\(s\) \['blank_full_time_study'\]", + ), + ( + _with(BASE, "rented_nonprofit_social", "choices", "assisted_renter_tenure"), + "must be one of", + ), + (_with(BASE, "impute", "choices", "blank_full_time_study"), "must be one of"), + (_with(BASE, "keep", "choices", "housing_cost_contradicting_tenure"), "one of"), + (_with(BASE, 1, "choices", "blank_full_time_study"), "must be one of"), + ], +) +def test_an_unknown_or_missing_part_of_the_document_refuses(document, message): + with pytest.raises(ValueError, match=message): + parse_donor_profile(_canonical(document)) + + +@pytest.mark.parametrize( + "text", + [ + json.dumps(BASE, sort_keys=True), + json.dumps(BASE, separators=(",", ":")), + _canonical(BASE) + "\n", + _canonical(BASE).replace('"profile"', '"\\u0070rofile"'), + ], +) +def test_a_non_canonical_spelling_refuses(text): + assert json.loads(text) == BASE + with pytest.raises(ValueError, match="must be canonical JSON"): + parse_donor_profile(text) + + +@pytest.mark.parametrize( + ("text", "error", "message"), + [ + (None, TypeError, "must be JSON text"), + (b"{}", TypeError, "must be JSON text"), + ("{", ValueError, "is not JSON"), + ('{"format":NaN}', ValueError, "cannot hold NaN"), + ( + _canonical(BASE)[:-1] + ',"version":1}', + ValueError, + "repeats a key", + ), + ], +) +def test_a_document_that_is_not_one_json_object_refuses(text, error, message): + with pytest.raises(error, match=message): + parse_donor_profile(text) + + +def test_a_profile_built_directly_is_held_to_the_same_closed_sets(): + with pytest.raises(ValueError, match="must be one of"): + DonorProfile(NAME, VERSION, "a" * 64, {**CHOICES, "blank_full_time_study": "x"}) + with pytest.raises(ValueError, match="Unknown donor profile"): + DonorProfile("populace-us-cps-asec-nz", VERSION, "a" * 64, CHOICES) + + +@PROPERTY +@given( + values=st.tuples(*(st.sampled_from(values) for values in OFFERED.values())), + digest=st.text(alphabet="0123456789abcdef", min_size=64, max_size=64), + position=st.integers(min_value=0, max_value=300), +) +def test_canonical_text_round_trips_and_any_inserted_space_refuses( + values, digest, position +): + choices = dict(zip(OFFERED, values, strict=True)) + text = _canonical(_document(digest, **choices)) + profile = parse_donor_profile(text) + assert profile.canonical_text == text + assert dict(profile.choices) == choices + # A space anywhere either breaks the JSON, changes a name or value, or + # respells the same document; each refuses. + cut = position % (len(text) + 1) + with pytest.raises(ValueError): + parse_donor_profile(text[:cut] + " " + text[cut:]) + + +# --- The reader without a profile ------------------------------------------- + + +def test_without_a_profile_the_reader_opens_no_spm_unit_and_stages_nothing( + tmp_path, monkeypatch +): + path = tmp_path / "donor.h5" + pin = _write(path, _raw_tables()) + opened = [] + real = transport_module.read_frame_table + + def spy(store, key): + opened.append(key) + return real(store, key) + + monkeypatch.setattr(transport_module, "read_frame_table", spy) + plain = read_populace_us_donor(path, **pin) + explicit = read_populace_us_donor(path, **pin, profile=None) + assert opened == ["person", "household"] * 2 + for donor in (plain, explicit): + assert donor.donor_profile is None + for entity, columns in STAGED.items(): + assert not set(columns) & set(donor.tables[entity].columns) + for entity in ("person", "household"): + pd.testing.assert_frame_equal(plain.tables[entity], explicit.tables[entity]) + # The unprofiled frame keeps the donor's rent on the owner household. + assert plain.tables["household"]["rent"].tolist() == [25.0, 0.0] + assert plain.tables["household"]["mortgage_interest"].tolist() == [12.0, 7.0] + assert validate_concept_tables(plain.tables) == () + + +# --- The reader with a profile ---------------------------------------------- + + +def test_a_profile_stages_reconciles_and_records(tmp_path): + donor = _read(tmp_path) + household = donor.tables["household"] + person = donor.tables["person"] + assert household["tenure"].tolist() == [ + "owned_with_mortgage", + "rented_public_authority", + ] + assert household["rent"].tolist() == [0.0, 0.0] + assert household["mortgage_interest"].tolist() == [12.0, 0.0] + assert person["legal_marital_status"].tolist() == [ + "married", + "married", + "never_married", + "married", + "married", + "never_married", + ] + assert person["enrolled_full_time"].tolist() == [ + False, + True, + True, + False, + False, + False, + ] + # Staged text has the dtype decode gives its own text concepts. + assert household["tenure"].dtype == person["sex"].dtype + assert person["legal_marital_status"].dtype == person["sex"].dtype + assert validate_concept_tables(donor.tables) == () + record = donor.donor_profile + assert record["profile"] == NAME and record["version"] == VERSION + assert record["choices"] == CHOICES + assert record["document_sha256"] == _profile(record["donor_sha256"]).sha256 + assert set(record["tenure"]) == set(TENURE_DOMAIN) + assert record["tenure"]["owned_with_mortgage"] == {"households": 1, "weight": 1.0} + assert record["tenure"]["rented_public_authority"] == { + "households": 1, + "weight": 3.0, + } + assert record["household_tenure_type"] == { + "OWNED_WITH_MORTGAGE": 1, + "RENTED": 1, + "NONE": 0, + } + assert record["spm_units"] == { + "units": 3, + "units_without_members": 0, + "assistance_rule": "any_spm_unit_in_household", + "households_with_mixed_assistance": 1, + "assisted_renter_households": 1, + "assisted_other_households": 0, + "rent_free_households_with_spm_owner_tenure": 0, + "renter_households_with_spm_owner_tenure": 0, + } + assert record["reconciliation"] == { + "rent": { + "column": "present", + "contradicting_households": 1, + "contradicting_amount": 25.0, + "contradicting_weighted_amount": 25.0, + "total_amount": 25.0, + "weighted_total_amount": 25.0, + "zeroed": True, + }, + "mortgage_interest": { + "column": "present", + "contradicting_households": 1, + "contradicting_amount": 7.0, + "contradicting_weighted_amount": 21.0, + "total_amount": 19.0, + "weighted_total_amount": 33.0, + "zeroed": True, + }, + # Absent, not unreconciled: the donor carries no principal. + "mortgage_principal": {"column": "absent"}, + } + assert record["full_time_study"] == { + "enrolled_full_time": 2, + "blank_a_enrlw_by_source_year": {"2024": 1}, + "blank_a_ftpt_by_source_year": {"2024": 1}, + "read_false_by_source_year": {"2024": 1}, + } + assert record["legal_marital_status"] == { + "never_married": 2, + "married": 4, + "separated": 0, + "divorced": 0, + "widowed": 0, + } + assert set(record["legal_marital_status"]) == set(MARITAL_STATUS_DOMAIN) + json.dumps(record, allow_nan=False) + + +@pytest.mark.parametrize("value", OFFERED["assisted_renter_tenure"]) +def test_assisted_renter_tenure_takes_each_offered_value(tmp_path, value): + donor = _read(tmp_path, assisted_renter_tenure=value) + assert donor.tables["household"]["tenure"].tolist() == [ + "owned_with_mortgage", + value, + ] + # Both values are rented tenures, so the renter's rent survives either. + assert value in RENTED_TENURES + assert donor.donor_profile["choices"]["assisted_renter_tenure"] == value + assert donor.donor_profile["tenure"][value]["households"] == 1 + + +def test_an_unassisted_renter_is_a_private_renter_under_either_value(tmp_path): + tables = _raw_tables() + tables["spm_unit"]["receives_housing_assistance"] = [False, False, False] + for value in OFFERED["assisted_renter_tenure"]: + donor = _read(tmp_path, tables, assisted_renter_tenure=value) + assert donor.tables["household"]["tenure"].tolist()[1] == "rented_private" + + +def test_read_false_reads_blanks_as_not_studying_and_counts_them_by_year(tmp_path): + tables = _raw_tables() + tables["person"]["A_ENRLW"] = [np.nan, 1.0, 1.0, np.nan, 0.0, 1.0] + tables["person"]["A_FTPT"] = [np.nan, 1.0, np.nan, 1.0, 0.0, 2.0] + # One source year per household, as lineage requires. + tables["person"]["source_year"] = [2022, 2022, 2022, 2023, 2023, 2023] + donor = _read(tmp_path, tables, blank_full_time_study="read_false") + assert donor.tables["person"]["enrolled_full_time"].tolist() == [ + False, + True, + False, + False, + False, + False, + ] + assert donor.donor_profile["full_time_study"] == { + "enrolled_full_time": 1, + "blank_a_enrlw_by_source_year": {"2022": 1, "2023": 1}, + "blank_a_ftpt_by_source_year": {"2022": 2, "2023": 0}, + "read_false_by_source_year": {"2022": 2, "2023": 1}, + } + + +def test_refuse_refuses_a_blank_full_time_study_answer_with_its_counts(tmp_path): + with pytest.raises(ValueError, match=r"blank .*\{'2024': 1\}.*refuses"): + _read(tmp_path, blank_full_time_study="refuse") + + +def test_refuse_accepts_a_donor_with_no_blank_answers(tmp_path): + tables = _raw_tables() + tables["person"]["A_ENRLW"] = [2.0, 1.0, 1.0, 0.0, 0.0, 1.0] + tables["person"]["A_FTPT"] = [0.0, 1.0, 1.0, 0.0, 0.0, 2.0] + donor = _read(tmp_path, tables, blank_full_time_study="refuse") + assert donor.donor_profile["full_time_study"]["read_false_by_source_year"] == { + "2024": 0 + } + + +def test_tenure_wins_zeroes_contradicting_costs_and_refuse_refuses_them(tmp_path): + donor = _read(tmp_path, housing_cost_contradicting_tenure="tenure_wins") + assert donor.tables["household"]["rent"].tolist() == [0.0, 0.0] + with pytest.raises( + ValueError, + match=r"\{'rent': 1, 'mortgage_interest': 1\}, which this donor profile refuses", + ): + _read(tmp_path, housing_cost_contradicting_tenure="refuse") + + +def test_refuse_keeps_costs_that_agree_with_tenure(tmp_path): + tables = _raw_tables() + tables["person"]["pre_subsidy_rent"] = 0.0 + tables["person"].loc[3, "pre_subsidy_rent"] = 40.0 + tables["person"]["home_mortgage_interest"] = [12.0, 0.0, 0.0, 0.0, 0.0, 0.0] + for value in OFFERED["housing_cost_contradicting_tenure"]: + donor = _read(tmp_path, tables, housing_cost_contradicting_tenure=value) + assert donor.tables["household"]["rent"].tolist() == [0.0, 40.0] + assert donor.tables["household"]["mortgage_interest"].tolist() == [12.0, 0.0] + rent = donor.donor_profile["reconciliation"]["rent"] + assert rent["column"] == "present" + assert rent["contradicting_households"] == 0 + assert rent["zeroed"] is False + + +def test_a_profile_naming_other_bytes_refuses_before_the_file_is_opened( + tmp_path, monkeypatch +): + path = tmp_path / "donor.h5" + pin = _write(path, _raw_tables()) + + def never(*_, **__): + raise AssertionError("A mismatched profile must refuse before any read.") + + monkeypatch.setattr(Path, "open", never) + monkeypatch.setattr(pd, "HDFStore", never) + with pytest.raises(ValueError, match="names donor bytes other than"): + read_populace_us_donor(path, **pin, profile=_profile("e" * 64)) + with pytest.raises(TypeError, match="must be a parsed DonorProfile"): + read_populace_us_donor( + path, **pin, profile=_canonical(_document(pin["sha256"])) + ) + + +def _edited(edit): + tables = _raw_tables() + edit(tables) + return tables + + +def _set(table, column, values): + def edit(tables): + tables[table][column] = values + + return edit + + +def _drop(table, column): + def edit(tables): + tables[table].pop(column) + + return edit + + +@pytest.mark.parametrize( + ("edit", "message"), + [ + (lambda t: t.pop("spm_unit"), "needs the donor's spm_unit table"), + (_drop("household", "H_TENURE"), r"\['household.H_TENURE'\]"), + (_drop("household", "tenure_type"), r"\['household.tenure_type'\]"), + (_drop("person", "person_spm_unit_id"), r"\['person.person_spm_unit_id'\]"), + (_drop("person", "A_FTPT"), r"\['person.A_FTPT'\]"), + (_drop("person", "A_MARITL"), r"\['person.A_MARITL'\]"), + ( + _drop("spm_unit", "receives_housing_assistance"), + r"\['spm_unit.receives_housing_assistance'\]", + ), + (_set("person", "A_MARITL", [1, 1, 7, 1, 1, 8]), "A_MARITL holds codes"), + (_set("person", "A_MARITL", [0, 1, 7, 1, 1, 7]), "A_MARITL holds codes"), + (_set("person", "A_MARITL", [1.0, 1, 7, 1, 1, np.nan]), "A_MARITL has 1 blank"), + (_set("person", "A_MARITL", [1.5, 1, 7, 1, 1, 7]), "A_MARITL holds codes"), + (_set("person", "A_ENRLW", [2.0, 1.0, 1.0, np.nan, 0.0, 3.0]), "A_ENRLW holds"), + (_set("person", "A_ENRLW", [np.inf, 1, 1, np.nan, 0, 1]), "A_ENRLW holds"), + (_set("person", "A_FTPT", [0.0, 1.5, 1.0, np.nan, 0.0, 2.0]), "A_FTPT holds"), + (_set("household", "tenure_type", ["OWNED_WITH_MORTGAGE", "LEASED"]), "labels"), + (_set("household", "tenure_type", ["OWNED_OUTRIGHT", "RENTED"]), "labels"), + (_set("household", "tenure_type", ["NONE", None]), "labels outside"), + (_set("household", "H_TENURE", [1, 3]), "disagrees with H_TENURE in 1"), + (_set("household", "H_TENURE", [1.0, np.nan]), "H_TENURE has 1 blank"), + (_set("household", "H_TENURE", [1, 4]), "H_TENURE holds codes"), + ( + _set("spm_unit", "spm_unit_tenure_type", ["OWNER", "RENTER", "RENTER"]), + "spm_unit_tenure_type holds labels", + ), + ( + _set("spm_unit", "receives_housing_assistance", [0, 0, 1]), + "must be boolean", + ), + (_set("spm_unit", "spm_unit_id", [11, 21, 21]), "must be unique"), + (_set("spm_unit", "spm_unit_id", [11.0, 21.0, np.nan]), "integer ids"), + (_set("person", "person_spm_unit_id", [11.0] * 3 + [21.0] + [22.0] * 2), "ids"), + (_set("spm_unit", "spm_unit_id", [11, 21, 23]), "2 donor persons belong"), + ( + _set("person", "person_spm_unit_id", [11, 11, 11, 11, 22, 22]), + "1 donor SPM units span more than one household", + ), + ( + _set("person", "person_spm_unit_id", [11, 11, 21, 21, 22, 22]), + "span more than one household", + ), + ( + _set( + "spm_unit", + "spm_unit_tenure_type", + ["OWNER_WITH_MORTGAGE", "RENTER", "OWNER_WITH_MORTGAGE"], + ), + "1 donor households have SPM units that disagree on tenure", + ), + ( + _set("spm_unit", "spm_unit_tenure_type", ["RENTER", "RENTER", "RENTER"]), + "owner households have SPM renter tenure", + ), + ( + _set("person", "pre_subsidy_rent", [np.inf, 0, 0, 0, 0, 0]), + "rent must be finite before reconciliation", + ), + ], +) +def test_unexpected_values_and_failed_joins_refuse(tmp_path, edit, message): + with pytest.raises(ValueError, match=message): + _read(tmp_path, _edited(edit)) + + +@pytest.mark.parametrize( + ("edit", "message"), + [ + # A blank H_TENURE refuses as a blank, not as a disagreement. + (_set("household", "H_TENURE", [np.nan, 3.0]), "H_TENURE has 1 blank"), + # An unknown label refuses before H_TENURE is compared with it. + (_set("household", "tenure_type", ["NONE", "LEASED"]), "labels outside"), + # An invalid code refuses before any join or tenure is built. + ( + lambda t: ( + _set("person", "A_MARITL", [9, 1, 7, 1, 1, 7])(t), + _set("spm_unit", "spm_unit_id", [11, 21, 21])(t), + ), + "A_MARITL holds codes", + ), + ], +) +def test_raw_checks_fire_before_any_comparison_reads_the_value(tmp_path, edit, message): + with pytest.raises(ValueError, match=message): + _read(tmp_path, _edited(edit)) + + +def test_a_memberless_spm_unit_is_counted_and_stages_nothing(tmp_path): + """A unit with no member reaches no household, so it cannot change a + staged value: the reader counts it rather than refusing it.""" + (tmp_path / "plain").mkdir() + (tmp_path / "extra").mkdir() + plain = _read(tmp_path / "plain") + tables = _raw_tables() + tables["spm_unit"] = pd.concat( + [ + tables["spm_unit"], + pd.DataFrame( + { + "spm_unit_id": [99], + "spm_unit_tenure_type": ["OWNER_WITHOUT_MORTGAGE"], + "receives_housing_assistance": [True], + } + ), + ], + ignore_index=True, + ) + extra = _read(tmp_path / "extra", tables) + for entity in ("person", "household"): + pd.testing.assert_frame_equal(plain.tables[entity], extra.tables[entity]) + assert extra.donor_profile["spm_units"]["units"] == 4 + assert extra.donor_profile["spm_units"]["units_without_members"] == 1 + # The new bytes change the donor and document digests, and nothing else. + differ = {"spm_units", "donor_sha256", "document_sha256"} + assert {k: v for k, v in extra.donor_profile.items() if k not in differ} == { + k: v for k, v in plain.donor_profile.items() if k not in differ + } + + +def test_validation_still_runs_on_the_staged_frame(tmp_path, monkeypatch): + seen = [] + real = transport_module.validate_concept_tables + + def spy(tables): + seen.append({entity: set(table.columns) for entity, table in tables.items()}) + return real(tables) + + monkeypatch.setattr(transport_module, "validate_concept_tables", spy) + _read(tmp_path) + assert any("tenure" in columns["household"] for columns in seen) + monkeypatch.setattr(transport_module, "validate_concept_tables", real) + tables = _raw_tables() + tables["person"]["age"] = [40, 38, -1, 45, 42, 12] + with pytest.raises(ValueError, match="Invalid donor concepts"): + _read(tmp_path, tables) + + +def _copy_household(tables, source, copy, weight): + """Append household ``source`` and its persons again as household ``copy``.""" + person, household = tables["person"], tables["household"] + members = person.loc[person["person_household_id"] == source].copy() + first = len(person) + 1 + members["person_id"] = person["person_id"].max() + np.arange(1, len(members) + 1) + members["person_household_id"] = copy + members["source_household_id"] = copy + numbers = [f"{n:022d}" for n in range(first, first + len(members))] + members["source_person_id"] = numbers + members["person_source_id"] = numbers + row = household.loc[household["household_id"] == source].copy() + row["household_id"] = copy + row["household_weight"] = weight + tables["person"] = pd.concat([person, members], ignore_index=True) + tables["household"] = pd.concat([household, row], ignore_index=True) + + +def _five_households() -> dict[str, pd.DataFrame]: + """Five households that give every SPM counter of the record a value. + + 101 (weight 1) owns with a mortgage; its two SPM units differ in + assistance. 202 (weight 3) rents; its two SPM units differ in + assistance. 303 (weight 2, 101's persons again) lives rent free in an + unassisted SPM unit that owns without a mortgage. 404 (weight 5, 202's + persons again) lives rent free in an assisted SPM unit that owns with a + mortgage. 505 (weight 4, 202's persons again) rents, in an unassisted SPM + unit that owns without a mortgage. + """ + tables = _raw_tables() + _copy_household(tables, 101, 303, weight=2.0) + _copy_household(tables, 202, 404, weight=5.0) + _copy_household(tables, 202, 505, weight=4.0) + household = tables["household"] + household["tenure_type"] = [ + "OWNED_WITH_MORTGAGE", + "RENTED", + "NONE", + "NONE", + "RENTED", + ] + household["H_TENURE"] = [1, 2, 3, 3, 2] + tables["person"]["person_spm_unit_id"] = [ + *(11, 11, 12), + *(21, 22, 22), + *(31, 31, 31), + *(41, 41, 41), + *(51, 51, 51), + ] + tables["spm_unit"] = pd.DataFrame( + { + "spm_unit_id": [11, 12, 21, 22, 31, 41, 51], + "spm_unit_tenure_type": [ + "OWNER_WITH_MORTGAGE", + "OWNER_WITH_MORTGAGE", + "RENTER", + "RENTER", + "OWNER_WITHOUT_MORTGAGE", + "OWNER_WITH_MORTGAGE", + "OWNER_WITHOUT_MORTGAGE", + ], + "receives_housing_assistance": [ + True, + False, + False, + True, + False, + True, + False, + ], + } + ) + return tables + + +def test_rent_free_assisted_owner_and_mixed_households_give_the_whole_record( + tmp_path, +): + path = tmp_path / "donor.h5" + pin = _write(path, _five_households()) + profile = _profile(pin["sha256"]) + donor = read_populace_us_donor(path, **pin, profile=profile) + household = donor.tables["household"] + assert household["household_id"].tolist() == [101, 202, 303, 404, 505] + assert household["tenure"].tolist() == [ + "owned_with_mortgage", + "rented_public_authority", + "rent_free", + "rent_free", + "rented_private", + ] + # Rent survives only for renters, interest only for the mortgaged owner. + assert household["rent"].tolist() == [0.0, 0.0, 0.0, 0.0, 0.0] + assert household["mortgage_interest"].tolist() == [12.0, 0.0, 0.0, 0.0, 0.0] + assert validate_concept_tables(donor.tables) == () + empty = {"households": 0, "weight": 0.0} + assert donor.donor_profile == { + "profile": NAME, + "version": VERSION, + "document_sha256": profile.sha256, + "donor_sha256": pin["sha256"], + "choices": CHOICES, + "tenure": { + "owned_with_mortgage": {"households": 1, "weight": 1.0}, + "owned_outright": empty, + "rented_private": {"households": 1, "weight": 4.0}, + "rented_public_authority": {"households": 1, "weight": 3.0}, + "rented_nonprofit_social": empty, + "rent_free": {"households": 2, "weight": 7.0}, + }, + "household_tenure_type": { + "OWNED_WITH_MORTGAGE": 1, + "RENTED": 2, + "NONE": 2, + }, + "spm_units": { + "units": 7, + "units_without_members": 0, + "assistance_rule": "any_spm_unit_in_household", + # 101 and 202. + "households_with_mixed_assistance": 2, + # 202. + "assisted_renter_households": 1, + # 101, an owner, and 404, rent free. + "assisted_other_households": 2, + # 303 and 404. + "rent_free_households_with_spm_owner_tenure": 2, + # 505. + "renter_households_with_spm_owner_tenure": 1, + }, + "full_time_study": { + "enrolled_full_time": 4, + "blank_a_enrlw_by_source_year": {"2024": 3}, + "blank_a_ftpt_by_source_year": {"2024": 3}, + "read_false_by_source_year": {"2024": 3}, + }, + "legal_marital_status": { + "married": 10, + "widowed": 0, + "divorced": 0, + "separated": 0, + "never_married": 5, + }, + "reconciliation": { + # 25 each on owner 101 (weight 1) and rent-free 303 (weight 2). + "rent": { + "column": "present", + "contradicting_households": 2, + "contradicting_amount": 50.0, + "contradicting_weighted_amount": 75.0, + "total_amount": 50.0, + "weighted_total_amount": 75.0, + "zeroed": True, + }, + # 7 on 202 (weight 3), 12 on 303 (weight 2), 7 on 404 (weight 5), + # 7 on 505 (weight 4); 101 keeps its 12. + "mortgage_interest": { + "column": "present", + "contradicting_households": 4, + "contradicting_amount": 33.0, + "contradicting_weighted_amount": 108.0, + "total_amount": 45.0, + "weighted_total_amount": 120.0, + "zeroed": True, + }, + "mortgage_principal": {"column": "absent"}, + }, + } + assert set(donor.donor_profile["tenure"]) == set(TENURE_DOMAIN) + + +# Each A_MARITL code against the status the data dictionary cited at +# A_MARITL above gives it. +@pytest.mark.parametrize( + ("code", "status"), + [ + (1, "married"), + (2, "married"), + (3, "married"), + (4, "widowed"), + (5, "divorced"), + (6, "separated"), + (7, "never_married"), + ], +) +def test_each_a_maritl_code_reads_as_its_codebook_status(tmp_path, code, status): + assert A_MARITL[code] == status + tables = _raw_tables() + tables["person"]["A_MARITL"] = [code] * 6 + donor = _read(tmp_path, tables) + assert donor.tables["person"]["legal_marital_status"].tolist() == [status] * 6 + assert donor.donor_profile["legal_marital_status"] == { + value: 6 if value == status else 0 for value in MARITAL_STATUS_DOMAIN + } + + +# --- Staging properties against an independent oracle --------------------- + + +@st.composite +def _donors(draw, *, blanks=True, costs_agree=False): + """Raw households, SPM units and persons, and the decoded household rows. + + With ``blanks=False`` no enrollment answer is blank. With + ``costs_agree=True`` only renters carry rent and only owners whose SPM + units hold a mortgage carry mortgage interest, so no cost contradicts + the staged tenure. + """ + enrollment = [0.0, 1.0, 2.0, np.nan] if blanks else [0.0, 1.0, 2.0] + n_households = draw(st.integers(1, 6)) + households, units, persons = [], [], [] + for h in range(n_households): + label = draw(st.sampled_from(["OWNED_WITH_MORTGAGE", "RENTED", "NONE"])) + owner = label == "OWNED_WITH_MORTGAGE" + spm_tenure = draw( + st.sampled_from( + ["OWNER_WITH_MORTGAGE", "OWNER_WITHOUT_MORTGAGE"] + if owner + else ["OWNER_WITH_MORTGAGE", "OWNER_WITHOUT_MORTGAGE", "RENTER"] + ) + ) + pays_rent = label == "RENTED" or not costs_agree + pays_interest = ( + owner and spm_tenure == "OWNER_WITH_MORTGAGE" + ) or not costs_agree + households.append( + { + "household_id": 100 + h, + "tenure_type": label, + "H_TENURE": {"OWNED_WITH_MORTGAGE": 1, "RENTED": 2, "NONE": 3}[label], + "rent": draw(st.sampled_from([0.0, 1.0, 250.5])) if pays_rent else 0.0, + "mortgage_interest": ( + draw(st.sampled_from([0.0, 3.0, 99.25])) if pays_interest else 0.0 + ), + "weight": draw(st.sampled_from([0.5, 1.0, 4.0])), + } + ) + for u in range(draw(st.integers(1, 2))): + unit_id = 1000 + 10 * h + u + units.append( + { + "spm_unit_id": unit_id, + "spm_unit_tenure_type": spm_tenure, + "receives_housing_assistance": draw(st.booleans()), + } + ) + for _ in range(draw(st.integers(1, 2))): + persons.append( + { + "person_id": len(persons) + 1, + "person_household_id": 100 + h, + "person_spm_unit_id": unit_id, + "source_year": draw(st.sampled_from([2022, 2023, 2024])), + "A_MARITL": draw(st.integers(1, 7)), + "A_ENRLW": draw(st.sampled_from(enrollment)), + "A_FTPT": draw(st.sampled_from(enrollment)), + } + ) + person_order = draw(st.permutations(range(len(persons)))) + household_order = draw(st.permutations(range(n_households))) + return ( + pd.DataFrame(households), + pd.DataFrame(units), + pd.DataFrame([persons[i] for i in person_order]), + list(household_order), + ) + + +def _stage(households, units, persons, profile, decoded_order=None): + """Run the raw staging, then attach to decoded tables in another order.""" + raw_household = households[["household_id", "tenure_type", "H_TENURE"]].copy() + staged = transport_module._stage_donor_profile( + profile, persons, raw_household, units + ) + order = list(range(len(households))) if decoded_order is None else decoded_order + decoded = households.iloc[order].reset_index(drop=True) + tables = { + "person": persons[["person_id", "person_household_id"]] + .iloc[::-1] + .reset_index(drop=True), + "household": decoded[["household_id", "rent", "mortgage_interest"]].copy(), + } + weights = households["weight"].to_numpy(dtype=np.float64) + record = transport_module._attach_donor_profile(staged, tables, weights) + return tables, record + + +def _oracle_tenure(row, units, assisted_renter_tenure): + own = units.loc[units.spm_unit_id // 10 == row.household_id] + if row.tenure_type == "NONE": + return "rent_free" + if row.tenure_type == "RENTED": + assisted = own.receives_housing_assistance.any() + return assisted_renter_tenure if assisted else "rented_private" + if own.spm_unit_tenure_type.iloc[0] == "OWNER_WITH_MORTGAGE": + return "owned_with_mortgage" + return "owned_outright" + + +def _pays(tenure: str, column: str) -> bool: + if column == "rent": + return tenure in RENTED_TENURES + return tenure == "owned_with_mortgage" + + +def test_weighted_record_values_follow_decoded_rows_not_raw_rows(): + """Decoded rows in another order than the raw rows, unequal weights.""" + households = pd.DataFrame( + { + "household_id": [100, 101, 102], + "tenure_type": ["OWNED_WITH_MORTGAGE", "RENTED", "NONE"], + "H_TENURE": [1, 2, 3], + "rent": [10.0, 250.5, 1.0], + "mortgage_interest": [3.0, 99.25, 0.0], + "weight": [0.5, 4.0, 1.0], + } + ) + units = pd.DataFrame( + { + "spm_unit_id": [1000, 1010, 1020], + "spm_unit_tenure_type": [ + "OWNER_WITH_MORTGAGE", + "RENTER", + "OWNER_WITHOUT_MORTGAGE", + ], + "receives_housing_assistance": [False, True, False], + } + ) + persons = pd.DataFrame( + { + "person_id": [1, 2, 3], + "person_household_id": [100, 101, 102], + "person_spm_unit_id": [1000, 1010, 1020], + "source_year": [2024, 2024, 2024], + "A_MARITL": [1, 4, 7], + "A_ENRLW": [1.0, 1.0, 2.0], + "A_FTPT": [1.0, 2.0, 1.0], + } + ) + # Decoded rows 102, 100, 101 against raw weights 0.5, 4.0, 1.0. + tables, record = _stage(households, units, persons, _profile("f" * 64), [2, 0, 1]) + household = tables["household"] + assert household["household_id"].tolist() == [102, 100, 101] + assert household["tenure"].tolist() == [ + "rent_free", + "owned_with_mortgage", + "rented_public_authority", + ] + assert household["rent"].tolist() == [0.0, 0.0, 250.5] + assert household["mortgage_interest"].tolist() == [0.0, 3.0, 0.0] + empty = {"households": 0, "weight": 0.0} + assert record["tenure"] == { + "owned_with_mortgage": {"households": 1, "weight": 0.5}, + "owned_outright": empty, + "rented_private": empty, + "rented_public_authority": {"households": 1, "weight": 4.0}, + "rented_nonprofit_social": empty, + "rent_free": {"households": 1, "weight": 1.0}, + } + assert record["reconciliation"] == { + # 1.0 on rent-free 102 (weight 1) and 10.0 on owner 100 (weight 0.5). + "rent": { + "column": "present", + "contradicting_households": 2, + "contradicting_amount": 11.0, + "contradicting_weighted_amount": 6.0, + "total_amount": 261.5, + "weighted_total_amount": 1008.0, + "zeroed": True, + }, + # 99.25 on renter 101 (weight 4); owner 100 keeps its 3.0. + "mortgage_interest": { + "column": "present", + "contradicting_households": 1, + "contradicting_amount": 99.25, + "contradicting_weighted_amount": 397.0, + "total_amount": 102.25, + "weighted_total_amount": 398.5, + "zeroed": True, + }, + "mortgage_principal": {"column": "absent"}, + } + # The helper hands persons to the attach step in reverse order. + person = tables["person"] + assert person["person_id"].tolist() == [3, 2, 1] + assert person["legal_marital_status"].tolist() == [ + "never_married", + "widowed", + "married", + ] + assert person["enrolled_full_time"].tolist() == [False, False, True] + + +@PROPERTY +@given( + values=st.tuples(*(st.sampled_from(values) for values in OFFERED.values())), + data=st.data(), +) +def test_staging_follows_the_rules_and_leaves_a_consistent_frame(values, data): + """Each drawn donor stages: under a refusing choice the donor has no + blank answer, or no cost that contradicts its tenure.""" + choices = dict(zip(OFFERED, values, strict=True)) + households, units, persons, order = data.draw( + _donors( + blanks=choices["blank_full_time_study"] == "read_false", + costs_agree=choices["housing_cost_contradicting_tenure"] == "refuse", + ) + ) + profile = _profile("f" * 64, **choices) + blank = (persons.A_ENRLW.isna() | persons.A_FTPT.isna()).to_numpy() + tenure_by_id = { + row.household_id: _oracle_tenure(row, units, choices["assisted_renter_tenure"]) + for row in households.itertuples() + } + rented = np.asarray( + [tenure_by_id[i] in RENTED_TENURES for i in households.household_id] + ) + mortgaged = np.asarray( + [tenure_by_id[i] == "owned_with_mortgage" for i in households.household_id] + ) + rent = households["rent"].to_numpy() + interest = households["mortgage_interest"].to_numpy() + contradicts = ((~rented) & (rent != 0)).any() or ( + (~mortgaged) & (interest != 0) + ).any() + assert not (blank.any() and choices["blank_full_time_study"] == "refuse") + assert not ( + contradicts and choices["housing_cost_contradicting_tenure"] == "refuse" + ) + tables, record = _stage(households, units, persons, profile, order) + household = tables["household"] + assert household["tenure"].tolist() == [ + tenure_by_id[i] for i in household["household_id"] + ] + assert "rented_nonprofit_social" not in household["tenure"].tolist() + by_id = households.set_index("household_id") + expected_rent = [ + by_id.rent[i] if tenure_by_id[i] in RENTED_TENURES else 0.0 + for i in household["household_id"] + ] + expected_interest = [ + by_id.mortgage_interest[i] if tenure_by_id[i] == "owned_with_mortgage" else 0.0 + for i in household["household_id"] + ] + assert household["rent"].tolist() == expected_rent + assert household["mortgage_interest"].tolist() == expected_interest + weights = households["weight"].to_numpy() + for column, values_, keep in ( + ("rent", rent, rented), + ("mortgage_interest", interest, mortgaged), + ): + zeroed = ~keep & (values_ != 0) + assert record["reconciliation"][column] == { + "column": "present", + "contradicting_households": int(zeroed.sum()), + "contradicting_amount": fsum(values_[zeroed]), + "contradicting_weighted_amount": fsum((values_ * weights)[zeroed]), + "total_amount": fsum(values_), + "weighted_total_amount": fsum(values_ * weights), + "zeroed": bool(zeroed.any()), + } + assert record["reconciliation"]["mortgage_principal"] == {"column": "absent"} + assert sum(item["households"] for item in record["tenure"].values()) == len( + households + ) + person = tables["person"] + by_person = persons.set_index("person_id") + assert person["legal_marital_status"].tolist() == [ + A_MARITL[by_person.A_MARITL[i]] for i in person["person_id"] + ] + assert person["enrolled_full_time"].tolist() == [ + bool(by_person.A_ENRLW[i] == 1 and by_person.A_FTPT[i] == 1) + for i in person["person_id"] + ] + by_year = record["full_time_study"]["read_false_by_source_year"] + for year in (2022, 2023, 2024): + in_year = (persons.source_year == year).to_numpy() + assert by_year.get(str(year), 0) == int((blank & in_year).sum()) + staged = {"tenure", "rent", "mortgage_interest", *STAGED["person"]} + assert [v for v in validate_concept_tables(tables) if v.column in staged] == [] + + +@PROPERTY +@given(donor=_donors(), data=st.data()) +def test_a_refusing_choice_refuses_with_its_counts(donor, data): + """A blank answer under ``blank_full_time_study=refuse``, or a cost that + contradicts the staged tenure under ``refuse``, refuses with its counts. + A blank refuses first, because it refuses during staging.""" + households, units, persons, order = donor + households, persons = households.copy(), persons.copy() + refusing = data.draw(st.sampled_from([{"blank"}, {"cost"}, {"blank", "cost"}])) + if "blank" in refusing: + who = data.draw(st.integers(0, len(persons) - 1)) + column = data.draw(st.sampled_from(["A_ENRLW", "A_FTPT"])) + persons.loc[who, column] = np.nan + if "cost" in refusing: + # Every tenure contradicts rent or mortgage interest, so this does. + where = data.draw(st.integers(0, len(households) - 1)) + households.loc[where, ["rent", "mortgage_interest"]] = [1.0, 3.0] + choices = { + "assisted_renter_tenure": data.draw( + st.sampled_from(OFFERED["assisted_renter_tenure"]) + ), + "blank_full_time_study": "refuse" if "blank" in refusing else "read_false", + "housing_cost_contradicting_tenure": ( + "refuse" if "cost" in refusing else "tenure_wins" + ), + } + if "blank" in refusing: + blank = (persons.A_ENRLW.isna() | persons.A_FTPT.isna()).to_numpy() + by_year = { + str(year): int((blank & (persons.source_year == year).to_numpy()).sum()) + for year in sorted(set(persons.source_year)) + } + message = f"blank for persons by source year {by_year}, which" + else: + tenure_by_id = { + row.household_id: _oracle_tenure( + row, units, choices["assisted_renter_tenure"] + ) + for row in households.itertuples() + } + counts = { + column: sum( + int( + bool(getattr(row, column) != 0) + and not _pays(tenure_by_id[row.household_id], column) + ) + for row in households.itertuples() + ) + for column in ("rent", "mortgage_interest") + } + contradicted = {column: n for column, n in counts.items() if n} + message = f"contradict the staged tenure in households {contradicted}, which" + with pytest.raises(ValueError, match=re.escape(message)): + _stage(households, units, persons, _profile("f" * 64, **choices), order) + + +@PROPERTY +@given(donor=_donors(), data=st.data()) +def test_a_missing_spm_join_refuses_and_never_falls_through(donor, data): + """A household the join cannot reach would otherwise read as + rented_private (no assistance) or owned_outright (no mortgage flag).""" + households, units, persons, _ = donor + profile = _profile("f" * 64) + target = data.draw(st.sampled_from(households.household_id.tolist())) + detached = persons.copy() + detached.loc[detached.person_household_id == target, "person_spm_unit_id"] = 999 + with pytest.raises(ValueError, match="belong to no known SPM unit"): + _stage(households, units, detached, profile) + label = data.draw(st.sampled_from(["OWNED_WITH_MORTGAGE", "RENTED", "NONE"])) + orphan = pd.DataFrame( + [ + { + "household_id": 999, + "tenure_type": label, + "H_TENURE": {"OWNED_WITH_MORTGAGE": 1, "RENTED": 2, "NONE": 3}[label], + "rent": 0.0, + "mortgage_interest": 0.0, + "weight": 1.0, + } + ] + ) + with pytest.raises(ValueError, match="1 donor households have no SPM unit"): + _stage( + pd.concat([households, orphan], ignore_index=True), units, persons, profile + ) + + +@PROPERTY +@given( + values=st.lists( + st.one_of( + st.integers(-2, 9).map(float), + st.sampled_from([0.5, 1.5, np.nan, np.inf, -np.inf, 2.0000001]), + ), + min_size=1, + max_size=8, + ), + missing_ok=st.booleans(), +) +def test_survey_codes_refuse_anything_outside_the_codebook(values, missing_ok): + series = pd.Series(np.asarray(values, dtype=np.float64), name="A_TEST") + numbers = series.to_numpy() + blank = np.isnan(numbers) + invalid = ~blank & ~np.isin(numbers, [1.0, 2.0, 3.0]) + if invalid.any() or (blank.any() and not missing_ok): + with pytest.raises(ValueError, match="A_TEST"): + transport_module._profile_codes( + series, frozenset({1, 2, 3}), missing_ok=missing_ok + ) + return + codes, mask = transport_module._profile_codes( + series, frozenset({1, 2, 3}), missing_ok=missing_ok + ) + assert mask.tolist() == blank.tolist() + assert codes.tolist() == [ + -1 if m else int(v) for v, m in zip(numbers, blank, strict=True) + ] + + +@pytest.mark.parametrize("missing", [None, np.nan, pd.NA, 3]) +def test_a_missing_or_non_text_label_refuses(missing): + values = pd.Series(["RENTED", missing], name="tenure_type", dtype=object) + with pytest.raises(ValueError, match="labels outside"): + transport_module._profile_labels(values, {"RENTED"}) + + +@pytest.mark.parametrize( + "assistance", + [ + pd.Series([False, None, True], dtype="boolean"), + pd.Series([False, None, True], dtype=object), + pd.Series([0.0, 0.0, 1.0]), + ], +) +def test_assistance_must_be_boolean_with_no_nulls(assistance): + tables = _raw_tables() + tables["spm_unit"]["receives_housing_assistance"] = assistance + with pytest.raises(ValueError, match="must be boolean with no nulls"): + transport_module._stage_donor_profile( + _profile("a" * 64), + tables["person"], + tables["household"], + tables["spm_unit"], + ) + + +def test_the_shared_reader_names_no_country_and_no_donor_digest(): + """No country name, node id or donor digest literal in the shared module.""" + source = Path(transport_module.__file__).read_text() + strings = [ + node.value + for node in ast.walk(ast.parse(source)) + if isinstance(node, ast.Constant) and isinstance(node.value, str) + ] + assert not [s for s in strings if re.search(r"[0-9a-f]{64}", s)] + assert not [s for s in strings if re.search(r"(?i)zealand|belgi", s)] + # A country-scoped node id such as "nz.create". + assert not [s for s in strings if re.search(r"\b(nz|be|uk|us)\.[a-z_]", s)] + for name, _ in DONOR_PROFILE_CHOICES: + assert not re.search(r"(?i)\b(nz|be|uk)\b", name) diff --git a/test_support/microcosm_build/transport_create_baseline.py b/test_support/microcosm_build/transport_create_baseline.py new file mode 100644 index 0000000000..7e4ae0551c --- /dev/null +++ b/test_support/microcosm_build/transport_create_baseline.py @@ -0,0 +1,318 @@ +"""Frozen CREATE baselines: canonical bytes with no donor profile set. + +Each scenario builds a toy donor or a composed toy graph, runs CREATE on its +declared parameters and sources, and loads the same donor through the donor +codec. :func:`scenario_bytes` returns the canonical bytes of CREATE's frame +and receipt and of the codec's frame. The committed fixtures under +``packages/microcosm-build/tests/fixtures/transport_create_baseline/`` were +captured at the commit their provenance file names, before CREATE accepted a +donor profile, so a test that recomputes them shows that a graph setting no +profile still gets the same bytes. Write them with:: + + python -m test_support.microcosm_build.transport_create_baseline +""" + +from __future__ import annotations + +import math +import sys +import tempfile +from collections.abc import Callable, Mapping +from hashlib import sha256 +from pathlib import Path + +import numpy as np +import pandas as pd + +from microcosm.frame import Frame +from microcosm.graph import KernelContext, Node +from microcosm.graph.canonical import canonical_json + +#: The scenarios, in capture order. +SCENARIOS = ("toy", "toy_v2", "toy_profile_columns", "composed", "nz_toy") + + +def add_profile_columns(tables: dict[str, pd.DataFrame]) -> None: + """Add the raw survey answers and SPM units a donor profile reads. + + For the six-person synthetic donor. Household 101 owns with a mortgage + and carries rent; household 202 rents, with one assisted and one + unassisted SPM unit, and carries mortgage interest. Person 4 (source + year 2024) has blank enrollment answers. A donor without a profile + ignores every one of these columns and the ``spm_unit`` table. + """ + person = tables["person"] + person["home_mortgage_interest"] = [12.0, 0.0, 0.0, 7.0, 0.0, 0.0] + person["person_spm_unit_id"] = [11, 11, 11, 21, 22, 22] + person["A_MARITL"] = [1, 1, 7, 1, 1, 7] + person["A_ENRLW"] = [2.0, 1.0, 1.0, np.nan, 0.0, 1.0] + person["A_FTPT"] = [0.0, 1.0, 1.0, np.nan, 0.0, 2.0] + household = tables["household"] + household["tenure_type"] = ["OWNED_WITH_MORTGAGE", "RENTED"] + household["H_TENURE"] = [1, 2] + tables["spm_unit"] = pd.DataFrame( + { + "spm_unit_id": [11, 21, 22], + "spm_unit_tenure_type": ["OWNER_WITH_MORTGAGE", "RENTER", "RENTER"], + "receives_housing_assistance": [False, False, True], + } + ) + + +def _scalar(value: object) -> object: + """One cell as a typed canonical JSON value; NA and NaN stay distinct.""" + if value is None or value is pd.NA or value is pd.NaT: + return None + if isinstance(value, (bool, np.bool_)): + return bool(value) + if isinstance(value, (int, np.integer)): + return int(value) + if isinstance(value, (float, np.floating)): + value = float(value) + return value if math.isfinite(value) else {"nonfinite": repr(value)} + if isinstance(value, str): + return value + raise TypeError(f"No canonical form for {type(value).__name__}.") + + +def _index(index: pd.Index) -> dict: + return { + "name": index.name, + "dtype": repr(index.dtype), + "values": [_scalar(value) for value in index.tolist()], + } + + +def _series(series: pd.Series) -> dict: + return { + "name": series.name, + "dtype": repr(series.dtype), + "index": _index(series.index), + "values": [_scalar(value) for value in series.tolist()], + } + + +def _table(table: pd.DataFrame) -> dict: + return { + "index": _index(table.index), + "columns_name": table.columns.name, + "columns": [ + { + "name": column, + "dtype": repr(table[column].dtype), + "values": [_scalar(value) for value in table[column].tolist()], + } + for column in table.columns + ], + } + + +def _metadata(value: object) -> object: + """Frame metadata with its order and container kinds kept.""" + if isinstance(value, Mapping): + return {"mapping": [[key, _metadata(item)] for key, item in value.items()]} + if isinstance(value, tuple): + return {"tuple": [_metadata(item) for item in value]} + if isinstance(value, list): + return {"list": [_metadata(item) for item in value]} + if isinstance(value, frozenset): + return { + "frozenset": sorted( + (_metadata(item) for item in value), + key=lambda item: canonical_json(item), + ) + } + return _scalar(value) + + +def frame_document(frame: Frame) -> dict: + """Every table, dtype, index, weight, stratum and metadata item of a frame.""" + schema = frame.schema + return { + "schema": { + "person_entity": schema.person_entity, + "group_entities": list(schema.group_entities), + "links": [ + [link.name, link.left_entity, link.right_entity] + for link in schema.links + ], + }, + "tables": [[entity, _table(frame.table(entity))] for entity in frame.entities], + "links": [[name, _table(frame.link(name))] for name in frame.links], + "weights": [ + [ + entity, + frame.weights_for(entity).kind.value, + _series(pd.Series(frame.weights_for(entity).values)), + ] + for entity in frame.weighted_entities + ], + "strata": _series(frame.strata), + "mass_log": [ + [ + record.entity, + _scalar(record.old_total), + _scalar(record.new_total), + _scalar(record.declared_factor), + record.reason, + ] + for record in frame.mass_log + ], + "metadata": _metadata(frame.metadata), + } + + +def run_create( + kernel_ref: str, + params: Mapping[str, object], + sources: Mapping[str, Path], + *, + node_id: str = "create", +): + """Run CREATE on declared params and sources, as the CLI's inventory probe. + + CREATE reads no node id, so ``node_id`` names the probe node only. + """ + from microcosm.build.transport.population_kernels import ( + TRANSPORT_CREATE, + TRANSPORT_CREATE_DECLARED, + ) + + kernel = { + TRANSPORT_CREATE.ref: TRANSPORT_CREATE, + TRANSPORT_CREATE_DECLARED.ref: TRANSPORT_CREATE_DECLARED, + }[kernel_ref] + node = Node(node_id, kernel_ref, params=dict(params), sources=tuple(sources)) + return kernel.run( + KernelContext( + node=node, + tables={}, + weights={}, + strata=pd.Series(dtype="float64"), + params=node.params, + rng=np.random.default_rng(0), + sources={name: Path(path).resolve() for name, path in sources.items()}, + ) + ) + + +def _document( + name: str, + kernel_ref: str, + params, + sources, + donor: Path | None, + *, + node_id: str = "create", +) -> dict: + from microcosm.build.transport.codecs import load_populace_us_h5 + + result = run_create(kernel_ref, params, sources, node_id=node_id) + return { + "scenario": name, + "create": { + "kernel": kernel_ref, + "frame": frame_document(result.frame), + "receipt": result.receipt, + }, + "codec": None if donor is None else frame_document(load_populace_us_h5(donor)), + } + + +def _toy(root: Path, name: str) -> dict: + from microcosm.frame.unit_construction import MultiUnitRule + from test_support.microcosm_build.transport_graph import canonical_text + from test_support.microcosm_build.transport_population import ( + UNIT_RULE, + create_params, + digest, + write_population_sources, + ) + + edit = add_profile_columns if name == "toy_profile_columns" else None + sources = write_population_sources( + root / name, + edit_tables=edit, + time_period=2024 if edit is not None else None, + ) + params = create_params(sources) + kernel = "transport.create@1" + if name == "toy_v2": + declaration = MultiUnitRule.from_benefit_unit(UNIT_RULE).to_dict() + kernel = "transport.create@2" + params = { + **params, + "unit_rule": canonical_text(declaration), + "unit_rule_sha256": digest(declaration), + } + donor = None if name == "toy_v2" else sources.donor + return _document( + name, + kernel, + params, + {"donor": sources.donor, "facts": sources.facts}, + donor, + ) + + +def _composed(root: Path, name: str) -> dict: + from microcosm.build.transport.compose import skeleton_create_declaration + + if name == "composed": + from test_support.microcosm_build.transport_composed import ( + make_composed_fixture, + ) + + fixture = make_composed_fixture(root / name) + else: + from test_support.microcosm_build.transport_nz_toy import make_nz_toy_fixture + + fixture = make_nz_toy_fixture(root / name) + declaration = skeleton_create_declaration(fixture.spec) + sources = {source: fixture.sources[source] for source in declaration.sources} + donor = sources[declaration.params["donor_source"]] + # The composed graphs' own CREATE node id, as the CLI's probe uses it. + return _document( + name, + declaration.kernel, + declaration.params, + sources, + donor, + node_id=declaration.id, + ) + + +_BUILDERS: Mapping[str, Callable[[Path, str], dict]] = { + "toy": _toy, + "toy_v2": _toy, + "toy_profile_columns": _toy, + "composed": _composed, + "nz_toy": _composed, +} + + +def scenario_document(root: Path, name: str) -> dict: + """The CREATE and codec document of one scenario, built under ``root``.""" + return _BUILDERS[name](root, name) + + +def scenario_bytes(root: Path, name: str) -> bytes: + """The canonical bytes a scenario's fixture holds.""" + return canonical_json(scenario_document(root, name)) + + +def write_fixtures(directory: Path) -> dict[str, str]: + """Write every scenario's canonical bytes; return their SHA-256 digests.""" + directory.mkdir(parents=True, exist_ok=True) + digests = {} + with tempfile.TemporaryDirectory() as temporary: + for name in SCENARIOS: + payload = scenario_bytes(Path(temporary), name) + (directory / f"{name}.json").write_bytes(payload) + digests[name] = sha256(payload).hexdigest() + return digests + + +if __name__ == "__main__": # pragma: no cover - fixture capture entry point + for scenario, value in write_fixtures(Path(sys.argv[1])).items(): + print(f"{scenario} {value}") From 5479d1ae6b5c1e2203d10682969bf128e214f7bb Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 19 Nov 2026 23:51:56 +0000 Subject: [PATCH 2/6] Record the rebased base commit for the frozen CREATE baseline The five no-profile fixtures reproduce byte for byte on main 7ff5a26bc2 with the base commit's transport.py and population_kernels.py in place, so only the recorded base commit changes. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_transport_create_donor_profile.py | 2 +- .../tests/fixtures/transport_create_baseline/provenance.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_transport_create_donor_profile.py b/packages/microcosm-build/tests/engine_free/shared/test_transport_create_donor_profile.py index 8ecc9f8968..d9c61b5258 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_transport_create_donor_profile.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_transport_create_donor_profile.py @@ -68,7 +68,7 @@ from test_support.paths import paths_for BASELINE = paths_for("microcosm-build").tests / "fixtures/transport_create_baseline" -BASE_COMMIT = "cfd5a2a5ea8fbaa0269f434d10c50eb389eabc83" +BASE_COMMIT = "7ff5a26bc203c91a6f259d6efb62001aec0405a0" CHOICES = { "assisted_renter_tenure": "rented_public_authority", "blank_full_time_study": "read_false", diff --git a/packages/microcosm-build/tests/fixtures/transport_create_baseline/provenance.json b/packages/microcosm-build/tests/fixtures/transport_create_baseline/provenance.json index 86d5a0d21c..d57015598f 100644 --- a/packages/microcosm-build/tests/fixtures/transport_create_baseline/provenance.json +++ b/packages/microcosm-build/tests/fixtures/transport_create_baseline/provenance.json @@ -1,5 +1,5 @@ { - "base_commit": "cfd5a2a5ea8fbaa0269f434d10c50eb389eabc83", + "base_commit": "7ff5a26bc203c91a6f259d6efb62001aec0405a0", "capture_command": "python -m test_support.microcosm_build.transport_create_baseline packages/microcosm-build/tests/fixtures/transport_create_baseline", "capture_module": "test_support/microcosm_build/transport_create_baseline.py", "capture_module_sha256": "0743de62aa8208dbc00fc57a7e1bc43ad0e7f4d8a24786bc88ca31b489e300a0", From d456cedd4e87bb03a86edd04f062e152764460af Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 20 Nov 2026 07:30:20 +0000 Subject: [PATCH 3/6] Make the shared-module guards catch country codes and digest prefixes The two guard tests flagged only whole 64-hex digests, two country names and dotted node ids. One helper now reads a shared module's string constants and also flags bare country codes, such as a `country == "nz"` comparison or a country-keyed dict, and digest prefixes of eight or more hex characters. Tests plant each pattern and check ordinary strings pass. Co-Authored-By: Claude Fable 5.2 --- .../test_transport_create_donor_profile.py | 16 ++--- .../shared/test_transport_donor_profile.py | 50 ++++++++++++---- .../microcosm_frame/shared_source_literals.py | 58 +++++++++++++++++++ 3 files changed, 102 insertions(+), 22 deletions(-) create mode 100644 test_support/microcosm_frame/shared_source_literals.py diff --git a/packages/microcosm-build/tests/engine_free/shared/test_transport_create_donor_profile.py b/packages/microcosm-build/tests/engine_free/shared/test_transport_create_donor_profile.py index d9c61b5258..14af7ba310 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_transport_create_donor_profile.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_transport_create_donor_profile.py @@ -10,9 +10,7 @@ from __future__ import annotations -import ast import json -import re from functools import partial from hashlib import sha256 from pathlib import Path @@ -65,6 +63,9 @@ population_registry, write_population_sources, ) +from test_support.microcosm_frame.shared_source_literals import ( + country_or_digest_literals, +) from test_support.paths import paths_for BASELINE = paths_for("microcosm-build").tests / "fixtures/transport_create_baseline" @@ -508,13 +509,6 @@ def test_a_profile_on_a_donor_without_profile_answers_refuses(tmp_path): def test_create_names_no_country_node_id_or_donor_digest(): """CREATE selects a profile only through its param: its module holds no - country name, node id or donor digest literal.""" + country name or code, node id, or donor digest or digest prefix.""" source = Path(population_kernels_module.__file__).read_text() - strings = [ - node.value - for node in ast.walk(ast.parse(source)) - if isinstance(node, ast.Constant) and isinstance(node.value, str) - ] - assert not [s for s in strings if re.search(r"[0-9a-f]{64}", s)] - assert not [s for s in strings if re.search(r"(?i)zealand|belgi", s)] - assert not [s for s in strings if re.search(r"\b(nz|be|uk|us)\.[a-z_]", s)] + assert country_or_digest_literals(source) == [] diff --git a/packages/microcosm-frame/tests/engine_free/shared/test_transport_donor_profile.py b/packages/microcosm-frame/tests/engine_free/shared/test_transport_donor_profile.py index 62a548e475..51abfe1e68 100644 --- a/packages/microcosm-frame/tests/engine_free/shared/test_transport_donor_profile.py +++ b/packages/microcosm-frame/tests/engine_free/shared/test_transport_donor_profile.py @@ -7,7 +7,6 @@ against an independent oracle. No test opens a real donor. """ -import ast import itertools import json import re @@ -35,6 +34,9 @@ parse_donor_profile, read_populace_us_donor, ) +from test_support.microcosm_frame.shared_source_literals import ( + country_or_digest_literals, +) from test_support.paths import paths_for FIXTURE = paths_for("microcosm-frame").tests / "fixtures/transport/synthetic_donor.json" @@ -1327,16 +1329,42 @@ def test_assistance_must_be_boolean_with_no_nulls(assistance): def test_the_shared_reader_names_no_country_and_no_donor_digest(): - """No country name, node id or donor digest literal in the shared module.""" + """No country name or code, node id, or donor digest or digest prefix.""" source = Path(transport_module.__file__).read_text() - strings = [ - node.value - for node in ast.walk(ast.parse(source)) - if isinstance(node, ast.Constant) and isinstance(node.value, str) - ] - assert not [s for s in strings if re.search(r"[0-9a-f]{64}", s)] - assert not [s for s in strings if re.search(r"(?i)zealand|belgi", s)] - # A country-scoped node id such as "nz.create". - assert not [s for s in strings if re.search(r"\b(nz|be|uk|us)\.[a-z_]", s)] + assert country_or_digest_literals(source) == [] for name, _ in DONOR_PROFILE_CHOICES: assert not re.search(r"(?i)\b(nz|be|uk)\b", name) + + +@pytest.mark.parametrize( + "planted", + [ + 'chosen = country == "nz"', + 'BY_COUNTRY = {"be": 1}', + 'BY_COUNTRY = {"BE": 1, "us": 2}', + 'KNOWN = "48b9d479"', + 'KNOWN = "sha256:48B9D479FB"', + 'KNOWN = b"48b9d479fb4f"', + f'KNOWN = "{"a1" * 32}"', + 'NODE = "us.create"', + 'NOTE = "New Zealand rules"', + 'NOTE = f"{left}-uk-{right}"', + ], +) +def test_the_literal_guard_finds_a_planted_country_or_digest(planted): + assert country_or_digest_literals(planted) + + +@pytest.mark.parametrize( + "allowed", + [ + 'MESSAGE = "must be finite"', + 'ALPHABET = "0123456789abcdef"', + 'DONOR_COUNTRY = "us"', + 'NAME = "populace-us-cps-asec"', + 'DAY = "20260101"', + 'COLUMN = "A_ENRLW"', + ], +) +def test_the_literal_guard_passes_ordinary_strings(allowed): + assert country_or_digest_literals(allowed) == [] diff --git a/test_support/microcosm_frame/shared_source_literals.py b/test_support/microcosm_frame/shared_source_literals.py new file mode 100644 index 0000000000..875132b738 --- /dev/null +++ b/test_support/microcosm_frame/shared_source_literals.py @@ -0,0 +1,58 @@ +"""Find country and donor-digest literals in a shared module's source. + +A shared transport module selects donor behaviour through its parameters. It +holds no country name or code, no country-scoped node id, and no donor digest +or digest prefix, so no branch can key on one. +""" + +from __future__ import annotations + +import ast +import re + +# The hex alphabet is not a digest. +_HEX_ALPHABET = "0123456789abcdef" +# Eight or more hex characters holding a digit and a letter: a SHA-256, or a +# prefix of one long enough to name a file. +_DIGEST = re.compile( + r"(?i)(? list[str]: + """String constants in ``source`` that name a country or a digest. + + The donor's own country code, ``"us"``, is allowed: the donor is a US + survey, and the reader labels its strata with it. + """ + found = [] + for node in ast.walk(ast.parse(source)): + if not isinstance(node, ast.Constant): + continue + if isinstance(node.value, bytes): + text = node.value.decode("latin-1") + elif isinstance(node.value, str): + text = node.value + else: + continue + digests = [ + match.group(0) + for match in _DIGEST.finditer(text) + if match.group(0).lower() != _HEX_ALPHABET + ] + if ( + digests + or _COUNTRY_NAME.search(text) + or _COUNTRY_CODE.search(text) + or _BARE_CODE.fullmatch(text) + or _NODE_ID.search(text) + ): + found.append(text) + return found From dab5d58233ae48dda791943fa7de9afab8b21f3a Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 20 Nov 2026 18:38:26 +0000 Subject: [PATCH 4/6] Check donor-profile codes, costs and source years before they count Three reader fixes from the round-1 review of the donor-decoding profile: - Survey codes (A_MARITL, A_ENRLW, A_FTPT, H_TENURE) must have real integer or float storage, plain or pandas nullable. Each value is compared with each code in its own storage, so a complex 1+99j can no longer lose its imaginary part in a float cast and read as code 1. - Each housing cost is checked against its own concept's contract before tenure reconciliation, with the same validator and message as the reader without a profile. Under tenure_wins a negative cost in a contradicting household is refused instead of zeroed; under refuse the bound refuses before the contradiction count. Final validation still runs. - Source-year counts group on the year's text under the reader's lineage contract, so the integer 2022 and the string "2022" are one year and every blank answer is counted once, in the record and in the refusal. Tests go through the authenticated reader with pinned synthetic donors. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/frame/transport.py | 85 +++++--- .../shared/test_transport_donor_profile.py | 181 +++++++++++++++++- 2 files changed, 233 insertions(+), 33 deletions(-) diff --git a/packages/microcosm-frame/src/microcosm/frame/transport.py b/packages/microcosm-frame/src/microcosm/frame/transport.py index ebfa013be1..eac1d80f44 100644 --- a/packages/microcosm-frame/src/microcosm/frame/transport.py +++ b/packages/microcosm-frame/src/microcosm/frame/transport.py @@ -999,30 +999,31 @@ def _profile_codes( ) -> tuple[np.ndarray, np.ndarray]: """Whole-number survey codes, checked before any comparison reads them. - Returns the codes, with -1 where blank, and the blank mask. A blank - refuses unless ``missing_ok``; every other value must be a finite whole - number in ``allowed``. + Returns the codes, with -1 where blank, and the blank mask. The column + must have real integer or float storage, plain or pandas nullable; + boolean, complex and text storage refuse. A blank refuses unless + ``missing_ok``. Every other value must equal a code in ``allowed`` when + compared in its own storage, so no cast can turn it into a code first. """ - if pd.api.types.is_bool_dtype(values.dtype) or not pd.api.types.is_numeric_dtype( - values.dtype - ): - raise ValueError(f"Donor {values.name} must hold numeric survey codes.") - numbers = values.to_numpy(dtype=np.float64, na_value=np.nan) - blank = np.isnan(numbers) + if values.dtype.kind not in "iuf": + raise ValueError( + f"Donor {values.name} must hold numeric survey codes in real integer " + f"or float storage, found dtype {values.dtype}." + ) + blank = values.isna().to_numpy(dtype=bool) if blank.any() and not missing_ok: raise ValueError( f"Donor {values.name} has {int(blank.sum())} blank values, which this " "donor profile refuses." ) - present = numbers[~blank] - if ( - not np.isfinite(present).all() - or np.any(present != np.floor(present)) - or not np.isin(present, sorted(allowed)).all() - ): + codes = np.full(len(values), -1, dtype=np.int64) + matched = np.zeros(len(values), dtype=bool) + for code in sorted(allowed): + equal = (values == code).to_numpy(dtype=bool, na_value=False) + codes[equal] = code + matched |= equal + if np.any(~blank & ~matched): raise ValueError(f"Donor {values.name} holds codes outside {sorted(allowed)}.") - codes = np.full(len(numbers), -1, dtype=np.int64) - codes[~blank] = present.astype(np.int64) return codes, blank @@ -1051,15 +1052,26 @@ def _profile_ids(values: pd.Series) -> np.ndarray: return values.to_numpy(dtype=np.int64) -def _by_source_year(person: pd.DataFrame, mask: np.ndarray) -> dict[str, int]: - """Counts of ``mask`` for each donor source year, zeros included.""" +def _source_years(person: pd.DataFrame) -> np.ndarray | None: + """Each person's source year as its receipt key, or ``None`` if unrecorded. + + The key is the year's text under the lineage contract that the reader + already applies to this column (:func:`_source_id_payloads`): an exact + integer's decimal digits, or the nonempty string itself. Counts group on + this key, so an integer year and the same year spelled as a string are + one year, and every person is counted once. + """ if "source_year" not in person: + return None + payloads = _source_id_payloads(person["source_year"]) + return np.asarray([text for _, text in payloads], dtype=object) + + +def _by_source_year(years: np.ndarray | None, mask: np.ndarray) -> dict[str, int]: + """Counts of ``mask`` for each source year key, zeros included.""" + if years is None: return {"unrecorded": int(mask.sum())} - counts = ( - pd.Series(mask.astype(np.int64)) - .groupby(person["source_year"].to_numpy(), dropna=False, sort=True) - .sum() - ) + counts = pd.Series(mask.astype(np.int64)).groupby(years, sort=True).sum() return {str(year): int(count) for year, count in counts.items()} @@ -1117,10 +1129,11 @@ def _stage_donor_profile( person["A_FTPT"], _ENROLLMENT_CODES, missing_ok=True ) blank = enrolled_blank | full_time_blank + years = _source_years(person) if blank.any() and not read_false: raise ValueError( "Donor A_ENRLW or A_FTPT is blank for persons by source year " - f"{_by_source_year(person, blank)}, which this donor profile refuses." + f"{_by_source_year(years, blank)}, which this donor profile refuses." ) unit_ids = pd.Index(_profile_ids(spm_unit["spm_unit_id"])) member_ids = _profile_ids(person["person_spm_unit_id"]) @@ -1236,9 +1249,9 @@ def _stage_donor_profile( }, "full_time_study": { "enrolled_full_time": int(((enrolled == 1) & (full_time == 1)).sum()), - "blank_a_enrlw_by_source_year": _by_source_year(person, enrolled_blank), - "blank_a_ftpt_by_source_year": _by_source_year(person, full_time_blank), - "read_false_by_source_year": _by_source_year(person, blank), + "blank_a_enrlw_by_source_year": _by_source_year(years, enrolled_blank), + "blank_a_ftpt_by_source_year": _by_source_year(years, full_time_blank), + "read_false_by_source_year": _by_source_year(years, blank), }, "legal_marital_status": { value: int((statuses == value).sum()) for value in MARITAL_STATUS_DOMAIN @@ -1290,6 +1303,20 @@ def _attach_donor_profile( tenure = staged["tenure"][household_rows] household_weights = np.asarray(weights, dtype=np.float64)[household_rows] refuse = profile.choices["housing_cost_contradicting_tenure"] == "refuse" + # Each cost must meet its own concept's contract (dtype, nulls, finite, + # bounds) before reconciliation reads or zeroes it, so the record never + # counts, and tenure never hides, an amount the reader refuses without a + # profile. The tenure rules come after; final validation still runs. + costs = [column for column, _ in _TENURE_COSTS if column in household_table] + violations = validate_concept_tables( + { + "person": person_table[[PERSON_ID_COLUMN, PERSON_HOUSEHOLD_ID_COLUMN]], + "household": household_table[[HOUSEHOLD_ID_COLUMN, *costs]], + } + ) + if violations: + details = "; ".join(f"{v.entity}.{v.column}: {v.message}" for v in violations) + raise ValueError(f"Invalid donor concepts: {details}") reconciliation: dict[str, dict] = {} contradicted: dict[str, int] = {} reconciled: dict[str, np.ndarray] = {} @@ -1298,8 +1325,6 @@ def _attach_donor_profile( reconciliation[column] = {"column": "absent"} continue amounts = household_table[column].to_numpy(dtype=np.float64, copy=True) - if not np.isfinite(amounts).all(): - raise ValueError(f"Donor {column} must be finite before reconciliation.") contradicting = ~np.isin(tenure, payers) & (amounts != 0) count = int(contradicting.sum()) reconciliation[column] = { diff --git a/packages/microcosm-frame/tests/engine_free/shared/test_transport_donor_profile.py b/packages/microcosm-frame/tests/engine_free/shared/test_transport_donor_profile.py index 51abfe1e68..40aaf45ce5 100644 --- a/packages/microcosm-frame/tests/engine_free/shared/test_transport_donor_profile.py +++ b/packages/microcosm-frame/tests/engine_free/shared/test_transport_donor_profile.py @@ -125,10 +125,12 @@ def _raw_tables() -> dict[str, pd.DataFrame]: return tables -def _write(path: Path, tables: dict[str, pd.DataFrame]) -> dict: +def _write(path: Path, tables: dict[str, pd.DataFrame], *, fixed=()) -> dict: + """Write and pin a donor. Tables named in ``fixed`` use PyTables' fixed + format, which can hold an object column of mixed types.""" with pd.HDFStore(path, mode="w") as store: for name, table in tables.items(): - store.put(name, table, format="table") + store.put(name, table, format="fixed" if name in fixed else "table") return { "sha256": sha256(path.read_bytes()).hexdigest(), "size": path.stat().st_size, @@ -495,6 +497,41 @@ def test_refuse_accepts_a_donor_with_no_blank_answers(tmp_path): } +@pytest.mark.filterwarnings("ignore::pandas.errors.PerformanceWarning") +def test_an_integer_year_and_its_string_spelling_count_as_one_year(tmp_path): + """The lineage contract admits an exact integer or a nonempty string as a + source year, so one donor can spell 2022 both ways. The counts key each + year by its text and count every blank answer once, in the record and in + the refusal.""" + tables = _raw_tables() + # One spelling per household, as lineage requires. + tables["person"]["source_year"] = pd.Series( + [2022, 2022, 2022, "2022", "2022", "2022"], dtype=object + ) + tables["person"]["A_ENRLW"] = [np.nan, 1.0, 1.0, np.nan, 0.0, 1.0] + tables["person"]["A_FTPT"] = [np.nan, 1.0, 1.0, np.nan, 0.0, 2.0] + path = tmp_path / "donor.h5" + pin = _write(path, tables, fixed={"person"}) + with pd.HDFStore(path, mode="r") as store: + stored = store["person"]["source_year"].tolist() + assert [type(value) for value in stored] == [int] * 3 + [str] * 3 + donor = read_populace_us_donor( + path, **pin, profile=_profile(pin["sha256"], blank_full_time_study="read_false") + ) + assert donor.donor_profile["full_time_study"] == { + "enrolled_full_time": 2, + "blank_a_enrlw_by_source_year": {"2022": 2}, + "blank_a_ftpt_by_source_year": {"2022": 2}, + "read_false_by_source_year": {"2022": 2}, + } + with pytest.raises( + ValueError, match=r"by source year \{'2022': 2\}, which this donor profile" + ): + read_populace_us_donor( + path, **pin, profile=_profile(pin["sha256"], blank_full_time_study="refuse") + ) + + def test_tenure_wins_zeroes_contradicting_costs_and_refuse_refuses_them(tmp_path): donor = _read(tmp_path, housing_cost_contradicting_tenure="tenure_wins") assert donor.tables["household"]["rent"].tolist() == [0.0, 0.0] @@ -520,6 +557,46 @@ def test_refuse_keeps_costs_that_agree_with_tenure(tmp_path): assert rent["zeroed"] is False +@pytest.mark.parametrize("choice", OFFERED["housing_cost_contradicting_tenure"]) +@pytest.mark.parametrize( + ("column", "values", "violation"), + [ + # Owner household 101 carries a negative rent. + ( + "pre_subsidy_rent", + [-12.0, 0.0, 0.0, 0.0, 0.0, 0.0], + "household.rent: rent is below 0.0.", + ), + # Renter household 202 carries negative mortgage interest. + ( + "home_mortgage_interest", + [12.0, 0.0, 0.0, -5.0, 0.0, 0.0], + "household.mortgage_interest: mortgage_interest is below 0.0.", + ), + ], +) +def test_a_cost_below_its_bound_refuses_as_without_a_profile( + tmp_path, column, values, violation, choice +): + """A cost that contradicts tenure is checked against its own concept's + bounds before reconciliation, so ``tenure_wins`` cannot zero it out of + sight. Under ``refuse`` the bound refuses first: the amount is invalid + whatever the tenure, and the reader without a profile refuses it with + the same message.""" + tables = _raw_tables() + tables["person"][column] = values + path = tmp_path / "donor.h5" + pin = _write(path, tables) + message = f"Invalid donor concepts: {violation}" + with pytest.raises(ValueError) as plain: + read_populace_us_donor(path, **pin) + assert str(plain.value) == message + profile = _profile(pin["sha256"], housing_cost_contradicting_tenure=choice) + with pytest.raises(ValueError) as profiled: + read_populace_us_donor(path, **pin, profile=profile) + assert str(profiled.value) == message + + def test_a_profile_naming_other_bytes_refuses_before_the_file_is_opened( tmp_path, monkeypatch ): @@ -617,9 +694,27 @@ def edit(tables): _set("spm_unit", "spm_unit_tenure_type", ["RENTER", "RENTER", "RENTER"]), "owner households have SPM renter tenure", ), + # The cost's own concept check refuses before reconciliation reads it. ( _set("person", "pre_subsidy_rent", [np.inf, 0, 0, 0, 0, 0]), - "rent must be finite before reconciliation", + r"Invalid donor concepts: household\.rent: rent must be finite\.", + ), + # Complex storage refuses in the id, label and assistance checks too. + ( + _set("spm_unit", "spm_unit_id", np.array([11, 21, 22], dtype=complex)), + "integer ids", + ), + ( + _set("household", "tenure_type", np.array([1, 2], dtype=complex)), + "labels outside", + ), + ( + _set( + "spm_unit", + "receives_housing_assistance", + np.array([0, 0, 1], dtype=complex), + ), + "must be boolean", ), ], ) @@ -650,6 +745,35 @@ def test_raw_checks_fire_before_any_comparison_reads_the_value(tmp_path, edit, m _read(tmp_path, _edited(edit)) +@pytest.mark.parametrize("imaginary", [99.0, 0.0]) +@pytest.mark.parametrize( + ("table", "column"), + [ + ("person", "A_MARITL"), + ("person", "A_ENRLW"), + ("person", "A_FTPT"), + ("household", "H_TENURE"), + ], +) +def test_a_complex_survey_code_refuses_through_the_reader( + tmp_path, table, column, imaginary +): + """Complex storage refuses whatever its values. A cast to float would + drop ``1+99j`` onto the valid code 1 before any check saw it.""" + tables = _raw_tables() + values = tables[table][column].to_numpy(dtype=np.float64).astype(complex) + values[0] += 1j * imaginary + tables[table][column] = values + path = tmp_path / "donor.h5" + pin = _write(path, tables) + with pd.HDFStore(path, mode="r") as store: + assert store[table][column].dtype.kind == "c" + with pytest.raises( + ValueError, match=rf"{column} must hold numeric survey codes in real" + ): + read_populace_us_donor(path, **pin, profile=_profile(pin["sha256"])) + + def test_a_memberless_spm_unit_is_counted_and_stages_nothing(tmp_path): """A unit with no member reaches no household, so it cannot change a staged value: the reader counts it rather than refusing it.""" @@ -1301,6 +1425,57 @@ def test_survey_codes_refuse_anything_outside_the_codebook(values, missing_ok): ] +@pytest.mark.parametrize( + "values", + [ + pd.Series([1, 2, 3], dtype="int8"), + pd.Series([3, 1, 2], dtype="uint64"), + pd.Series([1.0, 2.0, 3.0], dtype="float32"), + pd.Series([1, None, 3], dtype="Int64"), + pd.Series([2.0, None, 1.0], dtype="Float64"), + ], + ids=lambda values: str(values.dtype), +) +def test_survey_codes_read_from_real_integer_or_float_storage(values): + codes, blank = transport_module._profile_codes( + values.rename("A_TEST"), frozenset({1, 2, 3}), missing_ok=True + ) + assert blank.tolist() == values.isna().tolist() + assert codes.tolist() == [-1 if pd.isna(v) else int(v) for v in values] + + +@pytest.mark.parametrize( + "values", + [ + pd.Series([1 + 99j, 2, 3]), + pd.Series([1 + 0j, 2, 3]), + pd.Series([True, False, True]), + pd.Series([True, None, True], dtype="boolean"), + pd.Series([1, 2, 3], dtype=object), + pd.Series(["1", "2", "3"], dtype="string"), + ], + ids=lambda values: str(values.dtype), +) +def test_survey_codes_refuse_storage_that_is_not_real_numbers(values): + with pytest.raises(ValueError, match="A_TEST must hold numeric survey codes"): + transport_module._profile_codes( + values.rename("A_TEST"), frozenset({1, 2, 3}), missing_ok=True + ) + + +def test_survey_codes_compare_in_their_own_storage(): + """An integer next to a code is never rounded onto it: 2**53 + 1 is + compared as an integer, where a float cast would read 2**53.""" + big = 2**53 + values = pd.Series([big + 1, 1], dtype="int64", name="A_TEST") + with pytest.raises(ValueError, match="A_TEST holds codes outside"): + transport_module._profile_codes(values, frozenset({big, 1})) + codes, _ = transport_module._profile_codes( + pd.Series([big, 1], dtype="int64", name="A_TEST"), frozenset({big, 1}) + ) + assert codes.tolist() == [big, 1] + + @pytest.mark.parametrize("missing", [None, np.nan, pd.NA, 3]) def test_a_missing_or_non_text_label_refuses(missing): values = pd.Series(["RENTED", missing], name="tenure_type", dtype=object) From 326215fe3d473c2a2b68f98bf2da88342a3fc0d6 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 20 Nov 2026 18:41:51 +0000 Subject: [PATCH 5/6] Widen the shared-module literal guard and correct coverage wording - The term-7 literal guard flags any hex run of 64 or more characters, hex runs of eight or more that hold a letter (all-letter runs included), node ids in any letter case, and "gb" only as a whole string. Its docstring calls it a heuristic and lists what it misses. The planted and ordinary cases cover the round-1 review's examples. - The frozen-baseline provenance and capture module say that toy_v2 holds no codec frame; the capture module's SHA-256 is updated, and the five fixture files are unchanged. - The changelog and ADR say the battery refuses stale support-bounds evidence when it is supplied to it, and that an ordinary graph run re-keys the producer and runs it again. Co-Authored-By: Claude Opus 5.5 --- changelog.d/donor-decoding-profile.added.md | 2 +- docs/concept-schema-transport-adr.md | 36 ++++++------ .../transport_create_baseline/provenance.json | 4 +- .../shared/test_transport_donor_profile.py | 20 +++++++ .../transport_create_baseline.py | 11 ++-- .../microcosm_frame/shared_source_literals.py | 57 +++++++++++++------ 6 files changed, 89 insertions(+), 41 deletions(-) diff --git a/changelog.d/donor-decoding-profile.added.md b/changelog.d/donor-decoding-profile.added.md index fe9e1e2cf1..12dbaa754e 100644 --- a/changelog.d/donor-decoding-profile.added.md +++ b/changelog.d/donor-decoding-profile.added.md @@ -1,3 +1,3 @@ Transport CREATE (`transport.create@1` and `@2`) accepts an optional `donor_profile` parameter: a canonical JSON document that selects a versioned donor-decoding profile and states each of its choices. The first profile, `populace-us-cps-asec` version 1, stages household tenure, legal marital status and full-time study from the donor's raw survey answers and SPM units, refuses a document written for other donor bytes, and records its counts in CREATE's receipt. No graph selects a profile in this change, and a graph that sets none keeps its CREATE frame and receipt bytes. -The change edits `microcosm/frame/transport.py` and `microcosm/build/transport/population_kernels.py`, so seven kernel refs move once: `transport.create@1`, `transport.create@2`, `transport.currency@1`, `transport.quantile_map@1`, `transport.quantile_map@2`, `transport.support_bounds@1` and `transport.boundary@1`. Their implementation hashes change, so the node records of these kernels and of every node downstream of them re-key, and those nodes run again. A stored CREATE inventory stops matching, because its store key includes CREATE's implementation hash (`transport/cli.py`). Stored support-bounds evidence is refused, not rebuilt: it records its producer's implementation hash, and the battery's header check refuses evidence whose hash differs from this build's (`transport/evidence_contract.py`). `gates.battery@1` does not move, and no committed digest moves. +The change edits `microcosm/frame/transport.py` and `microcosm/build/transport/population_kernels.py`, so seven kernel refs move once: `transport.create@1`, `transport.create@2`, `transport.currency@1`, `transport.quantile_map@1`, `transport.quantile_map@2`, `transport.support_bounds@1` and `transport.boundary@1`. Their implementation hashes change, so the node records of these kernels and of every node downstream of them re-key, and those nodes run again. A stored CREATE inventory stops matching, because its store key includes CREATE's implementation hash (`transport/cli.py`). Support-bounds evidence records its producer's implementation hash, so the battery's header check refuses evidence stored before this change when that evidence is supplied to it (`transport/evidence_contract.py`). An ordinary graph run does not supply it: the producer's node key includes the new hash, so the executor misses its cache and runs the producer again (`graph/executor.py`). `gates.battery@1` does not move, and no committed digest moves. diff --git a/docs/concept-schema-transport-adr.md b/docs/concept-schema-transport-adr.md index 57cdd23611..ffaa0517be 100644 --- a/docs/concept-schema-transport-adr.md +++ b/docs/concept-schema-transport-adr.md @@ -428,26 +428,30 @@ These hold for every input and are tested (Hypothesis properties unless noted): tenure and housing assistance, person `legal_marital_status` from `A_MARITL`, and person `enrolled_full_time` from `A_ENRLW` and `A_FTPT`. The reader refuses a document whose `donor_sha256` names other bytes - before it opens the file. It checks the raw codes and the SPM joins before - decoding, and it reconciles rent and mortgage costs with the staged tenure - before concept validation. CREATE's receipt records the document's digest, - its choices and the staging counts under `donor_profile`. A graph that sets - no profile reads what it read before (the person and household tables and - the `_time_period` series) and never the `spm_unit` table, and its CREATE - frame and receipt keep the bytes captured at the commit before this change. - No graph selects a profile when the parameter lands. The parameter still - moves seven kernel refs once, because it edits the reader's module and - CREATE's module: `transport.create@1` and `@2`, `transport.currency@1`, + before it opens the file. It checks the raw codes, in their own integer or + float storage, and the SPM joins before decoding. It checks each rent and + mortgage cost against its own concept's contract, then reconciles the + costs with the staged tenure, and then validates the whole frame. CREATE's + receipt records the document's digest, its choices and the staging counts + under `donor_profile`. A graph that sets no profile reads what it read + before (the person and household tables and the `_time_period` series) + and never the `spm_unit` table, and its CREATE frame and receipt keep the + bytes captured at the commit before this change. No graph selects a + profile when the parameter lands. The parameter still moves seven kernel + refs once, because it edits the reader's module and CREATE's module: + `transport.create@1` and `@2`, `transport.currency@1`, `transport.quantile_map@1` and `@2`, `transport.support_bounds@1` and `transport.boundary@1`. The node records of these kernels and of every node downstream of them re-key. A stored CREATE inventory stops matching, because its store key includes CREATE's implementation hash. The battery - refuses stored support-bounds evidence that records the old implementation - hash; it does not rebuild it. `gates.battery@1` does not move, and no - committed digest moves. A choice value the closed sets do not offer needs a - further edit to the reader's module, which moves every one of these refs - again except `transport.boundary@1`, whose hash reads CREATE's module but - not the reader's. + refuses support-bounds evidence that records the old implementation hash + when that evidence is supplied to it. An ordinary graph run does not + supply it: the producer's node key includes the new hash, so the executor + misses its cache and runs the producer again. `gates.battery@1` does not + move, and no committed digest moves. A choice value the closed sets do not + offer needs a further edit to the reader's module, which moves every one + of these refs again except `transport.boundary@1`, whose hash reads + CREATE's module but not the reader's. - The consuming builder supplies the destination frame declaration after transport. New Zealand's group bindings now execute on benefit units built from the concept pointers. Belgium's 39 `person_role` bindings on `Child` diff --git a/packages/microcosm-build/tests/fixtures/transport_create_baseline/provenance.json b/packages/microcosm-build/tests/fixtures/transport_create_baseline/provenance.json index d57015598f..24be771dd9 100644 --- a/packages/microcosm-build/tests/fixtures/transport_create_baseline/provenance.json +++ b/packages/microcosm-build/tests/fixtures/transport_create_baseline/provenance.json @@ -2,7 +2,7 @@ "base_commit": "7ff5a26bc203c91a6f259d6efb62001aec0405a0", "capture_command": "python -m test_support.microcosm_build.transport_create_baseline packages/microcosm-build/tests/fixtures/transport_create_baseline", "capture_module": "test_support/microcosm_build/transport_create_baseline.py", - "capture_module_sha256": "0743de62aa8208dbc00fc57a7e1bc43ad0e7f4d8a24786bc88ca31b489e300a0", + "capture_module_sha256": "6861491acb7dc8afade146561374956d8cdef42920b457f8c8206e26308febcc", "captured": "2026-11-19", "environment": { "numpy": "2.4.6", @@ -21,5 +21,5 @@ "kind": "transport_create_no_profile_baseline", "reproduction": "The capture module with this SHA-256, run with the base commit's microcosm/frame/transport.py and microcosm/build/transport/population_kernels.py in place of the edited ones, writes every file listed here byte for byte.", "schema_version": 1, - "scope": "Captured on the unedited base commit, before CREATE accepted a donor_profile. Each file holds the canonical bytes of transport.create's frame and receipt on its declared params and sources, and of the populace-us-h5-v1 codec's frame, for one toy donor or composed toy graph. No file holds real donor data." + "scope": "Captured on the unedited base commit, before CREATE accepted a donor_profile. Each file holds the canonical bytes of transport.create's frame and receipt on its declared params and sources, for one toy donor or composed toy graph. Four files (toy, toy_profile_columns, composed and nz_toy) also hold the populace-us-h5-v1 codec's frame of the same donor. toy_v2 runs transport.create@2 on a donor written by the same call as toy's, and its codec field is null. No file holds real donor data." } diff --git a/packages/microcosm-frame/tests/engine_free/shared/test_transport_donor_profile.py b/packages/microcosm-frame/tests/engine_free/shared/test_transport_donor_profile.py index 40aaf45ce5..39ec7f1e78 100644 --- a/packages/microcosm-frame/tests/engine_free/shared/test_transport_donor_profile.py +++ b/packages/microcosm-frame/tests/engine_free/shared/test_transport_donor_profile.py @@ -1524,6 +1524,18 @@ def test_the_shared_reader_names_no_country_and_no_donor_digest(): 'NODE = "us.create"', 'NOTE = "New Zealand rules"', 'NOTE = f"{left}-uk-{right}"', + # Node ids in any letter case. + 'NODE = "BE.create"', + 'NODE = "Nz.create"', + # A hex run of eight or more letters, and a 64-character run of + # digits or of letters alone. + 'KNOWN = "deadbeef"', + f'KNOWN = "{"1" * 64}"', + f'KNOWN = "{"ab" * 32}"', + # "gb" as a whole string, and "gbr" anywhere. + 'COUNTRY = "GB"', + 'COUNTRY = "gb"', + 'NOTE = "GBR rules"', ], ) def test_the_literal_guard_finds_a_planted_country_or_digest(planted): @@ -1539,6 +1551,14 @@ def test_the_literal_guard_finds_a_planted_country_or_digest(planted): 'NAME = "populace-us-cps-asec"', 'DAY = "20260101"', 'COLUMN = "A_ENRLW"', + # Runs of fewer than 64 digits are dates and counts. + 'COUNT = "12345678"', + f'COUNT = "{"9" * 63}"', + # "GB" in prose is a unit. + 'NOTE = "Memory budget of 32 GB"', + # The donor's own code passes, even in a branch: the module + # docstring names this as something the heuristic does not catch. + 'chosen = country == "us"', ], ) def test_the_literal_guard_passes_ordinary_strings(allowed): diff --git a/test_support/microcosm_build/transport_create_baseline.py b/test_support/microcosm_build/transport_create_baseline.py index 7e4ae0551c..ac1d49a82f 100644 --- a/test_support/microcosm_build/transport_create_baseline.py +++ b/test_support/microcosm_build/transport_create_baseline.py @@ -1,9 +1,12 @@ """Frozen CREATE baselines: canonical bytes with no donor profile set. -Each scenario builds a toy donor or a composed toy graph, runs CREATE on its -declared parameters and sources, and loads the same donor through the donor -codec. :func:`scenario_bytes` returns the canonical bytes of CREATE's frame -and receipt and of the codec's frame. The committed fixtures under +Each scenario builds a toy donor or a composed toy graph and runs CREATE on +its declared parameters and sources. Every scenario except ``toy_v2`` also +loads the same donor through the donor codec; ``toy_v2`` runs +``transport.create@2`` on a donor written by the same call as ``toy``'s, and +its ``codec`` field is null. :func:`scenario_bytes` returns the canonical +bytes of CREATE's frame and receipt and, where the scenario loads it, of the +codec's frame. The committed fixtures under ``packages/microcosm-build/tests/fixtures/transport_create_baseline/`` were captured at the commit their provenance file names, before CREATE accepted a donor profile, so a test that recomputes them shows that a graph setting no diff --git a/test_support/microcosm_frame/shared_source_literals.py b/test_support/microcosm_frame/shared_source_literals.py index 875132b738..3ac29c4c82 100644 --- a/test_support/microcosm_frame/shared_source_literals.py +++ b/test_support/microcosm_frame/shared_source_literals.py @@ -3,6 +3,26 @@ A shared transport module selects donor behaviour through its parameters. It holds no country name or code, no country-scoped node id, and no donor digest or digest prefix, so no branch can key on one. + +The check is a heuristic over the module's string and bytes constants +(f-string parts included). It flags a string that holds: + +- a country name (Zealand, Belgium), anywhere; +- the code ``nz``, ``nzl``, ``bel``, ``uk`` or ``gbr`` standing alone, or + ``be`` or ``gb`` as the whole string (both are also English, as in "must + be" and "32 GB"); +- a country-scoped node id such as ``nz.create``, in any letter case; +- a run of hex characters 64 or more long, whatever its composition, or 8 or + more long with at least one letter, except the hex alphabet itself. + +It does not catch a branch on the donor's own code, ``"us"``, which it allows +because the donor is a US survey and the reader labels its strata with it. It +passes runs of fewer than 64 digits (dates and counts look like them), so a +digest prefix made only of digits passes, as does any prefix shorter than +eight characters. It does not see a literal assembled at run time from +shorter parts or read from a parameter or file, a name in an identifier, +comment or non-string constant, ``be`` or ``gb`` inside a longer string, or a +country named in another language or by a numeric code. """ from __future__ import annotations @@ -12,25 +32,31 @@ # The hex alphabet is not a digest. _HEX_ALPHABET = "0123456789abcdef" -# Eight or more hex characters holding a digit and a letter: a SHA-256, or a -# prefix of one long enough to name a file. -_DIGEST = re.compile( - r"(?i)(? bool: + """Whether a hex run could be a digest, or a prefix long enough to name + a file. Runs of fewer than 64 digits are dates and counts.""" + if run.lower() == _HEX_ALPHABET: + return False + return len(run) >= _SHA256_LENGTH or not run.isdigit() def country_or_digest_literals(source: str) -> list[str]: """String constants in ``source`` that name a country or a digest. - The donor's own country code, ``"us"``, is allowed: the donor is a US - survey, and the reader labels its strata with it. + The module docstring says what the check flags and what it misses. """ found = [] for node in ast.walk(ast.parse(source)): @@ -42,13 +68,8 @@ def country_or_digest_literals(source: str) -> list[str]: text = node.value else: continue - digests = [ - match.group(0) - for match in _DIGEST.finditer(text) - if match.group(0).lower() != _HEX_ALPHABET - ] if ( - digests + any(_digest_like(match.group(0)) for match in _HEX_RUN.finditer(text)) or _COUNTRY_NAME.search(text) or _COUNTRY_CODE.search(text) or _BARE_CODE.fullmatch(text) From 155ec5de2ebc40659d81e309d27b6ac9044d6fdd Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 20 Nov 2026 23:11:57 +0000 Subject: [PATCH 6/6] Flag more country names in the shared-module literal guard The guard now also flags United Kingdom (joined by spaces, hyphens, underscores or nothing), Britain, British, England, Scotland and Aotearoa, in any letter case. Both production modules still return no literal at this head and at base 7ff5a26bc2. The planted-literal test gains one case for each new name. The module docstring lists exactly what flags; "us" and digit-only runs stay documented exceptions. Co-Authored-By: Claude Opus 5.5 --- .../shared/test_transport_donor_profile.py | 8 ++++++++ .../microcosm_frame/shared_source_literals.py | 16 ++++++++++++---- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/packages/microcosm-frame/tests/engine_free/shared/test_transport_donor_profile.py b/packages/microcosm-frame/tests/engine_free/shared/test_transport_donor_profile.py index 39ec7f1e78..0df96e3e15 100644 --- a/packages/microcosm-frame/tests/engine_free/shared/test_transport_donor_profile.py +++ b/packages/microcosm-frame/tests/engine_free/shared/test_transport_donor_profile.py @@ -1536,6 +1536,14 @@ def test_the_shared_reader_names_no_country_and_no_donor_digest(): 'COUNTRY = "GB"', 'COUNTRY = "gb"', 'NOTE = "GBR rules"', + # Other names for the countries the guard watches, in any case. + 'NOTE = "United Kingdom rules"', + 'KEY = "united_kingdom"', + 'NOTE = "Britain"', + 'NOTE = "british"', + 'NOTE = "England"', + 'NOTE = "SCOTLAND"', + 'NOTE = "Aotearoa"', ], ) def test_the_literal_guard_finds_a_planted_country_or_digest(planted): diff --git a/test_support/microcosm_frame/shared_source_literals.py b/test_support/microcosm_frame/shared_source_literals.py index 3ac29c4c82..8548641ac6 100644 --- a/test_support/microcosm_frame/shared_source_literals.py +++ b/test_support/microcosm_frame/shared_source_literals.py @@ -7,7 +7,11 @@ The check is a heuristic over the module's string and bytes constants (f-string parts included). It flags a string that holds: -- a country name (Zealand, Belgium), anywhere; +- one of these country names or parts of names, in any letter case, + anywhere in the string: ``zealand``, ``belgi`` (Belgium, Belgian), + ``united kingdom`` (with a space, hyphen, underscore or nothing between + the words), ``britain``, ``british``, ``england``, ``scotland`` or + ``aotearoa``; - the code ``nz``, ``nzl``, ``bel``, ``uk`` or ``gbr`` standing alone, or ``be`` or ``gb`` as the whole string (both are also English, as in "must be" and "32 GB"); @@ -21,8 +25,9 @@ digest prefix made only of digits passes, as does any prefix shorter than eight characters. It does not see a literal assembled at run time from shorter parts or read from a parameter or file, a name in an identifier, -comment or non-string constant, ``be`` or ``gb`` inside a longer string, or a -country named in another language or by a numeric code. +comment or non-string constant, ``be`` or ``gb`` inside a longer string, any +country name or spelling not listed above (Wales, Canada, a French or German +name for New Zealand), or a country named by a numeric code. """ from __future__ import annotations @@ -36,7 +41,10 @@ _HEX_RUN = re.compile(r"(?i)(?