From b56bdaa5ae2ce118896a78327fc7b1315a3a3f99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:42:26 +0000 Subject: [PATCH 01/30] Add a shared reader and selector for declared target sets microcosm.calibrate.target_sets reads one country's declarations of what each product calibrates to. For each product and mode, a declaration has compiled clauses (families, levels, metadata tests, named exclusions, a named rule) and the rows the tool builds itself, each with a rationale. select_target_set keeps each clause's specs in compile order, clause by clause in declaration order. The module holds no country code: a country passes its named predicates and rules. A target's family and level are the labels the shared target-loss rule reads (microcosm#1729). Part of microcosm#1728. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/calibrate/target_sets.py | 625 ++++++++++++++++++ .../engine_free/shared/test_target_sets.py | 362 ++++++++++ 2 files changed, 987 insertions(+) create mode 100644 packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py create mode 100644 packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py b/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py new file mode 100644 index 0000000000..2a0947606b --- /dev/null +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py @@ -0,0 +1,625 @@ +"""Declared target sets: which compiled targets a product calibrates to. + +A release tool calibrates to a subset of the targets its country compiles. +Each country declares that subset as data, for each product and mode: the +families, the levels and the rule. This module reads the declarations and +selects by them (microcosm#1728). It holds no country code: a country passes +the named predicates and rules its declarations use as callables. + +A declaration file has this form:: + + { + "version": 1, + "country": "", + "level_keys": ["", ...], + "products": { + "": { + "tool": "", + "option": "", + "default_mode": "", + "modes": { + "": { + "description": "", + "compiled": [, ...], + "built": [, ...] + } + } + } + } + } + +**Families and levels.** A target's family is ``spec.family``. Its level is +the first truthy value of the ``level_keys`` in its metadata, else +``"unspecified"``. These are the labels the shared target-loss rule reads +(``microcosm.calibrate.target_loss_rules``, microcosm#1729), so a target has +one family and one level everywhere. + +**Compiled clauses.** A clause keeps the compiled specs that pass all of its +tests, in compile order: + +- ``families``: family names, or ``"*"`` for any family; +- ``levels``: level names, or ``"*"`` for any level; +- ``metadata`` (optional): one test for each named key, one of + ``{"present": true}`` (the key is in the metadata), ``{"equals": v}``, + ``{"not_equals": v}`` (a missing key is not equal), or + ``{"not_prefix": "text"}`` (the key holds a nonempty string that does not + start with ``text``); +- ``exclude`` (optional): names of country predicates; a spec that any of + them accepts is dropped; +- ``rule`` (optional): the name of a country rule. It takes the clause's + specs and returns the specs it keeps (for example a reconciliation) and a + receipt. + +Each clause has an ``id``. A tool can turn on only some clauses by id (for +example from a ``--families`` option). The selection is the output of each +clause in declaration order. A spec that two clauses keep is an error in the +declaration. + +**Built rows.** A tool also makes rows that are not compiled (for example +population marginals from a ladder). A ``built`` entry names their family and +the level that each value of its option gives, so that the declaration states +the whole target set. The selector does not make these rows. + +**Rationale.** Each clause and built entry has a ``rationale``: why the +product keeps those rows. The UK membership files give a signed rationale for +each exclusion in the same way. +""" + +from __future__ import annotations + +import json +from collections import Counter +from collections.abc import Callable, Iterable, Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path +from types import MappingProxyType +from typing import Any + +__all__ = [ + "ANY", + "DECLARATION_VERSION", + "UNSPECIFIED_LEVEL", + "BuiltRows", + "MetadataTest", + "ProductDeclaration", + "TargetSetClause", + "TargetSetDeclaration", + "TargetSetDeclarationError", + "TargetSetDeclarations", + "TargetSetSelection", + "clause_predicate", + "load_target_set_declarations", + "select_target_set", + "target_level", + "target_set_census", + "undeclared_cells", +] + +ANY = "*" +DECLARATION_VERSION = 1 +UNSPECIFIED_LEVEL = "unspecified" + +_TOP_KEYS = frozenset({"version", "country", "description", "level_keys", "products"}) +_PRODUCT_KEYS = frozenset({"tool", "option", "default_mode", "modes"}) +_MODE_KEYS = frozenset({"description", "compiled", "built"}) +_CLAUSE_KEYS = frozenset( + {"id", "families", "levels", "metadata", "exclude", "rule", "rationale"} +) +_BUILT_KEYS = frozenset({"id", "family", "levels", "option", "source", "rationale"}) +_TEST_KINDS = frozenset({"present", "equals", "not_equals", "not_prefix"}) + +Predicate = Callable[[Any], bool] +Rule = Callable[[tuple[Any, ...]], tuple[Sequence[Any], Any]] + + +class TargetSetDeclarationError(ValueError): + """A declaration that does not have the declared form.""" + + +# --------------------------------------------------------------------------- +# The declaration +# --------------------------------------------------------------------------- + + +def target_level(spec: Any, level_keys: Sequence[str]) -> str: + """A spec's level: the first truthy ``level_keys`` value, else unspecified.""" + + metadata = spec.metadata + for key in level_keys: + value = metadata.get(key) + if value: + return str(value) + return UNSPECIFIED_LEVEL + + +@dataclass(frozen=True) +class MetadataTest: + """One test on one metadata key.""" + + key: str + kind: str + value: Any = None + + def accepts(self, metadata: Mapping[str, Any]) -> bool: + if self.kind == "present": + return (self.key in metadata) is bool(self.value) + if self.kind == "equals": + return metadata.get(self.key) == self.value + if self.kind == "not_equals": + return metadata.get(self.key) != self.value + held = metadata.get(self.key) + return isinstance(held, str) and bool(held) and not held.startswith(self.value) + + +@dataclass(frozen=True) +class TargetSetClause: + """Compiled specs of some families and levels that pass every test.""" + + clause_id: str + families: frozenset[str] | None + levels: frozenset[str] | None + metadata: tuple[MetadataTest, ...] + exclude: tuple[str, ...] + rule: str | None + rationale: str + + def accepts( + self, spec: Any, level: str, predicates: Mapping[str, Predicate] + ) -> bool: + if self.families is not None and spec.family not in self.families: + return False + return self.accepts_level_and_metadata(spec, level, predicates) + + def accepts_level_and_metadata( + self, spec: Any, level: str, predicates: Mapping[str, Predicate] + ) -> bool: + """Every test but the family one, for a caller that selected the family.""" + + if self.levels is not None and level not in self.levels: + return False + metadata = spec.metadata + if not all(test.accepts(metadata) for test in self.metadata): + return False + return not any(predicates[name](spec) for name in self.exclude) + + +@dataclass(frozen=True) +class BuiltRows: + """Rows a tool makes outside the compile, and the level each option gives.""" + + built_id: str + family: str + levels: Mapping[str, str] + option: str | None + source: str + rationale: str + + +@dataclass(frozen=True) +class TargetSetDeclaration: + """What one product calibrates to in one mode.""" + + country: str + product: str + mode: str + description: str + level_keys: tuple[str, ...] + compiled: tuple[TargetSetClause, ...] + built: tuple[BuiltRows, ...] + + @property + def clause_ids(self) -> tuple[str, ...]: + return tuple(clause.clause_id for clause in self.compiled) + + def clause(self, clause_id: str) -> TargetSetClause: + for clause in self.compiled: + if clause.clause_id == clause_id: + return clause + raise KeyError( + f"{self.product}/{self.mode} declares no compiled clause {clause_id!r}; " + f"it declares {list(self.clause_ids)}." + ) + + def built_rows(self, built_id: str) -> BuiltRows: + for built in self.built: + if built.built_id == built_id: + return built + raise KeyError( + f"{self.product}/{self.mode} declares no built rows {built_id!r}." + ) + + def level_of(self, spec: Any) -> str: + return target_level(spec, self.level_keys) + + +@dataclass(frozen=True) +class ProductDeclaration: + """One product: the option that picks its mode, and each mode's target set.""" + + product: str + tool: str + option: str + default_mode: str + modes: Mapping[str, TargetSetDeclaration] + + @property + def mode_names(self) -> tuple[str, ...]: + return tuple(self.modes) + + def mode(self, name: str) -> TargetSetDeclaration: + try: + return self.modes[name] + except KeyError: + raise KeyError( + f"{self.product} declares no mode {name!r}; it declares " + f"{list(self.modes)}." + ) from None + + +@dataclass(frozen=True) +class TargetSetDeclarations: + """Every product's declared target sets for one country.""" + + country: str + level_keys: tuple[str, ...] + products: Mapping[str, ProductDeclaration] + + def product(self, name: str) -> ProductDeclaration: + try: + return self.products[name] + except KeyError: + raise KeyError( + f"{self.country} declares no product {name!r}; it declares " + f"{list(self.products)}." + ) from None + + def declaration(self, product: str, mode: str) -> TargetSetDeclaration: + return self.product(product).mode(mode) + + +# --------------------------------------------------------------------------- +# Loading +# --------------------------------------------------------------------------- + + +def _fail(where: str, message: str) -> TargetSetDeclarationError: + return TargetSetDeclarationError(f"{where}: {message}") + + +def _require_keys( + where: str, + raw: object, + allowed: frozenset[str], + required: Iterable[str], +) -> Mapping[str, Any]: + if not isinstance(raw, Mapping): + raise _fail(where, "must be an object.") + unknown = sorted(set(raw) - allowed) + if unknown: + raise _fail(where, f"unknown keys {unknown}.") + missing = sorted(set(required) - set(raw)) + if missing: + raise _fail(where, f"missing keys {missing}.") + return raw + + +def _text(where: str, value: object) -> str: + if not isinstance(value, str) or not value or value != value.strip(): + raise _fail(where, "must be a nonempty string without outer spaces.") + return value + + +def _names(where: str, value: object) -> frozenset[str] | None: + if value == ANY: + return None + if not isinstance(value, list) or not value: + raise _fail(where, f"must be {ANY!r} or a nonempty list of names.") + names = [_text(where, item) for item in value] + if len(set(names)) != len(names): + raise _fail(where, "repeats a name.") + return frozenset(names) + + +def _metadata_tests(where: str, raw: object) -> tuple[MetadataTest, ...]: + if raw is None: + return () + if not isinstance(raw, Mapping): + raise _fail(where, "must be an object of key tests.") + tests = [] + for key, test in raw.items(): + _text(f"{where}.{key}", key) + if not isinstance(test, Mapping) or len(test) != 1: + raise _fail(f"{where}.{key}", "must hold exactly one test.") + ((kind, value),) = test.items() + if kind not in _TEST_KINDS: + raise _fail( + f"{where}.{key}", + f"unknown test {kind!r}; use one of {sorted(_TEST_KINDS)}.", + ) + if kind == "present" and not isinstance(value, bool): + raise _fail(f"{where}.{key}", "present takes true or false.") + if kind == "not_prefix": + _text(f"{where}.{key}", value) + tests.append(MetadataTest(key, kind, value)) + return tuple(tests) + + +def _clause(where: str, raw: object) -> TargetSetClause: + clause = _require_keys( + where, raw, _CLAUSE_KEYS, ("id", "families", "levels", "rationale") + ) + exclude = clause.get("exclude", []) + if not isinstance(exclude, list): + raise _fail(f"{where}.exclude", "must be a list of predicate names.") + rule = clause.get("rule") + return TargetSetClause( + clause_id=_text(f"{where}.id", clause["id"]), + families=_names(f"{where}.families", clause["families"]), + levels=_names(f"{where}.levels", clause["levels"]), + metadata=_metadata_tests(f"{where}.metadata", clause.get("metadata")), + exclude=tuple(_text(f"{where}.exclude", name) for name in exclude), + rule=None if rule is None else _text(f"{where}.rule", rule), + rationale=_text(f"{where}.rationale", clause["rationale"]), + ) + + +def _built(where: str, raw: object) -> BuiltRows: + built = _require_keys( + where, raw, _BUILT_KEYS, ("id", "family", "levels", "source", "rationale") + ) + levels = built["levels"] + if not isinstance(levels, Mapping) or not levels: + raise _fail(f"{where}.levels", "must map each option value to a level.") + option = built.get("option") + return BuiltRows( + built_id=_text(f"{where}.id", built["id"]), + family=_text(f"{where}.family", built["family"]), + levels=MappingProxyType( + { + _text(f"{where}.levels", value): _text(f"{where}.levels", level) + for value, level in levels.items() + } + ), + option=None if option is None else _text(f"{where}.option", option), + source=_text(f"{where}.source", built["source"]), + rationale=_text(f"{where}.rationale", built["rationale"]), + ) + + +def load_target_set_declarations( + source: str | Path | Mapping[str, Any], +) -> TargetSetDeclarations: + """Read and check one country's declarations (a path or a parsed object).""" + + if isinstance(source, Mapping): + raw, where = source, "target sets" + else: + path = Path(source) + raw, where = json.loads(path.read_text(encoding="utf-8")), str(path) + top = _require_keys( + where, raw, _TOP_KEYS, ("version", "country", "level_keys", "products") + ) + if top["version"] != DECLARATION_VERSION: + raise _fail(where, f"version must be {DECLARATION_VERSION}.") + country = _text(f"{where}.country", top["country"]) + level_keys = top["level_keys"] + if not isinstance(level_keys, list) or not level_keys: + raise _fail(f"{where}.level_keys", "must be a nonempty list of metadata keys.") + level_keys = tuple(_text(f"{where}.level_keys", key) for key in level_keys) + products_raw = top["products"] + if not isinstance(products_raw, Mapping) or not products_raw: + raise _fail(f"{where}.products", "must name at least one product.") + products: dict[str, ProductDeclaration] = {} + for product_name, product_raw in products_raw.items(): + at = f"{where}.products.{product_name}" + product = _require_keys(at, product_raw, _PRODUCT_KEYS, _PRODUCT_KEYS) + modes_raw = product["modes"] + if not isinstance(modes_raw, Mapping) or not modes_raw: + raise _fail(f"{at}.modes", "must name at least one mode.") + modes: dict[str, TargetSetDeclaration] = {} + for mode_name, mode_raw in modes_raw.items(): + mode_at = f"{at}.modes.{mode_name}" + mode = _require_keys( + mode_at, mode_raw, _MODE_KEYS, ("description", "compiled") + ) + compiled_raw = mode["compiled"] + if not isinstance(compiled_raw, list) or not compiled_raw: + raise _fail(f"{mode_at}.compiled", "must list at least one clause.") + compiled = tuple( + _clause(f"{mode_at}.compiled[{index}]", clause) + for index, clause in enumerate(compiled_raw) + ) + built_raw = mode.get("built", []) + if not isinstance(built_raw, list): + raise _fail(f"{mode_at}.built", "must be a list.") + built = tuple( + _built(f"{mode_at}.built[{index}]", entry) + for index, entry in enumerate(built_raw) + ) + ids = [clause.clause_id for clause in compiled] + [ + b.built_id for b in built + ] + if len(set(ids)) != len(ids): + raise _fail(mode_at, "repeats a clause or built id.") + modes[_text(mode_at, mode_name)] = TargetSetDeclaration( + country=country, + product=product_name, + mode=mode_name, + description=_text(f"{mode_at}.description", mode["description"]), + level_keys=level_keys, + compiled=compiled, + built=built, + ) + default_mode = _text(f"{at}.default_mode", product["default_mode"]) + if default_mode not in modes: + raise _fail( + f"{at}.default_mode", f"{default_mode!r} is not a declared mode." + ) + products[_text(at, product_name)] = ProductDeclaration( + product=product_name, + tool=_text(f"{at}.tool", product["tool"]), + option=_text(f"{at}.option", product["option"]), + default_mode=default_mode, + modes=MappingProxyType(modes), + ) + return TargetSetDeclarations( + country=country, + level_keys=level_keys, + products=MappingProxyType(products), + ) + + +# --------------------------------------------------------------------------- +# Selection +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class TargetSetSelection: + """The selected specs, in order, with each clause's count and rule receipt.""" + + declaration: TargetSetDeclaration + specs: tuple[Any, ...] + clause_counts: Mapping[str, int] + rule_receipts: Mapping[str, Any] + + +def select_target_set( + declaration: TargetSetDeclaration, + specs: Iterable[Any], + *, + clause_ids: Iterable[str] | None = None, + predicates: Mapping[str, Predicate] | None = None, + rules: Mapping[str, Rule] | None = None, +) -> TargetSetSelection: + """Select the declared target set from compiled ``specs``. + + Each compiled clause (only those in ``clause_ids``, when given) keeps the + specs it accepts, in compile order; a clause with a rule passes them to + the rule. The selection is the clauses' outputs in declaration order. + + Raises: + KeyError: If ``clause_ids`` names a clause the declaration lacks. + ValueError: If a clause names a predicate or rule not passed, or if + two clauses keep the same spec. + """ + + specs = tuple(specs) + predicates = dict(predicates or {}) + rules = dict(rules or {}) + if clause_ids is None: + clauses = declaration.compiled + else: + wanted = set(clause_ids) + for clause_id in sorted(wanted): + declaration.clause(clause_id) + clauses = tuple(c for c in declaration.compiled if c.clause_id in wanted) + for clause in clauses: + missing = [name for name in clause.exclude if name not in predicates] + if missing: + raise ValueError( + f"{declaration.product}/{declaration.mode} clause " + f"{clause.clause_id!r} excludes by {missing}, which the caller " + "did not pass." + ) + if clause.rule is not None and clause.rule not in rules: + raise ValueError( + f"{declaration.product}/{declaration.mode} clause " + f"{clause.clause_id!r} names rule {clause.rule!r}, which the " + "caller did not pass." + ) + levels = [declaration.level_of(spec) for spec in specs] + kept: list[Any] = [] + counts: dict[str, int] = {} + receipts: dict[str, Any] = {} + seen: dict[int, str] = {} + for clause in clauses: + picked: Sequence[Any] = [ + spec + for spec, level in zip(specs, levels, strict=True) + if clause.accepts(spec, level, predicates) + ] + if clause.rule is not None: + picked, receipts[clause.clause_id] = rules[clause.rule](tuple(picked)) + for spec in picked: + other = seen.setdefault(id(spec), clause.clause_id) + if other != clause.clause_id: + raise ValueError( + f"{declaration.product}/{declaration.mode}: clauses {other!r} " + f"and {clause.clause_id!r} both keep {spec.name!r}." + ) + counts[clause.clause_id] = len(picked) + kept.extend(picked) + return TargetSetSelection( + declaration=declaration, + specs=tuple(kept), + clause_counts=MappingProxyType(counts), + rule_receipts=MappingProxyType(receipts), + ) + + +def clause_predicate( + declaration: TargetSetDeclaration, + clause_id: str, + *, + predicates: Mapping[str, Predicate] | None = None, + test_family: bool = True, +) -> Predicate: + """One compiled clause as a spec predicate; its rule is not applied. + + With ``test_family=False`` the predicate skips the family test, for a + caller that has already selected the family. + """ + + clause = declaration.clause(clause_id) + predicates = dict(predicates or {}) + missing = [name for name in clause.exclude if name not in predicates] + if missing: + raise ValueError( + f"{declaration.product}/{declaration.mode} clause {clause_id!r} " + f"excludes by {missing}, which the caller did not pass." + ) + + def accepted(spec: Any) -> bool: + level = declaration.level_of(spec) + if test_family: + return clause.accepts(spec, level, predicates) + return clause.accepts_level_and_metadata(spec, level, predicates) + + return accepted + + +def target_set_census( + specs: Iterable[Any], level_keys: Sequence[str] +) -> dict[tuple[str, str], int]: + """Spec counts by (family, level), sorted.""" + + census = Counter( + (str(spec.family), target_level(spec, level_keys)) for spec in specs + ) + return dict(sorted(census.items())) + + +def undeclared_cells( + declaration: TargetSetDeclaration, specs: Iterable[Any] +) -> dict[tuple[str, str], int]: + """(family, level) cells of ``specs`` that no clause or built entry declares. + + Metadata tests, exclusions and rules are not applied: a cell is declared + when some compiled clause names its family and level (or any), or some + built entry gives its family that level. + """ + + def declared(family: str, level: str) -> bool: + for clause in declaration.compiled: + if (clause.families is None or family in clause.families) and ( + clause.levels is None or level in clause.levels + ): + return True + return any( + built.family == family and level in built.levels.values() + for built in declaration.built + ) + + census = target_set_census(specs, declaration.level_keys) + return {cell: n for cell, n in census.items() if not declared(*cell)} diff --git a/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py b/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py new file mode 100644 index 0000000000..2a99256086 --- /dev/null +++ b/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py @@ -0,0 +1,362 @@ +"""Declared target sets: the shared reader and selector (microcosm#1728).""" + +from __future__ import annotations + +import copy +import json +from types import SimpleNamespace + +import pytest + +from microcosm.calibrate.target_sets import ( + UNSPECIFIED_LEVEL, + TargetSetDeclarationError, + clause_predicate, + load_target_set_declarations, + select_target_set, + target_level, + target_set_census, + undeclared_cells, +) + + +def _spec(name: str, family: str, **metadata) -> SimpleNamespace: + return SimpleNamespace(name=name, family=family, metadata=metadata) + + +SPECS = ( + _spec("nation_tax", "tax", level="country"), + _spec("ca_tax", "tax", level="state", state="06", role="band"), + _spec("ca_tax_total", "tax", level="state", state="06", role="total"), + _spec("ca_benefit", "benefit", level="state", state="06"), + _spec("ca01_tax", "tax", level="district", state="06", record="district_file.ca01"), + _spec("ca_tax_file", "tax", level="state", state="06", record="district_file.ca"), + _spec("unlabelled", "tax", geo="state", state="06"), +) + +DECLARATIONS = { + "version": 1, + "country": "test", + "level_keys": ["level", "geo"], + "products": { + "national": { + "tool": "tools/national.py", + "option": "--surface", + "default_mode": "all", + "modes": { + "all": { + "description": "Every compiled target.", + "compiled": [ + {"id": "all", "families": "*", "levels": "*", "rationale": "r"} + ], + }, + "no_district": { + "description": "Every target but the district ones.", + "compiled": [ + { + "id": "rows", + "families": "*", + "levels": "*", + "exclude": ["district"], + "rationale": "r", + } + ], + }, + }, + }, + "local": { + "tool": "tools/local.py", + "option": "--mode", + "default_mode": "state", + "modes": { + "state": { + "description": "State benefit and state tax rows.", + "compiled": [ + { + "id": "benefit", + "families": ["benefit"], + "levels": ["state"], + "metadata": {"state": {"present": True}}, + "rationale": "r", + }, + { + "id": "tax", + "families": ["tax"], + "levels": ["state"], + "metadata": { + "state": {"present": True}, + "role": {"not_equals": "band"}, + }, + "rationale": "r", + }, + ], + "built": [ + { + "id": "population", + "family": "population", + "option": "--geographies", + "levels": {"state": "state", "cd": "district"}, + "source": "a ladder", + "rationale": "r", + } + ], + }, + "shares": { + "description": "State tax rows and district shares of them.", + "compiled": [ + { + "id": "tax", + "families": ["tax"], + "levels": ["state", "district"], + "metadata": {"state": {"present": True}}, + "rule": "shares", + "rationale": "r", + } + ], + }, + }, + }, + }, +} + + +def _declarations(**changes): + raw = copy.deepcopy(DECLARATIONS) + for path, value in changes.items(): + node = raw + *parents, leaf = path.split("__") + for key in parents: + node = node[int(key)] if isinstance(node, list) else node[key] + if value is _DELETE: + del node[leaf] + else: + node[leaf] = value + return load_target_set_declarations(raw) + + +_DELETE = object() + + +def _names(specs) -> list[str]: + return [spec.name for spec in specs] + + +def test_declarations_load_from_a_file_and_name_products_and_modes(tmp_path) -> None: + path = tmp_path / "target_sets.json" + path.write_text(json.dumps(DECLARATIONS), encoding="utf-8") + + declarations = load_target_set_declarations(path) + + assert declarations.country == "test" + assert declarations.level_keys == ("level", "geo") + assert tuple(declarations.products) == ("national", "local") + local = declarations.product("local") + assert local.option == "--mode" + assert local.default_mode == "state" + assert local.mode_names == ("state", "shares") + state = declarations.declaration("local", "state") + assert state.clause_ids == ("benefit", "tax") + assert state.built_rows("population").levels == {"state": "state", "cd": "district"} + with pytest.raises(KeyError, match="no mode 'county'"): + local.mode("county") + with pytest.raises(KeyError, match="no product 'regional'"): + declarations.product("regional") + with pytest.raises(KeyError, match="no compiled clause 'snap'"): + state.clause("snap") + + +@pytest.mark.parametrize( + ("changes", "message"), + [ + ({"version": 2}, "version must be 1"), + ({"extra": True}, "unknown keys"), + ({"level_keys": []}, "level_keys"), + ({"products__local__default_mode": "county"}, "not a declared mode"), + ({"products__local__modes__state__compiled": []}, "at least one clause"), + ( + {"products__local__modes__state__compiled__0__families": []}, + "nonempty list", + ), + ( + {"products__local__modes__state__compiled__0__levels": ["state", "state"]}, + "repeats a name", + ), + ( + {"products__local__modes__state__compiled__1__id": "benefit"}, + "repeats a clause or built id", + ), + ({"products__local__modes__state__compiled__0__rationale": _DELETE}, "missing"), + ( + { + "products__local__modes__state__compiled__0__metadata": { + "state": {"in": 1} + } + }, + "unknown test", + ), + ( + { + "products__local__modes__state__compiled__0__metadata": { + "state": {"present": "yes"} + } + }, + "present takes true or false", + ), + ( + {"products__local__modes__state__built__0__levels": {}}, + "map each option value", + ), + ], +) +def test_a_malformed_declaration_is_refused(changes, message) -> None: + with pytest.raises(TargetSetDeclarationError, match=message): + _declarations(**changes) + + +def test_a_level_is_the_first_truthy_level_key() -> None: + keys = ("level", "geo") + + assert target_level(_spec("a", "f", level="state", geo="district"), keys) == "state" + assert target_level(_spec("b", "f", level="", geo="district"), keys) == "district" + assert target_level(_spec("c", "f"), keys) == UNSPECIFIED_LEVEL + + +def test_wildcards_keep_every_spec_in_compile_order() -> None: + declaration = _declarations().declaration("national", "all") + + selection = select_target_set(declaration, SPECS) + + assert selection.specs == SPECS + assert dict(selection.clause_counts) == {"all": len(SPECS)} + + +def test_an_exclusion_predicate_drops_the_specs_it_accepts() -> None: + declaration = _declarations().declaration("national", "no_district") + + def district(spec) -> bool: + return spec.metadata.get("level") == "district" or "district_file" in str( + spec.metadata.get("record", "") + ) + + selection = select_target_set(declaration, SPECS, predicates={"district": district}) + + assert _names(selection.specs) == [ + "nation_tax", + "ca_tax", + "ca_tax_total", + "ca_benefit", + "unlabelled", + ] + with pytest.raises(ValueError, match="excludes by \\['district'\\]"): + select_target_set(declaration, SPECS) + + +def test_clauses_keep_family_level_and_metadata_matches_in_clause_order() -> None: + declaration = _declarations().declaration("local", "state") + + selection = select_target_set(declaration, SPECS) + + # Clause order (benefit, then tax), compile order inside each clause. The + # unlabelled spec's level comes from the second level key. + assert _names(selection.specs) == [ + "ca_benefit", + "ca_tax_total", + "ca_tax_file", + "unlabelled", + ] + assert dict(selection.clause_counts) == {"benefit": 1, "tax": 3} + + +def test_clause_ids_turn_on_only_some_clauses() -> None: + declaration = _declarations().declaration("local", "state") + + selection = select_target_set(declaration, SPECS, clause_ids=["tax"]) + + assert _names(selection.specs) == ["ca_tax_total", "ca_tax_file", "unlabelled"] + with pytest.raises(KeyError, match="no compiled clause 'snap'"): + select_target_set(declaration, SPECS, clause_ids=["tax", "snap"]) + + +def test_a_rule_takes_its_clause_specs_and_returns_specs_and_a_receipt() -> None: + declaration = _declarations().declaration("local", "shares") + seen = [] + + def shares(candidates): + seen.append(_names(candidates)) + return candidates[:2], {"rule": "shares", "in": len(candidates)} + + selection = select_target_set(declaration, SPECS, rules={"shares": shares}) + + assert seen == [["ca_tax", "ca_tax_total", "ca01_tax", "ca_tax_file", "unlabelled"]] + assert _names(selection.specs) == ["ca_tax", "ca_tax_total"] + assert dict(selection.rule_receipts) == {"tax": {"rule": "shares", "in": 5}} + with pytest.raises(ValueError, match="names rule 'shares'"): + select_target_set(declaration, SPECS) + + +def test_a_spec_that_two_clauses_keep_is_refused() -> None: + declarations = copy.deepcopy(DECLARATIONS) + clauses = declarations["products"]["local"]["modes"]["state"]["compiled"] + clauses[0]["families"] = ["benefit", "tax"] + declaration = load_target_set_declarations(declarations).declaration( + "local", "state" + ) + + with pytest.raises(ValueError, match="both keep 'ca_tax_total'"): + select_target_set(declaration, SPECS) + + +def test_metadata_tests_match_their_definitions() -> None: + declarations = copy.deepcopy(DECLARATIONS) + clause = declarations["products"]["local"]["modes"]["state"]["compiled"][1] + clause["levels"] = "*" + clause["metadata"] = { + "record": {"not_prefix": "district_file."}, + "role": {"equals": "total"}, + } + declaration = load_target_set_declarations(declarations).declaration( + "local", "state" + ) + specs = ( + _spec("kept", "tax", record="table_2.ca", role="total"), + _spec("district_file", "tax", record="district_file.ca", role="total"), + _spec("empty_record", "tax", record="", role="total"), + _spec("no_record", "tax", role="total"), + _spec("band", "tax", record="table_2.ca", role="band"), + _spec("no_role", "tax", record="table_2.ca"), + ) + + assert _names(select_target_set(declaration, specs, clause_ids=["tax"]).specs) == [ + "kept" + ] + + +def test_a_clause_predicate_can_skip_the_family_test() -> None: + declaration = _declarations().declaration("local", "state") + with_family = clause_predicate(declaration, "tax") + without_family = clause_predicate(declaration, "tax", test_family=False) + plain = SimpleNamespace(metadata={"level": "state", "state": "06"}) + + assert without_family(plain) + assert with_family(_spec("x", "tax", level="state", state="06")) + assert not with_family(_spec("x", "benefit", level="state", state="06")) + + +def test_census_and_undeclared_cells() -> None: + declaration = _declarations().declaration("local", "state") + specs = ( + *SPECS, + _spec("pop_ca", "population", geo="state"), + _spec("pop_ca01", "population", geo="district"), + _spec("pop_county", "population", geo="county"), + ) + + census = target_set_census(specs, declaration.level_keys) + + assert census[("tax", "state")] == 4 + assert census[("population", "district")] == 1 + assert undeclared_cells(declaration, specs) == { + ("population", "county"): 1, + ("tax", "country"): 1, + ("tax", "district"): 1, + } From 7f4006fffeb872829ce3890495084fd3d10749ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:42:26 +0000 Subject: [PATCH 02/30] Declare the US target sets and select by them, with no surface change us/target_sets.json declares the national tool's --target-surface modes and the ACS local tool's --soi-mode modes. _select_target_surface, state_admin_surface and soi_surface_predicate now select by it. us/country_package.json lists the new resource. On the pinned 41b2fb2 feed every surface keeps the same targets in the same order (count and TargetRegistry version, measured on main 0f963ac77): national full 31,748 and national_state 6,102; local state 4,380 (4,867 with the ladder's 487 population rows), totals 255, full 29,977, state_cd 26,425 and state_county 4,380. test_us_target_sets.py pins them, and checks that every compiled target's level is the one target_geography_level gives. docs/us-target-sets.md explains the declarations. docs/us-fact-to-target.md now says that the national and the local product calibrate to different subsets of the one compiled registry. Part of microcosm#1728. Co-Authored-By: Claude Opus 5.5 --- .../1728-us-target-set-declarations.added.md | 1 + docs/us-fact-to-target.md | 8 +- docs/us-target-sets.md | 133 ++++++ .../microcosm/build/us/country_package.json | 5 + .../src/microcosm/build/us/target_sets.json | 417 ++++++++++++++++++ .../microcosm/build/us_runtime/target_sets.py | 58 +++ .../engine_free/us/test_us_target_sets.py | 368 ++++++++++++++++ tools/build_us_acs_local_release.py | 107 +++-- tools/build_us_fiscal_refresh_release.py | 34 +- 9 files changed, 1060 insertions(+), 71 deletions(-) create mode 100644 changelog.d/1728-us-target-set-declarations.added.md create mode 100644 docs/us-target-sets.md create mode 100644 packages/microcosm-build/src/microcosm/build/us/target_sets.json create mode 100644 packages/microcosm-build/src/microcosm/build/us_runtime/target_sets.py create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_target_sets.py diff --git a/changelog.d/1728-us-target-set-declarations.added.md b/changelog.d/1728-us-target-set-declarations.added.md new file mode 100644 index 0000000000..0441a4ef01 --- /dev/null +++ b/changelog.d/1728-us-target-set-declarations.added.md @@ -0,0 +1 @@ +Each US release's target set is now declared as data (microcosm#1728): `us/target_sets.json` states, for the national tool's `--target-surface` modes and the ACS local tool's `--soi-mode` modes, the compiled families and levels each mode keeps, the tests and named rules that pick them, and the rows the tool builds itself. The shared, country-free reader and selector `microcosm.calibrate.target_sets` replaces the selection code in `_select_target_surface`, `state_admin_surface` and `soi_surface_predicate`. No surface changes: on the pinned `41b2fb2` feed every mode keeps the same targets in the same order (`national_state` 6,102, the local default 4,867 with its population rows), and `test_us_target_sets.py` pins each count and registry version. `docs/us-target-sets.md` explains the declarations. diff --git a/docs/us-fact-to-target.md b/docs/us-fact-to-target.md index 24bf605988..66aa6b1b1c 100644 --- a/docs/us-fact-to-target.md +++ b/docs/us-fact-to-target.md @@ -39,8 +39,12 @@ same cell and concept — e.g. congressional-district income binds from `irs_soi.congressional_district_2022`, while ACS (the `census_acs` source) supplies CD population and structure. Every US calibrated artifact compiles the same national + state + congressional-district target -surface (`us_runtime/fiscal_targets.py::compile_us_fiscal_target_registry`); -artifact record count changes L0, not target membership. The pinned +registry (`us_runtime/fiscal_targets.py::compile_us_fiscal_target_registry`); +artifact record count changes L0, not target membership. Each product then +calibrates to the subset that `us/target_sets.json` declares for its mode +([US target sets](us-target-sets.md)). The national build's `national_state` +mode and the local build's `state` mode are not the same set today +(microcosm#1728). The pinned `census_acs.acs1_2023` family remains a reviewed `survey_derived` exclusion because all of its facts are state-grain, while the compiler admits ACS only at congressional-district geography diff --git a/docs/us-target-sets.md b/docs/us-target-sets.md new file mode 100644 index 0000000000..5bde1f1a16 --- /dev/null +++ b/docs/us-target-sets.md @@ -0,0 +1,133 @@ +# US target sets + +Every US release compiles the same target registry +(`us_runtime/fiscal_targets.py::compile_us_fiscal_target_registry`). Each +release then calibrates to a subset of it. Since microcosm#1728, that subset is +declared as data, for each product and mode, in +[`packages/microcosm-build/src/microcosm/build/us/target_sets.json`](../packages/microcosm-build/src/microcosm/build/us/target_sets.json). + +- The shared reader and selector are in + [`microcosm.calibrate.target_sets`](../packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py). + They hold no country code. +- The US names (file, products, predicate, rule) are in + [`microcosm.build.us_runtime.target_sets`](../packages/microcosm-build/src/microcosm/build/us_runtime/target_sets.py). +- The national tool (`tools/build_us_fiscal_refresh_release.py`, + `_select_target_surface`) and the ACS local tool + (`tools/build_us_acs_local_release.py`, `state_admin_surface` and + `soi_surface_predicate`) select by the declarations. + +The declarations replaced the selection code without a change to any target +surface (see "What the declarations select" below). + +## The declaration + +The file has one entry for each product: + +| Product | Tool | Option | Default mode | Modes | +|---|---|---|---|---| +| `national` | `tools/build_us_fiscal_refresh_release.py` | `--target-surface` | `full` | `full`, `national_state` | +| `local` | `tools/build_us_acs_local_release.py` | `--soi-mode` | `state` | `state`, `totals`, `full`, `state_cd`, `state_county` | + +Each mode states three things: + +1. **Compiled clauses.** Each clause keeps the compiled targets of some + families at some levels that pass its tests: + - `families` and `levels`: lists of names, or `"*"` for any; + - `metadata`: tests on metadata keys (`present`, `equals`, `not_equals`, + `not_prefix`); + - `exclude`: named predicates that drop a target (the national + `congressional_district` classifier); + - `rule`: a named rule that takes the clause's targets and returns the + targets it keeps (the local `state_cd_district_shares` reconciliation). + + The selection is each clause's targets in declaration order, and the + compile order inside a clause. The local `--families` option turns + clauses on by id (`snap`, `medicaid`, `soi`). +2. **Built rows.** The rows a tool makes outside the compile: the population + totals from the PUMA ladder (`--geographies`), and in `state_county` the + county SOI shares and the ACS household rows from the county facts. The + selector does not make them. The declaration names their family and + levels, so that it states the whole target set. +3. **Rationale.** Each clause and built entry says why the product keeps + those rows, as the UK membership files + (`uk/target_reference_membership.json`, + `uk/local_target_reference_membership.json`) give a signed rationale for + each exclusion. + +A target's family is its `TargetSpec.family`. Its level is its +`ledger_geography_level`, else its `geography_level`. These are the labels +that the shared target-loss rule reads (microcosm#1729), so a target has one +family and one level everywhere. The US levels are `country`, `state`, +`congressional_district` and `county`. + +## What the declarations select + +On the pinned `41b2fb2` feed. The counts and the `TargetRegistry` versions +(an order-sensitive content hash) are the same as on main `0f963ac77`, before +the declarations: + +| Product | Mode | Targets | Registry version | +|---|---|---:|---| +| `national` | `full` | 31,748 | `4cc4cfb7a147` | +| `national` | `national_state` | 6,102 | `4dfe25b1238a` | +| `local` | `state` | 4,380 compiled + 487 population = **4,867** | `0ee16ca42be5` (compiled), `69b952ef181f` (with population) | +| `local` | `totals` | 255 compiled | `c6a0f757c0bc` | +| `local` | `full` | 29,977 compiled | `b6c71f2e8505` | +| `local` | `state_cd` | 26,425 compiled | `e0bb302e3add` | +| `local` | `state_county` | 4,380 compiled, then the county rows | `0ee16ca42be5` (compiled) | + +The 487 population rows are 51 state and 436 district totals from the +ladder with SHA256 `39a2ab2a…` (`--geographies state,cd`). +`packages/microcosm-build/tests/engine_free/us/test_us_target_sets.py` pins +all of these. The pinned-feed tests run when `MICROCOSM_US_CHRONICLE_FACTS` +names the feed, and the population test also needs +`MICROCOSM_US_PUMA_LADDER_ARTIFACT`. + +### The state rows of the two production surfaces + +The production national builds use `national_state`. The production local +builds use `state`. Their state rows, by family: + +| Family | `national` `national_state` | `local` `state` | +|---|---:|---:| +| `irs_soi` | 4,227 | 4,227 | +| `usda_snap` | 102 | 102 | +| `cms_medicaid` | 132 | 51 (enrollment only) | +| `census_population` | 918 (51 states × 18 age bands) | 51 (ladder totals, built) | +| `cms_aca` | 102 | — | +| `ssa` | 102 | — | +| `state_income_tax` | 44 | — | +| `hhs_acf_tanf` | 29 | — | +| **State rows** | **5,656** | **4,431** | + +`national_state` also has 446 country rows. `local` `state` has none, and it +has 436 district population rows. Whether the local build fits the national +rows and the full state set is decision 1 of microcosm#1728. + +## How to change a target set + +1. Change the mode's clauses or built entries in `target_sets.json`. The tools + read the file at run time. +2. Run `test_us_target_sets.py` with the pinned feed. A change that moves a + surface changes its pinned count and version: update them, and say which + rows moved in the pull request. +3. A change that moves a surface changes what the calibration fits, so a + build must measure it (`docs/us-release-build-rule.md`). + +A family or level that a feed re-pin adds enters a mode only if a clause names +it: + +- The national modes use `"*"` for families and levels. `full` keeps every + compiled target. `national_state` keeps every compiled target that the + congressional-district classifier does not drop. +- The local clauses name their families and levels. The SNAP and Medicaid + clauses keep state rows. The SOI clause keeps state rows in `state` and + `state_county`, and state and district rows in `totals`, `full` and + `state_cd`. + +Before the declarations, the local SNAP, Medicaid, `totals`, `full` and +`state_cd` filters did not test the level: they kept every row that carries +`state_fips`. On the pinned feed every such row is at a declared level, so no +surface changes. On a feed with such rows at another level (for example county +rows in the main feed), the declarations keep them out until a clause names +the level. diff --git a/packages/microcosm-build/src/microcosm/build/us/country_package.json b/packages/microcosm-build/src/microcosm/build/us/country_package.json index 855a488fe9..955f2e379b 100644 --- a/packages/microcosm-build/src/microcosm/build/us/country_package.json +++ b/packages/microcosm-build/src/microcosm/build/us/country_package.json @@ -182,6 +182,11 @@ "kind": "legacy_json", "schema_id": "legacy_json" }, + { + "path": "target_sets.json", + "kind": "legacy_json", + "schema_id": "legacy_json" + }, { "path": "tax_expenditure_reforms.json", "kind": "legacy_json", diff --git a/packages/microcosm-build/src/microcosm/build/us/target_sets.json b/packages/microcosm-build/src/microcosm/build/us/target_sets.json new file mode 100644 index 0000000000..477e275dc4 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us/target_sets.json @@ -0,0 +1,417 @@ +{ + "version": 1, + "country": "us", + "description": "The targets each US release calibrates to, for each product and mode: the compiled families and levels it keeps, the tests that pick them, and the rows the tool builds itself (microcosm#1728). microcosm.calibrate.target_sets reads this file; docs/us-target-sets.md explains it.", + "level_keys": [ + "ledger_geography_level", + "geography_level" + ], + "products": { + "national": { + "tool": "tools/build_us_fiscal_refresh_release.py", + "option": "--target-surface", + "default_mode": "full", + "modes": { + "full": { + "description": "Every compiled target.", + "compiled": [ + { + "id": "compiled", + "families": "*", + "levels": "*", + "rationale": "The tool's default: the release calibrates to the whole compiled registry." + } + ] + }, + "national_state": { + "description": "The country and state rows of every compiled family, except the rows classified as congressional-district. The production national builds use this mode.", + "compiled": [ + { + "id": "country_and_state", + "families": "*", + "levels": "*", + "exclude": [ + "congressional_district" + ], + "rationale": "District targets belong in the local solve: when microcosm#449 put small-area targets into the national solve, the share of targets within 10% fell by half (microcosm#625). The exclusion also drops the country and state rows of the IRS SOI congressional-district file. The target-parity and profile-coverage gates run on the full compiled registry before this selection." + } + ] + } + } + }, + "local": { + "tool": "tools/build_us_acs_local_release.py", + "option": "--soi-mode", + "default_mode": "state", + "modes": { + "state": { + "description": "State SNAP, state Medicaid enrollment and the IRS SOI state rows outside the congressional-district file, with population totals from the PUMA ladder.", + "compiled": [ + { + "id": "snap", + "families": [ + "usda_snap" + ], + "levels": [ + "state" + ], + "metadata": { + "state_fips": { + "present": true + } + }, + "rationale": "State SNAP rows (--families snap)." + }, + { + "id": "medicaid", + "families": [ + "cms_medicaid" + ], + "levels": [ + "state" + ], + "metadata": { + "state_fips": { + "present": true + }, + "target_role": { + "equals": "medicaid_enrollment" + } + }, + "rationale": "State Medicaid enrollment after the reviewed Rhode Island substitution (--families medicaid)." + }, + { + "id": "soi", + "families": [ + "irs_soi" + ], + "levels": [ + "state" + ], + "metadata": { + "state_fips": { + "present": true + }, + "ledger_layout_record_set_spec_id": { + "not_prefix": "irs_soi.congressional_district_" + } + }, + "rationale": "The SOI state rows of every target role, AGI bands included, outside the congressional-district file (--families soi). This is the default mode; docs/us-acs-local-soi-target-surface.md has its history." + } + ], + "built": [ + { + "id": "population", + "family": "census_population", + "option": "--geographies", + "levels": { + "state": "state", + "cd": "congressional_district", + "county": "county" + }, + "source": "US Census Bureau 2020 PUMA population ladder (--ladder)", + "rationale": "One population total for each state, 119th-Congress district and county that --geographies names (default state,cd)." + } + ] + }, + "totals": { + "description": "As state, but the SOI rows are every state-bearing row whose target role is not soi_fiscal_distribution, at state and district level.", + "compiled": [ + { + "id": "snap", + "families": [ + "usda_snap" + ], + "levels": [ + "state" + ], + "metadata": { + "state_fips": { + "present": true + } + }, + "rationale": "State SNAP rows (--families snap)." + }, + { + "id": "medicaid", + "families": [ + "cms_medicaid" + ], + "levels": [ + "state" + ], + "metadata": { + "state_fips": { + "present": true + }, + "target_role": { + "equals": "medicaid_enrollment" + } + }, + "rationale": "State Medicaid enrollment after the reviewed Rhode Island substitution (--families medicaid)." + }, + { + "id": "soi", + "families": [ + "irs_soi" + ], + "levels": [ + "state", + "congressional_district" + ], + "metadata": { + "state_fips": { + "present": true + }, + "target_role": { + "not_equals": "soi_fiscal_distribution" + } + }, + "rationale": "An explicit opt-in: the jetsam-safe Option B of the Build L runbook. Every SOI fact without a named role has the role soi_fiscal_distribution, so this mode drops the AGI bands and the all-income state and district rows." + } + ], + "built": [ + { + "id": "population", + "family": "census_population", + "option": "--geographies", + "levels": { + "state": "state", + "cd": "congressional_district", + "county": "county" + }, + "source": "US Census Bureau 2020 PUMA population ladder (--ladder)", + "rationale": "One population total for each state, 119th-Congress district and county that --geographies names (default state,cd)." + } + ] + }, + "full": { + "description": "As state, but the SOI rows are every state-bearing row at state and district level, the congressional-district file included, with both vintages of each state concept.", + "compiled": [ + { + "id": "snap", + "families": [ + "usda_snap" + ], + "levels": [ + "state" + ], + "metadata": { + "state_fips": { + "present": true + } + }, + "rationale": "State SNAP rows (--families snap)." + }, + { + "id": "medicaid", + "families": [ + "cms_medicaid" + ], + "levels": [ + "state" + ], + "metadata": { + "state_fips": { + "present": true + }, + "target_role": { + "equals": "medicaid_enrollment" + } + }, + "rationale": "State Medicaid enrollment after the reviewed Rhode Island substitution (--families medicaid)." + }, + { + "id": "soi", + "families": [ + "irs_soi" + ], + "levels": [ + "state", + "congressional_district" + ], + "metadata": { + "state_fips": { + "present": true + } + }, + "rationale": "An explicit opt-in that keeps every state-bearing SOI row. It does not fit in memory on one 128 GB machine (microcosm#1728)." + } + ], + "built": [ + { + "id": "population", + "family": "census_population", + "option": "--geographies", + "levels": { + "state": "state", + "cd": "congressional_district", + "county": "county" + }, + "source": "US Census Bureau 2020 PUMA population ladder (--ladder)", + "rationale": "One population total for each state, 119th-Congress district and county that --geographies names (default state,cd)." + } + ] + }, + "state_cd": { + "description": "As state, plus the congressional-district file's district rows as within-state shares of the Historic Table 2 state level, with one vintage for each state concept.", + "compiled": [ + { + "id": "snap", + "families": [ + "usda_snap" + ], + "levels": [ + "state" + ], + "metadata": { + "state_fips": { + "present": true + } + }, + "rationale": "State SNAP rows (--families snap)." + }, + { + "id": "medicaid", + "families": [ + "cms_medicaid" + ], + "levels": [ + "state" + ], + "metadata": { + "state_fips": { + "present": true + }, + "target_role": { + "equals": "medicaid_enrollment" + } + }, + "rationale": "State Medicaid enrollment after the reviewed Rhode Island substitution (--families medicaid)." + }, + { + "id": "soi", + "families": [ + "irs_soi" + ], + "levels": [ + "state", + "congressional_district" + ], + "metadata": { + "state_fips": { + "present": true + } + }, + "rule": "state_cd_district_shares", + "rationale": "An explicit opt-in. The rule (tools/us_acs_local_cd_surface.py state_cd_soi_surface) takes the state mode's SOI rows as the state level and keeps the district file's district rows only as shares of it. --cd-holdout-fraction holds a block of district rows out of the solve." + } + ], + "built": [ + { + "id": "population", + "family": "census_population", + "option": "--geographies", + "levels": { + "state": "state", + "cd": "congressional_district", + "county": "county" + }, + "source": "US Census Bureau 2020 PUMA population ladder (--ladder)", + "rationale": "One population total for each state, 119th-Congress district and county that --geographies names (default state,cd)." + } + ] + }, + "state_county": { + "description": "As state, plus county rows from the pinned county facts: SOI shares of each state row, ACS households, and county population.", + "compiled": [ + { + "id": "snap", + "families": [ + "usda_snap" + ], + "levels": [ + "state" + ], + "metadata": { + "state_fips": { + "present": true + } + }, + "rationale": "State SNAP rows (--families snap)." + }, + { + "id": "medicaid", + "families": [ + "cms_medicaid" + ], + "levels": [ + "state" + ], + "metadata": { + "state_fips": { + "present": true + }, + "target_role": { + "equals": "medicaid_enrollment" + } + }, + "rationale": "State Medicaid enrollment after the reviewed Rhode Island substitution (--families medicaid)." + }, + { + "id": "soi", + "families": [ + "irs_soi" + ], + "levels": [ + "state" + ], + "metadata": { + "state_fips": { + "present": true + }, + "ledger_layout_record_set_spec_id": { + "not_prefix": "irs_soi.congressional_district_" + } + }, + "rationale": "The state mode's SOI rows: the county rows split them, so they stay the state level (docs/us-acs-local-county-rung.md)." + } + ], + "built": [ + { + "id": "population", + "family": "census_population", + "option": "--geographies", + "levels": { + "state": "state", + "cd": "congressional_district", + "county": "county" + }, + "source": "US Census Bureau 2020 PUMA population ladder (--ladder)", + "rationale": "One population total for each state, 119th-Congress district and county that --geographies names (the County Files runbook uses state,cd,county)." + }, + { + "id": "county_soi", + "family": "irs_soi", + "levels": { + "county": "county" + }, + "source": "IRS SOI county file in the pinned county facts (--county-facts, us/chronicle_county_facts.json)", + "rationale": "County SOI facts give shares of their state row, never a second state level (tools/us_acs_local_county_surface.py)." + }, + { + "id": "acs_households", + "family": "acs_households", + "levels": { + "state": "state", + "county": "county" + }, + "source": "ACS household counts in the pinned county facts (--county-facts)", + "rationale": "Each state's ACS household total and its county rows (tools/us_acs_local_county_surface.py acs_household_surface)." + } + ] + } + } + } + } +} diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/target_sets.py b/packages/microcosm-build/src/microcosm/build/us_runtime/target_sets.py new file mode 100644 index 0000000000..c91cec5592 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/target_sets.py @@ -0,0 +1,58 @@ +"""The declared target sets of the US releases (microcosm#1728). + +``us/target_sets.json`` declares what each US product calibrates to in each +mode: the national release (``tools/build_us_fiscal_refresh_release.py``, +``--target-surface``) and the ACS local release +(``tools/build_us_acs_local_release.py``, ``--soi-mode``). The shared reader +and selector are in :mod:`microcosm.calibrate.target_sets`; this module names +the US file, products, predicates and rules. +""" + +from __future__ import annotations + +from functools import lru_cache +from importlib.resources import files +from pathlib import Path + +from microcosm.calibrate.target_sets import ( + TargetSetDeclaration, + TargetSetDeclarations, + load_target_set_declarations, +) + +__all__ = [ + "CONGRESSIONAL_DISTRICT_PREDICATE", + "LOCAL_PRODUCT", + "NATIONAL_PRODUCT", + "STATE_CD_RULE", + "US_TARGET_SETS_RESOURCE", + "us_target_set_declaration", + "us_target_set_declarations", + "us_target_sets_path", +] + +US_TARGET_SETS_RESOURCE = "target_sets.json" +NATIONAL_PRODUCT = "national" +LOCAL_PRODUCT = "local" +#: The predicate the national ``national_state`` mode excludes by: the shared +#: congressional-district classifier +#: (``microcosm.data.us_critical_targets.is_congressional_district_target``). +CONGRESSIONAL_DISTRICT_PREDICATE = "congressional_district" +#: The rule of the local ``state_cd`` mode +#: (``tools/us_acs_local_cd_surface.py`` ``state_cd_soi_surface``). +STATE_CD_RULE = "state_cd_district_shares" + + +def us_target_sets_path() -> Path: + return Path(str(files("microcosm.build.us").joinpath(US_TARGET_SETS_RESOURCE))) + + +@lru_cache(maxsize=1) +def us_target_set_declarations() -> TargetSetDeclarations: + """The packaged US declarations, read and checked once.""" + + return load_target_set_declarations(us_target_sets_path()) + + +def us_target_set_declaration(product: str, mode: str) -> TargetSetDeclaration: + return us_target_set_declarations().declaration(product, mode) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_target_sets.py b/packages/microcosm-build/tests/engine_free/us/test_us_target_sets.py new file mode 100644 index 0000000000..77208e929f --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_target_sets.py @@ -0,0 +1,368 @@ +"""The US products' declared target sets (microcosm#1728). + +``us/target_sets.json`` declares what the national release and the ACS local +release calibrate to. The engine-free tests check the declarations against +the tools. The pinned-feed tests prove that the declarations select the same +rows, in the same order, as the tool code they replace: each surface's count +and ``TargetRegistry.version`` (an order-sensitive content hash) were measured +on main ``0f963ac77`` before the change. They run only when +``MICROCOSM_US_CHRONICLE_FACTS`` points at the pinned feed. +""" + +from __future__ import annotations + +import hashlib +import importlib.util +import os +from pathlib import Path + +import pytest + +from microcosm.build.us_runtime.target_sets import ( + CONGRESSIONAL_DISTRICT_PREDICATE, + LOCAL_PRODUCT, + NATIONAL_PRODUCT, + STATE_CD_RULE, + us_target_set_declaration, + us_target_set_declarations, +) +from microcosm.calibrate import TargetRegistry +from microcosm.calibrate.target_sets import ( + select_target_set, + target_set_census, + undeclared_cells, +) +from test_support.paths import paths_for + +_TEST_PATHS = paths_for("microcosm-build") + +#: The level labels of US targets: the ledger compiler's +#: ``ledger_geography_level`` and the ladder's ``geography_level``. +US_LEVELS = {"country", "state", "congressional_district", "county"} + +#: Each surface on the pinned 41b2fb2 feed: (count, TargetRegistry.version). +PINNED_NATIONAL = { + "full": (31_748, "4cc4cfb7a147"), + "national_state": (6_102, "4dfe25b1238a"), +} +PINNED_LOCAL = { + "state": (4_380, "0ee16ca42be5"), + "totals": (255, "c6a0f757c0bc"), + "full": (29_977, "b6c71f2e8505"), + "state_cd": (26_425, "e0bb302e3add"), + "state_county": (4_380, "0ee16ca42be5"), +} +#: The national_state surface by family and level: every compiled family's +#: country and state rows; the district file's 49 country and 2,601 state +#: rows and every district row are out. +PINNED_NATIONAL_STATE_CENSUS = { + ("bea", "country"): 2, + ("cbo", "country"): 5, + ("census_population", "country"): 18, + ("census_population", "state"): 918, + ("cms_aca", "state"): 102, + ("cms_medicaid", "country"): 3, + ("cms_medicaid", "state"): 132, + ("cms_medicare", "country"): 1, + ("federal_reserve", "country"): 1, + ("hhs_acf_liheap", "country"): 1, + ("hhs_acf_tanf", "country"): 1, + ("hhs_acf_tanf", "state"): 29, + ("irs_soi", "country"): 392, + ("irs_soi", "state"): 4_227, + ("jct", "country"): 11, + ("ssa", "country"): 9, + ("ssa", "state"): 102, + ("state_income_tax", "state"): 44, + ("usda_snap", "country"): 2, + ("usda_snap", "state"): 102, +} +#: The local default with the PUMA ladder's state and district totals +#: (--geographies state,cd): microcosm#1728's 4,867. +PINNED_LADDER_SHA256 = ( + "39a2ab2abeab07a88362af7ab2940e0e1d50a297c919e4bbc6fb65bab51147d8" +) +PINNED_LOCAL_DEFAULT_WITH_POPULATION = (4_867, "69b952ef181f") + + +def _load_tool(name: str): + path = _TEST_PATHS.repository / "tools" / f"{name}.py" + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module + + +@pytest.fixture(scope="module") +def local_tool(): + return _load_tool("build_us_acs_local_release") + + +@pytest.fixture(scope="module") +def national_tool(): + return _load_tool("build_us_fiscal_refresh_release") + + +def _pinned_feed() -> str: + feed = os.environ.get("MICROCOSM_US_CHRONICLE_FACTS", "") + if not feed or not Path(feed).exists(): + pytest.skip( + "set MICROCOSM_US_CHRONICLE_FACTS to the pinned consumer-facts feed" + ) + return feed + + +# --------------------------------------------------------------------------- +# The declarations agree with the tools +# --------------------------------------------------------------------------- + + +def test_the_products_and_modes_are_the_tools_options( + national_tool, local_tool +) -> None: + declarations = us_target_set_declarations() + national = declarations.product(NATIONAL_PRODUCT) + local = declarations.product(LOCAL_PRODUCT) + + assert tuple(declarations.products) == (NATIONAL_PRODUCT, LOCAL_PRODUCT) + assert national.option == "--target-surface" + assert national.mode_names == national_tool.TARGET_SURFACE_MODES + assert national.default_mode == national_tool.TARGET_SURFACE_FULL + assert local.option == "--soi-mode" + assert local.mode_names == local_tool.SOI_MODES + assert local.default_mode == local_tool.DEFAULT_SOI_MODE + base = ["--ledger-facts", "facts.jsonl", "--out", "release"] + assert national_tool._parse_args(base).target_surface == national.default_mode + for product in (national, local): + assert (_TEST_PATHS.repository / product.tool).is_file(), product.tool + + +def test_every_local_mode_declares_the_families_option_clauses( + local_tool, tmp_path: Path +) -> None: + """``--families`` turns the local clauses on by id; its default names all.""" + + args = local_tool._parse_args( + [ + "--stage", + "materialize", + "--staging-h5", + str(tmp_path / "staging.h5"), + "--checkpoint-dir", + str(tmp_path / "ckpt"), + "--feed", + str(tmp_path / "facts.jsonl"), + ] + ) + assert args.families == "snap,medicaid,soi" + assert args.geographies == "state,cd" + for mode in local_tool.SOI_MODES: + declaration = us_target_set_declaration(LOCAL_PRODUCT, mode) + assert declaration.clause_ids == tuple(args.families.split(",")), mode + population = declaration.built_rows("population") + assert population.option == "--geographies" + assert set(args.geographies.split(",")) <= set(population.levels), mode + + +def test_the_declared_names_are_the_ones_the_code_uses(local_tool) -> None: + declarations = us_target_set_declarations() + assert declarations.level_keys == ("ledger_geography_level", "geography_level") + national_state = declarations.declaration(NATIONAL_PRODUCT, "national_state") + assert national_state.compiled[0].exclude == (CONGRESSIONAL_DISTRICT_PREDICATE,) + for mode in ("state", "state_county"): + clause = us_target_set_declaration(LOCAL_PRODUCT, mode).clause("soi") + (prefix_test,) = [t for t in clause.metadata if t.kind == "not_prefix"] + assert ( + prefix_test.value + == local_tool.CONGRESSIONAL_DISTRICT_RECORD_SET_SPEC_PREFIX + ) + assert prefix_test.value == local_tool.cd_surface.CD_FILE_RECORD_SET_SPEC_PREFIX + state_cd = us_target_set_declaration(LOCAL_PRODUCT, "state_cd").clause("soi") + assert state_cd.rule == STATE_CD_RULE + county = us_target_set_declaration(LOCAL_PRODUCT, "state_county") + assert county.built_rows("acs_households").family == ( + local_tool.county_surface.ACS_HOUSEHOLDS_FAMILY + ) + for product in declarations.products.values(): + for declaration in product.modes.values(): + for clause in declaration.compiled: + assert clause.levels is None or clause.levels <= US_LEVELS + for built in declaration.built: + assert set(built.levels.values()) <= US_LEVELS + + +def test_ladder_population_rows_have_the_declared_family_and_levels( + local_tool, +) -> None: + built = us_target_set_declaration(LOCAL_PRODUCT, "state").built_rows("population") + level_keys = us_target_set_declarations().level_keys + populations = {"state": {6: 39_000_000.0}, "cd": {601: 760_000.0}} + + specs = local_tool.ladder_population_target_specs(populations, ["state", "cd"]) + county = local_tool.county_surface.population_spec( + "pop_county_06001", 1_600_000.0, period=local_tool.PERIOD + ) + + from microcosm.build.us_runtime.target_loss_weights import ( + target_geography_level, + ) + from microcosm.calibrate.target_sets import target_level + + for spec in (*specs, county): + assert target_level(spec, level_keys) == target_geography_level(spec) + census = target_set_census((*specs, county), level_keys) + assert census == { + (built.family, built.levels["state"]): 1, + (built.family, built.levels["cd"]): 1, + (built.family, built.levels["county"]): 1, + } + + +def test_the_soi_predicate_is_the_declared_clause(local_tool) -> None: + """``soi_surface_predicate`` reads the declaration, whatever the mode.""" + + from types import SimpleNamespace + + ht2 = "irs_soi.historic_table_2.state_broad_totals.v1" + rows = { + "state_band": { + "state_fips": "06", + "ledger_geography_level": "state", + "ledger_layout_record_set_spec_id": ht2, + "target_role": "soi_fiscal_distribution", + }, + "district": { + "state_fips": "06", + "ledger_geography_level": "congressional_district", + "ledger_layout_record_set_spec_id": "irs_soi.congressional_district_2022.x", + "target_role": "aca_ptc_returns", + }, + "national": { + "ledger_geography_level": "country", + "ledger_layout_record_set_spec_id": ht2, + }, + } + expected = { + "state": {"state_band"}, + "state_county": {"state_band"}, + "totals": {"district"}, + "full": {"state_band", "district"}, + "state_cd": {"state_band", "district"}, + } + for mode, kept in expected.items(): + predicate = local_tool.soi_surface_predicate(mode) + assert { + name + for name, metadata in rows.items() + if predicate(SimpleNamespace(metadata=metadata)) + } == kept, mode + + +# --------------------------------------------------------------------------- +# On the pinned feed: the same rows in the same order as before the change +# --------------------------------------------------------------------------- + + +@pytest.fixture(scope="module") +def pinned_compile(local_tool): + feed = _pinned_feed() + registry, _substitutions = local_tool._compiled_fiscal_registry(feed) + return feed, registry + + +def test_pinned_feed_levels_are_the_target_loss_levels(pinned_compile) -> None: + """Every compiled target has the level the target-loss rows read + (``target_loss_weights.target_geography_level``, microcosm#1729).""" + + from microcosm.build.us_runtime.target_loss_weights import ( + target_geography_level, + ) + from microcosm.calibrate.target_sets import target_level + + _feed, registry = pinned_compile + level_keys = us_target_set_declarations().level_keys + + assert all( + target_level(spec, level_keys) == target_geography_level(spec) + for spec in registry.specs + ) + assert {target_level(spec, level_keys) for spec in registry.specs} == { + "country", + "state", + "congressional_district", + } + + +def test_pinned_feed_national_surfaces_are_unchanged( + pinned_compile, national_tool +) -> None: + _feed, registry = pinned_compile + assert len(registry.specs) == PINNED_NATIONAL["full"][0] + + for mode, (count, version) in PINNED_NATIONAL.items(): + kept, receipt = national_tool._select_target_surface(registry.specs, mode) + assert (len(kept), TargetRegistry(list(kept), country="us").version) == ( + count, + version, + ), mode + assert receipt["calibrated_targets"] == count + declaration = us_target_set_declaration(NATIONAL_PRODUCT, mode) + assert undeclared_cells(declaration, kept) == {} + if mode == "national_state": + census = target_set_census(kept, declaration.level_keys) + assert census == PINNED_NATIONAL_STATE_CENSUS + assert receipt["dropped_congressional_district_targets"] == ( + len(registry.specs) - count + ) + + +def test_pinned_feed_local_surfaces_are_unchanged(pinned_compile, local_tool) -> None: + feed, registry = pinned_compile + families = ["snap", "medicaid", "soi"] + + for mode, (count, version) in PINNED_LOCAL.items(): + surface = local_tool.state_admin_surface(feed, families, soi_mode=mode) + specs = surface.registry.specs + assert (len(specs), surface.registry.version) == (count, version), mode + declaration = us_target_set_declaration(LOCAL_PRODUCT, mode) + assert undeclared_cells(declaration, specs) == {}, mode + assert surface.soi_receipt["soi_mode"] == mode + if mode != "state_cd": + soi = sum(spec.family == "irs_soi" for spec in specs) + assert surface.soi_receipt["counts"] == {"total": soi} + + # The shared selector, run directly on the compile (after the Medicaid + # substitution), gives the same state surface as the tool. + declaration = us_target_set_declaration(LOCAL_PRODUCT, "state") + direct = select_target_set(declaration, registry.specs).specs + assert ( + TargetRegistry(list(direct), country="us").version == PINNED_LOCAL["state"][1] + ) + + +def test_pinned_feed_local_default_with_ladder_population_is_4867( + pinned_compile, local_tool +) -> None: + """Runs when ``MICROCOSM_US_PUMA_LADDER_ARTIFACT`` names the pinned ladder.""" + + ladder = os.environ.get("MICROCOSM_US_PUMA_LADDER_ARTIFACT", "") + if not ladder or not Path(ladder).exists(): + pytest.skip("set MICROCOSM_US_PUMA_LADDER_ARTIFACT to the PUMA ladder") + assert hashlib.sha256(Path(ladder).read_bytes()).hexdigest() == PINNED_LADDER_SHA256 + feed, _registry = pinned_compile + geographies = ["state", "cd"] + + surface = local_tool.state_admin_surface( + feed, ["snap", "medicaid", "soi"], soi_mode="state" + ) + populations = local_tool.ladder_population( + Path(ladder), sorted(set(geographies) | {"cd"}) + ) + joint = local_tool.require_one_label_per_geography( + surface.registry, populations, geographies + ) + + assert (len(joint.specs), joint.version) == PINNED_LOCAL_DEFAULT_WITH_POPULATION + declaration = us_target_set_declaration(LOCAL_PRODUCT, "state") + assert undeclared_cells(declaration, joint.specs) == {} diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index 732c4372a3..15884450ab 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -630,6 +630,11 @@ def _load_json(path: Path) -> dict: def soi_surface_predicate(soi_mode: str): """The ``irs_soi`` spec filter for one ``--soi-mode``. + It is the level and metadata tests of the mode's ``soi`` clause in + ``us/target_sets.json``, product ``local`` (microcosm#1728); the caller + selects the family. A spec's level is its ``ledger_geography_level`` + (else its ``geography_level``), which every compiled spec carries. + Every mode keeps only specs carrying ``state_fips`` (state rows, and the congressional-district rows that also carry their state). @@ -645,34 +650,19 @@ def soi_surface_predicate(soi_mode: str): - ``full`` keeps them all. - ``state_cd`` is not a filter: this returns the ``full`` candidates it starts from, and :func:`state_admin_surface` reconciles them. + - ``state_county`` keeps the ``state`` rows; the county rows split them. """ - _require_soi_mode(soi_mode) - if soi_mode == SOI_MODE_STATE_CD: - soi_mode = SOI_MODE_FULL - elif soi_mode == SOI_MODE_STATE_COUNTY: - soi_mode = SOI_MODE_STATE - - def selected(spec) -> bool: - metadata = spec.metadata - if "state_fips" not in metadata: - return False - if soi_mode == SOI_MODE_STATE: - record_set_spec = metadata.get("ledger_layout_record_set_spec_id") - return ( - metadata.get("ledger_geography_level") == "state" - and isinstance(record_set_spec, str) - and bool(record_set_spec) - and not record_set_spec.startswith( - CONGRESSIONAL_DISTRICT_RECORD_SET_SPEC_PREFIX - ) - ) - return ( - soi_mode == SOI_MODE_FULL - or metadata.get("target_role") != "soi_fiscal_distribution" - ) + from microcosm.build.us_runtime.target_sets import ( + LOCAL_PRODUCT, + us_target_set_declaration, + ) + from microcosm.calibrate.target_sets import clause_predicate - return selected + _require_soi_mode(soi_mode) + return clause_predicate( + us_target_set_declaration(LOCAL_PRODUCT, soi_mode), "soi", test_family=False + ) def _compiled_fiscal_registry(feed: str | Path): @@ -737,7 +727,10 @@ def state_admin_surface( feed -> ``compile_us_fiscal_target_registry(age_targets=True)`` -> ``apply_us_medicaid_enrollment_substitutions`` (RI FIPS-44) -> state-level - {usda_snap, cms_medicaid[enrollment], irs_soi}. The SOI slice follows + {usda_snap, cms_medicaid[enrollment], irs_soi}. The clauses ``snap``, + ``medicaid`` and ``soi`` of the mode's declaration in + ``us/target_sets.json`` (product ``local``, microcosm#1728) pick them, in + that order; ``families`` turns clauses on by id. The SOI slice follows :func:`soi_surface_predicate` for ``state`` (the default), ``totals`` and ``full``; ``state_cd`` adds the reconciled congressional-district rows (:func:`us_acs_local_cd_surface.state_cd_soi_surface`). @@ -757,7 +750,13 @@ def state_admin_surface( from microcosm.build.us_runtime.medicaid_take_up import ( apply_us_medicaid_enrollment_substitutions, ) + from microcosm.build.us_runtime.target_sets import ( + LOCAL_PRODUCT, + STATE_CD_RULE, + us_target_set_declaration, + ) from microcosm.calibrate.registry import TargetRegistry + from microcosm.calibrate.target_sets import select_target_set artifact = load_ledger_consumer_artifact(str(feed)) crosswalk_path = default_congressional_district_vintage_crosswalk_path() @@ -770,39 +769,33 @@ def state_admin_surface( ) registry, ri_substitutions = apply_us_medicaid_enrollment_substitutions(registry) - def state_level(spec) -> bool: - return "state_fips" in spec.metadata - - picked = [] - if "snap" in families: - picked += registry.select(family="usda_snap", predicate=state_level).specs - if "medicaid" in families: - picked += registry.select( - family="cms_medicaid", - predicate=lambda spec: ( - state_level(spec) - and spec.metadata.get("target_role") == "medicaid_enrollment" - ), - ).specs + def state_cd_district_shares(candidates): + surface = cd_surface.state_cd_soi_surface( + candidates, + state_surface_predicate=soi_surface_predicate(SOI_MODE_STATE), + crosswalk=crosswalk, + crosswalk_sha256=_sha256(crosswalk_path), + ) + return surface.specs, surface.receipt + + declaration = us_target_set_declaration(LOCAL_PRODUCT, soi_mode) + selection = select_target_set( + declaration, + registry.specs, + clause_ids=[ + clause_id for clause_id in declaration.clause_ids if clause_id in families + ], + rules={STATE_CD_RULE: state_cd_district_shares}, + ) soi_receipt: dict = {"soi_mode": soi_mode} - if "soi" in families: - candidates = registry.select( - family="irs_soi", predicate=soi_surface_predicate(soi_mode) - ).specs - if soi_mode == SOI_MODE_STATE_CD: - surface = cd_surface.state_cd_soi_surface( - candidates, - state_surface_predicate=soi_surface_predicate(SOI_MODE_STATE), - crosswalk=crosswalk, - crosswalk_sha256=_sha256(crosswalk_path), - ) - picked += list(surface.specs) - soi_receipt.update(surface.receipt) - else: - picked += candidates - soi_receipt["counts"] = {"total": len(candidates)} + if "soi" in selection.rule_receipts: + soi_receipt.update(selection.rule_receipts["soi"]) + elif "soi" in selection.clause_counts: + soi_receipt["counts"] = {"total": selection.clause_counts["soi"]} return AdminSurface( - TargetRegistry(list(picked), country="us"), ri_substitutions, soi_receipt + TargetRegistry(list(selection.specs), country="us"), + ri_substitutions, + soi_receipt, ) diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index c2216463ef..e6847c113b 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -10013,25 +10013,35 @@ def _select_target_surface( ) -> tuple[tuple[TargetSpec, ...], dict[str, object]]: """Return the specs the release calibrates to and a receipt of the choice. - ``full`` keeps every compiled spec. ``national_state`` drops every spec - ``is_congressional_district_target`` classifies as congressional-district - (CD geography rows and rows sourced from the SOI CD file, whatever their - geography). The target-parity and profile-coverage gates run on the full - compiled surface before this selection, so a dropped family is still - proven compiled. + Each mode is declared in ``us/target_sets.json``, product ``national`` + (microcosm#1728). ``full`` keeps every compiled spec. ``national_state`` + drops every spec ``is_congressional_district_target`` classifies as + congressional-district (CD geography rows and rows sourced from the SOI + CD file, whatever their geography), which leaves the country and state + rows of every family. The target-parity and profile-coverage gates run on + the full compiled surface before this selection, so a dropped family is + still proven compiled. """ + from microcosm.build.us_runtime.target_sets import ( + CONGRESSIONAL_DISTRICT_PREDICATE, + NATIONAL_PRODUCT, + us_target_set_declaration, + ) + from microcosm.calibrate.target_sets import select_target_set + if mode not in TARGET_SURFACE_MODES: raise ValueError( f"Unknown target surface {mode!r}; expected one of {TARGET_SURFACE_MODES}." ) specs = tuple(target_specs) - if mode == TARGET_SURFACE_FULL: - kept = specs - else: - kept = tuple( - spec for spec in specs if not _target_is_congressional_district(spec) - ) + kept = select_target_set( + us_target_set_declaration(NATIONAL_PRODUCT, mode), + specs, + predicates={ + CONGRESSIONAL_DISTRICT_PREDICATE: _target_is_congressional_district + }, + ).specs if not kept: raise ValueError(f"Target surface {mode!r} keeps no targets.") return kept, { From 3316038ccd7176e66ac650ae93f170964ae28e19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:54:19 +0000 Subject: [PATCH 03/30] Classify the US target-set module and re-pin the US F0 contracts The US runtime module classification (test_us_spine_blindness) now lists `us_runtime/target_sets.py` as a reviewed non-registry module. It names and loads the declared target sets, selects target specs only, and reads no frame. Registering `us/target_sets.json` as a `legacy_json` row in `country_package.json` adds the row's three normative fields: 42407 configuration fields (32621 authored), the `country_manifest` claim at 116 pointers, and a new pointer inventory digest. The row also moves the US bundle's semantic `spec_sha256` to f130419c, which pool builds record in their run config's spec binding. No target changes. Run on the merge of main 268156c8f, in an environment without country engines: `tools/repin_us_spec_engine_contracts.py --legacy-only` (no change), then without it, then `tools/spec_engine_coverage.py`. Both tools' `--check` modes pass, and coverage reads 42407/42407 fields and 41/41 inventory checks. Co-Authored-By: Claude Opus 5.5 --- docs/evidence/spec-engine/us-f0-coverage.json | 20 +++++++++---------- .../build/spec_engine/field_usage.py | 8 ++++---- .../us/test_spec_engine_coverage_tool.py | 10 +++++----- .../shared/test_spec_engine_field_usage.py | 10 +++++----- .../engine_free/us/test_us_spine_blindness.py | 3 +++ .../us/test_us_multispine_pool_tool.py | 2 +- tools/spec_engine_coverage.py | 2 +- 7 files changed, 29 insertions(+), 26 deletions(-) diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index 7b76e7220a..824a26fa95 100644 --- a/docs/evidence/spec-engine/us-f0-coverage.json +++ b/docs/evidence/spec-engine/us-f0-coverage.json @@ -6,7 +6,7 @@ "country": "us", "documentation_sha256": "fda6ec0dd925077f4d84d30a1c206dd81d82c5e16bd94506e81fe1b9f7e2f466", "field_usage": { - "authored_normative_field_count": 32618, + "authored_normative_field_count": 32621, "claim_count": 48, "claims": [ { @@ -16,8 +16,8 @@ "legacy_sinks": [], "mode": "front_end_validation", "pointer_class": "all", - "pointer_count": 113, - "pointer_sha256": "11b70807bf06832e71367643c7d0e09891c1d4923fe574b471d6632562129897", + "pointer_count": 116, + "pointer_sha256": "3a77833a2aee67d0f58a3dd972f947a79a24afc7c0ebc1821a0e8dd3cbf5771a", "rationale": null, "relative_sink_prefix": null, "source_prefix": "/authored/country_package.json", @@ -758,20 +758,20 @@ "verifier": "vintages" } ], - "configuration_field_count": 42404, - "consumed_field_count": 42404, + "configuration_field_count": 42407, + "consumed_field_count": 42407, "generation0_effect_counts": { "legacy_behavior": 38780, - "no_generation0_effect": 3624 + "no_generation0_effect": 3627 }, "mode_counts": { "compiler_semantic": 27674, - "front_end_validation": 358, + "front_end_validation": 361, "identity_only": 103, "legacy_behavior": 14269 }, "multiple_primary_use_field_count": 0, - "pointer_inventory_sha256": "38fc67ba13d62a5c0eaff36abb8f04d4d2974e21baaed6d2966d76480e643608", + "pointer_inventory_sha256": "b7565bf43ff7139460a8345d3858a6950c4fdcf4cb61afe6b056550040b1c710", "resolved_binding_field_count": 9786, "unused_field_count": 0 }, @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "9f56635edf7da4efa90d01e6ab263eb5f17267ab4bf5b2ad843d76b27f00cfb2" + "spec_sha256": "f130419c1b9d07fb452bc28ca80ff8de07562667e4e2940f0f02f75d550792d6" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "9f56635edf7da4efa90d01e6ab263eb5f17267ab4bf5b2ad843d76b27f00cfb2" + "spec_sha256": "f130419c1b9d07fb452bc28ca80ff8de07562667e4e2940f0f02f75d550792d6" }, "status": "pass" } diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py index d6a9e8751e..4089a583be 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py @@ -26,9 +26,9 @@ ) from .schemas import load_schema_registry -EXPECTED_AUTHORED_FIELD_COUNT = 32618 +EXPECTED_AUTHORED_FIELD_COUNT = 32621 EXPECTED_RESOLVED_BINDING_FIELD_COUNT = 9786 -EXPECTED_CONFIGURATION_FIELD_COUNT = 42404 +EXPECTED_CONFIGURATION_FIELD_COUNT = 42407 class FieldUsageError(AssertionError): @@ -369,8 +369,8 @@ def _path_inventory(rows: Sequence[tuple[str, object]]) -> tuple[int, str]: "bdd9e79157590fade42d28cc2b5d5c8b58e13903af75375a0e3235c94d2a8339", ), "country_manifest": ( - 113, - "11b70807bf06832e71367643c7d0e09891c1d4923fe574b471d6632562129897", + 116, + "3a77833a2aee67d0f58a3dd972f947a79a24afc7c0ebc1821a0e8dd3cbf5771a", ), "generated_authorities": ( 8_614, diff --git a/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py b/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py index 3a8ec0d1df..726dfa5037 100644 --- a/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py +++ b/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py @@ -82,22 +82,22 @@ def test_us_coverage_is_exact_complete_and_honest( assert_coverage_complete(coverage_report) assert coverage_report["status"] == "pass" fields = coverage_report["field_usage"] - assert fields["configuration_field_count"] == 42404 - assert fields["authored_normative_field_count"] == 32618 + assert fields["configuration_field_count"] == 42407 + assert fields["authored_normative_field_count"] == 32621 assert fields["resolved_binding_field_count"] == 9786 - assert fields["consumed_field_count"] == 42404 + assert fields["consumed_field_count"] == 42407 assert fields["unused_field_count"] == 0 assert fields["multiple_primary_use_field_count"] == 0 assert fields["claim_count"] == 48 assert fields["mode_counts"] == { "legacy_behavior": 14_269, "compiler_semantic": 27674, - "front_end_validation": 358, + "front_end_validation": 361, "identity_only": 103, } assert fields["generation0_effect_counts"] == { "legacy_behavior": 38_780, - "no_generation0_effect": 3624, + "no_generation0_effect": 3627, } inventory = coverage_report["inventory_coverage"] diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py index 6db563c643..dbfbae1de4 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py @@ -95,22 +95,22 @@ def _mutated_bundle( def test_exact_complete_ledger_has_one_primary_mode_per_pointer(field_ledger) -> None: - assert len(field_ledger.fields) == EXPECTED_CONFIGURATION_FIELD_COUNT == 42404 + assert len(field_ledger.fields) == EXPECTED_CONFIGURATION_FIELD_COUNT == 42407 assert field_ledger.source_counts == { - "authored": 32618, + "authored": 32621, "resolved_bindings": 9786, } assert field_ledger.mode_counts == { "legacy_behavior": 14_269, "compiler_semantic": 27674, - "front_end_validation": 358, + "front_end_validation": 361, "identity_only": 103, } assert field_ledger.generation0_effect_counts == { "legacy_behavior": 38_780, - "no_generation0_effect": 3624, + "no_generation0_effect": 3627, } - assert len({field.pointer for field in field_ledger.fields}) == 42404 + assert len({field.pointer for field in field_ledger.fields}) == 42407 def test_eligibility_concepts_are_validation_not_generation0_behavior( diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py index a95661f74f..9d843a36ad 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py @@ -472,6 +472,9 @@ # Calibration loss weights computed from target specs alone; reads no # frame and treats no population. "target_loss_weights.py", + # Names and loads the declared US target sets (us/target_sets.json); + # selects target specs only, reads no frame and treats no population. + "target_sets.py", # Data-only final-owner matrix; provenance owner above. "us_late_overlap_ownership.py", # Data-only late input/output registry; provenance owner above. diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py index 1289e207db..58c8cc4e88 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py @@ -373,7 +373,7 @@ def capture_equality(expected: object, actual: object) -> None: # microcosm#1686's shared SIPP person-file read moves it again. # The SIPP 2023 donor download tag and the financial-asset cache lookup # move it again. - "spec_sha256": "9f56635edf7da4efa90d01e6ab263eb5f17267ab4bf5b2ad843d76b27f00cfb2", + "spec_sha256": "f130419c1b9d07fb452bc28ca80ff8de07562667e4e2940f0f02f75d550792d6", }, } diff --git a/tools/spec_engine_coverage.py b/tools/spec_engine_coverage.py index 06ddab569f..8d5af2fa27 100644 --- a/tools/spec_engine_coverage.py +++ b/tools/spec_engine_coverage.py @@ -41,7 +41,7 @@ REPORT_SCHEMA_VERSION = 3 EXPECTED_POINTER_INVENTORY_SHA256 = ( - "38fc67ba13d62a5c0eaff36abb8f04d4d2974e21baaed6d2966d76480e643608" + "b7565bf43ff7139460a8345d3858a6950c4fdcf4cb61afe6b056550040b1c710" ) DEFAULT_REPORT_PATH = ( Path(__file__).resolve().parents[1] From f605ffa07edc812384a2d8bc0a77a6a35d97b62f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:17:36 +0000 Subject: [PATCH 04/30] Pin the bytes of the ACS local target surface on the pinned feed and ladder microcosm#1728 moves the code that builds the local target surface out of the tools. Each move must leave every target, role and receipt as it was. TargetRegistry.version sorts metadata keys, so it does not see a change of key order. Materialize writes target_registry.json and target_roles.json with the keys in insertion order, and their sha256 is in the run identity. test_us_acs_local_surface_bytes.py follows the target part of do_materialize for each non-county --soi-mode: the admin surface, the ladder populations, the role records, the district pro-rata populations, the ladder population rows, and the district and county hold-outs. It pins the sha256 of target_registry.json, of target_roles.json, of the target receipts, and of the population rows' matrix on a household table that supports every ladder cell (a release run refuses a cell with no household). Measured at 3316038cc and run twice: state 4,867 targets, totals 742, full 30,464, state_cd 26,912. The tests run only when MICROCOSM_US_CHRONICLE_FACTS and MICROCOSM_US_PUMA_LADDER_ARTIFACT name the pinned inputs. state_county is not pinned: it needs the pinned county facts, which are not on this machine, and a household frame for its support moves. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_acs_local_surface_bytes.py | 271 ++++++++++++++++++ 1 file changed, 271 insertions(+) create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_acs_local_surface_bytes.py diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_surface_bytes.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_surface_bytes.py new file mode 100644 index 0000000000..79576aac9a --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_surface_bytes.py @@ -0,0 +1,271 @@ +"""The bytes the ACS local materialize stage writes for its targets (microcosm#1728). + +The shared-code work of microcosm#1728 moves the code that builds the local +target surface out of the tools. Each move must leave every target, role and +receipt as it was. ``TargetRegistry.version`` sorts metadata keys, so it does +not see a change of key order; the stage writes ``target_registry.json`` and +``target_roles.json`` with the keys in insertion order, and their sha256 is in +the run identity. These tests pin those bytes. + +For each non-county ``--soi-mode``, the test follows the target part of +``do_materialize``: the admin surface, the ladder populations, the role +records, the district pro-rata populations (``state_cd``), the ladder +population rows, and the district and county hold-outs. The household frame +and the engine pass are not needed for that: a release keeps every compiled +target (a lost one stops the run) and every ladder cell (a cell with no +household stops the run without ``--allow-partial-geography``). So the test +gives the population rows a small household table that supports every ladder +cell, and pins the rows' matrix on that table too. + +The pins were measured at ``3316038cc``, before any code moved. They run only +when ``MICROCOSM_US_CHRONICLE_FACTS`` names the pinned feed and +``MICROCOSM_US_PUMA_LADDER_ARTIFACT`` names the pinned PUMA ladder. The +county mode (``state_county``) needs the pinned county facts and a household +frame for its support moves; it is not pinned here. +""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import os +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import pandas as pd +import pytest + +from microcosm.calibrate import TargetRegistry +from test_support.paths import paths_for + +_TEST_PATHS = paths_for("microcosm-build") + +#: The pinned PUMA ladder (as in ``test_us_target_sets.py``). +PINNED_LADDER_SHA256 = ( + "39a2ab2abeab07a88362af7ab2940e0e1d50a297c919e4bbc6fb65bab51147d8" +) + +#: The tool's defaults: ``--families`` and ``--geographies``. +FAMILIES = ("snap", "medicaid", "soi") +GEOGRAPHIES = ("state", "cd") + +#: For each mode on the pinned feed and ladder: the number of targets, and the +#: sha256 of ``target_registry.json``, of ``target_roles.json``, of the target +#: receipts (SOI surface, district hold-out, county hold-out) and of the +#: population rows' matrix on the supporting household table. +PINNED_BYTES: dict[str, dict[str, object]] = { + "full": { + "targets": 30_464, + "target_registry_sha256": ( + "d568f29827f8c24a07021628c747c4437b212984be9e82ff93cbebc1ec4ecb69" + ), + "target_roles_sha256": ( + "a55d88c7c2b747e7321de6cdae4671dfcb29b3ee5c97587d7983ac888652743a" + ), + "receipts_sha256": ( + "f102782cd2fcfdd896a91bbb163ab1a5120cf06e008aade657cb2b54b4b1eddb" + ), + "population_matrix_sha256": ( + "ae7785b655538f802e9ef7203c3ae6160ad250ed9e22c06c39475ae4614994f4" + ), + }, + "state": { + "targets": 4_867, + "target_registry_sha256": ( + "0157f2b653e51147b8e1b1fc364b0616d1198665718426384349c37cea8a0e4c" + ), + "target_roles_sha256": ( + "929b1b27b62f57c492829b51dd9c0e72a21b470b32345f0475a545f7d76de28d" + ), + "receipts_sha256": ( + "c5f148b6b2f72745dd1c3d470b88743f5acf9c5cc07c10fedeef6c6831f31afc" + ), + "population_matrix_sha256": ( + "ae7785b655538f802e9ef7203c3ae6160ad250ed9e22c06c39475ae4614994f4" + ), + }, + "state_cd": { + "targets": 26_912, + "target_registry_sha256": ( + "fad3ddf61915407fe187d9c739bd379d17c804347dc446e85f3e0303e8518bf3" + ), + "target_roles_sha256": ( + "ffa9c4c964ea84385f0bfe5ef3c1053937897bfcecff941315d0a61f0ab0cca4" + ), + "receipts_sha256": ( + "9c67654cd7c8ab53b68969bf7ea30134871a1407af37d87ae3b2067294efed7f" + ), + "population_matrix_sha256": ( + "ae7785b655538f802e9ef7203c3ae6160ad250ed9e22c06c39475ae4614994f4" + ), + }, + "totals": { + "targets": 742, + "target_registry_sha256": ( + "07a69bf412892b2e5e73868a6d49886c0077c875b07cce293bc742745d858d16" + ), + "target_roles_sha256": ( + "c1d5eca2710f97a073c111273b78d2d9e0f58777314b1bd74eb8dd95410a686e" + ), + "receipts_sha256": ( + "7195a0a24ce81a4f63d680781d9fbdc2b3f4a50c9d2b3fe1e16e9f4eff66e3e9" + ), + "population_matrix_sha256": ( + "ae7785b655538f802e9ef7203c3ae6160ad250ed9e22c06c39475ae4614994f4" + ), + }, +} + + +def _load_tool(name: str): + path = _TEST_PATHS.repository / "tools" / f"{name}.py" + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module + + +def _pinned_inputs() -> tuple[str, Path]: + feed = os.environ.get("MICROCOSM_US_CHRONICLE_FACTS", "") + if not feed or not Path(feed).exists(): + pytest.skip("set MICROCOSM_US_CHRONICLE_FACTS to the pinned 41b2fb2 feed") + ladder = os.environ.get("MICROCOSM_US_PUMA_LADDER_ARTIFACT", "") + if not ladder or not Path(ladder).exists(): + pytest.skip("set MICROCOSM_US_PUMA_LADDER_ARTIFACT to the PUMA ladder") + assert hashlib.sha256(Path(ladder).read_bytes()).hexdigest() == PINNED_LADDER_SHA256 + return feed, Path(ladder) + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _supporting_households(populations) -> tuple[pd.DataFrame, np.ndarray]: + """One household in each ladder district, and in each state with none.""" + + districts = sorted(int(code) for code in populations["cd"]) + states = {code // 100 for code in districts} + rows = [ + {"state_fips": code // 100, "congressional_district_geoid": code} + for code in districts + ] + rows += [ + {"state_fips": int(code), "congressional_district_geoid": 0} + for code in sorted(populations["state"]) + if int(code) not in states + ] + households = pd.DataFrame(rows) + return households, np.ones(len(households), dtype=np.float32) + + +def materialize_target_part(local_tool, feed: str, ladder: Path, soi_mode: str): + """The target part of ``do_materialize`` for one mode, without a frame. + + Returns ``(specs, roles, receipts, population_matrix)`` in the order the + stage writes them. + """ + + cd_surface = local_tool.cd_surface + county_surface = local_tool.county_surface + args = SimpleNamespace( + soi_mode=soi_mode, + cd_holdout_fraction=None, + county_column="county_fips", + county_holdout_fraction=county_surface.DEFAULT_COUNTY_HOLDOUT_FRACTION, + county_holdout_salt=county_surface.COUNTY_HOLDOUT_SALT, + ) + holdout_fraction = local_tool._cd_holdout_fraction(args) + surface = local_tool.state_admin_surface(feed, list(FAMILIES), soi_mode=soi_mode) + registry = surface.registry + populations = local_tool.ladder_population( + ladder, + sorted(set(GEOGRAPHIES) | {"cd"}), + county_column="county_fips", + ) + local_tool.require_one_label_per_geography(registry, populations, list(GEOGRAPHIES)) + compiled_specs = list(registry.specs) + admin_roles = [county_surface.target_record(spec) for spec in compiled_specs] + if soi_mode == local_tool.SOI_MODE_STATE_CD: + local_tool._attach_pro_rata_populations(admin_roles, populations["cd"]) + local_tool._require_pro_rata_populations(admin_roles) + households, sizes = _supporting_households(populations) + pop_roles, pop_matrix, pop_dropped = cd_surface.population_rows( + households, + sizes, + populations, + list(GEOGRAPHIES), + county_column="county_fips", + ) + assert pop_dropped == [] + pop_specs = local_tool.population_target_specs( + [record["name"] for record in pop_roles], + [record["value"] for record in pop_roles], + ) + roles = admin_roles + pop_roles + holdout = cd_surface.assign_target_roles(roles, fraction=holdout_fraction) + county_holdout = county_surface.assign_roles(roles, args) + receipts = { + "soi_surface": surface.soi_receipt, + "cd_holdout": holdout, + "county_holdout": county_holdout, + } + return (*compiled_specs, *pop_specs), roles, receipts, pop_matrix + + +def surface_bytes(local_tool, feed: str, ladder: Path, soi_mode: str, tmp_path: Path): + """The pinned measurements of one mode (see ``PINNED_BYTES``).""" + + specs, roles, receipts, pop_matrix = materialize_target_part( + local_tool, feed, ladder, soi_mode + ) + registry_path = tmp_path / f"target_registry_{soi_mode}.json" + TargetRegistry(specs, country="us").to_json(registry_path) + matrix = ( + str(pop_matrix.shape).encode() + + pop_matrix.indptr.astype(np.int64).tobytes() + + pop_matrix.indices.astype(np.int64).tobytes() + + pop_matrix.data.astype(np.float32).tobytes() + ) + return { + "targets": len(specs), + "target_registry_sha256": _sha256(registry_path.read_bytes()), + "target_roles_sha256": _sha256(json.dumps(roles, indent=1).encode()), + "receipts_sha256": _sha256(json.dumps(receipts, indent=1).encode()), + "population_matrix_sha256": _sha256(matrix), + } + + +@pytest.fixture(scope="module") +def local_tool(): + return _load_tool("build_us_acs_local_release") + + +@pytest.mark.parametrize("soi_mode", sorted(PINNED_BYTES)) +def test_pinned_feed_local_surface_bytes_are_unchanged( + local_tool, soi_mode: str, tmp_path: Path +) -> None: + feed, ladder = _pinned_inputs() + assert ( + surface_bytes(local_tool, feed, ladder, soi_mode, tmp_path) + == (PINNED_BYTES[soi_mode]) + ) + + +def test_every_non_county_mode_is_pinned(local_tool) -> None: + assert set(PINNED_BYTES) == set(local_tool.SOI_MODES) - { + local_tool.county_surface.SOI_MODE + } + + +def test_the_supporting_households_cover_every_cell() -> None: + populations = {"state": {6: 1.0, 11: 1.0, 72: 1.0}, "cd": {601: 1.0, 1198: 1.0}} + households, sizes = _supporting_households(populations) + assert households.to_dict("records") == [ + {"state_fips": 6, "congressional_district_geoid": 601}, + {"state_fips": 11, "congressional_district_geoid": 1198}, + {"state_fips": 72, "congressional_district_geoid": 0}, + ] + assert sizes.tolist() == [1.0, 1.0, 1.0] From fb34e5e29101af22fd452904a423675d96a0e7a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:42:46 +0000 Subject: [PATCH 05/30] Move the US ledger filter rules into us_runtime and compile in one place C1 of the shared-code work in microcosm#1728. No target changes. - The ledger filter rules move verbatim from tools/build_us_fiscal_refresh_release.py to microcosm.build.us_runtime.ledger_filter_rules: 25 names, 446 lines. They say how the national irs_soi slice reads a spec's AGI band, filing status and EITC child count, and which restated ledger_filter_* keys a spec may carry. Each definition is byte-identical. The tool imports all 25 names back (its materializer and filter guard call them, and tests and tools/bakeoff_us_support_mix.py read them there). It drops the two FSA balance-bound imports that only the moved code used, and keeps the two age-stamp keys, which a test reads through the tool. - tools/us_acs_local_cd_surface.py reads the rules from the package, so it no longer imports the national tool. - tools/build_us_acs_local_release.py compiles the registry in one function: _compiled_fiscal_registry takes the district crosswalk that state_admin_surface also gives the state_cd rule. - test_us_spine_blindness.py classifies the new module. - Two tests in test_us_fiscal_refresh_builder.py changed a rule on a freshly loaded tool and relied on that copy being thrown away. The rules now live in one package module that every load shares, so both use monkeypatch: one removes the age rule for its own run only, and one empties the refused EITC child-count sides where the comparison reads them. Proof: test_us_acs_local_surface_bytes.py (the C0 pins) passes unchanged on the pinned feed and ladder for state, totals, full and state_cd, and the pinned surfaces of test_us_target_sets.py pass. In all, 3,714 tests in the 47 files that load the changed tools or hold the module and binding registers pass locally (8 skipped), with the pinned feed and ladder set. Left for later commits, as planned: the import cycle between the district and county modules goes when C3 moves the population rows, and the county code's use of the argparse namespace moves with the county rung (C5), because #1719 changes check_support. Co-Authored-By: Claude Opus 5.5 --- .../1728-us-ledger-filter-rules.changed.md | 1 + .../build/us_runtime/ledger_filter_rules.py | 525 ++++++++++++++++++ .../us/test_us_fiscal_refresh_builder.py | 22 +- .../engine_free/us/test_us_spine_blindness.py | 3 + tools/build_us_acs_local_release.py | 31 +- tools/build_us_fiscal_refresh_release.py | 523 ++--------------- tools/us_acs_local_cd_surface.py | 32 +- 7 files changed, 608 insertions(+), 529 deletions(-) create mode 100644 changelog.d/1728-us-ledger-filter-rules.changed.md create mode 100644 packages/microcosm-build/src/microcosm/build/us_runtime/ledger_filter_rules.py diff --git a/changelog.d/1728-us-ledger-filter-rules.changed.md b/changelog.d/1728-us-ledger-filter-rules.changed.md new file mode 100644 index 0000000000..dd0e319e22 --- /dev/null +++ b/changelog.d/1728-us-ledger-filter-rules.changed.md @@ -0,0 +1 @@ +The US ledger filter rules (how the national `irs_soi` slice reads a spec's AGI band, filing status and EITC child count, and which restated `ledger_filter_*` keys a spec may carry) moved unchanged from `tools/build_us_fiscal_refresh_release.py` to `microcosm.build.us_runtime.ledger_filter_rules` (microcosm#1728). The tool imports them back under the same names, and the ACS local district surface reads them from the package instead of importing the tool. The ACS local tool now compiles the target registry in one function, `_compiled_fiscal_registry`. No target changes: `test_us_acs_local_surface_bytes.py` pins the bytes of the local registry, roles and target receipts on the pinned feed and ladder. diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/ledger_filter_rules.py b/packages/microcosm-build/src/microcosm/build/us_runtime/ledger_filter_rules.py new file mode 100644 index 0000000000..e580ad53aa --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/ledger_filter_rules.py @@ -0,0 +1,525 @@ +"""Which ``ledger_filter_*`` metadata the US materializers act on. + +The national release tool (``tools/build_us_fiscal_refresh_release.py``) +materializes each compiled target spec. These rules say how its ``irs_soi`` +slice reads a spec's AGI band, filing status and EITC child count, and which +restated ``ledger_filter_*`` keys a spec may carry. microcosm#1728 moved them +here from the tool, unchanged, so that the ACS local district surface +(``tools/us_acs_local_cd_surface.py``) reads them without importing the tool. +The tool imports them back under the same names. Function references in the +comments below (``_materialize_target_frame`` and others) are the tool's. +""" + +from __future__ import annotations + +import math +from collections.abc import Mapping + +import numpy as np + +from microcosm.build.us_runtime.fiscal_targets import ( + AGE_BOUND_STAMP_FROM_CONSTRAINT_ROWS, + AGE_BOUND_STAMP_SOURCE_KEY, +) +from microcosm.build.us_runtime.fsa_student_loan_targets import ( + FSA_BALANCE_LOWER_BOUND_KEY, + FSA_BALANCE_UPPER_BOUND_KEY, + FSA_MATERIALIZER, +) + +#: Restated constraints, a third class distinct from both the supported and +#: the identity ledger filter keys (``SUPPORTED_LEDGER_FILTER_METADATA_KEYS`` +#: and ``IDENTITY_LEDGER_FILTER_METADATA_KEYS`` in the national release tool): a +#: labelled feed re-expresses a fact's universe constraint in the Ledger's own +#: concept vocabulary (``us:statutes/26/62#adjusted_gross_income_lower_bound``) +#: alongside the compiled metadata the materializer actually slices on +#: (``agi_lower_bound``). These keys are NOT inert — they restrict the +#: microdata — so they can never join the supported set outright: a future +#: feed whose labelled bound disagreed with the compiled one would then be +#: silently ignored, materializing a wider population than the published cell +#: covers, which is the failure the guard exists to stop. Each key here is +#: accepted only per spec, and only when that spec also carries the filter the +#: materializer applies and the two select the same population; a restatement +#: that disagrees, or that has no compiled counterpart, stays fatal and the +#: refusal names the values. Values are the restated-constraint rule that +#: decides the comparison (see ``_restated_ledger_filter_refusal``). +RESTATED_LEDGER_FILTER_CONCEPTS = { + "us:statutes/26/62#adjusted_gross_income": "agi_band", + "us.tax.earned_income_credit_qualifying_children": "eitc_child_count", + "age": "age_band", + "federal_student_loan_balance": "student_loan_balance_band", +} + + +#: Bound-side suffixes a restated constraint key may carry. A key with no +#: suffix restates an exact value of the concept. +RESTATED_LEDGER_FILTER_BOUND_SIDES = ( + ("_lower_bound", "lower"), + ("_upper_bound", "upper"), +) + + +#: Compiled metadata the materializer slices the AGI band on, by bound +#: side: the ``irs_soi`` loop in :func:`_materialize_target_frame` reads +#: both through :func:`_as_bound` into one half-open mask. A restated AGI +#: bound is accepted only against its own side; the sibling side is judged +#: by its own key. +RESTATED_AGI_BAND_COMPILED_KEYS = { + "lower": "agi_lower_bound", + "upper": "agi_upper_bound", +} + + +#: Qualifying-child counts probed when deciding whether a restated EITC +#: child-count bound selects the same returns as the compiled filter. +#: :func:`_eitc_child_count_mask` resolves every compiled value to ``== 0``, +#: ``== 1``, ``== 2`` or ``>= 3``, and a compared restatement is ``>= n`` or +#: ``== n`` (an upper bound is refused before any comparison; see +#: :data:`RESTATED_EITC_CHILD_COUNT_REFUSED_SIDES`); evaluating both over +#: 0..16 separates every such pair, so equal masks over the probe mean equal +#: populations. Counts above the probe are refused rather than compared. +RESTATED_EITC_CHILD_COUNT_PROBE_MAX = 16 + + +#: Bound sides on which a restated EITC qualifying-child key is refused +#: outright, whatever its value and whatever the spec compiles. What an upper +#: bound selects turns on the Ledger's operator — ``< 1`` is the childless +#: returns, ``<= 1`` adds the one-child returns — and that operator is +#: unconfirmed for count constraints. The metadata key does not settle it: +#: :func:`microcosm.build.ledger_targets._constraint_bound_filters` stamps a +#: ``<`` row as ``_upper_bound`` (``<=`` becomes ``_upper_bound_inclusive``, +#: which no restated concept names, so it is refused by bare key), but the +#: dimension stamp in ``_ledger_metadata`` runs first and wins through +#: ``setdefault``, and can carry the same key with no operator at all. So no +#: reading is guessed until the Ledger confirms one (Max, 2026-09-22). Lower +#: and exact restatements stay under the agreement rule. +RESTATED_EITC_CHILD_COUNT_REFUSED_SIDES = frozenset({"upper"}) + + +#: Compiled metadata the materializer slices a person-age band on, by bound +#: side. Both age paths in :func:`_materialize_target_frame` read these +#: through :func:`_as_bound` into one half-open mask ``lower <= age < upper`` +#: — the ``population_age`` loop in :func:`_population_age_household_values` +#: and the age-banded ``policyengine_variable`` branch (the SSA SSI +#: recipients-by-age counts) — so a restated age bound is judged, like an AGI +#: bound, against its own side only. +#: +#: Numeric equality of the edges is equality of populations only for a +#: restated key whose operator is the mask's: ``age < 10`` and ``age <= 10`` +#: differ by everyone aged exactly ten, so the operator decides. +#: :func:`microcosm.build.ledger_targets._constraint_bound_filters` writes +#: ``age_lower_bound`` only for a ``>=`` row and ``age_upper_bound`` only for +#: a ``<`` row, the two operators of the materializer's mask. A ``>`` or +#: ``<=`` row is stamped ``age_lower_bound_exclusive`` / +#: ``age_upper_bound_inclusive``, which no restated concept names, so it stays +#: refused by bare key — as it must, because the compiled bound comes from +#: ``us_runtime.fiscal_targets._age_bounds``, which drops the operator: a +#: ``<= 4`` row compiles to ``age_upper_bound=4`` and the materializer's +#: ``age < 4`` would leave out the four-year-olds the published cell counts. +#: But the same ``ledger_filter_age_{lower,upper}_bound`` key can also be a +#: dimension's, which carries no operator (the ambiguity that keeps restated +#: qualifying-child upper bounds refused), so the key name alone does not +#: settle it; the compile's attestation does +#: (:data:`microcosm.build.us_runtime.fiscal_targets.AGE_BOUND_STAMP_SOURCE_KEY`). +RESTATED_AGE_BAND_COMPILED_KEYS = { + "lower": "age_lower_bound", + "upper": "age_upper_bound", +} + + +#: Materializers that apply the compiled age band, and so the only ones for +#: which ignoring an agreeing age restatement changes nothing. Both are read +#: in :func:`_materialize_target_frame`: ``population_age`` through +#: :func:`_population_age_household_values`, and ``policyengine_variable`` +#: through its age-banded branch, entered whenever either compiled age key is +#: present. Every other materializer (the ``irs_soi`` slice, the direct +#: household-variable measures) never reads an age bound, so a restated age +#: bound there would be silently ignored however well it agreed with metadata +#: the materializer also ignores; it is refused instead. +RESTATED_AGE_BAND_MATERIALIZERS = frozenset( + {"population_age", "policyengine_variable", FSA_MATERIALIZER} +) + + +#: Compiled edges of a Federal Student Aid debt-size band, by bound side, and +#: the one materializer that slices on them +#: (:func:`microcosm.build.us_runtime.fsa_student_loan_targets.fsa_student_loan_household_values`, +#: ``lower <= balance < upper`` on the person's own plus Parent PLUS balance, +#: microcosm#1074). A restated ``federal_student_loan_balance`` bound on any +#: other materializer would be ignored, so it refuses. +RESTATED_STUDENT_LOAN_BALANCE_BAND_COMPILED_KEYS = { + "lower": FSA_BALANCE_LOWER_BOUND_KEY, + "upper": FSA_BALANCE_UPPER_BOUND_KEY, +} + + +#: The exact-value age key the dimension stamp writes when ``age`` is itself +#: a dimension of the fact. +#: :func:`microcosm.build.ledger_targets._constraint_bound_filters` skips +#: every constraint row whose variable is already a dimension key, so on +#: such a fact an ``age_{lower,upper}_bound`` restatement cannot have come +#: from an operator-checked ``>=``/``<`` row — only from a dimension of that +#: name, which carries no operator at all. A restated age bound on a spec +#: carrying this key is refused, whatever its value, including ``all``. +#: ``_ledger_metadata`` stamps a dimension only when its value is not +#: ``None`` and then drops empty values, so an ``age`` dimension valued +#: ``None`` or ``""`` leaves no key here; the compile's attestation +#: (:data:`AGE_BOUND_STAMP_SOURCE_KEY`, which checks dimension keys whatever +#: their value) is what refuses that case. The pinned feeds have no age +#: dimension of any kind. +RESTATED_AGE_DIMENSION_KEY = "ledger_filter_age" + + +SUPPORTED_SOI_LEDGER_FILTERS = frozenset( + { + "ledger_filter_income_range", + "ledger_filter_filing_status", + "ledger_filter_eitc_child_count", + } +) + + +def _soi_eitc_child_count_filter(metadata: Mapping[str, str]) -> str | None: + explicit = metadata.get("ledger_filter_eitc_child_count") + if explicit and explicit.strip().lower() != "all": + return explicit + record_set = metadata.get("ledger_layout_record_set_id", "") + if record_set.endswith(".eitc_by_agi_children.no_qualifying_children"): + return "0" + if record_set.endswith(".eitc_by_agi_children.one_qualifying_child"): + return "1" + if record_set.endswith(".eitc_by_agi_children.two_qualifying_children"): + return "2" + if record_set.endswith(".eitc_by_agi_children.three_or_more_qualifying_children"): + return "3plus" + measure = metadata.get("source_measure_id", "") + if measure.startswith("eitc_no_children_"): + return "0" + if measure.startswith("eitc_one_child_"): + return "1" + if measure.startswith("eitc_two_children_"): + return "2" + if measure.startswith("eitc_three_or_more_children_"): + return "3plus" + return None + + +def _soi_requires_positive_eitc_filter(metadata: Mapping[str, str]) -> bool: + return ( + metadata.get("ledger_domain") + == "individual_income_tax_returns_with_earned_income_credit" + ) + + +def _is_noop_ledger_filter_value(value: str) -> bool: + return value.strip().lower().replace("_", " ") in {"", "all"} + + +def _unsupported_soi_ledger_filters(metadata: Mapping[str, str]) -> tuple[str, ...]: + """Ledger filter keys the SOI slice does not act on, for one spec. + + A non-empty result drops the spec from SOI materialization silently in + the ``irs_soi`` loop of :func:`_materialize_target_frame`, so an + accepted restatement must clear here too — otherwise + accepting it at the fatal guard would only move the spec from a refusal + to a silent disappearance. A restatement that disagrees stays listed, and + :func:`_assert_supported_ledger_filter_metadata` refuses it before the + materializer ever reaches this skip. + """ + + return tuple( + sorted( + key + for key, value in metadata.items() + if key.startswith("ledger_filter_") + and key not in SUPPORTED_SOI_LEDGER_FILTERS + and not _is_noop_ledger_filter_value(str(value)) + and _restated_ledger_filter_refusal(str(key), str(value), metadata) + is not None + ) + ) + + +def _eitc_child_count_mask(values: np.ndarray, filter_value: str) -> np.ndarray: + counts = np.asarray(values, dtype=np.float64) + normalized = str(filter_value).strip().lower().replace("_", " ") + if normalized in {"0", "none", "no children", "no qualifying children"}: + return counts == 0 + if normalized in {"1", "one", "one child", "one qualifying child"}: + return counts == 1 + if normalized in {"2", "two", "two children", "two qualifying children"}: + return counts == 2 + if normalized in { + "3", + "3+", + "3plus", + "three", + "three plus", + "three or more", + "three or more children", + "three or more qualifying children", + }: + return counts >= 3 + raise ValueError(f"Unsupported EITC child-count filter {filter_value!r}.") + + +def _as_bound(value: str) -> float: + if value == "-inf": + return -math.inf + if value == "inf": + return math.inf + return float(value) + + +def _restated_ledger_filter_concept(key: str) -> tuple[str, str | None]: + """Split a ``ledger_filter_*`` key into its concept and bound side. + + ``ledger_filter_us:statutes/26/62#adjusted_gross_income_lower_bound`` + splits into ``("us:statutes/26/62#adjusted_gross_income", "lower")``; a + key with no bound suffix keeps the whole concept and side ``None``, + meaning it restates an exact value. + """ + + if not key.startswith("ledger_filter_"): + return "", None + concept = key[len("ledger_filter_") :] + for suffix, side in RESTATED_LEDGER_FILTER_BOUND_SIDES: + if concept.endswith(suffix) and len(concept) > len(suffix): + return concept[: -len(suffix)], side + return concept, None + + +def _restated_bound_value(value: str) -> float | None: + try: + return _as_bound(value.strip()) + except ValueError: + return None + + +def _restated_count_value(value: str) -> float | None: + try: + count = float(value.strip()) + except ValueError: + return None + if not count.is_integer() or not 0 <= count <= RESTATED_EITC_CHILD_COUNT_PROBE_MAX: + return None + return count + + +def _restated_band_edge_refusal( + key: str, + value: str, + metadata: Mapping[str, str], + *, + compiled_key: str, +) -> str | None: + """Judge one restated half-open band edge against the edge it restates. + + Shared by the AGI and age rules, whose materializers both slice + ``lower <= x < upper`` on the compiled edge read through + :func:`_as_bound`, so a restated edge is ignorable exactly when it parses + to the same number. A missing compiled edge refuses: the age paths would + read it as the open end and the ``irs_soi`` loop indexes it directly, and + neither is the restated edge being checked. + """ + + compiled = metadata.get(compiled_key) + if compiled is None: + return f"{key}={value} restates a bound the spec does not compile: no {compiled_key}" + restated = _restated_bound_value(value) + applied = _restated_bound_value(str(compiled)) + if restated is None or applied is None or restated != applied: + return f"{key}={value} disagrees with {compiled_key}={compiled}" + return None + + +def _restated_agi_band_refusal( + key: str, + value: str, + metadata: Mapping[str, str], + *, + side: str | None, +) -> str | None: + if side is None: + return ( + f"{key}={value} restates an exact AGI, but the materializer " + "slices a half-open AGI band and applies no exact-value AGI filter" + ) + return _restated_band_edge_refusal( + key, value, metadata, compiled_key=RESTATED_AGI_BAND_COMPILED_KEYS[side] + ) + + +def _restated_age_band_refusal( + key: str, + value: str, + metadata: Mapping[str, str], + *, + side: str | None, +) -> str | None: + if side is None: + return ( + f"{key}={value} restates an exact age, but the materializer " + "slices a half-open age band and applies no exact-age filter" + ) + if RESTATED_AGE_DIMENSION_KEY in metadata: + return ( + f"{key}={value} restates an age bound on a fact whose dimensions " + f"include age ({RESTATED_AGE_DIMENSION_KEY}=" + f"{metadata[RESTATED_AGE_DIMENSION_KEY]}), so the bound came from " + "the dimension stamp, which carries no operator" + ) + materializer = metadata.get("materializer") + if materializer not in RESTATED_AGE_BAND_MATERIALIZERS: + return ( + f"{key}={value} restates an age bound on a spec whose materializer " + f"({materializer!r}) applies no age band" + ) + stamp_source = metadata.get(AGE_BOUND_STAMP_SOURCE_KEY) + if stamp_source != AGE_BOUND_STAMP_FROM_CONSTRAINT_ROWS: + return ( + f"{key}={value} restates an age bound whose operator is ambiguous: " + f"{AGE_BOUND_STAMP_SOURCE_KEY}={stamp_source} does not attest it " + "was stamped from a constraint row (>= or <), and a dimension of " + "that name carries no operator" + ) + return _restated_band_edge_refusal( + key, value, metadata, compiled_key=RESTATED_AGE_BAND_COMPILED_KEYS[side] + ) + + +def _restated_student_loan_balance_band_refusal( + key: str, + value: str, + metadata: Mapping[str, str], + *, + side: str | None, +) -> str | None: + if side is None: + return ( + f"{key}={value} restates an exact federal student loan balance, but " + "the materializer slices a half-open balance band" + ) + materializer = metadata.get("materializer") + if materializer != FSA_MATERIALIZER: + return ( + f"{key}={value} restates a federal student loan balance bound on a " + f"spec whose materializer ({materializer!r}) applies no balance band" + ) + return _restated_band_edge_refusal( + key, + value, + metadata, + compiled_key=RESTATED_STUDENT_LOAN_BALANCE_BAND_COMPILED_KEYS[side], + ) + + +def _restated_eitc_child_count_refusal( + key: str, + value: str, + metadata: Mapping[str, str], + *, + side: str | None, +) -> str | None: + if side in RESTATED_EITC_CHILD_COUNT_REFUSED_SIDES: + return ( + f"{key}={value} restates a qualifying-child {side} bound, refused " + "outright: the Ledger's operator for it (< or <=) is unconfirmed, " + "and the two readings select different returns" + ) + compiled = _soi_eitc_child_count_filter(metadata) + if compiled is None: + return ( + f"{key}={value} restates a qualifying-child bound on a spec that " + "carries no child-count filter for the materializer to apply" + ) + bound = _restated_count_value(value) + if bound is None: + return ( + f"{key}={value} is not a qualifying-child count in " + f"0..{RESTATED_EITC_CHILD_COUNT_PROBE_MAX}" + ) + counts = np.arange(RESTATED_EITC_CHILD_COUNT_PROBE_MAX + 1, dtype=np.float64) + if side == "lower": + restated_mask = counts >= bound + elif side is None: + restated_mask = counts == bound + else: + raise ValueError( + f"{key}: bound side {side!r} reached the qualifying-child " + "comparison, which reads only lower and exact restatements" + ) + try: + applied_mask = _eitc_child_count_mask(counts, compiled) + except ValueError: + return ( + f"{key}={value} cannot be compared: compiled child-count filter " + f"{compiled!r} is not one the materializer understands" + ) + if not np.array_equal(restated_mask, applied_mask): + return ( + f"{key}={value} selects different returns than the compiled " + f"child-count filter {compiled!r}" + ) + return None + + +def _restated_ledger_filter_refusal( + key: str, + value: str, + metadata: Mapping[str, str], +) -> str | None: + """Judge one otherwise-unsupported ``ledger_filter_*`` key for one spec. + + Returns ``None`` only when *key* restates, in the labelled feed's concept + vocabulary, a constraint the materializer already applies to this spec, + and the two select the same population — ignoring that restatement then + changes nothing. Every other key returns the entry to refuse with: the + bare key for a filter the materializer does not model (unchanged from + before this rule existed), or the key with both values when a restatement + disagrees with its compiled counterpart, or has none, or is applied by + no materializer for this spec, or — for a + qualifying-child upper bound, whose operator is unconfirmed (see + :data:`RESTATED_EITC_CHILD_COUNT_REFUSED_SIDES`) — the key with that + reason, whatever the spec compiles. + + Two compiled counterparts — the AGI band in + :data:`RESTATED_AGI_BAND_COMPILED_KEYS` and + :func:`_soi_eitc_child_count_filter` — are the ``irs_soi`` slice's, read + in the loop :func:`_materialize_target_frame` runs over ``irs_soi`` + specs, and this rule reads them off metadata without consulting the + spec's family. That family-blindness is the guard's existing shape: + ``ledger_filter_eitc_child_count`` is likewise a blanket supported key. A + spec of another family carries neither counterpart, so it refuses on the + "does not compile" arm rather than being accepted by accident. + + The third, the person-age band in :data:`RESTATED_AGE_BAND_COMPILED_KEYS`, + is read by two materializers (``population_age`` and the age-banded + ``policyengine_variable`` branch), so that rule is family-blind too but + names the materializers that apply the band + (:data:`RESTATED_AGE_BAND_MATERIALIZERS`) and refuses on every other; it + also refuses a bound on a fact whose dimensions include ``age`` + (:data:`RESTATED_AGE_DIMENSION_KEY`), and any bound the compile does not + attest was stamped from a ``>=`` / ``<`` constraint row + (:data:`AGE_BOUND_STAMP_SOURCE_KEY`): a dimension-stamped bound carries no + operator, and ``age < 10`` and ``age <= 10`` select different people. + """ + + concept, side = _restated_ledger_filter_concept(key) + rule = RESTATED_LEDGER_FILTER_CONCEPTS.get(concept) if concept else None + if rule is None: + return key + if rule == "agi_band": + return _restated_agi_band_refusal(key, value, metadata, side=side) + if rule == "eitc_child_count": + return _restated_eitc_child_count_refusal(key, value, metadata, side=side) + if rule == "age_band": + return _restated_age_band_refusal(key, value, metadata, side=side) + if rule == "student_loan_balance_band": + return _restated_student_loan_balance_band_refusal( + key, value, metadata, side=side + ) + raise ValueError( + f"RESTATED_LEDGER_FILTER_CONCEPTS maps {concept!r} to rule {rule!r}, " + "which has no comparison implemented." + ) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py index 5611c05447..7f672a88c1 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py @@ -4095,7 +4095,9 @@ def test_restated_eitc_child_upper_bounds_are_refused_outright() -> None: builder._assert_supported_ledger_filter_metadata(specs[:1]) -def test_restated_eitc_child_comparison_never_guesses_an_upper_reading() -> None: +def test_restated_eitc_child_comparison_never_guesses_an_upper_reading( + monkeypatch: pytest.MonkeyPatch, +) -> None: """Dropping ``upper`` from the refused sides must not reopen a guess. The comparison reads only lower and exact restatements. If a later edit @@ -4105,8 +4107,14 @@ def test_restated_eitc_child_comparison_never_guesses_an_upper_reading() -> None compiled ``0``). """ + from microcosm.build.us_runtime import ledger_filter_rules + builder = _load_builder_module() - builder.RESTATED_EITC_CHILD_COUNT_REFUSED_SIDES = frozenset() + # The comparison reads the refused sides where the rules live + # (us_runtime.ledger_filter_rules, microcosm#1728), so the edit goes there. + monkeypatch.setattr( + ledger_filter_rules, "RESTATED_EITC_CHILD_COUNT_REFUSED_SIDES", frozenset() + ) metadata = _soi_band_metadata( ledger_filter_eitc_child_count="0", **{_RESTATED_EITC_CHILDREN_UPPER: "0"}, @@ -4298,7 +4306,9 @@ def _ssa_age_band_metadata(**overrides: str | None) -> dict[str, str]: return metadata -def test_restated_age_bounds_pass_the_guard_only_where_they_agree() -> None: +def test_restated_age_bounds_pass_the_guard_only_where_they_agree( + monkeypatch: pytest.MonkeyPatch, +) -> None: """A restated age bound equal to the compiled one is ignorable, so accepted. The Ledger stamp restates a fact's ``age >= a`` / ``age < b`` rows as @@ -4348,8 +4358,10 @@ def test_restated_age_bounds_pass_the_guard_only_where_they_agree() -> None: assert builder._unsupported_soi_ledger_filters(spec.metadata) == () # Non-vacuity: with the concept unnamed, the same specs get the bare-key - # refusal every one of them got before this rule. - del builder.RESTATED_LEDGER_FILTER_CONCEPTS["age"] + # refusal every one of them got before this rule. The rules live in + # us_runtime.ledger_filter_rules, which every load of the tool shares, so + # the entry is removed for this test only (microcosm#1728). + monkeypatch.delitem(builder.RESTATED_LEDGER_FILTER_CONCEPTS, "age") refused = builder._unsupported_ledger_filter_metadata(specs) assert set(refused) == {spec.name for spec in specs} assert refused[specs[0].name] == (_RESTATED_AGE_LOWER, _RESTATED_AGE_UPPER) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py index 9d843a36ad..1feb1ee7e8 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py @@ -365,6 +365,9 @@ "h5_io.py", # US artifact I/O; no population treatment. "immigration.py", "input_mass.py", + # The national materializer's ledger filter rules (moved from the + # release tool, microcosm#1728); reads spec metadata only, no frame. + "ledger_filter_rules.py", "l0_refit_export.py", "late_producer_dag.py", # Pure contract/schedule derivation; no treatment. "medicaid_take_up.py", diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index 15884450ab..bdcd696606 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -665,11 +665,14 @@ def soi_surface_predicate(soi_mode: str): ) -def _compiled_fiscal_registry(feed: str | Path): +def _compiled_fiscal_registry(feed: str | Path, *, crosswalk=None): """The production compile path and its reviewed substitution records. feed -> ``compile_us_fiscal_target_registry(age_targets=True)`` -> ``apply_us_medicaid_enrollment_substitutions`` (RI FIPS-44). + ``crosswalk`` is the congressional-district vintage crosswalk the compile + reads; by default the reviewed one. :func:`state_admin_surface` passes the + one it also gives the ``state_cd`` rule, so the tool compiles in one place. """ from microcosm.build.ledger_artifact import load_ledger_consumer_artifact @@ -685,14 +688,14 @@ def _compiled_fiscal_registry(feed: str | Path): ) artifact = load_ledger_consumer_artifact(str(feed)) + if crosswalk is None: + crosswalk = load_congressional_district_vintage_crosswalk( + default_congressional_district_vintage_crosswalk_path() + ) registry = compile_us_fiscal_target_registry( artifact.facts, target_period=PERIOD, - congressional_district_vintage_crosswalk=( - load_congressional_district_vintage_crosswalk( - default_congressional_district_vintage_crosswalk_path() - ) - ), + congressional_district_vintage_crosswalk=crosswalk, age_targets=True, ) return apply_us_medicaid_enrollment_substitutions(registry) @@ -739,17 +742,10 @@ def state_admin_surface( # Refuse an unknown mode before loading the feed and compiling the registry. _require_soi_mode(soi_mode) - from microcosm.build.ledger_artifact import load_ledger_consumer_artifact from microcosm.build.us_runtime import ( default_congressional_district_vintage_crosswalk_path, load_congressional_district_vintage_crosswalk, ) - from microcosm.build.us_runtime.fiscal_targets import ( - compile_us_fiscal_target_registry, - ) - from microcosm.build.us_runtime.medicaid_take_up import ( - apply_us_medicaid_enrollment_substitutions, - ) from microcosm.build.us_runtime.target_sets import ( LOCAL_PRODUCT, STATE_CD_RULE, @@ -758,16 +754,9 @@ def state_admin_surface( from microcosm.calibrate.registry import TargetRegistry from microcosm.calibrate.target_sets import select_target_set - artifact = load_ledger_consumer_artifact(str(feed)) crosswalk_path = default_congressional_district_vintage_crosswalk_path() crosswalk = load_congressional_district_vintage_crosswalk(crosswalk_path) - registry = compile_us_fiscal_target_registry( - artifact.facts, - target_period=PERIOD, - congressional_district_vintage_crosswalk=crosswalk, - age_targets=True, - ) - registry, ri_substitutions = apply_us_medicaid_enrollment_substitutions(registry) + registry, ri_substitutions = _compiled_fiscal_registry(feed, crosswalk=crosswalk) def state_cd_district_shares(candidates): surface = cd_surface.state_cd_soi_surface( diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 590918663a..32bce2f4a5 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -290,14 +290,14 @@ calibrate_exact_k_ladder, exact_k_ladder_manifest_payload, ) -from microcosm.build.us_runtime.fiscal_targets import ( +from microcosm.build.us_runtime.fiscal_targets import ( # noqa: F401 + # The age-stamp keys are read by the ledger filter rules now (microcosm#1728); + # the tool keeps them for readers of its namespace. AGE_BOUND_STAMP_FROM_CONSTRAINT_ROWS, AGE_BOUND_STAMP_SOURCE_KEY, SSA_SSI_AGE_BAND_RECIPIENTS_TARGET_ROLE, ) from microcosm.build.us_runtime.fsa_student_loan_targets import ( - FSA_BALANCE_LOWER_BOUND_KEY, - FSA_BALANCE_UPPER_BOUND_KEY, FSA_BOUND_TABLES, FSA_MATERIALIZER, FSA_SOURCE_NAME, @@ -343,6 +343,37 @@ attach_l0_refit_entity_weights, load_us_frame, ) + +# The ledger filter rules moved to us_runtime (microcosm#1728). The tool keeps +# every name: the materializer and the filter guard call them, and tests and +# tools/bakeoff_us_support_mix.py read them from this module. +from microcosm.build.us_runtime.ledger_filter_rules import ( # noqa: F401 + RESTATED_AGE_BAND_COMPILED_KEYS, + RESTATED_AGE_BAND_MATERIALIZERS, + RESTATED_AGE_DIMENSION_KEY, + RESTATED_AGI_BAND_COMPILED_KEYS, + RESTATED_EITC_CHILD_COUNT_PROBE_MAX, + RESTATED_EITC_CHILD_COUNT_REFUSED_SIDES, + RESTATED_LEDGER_FILTER_BOUND_SIDES, + RESTATED_LEDGER_FILTER_CONCEPTS, + RESTATED_STUDENT_LOAN_BALANCE_BAND_COMPILED_KEYS, + SUPPORTED_SOI_LEDGER_FILTERS, + _as_bound, + _eitc_child_count_mask, + _is_noop_ledger_filter_value, + _restated_age_band_refusal, + _restated_agi_band_refusal, + _restated_band_edge_refusal, + _restated_bound_value, + _restated_count_value, + _restated_eitc_child_count_refusal, + _restated_ledger_filter_concept, + _restated_ledger_filter_refusal, + _restated_student_loan_balance_band_refusal, + _soi_eitc_child_count_filter, + _soi_requires_positive_eitc_filter, + _unsupported_soi_ledger_filters, +) from microcosm.build.us_runtime.medicare_irmaa_holdout import ( medicare_irmaa_holdout_from_sim, medicare_irmaa_holdout_unavailable, @@ -868,138 +899,6 @@ def _automatic_gc_suspended(): } ) -#: Restated constraints, a third class distinct from both sets above: a -#: labelled feed re-expresses a fact's universe constraint in the Ledger's own -#: concept vocabulary (``us:statutes/26/62#adjusted_gross_income_lower_bound``) -#: alongside the compiled metadata the materializer actually slices on -#: (``agi_lower_bound``). These keys are NOT inert — they restrict the -#: microdata — so they can never join the supported set outright: a future -#: feed whose labelled bound disagreed with the compiled one would then be -#: silently ignored, materializing a wider population than the published cell -#: covers, which is the failure the guard exists to stop. Each key here is -#: accepted only per spec, and only when that spec also carries the filter the -#: materializer applies and the two select the same population; a restatement -#: that disagrees, or that has no compiled counterpart, stays fatal and the -#: refusal names the values. Values are the restated-constraint rule that -#: decides the comparison (see ``_restated_ledger_filter_refusal``). -RESTATED_LEDGER_FILTER_CONCEPTS = { - "us:statutes/26/62#adjusted_gross_income": "agi_band", - "us.tax.earned_income_credit_qualifying_children": "eitc_child_count", - "age": "age_band", - "federal_student_loan_balance": "student_loan_balance_band", -} - -#: Bound-side suffixes a restated constraint key may carry. A key with no -#: suffix restates an exact value of the concept. -RESTATED_LEDGER_FILTER_BOUND_SIDES = ( - ("_lower_bound", "lower"), - ("_upper_bound", "upper"), -) - -#: Compiled metadata the materializer slices the AGI band on, by bound -#: side: the ``irs_soi`` loop in :func:`_materialize_target_frame` reads -#: both through :func:`_as_bound` into one half-open mask. A restated AGI -#: bound is accepted only against its own side; the sibling side is judged -#: by its own key. -RESTATED_AGI_BAND_COMPILED_KEYS = { - "lower": "agi_lower_bound", - "upper": "agi_upper_bound", -} - -#: Qualifying-child counts probed when deciding whether a restated EITC -#: child-count bound selects the same returns as the compiled filter. -#: :func:`_eitc_child_count_mask` resolves every compiled value to ``== 0``, -#: ``== 1``, ``== 2`` or ``>= 3``, and a compared restatement is ``>= n`` or -#: ``== n`` (an upper bound is refused before any comparison; see -#: :data:`RESTATED_EITC_CHILD_COUNT_REFUSED_SIDES`); evaluating both over -#: 0..16 separates every such pair, so equal masks over the probe mean equal -#: populations. Counts above the probe are refused rather than compared. -RESTATED_EITC_CHILD_COUNT_PROBE_MAX = 16 - -#: Bound sides on which a restated EITC qualifying-child key is refused -#: outright, whatever its value and whatever the spec compiles. What an upper -#: bound selects turns on the Ledger's operator — ``< 1`` is the childless -#: returns, ``<= 1`` adds the one-child returns — and that operator is -#: unconfirmed for count constraints. The metadata key does not settle it: -#: :func:`microcosm.build.ledger_targets._constraint_bound_filters` stamps a -#: ``<`` row as ``_upper_bound`` (``<=`` becomes ``_upper_bound_inclusive``, -#: which no restated concept names, so it is refused by bare key), but the -#: dimension stamp in ``_ledger_metadata`` runs first and wins through -#: ``setdefault``, and can carry the same key with no operator at all. So no -#: reading is guessed until the Ledger confirms one (Max, 2026-09-22). Lower -#: and exact restatements stay under the agreement rule. -RESTATED_EITC_CHILD_COUNT_REFUSED_SIDES = frozenset({"upper"}) - -#: Compiled metadata the materializer slices a person-age band on, by bound -#: side. Both age paths in :func:`_materialize_target_frame` read these -#: through :func:`_as_bound` into one half-open mask ``lower <= age < upper`` -#: — the ``population_age`` loop in :func:`_population_age_household_values` -#: and the age-banded ``policyengine_variable`` branch (the SSA SSI -#: recipients-by-age counts) — so a restated age bound is judged, like an AGI -#: bound, against its own side only. -#: -#: Numeric equality of the edges is equality of populations only for a -#: restated key whose operator is the mask's: ``age < 10`` and ``age <= 10`` -#: differ by everyone aged exactly ten, so the operator decides. -#: :func:`microcosm.build.ledger_targets._constraint_bound_filters` writes -#: ``age_lower_bound`` only for a ``>=`` row and ``age_upper_bound`` only for -#: a ``<`` row, the two operators of the materializer's mask. A ``>`` or -#: ``<=`` row is stamped ``age_lower_bound_exclusive`` / -#: ``age_upper_bound_inclusive``, which no restated concept names, so it stays -#: refused by bare key — as it must, because the compiled bound comes from -#: ``us_runtime.fiscal_targets._age_bounds``, which drops the operator: a -#: ``<= 4`` row compiles to ``age_upper_bound=4`` and the materializer's -#: ``age < 4`` would leave out the four-year-olds the published cell counts. -#: But the same ``ledger_filter_age_{lower,upper}_bound`` key can also be a -#: dimension's, which carries no operator (the ambiguity that keeps restated -#: qualifying-child upper bounds refused), so the key name alone does not -#: settle it; the compile's attestation does -#: (:data:`microcosm.build.us_runtime.fiscal_targets.AGE_BOUND_STAMP_SOURCE_KEY`). -RESTATED_AGE_BAND_COMPILED_KEYS = { - "lower": "age_lower_bound", - "upper": "age_upper_bound", -} - -#: Materializers that apply the compiled age band, and so the only ones for -#: which ignoring an agreeing age restatement changes nothing. Both are read -#: in :func:`_materialize_target_frame`: ``population_age`` through -#: :func:`_population_age_household_values`, and ``policyengine_variable`` -#: through its age-banded branch, entered whenever either compiled age key is -#: present. Every other materializer (the ``irs_soi`` slice, the direct -#: household-variable measures) never reads an age bound, so a restated age -#: bound there would be silently ignored however well it agreed with metadata -#: the materializer also ignores; it is refused instead. -RESTATED_AGE_BAND_MATERIALIZERS = frozenset( - {"population_age", "policyengine_variable", FSA_MATERIALIZER} -) - -#: Compiled edges of a Federal Student Aid debt-size band, by bound side, and -#: the one materializer that slices on them -#: (:func:`microcosm.build.us_runtime.fsa_student_loan_targets.fsa_student_loan_household_values`, -#: ``lower <= balance < upper`` on the person's own plus Parent PLUS balance, -#: microcosm#1074). A restated ``federal_student_loan_balance`` bound on any -#: other materializer would be ignored, so it refuses. -RESTATED_STUDENT_LOAN_BALANCE_BAND_COMPILED_KEYS = { - "lower": FSA_BALANCE_LOWER_BOUND_KEY, - "upper": FSA_BALANCE_UPPER_BOUND_KEY, -} - -#: The exact-value age key the dimension stamp writes when ``age`` is itself -#: a dimension of the fact. -#: :func:`microcosm.build.ledger_targets._constraint_bound_filters` skips -#: every constraint row whose variable is already a dimension key, so on -#: such a fact an ``age_{lower,upper}_bound`` restatement cannot have come -#: from an operator-checked ``>=``/``<`` row — only from a dimension of that -#: name, which carries no operator at all. A restated age bound on a spec -#: carrying this key is refused, whatever its value, including ``all``. -#: ``_ledger_metadata`` stamps a dimension only when its value is not -#: ``None`` and then drops empty values, so an ``age`` dimension valued -#: ``None`` or ``""`` leaves no key here; the compile's attestation -#: (:data:`AGE_BOUND_STAMP_SOURCE_KEY`, which checks dimension keys whatever -#: their value) is what refuses that case. The pinned feeds have no age -#: dimension of any kind. -RESTATED_AGE_DIMENSION_KEY = "ledger_filter_age" - FISCAL_TARGET_SOURCE_KEYS = { "cbo": "Congressional Budget Office revenue projections", "cms_aca": "CMS ACA marketplace enrollment public use files", @@ -1173,14 +1072,6 @@ def _env_default(name: str, default: str) -> str: "Single": "SINGLE", } -SUPPORTED_SOI_LEDGER_FILTERS = frozenset( - { - "ledger_filter_income_range", - "ledger_filter_filing_status", - "ledger_filter_eitc_child_count", - } -) - def _parse_ratified_exact_k(value: str) -> str | int: if value == "N": @@ -6387,98 +6278,6 @@ def _filing_status_names(values: np.ndarray) -> np.ndarray: ) -def _soi_eitc_child_count_filter(metadata: Mapping[str, str]) -> str | None: - explicit = metadata.get("ledger_filter_eitc_child_count") - if explicit and explicit.strip().lower() != "all": - return explicit - record_set = metadata.get("ledger_layout_record_set_id", "") - if record_set.endswith(".eitc_by_agi_children.no_qualifying_children"): - return "0" - if record_set.endswith(".eitc_by_agi_children.one_qualifying_child"): - return "1" - if record_set.endswith(".eitc_by_agi_children.two_qualifying_children"): - return "2" - if record_set.endswith(".eitc_by_agi_children.three_or_more_qualifying_children"): - return "3plus" - measure = metadata.get("source_measure_id", "") - if measure.startswith("eitc_no_children_"): - return "0" - if measure.startswith("eitc_one_child_"): - return "1" - if measure.startswith("eitc_two_children_"): - return "2" - if measure.startswith("eitc_three_or_more_children_"): - return "3plus" - return None - - -def _soi_requires_positive_eitc_filter(metadata: Mapping[str, str]) -> bool: - return ( - metadata.get("ledger_domain") - == "individual_income_tax_returns_with_earned_income_credit" - ) - - -def _is_noop_ledger_filter_value(value: str) -> bool: - return value.strip().lower().replace("_", " ") in {"", "all"} - - -def _unsupported_soi_ledger_filters(metadata: Mapping[str, str]) -> tuple[str, ...]: - """Ledger filter keys the SOI slice does not act on, for one spec. - - A non-empty result drops the spec from SOI materialization silently in - the ``irs_soi`` loop of :func:`_materialize_target_frame`, so an - accepted restatement must clear here too — otherwise - accepting it at the fatal guard would only move the spec from a refusal - to a silent disappearance. A restatement that disagrees stays listed, and - :func:`_assert_supported_ledger_filter_metadata` refuses it before the - materializer ever reaches this skip. - """ - - return tuple( - sorted( - key - for key, value in metadata.items() - if key.startswith("ledger_filter_") - and key not in SUPPORTED_SOI_LEDGER_FILTERS - and not _is_noop_ledger_filter_value(str(value)) - and _restated_ledger_filter_refusal(str(key), str(value), metadata) - is not None - ) - ) - - -def _eitc_child_count_mask(values: np.ndarray, filter_value: str) -> np.ndarray: - counts = np.asarray(values, dtype=np.float64) - normalized = str(filter_value).strip().lower().replace("_", " ") - if normalized in {"0", "none", "no children", "no qualifying children"}: - return counts == 0 - if normalized in {"1", "one", "one child", "one qualifying child"}: - return counts == 1 - if normalized in {"2", "two", "two children", "two qualifying children"}: - return counts == 2 - if normalized in { - "3", - "3+", - "3plus", - "three", - "three plus", - "three or more", - "three or more children", - "three or more qualifying children", - }: - return counts >= 3 - raise ValueError(f"Unsupported EITC child-count filter {filter_value!r}.") - - -def _as_bound(value: str) -> float: - if value == "-inf": - return -math.inf - if value == "inf": - return math.inf - return float(value) - - def _population_age_household_values( *, frame: Frame, @@ -6513,260 +6312,6 @@ def _population_age_household_values( return values -def _restated_ledger_filter_concept(key: str) -> tuple[str, str | None]: - """Split a ``ledger_filter_*`` key into its concept and bound side. - - ``ledger_filter_us:statutes/26/62#adjusted_gross_income_lower_bound`` - splits into ``("us:statutes/26/62#adjusted_gross_income", "lower")``; a - key with no bound suffix keeps the whole concept and side ``None``, - meaning it restates an exact value. - """ - - if not key.startswith("ledger_filter_"): - return "", None - concept = key[len("ledger_filter_") :] - for suffix, side in RESTATED_LEDGER_FILTER_BOUND_SIDES: - if concept.endswith(suffix) and len(concept) > len(suffix): - return concept[: -len(suffix)], side - return concept, None - - -def _restated_bound_value(value: str) -> float | None: - try: - return _as_bound(value.strip()) - except ValueError: - return None - - -def _restated_count_value(value: str) -> float | None: - try: - count = float(value.strip()) - except ValueError: - return None - if not count.is_integer() or not 0 <= count <= RESTATED_EITC_CHILD_COUNT_PROBE_MAX: - return None - return count - - -def _restated_band_edge_refusal( - key: str, - value: str, - metadata: Mapping[str, str], - *, - compiled_key: str, -) -> str | None: - """Judge one restated half-open band edge against the edge it restates. - - Shared by the AGI and age rules, whose materializers both slice - ``lower <= x < upper`` on the compiled edge read through - :func:`_as_bound`, so a restated edge is ignorable exactly when it parses - to the same number. A missing compiled edge refuses: the age paths would - read it as the open end and the ``irs_soi`` loop indexes it directly, and - neither is the restated edge being checked. - """ - - compiled = metadata.get(compiled_key) - if compiled is None: - return f"{key}={value} restates a bound the spec does not compile: no {compiled_key}" - restated = _restated_bound_value(value) - applied = _restated_bound_value(str(compiled)) - if restated is None or applied is None or restated != applied: - return f"{key}={value} disagrees with {compiled_key}={compiled}" - return None - - -def _restated_agi_band_refusal( - key: str, - value: str, - metadata: Mapping[str, str], - *, - side: str | None, -) -> str | None: - if side is None: - return ( - f"{key}={value} restates an exact AGI, but the materializer " - "slices a half-open AGI band and applies no exact-value AGI filter" - ) - return _restated_band_edge_refusal( - key, value, metadata, compiled_key=RESTATED_AGI_BAND_COMPILED_KEYS[side] - ) - - -def _restated_age_band_refusal( - key: str, - value: str, - metadata: Mapping[str, str], - *, - side: str | None, -) -> str | None: - if side is None: - return ( - f"{key}={value} restates an exact age, but the materializer " - "slices a half-open age band and applies no exact-age filter" - ) - if RESTATED_AGE_DIMENSION_KEY in metadata: - return ( - f"{key}={value} restates an age bound on a fact whose dimensions " - f"include age ({RESTATED_AGE_DIMENSION_KEY}=" - f"{metadata[RESTATED_AGE_DIMENSION_KEY]}), so the bound came from " - "the dimension stamp, which carries no operator" - ) - materializer = metadata.get("materializer") - if materializer not in RESTATED_AGE_BAND_MATERIALIZERS: - return ( - f"{key}={value} restates an age bound on a spec whose materializer " - f"({materializer!r}) applies no age band" - ) - stamp_source = metadata.get(AGE_BOUND_STAMP_SOURCE_KEY) - if stamp_source != AGE_BOUND_STAMP_FROM_CONSTRAINT_ROWS: - return ( - f"{key}={value} restates an age bound whose operator is ambiguous: " - f"{AGE_BOUND_STAMP_SOURCE_KEY}={stamp_source} does not attest it " - "was stamped from a constraint row (>= or <), and a dimension of " - "that name carries no operator" - ) - return _restated_band_edge_refusal( - key, value, metadata, compiled_key=RESTATED_AGE_BAND_COMPILED_KEYS[side] - ) - - -def _restated_student_loan_balance_band_refusal( - key: str, - value: str, - metadata: Mapping[str, str], - *, - side: str | None, -) -> str | None: - if side is None: - return ( - f"{key}={value} restates an exact federal student loan balance, but " - "the materializer slices a half-open balance band" - ) - materializer = metadata.get("materializer") - if materializer != FSA_MATERIALIZER: - return ( - f"{key}={value} restates a federal student loan balance bound on a " - f"spec whose materializer ({materializer!r}) applies no balance band" - ) - return _restated_band_edge_refusal( - key, - value, - metadata, - compiled_key=RESTATED_STUDENT_LOAN_BALANCE_BAND_COMPILED_KEYS[side], - ) - - -def _restated_eitc_child_count_refusal( - key: str, - value: str, - metadata: Mapping[str, str], - *, - side: str | None, -) -> str | None: - if side in RESTATED_EITC_CHILD_COUNT_REFUSED_SIDES: - return ( - f"{key}={value} restates a qualifying-child {side} bound, refused " - "outright: the Ledger's operator for it (< or <=) is unconfirmed, " - "and the two readings select different returns" - ) - compiled = _soi_eitc_child_count_filter(metadata) - if compiled is None: - return ( - f"{key}={value} restates a qualifying-child bound on a spec that " - "carries no child-count filter for the materializer to apply" - ) - bound = _restated_count_value(value) - if bound is None: - return ( - f"{key}={value} is not a qualifying-child count in " - f"0..{RESTATED_EITC_CHILD_COUNT_PROBE_MAX}" - ) - counts = np.arange(RESTATED_EITC_CHILD_COUNT_PROBE_MAX + 1, dtype=np.float64) - if side == "lower": - restated_mask = counts >= bound - elif side is None: - restated_mask = counts == bound - else: - raise ValueError( - f"{key}: bound side {side!r} reached the qualifying-child " - "comparison, which reads only lower and exact restatements" - ) - try: - applied_mask = _eitc_child_count_mask(counts, compiled) - except ValueError: - return ( - f"{key}={value} cannot be compared: compiled child-count filter " - f"{compiled!r} is not one the materializer understands" - ) - if not np.array_equal(restated_mask, applied_mask): - return ( - f"{key}={value} selects different returns than the compiled " - f"child-count filter {compiled!r}" - ) - return None - - -def _restated_ledger_filter_refusal( - key: str, - value: str, - metadata: Mapping[str, str], -) -> str | None: - """Judge one otherwise-unsupported ``ledger_filter_*`` key for one spec. - - Returns ``None`` only when *key* restates, in the labelled feed's concept - vocabulary, a constraint the materializer already applies to this spec, - and the two select the same population — ignoring that restatement then - changes nothing. Every other key returns the entry to refuse with: the - bare key for a filter the materializer does not model (unchanged from - before this rule existed), or the key with both values when a restatement - disagrees with its compiled counterpart, or has none, or is applied by - no materializer for this spec, or — for a - qualifying-child upper bound, whose operator is unconfirmed (see - :data:`RESTATED_EITC_CHILD_COUNT_REFUSED_SIDES`) — the key with that - reason, whatever the spec compiles. - - Two compiled counterparts — the AGI band in - :data:`RESTATED_AGI_BAND_COMPILED_KEYS` and - :func:`_soi_eitc_child_count_filter` — are the ``irs_soi`` slice's, read - in the loop :func:`_materialize_target_frame` runs over ``irs_soi`` - specs, and this rule reads them off metadata without consulting the - spec's family. That family-blindness is the guard's existing shape: - ``ledger_filter_eitc_child_count`` is likewise a blanket supported key. A - spec of another family carries neither counterpart, so it refuses on the - "does not compile" arm rather than being accepted by accident. - - The third, the person-age band in :data:`RESTATED_AGE_BAND_COMPILED_KEYS`, - is read by two materializers (``population_age`` and the age-banded - ``policyengine_variable`` branch), so that rule is family-blind too but - names the materializers that apply the band - (:data:`RESTATED_AGE_BAND_MATERIALIZERS`) and refuses on every other; it - also refuses a bound on a fact whose dimensions include ``age`` - (:data:`RESTATED_AGE_DIMENSION_KEY`), and any bound the compile does not - attest was stamped from a ``>=`` / ``<`` constraint row - (:data:`AGE_BOUND_STAMP_SOURCE_KEY`): a dimension-stamped bound carries no - operator, and ``age < 10`` and ``age <= 10`` select different people. - """ - - concept, side = _restated_ledger_filter_concept(key) - rule = RESTATED_LEDGER_FILTER_CONCEPTS.get(concept) if concept else None - if rule is None: - return key - if rule == "agi_band": - return _restated_agi_band_refusal(key, value, metadata, side=side) - if rule == "eitc_child_count": - return _restated_eitc_child_count_refusal(key, value, metadata, side=side) - if rule == "age_band": - return _restated_age_band_refusal(key, value, metadata, side=side) - if rule == "student_loan_balance_band": - return _restated_student_loan_balance_band_refusal( - key, value, metadata, side=side - ) - raise ValueError( - f"RESTATED_LEDGER_FILTER_CONCEPTS maps {concept!r} to rule {rule!r}, " - "which has no comparison implemented." - ) - - def _unsupported_ledger_filter_metadata( target_specs: Iterable[object], ) -> dict[str, tuple[str, ...]]: diff --git a/tools/us_acs_local_cd_surface.py b/tools/us_acs_local_cd_surface.py index 74fc9f352c..c7226b5193 100644 --- a/tools/us_acs_local_cd_surface.py +++ b/tools/us_acs_local_cd_surface.py @@ -169,12 +169,16 @@ GEOGRAPHY_CD = "congressional_district" -def _release_tool(): - """The sibling release tool (``tools/`` is on ``sys.path`` via the ACS tool).""" +def _filter_rules(): + """The ledger filter rules the national ``irs_soi`` slice reads. - import build_us_fiscal_refresh_release as release_tool + They moved from ``tools/build_us_fiscal_refresh_release.py`` to the + package (microcosm#1728), so this module no longer imports that tool. + """ + + from microcosm.build.us_runtime import ledger_filter_rules - return release_tool + return ledger_filter_rules # --------------------------------------------------------------------------- @@ -208,22 +212,22 @@ def soi_materializer_semantics(spec) -> tuple: masks. """ - tool = _release_tool() + rules = _filter_rules() metadata = _metadata(spec) return ( spec.family, spec.entity, spec.filter, metadata.get("source_variable", metadata.get("variable")), - repr(tool._as_bound(metadata["agi_lower_bound"])), - repr(tool._as_bound(metadata["agi_upper_bound"])), + repr(rules._as_bound(metadata["agi_lower_bound"])), + repr(rules._as_bound(metadata["agi_upper_bound"])), metadata.get("taxable_only") == "true", metadata.get("filing_status"), - tool._soi_eitc_child_count_filter(metadata), - tool._soi_requires_positive_eitc_filter(metadata), + rules._soi_eitc_child_count_filter(metadata), + rules._soi_requires_positive_eitc_filter(metadata), metadata.get("itemized_only") == "true", metadata.get("measure_mode") == "indicator_sum", - tool._unsupported_soi_ledger_filters(metadata), + rules._unsupported_soi_ledger_filters(metadata), ) @@ -235,14 +239,14 @@ def soi_concept_identity(spec) -> tuple[str, ...]: count separate the Historic Table 2 band rows from the all-income rows. """ - tool = _release_tool() + rules = _filter_rules() metadata = _metadata(spec) return ( str(metadata.get("source_measure_id")), - repr(tool._as_bound(metadata["agi_lower_bound"])), - repr(tool._as_bound(metadata["agi_upper_bound"])), + repr(rules._as_bound(metadata["agi_lower_bound"])), + repr(rules._as_bound(metadata["agi_upper_bound"])), str(metadata.get("filing_status", "")).lower(), - str(tool._soi_eitc_child_count_filter(metadata)), + str(rules._soi_eitc_child_count_filter(metadata)), ) From f4dee4c7015eabe0f2e5fc2d8a8e14be0802701e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:45:44 +0000 Subject: [PATCH 06/30] List target_sets.json in the US bundle generator's resources The US bundle generator writes country_package.json from LEGACY_RESOURCE_PATHS. The target_sets.json row was in the committed manifest but not in the generator, so the engine-tier check test_generator_reproduces_every_checked_in_bundle_byte failed on 3316038cc. The generated manifest now equals the committed one (checked without a country engine), and both re-pin tools' --check modes pass. Co-Authored-By: Claude Opus 5.5 --- tools/generate_us_bundle_from_constants.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/generate_us_bundle_from_constants.py b/tools/generate_us_bundle_from_constants.py index bb5fea9a9c..15237ef9e2 100644 --- a/tools/generate_us_bundle_from_constants.py +++ b/tools/generate_us_bundle_from_constants.py @@ -163,6 +163,8 @@ def _domain_builders() -> dict[str, Callable[[], object]]: "take_up_contract.json", "target_parity_feed_families.json", "target_parity_manifest.json", + # The declared target set of each US product (microcosm#1728). + "target_sets.json", "tax_expenditure_reforms.json", ) From 868f414bcf0323972cb4ed6c7b044e46d43baf92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:25:30 +0000 Subject: [PATCH 07/30] Run the ACS local hold-outs on shared code C2 of the shared-code work in microcosm#1728. No target, role or receipt changes. - microcosm.build.target_holdouts (new, country-free) draws held-out targets by hashed blocks from declared passes: scope and eligibility tests on the record, unit fields joined with '|', a concept-family rule, the salt, the default and largest fraction, and the receipt keys in order. It also builds the training target set, and scores the held rows against a pro-rata baseline (the parent target times the child's population share), with the populations attached from declared fields. - us/local_target_construction.json (new) declares the US district and county passes, their concept-family rule and their scoring, with the values the tools held. microcosm.build.us_runtime.local_target_construction reads it. - tools/us_acs_local_cd_surface.py, tools/us_acs_local_county_surface.py and tools/build_us_acs_local_release.py keep their function names and call the shared code. - The new resource row: country_package.json, the bundle generator's LEGACY_RESOURCE_PATHS, the US F0 re-pin (42,410 configuration fields, country_manifest at 119 pointers; the US bundle spec_sha256 moves to c25fbed9), and the module classification. Proof: - test_us_acs_local_surface_bytes.py (C0) passes unchanged on the pinned feed and ladder: the roles, units, populations and hold-out receipts are byte-identical. - test_us_target_holdouts.py (91 tests) holds the tool functions to verbatim copies of the replaced code (test_support/microcosm_build/us_target_holdouts_reference.py) on random records: roles, receipts, populations, training sets and scores, with key order. - test_target_holdouts.py (30 tests) tests the shared module on a made-up country. - 4,044 tests in the 51 files that load the changed tools or hold the registers pass locally (8 skipped), with the pinned feed and ladder set. Co-Authored-By: Claude Opus 5.5 --- .../1728-shared-target-holdouts.added.md | 1 + docs/evidence/spec-engine/us-f0-coverage.json | 20 +- .../build/spec_engine/field_usage.py | 8 +- .../src/microcosm/build/target_holdouts.py | 827 ++++++++++++++++++ .../microcosm/build/us/country_package.json | 5 + .../build/us/local_target_construction.json | 136 +++ .../us_runtime/local_target_construction.py | 90 ++ .../us/test_spec_engine_coverage_tool.py | 10 +- .../shared/test_spec_engine_field_usage.py | 10 +- .../shared/test_target_holdouts.py | 411 +++++++++ .../engine_free/us/test_us_spine_blindness.py | 4 + .../engine_free/us/test_us_target_holdouts.py | 354 ++++++++ .../us/test_us_multispine_pool_tool.py | 2 +- .../us_target_holdouts_reference.py | 471 ++++++++++ tools/build_us_acs_local_release.py | 42 +- tools/generate_us_bundle_from_constants.py | 2 + tools/spec_engine_coverage.py | 2 +- tools/us_acs_local_cd_surface.py | 308 ++----- tools/us_acs_local_county_surface.py | 136 +-- 19 files changed, 2442 insertions(+), 397 deletions(-) create mode 100644 changelog.d/1728-shared-target-holdouts.added.md create mode 100644 packages/microcosm-build/src/microcosm/build/target_holdouts.py create mode 100644 packages/microcosm-build/src/microcosm/build/us/local_target_construction.json create mode 100644 packages/microcosm-build/src/microcosm/build/us_runtime/local_target_construction.py create mode 100644 packages/microcosm-build/tests/engine_free/shared/test_target_holdouts.py create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_target_holdouts.py create mode 100644 test_support/microcosm_build/us_target_holdouts_reference.py diff --git a/changelog.d/1728-shared-target-holdouts.added.md b/changelog.d/1728-shared-target-holdouts.added.md new file mode 100644 index 0000000000..a72dc932dc --- /dev/null +++ b/changelog.d/1728-shared-target-holdouts.added.md @@ -0,0 +1 @@ +Target hold-outs are shared code for any country (microcosm#1728): `microcosm.build.target_holdouts` draws held-out targets by hashed blocks from declared passes (scope, eligibility, unit key, salt, fractions, receipt), builds the training target set, and scores the held rows against a pro-rata baseline. The ACS local release declares its district and county passes in the new `us/local_target_construction.json`, read by `microcosm.build.us_runtime.local_target_construction`; the tool functions call the shared code under their old names. No target, role or receipt changes: `test_us_target_holdouts.py` holds the shared code to verbatim copies of the replaced tool code, and the pinned bytes of `test_us_acs_local_surface_bytes.py` are unchanged. The new resource row moves the US F0 spec-engine pins (42,410 configuration fields). diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index 824a26fa95..4e892aac67 100644 --- a/docs/evidence/spec-engine/us-f0-coverage.json +++ b/docs/evidence/spec-engine/us-f0-coverage.json @@ -6,7 +6,7 @@ "country": "us", "documentation_sha256": "fda6ec0dd925077f4d84d30a1c206dd81d82c5e16bd94506e81fe1b9f7e2f466", "field_usage": { - "authored_normative_field_count": 32621, + "authored_normative_field_count": 32624, "claim_count": 48, "claims": [ { @@ -16,8 +16,8 @@ "legacy_sinks": [], "mode": "front_end_validation", "pointer_class": "all", - "pointer_count": 116, - "pointer_sha256": "3a77833a2aee67d0f58a3dd972f947a79a24afc7c0ebc1821a0e8dd3cbf5771a", + "pointer_count": 119, + "pointer_sha256": "f93afb3400960c441ef522bd35cb56dffceef802eeaeab7aa63489d55d53f896", "rationale": null, "relative_sink_prefix": null, "source_prefix": "/authored/country_package.json", @@ -758,20 +758,20 @@ "verifier": "vintages" } ], - "configuration_field_count": 42407, - "consumed_field_count": 42407, + "configuration_field_count": 42410, + "consumed_field_count": 42410, "generation0_effect_counts": { "legacy_behavior": 38780, - "no_generation0_effect": 3627 + "no_generation0_effect": 3630 }, "mode_counts": { "compiler_semantic": 27674, - "front_end_validation": 361, + "front_end_validation": 364, "identity_only": 103, "legacy_behavior": 14269 }, "multiple_primary_use_field_count": 0, - "pointer_inventory_sha256": "b7565bf43ff7139460a8345d3858a6950c4fdcf4cb61afe6b056550040b1c710", + "pointer_inventory_sha256": "bbf2213acf3453f09be80542c9b86f5571b6659ce196c1979be9961f0c0a6f66", "resolved_binding_field_count": 9786, "unused_field_count": 0 }, @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "f130419c1b9d07fb452bc28ca80ff8de07562667e4e2940f0f02f75d550792d6" + "spec_sha256": "c25fbed9c0d92248707f59101b516125f8437c42e2cebe84a72e28f6ac0f39c0" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "f130419c1b9d07fb452bc28ca80ff8de07562667e4e2940f0f02f75d550792d6" + "spec_sha256": "c25fbed9c0d92248707f59101b516125f8437c42e2cebe84a72e28f6ac0f39c0" }, "status": "pass" } diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py index 4089a583be..71b11bd0a8 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py @@ -26,9 +26,9 @@ ) from .schemas import load_schema_registry -EXPECTED_AUTHORED_FIELD_COUNT = 32621 +EXPECTED_AUTHORED_FIELD_COUNT = 32624 EXPECTED_RESOLVED_BINDING_FIELD_COUNT = 9786 -EXPECTED_CONFIGURATION_FIELD_COUNT = 42407 +EXPECTED_CONFIGURATION_FIELD_COUNT = 42410 class FieldUsageError(AssertionError): @@ -369,8 +369,8 @@ def _path_inventory(rows: Sequence[tuple[str, object]]) -> tuple[int, str]: "bdd9e79157590fade42d28cc2b5d5c8b58e13903af75375a0e3235c94d2a8339", ), "country_manifest": ( - 116, - "3a77833a2aee67d0f58a3dd972f947a79a24afc7c0ebc1821a0e8dd3cbf5771a", + 119, + "f93afb3400960c441ef522bd35cb56dffceef802eeaeab7aa63489d55d53f896", ), "generated_authorities": ( 8_614, diff --git a/packages/microcosm-build/src/microcosm/build/target_holdouts.py b/packages/microcosm-build/src/microcosm/build/target_holdouts.py new file mode 100644 index 0000000000..5384b28eb1 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/target_holdouts.py @@ -0,0 +1,827 @@ +"""Held-out calibration targets, drawn by hashed blocks, for any country. + +A local build holds some of its targets out of the calibration and scores the +calibrated file on them. One held-out target is not a fair test when its +siblings and its parent train, because adding up pins it. So a hold-out draws +whole *units*, for example every district target of one concept family in one +state. A unit is held out when a salted hash of its key falls below the +fraction (:func:`microcosm.build.holdout.hash_holdout_unit`). + +A country declares its passes as data, and :func:`load_target_holdouts` reads +them. Each pass declares: + +- ``scope``: tests on a record's fields that pick the records the pass + writes. With no test, the pass writes every record. +- ``eligible``: tests that pick, in scope, the records that get a unit. The + other records in scope train. +- ``unit_fields``: the fields the unit key joins with ``|``. The name + ``concept_family`` stands for the record's concept family + (:class:`ConceptFamilyRule`). +- ``salt``, ``default_fraction`` and ``max_fraction``. +- ``receipt``: the receipt keys the pass writes, in order. +- ``scoring``: how :func:`score_holdout` scores the held rows against a + pro-rata baseline, which is a parent target times the child's share of the + parent's population. + +A target record is a mapping with at least ``name``, ``value``, ``family`` +and ``geography_level``, the field names the targets carry everywhere. The +role pass adds ``holdout_unit`` and ``role``. The training target set +(:func:`training_target_set`) holds the training rows only, so a held-out +target never reaches the solve. Nothing here reads a frame or country code +(microcosm#1728). +""" + +from __future__ import annotations + +import math +from collections import defaultdict +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import Any + +import numpy as np +from scipy import sparse + +from microcosm.build.holdout import hash_holdout_unit + +__all__ = [ + "CONCEPT_FAMILY_FIELD", + "POPULATION_CHECKS", + "RECEIPT_KEYS", + "RECORD_TEST_KINDS", + "ROLE_HOLDOUT", + "ROLE_TRAIN", + "UNIT_SEPARATOR", + "ConceptFamilyRule", + "HoldoutPass", + "HoldoutScoring", + "PopulationShares", + "RecordTest", + "TargetHoldoutError", + "TargetHoldouts", + "assign_holdout_roles", + "attach_population_shares", + "csr_row_measure", + "error_summary", + "holdout_rows", + "load_target_holdouts", + "missing_population_shares", + "pro_rata_baseline", + "score_holdout", + "train_rows", + "training_target_set", +] + +#: The role a record trains under, and the role of a held-out record. +ROLE_TRAIN = "train" +ROLE_HOLDOUT = "holdout" +#: The separator of a unit key's fields. +UNIT_SEPARATOR = "|" +#: The unit field that stands for the record's concept family. +CONCEPT_FAMILY_FIELD = "concept_family" +#: ``equals`` compares a field with a value; ``truthy`` needs a field that is +#: present and not empty, zero or None. +RECORD_TEST_KINDS = ("equals", "truthy") +#: The receipt keys a pass may declare. +RECEIPT_KEYS = ( + "unit", + "salt", + "fraction", + "eligible_units", + "held_units", + "held_unit_keys", + "eligible_targets", + "held_targets", + "hash", +) +#: How the pro-rata baseline checks a row's populations: ``nonzero`` refuses +#: a missing or zero population; ``finite_positive`` also refuses a negative +#: or non-finite one. +POPULATION_CHECKS = ("nonzero", "finite_positive") + +_SECTION_KEYS = frozenset({"concept_families", "passes"}) +_FAMILY_KEYS = frozenset( + {"source_field", "families", "merge_prefixes", "strip_suffixes", "rationale"} +) +_PASS_KEYS = frozenset( + { + "id", + "label", + "unit", + "unit_fields", + "salt", + "default_fraction", + "max_fraction", + "scope", + "eligible", + "receipt", + "hash_description", + "scoring", + "rationale", + } +) +_SCORING_KEYS = frozenset( + { + "level", + "parent_name_field", + "child_population_field", + "parent_population_field", + "population_check", + "populations", + "by_family", + "target_fields", + "baseline", + } +) +_SHARES_KEYS = frozenset({"families", "code_field", "parent_code_divisor"}) + + +class TargetHoldoutError(ValueError): + """A hold-out declaration or a hold-out input is not valid.""" + + +@dataclass(frozen=True) +class RecordTest: + """One test on one field of a target record.""" + + key: str + kind: str + value: Any = None + + def accepts(self, record: Mapping[str, Any]) -> bool: + if self.kind == "equals": + return record.get(self.key) == self.value + return bool(record.get(self.key)) + + +@dataclass(frozen=True) +class ConceptFamilyRule: + """The concept family of a record: what one held unit groups together. + + For a record of one of ``families``, the family is its ``source_field`` + with the first matching ``merge_prefixes`` entry as the whole family, or + else without the first matching ``strip_suffixes`` entry. Measures that + add up to each other then share a family. A record of another family is + its own concept family. + """ + + source_field: str + families: frozenset[str] + merge_prefixes: tuple[str, ...] + strip_suffixes: tuple[str, ...] + rationale: str = "" + + def of_measure(self, measure: str) -> str: + measure = str(measure) + for prefix in self.merge_prefixes: + if measure.startswith(prefix): + return prefix + for suffix in self.strip_suffixes: + if measure.endswith(suffix): + return measure[: -len(suffix)] + return measure + + def of_record(self, record: Mapping[str, Any]) -> str: + if record.get("family") in self.families: + return self.of_measure(str(record.get(self.source_field))) + return str(record.get("family")) + + +@dataclass(frozen=True) +class PopulationShares: + """How a pass's rows get the populations of the pro-rata baseline. + + A row of one of ``families`` whose ``code_field`` is set gets its child + population, and its parent's population: the sum of the child + populations whose code divided by ``parent_code_divisor`` (integer + division) is the same. + """ + + families: frozenset[str] + code_field: str + parent_code_divisor: int + + +@dataclass(frozen=True) +class HoldoutScoring: + """How :func:`score_holdout` scores a pass's held rows.""" + + level: str + parent_name_field: str + child_population_field: str + parent_population_field: str + population_check: str + populations: PopulationShares | None + by_family: bool + target_fields: tuple[tuple[str, str], ...] + baseline: str + + +@dataclass(frozen=True) +class HoldoutPass: + """One declared hold-out pass (see the module docstring).""" + + pass_id: str + label: str + unit: str + unit_fields: tuple[str, ...] + salt: str + default_fraction: float + max_fraction: float + scope: tuple[RecordTest, ...] + eligible: tuple[RecordTest, ...] + receipt: tuple[str, ...] + hash_description: str | None + scoring: HoldoutScoring | None + rationale: str + + def in_scope(self, record: Mapping[str, Any]) -> bool: + return all(test.accepts(record) for test in self.scope) + + def unit_key( + self, record: Mapping[str, Any], concept_families: ConceptFamilyRule + ) -> str | None: + """The record's unit key, or None when the record is not eligible.""" + + if not all(test.accepts(record) for test in self.eligible): + return None + parts = [] + for field in self.unit_fields: + if field == CONCEPT_FAMILY_FIELD: + parts.append(concept_families.of_record(record)) + else: + parts.append(f"{record[field]}") + return UNIT_SEPARATOR.join(parts) + + +@dataclass(frozen=True) +class TargetHoldouts: + """A country's hold-out passes and its concept-family rule.""" + + concept_families: ConceptFamilyRule + passes: tuple[HoldoutPass, ...] + + def holdout_pass(self, pass_id: str) -> HoldoutPass: + for holdout_pass in self.passes: + if holdout_pass.pass_id == pass_id: + return holdout_pass + raise TargetHoldoutError( + f"No hold-out pass {pass_id!r}; declared: " + f"{[holdout_pass.pass_id for holdout_pass in self.passes]}." + ) + + +# --------------------------------------------------------------------------- +# Reading the declaration +# --------------------------------------------------------------------------- + + +def _mapping(value: Any, *, context: str, keys: frozenset[str]) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + raise TargetHoldoutError(f"{context} must be an object.") + unknown = sorted(set(value) - keys) + missing = sorted(keys - set(value)) + if unknown or missing: + raise TargetHoldoutError( + f"{context}: unknown keys {unknown}, missing keys {missing}." + ) + return value + + +def _text(value: Any, *, context: str) -> str: + if not isinstance(value, str) or not value: + raise TargetHoldoutError(f"{context} must be a non-empty string.") + return value + + +def _texts(value: Any, *, context: str, allow_empty: bool = False) -> tuple[str, ...]: + if not isinstance(value, list) or (not value and not allow_empty): + raise TargetHoldoutError(f"{context} must be a list of strings.") + items = tuple(_text(item, context=f"{context} entry") for item in value) + if len(set(items)) != len(items): + raise TargetHoldoutError(f"{context} repeats an entry.") + return items + + +def _fraction(value: Any, *, context: str) -> float: + if isinstance(value, bool) or not isinstance(value, int | float): + raise TargetHoldoutError(f"{context} must be a number.") + if not 0.0 <= float(value) <= 1.0: + raise TargetHoldoutError(f"{context} must be in [0, 1].") + return float(value) + + +def _record_tests(value: Any, *, context: str) -> tuple[RecordTest, ...]: + if not isinstance(value, list): + raise TargetHoldoutError(f"{context} must be a list of tests.") + tests = [] + for raw in value: + if not isinstance(raw, Mapping): + raise TargetHoldoutError(f"{context}: a test must be an object.") + kind = raw.get("kind") + if kind not in RECORD_TEST_KINDS: + raise TargetHoldoutError( + f"{context}: test kind {kind!r} is not one of {RECORD_TEST_KINDS}." + ) + expected = {"key", "kind", "value"} if kind == "equals" else {"key", "kind"} + if set(raw) != expected: + raise TargetHoldoutError( + f"{context}: a {kind!r} test has the keys {sorted(expected)}." + ) + tests.append( + RecordTest( + _text(raw["key"], context=f"{context} key"), kind, raw.get("value") + ) + ) + return tuple(tests) + + +def _population_shares(value: Any, *, context: str) -> PopulationShares | None: + if value is None: + return None + raw = _mapping(value, context=context, keys=_SHARES_KEYS) + divisor = raw["parent_code_divisor"] + if isinstance(divisor, bool) or not isinstance(divisor, int) or divisor < 1: + raise TargetHoldoutError( + f"{context} parent_code_divisor must be a positive integer." + ) + return PopulationShares( + families=frozenset(_texts(raw["families"], context=f"{context} families")), + code_field=_text(raw["code_field"], context=f"{context} code_field"), + parent_code_divisor=divisor, + ) + + +def _scoring(value: Any, *, context: str) -> HoldoutScoring | None: + if value is None: + return None + raw = _mapping(value, context=context, keys=_SCORING_KEYS) + check = raw["population_check"] + if check not in POPULATION_CHECKS: + raise TargetHoldoutError( + f"{context} population_check must be one of {POPULATION_CHECKS}." + ) + if not isinstance(raw["by_family"], bool): + raise TargetHoldoutError(f"{context} by_family must be true or false.") + fields = raw["target_fields"] + if not isinstance(fields, Mapping) or not all( + isinstance(key, str) and key and isinstance(field, str) and field + for key, field in fields.items() + ): + raise TargetHoldoutError( + f"{context} target_fields must map output keys to record fields." + ) + return HoldoutScoring( + level=_text(raw["level"], context=f"{context} level"), + parent_name_field=_text( + raw["parent_name_field"], context=f"{context} parent_name_field" + ), + child_population_field=_text( + raw["child_population_field"], context=f"{context} child_population_field" + ), + parent_population_field=_text( + raw["parent_population_field"], + context=f"{context} parent_population_field", + ), + population_check=check, + populations=_population_shares( + raw["populations"], context=f"{context} populations" + ), + by_family=raw["by_family"], + target_fields=tuple(fields.items()), + baseline=_text(raw["baseline"], context=f"{context} baseline"), + ) + + +def _holdout_pass(raw: Any) -> HoldoutPass: + raw = _mapping(raw, context="hold-out pass", keys=_PASS_KEYS) + pass_id = _text(raw["id"], context="hold-out pass id") + context = f"hold-out pass {pass_id!r}" + receipt = _texts(raw["receipt"], context=f"{context} receipt") + unknown = sorted(set(receipt) - set(RECEIPT_KEYS)) + if unknown: + raise TargetHoldoutError(f"{context} receipt has unknown keys {unknown}.") + hash_description = raw["hash_description"] + if ("hash" in receipt) != (hash_description is not None): + raise TargetHoldoutError( + f"{context}: hash_description is set exactly when the receipt has 'hash'." + ) + if hash_description is not None: + _text(hash_description, context=f"{context} hash_description") + default_fraction = _fraction( + raw["default_fraction"], context=f"{context} default_fraction" + ) + max_fraction = _fraction(raw["max_fraction"], context=f"{context} max_fraction") + if default_fraction > max_fraction: + raise TargetHoldoutError(f"{context}: default_fraction exceeds max_fraction.") + return HoldoutPass( + pass_id=pass_id, + label=_text(raw["label"], context=f"{context} label"), + unit=_text(raw["unit"], context=f"{context} unit"), + unit_fields=_texts(raw["unit_fields"], context=f"{context} unit_fields"), + salt=_text(raw["salt"], context=f"{context} salt"), + default_fraction=default_fraction, + max_fraction=max_fraction, + scope=_record_tests(raw["scope"], context=f"{context} scope"), + eligible=_record_tests(raw["eligible"], context=f"{context} eligible"), + receipt=receipt, + hash_description=hash_description, + scoring=_scoring(raw["scoring"], context=f"{context} scoring"), + rationale=_text(raw["rationale"], context=f"{context} rationale"), + ) + + +def load_target_holdouts(section: Mapping[str, Any]) -> TargetHoldouts: + """Read a country's ``holdouts`` declaration; refuse anything unknown.""" + + raw = _mapping(section, context="holdouts", keys=_SECTION_KEYS) + families = _mapping( + raw["concept_families"], context="holdouts concept_families", keys=_FAMILY_KEYS + ) + concept_families = ConceptFamilyRule( + source_field=_text( + families["source_field"], context="concept_families source_field" + ), + families=frozenset( + _texts(families["families"], context="concept_families families") + ), + merge_prefixes=_texts( + families["merge_prefixes"], + context="concept_families merge_prefixes", + allow_empty=True, + ), + strip_suffixes=_texts( + families["strip_suffixes"], + context="concept_families strip_suffixes", + allow_empty=True, + ), + rationale=_text(families["rationale"], context="concept_families rationale"), + ) + if not isinstance(raw["passes"], list) or not raw["passes"]: + raise TargetHoldoutError("holdouts passes must be a non-empty list.") + passes = tuple(_holdout_pass(item) for item in raw["passes"]) + ids = [holdout_pass.pass_id for holdout_pass in passes] + if len(set(ids)) != len(ids): + raise TargetHoldoutError(f"holdouts passes repeat an id: {ids}.") + return TargetHoldouts(concept_families=concept_families, passes=passes) + + +# --------------------------------------------------------------------------- +# Roles +# --------------------------------------------------------------------------- + + +def assign_holdout_roles( + records: Sequence[dict], + holdout_pass: HoldoutPass, + concept_families: ConceptFamilyRule, + *, + fraction: float | None = None, + salt: str | None = None, +) -> dict: + """Set ``holdout_unit`` and ``role`` on each record in scope; return the receipt. + + An eligible record gets its unit key and the unit's role: a unit is held + out by :func:`microcosm.build.holdout.hash_holdout_unit` on its key, once. + A record in scope that is not eligible gets no unit and trains. A record + out of scope keeps what it had. + """ + + fraction = holdout_pass.default_fraction if fraction is None else fraction + salt = holdout_pass.salt if salt is None else salt + if not isinstance(salt, str) or not salt: + raise TargetHoldoutError( + f"{holdout_pass.label} holdout salt must be a non-empty string." + ) + if not 0.0 <= float(fraction) <= holdout_pass.max_fraction: + raise TargetHoldoutError( + f"{holdout_pass.label} holdout fraction must be in " + f"[0, {holdout_pass.max_fraction}], got {fraction!r}." + ) + units: dict[str, bool] = {} + eligible: list[dict] = [] + for record in records: + if not holdout_pass.in_scope(record): + continue + unit = holdout_pass.unit_key(record, concept_families) + record["holdout_unit"] = unit + if unit is None: + record["role"] = ROLE_TRAIN + continue + if unit not in units: + units[unit] = hash_holdout_unit(unit, fraction=fraction, salt=salt) + record["role"] = ROLE_HOLDOUT if units[unit] else ROLE_TRAIN + eligible.append(record) + held_unit_keys = sorted(unit for unit, held in units.items() if held) + values = { + "unit": holdout_pass.unit, + "salt": salt, + "fraction": float(fraction), + "eligible_units": len(units), + "held_units": len(held_unit_keys), + "held_unit_keys": held_unit_keys, + "eligible_targets": len(eligible), + "held_targets": sum(1 for record in eligible if record["role"] == ROLE_HOLDOUT), + "hash": holdout_pass.hash_description, + } + return {key: values[key] for key in holdout_pass.receipt} + + +def train_rows(records: Sequence[Mapping]) -> list[int]: + return [ + index for index, record in enumerate(records) if record["role"] == ROLE_TRAIN + ] + + +def holdout_rows(records: Sequence[Mapping]) -> list[int]: + return [ + index for index, record in enumerate(records) if record["role"] == ROLE_HOLDOUT + ] + + +# --------------------------------------------------------------------------- +# The training target set +# --------------------------------------------------------------------------- + + +def csr_row_measure(matrix: sparse.csr_array, row: int, n: int): + """A callable measure returning one CSR row as a dense float64 vector. + + The calibrate kernel compiles targets through ``build_constraint_matrix``, + which reads each target's row and keeps its nonzeros; a callable measure + lets it read the row straight from the checkpoint CSR (the UK rowwise + precedent, ``uk_runtime.local_rowwise._rowwise_target_set``). Only one + dense row exists at a time. float32 values widen exactly to float64, as + the dense checkpoint's float32 columns did. + """ + + start, stop = int(matrix.indptr[row]), int(matrix.indptr[row + 1]) + indices = matrix.indices[start:stop] + data = matrix.data[start:stop] + + def measure(frame) -> np.ndarray: + values = np.zeros(n, dtype=np.float64) + values[indices] = data + return values + + # Calibration diagnostics name a callable measure by its qualified name; + # name the matrix row rather than this closure. + measure.__qualname__ = f"target_matrix_row[{row}]" + return measure + + +def training_target_set( + records: Sequence[Mapping], + matrix: sparse.csr_array, + n_households: int, + *, + specs: Sequence | None = None, +): + """The TargetSet the calibrator sees: training targets only. + + Held-out targets are never constructed, so they cannot reach the solve. + With ``specs`` (the checkpoint's registry specs, row-aligned with + ``records``) each target keeps its spec's value, period, source, + metadata and calibration hierarchy, as ``TargetSpec.to_target`` would, + and only its measure becomes the CSR row. + """ + + from microcosm.calibrate.target import Target, TargetSet + + if matrix.shape != (len(records), n_households): + raise ValueError( + f"target matrix shape {matrix.shape} does not match " + f"{len(records)} targets x {n_households} households." + ) + if specs is not None and [spec.name for spec in specs] != [ + record["name"] for record in records + ]: + raise ValueError("target specs are not row-aligned with the roles.") + targets = [] + for index in train_rows(records): + record = records[index] + if record["role"] != ROLE_TRAIN: # pragma: no cover - train_rows filters + raise AssertionError("a held-out target reached the calibration set") + measure = csr_row_measure(matrix, index, n_households) + if specs is None: + targets.append( + Target( + name=record["name"], + entity=record.get("entity", "household"), + measure=measure, + value=float(record["value"]), + period=record["period"], + source=record["source"], + ) + ) + continue + spec = specs[index] + if spec.filter is not None: + raise ValueError( + f"{spec.name}: a filtered spec cannot take a matrix-row measure; " + "the row already carries the filter." + ) + targets.append( + Target( + name=spec.name, + entity=spec.entity, + measure=measure, + value=spec.value, + period=spec.period, + tolerance=spec.tolerance, + source=spec.source, + metadata=spec.metadata, + hierarchy=spec.hierarchy, + ) + ) + held = {records[index]["name"] for index in holdout_rows(records)} + leaked = held & {target.name for target in targets} + if leaked: + raise AssertionError(f"held-out targets reached the calibrator: {leaked}") + return TargetSet(targets) + + +# --------------------------------------------------------------------------- +# Scoring against the pro-rata baseline +# --------------------------------------------------------------------------- + + +def error_summary(estimates, targets, *, cap: float) -> dict: + from microcosm.calibrate import relative_error_loss + + estimates = np.asarray(estimates, dtype=np.float64) + targets = np.asarray(targets, dtype=np.float64) + scale = np.maximum(np.abs(targets), 1.0) + errors = np.abs(estimates - targets) / scale + return { + "mean_abs_rel_error": float(errors.mean()), + "median_abs_rel_error": float(np.median(errors)), + "p90_abs_rel_error": float(np.quantile(errors, 0.9)), + "max_abs_rel_error": float(errors.max()), + "fraction_within_10pct": float((errors <= 0.10).mean()), + "capped_loss": float( + relative_error_loss(estimates, targets, target_loss_cap=cap) + ), + } + + +def attach_population_shares( + records: Sequence[dict], + child_populations: Mapping[int, float], + scoring: HoldoutScoring, +) -> None: + """Give each row its child and parent populations, for the baseline.""" + + shares = scoring.populations + if shares is None: + raise TargetHoldoutError( + f"The {scoring.level} scoring declares no population shares." + ) + parent_population: dict[int, float] = {} + for child, population in child_populations.items(): + parent = int(child) // shares.parent_code_divisor + parent_population[parent] = parent_population.get(parent, 0.0) + float( + population + ) + for record in records: + code = record.get(shares.code_field) + if record.get("family") not in shares.families or not code: + continue + child = int(code) + record[scoring.child_population_field] = float( + child_populations.get(child, 0.0) + ) + record[scoring.parent_population_field] = float( + parent_population.get(child // shares.parent_code_divisor, 0.0) + ) + + +def missing_population_shares( + records: Sequence[Mapping], scoring: HoldoutScoring +) -> list[str]: + """The rows the baseline cannot score: no positive child or parent population.""" + + shares = scoring.populations + if shares is None: + raise TargetHoldoutError( + f"The {scoring.level} scoring declares no population shares." + ) + return [ + record["name"] + for record in records + if record.get("family") in shares.families + and record.get(shares.code_field) + and not ( + record.get(scoring.child_population_field, 0) > 0 + and record.get(scoring.parent_population_field, 0) > 0 + ) + ] + + +def pro_rata_baseline( + records: Sequence[Mapping], rows: Sequence[int], scoring: HoldoutScoring +) -> np.ndarray: + """The parent target times the child's population share, for each row.""" + + by_name = {record["name"]: record for record in records} + values = [] + for index in rows: + record = records[index] + parent = by_name.get(record.get(scoring.parent_name_field)) + if scoring.population_check == "nonzero": + if parent is None: + raise TargetHoldoutError( + f"{record['name']} has no bound parent for the baseline." + ) + child = record.get(scoring.child_population_field) + parent_population = record.get(scoring.parent_population_field) + if not child or not parent_population: + raise TargetHoldoutError( + f"{record['name']} carries no child or parent population for " + "the pro-rata baseline." + ) + values.append( + float(parent["value"]) * float(child) / float(parent_population) + ) + continue + child = float(record.get(scoring.child_population_field, 0)) + parent_population = float(record.get(scoring.parent_population_field, 0)) + if parent is None or not ( + math.isfinite(child) + and math.isfinite(parent_population) + and child > 0 + and parent_population > 0 + ): + raise TargetHoldoutError( + f"{record['name']} has no parent or positive child and parent " + "population for the pro-rata baseline." + ) + values.append(float(parent["value"]) * child / parent_population) + return np.asarray(values, dtype=np.float64) + + +def score_holdout( + records: Sequence[Mapping], + matrix: sparse.csr_array, + scoring: HoldoutScoring, + *, + design_weights: np.ndarray, + final_weights: np.ndarray, + cap: float, + receipt: Mapping | None = None, +) -> dict: + """Held-out rows at the scoring level: calibrated vs design vs pro-rata.""" + + rows = [ + row + for row in holdout_rows(records) + if records[row].get("geography_level") == scoring.level + ] + base = {"report_only": True, **dict(receipt or {}), "n_targets": len(rows)} + if not rows: + return base + held = sparse.csr_array(matrix[rows]).astype(np.float64) + targets = np.asarray([records[index]["value"] for index in rows], dtype=np.float64) + final = held @ np.asarray(final_weights, dtype=np.float64) + design = held @ np.asarray(design_weights, dtype=np.float64) + baseline = pro_rata_baseline(records, rows, scoring) + scale = np.maximum(np.abs(targets), 1.0) + final_error = np.abs(final - targets) / scale + baseline_error = np.abs(baseline - targets) / scale + result = { + **base, + "calibrated": error_summary(final, targets, cap=cap), + "design_weights": error_summary(design, targets, cap=cap), + "pro_rata_baseline": error_summary(baseline, targets, cap=cap), + "calibrated_beats_pro_rata_share": float((final_error < baseline_error).mean()), + "baseline": scoring.baseline, + } + if scoring.by_family: + families: dict[str, list[int]] = defaultdict(list) + for position, index in enumerate(rows): + family = str(records[index]["holdout_unit"]).split(UNIT_SEPARATOR, 1)[1] + families[family].append(position) + by_family = {} + for family, positions in sorted(families.items()): + idx = np.asarray(positions) + by_family[family] = { + "n_targets": len(positions), + "calibrated_mean_abs_rel_error": float(final_error[idx].mean()), + "pro_rata_mean_abs_rel_error": float(baseline_error[idx].mean()), + "calibrated_beats_pro_rata": float( + (final_error[idx] < baseline_error[idx]).mean() + ), + } + result["by_family"] = by_family + result["targets"] = [ + { + "name": records[index]["name"], + **{key: records[index][field] for key, field in scoring.target_fields}, + "target": float(targets[position]), + "calibrated": float(final[position]), + "design": float(design[position]), + "pro_rata": float(baseline[position]), + } + for position, index in enumerate(rows) + ] + return result diff --git a/packages/microcosm-build/src/microcosm/build/us/country_package.json b/packages/microcosm-build/src/microcosm/build/us/country_package.json index 955f2e379b..07aacdbc49 100644 --- a/packages/microcosm-build/src/microcosm/build/us/country_package.json +++ b/packages/microcosm-build/src/microcosm/build/us/country_package.json @@ -107,6 +107,11 @@ "kind": "legacy_json", "schema_id": "legacy_json" }, + { + "path": "local_target_construction.json", + "kind": "legacy_json", + "schema_id": "legacy_json" + }, { "path": "obbba_reforms.json", "kind": "legacy_json", diff --git a/packages/microcosm-build/src/microcosm/build/us/local_target_construction.json b/packages/microcosm-build/src/microcosm/build/us/local_target_construction.json new file mode 100644 index 0000000000..45bbe183c8 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us/local_target_construction.json @@ -0,0 +1,136 @@ +{ + "version": 1, + "country": "us", + "description": "How the ACS local release (tools/build_us_acs_local_release.py) builds the targets that the compile does not give it (microcosm#1728). Each section is read by a shared, country-free module: holdouts by microcosm.build.target_holdouts.", + "holdouts": { + "concept_families": { + "source_field": "source_measure_id", + "families": [ + "irs_soi" + ], + "merge_prefixes": [ + "eitc" + ], + "strip_suffixes": [ + "_amount", + "_returns", + "_claims", + "_count" + ], + "rationale": "The holdout family of an IRS SOI measure is its concept without the count or amount suffix. Every EITC measure is one family, because the per-child-count rows add up to the EITC total and holding one out would leave it pinned by the rest. A target of another family is its own concept family." + }, + "passes": [ + { + "id": "district", + "label": "CD", + "unit": "state_x_soi_concept_family", + "unit_fields": [ + "state_fips", + "concept_family" + ], + "salt": "microcosm.us_acs_local.cd_holdout.v1", + "default_fraction": 0.1, + "max_fraction": 0.5, + "scope": [], + "eligible": [ + { + "key": "family", + "kind": "equals", + "value": "irs_soi" + }, + { + "key": "geography_level", + "kind": "equals", + "value": "congressional_district" + }, + { + "key": "state_cd_parent_target_name", + "kind": "truthy" + } + ], + "receipt": [ + "unit", + "salt", + "fraction", + "eligible_units", + "held_units", + "held_unit_keys", + "eligible_targets", + "held_targets", + "hash" + ], + "hash_description": "sha256(salt + 0x1f + unit)[:8] / 2**64 < fraction", + "scoring": { + "level": "congressional_district", + "parent_name_field": "state_cd_parent_target_name", + "child_population_field": "cd_population", + "parent_population_field": "state_population", + "population_check": "nonzero", + "populations": { + "families": [ + "irs_soi" + ], + "code_field": "congressional_district_geoid", + "parent_code_divisor": 100 + }, + "by_family": true, + "target_fields": { + "unit": "holdout_unit" + }, + "baseline": "state parent target x (district population / state population), populations from the PUMA ladder's 119th-plan district overlap" + }, + "rationale": "The held unit is every district target of one SOI concept family in one state. A single district, or a single district target, is not a fair holdout: with its state total and sibling districts trained it is pinned by adding up. Only district SOI targets with a bound state parent are eligible; every other target trains. The pass writes every record. The tool draws the default fraction under --soi-mode state_cd and none in the other modes." + }, + { + "id": "county", + "label": "County", + "unit": "state x county concept family", + "unit_fields": [ + "state_fips", + "concept_family" + ], + "salt": "acs-local-county-v1", + "default_fraction": 0.1, + "max_fraction": 0.5, + "scope": [ + { + "key": "geography_level", + "kind": "equals", + "value": "county" + } + ], + "eligible": [ + { + "key": "state_county_parent_target_name", + "kind": "truthy" + } + ], + "receipt": [ + "unit", + "salt", + "fraction", + "eligible_units", + "eligible_targets", + "held_units", + "held_unit_keys", + "held_targets" + ], + "hash_description": null, + "scoring": { + "level": "county", + "parent_name_field": "state_county_parent_target_name", + "child_population_field": "county_population", + "parent_population_field": "state_population", + "population_check": "finite_positive", + "populations": null, + "by_family": false, + "target_fields": { + "county_fips": "county_fips" + }, + "baseline": "state parent target x county population / state population" + }, + "rationale": "Hold out whole state and concept-family blocks of county rows, so that no held county row is pinned by its trained siblings. Only county rows with a state parent are eligible, so the county population rows always train. The pass writes county rows only, after the district pass." + } + ] + } +} diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/local_target_construction.py b/packages/microcosm-build/src/microcosm/build/us_runtime/local_target_construction.py new file mode 100644 index 0000000000..a6ac0499e1 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/local_target_construction.py @@ -0,0 +1,90 @@ +"""The declared target construction of the US ACS local release (microcosm#1728). + +``us/local_target_construction.json`` declares how the ACS local release +(``tools/build_us_acs_local_release.py``) builds the targets that the compile +does not give it. A shared, country-free module reads each section: + +- ``holdouts``: :mod:`microcosm.build.target_holdouts` (the district and the + county hold-out passes, and how their held rows are scored). + +This module names the US file and its passes. +""" + +from __future__ import annotations + +import json +from functools import lru_cache +from importlib.resources import files +from pathlib import Path +from typing import Any + +from microcosm.build.target_holdouts import ( + HoldoutPass, + HoldoutScoring, + TargetHoldouts, + load_target_holdouts, +) + +__all__ = [ + "COUNTY_HOLDOUT", + "DISTRICT_HOLDOUT", + "US_LOCAL_TARGET_CONSTRUCTION_RESOURCE", + "us_holdout_pass", + "us_holdout_scoring", + "us_local_target_construction", + "us_local_target_construction_path", + "us_target_holdouts", +] + +US_LOCAL_TARGET_CONSTRUCTION_RESOURCE = "local_target_construction.json" +#: The hold-out pass over district SOI rows (``--soi-mode state_cd``). +DISTRICT_HOLDOUT = "district" +#: The hold-out pass over county rows (``--soi-mode state_county``). +COUNTY_HOLDOUT = "county" + +_ENVELOPE_KEYS = frozenset({"version", "country", "description", "holdouts"}) + + +def us_local_target_construction_path() -> Path: + return Path( + str(files("microcosm.build.us").joinpath(US_LOCAL_TARGET_CONSTRUCTION_RESOURCE)) + ) + + +@lru_cache(maxsize=1) +def us_local_target_construction() -> dict[str, Any]: + """The packaged US file, with its envelope checked.""" + + payload = json.loads( + us_local_target_construction_path().read_text(encoding="utf-8") + ) + if not isinstance(payload, dict) or set(payload) != _ENVELOPE_KEYS: + raise ValueError( + f"{US_LOCAL_TARGET_CONSTRUCTION_RESOURCE} must hold exactly the keys " + f"{sorted(_ENVELOPE_KEYS)}." + ) + if payload["version"] != 1 or payload["country"] != "us": + raise ValueError( + f"{US_LOCAL_TARGET_CONSTRUCTION_RESOURCE} must be version 1 for country us." + ) + return payload + + +@lru_cache(maxsize=1) +def us_target_holdouts() -> TargetHoldouts: + """The US hold-out passes, read and checked once.""" + + return load_target_holdouts(us_local_target_construction()["holdouts"]) + + +def us_holdout_pass(pass_id: str) -> HoldoutPass: + return us_target_holdouts().holdout_pass(pass_id) + + +def us_holdout_scoring(pass_id: str) -> HoldoutScoring: + """The declared scoring of a US hold-out pass; refuse a pass without one.""" + + scoring = us_holdout_pass(pass_id).scoring + if scoring is None: + raise ValueError(f"The US hold-out pass {pass_id!r} declares no scoring.") + return scoring diff --git a/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py b/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py index 726dfa5037..92bd130306 100644 --- a/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py +++ b/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py @@ -82,22 +82,22 @@ def test_us_coverage_is_exact_complete_and_honest( assert_coverage_complete(coverage_report) assert coverage_report["status"] == "pass" fields = coverage_report["field_usage"] - assert fields["configuration_field_count"] == 42407 - assert fields["authored_normative_field_count"] == 32621 + assert fields["configuration_field_count"] == 42410 + assert fields["authored_normative_field_count"] == 32624 assert fields["resolved_binding_field_count"] == 9786 - assert fields["consumed_field_count"] == 42407 + assert fields["consumed_field_count"] == 42410 assert fields["unused_field_count"] == 0 assert fields["multiple_primary_use_field_count"] == 0 assert fields["claim_count"] == 48 assert fields["mode_counts"] == { "legacy_behavior": 14_269, "compiler_semantic": 27674, - "front_end_validation": 361, + "front_end_validation": 364, "identity_only": 103, } assert fields["generation0_effect_counts"] == { "legacy_behavior": 38_780, - "no_generation0_effect": 3627, + "no_generation0_effect": 3630, } inventory = coverage_report["inventory_coverage"] diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py index dbfbae1de4..2b9db90be3 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py @@ -95,22 +95,22 @@ def _mutated_bundle( def test_exact_complete_ledger_has_one_primary_mode_per_pointer(field_ledger) -> None: - assert len(field_ledger.fields) == EXPECTED_CONFIGURATION_FIELD_COUNT == 42407 + assert len(field_ledger.fields) == EXPECTED_CONFIGURATION_FIELD_COUNT == 42410 assert field_ledger.source_counts == { - "authored": 32621, + "authored": 32624, "resolved_bindings": 9786, } assert field_ledger.mode_counts == { "legacy_behavior": 14_269, "compiler_semantic": 27674, - "front_end_validation": 361, + "front_end_validation": 364, "identity_only": 103, } assert field_ledger.generation0_effect_counts == { "legacy_behavior": 38_780, - "no_generation0_effect": 3627, + "no_generation0_effect": 3630, } - assert len({field.pointer for field in field_ledger.fields}) == 42407 + assert len({field.pointer for field in field_ledger.fields}) == 42410 def test_eligibility_concepts_are_validation_not_generation0_behavior( diff --git a/packages/microcosm-build/tests/engine_free/shared/test_target_holdouts.py b/packages/microcosm-build/tests/engine_free/shared/test_target_holdouts.py new file mode 100644 index 0000000000..a22be3eefc --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_target_holdouts.py @@ -0,0 +1,411 @@ +"""The shared hold-out passes (microcosm.build.target_holdouts, microcosm#1728). + +The tests use a made-up country: regions hold districts, and a district target +of the ``tax`` family is held out with the other targets of its concept family +in its region. They check the reader, the record tests, the concept families, +the role pass and its receipt, the training target set, and the scoring +against the pro-rata baseline. No country code is read. +""" + +from __future__ import annotations + +import copy +import json +import math + +import numpy as np +import pytest +from scipy import sparse + +from microcosm.build.holdout import hash_holdout_unit +from microcosm.build.target_holdouts import ( + ROLE_HOLDOUT, + ROLE_TRAIN, + ConceptFamilyRule, + RecordTest, + TargetHoldoutError, + assign_holdout_roles, + attach_population_shares, + error_summary, + load_target_holdouts, + missing_population_shares, + pro_rata_baseline, + score_holdout, + training_target_set, +) + + +def _section() -> dict: + return { + "concept_families": { + "source_field": "measure", + "families": ["tax"], + "merge_prefixes": ["credit"], + "strip_suffixes": ["_amount", "_count"], + "rationale": "Counts and amounts of one concept are one family.", + }, + "passes": [ + { + "id": "district", + "label": "District", + "unit": "region_x_family", + "unit_fields": ["region", "concept_family"], + "salt": "test.district.v1", + "default_fraction": 0.25, + "max_fraction": 0.5, + "scope": [], + "eligible": [ + {"key": "geography_level", "kind": "equals", "value": "district"}, + {"key": "parent", "kind": "truthy"}, + ], + "receipt": ["unit", "fraction", "held_units", "hash"], + "hash_description": "a salted hash", + "scoring": { + "level": "district", + "parent_name_field": "parent", + "child_population_field": "child_pop", + "parent_population_field": "parent_pop", + "population_check": "nonzero", + "populations": { + "families": ["tax"], + "code_field": "code", + "parent_code_divisor": 100, + }, + "by_family": True, + "target_fields": {"unit": "holdout_unit"}, + "baseline": "parent x population share", + }, + "rationale": "Whole blocks, so no sibling pins a held row.", + }, + { + "id": "ward", + "label": "Ward", + "unit": "region_x_family", + "unit_fields": ["region", "concept_family"], + "salt": "test.ward.v1", + "default_fraction": 0.1, + "max_fraction": 0.5, + "scope": [ + {"key": "geography_level", "kind": "equals", "value": "ward"} + ], + "eligible": [{"key": "parent", "kind": "truthy"}], + "receipt": ["unit", "eligible_targets", "held_targets"], + "hash_description": None, + "scoring": None, + "rationale": "Ward rows only.", + }, + ], + } + + +def _records() -> list[dict]: + records = [ + { + "name": "r1_income", + "geography_level": "region", + "family": "tax", + "value": 100.0, + }, + { + "name": "r2_income", + "geography_level": "region", + "family": "tax", + "value": 80.0, + }, + ] + for region, parent in (("1", "r1_income"), ("2", "r2_income")): + for district in range(1, 5): + for measure in ("income_amount", "income_count", "credit_x", "other"): + records.append( + { + "name": f"d{region}{district}_{measure}", + "geography_level": "district", + "family": "tax", + "measure": measure, + "region": region, + "code": f"{region}{district:02d}", + "parent": parent if measure != "other" else "", + "value": float(10 * district), + } + ) + records.append( + { + "name": "w1", + "geography_level": "ward", + "family": "pop", + "region": "1", + "value": 7.0, + } + ) + return records + + +def test_the_reader_reads_a_declaration() -> None: + holdouts = load_target_holdouts(_section()) + district = holdouts.holdout_pass("district") + assert district.unit_fields == ("region", "concept_family") + assert district.eligible[1] == RecordTest("parent", "truthy") + assert district.scoring is not None + assert district.scoring.target_fields == (("unit", "holdout_unit"),) + assert holdouts.holdout_pass("ward").scoring is None + with pytest.raises(TargetHoldoutError, match="No hold-out pass"): + holdouts.holdout_pass("county") + + +def _mutations(): + def drop(path, key): + def mutate(section): + target = section + for step in path: + target = target[step] + del target[key] + + return mutate + + def set_(path, key, value): + def mutate(section): + target = section + for step in path: + target = target[step] + target[key] = value + + return mutate + + first = ("passes", 0) + return { + "unknown top key": set_((), "extra", 1), + "missing passes": drop((), "passes"), + "empty passes": set_((), "passes", []), + "unknown pass key": set_(first, "extra", 1), + "missing salt": drop(first, "salt"), + "empty salt": set_(first, "salt", ""), + "fraction above one": set_(first, "max_fraction", 1.5), + "default above max": set_(first, "default_fraction", 0.75), + "boolean fraction": set_(first, "default_fraction", True), + "unknown receipt key": set_(first, "receipt", ["unit", "nope"]), + "hash without description": set_(first, "hash_description", None), + "unknown test kind": set_(first, "eligible", [{"key": "a", "kind": "near"}]), + "equals without value": set_( + first, "eligible", [{"key": "a", "kind": "equals"}] + ), + "truthy with value": set_( + first, "eligible", [{"key": "a", "kind": "truthy", "value": 1}] + ), + "empty unit fields": set_(first, "unit_fields", []), + "bad population check": set_( + (*first, "scoring"), "population_check", "sometimes" + ), + "bad divisor": set_( + (*first, "scoring", "populations"), "parent_code_divisor", 0 + ), + "bad target fields": set_((*first, "scoring"), "target_fields", ["unit"]), + "repeated pass id": set_(("passes", 1), "id", "district"), + "bad family list": set_(("concept_families",), "families", "tax"), + } + + +@pytest.mark.parametrize("case", sorted(_mutations())) +def test_the_reader_refuses_a_malformed_declaration(case: str) -> None: + section = _section() + _mutations()[case](section) + with pytest.raises(TargetHoldoutError): + load_target_holdouts(section) + + +def test_record_tests() -> None: + equals = RecordTest("level", "equals", "district") + truthy = RecordTest("parent", "truthy") + assert equals.accepts({"level": "district"}) + assert not equals.accepts({"level": "region"}) + assert not equals.accepts({}) + assert truthy.accepts({"parent": "r1"}) + for value in ("", 0, None, []): + assert not truthy.accepts({"parent": value}) + assert not truthy.accepts({}) + + +def test_concept_families() -> None: + rule = ConceptFamilyRule("measure", frozenset({"tax"}), ("credit",), ("_amount",)) + assert rule.of_measure("credit_one_child_count") == "credit" + assert rule.of_measure("income_amount") == "income" + assert rule.of_measure("income_count") == "income_count" + assert rule.of_record({"family": "tax", "measure": "income_amount"}) == "income" + assert rule.of_record({"family": "pop", "measure": "income_amount"}) == "pop" + + +def test_the_role_pass() -> None: + holdouts = load_target_holdouts(_section()) + district = holdouts.holdout_pass("district") + records = _records() + receipt = assign_holdout_roles(records, district, holdouts.concept_families) + + assert list(receipt) == ["unit", "fraction", "held_units", "hash"] + assert receipt["fraction"] == 0.25 + assert receipt["hash"] == "a salted hash" + units = {} + for record in records: + assert list(record)[-2:] == ["holdout_unit", "role"] + eligible = record["geography_level"] == "district" and bool( + record.get("parent") + ) + if not eligible: + assert (record["holdout_unit"], record["role"]) == (None, ROLE_TRAIN) + continue + family = { + "income_amount": "income", + "income_count": "income", + "credit_x": "credit", + }[record["measure"]] + assert record["holdout_unit"] == f"{record['region']}|{family}" + held = hash_holdout_unit( + record["holdout_unit"], fraction=0.25, salt="test.district.v1" + ) + assert record["role"] == (ROLE_HOLDOUT if held else ROLE_TRAIN) + units[record["holdout_unit"]] = held + assert receipt["held_units"] == sum(units.values()) + + # The ward pass writes ward rows only; district rows keep their roles. + before = copy.deepcopy(records) + ward = assign_holdout_roles( + records, holdouts.holdout_pass("ward"), holdouts.concept_families + ) + assert records[:-1] == before[:-1] + assert records[-1]["holdout_unit"] is None + assert ward == {"unit": "region_x_family", "eligible_targets": 0, "held_targets": 0} + + +def test_the_role_pass_refuses_a_bad_fraction_or_salt() -> None: + holdouts = load_target_holdouts(_section()) + district = holdouts.holdout_pass("district") + for fraction in (-0.01, 0.51): + with pytest.raises(TargetHoldoutError, match="fraction must be in"): + assign_holdout_roles( + _records(), district, holdouts.concept_families, fraction=fraction + ) + with pytest.raises(TargetHoldoutError, match="salt"): + assign_holdout_roles(_records(), district, holdouts.concept_families, salt="") + + +def _scored(): + holdouts = load_target_holdouts(_section()) + district = holdouts.holdout_pass("district") + records = _records() + assign_holdout_roles(records, district, holdouts.concept_families, fraction=0.5) + attach_population_shares( + records, + {101: 10.0, 102: 30.0, 103: 20.0, 104: 40.0, 201: 5.0}, + district.scoring, + ) + return records, district.scoring + + +def test_population_shares() -> None: + records, scoring = _scored() + by_name = {record["name"]: record for record in records} + district = by_name["d12_income_amount"] + assert (district["child_pop"], district["parent_pop"]) == (30.0, 100.0) + # Districts the ladder does not know get no population and are named. + missing = missing_population_shares(records, scoring) + assert "d22_income_amount" in missing + assert "d12_income_amount" not in missing + assert "r1_income" not in by_name["r1_income"] + + +def test_the_training_target_set_keeps_training_rows_only() -> None: + records, _scoring = _scored() + for record in records: + record.setdefault("period", 2024) + record.setdefault("source", "test") + n = 4 + matrix = sparse.csr_array( + np.arange(len(records) * n, dtype=np.float32).reshape(len(records), n) + ) + target_set = training_target_set(records, matrix, n) + trained = [record["name"] for record in records if record["role"] == ROLE_TRAIN] + assert [target.name for target in target_set.targets] == trained + first = target_set.targets[0] + row = [record["name"] for record in records].index(first.name) + assert np.array_equal(first.measure(None), matrix.toarray()[row].astype(np.float64)) + with pytest.raises(ValueError, match="does not match"): + training_target_set(records, matrix, n + 1) + with pytest.raises(ValueError, match="row-aligned"): + training_target_set(records, matrix, n, specs=[]) + + +def test_scoring_against_the_pro_rata_baseline() -> None: + records, scoring = _scored() + held = [ + index + for index, record in enumerate(records) + if record["role"] == ROLE_HOLDOUT and record.get("child_pop") + ] + assert held, "the fixture must hold out some covered rows" + keep = {records[index]["name"] for index in held} + # Rows the ladder does not cover cannot be scored; train them here. + for record in records: + if record["role"] == ROLE_HOLDOUT and record["name"] not in keep: + record["role"] = ROLE_TRAIN + n = 3 + rng = np.random.default_rng(0) + matrix = sparse.csr_array(rng.uniform(0, 2, size=(len(records), n))) + design, final = np.ones(n), rng.uniform(0.5, 1.5, size=n) + result = score_holdout( + records, + matrix, + scoring, + design_weights=design, + final_weights=final, + cap=10.0, + receipt={"unit": "region_x_family"}, + ) + assert list(result)[:3] == ["report_only", "unit", "n_targets"] + assert result["n_targets"] == len(held) + assert list(result)[-2:] == ["by_family", "targets"] + first = result["targets"][0] + assert list(first) == [ + "name", + "unit", + "target", + "calibrated", + "design", + "pro_rata", + ] + record = records[held[0]] + parent = next(r for r in records if r["name"] == record["parent"]) + assert ( + first["pro_rata"] + == parent["value"] * record["child_pop"] / record["parent_pop"] + ) + json.dumps(result) + + for record in records: + record["role"] = ROLE_TRAIN + empty = score_holdout( + records, matrix, scoring, design_weights=design, final_weights=final, cap=10.0 + ) + assert empty == {"report_only": True, "n_targets": 0} + + +def test_the_population_checks() -> None: + _records_, scoring = _scored() + parent = {"name": "p", "value": 10.0} + row = {"name": "c", "parent": "p", "child_pop": float("nan"), "parent_pop": 4.0} + nonzero = pro_rata_baseline([parent, row], [1], scoring) + assert math.isnan(nonzero[0]) + strict = type(scoring)( + **{**scoring.__dict__, "population_check": "finite_positive"} + ) + with pytest.raises(TargetHoldoutError): + pro_rata_baseline([parent, row], [1], strict) + row["child_pop"] = 0.0 + with pytest.raises(TargetHoldoutError): + pro_rata_baseline([parent, row], [1], scoring) + row["child_pop"], row["parent"] = 2.0, "missing" + with pytest.raises(TargetHoldoutError): + pro_rata_baseline([parent, row], [1], scoring) + + +def test_error_summary() -> None: + summary = error_summary([1.0, 2.0, 4.0], [1.0, 1.0, 2.0], cap=10.0) + assert summary["max_abs_rel_error"] == 1.0 + assert summary["fraction_within_10pct"] == pytest.approx(1 / 3) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py index 1feb1ee7e8..bf7ac56faa 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py @@ -368,6 +368,10 @@ # The national materializer's ledger filter rules (moved from the # release tool, microcosm#1728); reads spec metadata only, no frame. "ledger_filter_rules.py", + # Names and loads the ACS local release's declared target + # construction (us/local_target_construction.json, microcosm#1728); + # reads no frame and treats no population. + "local_target_construction.py", "l0_refit_export.py", "late_producer_dag.py", # Pure contract/schedule derivation; no treatment. "medicaid_take_up.py", diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_target_holdouts.py b/packages/microcosm-build/tests/engine_free/us/test_us_target_holdouts.py new file mode 100644 index 0000000000..48cb8a9ba3 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_target_holdouts.py @@ -0,0 +1,354 @@ +"""The US local hold-outs on the shared code give what the tool code gave. + +microcosm#1728 moved the district and county hold-outs of the ACS local +release to the shared ``microcosm.build.target_holdouts``, with the US +choices in ``us/local_target_construction.json``. These tests hold the tool +functions, which now call the shared code, to verbatim copies of the code they +replace (``test_support/microcosm_build/us_target_holdouts_reference.py``) on +random target records: the same roles and units on every record, the same +receipts, populations, training target sets and scores, with the same key +order. ``test_us_acs_local_surface_bytes.py`` checks the same on the pinned +feed and ladder. +""" + +from __future__ import annotations + +import copy +import importlib.util +import json + +import numpy as np +import pytest +from scipy import sparse + +from microcosm.build.us_runtime.local_target_construction import ( + COUNTY_HOLDOUT, + DISTRICT_HOLDOUT, + us_holdout_pass, + us_local_target_construction, + us_target_holdouts, +) +from microcosm.calibrate import TargetSpec +from test_support.microcosm_build import us_target_holdouts_reference as reference +from test_support.paths import paths_for + +_TEST_PATHS = paths_for("microcosm-build") + +MEASURES = ( + "agi_amount", + "agi_returns", + "eitc_amount", + "eitc_one_child_amount", + "eitc_three_or_more_children_claims", + "salt_claims", + "mortgage_interest_count", + "wages", + "dividends_amount", +) +STATES = ("06", "36", "48") +SEEDS = range(12) + + +@pytest.fixture(scope="module") +def tool(): + path = _TEST_PATHS.repository / "tools" / "build_us_acs_local_release.py" + spec = importlib.util.spec_from_file_location("build_us_acs_local_release", path) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module + + +def _records(seed: int) -> list[dict]: + """Role records of every kind the hold-outs read, some of them defective.""" + + rng = np.random.default_rng(seed) + records: list[dict] = [] + + def add(**fields): + record = { + "name": f"t{len(records):04d}", + "entity": "household", + "period": 2024, + "value": float(rng.uniform(-50.0, 5_000.0)), + "source": "ledger_feed", + **fields, + } + records.append(record) + return record + + parents = {} + for state in STATES: + for measure in MEASURES: + parents[(state, measure)] = add( + family="irs_soi", + geography_level="state", + state_fips=state, + source_measure_id=measure, + )["name"] + add(family="usda_snap", geography_level="state", state_fips=state) + for _ in range(int(rng.integers(20, 60))): + state = STATES[int(rng.integers(len(STATES)))] + measure = MEASURES[int(rng.integers(len(MEASURES)))] + district = f"{state}{int(rng.integers(1, 9)):02d}" + record = add( + family="irs_soi", + geography_level="congressional_district", + state_fips=state, + congressional_district_geoid=district, + source_measure_id=measure, + ) + draw = rng.uniform() + if draw < 0.8: + record["state_cd_parent_target_name"] = parents[(state, measure)] + elif draw < 0.9: + record["state_cd_parent_target_name"] = "" + for _ in range(int(rng.integers(10, 40))): + state = STATES[int(rng.integers(len(STATES)))] + county = f"{state}{int(rng.integers(1, 200)):03d}" + family = ("irs_soi", "acs_households", "census_population_ladder")[ + int(rng.integers(3)) + ] + record = add( + family=family, + geography_level="county", + state_fips=state, + county_fips=county, + source_measure_id=MEASURES[int(rng.integers(len(MEASURES)))], + county_population=float(rng.uniform(1.0, 1e5)), + state_population=float(rng.uniform(1e5, 1e7)), + ) + if family != "census_population_ladder" and rng.uniform() < 0.85: + measure = record["source_measure_id"] + record["state_county_parent_target_name"] = parents[(state, measure)] + for state in STATES: + add( + family="census_population_ladder", + geography_level="state", + state_fips=state, + congressional_district_geoid=None, + ) + order = rng.permutation(len(records)) + return [records[index] for index in order] + + +def _cd_populations(records: list[dict], seed: int) -> dict[int, float]: + rng = np.random.default_rng(seed + 1_000) + codes = sorted( + { + int(record["congressional_district_geoid"]) + for record in records + if record.get("congressional_district_geoid") + } + ) + return {code: float(rng.uniform(1e4, 1e6)) for code in codes} + + +def _dumps(value) -> str: + return json.dumps(value, indent=1) + + +def test_the_declaration_holds_the_tool_constants() -> None: + district = us_holdout_pass(DISTRICT_HOLDOUT) + county = us_holdout_pass(COUNTY_HOLDOUT) + assert (district.salt, district.unit) == ( + reference.CD_HOLDOUT_SALT, + reference.CD_HOLDOUT_UNIT, + ) + assert (district.default_fraction, district.max_fraction) == ( + reference.DEFAULT_STATE_CD_HOLDOUT_FRACTION, + reference.MAX_CD_HOLDOUT_FRACTION, + ) + assert (county.salt, county.default_fraction, county.max_fraction) == ( + reference.COUNTY_HOLDOUT_SALT, + reference.DEFAULT_COUNTY_HOLDOUT_FRACTION, + reference.MAX_CD_HOLDOUT_FRACTION, + ) + assert set(us_local_target_construction()) == { + "version", + "country", + "description", + "holdouts", + } + + +def test_the_tool_names_read_the_declaration(tool) -> None: + cd_surface, county_surface = tool.cd_surface, tool.county_surface + assert cd_surface.CD_HOLDOUT_SALT == reference.CD_HOLDOUT_SALT + assert cd_surface.CD_HOLDOUT_UNIT == reference.CD_HOLDOUT_UNIT + assert cd_surface.DEFAULT_STATE_CD_HOLDOUT_FRACTION == 0.1 + assert cd_surface.MAX_CD_HOLDOUT_FRACTION == 0.5 + assert (cd_surface.ROLE_TRAIN, cd_surface.ROLE_HOLDOUT) == ( + reference.ROLE_TRAIN, + reference.ROLE_HOLDOUT, + ) + assert county_surface.COUNTY_HOLDOUT_SALT == reference.COUNTY_HOLDOUT_SALT + assert county_surface.DEFAULT_COUNTY_HOLDOUT_FRACTION == 0.1 + + +@pytest.mark.parametrize("measure", [*MEASURES, "eitc", "x_count_amount", "plain"]) +def test_concept_families_match(tool, measure: str) -> None: + assert tool.cd_surface.soi_concept_family(measure) == ( + reference.soi_concept_family(measure) + ) + + +@pytest.mark.parametrize("seed", SEEDS) +@pytest.mark.parametrize("fraction", [0.0, 0.1, 0.35, 0.5]) +def test_roles_and_receipts_match(tool, seed: int, fraction: float) -> None: + old, new = _records(seed), _records(seed) + salt = None if seed % 2 else f"salt-{seed}" + kwargs = {} if salt is None else {"salt": salt} + + old_cd = reference.cd_assign_target_roles(old, fraction=fraction, **kwargs) + new_cd = tool.cd_surface.assign_target_roles(new, fraction=fraction, **kwargs) + assert _dumps(new_cd) == _dumps(old_cd) + assert [tool.cd_surface.cd_holdout_unit_key(record) for record in new] == [ + reference.cd_holdout_unit_key(record) for record in old + ] + old_county = reference.county_assign_target_roles(old, fraction=fraction, **kwargs) + new_county = tool.county_surface.assign_target_roles( + new, fraction=fraction, **kwargs + ) + assert _dumps(new_county) == _dumps(old_county) + assert _dumps(new) == _dumps(old) + + +@pytest.mark.parametrize("fraction", [-0.1, 0.51, 1.0]) +def test_out_of_range_fractions_refuse_as_before(tool, fraction: float) -> None: + for old_call, new_call in ( + (reference.cd_assign_target_roles, tool.cd_surface.assign_target_roles), + (reference.county_assign_target_roles, tool.county_surface.assign_target_roles), + ): + with pytest.raises(ValueError): + old_call(_records(0), fraction=fraction) + with pytest.raises(ValueError): + new_call(_records(0), fraction=fraction) + + +@pytest.mark.parametrize("seed", SEEDS) +def test_populations_match(tool, seed: int) -> None: + old, new = _records(seed), _records(seed) + populations = _cd_populations(old, seed) + reference._attach_pro_rata_populations(old, populations) + tool._attach_pro_rata_populations(new, populations) + assert _dumps(new) == _dumps(old) + reference._require_pro_rata_populations(old) + tool._require_pro_rata_populations(new) + + # A district row without a ladder population refuses in both. + old_missing, new_missing = copy.deepcopy(old), copy.deepcopy(new) + for records in (old_missing, new_missing): + for record in records: + if record.get("congressional_district_geoid"): + record["cd_population"] = 0.0 + break + with pytest.raises(SystemExit) as old_error: + reference._require_pro_rata_populations(old_missing) + with pytest.raises(SystemExit) as new_error: + tool._require_pro_rata_populations(new_missing) + assert str(new_error.value) == str(old_error.value) + + +def _matrix(n_records: int, n_households: int, seed: int) -> sparse.csr_array: + rng = np.random.default_rng(seed + 2_000) + dense = rng.uniform(0.0, 3.0, size=(n_records, n_households)) + dense[rng.uniform(size=dense.shape) < 0.6] = 0.0 + return sparse.csr_array(dense.astype(np.float32)) + + +@pytest.mark.parametrize("seed", SEEDS) +def test_training_sets_and_scores_match(tool, seed: int) -> None: + old, new = _records(seed), _records(seed) + populations = _cd_populations(old, seed) + reference._attach_pro_rata_populations(old, populations) + tool._attach_pro_rata_populations(new, populations) + old_receipt = reference.cd_assign_target_roles(old, fraction=0.5) + new_receipt = tool.cd_surface.assign_target_roles(new, fraction=0.5) + old_county = reference.county_assign_target_roles(old, fraction=0.5) + tool.county_surface.assign_target_roles(new, fraction=0.5) + + n_households = 17 + matrix = _matrix(len(old), n_households, seed) + rng = np.random.default_rng(seed + 3_000) + design = rng.uniform(0.5, 2.0, size=n_households) + final = rng.uniform(0.1, 4.0, size=n_households).astype(np.float32) + + old_set = reference.calibration_target_set(old, matrix, n_households) + new_set = tool.cd_surface.calibration_target_set(new, matrix, n_households) + assert [ + (target.name, target.value, target.period, target.source) + for target in new_set.targets + ] == [ + (target.name, target.value, target.period, target.source) + for target in old_set.targets + ] + for old_target, new_target in zip(old_set.targets, new_set.targets, strict=True): + assert np.array_equal(new_target.measure(None), old_target.measure(None)) + assert new_target.measure.__qualname__ == old_target.measure.__qualname__ + + specs = [ + TargetSpec( + name=record["name"], + entity="household", + measure=record["name"], + value=record["value"], + period=2024, + source="ledger_feed", + family=record["family"], + metadata={"geography_level": record["geography_level"]}, + signed=record["value"] < 0, + ) + for record in old + ] + old_specs = reference.calibration_target_set(old, matrix, n_households, specs=specs) + new_specs = tool.cd_surface.calibration_target_set( + new, matrix, n_households, specs=specs + ) + assert [target.name for target in new_specs.targets] == [ + target.name for target in old_specs.targets + ] + assert [dict(target.metadata) for target in new_specs.targets] == [ + dict(target.metadata) for target in old_specs.targets + ] + + common = {"design_weights": design, "final_weights": final, "cap": 10.0} + old_cd = reference.score_cd_holdout(old, matrix, receipt=old_receipt, **common) + new_cd = tool.cd_surface.score_cd_holdout( + new, matrix, receipt=new_receipt, **common + ) + assert _dumps(new_cd) == _dumps(old_cd) + old_score = reference.score_county_holdout( + old, matrix, receipt=old_county, **common + ) + new_score = tool.county_surface.score_county_holdout( + new, matrix, receipt=old_county, **common + ) + assert _dumps(new_score) == _dumps(old_score) + + +def test_scores_with_no_held_rows_match(tool) -> None: + old, new = _records(3), _records(3) + reference.cd_assign_target_roles(old, fraction=0.0) + tool.cd_surface.assign_target_roles(new, fraction=0.0) + matrix = _matrix(len(old), 5, 3) + common = { + "design_weights": np.ones(5), + "final_weights": np.ones(5), + "cap": 10.0, + "receipt": {"unit": "x", "fraction": 0.0}, + } + assert _dumps(tool.cd_surface.score_cd_holdout(new, matrix, **common)) == _dumps( + reference.score_cd_holdout(old, matrix, **common) + ) + assert _dumps( + tool.county_surface.score_county_holdout(new, matrix, **common) + ) == _dumps(reference.score_county_holdout(old, matrix, **common)) + + +def test_every_declared_pass_has_scoring() -> None: + assert [holdout_pass.pass_id for holdout_pass in us_target_holdouts().passes] == [ + DISTRICT_HOLDOUT, + COUNTY_HOLDOUT, + ] + assert all(holdout_pass.scoring for holdout_pass in us_target_holdouts().passes) diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py index 58c8cc4e88..1335df1ab9 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py @@ -373,7 +373,7 @@ def capture_equality(expected: object, actual: object) -> None: # microcosm#1686's shared SIPP person-file read moves it again. # The SIPP 2023 donor download tag and the financial-asset cache lookup # move it again. - "spec_sha256": "f130419c1b9d07fb452bc28ca80ff8de07562667e4e2940f0f02f75d550792d6", + "spec_sha256": "c25fbed9c0d92248707f59101b516125f8437c42e2cebe84a72e28f6ac0f39c0", }, } diff --git a/test_support/microcosm_build/us_target_holdouts_reference.py b/test_support/microcosm_build/us_target_holdouts_reference.py new file mode 100644 index 0000000000..aac11666cb --- /dev/null +++ b/test_support/microcosm_build/us_target_holdouts_reference.py @@ -0,0 +1,471 @@ +"""Verbatim copies of the US local hold-out code before microcosm#1728 moved it. + +``tools/us_acs_local_cd_surface.py``, ``tools/us_acs_local_county_surface.py`` +and ``tools/build_us_acs_local_release.py`` held this code at ``f4dee4c70``. It +now lives in the shared ``microcosm.build.target_holdouts``, with the US +choices in ``us/local_target_construction.json``. The equivalence tests hold +the shared code to these copies. Only names changed: the district and county +versions of ``assign_target_roles`` and ``pro_rata_baseline`` carry a ``cd_`` +or ``county_`` prefix, and ``cd_surface.`` is dropped from the county code. +""" + +# ruff: noqa + +from __future__ import annotations + +import math +from collections import defaultdict +from collections.abc import Mapping, Sequence + +import numpy as np +from scipy import sparse + +CD_HOLDOUT_SALT = "microcosm.us_acs_local.cd_holdout.v1" + +CD_HOLDOUT_UNIT = "state_x_soi_concept_family" + +DEFAULT_STATE_CD_HOLDOUT_FRACTION = 0.1 + +MAX_CD_HOLDOUT_FRACTION = 0.5 + +ROLE_TRAIN = "train" + +ROLE_HOLDOUT = "holdout" + +GEOGRAPHY_CD = "congressional_district" + +def soi_concept_family(source_measure_id: str) -> str: + """The holdout family of an SOI measure: its concept without count/amount. + + Every EITC measure is one family, because the per-child-count rows add up + to the EITC total and holding one out would leave it pinned by the rest. + """ + + measure = str(source_measure_id) + if measure.startswith("eitc"): + return "eitc" + for suffix in ("_amount", "_returns", "_claims", "_count"): + if measure.endswith(suffix): + return measure[: -len(suffix)] + return measure + +def cd_holdout_unit_key(record: Mapping) -> str | None: + """The holdout unit of a district SOI target, or None if not eligible.""" + + if record.get("family") != "irs_soi": + return None + if record.get("geography_level") != GEOGRAPHY_CD: + return None + if not record.get("state_cd_parent_target_name"): + return None + return ( + f"{record['state_fips']}|" + f"{soi_concept_family(str(record.get('source_measure_id')))}" + ) + +def cd_assign_target_roles( + records: Sequence[dict], + *, + fraction: float, + salt: str = CD_HOLDOUT_SALT, +) -> dict: + """Set ``role`` and ``holdout_unit`` on every record; return the receipt. + + Only district SOI targets with a bound state parent are eligible; every + other target trains. A unit is held out by + :func:`microcosm.build.holdout.hash_holdout_unit` on its key. + """ + + from microcosm.build.holdout import hash_holdout_unit + + if not 0.0 <= float(fraction) <= MAX_CD_HOLDOUT_FRACTION: + raise ValueError( + f"CD holdout fraction must be in [0, {MAX_CD_HOLDOUT_FRACTION}], " + f"got {fraction!r}." + ) + units: dict[str, bool] = {} + for record in records: + unit = cd_holdout_unit_key(record) + record["holdout_unit"] = unit + if unit is None: + record["role"] = ROLE_TRAIN + continue + if unit not in units: + units[unit] = hash_holdout_unit(unit, fraction=fraction, salt=salt) + record["role"] = ROLE_HOLDOUT if units[unit] else ROLE_TRAIN + held_units = sorted(unit for unit, held in units.items() if held) + return { + "unit": CD_HOLDOUT_UNIT, + "salt": salt, + "fraction": float(fraction), + "eligible_units": len(units), + "held_units": len(held_units), + "held_unit_keys": held_units, + "eligible_targets": sum( + 1 for record in records if record["holdout_unit"] is not None + ), + "held_targets": sum(1 for record in records if record["role"] == ROLE_HOLDOUT), + "hash": "sha256(salt + 0x1f + unit)[:8] / 2**64 < fraction", + } + +def train_rows(records: Sequence[Mapping]) -> list[int]: + return [ + index for index, record in enumerate(records) if record["role"] == ROLE_TRAIN + ] + +def holdout_rows(records: Sequence[Mapping]) -> list[int]: + return [ + index for index, record in enumerate(records) if record["role"] == ROLE_HOLDOUT + ] + +def csr_row_measure(matrix: sparse.csr_array, row: int, n: int): + """A callable measure returning one CSR row as a dense float64 vector. + + The calibrate kernel compiles targets through ``build_constraint_matrix``, + which reads each target's row and keeps its nonzeros; a callable measure + lets it read the row straight from the checkpoint CSR (the UK rowwise + precedent, ``uk_runtime.local_rowwise._rowwise_target_set``). Only one + dense row exists at a time. float32 values widen exactly to float64, as + the dense checkpoint's float32 columns did. + """ + + start, stop = int(matrix.indptr[row]), int(matrix.indptr[row + 1]) + indices = matrix.indices[start:stop] + data = matrix.data[start:stop] + + def measure(frame) -> np.ndarray: + values = np.zeros(n, dtype=np.float64) + values[indices] = data + return values + + # Calibration diagnostics name a callable measure by its qualified name; + # name the matrix row rather than this closure. + measure.__qualname__ = f"target_matrix_row[{row}]" + return measure + +def calibration_target_set( + records: Sequence[Mapping], + matrix: sparse.csr_array, + n_households: int, + *, + specs: Sequence | None = None, +): + """The TargetSet the calibrator sees: training targets only. + + Held-out targets are never constructed, so they cannot reach the solve. + With ``specs`` (the checkpoint's registry specs, row-aligned with + ``records``) each target keeps its spec's value, period, source, + metadata and calibration hierarchy, as ``TargetSpec.to_target`` would, + and only its measure becomes the CSR row. + """ + + from microcosm.calibrate.target import Target, TargetSet + + if matrix.shape != (len(records), n_households): + raise ValueError( + f"target matrix shape {matrix.shape} does not match " + f"{len(records)} targets x {n_households} households." + ) + if specs is not None and [spec.name for spec in specs] != [ + record["name"] for record in records + ]: + raise ValueError("target specs are not row-aligned with the roles.") + targets = [] + for index in train_rows(records): + record = records[index] + if record["role"] != ROLE_TRAIN: # pragma: no cover - train_rows filters + raise AssertionError("a held-out target reached the calibration set") + measure = csr_row_measure(matrix, index, n_households) + if specs is None: + targets.append( + Target( + name=record["name"], + entity=record.get("entity", "household"), + measure=measure, + value=float(record["value"]), + period=record["period"], + source=record["source"], + ) + ) + continue + spec = specs[index] + if spec.filter is not None: + raise ValueError( + f"{spec.name}: a filtered spec cannot take a matrix-row measure; " + "the row already carries the filter." + ) + targets.append( + Target( + name=spec.name, + entity=spec.entity, + measure=measure, + value=spec.value, + period=spec.period, + tolerance=spec.tolerance, + source=spec.source, + metadata=spec.metadata, + hierarchy=spec.hierarchy, + ) + ) + held = {records[index]["name"] for index in holdout_rows(records)} + leaked = held & {target.name for target in targets} + if leaked: + raise AssertionError(f"held-out targets reached the calibrator: {leaked}") + return TargetSet(targets) + +def _error_summary(estimates, targets, *, cap: float) -> dict: + from microcosm.calibrate import relative_error_loss + + estimates = np.asarray(estimates, dtype=np.float64) + targets = np.asarray(targets, dtype=np.float64) + scale = np.maximum(np.abs(targets), 1.0) + errors = np.abs(estimates - targets) / scale + return { + "mean_abs_rel_error": float(errors.mean()), + "median_abs_rel_error": float(np.median(errors)), + "p90_abs_rel_error": float(np.quantile(errors, 0.9)), + "max_abs_rel_error": float(errors.max()), + "fraction_within_10pct": float((errors <= 0.10).mean()), + "capped_loss": float( + relative_error_loss(estimates, targets, target_loss_cap=cap) + ), + } + +def cd_pro_rata_baseline(records: Sequence[Mapping], rows: Sequence[int]) -> np.ndarray: + """State parent value x district population share, for each row.""" + + by_name = {record["name"]: record for record in records} + values = [] + for index in rows: + record = records[index] + parent = by_name.get(record.get("state_cd_parent_target_name")) + if parent is None: + raise ValueError( + f"{record['name']} has no bound state parent for the baseline." + ) + cd_population = record.get("cd_population") + state_population = record.get("state_population") + if not cd_population or not state_population: + raise ValueError( + f"{record['name']} carries no district/state population for " + "the pro-rata baseline." + ) + values.append( + float(parent["value"]) * float(cd_population) / float(state_population) + ) + return np.asarray(values, dtype=np.float64) + +def score_cd_holdout( + records: Sequence[Mapping], + matrix: sparse.csr_array, + *, + design_weights: np.ndarray, + final_weights: np.ndarray, + cap: float, + receipt: Mapping | None = None, +) -> dict: + """Held-out district targets: calibrated vs design vs pro-rata baseline.""" + + rows = [ + row for row in holdout_rows(records) + if records[row].get("geography_level") == GEOGRAPHY_CD + ] + base = {"report_only": True, **dict(receipt or {})} + if not rows: + return {**base, "n_targets": 0} + held = sparse.csr_array(matrix[rows]).astype(np.float64) + targets = np.asarray([records[i]["value"] for i in rows], dtype=np.float64) + final = held @ np.asarray(final_weights, dtype=np.float64) + design = held @ np.asarray(design_weights, dtype=np.float64) + baseline = cd_pro_rata_baseline(records, rows) + scale = np.maximum(np.abs(targets), 1.0) + final_error = np.abs(final - targets) / scale + baseline_error = np.abs(baseline - targets) / scale + families: dict[str, list[int]] = defaultdict(list) + for position, index in enumerate(rows): + families[str(records[index]["holdout_unit"]).split("|", 1)[1]].append(position) + by_family = {} + for family, positions in sorted(families.items()): + idx = np.asarray(positions) + by_family[family] = { + "n_targets": len(positions), + "calibrated_mean_abs_rel_error": float(final_error[idx].mean()), + "pro_rata_mean_abs_rel_error": float(baseline_error[idx].mean()), + "calibrated_beats_pro_rata": float( + (final_error[idx] < baseline_error[idx]).mean() + ), + } + return { + **base, + "n_targets": len(rows), + "calibrated": _error_summary(final, targets, cap=cap), + "design_weights": _error_summary(design, targets, cap=cap), + "pro_rata_baseline": _error_summary(baseline, targets, cap=cap), + "calibrated_beats_pro_rata_share": float((final_error < baseline_error).mean()), + "baseline": ( + "state parent target x (district population / state population), " + "populations from the PUMA ladder's 119th-plan district overlap" + ), + "by_family": by_family, + "targets": [ + { + "name": records[index]["name"], + "unit": records[index]["holdout_unit"], + "target": float(targets[position]), + "calibrated": float(final[position]), + "design": float(design[position]), + "pro_rata": float(baseline[position]), + } + for position, index in enumerate(rows) + ], + } + +COUNTY_HOLDOUT_SALT = "acs-local-county-v1" + +DEFAULT_COUNTY_HOLDOUT_FRACTION = 0.1 + +def county_assign_target_roles( + records, *, fraction=DEFAULT_COUNTY_HOLDOUT_FRACTION, salt=COUNTY_HOLDOUT_SALT +): + """Hold out whole state/concept-family blocks to prevent sibling leakage.""" + from microcosm.build.holdout import hash_holdout_unit + + if not isinstance(salt, str) or not salt: + raise ValueError("County holdout salt must be a non-empty string.") + if not 0 <= fraction <= MAX_CD_HOLDOUT_FRACTION: + raise ValueError( + f"County holdout fraction must be in [0, {MAX_CD_HOLDOUT_FRACTION}]." + ) + units = {} + eligible = [] + for record in records: + if record.get("geography_level") != "county": + continue + unit = None + if record.get("state_county_parent_target_name"): + family = ( + soi_concept_family(str(record.get("source_measure_id"))) + if record.get("family") == "irs_soi" + else str(record.get("family")) + ) + unit = f"{record['state_fips']}|{family}" + record["holdout_unit"] = unit + record["role"] = ROLE_TRAIN + if unit is not None: + eligible.append(record) + units.setdefault( + unit, hash_holdout_unit(unit, fraction=fraction, salt=salt) + ) + if units[unit]: + record["role"] = ROLE_HOLDOUT + return { + "unit": "state x county concept family", + "salt": salt, + "fraction": float(fraction), + "eligible_units": len(units), + "eligible_targets": len(eligible), + "held_units": sum(units.values()), + "held_unit_keys": sorted(key for key, value in units.items() if value), + "held_targets": sum( + record["role"] == ROLE_HOLDOUT for record in eligible + ), + } + +def county_pro_rata_baseline(records, rows): + by_name = {record["name"]: record for record in records} + values = [] + for index in rows: + record = records[index] + parent = by_name.get(record.get("state_county_parent_target_name")) + county, state = ( + float(record.get("county_population", 0)), + float(record.get("state_population", 0)), + ) + if parent is None or not ( + math.isfinite(county) and math.isfinite(state) and county > 0 and state > 0 + ): + raise ValueError( + f"{record['name']} has no state parent or positive county/state population for pro-rata baseline." + ) + values.append(float(parent["value"]) * county / state) + return np.asarray(values, dtype=float) + +def score_county_holdout( + records, matrix, *, design_weights, final_weights, cap, receipt=None +): + rows = [ + index + for index, record in enumerate(records) + if record.get("geography_level") == "county" + and record.get("role") == ROLE_HOLDOUT + ] + base = {"report_only": True, **dict(receipt or {}), "n_targets": len(rows)} + if not rows: + return base + held = sparse.csr_array(matrix[rows]).astype(float) + targets = np.asarray([records[index]["value"] for index in rows], float) + final, design = held @ np.asarray(final_weights), held @ np.asarray(design_weights) + baseline = county_pro_rata_baseline(records, rows) + scale = np.maximum(np.abs(targets), 1.0) + return { + **base, + "calibrated": _error_summary(final, targets, cap=cap), + "design_weights": _error_summary(design, targets, cap=cap), + "pro_rata_baseline": _error_summary(baseline, targets, cap=cap), + "calibrated_beats_pro_rata_share": float( + ( + np.abs(final - targets) / scale < np.abs(baseline - targets) / scale + ).mean() + ), + "baseline": "state parent target x county population / state population", + "targets": [ + { + "name": records[index]["name"], + "county_fips": records[index]["county_fips"], + "target": float(targets[position]), + "calibrated": float(final[position]), + "design": float(design[position]), + "pro_rata": float(baseline[position]), + } + for position, index in enumerate(rows) + ], + } + +def _attach_pro_rata_populations(targets: list[dict], cd_populations: dict) -> None: + """Give each district SOI target its district and state populations. + + The pro-rata baseline allocates the state parent by these; both come + from the PUMA ladder's 119th-plan district overlap populations, so a + state's district shares sum to one. + """ + + state_population: dict[int, float] = {} + for district, population in cd_populations.items(): + state = int(district) // 100 + state_population[state] = state_population.get(state, 0.0) + float(population) + for target in targets: + geoid = target.get("congressional_district_geoid") + if target.get("family") != "irs_soi" or not geoid: + continue + district = int(geoid) + target["cd_population"] = float(cd_populations.get(district, 0.0)) + target["state_population"] = float(state_population.get(district // 100, 0.0)) + +def _require_pro_rata_populations(targets: list[dict]) -> None: + """Refuse, before any solve, a district row the baseline cannot score.""" + + unpopulated = [ + target["name"] + for target in targets + if target.get("family") == "irs_soi" + and target.get("congressional_district_geoid") + and not ( + target.get("cd_population", 0) > 0 and target.get("state_population", 0) > 0 + ) + ] + if unpopulated: + raise SystemExit( + f"{len(unpopulated)} district SOI target(s) have no positive " + "ladder district or state population for the pro-rata " + f"baseline (e.g. {unpopulated[:3]}); refusing before the solve." + ) diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index bdcd696606..e526051a19 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -2217,34 +2217,34 @@ def _attach_pro_rata_populations(targets: list[dict], cd_populations: dict) -> N The pro-rata baseline allocates the state parent by these; both come from the PUMA ladder's 119th-plan district overlap populations, so a - state's district shares sum to one. + state's district shares sum to one. The shared + :func:`microcosm.build.target_holdouts.attach_population_shares` reads the + district hold-out's declared fields (microcosm#1728). """ - state_population: dict[int, float] = {} - for district, population in cd_populations.items(): - state = int(district) // 100 - state_population[state] = state_population.get(state, 0.0) + float(population) - for target in targets: - geoid = target.get("congressional_district_geoid") - if target.get("family") != "irs_soi" or not geoid: - continue - district = int(geoid) - target["cd_population"] = float(cd_populations.get(district, 0.0)) - target["state_population"] = float(state_population.get(district // 100, 0.0)) + from microcosm.build.target_holdouts import attach_population_shares + from microcosm.build.us_runtime.local_target_construction import ( + DISTRICT_HOLDOUT, + us_holdout_scoring, + ) + + attach_population_shares( + targets, cd_populations, us_holdout_scoring(DISTRICT_HOLDOUT) + ) def _require_pro_rata_populations(targets: list[dict]) -> None: """Refuse, before any solve, a district row the baseline cannot score.""" - unpopulated = [ - target["name"] - for target in targets - if target.get("family") == "irs_soi" - and target.get("congressional_district_geoid") - and not ( - target.get("cd_population", 0) > 0 and target.get("state_population", 0) > 0 - ) - ] + from microcosm.build.target_holdouts import missing_population_shares + from microcosm.build.us_runtime.local_target_construction import ( + DISTRICT_HOLDOUT, + us_holdout_scoring, + ) + + unpopulated = missing_population_shares( + targets, us_holdout_scoring(DISTRICT_HOLDOUT) + ) if unpopulated: raise SystemExit( f"{len(unpopulated)} district SOI target(s) have no positive " diff --git a/tools/generate_us_bundle_from_constants.py b/tools/generate_us_bundle_from_constants.py index 15237ef9e2..c981a3fb9b 100644 --- a/tools/generate_us_bundle_from_constants.py +++ b/tools/generate_us_bundle_from_constants.py @@ -148,6 +148,8 @@ def _domain_builders() -> dict[str, Callable[[], object]]: "federal_eitc_by_state.json", "fiscal_target_references.json", "gates.json", + # The ACS local release's declared target construction (microcosm#1728). + "local_target_construction.json", "obbba_reforms.json", "puf_aggregate_record_disaggregation.json", "release_input_coverage_manifest.json", diff --git a/tools/spec_engine_coverage.py b/tools/spec_engine_coverage.py index 8d5af2fa27..b7f268cfb0 100644 --- a/tools/spec_engine_coverage.py +++ b/tools/spec_engine_coverage.py @@ -41,7 +41,7 @@ REPORT_SCHEMA_VERSION = 3 EXPECTED_POINTER_INVENTORY_SHA256 = ( - "b7565bf43ff7139460a8345d3858a6950c4fdcf4cb61afe6b056550040b1c710" + "bbf2213acf3453f09be80542c9b86f5571b6659ce196c1979be9961f0c0a6f66" ) DEFAULT_REPORT_PATH = ( Path(__file__).resolve().parents[1] diff --git a/tools/us_acs_local_cd_surface.py b/tools/us_acs_local_cd_surface.py index c7226b5193..81813d4861 100644 --- a/tools/us_acs_local_cd_surface.py +++ b/tools/us_acs_local_cd_surface.py @@ -40,6 +40,17 @@ import pandas as pd from scipy import sparse +from microcosm.build import target_holdouts + +# The shared role names; the county module and tests read them from here. +from microcosm.build.target_holdouts import ROLE_HOLDOUT, ROLE_TRAIN # noqa: F401 +from microcosm.build.us_runtime.local_target_construction import ( + DISTRICT_HOLDOUT, + us_holdout_pass, + us_holdout_scoring, + us_target_holdouts, +) + # --------------------------------------------------------------------------- # Surface constants # --------------------------------------------------------------------------- @@ -138,18 +149,18 @@ # Holdout constants # --------------------------------------------------------------------------- -#: Salt of the CD holdout hash. Changing it re-draws every held unit. -CD_HOLDOUT_SALT = "microcosm.us_acs_local.cd_holdout.v1" -#: The held unit: every district target of one SOI concept family in one -#: state. A single district (or a single district target) is not a fair -#: holdout: with its state total and sibling districts trained it is pinned -#: by adding up. Concept families also group measures that add up to each -#: other (EITC by number of children sums to the EITC total). -CD_HOLDOUT_UNIT = "state_x_soi_concept_family" -DEFAULT_STATE_CD_HOLDOUT_FRACTION = 0.1 -MAX_CD_HOLDOUT_FRACTION = 0.5 -ROLE_TRAIN = "train" -ROLE_HOLDOUT = "holdout" +#: The district hold-out pass, declared in ``us/local_target_construction.json`` +#: (``holdouts``, microcosm#1728) and run by the shared +#: :mod:`microcosm.build.target_holdouts`. The held unit is every district +#: target of one SOI concept family in one state: a single district target is +#: not a fair holdout, because its state total and trained siblings pin it by +#: adding up. Changing the salt re-draws every held unit. ``ROLE_TRAIN`` and +#: ``ROLE_HOLDOUT`` are the shared role names. +_DISTRICT_HOLDOUT = us_holdout_pass(DISTRICT_HOLDOUT) +CD_HOLDOUT_SALT = _DISTRICT_HOLDOUT.salt +CD_HOLDOUT_UNIT = _DISTRICT_HOLDOUT.unit +DEFAULT_STATE_CD_HOLDOUT_FRACTION = _DISTRICT_HOLDOUT.default_fraction +MAX_CD_HOLDOUT_FRACTION = _DISTRICT_HOLDOUT.max_fraction # --------------------------------------------------------------------------- # Sampling constants: the rung tokens of tools/build_us_multispine_pool.py @@ -255,15 +266,11 @@ def soi_concept_family(source_measure_id: str) -> str: Every EITC measure is one family, because the per-child-count rows add up to the EITC total and holding one out would leave it pinned by the rest. + The rule is declared in ``us/local_target_construction.json`` + (``holdouts.concept_families``, microcosm#1728). """ - measure = str(source_measure_id) - if measure.startswith("eitc"): - return "eitc" - for suffix in ("_amount", "_returns", "_claims", "_count"): - if measure.endswith(suffix): - return measure[: -len(suffix)] - return measure + return us_target_holdouts().concept_families.of_measure(source_measure_id) # --------------------------------------------------------------------------- @@ -1223,30 +1230,7 @@ def load_target_matrix(path: Path) -> sparse.csr_array: return matrix -def csr_row_measure(matrix: sparse.csr_array, row: int, n: int): - """A callable measure returning one CSR row as a dense float64 vector. - - The calibrate kernel compiles targets through ``build_constraint_matrix``, - which reads each target's row and keeps its nonzeros; a callable measure - lets it read the row straight from the checkpoint CSR (the UK rowwise - precedent, ``uk_runtime.local_rowwise._rowwise_target_set``). Only one - dense row exists at a time. float32 values widen exactly to float64, as - the dense checkpoint's float32 columns did. - """ - - start, stop = int(matrix.indptr[row]), int(matrix.indptr[row + 1]) - indices = matrix.indices[start:stop] - data = matrix.data[start:stop] - - def measure(frame) -> np.ndarray: - values = np.zeros(n, dtype=np.float64) - values[indices] = data - return values - - # Calibration diagnostics name a callable measure by its qualified name; - # name the matrix row rather than this closure. - measure.__qualname__ = f"target_matrix_row[{row}]" - return measure +csr_row_measure = target_holdouts.csr_row_measure # --------------------------------------------------------------------------- @@ -1288,16 +1272,7 @@ def target_record(spec) -> dict: def cd_holdout_unit_key(record: Mapping) -> str | None: """The holdout unit of a district SOI target, or None if not eligible.""" - if record.get("family") != "irs_soi": - return None - if record.get("geography_level") != GEOGRAPHY_CD: - return None - if not record.get("state_cd_parent_target_name"): - return None - return ( - f"{record['state_fips']}|" - f"{soi_concept_family(str(record.get('source_measure_id')))}" - ) + return _DISTRICT_HOLDOUT.unit_key(record, us_target_holdouts().concept_families) def assign_target_roles( @@ -1310,123 +1285,29 @@ def assign_target_roles( Only district SOI targets with a bound state parent are eligible; every other target trains. A unit is held out by - :func:`microcosm.build.holdout.hash_holdout_unit` on its key. + :func:`microcosm.build.holdout.hash_holdout_unit` on its key. The shared + :func:`microcosm.build.target_holdouts.assign_holdout_roles` runs the + declared district pass (microcosm#1728). """ - from microcosm.build.holdout import hash_holdout_unit - - if not 0.0 <= float(fraction) <= MAX_CD_HOLDOUT_FRACTION: - raise ValueError( - f"CD holdout fraction must be in [0, {MAX_CD_HOLDOUT_FRACTION}], " - f"got {fraction!r}." - ) - units: dict[str, bool] = {} - for record in records: - unit = cd_holdout_unit_key(record) - record["holdout_unit"] = unit - if unit is None: - record["role"] = ROLE_TRAIN - continue - if unit not in units: - units[unit] = hash_holdout_unit(unit, fraction=fraction, salt=salt) - record["role"] = ROLE_HOLDOUT if units[unit] else ROLE_TRAIN - held_units = sorted(unit for unit, held in units.items() if held) - return { - "unit": CD_HOLDOUT_UNIT, - "salt": salt, - "fraction": float(fraction), - "eligible_units": len(units), - "held_units": len(held_units), - "held_unit_keys": held_units, - "eligible_targets": sum( - 1 for record in records if record["holdout_unit"] is not None - ), - "held_targets": sum(1 for record in records if record["role"] == ROLE_HOLDOUT), - "hash": "sha256(salt + 0x1f + unit)[:8] / 2**64 < fraction", - } + return target_holdouts.assign_holdout_roles( + records, + _DISTRICT_HOLDOUT, + us_target_holdouts().concept_families, + fraction=fraction, + salt=salt, + ) -def train_rows(records: Sequence[Mapping]) -> list[int]: - return [ - index for index, record in enumerate(records) if record["role"] == ROLE_TRAIN - ] +#: The training and the held-out rows, the CSR-row measure and the training +#: target set are shared code (microcosm.build.target_holdouts, microcosm#1728). +train_rows = target_holdouts.train_rows -def holdout_rows(records: Sequence[Mapping]) -> list[int]: - return [ - index for index, record in enumerate(records) if record["role"] == ROLE_HOLDOUT - ] +holdout_rows = target_holdouts.holdout_rows -def calibration_target_set( - records: Sequence[Mapping], - matrix: sparse.csr_array, - n_households: int, - *, - specs: Sequence | None = None, -): - """The TargetSet the calibrator sees: training targets only. - - Held-out targets are never constructed, so they cannot reach the solve. - With ``specs`` (the checkpoint's registry specs, row-aligned with - ``records``) each target keeps its spec's value, period, source, - metadata and calibration hierarchy, as ``TargetSpec.to_target`` would, - and only its measure becomes the CSR row. - """ - - from microcosm.calibrate.target import Target, TargetSet - - if matrix.shape != (len(records), n_households): - raise ValueError( - f"target matrix shape {matrix.shape} does not match " - f"{len(records)} targets x {n_households} households." - ) - if specs is not None and [spec.name for spec in specs] != [ - record["name"] for record in records - ]: - raise ValueError("target specs are not row-aligned with the roles.") - targets = [] - for index in train_rows(records): - record = records[index] - if record["role"] != ROLE_TRAIN: # pragma: no cover - train_rows filters - raise AssertionError("a held-out target reached the calibration set") - measure = csr_row_measure(matrix, index, n_households) - if specs is None: - targets.append( - Target( - name=record["name"], - entity=record.get("entity", "household"), - measure=measure, - value=float(record["value"]), - period=record["period"], - source=record["source"], - ) - ) - continue - spec = specs[index] - if spec.filter is not None: - raise ValueError( - f"{spec.name}: a filtered spec cannot take a matrix-row measure; " - "the row already carries the filter." - ) - targets.append( - Target( - name=spec.name, - entity=spec.entity, - measure=measure, - value=spec.value, - period=spec.period, - tolerance=spec.tolerance, - source=spec.source, - metadata=spec.metadata, - hierarchy=spec.hierarchy, - ) - ) - held = {records[index]["name"] for index in holdout_rows(records)} - leaked = held & {target.name for target in targets} - if leaked: - raise AssertionError(f"held-out targets reached the calibrator: {leaked}") - return TargetSet(targets) +calibration_target_set = target_holdouts.training_target_set # --------------------------------------------------------------------------- @@ -1434,48 +1315,15 @@ def calibration_target_set( # --------------------------------------------------------------------------- -def _error_summary(estimates, targets, *, cap: float) -> dict: - from microcosm.calibrate import relative_error_loss - - estimates = np.asarray(estimates, dtype=np.float64) - targets = np.asarray(targets, dtype=np.float64) - scale = np.maximum(np.abs(targets), 1.0) - errors = np.abs(estimates - targets) / scale - return { - "mean_abs_rel_error": float(errors.mean()), - "median_abs_rel_error": float(np.median(errors)), - "p90_abs_rel_error": float(np.quantile(errors, 0.9)), - "max_abs_rel_error": float(errors.max()), - "fraction_within_10pct": float((errors <= 0.10).mean()), - "capped_loss": float( - relative_error_loss(estimates, targets, target_loss_cap=cap) - ), - } +_error_summary = target_holdouts.error_summary def pro_rata_baseline(records: Sequence[Mapping], rows: Sequence[int]) -> np.ndarray: """State parent value x district population share, for each row.""" - by_name = {record["name"]: record for record in records} - values = [] - for index in rows: - record = records[index] - parent = by_name.get(record.get("state_cd_parent_target_name")) - if parent is None: - raise ValueError( - f"{record['name']} has no bound state parent for the baseline." - ) - cd_population = record.get("cd_population") - state_population = record.get("state_population") - if not cd_population or not state_population: - raise ValueError( - f"{record['name']} carries no district/state population for " - "the pro-rata baseline." - ) - values.append( - float(parent["value"]) * float(cd_population) / float(state_population) - ) - return np.asarray(values, dtype=np.float64) + return target_holdouts.pro_rata_baseline( + records, rows, us_holdout_scoring(DISTRICT_HOLDOUT) + ) def score_cd_holdout( @@ -1489,59 +1337,15 @@ def score_cd_holdout( ) -> dict: """Held-out district targets: calibrated vs design vs pro-rata baseline.""" - rows = [ - row for row in holdout_rows(records) - if records[row].get("geography_level") == GEOGRAPHY_CD - ] - base = {"report_only": True, **dict(receipt or {})} - if not rows: - return {**base, "n_targets": 0} - held = sparse.csr_array(matrix[rows]).astype(np.float64) - targets = np.asarray([records[i]["value"] for i in rows], dtype=np.float64) - final = held @ np.asarray(final_weights, dtype=np.float64) - design = held @ np.asarray(design_weights, dtype=np.float64) - baseline = pro_rata_baseline(records, rows) - scale = np.maximum(np.abs(targets), 1.0) - final_error = np.abs(final - targets) / scale - baseline_error = np.abs(baseline - targets) / scale - families: dict[str, list[int]] = defaultdict(list) - for position, index in enumerate(rows): - families[str(records[index]["holdout_unit"]).split("|", 1)[1]].append(position) - by_family = {} - for family, positions in sorted(families.items()): - idx = np.asarray(positions) - by_family[family] = { - "n_targets": len(positions), - "calibrated_mean_abs_rel_error": float(final_error[idx].mean()), - "pro_rata_mean_abs_rel_error": float(baseline_error[idx].mean()), - "calibrated_beats_pro_rata": float( - (final_error[idx] < baseline_error[idx]).mean() - ), - } - return { - **base, - "n_targets": len(rows), - "calibrated": _error_summary(final, targets, cap=cap), - "design_weights": _error_summary(design, targets, cap=cap), - "pro_rata_baseline": _error_summary(baseline, targets, cap=cap), - "calibrated_beats_pro_rata_share": float((final_error < baseline_error).mean()), - "baseline": ( - "state parent target x (district population / state population), " - "populations from the PUMA ladder's 119th-plan district overlap" - ), - "by_family": by_family, - "targets": [ - { - "name": records[index]["name"], - "unit": records[index]["holdout_unit"], - "target": float(targets[position]), - "calibrated": float(final[position]), - "design": float(design[position]), - "pro_rata": float(baseline[position]), - } - for position, index in enumerate(rows) - ], - } + return target_holdouts.score_holdout( + records, + matrix, + us_holdout_scoring(DISTRICT_HOLDOUT), + design_weights=design_weights, + final_weights=final_weights, + cap=cap, + receipt=receipt, + ) # --------------------------------------------------------------------------- diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index 3458ef90af..c393380281 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -26,9 +26,21 @@ import us_acs_local_cd_surface as cd_surface from scipy import sparse +from microcosm.build import target_holdouts +from microcosm.build.us_runtime.local_target_construction import ( + COUNTY_HOLDOUT, + us_holdout_pass, + us_holdout_scoring, + us_target_holdouts, +) + COUNTY_COLUMN = "county_fips" -COUNTY_HOLDOUT_SALT = "acs-local-county-v1" -DEFAULT_COUNTY_HOLDOUT_FRACTION = 0.1 +#: The county hold-out pass, declared in ``us/local_target_construction.json`` +#: (``holdouts``, microcosm#1728) and run by the shared +#: :mod:`microcosm.build.target_holdouts`. +_COUNTY_HOLDOUT = us_holdout_pass(COUNTY_HOLDOUT) +COUNTY_HOLDOUT_SALT = _COUNTY_HOLDOUT.salt +DEFAULT_COUNTY_HOLDOUT_FRACTION = _COUNTY_HOLDOUT.default_fraction RELIABILITY_FILENAME = "county_reliability.json" RELIABILITY_CSV_FILENAME = "county_reliability.csv" SUPPORT_FILENAME = "county_support.json" @@ -1595,111 +1607,39 @@ def target_record(spec): def assign_target_roles( records, *, fraction=DEFAULT_COUNTY_HOLDOUT_FRACTION, salt=COUNTY_HOLDOUT_SALT ): - """Hold out whole state/concept-family blocks to prevent sibling leakage.""" - from microcosm.build.holdout import hash_holdout_unit + """Hold out whole state/concept-family blocks to prevent sibling leakage. - if not isinstance(salt, str) or not salt: - raise ValueError("County holdout salt must be a non-empty string.") - if not 0 <= fraction <= cd_surface.MAX_CD_HOLDOUT_FRACTION: - raise ValueError( - f"County holdout fraction must be in [0, {cd_surface.MAX_CD_HOLDOUT_FRACTION}]." - ) - units = {} - eligible = [] - for record in records: - if record.get("geography_level") != "county": - continue - unit = None - if record.get("state_county_parent_target_name"): - family = ( - cd_surface.soi_concept_family(str(record.get("source_measure_id"))) - if record.get("family") == "irs_soi" - else str(record.get("family")) - ) - unit = f"{record['state_fips']}|{family}" - record["holdout_unit"] = unit - record["role"] = cd_surface.ROLE_TRAIN - if unit is not None: - eligible.append(record) - units.setdefault( - unit, hash_holdout_unit(unit, fraction=fraction, salt=salt) - ) - if units[unit]: - record["role"] = cd_surface.ROLE_HOLDOUT - return { - "unit": "state x county concept family", - "salt": salt, - "fraction": float(fraction), - "eligible_units": len(units), - "eligible_targets": len(eligible), - "held_units": sum(units.values()), - "held_unit_keys": sorted(key for key, value in units.items() if value), - "held_targets": sum( - record["role"] == cd_surface.ROLE_HOLDOUT for record in eligible - ), - } + The shared :func:`microcosm.build.target_holdouts.assign_holdout_roles` + runs the declared county pass over the county rows (microcosm#1728). + """ + + return target_holdouts.assign_holdout_roles( + records, + _COUNTY_HOLDOUT, + us_target_holdouts().concept_families, + fraction=fraction, + salt=salt, + ) def pro_rata_baseline(records, rows): - by_name = {record["name"]: record for record in records} - values = [] - for index in rows: - record = records[index] - parent = by_name.get(record.get("state_county_parent_target_name")) - county, state = ( - float(record.get("county_population", 0)), - float(record.get("state_population", 0)), - ) - if parent is None or not ( - math.isfinite(county) and math.isfinite(state) and county > 0 and state > 0 - ): - raise ValueError( - f"{record['name']} has no state parent or positive county/state population for pro-rata baseline." - ) - values.append(float(parent["value"]) * county / state) - return np.asarray(values, dtype=float) + return target_holdouts.pro_rata_baseline( + records, rows, us_holdout_scoring(COUNTY_HOLDOUT) + ) def score_county_holdout( records, matrix, *, design_weights, final_weights, cap, receipt=None ): - rows = [ - index - for index, record in enumerate(records) - if record.get("geography_level") == "county" - and record.get("role") == cd_surface.ROLE_HOLDOUT - ] - base = {"report_only": True, **dict(receipt or {}), "n_targets": len(rows)} - if not rows: - return base - held = sparse.csr_array(matrix[rows]).astype(float) - targets = np.asarray([records[index]["value"] for index in rows], float) - final, design = held @ np.asarray(final_weights), held @ np.asarray(design_weights) - baseline = pro_rata_baseline(records, rows) - scale = np.maximum(np.abs(targets), 1.0) - return { - **base, - "calibrated": cd_surface._error_summary(final, targets, cap=cap), - "design_weights": cd_surface._error_summary(design, targets, cap=cap), - "pro_rata_baseline": cd_surface._error_summary(baseline, targets, cap=cap), - "calibrated_beats_pro_rata_share": float( - ( - np.abs(final - targets) / scale < np.abs(baseline - targets) / scale - ).mean() - ), - "baseline": "state parent target x county population / state population", - "targets": [ - { - "name": records[index]["name"], - "county_fips": records[index]["county_fips"], - "target": float(targets[position]), - "calibrated": float(final[position]), - "design": float(design[position]), - "pro_rata": float(baseline[position]), - } - for position, index in enumerate(rows) - ], - } + return target_holdouts.score_holdout( + records, + matrix, + us_holdout_scoring(COUNTY_HOLDOUT), + design_weights=design_weights, + final_weights=final_weights, + cap=cap, + receipt=receipt, + ) def reliability_grade(ess, error): From 904a46d868352b6b8b572b0262d4b6c9e7926324 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:49:01 +0000 Subject: [PATCH 08/30] Build the state and district ladder population rows with shared code C3 of the shared-code work in microcosm#1728. No target changes. - microcosm.build.ladder_population_targets (new, country-free) makes, for each declared geography level, the population rows (household size times the cell indicator; a household of size zero supports its cell but adds nothing), the cells that no household supports, and the target specs with their calibration hierarchy. Names, record code fields, geography ids, labels, sources and families are declared; a country passes a label lookup for each label kind. - us/local_target_construction.json gains the ladder_population section: the state and district levels with the values the tools held. microcosm.build.us_runtime.local_target_construction reads it and gives the label lookups (Census state names, and congressional_district_label). - tools/us_acs_local_cd_surface.py (population_rows, population_target_name) and tools/build_us_acs_local_release.py (population_targets, population_target_specs) keep their names and call the shared code. The county population rows and specs stay with the county rung (C5). - The district module no longer imports the county module: the local tool's population_targets picks the county rung's rows for a county run, and the district rows refuse a county level. No spec-engine pin moves: the pins read the resource row, not its content. Proof: - test_us_acs_local_surface_bytes.py (C0) and the pinned surfaces of test_us_target_sets.py pass unchanged on the pinned feed and ladder. - test_us_ladder_population.py (54 tests) holds the tool functions to verbatim copies of the replaced code (test_support/microcosm_build/us_ladder_population_reference.py) on random households and ladders: records, matrix rows, dropped cells and specs. - test_ladder_population_targets.py (13 tests) tests the shared module on a made-up country. - 4,111 tests in the 53 files that load the changed tools or hold the registers ran locally with the pinned feed and ladder. All passed (8 skipped) except one C2 test that checks the file's top-level keys; this commit adds the new section to it, and that file passes. Co-Authored-By: Claude Opus 5.5 --- ...-shared-ladder-population-targets.added.md | 1 + .../build/ladder_population_targets.py | 375 ++++++++++++++++++ .../build/us/local_target_construction.json | 66 ++- .../us_runtime/local_target_construction.py | 51 ++- .../shared/test_ladder_population_targets.py | 205 ++++++++++ .../us/test_us_ladder_population.py | 177 +++++++++ .../engine_free/us/test_us_target_holdouts.py | 1 + .../us_ladder_population_reference.py | 194 +++++++++ tools/build_us_acs_local_release.py | 113 +++--- tools/us_acs_local_cd_surface.py | 82 ++-- 10 files changed, 1141 insertions(+), 124 deletions(-) create mode 100644 changelog.d/1728-shared-ladder-population-targets.added.md create mode 100644 packages/microcosm-build/src/microcosm/build/ladder_population_targets.py create mode 100644 packages/microcosm-build/tests/engine_free/shared/test_ladder_population_targets.py create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_ladder_population.py create mode 100644 test_support/microcosm_build/us_ladder_population_reference.py diff --git a/changelog.d/1728-shared-ladder-population-targets.added.md b/changelog.d/1728-shared-ladder-population-targets.added.md new file mode 100644 index 0000000000..78e05e1822 --- /dev/null +++ b/changelog.d/1728-shared-ladder-population-targets.added.md @@ -0,0 +1 @@ +Ladder population targets are shared code for any country (microcosm#1728): `microcosm.build.ladder_population_targets` makes, for each declared geography level, the population rows (household size times the cell indicator), the cells no household supports, and the target specs with their calibration hierarchy, from declared names, record codes, geography ids and label lookups. The ACS local release declares its state and district levels in the `ladder_population` section of `us/local_target_construction.json`; the county rows stay with the county rung. The district module no longer imports the county module: the local tool picks the county rows for a county run. No target changes: `test_us_ladder_population.py` holds the shared code to verbatim copies of the replaced tool code, and the pinned bytes of `test_us_acs_local_surface_bytes.py` are unchanged. diff --git a/packages/microcosm-build/src/microcosm/build/ladder_population_targets.py b/packages/microcosm-build/src/microcosm/build/ladder_population_targets.py new file mode 100644 index 0000000000..07fcf9c730 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/ladder_population_targets.py @@ -0,0 +1,375 @@ +"""Population targets from a geography ladder, for any country. + +A geography ladder gives the population of each cell of each geography level +(a state, a district). A local build calibrates to those totals. This module +makes, for each declared level: + +- the role record of each cell's target (:func:`population_rows`), with the + record fields the country declares; +- the cell's row of the target matrix: each household's size where the + household is in the cell, so the weighted row is the cell's population. A + household of size zero supports its cell but adds nothing to the row; +- the cells that no household supports, by name. The caller decides whether + a smaller surface is acceptable; +- the cell's target spec with its calibration hierarchy + (:func:`population_target_specs`). A country gives a label lookup for each + declared label kind. + +A country declares its levels as data, and :func:`load_ladder_population` +reads them (microcosm#1728). Nothing here reads country code. +""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from typing import Any + +import numpy as np +import pandas as pd +from scipy import sparse + +__all__ = [ + "CodeField", + "LadderLevel", + "LadderPopulation", + "LadderPopulationError", + "load_ladder_population", + "population_rows", + "population_target_specs", +] + +#: A label lookup: ``(cell code as named, geography id) -> label or None``. +LabelLookup = Callable[[str, str], "str | None"] + +_SECTION_KEYS = frozenset({"name_prefix", "record", "spec", "levels", "rationale"}) +_RECORD_KEYS = frozenset({"source", "family"}) +_SPEC_KEYS = frozenset( + {"entity", "family", "source", "provider", "category", "target_label"} +) +_NODE_KEYS = frozenset({"id", "label"}) +_LEVEL_KEYS = frozenset( + { + "geography", + "level", + "household_column", + "code_digits", + "geography_id_prefix", + "label", + "record_codes", + } +) +_CODE_KEYS = frozenset({"field", "divisor", "digits"}) + + +class LadderPopulationError(ValueError): + """A ladder population declaration or input is not valid.""" + + +@dataclass(frozen=True) +class CodeField: + """A record field made from the cell code: ``code // divisor``, zero-padded. + + With no divisor the field is None (the level has no such code). + """ + + field: str + divisor: int | None + digits: int | None + + def value(self, code: int) -> str | None: + if self.divisor is None: + return None + return f"{int(code) // self.divisor:0{self.digits}d}" + + +@dataclass(frozen=True) +class LadderLevel: + """One declared geography level of the ladder.""" + + geography: str + level: str + household_column: str + code_digits: int + geography_id_prefix: str + label: str + record_codes: tuple[CodeField, ...] + + +@dataclass(frozen=True) +class LadderPopulation: + """A country's ladder population targets.""" + + name_prefix: str + record_source: str + record_family: str + entity: str + spec_family: str + spec_source: str + provider: tuple[str, str] + category: tuple[str, str] + target_label: str + levels: tuple[LadderLevel, ...] + rationale: str + + def level(self, geography: str) -> LadderLevel: + for level in self.levels: + if level.geography == geography: + return level + raise LadderPopulationError( + f"No ladder population level {geography!r}; declared: " + f"{[level.geography for level in self.levels]}." + ) + + def name_prefix_of(self, level: LadderLevel) -> str: + return f"{self.name_prefix}{level.geography}_" + + def target_name(self, geography: str, code: int) -> str: + level = self.level(geography) + return f"{self.name_prefix_of(level)}{int(code):0{level.code_digits}d}" + + def level_of_name(self, name: str) -> LadderLevel | None: + for level in self.levels: + if name.startswith(self.name_prefix_of(level)): + return level + return None + + +# --------------------------------------------------------------------------- +# Reading the declaration +# --------------------------------------------------------------------------- + + +def _mapping(value: Any, *, context: str, keys: frozenset[str]) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + raise LadderPopulationError(f"{context} must be an object.") + unknown = sorted(set(value) - keys) + missing = sorted(keys - set(value)) + if unknown or missing: + raise LadderPopulationError( + f"{context}: unknown keys {unknown}, missing keys {missing}." + ) + return value + + +def _text(value: Any, *, context: str) -> str: + if not isinstance(value, str) or not value: + raise LadderPopulationError(f"{context} must be a non-empty string.") + return value + + +def _positive_int(value: Any, *, context: str) -> int: + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise LadderPopulationError(f"{context} must be a positive integer.") + return value + + +def _code_field(raw: Any, *, context: str) -> CodeField: + raw = _mapping(raw, context=context, keys=_CODE_KEYS) + field = _text(raw["field"], context=f"{context} field") + if raw["divisor"] is None: + if raw["digits"] is not None: + raise LadderPopulationError( + f"{context}: a field with no divisor has no digits." + ) + return CodeField(field, None, None) + return CodeField( + field, + _positive_int(raw["divisor"], context=f"{context} divisor"), + _positive_int(raw["digits"], context=f"{context} digits"), + ) + + +def _level(raw: Any) -> LadderLevel: + raw = _mapping(raw, context="ladder level", keys=_LEVEL_KEYS) + geography = _text(raw["geography"], context="ladder level geography") + context = f"ladder level {geography!r}" + codes = raw["record_codes"] + if not isinstance(codes, list): + raise LadderPopulationError(f"{context} record_codes must be a list.") + record_codes = tuple( + _code_field(item, context=f"{context} record code") for item in codes + ) + fields = [code.field for code in record_codes] + if len(set(fields)) != len(fields): + raise LadderPopulationError(f"{context} record_codes repeat a field.") + return LadderLevel( + geography=geography, + level=_text(raw["level"], context=f"{context} level"), + household_column=_text( + raw["household_column"], context=f"{context} household_column" + ), + code_digits=_positive_int(raw["code_digits"], context=f"{context} code_digits"), + geography_id_prefix=_text( + raw["geography_id_prefix"], context=f"{context} geography_id_prefix" + ), + label=_text(raw["label"], context=f"{context} label"), + record_codes=record_codes, + ) + + +def load_ladder_population(section: Mapping[str, Any]) -> LadderPopulation: + """Read a country's ``ladder_population`` declaration; refuse anything unknown.""" + + raw = _mapping(section, context="ladder_population", keys=_SECTION_KEYS) + record = _mapping( + raw["record"], context="ladder_population record", keys=_RECORD_KEYS + ) + spec = _mapping(raw["spec"], context="ladder_population spec", keys=_SPEC_KEYS) + provider = _mapping(spec["provider"], context="spec provider", keys=_NODE_KEYS) + category = _mapping(spec["category"], context="spec category", keys=_NODE_KEYS) + target_label = _text(spec["target_label"], context="spec target_label") + if "{label}" not in target_label: + raise LadderPopulationError("spec target_label must contain {label}.") + if not isinstance(raw["levels"], list) or not raw["levels"]: + raise LadderPopulationError( + "ladder_population levels must be a non-empty list." + ) + levels = tuple(_level(item) for item in raw["levels"]) + geographies = [level.geography for level in levels] + if len(set(geographies)) != len(geographies): + raise LadderPopulationError(f"ladder_population levels repeat: {geographies}.") + return LadderPopulation( + name_prefix=_text(raw["name_prefix"], context="ladder_population name_prefix"), + record_source=_text(record["source"], context="record source"), + record_family=_text(record["family"], context="record family"), + entity=_text(spec["entity"], context="spec entity"), + spec_family=_text(spec["family"], context="spec family"), + spec_source=_text(spec["source"], context="spec source"), + provider=( + _text(provider["id"], context="provider id"), + _text(provider["label"], context="provider label"), + ), + category=( + _text(category["id"], context="category id"), + _text(category["label"], context="category label"), + ), + target_label=target_label, + levels=levels, + rationale=_text(raw["rationale"], context="ladder_population rationale"), + ) + + +# --------------------------------------------------------------------------- +# Rows and specs +# --------------------------------------------------------------------------- + + +def population_rows( + households: pd.DataFrame, + household_size: np.ndarray, + ladder_populations: Mapping[str, Mapping[int, float]], + geographies: Sequence[str], + declaration: LadderPopulation, +) -> tuple[list[dict], sparse.csr_array, list[str]]: + """Ladder population marginals as sparse rows (household size x 1[cell]). + + Returns (target records, CSR rows, dropped cell names), in the order of + ``geographies`` and then of the cell codes. A ladder cell with no + supporting household is dropped and named. + """ + + size32 = np.asarray(household_size, dtype=np.float32) + records: list[dict] = [] + rows: list[np.ndarray] = [] + cols: list[np.ndarray] = [] + data: list[np.ndarray] = [] + dropped: list[str] = [] + for geography in geographies: + level = declaration.level(geography) + codes = pd.to_numeric(households[level.household_column]).to_numpy() + for value, population in sorted(ladder_populations[geography].items()): + name = declaration.target_name(geography, value) + present = np.flatnonzero(codes == value) + if not len(present): + dropped.append(name) + continue + present = present[size32[present] != 0] + row = len(records) + rows.append(np.full(len(present), row, dtype=np.int32)) + cols.append(present.astype(np.int32)) + data.append(size32[present]) + record = { + "name": name, + "value": float(population), + "source": declaration.record_source, + "family": declaration.record_family, + "geography_level": level.level, + } + for code in level.record_codes: + record[code.field] = code.value(value) + records.append(record) + matrix = sparse.csr_array( + ( + np.concatenate(data) if data else np.empty(0, np.float32), + ( + np.concatenate(rows) if rows else np.empty(0, np.int32), + np.concatenate(cols) if cols else np.empty(0, np.int32), + ), + ), + shape=(len(records), len(households)), + ) + matrix.sort_indices() + return records, matrix, dropped + + +def population_target_specs( + names: Sequence[str], + values: Sequence[float], + declaration: LadderPopulation, + *, + period: int, + labels: Mapping[str, LabelLookup], +) -> tuple: + """The target spec of each named cell, with its calibration hierarchy. + + A name says its level (``_``). The level's + label lookup gives the geography's label from the code and the + geography id; a code with no label is refused. + """ + + from microcosm.calibrate import TargetSpec + from microcosm.calibrate.hierarchy import ( + CalibrationHierarchy, + HierarchyCategory, + HierarchyGeography, + HierarchyNode, + ) + + provider = HierarchyNode(*declaration.provider) + category = HierarchyCategory(*declaration.category, provider.id) + specs = [] + for name, value in zip(names, values, strict=True): + level = declaration.level_of_name(name) + if level is None: + raise LadderPopulationError(f"Unknown population target name {name!r}.") + code = name.removeprefix(declaration.name_prefix_of(level)) + geography_id = f"{level.geography_id_prefix}{code}" + label = labels[level.label](code, geography_id) + if label is None: + raise LadderPopulationError( + f"Population target {name!r} names no {level.level} code." + ) + geography = HierarchyGeography(geography_id, label, level.level) + specs.append( + TargetSpec( + name=name, + entity=declaration.entity, + measure=name, + value=value, + period=period, + source=declaration.spec_source, + family=declaration.spec_family, + metadata={"geography_level": geography.level}, + hierarchy=CalibrationHierarchy( + provider=provider, + category=category, + geography=geography, + dimensions=(), + target=HierarchyNode( + name, declaration.target_label.format(label=label) + ), + ), + ) + ) + return tuple(specs) diff --git a/packages/microcosm-build/src/microcosm/build/us/local_target_construction.json b/packages/microcosm-build/src/microcosm/build/us/local_target_construction.json index 45bbe183c8..9e20d68880 100644 --- a/packages/microcosm-build/src/microcosm/build/us/local_target_construction.json +++ b/packages/microcosm-build/src/microcosm/build/us/local_target_construction.json @@ -1,7 +1,7 @@ { "version": 1, "country": "us", - "description": "How the ACS local release (tools/build_us_acs_local_release.py) builds the targets that the compile does not give it (microcosm#1728). Each section is read by a shared, country-free module: holdouts by microcosm.build.target_holdouts.", + "description": "How the ACS local release (tools/build_us_acs_local_release.py) builds the targets that the compile does not give it (microcosm#1728). Each section is read by a shared, country-free module: holdouts by microcosm.build.target_holdouts, ladder_population by microcosm.build.ladder_population_targets.", "holdouts": { "concept_families": { "source_field": "source_measure_id", @@ -132,5 +132,69 @@ "rationale": "Hold out whole state and concept-family blocks of county rows, so that no held county row is pinned by its trained siblings. Only county rows with a state parent are eligible, so the county population rows always train. The pass writes county rows only, after the district pass." } ] + }, + "ladder_population": { + "name_prefix": "pop_", + "record": { + "source": "us_puma_ladder_2020", + "family": "census_population_ladder" + }, + "spec": { + "entity": "household", + "family": "census_population", + "source": "US Census Bureau 2020 PUMA population ladder", + "provider": { + "id": "census_population", + "label": "Census population" + }, + "category": { + "id": "census_population.resident_population", + "label": "Resident population" + }, + "target_label": "{label} resident population" + }, + "levels": [ + { + "geography": "state", + "level": "state", + "household_column": "state_fips", + "code_digits": 2, + "geography_id_prefix": "0400000US", + "label": "us_state_name", + "record_codes": [ + { + "field": "state_fips", + "divisor": 1, + "digits": 2 + }, + { + "field": "congressional_district_geoid", + "divisor": null, + "digits": null + } + ] + }, + { + "geography": "cd", + "level": "congressional_district", + "household_column": "congressional_district_geoid", + "code_digits": 4, + "geography_id_prefix": "5001900US", + "label": "us_congressional_district_name", + "record_codes": [ + { + "field": "state_fips", + "divisor": 100, + "digits": 2 + }, + { + "field": "congressional_district_geoid", + "divisor": 1, + "digits": 4 + } + ] + } + ], + "rationale": "The PUMA ladder's state and district populations (--geographies state,cd): a state is the sum of its PUMAs and a district the sum of its PUMA overlaps on the 119th Congress plan. Each household adds its persons to its cell's row. A release run refuses a cell that no household supports; --allow-partial-geography is for capped smokes. The county population rows belong to the county rung (tools/us_acs_local_county_surface.py)." } } diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/local_target_construction.py b/packages/microcosm-build/src/microcosm/build/us_runtime/local_target_construction.py index a6ac0499e1..c1ebc8fa08 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/local_target_construction.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/local_target_construction.py @@ -6,8 +6,10 @@ - ``holdouts``: :mod:`microcosm.build.target_holdouts` (the district and the county hold-out passes, and how their held rows are scored). +- ``ladder_population``: :mod:`microcosm.build.ladder_population_targets` + (the PUMA ladder's state and district population rows and specs). -This module names the US file and its passes. +This module names the US file, its passes and its label lookups. """ from __future__ import annotations @@ -18,6 +20,11 @@ from pathlib import Path from typing import Any +from microcosm.build.ladder_population_targets import ( + LabelLookup, + LadderPopulation, + load_ladder_population, +) from microcosm.build.target_holdouts import ( HoldoutPass, HoldoutScoring, @@ -28,11 +35,15 @@ __all__ = [ "COUNTY_HOLDOUT", "DISTRICT_HOLDOUT", + "US_DISTRICT_LABEL", "US_LOCAL_TARGET_CONSTRUCTION_RESOURCE", + "US_STATE_LABEL", "us_holdout_pass", "us_holdout_scoring", + "us_ladder_population", "us_local_target_construction", "us_local_target_construction_path", + "us_population_labels", "us_target_holdouts", ] @@ -41,8 +52,15 @@ DISTRICT_HOLDOUT = "district" #: The hold-out pass over county rows (``--soi-mode state_county``). COUNTY_HOLDOUT = "county" - -_ENVELOPE_KEYS = frozenset({"version", "country", "description", "holdouts"}) +#: The label lookups the ladder levels name: a state's Census name, and a +#: district's Census Bureau name (one label for each geography across target +#: sources, microcosm#1335). +US_STATE_LABEL = "us_state_name" +US_DISTRICT_LABEL = "us_congressional_district_name" + +_ENVELOPE_KEYS = frozenset( + {"version", "country", "description", "holdouts", "ladder_population"} +) def us_local_target_construction_path() -> Path: @@ -88,3 +106,30 @@ def us_holdout_scoring(pass_id: str) -> HoldoutScoring: if scoring is None: raise ValueError(f"The US hold-out pass {pass_id!r} declares no scoring.") return scoring + + +@lru_cache(maxsize=1) +def us_ladder_population() -> LadderPopulation: + """The US ladder population levels, read and checked once.""" + + return load_ladder_population(us_local_target_construction()["ladder_population"]) + + +def _state_label(code: str, geography_id: str) -> str | None: + from microcosm.calibrate.geography_constants import US_STATE_FIPS_TO_NAME + + return US_STATE_FIPS_TO_NAME.get(code) + + +def _district_label(code: str, geography_id: str) -> str | None: + from microcosm.build.us_runtime.congressional_district_vintage import ( + congressional_district_label, + ) + + return congressional_district_label(geography_id) + + +def us_population_labels() -> dict[str, LabelLookup]: + """The label lookup of each label kind the US ladder levels name.""" + + return {US_STATE_LABEL: _state_label, US_DISTRICT_LABEL: _district_label} diff --git a/packages/microcosm-build/tests/engine_free/shared/test_ladder_population_targets.py b/packages/microcosm-build/tests/engine_free/shared/test_ladder_population_targets.py new file mode 100644 index 0000000000..d229f17ad8 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_ladder_population_targets.py @@ -0,0 +1,205 @@ +"""Shared ladder population targets (microcosm.build.ladder_population_targets). + +The tests use a made-up country of regions (code ``R``) and districts (code +``RDD``). They check the reader, the code fields, the rows (dropped cells, a +household of size zero), and the specs with their labels. No country code is +read (microcosm#1728). +""" + +from __future__ import annotations + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.ladder_population_targets import ( + CodeField, + LadderPopulationError, + load_ladder_population, + population_rows, + population_target_specs, +) + + +def _section() -> dict: + return { + "name_prefix": "pop_", + "record": {"source": "test_ladder", "family": "test_population_ladder"}, + "spec": { + "entity": "household", + "family": "test_population", + "source": "Test ladder", + "provider": {"id": "census", "label": "Census"}, + "category": {"id": "census.people", "label": "People"}, + "target_label": "{label} people", + }, + "levels": [ + { + "geography": "region", + "level": "region", + "household_column": "region_code", + "code_digits": 1, + "geography_id_prefix": "R:", + "label": "region_name", + "record_codes": [ + {"field": "region", "divisor": 1, "digits": 1}, + {"field": "district", "divisor": None, "digits": None}, + ], + }, + { + "geography": "district", + "level": "district", + "household_column": "district_code", + "code_digits": 3, + "geography_id_prefix": "D:", + "label": "district_name", + "record_codes": [ + {"field": "region", "divisor": 100, "digits": 1}, + {"field": "district", "divisor": 1, "digits": 3}, + ], + }, + ], + "rationale": "Region and district totals.", + } + + +LABELS = { + "region_name": lambda code, geography_id: {"1": "North", "2": "South"}.get(code), + "district_name": lambda code, geography_id: f"District {geography_id}", +} + + +def test_code_fields() -> None: + assert CodeField("region", 100, 1).value(205) == "2" + assert CodeField("district", 1, 3).value(7) == "007" + assert CodeField("district", None, None).value(205) is None + + +def test_names_and_levels() -> None: + declaration = load_ladder_population(_section()) + assert declaration.target_name("district", 105) == "pop_district_105" + assert declaration.target_name("region", 2) == "pop_region_2" + assert declaration.level_of_name("pop_district_105").geography == "district" + assert declaration.level_of_name("pop_ward_1") is None + with pytest.raises(LadderPopulationError, match="No ladder population level"): + declaration.level("ward") + + +def test_rows() -> None: + declaration = load_ladder_population(_section()) + households = pd.DataFrame( + {"region_code": [1, 1, 2, 1], "district_code": [101, 102, 201, 101]} + ) + sizes = np.asarray([2.0, 0.0, 3.0, 1.0], dtype=np.float32) + populations = { + "region": {1: 100.0, 2: 50.0, 3: 10.0}, + "district": {101: 60.0, 102: 40.0, 201: 50.0}, + } + records, matrix, dropped = population_rows( + households, sizes, populations, ["region", "district"], declaration + ) + assert dropped == ["pop_region_3"] + assert [record["name"] for record in records] == [ + "pop_region_1", + "pop_region_2", + "pop_district_101", + "pop_district_102", + "pop_district_201", + ] + assert records[0] == { + "name": "pop_region_1", + "value": 100.0, + "source": "test_ladder", + "family": "test_population_ladder", + "geography_level": "region", + "region": "1", + "district": None, + } + assert records[2]["region"] == "1" and records[2]["district"] == "101" + dense = matrix.toarray() + # The size-zero household supports district 102 but adds nothing to it. + assert dense[3].tolist() == [0.0, 0.0, 0.0, 0.0] + assert dense[0].tolist() == [2.0, 0.0, 0.0, 1.0] + assert matrix.data.dtype == np.float32 + + +def test_specs() -> None: + declaration = load_ladder_population(_section()) + specs = population_target_specs( + ["pop_region_1", "pop_district_101"], + [100.0, 60.0], + declaration, + period=2030, + labels=LABELS, + ) + region, district = specs + assert region.metadata == {"geography_level": "region"} + assert region.hierarchy.geography.id == "R:1" + assert region.hierarchy.target.label == "North people" + assert district.hierarchy.geography.label == "District D:101" + assert region.hierarchy.provider is district.hierarchy.provider + assert (region.period, region.family, region.source) == ( + 2030, + "test_population", + "Test ladder", + ) + with pytest.raises(LadderPopulationError, match="names no region"): + population_target_specs( + ["pop_region_9"], [1.0], declaration, period=2030, labels=LABELS + ) + with pytest.raises(LadderPopulationError, match="Unknown population target"): + population_target_specs( + ["pop_ward_1"], [1.0], declaration, period=2030, labels=LABELS + ) + + +def _mutations(): + def set_(path, key, value): + def mutate(section): + target = section + for step in path: + target = target[step] + target[key] = value + + return mutate + + def drop(path, key): + def mutate(section): + target = section + for step in path: + target = target[step] + del target[key] + + return mutate + + first = ("levels", 0) + return { + "unknown key": set_((), "extra", 1), + "missing record": drop((), "record"), + "empty levels": set_((), "levels", []), + "repeated level": set_(("levels", 1), "geography", "region"), + "zero digits": set_(first, "code_digits", 0), + "label without placeholder": set_(("spec",), "target_label", "people"), + "digits without divisor": set_( + first, "record_codes", [{"field": "x", "divisor": None, "digits": 2}] + ), + "repeated record field": set_( + first, + "record_codes", + [ + {"field": "x", "divisor": 1, "digits": 1}, + {"field": "x", "divisor": 1, "digits": 1}, + ], + ), + "boolean divisor": set_( + first, "record_codes", [{"field": "x", "divisor": True, "digits": 1}] + ), + } + + +@pytest.mark.parametrize("case", sorted(_mutations())) +def test_the_reader_refuses_a_malformed_declaration(case: str) -> None: + section = _section() + _mutations()[case](section) + with pytest.raises(LadderPopulationError): + load_ladder_population(section) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_ladder_population.py b/packages/microcosm-build/tests/engine_free/us/test_us_ladder_population.py new file mode 100644 index 0000000000..082d4c28ca --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_ladder_population.py @@ -0,0 +1,177 @@ +"""The US ladder population rows on the shared code give what the tool code gave. + +microcosm#1728 moved the state and district population rows and specs of the +ACS local release to the shared ``microcosm.build.ladder_population_targets``, +with the US levels in ``us/local_target_construction.json``. These tests hold +the tool functions, which now call the shared code, to verbatim copies of the +code they replace (``test_support/microcosm_build/us_ladder_population_reference.py``) +on random households and ladders: the same records, matrix rows, dropped +cells and target specs. ``test_us_acs_local_surface_bytes.py`` checks the same +on the pinned feed and ladder. +""" + +from __future__ import annotations + +import importlib.util +import json + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.us_runtime.congressional_district_vintage import ( + CURRENT_CONGRESSIONAL_DISTRICT_PREFIX, +) +from microcosm.build.us_runtime.local_target_construction import ( + us_ladder_population, +) +from microcosm.calibrate.geography_constants import US_STATE_FIPS_TO_NAME +from test_support.microcosm_build import us_ladder_population_reference as reference +from test_support.paths import paths_for + +_TEST_PATHS = paths_for("microcosm-build") +SEEDS = range(10) +GEOGRAPHY_LISTS = (["state"], ["cd"], ["state", "cd"], ["cd", "state"]) + + +@pytest.fixture(scope="module") +def tool(): + path = _TEST_PATHS.repository / "tools" / "build_us_acs_local_release.py" + spec = importlib.util.spec_from_file_location("build_us_acs_local_release", path) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module + + +def _ladder(seed: int): + """Households, sizes and ladder populations, with some cells unsupported.""" + + rng = np.random.default_rng(seed) + states = sorted(int(code) for code in US_STATE_FIPS_TO_NAME) + chosen = sorted(rng.choice(states, size=6, replace=False).tolist()) + districts = sorted( + {state * 100 + int(rng.integers(0, 8)) for state in chosen for _ in range(3)} + ) + populations = { + "state": {state: float(rng.uniform(1e5, 4e7)) for state in chosen}, + "cd": {district: float(rng.uniform(5e5, 9e5)) for district in districts}, + } + supported = [code for code in districts if rng.uniform() < 0.8] + rows = [] + for _ in range(int(rng.integers(20, 80))): + district = supported[int(rng.integers(len(supported)))] + rows.append( + {"state_fips": district // 100, "congressional_district_geoid": district} + ) + households = pd.DataFrame(rows) + sizes = rng.integers(0, 6, size=len(households)).astype(np.float32) + return households, sizes, populations + + +def _matrix_bytes(matrix) -> tuple: + return ( + matrix.shape, + matrix.indptr.tolist(), + matrix.indices.tolist(), + matrix.data.astype(np.float32).tolist(), + ) + + +def test_the_declaration_holds_the_tool_values(tool) -> None: + declaration = us_ladder_population() + district = declaration.level("cd") + assert district.geography_id_prefix == CURRENT_CONGRESSIONAL_DISTRICT_PREFIX + assert {level.geography: level.code_digits for level in declaration.levels} == { + geography: digits + for geography, digits in reference.POPULATION_TARGET_CODE_DIGITS.items() + if geography != "county" + } + assert tool.cd_surface.POPULATION_TARGET_CODE_DIGITS == ( + reference.POPULATION_TARGET_CODE_DIGITS + ) + for geography, code in (("state", 6), ("cd", 601), ("county", 6037)): + assert tool.cd_surface.population_target_name(geography, code) == ( + reference.population_target_name(geography, code) + ) + + +@pytest.mark.parametrize("seed", SEEDS) +@pytest.mark.parametrize("geographies", GEOGRAPHY_LISTS) +def test_population_rows_match(tool, seed: int, geographies: list[str]) -> None: + households, sizes, populations = _ladder(seed) + old_records, old_matrix, old_dropped = reference.population_rows( + households, sizes, populations, geographies + ) + new_records, new_matrix, new_dropped = tool.cd_surface.population_rows( + households, sizes, populations, geographies + ) + assert json.dumps(new_records) == json.dumps(old_records) + assert _matrix_bytes(new_matrix) == _matrix_bytes(old_matrix) + assert new_dropped == old_dropped + + +@pytest.mark.parametrize("seed", SEEDS) +def test_population_specs_match(tool, seed: int) -> None: + _households, _sizes, populations = _ladder(seed) + for geographies in GEOGRAPHY_LISTS: + old = reference.ladder_population_target_specs(populations, geographies) + new = tool.ladder_population_target_specs(populations, geographies) + assert new == old + assert json.dumps([spec.to_dict() for spec in new]) == json.dumps( + [spec.to_dict() for spec in old] + ) + + +def test_county_specs_keep_their_place(tool) -> None: + names = ["pop_state_06", "pop_county_06037", "pop_cd_0601", "pop_county_36061"] + values = [3.9e7, 9.7e6, 7.6e5, 1.6e6] + specs = tool.population_target_specs(names, values) + assert [spec.name for spec in specs] == names + assert specs[0] == reference.population_target_specs(names[:1], values[:1])[0] + assert specs[2] == reference.population_target_specs(names[2:3], values[2:3])[0] + assert specs[1] == tool.county_surface.population_spec( + names[1], values[1], period=tool.PERIOD + ) + with pytest.raises(ValueError): + tool.population_target_specs(names, values[:-1]) + + +def test_a_state_code_with_no_name_refuses(tool) -> None: + with pytest.raises(ValueError): + reference.population_target_specs(["pop_state_99"], [1.0]) + with pytest.raises(ValueError): + tool.population_target_specs(["pop_state_99"], [1.0]) + + +class _Frame: + def __init__(self, households: pd.DataFrame, persons: pd.DataFrame) -> None: + self._tables = {"household": households, "person": persons} + + def table(self, name: str) -> pd.DataFrame: + return self._tables[name] + + +def test_the_tool_picks_the_county_rows_only_for_a_county_run(tool) -> None: + households, _sizes, populations = _ladder(4) + households = households.assign(household_id=np.arange(len(households))) + persons = pd.DataFrame( + {"person_household_id": np.repeat(households["household_id"], 2)} + ) + frame = _Frame(households, persons) + sizes = tool.household_sizes(frame) + + records, matrix, dropped = tool.population_targets( + frame, populations, ["state", "cd"] + ) + old_records, old_matrix, old_dropped = reference.population_rows( + households, sizes, populations, ["state", "cd"] + ) + assert json.dumps(records) == json.dumps(old_records) + assert _matrix_bytes(matrix) == _matrix_bytes(old_matrix) + assert dropped == old_dropped + + with pytest.raises(ValueError, match="county rung"): + tool.cd_surface.population_rows( + households, sizes, populations, ["state", "county"] + ) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_target_holdouts.py b/packages/microcosm-build/tests/engine_free/us/test_us_target_holdouts.py index 48cb8a9ba3..b3c7f8b1ae 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_target_holdouts.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_target_holdouts.py @@ -169,6 +169,7 @@ def test_the_declaration_holds_the_tool_constants() -> None: "country", "description", "holdouts", + "ladder_population", } diff --git a/test_support/microcosm_build/us_ladder_population_reference.py b/test_support/microcosm_build/us_ladder_population_reference.py new file mode 100644 index 0000000000..bcfee3dc80 --- /dev/null +++ b/test_support/microcosm_build/us_ladder_population_reference.py @@ -0,0 +1,194 @@ +"""Verbatim copies of the US ladder population code before microcosm#1728 moved it. + +``tools/us_acs_local_cd_surface.py`` and ``tools/build_us_acs_local_release.py`` +held this code at ``868f414bc``. The state and district rows and specs now live +in the shared ``microcosm.build.ladder_population_targets``, with the US levels +in ``us/local_target_construction.json``. The equivalence tests hold the shared +code to these copies on state and district cells. Only one name changed: +``cd_surface.population_target_name`` is ``population_target_name`` here. The +county branches still name the county module; the tests do not reach them. +""" + +# ruff: noqa + +from __future__ import annotations + +from collections.abc import Mapping, Sequence + +import numpy as np +import pandas as pd +from scipy import sparse + +GEOGRAPHY_STATE = "state" + +GEOGRAPHY_CD = "congressional_district" + +PERIOD = 2024 + +POPULATION_TARGET_CODE_DIGITS: Mapping[str, int] = {"state": 2, "cd": 4, "county": 5} + +def population_target_name(geography: str, code: int) -> str: + """A ladder population target's name: ``pop_state_06``, ``pop_cd_0601``.""" + + digits = POPULATION_TARGET_CODE_DIGITS[geography] + return f"pop_{geography}_{int(code):0{digits}d}" + +def population_rows( + households: pd.DataFrame, + household_size: np.ndarray, + ladder_populations: Mapping[str, Mapping[int, float]], + geographies: Sequence[str], + *, + county_column: str = "county_fips", +) -> tuple[list[dict], sparse.csr_array, list[str]]: + """Ladder population marginals as sparse rows (household size x 1[geo]). + + Returns (target records, CSR rows, dropped cell names). A ladder cell + with no supporting household is dropped and named, as before. + """ + + if "county" in geographies: + import us_acs_local_county_surface as county_surface + + return county_surface.population_rows( + households, household_size, ladder_populations, geographies, + county_column=county_column, + ) + column_map = { + "state": ("state_fips", "state", GEOGRAPHY_STATE), + "cd": ("congressional_district_geoid", "cd", GEOGRAPHY_CD), + } + size32 = np.asarray(household_size, dtype=np.float32) + records: list[dict] = [] + rows: list[np.ndarray] = [] + cols: list[np.ndarray] = [] + data: list[np.ndarray] = [] + dropped: list[str] = [] + for geography in geographies: + column, key, level = column_map[geography] + codes = pd.to_numeric(households[column]).to_numpy() + for value, population in sorted(ladder_populations[key].items()): + name = population_target_name(geography, value) + present = np.flatnonzero(codes == value) + if not len(present): + dropped.append(name) + continue + present = present[size32[present] != 0] + row = len(records) + rows.append(np.full(len(present), row, dtype=np.int32)) + cols.append(present.astype(np.int32)) + data.append(size32[present]) + record = { + "name": name, + "value": float(population), + "source": "us_puma_ladder_2020", + "family": "census_population_ladder", + "geography_level": level, + "state_fips": f"{int(value) // (100 if geography == 'cd' else 1):02d}", + "congressional_district_geoid": ( + f"{int(value):04d}" if geography == "cd" else None + ), + } + records.append(record) + matrix = sparse.csr_array( + ( + np.concatenate(data) if data else np.empty(0, np.float32), + ( + np.concatenate(rows) if rows else np.empty(0, np.int32), + np.concatenate(cols) if cols else np.empty(0, np.int32), + ), + ), + shape=(len(records), len(households)), + ) + matrix.sort_indices() + return records, matrix, dropped + +def population_target_specs(names, values): + """Declare ladder population targets with the shared diagnostics hierarchy. + + Each geography carries the label the release's other targets give the + same id: a state its Census name, the name the ledger targets take from + their facts ("Maine"), and a district the Census Bureau's name, which + the IRS SOI district rows carry too. A registry refuses one US geography + with two labels (microcosm#1335). + """ + + from microcosm.build.us_runtime.congressional_district_vintage import ( + CURRENT_CONGRESSIONAL_DISTRICT_PREFIX, + congressional_district_label, + ) + from microcosm.calibrate import TargetSpec + from microcosm.calibrate.geography_constants import US_STATE_FIPS_TO_NAME + from microcosm.calibrate.hierarchy import ( + CalibrationHierarchy, + HierarchyCategory, + HierarchyGeography, + HierarchyNode, + ) + + provider = HierarchyNode("census_population", "Census population") + category = HierarchyCategory( + "census_population.resident_population", + "Resident population", + provider.id, + ) + specs = [] + for name, value in zip(names, values, strict=True): + if name.startswith("pop_county_"): + specs.append(county_surface.population_spec(name, value, period=PERIOD)) + continue + if name.startswith("pop_state_"): + fips = name.removeprefix("pop_state_") + label = US_STATE_FIPS_TO_NAME.get(fips) + if label is None: + raise ValueError( + f"Population target {name!r} names no US state FIPS code." + ) + geography = HierarchyGeography(f"0400000US{fips}", label, "state") + elif name.startswith("pop_cd_"): + geoid = name.removeprefix("pop_cd_") + # The ladder's districts are the 119th Congress plan. + geography_id = f"{CURRENT_CONGRESSIONAL_DISTRICT_PREFIX}{geoid}" + label = congressional_district_label(geography_id) + geography = HierarchyGeography( + geography_id, label, "congressional_district" + ) + else: # pragma: no cover - names originate in population_measure_arrays + raise ValueError(f"Unknown population target name {name!r}.") + specs.append( + TargetSpec( + name=name, + entity="household", + measure=name, + value=value, + period=PERIOD, + source="US Census Bureau 2020 PUMA population ladder", + family="census_population", + metadata={"geography_level": geography.level}, + hierarchy=CalibrationHierarchy( + provider=provider, + category=category, + geography=geography, + dimensions=(), + target=HierarchyNode(name, f"{label} resident population"), + ), + ) + ) + return tuple(specs) + +def ladder_population_target_specs(ladder_populations, geographies): + """Every population target the ladder declares, before a household is read. + + :func:`population_targets` later drops a ladder cell no staged household + supports, so its targets are a subset of these with the same labels. + """ + + cells = [ + (population_target_name(geography, code), float(population)) + for geography in geographies + for code, population in sorted(ladder_populations[geography].items()) + ] + return population_target_specs( + [name for name, _population in cells], + [population for _name, population in cells], + ) diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index e526051a19..26fbd602c4 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -1619,10 +1619,17 @@ def population_targets( involved. A ladder cell with no supporting household is DROPPED from the surface and returned in the third element: the caller decides whether a shrunken surface is acceptable (a capped smoke) or a defect (release). - Returns ``(target records, CSR rows, dropped cell names)``. + Returns ``(target records, CSR rows, dropped cell names)``. A county run + takes its rows from the county rung, which adds the county rows to the + state and district rows. """ - return cd_surface.population_rows( + rows = ( + county_surface.population_rows + if "county" in geographies + else cd_surface.population_rows + ) + return rows( frame.table("household"), household_sizes(frame), ladder_populations, @@ -1638,71 +1645,49 @@ def population_target_specs(names, values): same id: a state its Census name, the name the ledger targets take from their facts ("Maine"), and a district the Census Bureau's name, which the IRS SOI district rows carry too. A registry refuses one US geography - with two labels (microcosm#1335). + with two labels (microcosm#1335). The state and district specs are the + shared :func:`microcosm.build.ladder_population_targets.population_target_specs` + over the declared US levels (microcosm#1728); county specs are the county + rung's. """ - from microcosm.build.us_runtime.congressional_district_vintage import ( - CURRENT_CONGRESSIONAL_DISTRICT_PREFIX, - congressional_district_label, - ) - from microcosm.calibrate import TargetSpec - from microcosm.calibrate.geography_constants import US_STATE_FIPS_TO_NAME - from microcosm.calibrate.hierarchy import ( - CalibrationHierarchy, - HierarchyCategory, - HierarchyGeography, - HierarchyNode, - ) - - provider = HierarchyNode("census_population", "Census population") - category = HierarchyCategory( - "census_population.resident_population", - "Resident population", - provider.id, - ) - specs = [] - for name, value in zip(names, values, strict=True): - if name.startswith("pop_county_"): - specs.append(county_surface.population_spec(name, value, period=PERIOD)) - continue - if name.startswith("pop_state_"): - fips = name.removeprefix("pop_state_") - label = US_STATE_FIPS_TO_NAME.get(fips) - if label is None: - raise ValueError( - f"Population target {name!r} names no US state FIPS code." - ) - geography = HierarchyGeography(f"0400000US{fips}", label, "state") - elif name.startswith("pop_cd_"): - geoid = name.removeprefix("pop_cd_") - # The ladder's districts are the 119th Congress plan. - geography_id = f"{CURRENT_CONGRESSIONAL_DISTRICT_PREFIX}{geoid}" - label = congressional_district_label(geography_id) - geography = HierarchyGeography( - geography_id, label, "congressional_district" - ) - else: # pragma: no cover - names originate in population_measure_arrays - raise ValueError(f"Unknown population target name {name!r}.") - specs.append( - TargetSpec( - name=name, - entity="household", - measure=name, - value=value, - period=PERIOD, - source="US Census Bureau 2020 PUMA population ladder", - family="census_population", - metadata={"geography_level": geography.level}, - hierarchy=CalibrationHierarchy( - provider=provider, - category=category, - geography=geography, - dimensions=(), - target=HierarchyNode(name, f"{label} resident population"), - ), - ) + from microcosm.build.ladder_population_targets import ( + population_target_specs as ladder_population_specs, + ) + from microcosm.build.us_runtime.local_target_construction import ( + us_ladder_population, + us_population_labels, + ) + + names, values = list(names), list(values) + if len(names) != len(values): + raise ValueError( + f"{len(names)} population target names but {len(values)} values." + ) + county = [name.startswith("pop_county_") for name in names] + ladder_specs = iter( + ladder_population_specs( + [ + name + for name, is_county in zip(names, county, strict=True) + if not is_county + ], + [ + value + for value, is_county in zip(values, county, strict=True) + if not is_county + ], + us_ladder_population(), + period=PERIOD, + labels=us_population_labels(), ) - return tuple(specs) + ) + return tuple( + county_surface.population_spec(name, value, period=PERIOD) + if is_county + else next(ladder_specs) + for name, value, is_county in zip(names, values, county, strict=True) + ) def ladder_population_target_specs(ladder_populations, geographies): diff --git a/tools/us_acs_local_cd_surface.py b/tools/us_acs_local_cd_surface.py index 81813d4861..877feacabe 100644 --- a/tools/us_acs_local_cd_surface.py +++ b/tools/us_acs_local_cd_surface.py @@ -40,7 +40,7 @@ import pandas as pd from scipy import sparse -from microcosm.build import target_holdouts +from microcosm.build import ladder_population_targets, target_holdouts # The shared role names; the county module and tests read them from here. from microcosm.build.target_holdouts import ROLE_HOLDOUT, ROLE_TRAIN # noqa: F401 @@ -48,6 +48,7 @@ DISTRICT_HOLDOUT, us_holdout_pass, us_holdout_scoring, + us_ladder_population, us_target_holdouts, ) @@ -1129,14 +1130,20 @@ def district_row_parents( #: Digits of a ladder population target's geography code, by ladder geography. -POPULATION_TARGET_CODE_DIGITS: Mapping[str, int] = {"state": 2, "cd": 4, "county": 5} +POPULATION_TARGET_CODE_DIGITS: Mapping[str, int] = { + # The state and district levels are declared in + # us/local_target_construction.json (ladder_population, microcosm#1728); + # the county rung names its own rows. + **{level.geography: level.code_digits for level in us_ladder_population().levels}, + "county": 5, +} def population_target_name(geography: str, code: int) -> str: """A ladder population target's name: ``pop_state_06``, ``pop_cd_0601``.""" digits = POPULATION_TARGET_CODE_DIGITS[geography] - return f"pop_{geography}_{int(code):0{digits}d}" + return f"{us_ladder_population().name_prefix}{geography}_{int(code):0{digits}d}" def population_rows( @@ -1150,64 +1157,27 @@ def population_rows( """Ladder population marginals as sparse rows (household size x 1[geo]). Returns (target records, CSR rows, dropped cell names). A ladder cell - with no supporting household is dropped and named, as before. + with no supporting household is dropped and named, as before. The rows + are the shared + :func:`microcosm.build.ladder_population_targets.population_rows` over the + declared US state and district levels (microcosm#1728). County rows are + the county rung's (``us_acs_local_county_surface.population_rows``), which + calls this function for its other levels; ``county_column`` is kept for + callers that pass it. """ if "county" in geographies: - import us_acs_local_county_surface as county_surface - - return county_surface.population_rows( - households, household_size, ladder_populations, geographies, - county_column=county_column, + raise ValueError( + "County population rows are the county rung's: call " + "us_acs_local_county_surface.population_rows." ) - column_map = { - "state": ("state_fips", "state", GEOGRAPHY_STATE), - "cd": ("congressional_district_geoid", "cd", GEOGRAPHY_CD), - } - size32 = np.asarray(household_size, dtype=np.float32) - records: list[dict] = [] - rows: list[np.ndarray] = [] - cols: list[np.ndarray] = [] - data: list[np.ndarray] = [] - dropped: list[str] = [] - for geography in geographies: - column, key, level = column_map[geography] - codes = pd.to_numeric(households[column]).to_numpy() - for value, population in sorted(ladder_populations[key].items()): - name = population_target_name(geography, value) - present = np.flatnonzero(codes == value) - if not len(present): - dropped.append(name) - continue - present = present[size32[present] != 0] - row = len(records) - rows.append(np.full(len(present), row, dtype=np.int32)) - cols.append(present.astype(np.int32)) - data.append(size32[present]) - record = { - "name": name, - "value": float(population), - "source": "us_puma_ladder_2020", - "family": "census_population_ladder", - "geography_level": level, - "state_fips": f"{int(value) // (100 if geography == 'cd' else 1):02d}", - "congressional_district_geoid": ( - f"{int(value):04d}" if geography == "cd" else None - ), - } - records.append(record) - matrix = sparse.csr_array( - ( - np.concatenate(data) if data else np.empty(0, np.float32), - ( - np.concatenate(rows) if rows else np.empty(0, np.int32), - np.concatenate(cols) if cols else np.empty(0, np.int32), - ), - ), - shape=(len(records), len(households)), + return ladder_population_targets.population_rows( + households, + household_size, + ladder_populations, + geographies, + us_ladder_population(), ) - matrix.sort_indices() - return records, matrix, dropped def save_target_matrix(path: Path, matrix: sparse.csr_array) -> str: From 33cdf66674345f64da140b552bf531aeb08934b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:12:44 +0000 Subject: [PATCH 09/30] Declare the US compile registers as data, and document the declarations C6 of the shared-code work in microcosm#1728, with the docs. No target changes. - microcosm.build.declared_registers (new, country-free) reads a reviewed register from a package JSON file: a description, the key fields (one, or a tuple), the value fields (one, a tuple, or none for a set) and the entries in order, each with an optional note. JSON arrays read back as tuples, so a register reads back as the Python literal it replaces. - us/fiscal_target_registers.json (new) holds 13 registers of the US fiscal target compile, generated from the live objects: the fact exclusions with their reasons and vintage scope, the misread source columns, the restamped source packages, the SOI variable maps, the direct and indicator Ledger targets, and the M-CHIP states. The comments that stood beside them in the code are their descriptions and the notes of their entries. microcosm.build.us_runtime.fiscal_target_registers names the file. - us_runtime/fiscal_targets.py and us_runtime/source_vintage.py keep every name and read the registers from the file (about 890 lines of literals go). - The new resource row: country_package.json, the bundle generator's LEGACY_RESOURCE_PATHS, the US F0 re-pin (42,413 configuration fields), the module classification, and the two modules the transport bindings now reach (BINDING_MODULES_ADDED_AFTER_BASE). - docs/us-target-sets.md describes the declared construction (us/local_target_construction.json) and the compile registers, and how to change them. Proof, measured on 904a46d86 before the move and pinned in test_us_fiscal_target_registers.py: - each register's digest (keys, values, Python types and entry order); - the pinned-feed compile under four flag sets (with and without aging, with and without the student-loan targets): count, TargetRegistry.version and the sha256 of the full registry JSON; - the exclusion receipt. test_declared_registers.py tests the shared reader on made-up registers. 5,599 tests in the 94 files that load the changed tools or the compile, or hold the registers, ran locally with the pinned feed and ladder. All passed (46 skipped) except one case of the new register test: it read the module's dict after another test had reordered it (monkeypatch.delitem restores a key at the end). The test now reads each fiscal_targets register fresh from the file and checks the module's content; it passes after those tests in one process. Co-Authored-By: Claude Opus 5.5 --- ...1728-us-fiscal-target-registers.changed.md | 1 + docs/evidence/spec-engine/us-f0-coverage.json | 20 +- docs/us-target-sets.md | 56 + .../src/microcosm/build/declared_registers.py | 173 ++ .../build/spec_engine/field_usage.py | 8 +- .../microcosm/build/us/country_package.json | 5 + .../build/us/fiscal_target_registers.json | 1559 +++++++++++++++++ .../us_runtime/fiscal_target_registers.py | 29 + .../build/us_runtime/fiscal_targets.py | 881 +--------- .../build/us_runtime/source_vintage.py | 84 +- .../us/test_spec_engine_coverage_tool.py | 10 +- .../shared/test_declared_registers.py | 132 ++ .../shared/test_spec_engine_field_usage.py | 10 +- .../shared/test_transport_evidence_kernels.py | 4 + .../us/test_us_fiscal_target_registers.py | 239 +++ .../engine_free/us/test_us_spine_blindness.py | 3 + .../us/test_us_multispine_pool_tool.py | 2 +- tools/generate_us_bundle_from_constants.py | 2 + tools/spec_engine_coverage.py | 2 +- 19 files changed, 2302 insertions(+), 918 deletions(-) create mode 100644 changelog.d/1728-us-fiscal-target-registers.changed.md create mode 100644 packages/microcosm-build/src/microcosm/build/declared_registers.py create mode 100644 packages/microcosm-build/src/microcosm/build/us/fiscal_target_registers.json create mode 100644 packages/microcosm-build/src/microcosm/build/us_runtime/fiscal_target_registers.py create mode 100644 packages/microcosm-build/tests/engine_free/shared/test_declared_registers.py create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_fiscal_target_registers.py diff --git a/changelog.d/1728-us-fiscal-target-registers.changed.md b/changelog.d/1728-us-fiscal-target-registers.changed.md new file mode 100644 index 0000000000..68e2fef4ed --- /dev/null +++ b/changelog.d/1728-us-fiscal-target-registers.changed.md @@ -0,0 +1 @@ +The reviewed registers of the US fiscal target compile are declared data (microcosm#1728): the fact exclusions with their reasons and vintage scope, the misread source columns, the restamped source packages, the SOI variable maps, the direct and indicator Ledger targets, and the M-CHIP states moved from Python literals in `us_runtime/fiscal_targets.py` and `us_runtime/source_vintage.py` to `us/fiscal_target_registers.json`, with the comments that stood beside them as descriptions and notes. The new shared `microcosm.build.declared_registers` reads a register back as the literal it replaces (JSON arrays as tuples, entries in order), and the code keeps every name. No target changes: `test_us_fiscal_target_registers.py` pins each register's digest as measured on the literals, the pinned-feed compile under four flag sets, and the exclusion receipt. `docs/us-target-sets.md` describes the declared construction and the registers. The new resource row moves the US F0 spec-engine pins (42,413 configuration fields). diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index 4e892aac67..575dab1813 100644 --- a/docs/evidence/spec-engine/us-f0-coverage.json +++ b/docs/evidence/spec-engine/us-f0-coverage.json @@ -6,7 +6,7 @@ "country": "us", "documentation_sha256": "fda6ec0dd925077f4d84d30a1c206dd81d82c5e16bd94506e81fe1b9f7e2f466", "field_usage": { - "authored_normative_field_count": 32624, + "authored_normative_field_count": 32627, "claim_count": 48, "claims": [ { @@ -16,8 +16,8 @@ "legacy_sinks": [], "mode": "front_end_validation", "pointer_class": "all", - "pointer_count": 119, - "pointer_sha256": "f93afb3400960c441ef522bd35cb56dffceef802eeaeab7aa63489d55d53f896", + "pointer_count": 122, + "pointer_sha256": "5887af82b9909867a4f39af35d63d857174c22509a036a5c94cdeeb7f5d27ac3", "rationale": null, "relative_sink_prefix": null, "source_prefix": "/authored/country_package.json", @@ -758,20 +758,20 @@ "verifier": "vintages" } ], - "configuration_field_count": 42410, - "consumed_field_count": 42410, + "configuration_field_count": 42413, + "consumed_field_count": 42413, "generation0_effect_counts": { "legacy_behavior": 38780, - "no_generation0_effect": 3630 + "no_generation0_effect": 3633 }, "mode_counts": { "compiler_semantic": 27674, - "front_end_validation": 364, + "front_end_validation": 367, "identity_only": 103, "legacy_behavior": 14269 }, "multiple_primary_use_field_count": 0, - "pointer_inventory_sha256": "bbf2213acf3453f09be80542c9b86f5571b6659ce196c1979be9961f0c0a6f66", + "pointer_inventory_sha256": "8e3b7c8680e0a5c5626867c1b697b6b6d98058b383c2f7d368f0b5b5df3105b1", "resolved_binding_field_count": 9786, "unused_field_count": 0 }, @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "c25fbed9c0d92248707f59101b516125f8437c42e2cebe84a72e28f6ac0f39c0" + "spec_sha256": "5035e939cc241ca9e94b9454a94e90e4450a4724d28aadb76026ee86d2442820" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "c25fbed9c0d92248707f59101b516125f8437c42e2cebe84a72e28f6ac0f39c0" + "spec_sha256": "5035e939cc241ca9e94b9454a94e90e4450a4724d28aadb76026ee86d2442820" }, "status": "pass" } diff --git a/docs/us-target-sets.md b/docs/us-target-sets.md index 5bde1f1a16..59850cb48d 100644 --- a/docs/us-target-sets.md +++ b/docs/us-target-sets.md @@ -131,3 +131,59 @@ Before the declarations, the local SNAP, Medicaid, `totals`, `full` and surface changes. On a feed with such rows at another level (for example county rows in the main feed), the declarations keep them out until a clause names the level. + +## Rows the local tool builds, and its hold-outs + +`us/local_target_construction.json` declares how the ACS local release builds +the targets that the compile does not give it. Shared, country-free modules +read each section (microcosm#1728): + +| Section | Shared module | What the section declares | +|---|---|---| +| `holdouts` | `microcosm.build.target_holdouts` | The district pass (`--soi-mode state_cd`) and the county pass (`state_county`): which records each pass writes (`scope`), which get a held unit (`eligible`), the unit key (`unit_fields`, with the concept-family rule), the salt, the default and largest fraction, the receipt keys, and how the held rows are scored against the pro-rata baseline. | +| `ladder_population` | `microcosm.build.ladder_population_targets` | The PUMA ladder's state and district levels: the target names, the household column of each level, the code fields of each record, the geography ids and the label lookup of each level. | + +The tool functions keep their names (`assign_target_roles`, +`calibration_target_set`, `score_cd_holdout`, `population_rows`, +`population_target_specs` and others) and call the shared modules. A record +has at least `name`, `value`, `family` and `geography_level`. The role pass +adds `holdout_unit` and `role`, and the training target set holds the +training rows only. + +Two parts of the local surface are still tool code. The district SOI shares +of `state_cd` (`tools/us_acs_local_cd_surface.py`) and the county rung +(`tools/us_acs_local_county_surface.py`) make child rows as shares of parent +rows. One nesting rule across all levels will replace them, together with the +district rows of microcosm#1731. + +## The compile registers + +`us/fiscal_target_registers.json` holds the reviewed registers of the US +fiscal target compile (`us_runtime/fiscal_targets.py` and +`us_runtime/source_vintage.py`). The shared +`microcosm.build.declared_registers` reads them. Each register keeps the +comments that stood beside it in the code, as its `description` and as the +`note` of an entry. + +| Register | What it holds | +|---|---| +| `support_exclusions`, `all_vintage_support_exclusions`, `exclusion_vintage_bypasses` | The facts the compile drops, with the reason for each, and their vintage scope. | +| `source_column_exclusions` | The IRS columns a package reads under a measure whose concept they do not carry (microcosm#1038). | +| `restamped_source_packages`, `later_period_observation_exemptions` | The source packages whose period stamp is wrong (microcosm#1030). | +| `soi_amount_measure_variables`, `soi_return_measure_variables`, `soi_variables`, `soi_base_variable_overrides` | The model variable of each IRS SOI measure and concept. | +| `direct_targets`, `indicator_targets` | The model variable, family and metadata of each direct and indicator Ledger target. | +| `m_chip_state_fips` | The M-CHIP states whose CHIP rows never calibrate (microcosm#321). | + +A section has a `key` (one field, or a list of fields for a tuple key), a +`value` (one field, a list of fields for a tuple value, or `null` for a set) +and its `entries` in order. JSON arrays read back as tuples. + +To change a register: + +1. Edit its entries. Give each new entry its reason or note. +2. Run `test_us_fiscal_target_registers.py`. It pins each register's digest + and, with the pinned feed, the compile under four flag sets and the + exclusion receipt. An intended change moves these pins: update them and + say which targets moved. +3. A change that moves the compile changes what the calibration fits, so a + build must measure it. diff --git a/packages/microcosm-build/src/microcosm/build/declared_registers.py b/packages/microcosm-build/src/microcosm/build/declared_registers.py new file mode 100644 index 0000000000..3a132830e9 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/declared_registers.py @@ -0,0 +1,173 @@ +"""Reviewed registers declared as data, for any country (microcosm#1728). + +A country keeps reviewed lists in its package: the facts its compile drops and +why, the source columns a package reads under the wrong measure, the source +packages whose period stamps are wrong, the variable each published measure +maps to. A JSON file (``version``, ``country``, ``description``, +``registers``) holds one section for each register: + +- ``description``: why the register exists and how the code reads it; +- ``key``: the entry fields that make the key. With one field the key is that + field's value; with several it is the tuple of their values, in order; +- ``value``: the entry field that is the value, a list of fields (the value is + the tuple of their values, in order), or null (the register is a set of + keys); +- ``entries``: the entries, in order. An entry may also carry a ``note``. + +A description or a note is a string or a list of lines. :func:`load_register` +reads one section. JSON arrays read back as tuples and JSON objects as dicts, +so a register reads back as the Python literal it replaces, in entry order. +Nothing here holds country data. +""" + +from __future__ import annotations + +import json +from collections.abc import Mapping +from functools import cache +from importlib.resources import files +from typing import Any + +__all__ = [ + "NOTE_FIELD", + "DeclaredRegisterError", + "load_register", + "package_register", + "package_registers", +] + +#: The optional entry field that explains one entry. +NOTE_FIELD = "note" + +_FILE_KEYS = frozenset({"version", "country", "description", "registers"}) +_SECTION_KEYS = frozenset({"description", "key", "value", "entries"}) + + +class DeclaredRegisterError(ValueError): + """A declared register is not valid.""" + + +def _text_or_lines(value: Any) -> bool: + if isinstance(value, str): + return bool(value) + return ( + isinstance(value, list) + and bool(value) + and all(isinstance(line, str) for line in value) + ) + + +def _frozen(value: Any) -> Any: + if isinstance(value, list): + return tuple(_frozen(item) for item in value) + if isinstance(value, dict): + return {key: _frozen(item) for key, item in value.items()} + return value + + +def _fields(value: Any, *, context: str, allow_none: bool) -> tuple[str, ...]: + if value is None and allow_none: + return () + if isinstance(value, str) and value: + return (value,) + if ( + isinstance(value, list) + and value + and all(isinstance(field, str) and field for field in value) + and len(set(value)) == len(value) + ): + return tuple(value) + raise DeclaredRegisterError( + f"{context} must be a field name or a list of distinct field names." + ) + + +def load_register(section: Mapping[str, Any], *, name: str = "register") -> Any: + """Read one declared register: a dict in entry order, or a frozenset of keys.""" + + if not isinstance(section, Mapping) or set(section) != _SECTION_KEYS: + raise DeclaredRegisterError( + f"Register {name!r} must hold exactly the keys {sorted(_SECTION_KEYS)}." + ) + if not _text_or_lines(section["description"]): + raise DeclaredRegisterError( + f"Register {name!r} description must be a string or a list of lines." + ) + key_fields = _fields(section["key"], context=f"{name} key", allow_none=False) + raw_value = section["value"] + value_fields = _fields(raw_value, context=f"{name} value", allow_none=True) + if set(key_fields) & set(value_fields) or NOTE_FIELD in { + *key_fields, + *value_fields, + }: + raise DeclaredRegisterError( + f"Register {name!r} key and value fields overlap or use {NOTE_FIELD!r}." + ) + entries = section["entries"] + if not isinstance(entries, list): + raise DeclaredRegisterError(f"Register {name!r} entries must be a list.") + fields = {*key_fields, *value_fields} + result: dict[Any, Any] = {} + for position, entry in enumerate(entries): + context = f"register {name!r} entry {position}" + if not isinstance(entry, Mapping): + raise DeclaredRegisterError(f"{context} must be an object.") + unknown = sorted(set(entry) - fields - {NOTE_FIELD}) + missing = sorted(fields - set(entry)) + if unknown or missing: + raise DeclaredRegisterError( + f"{context}: unknown fields {unknown}, missing fields {missing}." + ) + if NOTE_FIELD in entry and not _text_or_lines(entry[NOTE_FIELD]): + raise DeclaredRegisterError( + f"{context} note must be a string or a list of lines." + ) + key = ( + _frozen(entry[key_fields[0]]) + if len(key_fields) == 1 + else tuple(_frozen(entry[field]) for field in key_fields) + ) + if key in result: + raise DeclaredRegisterError(f"Register {name!r} repeats the key {key!r}.") + if raw_value is None: + result[key] = None + elif isinstance(raw_value, str): + result[key] = _frozen(entry[raw_value]) + else: + result[key] = tuple(_frozen(entry[field]) for field in value_fields) + if raw_value is None: + return frozenset(result) + return result + + +@cache +def package_registers(package: str, resource: str) -> Mapping[str, Any]: + """The register sections of a package's JSON resource, read and checked once.""" + + payload = json.loads(files(package).joinpath(resource).read_text(encoding="utf-8")) + if not isinstance(payload, dict) or set(payload) != _FILE_KEYS: + raise DeclaredRegisterError( + f"{package}/{resource} must hold exactly the keys {sorted(_FILE_KEYS)}." + ) + if payload["version"] != 1: + raise DeclaredRegisterError(f"{package}/{resource} must be version 1.") + if not isinstance(payload["country"], str) or not payload["country"]: + raise DeclaredRegisterError(f"{package}/{resource} must name its country.") + if not _text_or_lines(payload["description"]): + raise DeclaredRegisterError(f"{package}/{resource} needs a description.") + registers = payload["registers"] + if not isinstance(registers, dict) or not registers: + raise DeclaredRegisterError(f"{package}/{resource} declares no register.") + return registers + + +def package_register(package: str, resource: str, name: str) -> Any: + """Read one register of a package's JSON resource (see :func:`load_register`).""" + + registers = package_registers(package, resource) + if name not in registers: + raise DeclaredRegisterError( + f"{package}/{resource} declares no register {name!r}; it has " + f"{sorted(registers)}." + ) + return load_register(registers[name], name=name) diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py index 71b11bd0a8..94030a43c1 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py @@ -26,9 +26,9 @@ ) from .schemas import load_schema_registry -EXPECTED_AUTHORED_FIELD_COUNT = 32624 +EXPECTED_AUTHORED_FIELD_COUNT = 32627 EXPECTED_RESOLVED_BINDING_FIELD_COUNT = 9786 -EXPECTED_CONFIGURATION_FIELD_COUNT = 42410 +EXPECTED_CONFIGURATION_FIELD_COUNT = 42413 class FieldUsageError(AssertionError): @@ -369,8 +369,8 @@ def _path_inventory(rows: Sequence[tuple[str, object]]) -> tuple[int, str]: "bdd9e79157590fade42d28cc2b5d5c8b58e13903af75375a0e3235c94d2a8339", ), "country_manifest": ( - 119, - "f93afb3400960c441ef522bd35cb56dffceef802eeaeab7aa63489d55d53f896", + 122, + "5887af82b9909867a4f39af35d63d857174c22509a036a5c94cdeeb7f5d27ac3", ), "generated_authorities": ( 8_614, diff --git a/packages/microcosm-build/src/microcosm/build/us/country_package.json b/packages/microcosm-build/src/microcosm/build/us/country_package.json index 07aacdbc49..6a26bac48d 100644 --- a/packages/microcosm-build/src/microcosm/build/us/country_package.json +++ b/packages/microcosm-build/src/microcosm/build/us/country_package.json @@ -97,6 +97,11 @@ "kind": "legacy_json", "schema_id": "legacy_json" }, + { + "path": "fiscal_target_registers.json", + "kind": "legacy_json", + "schema_id": "legacy_json" + }, { "path": "fiscal_target_references.json", "kind": "legacy_json", diff --git a/packages/microcosm-build/src/microcosm/build/us/fiscal_target_registers.json b/packages/microcosm-build/src/microcosm/build/us/fiscal_target_registers.json new file mode 100644 index 0000000000..ac6f753c7d --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us/fiscal_target_registers.json @@ -0,0 +1,1559 @@ +{ + "version": 1, + "country": "us", + "description": [ + "The reviewed registers of the US fiscal target compile", + "(microcosm.build.us_runtime.fiscal_targets and source_vintage), declared as data", + "(microcosm#1728) and read by the shared microcosm.build.declared_registers.", + "Each register's description and notes are the comments that stood beside it in the code." + ], + "registers": { + "support_exclusions": { + "description": [ + "Facts the US compile drops, keyed by exact source_record_id, each with its reason.", + "all_vintage_support_exclusions widens an entry to every vintage of its cell, and", + "exclusion_vintage_bypasses lists the reviewed exceptions to the vintage scope check." + ], + "key": "source_record_id", + "value": "reason", + "entries": [ + { + "source_record_id": "irs_soi.ty2023.table_1_4.all.other_income_net_loss_amount", + "reason": "The PUF pipeline maps miscellaneous_income = E01200 (policyengine-us- data datasets/puf/puf.py), but E01200 is Form 4797 / Form 1040 line 14 business-property net gain or loss (IRS Research Bulletin 2017 Table A1), not the 'other income' line concept SOI Table 1.4 reports (Form 1040 line 21 in ty2015; Schedule 1 in later years) — microcosm#393's remedy experiments reached this final determination and the export-parity registry already carries it for the miscellaneous_income column. Both signs are therefore concept- mismatched, and the measured legs bear the 4797 reading: ty2015 E01200 as the pipeline ingests it (aggregate records removed) is two-sided ($22.84B positive on 1.09M returns vs $21.55B negative on 1.18M; $33.42B/$21.95B on the full raw file) while SOI ty2015 other income is heavily positive ($46.77B on 6.12M income returns vs $6.69B on 332,708 loss returns, with NOL a separate item at $197.5B on 1,138,112 returns; ty2023 keeps the concepts separate as items 91-94 vs 95-96, raw loss $12.21B on 318,839 returns before feed aging). Build P attempts 9/10 (microcosm#507) measured the consequence: the solve must crush truthful business-property loss mass to fit the loss rows ($34.3B design-weight truth vs $13.3B aged target), and the income row's historical +0.005% fit was free reweighting, not concept agreement. All four rows are excluded until the microcosm#393 remedy lands in full: remap E01200 to other_net_gain AND separately source or impute true miscellaneous income — a remap-only rebuild leaves miscellaneous_income zero/absent, so these exclusions lift only when both halves land." + }, + { + "source_record_id": "irs_soi.ty2023.table_1_4.all.other_income_net_loss_returns", + "reason": "Same Form 4797 concept mismatch as the other_income_net_loss_amount entry: E01200 carries Form 1040 line-14 business-property net gain/loss, not the SOI Table 1.4 line-21 'other income' concept, so this row compares incompatible concepts regardless of sign. Excluded until the microcosm#393 remedy lands in full (remap E01200 to other_net_gain AND separately source true miscellaneous income); see the loss-amount entry for the full adjudication." + }, + { + "source_record_id": "irs_soi.ty2023.table_1_4.all.other_income_net_income_amount", + "reason": "Same Form 4797 concept mismatch as the other_income_net_loss_amount entry: E01200 carries Form 1040 line-14 business-property net gain/loss, not the SOI Table 1.4 line-21 'other income' concept, so this row compares incompatible concepts regardless of sign. Excluded until the microcosm#393 remedy lands in full (remap E01200 to other_net_gain AND separately source true miscellaneous income); see the loss-amount entry for the full adjudication." + }, + { + "source_record_id": "irs_soi.ty2023.table_1_4.all.other_income_net_income_returns", + "reason": "Same Form 4797 concept mismatch as the other_income_net_loss_amount entry: E01200 carries Form 1040 line-14 business-property net gain/loss, not the SOI Table 1.4 line-21 'other income' concept, so this row compares incompatible concepts regardless of sign. Excluded until the microcosm#393 remedy lands in full (remap E01200 to other_net_gain AND separately source true miscellaneous income); see the loss-amount entry for the full adjudication." + }, + { + "source_record_id": "census_stc.fy2023.individual_income_tax_collections.tn.t40.collections", + "reason": "Tennessee has no modeled 2024 state individual income tax support in PolicyEngine-US; this STC residual collection row cannot be estimated from the current state_income_tax variable." + }, + { + "source_record_id": "census_stc.fy2024.individual_income_tax_collections.tn.t40.collections", + "reason": "Tennessee has no modeled 2024 state individual income tax support in PolicyEngine-US; this STC residual collection row cannot be estimated from the current state_income_tax variable." + }, + { + "source_record_id": "irs_soi.ty2022.historic_table_2.state_agi.vt.under_1.taxable_interest_amount", + "reason": "Current national CPS+PUF support has zero Vermont taxable-interest support in the under-$1 AGI slice; this narrow offset-income cell needs richer state/tail support before it can be calibrated. MEASURED on the Build P2 dense frame (base-P2 fca79b42, FULL 337,704-household pool, no selection, frame identity b54feb926c6e5396…, release populace-us-2024-buildp-dense-cae8640-20260728T050443Z): registry aggregates exactly 0.0 initial and final for both rows, household weights strictly positive (min 19.58), taxable_interest_income nonnegative with 201,242 positive person records (122,852 unique carrier households) pool-wide — the cell is unexpressible from the pool itself, not a sparse-selection artifact, which is the ia/nd class. A legacy Build P sparse-only register carried a redundant VT pair; this standing entry is now the sole surface-wide exclusion." + }, + { + "source_record_id": "irs_soi.ty2022.historic_table_2.state_agi.vt.under_1.taxable_interest_returns", + "reason": "Current national CPS+PUF support has zero Vermont taxable-interest support in the under-$1 AGI slice; this narrow offset-income cell needs richer state/tail support before it can be calibrated. MEASURED on the Build P2 dense frame (base-P2 fca79b42, FULL 337,704-household pool, no selection, frame identity b54feb926c6e5396…, release populace-us-2024-buildp-dense-cae8640-20260728T050443Z): registry aggregates exactly 0.0 initial and final for both rows, household weights strictly positive (min 19.58), taxable_interest_income nonnegative with 201,242 positive person records (122,852 unique carrier households) pool-wide — the cell is unexpressible from the pool itself, not a sparse-selection artifact, which is the ia/nd class. A legacy Build P sparse-only register carried a redundant VT pair; this standing entry is now the sole surface-wide exclusion." + }, + { + "source_record_id": "irs_soi.ty2022.historic_table_2.state_agi.ia.under_1.taxable_interest_amount", + "reason": "Current national CPS+PUF support has zero Iowa taxable-interest support in the under-$1 AGI slice; this narrow offset-income cell needs richer state/tail support before it can be calibrated." + }, + { + "source_record_id": "irs_soi.ty2022.historic_table_2.state_agi.ia.under_1.taxable_interest_returns", + "reason": "Current national CPS+PUF support has zero Iowa taxable-interest support in the under-$1 AGI slice; this narrow offset-income cell needs richer state/tail support before it can be calibrated." + }, + { + "source_record_id": "irs_soi.ty2022.historic_table_2.state_agi.nd.under_1.taxable_interest_amount", + "reason": "Current national CPS+PUF support has zero North Dakota taxable-interest support in the under-$1 AGI slice; this narrow offset-income cell needs richer state/tail support before it can be calibrated." + }, + { + "source_record_id": "irs_soi.ty2022.historic_table_2.state_agi.nd.under_1.taxable_interest_returns", + "reason": "Current national CPS+PUF support has zero North Dakota taxable-interest support in the under-$1 AGI slice; this narrow offset-income cell needs richer state/tail support before it can be calibrated." + }, + { + "source_record_id": "irs_soi.ty2023.form_w2_social_security_tips.box_7_social_security_tips.return_count", + "reason": "The SIPP tip stage now materializes tip_income (549 carriers, $9.9B weighted on certified Build M), but that support is under 1% of the 6.04M-return W-2 Box 7 class, so binding the return-count target would demand ~600x weight concentration on those carriers. The dollar-amount target binds first; the count target waits for tip support widening (PolicyEngine/microcosm#451 item 3). Every vintage of the cell is excluded (decision d179)." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.ar.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in Arkansas under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.az.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in Arizona under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.co.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in Colorado under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.ct.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in Connecticut under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.de.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in Delaware under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.ga.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in Georgia under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.id.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in Idaho under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.in.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in Indiana under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.ks.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in Kansas under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.ky.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in Kentucky under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.me.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in Maine under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.mi.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in Michigan under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.mt.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in Montana under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.nm.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in New Mexico under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.nv.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in Nevada under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.ok.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in Oklahoma under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.or.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in Oregon under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.pa.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in Pennsylvania under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.sd.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in South Dakota under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.tx.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in Texas under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.vt.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in Vermont under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "hhs_acf_tanf.fy2024.cash_assistance.wv.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds", + "reason": "Current 2024 base microdata have zero positive TANF benefit support in West Virginia under PolicyEngine-US state TANF formulas." + }, + { + "source_record_id": "irs_soi.ty2022.historic_table_2.state_agi.ak.under_1.return_count", + "reason": "Current 2024 base microdata have zero Alaska return-count support in the SOI under-$1 AGI bin." + }, + { + "source_record_id": "irs_soi.ty2022.historic_table_2.us.under_1.income_tax_before_credits_returns", + "reason": "Current 2024 base microdata have zero positive income-tax-before-credits support in the SOI under-$1 AGI bin." + }, + { + "source_record_id": "irs_soi.ty2022.historic_table_2.us.under_1.income_tax_before_credits_amount", + "reason": "Current 2024 base microdata have zero income-tax-before-credits amount support in the SOI under-$1 AGI bin." + }, + { + "source_record_id": "irs_soi.ty2022.historic_table_2.us.under_1.income_tax_liability_returns", + "reason": "Current 2024 base microdata have zero positive income-tax-liability support in the SOI under-$1 AGI bin." + }, + { + "source_record_id": "irs_soi.ty2022.historic_table_2.us.under_1.income_tax_liability_amount", + "reason": "Current 2024 base microdata have zero income-tax-liability amount support in the SOI under-$1 AGI bin." + }, + { + "source_record_id": "irs_soi.ty2022.historic_table_2.us.1_to_10k.taxable_income_returns", + "reason": "Current 2024 base microdata have zero positive taxable-income support in this SOI AGI bin." + }, + { + "source_record_id": "irs_soi.ty2022.historic_table_2.us.1_to_10k.taxable_income_amount", + "reason": "Current 2024 base microdata have zero taxable-income amount support in this SOI AGI bin." + }, + { + "source_record_id": "irs_soi.ty2022.historic_table_2.us.500k_to_1m.actc_claims", + "reason": "Current-law PolicyEngine-US refundable CTC support is zero in this high-income SOI AGI bin." + }, + { + "source_record_id": "irs_soi.ty2022.historic_table_2.us.500k_to_1m.actc_amount", + "reason": "Current-law PolicyEngine-US refundable CTC amount support is zero in this high-income SOI AGI bin." + }, + { + "source_record_id": "irs_soi.ty2022.historic_table_2.us.500k_to_1m.medical_dental_expense_returns", + "reason": "Current 2024 base microdata have zero positive medical-expense deduction support in this SOI AGI bin." + }, + { + "source_record_id": "irs_soi.ty2022.historic_table_2.us.500k_to_1m.medical_dental_expense_amount", + "reason": "Current 2024 base microdata have zero medical-expense deduction amount support in this SOI AGI bin." + }, + { + "source_record_id": "irs_soi.ty2022.historic_table_2.us.1m_plus.medical_dental_expense_returns", + "reason": "Current 2024 base microdata have zero positive medical-expense deduction support in this SOI AGI bin." + }, + { + "source_record_id": "irs_soi.ty2022.historic_table_2.us.1m_plus.medical_dental_expense_amount", + "reason": "Current 2024 base microdata have zero medical-expense deduction amount support in this SOI AGI bin." + } + ] + }, + "all_vintage_support_exclusions": { + "description": [ + "The register above is keyed by exact source_record_id, and latest-vintage", + "selection activates the newest remaining fact for each target shape, so", + "excluding one vintage of a cell hands its key to the next vintage the feed", + "carries. The 2026-09-18 feed re-pin (docs/us-chronicle-feed-repin.md) added", + "SOI Table 1.4 cells for ty2020-2022, and the ty2022 other-income rows then", + "calibrated in place of the excluded ty2023 rows (microcosm#956). A fact", + "matches an entry here when its source_record_id equals the entry's once", + "period tokens are stripped (_period_free_source_record_id), so each entry", + "drops every vintage of its cell:", + "", + "- the four #564 other-income rows: the Form 4797 concept mismatch does not", + " depend on the tax year;", + "- the #451 W-2 Box 7 tips return count: tip support is thin at every", + " vintage, and the ty2020 fact carries the same 6,038,613 returns as the", + " excluded ty2023 row (the pinned feed's ty2023 W-2 record sets come from", + " the soi-w2-statistics-2020 package, chronicle_feed_scope.json). The July", + " feed (consumer_facts_buildn_v9_4, facts b3c0835...) carried only the", + " ty2020 vintage, so the ty2023-keyed exclusion matched nothing and the", + " row calibrated (-52% in experiments/replacement_scorecard/", + " incumbent_48b9d479.md). The pinned feed carries both, latest-vintage", + " fallback selected ty2020, and #1016 kept it as the one reviewed vintage", + " bypass until decision d179 ruled to enforce #451 at every vintage." + ], + "key": "source_record_id", + "value": null, + "entries": [ + { + "source_record_id": "irs_soi.ty2023.form_w2_social_security_tips.box_7_social_security_tips.return_count" + }, + { + "source_record_id": "irs_soi.ty2023.table_1_4.all.other_income_net_income_amount" + }, + { + "source_record_id": "irs_soi.ty2023.table_1_4.all.other_income_net_income_returns" + }, + { + "source_record_id": "irs_soi.ty2023.table_1_4.all.other_income_net_loss_amount" + }, + { + "source_record_id": "irs_soi.ty2023.table_1_4.all.other_income_net_loss_returns" + } + ] + }, + "exclusion_vintage_bypasses": { + "description": [ + "Reviewed vintage bypasses. Every other exclusion stays keyed to its exact", + "vintage, and the compile refuses a selected fact that is another vintage of", + "an excluded cell (_check_exclusion_vintage_scope) unless its id is listed", + "here with a reason. Removing an entry is mechanical; adding one needs review.", + "Empty since decision d179 scoped the ty2020 tips return count's exclusion to", + "every vintage." + ], + "key": "source_record_id", + "value": "reason", + "entries": [] + }, + "source_column_exclusions": { + "description": [ + "Reviewed source-column concept exclusions (microcosm#1038). Each entry is an", + "IRS column that a Chronicle package publishes under a measure id whose", + "concept the column does not carry, so no fact read from that column", + "compiles, whatever its package, geography or vintage, and a package", + "corrected to read the right column passes untouched. The key is (measure_id,", + "layout.source_column_id) because the IRS column is the definition. The", + "congressional-district documentation guide (22incddocguide.docx) defines:", + "", + "- N18425/A18425 as \"State and local income taxes\" (Schedule A line 5a) and", + " N18460/A18460 as \"Limited state and local taxes\" (line 5e). salt_deduction,", + " like the Historic Table 2 rows of these measure ids, is the limited line 5e", + " deduction.", + "- N85530/A85530 as \"Additional Medicare tax\" (Form 8959 line 24) and", + " N85770/A85770 as \"Total premium tax credit\" (Form 8962 line 24; the guide", + " prints \"8926:24\"). N85770/A85770 is what the Historic Table 2 rows of", + " these measure ids read and what assigned_aca_ptc measures. The amount was", + " dropped before by a hard-coded congressional-district check; the returns", + " row compiled as premium-tax-credit recipients. A package corrected to read", + " N85770/A85770 compiles as assigned_aca_ptc targets with no further gate,", + " which is intended: those columns are the premium tax credit.", + "", + "Chronicle's congressional_district_2022 package reads these four columns", + "under the limited_state_local_taxes_* and premium_tax_credit_* measure ids;", + "the 46 other measures it shares with a Historic Table 2 package read the", + "same column there. Of the six it has alone, interest_paid_deduction_* reads", + "N19300/A19300, \"Mortgage interest paid\" (Schedule A line 8a), while", + "interest_deduction is the line 10 total (lines 8a-8c plus investment", + "interest on line 9; 8a is 85.6% of it in the TY2022 US row). That is a", + "component of the measure's concept, not another concept, so it is not", + "listed here: like the line 7 capital-gains rows, it needs a share-or-drop", + "decision of its own, which also binds the state_cd surface's itemized", + "bridge.", + "A congressional-district fact of a listed measure that carries no", + "layout.source_column_id refuses the compile, so a feed schema change cannot", + "silently lift the exclusion." + ], + "key": [ + "measure_id", + "source_column_id" + ], + "value": "reason", + "entries": [ + { + "measure_id": "limited_state_local_taxes_returns", + "source_column_id": "N18425", + "reason": "N18425 counts returns with state and local income taxes (Schedule A line 5a), not returns with the limited state and local tax deduction (line 5e, N18460). Chronicle's congressional_district_2022 package reads it under this measure id: TY2022 US 10,842,580 returns against 14,777,040 for N18460 in the same file and 14,968,720 in Historic Table 2." + }, + { + "measure_id": "limited_state_local_taxes_amount", + "source_column_id": "A18425", + "reason": "A18425 is state and local income taxes before the $10,000 limit (Schedule A line 5a), not the limited deduction (line 5e, A18460) salt_deduction measures. Chronicle's congressional_district_2022 package reads it under this measure id: TY2022 US $250.4B against $121.2B for A18460 in the same file, so on the full surface the congressional-district rows summed to 1.98x the national Historic Table 2 target." + }, + { + "measure_id": "premium_tax_credit_returns", + "source_column_id": "N85530", + "reason": "N85530 counts returns with additional Medicare tax (Form 8959 line 24), not returns with the premium tax credit (Form 8962 line 24, N85770) assigned_aca_ptc measures. Chronicle's congressional_district_2022 package reads it under this measure id: TY2022 US 6,848,330 returns against 7,713,000 for N85770 in the same file." + }, + { + "measure_id": "premium_tax_credit_amount", + "source_column_id": "A85530", + "reason": "A85530 is additional Medicare tax (Form 8959 line 24), not the premium tax credit (Form 8962 line 24, A85770). Chronicle's congressional_district_2022 package reads it under this measure id: TY2022 US $14.2B against $53.1B for A85770 in the same file." + } + ] + }, + "soi_amount_measure_variables": { + "description": [ + "The model variable each IRS SOI amount measure (source_measure_id) maps to.", + "The compile reads a measure here first, then in soi_return_measure_variables." + ], + "key": "measure_id", + "value": "variable", + "entries": [ + { + "measure_id": "adjusted_gross_income", + "variable": "adjusted_gross_income" + }, + { + "measure_id": "actc_amount", + "variable": "refundable_ctc" + }, + { + "measure_id": "ctc_amount", + "variable": "ctc" + }, + { + "measure_id": "eitc_amount", + "variable": "eitc" + }, + { + "measure_id": "eitc_no_children_amount", + "variable": "eitc" + }, + { + "measure_id": "eitc_one_child_amount", + "variable": "eitc" + }, + { + "measure_id": "eitc_three_or_more_children_amount", + "variable": "eitc" + }, + { + "measure_id": "eitc_total", + "variable": "eitc" + }, + { + "measure_id": "eitc_two_children_amount", + "variable": "eitc" + }, + { + "measure_id": "income_tax_before_credits_amount", + "variable": "income_tax_before_credits" + }, + { + "measure_id": "income_tax_liability_amount", + "variable": "income_tax" + }, + { + "measure_id": "interest_paid_deduction_amount", + "variable": "interest_deduction" + }, + { + "measure_id": "itemized_deductions_amount", + "variable": "itemized_taxable_income_deductions" + }, + { + "measure_id": "limited_state_local_taxes_amount", + "variable": "salt_deduction" + }, + { + "measure_id": "medical_dental_expense_amount", + "variable": "medical_expense_deduction" + }, + { + "measure_id": "net_capital_gains_amount", + "variable": "capital_gains_gross" + }, + { + "measure_id": "ordinary_dividends_amount", + "variable": "ordinary_dividends" + }, + { + "measure_id": "partnership_scorp_income_amount", + "variable": "partnership_and_s_corp_income" + }, + { + "measure_id": "premium_tax_credit_amount", + "variable": "assigned_aca_ptc" + }, + { + "measure_id": "qualified_business_income_deduction_amount", + "variable": "qualified_business_income_deduction" + }, + { + "measure_id": "qualified_dividends_amount", + "variable": "qualified_dividends" + }, + { + "measure_id": "real_estate_taxes_amount", + "variable": "real_estate_taxes" + }, + { + "measure_id": "rental_royalty_income_amount", + "variable": "rent_and_royalty_net_income" + }, + { + "measure_id": "schedule_c_income_amount", + "variable": "business_net_profits" + }, + { + "measure_id": "tax_exempt_interest_amount", + "variable": "tax_exempt_interest_income" + }, + { + "measure_id": "tax_filer_individual_count", + "variable": "tax_filer_individual_count" + }, + { + "measure_id": "taxable_income_amount", + "variable": "taxable_income" + }, + { + "measure_id": "taxable_interest_amount", + "variable": "taxable_interest_income" + }, + { + "measure_id": "taxable_ira_distributions_amount", + "variable": "ira_distributions" + }, + { + "measure_id": "taxable_pension_income_amount", + "variable": "taxable_pension_income" + }, + { + "measure_id": "taxable_social_security_amount", + "variable": "taxable_social_security" + }, + { + "measure_id": "total_itemized_deductions_amount", + "variable": "itemized_taxable_income_deductions" + }, + { + "measure_id": "total_earned_income_credit_amount", + "variable": "eitc" + }, + { + "measure_id": "unemployment_compensation_amount", + "variable": "unemployment_compensation" + }, + { + "measure_id": "wages_salaries_amount", + "variable": "employment_income" + }, + { + "measure_id": "charitable_amount", + "variable": "charitable_deduction" + }, + { + "measure_id": "estate_trust_net_income_amount", + "variable": "estate_income", + "note": [ + "Build H (microcosm#299): SOI Table 1.4 income/loss lines that identify the", + "floating export-input columns. Income legs sum the positive part of the", + "signed model variable, loss legs the negative-part magnitude", + "(see _signed_component), matching SOI's returns-with-net-income vs", + "returns-with-net-loss split. estate_income and miscellaneous_income are", + "export columns with reviewed exclusions in", + "US_EXPORT_INPUT_MASS_REVIEWED_EXCLUSIONS", + "(tools/build_us_fiscal_refresh_release.py), so the export-mass gate does", + "not check their drift. The estate rows pin estate_income to SOI. The", + "other-income rows compile to no target at any vintage", + "(US_FISCAL_TARGET_ALL_VINTAGE_SUPPORT_EXCLUSIONS, microcosm#393), so no", + "SOI line pins miscellaneous_income today. Both move federal income tax.", + "In policyengine-us 2.2.1 and 2.23.2 a non-dependent's positive", + "miscellaneous_income is gross income; loss_ald deducts estate_income", + "losses above the line, subject to the section 461(l) limit; and", + "estate_income counts toward qualified business income while", + "estate_income_would_be_qualified is true (the default). From 2.23.2", + "(PolicyEngine/policyengine-us#9633) a non-dependent's positive", + "estate_income is also gross income, and so AGI, and a non-dependent's", + "signed estate_income plus the Schedule K-1 (Form 1041) box 14 code H", + "adjustment enters net investment income." + ] + }, + { + "measure_id": "estate_trust_net_loss_amount", + "variable": "estate_losses" + }, + { + "measure_id": "other_income_net_income_amount", + "variable": "miscellaneous_income" + }, + { + "measure_id": "other_income_net_loss_amount", + "variable": "miscellaneous_losses" + }, + { + "measure_id": "partnership_net_income_amount", + "variable": "partnership_income", + "note": [ + "SOI Table 1.4 publishes partnership and S corporation net income and net", + "loss separately from TY2021 (Chronicle's table_1_4 measure ids; losses", + "are positive magnitudes). Each entity leg binds that entity's own Schedule", + "E line-32 leaf, summed to the return, positive part for net income and", + "negative-part magnitude for net loss (microcosm#1258)." + ] + }, + { + "measure_id": "partnership_net_loss_amount", + "variable": "partnership_losses" + }, + { + "measure_id": "s_corporation_net_income_amount", + "variable": "s_corp_income" + }, + { + "measure_id": "s_corporation_net_loss_amount", + "variable": "s_corp_losses" + }, + { + "measure_id": "capital_gain_distributions_amount", + "variable": "non_sch_d_capital_gains", + "note": [ + "SOI Table 1.4 \"capital gain distributions reported on Form 1040\" ==", + "PUF E01100 == PolicyEngine-US non_sch_d_capital_gains (Form 1040 line 7", + "when Schedule D is not required); concept-confirmed against pe-us source." + ] + }, + { + "measure_id": "home_mortgage_interest_amount", + "variable": "deductible_mortgage_interest", + "note": [ + "Build H (microcosm#299): SOI Table 2.1 \"Home mortgage interest\" itemized-", + "deduction total (financial-institution + personal-seller legs summed;", + "TY2023 $171,364,787,000 / 11,644,348 returns; CBO-aged ~$186.3B@2024).", + "The record set irs_soi.ty2023.table_2_1.itemized_all_returns makes", + "_soi_return_universe_from_record_set_id -> \"itemized_returns\", so", + "_soi_reference_from_fact auto-stamps itemized_only=true and the target", + "sums the model variable over ITEMIZERS ONLY -- the correct universe for a", + "Schedule-A line. Only the CW/CX \"Total\" measure is mapped; the two leg", + "measures (mortgage_interest_paid_*, home_mortgage_personal_seller_*) stay", + "unmapped to avoid double-counting.", + "", + "microcosm#511: the SOI line is the amount DEDUCTED on Schedule A, i.e.", + "after the section 163(h)(3) acquisition-debt caps, so the target maps to", + "the engine's capped deductible_mortgage_interest_tax_unit rather than the", + "gross home_mortgage_interest export input Build H used. On certified O-1", + "the gross column summed $241.3B over itemizers (+29.5%) while the capped", + "concept summed $214.2B (+15.0%) against the $186.3B aged fact -- the cap", + "haircut alone was a $27.1B pure concept gap. The capped formula is linear", + "in the first/second_home_mortgage_interest export inputs (balances and", + "origination years only set the deductible share), so calibration keeps", + "the same pull-through to the export mass that Build H wanted. A", + "positive-balance unit's deductible share is always positive; gross and", + "structural carriers are independently imputed, so equality is a data", + "property, verified on O-1 post-itemizer-mask (identical weighted carrier", + "totals; the only gross-vs-structural divergent units are non-itemizers).", + "The residual overshoot is the donor-side E19200 total-interest lineage", + "(microcosm#515, #487-adjacent)." + ] + } + ] + }, + "soi_return_measure_variables": { + "description": [ + "The model variable each IRS SOI return-count measure (source_measure_id) maps to:", + "the count is of tax units with a positive value of that variable." + ], + "key": "measure_id", + "value": "variable", + "entries": [ + { + "measure_id": "actc_claims", + "variable": "refundable_ctc" + }, + { + "measure_id": "ctc_claims", + "variable": "ctc" + }, + { + "measure_id": "eitc_claims", + "variable": "eitc" + }, + { + "measure_id": "eitc_no_children_claims", + "variable": "eitc" + }, + { + "measure_id": "eitc_one_child_claims", + "variable": "eitc" + }, + { + "measure_id": "eitc_returns", + "variable": "eitc" + }, + { + "measure_id": "eitc_three_or_more_children_claims", + "variable": "eitc" + }, + { + "measure_id": "eitc_two_children_claims", + "variable": "eitc" + }, + { + "measure_id": "income_tax_before_credits_returns", + "variable": "income_tax_before_credits" + }, + { + "measure_id": "income_tax_liability_returns", + "variable": "income_tax" + }, + { + "measure_id": "interest_paid_deduction_returns", + "variable": "interest_deduction" + }, + { + "measure_id": "limited_state_local_taxes_returns", + "variable": "salt_deduction" + }, + { + "measure_id": "medical_dental_expense_returns", + "variable": "medical_expense_deduction" + }, + { + "measure_id": "net_capital_gains_returns", + "variable": "capital_gains_gross" + }, + { + "measure_id": "ordinary_dividends_returns", + "variable": "ordinary_dividends" + }, + { + "measure_id": "partnership_scorp_income_returns", + "variable": "partnership_and_s_corp_income" + }, + { + "measure_id": "premium_tax_credit_returns", + "variable": "assigned_aca_ptc" + }, + { + "measure_id": "qualified_business_income_deduction_returns", + "variable": "qualified_business_income_deduction" + }, + { + "measure_id": "qualified_dividends_returns", + "variable": "qualified_dividends" + }, + { + "measure_id": "real_estate_taxes_claims", + "variable": "real_estate_taxes" + }, + { + "measure_id": "rental_royalty_income_returns", + "variable": "rent_and_royalty_net_income" + }, + { + "measure_id": "return_count", + "variable": "count" + }, + { + "measure_id": "schedule_c_income_returns", + "variable": "business_net_profits" + }, + { + "measure_id": "tax_exempt_interest_returns", + "variable": "tax_exempt_interest_income" + }, + { + "measure_id": "taxable_income_returns", + "variable": "taxable_income" + }, + { + "measure_id": "taxable_interest_returns", + "variable": "taxable_interest_income" + }, + { + "measure_id": "taxable_ira_distributions_returns", + "variable": "ira_distributions" + }, + { + "measure_id": "taxable_pension_income_returns", + "variable": "taxable_pension_income" + }, + { + "measure_id": "taxable_social_security_returns", + "variable": "taxable_social_security" + }, + { + "measure_id": "total_earned_income_credit_returns", + "variable": "eitc" + }, + { + "measure_id": "unemployment_compensation_returns", + "variable": "unemployment_compensation" + }, + { + "measure_id": "wages_salaries_returns", + "variable": "employment_income" + }, + { + "measure_id": "charitable_returns", + "variable": "charitable_deduction" + }, + { + "measure_id": "estate_trust_net_income_returns", + "variable": "estate_income", + "note": [ + "Build H (microcosm#299): return counts paired with the Table 1.4 income/", + "loss amount lines above (indicator sums of the signed model variable's", + "positive / negative part)." + ] + }, + { + "measure_id": "estate_trust_net_loss_returns", + "variable": "estate_losses" + }, + { + "measure_id": "other_income_net_income_returns", + "variable": "miscellaneous_income" + }, + { + "measure_id": "other_income_net_loss_returns", + "variable": "miscellaneous_losses" + }, + { + "measure_id": "partnership_net_income_returns", + "variable": "partnership_income", + "note": [ + "microcosm#1258: return counts paired with the Table 1.4 partnership and", + "S corporation legs above." + ] + }, + { + "measure_id": "partnership_net_loss_returns", + "variable": "partnership_losses" + }, + { + "measure_id": "s_corporation_net_income_returns", + "variable": "s_corp_income" + }, + { + "measure_id": "s_corporation_net_loss_returns", + "variable": "s_corp_losses" + }, + { + "measure_id": "capital_gain_distributions_returns", + "variable": "non_sch_d_capital_gains" + }, + { + "measure_id": "home_mortgage_interest_returns", + "variable": "deductible_mortgage_interest", + "note": [ + "Build H (microcosm#299): return count paired with the Table 2.1 home", + "mortgage interest amount above (indicator sum over itemizers claiming a", + "home mortgage interest deduction). microcosm#511: indicator over the same", + "capped concept as the amount row. The deductible share is positive", + "wherever a positive mortgage balance backs positive interest; carrier", + "equality with the old gross indicator is a data property (independently", + "imputed columns), verified on O-1 post-itemizer-mask." + ] + } + ] + }, + "soi_variables": { + "description": [ + "The model variable of each SOI concept variable. A concept in", + "soi_base_variable_overrides materializes from several base variables instead." + ], + "key": "soi_variable", + "value": "variable", + "entries": [ + { + "soi_variable": "adjusted_gross_income", + "variable": "adjusted_gross_income" + }, + { + "soi_variable": "business_net_profits", + "variable": "self_employment_income" + }, + { + "soi_variable": "business_net_losses", + "variable": "self_employment_income" + }, + { + "soi_variable": "capital_gains_distributions", + "variable": "capital_gains" + }, + { + "soi_variable": "capital_gains_gross", + "variable": "capital_gains" + }, + { + "soi_variable": "capital_gains_losses", + "variable": "capital_losses" + }, + { + "soi_variable": "charitable_deduction", + "variable": "charitable_deduction" + }, + { + "soi_variable": "ctc", + "variable": "ctc" + }, + { + "soi_variable": "employment_income", + "variable": "employment_income" + }, + { + "soi_variable": "eitc", + "variable": "eitc" + }, + { + "soi_variable": "estate_income", + "variable": "estate_income" + }, + { + "soi_variable": "estate_losses", + "variable": "estate_income" + }, + { + "soi_variable": "miscellaneous_income", + "variable": "miscellaneous_income", + "note": [ + "Build H (microcosm#299): concept -> signed model column for the export", + "dimensions identified by SOI Table 1.4. income/loss concept pairs share", + "one signed column (same pattern as business/rent/partnership above);", + "_signed_component takes the positive part for the income concept and the", + "negative-part magnitude for the \"_losses\" concept." + ] + }, + { + "soi_variable": "miscellaneous_losses", + "variable": "miscellaneous_income" + }, + { + "soi_variable": "non_sch_d_capital_gains", + "variable": "non_sch_d_capital_gains" + }, + { + "soi_variable": "deductible_mortgage_interest", + "variable": "deductible_mortgage_interest_tax_unit", + "note": [ + "microcosm#511 (supersedes the Build H gross mapping): SOI Table 2.1 home", + "mortgage interest is the amount deducted on Schedule A, post the section", + "163(h)(3) acquisition-debt caps, so the concept maps to the engine's", + "capped tax-unit aggregate. itemized_only masking (auto from the", + "itemized_all_returns record set, plus the concept's membership in", + "_SOI_ITEMIZED_ONLY_VARIABLES) restricts the sum to itemizers, matching", + "the Schedule-A universe." + ] + }, + { + "soi_variable": "exempt_interest", + "variable": "tax_exempt_interest_income" + }, + { + "soi_variable": "income_tax", + "variable": "income_tax" + }, + { + "soi_variable": "income_tax_before_credits", + "variable": "income_tax_before_credits" + }, + { + "soi_variable": "interest_deduction", + "variable": "interest_deduction" + }, + { + "soi_variable": "ira_distributions", + "variable": "taxable_ira_distributions" + }, + { + "soi_variable": "itemized_taxable_income_deductions", + "variable": "itemized_taxable_income_deductions" + }, + { + "soi_variable": "medical_expense_deduction", + "variable": "medical_expense_deduction" + }, + { + "soi_variable": "ordinary_dividends", + "variable": "ordinary_dividend_income" + }, + { + "soi_variable": "partnership_and_s_corp_income", + "variable": "tax_unit_partnership_s_corp_income" + }, + { + "soi_variable": "partnership_and_s_corp_losses", + "variable": "tax_unit_partnership_s_corp_income" + }, + { + "soi_variable": "partnership_income", + "variable": "partnership_income", + "note": [ + "microcosm#1258: Table 1.4's entity legs read each entity's own person", + "leaf; the materializer sums it to the tax unit before taking the part." + ] + }, + { + "soi_variable": "partnership_losses", + "variable": "partnership_income" + }, + { + "soi_variable": "s_corp_income", + "variable": "s_corp_income" + }, + { + "soi_variable": "s_corp_losses", + "variable": "s_corp_income" + }, + { + "soi_variable": "assigned_aca_ptc", + "variable": "assigned_aca_ptc" + }, + { + "soi_variable": "qualified_business_income_deduction", + "variable": "qualified_business_income_deduction" + }, + { + "soi_variable": "qualified_dividends", + "variable": "qualified_dividend_income" + }, + { + "soi_variable": "real_estate_taxes", + "variable": "real_estate_taxes" + }, + { + "soi_variable": "rent_and_royalty_net_income", + "variable": "rent_and_royalty_net_income" + }, + { + "soi_variable": "rent_and_royalty_net_losses", + "variable": "rent_and_royalty_net_income" + }, + { + "soi_variable": "refundable_ctc", + "variable": "refundable_ctc" + }, + { + "soi_variable": "salt_deduction", + "variable": "salt_deduction" + }, + { + "soi_variable": "tax_exempt_interest_income", + "variable": "tax_exempt_interest_income" + }, + { + "soi_variable": "taxable_income", + "variable": "taxable_income" + }, + { + "soi_variable": "taxable_interest_income", + "variable": "taxable_interest_income" + }, + { + "soi_variable": "tax_filer_individual_count", + "variable": "tax_unit_size" + }, + { + "soi_variable": "taxable_pension_income", + "variable": "taxable_pension_income" + }, + { + "soi_variable": "taxable_social_security", + "variable": "tax_unit_taxable_social_security" + }, + { + "soi_variable": "tip_income", + "variable": "tip_income" + }, + { + "soi_variable": "total_pension_income", + "variable": "pension_income" + }, + { + "soi_variable": "total_social_security", + "variable": "tax_unit_social_security" + }, + { + "soi_variable": "unemployment_compensation", + "variable": "unemployment_compensation" + } + ] + }, + "soi_base_variable_overrides": { + "description": [ + "SOI concept variables that materialize from several base model variables." + ], + "key": "soi_variable", + "value": "base_variables", + "entries": [ + { + "soi_variable": "ctc", + "base_variables": [ + "ctc", + "ctc_limiting_tax_liability" + ] + }, + { + "soi_variable": "ordinary_dividends", + "base_variables": [ + "qualified_dividend_income", + "non_qualified_dividend_income" + ] + }, + { + "soi_variable": "rent_and_royalty_net_income", + "base_variables": [ + "rental_income", + "farm_rent_income" + ] + }, + { + "soi_variable": "rent_and_royalty_net_losses", + "base_variables": [ + "rental_income", + "farm_rent_income" + ] + } + ] + }, + "direct_targets": { + "description": [ + "Direct Ledger targets. A fact of (source, measure_id, groupby_value_id) compiles to", + "the listed model variable, target family and metadata. The compile tries the fact's", + "own groupby value first, then the entry with a null groupby_value_id." + ], + "key": [ + "source", + "measure_id", + "groupby_value_id" + ], + "value": [ + "variable", + "family", + "metadata" + ], + "entries": [ + { + "source": "cbo", + "measure_id": "projected_amount", + "groupby_value_id": "adjusted_gross_income", + "variable": "adjusted_gross_income", + "family": "cbo", + "metadata": { + "target_role": "cbo_adjusted_gross_income" + } + }, + { + "source": "cbo", + "measure_id": "projected_amount", + "groupby_value_id": "wages_and_salaries", + "variable": "employment_income", + "family": "cbo", + "metadata": { + "target_role": "cbo_wages_and_salaries" + } + }, + { + "source": "cbo", + "measure_id": "projected_amount", + "groupby_value_id": "qualified_dividend_income", + "variable": "qualified_dividend_income", + "family": "cbo", + "metadata": { + "target_role": "cbo_qualified_dividend_income" + } + }, + { + "source": "cbo", + "measure_id": "projected_amount", + "groupby_value_id": "net_capital_gain", + "variable": "capital_gains", + "family": "cbo", + "metadata": { + "target_role": "cbo_net_capital_gain" + } + }, + { + "source": "cbo", + "measure_id": "projected_amount", + "groupby_value_id": "net_business_income", + "variable": "cbo_net_business_income", + "family": "cbo", + "metadata": { + "target_role": "cbo_net_business_income" + } + }, + { + "source": "ssa", + "measure_id": "payment_amount", + "groupby_value_id": "social_security_benefits", + "variable": "social_security", + "family": "ssa", + "metadata": { + "target_role": "social_security_total" + } + }, + { + "source": "ssa", + "measure_id": "payment_amount", + "groupby_value_id": "social_security_retirement_benefits", + "variable": "social_security_retirement", + "family": "ssa", + "metadata": { + "target_role": "ssa_retirement_total" + } + }, + { + "source": "ssa", + "measure_id": "payment_amount", + "groupby_value_id": "social_security_disability_benefits", + "variable": "social_security_disability", + "family": "ssa", + "metadata": { + "target_role": "ssa_disability_total" + } + }, + { + "source": "ssa", + "measure_id": "payment_amount", + "groupby_value_id": "social_security_survivors_benefits", + "variable": "social_security_survivors", + "family": "ssa", + "metadata": { + "target_role": "ssa_survivors_total" + } + }, + { + "source": "ssa", + "measure_id": "payment_amount", + "groupby_value_id": "social_security_dependents_benefits", + "variable": "social_security_dependents", + "family": "ssa", + "metadata": { + "target_role": "ssa_dependents_total" + } + }, + { + "source": "ssa", + "measure_id": "payment_amount", + "groupby_value_id": "ssi_payments", + "variable": "ssi", + "family": "ssa", + "metadata": { + "target_role": "ssi_total" + } + }, + { + "source": "usda_snap", + "measure_id": "total_benefits", + "groupby_value_id": null, + "variable": "snap", + "family": "usda_snap", + "metadata": { + "target_role": "snap_total" + } + }, + { + "source": "hhs_acf_tanf", + "measure_id": "all_funds", + "groupby_value_id": null, + "variable": "tanf", + "family": "hhs_acf_tanf", + "metadata": { + "target_role": "tanf_total" + } + }, + { + "source": "cms_nhe", + "measure_id": "expenditure_amount", + "groupby_value_id": "medicaid_title_xix", + "variable": "medicaid", + "family": "cms_medicaid", + "metadata": { + "target_role": "medicaid_spending", + "calibration_role": "validation_only", + "exclusion_reason": "PolicyEngine-US allocates medicaid spending from state totals through person_weight-dependent denominators. Reweighting then recomputes per-person medicaid costs, so this is not a linear calibration row." + } + }, + { + "source": "cms_medicare", + "measure_id": "actual_amount", + "groupby_value_id": "premiums_from_enrollees", + "variable": "gross_medicare_part_b_premium_if_enrolled", + "family": "cms_medicare", + "metadata": { + "target_role": "medicare_part_b_premium_total" + }, + "note": [ + "2025 Trustees Report Table III.C3 Part B premiums from enrollees.", + "gross_medicare_part_b_premium is defined for is_medicare_eligible, so", + "it also charges eligible people who never enrolled. PolicyEngine-US", + "documents the enrollment-gated gross_medicare_part_b_premium_if_enrolled", + "for CMS premiums-from-enrollees targets (microcosm#1206).", + "The target includes income-related premiums (IRMAA). On the locked", + "policyengine-us 2.2.1 a 2024 release has none, because IRMAA rests on", + "income two years earlier and the H5 carries 2024 inputs only, so this", + "row reads the standard premium alone until Microcosm's engine includes", + "PolicyEngine/policyengine-us#10106 (see microcosm#1206 for the sums)." + ] + }, + { + "source": "federal_reserve", + "measure_id": "amount_outstanding", + "groupby_value_id": "fl152090005", + "variable": "net_worth", + "family": "federal_reserve", + "metadata": { + "target_role": "household_net_worth" + }, + "note": [ + "Household net worth: the retired us-data/eCPS pipeline calibrated a", + "national wealth control (loss.py \"net_worth\", PR #282). Per-household", + "net_worth is SCF-imputed and fixed, so the weighted sum is linear in the", + "reweighting weights — a valid direct-sum target that pins the post-reweight", + "aggregate the input-stage SCF imputation does not. Federal Reserve Z.1", + "series BOGZ1FL192090005Q (households & nonprofits net worth)." + ] + } + ] + }, + "indicator_targets": { + "description": [ + "Indicator Ledger targets. A fact of (source, measure_id) compiles to an indicator", + "sum over the listed base variable or variables, with the listed family and metadata." + ], + "key": [ + "source", + "measure_id" + ], + "value": [ + "base_variables", + "family", + "metadata" + ], + "entries": [ + { + "source": "cms_aca", + "measure_id": "marketplace_enrollment", + "base_variables": "has_marketplace_health_coverage_at_interview", + "family": "cms_aca", + "metadata": { + "target_role": "aca_enrollment" + } + }, + { + "source": "cms_aca", + "measure_id": "aptc_recipients", + "base_variables": "assigned_aca_ptc", + "family": "cms_aca", + "metadata": { + "target_role": "aca_ptc_recipients", + "indicator_map_to": "person", + "indicator_filter_variable": "is_aca_ptc_eligible" + }, + "note": [ + "CMS reports APTC recipients as people. We proxy this as an indicator-sum", + "over eligible people in tax units with positive assigned PTC: the tax-unit", + "assigned_aca_ptc is projected to person grain (indicator_map_to) and", + "filtered to is_aca_ptc_eligible. Validated at 20.24M vs the 19.74M CMS", + "target (+2.5%); see PR #68." + ] + }, + { + "source": "cms_aca", + "measure_id": "bronze_aptc_consumers", + "base_variables": "selected_marketplace_plan_benchmark_ratio", + "family": "cms_aca", + "metadata": { + "target_role": "aca_bronze_aptc_consumers", + "measure_mode": "less_than_indicator_sum", + "indicator_less_than": "1.0", + "indicator_filter_variable": "assigned_aca_ptc" + } + }, + { + "source": "cms_medicaid", + "measure_id": "total_medicaid_enrollment", + "base_variables": "medicaid_enrolled", + "family": "cms_medicaid", + "metadata": { + "target_role": "medicaid_enrollment" + } + }, + { + "source": "cms_medicaid", + "measure_id": "chip_enrollment", + "base_variables": "chip_enrolled", + "family": "cms_medicaid", + "metadata": { + "target_role": "chip_enrollment" + } + }, + { + "source": "cms_medicaid", + "measure_id": "total_chip_enrollment", + "base_variables": "chip_enrolled", + "family": "cms_medicaid", + "metadata": { + "target_role": "chip_enrollment" + } + }, + { + "source": "cms_medicaid", + "measure_id": "total_medicaid_chip_enrollment", + "base_variables": [ + "medicaid_enrolled", + "chip_enrolled" + ], + "family": "cms_medicaid", + "metadata": { + "target_role": "medicaid_chip_enrollment" + } + }, + { + "source": "usda_snap", + "measure_id": "average_monthly_households", + "base_variables": "snap", + "family": "usda_snap", + "metadata": { + "target_role": "snap_households", + "fact_aggregation": "time_mean" + }, + "note": [ + "FNS reports fiscal-year average monthly caseloads. We proxy the", + "household caseload as an indicator sum over SPM units with positive", + "annual snap. The take-up assignment seeds takers to reproduce the FNS", + "participation rate, so the taker set is the model counterpart of the", + "average monthly caseload rather than an annual-ever count. Validated", + "on populace-us-2024-buildi-sparse-rmloss100: 21.89M weighted taker", + "units vs the 22.20M FY2024 FNS national average (-1.4%) with no", + "calibration pressure on counts.", + "", + "average_monthly_persons is deliberately NOT mapped: the real SNAP", + "assistance unit is often a subset of the SPM unit (FY2024 FNS persons", + "per household is 1.88 vs 2.82 members per simulated taker unit), and", + "PolicyEngine-US does not model sub-unit participation, so a person", + "indicator overcounts by ~50% and would fight the household target." + ] + }, + { + "source": "hhs_acf_liheap", + "measure_id": "households_served", + "base_variables": "spm_unit_energy_subsidy", + "family": "hhs_acf_liheap", + "metadata": { + "target_role": "liheap_households" + }, + "note": [ + "LIHEAP recipient households: the retired us-data/eCPS pipeline calibrated", + "the ACF national recipient-household count (loss.py", + "_add_liheap_targets_from_db, PR #688) as an indicator sum of the model's", + "energy-subsidy receipt over SPM units — the exact SNAP-caseload pattern.", + "Only the recipient COUNT is targeted; LIHEAP dollars stay deferred (the", + "ACF component split is not a clean model concept, us-data PR #688)." + ] + } + ] + }, + "m_chip_state_fips": { + "description": [ + "Medicaid-expansion-CHIP (M-CHIP) states whose CMS CHIP enrollment rows never", + "calibrate (PolicyEngine/microcosm#321). PolicyEngine-US 2.2.1 sets", + "gov.hhs.chip.child.income_limit to -inf in all twenty (and in Rhode Island,", + "which sits outside the set), covering their children through the Medicaid", + "child limits, so chip_enrolled there can come only from the pregnant-person", + "paths. The reason differs by state:", + "- AK DC HI NC ND NH NM OH SC VT WY: the child, pregnant and FCEP limits are", + " all -inf, so the model has no CHIP path and the rows have no support.", + "- CA IL KY MD ME MI NE OK: the CMS count is mostly M-CHIP children (PE-US's", + " MACPAC enrollment parameters), a concept only a pregnant or FCEP path could", + " stand in for.", + "- MN: most of its count is separate CHIP (884 M-CHIP vs 4,285 separate in", + " the same parameters), so the concept argument does not hold; MN is", + " excluded because it is in the #321 state set.", + "_without_m_chip_state_chip_enrollment_targets drops these states' direct and", + "derived CHIP rows at every period, after latest-vintage selection, and the", + "derivation below never builds a derived row for them." + ], + "key": "state_fips", + "value": null, + "entries": [ + { + "state_fips": "02" + }, + { + "state_fips": "06" + }, + { + "state_fips": "11" + }, + { + "state_fips": "15" + }, + { + "state_fips": "17" + }, + { + "state_fips": "21" + }, + { + "state_fips": "23" + }, + { + "state_fips": "24" + }, + { + "state_fips": "26" + }, + { + "state_fips": "27" + }, + { + "state_fips": "31" + }, + { + "state_fips": "33" + }, + { + "state_fips": "35" + }, + { + "state_fips": "37" + }, + { + "state_fips": "38" + }, + { + "state_fips": "39" + }, + { + "state_fips": "40" + }, + { + "state_fips": "45" + }, + { + "state_fips": "50" + }, + { + "state_fips": "56" + } + ] + }, + "restamped_source_packages": { + "description": [ + "Reviewed against consumer_facts_us_c5e5bf8.jsonl (Chronicle c5e5bf8, sha256", + "b8543739...): these are the 26,893 facts both rules detect. Each data year", + "was confirmed from the file itself (title cell or content match), not from", + "Chronicle labels. \"Newest\" claims were checked on irs.gov on 2026-09-25." + ], + "key": "package_id", + "value": [ + "data_year", + "stamped_periods", + "source_file", + "source_sha256", + "reason" + ], + "entries": [ + { + "package_id": "soi-w2-statistics-2020", + "data_year": 2020, + "stamped_periods": [ + 2023 + ], + "source_file": "20in04w2all.xlsx", + "source_sha256": "1178d77618cc1d2f873506909eeec660f36e3599854f31337f9dcaec6cfc442f", + "reason": "IRS SOI Form W-2 statistics Table 4.B, titled 'Tax Year 2020'. The ty2023 tips return_count, taxpayer_count and amount share their source cells, bytes and values with the ty2020 twins; the ty2023 401(k) and designated Roth 401(k) amounts are cells D22 and D41 of the same table. As of 2026-09-25 TY2020 is the newest W-2 table on irs.gov." + }, + { + "package_id": "soi-congressional-district-2022", + "data_year": 2022, + "stamped_periods": [ + 2023 + ], + "source_file": "22incd.csv", + "source_sha256": "137522878af78d624cfddc0e17cd36ae76a21b7bed166c7bb96ad3243a18a668", + "reason": "IRS SOI congressional district data for tax year 2022 (the newest CD release as of 2026-09-25). The single-district states match the TY2022 county file (for example WY N1 280,740), and the US taxable interest is 92.7% of TY2022 Table 1.4 against 39.4% of TY2023 (PolicyEngine/chronicle#117)." + }, + { + "package_id": "soi-state-2022", + "data_year": 2022, + "stamped_periods": [ + 2023 + ], + "source_file": "22in54us.xlsx", + "source_sha256": "5e58050449c07c2e941f280c60d597784047f02ee1fa93dc1aed64fc1ea493f6", + "reason": "IRS SOI Historic Table 2 US totals, titled 'Tax Year 2022'." + }, + { + "package_id": "soi-ira-roth-contributions-2022", + "data_year": 2022, + "stamped_periods": [ + 2023 + ], + "source_file": "22in06ira.xlsx", + "source_sha256": "c1fb0894cb09d2486be4510b7e6ce0b8597787725b928ab8813f577d9fb13183", + "reason": "IRS SOI IRA Table 6 (Roth contributions), titled 'Tax Year 2022'." + }, + { + "package_id": "soi-ira-traditional-contributions-2022", + "data_year": 2022, + "stamped_periods": [ + 2023 + ], + "source_file": "22in05ira.xlsx", + "source_sha256": "31ce9dd2fe631b336170af339bd7e9de86901cd20dbfd4cb8fb1c9a1d55cd90f", + "reason": "IRS SOI IRA Table 5 (traditional contributions), titled 'Tax Year 2022'." + } + ] + }, + "later_period_observation_exemptions": { + "description": [ + "None on the pinned feed: no package there observes a year after its key." + ], + "key": "package_id", + "value": [ + "periods", + "reason" + ], + "entries": [] + } + } +} diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/fiscal_target_registers.py b/packages/microcosm-build/src/microcosm/build/us_runtime/fiscal_target_registers.py new file mode 100644 index 0000000000..fced445665 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/fiscal_target_registers.py @@ -0,0 +1,29 @@ +"""The reviewed registers of the US fiscal target compile (microcosm#1728). + +``us/fiscal_target_registers.json`` holds the registers that +:mod:`microcosm.build.us_runtime.fiscal_targets` and +:mod:`microcosm.build.us_runtime.source_vintage` read: the facts the compile +drops and why, the source columns a package reads under the wrong measure, the +restamped source packages, the SOI variable maps, the direct and indicator +targets, and the M-CHIP states. Each register keeps the comments that stood +beside it in the code as its description and notes. The shared +:mod:`microcosm.build.declared_registers` reads them. +""" + +from __future__ import annotations + +from typing import Any + +from microcosm.build.declared_registers import package_register + +__all__ = ["US_FISCAL_TARGET_REGISTERS_RESOURCE", "us_fiscal_target_register"] + +US_FISCAL_TARGET_REGISTERS_RESOURCE = "fiscal_target_registers.json" + + +def us_fiscal_target_register(name: str) -> Any: + """One register of the file: a dict in entry order, or a frozenset of keys.""" + + return package_register( + "microcosm.build.us", US_FISCAL_TARGET_REGISTERS_RESOURCE, name + ) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/fiscal_targets.py b/packages/microcosm-build/src/microcosm/build/us_runtime/fiscal_targets.py index fd0516cf15..c5e2266e93 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/fiscal_targets.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/fiscal_targets.py @@ -29,6 +29,9 @@ from microcosm.build.us_runtime.congressional_district_vintage import ( translate_congressional_district_facts_to_current_vintage, ) +from microcosm.build.us_runtime.fiscal_target_registers import ( + us_fiscal_target_register, +) from microcosm.build.us_runtime.fsa_student_loan_targets import ( FSA_SOURCE_NAME, apply_fsa_student_loan_plan, @@ -124,249 +127,25 @@ def _us_hierarchy_seed( ) -SOI_AMOUNT_MEASURE_VARIABLES: dict[str, str] = { - "adjusted_gross_income": "adjusted_gross_income", - "actc_amount": "refundable_ctc", - "ctc_amount": "ctc", - "eitc_amount": "eitc", - "eitc_no_children_amount": "eitc", - "eitc_one_child_amount": "eitc", - "eitc_three_or_more_children_amount": "eitc", - "eitc_total": "eitc", - "eitc_two_children_amount": "eitc", - "income_tax_before_credits_amount": "income_tax_before_credits", - "income_tax_liability_amount": "income_tax", - "interest_paid_deduction_amount": "interest_deduction", - "itemized_deductions_amount": "itemized_taxable_income_deductions", - "limited_state_local_taxes_amount": "salt_deduction", - "medical_dental_expense_amount": "medical_expense_deduction", - "net_capital_gains_amount": "capital_gains_gross", - "ordinary_dividends_amount": "ordinary_dividends", - "partnership_scorp_income_amount": "partnership_and_s_corp_income", - "premium_tax_credit_amount": "assigned_aca_ptc", - "qualified_business_income_deduction_amount": ( - "qualified_business_income_deduction" - ), - "qualified_dividends_amount": "qualified_dividends", - "real_estate_taxes_amount": "real_estate_taxes", - "rental_royalty_income_amount": "rent_and_royalty_net_income", - "schedule_c_income_amount": "business_net_profits", - "tax_exempt_interest_amount": "tax_exempt_interest_income", - "tax_filer_individual_count": "tax_filer_individual_count", - "taxable_income_amount": "taxable_income", - "taxable_interest_amount": "taxable_interest_income", - "taxable_ira_distributions_amount": "ira_distributions", - "taxable_pension_income_amount": "taxable_pension_income", - "taxable_social_security_amount": "taxable_social_security", - "total_itemized_deductions_amount": "itemized_taxable_income_deductions", - "total_earned_income_credit_amount": "eitc", - "unemployment_compensation_amount": "unemployment_compensation", - "wages_salaries_amount": "employment_income", - "charitable_amount": "charitable_deduction", - # Build H (microcosm#299): SOI Table 1.4 income/loss lines that identify the - # floating export-input columns. Income legs sum the positive part of the - # signed model variable, loss legs the negative-part magnitude - # (see _signed_component), matching SOI's returns-with-net-income vs - # returns-with-net-loss split. estate_income and miscellaneous_income are - # export columns with reviewed exclusions in - # US_EXPORT_INPUT_MASS_REVIEWED_EXCLUSIONS - # (tools/build_us_fiscal_refresh_release.py), so the export-mass gate does - # not check their drift. The estate rows pin estate_income to SOI. The - # other-income rows compile to no target at any vintage - # (US_FISCAL_TARGET_ALL_VINTAGE_SUPPORT_EXCLUSIONS, microcosm#393), so no - # SOI line pins miscellaneous_income today. Both move federal income tax. - # In policyengine-us 2.2.1 and 2.23.2 a non-dependent's positive - # miscellaneous_income is gross income; loss_ald deducts estate_income - # losses above the line, subject to the section 461(l) limit; and - # estate_income counts toward qualified business income while - # estate_income_would_be_qualified is true (the default). From 2.23.2 - # (PolicyEngine/policyengine-us#9633) a non-dependent's positive - # estate_income is also gross income, and so AGI, and a non-dependent's - # signed estate_income plus the Schedule K-1 (Form 1041) box 14 code H - # adjustment enters net investment income. - "estate_trust_net_income_amount": "estate_income", - "estate_trust_net_loss_amount": "estate_losses", - "other_income_net_income_amount": "miscellaneous_income", - "other_income_net_loss_amount": "miscellaneous_losses", - # SOI Table 1.4 publishes partnership and S corporation net income and net - # loss separately from TY2021 (Chronicle's table_1_4 measure ids; losses - # are positive magnitudes). Each entity leg binds that entity's own Schedule - # E line-32 leaf, summed to the return, positive part for net income and - # negative-part magnitude for net loss (microcosm#1258). - "partnership_net_income_amount": "partnership_income", - "partnership_net_loss_amount": "partnership_losses", - "s_corporation_net_income_amount": "s_corp_income", - "s_corporation_net_loss_amount": "s_corp_losses", - # SOI Table 1.4 "capital gain distributions reported on Form 1040" == - # PUF E01100 == PolicyEngine-US non_sch_d_capital_gains (Form 1040 line 7 - # when Schedule D is not required); concept-confirmed against pe-us source. - "capital_gain_distributions_amount": "non_sch_d_capital_gains", - # Build H (microcosm#299): SOI Table 2.1 "Home mortgage interest" itemized- - # deduction total (financial-institution + personal-seller legs summed; - # TY2023 $171,364,787,000 / 11,644,348 returns; CBO-aged ~$186.3B@2024). - # The record set irs_soi.ty2023.table_2_1.itemized_all_returns makes - # _soi_return_universe_from_record_set_id -> "itemized_returns", so - # _soi_reference_from_fact auto-stamps itemized_only=true and the target - # sums the model variable over ITEMIZERS ONLY -- the correct universe for a - # Schedule-A line. Only the CW/CX "Total" measure is mapped; the two leg - # measures (mortgage_interest_paid_*, home_mortgage_personal_seller_*) stay - # unmapped to avoid double-counting. - # - # microcosm#511: the SOI line is the amount DEDUCTED on Schedule A, i.e. - # after the section 163(h)(3) acquisition-debt caps, so the target maps to - # the engine's capped deductible_mortgage_interest_tax_unit rather than the - # gross home_mortgage_interest export input Build H used. On certified O-1 - # the gross column summed $241.3B over itemizers (+29.5%) while the capped - # concept summed $214.2B (+15.0%) against the $186.3B aged fact -- the cap - # haircut alone was a $27.1B pure concept gap. The capped formula is linear - # in the first/second_home_mortgage_interest export inputs (balances and - # origination years only set the deductible share), so calibration keeps - # the same pull-through to the export mass that Build H wanted. A - # positive-balance unit's deductible share is always positive; gross and - # structural carriers are independently imputed, so equality is a data - # property, verified on O-1 post-itemizer-mask (identical weighted carrier - # totals; the only gross-vs-structural divergent units are non-itemizers). - # The residual overshoot is the donor-side E19200 total-interest lineage - # (microcosm#515, #487-adjacent). - "home_mortgage_interest_amount": "deductible_mortgage_interest", -} +#: Declared in ``us/fiscal_target_registers.json`` (``soi_amount_measure_variables``), with the notes on its entries. +SOI_AMOUNT_MEASURE_VARIABLES: dict[str, str] = us_fiscal_target_register( + "soi_amount_measure_variables" +) -SOI_RETURN_MEASURE_VARIABLES: dict[str, str] = { - "actc_claims": "refundable_ctc", - "ctc_claims": "ctc", - "eitc_claims": "eitc", - "eitc_no_children_claims": "eitc", - "eitc_one_child_claims": "eitc", - "eitc_returns": "eitc", - "eitc_three_or_more_children_claims": "eitc", - "eitc_two_children_claims": "eitc", - "income_tax_before_credits_returns": "income_tax_before_credits", - "income_tax_liability_returns": "income_tax", - "interest_paid_deduction_returns": "interest_deduction", - "limited_state_local_taxes_returns": "salt_deduction", - "medical_dental_expense_returns": "medical_expense_deduction", - "net_capital_gains_returns": "capital_gains_gross", - "ordinary_dividends_returns": "ordinary_dividends", - "partnership_scorp_income_returns": "partnership_and_s_corp_income", - "premium_tax_credit_returns": "assigned_aca_ptc", - "qualified_business_income_deduction_returns": ( - "qualified_business_income_deduction" - ), - "qualified_dividends_returns": "qualified_dividends", - "real_estate_taxes_claims": "real_estate_taxes", - "rental_royalty_income_returns": "rent_and_royalty_net_income", - "return_count": "count", - "schedule_c_income_returns": "business_net_profits", - "tax_exempt_interest_returns": "tax_exempt_interest_income", - "taxable_income_returns": "taxable_income", - "taxable_interest_returns": "taxable_interest_income", - "taxable_ira_distributions_returns": "ira_distributions", - "taxable_pension_income_returns": "taxable_pension_income", - "taxable_social_security_returns": "taxable_social_security", - "total_earned_income_credit_returns": "eitc", - "unemployment_compensation_returns": "unemployment_compensation", - "wages_salaries_returns": "employment_income", - "charitable_returns": "charitable_deduction", - # Build H (microcosm#299): return counts paired with the Table 1.4 income/ - # loss amount lines above (indicator sums of the signed model variable's - # positive / negative part). - "estate_trust_net_income_returns": "estate_income", - "estate_trust_net_loss_returns": "estate_losses", - "other_income_net_income_returns": "miscellaneous_income", - "other_income_net_loss_returns": "miscellaneous_losses", - # microcosm#1258: return counts paired with the Table 1.4 partnership and - # S corporation legs above. - "partnership_net_income_returns": "partnership_income", - "partnership_net_loss_returns": "partnership_losses", - "s_corporation_net_income_returns": "s_corp_income", - "s_corporation_net_loss_returns": "s_corp_losses", - "capital_gain_distributions_returns": "non_sch_d_capital_gains", - # Build H (microcosm#299): return count paired with the Table 2.1 home - # mortgage interest amount above (indicator sum over itemizers claiming a - # home mortgage interest deduction). microcosm#511: indicator over the same - # capped concept as the amount row. The deductible share is positive - # wherever a positive mortgage balance backs positive interest; carrier - # equality with the old gross indicator is a data property (independently - # imputed columns), verified on O-1 post-itemizer-mask. - "home_mortgage_interest_returns": "deductible_mortgage_interest", -} +#: Declared in ``us/fiscal_target_registers.json`` (``soi_return_measure_variables``), with the notes on its entries. +SOI_RETURN_MEASURE_VARIABLES: dict[str, str] = us_fiscal_target_register( + "soi_return_measure_variables" +) -SOI_VARIABLE_MAP: dict[str, str] = { - "adjusted_gross_income": "adjusted_gross_income", - "business_net_profits": "self_employment_income", - "business_net_losses": "self_employment_income", - "capital_gains_distributions": "capital_gains", - "capital_gains_gross": "capital_gains", - "capital_gains_losses": "capital_losses", - "charitable_deduction": "charitable_deduction", - "ctc": "ctc", - "employment_income": "employment_income", - "eitc": "eitc", - "estate_income": "estate_income", - "estate_losses": "estate_income", - # Build H (microcosm#299): concept -> signed model column for the export - # dimensions identified by SOI Table 1.4. income/loss concept pairs share - # one signed column (same pattern as business/rent/partnership above); - # _signed_component takes the positive part for the income concept and the - # negative-part magnitude for the "_losses" concept. - "miscellaneous_income": "miscellaneous_income", - "miscellaneous_losses": "miscellaneous_income", - "non_sch_d_capital_gains": "non_sch_d_capital_gains", - # microcosm#511 (supersedes the Build H gross mapping): SOI Table 2.1 home - # mortgage interest is the amount deducted on Schedule A, post the section - # 163(h)(3) acquisition-debt caps, so the concept maps to the engine's - # capped tax-unit aggregate. itemized_only masking (auto from the - # itemized_all_returns record set, plus the concept's membership in - # _SOI_ITEMIZED_ONLY_VARIABLES) restricts the sum to itemizers, matching - # the Schedule-A universe. - "deductible_mortgage_interest": "deductible_mortgage_interest_tax_unit", - "exempt_interest": "tax_exempt_interest_income", - "income_tax": "income_tax", - "income_tax_before_credits": "income_tax_before_credits", - "interest_deduction": "interest_deduction", - "ira_distributions": "taxable_ira_distributions", - "itemized_taxable_income_deductions": "itemized_taxable_income_deductions", - "medical_expense_deduction": "medical_expense_deduction", - "ordinary_dividends": "ordinary_dividend_income", - "partnership_and_s_corp_income": "tax_unit_partnership_s_corp_income", - "partnership_and_s_corp_losses": "tax_unit_partnership_s_corp_income", - # microcosm#1258: Table 1.4's entity legs read each entity's own person - # leaf; the materializer sums it to the tax unit before taking the part. - "partnership_income": "partnership_income", - "partnership_losses": "partnership_income", - "s_corp_income": "s_corp_income", - "s_corp_losses": "s_corp_income", - "assigned_aca_ptc": "assigned_aca_ptc", - "qualified_business_income_deduction": "qualified_business_income_deduction", - "qualified_dividends": "qualified_dividend_income", - "real_estate_taxes": "real_estate_taxes", - "rent_and_royalty_net_income": "rent_and_royalty_net_income", - "rent_and_royalty_net_losses": "rent_and_royalty_net_income", - "refundable_ctc": "refundable_ctc", - "salt_deduction": "salt_deduction", - "tax_exempt_interest_income": "tax_exempt_interest_income", - "taxable_income": "taxable_income", - "taxable_interest_income": "taxable_interest_income", - "tax_filer_individual_count": "tax_unit_size", - "taxable_pension_income": "taxable_pension_income", - "taxable_social_security": "tax_unit_taxable_social_security", - "tip_income": "tip_income", - "total_pension_income": "pension_income", - "total_social_security": "tax_unit_social_security", - "unemployment_compensation": "unemployment_compensation", -} +#: Declared in ``us/fiscal_target_registers.json`` (``soi_variables``), with the notes on its entries. +SOI_VARIABLE_MAP: dict[str, str] = us_fiscal_target_register("soi_variables") -_SOI_BASE_VARIABLE_OVERRIDES: dict[str, tuple[str, ...]] = { - "ctc": ("ctc", "ctc_limiting_tax_liability"), - "ordinary_dividends": ( - "qualified_dividend_income", - "non_qualified_dividend_income", - ), - "rent_and_royalty_net_income": ("rental_income", "farm_rent_income"), - "rent_and_royalty_net_losses": ("rental_income", "farm_rent_income"), -} +#: Declared in ``us/fiscal_target_registers.json`` (``soi_base_variable_overrides``). +_SOI_BASE_VARIABLE_OVERRIDES: dict[str, tuple[str, ...]] = us_fiscal_target_register( + "soi_base_variable_overrides" +) _SOI_EITC_CHILD_COUNT_LAYOUT_DIMENSIONS = frozenset( { @@ -418,580 +197,41 @@ def _us_hierarchy_seed( ) +#: Declared in ``us/fiscal_target_registers.json`` (``direct_targets``), with the notes on its entries. DIRECT_LEDGER_TARGETS: dict[ tuple[str, str, str | None], tuple[str, str, dict[str, str]] -] = { - ("cbo", "projected_amount", "adjusted_gross_income"): ( - "adjusted_gross_income", - "cbo", - {"target_role": "cbo_adjusted_gross_income"}, - ), - ("cbo", "projected_amount", "wages_and_salaries"): ( - "employment_income", - "cbo", - {"target_role": "cbo_wages_and_salaries"}, - ), - ("cbo", "projected_amount", "qualified_dividend_income"): ( - "qualified_dividend_income", - "cbo", - {"target_role": "cbo_qualified_dividend_income"}, - ), - ("cbo", "projected_amount", "net_capital_gain"): ( - "capital_gains", - "cbo", - {"target_role": "cbo_net_capital_gain"}, - ), - ("cbo", "projected_amount", "net_business_income"): ( - "cbo_net_business_income", - "cbo", - {"target_role": "cbo_net_business_income"}, - ), - ("ssa", "payment_amount", "social_security_benefits"): ( - "social_security", - "ssa", - {"target_role": "social_security_total"}, - ), - ("ssa", "payment_amount", "social_security_retirement_benefits"): ( - "social_security_retirement", - "ssa", - {"target_role": "ssa_retirement_total"}, - ), - ("ssa", "payment_amount", "social_security_disability_benefits"): ( - "social_security_disability", - "ssa", - {"target_role": "ssa_disability_total"}, - ), - ("ssa", "payment_amount", "social_security_survivors_benefits"): ( - "social_security_survivors", - "ssa", - {"target_role": "ssa_survivors_total"}, - ), - ("ssa", "payment_amount", "social_security_dependents_benefits"): ( - "social_security_dependents", - "ssa", - {"target_role": "ssa_dependents_total"}, - ), - ("ssa", "payment_amount", "ssi_payments"): ( - "ssi", - "ssa", - {"target_role": "ssi_total"}, - ), - ("usda_snap", "total_benefits", None): ( - "snap", - "usda_snap", - {"target_role": "snap_total"}, - ), - ("hhs_acf_tanf", "all_funds", None): ( - "tanf", - "hhs_acf_tanf", - {"target_role": "tanf_total"}, - ), - ("cms_nhe", "expenditure_amount", "medicaid_title_xix"): ( - "medicaid", - "cms_medicaid", - { - "target_role": "medicaid_spending", - "calibration_role": "validation_only", - "exclusion_reason": ( - "PolicyEngine-US allocates medicaid spending from state totals " - "through person_weight-dependent denominators. Reweighting then " - "recomputes per-person medicaid costs, so this is not a linear " - "calibration row." - ), - }, - ), - # 2025 Trustees Report Table III.C3 Part B premiums from enrollees. - # gross_medicare_part_b_premium is defined for is_medicare_eligible, so - # it also charges eligible people who never enrolled. PolicyEngine-US - # documents the enrollment-gated gross_medicare_part_b_premium_if_enrolled - # for CMS premiums-from-enrollees targets (microcosm#1206). - # The target includes income-related premiums (IRMAA). On the locked - # policyengine-us 2.2.1 a 2024 release has none, because IRMAA rests on - # income two years earlier and the H5 carries 2024 inputs only, so this - # row reads the standard premium alone until Microcosm's engine includes - # PolicyEngine/policyengine-us#10106 (see microcosm#1206 for the sums). - ("cms_medicare", "actual_amount", "premiums_from_enrollees"): ( - "gross_medicare_part_b_premium_if_enrolled", - "cms_medicare", - {"target_role": "medicare_part_b_premium_total"}, - ), - # Household net worth: the retired us-data/eCPS pipeline calibrated a - # national wealth control (loss.py "net_worth", PR #282). Per-household - # net_worth is SCF-imputed and fixed, so the weighted sum is linear in the - # reweighting weights — a valid direct-sum target that pins the post-reweight - # aggregate the input-stage SCF imputation does not. Federal Reserve Z.1 - # series BOGZ1FL192090005Q (households & nonprofits net worth). - ("federal_reserve", "amount_outstanding", "fl152090005"): ( - "net_worth", - "federal_reserve", - {"target_role": "household_net_worth"}, - ), -} +] = us_fiscal_target_register("direct_targets") IndicatorBaseVariables = str | tuple[str, ...] IndicatorLedgerTarget = tuple[IndicatorBaseVariables, str, dict[str, str]] -INDICATOR_LEDGER_TARGETS: dict[tuple[str, str], IndicatorLedgerTarget] = { - ("cms_aca", "marketplace_enrollment"): ( - "has_marketplace_health_coverage_at_interview", - "cms_aca", - {"target_role": "aca_enrollment"}, - ), - # CMS reports APTC recipients as people. We proxy this as an indicator-sum - # over eligible people in tax units with positive assigned PTC: the tax-unit - # assigned_aca_ptc is projected to person grain (indicator_map_to) and - # filtered to is_aca_ptc_eligible. Validated at 20.24M vs the 19.74M CMS - # target (+2.5%); see PR #68. - ("cms_aca", "aptc_recipients"): ( - "assigned_aca_ptc", - "cms_aca", - { - "target_role": "aca_ptc_recipients", - "indicator_map_to": "person", - "indicator_filter_variable": "is_aca_ptc_eligible", - }, - ), - ("cms_aca", "bronze_aptc_consumers"): ( - "selected_marketplace_plan_benchmark_ratio", - "cms_aca", - { - "target_role": "aca_bronze_aptc_consumers", - "measure_mode": "less_than_indicator_sum", - "indicator_less_than": "1.0", - "indicator_filter_variable": "assigned_aca_ptc", - }, - ), - ("cms_medicaid", "total_medicaid_enrollment"): ( - "medicaid_enrolled", - "cms_medicaid", - {"target_role": "medicaid_enrollment"}, - ), - ("cms_medicaid", "chip_enrollment"): ( - "chip_enrolled", - "cms_medicaid", - {"target_role": "chip_enrollment"}, - ), - ("cms_medicaid", "total_chip_enrollment"): ( - "chip_enrolled", - "cms_medicaid", - {"target_role": "chip_enrollment"}, - ), - ("cms_medicaid", "total_medicaid_chip_enrollment"): ( - ("medicaid_enrolled", "chip_enrolled"), - "cms_medicaid", - {"target_role": "medicaid_chip_enrollment"}, - ), - # FNS reports fiscal-year average monthly caseloads. We proxy the - # household caseload as an indicator sum over SPM units with positive - # annual snap. The take-up assignment seeds takers to reproduce the FNS - # participation rate, so the taker set is the model counterpart of the - # average monthly caseload rather than an annual-ever count. Validated - # on populace-us-2024-buildi-sparse-rmloss100: 21.89M weighted taker - # units vs the 22.20M FY2024 FNS national average (-1.4%) with no - # calibration pressure on counts. - # - # average_monthly_persons is deliberately NOT mapped: the real SNAP - # assistance unit is often a subset of the SPM unit (FY2024 FNS persons - # per household is 1.88 vs 2.82 members per simulated taker unit), and - # PolicyEngine-US does not model sub-unit participation, so a person - # indicator overcounts by ~50% and would fight the household target. - ("usda_snap", "average_monthly_households"): ( - "snap", - "usda_snap", - { - "target_role": "snap_households", - "fact_aggregation": "time_mean", - }, - ), - # LIHEAP recipient households: the retired us-data/eCPS pipeline calibrated - # the ACF national recipient-household count (loss.py - # _add_liheap_targets_from_db, PR #688) as an indicator sum of the model's - # energy-subsidy receipt over SPM units — the exact SNAP-caseload pattern. - # Only the recipient COUNT is targeted; LIHEAP dollars stay deferred (the - # ACF component split is not a clean model concept, us-data PR #688). - ("hhs_acf_liheap", "households_served"): ( - "spm_unit_energy_subsidy", - "hhs_acf_liheap", - {"target_role": "liheap_households"}, - ), -} +#: Declared in ``us/fiscal_target_registers.json`` (``indicator_targets``), with the notes on its entries. +INDICATOR_LEDGER_TARGETS: dict[tuple[str, str], IndicatorLedgerTarget] = ( + us_fiscal_target_register("indicator_targets") +) -US_FISCAL_TARGET_SUPPORT_EXCLUSIONS: dict[str, str] = { - "irs_soi.ty2023.table_1_4.all.other_income_net_loss_amount": ( - "The PUF pipeline maps miscellaneous_income = E01200 (policyengine-us- " - "data datasets/puf/puf.py), but E01200 is Form 4797 / Form 1040 line 14 " - "business-property net gain or loss (IRS Research Bulletin 2017 Table " - "A1), not the 'other income' line concept SOI Table 1.4 reports (Form " - "1040 line 21 in ty2015; Schedule 1 in later years) — microcosm#393's " - "remedy experiments reached this final " - "determination and the export-parity registry already carries it for the " - "miscellaneous_income column. Both signs are therefore concept- " - "mismatched, and the measured legs bear the 4797 reading: ty2015 E01200 " - "as the pipeline ingests it (aggregate records removed) is two-sided " - "($22.84B positive on 1.09M returns vs $21.55B negative on 1.18M; " - "$33.42B/$21.95B on the full raw file) while SOI ty2015 other income " - "is heavily positive " - "($46.77B on 6.12M income returns vs $6.69B on 332,708 loss returns, " - "with NOL a separate item at $197.5B on 1,138,112 returns; ty2023 keeps " - "the concepts separate as items 91-94 vs 95-96, raw loss $12.21B on " - "318,839 returns before feed aging). Build P attempts 9/10 " - "(microcosm#507) measured the consequence: the solve must crush truthful " - "business-property loss mass to fit the loss rows ($34.3B design-weight " - "truth vs $13.3B aged target), and the income row's historical +0.005% " - "fit was free reweighting, not concept agreement. All four rows are " - "excluded until the microcosm#393 remedy lands in full: remap E01200 to " - "other_net_gain AND separately source or impute true miscellaneous " - "income — a remap-only rebuild leaves miscellaneous_income " - "zero/absent, so these exclusions lift only when both halves land." - ), - "irs_soi.ty2023.table_1_4.all.other_income_net_loss_returns": ( - "Same Form 4797 concept mismatch as the other_income_net_loss_amount " - "entry: E01200 carries Form 1040 line-14 business-property net " - "gain/loss, not the SOI Table 1.4 line-21 'other income' concept, so " - "this row compares incompatible concepts regardless of sign. Excluded " - "until the microcosm#393 remedy lands in full (remap E01200 to " - "other_net_gain AND separately source true miscellaneous income); " - "see the loss-amount entry for the full adjudication." - ), - "irs_soi.ty2023.table_1_4.all.other_income_net_income_amount": ( - "Same Form 4797 concept mismatch as the other_income_net_loss_amount " - "entry: E01200 carries Form 1040 line-14 business-property net " - "gain/loss, not the SOI Table 1.4 line-21 'other income' concept, so " - "this row compares incompatible concepts regardless of sign. Excluded " - "until the microcosm#393 remedy lands in full (remap E01200 to " - "other_net_gain AND separately source true miscellaneous income); " - "see the loss-amount entry for the full adjudication." - ), - "irs_soi.ty2023.table_1_4.all.other_income_net_income_returns": ( - "Same Form 4797 concept mismatch as the other_income_net_loss_amount " - "entry: E01200 carries Form 1040 line-14 business-property net " - "gain/loss, not the SOI Table 1.4 line-21 'other income' concept, so " - "this row compares incompatible concepts regardless of sign. Excluded " - "until the microcosm#393 remedy lands in full (remap E01200 to " - "other_net_gain AND separately source true miscellaneous income); " - "see the loss-amount entry for the full adjudication." - ), - "census_stc.fy2023.individual_income_tax_collections.tn.t40.collections": ( - "Tennessee has no modeled 2024 state individual income tax support in " - "PolicyEngine-US; this STC residual collection row cannot be estimated " - "from the current state_income_tax variable." - ), - "census_stc.fy2024.individual_income_tax_collections.tn.t40.collections": ( - "Tennessee has no modeled 2024 state individual income tax support in " - "PolicyEngine-US; this STC residual collection row cannot be estimated " - "from the current state_income_tax variable." - ), - "irs_soi.ty2022.historic_table_2.state_agi.vt.under_1.taxable_interest_amount": ( - "Current national CPS+PUF support has zero Vermont taxable-interest " - "support in the under-$1 AGI slice; this narrow offset-income cell needs " - "richer state/tail support before it can be calibrated. MEASURED on the " - "Build P2 dense frame (base-P2 fca79b42, FULL 337,704-household pool, no " - "selection, frame identity b54feb926c6e5396…, release " - "populace-us-2024-buildp-dense-cae8640-20260728T050443Z): registry " - "aggregates " - "exactly 0.0 initial and final for both rows, household weights strictly " - "positive (min 19.58), taxable_interest_income nonnegative with 201,242 " - "positive person records (122,852 unique carrier households) pool-wide — the cell is unexpressible from the pool " - "itself, not a sparse-selection artifact, which is the ia/nd class. A " - "legacy Build P sparse-only register carried a redundant VT pair; this " - "standing entry is now the sole surface-wide exclusion." - ), - "irs_soi.ty2022.historic_table_2.state_agi.vt.under_1.taxable_interest_returns": ( - "Current national CPS+PUF support has zero Vermont taxable-interest " - "support in the under-$1 AGI slice; this narrow offset-income cell needs " - "richer state/tail support before it can be calibrated. MEASURED on the " - "Build P2 dense frame (base-P2 fca79b42, FULL 337,704-household pool, no " - "selection, frame identity b54feb926c6e5396…, release " - "populace-us-2024-buildp-dense-cae8640-20260728T050443Z): registry " - "aggregates " - "exactly 0.0 initial and final for both rows, household weights strictly " - "positive (min 19.58), taxable_interest_income nonnegative with 201,242 " - "positive person records (122,852 unique carrier households) pool-wide — the cell is unexpressible from the pool " - "itself, not a sparse-selection artifact, which is the ia/nd class. A " - "legacy Build P sparse-only register carried a redundant VT pair; this " - "standing entry is now the sole surface-wide exclusion." - ), - "irs_soi.ty2022.historic_table_2.state_agi.ia.under_1.taxable_interest_amount": ( - "Current national CPS+PUF support has zero Iowa taxable-interest support " - "in the under-$1 AGI slice; this narrow offset-income cell needs richer " - "state/tail support before it can be calibrated." - ), - "irs_soi.ty2022.historic_table_2.state_agi.ia.under_1.taxable_interest_returns": ( - "Current national CPS+PUF support has zero Iowa taxable-interest support " - "in the under-$1 AGI slice; this narrow offset-income cell needs richer " - "state/tail support before it can be calibrated." - ), - "irs_soi.ty2022.historic_table_2.state_agi.nd.under_1.taxable_interest_amount": ( - "Current national CPS+PUF support has zero North Dakota taxable-interest " - "support in the under-$1 AGI slice; this narrow offset-income cell needs " - "richer state/tail support before it can be calibrated." - ), - "irs_soi.ty2022.historic_table_2.state_agi.nd.under_1.taxable_interest_returns": ( - "Current national CPS+PUF support has zero North Dakota taxable-interest " - "support in the under-$1 AGI slice; this narrow offset-income cell needs " - "richer state/tail support before it can be calibrated." - ), - "irs_soi.ty2023.form_w2_social_security_tips.box_7_social_security_tips.return_count": ( - "The SIPP tip stage now materializes tip_income (549 carriers, $9.9B " - "weighted on certified Build M), but that support is under 1% of the " - "6.04M-return W-2 Box 7 class, so binding the return-count target " - "would demand ~600x weight concentration on those carriers. The " - "dollar-amount target binds first; the count target waits for tip " - "support widening (PolicyEngine/microcosm#451 item 3). Every vintage " - "of the cell is excluded (decision d179)." - ), - "hhs_acf_tanf.fy2024.cash_assistance.ar.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in Arkansas under PolicyEngine-US state TANF formulas." - ), - "hhs_acf_tanf.fy2024.cash_assistance.az.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in Arizona under PolicyEngine-US state TANF formulas." - ), - "hhs_acf_tanf.fy2024.cash_assistance.co.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in Colorado under PolicyEngine-US state TANF formulas." - ), - "hhs_acf_tanf.fy2024.cash_assistance.ct.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in Connecticut under PolicyEngine-US state TANF formulas." - ), - "hhs_acf_tanf.fy2024.cash_assistance.de.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in Delaware under PolicyEngine-US state TANF formulas." - ), - "hhs_acf_tanf.fy2024.cash_assistance.ga.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in Georgia under PolicyEngine-US state TANF formulas." - ), - "hhs_acf_tanf.fy2024.cash_assistance.id.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in Idaho under PolicyEngine-US state TANF formulas." - ), - "hhs_acf_tanf.fy2024.cash_assistance.in.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in Indiana under PolicyEngine-US state TANF formulas." - ), - "hhs_acf_tanf.fy2024.cash_assistance.ks.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in Kansas under PolicyEngine-US state TANF formulas." - ), - "hhs_acf_tanf.fy2024.cash_assistance.ky.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in Kentucky under PolicyEngine-US state TANF formulas." - ), - "hhs_acf_tanf.fy2024.cash_assistance.me.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in Maine under PolicyEngine-US state TANF formulas." - ), - "hhs_acf_tanf.fy2024.cash_assistance.mi.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in Michigan under PolicyEngine-US state TANF formulas." - ), - "hhs_acf_tanf.fy2024.cash_assistance.mt.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in Montana under PolicyEngine-US state TANF formulas." - ), - "hhs_acf_tanf.fy2024.cash_assistance.nm.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in New Mexico under PolicyEngine-US state TANF formulas." - ), - "hhs_acf_tanf.fy2024.cash_assistance.nv.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in Nevada under PolicyEngine-US state TANF formulas." - ), - "hhs_acf_tanf.fy2024.cash_assistance.ok.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in Oklahoma under PolicyEngine-US state TANF formulas." - ), - "hhs_acf_tanf.fy2024.cash_assistance.or.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in Oregon under PolicyEngine-US state TANF formulas." - ), - "hhs_acf_tanf.fy2024.cash_assistance.pa.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in Pennsylvania under PolicyEngine-US state TANF formulas." - ), - "hhs_acf_tanf.fy2024.cash_assistance.sd.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in South Dakota under PolicyEngine-US state TANF formulas." - ), - "hhs_acf_tanf.fy2024.cash_assistance.tx.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in Texas under PolicyEngine-US state TANF formulas." - ), - "hhs_acf_tanf.fy2024.cash_assistance.vt.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in Vermont under PolicyEngine-US state TANF formulas." - ), - "hhs_acf_tanf.fy2024.cash_assistance.wv.basic_assistance_excluding_relative_foster_care_and_adoption_guardianship.all_funds": ( - "Current 2024 base microdata have zero positive TANF benefit support " - "in West Virginia under PolicyEngine-US state TANF formulas." - ), - "irs_soi.ty2022.historic_table_2.state_agi.ak.under_1.return_count": ( - "Current 2024 base microdata have zero Alaska return-count support in " - "the SOI under-$1 AGI bin." - ), - "irs_soi.ty2022.historic_table_2.us.under_1.income_tax_before_credits_returns": ( - "Current 2024 base microdata have zero positive income-tax-before-" - "credits support in the SOI under-$1 AGI bin." - ), - "irs_soi.ty2022.historic_table_2.us.under_1.income_tax_before_credits_amount": ( - "Current 2024 base microdata have zero income-tax-before-credits " - "amount support in the SOI under-$1 AGI bin." - ), - "irs_soi.ty2022.historic_table_2.us.under_1.income_tax_liability_returns": ( - "Current 2024 base microdata have zero positive income-tax-liability " - "support in the SOI under-$1 AGI bin." - ), - "irs_soi.ty2022.historic_table_2.us.under_1.income_tax_liability_amount": ( - "Current 2024 base microdata have zero income-tax-liability amount " - "support in the SOI under-$1 AGI bin." - ), - "irs_soi.ty2022.historic_table_2.us.1_to_10k.taxable_income_returns": ( - "Current 2024 base microdata have zero positive taxable-income support " - "in this SOI AGI bin." - ), - "irs_soi.ty2022.historic_table_2.us.1_to_10k.taxable_income_amount": ( - "Current 2024 base microdata have zero taxable-income amount support " - "in this SOI AGI bin." - ), - "irs_soi.ty2022.historic_table_2.us.500k_to_1m.actc_claims": ( - "Current-law PolicyEngine-US refundable CTC support is zero in this " - "high-income SOI AGI bin." - ), - "irs_soi.ty2022.historic_table_2.us.500k_to_1m.actc_amount": ( - "Current-law PolicyEngine-US refundable CTC amount support is zero in " - "this high-income SOI AGI bin." - ), - "irs_soi.ty2022.historic_table_2.us.500k_to_1m.medical_dental_expense_returns": ( - "Current 2024 base microdata have zero positive medical-expense " - "deduction support in this SOI AGI bin." - ), - "irs_soi.ty2022.historic_table_2.us.500k_to_1m.medical_dental_expense_amount": ( - "Current 2024 base microdata have zero medical-expense deduction " - "amount support in this SOI AGI bin." - ), - "irs_soi.ty2022.historic_table_2.us.1m_plus.medical_dental_expense_returns": ( - "Current 2024 base microdata have zero positive medical-expense " - "deduction support in this SOI AGI bin." - ), - "irs_soi.ty2022.historic_table_2.us.1m_plus.medical_dental_expense_amount": ( - "Current 2024 base microdata have zero medical-expense deduction " - "amount support in this SOI AGI bin." - ), -} +#: Declared in ``us/fiscal_target_registers.json`` (``support_exclusions``), each entry with its reason. +US_FISCAL_TARGET_SUPPORT_EXCLUSIONS: dict[str, str] = us_fiscal_target_register( + "support_exclusions" +) -# The register above is keyed by exact source_record_id, and latest-vintage -# selection activates the newest remaining fact for each target shape, so -# excluding one vintage of a cell hands its key to the next vintage the feed -# carries. The 2026-09-18 feed re-pin (docs/us-chronicle-feed-repin.md) added -# SOI Table 1.4 cells for ty2020-2022, and the ty2022 other-income rows then -# calibrated in place of the excluded ty2023 rows (microcosm#956). A fact -# matches an entry here when its source_record_id equals the entry's once -# period tokens are stripped (_period_free_source_record_id), so each entry -# drops every vintage of its cell: -# -# - the four #564 other-income rows: the Form 4797 concept mismatch does not -# depend on the tax year; -# - the #451 W-2 Box 7 tips return count: tip support is thin at every -# vintage, and the ty2020 fact carries the same 6,038,613 returns as the -# excluded ty2023 row (the pinned feed's ty2023 W-2 record sets come from -# the soi-w2-statistics-2020 package, chronicle_feed_scope.json). The July -# feed (consumer_facts_buildn_v9_4, facts b3c0835...) carried only the -# ty2020 vintage, so the ty2023-keyed exclusion matched nothing and the -# row calibrated (-52% in experiments/replacement_scorecard/ -# incumbent_48b9d479.md). The pinned feed carries both, latest-vintage -# fallback selected ty2020, and #1016 kept it as the one reviewed vintage -# bypass until decision d179 ruled to enforce #451 at every vintage. -US_FISCAL_TARGET_ALL_VINTAGE_SUPPORT_EXCLUSIONS: frozenset[str] = frozenset( - { - "irs_soi.ty2023.table_1_4.all.other_income_net_loss_amount", - "irs_soi.ty2023.table_1_4.all.other_income_net_loss_returns", - "irs_soi.ty2023.table_1_4.all.other_income_net_income_amount", - "irs_soi.ty2023.table_1_4.all.other_income_net_income_returns", - "irs_soi.ty2023.form_w2_social_security_tips.box_7_social_security_tips.return_count", - } +#: Declared in ``us/fiscal_target_registers.json`` (``all_vintage_support_exclusions``); its description says how a fact matches an entry at every vintage. +US_FISCAL_TARGET_ALL_VINTAGE_SUPPORT_EXCLUSIONS: frozenset[str] = ( + us_fiscal_target_register("all_vintage_support_exclusions") ) -# Reviewed vintage bypasses. Every other exclusion stays keyed to its exact -# vintage, and the compile refuses a selected fact that is another vintage of -# an excluded cell (_check_exclusion_vintage_scope) unless its id is listed -# here with a reason. Removing an entry is mechanical; adding one needs review. -# Empty since decision d179 scoped the ty2020 tips return count's exclusion to -# every vintage. -US_FISCAL_TARGET_EXCLUSION_VINTAGE_BYPASSES: dict[str, str] = {} - -# Reviewed source-column concept exclusions (microcosm#1038). Each entry is an -# IRS column that a Chronicle package publishes under a measure id whose -# concept the column does not carry, so no fact read from that column -# compiles, whatever its package, geography or vintage, and a package -# corrected to read the right column passes untouched. The key is (measure_id, -# layout.source_column_id) because the IRS column is the definition. The -# congressional-district documentation guide (22incddocguide.docx) defines: -# -# - N18425/A18425 as "State and local income taxes" (Schedule A line 5a) and -# N18460/A18460 as "Limited state and local taxes" (line 5e). salt_deduction, -# like the Historic Table 2 rows of these measure ids, is the limited line 5e -# deduction. -# - N85530/A85530 as "Additional Medicare tax" (Form 8959 line 24) and -# N85770/A85770 as "Total premium tax credit" (Form 8962 line 24; the guide -# prints "8926:24"). N85770/A85770 is what the Historic Table 2 rows of -# these measure ids read and what assigned_aca_ptc measures. The amount was -# dropped before by a hard-coded congressional-district check; the returns -# row compiled as premium-tax-credit recipients. A package corrected to read -# N85770/A85770 compiles as assigned_aca_ptc targets with no further gate, -# which is intended: those columns are the premium tax credit. -# -# Chronicle's congressional_district_2022 package reads these four columns -# under the limited_state_local_taxes_* and premium_tax_credit_* measure ids; -# the 46 other measures it shares with a Historic Table 2 package read the -# same column there. Of the six it has alone, interest_paid_deduction_* reads -# N19300/A19300, "Mortgage interest paid" (Schedule A line 8a), while -# interest_deduction is the line 10 total (lines 8a-8c plus investment -# interest on line 9; 8a is 85.6% of it in the TY2022 US row). That is a -# component of the measure's concept, not another concept, so it is not -# listed here: like the line 7 capital-gains rows, it needs a share-or-drop -# decision of its own, which also binds the state_cd surface's itemized -# bridge. -# A congressional-district fact of a listed measure that carries no -# layout.source_column_id refuses the compile, so a feed schema change cannot -# silently lift the exclusion. -US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS: dict[tuple[str, str], str] = { - ("limited_state_local_taxes_returns", "N18425"): ( - "N18425 counts returns with state and local income taxes (Schedule A " - "line 5a), not returns with the limited state and local tax deduction " - "(line 5e, N18460). Chronicle's congressional_district_2022 package " - "reads it under this measure id: TY2022 US 10,842,580 returns against " - "14,777,040 for N18460 in the same file and 14,968,720 in Historic " - "Table 2." - ), - ("limited_state_local_taxes_amount", "A18425"): ( - "A18425 is state and local income taxes before the $10,000 limit " - "(Schedule A line 5a), not the limited deduction (line 5e, A18460) " - "salt_deduction measures. Chronicle's congressional_district_2022 " - "package reads it under this measure id: TY2022 US $250.4B against " - "$121.2B for A18460 in the same file, so on the full surface the " - "congressional-district rows summed to 1.98x the national Historic " - "Table 2 target." - ), - ("premium_tax_credit_returns", "N85530"): ( - "N85530 counts returns with additional Medicare tax (Form 8959 line 24), " - "not returns with the premium tax credit (Form 8962 line 24, N85770) " - "assigned_aca_ptc measures. Chronicle's congressional_district_2022 " - "package reads it under this measure id: TY2022 US 6,848,330 returns " - "against 7,713,000 for N85770 in the same file." - ), - ("premium_tax_credit_amount", "A85530"): ( - "A85530 is additional Medicare tax (Form 8959 line 24), not the premium " - "tax credit (Form 8962 line 24, A85770). Chronicle's " - "congressional_district_2022 package reads it under this measure id: " - "TY2022 US $14.2B against $53.1B for A85770 in the same file." - ), -} +#: Declared in ``us/fiscal_target_registers.json`` (``exclusion_vintage_bypasses``); adding an entry needs review. +US_FISCAL_TARGET_EXCLUSION_VINTAGE_BYPASSES: dict[str, str] = us_fiscal_target_register( + "exclusion_vintage_bypasses" +) + +#: Declared in ``us/fiscal_target_registers.json`` (``source_column_exclusions``); its description gives the IRS column definitions (microcosm#1038). +US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS: dict[tuple[str, str], str] = ( + us_fiscal_target_register("source_column_exclusions") +) @dataclass(frozen=True) @@ -1367,47 +607,8 @@ def us_fiscal_target_exclusion_receipt( } -# Medicaid-expansion-CHIP (M-CHIP) states whose CMS CHIP enrollment rows never -# calibrate (PolicyEngine/microcosm#321). PolicyEngine-US 2.2.1 sets -# gov.hhs.chip.child.income_limit to -inf in all twenty (and in Rhode Island, -# which sits outside the set), covering their children through the Medicaid -# child limits, so chip_enrolled there can come only from the pregnant-person -# paths. The reason differs by state: -# - AK DC HI NC ND NH NM OH SC VT WY: the child, pregnant and FCEP limits are -# all -inf, so the model has no CHIP path and the rows have no support. -# - CA IL KY MD ME MI NE OK: the CMS count is mostly M-CHIP children (PE-US's -# MACPAC enrollment parameters), a concept only a pregnant or FCEP path could -# stand in for. -# - MN: most of its count is separate CHIP (884 M-CHIP vs 4,285 separate in -# the same parameters), so the concept argument does not hold; MN is -# excluded because it is in the #321 state set. -# _without_m_chip_state_chip_enrollment_targets drops these states' direct and -# derived CHIP rows at every period, after latest-vintage selection, and the -# derivation below never builds a derived row for them. -_M_CHIP_STATE_FIPS = frozenset( - { - "02", - "06", - "11", - "15", - "17", - "21", - "23", - "24", - "26", - "27", - "31", - "33", - "35", - "37", - "38", - "39", - "40", - "45", - "50", - "56", - } -) +#: Declared in ``us/fiscal_target_registers.json`` (``m_chip_state_fips``); its description gives the M-CHIP reasons (microcosm#321). +_M_CHIP_STATE_FIPS: frozenset[str] = us_fiscal_target_register("m_chip_state_fips") def _with_derived_chip_enrollment_targets(registry: TargetRegistry) -> TargetRegistry: diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/source_vintage.py b/packages/microcosm-build/src/microcosm/build/us_runtime/source_vintage.py index 3540f78f70..ba7880265f 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/source_vintage.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/source_vintage.py @@ -70,6 +70,9 @@ from dataclasses import dataclass, replace from types import MappingProxyType +from microcosm.build.us_runtime.fiscal_target_registers import ( + us_fiscal_target_register, +) from microcosm.build.us_runtime.target_aging import ( _cbo_projection_series, _period_year, @@ -150,66 +153,43 @@ def _restamped( ) -# Reviewed against consumer_facts_us_c5e5bf8.jsonl (Chronicle c5e5bf8, sha256 -# b8543739...): these are the 26,893 facts both rules detect. Each data year -# was confirmed from the file itself (title cell or content match), not from -# Chronicle labels. "Newest" claims were checked on irs.gov on 2026-09-25. +#: Declared in ``us/fiscal_target_registers.json`` +#: (``restamped_source_packages``); its description and each package's reason +#: give the review evidence. US_RESTAMPED_SOURCE_PACKAGES: Mapping[str, RestampedSourcePackage] = MappingProxyType( dict( - ( - _restamped( - "soi-w2-statistics-2020", - 2020, - "20in04w2all.xlsx", - "1178d77618cc1d2f873506909eeec660f36e3599854f31337f9dcaec6cfc442f", - "IRS SOI Form W-2 statistics Table 4.B, titled 'Tax Year 2020'. " - "The ty2023 tips return_count, taxpayer_count and amount share " - "their source cells, bytes and values with the ty2020 twins; " - "the ty2023 401(k) and designated Roth 401(k) amounts are cells " - "D22 and D41 of the same table. As of 2026-09-25 TY2020 is the " - "newest W-2 table on irs.gov.", - ), - _restamped( - "soi-congressional-district-2022", - 2022, - "22incd.csv", - "137522878af78d624cfddc0e17cd36ae76a21b7bed166c7bb96ad3243a18a668", - "IRS SOI congressional district data for tax year 2022 (the " - "newest CD release as of 2026-09-25). The single-district " - "states match the TY2022 county file (for example WY N1 " - "280,740), and the US taxable interest is 92.7% of TY2022 " - "Table 1.4 against 39.4% of TY2023 (PolicyEngine/chronicle#117).", - ), - _restamped( - "soi-state-2022", - 2022, - "22in54us.xlsx", - "5e58050449c07c2e941f280c60d597784047f02ee1fa93dc1aed64fc1ea493f6", - "IRS SOI Historic Table 2 US totals, titled 'Tax Year 2022'.", - ), - _restamped( - "soi-ira-roth-contributions-2022", - 2022, - "22in06ira.xlsx", - "c1fb0894cb09d2486be4510b7e6ce0b8597787725b928ab8813f577d9fb13183", - "IRS SOI IRA Table 6 (Roth contributions), titled 'Tax Year 2022'.", - ), - _restamped( - "soi-ira-traditional-contributions-2022", - 2022, - "22in05ira.xlsx", - "31ce9dd2fe631b336170af339bd7e9de86901cd20dbfd4cb8fb1c9a1d55cd90f", - "IRS SOI IRA Table 5 (traditional contributions), titled " - "'Tax Year 2022'.", - ), + _restamped( + package_id, + data_year, + source_file, + source_sha256, + reason, + stamped_periods=stamped_periods, ) + for package_id, ( + data_year, + stamped_periods, + source_file, + source_sha256, + reason, + ) in us_fiscal_target_register("restamped_source_packages").items() ) ) -# None on the pinned feed: no package there observes a year after its key. +#: Declared in ``us/fiscal_target_registers.json`` +#: (``later_period_observation_exemptions``). US_LATER_PERIOD_OBSERVATION_EXEMPTIONS: Mapping[ str, LaterPeriodObservationExemption -] = MappingProxyType({}) +] = MappingProxyType( + { + package_id: LaterPeriodObservationExemption( + package_id=package_id, periods=frozenset(periods), reason=reason + ) + for package_id, (periods, reason) in us_fiscal_target_register( + "later_period_observation_exemptions" + ).items() + } +) @dataclass(frozen=True) diff --git a/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py b/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py index 92bd130306..d3c5812f7d 100644 --- a/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py +++ b/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py @@ -82,22 +82,22 @@ def test_us_coverage_is_exact_complete_and_honest( assert_coverage_complete(coverage_report) assert coverage_report["status"] == "pass" fields = coverage_report["field_usage"] - assert fields["configuration_field_count"] == 42410 - assert fields["authored_normative_field_count"] == 32624 + assert fields["configuration_field_count"] == 42413 + assert fields["authored_normative_field_count"] == 32627 assert fields["resolved_binding_field_count"] == 9786 - assert fields["consumed_field_count"] == 42410 + assert fields["consumed_field_count"] == 42413 assert fields["unused_field_count"] == 0 assert fields["multiple_primary_use_field_count"] == 0 assert fields["claim_count"] == 48 assert fields["mode_counts"] == { "legacy_behavior": 14_269, "compiler_semantic": 27674, - "front_end_validation": 364, + "front_end_validation": 367, "identity_only": 103, } assert fields["generation0_effect_counts"] == { "legacy_behavior": 38_780, - "no_generation0_effect": 3630, + "no_generation0_effect": 3633, } inventory = coverage_report["inventory_coverage"] diff --git a/packages/microcosm-build/tests/engine_free/shared/test_declared_registers.py b/packages/microcosm-build/tests/engine_free/shared/test_declared_registers.py new file mode 100644 index 0000000000..e87a416994 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_declared_registers.py @@ -0,0 +1,132 @@ +"""Reviewed registers declared as data (microcosm.build.declared_registers). + +The registers here are made up. They check how a section reads back: one key +field or a tuple of them, one value field, a tuple of them or none, JSON arrays +as tuples, entry order, and the refusals. No country data is read +(microcosm#1728). +""" + +from __future__ import annotations + +import copy + +import pytest + +from microcosm.build.declared_registers import ( + DeclaredRegisterError, + load_register, +) + + +def _section(**overrides) -> dict: + section = { + "description": ["Columns a package reads under the wrong measure."], + "key": ["measure", "column"], + "value": "reason", + "entries": [ + {"measure": "tax_b", "column": "C2", "reason": "Wrong line."}, + { + "measure": "tax_a", + "column": "C1", + "reason": "Wrong form.", + "note": ["Checked against the guide."], + }, + ], + } + section.update(overrides) + return section + + +def test_a_tuple_key_and_one_value_keep_entry_order() -> None: + register = load_register(_section()) + assert register == {("tax_b", "C2"): "Wrong line.", ("tax_a", "C1"): "Wrong form."} + assert list(register) == [("tax_b", "C2"), ("tax_a", "C1")] + + +def test_one_key_field_and_tuple_values() -> None: + register = load_register( + { + "description": "Variables of each concept.", + "key": "concept", + "value": ["variables", "family", "metadata"], + "entries": [ + { + "concept": "income", + "variables": ["wages", "tips"], + "family": "tax", + "metadata": {"role": "x"}, + }, + { + "concept": "rent", + "variables": "rent", + "family": "tax", + "metadata": {}, + }, + ], + } + ) + assert register == { + "income": (("wages", "tips"), "tax", {"role": "x"}), + "rent": ("rent", "tax", {}), + } + assert isinstance(register["income"][0], tuple) + + +def test_a_set_register_and_a_null_key_part() -> None: + assert load_register( + { + "description": "Excluded states.", + "key": "state", + "value": None, + "entries": [{"state": "02"}, {"state": "06"}], + } + ) == frozenset({"02", "06"}) + assert load_register( + { + "description": "Groups.", + "key": ["source", "group"], + "value": "variable", + "entries": [{"source": "cbo", "group": None, "variable": "v"}], + } + ) == {("cbo", None): "v"} + + +def _broken(): + def change(path, value): + def mutate(section): + target = section + for step in path[:-1]: + target = target[step] + if value is _DROP: + del target[path[-1]] + else: + target[path[-1]] = value + + return mutate + + return { + "no description": change(("description",), _DROP), + "empty description": change(("description",), []), + "unknown section key": change(("extra",), 1), + "repeated key field": change(("key",), ["measure", "measure"]), + "key and value overlap": change(("value",), "measure"), + "note as a field": change(("value",), "note"), + "entries not a list": change(("entries",), {}), + "missing field": change(("entries", 0, "column"), _DROP), + "unknown field": change(("entries", 0, "extra"), 1), + "empty note": change(("entries", 1, "note"), ""), + "repeated key": change(("entries", 1, "column"), "C2"), + } + + +_DROP = object() + + +@pytest.mark.parametrize("case", sorted(_broken())) +def test_a_malformed_register_refuses(case: str) -> None: + section = copy.deepcopy(_section()) + if case == "repeated key": + section["entries"][1]["measure"] = "tax_b" + _broken()[case](section) + with pytest.raises(DeclaredRegisterError): + load_register(section) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py index 2b9db90be3..6c08206980 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py @@ -95,22 +95,22 @@ def _mutated_bundle( def test_exact_complete_ledger_has_one_primary_mode_per_pointer(field_ledger) -> None: - assert len(field_ledger.fields) == EXPECTED_CONFIGURATION_FIELD_COUNT == 42410 + assert len(field_ledger.fields) == EXPECTED_CONFIGURATION_FIELD_COUNT == 42413 assert field_ledger.source_counts == { - "authored": 32624, + "authored": 32627, "resolved_bindings": 9786, } assert field_ledger.mode_counts == { "legacy_behavior": 14_269, "compiler_semantic": 27674, - "front_end_validation": 364, + "front_end_validation": 367, "identity_only": 103, } assert field_ledger.generation0_effect_counts == { "legacy_behavior": 38_780, - "no_generation0_effect": 3630, + "no_generation0_effect": 3633, } - assert len({field.pointer for field in field_ledger.fields}) == 42410 + assert len({field.pointer for field in field_ledger.fields}) == 42413 def test_eligibility_concepts_are_validation_not_generation0_behavior( diff --git a/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py b/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py index ee59342f73..7144b87bfe 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py @@ -155,6 +155,10 @@ # microcosm#1030: us_runtime.fiscal_targets imports the source-vintage # corrections for restamped Chronicle facts. "microcosm.build.us_runtime.source_vintage", + # microcosm#1728: us_runtime.fiscal_targets and source_vintage read + # their reviewed registers through these two modules. + "microcosm.build.declared_registers", + "microcosm.build.us_runtime.fiscal_target_registers", # microcosm#1585: the US keyed draws call # stochastic_assignment.stable_identity_uniforms. "microcosm.build.stochastic_assignment", diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_target_registers.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_target_registers.py new file mode 100644 index 0000000000..f2fafc8ca7 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_target_registers.py @@ -0,0 +1,239 @@ +"""The US compile registers read from declared data as the old literals did. + +microcosm#1728 moved the reviewed registers of the US fiscal target compile +from Python literals in ``us_runtime/fiscal_targets.py`` and +``us_runtime/source_vintage.py`` to ``us/fiscal_target_registers.json``, read +by the shared ``microcosm.build.declared_registers``. The digests below were +measured on the literals at ``904a46d86``, before the move. A digest covers +the keys, the values, their Python types (a tuple is not a list) and the entry +order, so an equal digest is the same register. + +The pinned-feed tests compile the pinned ``41b2fb2`` feed under four flag sets +and pin the full registry JSON, and pin the exclusion receipt. They run only +when ``MICROCOSM_US_CHRONICLE_FACTS`` names the pinned feed. +""" + +from __future__ import annotations + +import dataclasses +import hashlib +import json +import os +from pathlib import Path + +import pytest + +from microcosm.build.declared_registers import package_registers +from microcosm.build.us_runtime import fiscal_targets, source_vintage +from microcosm.build.us_runtime.fiscal_target_registers import ( + US_FISCAL_TARGET_REGISTERS_RESOURCE, + us_fiscal_target_register, +) + +#: (module, name) -> digest of the literal it replaced. +PINNED_REGISTERS = { + ("fiscal_targets", "SOI_AMOUNT_MEASURE_VARIABLES"): ( + "e9de59d33a9f522ae88ebf34e76365cc010dfc7ee04d12a42a632460dffb7330" + ), + ("fiscal_targets", "SOI_RETURN_MEASURE_VARIABLES"): ( + "62b1cd21abd3dbbc469e68722e8fd6e60e8d0775f12cf4cf1008aac30f9d248d" + ), + ("fiscal_targets", "SOI_VARIABLE_MAP"): ( + "fdadeab36c1c42177bc57d8987395e6628944c182c8cb30a63cf92e564ac121e" + ), + ("fiscal_targets", "_SOI_BASE_VARIABLE_OVERRIDES"): ( + "3104dff5c88f8de11c3f80c9e362da7e7c6d2a4dfe5102b7a063a22142b93a17" + ), + ("fiscal_targets", "DIRECT_LEDGER_TARGETS"): ( + "c991f34caf1e9bde876777a2785f42f736b0331013ce0a72c4e25c627863e9e5" + ), + ("fiscal_targets", "INDICATOR_LEDGER_TARGETS"): ( + "dbe04076e64d03cd561a0ce2087db3d36e87e93d7f7b1405633d23267e098d49" + ), + ("fiscal_targets", "US_FISCAL_TARGET_SUPPORT_EXCLUSIONS"): ( + "0557e4028686d83baffb643546ce607f3ccdad925fdd3069d20461fac4ef45ac" + ), + ("fiscal_targets", "US_FISCAL_TARGET_ALL_VINTAGE_SUPPORT_EXCLUSIONS"): ( + "8bf5ae5682a618737d7d2868e72a2f0433b3febc6d63741cbaa4a59074019444" + ), + ("fiscal_targets", "US_FISCAL_TARGET_EXCLUSION_VINTAGE_BYPASSES"): ( + "42adf0d3280d340b19fe97e4e275dfe458029cfa2c8f287e44f0099b444fed47" + ), + ("fiscal_targets", "US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS"): ( + "0209724942fcbafcd460630749e066fe46d0efdf2d44f61b18a8ce6279e63ed4" + ), + ("fiscal_targets", "_M_CHIP_STATE_FIPS"): ( + "c952168ebc0e0c1d346306e248ff51a570e163a8bc5b26cdbecdaf8ec99346e8" + ), + ("source_vintage", "US_RESTAMPED_SOURCE_PACKAGES"): ( + "2c259b40a92efbe2a582a5f7f2c336f3a30f2ffcf2873bc306c5b8a3ddf26ab1" + ), + ("source_vintage", "US_LATER_PERIOD_OBSERVATION_EXEMPTIONS"): ( + "42adf0d3280d340b19fe97e4e275dfe458029cfa2c8f287e44f0099b444fed47" + ), +} + +#: The compile of the pinned feed under four flag sets, before the move: +#: (targets, TargetRegistry.version, sha256 of the registry JSON). +PINNED_COMPILES = { + "unaged": ( + 31_747, + "8cb6469905f8", + "efded864baf7c0b18d4326c7dd9515556f03c495df6c92963972b9fbab5a61fc", + ), + "aged": ( + 31_747, + "6fe934db05ea", + "c756b266e2e7f074c906817248f9cb99c0c5c930be80bde3639abe195a0b8fa9", + ), + "unaged_student_loans": ( + 31_877, + "d8c4e2f13bee", + "0e733bfd69d4e6c67b2e5a8b0372a2d2aa9f7f7fd4efff31b261914bf8c310ea", + ), + "aged_student_loans": ( + 31_877, + "fe558dd37fb4", + "6767f33ac5fad73ffc56333ca0634b77b041e21a3106d424a3751ae56b98b756", + ), +} +COMPILE_FLAGS = { + "unaged": {"allow_unaged_dollar_targets": True}, + "aged": {"age_targets": True}, + "unaged_student_loans": { + "allow_unaged_dollar_targets": True, + "student_loan_targets": True, + }, + "aged_student_loans": {"age_targets": True, "student_loan_targets": True}, +} +PINNED_EXCLUSION_RECEIPT_SHA256 = ( + "04a74b9cdcc674465497c1bff28ed953173690e36d2bda5c1480a92c1bffe22f" +) + +#: The register sections of the file, and the names the code gives them. +SECTIONS = { + "support_exclusions": "US_FISCAL_TARGET_SUPPORT_EXCLUSIONS", + "all_vintage_support_exclusions": "US_FISCAL_TARGET_ALL_VINTAGE_SUPPORT_EXCLUSIONS", + "exclusion_vintage_bypasses": "US_FISCAL_TARGET_EXCLUSION_VINTAGE_BYPASSES", + "source_column_exclusions": "US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS", + "soi_amount_measure_variables": "SOI_AMOUNT_MEASURE_VARIABLES", + "soi_return_measure_variables": "SOI_RETURN_MEASURE_VARIABLES", + "soi_variables": "SOI_VARIABLE_MAP", + "soi_base_variable_overrides": "_SOI_BASE_VARIABLE_OVERRIDES", + "direct_targets": "DIRECT_LEDGER_TARGETS", + "indicator_targets": "INDICATOR_LEDGER_TARGETS", + "m_chip_state_fips": "_M_CHIP_STATE_FIPS", + "restamped_source_packages": "US_RESTAMPED_SOURCE_PACKAGES", + "later_period_observation_exemptions": "US_LATER_PERIOD_OBSERVATION_EXEMPTIONS", +} + + +def _canon(value): + """Keys, values, Python types and order, as JSON (the baseline's encoding).""" + + if isinstance(value, dict) or ( + hasattr(value, "items") and not isinstance(value, (str, bytes)) + ): + return ["", [[_canon(k), _canon(v)] for k, v in value.items()]] + if isinstance(value, (frozenset, set)): + return ["", sorted(_canon(v) for v in value)] + if isinstance(value, (tuple, list)): + kind = "" if isinstance(value, tuple) else "" + return [kind, [_canon(v) for v in value]] + if dataclasses.is_dataclass(value): + return [ + "", + [ + [field.name, _canon(getattr(value, field.name))] + for field in dataclasses.fields(value) + ], + ] + return [type(value).__name__, value] + + +def _digest(value) -> str: + return hashlib.sha256(json.dumps(_canon(value), default=str).encode()).hexdigest() + + +@pytest.mark.parametrize( + ("module", "name"), sorted(PINNED_REGISTERS), ids=lambda part: str(part) +) +def test_each_register_reads_back_as_the_literal_it_replaced( + module: str, name: str +) -> None: + """The declared register equals the literal: content, types and order. + + A ``fiscal_targets`` register is read fresh from the file, because other + tests patch the module's dict in place, and ``monkeypatch.delitem`` + restores a key at the end, which changes the order but not the content. + The module's object must hold the same content. The ``source_vintage`` + registers are read-only mapping proxies, so the module's objects are read. + """ + + if module == "fiscal_targets": + section = {value: key for key, value in SECTIONS.items()}[name] + declared = us_fiscal_target_register(section) + assert getattr(fiscal_targets, name) == declared + else: + declared = getattr(source_vintage, name) + assert _digest(declared) == PINNED_REGISTERS[(module, name)] + + +def test_the_file_declares_exactly_the_registers_the_code_reads() -> None: + registers = package_registers( + "microcosm.build.us", US_FISCAL_TARGET_REGISTERS_RESOURCE + ) + assert set(registers) == set(SECTIONS) + assert sorted(SECTIONS.values()) == sorted( + name for _module, name in PINNED_REGISTERS + ) + + +def _pinned_feed() -> str: + feed = os.environ.get("MICROCOSM_US_CHRONICLE_FACTS", "") + if not feed or not Path(feed).exists(): + pytest.skip("set MICROCOSM_US_CHRONICLE_FACTS to the pinned 41b2fb2 feed") + return feed + + +@pytest.fixture(scope="module") +def pinned_facts(): + from microcosm.build.ledger_artifact import load_ledger_consumer_artifact + from microcosm.build.us_runtime import ( + default_congressional_district_vintage_crosswalk_path, + load_congressional_district_vintage_crosswalk, + ) + + facts = load_ledger_consumer_artifact(_pinned_feed()).facts + crosswalk = load_congressional_district_vintage_crosswalk( + default_congressional_district_vintage_crosswalk_path() + ) + return facts, crosswalk + + +@pytest.mark.parametrize("label", sorted(PINNED_COMPILES)) +def test_pinned_feed_compiles_are_unchanged(pinned_facts, label: str, tmp_path) -> None: + facts, crosswalk = pinned_facts + registry = fiscal_targets.compile_us_fiscal_target_registry( + facts, + target_period=2024, + congressional_district_vintage_crosswalk=crosswalk, + **COMPILE_FLAGS[label], + ) + path = registry.to_json(tmp_path / f"{label}.json") + assert ( + len(registry.specs), + registry.version, + hashlib.sha256(path.read_bytes()).hexdigest(), + ) == PINNED_COMPILES[label] + + +def test_pinned_feed_exclusion_receipt_is_unchanged(pinned_facts) -> None: + facts, crosswalk = pinned_facts + receipt = fiscal_targets.us_fiscal_target_exclusion_receipt( + facts, target_period=2024, congressional_district_vintage_crosswalk=crosswalk + ) + digest = hashlib.sha256( + json.dumps(receipt, indent=1, default=str).encode() + ).hexdigest() + assert digest == PINNED_EXCLUSION_RECEIPT_SHA256 diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py index bf7ac56faa..25b2812de5 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py @@ -372,6 +372,9 @@ # construction (us/local_target_construction.json, microcosm#1728); # reads no frame and treats no population. "local_target_construction.py", + # Names the reviewed registers of the fiscal target compile + # (us/fiscal_target_registers.json, microcosm#1728); reads no frame. + "fiscal_target_registers.py", "l0_refit_export.py", "late_producer_dag.py", # Pure contract/schedule derivation; no treatment. "medicaid_take_up.py", diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py index 1335df1ab9..2c2b7ac43d 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py @@ -373,7 +373,7 @@ def capture_equality(expected: object, actual: object) -> None: # microcosm#1686's shared SIPP person-file read moves it again. # The SIPP 2023 donor download tag and the financial-asset cache lookup # move it again. - "spec_sha256": "c25fbed9c0d92248707f59101b516125f8437c42e2cebe84a72e28f6ac0f39c0", + "spec_sha256": "5035e939cc241ca9e94b9454a94e90e4450a4724d28aadb76026ee86d2442820", }, } diff --git a/tools/generate_us_bundle_from_constants.py b/tools/generate_us_bundle_from_constants.py index c981a3fb9b..dc9407b544 100644 --- a/tools/generate_us_bundle_from_constants.py +++ b/tools/generate_us_bundle_from_constants.py @@ -146,6 +146,8 @@ def _domain_builders() -> dict[str, Callable[[], object]]: "ecps_parity_known_gaps.json", "ecps_parity_reference.json", "federal_eitc_by_state.json", + # The reviewed registers of the US fiscal target compile (microcosm#1728). + "fiscal_target_registers.json", "fiscal_target_references.json", "gates.json", # The ACS local release's declared target construction (microcosm#1728). diff --git a/tools/spec_engine_coverage.py b/tools/spec_engine_coverage.py index b7f268cfb0..5525c592ef 100644 --- a/tools/spec_engine_coverage.py +++ b/tools/spec_engine_coverage.py @@ -41,7 +41,7 @@ REPORT_SCHEMA_VERSION = 3 EXPECTED_POINTER_INVENTORY_SHA256 = ( - "bbf2213acf3453f09be80542c9b86f5571b6659ce196c1979be9961f0c0a6f66" + "8e3b7c8680e0a5c5626867c1b697b6b6d98058b383c2f7d368f0b5b5df3105b1" ) DEFAULT_REPORT_PATH = ( Path(__file__).resolve().parents[1] From fba28da9808c7f576f9917a7d5b2d5e22a3c3e85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:39:51 +0000 Subject: [PATCH 10/30] Pin the new name of the US matrix-row measures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Commit C2 moved csr_row_measure from the district tool to the shared microcosm.build.target_holdouts. The calibration diagnostics name a callable measure ., so each matrix-row measure is now microcosm.build.target_holdouts.target_matrix_row[N] instead of us_acs_local_cd_surface.target_matrix_row[N]. The targets and weights do not change, but target_surface.sha256 does. María accepted the new name on 26 Nov 2026 (microcosm#1759 plan, decision 1). The new test pins it, and the changelog says so for anyone who compares two releases. Co-Authored-By: Claude Opus 5.5 --- .../1728-shared-target-holdouts.added.md | 2 +- .../engine_free/us/test_us_target_holdouts.py | 29 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/changelog.d/1728-shared-target-holdouts.added.md b/changelog.d/1728-shared-target-holdouts.added.md index a72dc932dc..2bd9ccd34b 100644 --- a/changelog.d/1728-shared-target-holdouts.added.md +++ b/changelog.d/1728-shared-target-holdouts.added.md @@ -1 +1 @@ -Target hold-outs are shared code for any country (microcosm#1728): `microcosm.build.target_holdouts` draws held-out targets by hashed blocks from declared passes (scope, eligibility, unit key, salt, fractions, receipt), builds the training target set, and scores the held rows against a pro-rata baseline. The ACS local release declares its district and county passes in the new `us/local_target_construction.json`, read by `microcosm.build.us_runtime.local_target_construction`; the tool functions call the shared code under their old names. No target, role or receipt changes: `test_us_target_holdouts.py` holds the shared code to verbatim copies of the replaced tool code, and the pinned bytes of `test_us_acs_local_surface_bytes.py` are unchanged. The new resource row moves the US F0 spec-engine pins (42,410 configuration fields). +Target hold-outs are shared code for any country (microcosm#1728): `microcosm.build.target_holdouts` draws held-out targets by hashed blocks from declared passes (scope, eligibility, unit key, salt, fractions, receipt), builds the training target set, and scores the held rows against a pro-rata baseline. The ACS local release declares its district and county passes in the new `us/local_target_construction.json`, read by `microcosm.build.us_runtime.local_target_construction`; the tool functions call the shared code under their old names. No target, role or receipt changes: `test_us_target_holdouts.py` holds the shared code to verbatim copies of the replaced tool code, and the pinned bytes of `test_us_acs_local_surface_bytes.py` are unchanged. The new resource row moves the US F0 spec-engine pins (42,410 configuration fields). One label changes: `calibration_diagnostics.json` names each matrix-row measure `microcosm.build.target_holdouts.target_matrix_row[N]` instead of `us_acs_local_cd_surface.target_matrix_row[N]`, because the function that makes it moved to the shared module. So the diagnostics' `target_surface.sha256` (and the same field in `build_manifest.json`) changes for the same targets and weights; `names_sha256` and `values_sha256` do not. Accepted on 26 Nov 2026 and pinned in `test_us_target_holdouts.py`. diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_target_holdouts.py b/packages/microcosm-build/tests/engine_free/us/test_us_target_holdouts.py index b3c7f8b1ae..8093cd730b 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_target_holdouts.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_target_holdouts.py @@ -328,6 +328,35 @@ def test_training_sets_and_scores_match(tool, seed: int) -> None: assert _dumps(new_score) == _dumps(old_score) +def test_diagnostics_name_each_matrix_row_by_the_shared_module(tool) -> None: + """The name ``calibration_diagnostics.json`` gives a matrix-row measure. + + The diagnostics name a callable measure ``.``. + Before microcosm#1728 moved ``csr_row_measure`` to the shared + ``microcosm.build.target_holdouts``, the district tool defined it, so the + name was ``us_acs_local_cd_surface.target_matrix_row[N]``. It is now + ``microcosm.build.target_holdouts.target_matrix_row[N]``: the targets and + weights are the same, but ``target_surface.sha256`` changes. María + accepted the new name on 26 Nov 2026; this pins it. + """ + + from microcosm.calibrate.diagnostics import _selector_payload + + records = _records(5) + tool.cd_surface.assign_target_roles(records, fraction=0.5) + matrix = _matrix(len(records), 7, 5) + target_set = tool.cd_surface.calibration_target_set(records, matrix, 7) + rows = tool.cd_surface.train_rows(records) + assert rows + assert [_selector_payload(target.measure) for target in target_set.targets] == [ + { + "kind": "callable", + "name": f"microcosm.build.target_holdouts.target_matrix_row[{row}]", + } + for row in rows + ] + + def test_scores_with_no_held_rows_match(tool) -> None: old, new = _records(3), _records(3) reference.cd_assign_target_roles(old, fraction=0.0) From e9317a3bbb13c28fcf65a985f3853d6f3b152f67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:39:57 +0000 Subject: [PATCH 11/30] Read a declared level rule and select by level in the shared target sets microcosm.calibrate.target_sets gains what the UK selection needs, as data: - A declaration can give a level_rule in place of level_keys: the metadata keys, a closed set of levels or "*", and whether two keys that disagree are refused. level_keys stays the short form of an open rule that takes the first key, so the US declarations read as before. - select_by_levels keeps the targets of a run-time set of levels (all by default) in compile order, for a mode with one clause for each level of a closed set. It returns them as a registry with the receipt schema microcosm.calibrate.target-selection.v1, and refuses a bad request, a requested level that no target has, and an empty selection, with the texts of microcosm.calibrate.target_selection. Nothing calls it yet (microcosm#1759, step D1). New shared tests cover the rule's forms and refusals and the selection and its receipt; the existing target-set tests pass unchanged. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/calibrate/target_sets.py | 254 +++++++++++++++++- .../engine_free/shared/test_target_sets.py | 220 +++++++++++++++ 2 files changed, 466 insertions(+), 8 deletions(-) diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py b/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py index 2a0947606b..54b5dd720e 100644 --- a/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py @@ -34,6 +34,21 @@ (``microcosm.calibrate.target_loss_rules``, microcosm#1729), so a target has one family and one level everywhere. +A declaration can give a ``level_rule`` in place of ``level_keys``:: + + "level_rule": { + "keys": ["", ...], + "values": ["", ...] or "*", + "conflict": "first" or "refuse", + "rationale": "" + } + +``values`` closes the set of levels: a target whose level is not one of them, +or that has no level, is refused. With ``"conflict": "refuse"``, a target +whose keys hold two different levels is refused; with ``"first"``, the first +key that has a value gives the level. ``level_keys`` is the short form of a +rule with ``"values": "*"`` and ``"conflict": "first"``. + **Compiled clauses.** A clause keeps the compiled specs that pass all of its tests, in compile order: @@ -60,6 +75,15 @@ the level that each value of its option gives, so that the declaration states the whole target set. The selector does not make these rows. +**Selection by level.** A mode with a closed level set and one clause for +each level (any family, no tests, its own level) can also be selected by a +set of levels that the caller gives at run time. :func:`select_by_levels` +keeps the targets of those levels (all of them by default) in compile order. +It returns them as a registry, with a receipt that lists every target, kept +or not (schema ``microcosm.calibrate.target-selection.v1``). It refuses a +requested level that no target has, and an empty selection. The UK full +build selects its solve surface this way (microcosm#1759). + **Rationale.** Each clause and built entry has a ``rationale``: why the product keeps those rows. The UK membership files give a signed rationale for each exclusion in the same way. @@ -67,6 +91,7 @@ from __future__ import annotations +import hashlib import json from collections import Counter from collections.abc import Callable, Iterable, Mapping, Sequence @@ -75,11 +100,17 @@ from types import MappingProxyType from typing import Any +from .registry import TargetRegistry + __all__ = [ "ANY", "DECLARATION_VERSION", + "LEVEL_CONFLICTS", + "SELECTION_RECEIPT_SCHEMA", "UNSPECIFIED_LEVEL", "BuiltRows", + "LevelRule", + "LevelSelection", "MetadataTest", "ProductDeclaration", "TargetSetClause", @@ -89,6 +120,7 @@ "TargetSetSelection", "clause_predicate", "load_target_set_declarations", + "select_by_levels", "select_target_set", "target_level", "target_set_census", @@ -98,8 +130,15 @@ ANY = "*" DECLARATION_VERSION = 1 UNSPECIFIED_LEVEL = "unspecified" +#: How a level rule treats a target whose keys hold different levels. +LEVEL_CONFLICTS = ("first", "refuse") +#: The receipt schema of :func:`select_by_levels`. +SELECTION_RECEIPT_SCHEMA = "microcosm.calibrate.target-selection.v1" -_TOP_KEYS = frozenset({"version", "country", "description", "level_keys", "products"}) +_TOP_KEYS = frozenset( + {"version", "country", "description", "level_keys", "level_rule", "products"} +) +_LEVEL_RULE_KEYS = frozenset({"keys", "values", "conflict", "rationale"}) _PRODUCT_KEYS = frozenset({"tool", "option", "default_mode", "modes"}) _MODE_KEYS = frozenset({"description", "compiled", "built"}) _CLAUSE_KEYS = frozenset( @@ -132,6 +171,43 @@ def target_level(spec: Any, level_keys: Sequence[str]) -> str: return UNSPECIFIED_LEVEL +@dataclass(frozen=True) +class LevelRule: + """How a target's level is read from its metadata (see the module docstring). + + The level is the first truthy value of ``keys``. With ``conflict`` set to + ``"refuse"``, two keys that hold different truthy values are refused. + With ``values`` (a closed set), a level outside it is refused, and so is a + target with no level; without it (``None``), a target with no level is + ``"unspecified"``. + """ + + keys: tuple[str, ...] + values: frozenset[str] | None = None + conflict: str = "first" + rationale: str = "" + + def level_of(self, spec: Any) -> str: + if self.values is None and self.conflict == "first": + return target_level(spec, self.keys) + held = [spec.metadata.get(key) for key in self.keys] + if self.conflict == "refuse": + present = [value for value in held if value] + if any(value != present[0] for value in present[1:]): + raise ValueError( + f"Target {spec.name!r} has contradictory geography levels." + ) + # The first truthy value, else the last key's value, as ``a or b`` does. + level = next((value for value in held if value), held[-1]) + if self.values is None: + return str(level) if level else UNSPECIFIED_LEVEL + if level not in self.values: + raise ValueError( + f"Target {spec.name!r} has unsupported geography level {level!r}." + ) + return str(level) + + @dataclass(frozen=True) class MetadataTest: """One test on one metadata key.""" @@ -206,6 +282,8 @@ class TargetSetDeclaration: level_keys: tuple[str, ...] compiled: tuple[TargetSetClause, ...] built: tuple[BuiltRows, ...] + #: The country's level rule; ``None`` reads ``level_keys`` alone. + level_rule: LevelRule | None = None @property def clause_ids(self) -> tuple[str, ...]: @@ -229,6 +307,8 @@ def built_rows(self, built_id: str) -> BuiltRows: ) def level_of(self, spec: Any) -> str: + if self.level_rule is not None: + return self.level_rule.level_of(spec) return target_level(spec, self.level_keys) @@ -263,6 +343,7 @@ class TargetSetDeclarations: country: str level_keys: tuple[str, ...] products: Mapping[str, ProductDeclaration] + level_rule: LevelRule | None = None def product(self, name: str) -> ProductDeclaration: try: @@ -363,6 +444,36 @@ def _clause(where: str, raw: object) -> TargetSetClause: ) +def _level_rule(where: str, top: Mapping[str, Any]) -> LevelRule: + """The declaration's level rule: ``level_rule``, or the ``level_keys`` form.""" + + if ("level_keys" in top) == ("level_rule" in top): + raise _fail(where, "give exactly one of level_keys and level_rule.") + if "level_keys" in top: + level_keys = top["level_keys"] + if not isinstance(level_keys, list) or not level_keys: + raise _fail( + f"{where}.level_keys", "must be a nonempty list of metadata keys." + ) + return LevelRule(tuple(_text(f"{where}.level_keys", key) for key in level_keys)) + at = f"{where}.level_rule" + rule = _require_keys(at, top["level_rule"], _LEVEL_RULE_KEYS, _LEVEL_RULE_KEYS) + keys = rule["keys"] + if not isinstance(keys, list) or not keys: + raise _fail(f"{at}.keys", "must be a nonempty list of metadata keys.") + keys = tuple(_text(f"{at}.keys", key) for key in keys) + if len(set(keys)) != len(keys): + raise _fail(f"{at}.keys", "repeats a key.") + if rule["conflict"] not in LEVEL_CONFLICTS: + raise _fail(f"{at}.conflict", f"must be one of {list(LEVEL_CONFLICTS)}.") + return LevelRule( + keys=keys, + values=_names(f"{at}.values", rule["values"]), + conflict=rule["conflict"], + rationale=_text(f"{at}.rationale", rule["rationale"]), + ) + + def _built(where: str, raw: object) -> BuiltRows: built = _require_keys( where, raw, _BUILT_KEYS, ("id", "family", "levels", "source", "rationale") @@ -396,16 +507,12 @@ def load_target_set_declarations( else: path = Path(source) raw, where = json.loads(path.read_text(encoding="utf-8")), str(path) - top = _require_keys( - where, raw, _TOP_KEYS, ("version", "country", "level_keys", "products") - ) + top = _require_keys(where, raw, _TOP_KEYS, ("version", "country", "products")) if top["version"] != DECLARATION_VERSION: raise _fail(where, f"version must be {DECLARATION_VERSION}.") country = _text(f"{where}.country", top["country"]) - level_keys = top["level_keys"] - if not isinstance(level_keys, list) or not level_keys: - raise _fail(f"{where}.level_keys", "must be a nonempty list of metadata keys.") - level_keys = tuple(_text(f"{where}.level_keys", key) for key in level_keys) + level_rule = _level_rule(where, top) + level_keys = level_rule.keys products_raw = top["products"] if not isinstance(products_raw, Mapping) or not products_raw: raise _fail(f"{where}.products", "must name at least one product.") @@ -449,6 +556,7 @@ def load_target_set_declarations( level_keys=level_keys, compiled=compiled, built=built, + level_rule=level_rule, ) default_mode = _text(f"{at}.default_mode", product["default_mode"]) if default_mode not in modes: @@ -466,6 +574,7 @@ def load_target_set_declarations( country=country, level_keys=level_keys, products=MappingProxyType(products), + level_rule=level_rule, ) @@ -558,6 +667,135 @@ def select_target_set( ) +@dataclass(frozen=True) +class LevelSelection: + """Selected targets in compile order, and a receipt detached from them.""" + + registry: TargetRegistry + _receipt_json: str + + @property + def receipt(self) -> dict[str, object]: + """A fresh receipt; a caller that changes it cannot change its bytes.""" + return json.loads(self._receipt_json) + + @property + def sha256(self) -> str: + return hashlib.sha256(self.to_bytes()).hexdigest() + + def to_bytes(self) -> bytes: + """The canonical receipt bytes.""" + return self._receipt_json.encode("utf-8") + + +def _require_level_mode(declaration: TargetSetDeclaration) -> None: + """Refuse a mode that is not one clause for each level of a closed set.""" + + at = f"{declaration.product}/{declaration.mode}" + rule = declaration.level_rule + if rule is None or rule.values is None: + raise TargetSetDeclarationError( + f"{at}: selection by level needs a level_rule with a closed set of values." + ) + for clause in declaration.compiled: + if ( + clause.families is not None + or clause.levels != frozenset({clause.clause_id}) + or clause.metadata + or clause.exclude + or clause.rule is not None + ): + raise TargetSetDeclarationError( + f"{at}: clause {clause.clause_id!r} is not a level clause (any " + "family, levels [its own id], and no test, exclusion or rule)." + ) + if set(declaration.clause_ids) != rule.values: + raise TargetSetDeclarationError( + f"{at}: the clauses {sorted(declaration.clause_ids)} are not the " + f"levels {sorted(rule.values)}." + ) + + +def select_by_levels( + registry: TargetRegistry, + declaration: TargetSetDeclaration, + levels: Sequence[str] | None = None, +) -> LevelSelection: + """Keep the targets of the requested levels (all by default), in compile order. + + ``declaration`` is a mode with a closed level set and one clause for each + level (:func:`_require_level_mode`). Each target's level comes from the + declared rule, which refuses a target it cannot place. The kept targets + are the ones the requested clauses keep (:func:`select_target_set`), in + the registry's order. The receipt lists every target with its level and + whether it was kept. + + Raises: + TypeError: If ``registry`` is not a :class:`TargetRegistry`. + TargetSetDeclarationError: If ``declaration`` is not a level mode. + ValueError: If ``levels`` is empty, repeats a level or names one with + outer spaces; if a requested level has no target; if a target's + level cannot be read; or if nothing is kept. + """ + + if not isinstance(registry, TargetRegistry): + raise TypeError("Target selection requires TargetRegistry.") + _require_level_mode(declaration) + requested = None + if levels is not None: + if isinstance(levels, str | bytes): + raise ValueError("geography_levels must be a nonempty sequence of levels.") + requested = tuple(levels) + if not requested or any( + not isinstance(level, str) or not level or level != level.strip() + for level in requested + ): + raise ValueError("geography_levels must contain nonempty literal names.") + if len(set(requested)) != len(requested): + raise ValueError("geography_levels must not repeat levels.") + requested = tuple(sorted(requested)) + resolved = [declaration.level_of(spec) for spec in registry.specs] + if requested is not None and (unknown := set(requested) - set(resolved)): + raise ValueError( + f"Target selector contains unknown geography levels {sorted(unknown)}." + ) + kept = { + id(spec) + for spec in select_target_set( + declaration, registry.specs, clause_ids=requested + ).specs + } + selected = registry.select(predicate=lambda spec: id(spec) in kept) + if not selected.specs: + raise ValueError("Target selection requires a nonempty selected problem.") + included, excluded = [], [] + for spec, level in zip(registry.specs, resolved, strict=True): + row = { + "name": spec.name, + "period": spec.period, + "geography_level": level, + "family": spec.family, + "source": spec.source, + } + if id(spec) in kept: + reason = "all_geographies" if requested is None else "geography_selected" + included.append({**row, "reason": reason}) + else: + excluded.append({**row, "reason": "geography_not_selected"}) + receipt = { + "schema": SELECTION_RECEIPT_SCHEMA, + "source_registry_version": registry.version, + "selected_registry_version": selected.version, + "selector": {"geography_levels": requested, "explicit": requested is not None}, + "included": included, + "excluded": excluded, + } + return LevelSelection( + selected, + json.dumps(receipt, sort_keys=True, separators=(",", ":"), allow_nan=False), + ) + + def clause_predicate( declaration: TargetSetDeclaration, clause_id: str, diff --git a/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py b/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py index 2a99256086..9c8bbf7f17 100644 --- a/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py +++ b/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py @@ -13,6 +13,7 @@ TargetSetDeclarationError, clause_predicate, load_target_set_declarations, + select_by_levels, select_target_set, target_level, target_set_census, @@ -360,3 +361,222 @@ def test_census_and_undeclared_cells() -> None: ("tax", "country"): 1, ("tax", "district"): 1, } + + +# --------------------------------------------------------------------------- +# Level rules and selection by level (microcosm#1759) +# --------------------------------------------------------------------------- + +LEVELS = ("country", "region", "la") + + +def _level_declarations(**rule) -> dict: + return { + "version": 1, + "country": "test", + "level_rule": { + "keys": ["level", "geo"], + "values": list(LEVELS), + "conflict": "refuse", + "rationale": "r", + **rule, + }, + "products": { + "full": { + "tool": "tools/full.py", + "option": "--levels", + "default_mode": "levels", + "modes": { + "levels": { + "description": "One clause for each level.", + "compiled": [ + { + "id": level, + "families": "*", + "levels": [level], + "rationale": "r", + } + for level in LEVELS + ], + } + }, + } + }, + } + + +def _level_mode(**rule): + return load_target_set_declarations(_level_declarations(**rule)).declaration( + "full", "levels" + ) + + +def _registry(*rows): + from microcosm.calibrate.registry import TargetRegistry, TargetSpec + + return TargetRegistry( + [ + TargetSpec( + name=name, + entity="household", + measure="household_weight", + value=1.0 + index, + period=2025, + source="test", + family=family, + metadata=metadata, + ) + for index, (name, family, metadata) in enumerate(rows) + ], + country="test", + ) + + +def test_a_level_rule_reads_the_first_key_and_refuses_what_it_cannot_place() -> None: + rule = _level_mode().level_rule + assert rule.keys == ("level", "geo") + assert rule.values == frozenset(LEVELS) + assert rule.level_of(_spec("a", "tax", level="la")) == "la" + assert rule.level_of(_spec("b", "tax", geo="region")) == "region" + assert rule.level_of(_spec("c", "tax", level="la", geo="la")) == "la" + assert rule.level_of(_spec("d", "tax", level="", geo="country")) == "country" + with pytest.raises(ValueError, match="'e' has contradictory geography levels"): + rule.level_of(_spec("e", "tax", level="la", geo="region")) + with pytest.raises(ValueError, match="'f' has unsupported geography level None"): + rule.level_of(_spec("f", "tax")) + with pytest.raises(ValueError, match="unsupported geography level ''"): + rule.level_of(_spec("g", "tax", level=None, geo="")) + with pytest.raises(ValueError, match="unsupported geography level 'nation'"): + rule.level_of(_spec("h", "tax", geo="nation")) + + +def test_an_open_rule_and_the_first_conflict_rule() -> None: + first = _level_mode(conflict="first").level_rule + assert first.level_of(_spec("a", "tax", level="la", geo="region")) == "la" + open_rule = _level_mode(values="*").level_rule + assert open_rule.values is None + assert open_rule.level_of(_spec("b", "tax")) == UNSPECIFIED_LEVEL + assert open_rule.level_of(_spec("c", "tax", geo="nation")) == "nation" + with pytest.raises(ValueError, match="contradictory"): + open_rule.level_of(_spec("d", "tax", level="la", geo="region")) + # The level_keys form reads exactly as target_level does. + keys_form = _declarations().declaration("national", "all") + assert keys_form.level_rule.values is None + assert keys_form.level_rule.conflict == "first" + for spec in SPECS: + assert keys_form.level_of(spec) == target_level(spec, ("level", "geo")) + + +@pytest.mark.parametrize( + ("rule", "message"), + [ + ({"conflict": "maybe"}, "must be one of"), + ({"keys": []}, "nonempty list of metadata keys"), + ({"keys": ["level", "level"]}, "repeats a key"), + ({"values": []}, "nonempty list"), + ({"rationale": ""}, "nonempty string"), + ({"extra": 1}, "unknown keys"), + ], +) +def test_a_malformed_level_rule_is_refused(rule, message) -> None: + with pytest.raises(TargetSetDeclarationError, match=message): + load_target_set_declarations(_level_declarations(**rule)) + + +def test_a_declaration_gives_exactly_one_level_form() -> None: + both = _level_declarations() + both["level_keys"] = ["level"] + with pytest.raises(TargetSetDeclarationError, match="exactly one of"): + load_target_set_declarations(both) + neither = _level_declarations() + del neither["level_rule"] + with pytest.raises(TargetSetDeclarationError, match="exactly one of"): + load_target_set_declarations(neither) + + +def test_select_by_levels_keeps_compile_order_and_lists_every_target() -> None: + registry = _registry( + ("la_1", "tax", {"level": "la"}), + ("uk", "tax", {"geo": "country"}), + ("north", "benefit", {"level": "region", "geo": "region"}), + ("la_2", "benefit", {"geo": "la"}), + ) + selection = select_by_levels(registry, _level_mode(), ["la", "country"]) + assert [spec.name for spec in selection.registry.specs] == ["la_1", "uk", "la_2"] + receipt = selection.receipt + assert receipt["schema"] == "microcosm.calibrate.target-selection.v1" + assert receipt["selector"] == { + "geography_levels": ["country", "la"], + "explicit": True, + } + assert receipt["source_registry_version"] == registry.version + assert receipt["selected_registry_version"] == selection.registry.version + assert [(row["name"], row["reason"]) for row in receipt["included"]] == [ + ("la_1", "geography_selected"), + ("uk", "geography_selected"), + ("la_2", "geography_selected"), + ] + assert [(row["name"], row["geography_level"]) for row in receipt["excluded"]] == [ + ("north", "region") + ] + everything = select_by_levels(registry, _level_mode()) + assert everything.registry.version == registry.version + assert everything.receipt["selector"] == { + "geography_levels": None, + "explicit": False, + } + assert {row["reason"] for row in everything.receipt["included"]} == { + "all_geographies" + } + assert everything.sha256 != selection.sha256 + receipt["included"].clear() + assert selection.receipt["included"] + + +@pytest.mark.parametrize( + ("levels", "message"), + [ + ("la", "nonempty sequence of levels"), + ([], "nonempty literal names"), + ([" la"], "nonempty literal names"), + (["la", "la"], "must not repeat levels"), + (["region"], r"unknown geography levels \['region'\]"), + (["nowhere", "region"], r"unknown geography levels \['nowhere', 'region'\]"), + ], +) +def test_select_by_levels_refuses_a_bad_request(levels, message) -> None: + registry = _registry(("la_1", "tax", {"level": "la"})) + with pytest.raises(ValueError, match=message): + select_by_levels(registry, _level_mode(), levels) + + +def test_select_by_levels_refuses_an_empty_selection_and_a_non_registry() -> None: + with pytest.raises(ValueError, match="nonempty selected problem"): + select_by_levels(_registry(), _level_mode()) + with pytest.raises(TypeError, match="requires TargetRegistry"): + select_by_levels([], _level_mode()) + with pytest.raises(ValueError, match="contradictory"): + select_by_levels( + _registry(("x", "tax", {"level": "la", "geo": "region"})), _level_mode() + ) + + +def test_select_by_levels_needs_a_level_mode() -> None: + registry = _registry(("la_1", "tax", {"level": "la"})) + with pytest.raises(TargetSetDeclarationError, match="closed set of values"): + select_by_levels(registry, _level_mode(values="*")) + family_clause = _level_declarations() + mode = family_clause["products"]["full"]["modes"]["levels"] + mode["compiled"][0]["families"] = ["tax"] + with pytest.raises(TargetSetDeclarationError, match="not a level clause"): + select_by_levels( + registry, + load_target_set_declarations(family_clause).declaration("full", "levels"), + ) + missing = _level_declarations() + missing["products"]["full"]["modes"]["levels"]["compiled"].pop() + with pytest.raises(TargetSetDeclarationError, match="are not the levels"): + select_by_levels( + registry, + load_target_set_declarations(missing).declaration("full", "levels"), + ) From 61e24394d115a98a1198bb046cc3e9ae6a2ba036 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:40:17 +0000 Subject: [PATCH 12/30] Select the UK full build's solve surface with the declared target sets The UK now declares its target sets the way the US does (microcosm#1759, step D2): - uk/target_sets.json (a new legacy_json row in uk/country_package.json) declares the UK level rule: a target's level is geography_level or ledger_geography_level, the two must agree, and it must be one of country, region, constituency, la and brma. It also declares the full build's product with one mode, "levels", that has one clause for each level. - uk_runtime/target_sets.py names the file and products. graph_targets.target_geography reads the declared rule, and uk.full.target_selection@1 calls the shared select_by_levels. - microcosm.calibrate.target_selection and its tests are removed: the UK kernel was the only caller. - The full-graph target kernels hash the shared and UK target-set modules in place of target_selection. The national kernels now hash them too: the national problem writes each row's level, and it now reads the level through the UK adapter, not through graph_targets, which those kernels never hashed. No selection changes. test_uk_level_selection.py compares the new code with verbatim copies of the removed selector and UK resolver (test_support/microcosm_build/target_selection_reference.py) on 400 random registries and requests: the same registry version, the same receipt bytes, or the same refusal type and text. The new resource is in the UK solve fingerprint, so the first UK build after this change computes the spine from frs_brma on, the target nodes and the national graph again. Co-Authored-By: Claude Opus 5.5 --- ...59-uk-declared-target-selection.changed.md | 1 + .../microcosm/build/uk/country_package.json | 5 + .../src/microcosm/build/uk/target_sets.json | 74 ++++++++ .../build/uk_runtime/graph_national.py | 12 +- .../build/uk_runtime/graph_targets.py | 38 ++-- .../microcosm/build/uk_runtime/target_sets.py | 65 +++++++ .../engine_free/shared/test_country_spec.py | 6 + .../shared/test_first_party_imports.py | 8 +- .../engine_free/uk/test_uk_level_selection.py | 162 ++++++++++++++++++ .../uk/test_uk_target_compile_modules.py | 8 +- .../shared/test_target_selection.py | 72 -------- .../target_selection_reference.py | 25 ++- 12 files changed, 375 insertions(+), 101 deletions(-) create mode 100644 changelog.d/1759-uk-declared-target-selection.changed.md create mode 100644 packages/microcosm-build/src/microcosm/build/uk/target_sets.json create mode 100644 packages/microcosm-build/src/microcosm/build/uk_runtime/target_sets.py create mode 100644 packages/microcosm-build/tests/engine_free/uk/test_uk_level_selection.py delete mode 100644 packages/microcosm-calibrate/tests/engine_free/shared/test_target_selection.py rename packages/microcosm-calibrate/src/microcosm/calibrate/target_selection.py => test_support/microcosm_build/target_selection_reference.py (80%) diff --git a/changelog.d/1759-uk-declared-target-selection.changed.md b/changelog.d/1759-uk-declared-target-selection.changed.md new file mode 100644 index 0000000000..37098749ba --- /dev/null +++ b/changelog.d/1759-uk-declared-target-selection.changed.md @@ -0,0 +1 @@ +The UK full build selects its solve surface with the shared declared target sets, as the US does (microcosm#1759). `uk/target_sets.json` declares the UK level rule (a target's level is `geography_level` or `ledger_geography_level`; the two must agree, and the level must be one of country, region, constituency, la and brma) and the full build's selection by level, one clause for each level. `microcosm.calibrate.target_sets` reads a declared `level_rule` (the US `level_keys` form is unchanged) and its new `select_by_levels` keeps the requested levels in compile order with the same receipt (`microcosm.calibrate.target-selection.v1`). `microcosm.calibrate.target_selection` is removed: the UK selection kernel was its only caller, and `uk_runtime.graph_targets.target_geography` now reads the declared rule. No selection changes: `test_uk_level_selection.py` holds the new code to verbatim copies of the removed selector and resolver on random registries, refusals included. The new UK resource is in the UK solve fingerprint, so the first UK build after this change computes the spine from `frs_brma` on, the target nodes and the national graph again. diff --git a/packages/microcosm-build/src/microcosm/build/uk/country_package.json b/packages/microcosm-build/src/microcosm/build/uk/country_package.json index 4031ed2699..7ff6f4e272 100644 --- a/packages/microcosm-build/src/microcosm/build/uk/country_package.json +++ b/packages/microcosm-build/src/microcosm/build/uk/country_package.json @@ -656,6 +656,11 @@ "path": "hmrc_spi_table_3_11_uk_rows.json", "kind": "legacy_json", "schema_id": "legacy_json" + }, + { + "path": "target_sets.json", + "kind": "legacy_json", + "schema_id": "legacy_json" } ] } diff --git a/packages/microcosm-build/src/microcosm/build/uk/target_sets.json b/packages/microcosm-build/src/microcosm/build/uk/target_sets.json new file mode 100644 index 0000000000..d42678fb11 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk/target_sets.json @@ -0,0 +1,74 @@ +{ + "version": 1, + "country": "uk", + "description": "The targets each UK build calibrates to (microcosm#1759): the level rule that places every compiled UK target at one geography level, and the full build's selection of its solve surface by level. microcosm.calibrate.target_sets reads this file; microcosm.build.uk_runtime.target_sets names its products. The US declares its target sets the same way, in us/target_sets.json (microcosm#1728).", + "level_rule": { + "keys": [ + "geography_level", + "ledger_geography_level" + ], + "values": [ + "country", + "region", + "constituency", + "la", + "brma" + ], + "conflict": "refuse", + "rationale": "A compiled UK target names its level in its local metadata (geography_level), in the Ledger's (ledger_geography_level), or in both. Both must then agree, and the level must be one of the five grains a UK build calibrates at; any other target is refused, not placed by a guess. This is the rule the UK resolver uk_runtime.graph_targets.target_geography applied in code before microcosm#1759." + }, + "products": { + "full": { + "tool": "packages/microcosm-build/src/microcosm/build/uk_runtime/full_build_cli.py", + "option": "--target-geographies", + "default_mode": "levels", + "modes": { + "levels": { + "description": "The full (local-line) build's solve surface: the compiled targets of the levels the build requests, all of them by default, in compile order, with a receipt that lists every target (uk.full.target_selection@1). The node first applies the build's family filter (--households-only) and, with no area BRMAs, drops the brma rows.", + "compiled": [ + { + "id": "country", + "families": "*", + "levels": [ + "country" + ], + "rationale": "The country-level rows. Kept when the build requests this level; a build requests every level unless --target-geographies names a subset." + }, + { + "id": "region", + "families": "*", + "levels": [ + "region" + ], + "rationale": "The region-level rows. Kept when the build requests this level; a build requests every level unless --target-geographies names a subset." + }, + { + "id": "constituency", + "families": "*", + "levels": [ + "constituency" + ], + "rationale": "The Westminster constituency cells. Kept when the build requests this level; a build requests every level unless --target-geographies names a subset." + }, + { + "id": "la", + "families": "*", + "levels": [ + "la" + ], + "rationale": "The local-authority cells. Kept when the build requests this level; a build requests every level unless --target-geographies names a subset." + }, + { + "id": "brma", + "families": "*", + "levels": [ + "brma" + ], + "rationale": "The Broad Rental Market Area cells. Kept when the build requests this level; a build requests every level unless --target-geographies names a subset. With no area BRMAs (--brma-localisation none) the node drops these rows before it selects, because they would bind on the spine's regional BRMA draw (microcosm#1305)." + } + ] + } + } + } + } +} diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_national.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_national.py index 9959a07799..5d993a96fa 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_national.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_national.py @@ -114,7 +114,6 @@ register_uk_source_codecs, registry_from_payload, registry_payload, - target_geography, ) from .local_rowwise import UKRowwiseNationalRows from .measure_simulation import UKMeasureResolver @@ -134,6 +133,7 @@ UK_ROWWISE_NATIONAL_POSTURE, UKRowwisePosture, ) +from .target_sets import uk_target_level from .weight_year import uk_dataset_year_frame, uk_weight_projection_factor NATIONAL_TARGET_TYPE = ArtifactType("microcosm.uk.national-target-registry", 1) @@ -475,8 +475,9 @@ def implementation_hash(self) -> str: import microcosm.calibrate.artifacts as calibrate_artifacts import microcosm.calibrate.matrix as calibrate_matrix import microcosm.calibrate.target_loss_rules as calibrate_target_loss_rules + import microcosm.calibrate.target_sets as calibrate_target_sets - from . import receipt_counts, weighted_integrity + from . import receipt_counts, target_sets, weighted_integrity from .target_compile_modules import uk_target_compile_modules implementation = source_hash( @@ -497,6 +498,11 @@ def implementation_hash(self) -> str: # shared rules (microcosm#1729): an edit to a shared rule must # re-key the national problem. calibrate_target_loss_rules, + # The national problem writes each row's level, which the + # declared UK level rule gives (uk/target_sets.json through the + # shared target sets, microcosm#1759). + calibrate_target_sets, + target_sets, support_floor_rules, # The constraint matrices and their encoding, as the dense kernels # hash them (microcosm#1492). Not calibrate.solve: neither the @@ -873,7 +879,7 @@ def national_target_geography_levels(registry: TargetRegistry) -> dict[str, str] """ declared = { - spec.to_target().row_name: target_geography(spec) + spec.to_target().row_name: uk_target_level(spec) for spec in registry.specs if spec.metadata.get("geography_level") is not None or spec.metadata.get("ledger_geography_level") is not None diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_targets.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_targets.py index 88f59b7155..b06188ce8a 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_targets.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_targets.py @@ -17,7 +17,7 @@ import microcosm.calibrate.artifacts as calibrate_artifacts import microcosm.calibrate.matrix as calibrate_matrix -import microcosm.calibrate.target_selection as calibrate_target_selection +import microcosm.calibrate.target_sets as calibrate_target_sets from microcosm.build import cross_grain from microcosm.calibrate import CalibrationHierarchy, TargetRegistry, TargetSpec from microcosm.calibrate.artifacts import ( @@ -28,7 +28,7 @@ encode_problem, ) from microcosm.calibrate.matrix import build_constraint_matrix -from microcosm.calibrate.target_selection import select_targets +from microcosm.calibrate.target_sets import select_by_levels from microcosm.graph import ( ArtifactInput, ArtifactOutput, @@ -54,6 +54,7 @@ ledger_targets, local_doctrine, support_floor, + target_sets, target_weights, ) from .full_measure import resolve_uk_full_national_problem @@ -114,19 +115,14 @@ def registry_from_payload(payload: Mapping) -> TargetRegistry: def target_geography(spec: TargetSpec) -> str: - """Resolve explicit metadata without interpreting legacy registry buckets.""" - - metadata = spec.metadata - local = metadata.get("geography_level") - ledger = metadata.get("ledger_geography_level") - if local and ledger and local != ledger: - raise ValueError(f"Target {spec.name!r} has contradictory geography levels.") - level = local or ledger - if level not in {"country", "region", "constituency", "la", "brma"}: - raise ValueError( - f"Target {spec.name!r} has unsupported geography level {level!r}." - ) - return str(level) + """Resolve explicit metadata without interpreting legacy registry buckets. + + The rule is declared in ``uk/target_sets.json`` (microcosm#1759): the + level is ``geography_level`` or ``ledger_geography_level``, the two must + agree when both are set, and it must be one of the five UK grains. + """ + + return target_sets.uk_target_level(spec) def _surface_records(frame: pd.DataFrame) -> list[dict]: @@ -243,8 +239,12 @@ def implementation_hash(self) -> str: measure_simulation, support_floor, # The selection, the constraint matrices and their encoding, as - # the transport kernels hash them (microcosm#1492). - calibrate_target_selection, + # the transport kernels hash them (microcosm#1492). The selection + # and the level rule read uk/target_sets.json through the shared + # target sets (microcosm#1759); the file's bytes are in the solve + # fingerprint below. + calibrate_target_sets, + target_sets, calibrate_matrix, calibrate_artifacts, # full_targets takes its exclusion clock from here. Hashed @@ -438,8 +438,8 @@ def run(self, context: KernelContext) -> KernelResult: registry = registry.select( predicate=lambda spec: target_geography(spec) != "brma" ) - selected = select_targets( - registry, geography_levels=levels, geography_resolver=target_geography + selected = select_by_levels( + registry, target_sets.uk_full_level_selection(), levels ) if not len(selected.registry): raise ValueError("Full build target selection contains no constraints.") diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/target_sets.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/target_sets.py new file mode 100644 index 0000000000..58b2a50621 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/target_sets.py @@ -0,0 +1,65 @@ +"""The declared target sets of the UK builds (microcosm#1759). + +``uk/target_sets.json`` declares the UK level rule, which places every +compiled UK target at one geography level, and the full build's selection of +its solve surface by level (``uk.full.target_selection@1``, from the full +build's ``--target-geographies``). The shared reader and selector are in +:mod:`microcosm.calibrate.target_sets`; this module names the UK file and +products. The US declares its target sets the same way, in +``us/target_sets.json`` (microcosm#1728). +""" + +from __future__ import annotations + +from functools import lru_cache +from importlib.resources import files +from pathlib import Path +from typing import Any + +from microcosm.calibrate.target_sets import ( + TargetSetDeclaration, + TargetSetDeclarations, + load_target_set_declarations, +) + +__all__ = [ + "FULL_LEVELS_MODE", + "FULL_PRODUCT", + "UK_TARGET_SETS_RESOURCE", + "uk_full_level_selection", + "uk_target_level", + "uk_target_set_declarations", + "uk_target_sets_path", +] + +UK_TARGET_SETS_RESOURCE = "target_sets.json" +#: The full build's product, and its one mode: selection by level. +FULL_PRODUCT = "full" +FULL_LEVELS_MODE = "levels" + + +def uk_target_sets_path() -> Path: + return Path(str(files("microcosm.build.uk").joinpath(UK_TARGET_SETS_RESOURCE))) + + +@lru_cache(maxsize=1) +def uk_target_set_declarations() -> TargetSetDeclarations: + """The packaged UK declarations, read and checked once.""" + + return load_target_set_declarations(uk_target_sets_path()) + + +def uk_full_level_selection() -> TargetSetDeclaration: + """The full build's selection by level (``uk.full.target_selection@1``).""" + + return uk_target_set_declarations().declaration(FULL_PRODUCT, FULL_LEVELS_MODE) + + +def uk_target_level(spec: Any) -> str: + """A compiled UK target's geography level, by the declared level rule. + + Refuses a target whose two level keys disagree, or whose level is not one + of the declared five. + """ + + return uk_target_set_declarations().level_rule.level_of(spec) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_country_spec.py b/packages/microcosm-build/tests/engine_free/shared/test_country_spec.py index 1e07c17cdb..2f9934bbf8 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_country_spec.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_country_spec.py @@ -1227,6 +1227,9 @@ def test_spi_spine_adds_no_country_package_resources(self) -> None: "desnz_constituency_energy_facts.json", "local_small_cell_rule.json", "hmrc_spi_table_3_11_uk_rows.json", + # microcosm#1759: the UK level rule, the full build's selection + # by level and the calibration lines. + "target_sets.json", ) def test_uk_source_manifest_contains_only_canonical_spine_stages(self) -> None: @@ -1420,6 +1423,9 @@ def test_uk_package_loads(self) -> None: "desnz_constituency_energy_facts.json", "local_small_cell_rule.json", "hmrc_spi_table_3_11_uk_rows.json", + # microcosm#1759: the UK level rule, the full build's selection + # by level and the calibration lines. + "target_sets.json", ) def test_uk_target_references_accept_regenerated_contract_fields(self) -> None: diff --git a/packages/microcosm-build/tests/engine_free/shared/test_first_party_imports.py b/packages/microcosm-build/tests/engine_free/shared/test_first_party_imports.py index eb5b6a9953..01e641b0ea 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_first_party_imports.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_first_party_imports.py @@ -91,11 +91,11 @@ def test_a_package_import_with_no_name_read_reads_the_package(scratch_package): def test_a_submodule_resolves_the_same_before_it_is_imported(monkeypatch): """A function-level ``from package import submodule`` names the submodule whether or not an earlier test imported it.""" - name = "microcosm.calibrate.target_selection" - assert defining_module("microcosm.calibrate", "target_selection") == name + name = "microcosm.calibrate.target_sets" + assert defining_module("microcosm.calibrate", "target_sets") == name monkeypatch.delitem(sys.modules, name, raising=False) - monkeypatch.delattr(microcosm.calibrate, "target_selection", raising=False) - assert defining_module("microcosm.calibrate", "target_selection") == name + monkeypatch.delattr(microcosm.calibrate, "target_sets", raising=False) + assert defining_module("microcosm.calibrate", "target_sets") == name def test_the_walk_follows_an_exclusion_but_not_its_imports(scratch_package): diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_level_selection.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_level_selection.py new file mode 100644 index 0000000000..8e151018bc --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_level_selection.py @@ -0,0 +1,162 @@ +"""The UK full build's selection by level, against the code it replaced. + +Before microcosm#1759 the UK full build selected its solve surface with +``microcosm.calibrate.target_selection.select_targets`` and the UK resolver +``uk_runtime.graph_targets.target_geography``. It now selects with the shared +``microcosm.calibrate.target_sets.select_by_levels`` and the UK's declared +level rule (``uk/target_sets.json``). ``test_support/microcosm_build/target_selection_reference.py`` +holds verbatim copies of the old code. On random registries and requests the +two give the same registry, the same receipt bytes, or the same refusal. +""" + +from __future__ import annotations + +import numpy as np +import pytest + +from microcosm.build.uk_runtime.target_sets import ( + uk_full_level_selection, + uk_target_set_declarations, +) +from microcosm.calibrate.registry import TargetRegistry, TargetSpec +from microcosm.calibrate.target_sets import select_by_levels +from test_support.microcosm_build import target_selection_reference as reference + +UK_LEVELS = ("country", "region", "constituency", "la", "brma") + +#: The full build's level mode, as uk/target_sets.json declares it. +DECLARATION = uk_full_level_selection() + + +def test_the_packaged_level_rule_is_the_rule_the_uk_resolver_applied() -> None: + rule = uk_target_set_declarations().level_rule + assert rule.keys == ("geography_level", "ledger_geography_level") + assert rule.values == frozenset(UK_LEVELS) + assert rule.conflict == "refuse" + assert DECLARATION.level_rule == rule + assert DECLARATION.clause_ids == UK_LEVELS + + +#: Levels the UK rule refuses. A spec's metadata values are nonempty +#: strings, so a missing level is a missing key. +_BAD = ("nation", " la", "LA") +_FAMILIES = ("census_households", "hmrc_income", "dwp_uc", "high_value_homes") + + +def _level(rng) -> str: + if rng.uniform() < 0.005: + return str(rng.choice(_BAD)) + return str(rng.choice(UK_LEVELS)) + + +def _registry(seed: int) -> TargetRegistry: + rng = np.random.default_rng(seed) + specs = [] + for index in range(int(rng.integers(0, 30))): + metadata = {} + local = _level(rng) + ledger = local if rng.uniform() < 0.97 else _level(rng) + if rng.uniform() < 0.95: + metadata["geography_level"] = local + if rng.uniform() < 0.6: + metadata["ledger_geography_level"] = ledger + if rng.uniform() < 0.5: + metadata["area_code"] = f"E{index:08d}" + specs.append( + TargetSpec( + name=f"target_{index}", + entity="household", + measure="household_weight", + value=float(rng.uniform(1.0, 1e6)), + period=int(rng.choice([2024, 2025])), + source=str(rng.choice(["ons", "hmrc", "dwp"])), + family=str(rng.choice(_FAMILIES)), + metadata=metadata, + ) + ) + return TargetRegistry(specs, country="uk") + + +def _request(seed: int): + rng = np.random.default_rng(seed + 50_000) + draw = rng.uniform() + if draw < 0.3: + return None + if draw < 0.85: + size = int(rng.integers(1, len(UK_LEVELS) + 1)) + return list(rng.choice(UK_LEVELS, size=size, replace=False)) + return [[], ["nowhere"], ["la", "la"], [" la"], "la", ("brma", "nowhere")][ + int(rng.integers(6)) + ] + + +def _outcome(select): + try: + selection = select() + except Exception as error: # noqa: BLE001 - the refusal is the outcome + return ("refused", type(error).__name__, str(error)) + return ( + "selected", + selection.registry.version, + [spec.name for spec in selection.registry.specs], + selection.to_bytes(), + ) + + +@pytest.mark.parametrize("seed", range(400)) +def test_selection_matches_the_replaced_code(seed: int) -> None: + registry, levels = _registry(seed), _request(seed) + old = _outcome( + lambda: reference.select_targets( + registry, + geography_levels=levels, + geography_resolver=reference.target_geography, + ) + ) + new = _outcome(lambda: select_by_levels(registry, DECLARATION, levels)) + assert new == old + + +def test_the_random_cases_cover_selections_and_each_refusal() -> None: + selected, messages = 0, [] + for seed in range(400): + registry, levels = _registry(seed), _request(seed) + outcome = _outcome( + lambda registry=registry, levels=levels: select_by_levels( + registry, DECLARATION, levels + ) + ) + if outcome[0] == "selected": + selected += 1 + else: + messages.append(outcome[2]) + assert selected >= 50 + text = " ".join(messages) + for fragment in ( + "contradictory", + "unsupported geography level", + "unknown geography levels", + "nonempty literal names", + "must not repeat", + "nonempty sequence", + ): + assert fragment in text, fragment + + +def test_the_level_rule_reads_as_the_uk_resolver_did() -> None: + for seed in range(200): + for spec in _registry(seed).specs: + old = _outcome(lambda spec=spec: _Wrapped(reference.target_geography(spec))) + new = _outcome(lambda spec=spec: _Wrapped(DECLARATION.level_of(spec))) + assert new == old + + +class _Wrapped: + """A level dressed as a selection, so _outcome compares it.""" + + def __init__(self, level: str) -> None: + self.registry = TargetRegistry([], country="uk") + self._level = level + + def to_bytes(self) -> bytes: + return self._level.encode() diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_target_compile_modules.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_target_compile_modules.py index 2c4e7f76e6..8930436abf 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_target_compile_modules.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_target_compile_modules.py @@ -166,8 +166,12 @@ def test_national_target_kernels_hash_the_fact_decoder(monkeypatch): #: microcosm#1492, and the kernels that now hash it. All four full-graph #: kernels share one hash, so what one of them runs re-keys all four. _RUN_MODULES = { - # uk.full.target_selection@1 calls select_targets. - "microcosm.calibrate.target_selection": _FULL_GRAPH, + # uk.full.target_selection@1 calls select_by_levels, and every target + # kernel's level reader (graph_targets.target_geography) reads the + # declared level rule through the UK adapter (microcosm#1759). + # The national problem writes each row's level by the same rule. + "microcosm.calibrate.target_sets": _FULL_GRAPH + _NATIONAL_GRAPH, + "microcosm.build.uk_runtime.target_sets": _FULL_GRAPH + _NATIONAL_GRAPH, # The measures and problem kernels build and encode constraint matrices. "microcosm.calibrate.matrix": _FULL_GRAPH + _NATIONAL_GRAPH, "microcosm.calibrate.artifacts": _FULL_GRAPH + _NATIONAL_GRAPH, diff --git a/packages/microcosm-calibrate/tests/engine_free/shared/test_target_selection.py b/packages/microcosm-calibrate/tests/engine_free/shared/test_target_selection.py deleted file mode 100644 index 74c40fdddb..0000000000 --- a/packages/microcosm-calibrate/tests/engine_free/shared/test_target_selection.py +++ /dev/null @@ -1,72 +0,0 @@ -"""Target scope is explicit and preserves ordered fact identities.""" - -import pytest - -from microcosm.calibrate import TargetRegistry, TargetSpec -from microcosm.calibrate.target_selection import select_targets - - -def registry(): - return TargetRegistry( - [ - TargetSpec( - "population", - "person", - 20, - "one", - period=2024, - source="census", - metadata={"geography_level": "country"}, - ), - TargetSpec( - "population", - "person", - 22, - "one", - period=2025, - source="census", - metadata={"geography_level": "region"}, - ), - TargetSpec( - "local", - "person", - 5, - "one", - period=2025, - source="census", - metadata={"geography_level": "district"}, - ), - ], - country="test", - ) - - -def test_default_all_and_explicit_country_are_distinct(): - all_targets = select_targets(registry()) - assert all_targets.registry.specs == registry().specs - assert all_targets.receipt["selector"] == { - "geography_levels": None, - "explicit": False, - } - selected = select_targets(registry(), geography_levels=("country",)) - assert [spec.key for spec in selected.registry.specs] == [("population", 2024)] - assert [row["period"] for row in selected.receipt["excluded"]] == [2025, 2025] - assert all( - row["reason"] == "geography_not_selected" - for row in selected.receipt["excluded"] - ) - assert selected.receipt["source_registry_version"] == registry().version - - -def test_missing_unknown_empty_and_resolved_geographies(): - with pytest.raises(ValueError, match="unknown"): - select_targets(registry(), geography_levels=("missing",)) - with pytest.raises(ValueError, match="nonempty"): - select_targets(registry(), geography_levels=()) - missing = TargetRegistry( - [TargetSpec("x", "person", 1, "one", source="test")], country="test" - ) - with pytest.raises(ValueError, match="geography"): - select_targets(missing) - resolved = select_targets(missing, geography_resolver=lambda spec: "country") - assert resolved.receipt["included"][0]["geography_level"] == "country" diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/target_selection.py b/test_support/microcosm_build/target_selection_reference.py similarity index 80% rename from packages/microcosm-calibrate/src/microcosm/calibrate/target_selection.py rename to test_support/microcosm_build/target_selection_reference.py index 4024426de8..c61d87e964 100644 --- a/packages/microcosm-calibrate/src/microcosm/calibrate/target_selection.py +++ b/test_support/microcosm_build/target_selection_reference.py @@ -1,3 +1,8 @@ +# Verbatim copy of microcosm.calibrate.target_selection at 508351658 (the head +# of microcosm#1755 before microcosm#1759 moved the UK selection onto the +# declared target sets). Tests hold the shared selector to it; do not edit. +# ruff: noqa + """Explicit target-scope selection, independent of country and pool sizing. Selection does not admit unsupported targets, adjudicate source authority, or @@ -12,7 +17,7 @@ from collections.abc import Callable, Sequence from dataclasses import dataclass -from .registry import TargetRegistry, TargetSpec +from microcosm.calibrate.registry import TargetRegistry, TargetSpec @dataclass(frozen=True) @@ -121,3 +126,21 @@ def select_targets( selected, json.dumps(receipt, sort_keys=True, separators=(",", ":"), allow_nan=False), ) + + +# Verbatim copy of microcosm.build.uk_runtime.graph_targets.target_geography at +# 508351658: the UK resolver the full build passed to select_targets. +def target_geography(spec: TargetSpec) -> str: + """Resolve explicit metadata without interpreting legacy registry buckets.""" + + metadata = spec.metadata + local = metadata.get("geography_level") + ledger = metadata.get("ledger_geography_level") + if local and ledger and local != ledger: + raise ValueError(f"Target {spec.name!r} has contradictory geography levels.") + level = local or ledger + if level not in {"country", "region", "constituency", "la", "brma"}: + raise ValueError( + f"Target {spec.name!r} has unsupported geography level {level!r}." + ) + return str(level) From 0d5dc1a9db17abd8e9dfdb4afc909f4aa9130b5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:46:19 +0000 Subject: [PATCH 13/30] Declare the UK calibration lines as target sets The two UK calibration lines (microcosm#1301) become the modes of a calibration_line product in uk/target_sets.json (microcosm#1759, step D3): - Each mode has one clause that keeps every compiled national reference except the ones the predicate off_calibration_line names. - uk_runtime.ledger_targets.uk_registry_on_calibration_line selects through the declared mode with the shared select_target_set. It binds that predicate to the contract targets whose calibration_lines leave the line out. The membership stays with each target in uk/uk_population_targets.json. - UK_CALIBRATION_LINES is the product's declared modes. - The shared selector reads a target's level only when an active clause tests levels, so the closed UK level rule does not refuse rows that a line selection never places by level. The US declarations are open rules, so their results do not change. - ledger_targets now imports the shared and UK target-set modules, so both join UK_TARGET_COMPILE_MODULE_NAMES. No line changes. test_uk_calibration_line_selection.py holds the new function to a verbatim copy of the old one (test_support/microcosm_build/calibration_line_reference.py). It covers 150 random registries on each line and an unknown line: the same registry (the same object when nothing drops), the same receipt, or the same refusal. The existing line, CenTax and measurement-period tests pass unchanged. Co-Authored-By: Claude Opus 5.5 --- ...59-uk-declared-target-selection.changed.md | 2 +- .../src/microcosm/build/uk/target_sets.json | 37 +++++- .../build/uk_runtime/ledger_targets.py | 43 +++++-- .../uk_runtime/target_compile_modules.py | 2 + .../microcosm/build/uk_runtime/target_sets.py | 28 +++- .../uk/test_uk_calibration_line_selection.py | 120 ++++++++++++++++++ .../src/microcosm/calibrate/target_sets.py | 12 +- .../engine_free/shared/test_target_sets.py | 39 ++++++ .../calibration_line_reference.py | 65 ++++++++++ 9 files changed, 327 insertions(+), 21 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/uk/test_uk_calibration_line_selection.py create mode 100644 test_support/microcosm_build/calibration_line_reference.py diff --git a/changelog.d/1759-uk-declared-target-selection.changed.md b/changelog.d/1759-uk-declared-target-selection.changed.md index 37098749ba..c92843f0d7 100644 --- a/changelog.d/1759-uk-declared-target-selection.changed.md +++ b/changelog.d/1759-uk-declared-target-selection.changed.md @@ -1 +1 @@ -The UK full build selects its solve surface with the shared declared target sets, as the US does (microcosm#1759). `uk/target_sets.json` declares the UK level rule (a target's level is `geography_level` or `ledger_geography_level`; the two must agree, and the level must be one of country, region, constituency, la and brma) and the full build's selection by level, one clause for each level. `microcosm.calibrate.target_sets` reads a declared `level_rule` (the US `level_keys` form is unchanged) and its new `select_by_levels` keeps the requested levels in compile order with the same receipt (`microcosm.calibrate.target-selection.v1`). `microcosm.calibrate.target_selection` is removed: the UK selection kernel was its only caller, and `uk_runtime.graph_targets.target_geography` now reads the declared rule. No selection changes: `test_uk_level_selection.py` holds the new code to verbatim copies of the removed selector and resolver on random registries, refusals included. The new UK resource is in the UK solve fingerprint, so the first UK build after this change computes the spine from `frs_brma` on, the target nodes and the national graph again. +The UK full build selects its solve surface with the shared declared target sets, as the US does (microcosm#1759). `uk/target_sets.json` declares the UK level rule (a target's level is `geography_level` or `ledger_geography_level`; the two must agree, and the level must be one of country, region, constituency, la and brma) and the full build's selection by level, one clause for each level. `microcosm.calibrate.target_sets` reads a declared `level_rule` (the US `level_keys` form is unchanged) and its new `select_by_levels` keeps the requested levels in compile order with the same receipt (`microcosm.calibrate.target-selection.v1`). `microcosm.calibrate.target_selection` is removed: the UK selection kernel was its only caller, and `uk_runtime.graph_targets.target_geography` now reads the declared rule. No selection changes: `test_uk_level_selection.py` holds the new code to verbatim copies of the removed selector and resolver on random registries, refusals included. The new UK resource is in the UK solve fingerprint, so the first UK build after this change computes the spine from `frs_brma` on, the target nodes and the national graph again. The two UK calibration lines are declared there too, as the modes of a `calibration_line` product: `uk_runtime.ledger_targets.uk_registry_on_calibration_line` selects through it with one UK predicate that reads each contract target's `calibration_lines`, which stay in `uk/uk_population_targets.json`; `UK_CALIBRATION_LINES` is the declared modes. The shared selector now reads a target's level only when a clause tests levels. `test_uk_calibration_line_selection.py` holds the line filter to a verbatim copy of the replaced function: the same registry (the same object when nothing drops), the same receipt, or the same refusal. diff --git a/packages/microcosm-build/src/microcosm/build/uk/target_sets.json b/packages/microcosm-build/src/microcosm/build/uk/target_sets.json index d42678fb11..d8c117ac08 100644 --- a/packages/microcosm-build/src/microcosm/build/uk/target_sets.json +++ b/packages/microcosm-build/src/microcosm/build/uk/target_sets.json @@ -1,7 +1,7 @@ { "version": 1, "country": "uk", - "description": "The targets each UK build calibrates to (microcosm#1759): the level rule that places every compiled UK target at one geography level, and the full build's selection of its solve surface by level. microcosm.calibrate.target_sets reads this file; microcosm.build.uk_runtime.target_sets names its products. The US declares its target sets the same way, in us/target_sets.json (microcosm#1728).", + "description": "The targets each UK build calibrates to (microcosm#1759): the level rule that places every compiled UK target at one geography level, the full build's selection of its solve surface by level, and the two calibration lines. microcosm.calibrate.target_sets reads this file; microcosm.build.uk_runtime.target_sets names its products. The US declares its target sets the same way, in us/target_sets.json (microcosm#1728).", "level_rule": { "keys": [ "geography_level", @@ -69,6 +69,41 @@ ] } } + }, + "calibration_line": { + "tool": "packages/microcosm-build/src/microcosm/build/uk_runtime/full_targets.py", + "option": "line (uk_runtime.ledger_targets.uk_registry_on_calibration_line)", + "default_mode": "local", + "modes": { + "national": { + "description": "The national line's solve surface (load_uk_national_target_inputs and the release-cut certifier): the compiled national registry less the references whose contract target binds on the local line only. They leave right after the compile, before reconciliation, the measure exclusions and the frozen-register check (microcosm#1301).", + "compiled": [ + { + "id": "on_line", + "families": "*", + "levels": "*", + "exclude": [ + "off_calibration_line" + ], + "rationale": "A contract target binds on every line unless its calibration_lines field in uk/uk_population_targets.json narrows it; the field and its reason stay with the target, and uk_runtime.ledger_targets passes this clause the targets it leaves out. The high-value homes region rows bind on the local line only (microcosm#1240, microcosm#1301): on the national line they would move the national registry and solve while the Land Registry knots' tails place more homes in the top bands than the derived stock (microcosm#1112)." + } + ] + }, + "local": { + "description": "The local line's national rows (load_uk_full_target_inputs; the full dense build binds them beside the local surface): the compiled national registry less the references whose contract target binds on the national line only, dropped at the same point.", + "compiled": [ + { + "id": "on_line", + "families": "*", + "levels": "*", + "exclude": [ + "off_calibration_line" + ], + "rationale": "A contract target binds on every line unless its calibration_lines field in uk/uk_population_targets.json narrows it; the field and its reason stay with the target, and uk_runtime.ledger_targets passes this clause the targets it leaves out. The CenTax childcare-parent bands bind on the national line only (microcosm#1399)." + } + ] + } + } } } } diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/ledger_targets.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/ledger_targets.py index 6bce3bf2f6..525db1bf1d 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/ledger_targets.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/ledger_targets.py @@ -74,6 +74,11 @@ load_uk_scotland_brma_la_overlap, scotland_brma_council_overlaps, ) +from microcosm.build.uk_runtime.target_sets import ( + OFF_CALIBRATION_LINE, + uk_calibration_line_selection, + uk_calibration_lines, +) from microcosm.build.uk_runtime.tenure_drift import tenure_drift_appliers from microcosm.build.uk_runtime.uc_source_periods import ( validate_uc_source_month_coverage, @@ -87,6 +92,7 @@ UK_REGION_TIER, UK_REGION_TIER_ENUM, ) +from microcosm.calibrate.target_sets import select_target_set from microcosm.frame import Frame @@ -2067,8 +2073,9 @@ def _uk_contract_targets( #: The lines a UK contract target can bind on (microcosm#1301): the national #: line (``load_uk_national_target_inputs``, the release-cut certifier) and the #: local line (the full dense build, whose solve binds the national rows beside -#: the local surface). -UK_CALIBRATION_LINES: tuple[str, ...] = ("national", "local") +#: the local surface). They are the modes of the ``calibration_line`` product +#: in ``uk/target_sets.json`` (microcosm#1759). +UK_CALIBRATION_LINES: tuple[str, ...] = uk_calibration_lines() def uk_contract_target_calibration_lines(target: Mapping[str, Any]) -> frozenset[str]: @@ -2119,6 +2126,11 @@ def uk_registry_on_calibration_line( frozen-register check. A line no declaration narrows keeps its registry (the same object, so the same version). The receipt names the line, the all-lines registry version and count, and the dropped contract targets. + + The line is a mode of the declared ``calibration_line`` product + (``uk/target_sets.json``); its one clause keeps every reference but the + ones :data:`OFF_CALIBRATION_LINE` names, which this function binds to the + contract targets that leave ``line`` out (microcosm#1759). """ if line not in UK_CALIBRATION_LINES: @@ -2131,28 +2143,31 @@ def uk_registry_on_calibration_line( for target_id, target in _uk_contract_targets(national_only=False).items() if line not in uk_contract_target_calibration_lines(target) ) - kept: list[TargetSpec] = [] - dropped: list[TargetSpec] = [] - dropped_target_ids: set[str] = set() - for spec in registry.specs: - target_id = str( + + def contract_target_id(spec: TargetSpec) -> str: + return str( spec.metadata.get("contract_target_id") or spec.name.split("@", 1)[0] ) - if target_id in off_line: - dropped.append(spec) - dropped_target_ids.add(target_id) - else: - kept.append(spec) + + kept = select_target_set( + uk_calibration_line_selection(line), + registry.specs, + predicates={ + OFF_CALIBRATION_LINE: lambda spec: contract_target_id(spec) in off_line + }, + ).specs + on_line = {id(spec) for spec in kept} + dropped = [spec for spec in registry.specs if id(spec) not in on_line] receipt: dict[str, Any] = { "line": line, "all_lines_registry_version": registry.version, "all_lines_reference_count": len(registry.specs), "dropped_reference_count": len(dropped), - "dropped_target_ids": sorted(dropped_target_ids), + "dropped_target_ids": sorted({contract_target_id(spec) for spec in dropped}), } if not dropped: return registry, receipt - return TargetRegistry(kept, country=registry.country), receipt + return TargetRegistry(list(kept), country=registry.country), receipt def _spec_geography(spec: TargetSpec) -> tuple[str, str]: diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/target_compile_modules.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/target_compile_modules.py index 7edec3c404..1f7ff84a00 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/target_compile_modules.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/target_compile_modules.py @@ -70,6 +70,7 @@ "microcosm.build.uk_runtime.national_reconciliation", "microcosm.build.uk_runtime.off_surface_cells", "microcosm.build.uk_runtime.scotland_brma_la_overlap", + "microcosm.build.uk_runtime.target_sets", "microcosm.build.uk_runtime.tenure_constants", "microcosm.build.uk_runtime.uc_relationships", "microcosm.build.uk_runtime.uc_source_periods", @@ -79,6 +80,7 @@ "microcosm.calibrate.hierarchy", "microcosm.calibrate.registry", "microcosm.calibrate.target", + "microcosm.calibrate.target_sets", ) EXCLUDED_DIRECT_IMPORTS: Mapping[str, str] = MappingProxyType( diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/target_sets.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/target_sets.py index 58b2a50621..a3035fefa3 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/target_sets.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/target_sets.py @@ -1,9 +1,11 @@ """The declared target sets of the UK builds (microcosm#1759). ``uk/target_sets.json`` declares the UK level rule, which places every -compiled UK target at one geography level, and the full build's selection of -its solve surface by level (``uk.full.target_selection@1``, from the full -build's ``--target-geographies``). The shared reader and selector are in +compiled UK target at one geography level; the full build's selection of its +solve surface by level (``uk.full.target_selection@1``, from the full build's +``--target-geographies``); and the two calibration lines, which drop the +compiled national references a line does not bind (``calibration_line``, one +mode for each line). The shared reader and selector are in :mod:`microcosm.calibrate.target_sets`; this module names the UK file and products. The US declares its target sets the same way, in ``us/target_sets.json`` (microcosm#1728). @@ -23,9 +25,13 @@ ) __all__ = [ + "CALIBRATION_LINE_PRODUCT", "FULL_LEVELS_MODE", "FULL_PRODUCT", + "OFF_CALIBRATION_LINE", "UK_TARGET_SETS_RESOURCE", + "uk_calibration_line_selection", + "uk_calibration_lines", "uk_full_level_selection", "uk_target_level", "uk_target_set_declarations", @@ -36,6 +42,10 @@ #: The full build's product, and its one mode: selection by level. FULL_PRODUCT = "full" FULL_LEVELS_MODE = "levels" +#: The calibration lines' product, one mode for each line, and the predicate +#: its clause excludes by: the targets whose contract leaves the line out. +CALIBRATION_LINE_PRODUCT = "calibration_line" +OFF_CALIBRATION_LINE = "off_calibration_line" def uk_target_sets_path() -> Path: @@ -55,6 +65,18 @@ def uk_full_level_selection() -> TargetSetDeclaration: return uk_target_set_declarations().declaration(FULL_PRODUCT, FULL_LEVELS_MODE) +def uk_calibration_lines() -> tuple[str, ...]: + """The declared calibration lines, in declaration order.""" + + return uk_target_set_declarations().product(CALIBRATION_LINE_PRODUCT).mode_names + + +def uk_calibration_line_selection(line: str) -> TargetSetDeclaration: + """The selection of one calibration line's national references.""" + + return uk_target_set_declarations().declaration(CALIBRATION_LINE_PRODUCT, line) + + def uk_target_level(spec: Any) -> str: """A compiled UK target's geography level, by the declared level rule. diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_calibration_line_selection.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_calibration_line_selection.py new file mode 100644 index 0000000000..454b7d1ca3 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_calibration_line_selection.py @@ -0,0 +1,120 @@ +"""The UK calibration lines as declared target sets, against the replaced code. + +Before microcosm#1759, ``uk_runtime.ledger_targets.uk_registry_on_calibration_line`` +dropped the targets that a line does not bind with its own loop. It now +selects through ``uk/target_sets.json`` (product ``calibration_line``, one mode +for each line) with the shared ``select_target_set`` and one UK predicate. +``test_support/microcosm_build/calibration_line_reference.py`` holds the old +function verbatim. On random registries the two give the same registry (the +same object when nothing drops), the same receipt, or the same refusal. +""" + +from __future__ import annotations + +import numpy as np +import pytest + +from microcosm.build.uk_runtime import ledger_targets +from microcosm.build.uk_runtime.target_sets import ( + CALIBRATION_LINE_PRODUCT, + uk_calibration_lines, + uk_target_set_declarations, +) +from microcosm.calibrate import TargetRegistry, TargetSpec +from test_support.microcosm_build import calibration_line_reference as reference + +_CONTRACT = ledger_targets._uk_contract_targets(national_only=False) +#: The contract targets that bind on one line only, and some that bind on both. +_NARROWED = sorted( + target_id + for target_id, target in _CONTRACT.items() + if ledger_targets.uk_contract_target_calibration_lines(target) + != frozenset(ledger_targets.UK_CALIBRATION_LINES) +) +_BOTH = sorted(set(_CONTRACT) - set(_NARROWED))[:40] + + +def _registry(seed: int) -> TargetRegistry: + rng = np.random.default_rng(seed) + specs = [] + for index in range(int(rng.integers(0, 25))): + draw = rng.uniform() + if draw < 0.3: + target_id = str(rng.choice(_NARROWED)) + elif draw < 0.8: + target_id = str(rng.choice(_BOTH)) + else: + target_id = f"microcosm.test.unknown_{index}" + metadata = {} + if rng.uniform() < 0.5: + metadata["contract_target_id"] = target_id + name = f"row_{index}@2025" + else: + name = f"{target_id}@{2024 + int(rng.integers(2))}#{index}" + # A line selection must not read levels: some rows have none. + if rng.uniform() < 0.5: + metadata["geography_level"] = str( + rng.choice(["country", "region", "nation"]) + ) + specs.append( + TargetSpec( + name=name, + entity="household", + measure="household_weight", + value=float(rng.uniform(1.0, 1e6)), + period=2025, + source="test", + family="test_family", + metadata=metadata, + ) + ) + return TargetRegistry(specs, country="uk") + + +def _outcome(select, registry): + try: + result, receipt = select() + except Exception as error: # noqa: BLE001 - the refusal is the outcome + return ("refused", type(error).__name__, str(error)) + return ( + "selected", + result is registry, + result.version, + [spec.name for spec in result.specs], + receipt, + ) + + +@pytest.mark.parametrize("seed", range(150)) +@pytest.mark.parametrize("line", ["national", "local", "regional"]) +def test_each_line_matches_the_replaced_code(seed: int, line: str) -> None: + registry = _registry(seed) + old = _outcome( + lambda: reference.uk_registry_on_calibration_line(registry, line=line), + registry, + ) + new = _outcome( + lambda: ledger_targets.uk_registry_on_calibration_line(registry, line=line), + registry, + ) + assert new == old + + +def test_the_cases_drop_rows_on_both_lines() -> None: + dropped = {"national": 0, "local": 0} + for seed in range(150): + registry = _registry(seed) + for line in dropped: + result, receipt = ledger_targets.uk_registry_on_calibration_line( + registry, line=line + ) + dropped[line] += receipt["dropped_reference_count"] + assert (result is registry) == (receipt["dropped_reference_count"] == 0) + assert all(count > 0 for count in dropped.values()), dropped + + +def test_the_lines_are_the_declared_modes() -> None: + product = uk_target_set_declarations().product(CALIBRATION_LINE_PRODUCT) + assert ledger_targets.UK_CALIBRATION_LINES == uk_calibration_lines() + assert uk_calibration_lines() == product.mode_names == ("national", "local") + assert _NARROWED diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py b/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py index 54b5dd720e..46b33602c8 100644 --- a/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py @@ -605,7 +605,10 @@ def select_target_set( Each compiled clause (only those in ``clause_ids``, when given) keeps the specs it accepts, in compile order; a clause with a rule passes them to - the rule. The selection is the clauses' outputs in declaration order. + the rule. The selection is the clauses' outputs in declaration order. A + spec's level is read only when an active clause tests levels, so a + closed level rule refuses only the specs that a selection places by + level. Raises: KeyError: If ``clause_ids`` names a clause the declaration lacks. @@ -637,7 +640,12 @@ def select_target_set( f"{clause.clause_id!r} names rule {clause.rule!r}, which the " "caller did not pass." ) - levels = [declaration.level_of(spec) for spec in specs] + # A level is read only when a clause tests levels, so a closed level rule + # does not refuse a target that no active clause places by level. + if any(clause.levels is not None for clause in clauses): + levels = [declaration.level_of(spec) for spec in specs] + else: + levels = [UNSPECIFIED_LEVEL] * len(specs) kept: list[Any] = [] counts: dict[str, int] = {} receipts: dict[str, Any] = {} diff --git a/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py b/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py index 9c8bbf7f17..4471295188 100644 --- a/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py +++ b/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py @@ -580,3 +580,42 @@ def test_select_by_levels_needs_a_level_mode() -> None: registry, load_target_set_declarations(missing).declaration("full", "levels"), ) + + +def test_a_selection_that_tests_no_level_reads_no_level() -> None: + """A closed rule refuses an unplaced target only where a clause tests levels.""" + + declarations = _level_declarations() + declarations["products"]["lines"] = { + "tool": "t", + "option": "line", + "default_mode": "national", + "modes": { + "national": { + "description": "Every target but the local-only ones.", + "compiled": [ + { + "id": "on_line", + "families": "*", + "levels": "*", + "exclude": ["off_line"], + "rationale": "r", + } + ], + } + }, + } + loaded = load_target_set_declarations(declarations) + specs = ( + _spec("placed", "tax", level="la"), + _spec("unplaced", "tax"), + _spec("local_only", "tax", level="nation"), + ) + selection = select_target_set( + loaded.declaration("lines", "national"), + specs, + predicates={"off_line": lambda spec: spec.name == "local_only"}, + ) + assert [spec.name for spec in selection.specs] == ["placed", "unplaced"] + with pytest.raises(ValueError, match="'unplaced' has unsupported geography level"): + select_target_set(loaded.declaration("full", "levels"), specs) diff --git a/test_support/microcosm_build/calibration_line_reference.py b/test_support/microcosm_build/calibration_line_reference.py new file mode 100644 index 0000000000..2c8f7a614e --- /dev/null +++ b/test_support/microcosm_build/calibration_line_reference.py @@ -0,0 +1,65 @@ +# Verbatim copy of uk_registry_on_calibration_line from +# microcosm.build.uk_runtime.ledger_targets at 508351658, before microcosm#1759 +# declared the calibration lines in uk/target_sets.json. Tests hold the new +# code to it; do not edit. It reads the contract through the live helpers. +# ruff: noqa + +from __future__ import annotations + +from typing import Any + +from microcosm.build.uk_runtime.ledger_targets import ( + _uk_contract_targets, + uk_contract_target_calibration_lines, +) +from microcosm.calibrate import TargetRegistry, TargetSpec + +UK_CALIBRATION_LINES: tuple[str, ...] = ("national", "local") + + +def uk_registry_on_calibration_line( + registry: TargetRegistry, *, line: str +) -> tuple[TargetRegistry, dict[str, Any]]: + """The compiled registry less the references ``line`` does not bind. + + Every committed reference compiles on every line, so the compile-parity + registries stay complete; a line's solve surface drops the references + whose contract target's ``calibration_lines`` leave ``line`` out, right + after the compile and before reconciliation, the measure exclusions and the + frozen-register check. A line no declaration narrows keeps its registry + (the same object, so the same version). The receipt names the line, the + all-lines registry version and count, and the dropped contract targets. + """ + + if line not in UK_CALIBRATION_LINES: + raise ValueError( + f"unknown UK calibration line {line!r}; the lines are " + f"{list(UK_CALIBRATION_LINES)!r}." + ) + off_line = frozenset( + target_id + for target_id, target in _uk_contract_targets(national_only=False).items() + if line not in uk_contract_target_calibration_lines(target) + ) + kept: list[TargetSpec] = [] + dropped: list[TargetSpec] = [] + dropped_target_ids: set[str] = set() + for spec in registry.specs: + target_id = str( + spec.metadata.get("contract_target_id") or spec.name.split("@", 1)[0] + ) + if target_id in off_line: + dropped.append(spec) + dropped_target_ids.add(target_id) + else: + kept.append(spec) + receipt: dict[str, Any] = { + "line": line, + "all_lines_registry_version": registry.version, + "all_lines_reference_count": len(registry.specs), + "dropped_reference_count": len(dropped), + "dropped_target_ids": sorted(dropped_target_ids), + } + if not dropped: + return registry, receipt + return TargetRegistry(kept, country=registry.country), receipt From 4e74c81a1cd3ab3d326b228e12e1070ea3b13725 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:51:59 +0000 Subject: [PATCH 14/30] Share the hold-out split and the held estimates between the UK and the US MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The UK rowwise hold-out and the US local hold-out keep their own draws: rotated folds over the UK's local target rows, and hashed blocks over US units. They now share the two steps after the draw (microcosm#1759, step D4): - microcosm.build.holdout.HoldoutSplit names a split's training rows and held rows. fold_splits makes one for each rotated fold, and target_holdouts.role_split makes one from the US roles. - microcosm.build.holdout.held_estimates gives the held rows' estimates from the target matrix and the solved weights, in float64. rotated_uk_local_holdout (with the size stage's record columns) and target_holdouts.score_holdout both call it. - The UK hold-out node (uk.full.rotated-holdout@1) now also hashes microcosm.build.holdout. It already ran rotated_folds from that module without hashing it. No result changes. test_holdout.py compares fold_splits with the old rotated_folds and setdiff1d code. It also compares held_estimates with the replaced UK and US expressions on random float64 and float32 data, byte for byte. The 91 US hold-out tests still match the verbatim copies of the old tool code, and the UK hold-out, candidate-scorer and graph tests pass unchanged. The UK fold constants stay in local_rowwise.py, as María ruled. Co-Authored-By: Claude Opus 5.5 --- .../1759-shared-holdout-split.changed.md | 1 + .../src/microcosm/build/holdout.py | 71 +++++++++++++++ .../src/microcosm/build/target_holdouts.py | 33 +++++-- .../build/uk_runtime/graph_terminal.py | 4 + .../build/uk_runtime/local_rowwise.py | 31 +++---- .../tests/engine_free/shared/test_holdout.py | 86 +++++++++++++++++++ 6 files changed, 201 insertions(+), 25 deletions(-) create mode 100644 changelog.d/1759-shared-holdout-split.changed.md diff --git a/changelog.d/1759-shared-holdout-split.changed.md b/changelog.d/1759-shared-holdout-split.changed.md new file mode 100644 index 0000000000..08b38192b5 --- /dev/null +++ b/changelog.d/1759-shared-holdout-split.changed.md @@ -0,0 +1 @@ +The UK and US hold-outs share their last two steps (microcosm#1759). `microcosm.build.holdout` gains `HoldoutSplit` (a split's training rows and held rows), `fold_splits` (the UK's rotated folds as splits) and `held_estimates` (the held rows' estimates from the target matrix and the solved weights, in float64). The UK rowwise hold-out (`uk_runtime.local_rowwise.rotated_uk_local_holdout`) and the US local hold-out (`microcosm.build.target_holdouts`, through the new `role_split`) both use them; the two draws stay apart on purpose (rotated folds over UK local target rows, hashed blocks over US units). No hold-out result changes: `test_holdout.py` holds the new functions to the replaced UK and US expressions byte for byte, and the US hold-out tests compare with verbatim copies of the old tool code. The UK hold-out node now also hashes `microcosm.build.holdout`, which it ran without hashing. The UK hold-out keeps its constants (5 folds, seed 20260529, in `uk_runtime/local_rowwise.py`); a stricter UK hold-out would start there. diff --git a/packages/microcosm-build/src/microcosm/build/holdout.py b/packages/microcosm-build/src/microcosm/build/holdout.py index 48da446677..c739ad0c08 100644 --- a/packages/microcosm-build/src/microcosm/build/holdout.py +++ b/packages/microcosm-build/src/microcosm/build/holdout.py @@ -16,6 +16,14 @@ reshuffles every fold when one target is added or the surface is reordered; a keyed hash does not, so a holdout assigned this way stays the same set of units across surface revisions, and raising the fraction only adds units. + +Both shapes end in the same two steps (microcosm#1759). A :class:`HoldoutSplit` +names the target rows a solve trains on and the rows it is scored on: the UK +rowwise hold-out makes one for each rotated fold (:func:`fold_splits`), and +the US local hold-out makes one from its hashed roles +(:func:`microcosm.build.target_holdouts.role_split`). :func:`held_estimates` +gives the held rows' estimates from the target matrix and the solved weights, +in float64, for both scorers. """ from __future__ import annotations @@ -26,6 +34,7 @@ from dataclasses import dataclass import numpy as np +from scipy import sparse __all__ = [ "rotated_folds", @@ -33,6 +42,9 @@ "RotationSummary", "hash_holdout_uniform", "hash_holdout_unit", + "HoldoutSplit", + "fold_splits", + "held_estimates", ] #: Units per draw: the first 8 bytes of a SHA-256 digest, read big-endian. @@ -153,3 +165,62 @@ def hash_holdout_unit(key: str, *, fraction: float, salt: str) -> bool: ): raise ValueError(f"holdout fraction must be in [0, 1], got {fraction!r}.") return hash_holdout_uniform(key, salt=salt) < float(fraction) + + +@dataclass(frozen=True) +class HoldoutSplit: + """One hold-out split of a target surface. + + Attributes: + name: The split's name, for example ``"fold_0"`` or ``"roles"``. + train_rows: The target rows the solve trains on, as int64. + held_rows: The target rows the solve is scored on, as int64. + """ + + name: str + train_rows: np.ndarray + held_rows: np.ndarray + + +def fold_splits( + n_targets: int, *, n_folds: int = 5, seed: int = 20260529 +) -> tuple[HoldoutSplit, ...]: + """:func:`rotated_folds` as splits: each fold is held, the others train. + + The training rows are the sorted rows of no other fold + (``np.setdiff1d`` over ``range(n_targets)``); the arguments and refusals + are those of :func:`rotated_folds`. + """ + + every_row = np.arange(n_targets, dtype=np.int64) + return tuple( + HoldoutSplit( + name=f"fold_{index}", + train_rows=np.setdiff1d(every_row, held, assume_unique=True), + held_rows=held, + ) + for index, held in enumerate( + rotated_folds(n_targets, n_folds=n_folds, seed=seed) + ) + ) + + +def held_estimates( + matrix, rows, weights, *, columns: np.ndarray | None = None +) -> np.ndarray: + """The held rows' estimates: ``matrix[rows]`` times ``weights``, in float64. + + ``matrix`` is a sparse target matrix (targets by records); a dense one is + read as CSR. ``columns``, when given, first keeps those record columns, + in that order, as a solve that kept only some records needs. The matrix + rows and the weights are widened to float64 before the product, so the + result does not depend on their stored precision. + """ + + held = matrix[rows] + if not sparse.issparse(held): + held = sparse.csr_array(held) + if columns is not None: + held = held[:, columns] + estimates = held.astype(np.float64) @ np.asarray(weights, dtype=np.float64) + return np.asarray(estimates, dtype=np.float64).reshape(-1) diff --git a/packages/microcosm-build/src/microcosm/build/target_holdouts.py b/packages/microcosm-build/src/microcosm/build/target_holdouts.py index 5384b28eb1..cb0305385e 100644 --- a/packages/microcosm-build/src/microcosm/build/target_holdouts.py +++ b/packages/microcosm-build/src/microcosm/build/target_holdouts.py @@ -42,7 +42,11 @@ import numpy as np from scipy import sparse -from microcosm.build.holdout import hash_holdout_unit +from microcosm.build.holdout import ( + HoldoutSplit, + hash_holdout_unit, + held_estimates, +) __all__ = [ "CONCEPT_FAMILY_FIELD", @@ -67,6 +71,7 @@ "load_target_holdouts", "missing_population_shares", "pro_rata_baseline", + "role_split", "score_holdout", "train_rows", "training_target_set", @@ -539,6 +544,20 @@ def holdout_rows(records: Sequence[Mapping]) -> list[int]: ] +def role_split(records: Sequence[Mapping]) -> HoldoutSplit: + """The records' roles as one shared hold-out split (``"roles"``). + + The same split type as the UK's rotated folds + (:func:`microcosm.build.holdout.fold_splits`, microcosm#1759). + """ + + return HoldoutSplit( + name="roles", + train_rows=np.asarray(train_rows(records), dtype=np.int64), + held_rows=np.asarray(holdout_rows(records), dtype=np.int64), + ) + + # --------------------------------------------------------------------------- # The training target set # --------------------------------------------------------------------------- @@ -597,8 +616,9 @@ def training_target_set( record["name"] for record in records ]: raise ValueError("target specs are not row-aligned with the roles.") + split = role_split(records) targets = [] - for index in train_rows(records): + for index in split.train_rows.tolist(): record = records[index] if record["role"] != ROLE_TRAIN: # pragma: no cover - train_rows filters raise AssertionError("a held-out target reached the calibration set") @@ -634,7 +654,7 @@ def training_target_set( hierarchy=spec.hierarchy, ) ) - held = {records[index]["name"] for index in holdout_rows(records)} + held = {records[index]["name"] for index in split.held_rows.tolist()} leaked = held & {target.name for target in targets} if leaked: raise AssertionError(f"held-out targets reached the calibrator: {leaked}") @@ -774,16 +794,15 @@ def score_holdout( rows = [ row - for row in holdout_rows(records) + for row in role_split(records).held_rows.tolist() if records[row].get("geography_level") == scoring.level ] base = {"report_only": True, **dict(receipt or {}), "n_targets": len(rows)} if not rows: return base - held = sparse.csr_array(matrix[rows]).astype(np.float64) targets = np.asarray([records[index]["value"] for index in rows], dtype=np.float64) - final = held @ np.asarray(final_weights, dtype=np.float64) - design = held @ np.asarray(design_weights, dtype=np.float64) + final = held_estimates(matrix, rows, final_weights) + design = held_estimates(matrix, rows, design_weights) baseline = pro_rata_baseline(records, rows, scoring) scale = np.maximum(np.abs(targets), 1.0) final_error = np.abs(final - targets) / scale diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_terminal.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_terminal.py index 496fad4f2d..c8ca4f0c53 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_terminal.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_terminal.py @@ -1353,6 +1353,7 @@ class UKFullHoldoutKernel(KernelBase): ) def implementation_hash(self) -> str: + import microcosm.build.holdout as shared_holdout import microcosm.calibrate.target_loss_rules as calibrate_target_loss_rules from . import ( @@ -1379,6 +1380,9 @@ def implementation_hash(self) -> str: # The shared rules that compute the weights the # holdout re-applies (microcosm#1729). calibrate_target_loss_rules, + # The folds and the held rows' estimates + # (fold_splits, held_estimates; microcosm#1759). + shared_holdout, dependencies=self.capabilities.dependencies, ), # The holdout repeats the solve: it keys on the solve diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/local_rowwise.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/local_rowwise.py index 1152b778e7..9b2169b391 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/local_rowwise.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/local_rowwise.py @@ -31,7 +31,7 @@ import pandas as pd from scipy import sparse as sp -from microcosm.build.holdout import rotated_folds, summarize_rotations +from microcosm.build.holdout import fold_splits, held_estimates, summarize_rotations from microcosm.build.uk_runtime import local_target_census from microcosm.build.uk_runtime.local_doctrine import ( UK_LOCAL_ROW_METADATA_RULES, @@ -2010,12 +2010,11 @@ def rotated_uk_local_holdout( 0 if national_rows is None else len(national_rows.targets) ), } - folds = rotated_folds( + splits = fold_splits( len(problem.targets), n_folds=UK_LOCAL_HOLDOUT_FOLDS, seed=UK_LOCAL_HOLDOUT_SEED, ) - all_indices = np.arange(len(problem.targets), dtype=np.int64) # A row-metadata rule weights the held rows from their own row carrier # (microcosm#1124); the grain rules keep the grain-label path. local_rows = ( @@ -2031,12 +2030,8 @@ def rotated_uk_local_holdout( for family in bound_families if str(family).startswith("national/") ] - for fold_index, holdout_indices in enumerate(folds): - train_indices = np.setdiff1d( - all_indices, - holdout_indices, - assume_unique=True, - ) + for fold_index, split in enumerate(splits): + train_indices, holdout_indices = split.train_rows, split.held_rows train_problem = _subset_rowwise_problem(problem, train_indices) train_families = _derive_uk_local_bound_families_from_target_frame( train_problem.target_frame, @@ -2072,16 +2067,16 @@ def rotated_uk_local_holdout( refit_l2_basis=refit_l2_basis, ) held_targets = problem.targets[holdout_indices] - held_estimates = np.asarray( - problem.matrix[holdout_indices][ - :, + fold_estimates = held_estimates( + problem.matrix, + holdout_indices, + train_solve.weights, + columns=( np.arange(problem.n_households) if train_solve.selected_support is None - else train_solve.selected_support, - ] - @ train_solve.weights, - dtype=np.float64, - ).reshape(-1) + else train_solve.selected_support + ), + ) if local_rows is not None: held_weights = uk_target_loss_weights_for_rows( local_rows.take(holdout_indices), rule=target_weight_rule @@ -2092,7 +2087,7 @@ def rotated_uk_local_holdout( rule=target_weight_rule, ) loss = relative_error_loss( - held_estimates, + fold_estimates, held_targets, target_loss_weights=held_weights, target_loss_scales=uk_family_floored_loss_scales( diff --git a/packages/microcosm-build/tests/engine_free/shared/test_holdout.py b/packages/microcosm-build/tests/engine_free/shared/test_holdout.py index 84db0a3977..ccaff9cf1d 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_holdout.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_holdout.py @@ -52,3 +52,89 @@ def test_empty_and_nonfinite_refused(self) -> None: summarize_rotations([]) with pytest.raises(ValueError, match="non-finite"): summarize_rotations([0.1, float("nan")]) + + +# --------------------------------------------------------------------------- +# The shared split and held estimates (microcosm#1759), against the code they +# replaced in uk_runtime.local_rowwise and microcosm.build.target_holdouts. +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("n_targets", [2, 5, 17, 103]) +@pytest.mark.parametrize("seed", [1, 20260529]) +def test_fold_splits_are_the_folds_the_uk_holdout_built(n_targets, seed) -> None: + from microcosm.build.holdout import fold_splits + + n_folds = min(5, n_targets) + every_row = np.arange(n_targets, dtype=np.int64) + old = [ + (np.setdiff1d(every_row, held, assume_unique=True), held) + for held in rotated_folds(n_targets, n_folds=n_folds, seed=seed) + ] + new = fold_splits(n_targets, n_folds=n_folds, seed=seed) + assert [split.name for split in new] == [f"fold_{i}" for i in range(n_folds)] + for (old_train, old_held), split in zip(old, new, strict=True): + assert split.train_rows.dtype == old_train.dtype + assert split.held_rows.dtype == old_held.dtype + assert split.train_rows.tobytes() == old_train.tobytes() + assert split.held_rows.tobytes() == old_held.tobytes() + + +def _sparse(seed: int, shape, dtype, kind): + + rng = np.random.default_rng(seed) + dense = rng.normal(0.0, 3.0, size=shape) + dense[rng.uniform(size=shape) < 0.7] = 0.0 + return kind(dense.astype(dtype)) + + +@pytest.mark.parametrize("seed", range(20)) +@pytest.mark.parametrize("weight_dtype", [np.float64, np.float32]) +def test_held_estimates_match_the_uk_expression(seed, weight_dtype) -> None: + from scipy import sparse + + from microcosm.build.holdout import held_estimates + + rng = np.random.default_rng(seed + 100) + matrix = _sparse(seed, (40, 60), np.float64, sparse.csr_matrix) + rows = np.sort(rng.choice(40, size=9, replace=False)).astype(np.int64) + weights = rng.uniform(0.0, 5.0, size=60).astype(weight_dtype) + for columns in (np.arange(60), np.sort(rng.choice(60, size=25, replace=False))): + used = weights[: len(columns)] + old = np.asarray(matrix[rows][:, columns] @ used, dtype=np.float64).reshape(-1) + new = held_estimates(matrix, rows, used, columns=columns) + assert new.dtype == old.dtype + assert new.tobytes() == old.tobytes() + + +@pytest.mark.parametrize("seed", range(20)) +@pytest.mark.parametrize("weight_dtype", [np.float64, np.float32]) +def test_held_estimates_match_the_us_expression(seed, weight_dtype) -> None: + from scipy import sparse + + from microcosm.build.holdout import held_estimates + + rng = np.random.default_rng(seed + 200) + matrix = _sparse(seed, (30, 45), np.float32, sparse.csr_array) + rows = sorted(int(row) for row in rng.choice(30, size=7, replace=False)) + weights = rng.uniform(0.1, 4.0, size=45).astype(weight_dtype) + held = sparse.csr_array(matrix[rows]).astype(np.float64) + old = held @ np.asarray(weights, dtype=np.float64) + new = held_estimates(matrix, rows, weights) + assert new.dtype == old.dtype + assert new.tobytes() == old.tobytes() + + +def test_role_split_holds_the_roles() -> None: + from microcosm.build.target_holdouts import ( + holdout_rows, + role_split, + train_rows, + ) + + records = [{"role": role} for role in ("train", "holdout", "train", "holdout")] + split = role_split(records) + assert split.name == "roles" + assert split.train_rows.tolist() == train_rows(records) == [0, 2] + assert split.held_rows.tolist() == holdout_rows(records) == [1, 3] + assert split.train_rows.dtype == split.held_rows.dtype == np.int64 From 2ead043a469bd1eb306ca918c76c4b45c23bd733 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:56:26 +0000 Subject: [PATCH 15/30] Add the shared review core for signed register entries microcosm.build.declared_registers gains what every signed register file needs, for any country (microcosm#1759, step D5): - read_strict_json reads JSON and refuses duplicate keys, non-finite numbers and malformed text, with the texts the UK reviewed-exclusion reader uses; - canonical_date reads a date only as YYYY-MM-DD (date.fromisoformat also accepts the compact and week-date forms); - ReviewWindow is an entry's window, approved_on to expires_on with both days in force, and gives its state on a date and the days left; - stale_entries gives the declared entries that name nothing found. They return values; the country's code keeps its error texts and decides what a lapse does. No code calls them yet. The new shared tests cover each function; the US register tests and spec-engine checks pass unchanged. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/build/declared_registers.py | 124 +++++++++++++++++- .../shared/test_declared_registers.py | 91 +++++++++++++ 2 files changed, 214 insertions(+), 1 deletion(-) diff --git a/packages/microcosm-build/src/microcosm/build/declared_registers.py b/packages/microcosm-build/src/microcosm/build/declared_registers.py index 3a132830e9..bb4a08f543 100644 --- a/packages/microcosm-build/src/microcosm/build/declared_registers.py +++ b/packages/microcosm-build/src/microcosm/build/declared_registers.py @@ -18,22 +18,45 @@ reads one section. JSON arrays read back as tuples and JSON objects as dicts, so a register reads back as the Python literal it replaces, in entry order. Nothing here holds country data. + +**Signed entries** (microcosm#1759). Many reviewed files sign each entry: who +approved it, on what date, and until when it is in force. Every such file +needs the same few things, which the end of this module holds for any +country: + +- :func:`read_strict_json` reads JSON and refuses duplicate keys and + non-finite numbers; +- :func:`canonical_date` reads a date only in its one canonical spelling + (``YYYY-MM-DD``); +- :class:`ReviewWindow` is an entry's window, ``approved_on`` to + ``expires_on`` with both days included, and its state on a date; +- :func:`stale_entries` gives the declared entries that name nothing found. + +They return values. The country's code writes the error texts and decides +what a lapse does: refuse a run, fail a gate, or report it. """ from __future__ import annotations import json -from collections.abc import Mapping +from collections.abc import Iterable, Mapping +from dataclasses import dataclass +from datetime import date from functools import cache from importlib.resources import files from typing import Any __all__ = [ "NOTE_FIELD", + "WINDOW_STATES", "DeclaredRegisterError", + "ReviewWindow", + "canonical_date", "load_register", "package_register", "package_registers", + "read_strict_json", + "stale_entries", ] #: The optional entry field that explains one entry. @@ -171,3 +194,102 @@ def package_register(package: str, resource: str, name: str) -> Any: f"{sorted(registers)}." ) return load_register(registers[name], name=name) + + +# --------------------------------------------------------------------------- +# Signed entries: strict reads and review windows +# --------------------------------------------------------------------------- + +#: The states of a review window on a date, in time order. +WINDOW_STATES = ("premature", "in_force", "expired") + + +def read_strict_json(text: str, *, label: str) -> Any: + """Read JSON text; refuse duplicate object keys and non-finite numbers. + + Raises: + DeclaredRegisterError: ``"{label}: duplicate JSON key(s): [...]."``, + ``"{label}: non-finite JSON value 'NaN' is invalid."`` or + ``"{label}: malformed JSON: ."``. + """ + + def strict_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + duplicates: set[str] = set() + for name, value in pairs: + if name in result: + duplicates.add(name) + result[name] = value + if duplicates: + raise DeclaredRegisterError( + f"{label}: duplicate JSON key(s): {sorted(duplicates)}." + ) + return result + + def reject_nonfinite(value: str) -> Any: + raise DeclaredRegisterError( + f"{label}: non-finite JSON value {value!r} is invalid." + ) + + try: + return json.loads( + text, object_pairs_hook=strict_object, parse_constant=reject_nonfinite + ) + except json.JSONDecodeError as exc: + raise DeclaredRegisterError(f"{label}: malformed JSON: {exc.msg}.") from exc + + +def canonical_date(value: Any) -> date | None: + """``value`` as a date if it is a canonical ISO date string, else None. + + ``date.fromisoformat`` also reads the compact (``20270210``) and week-date + forms. A signed date has one spelling, because the raw text is often + sealed into a digest, so only ``YYYY-MM-DD`` counts. + """ + + if not isinstance(value, str): + return None + try: + parsed = date.fromisoformat(value) + except ValueError: + return None + return parsed if parsed.isoformat() == value else None + + +@dataclass(frozen=True) +class ReviewWindow: + """The days an approval is in force: ``approved_on`` to ``expires_on``. + + Both days are in force. A date before ``approved_on`` is premature; a + date after ``expires_on`` is expired. + """ + + approved_on: date + expires_on: date + + def premature(self, on: date) -> bool: + return on < self.approved_on + + def expired(self, on: date) -> bool: + return on > self.expires_on + + def in_force(self, on: date) -> bool: + return self.approved_on <= on <= self.expires_on + + def state(self, on: date) -> str: + """One of :data:`WINDOW_STATES`.""" + + if self.premature(on): + return "premature" + return "expired" if self.expired(on) else "in_force" + + def days_left(self, on: date) -> int: + """Days from ``on`` to ``expires_on``; negative once expired.""" + + return (self.expires_on - on).days + + +def stale_entries(declared: Iterable[str], matched: Iterable[str]) -> list[str]: + """The declared entries that name nothing found, sorted.""" + + return sorted(set(declared) - set(matched)) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_declared_registers.py b/packages/microcosm-build/tests/engine_free/shared/test_declared_registers.py index e87a416994..ebf5c9cc84 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_declared_registers.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_declared_registers.py @@ -130,3 +130,94 @@ def test_a_malformed_register_refuses(case: str) -> None: _broken()[case](section) with pytest.raises(DeclaredRegisterError): load_register(section) + + +# --------------------------------------------------------------------------- +# Signed entries: strict reads and review windows (microcosm#1759) +# --------------------------------------------------------------------------- + + +def test_read_strict_json_refuses_duplicates_non_finite_and_malformed() -> None: + from microcosm.build.declared_registers import read_strict_json + + assert read_strict_json('{"a": [1, {"b": 2.5}]}', label="f") == { + "a": [1, {"b": 2.5}] + } + with pytest.raises( + DeclaredRegisterError, match=r"^f: duplicate JSON key\(s\): \['a'\]\.$" + ): + read_strict_json('{"a": 1, "a": 2}', label="f") + with pytest.raises( + DeclaredRegisterError, match=r"duplicate JSON key\(s\): \['b'\]" + ): + read_strict_json('{"a": {"b": 1, "b": 1}}', label="f") + for constant in ("NaN", "Infinity", "-Infinity"): + with pytest.raises( + DeclaredRegisterError, + match=rf"^f: non-finite JSON value '{constant}' is invalid\.$", + ): + read_strict_json(f'{{"a": {constant}}}', label="f") + with pytest.raises(DeclaredRegisterError, match=r"^f: malformed JSON: .+\.$"): + read_strict_json('{"a": }', label="f") + assert issubclass(DeclaredRegisterError, ValueError) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2026-11-26", "2026-11-26"), + ("2024-02-29", "2024-02-29"), + ("20261126", None), + ("2026-W48-4", None), + ("2026-11-26T00:00", None), + ("2026-02-30", None), + (" 2026-11-26", None), + ("", None), + (None, None), + (20261126, None), + ], +) +def test_canonical_date_reads_only_the_canonical_spelling(value, expected) -> None: + from microcosm.build.declared_registers import canonical_date + + parsed = canonical_date(value) + assert (None if parsed is None else parsed.isoformat()) == expected + + +def test_a_review_window_includes_both_days() -> None: + from datetime import date + + from microcosm.build.declared_registers import WINDOW_STATES, ReviewWindow + + window = ReviewWindow(date(2026, 10, 1), date(2026, 12, 31)) + states = { + day: window.state(date.fromisoformat(day)) + for day in ( + "2026-09-30", + "2026-10-01", + "2026-11-26", + "2026-12-31", + "2027-01-01", + ) + } + assert states == { + "2026-09-30": "premature", + "2026-10-01": "in_force", + "2026-11-26": "in_force", + "2026-12-31": "in_force", + "2027-01-01": "expired", + } + assert set(states.values()) == set(WINDOW_STATES) + assert window.premature(date(2026, 9, 30)) and not window.in_force( + date(2026, 9, 30) + ) + assert window.expired(date(2027, 1, 1)) and not window.in_force(date(2027, 1, 1)) + assert window.days_left(date(2026, 12, 24)) == 7 + assert window.days_left(date(2027, 1, 2)) == -2 + + +def test_stale_entries_are_the_declared_names_not_found() -> None: + from microcosm.build.declared_registers import stale_entries + + assert stale_entries(["b", "a", "c", "a"], {"c"}) == ["a", "b"] + assert stale_entries([], ["x"]) == [] From c866b89510f77c8026b40c46289b4381219a9994 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:04:02 +0000 Subject: [PATCH 16/30] Check the UK exclusions' and support floor's dates with the review core The UK compile-side loaders of signed entries now use the shared review core (microcosm#1759, step D6): - measure_simulation.load_uk_calibration_measure_exclusions reads each approval and expiry with canonical_date. - apply_uk_calibration_measure_exclusions checks each window and its seven-day warning with ReviewWindow, and finds stale entries with stale_entries. - support_floor.uk_support_floor_from_payload reads the floor's dates with canonical_date, and UKSupportFloor.assert_in_force uses ReviewWindow. Each function keeps its texts, its order and its policy. The full-graph target kernels and the national kernels now also hash declared_registers, which these modules import (test_uk_target_compile_modules found the new import). No change in results, warnings or refusals. test_uk_review_loaders.py holds the new code to verbatim copies of the old functions (test_support/microcosm_build/uk_review_loaders_reference.py) on the packaged file, on 13 changed copies and on the days around each window edge (34 refusals and 34 warnings among the cases). The existing exclusion, support-floor and full-target tests pass unchanged. The small-cell deferrals (ledger_targets.assert_uk_local_deferrals_in_force) keep their own expiry check: it parses with date.fromisoformat, so it also accepts compact dates, and moving it would change what it accepts. Co-Authored-By: Claude Opus 5.5 --- .../1759-shared-review-core.changed.md | 1 + .../build/uk_runtime/graph_national.py | 4 + .../build/uk_runtime/graph_targets.py | 5 +- .../build/uk_runtime/measure_simulation.py | 27 +- .../build/uk_runtime/support_floor.py | 10 +- .../engine_free/uk/test_uk_review_loaders.py | 206 +++++++++++++++ .../uk_review_loaders_reference.py | 238 ++++++++++++++++++ 7 files changed, 473 insertions(+), 18 deletions(-) create mode 100644 changelog.d/1759-shared-review-core.changed.md create mode 100644 packages/microcosm-build/tests/engine_free/uk/test_uk_review_loaders.py create mode 100644 test_support/microcosm_build/uk_review_loaders_reference.py diff --git a/changelog.d/1759-shared-review-core.changed.md b/changelog.d/1759-shared-review-core.changed.md new file mode 100644 index 0000000000..989773327b --- /dev/null +++ b/changelog.d/1759-shared-review-core.changed.md @@ -0,0 +1 @@ +Signed register entries are checked with one shared review core (microcosm#1759). `microcosm.build.declared_registers` gains `read_strict_json`, `canonical_date`, `ReviewWindow` and `stale_entries`; they return values, and each country's code keeps its texts and decides what a lapse does. The UK calibration measure exclusions and the support floor (`uk_runtime.measure_simulation`, `uk_runtime.support_floor`) read their dates and windows with it. No result, warning or error text changes: `test_uk_review_loaders.py` holds the new code to verbatim copies of the old functions on the packaged file, on changed copies and on the days around each window edge. The UK target and national kernels now also hash `declared_registers`. The small-cell deferrals keep their own expiry check: it also accepts compact dates, so moving it would change what it accepts. diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_national.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_national.py index 5d993a96fa..6652e3a91d 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_national.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_national.py @@ -476,6 +476,7 @@ def implementation_hash(self) -> str: import microcosm.calibrate.matrix as calibrate_matrix import microcosm.calibrate.target_loss_rules as calibrate_target_loss_rules import microcosm.calibrate.target_sets as calibrate_target_sets + from microcosm.build import declared_registers from . import receipt_counts, target_sets, weighted_integrity from .target_compile_modules import uk_target_compile_modules @@ -503,6 +504,9 @@ def implementation_hash(self) -> str: # shared target sets, microcosm#1759). calibrate_target_sets, target_sets, + # The review windows and canonical dates that measure_simulation + # and support_floor check their signed entries with (microcosm#1759). + declared_registers, support_floor_rules, # The constraint matrices and their encoding, as the dense kernels # hash them (microcosm#1492). Not calibrate.solve: neither the diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_targets.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_targets.py index b06188ce8a..891861e7f3 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_targets.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_targets.py @@ -18,7 +18,7 @@ import microcosm.calibrate.artifacts as calibrate_artifacts import microcosm.calibrate.matrix as calibrate_matrix import microcosm.calibrate.target_sets as calibrate_target_sets -from microcosm.build import cross_grain +from microcosm.build import cross_grain, declared_registers from microcosm.calibrate import CalibrationHierarchy, TargetRegistry, TargetSpec from microcosm.calibrate.artifacts import ( PROBLEM_TYPE, @@ -238,6 +238,9 @@ def implementation_hash(self) -> str: # alone must re-key the measures and everything they feed. measure_simulation, support_floor, + # The review windows and canonical dates that measure_simulation + # and support_floor check their signed entries with (microcosm#1759). + declared_registers, # The selection, the constraint matrices and their encoding, as # the transport kernels hash them (microcosm#1492). The selection # and the level rule read uk/target_sets.json through the shared diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/measure_simulation.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/measure_simulation.py index bdbbbb7a4d..b6768d8fc5 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/measure_simulation.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/measure_simulation.py @@ -15,6 +15,11 @@ import numpy as np import pandas as pd +from microcosm.build.declared_registers import ( + ReviewWindow, + canonical_date, + stale_entries, +) from microcosm.build.target_materialization import ( evaluate_named_term, named_term_leaves, @@ -2110,16 +2115,14 @@ def load_uk_calibration_measure_exclusions( "resolved, who approved it, and for how long." ) for field in ("approved_on", "expires_on"): - try: - parsed = date.fromisoformat(record[field]) - except ValueError: - parsed = None - if parsed is None or parsed.isoformat() != record[field]: + if canonical_date(record[field]) is None: raise ValueError( f"UK calibration measure exclusion {name!r} {field} must be " f"canonical ISO (YYYY-MM-DD), got {record[field]!r}." ) - if record["expires_on"] <= record["approved_on"]: + if canonical_date(record["expires_on"]) <= canonical_date( + record["approved_on"] + ): raise ValueError( f"UK calibration measure exclusion {name!r} expires_on must be " "after approved_on." @@ -2147,9 +2150,11 @@ def apply_uk_calibration_measure_exclusions( evaluated_on = exclusion_evaluation_date(now) for entry in exclusions: - approved = date.fromisoformat(entry["approved_on"]) - expires = date.fromisoformat(entry["expires_on"]) - if not approved <= evaluated_on <= expires: + window = ReviewWindow( + date.fromisoformat(entry["approved_on"]), + date.fromisoformat(entry["expires_on"]), + ) + if not window.in_force(evaluated_on): raise ValueError( f"UK calibration measure exclusion {entry['name']!r} is outside " f"its reviewed window ({entry['approved_on']}..{entry['expires_on']}, " @@ -2157,7 +2162,7 @@ def apply_uk_calibration_measure_exclusions( f"gap ({entry['tracking']}) or renew the adjudication with a new " "approval and expiry." ) - if (expires - evaluated_on).days <= 7: + if window.days_left(evaluated_on) <= 7: warnings.warn( f"UK calibration measure exclusion {entry['name']!r} expires " f"{entry['expires_on']} — within one week of the evaluation " @@ -2169,7 +2174,7 @@ def apply_uk_calibration_measure_exclusions( ) declared = {entry["name"]: entry for entry in exclusions} matched = {spec.name for spec in registry.specs if spec.name in declared} - stale = sorted(set(declared) - matched) + stale = stale_entries(declared, matched) if stale: raise ValueError( "UK calibration measure exclusion matched zero registry specs: " diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/support_floor.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/support_floor.py index 4b01f4a2f4..0bf927e4cb 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/support_floor.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/support_floor.py @@ -42,6 +42,7 @@ import numpy as np from scipy import sparse +from microcosm.build.declared_registers import ReviewWindow, canonical_date from microcosm.calibrate import TargetRegistry UK_SUPPORT_FLOOR_KEY = "support_floor" @@ -154,7 +155,7 @@ def record(self, evaluated_on: date) -> dict[str, str]: } def assert_in_force(self, evaluated_on: date) -> None: - if not self.approved_on <= evaluated_on <= self.expires_on: + if not ReviewWindow(self.approved_on, self.expires_on).in_force(evaluated_on): raise ValueError( "UK support floor is outside its reviewed window " f"({self.approved_on.isoformat()}..{self.expires_on.isoformat()}, " @@ -197,11 +198,8 @@ def uk_support_floor_from_payload(block: Mapping[str, Any]) -> UKSupportFloor: raise ValueError(f"UK support floor {field} is empty.") dates = {} for field in ("approved_on", "expires_on"): - try: - parsed = date.fromisoformat(str(block[field])) - except ValueError: - parsed = None - if parsed is None or parsed.isoformat() != block[field]: + parsed = canonical_date(block[field]) + if parsed is None: raise ValueError( f"UK support floor {field} must be canonical ISO (YYYY-MM-DD), " f"got {block[field]!r}." diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_review_loaders.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_review_loaders.py new file mode 100644 index 0000000000..6fe0fdebc8 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_review_loaders.py @@ -0,0 +1,206 @@ +"""The UK signed-entry loaders on the shared review core, against the old code. + +microcosm#1759 step D6 moved the date and window checks of the calibration +measure exclusions (``uk_runtime.measure_simulation``) and of the support +floor (``uk_runtime.support_floor``) onto ``microcosm.build.declared_registers`` +(``canonical_date``, ``ReviewWindow``, ``stale_entries``). Each UK function +keeps its texts and its policy. ``test_support/microcosm_build/ +uk_review_loaders_reference.py`` holds the old functions verbatim. On the +packaged file, on changed copies and on dates around each window edge, the +two give the same value, the same warnings, or the same refusal. +""" + +from __future__ import annotations + +import copy +import json +import warnings +from datetime import date, timedelta +from importlib.resources import files + +import pytest + +from microcosm.build.uk_runtime import measure_simulation, support_floor +from microcosm.calibrate import TargetRegistry, TargetSpec +from test_support.microcosm_build import uk_review_loaders_reference as reference + +_PAYLOAD = json.loads( + files("microcosm.build.uk") + .joinpath("calibration_measure_exclusions.json") + .read_text(encoding="utf-8") +) + + +def _outcome(call): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + try: + value = call() + except Exception as error: # noqa: BLE001 - the refusal is the outcome + value = ("refused", isinstance(error, ValueError), str(error)) + return value, [(w.category.__name__, str(w.message)) for w in caught] + + +def _entry_changes(): + first = 0 + return { + "packaged": lambda payload: None, + "compact approval": lambda p: p["exclusions"][first].update( + approved_on=p["exclusions"][first]["approved_on"].replace("-", "") + ), + "week-date expiry": lambda p: p["exclusions"][first].update( + expires_on="2027-W05-3" + ), + "impossible day": lambda p: p["exclusions"][first].update( + approved_on="2026-02-30" + ), + "expiry before approval": lambda p: p["exclusions"][first].update( + approved_on="2027-01-02", expires_on="2027-01-01" + ), + "expiry on approval": lambda p: p["exclusions"][first].update( + approved_on="2027-01-01", expires_on="2027-01-01" + ), + "padded date": lambda p: p["exclusions"][first].update( + expires_on=" 2027-01-01" + ), + "empty tracking": lambda p: p["exclusions"][first].update(tracking=" "), + "missing reason": lambda p: p["exclusions"][first].pop("reason"), + "unknown field": lambda p: p["exclusions"][first].update(extra="x"), + "duplicate name": lambda p: p["exclusions"].append( + copy.deepcopy(p["exclusions"][first]) + ), + "entry not an object": lambda p: p["exclusions"].append("x"), + "bad schema": lambda p: p.update(schema_version=3), + "unknown top key": lambda p: p.update(extra=1), + } + + +@pytest.mark.parametrize("change", sorted(_entry_changes())) +def test_the_exclusion_loader_matches_the_replaced_code(change, tmp_path) -> None: + payload = copy.deepcopy(_PAYLOAD) + _entry_changes()[change](payload) + path = tmp_path / "exclusions.json" + path.write_text(json.dumps(payload), encoding="utf-8") + old = _outcome(lambda: reference.load_uk_calibration_measure_exclusions(path)) + new = _outcome( + lambda: measure_simulation.load_uk_calibration_measure_exclusions(path) + ) + assert new == old + + +def _registry(names) -> TargetRegistry: + return TargetRegistry( + [ + TargetSpec( + name=name, + entity="household", + measure="household_weight", + value=1.0, + period=2025, + source="test", + family="test_family", + ) + for name in names + ], + country="uk", + ) + + +def _edge_dates(entry) -> list[date]: + approved = date.fromisoformat(entry["approved_on"]) + expires = date.fromisoformat(entry["expires_on"]) + return [ + approved - timedelta(days=1), + approved, + expires - timedelta(days=8), + expires - timedelta(days=7), + expires, + expires + timedelta(days=1), + ] + + +_EXCLUSIONS = reference.load_uk_calibration_measure_exclusions() + + +@pytest.mark.parametrize("index", range(0, len(_EXCLUSIONS), 9)) +def test_the_exclusion_window_matches_the_replaced_code(index) -> None: + entry = _EXCLUSIONS[index] + registry = _registry([entry["name"], "other_target@2025"]) + for on in _edge_dates(entry): + old = _outcome( + lambda on=on: _applied( + reference.apply_uk_calibration_measure_exclusions( + registry, (entry,), now=on + ) + ) + ) + new = _outcome( + lambda on=on: _applied( + measure_simulation.apply_uk_calibration_measure_exclusions( + registry, (entry,), now=on + ) + ) + ) + assert new == old + + +def _applied(result): + registry, receipt = result + return registry.version, [spec.name for spec in registry.specs], receipt + + +def test_every_exclusion_on_one_date_and_a_stale_entry() -> None: + on = date(2026, 11, 26) + names = [entry["name"] for entry in _EXCLUSIONS] + for registry in (_registry(names), _registry(names[1:]), _registry([])): + old = _outcome( + lambda registry=registry: _applied( + reference.apply_uk_calibration_measure_exclusions( + registry, _EXCLUSIONS, now=on + ) + ) + ) + new = _outcome( + lambda registry=registry: _applied( + measure_simulation.apply_uk_calibration_measure_exclusions( + registry, _EXCLUSIONS, now=on + ) + ) + ) + assert new == old + + +def _floor_changes(): + return { + "packaged": lambda block: None, + "compact approval": lambda b: b.update( + approved_on=b["approved_on"].replace("-", "") + ), + "impossible expiry": lambda b: b.update(expires_on="2027-02-30"), + "expiry on approval": lambda b: b.update(expires_on=b["approved_on"]), + "date as a number": lambda b: b.update(approved_on=20261126), + "padded date": lambda b: b.update(expires_on=b["expires_on"] + " "), + } + + +@pytest.mark.parametrize("change", sorted(_floor_changes())) +def test_the_support_floor_reader_matches_the_replaced_code(change) -> None: + block = copy.deepcopy(_PAYLOAD["support_floor"]) + _floor_changes()[change](block) + old = _outcome(lambda: reference.uk_support_floor_from_payload(block)) + new = _outcome(lambda: support_floor.uk_support_floor_from_payload(block)) + assert new == old + + +def test_the_support_floor_window_matches_the_replaced_code() -> None: + floor = support_floor.uk_support_floor_from_payload(_PAYLOAD["support_floor"]) + edges = _edge_dates( + { + "approved_on": floor.approved_on.isoformat(), + "expires_on": floor.expires_on.isoformat(), + } + ) + for on in edges: + old = _outcome(lambda on=on: reference.assert_in_force(floor, on)) + new = _outcome(lambda on=on: floor.assert_in_force(on)) + assert new == old diff --git a/test_support/microcosm_build/uk_review_loaders_reference.py b/test_support/microcosm_build/uk_review_loaders_reference.py new file mode 100644 index 0000000000..e1f6cf6019 --- /dev/null +++ b/test_support/microcosm_build/uk_review_loaders_reference.py @@ -0,0 +1,238 @@ +# Verbatim copies, at 2ead043a4 (before microcosm#1759 step D6), of the UK +# loaders that now check their signed entries with +# microcosm.build.declared_registers: the calibration measure exclusions' +# loader and applier (uk_runtime.measure_simulation), and the support floor's +# payload reader and window check (uk_runtime.support_floor; +# UKSupportFloor.assert_in_force as a function). Tests hold the new code to +# them; do not edit. +# ruff: noqa + +from __future__ import annotations + +import json +import warnings +from collections.abc import Mapping +from datetime import date +from importlib import resources as importlib_resources +from pathlib import Path +from typing import Any + +from microcosm.build.uk_runtime.measure_simulation import ( + _UK_MEASURE_EXCLUSION_FIELDS, +) +from microcosm.build.uk_runtime.support_floor import ( + _FIELDS, + _TEXT_FIELDS, + UK_SUPPORT_FLOOR_METRIC, + UK_SUPPORT_FLOOR_VALUE, + UKSupportFloor, + _scopes_from_payload, +) +from microcosm.build.uk_runtime.weighted_integrity import exclusion_evaluation_date +from microcosm.calibrate import TargetRegistry + + +def load_uk_calibration_measure_exclusions( + path: Path | None = None, +) -> tuple[dict[str, str], ...]: + """Load and validate the reviewed UK calibration-measure exclusions.""" + + if path is None: + text = ( + importlib_resources.files("microcosm.build.uk") + .joinpath("calibration_measure_exclusions.json") + .read_text(encoding="utf-8") + ) + else: + text = Path(path).read_text(encoding="utf-8") + payload = json.loads(text) + # Schema 4 carries the signed zero-support floor (microcosm#1095 U3) in + # scopes of one unit each, which + # ``support_floor.load_uk_support_floor_declaration`` reads; schema 3's + # single-scope floor is retired with it. + schema_version = payload.get("schema_version") + allowed_top = {"schema_version", "exclusions"} + if schema_version == 4: + allowed_top.add("support_floor") + unknown = sorted(set(payload) - allowed_top) + if unknown: + raise ValueError(f"unknown top-level exclusion key(s): {unknown}") + if schema_version not in (2, 4): + raise ValueError( + "UK calibration measure exclusions schema_version must be 2 or 4." + ) + exclusions = payload.get("exclusions") + if not isinstance(exclusions, list): + raise ValueError("UK calibration measure exclusions must contain a list.") + seen: set[str] = set() + loaded: list[dict[str, str]] = [] + for entry in exclusions: + if not isinstance(entry, dict): + raise ValueError( + "UK calibration measure exclusion entries must be objects." + ) + unknown_fields = sorted(set(entry) - set(_UK_MEASURE_EXCLUSION_FIELDS)) + if unknown_fields: + raise ValueError( + "unknown UK calibration measure exclusion field(s) " + f"{unknown_fields} on {entry.get('name')!r}." + ) + record = { + field: str(entry.get(field, "")) for field in _UK_MEASURE_EXCLUSION_FIELDS + } + name = record["name"] + if name in seen: + raise ValueError(f"duplicate UK calibration measure exclusion {name!r}.") + for field in _UK_MEASURE_EXCLUSION_FIELDS: + if not record[field].strip(): + raise ValueError( + f"UK calibration measure exclusion {name!r} has empty {field}; " + "a narrowed target surface names why, where it is being " + "resolved, who approved it, and for how long." + ) + for field in ("approved_on", "expires_on"): + try: + parsed = date.fromisoformat(record[field]) + except ValueError: + parsed = None + if parsed is None or parsed.isoformat() != record[field]: + raise ValueError( + f"UK calibration measure exclusion {name!r} {field} must be " + f"canonical ISO (YYYY-MM-DD), got {record[field]!r}." + ) + if record["expires_on"] <= record["approved_on"]: + raise ValueError( + f"UK calibration measure exclusion {name!r} expires_on must be " + "after approved_on." + ) + seen.add(name) + loaded.append(record) + return tuple(loaded) + + +def apply_uk_calibration_measure_exclusions( + registry: TargetRegistry, + exclusions: tuple[dict[str, str], ...], + *, + now: date | None = None, +) -> tuple[TargetRegistry, dict[str, dict[str, str]]]: + """Remove reviewed excluded references from a UK target registry. + + The receipt carries every field the register declares, tracking included: + an exclusion narrows the calibrated target surface, so the run evidence + must say where each narrowing is being resolved, not only why. The window + is enforced at apply time — outside ``approved_on``..``expires_on`` the + run fails with a correct-or-renew message rather than the narrowing + lapsing silently or living forever. + """ + + evaluated_on = exclusion_evaluation_date(now) + for entry in exclusions: + approved = date.fromisoformat(entry["approved_on"]) + expires = date.fromisoformat(entry["expires_on"]) + if not approved <= evaluated_on <= expires: + raise ValueError( + f"UK calibration measure exclusion {entry['name']!r} is outside " + f"its reviewed window ({entry['approved_on']}..{entry['expires_on']}, " + f"evaluated {evaluated_on.isoformat()}): correct the underlying " + f"gap ({entry['tracking']}) or renew the adjudication with a new " + "approval and expiry." + ) + if (expires - evaluated_on).days <= 7: + warnings.warn( + f"UK calibration measure exclusion {entry['name']!r} expires " + f"{entry['expires_on']} — within one week of the evaluation " + f"date {evaluated_on.isoformat()}; correct the underlying gap " + f"({entry['tracking']}) or renew the adjudication before the " + "run fails on expiry.", + UserWarning, + stacklevel=2, + ) + declared = {entry["name"]: entry for entry in exclusions} + matched = {spec.name for spec in registry.specs if spec.name in declared} + stale = sorted(set(declared) - matched) + if stale: + raise ValueError( + "UK calibration measure exclusion matched zero registry specs: " + + ", ".join(stale) + ) + kept = [spec for spec in registry.specs if spec.name not in declared] + receipt = { + name: { + field: declared[name][field] + for field in _UK_MEASURE_EXCLUSION_FIELDS + if field != "name" + } + for name in sorted(matched) + } + for record in receipt.values(): + record["evaluated_on"] = evaluated_on.isoformat() + return TargetRegistry(kept, country=registry.country), receipt + + +def uk_support_floor_from_payload(block: Mapping[str, Any]) -> UKSupportFloor: + """Validate the ``support_floor`` block closed-world.""" + + if not isinstance(block, Mapping): + raise ValueError("UK support floor must be an object.") + unknown = sorted(set(block) - set(_FIELDS)) + missing = sorted(set(_FIELDS) - set(block)) + if unknown or missing: + raise ValueError( + f"UK support floor fields are closed-world: unknown {unknown}, " + f"missing {missing}." + ) + if block["metric"] != UK_SUPPORT_FLOOR_METRIC: + raise ValueError( + f"UK support floor metric must be {UK_SUPPORT_FLOOR_METRIC!r}, got " + f"{block['metric']!r}." + ) + floor = block["floor"] + if ( + not isinstance(floor, int) + or isinstance(floor, bool) + or floor != UK_SUPPORT_FLOOR_VALUE + ): + raise ValueError( + f"UK support floor must be {UK_SUPPORT_FLOOR_VALUE}: a row that any source " + "household carries stays bound however few they are (María's rule of " + "2026-10-21)." + ) + scopes = _scopes_from_payload(block["scopes"]) + for field in _TEXT_FIELDS: + if not isinstance(block[field], str) or not block[field].strip(): + raise ValueError(f"UK support floor {field} is empty.") + dates = {} + for field in ("approved_on", "expires_on"): + try: + parsed = date.fromisoformat(str(block[field])) + except ValueError: + parsed = None + if parsed is None or parsed.isoformat() != block[field]: + raise ValueError( + f"UK support floor {field} must be canonical ISO (YYYY-MM-DD), " + f"got {block[field]!r}." + ) + dates[field] = parsed + if dates["expires_on"] <= dates["approved_on"]: + raise ValueError("UK support floor expires_on must be after approved_on.") + return UKSupportFloor( + scopes=scopes, + floor=floor, + reason=block["reason"], + tracking=block["tracking"], + approved_by=block["approved_by"], + adjudication=block["adjudication"], + approved_on=dates["approved_on"], + expires_on=dates["expires_on"], + ) + + +def assert_in_force(self, evaluated_on: date) -> None: + if not self.approved_on <= evaluated_on <= self.expires_on: + raise ValueError( + "UK support floor is outside its reviewed window " + f"({self.approved_on.isoformat()}..{self.expires_on.isoformat()}, " + f"evaluated {evaluated_on.isoformat()}): renew the signature " + f"({self.tracking})." + ) From 34c8d436a6e8c42ca8453def04e6e1aedb15405f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:11:39 +0000 Subject: [PATCH 17/30] Read the UK reviewed exclusions with the shared review core The UK reviewed-exclusion registers (target fit, local target fit and area support) now use the shared review core (microcosm#1759, step D7): - weighted_integrity._read_register_payload reads with read_strict_json, which keeps its texts for duplicate keys, non-finite numbers and malformed JSON. The "must be a JSON object" check stays with the UK. - UKReviewedExclusion reads approved_on and expires_on with canonical_date, with the same message. Its new window() gives the ReviewWindow, and expired and premature read it. - The national gate kernel and uk.full gate kernels, which hash weighted_integrity, now also hash declared_registers. Every public name stays where battery_bindings and the tools import it. battery_bindings, gate_battery, stage_health and graph_evidence are not changed. No change in what these registers read, accept or refuse. test_uk_reviewed_exclusions_core.py holds the new code to verbatim copies of the old reader, date checks and window methods (test_support/microcosm_build/uk_reviewed_exclusion_reference.py) on the three packaged files, on ten changed texts, on ten date pairs and on the days around every packaged entry's window. The existing weighted-integrity, terminal-gate, battery-binding, graph and CLI tests pass unchanged. Co-Authored-By: Claude Opus 5.5 --- .../1759-shared-review-core.changed.md | 2 +- .../build/uk_runtime/graph_national.py | 5 +- .../build/uk_runtime/graph_terminal.py | 5 +- .../build/uk_runtime/weighted_integrity.py | 58 +++----- .../uk/test_uk_reviewed_exclusions_core.py | 138 ++++++++++++++++++ .../uk_reviewed_exclusion_reference.py | 91 ++++++++++++ 6 files changed, 260 insertions(+), 39 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/uk/test_uk_reviewed_exclusions_core.py create mode 100644 test_support/microcosm_build/uk_reviewed_exclusion_reference.py diff --git a/changelog.d/1759-shared-review-core.changed.md b/changelog.d/1759-shared-review-core.changed.md index 989773327b..ee0a4fe5be 100644 --- a/changelog.d/1759-shared-review-core.changed.md +++ b/changelog.d/1759-shared-review-core.changed.md @@ -1 +1 @@ -Signed register entries are checked with one shared review core (microcosm#1759). `microcosm.build.declared_registers` gains `read_strict_json`, `canonical_date`, `ReviewWindow` and `stale_entries`; they return values, and each country's code keeps its texts and decides what a lapse does. The UK calibration measure exclusions and the support floor (`uk_runtime.measure_simulation`, `uk_runtime.support_floor`) read their dates and windows with it. No result, warning or error text changes: `test_uk_review_loaders.py` holds the new code to verbatim copies of the old functions on the packaged file, on changed copies and on the days around each window edge. The UK target and national kernels now also hash `declared_registers`. The small-cell deferrals keep their own expiry check: it also accepts compact dates, so moving it would change what it accepts. +Signed register entries are checked with one shared review core (microcosm#1759). `microcosm.build.declared_registers` gains `read_strict_json`, `canonical_date`, `ReviewWindow` and `stale_entries`; they return values, and each country's code keeps its texts and decides what a lapse does. The UK calibration measure exclusions and the support floor (`uk_runtime.measure_simulation`, `uk_runtime.support_floor`) read their dates and windows with it. No result, warning or error text changes: `test_uk_review_loaders.py` holds the new code to verbatim copies of the old functions on the packaged file, on changed copies and on the days around each window edge. The UK target and national kernels now also hash `declared_registers`. The small-cell deferrals keep their own expiry check: it also accepts compact dates, so moving it would change what it accepts. The UK reviewed-exclusion registers (target fit, local target fit and area support, in `uk_runtime.weighted_integrity`) read their files with `read_strict_json` and their dates and windows with `canonical_date` and `ReviewWindow` (`UKReviewedExclusion.window()` is new); `test_uk_reviewed_exclusions_core.py` holds them to verbatim copies of the old reader, date checks and window methods. The UK gate kernels that read these registers now also hash `declared_registers`. diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_national.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_national.py index 6652e3a91d..e0149bab61 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_national.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_national.py @@ -1028,7 +1028,7 @@ class UKNationalGateKernel(_NationalKernel): ) def implementation_hash(self) -> str: - from .. import gate_battery + from .. import declared_registers, gate_battery from . import battery_bindings, diagnostics, receipt_counts, weighted_integrity return hashlib.sha256( @@ -1041,6 +1041,9 @@ def implementation_hash(self) -> str: battery_bindings, calibration_run, weighted_integrity, + # The reviewed exclusions' strict reader and windows + # (microcosm#1759). + declared_registers, # The input-mass gate's source-household counts. receipt_counts, diagnostics, diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_terminal.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_terminal.py index c8ca4f0c53..a7caeacd10 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_terminal.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_terminal.py @@ -823,7 +823,7 @@ def implementation_hash(self) -> str: # The gate evaluators (``gates``) and the register loaders # (``terminal_gates``) decide the report as much as the bindings do, # so an edit to either re-keys the gate nodes (microcosm#1301). - from .. import gate_battery, gates + from .. import declared_registers, gate_battery, gates from . import ( battery_bindings, diagnostics, @@ -845,6 +845,9 @@ def implementation_hash(self) -> str: local_rowwise, terminal_gates, weighted_integrity, + # The reviewed exclusions' strict reader and windows + # (microcosm#1759). + declared_registers, diagnostics, ), "country_resources": self._country_resources(), diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/weighted_integrity.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/weighted_integrity.py index f44a5d8ae6..62f4fb994c 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/weighted_integrity.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/weighted_integrity.py @@ -129,6 +129,11 @@ import numpy as np import pandas as pd +from microcosm.build.declared_registers import ( + ReviewWindow, + canonical_date, + read_strict_json, +) from microcosm.build.gates import ( GateResult, input_mass_parity_gate, @@ -385,18 +390,11 @@ def __post_init__(self) -> None: parsed: dict[str, date] = {} for name in ("approved_on", "expires_on"): value = getattr(self, name) - try: - parsed[name] = date.fromisoformat(value) - except (TypeError, ValueError) as exc: - raise ValueError( - f"UK reviewed exclusion {name} must be an ISO date " - f"(YYYY-MM-DD), got {value!r}." - ) from exc - # fromisoformat also accepts compact (20270210) and week-date - # forms; the receipt pins the canonical rendering because the - # raw string is sealed into the policy digest — two spellings - # of one date must not produce two digests. - if parsed[name].isoformat() != value: + # Only the canonical spelling counts (canonical_date): the receipt + # pins it because the raw string is sealed into the policy digest + # — two spellings of one date must not produce two digests. + parsed[name] = canonical_date(value) + if parsed[name] is None: raise ValueError( f"UK reviewed exclusion {name} must be an ISO date " f"(YYYY-MM-DD), got {value!r}." @@ -408,15 +406,22 @@ def __post_init__(self) -> None: f"expires_on={self.expires_on!r}." ) + def window(self) -> ReviewWindow: + """The entry's review window (both days in force).""" + + return ReviewWindow( + date.fromisoformat(self.approved_on), date.fromisoformat(self.expires_on) + ) + def expired(self, now: date) -> bool: """Honored through ``expires_on``; expired strictly after it.""" - return now > date.fromisoformat(self.expires_on) + return self.window().expired(now) def premature(self, now: date) -> bool: """In force from ``approved_on``; premature strictly before it.""" - return now < date.fromisoformat(self.approved_on) + return self.window().premature(now) def applies_on(self, line: str | None) -> bool: """Whether the entry is in scope on a release line. @@ -652,28 +657,9 @@ def _read_register_payload( raw = Path(source).read_text(encoding="utf-8") label = str(source) - def strict_object(pairs: list[tuple[str, object]]) -> dict[str, object]: - result: dict[str, object] = {} - duplicates: set[str] = set() - for name, value in pairs: - if name in result: - duplicates.add(name) - result[name] = value - if duplicates: - raise ValueError(f"{label}: duplicate JSON key(s): {sorted(duplicates)}.") - return result - - def reject_nonfinite_json(value: str) -> object: - raise ValueError(f"{label}: non-finite JSON value {value!r} is invalid.") - - try: - payload = json.loads( - raw, - object_pairs_hook=strict_object, - parse_constant=reject_nonfinite_json, - ) - except json.JSONDecodeError as exc: - raise ValueError(f"{label}: malformed JSON: {exc.msg}.") from exc + # Duplicate keys, non-finite numbers and malformed text are refused + # (microcosm#1759: the shared strict reader). + payload = read_strict_json(raw, label=label) if not isinstance(payload, Mapping): raise ValueError(f"{label}: exclusion register must be a JSON object.") return payload, label diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_reviewed_exclusions_core.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_reviewed_exclusions_core.py new file mode 100644 index 0000000000..fdb52ad5db --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_reviewed_exclusions_core.py @@ -0,0 +1,138 @@ +"""The UK reviewed-exclusion registers on the shared review core. + +microcosm#1759 step D7 moved three pieces of ``uk_runtime.weighted_integrity`` +onto ``microcosm.build.declared_registers``: the strict JSON reader of the +reviewed-exclusion files (``read_strict_json``), the date checks of +``UKReviewedExclusion`` (``canonical_date``) and its window +(``ReviewWindow``). ``test_support/microcosm_build/ +uk_reviewed_exclusion_reference.py`` holds the old code verbatim. On the +packaged files, on changed texts and on the days around every packaged +entry's window, the two give the same value or the same refusal text. +""" + +from __future__ import annotations + +from datetime import date, timedelta +from types import SimpleNamespace + +import pytest + +from microcosm.build.uk_runtime import weighted_integrity +from test_support.microcosm_build import uk_reviewed_exclusion_reference as reference + +#: The reviewed-exclusion files this reader serves. +RESOURCES = ( + "target_fit_reviewed_exclusions.json", + "local_target_fit_reviewed_exclusions.json", + "local_area_support_exclusions.json", +) + + +def _outcome(call): + try: + return ("value", call()) + except ValueError as error: + return ("refused", str(error)) + + +@pytest.mark.parametrize("resource", RESOURCES) +def test_the_packaged_files_read_the_same(resource) -> None: + old = _outcome(lambda: reference._read_register_payload(None, resource=resource)) + new = _outcome( + lambda: weighted_integrity._read_register_payload(None, resource=resource) + ) + assert new == old + assert new[0] == "value" + + +@pytest.mark.parametrize( + "text", + [ + '{"a": 1, "a": 2}', + '{"a": {"b": 1, "b": 1, "c": 2, "c": 3}}', + '{"a": NaN}', + '{"a": [Infinity]}', + '{"a": -Infinity}', + '{"a": }', + "", + "[1, 2]", + '"text"', + '{"exclusions": {}}', + ], +) +def test_changed_texts_read_the_same(text, tmp_path) -> None: + path = tmp_path / "register.json" + path.write_text(text, encoding="utf-8") + old = _outcome(lambda: reference._read_register_payload(path, resource="x")) + new = _outcome( + lambda: weighted_integrity._read_register_payload(path, resource="x") + ) + assert new == old + + +@pytest.mark.parametrize( + ("approved_on", "expires_on"), + [ + ("2026-10-01", "2027-03-31"), + ("20261001", "2027-03-31"), + ("2026-10-01", "2027-W13-3"), + ("2026-02-30", "2027-03-31"), + ("2026-10-01", " 2027-03-31"), + ("2026-10-01", "2026-10-01"), + ("2027-03-31", "2026-10-01"), + (None, "2027-03-31"), + ("2026-10-01", 20270331), + ("", "2027-03-31"), + ], +) +def test_the_date_checks_refuse_the_same(approved_on, expires_on) -> None: + def new() -> None: + weighted_integrity.UKReviewedExclusion( + reason="r", + approved_by="a", + adjudication="d", + approved_on=approved_on, + expires_on=expires_on, + ) + + old = _outcome( + lambda: reference.check_dates( + SimpleNamespace(approved_on=approved_on, expires_on=expires_on) + ) + ) + outcome = _outcome(new) + assert outcome[0] == old[0] + if old[0] == "refused": + assert outcome[1] == old[1] + + +def _packaged_entries(): + for resource in RESOURCES: + payload, _label = reference._read_register_payload(None, resource=resource) + for block in ("exclusions", "bound_despite_support_floor"): + for name, entry in (payload.get(block) or {}).items(): + yield f"{resource}:{name}", entry + + +def test_every_packaged_window_reads_the_same() -> None: + checked = 0 + for _name, entry in _packaged_entries(): + record = weighted_integrity.UKReviewedExclusion( + reason=entry["reason"], + approved_by=entry["approved_by"], + adjudication=entry["adjudication"], + approved_on=entry["approved_on"], + expires_on=entry["expires_on"], + ) + approved = date.fromisoformat(entry["approved_on"]) + expires = date.fromisoformat(entry["expires_on"]) + for on in ( + approved - timedelta(days=1), + approved, + expires, + expires + timedelta(days=1), + ): + assert record.expired(on) == reference.expired(record, on) + assert record.premature(on) == reference.premature(record, on) + checked += 1 + assert checked > 0 diff --git a/test_support/microcosm_build/uk_reviewed_exclusion_reference.py b/test_support/microcosm_build/uk_reviewed_exclusion_reference.py new file mode 100644 index 0000000000..7eb994d13f --- /dev/null +++ b/test_support/microcosm_build/uk_reviewed_exclusion_reference.py @@ -0,0 +1,91 @@ +# Verbatim copies, at c866b8951 (before microcosm#1759 step D7), of the UK +# reviewed-exclusion code that now uses microcosm.build.declared_registers: +# uk_runtime.weighted_integrity._read_register_payload, the date checks of +# UKReviewedExclusion.__post_init__ (as check_dates), and its expired and +# premature methods (as functions). Tests hold the new code to them; do not +# edit. +# ruff: noqa + +from __future__ import annotations + +import json +from collections.abc import Mapping +from datetime import date +from importlib.resources import files +from pathlib import Path + + +def _read_register_payload( + source: str | Path | None, *, resource: str +) -> tuple[Mapping[str, object], str]: + if source is None: + raw = files("microcosm.build.uk").joinpath(resource).read_text("utf-8") + label = resource + else: + raw = Path(source).read_text(encoding="utf-8") + label = str(source) + + def strict_object(pairs: list[tuple[str, object]]) -> dict[str, object]: + result: dict[str, object] = {} + duplicates: set[str] = set() + for name, value in pairs: + if name in result: + duplicates.add(name) + result[name] = value + if duplicates: + raise ValueError(f"{label}: duplicate JSON key(s): {sorted(duplicates)}.") + return result + + def reject_nonfinite_json(value: str) -> object: + raise ValueError(f"{label}: non-finite JSON value {value!r} is invalid.") + + try: + payload = json.loads( + raw, + object_pairs_hook=strict_object, + parse_constant=reject_nonfinite_json, + ) + except json.JSONDecodeError as exc: + raise ValueError(f"{label}: malformed JSON: {exc.msg}.") from exc + if not isinstance(payload, Mapping): + raise ValueError(f"{label}: exclusion register must be a JSON object.") + return payload, label + + +def check_dates(self) -> None: + parsed: dict[str, date] = {} + for name in ("approved_on", "expires_on"): + value = getattr(self, name) + try: + parsed[name] = date.fromisoformat(value) + except (TypeError, ValueError) as exc: + raise ValueError( + f"UK reviewed exclusion {name} must be an ISO date " + f"(YYYY-MM-DD), got {value!r}." + ) from exc + # fromisoformat also accepts compact (20270210) and week-date + # forms; the receipt pins the canonical rendering because the + # raw string is sealed into the policy digest — two spellings + # of one date must not produce two digests. + if parsed[name].isoformat() != value: + raise ValueError( + f"UK reviewed exclusion {name} must be an ISO date " + f"(YYYY-MM-DD), got {value!r}." + ) + if parsed["expires_on"] <= parsed["approved_on"]: + raise ValueError( + "UK reviewed exclusion expires_on must be after approved_on; " + f"got approved_on={self.approved_on!r}, " + f"expires_on={self.expires_on!r}." + ) + + +def expired(self, now: date) -> bool: + """Honored through ``expires_on``; expired strictly after it.""" + + return now > date.fromisoformat(self.expires_on) + +def premature(self, now: date) -> bool: + """In force from ``approved_on``; premature strictly before it.""" + + return now < date.fromisoformat(self.approved_on) From ca3a67e9b425ed58c7fe4dfb3d893caa9539bf14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:34:22 +0000 Subject: [PATCH 18/30] Pin the UK target nodes' artifacts on the pinned feed The digests were measured at 38dbd0187, before the UK selection moved to the shared target sets: the full surface, the selection for 19 parameter sets (13 selections, 6 refusals) and the national registry, on the pinned Chronicle feed and the 2021 output-area ladder, at calibration year 2025 and review date 2026-11-26. The tests run when MICROCOSM_UK_CHRONICLE_FACTS and MICROCOSM_UK_OA_LADDER are set. The selection tests can read a saved surface (MICROCOSM_UK_TARGET_SURFACE) that has the pinned digest. Part of microcosm#1759. Co-Authored-By: Claude Opus 5.5 --- .../uk/test_uk_target_surface_pins.py | 250 ++++++++++++++++++ 1 file changed, 250 insertions(+) create mode 100644 packages/microcosm-build/tests/engine_free/uk/test_uk_target_surface_pins.py diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_target_surface_pins.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_target_surface_pins.py new file mode 100644 index 0000000000..95bdd5d596 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_target_surface_pins.py @@ -0,0 +1,250 @@ +"""The UK target nodes' artifacts on the pinned Chronicle feed (microcosm#1759). + +microcosm#1759 moves the UK target selection, the calibration lines and the +review loaders onto shared code, with no output change. These pins hold the +bytes that the UK target nodes wrote before the move, at ``38dbd0187`` (the +merge of main ``4b78a9b23``), on the pinned feed (``uk/chronicle_feed.json``) +and the 2021 output-area ladder, at calibration year 2025 and review date +2026-11-26: + +- ``uk.full.target_compilation@1``: the full (local-line) surface; +- ``uk.full.target_selection@1``: the selection for each parameter set below, + or the refusal (type and message); +- ``uk.full.national_targets@1``: the national line's registry artifact. + +The tests run only when ``MICROCOSM_UK_CHRONICLE_FACTS`` names the pinned +feed's artifact folder and ``MICROCOSM_UK_OA_LADDER`` names the ladder. The +selection tests can read a saved surface instead (``MICROCOSM_UK_TARGET_SURFACE``), +which must have the pinned digest. The compile reads published Chronicle +facts and the census ladder, not survey microdata, and the pins are digests. +""" + +from __future__ import annotations + +import hashlib +import json +import os +from pathlib import Path +from types import SimpleNamespace + +import pytest + +CALIBRATION_YEAR = 2025 +REVIEW_DATE = "2026-11-26" + +#: (sha256, bytes) of each node's artifact at 38dbd0187. +PINNED_SURFACE = ( + "c676841b689c5c61e60e756b13fdeb1e4b19b3f8d2177c012fa7416dfd6175dd", + 379_861_377, +) +PINNED_NATIONAL_REGISTRY = ( + "e30a9753f74401fc10843cf2dfe14503dfc9e18e771d087a9f53d86531413c27", + 19_791_099, +) + +#: The selection node's parameters: what the full build CLI and graph pass, +#: and refusals. +SELECTIONS: dict[str, dict] = { + "all": {}, + "all_explicit": { + "geography_levels": ["brma", "constituency", "country", "la", "region"] + }, + "country": {"geography_levels": ["country"]}, + "region": {"geography_levels": ["region"]}, + "constituency": {"geography_levels": ["constituency"]}, + "la": {"geography_levels": ["la"]}, + "brma": {"geography_levels": ["brma"]}, + "national_levels": {"geography_levels": ["region", "country"]}, + "local_levels": {"geography_levels": ["la", "constituency"]}, + "households_only": {"target_families": ["census_households/constituency"]}, + "households_only_levels": { + "target_families": ["census_households/constituency"], + "geography_levels": ["constituency"], + }, + "no_brma": {"brma_rows": False}, + "no_brma_levels": { + "brma_rows": False, + "geography_levels": ["country", "region", "constituency", "la"], + }, + "refuse_unknown_level": {"geography_levels": ["nowhere"]}, + "refuse_empty_levels": {"geography_levels": []}, + "refuse_repeated_level": {"geography_levels": ["la", "la"]}, + "refuse_blank_level": {"geography_levels": [" la"]}, + "refuse_unknown_family": {"target_families": ["no_such_family"]}, + "refuse_brma_without_rows": {"brma_rows": False, "geography_levels": ["brma"]}, +} + +#: label -> {"sha256", "targets"} or {"error", "message"}, at 38dbd0187. +PINNED_SELECTIONS: dict[str, dict] = { + "all": { + "sha256": "4e834dcb26b7c7603ffd85c9b8dbb16ffa919d365924b43c267299d3f16b41e4", + "targets": 28726, + }, + "all_explicit": { + "sha256": "8c80fae2d8f1d70cf60ea1a4953607d39784290e278d5de3ee474ee61f2f0e61", + "targets": 28726, + }, + "country": { + "sha256": "7fcd7419be2d2d8e3e3fa8cc98205588ea9c73e73d98d9871966350092feff3c", + "targets": 938, + }, + "region": { + "sha256": "a364302e885b33fd39a30dcc0a329ab47b08b58481ce4e7beba15fde46be680e", + "targets": 631, + }, + "constituency": { + "sha256": "2b44243a3b998ad37b592a03caae27d78e39c977d0aa2e297bd6f7f0a0693f85", + "targets": 15207, + }, + "la": { + "sha256": "699eac8dac04bde66754a1ccabb59f759ce4fe9404a5e0f864837851659175d5", + "targets": 11932, + }, + "brma": { + "sha256": "f3ee6b5fdb0b21275e7ffa3bb865014a0de5a8595a199adad4db3aaf7a49859d", + "targets": 18, + }, + "national_levels": { + "sha256": "81f8eaf8a1585dca7c4e393bdc77ae1b76842a4e94a0e3c40aa9a987c3a0457a", + "targets": 1569, + }, + "local_levels": { + "sha256": "0c8c62791004b27512a1369c0e496d78c48e48c4299bd6ead474f1d9092cf6df", + "targets": 27139, + }, + "households_only": { + "sha256": "f38c78cf592b25e10df8989cf1d4cde236b5ba0860d761d116d97dc3f0508f69", + "targets": 650, + }, + "households_only_levels": { + "sha256": "cc5da76d3f8c76ae3107cd531a19f6f6cd993b93f31ff1a791535e9ea85e02b3", + "targets": 650, + }, + "no_brma": { + "sha256": "3782a85a3d700cf87ea4f51ea925e78a49d025883dfb9e9261f90f28008034b3", + "targets": 28708, + }, + "no_brma_levels": { + "sha256": "3066f8d9e9e08898eae3bcf548831c6aa4dabdc6c60eeabff6e5b425dbc42d4b", + "targets": 28708, + }, + "refuse_unknown_level": { + "error": "ValueError", + "message": "Target selector contains unknown geography levels ['nowhere'].", + }, + "refuse_empty_levels": { + "error": "ValueError", + "message": "geography_levels must contain nonempty literal names.", + }, + "refuse_repeated_level": { + "error": "ValueError", + "message": "geography_levels must not repeat levels.", + }, + "refuse_blank_level": { + "error": "ValueError", + "message": "geography_levels must contain nonempty literal names.", + }, + "refuse_unknown_family": { + "error": "ValueError", + "message": "Target selection requires a nonempty selected problem.", + }, + "refuse_brma_without_rows": { + "error": "ValueError", + "message": "Target selector contains unknown geography levels ['brma'].", + }, +} + + +def _sha256(payload: bytes) -> str: + return hashlib.sha256(payload).hexdigest() + + +def _context(*, artifacts=None, params=None, sources=None) -> SimpleNamespace: + return SimpleNamespace( + artifacts=artifacts or {}, params=params or {}, sources=sources or {} + ) + + +def _feed_and_ladder() -> tuple[str, str]: + feed = os.environ.get("MICROCOSM_UK_CHRONICLE_FACTS", "") + ladder = os.environ.get("MICROCOSM_UK_OA_LADDER", "") + if not (feed and Path(feed).exists() and ladder and Path(ladder).is_file()): + pytest.skip( + "set MICROCOSM_UK_CHRONICLE_FACTS (the pinned UK feed's artifact " + "folder) and MICROCOSM_UK_OA_LADDER (uk_oa_ladder_2021.npz)" + ) + return feed, ladder + + +@pytest.fixture(scope="module") +def compiled_surface() -> bytes: + from microcosm.build.uk_runtime.graph_targets import ( + UKFullTargetCompilationKernel, + ) + + feed, ladder = _feed_and_ladder() + result = UKFullTargetCompilationKernel().run( + _context( + params={"calibration_year": CALIBRATION_YEAR, "review_date": REVIEW_DATE}, + sources={"uk_ledger_facts": feed, "uk_ladder": ladder}, + ) + ) + return result.artifacts["surface"] + + +@pytest.fixture(scope="module") +def surface(request) -> bytes: + saved = os.environ.get("MICROCOSM_UK_TARGET_SURFACE", "") + if saved and Path(saved).is_file(): + payload = Path(saved).read_bytes() + assert (_sha256(payload), len(payload)) == PINNED_SURFACE + return payload + return request.getfixturevalue("compiled_surface") + + +def test_the_full_surface_is_unchanged(compiled_surface: bytes) -> None: + assert (_sha256(compiled_surface), len(compiled_surface)) == PINNED_SURFACE + + +@pytest.mark.parametrize("label", sorted(SELECTIONS)) +def test_each_selection_is_unchanged(surface: bytes, label: str) -> None: + from microcosm.build.uk_runtime.graph_targets import UKFullTargetSelectionKernel + + try: + result = UKFullTargetSelectionKernel().run( + _context( + artifacts={"surface": SimpleNamespace(payload=surface)}, + params=SELECTIONS[label], + ) + ) + except Exception as error: # noqa: BLE001 - the refusal is the pin + outcome = {"error": type(error).__name__, "message": str(error)} + else: + payload = result.artifacts["selection"] + outcome = { + "sha256": _sha256(payload), + "targets": len(json.loads(payload)["registry"]["specs"]), + } + assert outcome == PINNED_SELECTIONS[label] + + +def test_the_national_registry_is_unchanged() -> None: + from microcosm.build.uk_runtime.graph_national import UKNationalTargetKernel + + feed, _ladder = _feed_and_ladder() + result = UKNationalTargetKernel().run( + _context( + params={ + "calibration_year": CALIBRATION_YEAR, + "review_date": REVIEW_DATE, + "allow_unpinned_feed": False, + }, + sources={"uk_ledger_facts": feed}, + ) + ) + payload = result.artifacts["registry"] + assert (_sha256(payload), len(payload)) == PINNED_NATIONAL_REGISTRY + + +def test_every_selection_has_a_pin() -> None: + assert set(PINNED_SELECTIONS) == set(SELECTIONS) From 9130ebe15e2e8862b43d10392d9116cfd0c266b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:34:22 +0000 Subject: [PATCH 19/30] Describe the UK target sets docs/uk-target-sets.md describes the UK declaration (the level rule, the full build's selection by level and the calibration lines), the shared hold-out split, the signed entries on the shared review core, what stays UK code and what a UK build computes again. The US page and uk/target_sets.json link to it. Part of microcosm#1759. Co-Authored-By: Claude Opus 5.5 --- docs/uk-target-sets.md | 155 ++++++++++++++++++ docs/us-target-sets.md | 4 +- .../src/microcosm/build/uk/target_sets.json | 2 +- 3 files changed, 159 insertions(+), 2 deletions(-) create mode 100644 docs/uk-target-sets.md diff --git a/docs/uk-target-sets.md b/docs/uk-target-sets.md new file mode 100644 index 0000000000..2c52a47c21 --- /dev/null +++ b/docs/uk-target-sets.md @@ -0,0 +1,155 @@ +# UK target sets + +The UK declares its target sets the way the US does +([US target sets](us-target-sets.md)). Since microcosm#1759 the UK choices are +data in +[`packages/microcosm-build/src/microcosm/build/uk/target_sets.json`](../packages/microcosm-build/src/microcosm/build/uk/target_sets.json), +read by the shared +[`microcosm.calibrate.target_sets`](../packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py). +The UK names (file, products, predicate) are in +[`microcosm.build.uk_runtime.target_sets`](../packages/microcosm-build/src/microcosm/build/uk_runtime/target_sets.py). + +The move changed no target, selection or receipt. The proofs are listed under +"How the move was checked" below. + +## The level rule + +Every compiled UK target has one geography level. The file declares how to +read it: + +```json +"level_rule": { + "keys": ["geography_level", "ledger_geography_level"], + "values": ["country", "region", "constituency", "la", "brma"], + "conflict": "refuse" +} +``` + +- The level is the first of the two keys that has a value. +- When both keys have a value, they must agree. +- The level must be one of the five grains. A target with no level, or with + another level, is refused. + +`uk_runtime.graph_targets.target_geography` and the national problem +(`graph_national.national_target_geography_levels`) read levels with this +rule. The US file gives the short form `level_keys`, which is an open rule +that takes the first key. + +## The products + +| Product | Where it runs | Option | Modes | +|---|---|---|---| +| `full` | `uk.full.target_selection@1` (`uk_runtime/graph_targets.py`) | `--target-geographies` of the full build | `levels` | +| `calibration_line` | `uk_runtime/full_targets.py`, through `ledger_targets.uk_registry_on_calibration_line` | the line of the build | `national`, `local` | + +### `full`: the solve surface by level + +The `levels` mode has one clause for each of the five levels. The selection +node keeps the clauses of the levels that the build requests (all of them by +default), in compile order, with the shared `select_by_levels`. Its receipt +lists every target, kept or not (schema +`microcosm.calibrate.target-selection.v1`, read by `uk_runtime/full_gates.py`). + +Two filters run before the selection and stay in the node: + +- `--households-only` keeps only the `census_households/constituency` family; +- with no area BRMAs (`--brma-localisation none`), the node drops the `brma` + rows, because they would bind on the spine's regional BRMA draw + (microcosm#1305). + +The receipt records the registry after these filters. + +### `calibration_line`: what each line binds + +A UK build runs on one of two lines: the national line +(`load_uk_national_target_inputs`, the release-cut certifier) or the local +line (the full dense build, which binds the national rows beside the local +surface). A contract target in `uk/uk_population_targets.json` binds on both +lines unless its `calibration_lines` field names one. Each line's mode has one +clause that keeps every compiled national reference except the ones that the +predicate `off_calibration_line` names. The UK code binds that predicate to +the contract targets that leave the line out. + +The membership stays with each contract target, with its reason. The rows +leave right after the compile, before reconciliation, the measure exclusions +and the frozen-register check. `UK_CALIBRATION_LINES` is the declared modes. + +## Hold-outs + +The UK and US hold-outs keep different draws on purpose: + +- The UK rowwise hold-out (`uk_runtime/local_rowwise.py`, + `rotated_uk_local_holdout`) is report-only. It deals the local target rows + into 5 rotated folds (seed 20260529) and solves once for each fold. +- The US local hold-out holds out hashed blocks of units + (`us/local_target_construction.json`). + +Both now share the last two steps in `microcosm.build.holdout`: the +`HoldoutSplit` type (`fold_splits` for the UK, `target_holdouts.role_split` +for the US) and `held_estimates`. + +The UK fold count and seed stay constants in `local_rowwise.py` +(`UK_LOCAL_HOLDOUT_FOLDS`, `UK_LOCAL_HOLDOUT_SEED`), as María ruled on +26 Nov 2026. A stricter UK hold-out, for example one that declares its draw as +data, would start there. + +## Signed entries + +The UK reviewed files sign each entry (approved by, approved on, expires on). +The UK code reads their dates and windows with the shared review core in +[`microcosm.build.declared_registers`](../packages/microcosm-build/src/microcosm/build/declared_registers.py): +`read_strict_json`, `canonical_date`, `ReviewWindow` and `stale_entries`. The +users are: + +- the calibration measure exclusions and the support floor + (`uk_runtime/measure_simulation.py`, `uk_runtime/support_floor.py`); +- the reviewed exclusions of the target-fit, local target-fit and area-support + gates (`uk_runtime/weighted_integrity.py`). + +Each UK function keeps its error texts and decides what a lapse does: it +refuses a run, fails a gate, or reports. + +Not moved: + +- The small-cell deferrals (`ledger_targets.assert_uk_local_deferrals_in_force`) + check only the expiry, and they also accept compact dates. Moving them would + change what they accept. +- The other UK signed files (for example the uprating holds) can use the core + later. + +## The support floor stays UK code + +The UK zero-support floor (`uk_runtime/support_floor.py`) drops the target rows +that no source household carries. The US county minimum support +(`tools/us_acs_local_county_surface.py`, `plan_minimum_support`) moves donor +households in the frame before targets exist. These are different policies at +different stages, so a shared module would have one caller. +`uk_runtime/off_surface_cells.py` builds cross-grain rows, so it belongs to +the nesting work of microcosm#1760. + +## How the move was checked + +- `test_uk_level_selection.py` compares the selection by level with verbatim + copies of the removed `select_targets` and UK resolver, on 400 random + registries and requests, refusals included. +- `test_uk_calibration_line_selection.py` compares the line filter with a + verbatim copy of the old function. +- `test_holdout.py` compares the split and the held estimates with the + replaced UK and US expressions, byte for byte. +- `test_uk_review_loaders.py` and `test_uk_reviewed_exclusions_core.py` + compare the signed-entry loaders with verbatim copies of the old code. +- `test_uk_target_surface_pins.py` pins the bytes of the UK target nodes' + artifacts on the pinned Chronicle feed: the full surface, each selection + and the national registry. + +## What a UK build computes again + +`uk/target_sets.json` is a solve-scoped UK resource, so it is in the UK solve +fingerprint. The spine gates also hash that fingerprint. So the first UK build +after this change computes these again: + +- the spine from `frs_brma` on; +- the target nodes and every node after them; +- the national graph. + +The outputs are the same bytes. diff --git a/docs/us-target-sets.md b/docs/us-target-sets.md index 59850cb48d..04588220a9 100644 --- a/docs/us-target-sets.md +++ b/docs/us-target-sets.md @@ -17,7 +17,9 @@ declared as data, for each product and mode, in `soi_surface_predicate`) select by the declarations. The declarations replaced the selection code without a change to any target -surface (see "What the declarations select" below). +surface (see "What the declarations select" below). The UK declares its target +sets the same way, with the same shared reader and selector +([UK target sets](uk-target-sets.md), microcosm#1759). ## The declaration diff --git a/packages/microcosm-build/src/microcosm/build/uk/target_sets.json b/packages/microcosm-build/src/microcosm/build/uk/target_sets.json index d8c117ac08..ebf1ff2636 100644 --- a/packages/microcosm-build/src/microcosm/build/uk/target_sets.json +++ b/packages/microcosm-build/src/microcosm/build/uk/target_sets.json @@ -1,7 +1,7 @@ { "version": 1, "country": "uk", - "description": "The targets each UK build calibrates to (microcosm#1759): the level rule that places every compiled UK target at one geography level, the full build's selection of its solve surface by level, and the two calibration lines. microcosm.calibrate.target_sets reads this file; microcosm.build.uk_runtime.target_sets names its products. The US declares its target sets the same way, in us/target_sets.json (microcosm#1728).", + "description": "The targets each UK build calibrates to (microcosm#1759): the level rule that places every compiled UK target at one geography level, the full build's selection of its solve surface by level, and the two calibration lines. microcosm.calibrate.target_sets reads this file; microcosm.build.uk_runtime.target_sets names its products; docs/uk-target-sets.md explains it. The US declares its target sets the same way, in us/target_sets.json (microcosm#1728).", "level_rule": { "keys": [ "geography_level", From dcd2e470eb7ab7ec4c15787fddc8a7c40d07ac72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:10:05 +0000 Subject: [PATCH 20/30] Read the declaration files strictly The review of microcosm#1755 found that three readers took a repeated JSON key without a word: plain json.loads keeps the last one, so a second mode or register of one name replaced the first. The target-set reader, the declared registers and the US local target construction now refuse a repeated key and a non-finite number. A version must be the integer 1 (True passed before), and a list of clause names refuses "*", which would match only a name "*". The packaged files already pass, so no selection or register changes. Part of microcosm#1728. Co-Authored-By: Claude Fable 5.2 --- ...1728-strict-declaration-readers.changed.md | 1 + .../src/microcosm/build/declared_registers.py | 9 ++++- .../us_runtime/local_target_construction.py | 15 +++++-- .../shared/test_declared_registers.py | 33 +++++++++++++++ .../src/microcosm/calibrate/target_sets.py | 40 +++++++++++++++++-- .../engine_free/shared/test_target_sets.py | 32 +++++++++++++++ 6 files changed, 121 insertions(+), 9 deletions(-) create mode 100644 changelog.d/1728-strict-declaration-readers.changed.md diff --git a/changelog.d/1728-strict-declaration-readers.changed.md b/changelog.d/1728-strict-declaration-readers.changed.md new file mode 100644 index 0000000000..50332b182f --- /dev/null +++ b/changelog.d/1728-strict-declaration-readers.changed.md @@ -0,0 +1 @@ +The declaration readers of microcosm#1728 are strict: `microcosm.calibrate.target_sets.load_target_set_declarations`, `microcosm.build.declared_registers.package_registers` and the US local target construction refuse a repeated JSON key (plain `json.loads` kept the last one, so a second mode or register of one name replaced the first without a word), a non-finite number, and a version that is not the integer 1. A list of clause names refuses `"*"`, which would match only a name `*`; give `"*"` alone for every name. The packaged files already pass, so no selection or register changes. diff --git a/packages/microcosm-build/src/microcosm/build/declared_registers.py b/packages/microcosm-build/src/microcosm/build/declared_registers.py index bb4a08f543..c4ee342048 100644 --- a/packages/microcosm-build/src/microcosm/build/declared_registers.py +++ b/packages/microcosm-build/src/microcosm/build/declared_registers.py @@ -167,12 +167,17 @@ def load_register(section: Mapping[str, Any], *, name: str = "register") -> Any: def package_registers(package: str, resource: str) -> Mapping[str, Any]: """The register sections of a package's JSON resource, read and checked once.""" - payload = json.loads(files(package).joinpath(resource).read_text(encoding="utf-8")) + # Read strictly: plain json.loads keeps the last of two equal keys, so a + # second register of one name would replace the first without a word. + payload = read_strict_json( + files(package).joinpath(resource).read_text(encoding="utf-8"), + label=f"{package}/{resource}", + ) if not isinstance(payload, dict) or set(payload) != _FILE_KEYS: raise DeclaredRegisterError( f"{package}/{resource} must hold exactly the keys {sorted(_FILE_KEYS)}." ) - if payload["version"] != 1: + if type(payload["version"]) is not int or payload["version"] != 1: raise DeclaredRegisterError(f"{package}/{resource} must be version 1.") if not isinstance(payload["country"], str) or not payload["country"]: raise DeclaredRegisterError(f"{package}/{resource} must name its country.") diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/local_target_construction.py b/packages/microcosm-build/src/microcosm/build/us_runtime/local_target_construction.py index c1ebc8fa08..79f62cdfb3 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/local_target_construction.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/local_target_construction.py @@ -14,12 +14,12 @@ from __future__ import annotations -import json from functools import lru_cache from importlib.resources import files from pathlib import Path from typing import Any +from microcosm.build.declared_registers import read_strict_json from microcosm.build.ladder_population_targets import ( LabelLookup, LadderPopulation, @@ -73,15 +73,22 @@ def us_local_target_construction_path() -> Path: def us_local_target_construction() -> dict[str, Any]: """The packaged US file, with its envelope checked.""" - payload = json.loads( - us_local_target_construction_path().read_text(encoding="utf-8") + # Read strictly: a repeated JSON key (a second pass list, a second field + # of one name) is refused, not resolved to the last one. + payload = read_strict_json( + us_local_target_construction_path().read_text(encoding="utf-8"), + label=US_LOCAL_TARGET_CONSTRUCTION_RESOURCE, ) if not isinstance(payload, dict) or set(payload) != _ENVELOPE_KEYS: raise ValueError( f"{US_LOCAL_TARGET_CONSTRUCTION_RESOURCE} must hold exactly the keys " f"{sorted(_ENVELOPE_KEYS)}." ) - if payload["version"] != 1 or payload["country"] != "us": + if ( + type(payload["version"]) is not int + or payload["version"] != 1 + or payload["country"] != "us" + ): raise ValueError( f"{US_LOCAL_TARGET_CONSTRUCTION_RESOURCE} must be version 1 for country us." ) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_declared_registers.py b/packages/microcosm-build/tests/engine_free/shared/test_declared_registers.py index ebf5c9cc84..e1078c77b0 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_declared_registers.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_declared_registers.py @@ -221,3 +221,36 @@ def test_stale_entries_are_the_declared_names_not_found() -> None: assert stale_entries(["b", "a", "c", "a"], {"c"}) == ["a", "b"] assert stale_entries([], ["x"]) == [] + + +def test_a_register_file_is_read_strictly(tmp_path, monkeypatch) -> None: + # Plain json.loads keeps the last of two equal keys, so a second register + # of one name would replace the first one without a word (the review of + # microcosm#1755). + import microcosm.build.declared_registers as module + + monkeypatch.setattr(module, "files", lambda _package: tmp_path) + envelope = '"version": 1, "country": "test", "description": "d"' + cases = { + "good.json": "{" + envelope + ', "registers": {"r": {}}}', + "repeated_top.json": '{"version": 1, ' + envelope + ', "registers": {"r": {}}}', + "repeated_register.json": "{" + envelope + ', "registers": {"r": {}, "r": {}}}', + "true_version.json": ( + '{"version": true, "country": "test", "description": "d", ' + '"registers": {"r": {}}}' + ), + } + for name, text in cases.items(): + (tmp_path / name).write_text(text, encoding="utf-8") + assert module.package_registers("test.package", "good.json") == {"r": {}} + for name, key in ( + ("repeated_top.json", "version"), + ("repeated_register.json", "r"), + ): + with pytest.raises(DeclaredRegisterError) as refusal: + module.package_registers("test.package", name) + assert str(refusal.value) == ( + f"test.package/{name}: duplicate JSON key(s): ['{key}']." + ) + with pytest.raises(DeclaredRegisterError, match="must be version 1"): + module.package_registers("test.package", "true_version.json") diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py b/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py index 46b33602c8..e2782ecc69 100644 --- a/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py @@ -398,6 +398,9 @@ def _names(where: str, value: object) -> frozenset[str] | None: names = [_text(where, item) for item in value] if len(set(names)) != len(names): raise _fail(where, "repeats a name.") + if ANY in names: + # A list holds literal names: ["*"] would match only a name "*". + raise _fail(where, f"lists {ANY!r} as a name; give {ANY!r} alone, not a list.") return frozenset(names) @@ -497,18 +500,49 @@ def _built(where: str, raw: object) -> BuiltRows: ) +def _read_declaration_file(path: Path) -> object: + """Read a declaration file; refuse a repeated key or a non-finite number. + + Plain ``json.loads`` keeps the last of two equal keys, so a second + ``"state"`` mode or a second ``"levels"`` in a clause would replace the + first one without a word. + """ + + where = str(path) + + def no_repeated_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + keys = [key for key, _value in pairs] + repeated = sorted({key for key in keys if keys.count(key) > 1}) + if repeated: + raise _fail(where, f"repeats the JSON key(s) {repeated}.") + return dict(pairs) + + def no_constant(value: str) -> Any: + raise _fail(where, f"holds the non-finite number {value}.") + + return json.loads( + path.read_text(encoding="utf-8"), + object_pairs_hook=no_repeated_keys, + parse_constant=no_constant, + ) + + def load_target_set_declarations( source: str | Path | Mapping[str, Any], ) -> TargetSetDeclarations: - """Read and check one country's declarations (a path or a parsed object).""" + """Read and check one country's declarations (a path or a parsed object). + + A file is read strictly: a repeated JSON key and a non-finite number are + refused. + """ if isinstance(source, Mapping): raw, where = source, "target sets" else: path = Path(source) - raw, where = json.loads(path.read_text(encoding="utf-8")), str(path) + raw, where = _read_declaration_file(path), str(path) top = _require_keys(where, raw, _TOP_KEYS, ("version", "country", "products")) - if top["version"] != DECLARATION_VERSION: + if type(top["version"]) is not int or top["version"] != DECLARATION_VERSION: raise _fail(where, f"version must be {DECLARATION_VERSION}.") country = _text(f"{where}.country", top["country"]) level_rule = _level_rule(where, top) diff --git a/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py b/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py index 4471295188..e2abcba253 100644 --- a/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py +++ b/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py @@ -166,10 +166,37 @@ def test_declarations_load_from_a_file_and_name_products_and_modes(tmp_path) -> state.clause("snap") +def test_a_file_with_a_repeated_key_or_a_non_finite_number_is_refused( + tmp_path, +) -> None: + # Plain json.loads keeps the last of two equal keys: a second mode of one + # name, or a second "levels" in a clause, would replace the first one + # without a word (the review of microcosm#1755). + text = json.dumps(DECLARATIONS) + path = tmp_path / "target_sets.json" + path.write_text('{"version": 1, ' + text[1:], encoding="utf-8") + with pytest.raises( + TargetSetDeclarationError, match=r"repeats the JSON key\(s\) \['version'\]" + ): + load_target_set_declarations(path) + nested = text.replace('"modes": {', '"modes": {"all": {}, ', 1) + assert nested != text + path.write_text(nested, encoding="utf-8") + with pytest.raises( + TargetSetDeclarationError, match=r"repeats the JSON key\(s\) \['all'\]" + ): + load_target_set_declarations(path) + path.write_text(text[:-1] + ', "extra": NaN}', encoding="utf-8") + with pytest.raises(TargetSetDeclarationError, match="non-finite number NaN"): + load_target_set_declarations(path) + + @pytest.mark.parametrize( ("changes", "message"), [ ({"version": 2}, "version must be 1"), + # True equals 1 in Python; a version is the integer. + ({"version": True}, "version must be 1"), ({"extra": True}, "unknown keys"), ({"level_keys": []}, "level_keys"), ({"products__local__default_mode": "county"}, "not a declared mode"), @@ -182,6 +209,11 @@ def test_declarations_load_from_a_file_and_name_products_and_modes(tmp_path) -> {"products__local__modes__state__compiled__0__levels": ["state", "state"]}, "repeats a name", ), + # A list holds literal names, so ["*"] would match only a name "*". + ( + {"products__local__modes__state__compiled__0__families": ["*"]}, + "give '\\*' alone, not a list", + ), ( {"products__local__modes__state__compiled__1__id": "benefit"}, "repeats a clause or built id", From 47561f9a3412c868995cf530a41abbd56b66045f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:10:05 +0000 Subject: [PATCH 21/30] Keep the replaced refusal texts in the shared hold-out and ladder code The review of microcosm#1755 found that the shared code wrote generic refusal texts, and that the tests compared only the error class. - A pass's scoring declares child_label and parent_label, and a ladder level declares code_name. With them the pro-rata baseline refusals and the ladder's state-code refusal have the replaced texts again. - assign_holdout_roles refuses None for the fraction and the salt. Only an omitted argument draws with the declared value, so a caller that forwards an unset option cannot hold targets out silently. - The US tests compare each refusal's class and text with the replaced code. Three cases still differ from the replaced code, because one shared check now serves both passes: the county fraction refusal also names the value, the district pass checks its salt before it reads a record, and the county scorer reads role on every record. The tests pin them. No run of the tool reaches them: the command line checks fractions and salts first, and the district pass gives every record a role. No target, role or receipt changes. Part of microcosm#1728. Co-Authored-By: Claude Fable 5.2 --- .../1728-shared-target-holdouts.added.md | 2 +- .../build/ladder_population_targets.py | 9 +- .../src/microcosm/build/target_holdouts.py | 54 +++++- .../build/us/local_target_construction.json | 6 + .../shared/test_ladder_population_targets.py | 2 + .../shared/test_target_holdouts.py | 33 +++- .../us/test_us_ladder_population.py | 5 +- .../engine_free/us/test_us_target_holdouts.py | 181 +++++++++++++++++- 8 files changed, 269 insertions(+), 23 deletions(-) diff --git a/changelog.d/1728-shared-target-holdouts.added.md b/changelog.d/1728-shared-target-holdouts.added.md index 2bd9ccd34b..5845d4fe73 100644 --- a/changelog.d/1728-shared-target-holdouts.added.md +++ b/changelog.d/1728-shared-target-holdouts.added.md @@ -1 +1 @@ -Target hold-outs are shared code for any country (microcosm#1728): `microcosm.build.target_holdouts` draws held-out targets by hashed blocks from declared passes (scope, eligibility, unit key, salt, fractions, receipt), builds the training target set, and scores the held rows against a pro-rata baseline. The ACS local release declares its district and county passes in the new `us/local_target_construction.json`, read by `microcosm.build.us_runtime.local_target_construction`; the tool functions call the shared code under their old names. No target, role or receipt changes: `test_us_target_holdouts.py` holds the shared code to verbatim copies of the replaced tool code, and the pinned bytes of `test_us_acs_local_surface_bytes.py` are unchanged. The new resource row moves the US F0 spec-engine pins (42,410 configuration fields). One label changes: `calibration_diagnostics.json` names each matrix-row measure `microcosm.build.target_holdouts.target_matrix_row[N]` instead of `us_acs_local_cd_surface.target_matrix_row[N]`, because the function that makes it moved to the shared module. So the diagnostics' `target_surface.sha256` (and the same field in `build_manifest.json`) changes for the same targets and weights; `names_sha256` and `values_sha256` do not. Accepted on 26 Nov 2026 and pinned in `test_us_target_holdouts.py`. +Target hold-outs are shared code for any country (microcosm#1728): `microcosm.build.target_holdouts` draws held-out targets by hashed blocks from declared passes (scope, eligibility, unit key, salt, fractions, receipt), builds the training target set, and scores the held rows against a pro-rata baseline. The ACS local release declares its district and county passes in the new `us/local_target_construction.json`, read by `microcosm.build.us_runtime.local_target_construction`; the tool functions call the shared code under their old names. No target, role or receipt changes: `test_us_target_holdouts.py` holds the shared code to verbatim copies of the replaced tool code, and the pinned bytes of `test_us_acs_local_surface_bytes.py` are unchanged. A refusal keeps its text and stays a `ValueError` (the shared `TargetHoldoutError` is a subclass), except where one shared check now serves both passes: the county fraction refusal also names the value, the district pass checks its salt first, and the county scorer reads `role` on every record. `fraction=None` and `salt=None` are refused; only an omitted argument draws with the declared value. `docs/us-target-sets.md` lists these under "Refusals". The new resource row moves the US F0 spec-engine pins (42,410 configuration fields at this step; 42,413 after the compile registers). One label changes: `calibration_diagnostics.json` names each matrix-row measure `microcosm.build.target_holdouts.target_matrix_row[N]` instead of `us_acs_local_cd_surface.target_matrix_row[N]`, because the function that makes it moved to the shared module. So the diagnostics' `target_surface.sha256` (and the same field in `build_manifest.json`) changes for the same targets and weights; `names_sha256` and `values_sha256` do not. Accepted on 26 Nov 2026 and pinned in `test_us_target_holdouts.py`. diff --git a/packages/microcosm-build/src/microcosm/build/ladder_population_targets.py b/packages/microcosm-build/src/microcosm/build/ladder_population_targets.py index 07fcf9c730..def99c93ee 100644 --- a/packages/microcosm-build/src/microcosm/build/ladder_population_targets.py +++ b/packages/microcosm-build/src/microcosm/build/ladder_population_targets.py @@ -13,7 +13,8 @@ a smaller surface is acceptable; - the cell's target spec with its calibration hierarchy (:func:`population_target_specs`). A country gives a label lookup for each - declared label kind. + declared label kind, and each level's ``code_name``: what a refusal calls + a code that has no label. A country declares its levels as data, and :func:`load_ladder_population` reads them (microcosm#1728). Nothing here reads country code. @@ -52,6 +53,7 @@ { "geography", "level", + "code_name", "household_column", "code_digits", "geography_id_prefix", @@ -89,6 +91,8 @@ class LadderLevel: geography: str level: str + #: What a refusal calls the level's code (for example ``US state FIPS``). + code_name: str household_column: str code_digits: int geography_id_prefix: str @@ -196,6 +200,7 @@ def _level(raw: Any) -> LadderLevel: return LadderLevel( geography=geography, level=_text(raw["level"], context=f"{context} level"), + code_name=_text(raw["code_name"], context=f"{context} code_name"), household_column=_text( raw["household_column"], context=f"{context} household_column" ), @@ -348,7 +353,7 @@ def population_target_specs( label = labels[level.label](code, geography_id) if label is None: raise LadderPopulationError( - f"Population target {name!r} names no {level.level} code." + f"Population target {name!r} names no {level.code_name} code." ) geography = HierarchyGeography(geography_id, label, level.level) specs.append( diff --git a/packages/microcosm-build/src/microcosm/build/target_holdouts.py b/packages/microcosm-build/src/microcosm/build/target_holdouts.py index cb0305385e..bd3cc76b23 100644 --- a/packages/microcosm-build/src/microcosm/build/target_holdouts.py +++ b/packages/microcosm-build/src/microcosm/build/target_holdouts.py @@ -21,7 +21,8 @@ - ``receipt``: the receipt keys the pass writes, in order. - ``scoring``: how :func:`score_holdout` scores the held rows against a pro-rata baseline, which is a parent target times the child's share of the - parent's population. + parent's population. ``child_label`` and ``parent_label`` are the words a + refusal uses for the two levels. A target record is a mapping with at least ``name``, ``value``, ``family`` and ``geography_level``, the field names the targets carry everywhere. The @@ -128,6 +129,8 @@ _SCORING_KEYS = frozenset( { "level", + "child_label", + "parent_label", "parent_name_field", "child_population_field", "parent_population_field", @@ -209,9 +212,15 @@ class PopulationShares: @dataclass(frozen=True) class HoldoutScoring: - """How :func:`score_holdout` scores a pass's held rows.""" + """How :func:`score_holdout` scores a pass's held rows. + + ``child_label`` and ``parent_label`` name the two levels in a refusal of + the pro-rata baseline (for example ``county`` and ``state``). + """ level: str + child_label: str + parent_label: str parent_name_field: str child_population_field: str parent_population_field: str @@ -378,6 +387,8 @@ def _scoring(value: Any, *, context: str) -> HoldoutScoring | None: ) return HoldoutScoring( level=_text(raw["level"], context=f"{context} level"), + child_label=_text(raw["child_label"], context=f"{context} child_label"), + parent_label=_text(raw["parent_label"], context=f"{context} parent_label"), parent_name_field=_text( raw["parent_name_field"], context=f"{context} parent_name_field" ), @@ -476,13 +487,26 @@ def load_target_holdouts(section: Mapping[str, Any]) -> TargetHoldouts: # --------------------------------------------------------------------------- +class _DeclaredValue: + """The default of an argument that takes the pass's declared value.""" + + def __repr__(self) -> str: + return "DECLARED" + + +#: Leave ``fraction`` or ``salt`` out of :func:`assign_holdout_roles` to draw +#: with the pass's declared value. ``None`` is not that: a caller that +#: forwards an unset option is refused, not given a silent draw. +DECLARED: Any = _DeclaredValue() + + def assign_holdout_roles( records: Sequence[dict], holdout_pass: HoldoutPass, concept_families: ConceptFamilyRule, *, - fraction: float | None = None, - salt: str | None = None, + fraction: float = DECLARED, + salt: str = DECLARED, ) -> dict: """Set ``holdout_unit`` and ``role`` on each record in scope; return the receipt. @@ -490,10 +514,17 @@ def assign_holdout_roles( out by :func:`microcosm.build.holdout.hash_holdout_unit` on its key, once. A record in scope that is not eligible gets no unit and trains. A record out of scope keeps what it had. + + The salt and then the fraction are checked before any record is read. + A salt that is not a non-empty string, and a fraction outside + ``[0, max_fraction]``, raise :class:`TargetHoldoutError`. A fraction that + is not a number (``None`` included) raises ``TypeError``. """ - fraction = holdout_pass.default_fraction if fraction is None else fraction - salt = holdout_pass.salt if salt is None else salt + if fraction is DECLARED: + fraction = holdout_pass.default_fraction + if salt is DECLARED: + salt = holdout_pass.salt if not isinstance(salt, str) or not salt: raise TargetHoldoutError( f"{holdout_pass.label} holdout salt must be a non-empty string." @@ -751,13 +782,15 @@ def pro_rata_baseline( if scoring.population_check == "nonzero": if parent is None: raise TargetHoldoutError( - f"{record['name']} has no bound parent for the baseline." + f"{record['name']} has no bound {scoring.parent_label} parent " + "for the baseline." ) child = record.get(scoring.child_population_field) parent_population = record.get(scoring.parent_population_field) if not child or not parent_population: raise TargetHoldoutError( - f"{record['name']} carries no child or parent population for " + f"{record['name']} carries no " + f"{scoring.child_label}/{scoring.parent_label} population for " "the pro-rata baseline." ) values.append( @@ -773,8 +806,9 @@ def pro_rata_baseline( and parent_population > 0 ): raise TargetHoldoutError( - f"{record['name']} has no parent or positive child and parent " - "population for the pro-rata baseline." + f"{record['name']} has no {scoring.parent_label} parent or positive " + f"{scoring.child_label}/{scoring.parent_label} population for " + "pro-rata baseline." ) values.append(float(parent["value"]) * child / parent_population) return np.asarray(values, dtype=np.float64) diff --git a/packages/microcosm-build/src/microcosm/build/us/local_target_construction.json b/packages/microcosm-build/src/microcosm/build/us/local_target_construction.json index 9e20d68880..0dfd14bc8f 100644 --- a/packages/microcosm-build/src/microcosm/build/us/local_target_construction.json +++ b/packages/microcosm-build/src/microcosm/build/us/local_target_construction.json @@ -62,6 +62,8 @@ "hash_description": "sha256(salt + 0x1f + unit)[:8] / 2**64 < fraction", "scoring": { "level": "congressional_district", + "child_label": "district", + "parent_label": "state", "parent_name_field": "state_cd_parent_target_name", "child_population_field": "cd_population", "parent_population_field": "state_population", @@ -118,6 +120,8 @@ "hash_description": null, "scoring": { "level": "county", + "child_label": "county", + "parent_label": "state", "parent_name_field": "state_county_parent_target_name", "child_population_field": "county_population", "parent_population_field": "state_population", @@ -157,6 +161,7 @@ { "geography": "state", "level": "state", + "code_name": "US state FIPS", "household_column": "state_fips", "code_digits": 2, "geography_id_prefix": "0400000US", @@ -177,6 +182,7 @@ { "geography": "cd", "level": "congressional_district", + "code_name": "congressional district", "household_column": "congressional_district_geoid", "code_digits": 4, "geography_id_prefix": "5001900US", diff --git a/packages/microcosm-build/tests/engine_free/shared/test_ladder_population_targets.py b/packages/microcosm-build/tests/engine_free/shared/test_ladder_population_targets.py index d229f17ad8..7379f827e9 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_ladder_population_targets.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_ladder_population_targets.py @@ -37,6 +37,7 @@ def _section() -> dict: { "geography": "region", "level": "region", + "code_name": "region", "household_column": "region_code", "code_digits": 1, "geography_id_prefix": "R:", @@ -49,6 +50,7 @@ def _section() -> dict: { "geography": "district", "level": "district", + "code_name": "district", "household_column": "district_code", "code_digits": 3, "geography_id_prefix": "D:", diff --git a/packages/microcosm-build/tests/engine_free/shared/test_target_holdouts.py b/packages/microcosm-build/tests/engine_free/shared/test_target_holdouts.py index a22be3eefc..75aedad216 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_target_holdouts.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_target_holdouts.py @@ -62,6 +62,8 @@ def _section() -> dict: "hash_description": "a salted hash", "scoring": { "level": "district", + "child_label": "district", + "parent_label": "region", "parent_name_field": "parent", "child_population_field": "child_pop", "parent_population_field": "parent_pop", @@ -286,6 +288,22 @@ def test_the_role_pass_refuses_a_bad_fraction_or_salt() -> None: assign_holdout_roles(_records(), district, holdouts.concept_families, salt="") +def test_an_unset_fraction_or_salt_is_refused_not_defaulted() -> None: + # Only an omitted argument draws with the declared value. A caller that + # forwards an unset option (None) must not hold targets out silently + # (the review of microcosm#1755). + holdouts = load_target_holdouts(_section()) + district = holdouts.holdout_pass("district") + declared = assign_holdout_roles(_records(), district, holdouts.concept_families) + assert declared["fraction"] == district.default_fraction + with pytest.raises(TypeError): + assign_holdout_roles( + _records(), district, holdouts.concept_families, fraction=None + ) + with pytest.raises(TargetHoldoutError, match="salt must be a non-empty string"): + assign_holdout_roles(_records(), district, holdouts.concept_families, salt=None) + + def _scored(): holdouts = load_target_holdouts(_section()) district = holdouts.holdout_pass("district") @@ -395,14 +413,23 @@ def test_the_population_checks() -> None: strict = type(scoring)( **{**scoring.__dict__, "population_check": "finite_positive"} ) - with pytest.raises(TargetHoldoutError): + # Each refusal names the declared labels of the two levels. + with pytest.raises(TargetHoldoutError) as refusal: pro_rata_baseline([parent, row], [1], strict) + assert str(refusal.value) == ( + "c has no region parent or positive district/region population for " + "pro-rata baseline." + ) row["child_pop"] = 0.0 - with pytest.raises(TargetHoldoutError): + with pytest.raises(TargetHoldoutError) as refusal: pro_rata_baseline([parent, row], [1], scoring) + assert str(refusal.value) == ( + "c carries no district/region population for the pro-rata baseline." + ) row["child_pop"], row["parent"] = 2.0, "missing" - with pytest.raises(TargetHoldoutError): + with pytest.raises(TargetHoldoutError) as refusal: pro_rata_baseline([parent, row], [1], scoring) + assert str(refusal.value) == "c has no bound region parent for the baseline." def test_error_summary() -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_ladder_population.py b/packages/microcosm-build/tests/engine_free/us/test_us_ladder_population.py index 082d4c28ca..fb96845956 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_ladder_population.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_ladder_population.py @@ -138,10 +138,11 @@ def test_county_specs_keep_their_place(tool) -> None: def test_a_state_code_with_no_name_refuses(tool) -> None: - with pytest.raises(ValueError): + with pytest.raises(ValueError) as old: reference.population_target_specs(["pop_state_99"], [1.0]) - with pytest.raises(ValueError): + with pytest.raises(ValueError) as new: tool.population_target_specs(["pop_state_99"], [1.0]) + assert str(new.value) == str(old.value) class _Frame: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_target_holdouts.py b/packages/microcosm-build/tests/engine_free/us/test_us_target_holdouts.py index 8093cd730b..285f6bd09d 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_target_holdouts.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_target_holdouts.py @@ -21,6 +21,7 @@ import pytest from scipy import sparse +from microcosm.build.target_holdouts import TargetHoldoutError from microcosm.build.us_runtime.local_target_construction import ( COUNTY_HOLDOUT, DISTRICT_HOLDOUT, @@ -215,16 +216,164 @@ def test_roles_and_receipts_match(tool, seed: int, fraction: float) -> None: assert _dumps(new) == _dumps(old) +def _refusal(call): + """The class and the text of a refusal, or None when the call returns.""" + + try: + call() + except Exception as error: # noqa: BLE001 - the refusal is the outcome + return type(error), str(error) + return None + + +def _same_text(new, old) -> bool: + """A shared refusal: a ValueError as before, with the replaced text.""" + + return ( + old is not None + and new is not None + and old[0] is ValueError + and new[0] is TargetHoldoutError + and issubclass(TargetHoldoutError, ValueError) + and new[1] == old[1] + ) + + @pytest.mark.parametrize("fraction", [-0.1, 0.51, 1.0]) -def test_out_of_range_fractions_refuse_as_before(tool, fraction: float) -> None: +def test_out_of_range_fractions_refuse(tool, fraction: float) -> None: + old = _refusal( + lambda: reference.cd_assign_target_roles(_records(0), fraction=fraction) + ) + new = _refusal( + lambda: tool.cd_surface.assign_target_roles(_records(0), fraction=fraction) + ) + assert _same_text(new, old) + # One shared check writes both texts, so the county text now names the + # value too (docs/us-target-sets.md, "Refusals"). + old = _refusal( + lambda: reference.county_assign_target_roles(_records(0), fraction=fraction) + ) + new = _refusal( + lambda: tool.county_surface.assign_target_roles(_records(0), fraction=fraction) + ) + assert old == (ValueError, "County holdout fraction must be in [0, 0.5].") + assert new == ( + TargetHoldoutError, + f"County holdout fraction must be in [0, 0.5], got {fraction!r}.", + ) + + +def test_an_unset_fraction_or_salt_is_refused_not_defaulted(tool) -> None: + # None never draws the declared default: a caller that forwards an unset + # option must not hold targets out silently (the review of microcosm#1755). for old_call, new_call in ( (reference.cd_assign_target_roles, tool.cd_surface.assign_target_roles), (reference.county_assign_target_roles, tool.county_surface.assign_target_roles), ): - with pytest.raises(ValueError): - old_call(_records(0), fraction=fraction) - with pytest.raises(ValueError): - new_call(_records(0), fraction=fraction) + with pytest.raises(TypeError): + old_call(_records(0), fraction=None) + with pytest.raises(TypeError): + new_call(_records(0), fraction=None) + old = _refusal(lambda: reference.county_assign_target_roles(_records(0), salt=None)) + new = _refusal( + lambda: tool.county_surface.assign_target_roles(_records(0), salt=None) + ) + assert _same_text(new, old) + + +def test_the_district_pass_checks_its_salt_first(tool) -> None: + # The replaced district code left the salt to the hash of the first + # eligible unit: the refusal had the hash's text, and with no eligible + # unit an empty salt drew a receipt. One shared check now refuses first, + # for both passes (docs/us-target-sets.md, "Refusals"). + old = _refusal( + lambda: reference.cd_assign_target_roles(_records(0), fraction=0.1, salt="") + ) + assert old == (ValueError, "holdout salt must be a non-empty string, got ''.") + assert ( + _refusal(lambda: reference.cd_assign_target_roles([], fraction=0.1, salt="")) + is None + ) + for records in (_records(0), []): + new = _refusal( + lambda records=records: tool.cd_surface.assign_target_roles( + records, fraction=0.1, salt="" + ) + ) + assert new == ( + TargetHoldoutError, + "CD holdout salt must be a non-empty string.", + ) + + +def test_the_baseline_refusals_keep_their_texts(tool) -> None: + parent = {"name": "p", "value": 10.0} + district_rows = ( + { + "name": "c", + "state_cd_parent_target_name": "missing", + "cd_population": 1.0, + "state_population": 2.0, + }, + { + "name": "c", + "state_cd_parent_target_name": "p", + "cd_population": 0.0, + "state_population": 2.0, + }, + {"name": "c", "state_cd_parent_target_name": "p"}, + ) + for row in district_rows: + old = _refusal( + lambda row=row: reference.cd_pro_rata_baseline([parent, row], [1]) + ) + new = _refusal( + lambda row=row: tool.cd_surface.pro_rata_baseline([parent, row], [1]) + ) + assert _same_text(new, old) + county_rows = ( + { + "name": "c", + "state_county_parent_target_name": "missing", + "county_population": 1.0, + "state_population": 2.0, + }, + { + "name": "c", + "state_county_parent_target_name": "p", + "county_population": float("nan"), + "state_population": 2.0, + }, + {"name": "c", "state_county_parent_target_name": "p"}, + ) + for row in county_rows: + old = _refusal( + lambda row=row: reference.county_pro_rata_baseline([parent, row], [1]) + ) + new = _refusal( + lambda row=row: tool.county_surface.pro_rata_baseline([parent, row], [1]) + ) + assert _same_text(new, old) + + +def test_scoring_reads_the_role_of_every_record(tool) -> None: + # One shared scorer reads ``role`` at both levels, as the replaced + # district scorer did. The replaced county scorer skipped a record with + # no role. The tool never passes one: the district pass writes every + # record first, and the training set already needed every role. + records = [{"name": "s", "geography_level": "state"}] + matrix = sparse.csr_array(np.zeros((1, 2))) + common = {"design_weights": np.ones(2), "final_weights": np.ones(2), "cap": 10.0} + with pytest.raises(KeyError): + reference.score_cd_holdout(records, matrix, **common) + with pytest.raises(KeyError): + tool.cd_surface.score_cd_holdout(records, matrix, **common) + assert reference.score_county_holdout(records, matrix, **common) == { + "report_only": True, + "n_targets": 0, + } + with pytest.raises(KeyError): + tool.county_surface.score_county_holdout(records, matrix, **common) @pytest.mark.parametrize("seed", SEEDS) @@ -382,3 +531,25 @@ def test_every_declared_pass_has_scoring() -> None: COUNTY_HOLDOUT, ] assert all(holdout_pass.scoring for holdout_pass in us_target_holdouts().passes) + + +def test_the_us_file_is_read_strictly(tmp_path, monkeypatch) -> None: + # A repeated JSON key is refused, not resolved to the last one (the + # review of microcosm#1755). + from microcosm.build.us_runtime import local_target_construction as module + + text = module.us_local_target_construction_path().read_text(encoding="utf-8") + path = tmp_path / "local_target_construction.json" + monkeypatch.setattr(module, "us_local_target_construction_path", lambda: path) + read = module.us_local_target_construction.__wrapped__ + + path.write_text(text, encoding="utf-8") + assert read() == us_local_target_construction() + path.write_text('{"version": 1, ' + text.lstrip()[1:], encoding="utf-8") + with pytest.raises(ValueError, match="duplicate JSON key"): + read() + changed = text.replace('"version": 1', '"version": true', 1) + assert changed != text + path.write_text(changed, encoding="utf-8") + with pytest.raises(ValueError, match="must be version 1"): + read() From f7cdd43fc171b46b084ba86fa79d674d735946a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:10:05 +0000 Subject: [PATCH 22/30] Raise a plain ValueError from the UK reviewed-exclusion reader The shared strict reader raises DeclaredRegisterError, a ValueError subclass. A gate that fails closed records the class name of the error in its report, so a malformed register gave a different report than before (the review of microcosm#1755). The UK reader raises a plain ValueError with the same text again. The UK loader tests now compare the error class as well as the text. Part of microcosm#1759. Co-Authored-By: Claude Fable 5.2 --- changelog.d/1759-shared-review-core.changed.md | 2 +- .../microcosm/build/uk_runtime/weighted_integrity.py | 10 ++++++++-- .../tests/engine_free/uk/test_uk_review_loaders.py | 2 +- .../engine_free/uk/test_uk_reviewed_exclusions_core.py | 10 ++++++---- 4 files changed, 16 insertions(+), 8 deletions(-) diff --git a/changelog.d/1759-shared-review-core.changed.md b/changelog.d/1759-shared-review-core.changed.md index ee0a4fe5be..d91a1635d6 100644 --- a/changelog.d/1759-shared-review-core.changed.md +++ b/changelog.d/1759-shared-review-core.changed.md @@ -1 +1 @@ -Signed register entries are checked with one shared review core (microcosm#1759). `microcosm.build.declared_registers` gains `read_strict_json`, `canonical_date`, `ReviewWindow` and `stale_entries`; they return values, and each country's code keeps its texts and decides what a lapse does. The UK calibration measure exclusions and the support floor (`uk_runtime.measure_simulation`, `uk_runtime.support_floor`) read their dates and windows with it. No result, warning or error text changes: `test_uk_review_loaders.py` holds the new code to verbatim copies of the old functions on the packaged file, on changed copies and on the days around each window edge. The UK target and national kernels now also hash `declared_registers`. The small-cell deferrals keep their own expiry check: it also accepts compact dates, so moving it would change what it accepts. The UK reviewed-exclusion registers (target fit, local target fit and area support, in `uk_runtime.weighted_integrity`) read their files with `read_strict_json` and their dates and windows with `canonical_date` and `ReviewWindow` (`UKReviewedExclusion.window()` is new); `test_uk_reviewed_exclusions_core.py` holds them to verbatim copies of the old reader, date checks and window methods. The UK gate kernels that read these registers now also hash `declared_registers`. +Signed register entries are checked with one shared review core (microcosm#1759). `microcosm.build.declared_registers` gains `read_strict_json`, `canonical_date`, `ReviewWindow` and `stale_entries`; they return values, and each country's code keeps its texts and decides what a lapse does. The UK calibration measure exclusions and the support floor (`uk_runtime.measure_simulation`, `uk_runtime.support_floor`) read their dates and windows with it. No result, warning, error class or error text changes: `test_uk_review_loaders.py` holds the new code to verbatim copies of the old functions on the packaged file, on changed copies and on the days around each window edge. The UK target and national kernels now also hash `declared_registers`. The small-cell deferrals keep their own expiry check: it also accepts compact dates, so moving it would change what it accepts. The UK reviewed-exclusion registers (target fit, local target fit and area support, in `uk_runtime.weighted_integrity`) read their files with `read_strict_json` and their dates and windows with `canonical_date` and `ReviewWindow` (`UKReviewedExclusion.window()` is new); `test_uk_reviewed_exclusions_core.py` holds them to verbatim copies of the old reader, date checks and window methods, by error class and text (a gate that fails closed records the class name, so the reader still raises a plain `ValueError`). The UK gate kernels that read these registers now also hash `declared_registers`. diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/weighted_integrity.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/weighted_integrity.py index 62f4fb994c..cc860f613d 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/weighted_integrity.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/weighted_integrity.py @@ -130,6 +130,7 @@ import pandas as pd from microcosm.build.declared_registers import ( + DeclaredRegisterError, ReviewWindow, canonical_date, read_strict_json, @@ -658,8 +659,13 @@ def _read_register_payload( label = str(source) # Duplicate keys, non-finite numbers and malformed text are refused - # (microcosm#1759: the shared strict reader). - payload = read_strict_json(raw, label=label) + # (microcosm#1759: the shared strict reader). A gate that fails closed + # records the class of the error (gate_battery, ``evaluation_error.type``), + # so the refusal stays a plain ValueError with the reader's text. + try: + payload = read_strict_json(raw, label=label) + except DeclaredRegisterError as error: + raise ValueError(str(error)) from error if not isinstance(payload, Mapping): raise ValueError(f"{label}: exclusion register must be a JSON object.") return payload, label diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_review_loaders.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_review_loaders.py index 6fe0fdebc8..12fab83ea2 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_review_loaders.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_review_loaders.py @@ -37,7 +37,7 @@ def _outcome(call): try: value = call() except Exception as error: # noqa: BLE001 - the refusal is the outcome - value = ("refused", isinstance(error, ValueError), str(error)) + value = ("refused", type(error).__name__, str(error)) return value, [(w.category.__name__, str(w.message)) for w in caught] diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_reviewed_exclusions_core.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_reviewed_exclusions_core.py index fdb52ad5db..a5a704394b 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_reviewed_exclusions_core.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_reviewed_exclusions_core.py @@ -7,7 +7,9 @@ (``ReviewWindow``). ``test_support/microcosm_build/ uk_reviewed_exclusion_reference.py`` holds the old code verbatim. On the packaged files, on changed texts and on the days around every packaged -entry's window, the two give the same value or the same refusal text. +entry's window, the two give the same value or the same refusal: the same +error class and the same text. A gate that fails closed records the class +name in its report, so the class is part of the output. """ from __future__ import annotations @@ -31,8 +33,8 @@ def _outcome(call): try: return ("value", call()) - except ValueError as error: - return ("refused", str(error)) + except Exception as error: # noqa: BLE001 - the refusal is the outcome + return ("refused", type(error).__name__, str(error)) @pytest.mark.parametrize("resource", RESOURCES) @@ -103,7 +105,7 @@ def new() -> None: outcome = _outcome(new) assert outcome[0] == old[0] if old[0] == "refused": - assert outcome[1] == old[1] + assert outcome[1:] == old[1:] def _packaged_entries(): From b66abff84f3a30a580d1d4ea16300698fe95886f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:10:05 +0000 Subject: [PATCH 23/30] Hash the shared modules the UK hold-out kernel runs uk.full.rotated-holdout@1 rebuilds the problem inputs, so it runs the declared level rule (microcosm.calibrate.target_sets through the UK adapter) and the review core (microcosm.build.declared_registers). It hashed neither (the review of microcosm#1755). No stale result was possible, because a node key chains through its producers' keys, but the kernel now hashes what it runs. test_uk_graph_terminal.py pins these entries, the shared hold-out module, and the review core in each gate kernel's hash. No test pinned them before. Part of microcosm#1759. Co-Authored-By: Claude Fable 5.2 --- .../1759-shared-holdout-split.changed.md | 2 +- .../build/uk_runtime/graph_terminal.py | 11 ++++ .../engine_free/uk/test_uk_graph_terminal.py | 64 +++++++++++++++++++ 3 files changed, 76 insertions(+), 1 deletion(-) diff --git a/changelog.d/1759-shared-holdout-split.changed.md b/changelog.d/1759-shared-holdout-split.changed.md index 08b38192b5..9e4e171b6f 100644 --- a/changelog.d/1759-shared-holdout-split.changed.md +++ b/changelog.d/1759-shared-holdout-split.changed.md @@ -1 +1 @@ -The UK and US hold-outs share their last two steps (microcosm#1759). `microcosm.build.holdout` gains `HoldoutSplit` (a split's training rows and held rows), `fold_splits` (the UK's rotated folds as splits) and `held_estimates` (the held rows' estimates from the target matrix and the solved weights, in float64). The UK rowwise hold-out (`uk_runtime.local_rowwise.rotated_uk_local_holdout`) and the US local hold-out (`microcosm.build.target_holdouts`, through the new `role_split`) both use them; the two draws stay apart on purpose (rotated folds over UK local target rows, hashed blocks over US units). No hold-out result changes: `test_holdout.py` holds the new functions to the replaced UK and US expressions byte for byte, and the US hold-out tests compare with verbatim copies of the old tool code. The UK hold-out node now also hashes `microcosm.build.holdout`, which it ran without hashing. The UK hold-out keeps its constants (5 folds, seed 20260529, in `uk_runtime/local_rowwise.py`); a stricter UK hold-out would start there. +The UK and US hold-outs share their last two steps (microcosm#1759). `microcosm.build.holdout` gains `HoldoutSplit` (a split's training rows and held rows), `fold_splits` (the UK's rotated folds as splits) and `held_estimates` (the held rows' estimates from the target matrix and the solved weights, in float64). The UK rowwise hold-out (`uk_runtime.local_rowwise.rotated_uk_local_holdout`) and the US local hold-out (`microcosm.build.target_holdouts`, through the new `role_split`) both use them; the two draws stay apart on purpose (rotated folds over UK local target rows, hashed blocks over US units). No hold-out result changes: `test_holdout.py` holds the new functions to the replaced UK and US expressions byte for byte on float64 matrices, which is what both builds pass (a float32 matrix with float32 weights is widened before the product, where the replaced UK expression multiplied in float32), and the US hold-out tests compare with verbatim copies of the old tool code. The UK hold-out node now also hashes `microcosm.build.holdout`, which it ran without hashing, and the modules it reaches when it rebuilds the problem inputs: the declared level rule (`microcosm.calibrate.target_sets`, `uk_runtime.target_sets`) and the review core (`microcosm.build.declared_registers`). `test_uk_graph_terminal.py` pins these entries and the gate kernels' review-core entry. The UK hold-out keeps its constants (5 folds, seed 20260529, in `uk_runtime/local_rowwise.py`); a stricter UK hold-out would start there. diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_terminal.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_terminal.py index a7caeacd10..6eae2647c3 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_terminal.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_terminal.py @@ -1358,13 +1358,16 @@ class UKFullHoldoutKernel(KernelBase): def implementation_hash(self) -> str: import microcosm.build.holdout as shared_holdout import microcosm.calibrate.target_loss_rules as calibrate_target_loss_rules + import microcosm.calibrate.target_sets as calibrate_target_sets + from .. import declared_registers from . import ( dataset_size, graph_targets, local_doctrine, local_rowwise, national_doctrine, + target_sets, target_weights, ) from .solve_scope import uk_solve_fingerprint @@ -1386,6 +1389,14 @@ def implementation_hash(self) -> str: # The folds and the held rows' estimates # (fold_splits, held_estimates; microcosm#1759). shared_holdout, + # The holdout rebuilds the problem inputs + # (graph_targets.reconstruct_uk_full_problem_inputs): + # each row's level comes from the declared level rule + # (calibrate.target_sets through the UK adapter), and + # the support floor's window from the review core. + calibrate_target_sets, + target_sets, + declared_registers, dependencies=self.capabilities.dependencies, ), # The holdout repeats the solve: it keys on the solve diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_graph_terminal.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_graph_terminal.py index f1cc12f2c0..247b075523 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_graph_terminal.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_graph_terminal.py @@ -1602,3 +1602,67 @@ def test_the_dense_gates_refuse_references_of_two_builds() -> None: _require_one_reference( {"input_mass_reference": national, "reference_surface": national} ) + + +def _hashed_names(monkeypatch, module, kernel) -> set[str]: + """The names of the modules one kernel passes to ``source_hash``. + + The real hash is not called: it needs every declared dependency + installed, and the hold-out kernel declares the engine. + """ + + hashed: set[str] = set() + + def recording(*objects, **_options): + hashed.update(obj.__name__ for obj in objects) + return "recorded" + + monkeypatch.setattr(module, "source_hash", recording) + kernel.implementation_hash() + return hashed + + +def test_the_holdout_kernel_hashes_the_shared_code_it_runs(monkeypatch): + # The rotated holdout draws its folds and its held estimates in the + # shared hold-out module. It also rebuilds the problem inputs + # (graph_targets.reconstruct_uk_full_problem_inputs): each row's level + # comes from the declared level rule, and the support floor's window + # from the review core (microcosm#1759). The import-coverage test + # (test_uk_target_compile_modules) walks the target, problem and national + # kernels only, so this pins the hold-out kernel (the review of + # microcosm#1755). + from microcosm.build.uk_runtime import graph_terminal + + hashed = _hashed_names( + monkeypatch, graph_terminal, graph_terminal.UKFullHoldoutKernel() + ) + assert { + "microcosm.build.holdout", + "microcosm.calibrate.target_sets", + "microcosm.build.uk_runtime.target_sets", + "microcosm.build.declared_registers", + "microcosm.build.uk_runtime.graph_targets", + "microcosm.build.uk_runtime.local_rowwise", + } <= hashed + + +def test_every_gate_kernel_hashes_the_review_core(monkeypatch): + # The gates read the reviewed exclusions with the shared strict reader + # and review windows (weighted_integrity, microcosm#1759), so an edit to + # the review core alone re-keys every gate node. + from microcosm.build.uk_runtime import graph_national, graph_terminal + + core = "microcosm.build.declared_registers" + for kernel in ( + graph_terminal.UKFullGateKernel, + graph_terminal.UKFullPreflightGateKernel, + ): + hashed = _hashed_names( + monkeypatch, + graph_terminal, + kernel(coverage_engine=object(), engine_identity="fixture"), + ) + assert core in hashed, kernel.__name__ + assert core in _hashed_names( + monkeypatch, graph_national, graph_national.UKNationalGateKernel() + ) From 0f4b6e8ca4f5c06431041e85471dd6ee5f245895 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:10:05 +0000 Subject: [PATCH 24/30] State what the proofs of the shared target code cover Corrections from the review of microcosm#1755. They change texts and add one test; no code path changes. - held_estimates multiplies in float64. It gives the bytes of the replaced UK expression for a float64 matrix, which the UK problem matrix always is. A new test pins the float32 case, where the two differ. - The SOI clause of the local state and state_county modes reads a row's level as ledger_geography_level, else geography_level. The replaced filter read only ledger_geography_level. Every compiled row carries it. - The byte pins of test_us_acs_local_surface_bytes.py were measured after the declared selection replaced the selection code, so they hold the later moves only. - docs/us-target-sets.md lists the refusals that keep their texts and the three that differ. docs/uk-target-sets.md states the hold-out kernel's hash and the reader's error class. Part of microcosm#1728 and microcosm#1759. Co-Authored-By: Claude Fable 5.2 --- docs/uk-target-sets.md | 19 +++++++--- docs/us-target-sets.md | 35 +++++++++++++++++++ .../src/microcosm/build/holdout.py | 6 ++++ .../tests/engine_free/shared/test_holdout.py | 22 ++++++++++++ .../us/test_us_acs_local_surface_bytes.py | 7 +++- 5 files changed, 84 insertions(+), 5 deletions(-) diff --git a/docs/uk-target-sets.md b/docs/uk-target-sets.md index 2c52a47c21..bda55ad9db 100644 --- a/docs/uk-target-sets.md +++ b/docs/uk-target-sets.md @@ -86,7 +86,13 @@ The UK and US hold-outs keep different draws on purpose: Both now share the last two steps in `microcosm.build.holdout`: the `HoldoutSplit` type (`fold_splits` for the UK, `target_holdouts.role_split` -for the US) and `held_estimates`. +for the US) and `held_estimates`. `held_estimates` multiplies in float64. The +UK problem matrix is float64, so the UK estimates are the same bytes as +before. + +The UK hold-out node (`uk.full.rotated-holdout@1`) hashes the shared hold-out +module. It also hashes the modules it reaches when it rebuilds the problem +inputs: the declared level rule and the review core. The UK fold count and seed stay constants in `local_rowwise.py` (`UK_LOCAL_HOLDOUT_FOLDS`, `UK_LOCAL_HOLDOUT_SEED`), as María ruled on @@ -106,8 +112,10 @@ users are: - the reviewed exclusions of the target-fit, local target-fit and area-support gates (`uk_runtime/weighted_integrity.py`). -Each UK function keeps its error texts and decides what a lapse does: it -refuses a run, fails a gate, or reports. +Each UK function keeps its error texts and its error class, and decides what +a lapse does: it refuses a run, fails a gate, or reports. A gate that fails +closed records the class name of the error, so the reviewed-exclusion reader +still raises a plain `ValueError`. Not moved: @@ -137,7 +145,10 @@ the nesting work of microcosm#1760. - `test_holdout.py` compares the split and the held estimates with the replaced UK and US expressions, byte for byte. - `test_uk_review_loaders.py` and `test_uk_reviewed_exclusions_core.py` - compare the signed-entry loaders with verbatim copies of the old code. + compare the signed-entry loaders with verbatim copies of the old code, by + value, warning, error class and error text. +- `test_uk_graph_terminal.py` pins the shared modules in the hash of the + hold-out kernel and of each gate kernel. - `test_uk_target_surface_pins.py` pins the bytes of the UK target nodes' artifacts on the pinned Chronicle feed: the full surface, each selection and the national registry. diff --git a/docs/us-target-sets.md b/docs/us-target-sets.md index 04588220a9..37bc99b2dc 100644 --- a/docs/us-target-sets.md +++ b/docs/us-target-sets.md @@ -134,6 +134,16 @@ surface changes. On a feed with such rows at another level (for example county rows in the main feed), the declarations keep them out until a clause names the level. +The SOI clause of `state` and `state_county` reads a row's level as every +clause does: `ledger_geography_level`, else `geography_level`. The filter it +replaced read only `ledger_geography_level`. So a state SOI row that carries +only `geography_level` now enters these two modes. Every compiled row carries +`ledger_geography_level`, so no compiled registry changes. + +A declaration file is read strictly: a repeated JSON key, a non-finite number, +`"*"` inside a list of names and a version that is not the integer are +refused. + ## Rows the local tool builds, and its hold-outs `us/local_target_construction.json` declares how the ACS local release builds @@ -152,6 +162,31 @@ has at least `name`, `value`, `family` and `geography_level`. The role pass adds `holdout_unit` and `role`, and the training target set holds the training rows only. +### Refusals + +The targets, roles and receipts are the same as before the move. A refusal is +still a `ValueError`: the shared modules raise `TargetHoldoutError` and +`LadderPopulationError`, which are subclasses. The texts are the replaced +ones, and a declaration gives the words that name a level (`child_label` and +`parent_label` of a pass's scoring, `code_name` of a ladder level). One shared +check now serves both passes, so three cases differ from the replaced code: + +- The county pass's fraction refusal also names the value, as the district + pass's always did (`..., got 0.51.`). +- The district pass checks its salt before it reads a record, as the county + pass always did, and refuses with `CD holdout salt must be a non-empty + string.` The replaced district code left the salt to the hash of the first + eligible unit. +- The county scorer reads `role` on every record, as the district scorer + always did. The replaced county scorer skipped a record with no role. + +The command line checks the fractions and the salts before any of these, and +the district pass gives every record a role, so no run of the tool reaches a +changed case. `fraction=None` and `salt=None` are refused: only an omitted +argument draws with the declared value. `test_us_target_holdouts.py` and +`test_us_ladder_population.py` compare each refusal's text with the replaced +code and pin the three differences. + Two parts of the local surface are still tool code. The district SOI shares of `state_cd` (`tools/us_acs_local_cd_surface.py`) and the county rung (`tools/us_acs_local_county_surface.py`) make child rows as shares of parent diff --git a/packages/microcosm-build/src/microcosm/build/holdout.py b/packages/microcosm-build/src/microcosm/build/holdout.py index c739ad0c08..292ffc8c65 100644 --- a/packages/microcosm-build/src/microcosm/build/holdout.py +++ b/packages/microcosm-build/src/microcosm/build/holdout.py @@ -215,6 +215,12 @@ def held_estimates( in that order, as a solve that kept only some records needs. The matrix rows and the weights are widened to float64 before the product, so the result does not depend on their stored precision. + + This is the US expression. The UK expression it also replaced + (``matrix[rows][:, columns] @ weights``) multiplied in the stored + precision. The two give the same bytes when the matrix is float64, which + the UK problem matrix always is; they differ only for a float32 matrix + with float32 weights, which no build passes. """ held = matrix[rows] diff --git a/packages/microcosm-build/tests/engine_free/shared/test_holdout.py b/packages/microcosm-build/tests/engine_free/shared/test_holdout.py index ccaff9cf1d..18340e9edd 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_holdout.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_holdout.py @@ -107,6 +107,28 @@ def test_held_estimates_match_the_uk_expression(seed, weight_dtype) -> None: assert new.tobytes() == old.tobytes() +def test_held_estimates_widen_a_float32_matrix_before_the_product() -> None: + # The premise of the UK equality above: the UK problem matrix is float64. + # For a float32 matrix with float32 weights the replaced UK expression + # multiplied in float32 and the shared function multiplies in float64, so + # the bytes differ (the review of microcosm#1755). No build passes that. + from scipy import sparse + + from microcosm.build.holdout import held_estimates + + matrix = _sparse(3, (40, 60), np.float32, sparse.csr_matrix) + rows = np.arange(0, 40, 4, dtype=np.int64) + weights = np.random.default_rng(7).uniform(0.0, 5.0, size=60).astype(np.float32) + in_float32 = np.asarray(matrix[rows] @ weights, dtype=np.float64).reshape(-1) + in_float64 = np.asarray( + matrix[rows].astype(np.float64) @ weights.astype(np.float64) + ).reshape(-1) + new = held_estimates(matrix, rows, weights) + assert new.tobytes() == in_float64.tobytes() + assert new.tobytes() != in_float32.tobytes() + np.testing.assert_allclose(new, in_float32, rtol=1e-5) + + @pytest.mark.parametrize("seed", range(20)) @pytest.mark.parametrize("weight_dtype", [np.float64, np.float32]) def test_held_estimates_match_the_us_expression(seed, weight_dtype) -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_surface_bytes.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_surface_bytes.py index 79576aac9a..83ca5aeaf2 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_surface_bytes.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_surface_bytes.py @@ -17,7 +17,12 @@ gives the population rows a small household table that supports every ladder cell, and pins the rows' matrix on that table too. -The pins were measured at ``3316038cc``, before any code moved. They run only +The pins were measured at ``3316038cc``. That is after the declared target +sets replaced the selection code (``7f4006fff``), and before any other code +moved. So these bytes hold the later moves: the filter rules, the hold-outs, +the ladder rows and the compile registers. The declared selection itself is +held by ``test_us_target_sets.py``, whose registry versions, censuses and +receipts were measured on main before that change. The pins run only when ``MICROCOSM_US_CHRONICLE_FACTS`` names the pinned feed and ``MICROCOSM_US_PUMA_LADDER_ARTIFACT`` names the pinned PUMA ladder. The county mode (``state_county``) needs the pinned county facts and a household From 202b8252618a587ceba8c770528204fa76d1c19e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:10:06 +0000 Subject: [PATCH 25/30] Sort the US resource rows fiscal_target_registers.json was listed before fiscal_target_references.json, the one row of the 28 US JSON resources out of order (the review of microcosm#1755). The package list and the generator's list now agree on the sorted order. Both --check modes of the re-pin tools pass with no pin changed, so the order moves no spec-engine pin. Part of microcosm#1728. Co-Authored-By: Claude Fable 5.2 --- .../src/microcosm/build/us/country_package.json | 4 ++-- tools/generate_us_bundle_from_constants.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/us/country_package.json b/packages/microcosm-build/src/microcosm/build/us/country_package.json index 6a26bac48d..d1236341ed 100644 --- a/packages/microcosm-build/src/microcosm/build/us/country_package.json +++ b/packages/microcosm-build/src/microcosm/build/us/country_package.json @@ -98,12 +98,12 @@ "schema_id": "legacy_json" }, { - "path": "fiscal_target_registers.json", + "path": "fiscal_target_references.json", "kind": "legacy_json", "schema_id": "legacy_json" }, { - "path": "fiscal_target_references.json", + "path": "fiscal_target_registers.json", "kind": "legacy_json", "schema_id": "legacy_json" }, diff --git a/tools/generate_us_bundle_from_constants.py b/tools/generate_us_bundle_from_constants.py index dc9407b544..069c2b5da9 100644 --- a/tools/generate_us_bundle_from_constants.py +++ b/tools/generate_us_bundle_from_constants.py @@ -146,9 +146,9 @@ def _domain_builders() -> dict[str, Callable[[], object]]: "ecps_parity_known_gaps.json", "ecps_parity_reference.json", "federal_eitc_by_state.json", + "fiscal_target_references.json", # The reviewed registers of the US fiscal target compile (microcosm#1728). "fiscal_target_registers.json", - "fiscal_target_references.json", "gates.json", # The ACS local release's declared target construction (microcosm#1728). "local_target_construction.json", From ca2444289a8945dca7ca9b1211c534416e270e2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 11:54:51 +0000 Subject: [PATCH 26/30] Skip the UK target pins while the package pins another feed The digests of test_uk_target_surface_pins.py hold Chronicle feed 15040ea5, the UK input files of 38dbd0187 and review date 2026-11-26. Every pin passed at 9130ebe15, after the move to shared code: that is the proof of the move. Main has re-pinned the UK feed to e4d46c93 and renewed register entries with approval date 2026-11-27 (microcosm#1736). So the surface is different now, and the renewed entries are not in force on the old review date. The tests now skip, with the reason, while the package pins another feed than PINNED_FEED_COMMIT. To use them again, measure the surface, the selections and the national registry on the new feed, and set the feed commit, the review date and the digests together. Part of microcosm#1759. Co-Authored-By: Claude Fable 5.2 --- docs/uk-target-sets.md | 6 ++-- .../uk/test_uk_target_surface_pins.py | 33 +++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/docs/uk-target-sets.md b/docs/uk-target-sets.md index bda55ad9db..493a3b4f48 100644 --- a/docs/uk-target-sets.md +++ b/docs/uk-target-sets.md @@ -150,8 +150,10 @@ the nesting work of microcosm#1760. - `test_uk_graph_terminal.py` pins the shared modules in the hash of the hold-out kernel and of each gate kernel. - `test_uk_target_surface_pins.py` pins the bytes of the UK target nodes' - artifacts on the pinned Chronicle feed: the full surface, each selection - and the national registry. + artifacts on Chronicle feed `15040ea5`: the full surface, each selection + and the national registry. Every pin passed after the move. The digests + hold that feed, so the tests skip while the package pins another feed, + until the pins are measured again on it. ## What a UK build computes again diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_target_surface_pins.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_target_surface_pins.py index 95bdd5d596..2ac7716c6c 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_target_surface_pins.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_target_surface_pins.py @@ -17,6 +17,15 @@ selection tests can read a saved surface instead (``MICROCOSM_UK_TARGET_SURFACE``), which must have the pinned digest. The compile reads published Chronicle facts and the census ladder, not survey microdata, and the pins are digests. + +The digests hold one feed (``PINNED_FEED_COMMIT``), the UK input files of +``38dbd0187`` and one review date. At ``9130ebe15``, after the move, every +test passed on them: that is the proof of the move. A feed re-pin changes the +surface, and a renewed register entry is not in force on the old review date. +So when the package pins another feed, the tests skip: measure the surface, +the selections and the national registry again on the new feed (two compiles, +about two hours), and set ``PINNED_FEED_COMMIT``, ``REVIEW_DATE`` and the +digests together. """ from __future__ import annotations @@ -31,6 +40,9 @@ CALIBRATION_YEAR = 2025 REVIEW_DATE = "2026-11-26" +#: The Chronicle commit of the feed the pins were measured on: the +#: ``source_commit`` of ``uk/chronicle_feed.json`` at ``38dbd0187``. +PINNED_FEED_COMMIT = "15040ea53a131ee09f713459554f5f22a4afc6bd" #: (sha256, bytes) of each node's artifact at 38dbd0187. PINNED_SURFACE = ( @@ -165,7 +177,27 @@ def _context(*, artifacts=None, params=None, sources=None) -> SimpleNamespace: ) +def _packaged_feed_commit() -> str: + from importlib.resources import files + + pin = files("microcosm.build.uk").joinpath("chronicle_feed.json") + return json.loads(pin.read_text(encoding="utf-8"))["source_commit"] + + +def _require_the_measured_feed() -> None: + """Skip when the package pins another feed than the pins were measured on.""" + + packaged = _packaged_feed_commit() + if packaged != PINNED_FEED_COMMIT: + pytest.skip( + f"the pins were measured on feed {PINNED_FEED_COMMIT[:8]}, and the " + f"package now pins {packaged[:8]}: measure them again on the new " + "feed (see the module docstring)" + ) + + def _feed_and_ladder() -> tuple[str, str]: + _require_the_measured_feed() feed = os.environ.get("MICROCOSM_UK_CHRONICLE_FACTS", "") ladder = os.environ.get("MICROCOSM_UK_OA_LADDER", "") if not (feed and Path(feed).exists() and ladder and Path(ladder).is_file()): @@ -194,6 +226,7 @@ def compiled_surface() -> bytes: @pytest.fixture(scope="module") def surface(request) -> bytes: + _require_the_measured_feed() saved = os.environ.get("MICROCOSM_UK_TARGET_SURFACE", "") if saved and Path(saved).is_file(): payload = Path(saved).read_bytes() From 36d976c7b77ce0ac7bfc6e1072cdb4aa4ecb6ff5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:51:55 +0000 Subject: [PATCH 27/30] Declare the US level rule and record the rows left out by level From the review of microcosm#1755 (suggestions 1 and 2). One form for the level rule. us/target_sets.json now declares a level_rule, as the UK file does: the first of ledger_geography_level and geography_level that has a value, any level accepted. The shared reader loses the short level_keys form and target_level; target_set_census takes the rule. us_runtime.target_loss_weights.target_geography_level reads the declared rule in place of its own copy of that reading. A test holds it to a verbatim copy of the replaced code. On the pinned feed all 31,748 compiled targets set ledger_geography_level only, so no compiled target sets both level fields; a test pins that. A record of the rows left out by level. select_target_set counts, by family and level, the targets that an active clause names by family and that no such clause keeps at their level (left_out_by_level). The ACS local tool writes the counts in materialize_rss.json under target_levels_left_out, beside the SOI receipt, whose pinned bytes are equal. The assertion that could not fail (undeclared_cells on the kept rows) is replaced by a pin of the counts for each local mode: the country rows of the three families in every mode, and the district SOI rows in state and state_county. No target, order or pinned receipt changes. The US rule stays open: a closed rule and a refusal of an undeclared level add run-time refusals to a US build, and they are not in this commit. Co-Authored-By: Claude Fable 5.2 --- .../1728-one-level-rule-form.changed.md | 1 + .../1728-rows-left-out-by-level.added.md | 1 + ...59-uk-declared-target-selection.changed.md | 2 +- docs/us-target-sets.md | 50 ++++++- .../src/microcosm/build/us/target_sets.json | 13 +- .../build/us_runtime/target_loss_weights.py | 16 ++- .../microcosm/build/us_runtime/target_sets.py | 12 +- .../us/test_us_acs_local_county_surface.py | 1 + .../engine_free/us/test_us_target_sets.py | 113 +++++++++++++--- .../src/microcosm/calibrate/target_sets.py | 127 ++++++++---------- .../engine_free/shared/test_target_sets.py | 107 +++++++++++---- tools/build_us_acs_local_release.py | 26 +++- 12 files changed, 336 insertions(+), 133 deletions(-) create mode 100644 changelog.d/1728-one-level-rule-form.changed.md create mode 100644 changelog.d/1728-rows-left-out-by-level.added.md diff --git a/changelog.d/1728-one-level-rule-form.changed.md b/changelog.d/1728-one-level-rule-form.changed.md new file mode 100644 index 0000000000..c0aa2a9407 --- /dev/null +++ b/changelog.d/1728-one-level-rule-form.changed.md @@ -0,0 +1 @@ +Each country now declares how to read a target's geography level in one form, a `level_rule` (microcosm#1728, from the review of microcosm#1755). `us/target_sets.json` gives the US rule in full: the first of `ledger_geography_level` and `geography_level` that has a value, any level accepted. The short `level_keys` form is removed from `microcosm.calibrate.target_sets`, with `target_level`; `target_set_census` takes the rule. `us_runtime.target_loss_weights.target_geography_level` reads the declared rule in place of its own copy of that reading, so a US target has one level in the selection, in the loss weights and in the summaries. No level changes: `test_us_target_sets.py` holds the reader to a verbatim copy of the replaced code, and on the pinned feed every compiled target sets `ledger_geography_level` only. diff --git a/changelog.d/1728-rows-left-out-by-level.added.md b/changelog.d/1728-rows-left-out-by-level.added.md new file mode 100644 index 0000000000..cce035d8b4 --- /dev/null +++ b/changelog.d/1728-rows-left-out-by-level.added.md @@ -0,0 +1 @@ +A declared selection now records the rows it leaves out because of their level (microcosm#1728, from the review of microcosm#1755). `select_target_set` counts, by family and level, the targets that an active clause names by family and that no such clause keeps at their level (`TargetSetSelection.left_out_by_level`). The ACS local tool writes the counts in `materialize_rss.json` under `target_levels_left_out`. No target or receipt changes: the SOI receipt is as before, and `test_us_target_sets.py` pins the counts of each local mode on the pinned feed (the country rows of the three families in every mode, and the district SOI rows in `state` and `state_county`). diff --git a/changelog.d/1759-uk-declared-target-selection.changed.md b/changelog.d/1759-uk-declared-target-selection.changed.md index c92843f0d7..97d8c5c164 100644 --- a/changelog.d/1759-uk-declared-target-selection.changed.md +++ b/changelog.d/1759-uk-declared-target-selection.changed.md @@ -1 +1 @@ -The UK full build selects its solve surface with the shared declared target sets, as the US does (microcosm#1759). `uk/target_sets.json` declares the UK level rule (a target's level is `geography_level` or `ledger_geography_level`; the two must agree, and the level must be one of country, region, constituency, la and brma) and the full build's selection by level, one clause for each level. `microcosm.calibrate.target_sets` reads a declared `level_rule` (the US `level_keys` form is unchanged) and its new `select_by_levels` keeps the requested levels in compile order with the same receipt (`microcosm.calibrate.target-selection.v1`). `microcosm.calibrate.target_selection` is removed: the UK selection kernel was its only caller, and `uk_runtime.graph_targets.target_geography` now reads the declared rule. No selection changes: `test_uk_level_selection.py` holds the new code to verbatim copies of the removed selector and resolver on random registries, refusals included. The new UK resource is in the UK solve fingerprint, so the first UK build after this change computes the spine from `frs_brma` on, the target nodes and the national graph again. The two UK calibration lines are declared there too, as the modes of a `calibration_line` product: `uk_runtime.ledger_targets.uk_registry_on_calibration_line` selects through it with one UK predicate that reads each contract target's `calibration_lines`, which stay in `uk/uk_population_targets.json`; `UK_CALIBRATION_LINES` is the declared modes. The shared selector now reads a target's level only when a clause tests levels. `test_uk_calibration_line_selection.py` holds the line filter to a verbatim copy of the replaced function: the same registry (the same object when nothing drops), the same receipt, or the same refusal. +The UK full build selects its solve surface with the shared declared target sets, as the US does (microcosm#1759). `uk/target_sets.json` declares the UK level rule (a target's level is `geography_level` or `ledger_geography_level`; the two must agree, and the level must be one of country, region, constituency, la and brma) and the full build's selection by level, one clause for each level. `microcosm.calibrate.target_sets` reads a declared `level_rule` (the US file declares its rule in the same form) and its new `select_by_levels` keeps the requested levels in compile order with the same receipt (`microcosm.calibrate.target-selection.v1`). `microcosm.calibrate.target_selection` is removed: the UK selection kernel was its only caller, and `uk_runtime.graph_targets.target_geography` now reads the declared rule. No selection changes: `test_uk_level_selection.py` holds the new code to verbatim copies of the removed selector and resolver on random registries, refusals included. The new UK resource is in the UK solve fingerprint, so the first UK build after this change computes the spine from `frs_brma` on, the target nodes and the national graph again. The two UK calibration lines are declared there too, as the modes of a `calibration_line` product: `uk_runtime.ledger_targets.uk_registry_on_calibration_line` selects through it with one UK predicate that reads each contract target's `calibration_lines`, which stay in `uk/uk_population_targets.json`; `UK_CALIBRATION_LINES` is the declared modes. The shared selector now reads a target's level only when a clause tests levels. `test_uk_calibration_line_selection.py` holds the line filter to a verbatim copy of the replaced function: the same registry (the same object when nothing drops), the same receipt, or the same refusal. diff --git a/docs/us-target-sets.md b/docs/us-target-sets.md index 37bc99b2dc..de0e7a319c 100644 --- a/docs/us-target-sets.md +++ b/docs/us-target-sets.md @@ -56,11 +56,29 @@ Each mode states three things: `uk/local_target_reference_membership.json`) give a signed rationale for each exclusion. -A target's family is its `TargetSpec.family`. Its level is its -`ledger_geography_level`, else its `geography_level`. These are the labels -that the shared target-loss rule reads (microcosm#1729), so a target has one -family and one level everywhere. The US levels are `country`, `state`, -`congressional_district` and `county`. +A target's family is its `TargetSpec.family`. Its level comes from the level +rule that the file declares, in the form the UK file uses: + +```json +"level_rule": { + "keys": ["ledger_geography_level", "geography_level"], + "values": "*", + "conflict": "first" +} +``` + +- The level is the first of the two keys that has a value. A compiled target + names its level in `ledger_geography_level`. A row that a tool builds from + the PUMA ladder or the county facts names it in `geography_level`. +- The rule is open (`"values": "*"`): it accepts any level, and a target with + neither key has the level `unspecified`. + +The target-loss rows read the same rule +(`us_runtime.target_loss_weights.target_geography_level`, microcosm#1729), so +a target has one family and one level everywhere. The US levels are +`country`, `state`, `congressional_district` and `county`. On the pinned feed +every compiled target sets `ledger_geography_level` only, so the two keys of a +compiled target cannot disagree; `test_us_target_sets.py` holds that. ## What the declarations select @@ -134,6 +152,28 @@ surface changes. On a feed with such rows at another level (for example county rows in the main feed), the declarations keep them out until a clause names the level. +### Rows left out by level + +A clause that lists levels drops the rows of its families at every other +level. The selection counts those rows by family and level +(`TargetSetSelection.left_out_by_level`), and the local tool writes the counts +in `materialize_rss.json`, under `target_levels_left_out`, beside the SOI +receipt. So a row that a mode does not keep because of its level leaves a +record. On the pinned feed: + +| Family | Level | Rows | Left out by | +|---|---|---:|---| +| `usda_snap` | `country` | 2 | every local mode | +| `cms_medicaid` | `country` | 3 | every local mode | +| `irs_soi` | `country` | 441 | every local mode | +| `irs_soi` | `congressional_district` | 22,996 | `state` and `state_county` | + +`test_us_target_sets.py` pins these counts for each mode. After a feed re-pin, +a row of one of the three families at a new level (for example a county SNAP +row) is a new line in the record and a failure of that test, which runs with +the pinned feed. The national modes list no level, so they leave no row out +by level. + The SOI clause of `state` and `state_county` reads a row's level as every clause does: `ledger_geography_level`, else `geography_level`. The filter it replaced read only `ledger_geography_level`. So a state SOI row that carries diff --git a/packages/microcosm-build/src/microcosm/build/us/target_sets.json b/packages/microcosm-build/src/microcosm/build/us/target_sets.json index 477e275dc4..5b88a8bdc4 100644 --- a/packages/microcosm-build/src/microcosm/build/us/target_sets.json +++ b/packages/microcosm-build/src/microcosm/build/us/target_sets.json @@ -2,10 +2,15 @@ "version": 1, "country": "us", "description": "The targets each US release calibrates to, for each product and mode: the compiled families and levels it keeps, the tests that pick them, and the rows the tool builds itself (microcosm#1728). microcosm.calibrate.target_sets reads this file; docs/us-target-sets.md explains it.", - "level_keys": [ - "ledger_geography_level", - "geography_level" - ], + "level_rule": { + "keys": [ + "ledger_geography_level", + "geography_level" + ], + "values": "*", + "conflict": "first", + "rationale": "A compiled US target names its level in the Ledger's metadata (ledger_geography_level). A row that a tool builds from the PUMA ladder or the county facts names it in its local metadata (geography_level). The first key that has a value gives the level, and a target with neither has the level unspecified. The target-loss rows read this rule too (us_runtime.target_loss_weights.target_geography_level, microcosm#1729), so a US target has one level everywhere." + }, "products": { "national": { "tool": "tools/build_us_fiscal_refresh_release.py", diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/target_loss_weights.py b/packages/microcosm-build/src/microcosm/build/us_runtime/target_loss_weights.py index f25a04b881..819daca27d 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/target_loss_weights.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/target_loss_weights.py @@ -76,6 +76,8 @@ value_basis_weights, ) +from .target_sets import us_target_level + #: The loss formula's identifier, recorded in release diagnostics. US_FISCAL_TARGET_LOSS_WEIGHTING = ( "sqrt_value_concept_budget_weighted_mape_50_50_amount_count_target_scale_cap_100pct" @@ -769,14 +771,14 @@ def target_loss_weights_sha256(names: Sequence[str], weights: np.ndarray) -> str def target_geography_level(spec) -> str: - """A spec's geography level for summaries (ledger or ladder metadata).""" + """A spec's geography level, by the level rule of ``us/target_sets.json``. - metadata = spec.metadata - return str( - metadata.get("ledger_geography_level") - or metadata.get("geography_level") - or "unspecified" - ) + The declared target sets place a target by the same rule + (:func:`~.target_sets.us_target_level`), so a US target has one level in + the selection, in the loss weights and in the summaries. + """ + + return us_target_level(spec) def target_loss_weight_distribution( diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/target_sets.py b/packages/microcosm-build/src/microcosm/build/us_runtime/target_sets.py index c91cec5592..c77f8ee91b 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/target_sets.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/target_sets.py @@ -5,7 +5,9 @@ ``--target-surface``) and the ACS local release (``tools/build_us_acs_local_release.py``, ``--soi-mode``). The shared reader and selector are in :mod:`microcosm.calibrate.target_sets`; this module names -the US file, products, predicates and rules. +the US file, products, predicates and rules. The file also declares the US +level rule, which gives every US target its geography level; the UK declares +its rule the same way, in ``uk/target_sets.json`` (microcosm#1759). """ from __future__ import annotations @@ -13,6 +15,7 @@ from functools import lru_cache from importlib.resources import files from pathlib import Path +from typing import Any from microcosm.calibrate.target_sets import ( TargetSetDeclaration, @@ -26,6 +29,7 @@ "NATIONAL_PRODUCT", "STATE_CD_RULE", "US_TARGET_SETS_RESOURCE", + "us_target_level", "us_target_set_declaration", "us_target_set_declarations", "us_target_sets_path", @@ -56,3 +60,9 @@ def us_target_set_declarations() -> TargetSetDeclarations: def us_target_set_declaration(product: str, mode: str) -> TargetSetDeclaration: return us_target_set_declarations().declaration(product, mode) + + +def us_target_level(spec: Any) -> str: + """A US target's geography level, by the declared level rule.""" + + return us_target_set_declarations().level_rule.level_of(spec) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py index c10e552da9..ae12fdf5ba 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py @@ -934,6 +934,7 @@ def _materialize_county_fixture( registry=TargetRegistry(parents, country="us"), ri_substitutions=[], soi_receipt={}, + levels_left_out=[], ) populations = { "state": {1: 200.0}, diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_target_sets.py b/packages/microcosm-build/tests/engine_free/us/test_us_target_sets.py index 77208e929f..deccdc1daf 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_target_sets.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_target_sets.py @@ -52,6 +52,27 @@ "state_cd": (26_425, "e0bb302e3add"), "state_county": (4_380, "0ee16ca42be5"), } +#: The compiled targets of the local families that each local mode leaves out +#: because of their level, on the pinned feed: (family, level) -> targets. +#: No local mode keeps a country row. The ``state`` and ``state_county`` +#: modes also leave out every district row of IRS SOI: the district file's +#: rows, and the 324 district rows of the Historic Table 2 record set. +_COUNTRY_ROWS_LEFT_OUT = { + ("cms_medicaid", "country"): 3, + ("irs_soi", "country"): 441, + ("usda_snap", "country"): 2, +} +_STATE_ROWS_LEFT_OUT = { + **_COUNTRY_ROWS_LEFT_OUT, + ("irs_soi", "congressional_district"): 22_996, +} +PINNED_LOCAL_LEVELS_LEFT_OUT = { + "state": _STATE_ROWS_LEFT_OUT, + "totals": _COUNTRY_ROWS_LEFT_OUT, + "full": _COUNTRY_ROWS_LEFT_OUT, + "state_cd": _COUNTRY_ROWS_LEFT_OUT, + "state_county": _STATE_ROWS_LEFT_OUT, +} #: The national_state surface by family and level: every compiled family's #: country and state rows; the district file's 49 country and 2,601 state #: rows and every district row are out. @@ -167,7 +188,10 @@ def test_every_local_mode_declares_the_families_option_clauses( def test_the_declared_names_are_the_ones_the_code_uses(local_tool) -> None: declarations = us_target_set_declarations() - assert declarations.level_keys == ("ledger_geography_level", "geography_level") + assert declarations.level_rule.keys == ( + "ledger_geography_level", + "geography_level", + ) national_state = declarations.declaration(NATIONAL_PRODUCT, "national_state") assert national_state.compiled[0].exclude == (CONGRESSIONAL_DISTRICT_PREDICATE,) for mode in ("state", "state_county"): @@ -196,7 +220,7 @@ def test_ladder_population_rows_have_the_declared_family_and_levels( local_tool, ) -> None: built = us_target_set_declaration(LOCAL_PRODUCT, "state").built_rows("population") - level_keys = us_target_set_declarations().level_keys + level_rule = us_target_set_declarations().level_rule populations = {"state": {6: 39_000_000.0}, "cd": {601: 760_000.0}} specs = local_tool.ladder_population_target_specs(populations, ["state", "cd"]) @@ -204,14 +228,7 @@ def test_ladder_population_rows_have_the_declared_family_and_levels( "pop_county_06001", 1_600_000.0, period=local_tool.PERIOD ) - from microcosm.build.us_runtime.target_loss_weights import ( - target_geography_level, - ) - from microcosm.calibrate.target_sets import target_level - - for spec in (*specs, county): - assert target_level(spec, level_keys) == target_geography_level(spec) - census = target_set_census((*specs, county), level_keys) + census = target_set_census((*specs, county), level_rule) assert census == { (built.family, built.levels["state"]): 1, (built.family, built.levels["cd"]): 1, @@ -219,6 +236,50 @@ def test_ladder_population_rows_have_the_declared_family_and_levels( } +def _target_geography_level_before_the_declared_rule(spec) -> str: + """``target_loss_weights.target_geography_level`` as it was in code, before + it read the level rule of ``us/target_sets.json`` (a verbatim copy).""" + + metadata = spec.metadata + return str( + metadata.get("ledger_geography_level") + or metadata.get("geography_level") + or "unspecified" + ) + + +@pytest.mark.parametrize( + "metadata", + [ + {"ledger_geography_level": "state"}, + {"geography_level": "county"}, + {"ledger_geography_level": "state", "geography_level": "state"}, + {"ledger_geography_level": "state", "geography_level": "county"}, + {"ledger_geography_level": "", "geography_level": "county"}, + {"ledger_geography_level": None, "geography_level": ""}, + {"ledger_geography_level": "parish"}, + {}, + ], +) +def test_the_target_loss_rows_read_the_declared_level_rule(metadata) -> None: + """The declared rule reads a level as the target-loss code did.""" + + from types import SimpleNamespace + + from microcosm.build.us_runtime.target_loss_weights import ( + target_geography_level, + ) + from microcosm.build.us_runtime.target_sets import us_target_level + + spec = SimpleNamespace(name="row", family="irs_soi", metadata=metadata) + + assert ( + target_geography_level(spec) + == us_target_level(spec) + == _target_geography_level_before_the_declared_rule(spec) + ) + + def test_the_soi_predicate_is_the_declared_clause(local_tool) -> None: """``soi_surface_predicate`` reads the declaration, whatever the mode.""" @@ -273,25 +334,33 @@ def pinned_compile(local_tool): def test_pinned_feed_levels_are_the_target_loss_levels(pinned_compile) -> None: """Every compiled target has the level the target-loss rows read - (``target_loss_weights.target_geography_level``, microcosm#1729).""" + (``target_loss_weights.target_geography_level``, microcosm#1729), and it + names that level in the Ledger's key alone, so the two level keys of a + compiled target cannot disagree.""" from microcosm.build.us_runtime.target_loss_weights import ( target_geography_level, ) - from microcosm.calibrate.target_sets import target_level _feed, registry = pinned_compile - level_keys = us_target_set_declarations().level_keys + rule = us_target_set_declarations().level_rule assert all( - target_level(spec, level_keys) == target_geography_level(spec) + rule.level_of(spec) + == target_geography_level(spec) + == _target_geography_level_before_the_declared_rule(spec) for spec in registry.specs ) - assert {target_level(spec, level_keys) for spec in registry.specs} == { + assert {rule.level_of(spec) for spec in registry.specs} == { "country", "state", "congressional_district", } + keys_held = { + tuple(bool(spec.metadata.get(key)) for key in rule.keys) + for spec in registry.specs + } + assert keys_held == {(True, False)} def test_pinned_feed_national_surfaces_are_unchanged( @@ -308,9 +377,8 @@ def test_pinned_feed_national_surfaces_are_unchanged( ), mode assert receipt["calibrated_targets"] == count declaration = us_target_set_declaration(NATIONAL_PRODUCT, mode) - assert undeclared_cells(declaration, kept) == {} if mode == "national_state": - census = target_set_census(kept, declaration.level_keys) + census = target_set_census(kept, declaration.level_rule) assert census == PINNED_NATIONAL_STATE_CENSUS assert receipt["dropped_congressional_district_targets"] == ( len(registry.specs) - count @@ -325,8 +393,15 @@ def test_pinned_feed_local_surfaces_are_unchanged(pinned_compile, local_tool) -> surface = local_tool.state_admin_surface(feed, families, soi_mode=mode) specs = surface.registry.specs assert (len(specs), surface.registry.version) == (count, version), mode - declaration = us_target_set_declaration(LOCAL_PRODUCT, mode) - assert undeclared_cells(declaration, specs) == {}, mode + # Every compiled row of the three families is kept or is in the + # record of the rows left out by level, with nothing else at a level + # the mode does not list. + left_out = { + (record["family"], record["geography_level"]): record["targets"] + for record in surface.levels_left_out + } + assert left_out == PINNED_LOCAL_LEVELS_LEFT_OUT[mode], mode + assert len(left_out) == len(surface.levels_left_out), mode assert surface.soi_receipt["soi_mode"] == mode if mode != "state_cd": soi = sum(spec.family == "irs_soi" for spec in specs) diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py b/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py index e2782ecc69..41b95f5a29 100644 --- a/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py @@ -11,7 +11,12 @@ { "version": 1, "country": "", - "level_keys": ["", ...], + "level_rule": { + "keys": ["", ...], + "values": ["", ...] or "*", + "conflict": "first" or "refuse", + "rationale": "" + }, "products": { "": { "tool": "", @@ -28,26 +33,18 @@ } } -**Families and levels.** A target's family is ``spec.family``. Its level is -the first truthy value of the ``level_keys`` in its metadata, else -``"unspecified"``. These are the labels the shared target-loss rule reads -(``microcosm.calibrate.target_loss_rules``, microcosm#1729), so a target has -one family and one level everywhere. - -A declaration can give a ``level_rule`` in place of ``level_keys``:: - - "level_rule": { - "keys": ["", ...], - "values": ["", ...] or "*", - "conflict": "first" or "refuse", - "rationale": "" - } +**Families and levels.** A target's family is ``spec.family``. Its level +comes from the country's ``level_rule``: the first truthy value of the rule's +``keys`` in the target's metadata. These are the labels the shared +target-loss rule reads (``microcosm.calibrate.target_loss_rules``, +microcosm#1729), so a target has one family and one level everywhere, and +each country states its reading in one form. ``values`` closes the set of levels: a target whose level is not one of them, -or that has no level, is refused. With ``"conflict": "refuse"``, a target -whose keys hold two different levels is refused; with ``"first"``, the first -key that has a value gives the level. ``level_keys`` is the short form of a -rule with ``"values": "*"`` and ``"conflict": "first"``. +or that has no level, is refused. With ``"values": "*"`` any level is +accepted, and a target with no level has the level ``"unspecified"``. With +``"conflict": "refuse"``, a target whose keys hold two different levels is +refused; with ``"first"``, the first key that has a value gives the level. **Compiled clauses.** A clause keeps the compiled specs that pass all of its tests, in compile order: @@ -70,6 +67,13 @@ clause in declaration order. A spec that two clauses keep is an error in the declaration. +**Rows left out by level.** A clause that lists ``levels`` drops the targets +of its families at every other level. The selection counts them by family and +level (``left_out_by_level``), so a target that a product does not keep +because of its level leaves a record: a target is counted when an active +clause names its family and no active clause that names its family keeps its +level. A tool writes the counts in its receipt. + **Built rows.** A tool also makes rows that are not compiled (for example population marginals from a ladder). A ``built`` entry names their family and the level that each value of its option gives, so that the declaration states @@ -122,7 +126,6 @@ "load_target_set_declarations", "select_by_levels", "select_target_set", - "target_level", "target_set_census", "undeclared_cells", ] @@ -134,10 +137,7 @@ LEVEL_CONFLICTS = ("first", "refuse") #: The receipt schema of :func:`select_by_levels`. SELECTION_RECEIPT_SCHEMA = "microcosm.calibrate.target-selection.v1" - -_TOP_KEYS = frozenset( - {"version", "country", "description", "level_keys", "level_rule", "products"} -) +_TOP_KEYS = frozenset({"version", "country", "description", "level_rule", "products"}) _LEVEL_RULE_KEYS = frozenset({"keys", "values", "conflict", "rationale"}) _PRODUCT_KEYS = frozenset({"tool", "option", "default_mode", "modes"}) _MODE_KEYS = frozenset({"description", "compiled", "built"}) @@ -160,17 +160,6 @@ class TargetSetDeclarationError(ValueError): # --------------------------------------------------------------------------- -def target_level(spec: Any, level_keys: Sequence[str]) -> str: - """A spec's level: the first truthy ``level_keys`` value, else unspecified.""" - - metadata = spec.metadata - for key in level_keys: - value = metadata.get(key) - if value: - return str(value) - return UNSPECIFIED_LEVEL - - @dataclass(frozen=True) class LevelRule: """How a target's level is read from its metadata (see the module docstring). @@ -188,8 +177,6 @@ class LevelRule: rationale: str = "" def level_of(self, spec: Any) -> str: - if self.values is None and self.conflict == "first": - return target_level(spec, self.keys) held = [spec.metadata.get(key) for key in self.keys] if self.conflict == "refuse": present = [value for value in held if value] @@ -279,11 +266,10 @@ class TargetSetDeclaration: product: str mode: str description: str - level_keys: tuple[str, ...] + #: The country's level rule, the same one for every product and mode. + level_rule: LevelRule compiled: tuple[TargetSetClause, ...] built: tuple[BuiltRows, ...] - #: The country's level rule; ``None`` reads ``level_keys`` alone. - level_rule: LevelRule | None = None @property def clause_ids(self) -> tuple[str, ...]: @@ -307,9 +293,7 @@ def built_rows(self, built_id: str) -> BuiltRows: ) def level_of(self, spec: Any) -> str: - if self.level_rule is not None: - return self.level_rule.level_of(spec) - return target_level(spec, self.level_keys) + return self.level_rule.level_of(spec) @dataclass(frozen=True) @@ -341,9 +325,8 @@ class TargetSetDeclarations: """Every product's declared target sets for one country.""" country: str - level_keys: tuple[str, ...] + level_rule: LevelRule products: Mapping[str, ProductDeclaration] - level_rule: LevelRule | None = None def product(self, name: str) -> ProductDeclaration: try: @@ -448,17 +431,8 @@ def _clause(where: str, raw: object) -> TargetSetClause: def _level_rule(where: str, top: Mapping[str, Any]) -> LevelRule: - """The declaration's level rule: ``level_rule``, or the ``level_keys`` form.""" + """The country's level rule.""" - if ("level_keys" in top) == ("level_rule" in top): - raise _fail(where, "give exactly one of level_keys and level_rule.") - if "level_keys" in top: - level_keys = top["level_keys"] - if not isinstance(level_keys, list) or not level_keys: - raise _fail( - f"{where}.level_keys", "must be a nonempty list of metadata keys." - ) - return LevelRule(tuple(_text(f"{where}.level_keys", key) for key in level_keys)) at = f"{where}.level_rule" rule = _require_keys(at, top["level_rule"], _LEVEL_RULE_KEYS, _LEVEL_RULE_KEYS) keys = rule["keys"] @@ -541,12 +515,13 @@ def load_target_set_declarations( else: path = Path(source) raw, where = _read_declaration_file(path), str(path) - top = _require_keys(where, raw, _TOP_KEYS, ("version", "country", "products")) + top = _require_keys( + where, raw, _TOP_KEYS, ("version", "country", "level_rule", "products") + ) if type(top["version"]) is not int or top["version"] != DECLARATION_VERSION: raise _fail(where, f"version must be {DECLARATION_VERSION}.") country = _text(f"{where}.country", top["country"]) level_rule = _level_rule(where, top) - level_keys = level_rule.keys products_raw = top["products"] if not isinstance(products_raw, Mapping) or not products_raw: raise _fail(f"{where}.products", "must name at least one product.") @@ -587,10 +562,9 @@ def load_target_set_declarations( product=product_name, mode=mode_name, description=_text(f"{mode_at}.description", mode["description"]), - level_keys=level_keys, + level_rule=level_rule, compiled=compiled, built=built, - level_rule=level_rule, ) default_mode = _text(f"{at}.default_mode", product["default_mode"]) if default_mode not in modes: @@ -606,9 +580,8 @@ def load_target_set_declarations( ) return TargetSetDeclarations( country=country, - level_keys=level_keys, - products=MappingProxyType(products), level_rule=level_rule, + products=MappingProxyType(products), ) @@ -625,6 +598,10 @@ class TargetSetSelection: specs: tuple[Any, ...] clause_counts: Mapping[str, int] rule_receipts: Mapping[str, Any] + #: The input specs that the active clauses name by family and that none + #: of those clauses keeps because of its level, counted by (family, + #: level) and sorted. Empty when no active clause lists levels. + left_out_by_level: Mapping[tuple[str, str], int] def select_target_set( @@ -642,7 +619,8 @@ def select_target_set( the rule. The selection is the clauses' outputs in declaration order. A spec's level is read only when an active clause tests levels, so a closed level rule refuses only the specs that a selection places by - level. + level. The selection also counts the specs that the active clauses leave + out because of their level (``left_out_by_level``). Raises: KeyError: If ``clause_ids`` names a clause the declaration lacks. @@ -676,8 +654,20 @@ def select_target_set( ) # A level is read only when a clause tests levels, so a closed level rule # does not refuse a target that no active clause places by level. + left_out: Counter[tuple[str, str]] = Counter() if any(clause.levels is not None for clause in clauses): levels = [declaration.level_of(spec) for spec in specs] + for spec, level in zip(specs, levels, strict=True): + naming = [ + clause + for clause in clauses + if clause.families is None or spec.family in clause.families + ] + if naming and all( + clause.levels is not None and level not in clause.levels + for clause in naming + ): + left_out[(str(spec.family), level)] += 1 else: levels = [UNSPECIFIED_LEVEL] * len(specs) kept: list[Any] = [] @@ -706,6 +696,7 @@ def select_target_set( specs=tuple(kept), clause_counts=MappingProxyType(counts), rule_receipts=MappingProxyType(receipts), + left_out_by_level=MappingProxyType(dict(sorted(left_out.items()))), ) @@ -735,7 +726,7 @@ def _require_level_mode(declaration: TargetSetDeclaration) -> None: at = f"{declaration.product}/{declaration.mode}" rule = declaration.level_rule - if rule is None or rule.values is None: + if rule.values is None: raise TargetSetDeclarationError( f"{at}: selection by level needs a level_rule with a closed set of values." ) @@ -870,13 +861,11 @@ def accepted(spec: Any) -> bool: def target_set_census( - specs: Iterable[Any], level_keys: Sequence[str] + specs: Iterable[Any], level_rule: LevelRule ) -> dict[tuple[str, str], int]: - """Spec counts by (family, level), sorted.""" + """Spec counts by (family, level), sorted; the rule gives each level.""" - census = Counter( - (str(spec.family), target_level(spec, level_keys)) for spec in specs - ) + census = Counter((str(spec.family), level_rule.level_of(spec)) for spec in specs) return dict(sorted(census.items())) @@ -901,5 +890,5 @@ def declared(family: str, level: str) -> bool: for built in declaration.built ) - census = target_set_census(specs, declaration.level_keys) + census = target_set_census(specs, declaration.level_rule) return {cell: n for cell, n in census.items() if not declared(*cell)} diff --git a/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py b/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py index e2abcba253..93644bb013 100644 --- a/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py +++ b/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py @@ -15,7 +15,6 @@ load_target_set_declarations, select_by_levels, select_target_set, - target_level, target_set_census, undeclared_cells, ) @@ -38,7 +37,12 @@ def _spec(name: str, family: str, **metadata) -> SimpleNamespace: DECLARATIONS = { "version": 1, "country": "test", - "level_keys": ["level", "geo"], + "level_rule": { + "keys": ["level", "geo"], + "values": "*", + "conflict": "first", + "rationale": "r", + }, "products": { "national": { "tool": "tools/national.py", @@ -149,7 +153,7 @@ def test_declarations_load_from_a_file_and_name_products_and_modes(tmp_path) -> declarations = load_target_set_declarations(path) assert declarations.country == "test" - assert declarations.level_keys == ("level", "geo") + assert declarations.level_rule.keys == ("level", "geo") assert tuple(declarations.products) == ("national", "local") local = declarations.product("local") assert local.option == "--mode" @@ -198,7 +202,9 @@ def test_a_file_with_a_repeated_key_or_a_non_finite_number_is_refused( # True equals 1 in Python; a version is the integer. ({"version": True}, "version must be 1"), ({"extra": True}, "unknown keys"), - ({"level_keys": []}, "level_keys"), + ({"level_rule__keys": []}, "nonempty list of metadata keys"), + # The short form of the rule is gone: a country gives the rule in full. + ({"level_keys": ["level", "geo"]}, "unknown keys"), ({"products__local__default_mode": "county"}, "not a declared mode"), ({"products__local__modes__state__compiled": []}, "at least one clause"), ( @@ -247,11 +253,11 @@ def test_a_malformed_declaration_is_refused(changes, message) -> None: def test_a_level_is_the_first_truthy_level_key() -> None: - keys = ("level", "geo") + rule = _declarations().level_rule - assert target_level(_spec("a", "f", level="state", geo="district"), keys) == "state" - assert target_level(_spec("b", "f", level="", geo="district"), keys) == "district" - assert target_level(_spec("c", "f"), keys) == UNSPECIFIED_LEVEL + assert rule.level_of(_spec("a", "f", level="state", geo="district")) == "state" + assert rule.level_of(_spec("b", "f", level="", geo="district")) == "district" + assert rule.level_of(_spec("c", "f")) == UNSPECIFIED_LEVEL def test_wildcards_keep_every_spec_in_compile_order() -> None: @@ -310,6 +316,52 @@ def test_clause_ids_turn_on_only_some_clauses() -> None: select_target_set(declaration, SPECS, clause_ids=["tax", "snap"]) +def test_a_selection_counts_the_specs_it_leaves_out_by_level() -> None: + """A clause drops the rows of its family at a level it does not list; the + selection records them by family and level.""" + + declarations = _declarations() + state = declarations.declaration("local", "state") + county_benefit = _spec("county_benefit", "benefit", level="county", state="06") + specs = (*SPECS, county_benefit) + + selection = select_target_set(state, specs) + + assert "county_benefit" not in _names(selection.specs) + assert dict(selection.left_out_by_level) == { + ("benefit", "county"): 1, + ("tax", "country"): 1, + ("tax", "district"): 1, + } + assert list(selection.left_out_by_level) == sorted(selection.left_out_by_level) + # A row that fails another test at a kept level is not left out by level: + # ca_tax is a state row with the role "band". + assert "ca_tax" not in _names(selection.specs) + + # Only the active clauses count. + only_tax = select_target_set(state, specs, clause_ids=["tax"]) + assert dict(only_tax.left_out_by_level) == { + ("tax", "country"): 1, + ("tax", "district"): 1, + } + # A mode that lists no level reads no level and leaves none out. + everything = select_target_set(declarations.declaration("national", "all"), specs) + assert dict(everything.left_out_by_level) == {} + + # With one clause for each level, a subset of the clauses leaves out the + # rows of the other levels, and every clause together leaves out none. + level_mode = _level_mode() + rows = ( + _spec("a", "tax", level="country"), + _spec("b", "tax", level="la"), + _spec("c", "benefit", geo="la"), + ) + subset = select_target_set(level_mode, rows, clause_ids=["country"]) + assert _names(subset.specs) == ["a"] + assert dict(subset.left_out_by_level) == {("benefit", "la"): 1, ("tax", "la"): 1} + assert dict(select_target_set(level_mode, rows).left_out_by_level) == {} + + def test_a_rule_takes_its_clause_specs_and_returns_specs_and_a_receipt() -> None: declaration = _declarations().declaration("local", "shares") seen = [] @@ -384,7 +436,7 @@ def test_census_and_undeclared_cells() -> None: _spec("pop_county", "population", geo="county"), ) - census = target_set_census(specs, declaration.level_keys) + census = target_set_census(specs, declaration.level_rule) assert census[("tax", "state")] == 4 assert census[("population", "district")] == 1 @@ -491,12 +543,19 @@ def test_an_open_rule_and_the_first_conflict_rule() -> None: assert open_rule.level_of(_spec("c", "tax", geo="nation")) == "nation" with pytest.raises(ValueError, match="contradictory"): open_rule.level_of(_spec("d", "tax", level="la", geo="region")) - # The level_keys form reads exactly as target_level does. - keys_form = _declarations().declaration("national", "all") - assert keys_form.level_rule.values is None - assert keys_form.level_rule.conflict == "first" - for spec in SPECS: - assert keys_form.level_of(spec) == target_level(spec, ("level", "geo")) + # An open rule with "first" reads the first key that has a value. + open_first = _declarations().declaration("national", "all") + assert open_first.level_rule.values is None + assert open_first.level_rule.conflict == "first" + assert [open_first.level_of(spec) for spec in SPECS] == [ + "country", + "state", + "state", + "state", + "district", + "state", + "state", + ] @pytest.mark.parametrize( @@ -515,15 +574,15 @@ def test_a_malformed_level_rule_is_refused(rule, message) -> None: load_target_set_declarations(_level_declarations(**rule)) -def test_a_declaration_gives_exactly_one_level_form() -> None: - both = _level_declarations() - both["level_keys"] = ["level"] - with pytest.raises(TargetSetDeclarationError, match="exactly one of"): - load_target_set_declarations(both) - neither = _level_declarations() - del neither["level_rule"] - with pytest.raises(TargetSetDeclarationError, match="exactly one of"): - load_target_set_declarations(neither) +def test_a_declaration_needs_a_level_rule() -> None: + short_form = _level_declarations() + short_form["level_keys"] = ["level"] + with pytest.raises(TargetSetDeclarationError, match="unknown keys"): + load_target_set_declarations(short_form) + no_rule = _level_declarations() + del no_rule["level_rule"] + with pytest.raises(TargetSetDeclarationError, match="missing keys"): + load_target_set_declarations(no_rule) def test_select_by_levels_keeps_compile_order_and_lists_every_target() -> None: diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index c8cb74331f..5914866e70 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -737,12 +737,24 @@ def state_admin_specs( class AdminSurface: - """The compiled admin registry plus how its SOI slice was chosen.""" + """The compiled admin registry plus how its SOI slice was chosen. - def __init__(self, registry, ri_substitutions, soi_receipt: dict) -> None: + ``levels_left_out`` lists the compiled targets of the selected families + that the mode does not keep because of their level: one record for each + family and level, with the number of targets. + """ + + def __init__( + self, + registry, + ri_substitutions, + soi_receipt: dict, + levels_left_out: list[dict] | None = None, + ) -> None: self.registry = registry self.ri_substitutions = ri_substitutions self.soi_receipt = soi_receipt + self.levels_left_out = list(levels_left_out or []) def state_admin_surface( @@ -758,7 +770,10 @@ def state_admin_surface( that order; ``families`` turns clauses on by id. The SOI slice follows :func:`soi_surface_predicate` for ``state`` (the default), ``totals`` and ``full``; ``state_cd`` adds the reconciled congressional-district rows - (:func:`us_acs_local_cd_surface.state_cd_soi_surface`). + (:func:`us_acs_local_cd_surface.state_cd_soi_surface`). The surface also + lists the compiled targets of those families that the mode leaves out + because of their level (``levels_left_out``); the materialize stage + writes the list in ``materialize_rss.json``. """ # Refuse an unknown mode before loading the feed and compiling the registry. @@ -807,6 +822,10 @@ def state_cd_district_shares(candidates): TargetRegistry(list(selection.specs), country="us"), ri_substitutions, soi_receipt, + [ + {"family": family, "geography_level": level, "targets": count} + for (family, level), count in selection.left_out_by_level.items() + ], ) @@ -2504,6 +2523,7 @@ def do_materialize(args) -> None: "target_matrix": {"shape": matrix_shape, "nnz": matrix_nnz}, "carrier_check": materialized.carrier_check, "soi_surface": surface.soi_receipt, + "target_levels_left_out": surface.levels_left_out, "cd_holdout": holdout, **county_surface.run_metadata(args, county_holdout), "sampling": sampling, From 8fd3e88e9609ccd643a983f59be6aebc99555372 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:35:03 +0000 Subject: [PATCH 28/30] Make the declared target sets a typed resource of the spec engine From the review of microcosm#1755 (suggestion 3). The declared target sets decide what a build calibrates to, and most of each file is prose: a description for each mode and a rationale for each clause. They were legacy_json resources, the kind for files from before the spec engine. The bundle gives that kind no semantic content, so the bundle's spec_sha256 did not cover a clause, and the UK solve keyed on the file's bytes: a reworded rationale merged between the two builds of a local release would force the second build to solve again (microcosm#1301). The spec engine already separates a typed resource's normative content from its documentation. So the target sets become a typed resource: - A new resource kind, target_sets, with target_sets.schema.json, the sixteenth schema of the catalog. Each description and rationale is documentation; every other field is normative. - us/target_sets.json and uk/target_sets.json become us/spec/target_sets.yaml and uk/spec/target_sets.yaml. The products and the modes are lists with an id, so their declared order is content (two UK refusals list the calibration lines in that order); the order of the fields of an object is not content. - microcosm.calibrate.target_sets takes the object the spec engine parsed. Its own file reader is removed. The country modules read through country_spec.load_country_target_sets, which loads the one resource as the bundle loader does. - The country spec records, for each typed resource, the sha256 of its normative projection (ResolvedCountrySpec.content_hashes). fingerprint_excluding takes that hash for the resources named in by_content, and the UK solve fingerprint names its target sets there. The calibrated gates and the release manifests keep the byte hash. The US typed files are generated from the constants-era code. That code never held the target sets, so the US file is written by hand: the generator declares its manifest row (AUTHORED_DOMAIN_KINDS) and does not write it. The F0 field ledger has a reviewed claim for the domain, a front-end validation with its own verifier: the release tools read the typed domain themselves, so it does not pass through the constants adapter. The US pins move to 42,557 configuration fields and a new spec_sha256, which now covers the declared clauses. No target, order or receipt changes. The pinned US surfaces, censuses and receipt bytes hold on the pinned feed, and the UK selection and calibration-line tests still match the verbatim copies of the replaced code. test_uk_solve_scope.py edits the packaged file both ways: a reworded description or rationale, another layout or another order of a set of names re-keys no solve kernel; a new level, a changed clause level or family, a removed exclusion, or another order of the clauses or the modes re-keys every solve kernel. The UK solve fingerprint has a new value, so the first UK build after this change computes the solve-scoped nodes again, with the same outputs. Co-Authored-By: Claude Fable 5.2 --- .../1728-one-level-rule-form.changed.md | 2 +- ...1728-strict-declaration-readers.changed.md | 2 +- ...1728-typed-target-sets-resource.changed.md | 1 + .../1728-us-target-set-declarations.added.md | 2 +- ...59-uk-declared-target-selection.changed.md | 2 +- ...1759-uk-target-sets-content-key.changed.md | 1 + docs/evidence/spec-engine/us-f0-coverage.json | 34 +- docs/spec-engine.md | 11 + docs/uk-target-sets.md | 54 +- docs/us-fact-to-target.md | 2 +- docs/us-target-sets.md | 69 ++- .../src/microcosm/build/country_spec.py | 210 +++++++- .../build/spec_engine/field_usage.py | 48 +- .../src/microcosm/build/spec_engine/model.py | 7 + .../schema/resource_manifest.schema.json | 1 + .../schema/target_sets.schema.json | 300 +++++++++++ .../microcosm/build/spec_engine/schemas.py | 16 +- .../microcosm/build/uk/country_package.json | 10 +- .../microcosm/build/uk/spec/target_sets.yaml | 105 ++++ .../src/microcosm/build/uk/target_sets.json | 109 ---- .../build/uk_runtime/graph_national.py | 2 +- .../build/uk_runtime/graph_targets.py | 8 +- .../build/uk_runtime/ledger_targets.py | 4 +- .../microcosm/build/uk_runtime/solve_scope.py | 35 +- .../microcosm/build/uk_runtime/target_sets.py | 26 +- .../microcosm/build/us/country_package.json | 10 +- .../microcosm/build/us/spec/target_sets.yaml | 303 +++++++++++ .../src/microcosm/build/us/target_sets.json | 422 --------------- .../build/us_runtime/target_loss_weights.py | 2 +- .../microcosm/build/us_runtime/target_sets.py | 28 +- .../us/test_spec_engine_coverage_tool.py | 12 +- .../engine_contract/us/test_us_spec_bundle.py | 9 +- .../engine_free/shared/test_country_spec.py | 9 +- .../shared/test_spec_engine_compiler_ir.py | 1 + .../test_spec_engine_country_bundles.py | 4 +- .../shared/test_spec_engine_field_usage.py | 10 +- .../shared/test_spec_engine_schema.py | 2 +- .../shared/test_spec_engine_target_sets.py | 481 ++++++++++++++++++ .../uk/test_uk_calibration_line_selection.py | 2 +- .../engine_free/uk/test_uk_level_selection.py | 4 +- .../engine_free/uk/test_uk_solve_scope.py | 273 +++++++++- .../engine_free/us/test_us_spec_bundle.py | 29 +- .../engine_free/us/test_us_spine_blindness.py | 2 +- .../engine_free/us/test_us_target_sets.py | 4 +- .../us/test_us_multispine_pool_tool.py | 2 +- .../src/microcosm/calibrate/target_sets.py | 217 ++++---- .../engine_free/shared/test_target_sets.py | 187 ++++--- .../calibration_line_reference.py | 2 +- .../microcosm_build/us_spec_bundle.py | 6 +- tools/build_us_acs_local_release.py | 4 +- tools/build_us_fiscal_refresh_release.py | 2 +- tools/generate_us_bundle_from_constants.py | 11 +- tools/spec_engine_coverage.py | 2 +- 53 files changed, 2239 insertions(+), 862 deletions(-) create mode 100644 changelog.d/1728-typed-target-sets-resource.changed.md create mode 100644 changelog.d/1759-uk-target-sets-content-key.changed.md create mode 100644 packages/microcosm-build/src/microcosm/build/spec_engine/schema/target_sets.schema.json create mode 100644 packages/microcosm-build/src/microcosm/build/uk/spec/target_sets.yaml delete mode 100644 packages/microcosm-build/src/microcosm/build/uk/target_sets.json create mode 100644 packages/microcosm-build/src/microcosm/build/us/spec/target_sets.yaml delete mode 100644 packages/microcosm-build/src/microcosm/build/us/target_sets.json create mode 100644 packages/microcosm-build/tests/engine_free/shared/test_spec_engine_target_sets.py diff --git a/changelog.d/1728-one-level-rule-form.changed.md b/changelog.d/1728-one-level-rule-form.changed.md index c0aa2a9407..53cffd703d 100644 --- a/changelog.d/1728-one-level-rule-form.changed.md +++ b/changelog.d/1728-one-level-rule-form.changed.md @@ -1 +1 @@ -Each country now declares how to read a target's geography level in one form, a `level_rule` (microcosm#1728, from the review of microcosm#1755). `us/target_sets.json` gives the US rule in full: the first of `ledger_geography_level` and `geography_level` that has a value, any level accepted. The short `level_keys` form is removed from `microcosm.calibrate.target_sets`, with `target_level`; `target_set_census` takes the rule. `us_runtime.target_loss_weights.target_geography_level` reads the declared rule in place of its own copy of that reading, so a US target has one level in the selection, in the loss weights and in the summaries. No level changes: `test_us_target_sets.py` holds the reader to a verbatim copy of the replaced code, and on the pinned feed every compiled target sets `ledger_geography_level` only. +Each country now declares how to read a target's geography level in one form, a `level_rule` (microcosm#1728, from the review of microcosm#1755). `us/spec/target_sets.yaml` gives the US rule in full: the first of `ledger_geography_level` and `geography_level` that has a value, any level accepted. The short `level_keys` form is removed from `microcosm.calibrate.target_sets`, with `target_level`; `target_set_census` takes the rule. `us_runtime.target_loss_weights.target_geography_level` reads the declared rule in place of its own copy of that reading, so a US target has one level in the selection, in the loss weights and in the summaries. No level changes: `test_us_target_sets.py` holds the reader to a verbatim copy of the replaced code, and on the pinned feed every compiled target sets `ledger_geography_level` only. diff --git a/changelog.d/1728-strict-declaration-readers.changed.md b/changelog.d/1728-strict-declaration-readers.changed.md index 50332b182f..cd8176fa98 100644 --- a/changelog.d/1728-strict-declaration-readers.changed.md +++ b/changelog.d/1728-strict-declaration-readers.changed.md @@ -1 +1 @@ -The declaration readers of microcosm#1728 are strict: `microcosm.calibrate.target_sets.load_target_set_declarations`, `microcosm.build.declared_registers.package_registers` and the US local target construction refuse a repeated JSON key (plain `json.loads` kept the last one, so a second mode or register of one name replaced the first without a word), a non-finite number, and a version that is not the integer 1. A list of clause names refuses `"*"`, which would match only a name `*`; give `"*"` alone for every name. The packaged files already pass, so no selection or register changes. +The declaration readers of microcosm#1728 are strict: `microcosm.build.declared_registers.package_registers` and the US local target construction refuse a repeated JSON key (plain `json.loads` kept the last one, so a second register of one name replaced the first without a word), a non-finite number, and a version that is not the integer 1. The declared target sets are read by the spec engine's strict reader, as a typed resource. A list of clause names refuses `"*"`, which would match only a name `*`; give `"*"` alone for every name. The packaged files already pass, so no selection or register changes. diff --git a/changelog.d/1728-typed-target-sets-resource.changed.md b/changelog.d/1728-typed-target-sets-resource.changed.md new file mode 100644 index 0000000000..43dbf4c402 --- /dev/null +++ b/changelog.d/1728-typed-target-sets-resource.changed.md @@ -0,0 +1 @@ +The declared target sets are now a typed resource of the spec engine (microcosm#1728 and microcosm#1759, from the review of microcosm#1755). The spec engine has a new resource kind, `target_sets`, with the schema `target_sets.schema.json`, the sixteenth schema of its catalog. `us/target_sets.json` and `uk/target_sets.json` become `us/spec/target_sets.yaml` and `uk/spec/target_sets.yaml`. The schema marks each `description` and `rationale` as documentation and every other field as normative, so the spec engine keeps the prose apart from the content a selection reads, and the bundle's `spec_sha256` now covers that content: a changed clause changes the spec hash, and a reworded rationale does not. The products and the modes are lists with an `id`, so their declared order is content; the order of the fields of an object is not. `microcosm.calibrate.target_sets.load_target_set_declarations` takes the object the spec engine parsed, and the file reader it had is removed; the country modules read through the new `country_spec.load_country_target_sets`, which loads the one resource as the bundle loader does. The US file is written by hand (`AUTHORED_DOMAIN_KINDS` of `tools/generate_us_bundle_from_constants.py`), with a reviewed claim in the F0 field ledger; the US pins move to 42,557 configuration fields and a new `spec_sha256`. No target, order or receipt changes: the pinned US surfaces and the UK equivalence tests hold. diff --git a/changelog.d/1728-us-target-set-declarations.added.md b/changelog.d/1728-us-target-set-declarations.added.md index 0441a4ef01..a8d9b3422f 100644 --- a/changelog.d/1728-us-target-set-declarations.added.md +++ b/changelog.d/1728-us-target-set-declarations.added.md @@ -1 +1 @@ -Each US release's target set is now declared as data (microcosm#1728): `us/target_sets.json` states, for the national tool's `--target-surface` modes and the ACS local tool's `--soi-mode` modes, the compiled families and levels each mode keeps, the tests and named rules that pick them, and the rows the tool builds itself. The shared, country-free reader and selector `microcosm.calibrate.target_sets` replaces the selection code in `_select_target_surface`, `state_admin_surface` and `soi_surface_predicate`. No surface changes: on the pinned `41b2fb2` feed every mode keeps the same targets in the same order (`national_state` 6,102, the local default 4,867 with its population rows), and `test_us_target_sets.py` pins each count and registry version. `docs/us-target-sets.md` explains the declarations. +Each US release's target set is now declared as data (microcosm#1728): `us/spec/target_sets.yaml` states, for the national tool's `--target-surface` modes and the ACS local tool's `--soi-mode` modes, the compiled families and levels each mode keeps, the tests and named rules that pick them, and the rows the tool builds itself. The shared, country-free reader and selector `microcosm.calibrate.target_sets` replaces the selection code in `_select_target_surface`, `state_admin_surface` and `soi_surface_predicate`. No surface changes: on the pinned `41b2fb2` feed every mode keeps the same targets in the same order (`national_state` 6,102, the local default 4,867 with its population rows), and `test_us_target_sets.py` pins each count and registry version. `docs/us-target-sets.md` explains the declarations. diff --git a/changelog.d/1759-uk-declared-target-selection.changed.md b/changelog.d/1759-uk-declared-target-selection.changed.md index 97d8c5c164..b1142e51ee 100644 --- a/changelog.d/1759-uk-declared-target-selection.changed.md +++ b/changelog.d/1759-uk-declared-target-selection.changed.md @@ -1 +1 @@ -The UK full build selects its solve surface with the shared declared target sets, as the US does (microcosm#1759). `uk/target_sets.json` declares the UK level rule (a target's level is `geography_level` or `ledger_geography_level`; the two must agree, and the level must be one of country, region, constituency, la and brma) and the full build's selection by level, one clause for each level. `microcosm.calibrate.target_sets` reads a declared `level_rule` (the US file declares its rule in the same form) and its new `select_by_levels` keeps the requested levels in compile order with the same receipt (`microcosm.calibrate.target-selection.v1`). `microcosm.calibrate.target_selection` is removed: the UK selection kernel was its only caller, and `uk_runtime.graph_targets.target_geography` now reads the declared rule. No selection changes: `test_uk_level_selection.py` holds the new code to verbatim copies of the removed selector and resolver on random registries, refusals included. The new UK resource is in the UK solve fingerprint, so the first UK build after this change computes the spine from `frs_brma` on, the target nodes and the national graph again. The two UK calibration lines are declared there too, as the modes of a `calibration_line` product: `uk_runtime.ledger_targets.uk_registry_on_calibration_line` selects through it with one UK predicate that reads each contract target's `calibration_lines`, which stay in `uk/uk_population_targets.json`; `UK_CALIBRATION_LINES` is the declared modes. The shared selector now reads a target's level only when a clause tests levels. `test_uk_calibration_line_selection.py` holds the line filter to a verbatim copy of the replaced function: the same registry (the same object when nothing drops), the same receipt, or the same refusal. +The UK full build selects its solve surface with the shared declared target sets, as the US does (microcosm#1759). `uk/spec/target_sets.yaml` declares the UK level rule (a target's level is `geography_level` or `ledger_geography_level`; the two must agree, and the level must be one of country, region, constituency, la and brma) and the full build's selection by level, one clause for each level. `microcosm.calibrate.target_sets` reads a declared `level_rule` (the US file declares its rule in the same form) and its new `select_by_levels` keeps the requested levels in compile order with the same receipt (`microcosm.calibrate.target-selection.v1`). `microcosm.calibrate.target_selection` is removed: the UK selection kernel was its only caller, and `uk_runtime.graph_targets.target_geography` now reads the declared rule. No selection changes: `test_uk_level_selection.py` holds the new code to verbatim copies of the removed selector and resolver on random registries, refusals included. The new UK resource is in the UK solve fingerprint, so the first UK build after this change computes the spine from `frs_brma` on, the target nodes and the national graph again. The two UK calibration lines are declared there too, as the modes of a `calibration_line` product: `uk_runtime.ledger_targets.uk_registry_on_calibration_line` selects through it with one UK predicate that reads each contract target's `calibration_lines`, which stay in `uk/uk_population_targets.json`; `UK_CALIBRATION_LINES` is the declared modes. The shared selector now reads a target's level only when a clause tests levels. `test_uk_calibration_line_selection.py` holds the line filter to a verbatim copy of the replaced function: the same registry (the same object when nothing drops), the same receipt, or the same refusal. diff --git a/changelog.d/1759-uk-target-sets-content-key.changed.md b/changelog.d/1759-uk-target-sets-content-key.changed.md new file mode 100644 index 0000000000..f2dfc4e1fc --- /dev/null +++ b/changelog.d/1759-uk-target-sets-content-key.changed.md @@ -0,0 +1 @@ +The UK solve fingerprint now reads `uk/spec/target_sets.yaml` by its normative content, not by its bytes (microcosm#1759, from the review of microcosm#1755). The country spec records, for each typed resource of a package, the sha256 of the normative projection that the spec engine gives it (`ResolvedCountrySpec.content_hashes`), and `fingerprint_excluding` takes that hash for the resources named in `by_content`. The UK solve names its declared target sets there (`uk_runtime.solve_scope.UK_CONTENT_KEYED_RESOURCES`). A reworded description or rationale, or a new layout of the file, re-keys no solve node, so it cannot force the second build of a local release to solve again; a changed clause, level or exclusion re-keys every node that keys on the solve fingerprint. The calibrated gates and the release manifests keep the byte hash. The solve fingerprint has a new value, so the first UK build after this change computes the solve-scoped nodes again, with the same outputs. `test_uk_solve_scope.py` edits the packaged file both ways and compares every solve kernel's key. diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index ddc403589b..d1bd55ded4 100644 --- a/docs/evidence/spec-engine/us-f0-coverage.json +++ b/docs/evidence/spec-engine/us-f0-coverage.json @@ -4,10 +4,10 @@ "version": 1 }, "country": "us", - "documentation_sha256": "fda6ec0dd925077f4d84d30a1c206dd81d82c5e16bd94506e81fe1b9f7e2f466", + "documentation_sha256": "3342f5315eeef08e5d2e91f29c9d06e6f8e5e065dfdb0222c8de573716bf0a97", "field_usage": { - "authored_normative_field_count": 32627, - "claim_count": 48, + "authored_normative_field_count": 32771, + "claim_count": 49, "claims": [ { "consumer": "loader.typed_resource_manifest", @@ -684,6 +684,20 @@ "source_prefix": "/authored/spec~1take_up.yaml", "verifier": "legacy" }, + { + "consumer": "country_spec.declared_target_sets.us_runtime_target_sets", + "generation0_effect": "no_generation0_effect", + "id": "target_sets", + "legacy_sinks": [], + "mode": "front_end_validation", + "pointer_class": "all", + "pointer_count": 144, + "pointer_sha256": "476b22fb8944797601151d253e4a1f1c545d1e49029dc3d391f0b7ff89733b6d", + "rationale": null, + "relative_sink_prefix": null, + "source_prefix": "/authored/spec~1target_sets.yaml", + "verifier": "target_sets" + }, { "consumer": "resolver.vintage_authorities", "generation0_effect": "no_generation0_effect", @@ -758,20 +772,20 @@ "verifier": "vintages" } ], - "configuration_field_count": 42413, - "consumed_field_count": 42413, + "configuration_field_count": 42557, + "consumed_field_count": 42557, "generation0_effect_counts": { "legacy_behavior": 38780, - "no_generation0_effect": 3633 + "no_generation0_effect": 3777 }, "mode_counts": { "compiler_semantic": 27674, - "front_end_validation": 367, + "front_end_validation": 511, "identity_only": 103, "legacy_behavior": 14269 }, "multiple_primary_use_field_count": 0, - "pointer_inventory_sha256": "8e3b7c8680e0a5c5626867c1b697b6b6d98058b383c2f7d368f0b5b5df3105b1", + "pointer_inventory_sha256": "7c37171ae40e7e9f43e9ecf36937cbd0a907b5516868b45dc3d9cf7ddec12d4d", "resolved_binding_field_count": 9786, "unused_field_count": 0 }, @@ -2585,7 +2599,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "0ff909ec0783ad5d1fbf3c70fadbd60aee9b05773ebdb1ad42fbc988a5593fa3" + "spec_sha256": "50ebe28107e5fe8ab45e5c637871c9f0efdc97c697480eb41bdc262c89bf18fa" } }, "report_schema_version": 3, @@ -2595,7 +2609,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "0ff909ec0783ad5d1fbf3c70fadbd60aee9b05773ebdb1ad42fbc988a5593fa3" + "spec_sha256": "50ebe28107e5fe8ab45e5c637871c9f0efdc97c697480eb41bdc262c89bf18fa" }, "status": "pass" } diff --git a/docs/spec-engine.md b/docs/spec-engine.md index 633256fe1a..e0918ecbde 100644 --- a/docs/spec-engine.md +++ b/docs/spec-engine.md @@ -561,6 +561,17 @@ Per "Gates and calibration": each gate a full executable record; the solver surface fully resolved; `k` a run-request knob with a declared bundle default and precedence; no `device` in normative content. +### target_sets.yaml + +The declared target sets: which compiled targets each product calibrates to, +for each mode, and the country's level rule (microcosm#1728, microcosm#1759). +The schema is country-free, and the UK and the US both ship the file. The +release tools read the typed domain themselves through +`country_spec.load_country_target_sets`. Each `description` and `rationale` is +documentation; the rest is normative. It is the one typed US file that is +written by hand: the constants-era code never held it. See +[US target sets](us-target-sets.md) and [UK target sets](uk-target-sets.md). + ### publication.yaml Attempt-event model + promotion protocol + release relationship graph; diff --git a/docs/uk-target-sets.md b/docs/uk-target-sets.md index 493a3b4f48..da046204ce 100644 --- a/docs/uk-target-sets.md +++ b/docs/uk-target-sets.md @@ -3,7 +3,9 @@ The UK declares its target sets the way the US does ([US target sets](us-target-sets.md)). Since microcosm#1759 the UK choices are data in -[`packages/microcosm-build/src/microcosm/build/uk/target_sets.json`](../packages/microcosm-build/src/microcosm/build/uk/target_sets.json), +[`packages/microcosm-build/src/microcosm/build/uk/spec/target_sets.yaml`](../packages/microcosm-build/src/microcosm/build/uk/spec/target_sets.yaml), +a typed resource of the UK spec bundle (kind `target_sets`; see +[US target sets](us-target-sets.md#a-typed-resource-of-the-spec-bundle)), read by the shared [`microcosm.calibrate.target_sets`](../packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py). The UK names (file, products, predicate) are in @@ -17,12 +19,11 @@ The move changed no target, selection or receipt. The proofs are listed under Every compiled UK target has one geography level. The file declares how to read it: -```json -"level_rule": { - "keys": ["geography_level", "ledger_geography_level"], - "values": ["country", "region", "constituency", "la", "brma"], - "conflict": "refuse" -} +```yaml +level_rule: + keys: [geography_level, ledger_geography_level] + values: [country, region, constituency, la, brma] + conflict: refuse ``` - The level is the first of the two keys that has a value. @@ -32,8 +33,9 @@ read it: `uk_runtime.graph_targets.target_geography` and the national problem (`graph_national.national_target_geography_levels`) read levels with this -rule. The US file gives the short form `level_keys`, which is an open rule -that takes the first key. +rule. The US file declares its rule in the same form: an open rule +(`"values": "*"`, `"conflict": "first"`) that takes the first key. The reader +has one form for the rule, so each country states its reading in full. ## The products @@ -157,8 +159,8 @@ the nesting work of microcosm#1760. ## What a UK build computes again -`uk/target_sets.json` is a solve-scoped UK resource, so it is in the UK solve -fingerprint. The spine gates also hash that fingerprint. So the first UK build +`uk/spec/target_sets.yaml` is a solve-scoped UK resource, so it is in the UK +solve fingerprint. The spine gates also hash that fingerprint. So the first UK build after this change computes these again: - the spine from `frs_brma` on; @@ -166,3 +168,33 @@ after this change computes these again: - the national graph. The outputs are the same bytes. + +### The file is in the fingerprint by its content + +Most of `uk/spec/target_sets.yaml` is prose: a description for each mode and a +rationale for each clause. No node reads that prose. The selections read the +clauses, levels, exclusions and rules. The spec engine already keeps the two +apart for a typed resource: the schema marks each `description` and +`rationale` as documentation, and every other field is normative. So the +solve fingerprint takes the hash of the file's normative content, not the +hash of its bytes (`uk_runtime.solve_scope.UK_CONTENT_KEYED_RESOURCES`): + +- The country spec records, for each typed resource of a package, the sha256 + of its normative projection (`ResolvedCountrySpec.content_hashes`). It is + the split that gives the bundle's `spec_sha256`, for one file. +- A reworded rationale, a new layout of the file or another order of the + fields of an object changes no solve key. The order of the products, the + modes and the clauses is content: they are lists. This matters for a local + release, whose second build must reuse the first build's solve + (microcosm#1301). +- A changed clause, level, test, exclusion or rule changes the key of every + node that keys on the solve fingerprint. No reader has to add a hash of its + own. +- The calibrated gate node and the release manifests keep the byte hash, so + provenance names the exact file. +- The other typed UK resources still enter the fingerprint by their bytes. + Each can join `UK_CONTENT_KEYED_RESOURCES` after a review of what its + surfaces hold. + +`test_uk_solve_scope.py` edits the packaged file both ways and compares every +solve kernel's key. diff --git a/docs/us-fact-to-target.md b/docs/us-fact-to-target.md index 66aa6b1b1c..665286a0b3 100644 --- a/docs/us-fact-to-target.md +++ b/docs/us-fact-to-target.md @@ -41,7 +41,7 @@ same cell and concept — e.g. congressional-district income binds from artifact compiles the same national + state + congressional-district target registry (`us_runtime/fiscal_targets.py::compile_us_fiscal_target_registry`); artifact record count changes L0, not target membership. Each product then -calibrates to the subset that `us/target_sets.json` declares for its mode +calibrates to the subset that `us/spec/target_sets.yaml` declares for its mode ([US target sets](us-target-sets.md)). The national build's `national_state` mode and the local build's `state` mode are not the same set today (microcosm#1728). The pinned diff --git a/docs/us-target-sets.md b/docs/us-target-sets.md index de0e7a319c..96b7038607 100644 --- a/docs/us-target-sets.md +++ b/docs/us-target-sets.md @@ -4,7 +4,9 @@ Every US release compiles the same target registry (`us_runtime/fiscal_targets.py::compile_us_fiscal_target_registry`). Each release then calibrates to a subset of it. Since microcosm#1728, that subset is declared as data, for each product and mode, in -[`packages/microcosm-build/src/microcosm/build/us/target_sets.json`](../packages/microcosm-build/src/microcosm/build/us/target_sets.json). +[`packages/microcosm-build/src/microcosm/build/us/spec/target_sets.yaml`](../packages/microcosm-build/src/microcosm/build/us/spec/target_sets.yaml). +The file is a typed resource of the US spec bundle (see "A typed resource of +the spec bundle" below). - The shared reader and selector are in [`microcosm.calibrate.target_sets`](../packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py). @@ -59,12 +61,11 @@ Each mode states three things: A target's family is its `TargetSpec.family`. Its level comes from the level rule that the file declares, in the form the UK file uses: -```json -"level_rule": { - "keys": ["ledger_geography_level", "geography_level"], - "values": "*", - "conflict": "first" -} +```yaml +level_rule: + keys: [ledger_geography_level, geography_level] + values: "*" + conflict: first ``` - The level is the first of the two keys that has a value. A compiled target @@ -124,14 +125,55 @@ builds use `state`. Their state rows, by family: has 436 district population rows. Whether the local build fits the national rows and the full state set is decision 1 of microcosm#1728. +## A typed resource of the spec bundle + +`spec/target_sets.yaml` is a typed resource of the country's spec bundle: kind +`target_sets`, schema +[`target_sets.schema.json`](../packages/microcosm-build/src/microcosm/build/spec_engine/schema/target_sets.schema.json) +([spec engine](spec-engine.md)). The UK file has the same kind and schema. + +- **One read.** The spec engine reads the file with its strict YAML 1.2 + reader (a repeated key and a non-finite number are refused) and checks it + against the schema, which is closed: an unknown field is refused. The + country modules read the same object through + `country_spec.load_country_target_sets`, which loads this one resource as + the bundle loader does. +- **Content and documentation are apart.** The schema marks each `description` + and `rationale` as documentation. Every other field is normative: it is what + a selection reads. The bundle's `spec_sha256` covers the normative content, + so a changed clause changes the spec hash that a US build records, and a + reworded rationale does not. +- **Order.** The products, the modes, the clauses and the built rows are + lists, so their declared order is content. The order of the fields of an + object is not content, and neither is the order of the names in a list of + families or levels. +- **What the schema cannot state.** The shared reader refuses a repeated + product, mode, clause or built id, a default mode that is not declared, and + `"*"` inside a list of names. +- **Written by hand.** The other US typed files are generated from the + constants-era code (`tools/generate_us_bundle_from_constants.py`). The + constants-era code never held the target sets, so this file is the + authority and the generator only declares its manifest row + (`AUTHORED_DOMAIN_KINDS`). +- **The F0 field ledger.** Every normative field of the US bundle has a + reviewed claim in `spec_engine/field_usage.py`. The `target_sets` claim is + a front-end validation: the release tools read the typed domain themselves, + so it does not pass through the constants adapter. Its verifier checks the + domain against the schema and the shared reader. + ## How to change a target set -1. Change the mode's clauses or built entries in `target_sets.json`. The tools - read the file at run time. -2. Run `test_us_target_sets.py` with the pinned feed. A change that moves a +1. Change the mode's clauses or built entries in `spec/target_sets.yaml`. The + tools read the file at run time. +2. Re-pin the US spec-engine contracts, because the file's content is in the + bundle's `spec_sha256` and in the field ledger: + `tools/repin_us_spec_engine_contracts.py`, then + `tools/spec_engine_coverage.py`. A change to a description or a rationale + alone moves no pin. +3. Run `test_us_target_sets.py` with the pinned feed. A change that moves a surface changes its pinned count and version: update them, and say which rows moved in the pull request. -3. A change that moves a surface changes what the calibration fits, so a +4. A change that moves a surface changes what the calibration fits, so a build must measure it (`docs/us-release-build-rule.md`). A family or level that a feed re-pin adds enters a mode only if a clause names @@ -180,9 +222,8 @@ replaced read only `ledger_geography_level`. So a state SOI row that carries only `geography_level` now enters these two modes. Every compiled row carries `ledger_geography_level`, so no compiled registry changes. -A declaration file is read strictly: a repeated JSON key, a non-finite number, -`"*"` inside a list of names and a version that is not the integer are -refused. +The file is read strictly and checked against its schema (see "A typed +resource of the spec bundle" above). ## Rows the local tool builds, and its hold-outs diff --git a/packages/microcosm-build/src/microcosm/build/country_spec.py b/packages/microcosm-build/src/microcosm/build/country_spec.py index 7a2caceb77..c1c1d6a58a 100644 --- a/packages/microcosm-build/src/microcosm/build/country_spec.py +++ b/packages/microcosm-build/src/microcosm/build/country_spec.py @@ -78,8 +78,10 @@ "country_stage_plan", "country_engine_abi_lock_check_environment", "load_country_take_up_contract_projection", + "load_country_target_sets", "load_country_spec", "load_gates_manifest", + "typed_resource_content_sha256", ] #: Resource kinds admitted by the binding ``resource_manifest.schema.json``. @@ -100,12 +102,16 @@ "publication", "vintages", "catalogs", + "target_sets", "schema", "legacy_json", } ) _LEGACY_RESOURCE_SCHEMA_ID = "legacy_json" +#: The domain tag of a typed resource's content hash +#: (:func:`typed_resource_content_sha256`). +_CONTENT_HASH_DOMAIN = "microcosm-country-spec/normative-content/1" _GENERATED_LOCK_FILENAMES = frozenset( {"bundle.lock.json", "engine_abi.lock.json", "plan.lock.json"} ) @@ -1630,6 +1636,16 @@ class ResolvedCountrySpec: migration evidence only. resource_hashes: Resource filename -> sha256 of its bytes (includes ``country_package.json`` itself). + content_hashes: Typed resource path -> sha256 of its normative + projection, for a generation-1 bundle. The spec engine separates + each typed resource's normative content from its documentation + (the fields its schema marks ``x-spec-surface: documentation``), + and ``spec_sha256`` covers the normative content alone. This is + that content for one resource. A cache key can use it in place of + the byte hash (:meth:`fingerprint_excluding`), so that an edit to + a description or a layout does not change the key; release + manifests keep the byte hash. A ``legacy_json`` resource has no + content hash: it has no schema to say what is documentation. resolved_spec: The canonical spec-engine object for a generation-1 bundle, when compiled. It remains ``None`` for generation-0 compatibility packages. @@ -1649,6 +1665,9 @@ class ResolvedCountrySpec: take_up_contract: Mapping[str, Any] | None resource_hashes: Mapping[str, str] resolved_spec: object | None = None + content_hashes: Mapping[str, str] = field( + default_factory=lambda: MappingProxyType({}) + ) @property def resources(self) -> tuple[str, ...]: @@ -1666,7 +1685,9 @@ def fingerprint(self) -> str: """ return compute_composition_fingerprint(self.resource_hashes.values()) - def fingerprint_excluding(self, excluded: Collection[str]) -> str: + def fingerprint_excluding( + self, excluded: Collection[str], *, by_content: Collection[str] = () + ) -> str: """Composition fingerprint over every resource hash but ``excluded``. A node whose computation reads none of the excluded resources keys on @@ -1677,14 +1698,24 @@ def fingerprint_excluding(self, excluded: Collection[str]) -> str: lacks those resources, and another exclusion set is another value. Release manifests keep recording :attr:`fingerprint`. + A resource in ``by_content`` enters by its content hash + (:attr:`content_hashes`), not by its byte hash. An edit to its + documentation, or a new layout of the file, then leaves the value as + it was, and an edit to its content changes it. Those names are bound + under a second domain tag, so the value is never one that hashes the + same resources by their bytes. + Raises: - TypeError: If ``excluded`` is a single string. + TypeError: If ``excluded`` or ``by_content`` is a single string. ValueError: If a name is not a declared resource, or is - ``country_package.json``, which declares the roster itself. + ``country_package.json``, which declares the roster itself; + if a ``by_content`` name has no content hash, or is also + excluded. """ - if isinstance(excluded, str): + if isinstance(excluded, str) or isinstance(by_content, str): raise TypeError("fingerprint_excluding takes a collection of names.") names = frozenset(excluded) + content_names = frozenset(by_content) if "country_package.json" in names: raise ValueError( "country_package.json declares the resource roster and cannot " @@ -1696,18 +1727,37 @@ def fingerprint_excluding(self, excluded: Collection[str]) -> str: f"{self.country}: cannot exclude undeclared resource(s) " f"{undeclared} from the fingerprint." ) - tag = hashlib.sha256( - b"microcosm-country-spec/excluding/1\n" - + "\n".join(sorted(names)).encode("utf-8") - ).hexdigest() + if content_names & names: + raise ValueError( + f"{self.country}: resource(s) {sorted(content_names & names)} " + "cannot be both excluded and hashed by content." + ) + without_content = sorted(content_names - set(self.content_hashes)) + if without_content: + raise ValueError( + f"{self.country}: resource(s) {without_content} have no content hash." + ) + tags = [ + hashlib.sha256( + b"microcosm-country-spec/excluding/1\n" + + "\n".join(sorted(names)).encode("utf-8") + ).hexdigest() + ] + if content_names: + tags.append( + hashlib.sha256( + b"microcosm-country-spec/by-content/1\n" + + "\n".join(sorted(content_names)).encode("utf-8") + ).hexdigest() + ) return compute_composition_fingerprint( ( *( - digest + self.content_hashes[name] if name in content_names else digest for name, digest in self.resource_hashes.items() if name not in names ), - tag, + *tags, ) ) @@ -2179,6 +2229,142 @@ def load_normalized(row: CountryResourceRow) -> Mapping[str, Any]: return projection +def _normalized_typed_resource( + resource_path: Path, schema_id: str +) -> tuple[Mapping[str, Any], Mapping[str, Any]]: + """One typed resource as the bundle loader reads it, without the bundle. + + The same strict YAML 1.2 parser, schema check, default injection and + normalizer as :func:`microcosm.build.spec_engine.load_bundle`. Returns + the normalized object and its projection onto each surface. + """ + + from microcosm.build.spec_engine import load_schema_registry, load_yaml12_file + from microcosm.build.spec_engine.canonical import normalize_and_project + from microcosm.build.spec_engine.model import thaw_json + + registry = load_schema_registry() + value = load_yaml12_file(resource_path) + registry.validate(value, schema_id) + defaulted = registry.validate_and_inject_defaults(value, schema_id) + normalized, projections = normalize_and_project( + defaulted, schema_id=schema_id, registry=registry + ) + thawed, surfaces = thaw_json(normalized), thaw_json(projections) + if not isinstance(thawed, Mapping) or not isinstance(surfaces, Mapping): + raise ValueError(f"{resource_path.name}: normalized resource is not an object.") + return thawed, surfaces + + +def _normative_content_sha256(normative: object) -> str: + from microcosm.build.spec_engine.canonical import sha256_json + + return sha256_json({"domain": _CONTENT_HASH_DOMAIN, "normative": normative}) + + +def typed_resource_content_sha256(resource_path: str | Path, schema_id: str) -> str: + """The content hash of one typed resource file: its normative projection. + + This is the value :attr:`ResolvedCountrySpec.content_hashes` holds for a + typed resource of a loaded package. A change to a field that the schema + marks as documentation, a new layout of the file, or another order of the + fields of an object leaves it as it was. + """ + + _normalized, surfaces = _normalized_typed_resource(Path(resource_path), schema_id) + return _normative_content_sha256(surfaces.get("normative", {})) + + +def _typed_content_hashes(resolved_spec: Any) -> dict[str, str]: + """Each typed resource's content hash, from the resolved bundle.""" + + from microcosm.build.spec_engine.model import ResourceKind, Surface, thaw_json + + return { + resource.descriptor.path.as_posix(): _normative_content_sha256( + thaw_json(resource.surface(Surface.NORMATIVE)) + ) + for resource in resolved_spec.resources + if resource.descriptor.kind + not in {ResourceKind.SCHEMA, ResourceKind.LEGACY_JSON} + } + + +def _checked_target_sets(document: Mapping[str, Any], *, country: str) -> None: + """Refuse declared target sets that the shared reader cannot use.""" + + from microcosm.calibrate.target_sets import load_target_set_declarations + + declarations = load_target_set_declarations(document) + if declarations.country != country: + raise ValueError( + f"target_sets declares country {declarations.country!r} but lives " + f"in the {country!r} package." + ) + + +def _validate_declared_target_sets(resolved_spec: Any, *, country: str) -> None: + """Check a bundle's ``target_sets`` domain, when it declares one. + + The schema states the form. The shared reader + (``microcosm.calibrate.target_sets``) adds what a schema cannot: unique + ids and a declared default mode. A package whose declared target sets + cannot be read does not load. + """ + + try: + domain = resolved_spec.domain("target_sets") + except KeyError: + return + document = domain.to_wire() + if not isinstance(document, Mapping): # pragma: no cover - schema invariant + raise ValueError("target_sets: normalized typed domain is not an object.") + _checked_target_sets(document, country=country) + + +def load_country_target_sets(country: str | Path) -> Mapping[str, Any] | None: + """Load only the manifest-declared ``target_sets`` resource of a package. + + The declared target sets say which compiled targets each product of a + country calibrates to (``microcosm.calibrate.target_sets``). Country + modules read them when they are imported, so this narrow seam reads the + one typed resource and not the whole bundle, as + :func:`load_country_take_up_contract_projection` does for take-up. It + uses the same strict parser, schema check, defaults and normalizer as the + bundle loader, so it returns the object the loaded bundle holds. + + Returns ``None`` for a package that declares no ``target_sets`` resource. + """ + + if isinstance(country, Path): + root = country + else: + root = Path(str(importlib_resources.files("microcosm.build").joinpath(country))) + package = _require_mapping( + json.loads((root / "country_package.json").read_text(encoding="utf-8")), + context="country_package.json", + ) + rows = [ + row + for row in _resolve_country_resource_rows(package.get("resources", [])) + if row.kind == "target_sets" + ] + if not rows: + return None + if len(rows) != 1: + raise ValueError( + "country_package.json: a package declares at most one target_sets resource." + ) + document, _surfaces = _normalized_typed_resource( + _country_resource_path(root, rows[0].path), rows[0].schema_id + ) + declared_country = _require_non_empty_string( + package.get("country"), field_name="country", context="country_package.json" + ) + _checked_target_sets(document, country=declared_country) + return document + + def country_resource(country: str, name: str) -> Traversable: """The packaged resource ``name`` of ``country``'s spec package. @@ -2353,6 +2539,7 @@ def _load_country_spec(root: Path) -> ResolvedCountrySpec: ) hashes: dict[str, str] = {"country_package.json": sha256_file(package_path)} + content_hashes: dict[str, str] = {} payloads: dict[str, Mapping[str, Any]] = {} for row in resource_rows: name = row.path @@ -2387,6 +2574,8 @@ def _load_country_spec(root: Path) -> ResolvedCountrySpec: from microcosm.build.spec_engine import load_bundle resolved_spec = load_bundle(root) + content_hashes = _typed_content_hashes(resolved_spec) + _validate_declared_target_sets(resolved_spec, country=declared_country) source_payload = _select_compatibility_payload( resolved_spec=resolved_spec, @@ -2499,6 +2688,7 @@ def _load_country_spec(root: Path) -> ResolvedCountrySpec: # Read-only: a cached spec is shared by every caller in the process. resource_hashes=MappingProxyType(hashes), resolved_spec=resolved_spec, + content_hashes=MappingProxyType(content_hashes), ) diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py index 94030a43c1..df0a2f739b 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py @@ -26,9 +26,9 @@ ) from .schemas import load_schema_registry -EXPECTED_AUTHORED_FIELD_COUNT = 32627 +EXPECTED_AUTHORED_FIELD_COUNT = 32771 EXPECTED_RESOLVED_BINDING_FIELD_COUNT = 9786 -EXPECTED_CONFIGURATION_FIELD_COUNT = 42413 +EXPECTED_CONFIGURATION_FIELD_COUNT = 42557 class FieldUsageError(AssertionError): @@ -528,6 +528,10 @@ def _path_inventory(rows: Sequence[tuple[str, object]]) -> tuple[int, str]: 328, "d53096196db4c34da260cce2f35af8e7ba67f978448656c602ee5e17529dc4e0", ), + "target_sets": ( + 144, + "476b22fb8944797601151d253e4a1f1c545d1e49029dc3d391f0b7ff89733b6d", + ), "vintage_records": ( 120, "825b4ab09602353fc4d6c24b6f7654f7582502c7acf963b7ff6c117b07208eb4", @@ -954,6 +958,17 @@ def default_usage_claims() -> tuple[UsageClaim, ...]: "/stacked_checkpoint_static_components", ), ), + # The release tools read this typed domain themselves + # (us_runtime.target_sets); the constants-era code never held it, + # so it does not pass through the legacy adapter. + _claim( + "target_sets", + f"{_A}/spec~1target_sets.yaml", + UsageMode.FRONT_END_VALIDATION, + _NO_EFFECT, + "country_spec.declared_target_sets.us_runtime_target_sets", + "target_sets", + ), _claim( "vintage_records", f"{_A}/spec~1vintages.yaml", @@ -1238,6 +1253,34 @@ def _verify_spine_assembly_validation( ) +def _verify_target_sets(context: _VerificationContext, claim: UsageClaim) -> None: + """The typed domain is valid, and it is what the release tools select by.""" + + document = _verify_domain_schema( + context, + kind=ResourceKind.TARGET_SETS, + schema_id="target_sets.schema.json", + claim_id=claim.id, + ) + _, source = _pointer_value(context.sources, claim.source_prefix) + if not _semantic_subset(source, document): + raise FieldUsageError(f"{claim.id}: typed domain binding differs") + # Imported here: only this claim needs the calibration reader. + from microcosm.calibrate.target_sets import ( + TargetSetDeclarationError, + load_target_set_declarations, + ) + + try: + declarations = load_target_set_declarations(document) + except TargetSetDeclarationError as error: + raise FieldUsageError( + f"{claim.id}: the declarations reader refuses the domain: {error}" + ) from error + if declarations.country != context.spec.country: + raise FieldUsageError(f"{claim.id}: declared country differs") + + def _verify_compiled_domain(context: _VerificationContext, claim: UsageClaim) -> None: kind = ResourceKind(_domain_kind(claim)) _, source = _pointer_value(context.sources, claim.source_prefix) @@ -1448,6 +1491,7 @@ def _verify_claim(context: _VerificationContext, claim: UsageClaim) -> None: "seed_protocol": lambda: _verify_seed_protocol(context, claim), "seed_bindings": lambda: _verify_seed_bindings(context, claim), "vintages": lambda: _verify_vintages(context, claim), + "target_sets": lambda: _verify_target_sets(context, claim), "authorities": lambda: _verify_authorities(context, claim), } verifier = verifiers.get(claim.verifier) diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/model.py b/packages/microcosm-build/src/microcosm/build/spec_engine/model.py index 1b3ded2e52..919e95ef91 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/model.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/model.py @@ -95,6 +95,7 @@ class ResourceKind(StrEnum): PUBLICATION = "publication" VINTAGES = "vintages" CATALOGS = "catalogs" + TARGET_SETS = "target_sets" SCHEMA = "schema" LEGACY_JSON = "legacy_json" @@ -233,6 +234,11 @@ class CatalogsSpec(DomainSpec): pass +@dataclass(frozen=True, slots=True) +class TargetSetsSpec(DomainSpec): + pass + + DOMAIN_TYPE_BY_KIND: Mapping[ResourceKind, type[DomainSpec]] = { ResourceKind.BUNDLE: BundleSpec, ResourceKind.SOURCES: SourcesSpec, @@ -246,6 +252,7 @@ class CatalogsSpec(DomainSpec): ResourceKind.PUBLICATION: PublicationSpec, ResourceKind.VINTAGES: VintagesSpec, ResourceKind.CATALOGS: CatalogsSpec, + ResourceKind.TARGET_SETS: TargetSetsSpec, ResourceKind.SCHEMA: DomainSpec, ResourceKind.LEGACY_JSON: DomainSpec, } diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/schema/resource_manifest.schema.json b/packages/microcosm-build/src/microcosm/build/spec_engine/schema/resource_manifest.schema.json index 31f3cacbfe..5cdc13d2ec 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/schema/resource_manifest.schema.json +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/schema/resource_manifest.schema.json @@ -49,6 +49,7 @@ "publication", "vintages", "catalogs", + "target_sets", "schema", "legacy_json" ] diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/schema/target_sets.schema.json b/packages/microcosm-build/src/microcosm/build/spec_engine/schema/target_sets.schema.json new file mode 100644 index 0000000000..2a85a2bb66 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/schema/target_sets.schema.json @@ -0,0 +1,300 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "target_sets.schema.json", + "title": "Declared target sets: the compiled targets each product calibrates to, for each mode", + "x-spec-surface": "normative", + "type": "object", + "additionalProperties": false, + "required": [ + "version", + "country", + "level_rule", + "products" + ], + "properties": { + "version": { + "const": 1 + }, + "country": { + "$ref": "defs.schema.json#/$defs/identifier" + }, + "description": { + "type": "string", + "minLength": 1, + "x-spec-surface": "documentation", + "description": "What the file declares. No selection reads it." + }, + "level_rule": { + "$ref": "#/$defs/level_rule" + }, + "products": { + "type": "array", + "minItems": 1, + "description": "In declared order. Each id is unique.", + "items": { + "$ref": "#/$defs/product" + } + } + }, + "$defs": { + "name": { + "type": "string", + "minLength": 1, + "pattern": "^\\S(.*\\S)?$" + }, + "names_or_any": { + "oneOf": [ + { + "const": "*" + }, + { + "type": "array", + "minItems": 1, + "uniqueItems": true, + "x-canonical-order": "set", + "items": { + "type": "string", + "minLength": 1, + "pattern": "^\\S(.*\\S)?$" + } + } + ] + }, + "level_rule": { + "type": "object", + "additionalProperties": false, + "required": [ + "keys", + "values", + "conflict", + "rationale" + ], + "description": "How a target's geography level is read from its metadata.", + "properties": { + "keys": { + "type": "array", + "minItems": 1, + "uniqueItems": true, + "description": "Metadata keys in reading order: the first one that has a value gives the level.", + "items": { + "$ref": "#/$defs/name" + } + }, + "values": { + "$ref": "#/$defs/names_or_any", + "description": "The closed set of levels, or \"*\" for any level." + }, + "conflict": { + "enum": [ + "first", + "refuse" + ] + }, + "rationale": { + "type": "string", + "minLength": 1, + "x-spec-surface": "documentation" + } + } + }, + "product": { + "type": "object", + "additionalProperties": false, + "required": [ + "id", + "tool", + "option", + "default_mode", + "modes" + ], + "properties": { + "id": { + "$ref": "defs.schema.json#/$defs/identifier" + }, + "tool": { + "$ref": "#/$defs/name" + }, + "option": { + "$ref": "#/$defs/name" + }, + "default_mode": { + "$ref": "defs.schema.json#/$defs/identifier" + }, + "modes": { + "type": "array", + "minItems": 1, + "description": "In declared order. Each id is unique in its product.", + "items": { + "$ref": "#/$defs/mode" + } + } + } + }, + "mode": { + "type": "object", + "additionalProperties": false, + "required": [ + "id", + "description", + "compiled" + ], + "properties": { + "id": { + "$ref": "defs.schema.json#/$defs/identifier" + }, + "description": { + "type": "string", + "minLength": 1, + "x-spec-surface": "documentation" + }, + "compiled": { + "type": "array", + "minItems": 1, + "description": "Clauses in selection order.", + "items": { + "$ref": "#/$defs/clause" + } + }, + "built": { + "type": "array", + "items": { + "$ref": "#/$defs/built_rows" + } + } + } + }, + "clause": { + "type": "object", + "additionalProperties": false, + "required": [ + "id", + "families", + "levels", + "rationale" + ], + "properties": { + "id": { + "$ref": "defs.schema.json#/$defs/identifier" + }, + "families": { + "$ref": "#/$defs/names_or_any" + }, + "levels": { + "$ref": "#/$defs/names_or_any" + }, + "metadata": { + "type": "object", + "description": "One test for each metadata key; every test must pass.", + "additionalProperties": { + "$ref": "#/$defs/metadata_test" + } + }, + "exclude": { + "type": "array", + "uniqueItems": true, + "description": "Names of country predicates; a target that any of them accepts is dropped.", + "items": { + "$ref": "#/$defs/name" + } + }, + "rule": { + "$ref": "#/$defs/name" + }, + "rationale": { + "type": "string", + "minLength": 1, + "x-spec-surface": "documentation" + } + } + }, + "metadata_test": { + "oneOf": [ + { + "type": "object", + "additionalProperties": false, + "required": [ + "present" + ], + "properties": { + "present": { + "type": "boolean" + } + } + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "equals" + ], + "properties": { + "equals": {} + } + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "not_equals" + ], + "properties": { + "not_equals": {} + } + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "not_prefix" + ], + "properties": { + "not_prefix": { + "type": "string", + "minLength": 1, + "pattern": "^\\S(.*\\S)?$" + } + } + } + ] + }, + "built_rows": { + "type": "object", + "additionalProperties": false, + "required": [ + "id", + "family", + "levels", + "source", + "rationale" + ], + "description": "Rows a tool makes outside the compile. The selector does not make them.", + "properties": { + "id": { + "$ref": "defs.schema.json#/$defs/identifier" + }, + "family": { + "$ref": "#/$defs/name" + }, + "option": { + "$ref": "#/$defs/name" + }, + "levels": { + "type": "object", + "minProperties": 1, + "description": "The level that each value of the option gives.", + "additionalProperties": { + "$ref": "#/$defs/name" + } + }, + "source": { + "$ref": "#/$defs/name" + }, + "rationale": { + "type": "string", + "minLength": 1, + "x-spec-surface": "documentation" + } + } + } + } +} diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/schemas.py b/packages/microcosm-build/src/microcosm/build/spec_engine/schemas.py index 72ce19e514..6d9644a464 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/schemas.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/schemas.py @@ -1,8 +1,8 @@ """Closed-world JSON Schema registry for country specification bundles. The registry deliberately has no filesystem or network retrieval fallback. -Every reference must resolve inside the fifteen schemas shipped with the -compiler. Keeping that boundary here makes both authored resources and +Every reference must resolve inside the schemas shipped with the compiler +(``SCHEMA_FILENAMES``). Keeping that boundary here makes both authored resources and emitted lock fragments use the same draft-2020-12 implementation. """ @@ -49,12 +49,13 @@ "sources.schema.json", "spine.schema.json", "take_up.schema.json", + "target_sets.schema.json", "vintages.schema.json", ) SCHEMA_IDS = frozenset(SCHEMA_FILENAMES) # Resource kinds with a single schema authority. ``schema`` is handled by -# ``SCHEMA_IDS_BY_KIND`` because each of the fifteen schema files is a valid +# ``SCHEMA_IDS_BY_KIND`` because each of the schema files is a valid # resource of that kind. ``legacy_json`` is an explicit generation-0 # compatibility sentinel and is never passed to the draft-2020 validator. SCHEMA_ID_BY_KIND: Mapping[str, str] = MappingProxyType( @@ -71,6 +72,7 @@ "publication": "publication.schema.json", "vintages": "vintages.schema.json", "catalogs": "catalogs.schema.json", + "target_sets": "target_sets.schema.json", "legacy_json": "legacy_json", } ) @@ -171,7 +173,7 @@ def from_package_data( cls, schema_root: Traversable | Path | None = None, ) -> SchemaRegistry: - """Load and verify exactly the approved fifteen-schema catalog. + """Load and verify exactly the approved schema catalog. An explicit ``schema_root`` is useful for golden and mutation tests. The catalog has exactly one home — package data at @@ -200,8 +202,8 @@ def _from_documents( if unexpected: details.append(f"unexpected={unexpected!r}") raise SpecSchemaError( - "schema catalog must contain exactly the approved 15 JSON " - f"schemas ({'; '.join(details)})" + "schema catalog must contain exactly the approved " + f"{len(SCHEMA_FILENAMES)} JSON schemas ({'; '.join(details)})" ) ids: dict[str, str] = {} @@ -447,7 +449,7 @@ def _schema_data_root() -> Traversable | Path: if packaged.is_dir(): return packaged raise SpecSchemaError( - "approved schema package data is absent; the fifteen-schema catalog " + "approved schema package data is absent; the schema catalog " "ships inside microcosm.build.spec_engine.schema (one copy — the " "former specs/schema fallback and its wheel force-include are retired)" ) diff --git a/packages/microcosm-build/src/microcosm/build/uk/country_package.json b/packages/microcosm-build/src/microcosm/build/uk/country_package.json index 668ab35c13..3e166fa65a 100644 --- a/packages/microcosm-build/src/microcosm/build/uk/country_package.json +++ b/packages/microcosm-build/src/microcosm/build/uk/country_package.json @@ -27,6 +27,11 @@ "kind": "spine", "schema_id": "spine.schema.json" }, + { + "path": "spec/target_sets.yaml", + "kind": "target_sets", + "schema_id": "target_sets.schema.json" + }, { "path": "spec/vintages.yaml", "kind": "vintages", @@ -661,11 +666,6 @@ "path": "hmrc_spi_table_3_11_uk_rows.json", "kind": "legacy_json", "schema_id": "legacy_json" - }, - { - "path": "target_sets.json", - "kind": "legacy_json", - "schema_id": "legacy_json" } ] } diff --git a/packages/microcosm-build/src/microcosm/build/uk/spec/target_sets.yaml b/packages/microcosm-build/src/microcosm/build/uk/spec/target_sets.yaml new file mode 100644 index 0000000000..992b87e026 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/uk/spec/target_sets.yaml @@ -0,0 +1,105 @@ +# The targets each UK build calibrates to (microcosm#1759). +# Schema: spec_engine/schema/target_sets.schema.json. Reader: microcosm.calibrate.target_sets. +# docs/uk-target-sets.md explains it. +version: 1 +country: uk +description: 'The targets each UK build calibrates to (microcosm#1759): the level rule that places every + compiled UK target at one geography level, the full build''s selection of its solve surface by level, + and the two calibration lines. microcosm.calibrate.target_sets reads this file; microcosm.build.uk_runtime.target_sets + names its products; docs/uk-target-sets.md explains it. The US declares its target sets the same way, + in us/spec/target_sets.yaml (microcosm#1728).' +level_rule: + keys: + - geography_level + - ledger_geography_level + values: + - country + - region + - constituency + - la + - brma + conflict: refuse + rationale: A compiled UK target names its level in its local metadata (geography_level), in the Ledger's + (ledger_geography_level), or in both. Both must then agree, and the level must be one of the five + grains a UK build calibrates at; any other target is refused, not placed by a guess. This is the rule + the UK resolver uk_runtime.graph_targets.target_geography applied in code before microcosm#1759. +products: +- id: full + tool: packages/microcosm-build/src/microcosm/build/uk_runtime/full_build_cli.py + option: --target-geographies + default_mode: levels + modes: + - id: levels + description: 'The full (local-line) build''s solve surface: the compiled targets of the levels the + build requests, all of them by default, in compile order, with a receipt that lists every target + (uk.full.target_selection@1). The node first applies the build''s family filter (--households-only) + and, with no area BRMAs, drops the brma rows.' + compiled: + - id: country + families: '*' + levels: + - country + rationale: The country-level rows. Kept when the build requests this level; a build requests every + level unless --target-geographies names a subset. + - id: region + families: '*' + levels: + - region + rationale: The region-level rows. Kept when the build requests this level; a build requests every + level unless --target-geographies names a subset. + - id: constituency + families: '*' + levels: + - constituency + rationale: The Westminster constituency cells. Kept when the build requests this level; a build + requests every level unless --target-geographies names a subset. + - id: la + families: '*' + levels: + - la + rationale: The local-authority cells. Kept when the build requests this level; a build requests + every level unless --target-geographies names a subset. + - id: brma + families: '*' + levels: + - brma + rationale: The Broad Rental Market Area cells. Kept when the build requests this level; a build + requests every level unless --target-geographies names a subset. With no area BRMAs (--brma-localisation + none) the node drops these rows before it selects, because they would bind on the spine's regional + BRMA draw (microcosm#1305). +- id: calibration_line + tool: packages/microcosm-build/src/microcosm/build/uk_runtime/full_targets.py + option: line (uk_runtime.ledger_targets.uk_registry_on_calibration_line) + default_mode: local + modes: + - id: national + description: 'The national line''s solve surface (load_uk_national_target_inputs and the release-cut + certifier): the compiled national registry less the references whose contract target binds on the + local line only. They leave right after the compile, before reconciliation, the measure exclusions + and the frozen-register check (microcosm#1301).' + compiled: + - id: on_line + families: '*' + levels: '*' + exclude: + - off_calibration_line + rationale: 'A contract target binds on every line unless its calibration_lines field in uk/uk_population_targets.json + narrows it; the field and its reason stay with the target, and uk_runtime.ledger_targets passes + this clause the targets it leaves out. The high-value homes region rows bind on the local line + only (microcosm#1240, microcosm#1301): on the national line they would move the national registry + and solve while the Land Registry knots'' tails place more homes in the top bands than the derived + stock (microcosm#1112).' + - id: local + description: 'The local line''s national rows (load_uk_full_target_inputs; the full dense build binds + them beside the local surface): the compiled national registry less the references whose contract + target binds on the national line only, dropped at the same point.' + compiled: + - id: on_line + families: '*' + levels: '*' + exclude: + - off_calibration_line + rationale: A contract target binds on every line unless its calibration_lines field in uk/uk_population_targets.json + narrows it; the field and its reason stay with the target, and uk_runtime.ledger_targets passes + this clause the targets it leaves out. The CenTax childcare-parent bands bind on the national + line only (microcosm#1399). diff --git a/packages/microcosm-build/src/microcosm/build/uk/target_sets.json b/packages/microcosm-build/src/microcosm/build/uk/target_sets.json deleted file mode 100644 index ebf1ff2636..0000000000 --- a/packages/microcosm-build/src/microcosm/build/uk/target_sets.json +++ /dev/null @@ -1,109 +0,0 @@ -{ - "version": 1, - "country": "uk", - "description": "The targets each UK build calibrates to (microcosm#1759): the level rule that places every compiled UK target at one geography level, the full build's selection of its solve surface by level, and the two calibration lines. microcosm.calibrate.target_sets reads this file; microcosm.build.uk_runtime.target_sets names its products; docs/uk-target-sets.md explains it. The US declares its target sets the same way, in us/target_sets.json (microcosm#1728).", - "level_rule": { - "keys": [ - "geography_level", - "ledger_geography_level" - ], - "values": [ - "country", - "region", - "constituency", - "la", - "brma" - ], - "conflict": "refuse", - "rationale": "A compiled UK target names its level in its local metadata (geography_level), in the Ledger's (ledger_geography_level), or in both. Both must then agree, and the level must be one of the five grains a UK build calibrates at; any other target is refused, not placed by a guess. This is the rule the UK resolver uk_runtime.graph_targets.target_geography applied in code before microcosm#1759." - }, - "products": { - "full": { - "tool": "packages/microcosm-build/src/microcosm/build/uk_runtime/full_build_cli.py", - "option": "--target-geographies", - "default_mode": "levels", - "modes": { - "levels": { - "description": "The full (local-line) build's solve surface: the compiled targets of the levels the build requests, all of them by default, in compile order, with a receipt that lists every target (uk.full.target_selection@1). The node first applies the build's family filter (--households-only) and, with no area BRMAs, drops the brma rows.", - "compiled": [ - { - "id": "country", - "families": "*", - "levels": [ - "country" - ], - "rationale": "The country-level rows. Kept when the build requests this level; a build requests every level unless --target-geographies names a subset." - }, - { - "id": "region", - "families": "*", - "levels": [ - "region" - ], - "rationale": "The region-level rows. Kept when the build requests this level; a build requests every level unless --target-geographies names a subset." - }, - { - "id": "constituency", - "families": "*", - "levels": [ - "constituency" - ], - "rationale": "The Westminster constituency cells. Kept when the build requests this level; a build requests every level unless --target-geographies names a subset." - }, - { - "id": "la", - "families": "*", - "levels": [ - "la" - ], - "rationale": "The local-authority cells. Kept when the build requests this level; a build requests every level unless --target-geographies names a subset." - }, - { - "id": "brma", - "families": "*", - "levels": [ - "brma" - ], - "rationale": "The Broad Rental Market Area cells. Kept when the build requests this level; a build requests every level unless --target-geographies names a subset. With no area BRMAs (--brma-localisation none) the node drops these rows before it selects, because they would bind on the spine's regional BRMA draw (microcosm#1305)." - } - ] - } - } - }, - "calibration_line": { - "tool": "packages/microcosm-build/src/microcosm/build/uk_runtime/full_targets.py", - "option": "line (uk_runtime.ledger_targets.uk_registry_on_calibration_line)", - "default_mode": "local", - "modes": { - "national": { - "description": "The national line's solve surface (load_uk_national_target_inputs and the release-cut certifier): the compiled national registry less the references whose contract target binds on the local line only. They leave right after the compile, before reconciliation, the measure exclusions and the frozen-register check (microcosm#1301).", - "compiled": [ - { - "id": "on_line", - "families": "*", - "levels": "*", - "exclude": [ - "off_calibration_line" - ], - "rationale": "A contract target binds on every line unless its calibration_lines field in uk/uk_population_targets.json narrows it; the field and its reason stay with the target, and uk_runtime.ledger_targets passes this clause the targets it leaves out. The high-value homes region rows bind on the local line only (microcosm#1240, microcosm#1301): on the national line they would move the national registry and solve while the Land Registry knots' tails place more homes in the top bands than the derived stock (microcosm#1112)." - } - ] - }, - "local": { - "description": "The local line's national rows (load_uk_full_target_inputs; the full dense build binds them beside the local surface): the compiled national registry less the references whose contract target binds on the national line only, dropped at the same point.", - "compiled": [ - { - "id": "on_line", - "families": "*", - "levels": "*", - "exclude": [ - "off_calibration_line" - ], - "rationale": "A contract target binds on every line unless its calibration_lines field in uk/uk_population_targets.json narrows it; the field and its reason stay with the target, and uk_runtime.ledger_targets passes this clause the targets it leaves out. The CenTax childcare-parent bands bind on the national line only (microcosm#1399)." - } - ] - } - } - } - } -} diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_national.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_national.py index e0149bab61..0b83ac7b10 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_national.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_national.py @@ -500,7 +500,7 @@ def implementation_hash(self) -> str: # re-key the national problem. calibrate_target_loss_rules, # The national problem writes each row's level, which the - # declared UK level rule gives (uk/target_sets.json through the + # declared UK level rule gives (uk/spec/target_sets.yaml through the # shared target sets, microcosm#1759). calibrate_target_sets, target_sets, diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_targets.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_targets.py index 891861e7f3..4a27a4f226 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_targets.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_targets.py @@ -117,7 +117,7 @@ def registry_from_payload(payload: Mapping) -> TargetRegistry: def target_geography(spec: TargetSpec) -> str: """Resolve explicit metadata without interpreting legacy registry buckets. - The rule is declared in ``uk/target_sets.json`` (microcosm#1759): the + The rule is declared in ``uk/spec/target_sets.yaml`` (microcosm#1759): the level is ``geography_level`` or ``ledger_geography_level``, the two must agree when both are set, and it must be one of the five UK grains. """ @@ -243,9 +243,9 @@ def implementation_hash(self) -> str: declared_registers, # The selection, the constraint matrices and their encoding, as # the transport kernels hash them (microcosm#1492). The selection - # and the level rule read uk/target_sets.json through the shared - # target sets (microcosm#1759); the file's bytes are in the solve - # fingerprint below. + # and the level rule read uk/spec/target_sets.yaml through the + # shared target sets (microcosm#1759); the file's normative + # content is in the solve fingerprint below. calibrate_target_sets, target_sets, calibrate_matrix, diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/ledger_targets.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/ledger_targets.py index 525db1bf1d..83a8539371 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/ledger_targets.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/ledger_targets.py @@ -2074,7 +2074,7 @@ def _uk_contract_targets( #: line (``load_uk_national_target_inputs``, the release-cut certifier) and the #: local line (the full dense build, whose solve binds the national rows beside #: the local surface). They are the modes of the ``calibration_line`` product -#: in ``uk/target_sets.json`` (microcosm#1759). +#: in ``uk/spec/target_sets.yaml`` (microcosm#1759). UK_CALIBRATION_LINES: tuple[str, ...] = uk_calibration_lines() @@ -2128,7 +2128,7 @@ def uk_registry_on_calibration_line( all-lines registry version and count, and the dropped contract targets. The line is a mode of the declared ``calibration_line`` product - (``uk/target_sets.json``); its one clause keeps every reference but the + (``uk/spec/target_sets.yaml``); its one clause keeps every reference but the ones :data:`OFF_CALIBRATION_LINE` names, which this function binds to the contract targets that leave ``line`` out (microcosm#1759). """ diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/solve_scope.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/solve_scope.py index 9567bd127a..af68ab0f1d 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/solve_scope.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/solve_scope.py @@ -26,13 +26,32 @@ will prompt, must not re-key the solve. The stock cells' value block stays in, since the frame's home values will be read from it. Membership is the same claim as for the gate-only registers, and the same suite tests it. + +The declared target sets (``spec/target_sets.yaml``, microcosm#1759) stay in +the fingerprint, but by their content, as :data:`UK_CONTENT_KEYED_RESOURCES`. +They are a typed resource of the spec bundle, and the spec engine separates a +typed resource's normative content from its documentation. The selections +read the clauses, levels, exclusions and rules; no node reads a description +or a rationale, and most of the file is that prose. So the fingerprint takes +the hash of the file's normative projection +(``ResolvedCountrySpec.content_hashes``): a reworded rationale merged between +the two builds of a release does not re-key the solve, and a changed clause +re-keys every node that keys on the fingerprint. The calibrated gate node and +the release manifests keep the byte hash. The other typed resources still +enter by their bytes; each can join this set after a review of what its +surfaces hold. """ from __future__ import annotations from microcosm.build import country_spec -__all__ = ["UK_GATE_ONLY_RESOURCES", "UK_POST_SOLVE_RESOURCES", "uk_solve_fingerprint"] +__all__ = [ + "UK_CONTENT_KEYED_RESOURCES", + "UK_GATE_ONLY_RESOURCES", + "UK_POST_SOLVE_RESOURCES", + "uk_solve_fingerprint", +] UK_GATE_ONLY_RESOURCES: frozenset[str] = frozenset( { @@ -62,14 +81,22 @@ ) +#: The solve-scoped typed resources that enter the fingerprint by the hash of +#: their normative projection, which leaves out their documentation (see the +#: module docstring). +UK_CONTENT_KEYED_RESOURCES: frozenset[str] = frozenset({"spec/target_sets.yaml"}) + + def uk_solve_fingerprint(spec: country_spec.ResolvedCountrySpec | None = None) -> str: """The UK country fingerprint without the gate-only and post-solve resources. - ``spec`` defaults to the packaged UK spec, looked up when called so a - test can substitute one. + The declared target sets enter by their content + (:data:`UK_CONTENT_KEYED_RESOURCES`). ``spec`` defaults to the packaged + UK spec, looked up when called so a test can substitute one. """ resolved = country_spec.load_country_spec("uk") if spec is None else spec return resolved.fingerprint_excluding( - UK_GATE_ONLY_RESOURCES | UK_POST_SOLVE_RESOURCES + UK_GATE_ONLY_RESOURCES | UK_POST_SOLVE_RESOURCES, + by_content=UK_CONTENT_KEYED_RESOURCES, ) diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/target_sets.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/target_sets.py index a3035fefa3..22cf968402 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/target_sets.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/target_sets.py @@ -1,14 +1,17 @@ """The declared target sets of the UK builds (microcosm#1759). -``uk/target_sets.json`` declares the UK level rule, which places every +``uk/spec/target_sets.yaml`` declares the UK level rule, which places every compiled UK target at one geography level; the full build's selection of its solve surface by level (``uk.full.target_selection@1``, from the full build's ``--target-geographies``); and the two calibration lines, which drop the compiled national references a line does not bind (``calibration_line``, one -mode for each line). The shared reader and selector are in +mode for each line). The file is a typed resource of the UK spec bundle +(kind ``target_sets``): the spec engine reads it strictly, checks it against +``target_sets.schema.json`` and keeps its descriptions and rationales apart +from its content. The shared reader and selector are in :mod:`microcosm.calibrate.target_sets`; this module names the UK file and products. The US declares its target sets the same way, in -``us/target_sets.json`` (microcosm#1728). +``us/spec/target_sets.yaml`` (microcosm#1728). """ from __future__ import annotations @@ -38,7 +41,7 @@ "uk_target_sets_path", ] -UK_TARGET_SETS_RESOURCE = "target_sets.json" +UK_TARGET_SETS_RESOURCE = "spec/target_sets.yaml" #: The full build's product, and its one mode: selection by level. FULL_PRODUCT = "full" FULL_LEVELS_MODE = "levels" @@ -54,9 +57,20 @@ def uk_target_sets_path() -> Path: @lru_cache(maxsize=1) def uk_target_set_declarations() -> TargetSetDeclarations: - """The packaged UK declarations, read and checked once.""" + """The packaged UK declarations, read and checked once. - return load_target_set_declarations(uk_target_sets_path()) + They come through :func:`microcosm.build.country_spec.load_country_target_sets`, + which reads the one typed resource as the bundle loader does. + """ + + # Imported here: the country spec module is large, and this module is + # imported by modules that the country spec's own imports reach. + from microcosm.build.country_spec import load_country_target_sets + + document = load_country_target_sets("uk") + if document is None: # pragma: no cover - the package declares the resource + raise RuntimeError("The UK package declares no target_sets resource.") + return load_target_set_declarations(document) def uk_full_level_selection() -> TargetSetDeclaration: diff --git a/packages/microcosm-build/src/microcosm/build/us/country_package.json b/packages/microcosm-build/src/microcosm/build/us/country_package.json index d1236341ed..3888daa206 100644 --- a/packages/microcosm-build/src/microcosm/build/us/country_package.json +++ b/packages/microcosm-build/src/microcosm/build/us/country_package.json @@ -57,6 +57,11 @@ "kind": "take_up", "schema_id": "take_up.schema.json" }, + { + "path": "spec/target_sets.yaml", + "kind": "target_sets", + "schema_id": "target_sets.schema.json" + }, { "path": "spec/vintages.yaml", "kind": "vintages", @@ -192,11 +197,6 @@ "kind": "legacy_json", "schema_id": "legacy_json" }, - { - "path": "target_sets.json", - "kind": "legacy_json", - "schema_id": "legacy_json" - }, { "path": "tax_expenditure_reforms.json", "kind": "legacy_json", diff --git a/packages/microcosm-build/src/microcosm/build/us/spec/target_sets.yaml b/packages/microcosm-build/src/microcosm/build/us/spec/target_sets.yaml new file mode 100644 index 0000000000..097e2b1cfb --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us/spec/target_sets.yaml @@ -0,0 +1,303 @@ +# The targets each US release calibrates to, for each product and mode (microcosm#1728). +# Written by hand: tools/generate_us_bundle_from_constants.py does not write this file. +# Schema: spec_engine/schema/target_sets.schema.json. Reader: microcosm.calibrate.target_sets. +# docs/us-target-sets.md explains it. +version: 1 +country: us +description: 'The targets each US release calibrates to, for each product and mode: the compiled families + and levels it keeps, the tests that pick them, and the rows the tool builds itself (microcosm#1728). + microcosm.calibrate.target_sets reads this file; docs/us-target-sets.md explains it.' +level_rule: + keys: + - ledger_geography_level + - geography_level + values: '*' + conflict: first + rationale: A compiled US target names its level in the Ledger's metadata (ledger_geography_level). A + row that a tool builds from the PUMA ladder or the county facts names it in its local metadata (geography_level). + The first key that has a value gives the level, and a target with neither has the level unspecified. + The target-loss rows read this rule too (us_runtime.target_loss_weights.target_geography_level, microcosm#1729), + so a US target has one level everywhere. +products: +- id: national + tool: tools/build_us_fiscal_refresh_release.py + option: --target-surface + default_mode: full + modes: + - id: full + description: Every compiled target. + compiled: + - id: compiled + families: '*' + levels: '*' + rationale: 'The tool''s default: the release calibrates to the whole compiled registry.' + - id: national_state + description: The country and state rows of every compiled family, except the rows classified as congressional-district. + The production national builds use this mode. + compiled: + - id: country_and_state + families: '*' + levels: '*' + exclude: + - congressional_district + rationale: 'District targets belong in the local solve: when microcosm#449 put small-area targets + into the national solve, the share of targets within 10% fell by half (microcosm#625). The exclusion + also drops the country and state rows of the IRS SOI congressional-district file. The target-parity + and profile-coverage gates run on the full compiled registry before this selection.' +- id: local + tool: tools/build_us_acs_local_release.py + option: --soi-mode + default_mode: state + modes: + - id: state + description: State SNAP, state Medicaid enrollment and the IRS SOI state rows outside the congressional-district + file, with population totals from the PUMA ladder. + compiled: + - id: snap + families: + - usda_snap + levels: + - state + metadata: + state_fips: + present: true + rationale: State SNAP rows (--families snap). + - id: medicaid + families: + - cms_medicaid + levels: + - state + metadata: + state_fips: + present: true + target_role: + equals: medicaid_enrollment + rationale: State Medicaid enrollment after the reviewed Rhode Island substitution (--families medicaid). + - id: soi + families: + - irs_soi + levels: + - state + metadata: + state_fips: + present: true + ledger_layout_record_set_spec_id: + not_prefix: irs_soi.congressional_district_ + rationale: The SOI state rows of every target role, AGI bands included, outside the congressional-district + file (--families soi). This is the default mode; docs/us-acs-local-soi-target-surface.md has its + history. + built: + - id: population + family: census_population + option: --geographies + levels: + state: state + cd: congressional_district + county: county + source: US Census Bureau 2020 PUMA population ladder (--ladder) + rationale: One population total for each state, 119th-Congress district and county that --geographies + names (default state,cd). + - id: totals + description: As state, but the SOI rows are every state-bearing row whose target role is not soi_fiscal_distribution, + at state and district level. + compiled: + - id: snap + families: + - usda_snap + levels: + - state + metadata: + state_fips: + present: true + rationale: State SNAP rows (--families snap). + - id: medicaid + families: + - cms_medicaid + levels: + - state + metadata: + state_fips: + present: true + target_role: + equals: medicaid_enrollment + rationale: State Medicaid enrollment after the reviewed Rhode Island substitution (--families medicaid). + - id: soi + families: + - irs_soi + levels: + - state + - congressional_district + metadata: + state_fips: + present: true + target_role: + not_equals: soi_fiscal_distribution + rationale: 'An explicit opt-in: the jetsam-safe Option B of the Build L runbook. Every SOI fact + without a named role has the role soi_fiscal_distribution, so this mode drops the AGI bands and + the all-income state and district rows.' + built: + - id: population + family: census_population + option: --geographies + levels: + state: state + cd: congressional_district + county: county + source: US Census Bureau 2020 PUMA population ladder (--ladder) + rationale: One population total for each state, 119th-Congress district and county that --geographies + names (default state,cd). + - id: full + description: As state, but the SOI rows are every state-bearing row at state and district level, the + congressional-district file included, with both vintages of each state concept. + compiled: + - id: snap + families: + - usda_snap + levels: + - state + metadata: + state_fips: + present: true + rationale: State SNAP rows (--families snap). + - id: medicaid + families: + - cms_medicaid + levels: + - state + metadata: + state_fips: + present: true + target_role: + equals: medicaid_enrollment + rationale: State Medicaid enrollment after the reviewed Rhode Island substitution (--families medicaid). + - id: soi + families: + - irs_soi + levels: + - state + - congressional_district + metadata: + state_fips: + present: true + rationale: An explicit opt-in that keeps every state-bearing SOI row. It does not fit in memory + on one 128 GB machine (microcosm#1728). + built: + - id: population + family: census_population + option: --geographies + levels: + state: state + cd: congressional_district + county: county + source: US Census Bureau 2020 PUMA population ladder (--ladder) + rationale: One population total for each state, 119th-Congress district and county that --geographies + names (default state,cd). + - id: state_cd + description: As state, plus the congressional-district file's district rows as within-state shares + of the Historic Table 2 state level, with one vintage for each state concept. + compiled: + - id: snap + families: + - usda_snap + levels: + - state + metadata: + state_fips: + present: true + rationale: State SNAP rows (--families snap). + - id: medicaid + families: + - cms_medicaid + levels: + - state + metadata: + state_fips: + present: true + target_role: + equals: medicaid_enrollment + rationale: State Medicaid enrollment after the reviewed Rhode Island substitution (--families medicaid). + - id: soi + families: + - irs_soi + levels: + - state + - congressional_district + metadata: + state_fips: + present: true + rule: state_cd_district_shares + rationale: An explicit opt-in. The rule (tools/us_acs_local_cd_surface.py state_cd_soi_surface) + takes the state mode's SOI rows as the state level and keeps the district file's district rows + only as shares of it. --cd-holdout-fraction holds a block of district rows out of the solve. + built: + - id: population + family: census_population + option: --geographies + levels: + state: state + cd: congressional_district + county: county + source: US Census Bureau 2020 PUMA population ladder (--ladder) + rationale: One population total for each state, 119th-Congress district and county that --geographies + names (default state,cd). + - id: state_county + description: 'As state, plus county rows from the pinned county facts: SOI shares of each state row, + ACS households, and county population.' + compiled: + - id: snap + families: + - usda_snap + levels: + - state + metadata: + state_fips: + present: true + rationale: State SNAP rows (--families snap). + - id: medicaid + families: + - cms_medicaid + levels: + - state + metadata: + state_fips: + present: true + target_role: + equals: medicaid_enrollment + rationale: State Medicaid enrollment after the reviewed Rhode Island substitution (--families medicaid). + - id: soi + families: + - irs_soi + levels: + - state + metadata: + state_fips: + present: true + ledger_layout_record_set_spec_id: + not_prefix: irs_soi.congressional_district_ + rationale: 'The state mode''s SOI rows: the county rows split them, so they stay the state level + (docs/us-acs-local-county-rung.md).' + built: + - id: population + family: census_population + option: --geographies + levels: + state: state + cd: congressional_district + county: county + source: US Census Bureau 2020 PUMA population ladder (--ladder) + rationale: One population total for each state, 119th-Congress district and county that --geographies + names (the County Files runbook uses state,cd,county). + - id: county_soi + family: irs_soi + levels: + county: county + source: IRS SOI county file in the pinned county facts (--county-facts, us/chronicle_county_facts.json) + rationale: County SOI facts give shares of their state row, never a second state level (tools/us_acs_local_county_surface.py). + - id: acs_households + family: acs_households + levels: + state: state + county: county + source: ACS household counts in the pinned county facts (--county-facts) + rationale: Each state's ACS household total and its county rows (tools/us_acs_local_county_surface.py + acs_household_surface). diff --git a/packages/microcosm-build/src/microcosm/build/us/target_sets.json b/packages/microcosm-build/src/microcosm/build/us/target_sets.json deleted file mode 100644 index 5b88a8bdc4..0000000000 --- a/packages/microcosm-build/src/microcosm/build/us/target_sets.json +++ /dev/null @@ -1,422 +0,0 @@ -{ - "version": 1, - "country": "us", - "description": "The targets each US release calibrates to, for each product and mode: the compiled families and levels it keeps, the tests that pick them, and the rows the tool builds itself (microcosm#1728). microcosm.calibrate.target_sets reads this file; docs/us-target-sets.md explains it.", - "level_rule": { - "keys": [ - "ledger_geography_level", - "geography_level" - ], - "values": "*", - "conflict": "first", - "rationale": "A compiled US target names its level in the Ledger's metadata (ledger_geography_level). A row that a tool builds from the PUMA ladder or the county facts names it in its local metadata (geography_level). The first key that has a value gives the level, and a target with neither has the level unspecified. The target-loss rows read this rule too (us_runtime.target_loss_weights.target_geography_level, microcosm#1729), so a US target has one level everywhere." - }, - "products": { - "national": { - "tool": "tools/build_us_fiscal_refresh_release.py", - "option": "--target-surface", - "default_mode": "full", - "modes": { - "full": { - "description": "Every compiled target.", - "compiled": [ - { - "id": "compiled", - "families": "*", - "levels": "*", - "rationale": "The tool's default: the release calibrates to the whole compiled registry." - } - ] - }, - "national_state": { - "description": "The country and state rows of every compiled family, except the rows classified as congressional-district. The production national builds use this mode.", - "compiled": [ - { - "id": "country_and_state", - "families": "*", - "levels": "*", - "exclude": [ - "congressional_district" - ], - "rationale": "District targets belong in the local solve: when microcosm#449 put small-area targets into the national solve, the share of targets within 10% fell by half (microcosm#625). The exclusion also drops the country and state rows of the IRS SOI congressional-district file. The target-parity and profile-coverage gates run on the full compiled registry before this selection." - } - ] - } - } - }, - "local": { - "tool": "tools/build_us_acs_local_release.py", - "option": "--soi-mode", - "default_mode": "state", - "modes": { - "state": { - "description": "State SNAP, state Medicaid enrollment and the IRS SOI state rows outside the congressional-district file, with population totals from the PUMA ladder.", - "compiled": [ - { - "id": "snap", - "families": [ - "usda_snap" - ], - "levels": [ - "state" - ], - "metadata": { - "state_fips": { - "present": true - } - }, - "rationale": "State SNAP rows (--families snap)." - }, - { - "id": "medicaid", - "families": [ - "cms_medicaid" - ], - "levels": [ - "state" - ], - "metadata": { - "state_fips": { - "present": true - }, - "target_role": { - "equals": "medicaid_enrollment" - } - }, - "rationale": "State Medicaid enrollment after the reviewed Rhode Island substitution (--families medicaid)." - }, - { - "id": "soi", - "families": [ - "irs_soi" - ], - "levels": [ - "state" - ], - "metadata": { - "state_fips": { - "present": true - }, - "ledger_layout_record_set_spec_id": { - "not_prefix": "irs_soi.congressional_district_" - } - }, - "rationale": "The SOI state rows of every target role, AGI bands included, outside the congressional-district file (--families soi). This is the default mode; docs/us-acs-local-soi-target-surface.md has its history." - } - ], - "built": [ - { - "id": "population", - "family": "census_population", - "option": "--geographies", - "levels": { - "state": "state", - "cd": "congressional_district", - "county": "county" - }, - "source": "US Census Bureau 2020 PUMA population ladder (--ladder)", - "rationale": "One population total for each state, 119th-Congress district and county that --geographies names (default state,cd)." - } - ] - }, - "totals": { - "description": "As state, but the SOI rows are every state-bearing row whose target role is not soi_fiscal_distribution, at state and district level.", - "compiled": [ - { - "id": "snap", - "families": [ - "usda_snap" - ], - "levels": [ - "state" - ], - "metadata": { - "state_fips": { - "present": true - } - }, - "rationale": "State SNAP rows (--families snap)." - }, - { - "id": "medicaid", - "families": [ - "cms_medicaid" - ], - "levels": [ - "state" - ], - "metadata": { - "state_fips": { - "present": true - }, - "target_role": { - "equals": "medicaid_enrollment" - } - }, - "rationale": "State Medicaid enrollment after the reviewed Rhode Island substitution (--families medicaid)." - }, - { - "id": "soi", - "families": [ - "irs_soi" - ], - "levels": [ - "state", - "congressional_district" - ], - "metadata": { - "state_fips": { - "present": true - }, - "target_role": { - "not_equals": "soi_fiscal_distribution" - } - }, - "rationale": "An explicit opt-in: the jetsam-safe Option B of the Build L runbook. Every SOI fact without a named role has the role soi_fiscal_distribution, so this mode drops the AGI bands and the all-income state and district rows." - } - ], - "built": [ - { - "id": "population", - "family": "census_population", - "option": "--geographies", - "levels": { - "state": "state", - "cd": "congressional_district", - "county": "county" - }, - "source": "US Census Bureau 2020 PUMA population ladder (--ladder)", - "rationale": "One population total for each state, 119th-Congress district and county that --geographies names (default state,cd)." - } - ] - }, - "full": { - "description": "As state, but the SOI rows are every state-bearing row at state and district level, the congressional-district file included, with both vintages of each state concept.", - "compiled": [ - { - "id": "snap", - "families": [ - "usda_snap" - ], - "levels": [ - "state" - ], - "metadata": { - "state_fips": { - "present": true - } - }, - "rationale": "State SNAP rows (--families snap)." - }, - { - "id": "medicaid", - "families": [ - "cms_medicaid" - ], - "levels": [ - "state" - ], - "metadata": { - "state_fips": { - "present": true - }, - "target_role": { - "equals": "medicaid_enrollment" - } - }, - "rationale": "State Medicaid enrollment after the reviewed Rhode Island substitution (--families medicaid)." - }, - { - "id": "soi", - "families": [ - "irs_soi" - ], - "levels": [ - "state", - "congressional_district" - ], - "metadata": { - "state_fips": { - "present": true - } - }, - "rationale": "An explicit opt-in that keeps every state-bearing SOI row. It does not fit in memory on one 128 GB machine (microcosm#1728)." - } - ], - "built": [ - { - "id": "population", - "family": "census_population", - "option": "--geographies", - "levels": { - "state": "state", - "cd": "congressional_district", - "county": "county" - }, - "source": "US Census Bureau 2020 PUMA population ladder (--ladder)", - "rationale": "One population total for each state, 119th-Congress district and county that --geographies names (default state,cd)." - } - ] - }, - "state_cd": { - "description": "As state, plus the congressional-district file's district rows as within-state shares of the Historic Table 2 state level, with one vintage for each state concept.", - "compiled": [ - { - "id": "snap", - "families": [ - "usda_snap" - ], - "levels": [ - "state" - ], - "metadata": { - "state_fips": { - "present": true - } - }, - "rationale": "State SNAP rows (--families snap)." - }, - { - "id": "medicaid", - "families": [ - "cms_medicaid" - ], - "levels": [ - "state" - ], - "metadata": { - "state_fips": { - "present": true - }, - "target_role": { - "equals": "medicaid_enrollment" - } - }, - "rationale": "State Medicaid enrollment after the reviewed Rhode Island substitution (--families medicaid)." - }, - { - "id": "soi", - "families": [ - "irs_soi" - ], - "levels": [ - "state", - "congressional_district" - ], - "metadata": { - "state_fips": { - "present": true - } - }, - "rule": "state_cd_district_shares", - "rationale": "An explicit opt-in. The rule (tools/us_acs_local_cd_surface.py state_cd_soi_surface) takes the state mode's SOI rows as the state level and keeps the district file's district rows only as shares of it. --cd-holdout-fraction holds a block of district rows out of the solve." - } - ], - "built": [ - { - "id": "population", - "family": "census_population", - "option": "--geographies", - "levels": { - "state": "state", - "cd": "congressional_district", - "county": "county" - }, - "source": "US Census Bureau 2020 PUMA population ladder (--ladder)", - "rationale": "One population total for each state, 119th-Congress district and county that --geographies names (default state,cd)." - } - ] - }, - "state_county": { - "description": "As state, plus county rows from the pinned county facts: SOI shares of each state row, ACS households, and county population.", - "compiled": [ - { - "id": "snap", - "families": [ - "usda_snap" - ], - "levels": [ - "state" - ], - "metadata": { - "state_fips": { - "present": true - } - }, - "rationale": "State SNAP rows (--families snap)." - }, - { - "id": "medicaid", - "families": [ - "cms_medicaid" - ], - "levels": [ - "state" - ], - "metadata": { - "state_fips": { - "present": true - }, - "target_role": { - "equals": "medicaid_enrollment" - } - }, - "rationale": "State Medicaid enrollment after the reviewed Rhode Island substitution (--families medicaid)." - }, - { - "id": "soi", - "families": [ - "irs_soi" - ], - "levels": [ - "state" - ], - "metadata": { - "state_fips": { - "present": true - }, - "ledger_layout_record_set_spec_id": { - "not_prefix": "irs_soi.congressional_district_" - } - }, - "rationale": "The state mode's SOI rows: the county rows split them, so they stay the state level (docs/us-acs-local-county-rung.md)." - } - ], - "built": [ - { - "id": "population", - "family": "census_population", - "option": "--geographies", - "levels": { - "state": "state", - "cd": "congressional_district", - "county": "county" - }, - "source": "US Census Bureau 2020 PUMA population ladder (--ladder)", - "rationale": "One population total for each state, 119th-Congress district and county that --geographies names (the County Files runbook uses state,cd,county)." - }, - { - "id": "county_soi", - "family": "irs_soi", - "levels": { - "county": "county" - }, - "source": "IRS SOI county file in the pinned county facts (--county-facts, us/chronicle_county_facts.json)", - "rationale": "County SOI facts give shares of their state row, never a second state level (tools/us_acs_local_county_surface.py)." - }, - { - "id": "acs_households", - "family": "acs_households", - "levels": { - "state": "state", - "county": "county" - }, - "source": "ACS household counts in the pinned county facts (--county-facts)", - "rationale": "Each state's ACS household total and its county rows (tools/us_acs_local_county_surface.py acs_household_surface)." - } - ] - } - } - } - } -} diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/target_loss_weights.py b/packages/microcosm-build/src/microcosm/build/us_runtime/target_loss_weights.py index 819daca27d..2f352a8b72 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/target_loss_weights.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/target_loss_weights.py @@ -771,7 +771,7 @@ def target_loss_weights_sha256(names: Sequence[str], weights: np.ndarray) -> str def target_geography_level(spec) -> str: - """A spec's geography level, by the level rule of ``us/target_sets.json``. + """A spec's geography level, by the level rule of ``us/spec/target_sets.yaml``. The declared target sets place a target by the same rule (:func:`~.target_sets.us_target_level`), so a US target has one level in diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/target_sets.py b/packages/microcosm-build/src/microcosm/build/us_runtime/target_sets.py index c77f8ee91b..25f29fc4c5 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/target_sets.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/target_sets.py @@ -1,13 +1,20 @@ """The declared target sets of the US releases (microcosm#1728). -``us/target_sets.json`` declares what each US product calibrates to in each +``us/spec/target_sets.yaml`` declares what each US product calibrates to in each mode: the national release (``tools/build_us_fiscal_refresh_release.py``, ``--target-surface``) and the ACS local release (``tools/build_us_acs_local_release.py``, ``--soi-mode``). The shared reader and selector are in :mod:`microcosm.calibrate.target_sets`; this module names the US file, products, predicates and rules. The file also declares the US level rule, which gives every US target its geography level; the UK declares -its rule the same way, in ``uk/target_sets.json`` (microcosm#1759). +its rule the same way, in ``uk/spec/target_sets.yaml`` (microcosm#1759). + +The file is a typed resource of the US spec bundle (kind ``target_sets``): +the spec engine reads it strictly, checks it against +``target_sets.schema.json`` and keeps its descriptions and rationales apart +from its content, which is part of the bundle's ``spec_sha256``. It is +written by hand: the constants-era code never held it, so +``tools/generate_us_bundle_from_constants.py`` does not write it. """ from __future__ import annotations @@ -35,7 +42,7 @@ "us_target_sets_path", ] -US_TARGET_SETS_RESOURCE = "target_sets.json" +US_TARGET_SETS_RESOURCE = "spec/target_sets.yaml" NATIONAL_PRODUCT = "national" LOCAL_PRODUCT = "local" #: The predicate the national ``national_state`` mode excludes by: the shared @@ -53,9 +60,20 @@ def us_target_sets_path() -> Path: @lru_cache(maxsize=1) def us_target_set_declarations() -> TargetSetDeclarations: - """The packaged US declarations, read and checked once.""" + """The packaged US declarations, read and checked once. - return load_target_set_declarations(us_target_sets_path()) + They come through :func:`microcosm.build.country_spec.load_country_target_sets`, + which reads the one typed resource as the bundle loader does. + """ + + # Imported here: the country spec module is large, and this module is + # imported by modules that the country spec's own imports reach. + from microcosm.build.country_spec import load_country_target_sets + + document = load_country_target_sets("us") + if document is None: # pragma: no cover - the package declares the resource + raise RuntimeError("The US package declares no target_sets resource.") + return load_target_set_declarations(document) def us_target_set_declaration(product: str, mode: str) -> TargetSetDeclaration: diff --git a/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py b/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py index d3c5812f7d..77c885f6f0 100644 --- a/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py +++ b/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py @@ -82,22 +82,22 @@ def test_us_coverage_is_exact_complete_and_honest( assert_coverage_complete(coverage_report) assert coverage_report["status"] == "pass" fields = coverage_report["field_usage"] - assert fields["configuration_field_count"] == 42413 - assert fields["authored_normative_field_count"] == 32627 + assert fields["configuration_field_count"] == 42557 + assert fields["authored_normative_field_count"] == 32771 assert fields["resolved_binding_field_count"] == 9786 - assert fields["consumed_field_count"] == 42413 + assert fields["consumed_field_count"] == 42557 assert fields["unused_field_count"] == 0 assert fields["multiple_primary_use_field_count"] == 0 - assert fields["claim_count"] == 48 + assert fields["claim_count"] == 49 assert fields["mode_counts"] == { "legacy_behavior": 14_269, "compiler_semantic": 27674, - "front_end_validation": 367, + "front_end_validation": 511, "identity_only": 103, } assert fields["generation0_effect_counts"] == { "legacy_behavior": 38_780, - "no_generation0_effect": 3633, + "no_generation0_effect": 3777, } inventory = coverage_report["inventory_coverage"] diff --git a/packages/microcosm-build/tests/engine_contract/us/test_us_spec_bundle.py b/packages/microcosm-build/tests/engine_contract/us/test_us_spec_bundle.py index 48a2c5a573..a6cf24764d 100644 --- a/packages/microcosm-build/tests/engine_contract/us/test_us_spec_bundle.py +++ b/packages/microcosm-build/tests/engine_contract/us/test_us_spec_bundle.py @@ -150,7 +150,8 @@ def test_typed_domains_are_exact_legacy_compatibility_projections( ) -> None: __import__("policyengine_us") documents = { - f"{kind}.yaml": _domain(resolved_us_spec, kind) for kind in TYPED_DOMAIN_KINDS + f"{kind}.yaml": _domain(resolved_us_spec, kind) + for kind in GENERATED_DOMAIN_KINDS } projections = generator.legacy_compatibility_projections(documents) for name, projection in projections.items(): @@ -442,7 +443,11 @@ def test_generator_reproduces_every_checked_in_bundle_byte( generated_documents: dict[str, dict[str, object]], monkeypatch: pytest.MonkeyPatch, ) -> None: - assert set(generated_documents) == {f"{kind}.yaml" for kind in TYPED_DOMAIN_KINDS} + assert set(generated_documents) == { + f"{kind}.yaml" for kind in GENERATED_DOMAIN_KINDS + } + assert set(generator.AUTHORED_DOMAIN_KINDS) == AUTHORED_DOMAIN_KINDS + assert set(generator.DOMAIN_KINDS) == GENERATED_DOMAIN_KINDS for filename, expected in generated_documents.items(): path = US_SPEC_ROOT / filename assert load_yaml12_file(path) == expected diff --git a/packages/microcosm-build/tests/engine_free/shared/test_country_spec.py b/packages/microcosm-build/tests/engine_free/shared/test_country_spec.py index e144a1192b..4bf98728b4 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_country_spec.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_country_spec.py @@ -1228,9 +1228,6 @@ def test_spi_spine_adds_no_country_package_resources(self) -> None: "desnz_constituency_energy_facts.json", "local_small_cell_rule.json", "hmrc_spi_table_3_11_uk_rows.json", - # microcosm#1759: the UK level rule, the full build's selection - # by level and the calibration lines. - "target_sets.json", ) def test_uk_source_manifest_contains_only_canonical_spine_stages(self) -> None: @@ -1290,6 +1287,9 @@ def test_uk_package_loads(self) -> None: "spec/geography.yaml", "spec/sources.yaml", "spec/spine.yaml", + # microcosm#1759: the UK level rule, the full build's selection + # by level and the calibration lines, as a typed resource. + "spec/target_sets.yaml", "spec/vintages.yaml", "degenerate_reviewed_exclusions.json", "target_fit_reviewed_exclusions.json", @@ -1425,9 +1425,6 @@ def test_uk_package_loads(self) -> None: "desnz_constituency_energy_facts.json", "local_small_cell_rule.json", "hmrc_spi_table_3_11_uk_rows.json", - # microcosm#1759: the UK level rule, the full build's selection - # by level and the calibration lines. - "target_sets.json", ) def test_uk_target_references_accept_regenerated_contract_fields(self) -> None: diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_compiler_ir.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_compiler_ir.py index a59775325c..384cc63ec7 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_compiler_ir.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_compiler_ir.py @@ -166,6 +166,7 @@ def test_ir_retains_all_typed_resolution_products(compiled_us: CompiledSpecIR) - "sources", "spine", "take_up", + "target_sets", "vintages", } diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_country_bundles.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_country_bundles.py index ad409d4de8..c3d9b520e6 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_country_bundles.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_country_bundles.py @@ -92,7 +92,9 @@ def test_country_bundle_loads_once_and_compiles_through_the_shared_core( assert country_spec.resolved_spec.spec_sha256 == direct.spec_sha256 compiled = compile_spec(direct) - assert set(compiled.resources_wire()) == EXPECTED_RESOURCES + # The UK also declares its target sets as a typed resource (microcosm#1759). + declared_target_sets = {"target_sets"} if country == "uk" else set() + assert set(compiled.resources_wire()) == EXPECTED_RESOURCES | declared_target_sets assert not compiled.producer_graph.present assert compiled.nodes == () assert {column.key for column in direct.columns} == expected_columns diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py index 6c08206980..20bd3ae356 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py @@ -95,22 +95,22 @@ def _mutated_bundle( def test_exact_complete_ledger_has_one_primary_mode_per_pointer(field_ledger) -> None: - assert len(field_ledger.fields) == EXPECTED_CONFIGURATION_FIELD_COUNT == 42413 + assert len(field_ledger.fields) == EXPECTED_CONFIGURATION_FIELD_COUNT == 42557 assert field_ledger.source_counts == { - "authored": 32627, + "authored": 32771, "resolved_bindings": 9786, } assert field_ledger.mode_counts == { "legacy_behavior": 14_269, "compiler_semantic": 27674, - "front_end_validation": 367, + "front_end_validation": 511, "identity_only": 103, } assert field_ledger.generation0_effect_counts == { "legacy_behavior": 38_780, - "no_generation0_effect": 3633, + "no_generation0_effect": 3777, } - assert len({field.pointer for field in field_ledger.fields}) == 42413 + assert len({field.pointer for field in field_ledger.fields}) == 42557 def test_eligibility_concepts_are_validation_not_generation0_behavior( diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_schema.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_schema.py index 8956ad3ca4..a50dcca189 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_schema.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_schema.py @@ -34,7 +34,7 @@ def test_schema_registry_loads_only_the_approved_closed_world() -> None: catalog = load_schema_registry() assert frozenset(catalog.schemas) == SCHEMA_IDS - assert len(catalog.schemas) == 15 + assert len(catalog.schemas) == 16 assert catalog.schema("locks.schema.json#/$defs/bundle_lock")["required"] == [ "grammar_receipt", "files", diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_target_sets.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_target_sets.py new file mode 100644 index 0000000000..698df04300 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_target_sets.py @@ -0,0 +1,481 @@ +"""The declared target sets as a typed resource of the spec engine (microcosm#1755). + +A country ships its declared target sets as ``spec/target_sets.yaml``, kind +``target_sets``, schema ``target_sets.schema.json``. The spec engine reads the +file strictly, checks its form, and separates the descriptions and rationales +(documentation) from the content a selection reads (normative). These tests +hold that split, the content hash that a cache key can use, and the narrow +loader that the country modules read through. +""" + +from __future__ import annotations + +import copy +import json +from pathlib import Path + +import pytest + +from microcosm.build import country_spec +from microcosm.build.country_spec import ( + load_country_target_sets, + typed_resource_content_sha256, +) +from microcosm.build.spec_engine import load_schema_registry +from microcosm.build.spec_engine.canonical import normalize_and_project +from microcosm.build.spec_engine.errors import SpecParseError, SpecValidationError +from microcosm.build.spec_engine.model import ResourceKind, thaw_json +from microcosm.build.spec_engine.schemas import ( + SCHEMA_ID_BY_KIND, + assert_schema_id_allowed, +) +from microcosm.calibrate.target_sets import ( + TargetSetDeclarationError, + load_target_set_declarations, +) + +SCHEMA = "target_sets.schema.json" + +DECLARATIONS = { + "version": 1, + "country": "zz", + "description": "What this file declares.", + "level_rule": { + "keys": ["level", "geo"], + "values": ["state", "district", "country"], + "conflict": "refuse", + "rationale": "Why a level is read this way.", + }, + "products": [ + { + "id": "national", + "tool": "tools/national.py", + "option": "--surface", + "default_mode": "all", + "modes": [ + { + "id": "all", + "description": "Every compiled target.", + "compiled": [ + { + "id": "all", + "families": "*", + "levels": "*", + "exclude": ["district"], + "rationale": "Why every row.", + } + ], + } + ], + }, + { + "id": "local", + "tool": "tools/local.py", + "option": "--mode", + "default_mode": "state", + "modes": [ + { + "id": "state", + "description": "State benefit and state tax rows.", + "compiled": [ + { + "id": "benefit", + "families": ["benefit"], + "levels": ["state"], + "metadata": {"state": {"present": True}}, + "rationale": "Why the benefit rows.", + }, + { + "id": "tax", + "families": ["tax", "levy"], + "levels": ["state", "district"], + "metadata": { + "state": {"present": True}, + "role": {"not_equals": "band"}, + }, + "rule": "shares", + "rationale": "Why the tax rows.", + }, + ], + "built": [ + { + "id": "population", + "family": "population", + "option": "--geographies", + "levels": {"state": "state", "cd": "district"}, + "source": "a ladder", + "rationale": "Why the population rows.", + } + ], + }, + { + "id": "totals", + "description": "The state totals.", + "compiled": [ + { + "id": "tax", + "families": ["tax"], + "levels": ["state"], + "rationale": "Why the totals.", + } + ], + }, + ], + }, + ], +} + +_DELETE = object() + + +def _edited(**changes) -> dict: + """``DECLARATIONS`` with each ``a__b__c`` path set to its value. + + A step into a list is an index, or the ``id`` of one of its objects. + """ + + raw = copy.deepcopy(DECLARATIONS) + for path, value in changes.items(): + node = raw + *parents, leaf = path.split("__") + for key in parents: + if not isinstance(node, list): + node = node[key] + elif key.isdigit(): + node = node[int(key)] + else: + (node,) = [item for item in node if item["id"] == key] + if value is _DELETE: + del node[leaf] + else: + node[leaf] = value + return raw + + +def _write(tmp_path: Path, raw: object, *, text: str | None = None) -> Path: + """A ``target_sets.yaml`` holding ``raw`` (JSON is YAML 1.2) or ``text``.""" + + path = tmp_path / "target_sets.yaml" + path.write_text( + json.dumps(raw, indent=1) if text is None else text, encoding="utf-8" + ) + return path + + +def _content(tmp_path: Path, **changes) -> str: + return typed_resource_content_sha256(_write(tmp_path, _edited(**changes)), SCHEMA) + + +def _package(tmp_path: Path, raw: object, *, text: str | None = None) -> Path: + """A country package ``zz`` that declares only its target sets.""" + + root = tmp_path / "zz" + (root / "spec").mkdir(parents=True, exist_ok=True) + (root / "country_package.json").write_text( + json.dumps( + { + "schema_version": 1, + "country": "zz", + "resources": [ + { + "path": "spec/target_sets.yaml", + "kind": "target_sets", + "schema_id": SCHEMA, + } + ], + } + ), + encoding="utf-8", + ) + _write(root / "spec", raw, text=text) + return root + + +_STATE = "products__local__modes__state" + + +# --------------------------------------------------------------------------- +# The kind and its schema +# --------------------------------------------------------------------------- + + +def test_the_target_sets_kind_has_one_schema() -> None: + assert ResourceKind.TARGET_SETS.value == "target_sets" + assert SCHEMA_ID_BY_KIND["target_sets"] == SCHEMA + assert "target_sets" in country_spec.ALLOWED_COUNTRY_RESOURCE_KINDS + assert_schema_id_allowed("target_sets", SCHEMA) + with pytest.raises(SpecValidationError, match="cannot use schema_id"): + assert_schema_id_allowed("target_sets", "legacy_json") + with pytest.raises(SpecValidationError, match="cannot use schema_id"): + assert_schema_id_allowed("legacy_json", SCHEMA) + load_schema_registry().validate(DECLARATIONS, SCHEMA) + + +@pytest.mark.parametrize( + ("changes", "message"), + [ + ({"version": 2}, "1 was expected"), + ({"extra": True}, "Additional properties"), + # The level rule has one form; the short form is not in the grammar. + ({"level_keys": ["level", "geo"]}, "Additional properties"), + ({"level_rule": _DELETE}, "'level_rule' is a required property"), + ({"level_rule__conflict": "maybe"}, "is not one of"), + ({"level_rule__keys": []}, "should be non-empty"), + ({"level_rule__values": []}, "is not valid under any of the given schemas"), + ({"level_rule__rationale": _DELETE}, "'rationale' is a required property"), + ({"products": []}, "should be non-empty"), + # Products and modes are lists with ids, not objects keyed by name. + ({"products": {"national": {}}}, "is not of type 'array'"), + ({"products__local__id": _DELETE}, "'id' is a required property"), + ({"products__local__modes": []}, "should be non-empty"), + ({f"{_STATE}__compiled": []}, "should be non-empty"), + ({f"{_STATE}__compiled__0__families": []}, "is not valid under any"), + ({f"{_STATE}__compiled__0__levels": ["state", "state"]}, "is not valid under"), + ({f"{_STATE}__compiled__0__rationale": _DELETE}, "'rationale' is a required"), + ({f"{_STATE}__compiled__0__metadata": {"state": {"in": 1}}}, "is not valid"), + ( + {f"{_STATE}__compiled__0__metadata": {"state": {"present": "yes"}}}, + "is not valid", + ), + ({f"{_STATE}__compiled__0__left": 1}, "Additional properties"), + ({f"{_STATE}__built__0__levels": {}}, "should be non-empty"), + ({f"{_STATE}__built__0__source": _DELETE}, "'source' is a required property"), + ], +) +def test_the_schema_refuses_a_malformed_declaration(changes, message) -> None: + with pytest.raises(SpecValidationError, match=message): + load_schema_registry().validate(_edited(**changes), SCHEMA) + + +# --------------------------------------------------------------------------- +# Normative content and documentation +# --------------------------------------------------------------------------- + + +def _leaves(node: object, path: str = "") -> dict[str, object]: + if isinstance(node, dict): + found: dict[str, object] = {} + for key, value in node.items(): + found.update(_leaves(value, f"{path}/{key}")) + return found + if isinstance(node, list): + found = {} + for index, value in enumerate(node): + found.update(_leaves(value, f"{path}/{index}")) + return found + return {path: node} + + +def test_the_descriptions_and_rationales_are_documentation() -> None: + registry = load_schema_registry() + _normalized, projections = normalize_and_project( + registry.validate_and_inject_defaults(DECLARATIONS, SCHEMA), + schema_id=SCHEMA, + registry=registry, + ) + surfaces = thaw_json(projections) + + documentation = _leaves(surfaces["documentation"]) + normative = _leaves(surfaces["normative"]) + everything = _leaves(DECLARATIONS) + + assert {path.rsplit("/", 1)[1] for path in documentation} == { + "description", + "rationale", + } + # Top, level rule, three modes, four clauses and one built entry. + assert len(documentation) == 10 + assert not any( + path.rsplit("/", 1)[1] in {"description", "rationale"} for path in normative + ) + assert len(normative) + len(documentation) == len(everything) + # Only these two surfaces hold a field of a declaration. + assert {surface for surface, fragment in surfaces.items() if _leaves(fragment)} == { + "normative", + "documentation", + } + + +@pytest.mark.parametrize( + "changes", + [ + {"description": "Other words."}, + {"description": _DELETE}, + {"level_rule__rationale": "Another reason."}, + {f"{_STATE}__description": "Other words."}, + {f"{_STATE}__compiled__0__rationale": "Another reason."}, + {f"{_STATE}__built__0__rationale": "Another reason."}, + # Names in a list of families or levels are a set. + {f"{_STATE}__compiled__1__families": ["levy", "tax"]}, + {f"{_STATE}__compiled__1__levels": ["district", "state"]}, + {"level_rule__values": ["country", "district", "state"]}, + # A clause's metadata tests are an object: every one must pass. + { + f"{_STATE}__compiled__1__metadata": { + "role": {"not_equals": "band"}, + "state": {"present": True}, + } + }, + {f"{_STATE}__built__0__levels": {"cd": "district", "state": "state"}}, + ], +) +def test_the_content_hash_does_not_read_prose_or_set_order(tmp_path, changes) -> None: + assert _content(tmp_path, **changes) == _content(tmp_path) + + +def test_the_content_hash_does_not_read_the_layout_of_the_file(tmp_path) -> None: + import yaml + + def reversed_fields(node): + if isinstance(node, dict): + return {key: reversed_fields(node[key]) for key in reversed(node)} + if isinstance(node, list): + return [reversed_fields(item) for item in node] + return node + + as_json = _content(tmp_path) + block_yaml = yaml.safe_dump(DECLARATIONS, sort_keys=False, width=60) + assert block_yaml.lstrip()[0] != "{" + flow_json = json.dumps(reversed_fields(DECLARATIONS), indent=7) + for text in ("# A comment.\n" + block_yaml, flow_json): + assert ( + typed_resource_content_sha256(_write(tmp_path, None, text=text), SCHEMA) + == as_json + ) + + +@pytest.mark.parametrize( + "changes", + [ + {"country": "yy"}, + {"level_rule__keys": ["geo", "level"]}, + {"level_rule__values": ["state", "district"]}, + {"level_rule__values": "*"}, + {"level_rule__conflict": "first"}, + {"products__local__tool": "tools/other.py"}, + {"products__local__option": "--other"}, + {"products__local__default_mode": "totals"}, + {"products__local__id": "area"}, + {f"{_STATE}__id": "states"}, + {f"{_STATE}__compiled__0__id": "benefits"}, + {f"{_STATE}__compiled__0__families": ["benefit", "tax"]}, + {f"{_STATE}__compiled__0__families": "*"}, + {f"{_STATE}__compiled__0__levels": ["state", "district"]}, + {f"{_STATE}__compiled__0__levels": "*"}, + {f"{_STATE}__compiled__0__metadata": {"state": {"present": False}}}, + {f"{_STATE}__compiled__1__metadata__role": {"equals": "band"}}, + {f"{_STATE}__compiled__0__exclude": ["a_predicate"]}, + {f"{_STATE}__compiled__0__rule": "a_rule"}, + {f"{_STATE}__compiled__1__rule": _DELETE}, + {f"{_STATE}__built__0__family": "people"}, + {f"{_STATE}__built__0__levels": {"state": "state"}}, + {f"{_STATE}__built__0__option": "--areas"}, + {f"{_STATE}__built__0__source": "another ladder"}, + {f"{_STATE}__built": _DELETE}, + ], +) +def test_the_content_hash_reads_every_field_a_selection_can_use( + tmp_path, changes +) -> None: + assert _content(tmp_path, **changes) != _content(tmp_path) + + +def test_the_content_hash_reads_the_order_of_clauses_modes_and_products( + tmp_path, +) -> None: + packaged = _content(tmp_path) + + raw = _edited() + raw["products"][1]["modes"][0]["compiled"].reverse() + assert typed_resource_content_sha256(_write(tmp_path, raw), SCHEMA) != packaged + + raw = _edited() + raw["products"][1]["modes"].reverse() + assert typed_resource_content_sha256(_write(tmp_path, raw), SCHEMA) != packaged + + raw = _edited() + raw["products"].reverse() + assert typed_resource_content_sha256(_write(tmp_path, raw), SCHEMA) != packaged + + +# --------------------------------------------------------------------------- +# The narrow loader +# --------------------------------------------------------------------------- + + +def test_the_narrow_loader_gives_the_object_the_reader_takes(tmp_path) -> None: + document = load_country_target_sets(_package(tmp_path, DECLARATIONS)) + + declarations = load_target_set_declarations(document) + assert declarations.country == "zz" + assert tuple(declarations.products) == ("national", "local") + assert declarations.product("local").mode_names == ("state", "totals") + assert declarations.declaration("local", "state").clause_ids == ("benefit", "tax") + assert declarations.level_rule.keys == ("level", "geo") + assert declarations.level_rule.values == {"state", "district", "country"} + # The names of a set are in canonical order in the loaded object. + assert document["level_rule"]["values"] == ["country", "district", "state"] + + +def test_a_package_without_target_sets_gives_none() -> None: + assert load_country_target_sets("be") is None + + +def test_the_file_is_read_strictly(tmp_path) -> None: + text = json.dumps(DECLARATIONS) + with pytest.raises(SpecParseError, match="duplicate mapping key"): + load_country_target_sets( + _package(tmp_path, None, text='{"version": 1, ' + text[1:]) + ) + with pytest.raises(SpecParseError): + load_country_target_sets( + _package(tmp_path, None, text=text[:-1] + ', "extra": .nan}') + ) + with pytest.raises(SpecValidationError, match="Additional properties"): + load_country_target_sets(_package(tmp_path, _edited(extra=True))) + + +def test_the_reader_refuses_what_the_schema_cannot_state(tmp_path) -> None: + # A list holds literal names, so ["*"] would match only a name "*". + with pytest.raises(TargetSetDeclarationError, match="alone, not a list"): + load_country_target_sets( + _package(tmp_path, _edited(**{f"{_STATE}__compiled__0__families": ["*"]})) + ) + with pytest.raises(TargetSetDeclarationError, match="not a declared mode"): + load_country_target_sets( + _package(tmp_path, _edited(products__local__default_mode="county")) + ) + with pytest.raises(TargetSetDeclarationError, match="repeats a clause"): + load_country_target_sets( + _package(tmp_path, _edited(**{f"{_STATE}__compiled__1__id": "benefit"})) + ) + twice = _edited() + twice["products"][1]["modes"].append( + copy.deepcopy(twice["products"][1]["modes"][0]) + ) + with pytest.raises(TargetSetDeclarationError, match="repeats the mode 'state'"): + load_country_target_sets(_package(tmp_path, twice)) + with pytest.raises(ValueError, match="lives in the 'zz' package"): + load_country_target_sets(_package(tmp_path, _edited(country="yy"))) + + +@pytest.mark.parametrize("country", ["uk", "us"]) +def test_each_packaged_file_is_a_typed_resource_that_loads(country) -> None: + """The packaged declarations are a typed resource, and they load through + the narrow loader. ``test_uk_solve_scope.py`` and ``test_us_spec_bundle.py`` + hold the loader to the object and the content hash of the whole bundle.""" + + document = load_country_target_sets(country) + assert document is not None + assert load_target_set_declarations(document).country == country + + root = Path(country_spec.__file__).parent / country + manifest = json.loads((root / "country_package.json").read_text(encoding="utf-8")) + (row,) = [row for row in manifest["resources"] if row["kind"] == "target_sets"] + assert row == { + "path": "spec/target_sets.yaml", + "kind": "target_sets", + "schema_id": SCHEMA, + } + assert (root / row["path"]).is_file() + assert not (root / "target_sets.json").exists() diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_calibration_line_selection.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_calibration_line_selection.py index 454b7d1ca3..bf84fd7a4c 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_calibration_line_selection.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_calibration_line_selection.py @@ -2,7 +2,7 @@ Before microcosm#1759, ``uk_runtime.ledger_targets.uk_registry_on_calibration_line`` dropped the targets that a line does not bind with its own loop. It now -selects through ``uk/target_sets.json`` (product ``calibration_line``, one mode +selects through ``uk/spec/target_sets.yaml`` (product ``calibration_line``, one mode for each line) with the shared ``select_target_set`` and one UK predicate. ``test_support/microcosm_build/calibration_line_reference.py`` holds the old function verbatim. On random registries the two give the same registry (the diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_level_selection.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_level_selection.py index 8e151018bc..83d651649e 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_level_selection.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_level_selection.py @@ -4,7 +4,7 @@ ``microcosm.calibrate.target_selection.select_targets`` and the UK resolver ``uk_runtime.graph_targets.target_geography``. It now selects with the shared ``microcosm.calibrate.target_sets.select_by_levels`` and the UK's declared -level rule (``uk/target_sets.json``). ``test_support/microcosm_build/target_selection_reference.py`` +level rule (``uk/spec/target_sets.yaml``). ``test_support/microcosm_build/target_selection_reference.py`` holds verbatim copies of the old code. On random registries and requests the two give the same registry, the same receipt bytes, or the same refusal. """ @@ -24,7 +24,7 @@ UK_LEVELS = ("country", "region", "constituency", "la", "brma") -#: The full build's level mode, as uk/target_sets.json declares it. +#: The full build's level mode, as uk/spec/target_sets.yaml declares it. DECLARATION = uk_full_level_selection() diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_solve_scope.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_solve_scope.py index 0a463e37d8..6d4f0cacb2 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_solve_scope.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_solve_scope.py @@ -7,6 +7,12 @@ sound from both sides: the source names no gate-only file outside the gate machinery, and editing each one leaves every solve kernel's key unchanged while the calibrated gates re-key. + +The declared target sets (``spec/target_sets.yaml``, a typed resource of the +spec bundle) are in the solve fingerprint by their normative content, not by +their bytes (microcosm#1755): an edit to their prose or their layout leaves +every solve kernel's key as it was, and an edit to a clause, a level or an +exclusion changes every one of them. """ from __future__ import annotations @@ -14,6 +20,7 @@ import ast import hashlib import inspect +import json import types from dataclasses import replace from pathlib import Path @@ -36,6 +43,7 @@ UKFullPreflightGateKernel, ) from microcosm.build.uk_runtime.solve_scope import ( + UK_CONTENT_KEYED_RESOURCES, UK_GATE_ONLY_RESOURCES, UK_POST_SOLVE_RESOURCES, uk_solve_fingerprint, @@ -44,6 +52,10 @@ from microcosm.build.uk_runtime.target_compile_modules import ( UK_TARGET_COMPILE_MODULE_NAMES, ) +from microcosm.build.uk_runtime.target_sets import ( + UK_TARGET_SETS_RESOURCE, + uk_target_sets_path, +) from test_support.paths import paths_for _PATHS = paths_for("microcosm-build") @@ -243,11 +255,57 @@ def readers() -> dict[str, set[str]]: def _perturbed(*resources: str) -> country_spec.ResolvedCountrySpec: + """The packaged spec after an edit to the content of each resource: its + byte hash changes, and so does its content hash when it has one.""" + spec = country_spec.load_country_spec("uk") hashes = dict(spec.resource_hashes) + content = dict(spec.content_hashes) for resource in resources: hashes[resource] = hashlib.sha256(hashes[resource].encode()).hexdigest() - return replace(spec, resource_hashes=MappingProxyType(hashes)) + if resource in content: + content[resource] = hashlib.sha256(content[resource].encode()).hexdigest() + return replace( + spec, + resource_hashes=MappingProxyType(hashes), + content_hashes=MappingProxyType(content), + ) + + +_TARGET_SETS_SCHEMA = "target_sets.schema.json" + + +def _with_target_sets(text: str, tmp_path: Path) -> country_spec.ResolvedCountrySpec: + """The packaged spec with ``text`` as its ``spec/target_sets.yaml``. + + The byte hash is the hash of the text. The content hash is the one the + loader gives a typed resource: the hash of its normative projection + (``country_spec.typed_resource_content_sha256``). The other resources are + as packaged. + """ + + path = tmp_path / "target_sets.yaml" + path.write_text(text, encoding="utf-8") + spec = country_spec.load_country_spec("uk") + return replace( + spec, + resource_hashes=MappingProxyType( + { + **spec.resource_hashes, + UK_TARGET_SETS_RESOURCE: hashlib.sha256( + text.encode("utf-8") + ).hexdigest(), + } + ), + content_hashes=MappingProxyType( + { + **spec.content_hashes, + UK_TARGET_SETS_RESOURCE: country_spec.typed_resource_content_sha256( + path, _TARGET_SETS_SCHEMA + ), + } + ), + ) # --------------------------------------------------------------------------- @@ -393,12 +451,28 @@ def test_fingerprint_excluding_refuses_what_it_cannot_honour(): # excluding nothing is not the full fingerprint. assert spec.fingerprint_excluding(()) != spec.fingerprint excluded = UK_GATE_ONLY_RESOURCES | UK_POST_SOLVE_RESOURCES - assert spec.fingerprint_excluding(excluded) == uk_solve_fingerprint() - assert spec.fingerprint_excluding(UK_GATE_ONLY_RESOURCES) != uk_solve_fingerprint() + by_content = UK_CONTENT_KEYED_RESOURCES + solve = uk_solve_fingerprint() + assert spec.fingerprint_excluding(excluded, by_content=by_content) == solve assert ( - spec.fingerprint_excluding(excluded | {"degenerate_reviewed_exclusions.json"}) - != uk_solve_fingerprint() + spec.fingerprint_excluding(UK_GATE_ONLY_RESOURCES, by_content=by_content) + != solve ) + assert ( + spec.fingerprint_excluding( + excluded | {"degenerate_reviewed_exclusions.json"}, by_content=by_content + ) + != solve + ) + # The resources hashed by content are bound too: the same exclusions with + # every resource hashed by its bytes is another fingerprint. + assert spec.fingerprint_excluding(excluded) != solve + with pytest.raises(ValueError, match="have no content hash"): + spec.fingerprint_excluding(excluded, by_content={"gates.json"}) + with pytest.raises(ValueError, match="both excluded and hashed by content"): + spec.fingerprint_excluding(excluded | by_content, by_content=by_content) + with pytest.raises(TypeError, match="collection"): + spec.fingerprint_excluding(excluded, by_content=UK_TARGET_SETS_RESOURCE) # --------------------------------------------------------------------------- @@ -439,11 +513,14 @@ def version(distribution): monkeypatch.setattr(metadata, "version", version) -def _hashes(monkeypatch, *resources): +def _hashes(monkeypatch, *resources, spec=None): + """Every solve kernel's key and the calibrated gates' key: on the packaged + spec, after an edit to ``resources``, or on ``spec``.""" + calibrated = UKFullGateKernel(coverage_engine=object(), engine_identity="fixture") with monkeypatch.context() as patch: - if resources: - edited = _perturbed(*resources) + if resources or spec is not None: + edited = _perturbed(*resources) if spec is None else spec patch.setattr( country_spec, "_load_packaged_country_spec", lambda _country: edited ) @@ -475,6 +552,186 @@ def test_a_solve_scoped_edit_rekeys_every_solve_kernel( assert edited_calibrated != calibrated +# --------------------------------------------------------------------------- +# The declared target sets: in the solve fingerprint by content +# --------------------------------------------------------------------------- + + +def _target_sets() -> dict: + """The packaged file as authored: parsed, before defaults and sorting.""" + + from microcosm.build.spec_engine import load_yaml12_file + + return load_yaml12_file(uk_target_sets_path()) + + +def _as_text(raw: dict) -> str: + """``raw`` as a file. JSON is YAML 1.2, so the strict reader takes it.""" + + return json.dumps(raw, indent=1, ensure_ascii=False) + "\n" + + +def _full_levels(raw: dict) -> dict: + """The full build's selection by level: the first product's one mode.""" + + (mode,) = raw["products"][0]["modes"] + assert (raw["products"][0]["id"], mode["id"]) == ("full", "levels") + return mode + + +def _calibration_lines(raw: dict) -> list: + product = raw["products"][1] + assert product["id"] == "calibration_line" + return product["modes"] + + +def _reworded(raw: dict) -> str: + """Every description and rationale of the file, with words added.""" + + raw["description"] += " More words." + raw["level_rule"]["rationale"] += " More words." + for product in raw["products"]: + for mode in product["modes"]: + mode["description"] += " More words." + for entry in (*mode["compiled"], *mode.get("built", ())): + entry["rationale"] += " More words." + return _as_text(raw) + + +def _reformatted(raw: dict) -> str: + """The same declarations in another layout: JSON in place of block YAML, + another indent, no final newline, and the fields of every object in the + reverse order.""" + + def relaid(node): + if isinstance(node, dict): + return {key: relaid(node[key]) for key in reversed(node)} + if isinstance(node, list): + return [relaid(item) for item in node] + return node + + relaid_raw = relaid(raw) + assert list(relaid_raw) != list(raw) + return json.dumps(relaid_raw, indent=4, ensure_ascii=False) + + +def _level_names_reordered(raw: dict) -> str: + """The names in a list of levels are a set: their order is not content.""" + + raw["level_rule"]["values"].reverse() + return _as_text(raw) + + +def _level_added(raw: dict) -> str: + raw["level_rule"]["values"].append("ward") + return _as_text(raw) + + +def _clause_level_changed(raw: dict) -> str: + _full_levels(raw)["compiled"][0]["levels"] = ["region"] + return _as_text(raw) + + +def _clause_family_changed(raw: dict) -> str: + _full_levels(raw)["compiled"][0]["families"] = ["tax"] + return _as_text(raw) + + +def _exclusion_removed(raw: dict) -> str: + del _calibration_lines(raw)[0]["compiled"][0]["exclude"] + return _as_text(raw) + + +def _clauses_reordered(raw: dict) -> str: + _full_levels(raw)["compiled"].reverse() + return _as_text(raw) + + +def _modes_reordered(raw: dict) -> str: + """The calibration lines are in declared order: a refusal lists them.""" + + _calibration_lines(raw).reverse() + return _as_text(raw) + + +def test_the_packaged_target_sets_have_the_content_hash_of_the_bundle(): + """The solve keys on the hash the bundle gives the typed resource, and the + builds read the object the bundle holds.""" + + spec = country_spec.load_country_spec("uk") + assert UK_CONTENT_KEYED_RESOURCES == {UK_TARGET_SETS_RESOURCE} + assert UK_CONTENT_KEYED_RESOURCES <= set(spec.resources) + assert not UK_CONTENT_KEYED_RESOURCES & ( + UK_GATE_ONLY_RESOURCES | UK_POST_SOLVE_RESOURCES + ) + # Every typed resource has a content hash, and no legacy JSON file has. + typed = {row.path for row in spec.resource_rows if row.kind != "legacy_json"} + assert set(spec.content_hashes) == typed + assert spec.content_hashes[UK_TARGET_SETS_RESOURCE] == ( + country_spec.typed_resource_content_sha256( + uk_target_sets_path(), _TARGET_SETS_SCHEMA + ) + ) + assert spec.resolved_spec.domain("target_sets").to_wire() == ( + country_spec.load_country_target_sets("uk") + ) + + +def test_the_unedited_target_sets_text_gives_the_packaged_hashes(tmp_path): + """The helper that edits the file gives the loader's own hashes.""" + + spec = country_spec.load_country_spec("uk") + text = uk_target_sets_path().read_text(encoding="utf-8") + same = _with_target_sets(text, tmp_path) + assert same.resource_hashes == spec.resource_hashes + assert same.content_hashes == spec.content_hashes + # The same declarations as JSON have other bytes and the same content. + as_json = _with_target_sets(_as_text(_target_sets()), tmp_path) + assert as_json.resource_hashes != spec.resource_hashes + assert as_json.content_hashes == spec.content_hashes + + +@pytest.mark.parametrize("edit", [_reworded, _reformatted, _level_names_reordered]) +def test_a_target_set_prose_or_layout_edit_rekeys_no_solve_kernel( + edit, tmp_path, monkeypatch, stand_in_dependency_versions +): + spec = country_spec.load_country_spec("uk") + edited = _with_target_sets(edit(_target_sets()), tmp_path) + assert edited.resource_hashes != spec.resource_hashes + assert edited.fingerprint != spec.fingerprint + assert uk_solve_fingerprint(edited) == uk_solve_fingerprint(spec) + + solve, calibrated = _hashes(monkeypatch) + edited_solve, edited_calibrated = _hashes(monkeypatch, spec=edited) + assert edited_solve == solve + # The calibrated gates key on every byte of the package. + assert edited_calibrated != calibrated + + +@pytest.mark.parametrize( + "edit", + [ + _level_added, + _clause_level_changed, + _clause_family_changed, + _exclusion_removed, + _clauses_reordered, + _modes_reordered, + ], +) +def test_a_target_set_content_edit_rekeys_every_solve_kernel( + edit, tmp_path, monkeypatch, stand_in_dependency_versions +): + spec = country_spec.load_country_spec("uk") + edited = _with_target_sets(edit(_target_sets()), tmp_path) + assert uk_solve_fingerprint(edited) != uk_solve_fingerprint(spec) + + solve, calibrated = _hashes(monkeypatch) + edited_solve, edited_calibrated = _hashes(monkeypatch, spec=edited) + assert {name for name in solve if edited_solve[name] == solve[name]} == set() + assert edited_calibrated != calibrated + + # --------------------------------------------------------------------------- # The source scan # --------------------------------------------------------------------------- diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_spec_bundle.py b/packages/microcosm-build/tests/engine_free/us/test_us_spec_bundle.py index dc816db364..9db1495bc5 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_spec_bundle.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_spec_bundle.py @@ -4,7 +4,7 @@ from test_support.microcosm_build.us_spec_bundle import * -def test_us_package_has_twelve_typed_domains_and_loads_through_one_seam( +def test_us_package_has_thirteen_typed_domains_and_loads_through_one_seam( resolved_us_spec: ResolvedSpec, resolved_country_spec: ResolvedCountrySpec, ) -> None: @@ -13,7 +13,7 @@ def test_us_package_has_twelve_typed_domains_and_loads_through_one_seam( assert isinstance(resources, list) typed_rows = [row for row in resources if row["kind"] != "legacy_json"] - assert len(typed_rows) == 12 + assert len(typed_rows) == 13 assert {row["kind"] for row in typed_rows} == TYPED_DOMAIN_KINDS assert all( row @@ -43,6 +43,31 @@ def test_us_package_has_twelve_typed_domains_and_loads_through_one_seam( assert len(resolved_country_spec.support_spine.support_spine.sources) == 2 +def test_the_declared_target_sets_are_the_bundles_typed_domain( + resolved_country_spec: ResolvedCountrySpec, +) -> None: + """The release tools read the declared target sets through a narrow + loader. It gives the object that the whole bundle holds, and the content + hash of a second read is the bundle's.""" + + from microcosm.build import country_spec + + assert resolved_country_spec.resolved_spec is not None + domain = resolved_country_spec.resolved_spec.domain("target_sets").to_wire() + assert country_spec.load_country_target_sets("us") == domain + path = "spec/target_sets.yaml" + assert resolved_country_spec.content_hashes[path] == ( + country_spec.typed_resource_content_sha256( + US_SPEC_ROOT.parent / path, "target_sets.schema.json" + ) + ) + assert set(resolved_country_spec.content_hashes) == { + row.path + for row in resolved_country_spec.resource_rows + if row.kind != "legacy_json" + } + + def test_constant_derived_domain_counts_are_complete( resolved_us_spec: ResolvedSpec, ) -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py index 017f7022c0..4ff419568d 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py @@ -485,7 +485,7 @@ # Calibration loss weights computed from target specs alone; reads no # frame and treats no population. "target_loss_weights.py", - # Names and loads the declared US target sets (us/target_sets.json); + # Names and loads the declared US target sets (us/spec/target_sets.yaml); # selects target specs only, reads no frame and treats no population. "target_sets.py", # Data-only final-owner matrix; provenance owner above. diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_target_sets.py b/packages/microcosm-build/tests/engine_free/us/test_us_target_sets.py index deccdc1daf..92ba0bb079 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_target_sets.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_target_sets.py @@ -1,6 +1,6 @@ """The US products' declared target sets (microcosm#1728). -``us/target_sets.json`` declares what the national release and the ACS local +``us/spec/target_sets.yaml`` declares what the national release and the ACS local release calibrate to. The engine-free tests check the declarations against the tools. The pinned-feed tests prove that the declarations select the same rows, in the same order, as the tool code they replace: each surface's count @@ -238,7 +238,7 @@ def test_ladder_population_rows_have_the_declared_family_and_levels( def _target_geography_level_before_the_declared_rule(spec) -> str: """``target_loss_weights.target_geography_level`` as it was in code, before - it read the level rule of ``us/target_sets.json`` (a verbatim copy).""" + it read the level rule of ``us/spec/target_sets.yaml`` (a verbatim copy).""" metadata = spec.metadata return str( diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py index aa00335f99..7cabcdf6fa 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py @@ -378,7 +378,7 @@ def capture_equality(expected: object, actual: object) -> None: # again. # microcosm#1728's three declared US resources (target sets, local # target construction and compile registers) move it again. - "spec_sha256": "0ff909ec0783ad5d1fbf3c70fadbd60aee9b05773ebdb1ad42fbc988a5593fa3", + "spec_sha256": "50ebe28107e5fe8ab45e5c637871c9f0efdc97c697480eb41bdc262c89bf18fa", }, } diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py b/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py index 41b95f5a29..0edbd1c299 100644 --- a/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/target_sets.py @@ -6,32 +6,36 @@ selects by them (microcosm#1728). It holds no country code: a country passes the named predicates and rules its declarations use as callables. -A declaration file has this form:: - - { - "version": 1, - "country": "", - "level_rule": { - "keys": ["", ...], - "values": ["", ...] or "*", - "conflict": "first" or "refuse", - "rationale": "" - }, - "products": { - "": { - "tool": "", - "option": "", - "default_mode": "", - "modes": { - "": { - "description": "", - "compiled": [, ...], - "built": [, ...] - } - } - } - } - } +A country ships its declarations as the typed ``target_sets`` resource of its +spec bundle (``/spec/target_sets.yaml``, schema +``target_sets.schema.json`` of ``microcosm.build.spec_engine``). The spec +engine reads the file strictly, checks it against the schema, and keeps the +descriptions and rationales apart from the content that a selection reads. +:func:`load_target_set_declarations` takes the object the engine parsed. It +has this form:: + + version: 1 + country: + level_rule: + keys: [, ...] + values: [, ...] # or "*" + conflict: first # or refuse + rationale: + products: + - id: + tool: + option: + default_mode: + modes: + - id: + description: + compiled: [, ...] + built: [, ...] + +The products, the modes, the clauses and the built rows are lists, so their +declared order is part of the declaration. The order of the fields of an +object is not, and neither is the order of the names in a list of families +or levels. **Families and levels.** A target's family is ``spec.family``. Its level comes from the country's ``level_rule``: the first truthy value of the rule's @@ -100,7 +104,6 @@ from collections import Counter from collections.abc import Callable, Iterable, Mapping, Sequence from dataclasses import dataclass -from pathlib import Path from types import MappingProxyType from typing import Any @@ -137,10 +140,11 @@ LEVEL_CONFLICTS = ("first", "refuse") #: The receipt schema of :func:`select_by_levels`. SELECTION_RECEIPT_SCHEMA = "microcosm.calibrate.target-selection.v1" + _TOP_KEYS = frozenset({"version", "country", "description", "level_rule", "products"}) _LEVEL_RULE_KEYS = frozenset({"keys", "values", "conflict", "rationale"}) -_PRODUCT_KEYS = frozenset({"tool", "option", "default_mode", "modes"}) -_MODE_KEYS = frozenset({"description", "compiled", "built"}) +_PRODUCT_KEYS = frozenset({"id", "tool", "option", "default_mode", "modes"}) +_MODE_KEYS = frozenset({"id", "description", "compiled", "built"}) _CLAUSE_KEYS = frozenset( {"id", "families", "levels", "metadata", "exclude", "rule", "rationale"} ) @@ -373,10 +377,18 @@ def _text(where: str, value: object) -> str: return value +def _items(where: str, value: object, what: str) -> Sequence[Any]: + """A nonempty list (a list or a tuple, as the spec engine gives it).""" + + if not isinstance(value, list | tuple) or not value: + raise _fail(where, f"must be a nonempty list of {what}.") + return value + + def _names(where: str, value: object) -> frozenset[str] | None: - if value == ANY: + if isinstance(value, str) and value == ANY: return None - if not isinstance(value, list) or not value: + if not isinstance(value, list | tuple) or not value: raise _fail(where, f"must be {ANY!r} or a nonempty list of names.") names = [_text(where, item) for item in value] if len(set(names)) != len(names): @@ -416,7 +428,7 @@ def _clause(where: str, raw: object) -> TargetSetClause: where, raw, _CLAUSE_KEYS, ("id", "families", "levels", "rationale") ) exclude = clause.get("exclude", []) - if not isinstance(exclude, list): + if not isinstance(exclude, list | tuple): raise _fail(f"{where}.exclude", "must be a list of predicate names.") rule = clause.get("rule") return TargetSetClause( @@ -435,10 +447,10 @@ def _level_rule(where: str, top: Mapping[str, Any]) -> LevelRule: at = f"{where}.level_rule" rule = _require_keys(at, top["level_rule"], _LEVEL_RULE_KEYS, _LEVEL_RULE_KEYS) - keys = rule["keys"] - if not isinstance(keys, list) or not keys: - raise _fail(f"{at}.keys", "must be a nonempty list of metadata keys.") - keys = tuple(_text(f"{at}.keys", key) for key in keys) + keys = tuple( + _text(f"{at}.keys", key) + for key in _items(f"{at}.keys", rule["keys"], "metadata keys") + ) if len(set(keys)) != len(keys): raise _fail(f"{at}.keys", "repeats a key.") if rule["conflict"] not in LEVEL_CONFLICTS: @@ -474,105 +486,86 @@ def _built(where: str, raw: object) -> BuiltRows: ) -def _read_declaration_file(path: Path) -> object: - """Read a declaration file; refuse a repeated key or a non-finite number. - - Plain ``json.loads`` keeps the last of two equal keys, so a second - ``"state"`` mode or a second ``"levels"`` in a clause would replace the - first one without a word. - """ - - where = str(path) - - def no_repeated_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]: - keys = [key for key, _value in pairs] - repeated = sorted({key for key in keys if keys.count(key) > 1}) - if repeated: - raise _fail(where, f"repeats the JSON key(s) {repeated}.") - return dict(pairs) - - def no_constant(value: str) -> Any: - raise _fail(where, f"holds the non-finite number {value}.") - - return json.loads( - path.read_text(encoding="utf-8"), - object_pairs_hook=no_repeated_keys, - parse_constant=no_constant, +def _mode( + where: str, raw: object, *, country: str, product: str, level_rule: LevelRule +) -> TargetSetDeclaration: + mode = _require_keys(where, raw, _MODE_KEYS, ("id", "description", "compiled")) + compiled = tuple( + _clause(f"{where}.compiled[{index}]", clause) + for index, clause in enumerate( + _items(f"{where}.compiled", mode["compiled"], "clauses") + ) + ) + built_raw = mode.get("built", []) + if not isinstance(built_raw, list | tuple): + raise _fail(f"{where}.built", "must be a list.") + built = tuple( + _built(f"{where}.built[{index}]", entry) + for index, entry in enumerate(built_raw) + ) + ids = [clause.clause_id for clause in compiled] + [b.built_id for b in built] + if len(set(ids)) != len(ids): + raise _fail(where, "repeats a clause or built id.") + return TargetSetDeclaration( + country=country, + product=product, + mode=_text(f"{where}.id", mode["id"]), + description=_text(f"{where}.description", mode["description"]), + level_rule=level_rule, + compiled=compiled, + built=built, ) -def load_target_set_declarations( - source: str | Path | Mapping[str, Any], -) -> TargetSetDeclarations: - """Read and check one country's declarations (a path or a parsed object). +def load_target_set_declarations(source: Mapping[str, Any]) -> TargetSetDeclarations: + """Check one country's declarations and give them as objects. - A file is read strictly: a repeated JSON key and a non-finite number are - refused. + ``source`` is the parsed ``target_sets`` resource of the country's spec + bundle. The spec engine has already read the file strictly and checked + its form against the schema. This function builds the objects a selection + uses, and it refuses what the schema cannot state: a repeated product, + mode, clause or built id, and a default mode that is not declared. """ - if isinstance(source, Mapping): - raw, where = source, "target sets" - else: - path = Path(source) - raw, where = _read_declaration_file(path), str(path) + where = "target sets" top = _require_keys( - where, raw, _TOP_KEYS, ("version", "country", "level_rule", "products") + where, source, _TOP_KEYS, ("version", "country", "level_rule", "products") ) if type(top["version"]) is not int or top["version"] != DECLARATION_VERSION: raise _fail(where, f"version must be {DECLARATION_VERSION}.") country = _text(f"{where}.country", top["country"]) level_rule = _level_rule(where, top) - products_raw = top["products"] - if not isinstance(products_raw, Mapping) or not products_raw: - raise _fail(f"{where}.products", "must name at least one product.") products: dict[str, ProductDeclaration] = {} - for product_name, product_raw in products_raw.items(): - at = f"{where}.products.{product_name}" + for index, product_raw in enumerate( + _items(f"{where}.products", top["products"], "products") + ): + at = f"{where}.products[{index}]" product = _require_keys(at, product_raw, _PRODUCT_KEYS, _PRODUCT_KEYS) - modes_raw = product["modes"] - if not isinstance(modes_raw, Mapping) or not modes_raw: - raise _fail(f"{at}.modes", "must name at least one mode.") + product_id = _text(f"{at}.id", product["id"]) + if product_id in products: + raise _fail(f"{where}.products", f"repeats the product {product_id!r}.") + at = f"{where}.products.{product_id}" modes: dict[str, TargetSetDeclaration] = {} - for mode_name, mode_raw in modes_raw.items(): - mode_at = f"{at}.modes.{mode_name}" - mode = _require_keys( - mode_at, mode_raw, _MODE_KEYS, ("description", "compiled") - ) - compiled_raw = mode["compiled"] - if not isinstance(compiled_raw, list) or not compiled_raw: - raise _fail(f"{mode_at}.compiled", "must list at least one clause.") - compiled = tuple( - _clause(f"{mode_at}.compiled[{index}]", clause) - for index, clause in enumerate(compiled_raw) - ) - built_raw = mode.get("built", []) - if not isinstance(built_raw, list): - raise _fail(f"{mode_at}.built", "must be a list.") - built = tuple( - _built(f"{mode_at}.built[{index}]", entry) - for index, entry in enumerate(built_raw) - ) - ids = [clause.clause_id for clause in compiled] + [ - b.built_id for b in built - ] - if len(set(ids)) != len(ids): - raise _fail(mode_at, "repeats a clause or built id.") - modes[_text(mode_at, mode_name)] = TargetSetDeclaration( + for mode_index, mode_raw in enumerate( + _items(f"{at}.modes", product["modes"], "modes") + ): + mode = _mode( + f"{at}.modes[{mode_index}]", + mode_raw, country=country, - product=product_name, - mode=mode_name, - description=_text(f"{mode_at}.description", mode["description"]), + product=product_id, level_rule=level_rule, - compiled=compiled, - built=built, ) + if mode.mode in modes: + raise _fail(f"{at}.modes", f"repeats the mode {mode.mode!r}.") + modes[mode.mode] = mode default_mode = _text(f"{at}.default_mode", product["default_mode"]) if default_mode not in modes: raise _fail( f"{at}.default_mode", f"{default_mode!r} is not a declared mode." ) - products[_text(at, product_name)] = ProductDeclaration( - product=product_name, + products[product_id] = ProductDeclaration( + product=product_id, tool=_text(f"{at}.tool", product["tool"]), option=_text(f"{at}.option", product["option"]), default_mode=default_mode, diff --git a/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py b/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py index 93644bb013..5acfa8ab95 100644 --- a/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py +++ b/packages/microcosm-calibrate/tests/engine_free/shared/test_target_sets.py @@ -1,9 +1,14 @@ -"""Declared target sets: the shared reader and selector (microcosm#1728).""" +"""Declared target sets: the shared reader and selector (microcosm#1728). + +The reader takes the object that the spec engine parsed from a country's +typed ``target_sets`` resource. The strict read of the file and its schema +are the spec engine's, and ``test_spec_engine_target_sets.py`` of the build +package tests them. +""" from __future__ import annotations import copy -import json from types import SimpleNamespace import pytest @@ -43,19 +48,22 @@ def _spec(name: str, family: str, **metadata) -> SimpleNamespace: "conflict": "first", "rationale": "r", }, - "products": { - "national": { + "products": [ + { + "id": "national", "tool": "tools/national.py", "option": "--surface", "default_mode": "all", - "modes": { - "all": { + "modes": [ + { + "id": "all", "description": "Every compiled target.", "compiled": [ {"id": "all", "families": "*", "levels": "*", "rationale": "r"} ], }, - "no_district": { + { + "id": "no_district", "description": "Every target but the district ones.", "compiled": [ { @@ -67,14 +75,16 @@ def _spec(name: str, family: str, **metadata) -> SimpleNamespace: } ], }, - }, + ], }, - "local": { + { + "id": "local", "tool": "tools/local.py", "option": "--mode", "default_mode": "state", - "modes": { - "state": { + "modes": [ + { + "id": "state", "description": "State benefit and state tax rows.", "compiled": [ { @@ -106,7 +116,8 @@ def _spec(name: str, family: str, **metadata) -> SimpleNamespace: } ], }, - "shares": { + { + "id": "shares", "description": "State tax rows and district shares of them.", "compiled": [ { @@ -119,24 +130,38 @@ def _spec(name: str, family: str, **metadata) -> SimpleNamespace: } ], }, - }, + ], }, - }, + ], } -def _declarations(**changes): +def _edited(**changes) -> dict: + """``DECLARATIONS`` with each ``a__b__c`` path set to its value. + + A step into a list is an index, or the ``id`` of one of its objects. + """ + raw = copy.deepcopy(DECLARATIONS) for path, value in changes.items(): node = raw *parents, leaf = path.split("__") for key in parents: - node = node[int(key)] if isinstance(node, list) else node[key] + if not isinstance(node, list): + node = node[key] + elif key.isdigit(): + node = node[int(key)] + else: + (node,) = [item for item in node if item["id"] == key] if value is _DELETE: del node[leaf] else: node[leaf] = value - return load_target_set_declarations(raw) + return raw + + +def _declarations(**changes): + return load_target_set_declarations(_edited(**changes)) _DELETE = object() @@ -146,11 +171,8 @@ def _names(specs) -> list[str]: return [spec.name for spec in specs] -def test_declarations_load_from_a_file_and_name_products_and_modes(tmp_path) -> None: - path = tmp_path / "target_sets.json" - path.write_text(json.dumps(DECLARATIONS), encoding="utf-8") - - declarations = load_target_set_declarations(path) +def test_declarations_name_products_and_modes_in_declared_order() -> None: + declarations = load_target_set_declarations(DECLARATIONS) assert declarations.country == "test" assert declarations.level_rule.keys == ("level", "geo") @@ -170,29 +192,29 @@ def test_declarations_load_from_a_file_and_name_products_and_modes(tmp_path) -> state.clause("snap") -def test_a_file_with_a_repeated_key_or_a_non_finite_number_is_refused( - tmp_path, -) -> None: - # Plain json.loads keeps the last of two equal keys: a second mode of one - # name, or a second "levels" in a clause, would replace the first one - # without a word (the review of microcosm#1755). - text = json.dumps(DECLARATIONS) - path = tmp_path / "target_sets.json" - path.write_text('{"version": 1, ' + text[1:], encoding="utf-8") - with pytest.raises( - TargetSetDeclarationError, match=r"repeats the JSON key\(s\) \['version'\]" - ): - load_target_set_declarations(path) - nested = text.replace('"modes": {', '"modes": {"all": {}, ', 1) - assert nested != text - path.write_text(nested, encoding="utf-8") - with pytest.raises( - TargetSetDeclarationError, match=r"repeats the JSON key\(s\) \['all'\]" - ): - load_target_set_declarations(path) - path.write_text(text[:-1] + ', "extra": NaN}', encoding="utf-8") - with pytest.raises(TargetSetDeclarationError, match="non-finite number NaN"): - load_target_set_declarations(path) +def test_the_reader_takes_the_frozen_lists_of_the_spec_engine() -> None: + """The spec engine holds a list as a tuple; the reader reads both.""" + + def frozen(node): + if isinstance(node, dict): + return {key: frozen(value) for key, value in node.items()} + if isinstance(node, list): + return tuple(frozen(item) for item in node) + return node + + assert load_target_set_declarations(frozen(DECLARATIONS)) == _declarations() + + +def test_a_repeated_product_or_mode_is_refused() -> None: + twice = _edited() + twice["products"].append(copy.deepcopy(twice["products"][0])) + with pytest.raises(TargetSetDeclarationError, match="repeats the product"): + load_target_set_declarations(twice) + twice = _edited() + modes = twice["products"][1]["modes"] + modes.append(copy.deepcopy(modes[0])) + with pytest.raises(TargetSetDeclarationError, match="repeats the mode 'state'"): + load_target_set_declarations(twice) @pytest.mark.parametrize( @@ -206,7 +228,9 @@ def test_a_file_with_a_repeated_key_or_a_non_finite_number_is_refused( # The short form of the rule is gone: a country gives the rule in full. ({"level_keys": ["level", "geo"]}, "unknown keys"), ({"products__local__default_mode": "county"}, "not a declared mode"), - ({"products__local__modes__state__compiled": []}, "at least one clause"), + ({"products": []}, "nonempty list of products"), + ({"products__local__modes": []}, "nonempty list of modes"), + ({"products__local__modes__state__compiled": []}, "nonempty list of clauses"), ( {"products__local__modes__state__compiled__0__families": []}, "nonempty list", @@ -380,12 +404,9 @@ def shares(candidates): def test_a_spec_that_two_clauses_keep_is_refused() -> None: - declarations = copy.deepcopy(DECLARATIONS) - clauses = declarations["products"]["local"]["modes"]["state"]["compiled"] - clauses[0]["families"] = ["benefit", "tax"] - declaration = load_target_set_declarations(declarations).declaration( - "local", "state" - ) + declaration = _declarations( + products__local__modes__state__compiled__0__families=["benefit", "tax"] + ).declaration("local", "state") with pytest.raises(ValueError, match="both keep 'ca_tax_total'"): select_target_set(declaration, SPECS) @@ -393,7 +414,7 @@ def test_a_spec_that_two_clauses_keep_is_refused() -> None: def test_metadata_tests_match_their_definitions() -> None: declarations = copy.deepcopy(DECLARATIONS) - clause = declarations["products"]["local"]["modes"]["state"]["compiled"][1] + clause = declarations["products"][1]["modes"][0]["compiled"][1] clause["levels"] = "*" clause["metadata"] = { "record": {"not_prefix": "district_file."}, @@ -465,13 +486,15 @@ def _level_declarations(**rule) -> dict: "rationale": "r", **rule, }, - "products": { - "full": { + "products": [ + { + "id": "full", "tool": "tools/full.py", "option": "--levels", "default_mode": "levels", - "modes": { - "levels": { + "modes": [ + { + "id": "levels", "description": "One clause for each level.", "compiled": [ { @@ -483,9 +506,9 @@ def _level_declarations(**rule) -> dict: for level in LEVELS ], } - }, + ], } - }, + ], } @@ -657,7 +680,7 @@ def test_select_by_levels_needs_a_level_mode() -> None: with pytest.raises(TargetSetDeclarationError, match="closed set of values"): select_by_levels(registry, _level_mode(values="*")) family_clause = _level_declarations() - mode = family_clause["products"]["full"]["modes"]["levels"] + mode = family_clause["products"][0]["modes"][0] mode["compiled"][0]["families"] = ["tax"] with pytest.raises(TargetSetDeclarationError, match="not a level clause"): select_by_levels( @@ -665,7 +688,7 @@ def test_select_by_levels_needs_a_level_mode() -> None: load_target_set_declarations(family_clause).declaration("full", "levels"), ) missing = _level_declarations() - missing["products"]["full"]["modes"]["levels"]["compiled"].pop() + missing["products"][0]["modes"][0]["compiled"].pop() with pytest.raises(TargetSetDeclarationError, match="are not the levels"): select_by_levels( registry, @@ -677,25 +700,29 @@ def test_a_selection_that_tests_no_level_reads_no_level() -> None: """A closed rule refuses an unplaced target only where a clause tests levels.""" declarations = _level_declarations() - declarations["products"]["lines"] = { - "tool": "t", - "option": "line", - "default_mode": "national", - "modes": { - "national": { - "description": "Every target but the local-only ones.", - "compiled": [ - { - "id": "on_line", - "families": "*", - "levels": "*", - "exclude": ["off_line"], - "rationale": "r", - } - ], - } - }, - } + declarations["products"].append( + { + "id": "lines", + "tool": "t", + "option": "line", + "default_mode": "national", + "modes": [ + { + "id": "national", + "description": "Every target but the local-only ones.", + "compiled": [ + { + "id": "on_line", + "families": "*", + "levels": "*", + "exclude": ["off_line"], + "rationale": "r", + } + ], + } + ], + } + ) loaded = load_target_set_declarations(declarations) specs = ( _spec("placed", "tax", level="la"), diff --git a/test_support/microcosm_build/calibration_line_reference.py b/test_support/microcosm_build/calibration_line_reference.py index 2c8f7a614e..06c55858e0 100644 --- a/test_support/microcosm_build/calibration_line_reference.py +++ b/test_support/microcosm_build/calibration_line_reference.py @@ -1,6 +1,6 @@ # Verbatim copy of uk_registry_on_calibration_line from # microcosm.build.uk_runtime.ledger_targets at 508351658, before microcosm#1759 -# declared the calibration lines in uk/target_sets.json. Tests hold the new +# declared the calibration lines in uk/spec/target_sets.yaml. Tests hold the new # code to it; do not edit. It reads the contract through the live helpers. # ruff: noqa diff --git a/test_support/microcosm_build/us_spec_bundle.py b/test_support/microcosm_build/us_spec_bundle.py index 06dbcce94d..1185d41c7e 100644 --- a/test_support/microcosm_build/us_spec_bundle.py +++ b/test_support/microcosm_build/us_spec_bundle.py @@ -64,7 +64,8 @@ def _load_generator_module(): generator = _load_generator_module() -TYPED_DOMAIN_KINDS = frozenset( +#: The typed domains that the generator builds from the constants-era code. +GENERATED_DOMAIN_KINDS = frozenset( { "battery", "bundle", @@ -80,6 +81,9 @@ def _load_generator_module(): "vintages", } ) +#: The typed domains that are written by hand (the declared target sets). +AUTHORED_DOMAIN_KINDS = frozenset({"target_sets"}) +TYPED_DOMAIN_KINDS = GENERATED_DOMAIN_KINDS | AUTHORED_DOMAIN_KINDS F_P_WAIVED_TARGETS = frozenset( { diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index 5914866e70..8b7bc4a948 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -653,7 +653,7 @@ def soi_surface_predicate(soi_mode: str): """The ``irs_soi`` spec filter for one ``--soi-mode``. It is the level and metadata tests of the mode's ``soi`` clause in - ``us/target_sets.json``, product ``local`` (microcosm#1728); the caller + ``us/spec/target_sets.yaml``, product ``local`` (microcosm#1728); the caller selects the family. A spec's level is its ``ledger_geography_level`` (else its ``geography_level``), which every compiled spec carries. @@ -766,7 +766,7 @@ def state_admin_surface( ``apply_us_medicaid_enrollment_substitutions`` (RI FIPS-44) -> state-level {usda_snap, cms_medicaid[enrollment], irs_soi}. The clauses ``snap``, ``medicaid`` and ``soi`` of the mode's declaration in - ``us/target_sets.json`` (product ``local``, microcosm#1728) pick them, in + ``us/spec/target_sets.yaml`` (product ``local``, microcosm#1728) pick them, in that order; ``families`` turns clauses on by id. The SOI slice follows :func:`soi_surface_predicate` for ``state`` (the default), ``totals`` and ``full``; ``state_cd`` adds the reconciled congressional-district rows diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 81302be373..dd38fe988f 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -9967,7 +9967,7 @@ def _select_target_surface( ) -> tuple[tuple[TargetSpec, ...], dict[str, object]]: """Return the specs the release calibrates to and a receipt of the choice. - Each mode is declared in ``us/target_sets.json``, product ``national`` + Each mode is declared in ``us/spec/target_sets.yaml``, product ``national`` (microcosm#1728). ``full`` keeps every compiled spec. ``national_state`` drops every spec ``is_congressional_district_target`` classifies as congressional-district (CD geography rows and rows sourced from the SOI diff --git a/tools/generate_us_bundle_from_constants.py b/tools/generate_us_bundle_from_constants.py index 069c2b5da9..a49fc88233 100644 --- a/tools/generate_us_bundle_from_constants.py +++ b/tools/generate_us_bundle_from_constants.py @@ -62,6 +62,13 @@ "take_up", "vintages", ) +#: Typed domains that are written by hand. The constants-era code never held +#: them, so no extractor builds them and this tool does not write their YAML. +#: The manifest declares them, and the bundle loader validates them. +AUTHORED_DOMAIN_KINDS = ( + # The declared target set of each US product (microcosm#1728). + "target_sets", +) def _domain_builders() -> dict[str, Callable[[], object]]: @@ -167,8 +174,6 @@ def _domain_builders() -> dict[str, Callable[[], object]]: "take_up_contract.json", "target_parity_feed_families.json", "target_parity_manifest.json", - # The declared target set of each US product (microcosm#1728). - "target_sets.json", "tax_expenditure_reforms.json", ) @@ -265,7 +270,7 @@ def country_manifest() -> dict[str, object]: "kind": kind, "schema_id": f"{kind}.schema.json", } - for kind in DOMAIN_KINDS + for kind in sorted((*DOMAIN_KINDS, *AUTHORED_DOMAIN_KINDS)) ] legacy_rows = [ {"path": path, "kind": "legacy_json", "schema_id": "legacy_json"} diff --git a/tools/spec_engine_coverage.py b/tools/spec_engine_coverage.py index 5525c592ef..76a0db4a9d 100644 --- a/tools/spec_engine_coverage.py +++ b/tools/spec_engine_coverage.py @@ -41,7 +41,7 @@ REPORT_SCHEMA_VERSION = 3 EXPECTED_POINTER_INVENTORY_SHA256 = ( - "8e3b7c8680e0a5c5626867c1b697b6b6d98058b383c2f7d368f0b5b5df3105b1" + "7c37171ae40e7e9f43e9ecf36937cbd0a907b5516868b45dc3d9cf7ddec12d4d" ) DEFAULT_REPORT_PATH = ( Path(__file__).resolve().parents[1] From 884f1eb53491cc1bcb39fff3e880ec4925269b18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:13:59 +0000 Subject: [PATCH 29/30] Name the declarations reader in the battery's binding identity The country spec now checks a package's declared target sets with the shared reader when it loads the bundle, and the US field ledger does the same for its target_sets claim. So the gate bindings' source closure reaches microcosm.calibrate.target_sets, one module more than the reviewed list of test_transport_evidence_kernels.py. The module joins that list. Co-Authored-By: Claude Fable 5.2 --- .../engine_free/shared/test_transport_evidence_kernels.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py b/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py index a5becc50e7..52809a4ebe 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py @@ -151,6 +151,10 @@ # their reviewed registers through these two modules. "microcosm.build.declared_registers", "microcosm.build.us_runtime.fiscal_target_registers", + # microcosm#1755: the country spec checks a package's declared target + # sets with the shared reader when it loads the bundle, and the US + # field ledger does the same for its target_sets claim. + "microcosm.calibrate.target_sets", # microcosm#1585: the US keyed draws call # stochastic_assignment.stable_identity_uniforms. "microcosm.build.stochastic_assignment", From 5eac92f5f08f1ed0adef591815458b2648eebbf5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:59:44 +0000 Subject: [PATCH 30/30] Exclude the target-set reader from the transport compile list The country spec's loader now checks a bundle's declared target sets with microcosm.calibrate.target_sets (microcosm#1728). country_spec is a listed transport compile module, so the closure test needs each of its first-party imports listed or excluded with a reason. Target compilation calls only the reference validators of country_spec. They do not read the reader, and a target set selects among the targets after the compile. So the reader joins EXCLUDED_DIRECT_IMPORTS with that reason, like the other imports of the loader. No compile kernel hashes the list module, so no node key changes. Co-Authored-By: Claude Fable 5.2 --- .../src/microcosm/build/transport/compile_modules.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/microcosm-build/src/microcosm/build/transport/compile_modules.py b/packages/microcosm-build/src/microcosm/build/transport/compile_modules.py index e38932c372..01f1e3925c 100644 --- a/packages/microcosm-build/src/microcosm/build/transport/compile_modules.py +++ b/packages/microcosm-build/src/microcosm/build/transport/compile_modules.py @@ -68,6 +68,12 @@ "microcosm.build.spec_engine.schemas": _COUNTRY_SPEC_LOADER, "microcosm.build.spec_engine.take_up_semantics": _COUNTRY_SPEC_LOADER, "microcosm.build.spec_engine.yaml12": _COUNTRY_SPEC_LOADER, + "microcosm.calibrate.target_sets": ( + "country_spec's loader checks a bundle's declared target sets with " + "this shared reader (_checked_target_sets, microcosm#1728); the " + "reference validators target compilation calls do not read it, and " + "a target set selects among the targets after the compile" + ), "microcosm.build.reference_intervals": ( "reference_profiles reaches it only when given an interval " "document; compile_target_surface calls validate_reference_resolution "