diff --git a/.github/workflows/pure-tests.yml b/.github/workflows/pure-tests.yml new file mode 100644 index 0000000..d932233 --- /dev/null +++ b/.github/workflows/pure-tests.yml @@ -0,0 +1,52 @@ +name: Pure preparation tests + +on: + pull_request: + branches: [main] + +permissions: + contents: read + +concurrency: + group: pure-preparation-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + pure-tests: + name: Synthetic currency tests + runs-on: ubuntu-24.04 + timeout-minutes: 5 + env: + OMP_NUM_THREADS: "1" + OPENBLAS_NUM_THREADS: "1" + MKL_NUM_THREADS: "1" + NUMEXPR_NUM_THREADS: "1" + VECLIB_MAXIMUM_THREADS: "1" + PYTHONDONTWRITEBYTECODE: "1" + PYTEST_DISABLE_PLUGIN_AUTOLOAD: "1" + UV_PYTHON_DOWNLOADS: never + steps: + - name: Check out the pull request + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Set up CPython + id: python + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.13.13" + architecture: x64 + check-latest: false + - name: Set up uv + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + version: "0.13.8" + enable-cache: false + - name: Install only the pinned pure-test dependencies + env: + PURE_TEST_PYTHON: ${{ steps.python.outputs.python-path }} + run: | + uv venv --python "$PURE_TEST_PYTHON" .venv + uv pip install --python .venv/bin/python --only-binary :all: --require-hashes -r ci/pure-test-requirements.txt + - name: Run the existing synthetic tests with model imports blocked + run: uv run --offline --no-sync python -I -B scripts/run_native_currency_tests.py diff --git a/README.md b/README.md index 97bd612..0f731fb 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,11 @@ -# Tax-benefit cliffs under 2017 federal rules +# Cliffs: archived experiments and counterfactual preparation -How many American adults would see their household's net income fall if they earned $1,000 more? We estimate that count under 2017 federal tax and benefit rules and, for comparison, under 2025 rules, with and without counting health coverage as income. Where PolicyEngine-US holds no 2017 value for a rule, as for state Medicaid limits and most state taxes, the 2017 runs read its earliest later value; METHODOLOGY.md lists them. We use [PolicyEngine-US](https://github.com/PolicyEngine/policyengine-us) and Microcosm, PolicyEngine's US microdata. +This repository contains archived experiments measuring whether a specified earnings increase lowers household resources, with and without government-valued health coverage. The 2017-oriented experiments combine dated policies with later rule fallbacks, selected monetary rescaling and population reweighting. These hybrid sensitivities do not estimate actual 2017 incidence or compare laws while holding a recent population and real incomes fixed. + +The [proposed counterfactual protocol](docs/counterfactual-protocol.md) describes a fresh comparison on one recent reference population. Its helper converts declared monetary inputs and preserves household characteristics. Fresh policy results require the managed population adapter and model/data qualification; existing result files report the hybrid experiments. - [results/summary.md](results/summary.md): the counts, with 95% intervals. -- [METHODOLOGY.md](METHODOLOGY.md): how we define a cliff, build the 2017 population and measure uncertainty, and what the model leaves out. +- [METHODOLOGY.md](METHODOLOGY.md): the archived experiment's definition, construction of 2017-oriented inputs, uncertainty and coverage limits. - [CORRECTION.md](CORRECTION.md): why our April 2025 estimate overstated the count, and the evidence. - [april2025/](april2025/): the scripts that reproduce the April 2025 estimate and trace the error. @@ -12,6 +14,8 @@ How many American adults would see their household's net income fall if they ear | Path | Contents | |---|---| | cliffs2017/run.py | One run: a year, with or without health coverage, on the full sample, a household subsample or one of several disjoint household groups | +| cliffs2017/native_currency.py | Explicit input-currency and field-disposition helper for the proposed counterfactual; no engine adapter or policy calculations | +| docs/counterfactual-protocol.md, docs/price_basis.csv | Proposed comparison and published annual-average CPI-U price basis | | cliffs2017/deflate.py | Scales the 2024 data to 2017 dollar levels and population; splits and subsamples households | | cliffs2017/aca2017.py | The ACA premium tax credit before 2018, which PolicyEngine-US leaves at $0 | | cliffs2017/decompose.py | Breaks each tested adult's change in net income into programs and taxes | @@ -34,7 +38,27 @@ How many American adults would see their household's net income fall if they ear | scripts/audit_*.py, scripts/summarize_parameters.py | The parameter and formula audits behind the coverage notes in METHODOLOGY.md, and the counts it quotes from the parameter audit | | tests/ | Property and example tests (pytest) | -## Running it +## Testing counterfactual preparation + +The helper tests use synthetic inputs and mock price indices and execute without model imports or population data. + +Numeric facts retain their finite numeric types, including fractional ages; numeric strings fail validation. Money converts to exact fractions. Representation guards limit integers and ratio components to 4,096 bits, decimal coefficients to 1,000 digits, decimal exponents to ±1,000 and numeric text to 2,048 characters. These resource limits apply to supplied numbers. + +Declare every input field explicitly. For age-derived birth facts, supply `calendar_scope` and `calendar_reason`, approve the scope in `InputContract.calendar_scopes`, and choose the reviewed drop or compatible hold. The returned `calendar_dispositions` records the scope, reason and disposition; `dropped_fields` also lists any dropped birth fact. Retained calendar values never shift or clamp. Lexical name guards cover selected common names; the complete reviewed field contract must identify other date and cohort facts. + +Run the isolated pure suite: + +```bash +uv run --no-project --python 3.13 --with pytest==9.2.0 --with hypothesis==6.170.15 python -m pytest tests/test_native_currency.py +``` + +The existing package pins and drivers below reproduce the archived experiments. New policy analysis requires the qualified managed `policyengine` interface described in the proposed protocol and entity-aware MicroSeries operations for weighted statistics. + +## Counterfactual qualification status + +A November 14, 2026 compatibility check in `policyengine` 6.19.0 refused the development target declaring US 2.124.0 and Core 3.36.0 at country source `43ca7bd3cd8615cac187db1b270ec2c3dd77f85f`. That certificate bound the 20260915 data release. Qualification of any replacement target must verify genuine package identities and prepared inputs; identical raw H5 bytes do not establish compatibility. + +## Reproducing archived experiments ```bash uv venv --python 3.13 && uv pip install -e ".[test]" && source .venv/bin/activate @@ -56,6 +80,8 @@ Each part needs about 11 GB of memory. To queue the runs under a memory limit, s Each result file records the repository commit and a hash of the cliffs2017/ code that produced it. The final results in this repository came from commit cd77a87, whose cliffs2017/ code hashes to 04f6b6c3. The files in results/counted_once/ came from commit cd77a87; each part stops unless it reproduces the counts of the committed run it rebuilds. results/take_up_bounds.json came from commit 5a53e32; the script reads the per-person files of the final runs, which those runs write and git ignores, and stops unless the files reproduce each run's count. results/driver_intervals.json came from commit 79a52f4; scripts/driver_intervals.py reads the same files and stops unless they reproduce each run's counts, in total and by largest loss. results/health_only.json came from commit 13e1553; scripts/health_only.py reads the same files and stops unless they reproduce each headline count. results/csfp/reach_2025.json holds the number of people the model gives a Commodity Supplemental Food Program package. It came from commit efa0b34, before the runs set WIC take-up, and no formula behind that program reads WIC. The Medicaid totals in results/medicaid/ also predate cliffs2017/wic_take_up.py, and tests/test_wic_take_up.py checks on a sample that setting WIC take-up from the draw leaves Medicaid's sums unchanged. We last regenerated the parameter and formula audit files before cliffs2017/wic_take_up.py existed (commits 3286bdd and 6915a57). +The run provenance digest covers every Python and CSV file under `cliffs2017/`, including the currency helper. A new helper changes that digest even when the archived calculation drivers remain untouched. The combination and part-scaling checks reject runs with different code digests. Reproduce an archived run from its recorded code version, or regenerate all compared parts together at one version; do not mix old and new parts or bypass the checks. + ## License MIT diff --git a/changelog.d/counterfactual-currency.added.md b/changelog.d/counterfactual-currency.added.md new file mode 100644 index 0000000..e53c825 --- /dev/null +++ b/changelog.d/counterfactual-currency.added.md @@ -0,0 +1 @@ +Add exact input-currency conversion, recorded age-led birth-fact dispositions, bounded numeric validation and synthetic tests, with a proposed protocol for historical-law comparisons on one recent reference population. Population estimation requires a qualified model/data pair and native-year adapter. diff --git a/ci/pure-test-requirements.txt b/ci/pure-test-requirements.txt new file mode 100644 index 0000000..cfdd538 --- /dev/null +++ b/ci/pure-test-requirements.txt @@ -0,0 +1,9 @@ +# Pure tests only: CPython 3.13 on Linux x86_64. Do not install this project. +# Metadata-derived pins; no dependency resolver or installation ran during preparation. +pytest==9.2.0 --hash=sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588 +hypothesis==6.170.15 --hash=sha256:f25261d1656f830a78863844be5fb55cd0208154dc9ddec85d44fe691488c557 +iniconfig==2.3.1 --hash=sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7 +packaging==26.3 --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c +pluggy==1.7.0 --hash=sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec +pygments==2.21.0 --hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9 +sortedcontainers==2.4.0 --hash=sha256:a163dcaede0f1c021485e957a39245190e74249897e2ae4b2aa38595db237ee0 diff --git a/cliffs2017/native_currency.py b/cliffs2017/native_currency.py new file mode 100644 index 0000000..3e1b9ac --- /dev/null +++ b/cliffs2017/native_currency.py @@ -0,0 +1,461 @@ +"""Input-unit conversion only: no engine, policy calculation, or statistics. + +The caller supplies a reviewed, complete field contract and explicit price indices. +This module does not discover inputs, classify the actual population, fetch weights, +change periods, broadcast annual amounts into months, or round currency to cents. +Fractions retain exact declared numeric ratios until a future engine adapter chooses +its own numeric representation. No such adapter is included. + +Numeric facts retain their supplied finite numeric types; numeric strings are invalid +facts. Monetary strings remain explicit exact decimals. Birth facts dropped for a +fixed-age experiment, or held alongside fixed age, require a reviewed scope and reason. +The result records those dispositions without altering any retained calendar value. +""" + +import math +from collections.abc import Mapping +from dataclasses import dataclass +from datetime import date +from decimal import Decimal, InvalidOperation +from enum import Enum +from fractions import Fraction +from types import MappingProxyType + + +class ContractError(ValueError): + """An undeclared, incompatible, missing, or malformed input.""" + + +class Kind(str, Enum): + PRIMITIVE_MONEY = "primitive_money" + POLICY_DERIVED = "policy_derived" + AGE = "fixed_age" + ID = "fixed_id" + WEIGHT = "fixed_weight" + CALENDAR = "fixed_calendar" + STRUCTURE = "fixed_structure" + DEMOGRAPHIC = "fixed_demographic" + DIMENSIONLESS = "fixed_dimensionless" + + +class Disposition(str, Enum): + SCALE = "scale_money" + KEEP = "keep_fact" + DROP = "drop_derived" + BACKGROUND = "named_background_money" + + +ENTITIES = frozenset( + {"person", "marital_unit", "family", "tax_unit", "spm_unit", "household"} +) +SUPPORTED_YEARS = frozenset(range(2017, 2027)) +MONEY_UNITS = frozenset({"USD/year", "USD/month", "USD/hour", "USD/stock"}) +FACT_UNITS = { + Kind.AGE: frozenset({"age_years"}), + Kind.ID: frozenset({"id"}), + Kind.WEIGHT: frozenset({"weight"}), + Kind.CALENDAR: frozenset({"calendar_year", "calendar_date"}), + Kind.STRUCTURE: frozenset({"id", "count", "flag"}), + Kind.DEMOGRAPHIC: frozenset({"category", "flag"}), + Kind.DIMENSIONLESS: frozenset({"fraction", "count", "flag"}), +} +ALL_UNITS = MONEY_UNITS | frozenset().union(*FACT_UNITS.values()) +# Representation limits bound arithmetic resources, not economic values or tax rules. +MAX_NUMERIC_BITS = 4096 +MAX_DECIMAL_DIGITS = 1000 +MAX_DECIMAL_EXPONENT = 1000 +MAX_NUMERIC_TEXT_LENGTH = 2048 + + +def _year(value): + if type(value) is not int or value not in SUPPORTED_YEARS: + raise ContractError("Year must be a declared integer in 2017–2026") + return value + + +def _number(value): + """Exact ratio of a finite declared number; bool and missing data are errors.""" + if isinstance(value, bool): + raise ContractError("Boolean is not a monetary/numeric value") + if isinstance(value, Fraction): + if ( + max(value.numerator.bit_length(), value.denominator.bit_length()) + > MAX_NUMERIC_BITS + ): + raise ContractError("Numeric ratio exceeds representation limits") + return value + if isinstance(value, int): + if value.bit_length() > MAX_NUMERIC_BITS: + raise ContractError("Integer exceeds representation limits") + return Fraction(value) + if isinstance(value, float) and not math.isfinite(value): + raise ContractError("Non-finite numeric value") + if not isinstance(value, (Decimal, float, str)): + raise ContractError("Expected a finite numeric value, without defaults") + if isinstance(value, str) and len(value) > MAX_NUMERIC_TEXT_LENGTH: + raise ContractError("Numeric text exceeds representation limits") + try: + decimal = value if isinstance(value, Decimal) else Decimal(str(value)) + if not decimal.is_finite(): + raise ContractError("Non-finite numeric value") + parts = decimal.as_tuple() + if ( + len(parts.digits) > MAX_DECIMAL_DIGITS + or abs(parts.exponent) > MAX_DECIMAL_EXPONENT + or decimal.adjusted() >= MAX_DECIMAL_DIGITS + ): + raise ContractError("Decimal exceeds representation limits") + return Fraction(decimal) + except (InvalidOperation, ValueError, ZeroDivisionError) as error: + raise ContractError("Invalid numeric value") from error + + +def _scope_names(values): + if not isinstance(values, (list, tuple, set, frozenset)) or any( + not isinstance(value, str) or not value.strip() for value in values + ): + raise ContractError("Scopes must be a collection of explicit names") + return frozenset(values) + + +def _birth_field(name): + return name in {"birth_year", "birth_date"} or name.endswith( + ("_birth_year", "_birth_date") + ) + + +def _period_unit(period, unit): + if not isinstance(period, str) or period not in {"year", "month", "eternity"}: + raise ContractError("Unsupported period; no implicit period conversion") + if not isinstance(unit, str) or unit not in ALL_UNITS: + raise ContractError("Unsupported unit") + if unit == "USD/month" and period != "month": + raise ContractError("USD/month requires explicit monthly blocks") + if unit in {"USD/year", "USD/hour", "USD/stock"} and period != "year": + raise ContractError("This currency unit requires an annual input block") + + +@dataclass(frozen=True) +class PriceBasis: + """Explicit indices, not an authoritative CPI series or a data downloader.""" + + index_by_year: Mapping + reference_year: int = 2025 + + def __post_init__(self): + if self.reference_year != 2025 or type(self.reference_year) is not int: + raise ContractError("This contract uses reference year 2025") + if not isinstance(self.index_by_year, Mapping): + raise ContractError("Price indices must be an explicit mapping") + indices = {} + for year, value in self.index_by_year.items(): + _year(year) + indices[year] = _number(value) + if indices[year] <= 0: + raise ContractError("Price indices must be positive") + if self.reference_year not in indices: + raise ContractError("Missing reference price index") + object.__setattr__(self, "index_by_year", MappingProxyType(indices)) + + def factor(self, target_year): + _year(target_year) + if target_year not in self.index_by_year: + raise ContractError("Missing explicitly supplied target price index") + return self.index_by_year[target_year] / self.index_by_year[self.reference_year] + + +@dataclass(frozen=True) +class FieldSpec: + name: str + entity: str + kind: Kind + disposition: Disposition + unit: str + period: str + background_scope: str | None = None + calendar_scope: str | None = None + calendar_reason: str | None = None + + def __post_init__(self): + if not isinstance(self.name, str) or not self.name.strip(): + raise ContractError("Field needs an explicit name") + if not isinstance(self.entity, str) or self.entity not in ENTITIES: + raise ContractError("Unsupported entity") + try: + object.__setattr__(self, "kind", Kind(self.kind)) + object.__setattr__(self, "disposition", Disposition(self.disposition)) + except (ValueError, TypeError) as error: + raise ContractError("Unknown kind or disposition") from error + _period_unit(self.period, self.unit) + if self.kind == Kind.PRIMITIVE_MONEY: + valid = self.disposition == Disposition.SCALE and self.unit in MONEY_UNITS + elif self.kind == Kind.POLICY_DERIVED: + valid = self.disposition == Disposition.DROP or ( + self.disposition == Disposition.BACKGROUND and self.unit in MONEY_UNITS + ) + elif self.kind == Kind.CALENDAR: + valid = self.unit in FACT_UNITS[self.kind] and ( + self.disposition == Disposition.KEEP + or (_birth_field(self.name) and self.disposition == Disposition.DROP) + ) + else: + valid = ( + self.disposition == Disposition.KEEP + and self.unit in FACT_UNITS[self.kind] + ) + if not valid: + raise ContractError("Kind, disposition and unit disagree") + if self.disposition == Disposition.BACKGROUND: + if ( + not isinstance(self.background_scope, str) + or not self.background_scope.strip() + ): + raise ContractError("Derived background needs a named excluded scope") + elif self.background_scope is not None: + raise ContractError("Scope is only valid for named background money") + if self.calendar_scope is not None or self.calendar_reason is not None: + if ( + self.kind != Kind.CALENDAR + or not _birth_field(self.name) + or not isinstance(self.calendar_scope, str) + or not self.calendar_scope.strip() + or not isinstance(self.calendar_reason, str) + or not self.calendar_reason.strip() + ): + raise ContractError("Birth disposition needs a named scope and reason") + elif self.kind == Kind.CALENDAR and self.disposition == Disposition.DROP: + raise ContractError("Dropped birth fact needs a named scope and reason") + # These lexical backstops do not discover every possible fact/date name. + # The caller must still review every field's complete declaration. + if (self.name == "age" or self.name.endswith("_age")) and self.kind != Kind.AGE: + raise ContractError("Age facts cannot be converted or reclassified") + if self.name.endswith("_weight") and self.kind != Kind.WEIGHT: + raise ContractError("Weight facts cannot be converted or reclassified") + if (self.name == "id" or self.name.endswith("_id")) and self.kind not in { + Kind.ID, + Kind.STRUCTURE, + }: + raise ContractError("Identifier facts cannot be converted") + if ( + self.name in {"birth_year", "birth_date"} + or self.name.endswith( + ("_origination_year", "_origination_date", "_birth_year", "_birth_date") + ) + ) and self.kind != Kind.CALENDAR: + raise ContractError("Calendar facts cannot be converted") + + +@dataclass(frozen=True) +class InputContract: + fields: tuple[FieldSpec, ...] + entity_counts: Mapping + background_scopes: frozenset[str] = frozenset() + calendar_scopes: frozenset[str] = frozenset() + + def __post_init__(self): + if not isinstance(self.fields, (list, tuple)): + raise ContractError("Fields must be an explicit sequence of declarations") + fields = tuple(self.fields) + if not all(isinstance(field, FieldSpec) for field in fields): + raise ContractError("Every field needs a FieldSpec") + names = [field.name for field in fields] + if len(set(names)) != len(names): + raise ContractError("Duplicate field declaration") + if not isinstance(self.entity_counts, Mapping): + raise ContractError("Entity counts must be declared") + counts = dict(self.entity_counts) + for entity, count in counts.items(): + if ( + not isinstance(entity, str) + or entity not in ENTITIES + or type(count) is not int + or count < 0 + ): + raise ContractError("Invalid entity/count") + scopes = _scope_names(self.background_scopes) + calendar_scopes = _scope_names(self.calendar_scopes) + age_entities = {field.entity for field in fields if field.kind == Kind.AGE} + for field in fields: + if field.entity not in counts: + raise ContractError("Missing entity count") + if ( + field.disposition == Disposition.BACKGROUND + and field.background_scope not in scopes + ): + raise ContractError("Background scope was not approved in the contract") + if field.kind == Kind.CALENDAR and _birth_field(field.name): + if ( + field.calendar_scope is not None + and field.calendar_scope not in calendar_scopes + ): + raise ContractError( + "Calendar scope was not approved in the contract" + ) + if field.entity in age_entities and field.calendar_scope is None: + raise ContractError( + "Fixed age with a birth fact needs a reviewed disposition" + ) + if ( + field.disposition == Disposition.DROP + and field.entity not in age_entities + ): + raise ContractError( + "Dropped birth fact requires a declared fixed age" + ) + object.__setattr__(self, "fields", fields) + object.__setattr__(self, "entity_counts", MappingProxyType(counts)) + object.__setattr__(self, "background_scopes", scopes) + object.__setattr__(self, "calendar_scopes", calendar_scopes) + + +def _fact(value, unit): + if unit == "flag": + if type(value) is not bool: + raise ContractError("Flag must be bool") + elif unit in {"id", "category"}: + if isinstance(value, bool) or not isinstance(value, (int, str)) or value == "": + raise ContractError( + "Identifier/category must be a nonempty string or integer" + ) + elif unit == "calendar_year": + if type(value) is not int: + raise ContractError("Calendar year must be an integer; never clamp") + elif unit == "calendar_date": + if not isinstance(value, str): + raise ContractError("Calendar date must be explicit ISO text") + try: + date.fromisoformat(value) + except ValueError as error: + raise ContractError("Invalid calendar date") from error + elif unit == "count": + if type(value) is not int or value < 0: + raise ContractError("Count must be a nonnegative integer") + else: + if isinstance(value, str): + raise ContractError("Numeric facts require numeric values, not text") + numeric = _number(value) + if unit in {"weight", "age_years"} and numeric < 0: + raise ContractError("Weight/age cannot be negative") + return value + + +def _block(values, *, count, period, convert): + def vector(items): + if not isinstance(items, (list, tuple)) or len(items) != count: + raise ContractError( + "Expected an explicit vector of the declared entity size" + ) + return tuple(convert(value) for value in items) + + if period == "month": + if not isinstance(values, Mapping): + raise ContractError("Monthly input requires twelve explicit month vectors") + if any(type(month) is not int for month in values) or set(values) != set( + range(1, 13) + ): + raise ContractError( + "Monthly block must contain exactly integer months 1–12" + ) + return MappingProxyType( + {month: vector(values[month]) for month in range(1, 13)} + ) + return vector(values) + + +@dataclass(frozen=True) +class ConvertedInputs: + values: Mapping + units: Mapping + dropped_fields: tuple[str, ...] + background_scopes: Mapping + target_year: int + reference_year: int + factor: Fraction + calendar_dispositions: Mapping + + +def to_native_inputs(values, *, contract, basis, target_year): + """Convert an exactly declared input block; never infer or supply defaults.""" + if not isinstance(contract, InputContract) or not isinstance(basis, PriceBasis): + raise ContractError("Explicit InputContract and PriceBasis are required") + if not isinstance(values, Mapping): + raise ContractError("Inputs must be a field mapping") + expected = {field.name for field in contract.fields} + if set(values) != expected: + raise ContractError("Unknown or missing fields; no implicit defaults") + factor = basis.factor(target_year) + converted, units, backgrounds, dropped = {}, {}, {}, [] + calendars = {} + for field in contract.fields: + mapper = ( + (lambda value: _number(value) * factor) + if field.unit in MONEY_UNITS + else (lambda value, unit=field.unit: _fact(value, unit)) + ) + block = _block( + values[field.name], + count=contract.entity_counts[field.entity], + period=field.period, + convert=mapper, + ) + if field.calendar_scope is not None: + calendars[field.name] = MappingProxyType( + { + "disposition": field.disposition.value, + "scope": field.calendar_scope, + "reason": field.calendar_reason, + } + ) + if field.disposition == Disposition.DROP: + dropped.append(field.name) + continue + converted[field.name] = block + units[field.name] = field.unit + if field.disposition == Disposition.BACKGROUND: + backgrounds[field.name] = field.background_scope + return ConvertedInputs( + MappingProxyType(converted), + MappingProxyType(units), + tuple(dropped), + MappingProxyType(backgrounds), + target_year, + basis.reference_year, + factor, + MappingProxyType(calendars), + ) + + +def cash_to_reference(values, *, basis, native_year, unit, period, entity_count): + """Only inverse currency conversion of caller-supplied cash, not policy compute.""" + if not isinstance(basis, PriceBasis): + raise ContractError("Explicit PriceBasis required") + _period_unit(period, unit) + if unit not in MONEY_UNITS: + raise ContractError("Cash output must have an approved currency unit") + if type(entity_count) is not int or entity_count < 0: + raise ContractError("Invalid entity count") + factor = basis.factor(native_year) + return _block( + values, + count=entity_count, + period=period, + convert=lambda value: _number(value) / factor, + ) + + +def earnings_shock_to_native(value, *, basis, target_year, unit): + """A declared scalar earnings increment; no period broadcasting or model call.""" + if ( + not isinstance(basis, PriceBasis) + or not isinstance(unit, str) + or unit + not in { + "USD/year", + "USD/month", + "USD/hour", + } + ): + raise ContractError( + "Shock requires an approved earnings-flow unit and price basis" + ) + return _number(value) * basis.factor(target_year) diff --git a/docs/counterfactual-protocol.md b/docs/counterfactual-protocol.md new file mode 100644 index 0000000..b710178 --- /dev/null +++ b/docs/counterfactual-protocol.md @@ -0,0 +1,47 @@ +# Recent-population historical-law counterfactual + +The proposed comparison uses one recent reference population. Fresh estimates require a population adapter and model/data qualification. Existing result files report the separate 2017-oriented hybrid sensitivity. + +## Estimand and reference population + +Compare the modeled 2017 and 2025 tax-benefit systems on one synthetic population with recent household characteristics. Estimate differences under the specified policy and resource conventions, excluding actual 2017 incidence and population change. + +Prepare the selected recent microdata once for 2025 after qualification. Freeze model/data/Core versions, source hashes, input projection, entity membership, ages, geography, survey weights, take-up draws and the selected adults. Record every retained payment input and every derived override. A change of input contract or data release requires a new preparation receipt. The `populace-us-2024-spm-20260909` and `populace-us-2024-spm-20260915` release tags have identical raw H5 bytes (SHA-256 `6496cc4393d4d3c6574f76eca231de5898c803b9067645591fd5c4d3e65aee84`). A changed model still requires verification of its prepared inputs. + +Initialize each policy calculation at its native year, including parameter-driven structural reforms, and calculate at that year. An annual supplied age defines the synthetic person's age in each experiment. For stored birth facts derived from age, record a reviewed drop disposition with its named scope and reason. Retain a birth fact alongside fixed age only under an explicitly reviewed compatible hold of birth-cohort consumers. The population adapter must keep held birth facts out of calculations that would contradict the fixed synthetic age. Never shift or clamp a retained date. + +Exclude cohort-sensitive Social Security entitlement and claiming changes from this comparison. Preserving actual birth cohorts defines a different estimand. Preserve loan and mortgage dates; resolve their legal interpretation or explicitly hold and exclude the affected deduction components before describing the covered historical tax provisions. + +## Currency and historical timing + +Use the published annual-average Consumer Price Index for All Urban Consumers (CPI-U), U.S. city average, all items, not seasonally adjusted. The frozen 2017–2025 values appear in [`price_basis.csv`](price_basis.csv). The [BLS annual-average table](https://www.bls.gov/regions/northeast/data/consumerpriceindex_us_table.htm) reports 245.120 for 2017 and 321.943 for 2025. BLS explains in its [shutdown FAQ, question 10](https://www.bls.gov/cpi/additional-resources/2025-federal-government-shutdown-impact-cpi-faq.htm) that the 2025 annual average uses the 11 published months. This price file ends in 2025; a 2026 population comparison requires a completed annual-average price basis. Rule tests for 2026 do not require that population comparison. + +For native year y, set D_y = CPI_y / CPI_2025. Multiply each approved primitive monetary input and the earnings increment by D_y, retaining its hourly, monthly, annual or stock unit. Divide each reported native-currency cash or health-inclusive resource total and loss by D_y before presentation in 2025 dollars or comparison with common-dollar thresholds. Preserve ages, identifiers, relationships, weights, rates and retained date facts. Apply this one price conversion throughout the comparison. Native statutory thresholds and rounding remain native; do not additionally rebase policy parameters or project the seeded inputs again. + +The model's CPI-U parameter contains monthly observations. Use the annual-average price basis above for this conversion and disclose the reference dataset's economic projection separately. + +Supply monthly variables through reviewed monthly blocks and retain annual payment totals in annual variables. Define reference-history inputs for y−1/y−2 and distinguish an instantaneous earnings shock from a steady-state increase. Specify the lookback convention before relying on a model fallback to its earliest income record. + +## Input and health accounts + +Use source-backed dispositions for every live input. Preserve observed endowments and recompute taxes, eligibility and benefits. Review the preliminary 377-label inventory against the actual runtime contract, resolving missing aliases and conflicting inputs explicitly. Record missing independent qualified dependent-care costs as missing or defaulted. Employer benefits and gross care bills do not establish those costs. + +Hold declared exogenous Social Security background payments at the same real amount and exclude entitlement and claiming responses. Audit constructor migration and final overrides so those responses cannot re-enter accidentally. Recompute covered taxability and means tests, and identify held payments separately from historical Social Security entitlement law. + +Define explicit, mutually consistent component lists for the cash and near-cash account and the account including health coverage. For the latter, use common unmasked reference health prices by location, age, family tier and benefit category, scaled into native currency. Recompute legal coverage and affordability under each law. Obtain common prices independently of eligibility-masked second-lowest-cost silver plan (SLCSP) and Children's Health Insurance Program (CHIP) outputs. Specify reference prices for Medicaid separately from its enrollment-dependent cost allocation. Count premium credits once. Value coverage at government cost and exclude interpretations of household willingness to pay. + +## Earnings experiments and reporting + +Freeze the selected-adult ranking on the reference preparation and change one adult at a time. The initial comparison uses the same real $1,000 annual earnings increase. Add larger increments after completing each scenario run, and label job entry at a law-specific minimum wage as a combined wage/policy experiment. + +Report finite-increment endpoint losses. These losses can reflect a discrete notch, overlapping continuous phase-outs above 100%, or rounding. Distinguish the endpoint-loss count from the prevalence of mathematical discontinuities. Label every table with law year, reference population/preparation, real increment, resource account and covered or held components. + +Run every reported law, earnings transition and valuation scenario through the managed model. Preserve entity mappings when applying frozen survey weights, and retain the survey-source household cluster for paired uncertainty. Compute each scenario afresh; saved totals from the hybrid or another scenario cannot supply its results. + +## Validation before estimation + +Before population execution, obtain the historical policy integration and a supported managed model/Core/data contract. Use the US qualification and publisher workflow with genuine wheel identities, loader/input checks and measured drift. Matching raw H5 bytes or version labels alone cannot establish compatibility. + +Verify the native-year adapter on bounded cases: structural initialization, entity/age/weight and real-input invariants, reviewed age/birth dispositions, monthly dispatch, lookbacks, source-input migrations, fresh-versus-clone/order agreement, a zero earnings change, and known tax/benefit boundaries. Verify the common health-price account separately. The currency helper converts declared input units and has pure synthetic example and property tests. Adapter and population qualification require their own checks. + +Execute each population scenario, retain its complete run and provenance records, and independently review the resulting estimates before replacing the paper's tables. diff --git a/docs/price_basis.csv b/docs/price_basis.csv new file mode 100644 index 0000000..8101ce5 --- /dev/null +++ b/docs/price_basis.csv @@ -0,0 +1,10 @@ +year,cpi_u_annual_average +2017,245.120 +2018,251.107 +2019,255.657 +2020,258.811 +2021,270.970 +2022,292.655 +2023,304.702 +2024,313.689 +2025,321.943 diff --git a/scripts/run_native_currency_tests.py b/scripts/run_native_currency_tests.py new file mode 100644 index 0000000..4184b5b --- /dev/null +++ b/scripts/run_native_currency_tests.py @@ -0,0 +1,72 @@ +"""Run the synthetic currency tests while refusing PolicyEngine imports.""" + +import importlib.abc +import importlib.metadata +import os +import sys +from pathlib import Path +from tempfile import TemporaryDirectory + +sys.dont_write_bytecode = True + + +def _is_policyengine_module(name): + return ( + name == "policyengine" + or name.startswith("policyengine.") + or name.startswith("policyengine_") + ) + + +class NoPolicyEngineImports(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path=None, target=None): + if _is_policyengine_module(fullname): + raise RuntimeError("Country/Core/model import forbidden: " + fullname) + return None + + +def _check_loaded_modules(): + if any(_is_policyengine_module(name) for name in sys.modules): + raise RuntimeError("A forbidden PolicyEngine module is already loaded") + + +sys.meta_path.insert(0, NoPolicyEngineImports()) +_check_loaded_modules() +if sys.argv[1:]: + raise RuntimeError("This runner accepts no test-path or pytest overrides") +if sys.implementation.name != "cpython" or sys.version_info[:3] != (3, 13, 13): + raise RuntimeError("The pure-test job requires CPython 3.13.13") +expected_versions = { + "pytest": "9.2.0", + "hypothesis": "6.170.15", + "iniconfig": "2.3.1", + "packaging": "26.3", + "pluggy": "1.7.0", + "pygments": "2.21.0", + "sortedcontainers": "2.4.0", +} +for name, expected in expected_versions.items(): + if importlib.metadata.version(name) != expected: + raise RuntimeError("Unexpected pure-test dependency version: " + name) + +root = Path(__file__).resolve().parents[1] +if Path.cwd().resolve() != root: + raise RuntimeError("Run this script from the repository root") +os.environ["PYTEST_DISABLE_PLUGIN_AUTOLOAD"] = "1" +os.environ["CLIFFS_MAX_EXAMPLES"] = "60" +sys.path.insert(0, str(root)) + +with TemporaryDirectory(prefix="cliffs-pure-tests-") as cache: + os.environ["HYPOTHESIS_STORAGE_DIRECTORY"] = str(Path(cache) / "hypothesis") + import pytest + + print( + "ISOLATED_PURE_RUNTIME", sys.version.split()[0], expected_versions, flush=True + ) + result = pytest.main( + ["-q", "-p", "no:cacheprovider", "tests/test_native_currency.py"] + ) + _check_loaded_modules() + print("COUNTRY_CORE_IMPORT_BLOCK_ENFORCED", flush=True) + +raise SystemExit(result) diff --git a/tests/test_native_currency.py b/tests/test_native_currency.py new file mode 100644 index 0000000..45d824c --- /dev/null +++ b/tests/test_native_currency.py @@ -0,0 +1,884 @@ +"""Entirely synthetic fixtures: mock indices are not CPI estimates or model outputs.""" + +from decimal import Decimal +from fractions import Fraction + +import pytest +from hypothesis import given, settings +from hypothesis import strategies as st + +from cliffs2017.native_currency import ( + ContractError, + Disposition, + FieldSpec, + InputContract, + Kind, + PriceBasis, + cash_to_reference, + earnings_shock_to_native, + to_native_inputs, +) + + +@pytest.fixture +def mock_basis(): + return PriceBasis({2017: "80", 2025: "100", 2026: "110"}) + + +def money(name="mock_earnings", *, period="year", unit="USD/year"): + return FieldSpec( + name, "person", Kind.PRIMITIVE_MONEY, Disposition.SCALE, unit, period + ) + + +def single_contract(spec): + return InputContract((spec,), {"person": 2}) + + +def test_synthetic_cashbook_preserves_facts_and_explicit_scope(mock_basis): + fields = ( + money(), + money("mock_hourly_wage", unit="USD/hour"), + money("mock_savings", unit="USD/stock"), + FieldSpec("age", "person", Kind.AGE, Disposition.KEEP, "age_years", "year"), + FieldSpec("person_id", "person", Kind.ID, Disposition.KEEP, "id", "eternity"), + FieldSpec( + "person_weight", "person", Kind.WEIGHT, Disposition.KEEP, "weight", "year" + ), + FieldSpec( + "first_home_mortgage_origination_year", + "person", + Kind.CALENDAR, + Disposition.KEEP, + "calendar_year", + "year", + ), + FieldSpec( + "mock_credit", + "person", + Kind.POLICY_DERIVED, + Disposition.DROP, + "USD/year", + "year", + ), + FieldSpec( + "mock_ss_payment", + "person", + Kind.POLICY_DERIVED, + Disposition.BACKGROUND, + "USD/year", + "year", + "ss_entitlement_excluded", + ), + ) + contract = InputContract( + fields, {"person": 2}, frozenset({"ss_entitlement_excluded"}) + ) + original = { + "mock_earnings": [50_000, -1_000], + "mock_hourly_wage": ["12.50", 20], + "mock_savings": [0, 100], + "age": [40, 8], + "person_id": [101, 102], + "person_weight": [Fraction(3, 2), 7], + "first_home_mortgage_origination_year": [2023, 0], + "mock_credit": [300, 100], + "mock_ss_payment": [10_000, 0], + } + result = to_native_inputs( + original, contract=contract, basis=mock_basis, target_year=2017 + ) + assert result.values["mock_earnings"] == (40_000, -800) + assert result.values["mock_hourly_wage"] == (10, 16) + assert result.values["mock_savings"] == (0, 80) + for name in ( + "age", + "person_id", + "person_weight", + "first_home_mortgage_origination_year", + ): + assert result.values[name] == tuple(original[name]) + assert result.values["mock_ss_payment"] == (8_000, 0) + assert result.dropped_fields == ("mock_credit",) + assert "mock_credit" not in result.values + assert result.background_scopes == {"mock_ss_payment": "ss_entitlement_excluded"} + assert result.units["mock_hourly_wage"] == "USD/hour" + # Snapshot caller-owned containers; neither direction mutates the other. + original["age"][0] = 99 + assert result.values["age"] == (40, 8) + with pytest.raises(TypeError): + result.values["age"] = (99, 8) + + +@pytest.mark.parametrize("year", [2017, 2025, 2026]) +@pytest.mark.parametrize("unit", ["USD/year", "USD/hour", "USD/stock"]) +def test_exact_roundtrip_with_nonterminating_values(year, unit, mock_basis): + original = [Fraction(-1, 3), Decimal("123456.7890123456789")] + spec = money(unit=unit) + result = to_native_inputs( + {spec.name: original}, + contract=single_contract(spec), + basis=mock_basis, + target_year=year, + ) + restored = cash_to_reference( + result.values[spec.name], + basis=mock_basis, + native_year=year, + unit=unit, + period="year", + entity_count=2, + ) + assert restored == tuple(Fraction(value) for value in original) + + +def test_months_remain_distinct_and_roundtrip_without_annual_broadcast(mock_basis): + original = {month: [month, month * 10] for month in range(1, 13)} + spec = money("mock_monthly_cost", period="month", unit="USD/month") + result = to_native_inputs( + {spec.name: original}, + contract=single_contract(spec), + basis=mock_basis, + target_year=2017, + ) + assert result.values[spec.name][1] == (Fraction(4, 5), 8) + assert result.values[spec.name][12] == (Fraction(48, 5), 96) + restored = cash_to_reference( + result.values[spec.name], + basis=mock_basis, + native_year=2017, + unit="USD/month", + period="month", + entity_count=2, + ) + assert dict(restored) == { + month: tuple(values) for month, values in original.items() + } + + +def test_same_real_shock_is_difference_in_converted_primitives(mock_basis): + spec = money() + contract = single_contract(spec) + baseline = to_native_inputs( + {spec.name: [10_000, 0]}, contract=contract, basis=mock_basis, target_year=2017 + ) + shocked = to_native_inputs( + {spec.name: [11_000, 0]}, contract=contract, basis=mock_basis, target_year=2017 + ) + converted_shock = earnings_shock_to_native( + 1_000, basis=mock_basis, target_year=2017, unit="USD/year" + ) + assert ( + shocked.values[spec.name][0] - baseline.values[spec.name][0] + == converted_shock + == 800 + ) + + +@pytest.mark.parametrize( + "bad_inputs", [{}, {"mock_earnings": [1, 2], "unreviewed": [1, 2]}] +) +def test_no_missing_field_defaults_or_unknown_field_passthrough(bad_inputs, mock_basis): + with pytest.raises(ContractError, match="Unknown or missing"): + to_native_inputs( + bad_inputs, + contract=single_contract(money()), + basis=mock_basis, + target_year=2017, + ) + + +@pytest.mark.parametrize("bad", [[1], [1, 2, 3], [[1], [2]], "12", None]) +def test_rejects_wrong_shape_or_nonnumeric_nested_values(bad, mock_basis): + with pytest.raises(ContractError): + to_native_inputs( + {"mock_earnings": bad}, + contract=single_contract(money()), + basis=mock_basis, + target_year=2017, + ) + + +@pytest.mark.parametrize( + "bad", [None, True, float("inf"), float("nan"), "NaN", Decimal("Infinity")] +) +def test_missing_boolean_or_nonfinite_money_is_never_coerced_to_zero(bad, mock_basis): + with pytest.raises(ContractError): + to_native_inputs( + {"mock_earnings": [1, bad]}, + contract=single_contract(money()), + basis=mock_basis, + target_year=2017, + ) + + +@pytest.mark.parametrize( + "bad_block", [[1, 2], {1: [1, 2]}, {month: [1] for month in range(1, 13)}] +) +def test_monthly_inputs_require_twelve_complete_vectors(bad_block, mock_basis): + spec = money(period="month", unit="USD/month") + with pytest.raises(ContractError): + to_native_inputs( + {spec.name: bad_block}, + contract=single_contract(spec), + basis=mock_basis, + target_year=2017, + ) + + +@pytest.mark.parametrize("year", [2016, 2027, True, "2017", 2018]) +def test_unsupported_or_unpriced_year_fails(year, mock_basis): + with pytest.raises(ContractError): + to_native_inputs( + {"mock_earnings": [1, 2]}, + contract=single_contract(money()), + basis=mock_basis, + target_year=year, + ) + + +@pytest.mark.parametrize( + "indices", [{2025: 0}, {2025: -1}, {2025: "NaN"}, {2017: 80}, {True: 80, 2025: 100}] +) +def test_price_basis_never_supplies_or_accepts_invalid_indices(indices): + with pytest.raises(ContractError): + PriceBasis(indices) + + +def test_price_basis_is_snapshot_of_declared_mapping(): + original = {2017: 80, 2025: 100} + basis = PriceBasis(original) + original[2017] = 999 + assert basis.factor(2017) == Fraction(4, 5) + + +@pytest.mark.parametrize("disposition", [Disposition.KEEP, Disposition.SCALE, "guess"]) +def test_derived_output_cannot_be_kept_or_scaled_as_primitive(disposition): + with pytest.raises(ContractError): + FieldSpec( + "mock_credit", + "person", + Kind.POLICY_DERIVED, + disposition, + "USD/year", + "year", + ) + + +def test_background_requires_both_named_scope_and_contract_approval(): + with pytest.raises(ContractError): + FieldSpec( + "mock_credit", + "person", + Kind.POLICY_DERIVED, + Disposition.BACKGROUND, + "USD/year", + "year", + ) + field = FieldSpec( + "mock_credit", + "person", + Kind.POLICY_DERIVED, + Disposition.BACKGROUND, + "USD/year", + "year", + "excluded_payment_policy", + ) + with pytest.raises(ContractError, match="not approved"): + single_contract(field) + + +@pytest.mark.parametrize( + "name", + ["age", "person_weight", "person_id", "first_home_mortgage_origination_year"], +) +def test_known_facts_cannot_be_misdeclared_as_money(name): + with pytest.raises(ContractError): + money(name) + + +@pytest.mark.parametrize( + "kwargs", + [ + {"unit": "USD"}, + {"unit": "USD/month", "period": "year"}, + {"unit": "USD/year", "period": "month"}, + {"period": "day"}, + ], +) +def test_unit_and_period_contract_has_no_implicit_conversions(kwargs): + with pytest.raises(ContractError): + money(**kwargs) + + +def test_dropped_derived_fields_are_still_shape_validated(mock_basis): + field = FieldSpec( + "mock_credit", + "person", + Kind.POLICY_DERIVED, + Disposition.DROP, + "USD/year", + "year", + ) + with pytest.raises(ContractError): + to_native_inputs( + {"mock_credit": [1]}, + contract=single_contract(field), + basis=mock_basis, + target_year=2017, + ) + + +@pytest.mark.parametrize( + "counts", [{}, {"person": True}, {"person": -1}, {"person": 2, "unknown_entity": 3}] +) +def test_declared_entity_shapes_are_required(counts): + with pytest.raises(ContractError): + InputContract((money(),), counts) + + +def test_duplicate_declarations_fail_before_conversion(): + with pytest.raises(ContractError): + InputContract((money(), money()), {"person": 2}) + + +def test_inverse_is_cash_only_and_shock_is_flow_only(mock_basis): + with pytest.raises(ContractError): + cash_to_reference( + [1, 2], + basis=mock_basis, + native_year=2017, + unit="weight", + period="year", + entity_count=2, + ) + with pytest.raises(ContractError): + earnings_shock_to_native( + 1, basis=mock_basis, target_year=2017, unit="USD/stock" + ) + + +def test_explicit_calendar_dates_and_structural_flags_are_unchanged(mock_basis): + fields = ( + FieldSpec( + "loan_origination_date", + "person", + Kind.CALENDAR, + Disposition.KEEP, + "calendar_date", + "year", + ), + FieldSpec( + "mock_member_id", + "person", + Kind.STRUCTURE, + Disposition.KEEP, + "id", + "eternity", + ), + FieldSpec( + "mock_role", "person", Kind.STRUCTURE, Disposition.KEEP, "flag", "year" + ), + ) + original = { + # Preserve actual calendar facts; the future adapter reviews loan treatment. + "loan_origination_date": ["2020-05-02", "1985-03-01"], + "mock_member_id": [101, 101], + "mock_role": [False, True], + } + result = to_native_inputs( + original, + contract=InputContract(fields, {"person": 2}), + basis=mock_basis, + target_year=2017, + ) + assert result.values == {name: tuple(values) for name, values in original.items()} + + +@pytest.mark.parametrize("bad_weight", [-1, float("nan"), None, True]) +def test_given_weights_are_validated_but_never_scaled_or_defaulted( + bad_weight, mock_basis +): + field = FieldSpec( + "person_weight", "person", Kind.WEIGHT, Disposition.KEEP, "weight", "year" + ) + with pytest.raises(ContractError): + to_native_inputs( + {field.name: [0, bad_weight]}, + contract=single_contract(field), + basis=mock_basis, + target_year=2017, + ) + + +def test_boolean_month_key_is_not_an_integer_month(mock_basis): + field = money(period="month", unit="USD/month") + invalid = {True if month == 1 else month: [1, 2] for month in range(1, 13)} + with pytest.raises(ContractError): + to_native_inputs( + {field.name: invalid}, + contract=single_contract(field), + basis=mock_basis, + target_year=2017, + ) + + +@pytest.mark.parametrize("reference_year", [2024, True, "2025"]) +def test_reference_year_is_explicit_and_supported(reference_year): + with pytest.raises(ContractError): + PriceBasis({2017: 80, 2025: 100}, reference_year=reference_year) + + +@settings(max_examples=50, deadline=None, database=None, derandomize=True) +@given( + endowments=st.lists( + st.one_of( + st.integers(-1_000_000, 1_000_000), + st.decimals( + "-1000000", "1000000", places=4, allow_nan=False, allow_infinity=False + ), + ), + min_size=1, + max_size=6, + ), + reference_price=st.decimals( + "1", "10000", places=3, allow_nan=False, allow_infinity=False + ), + native_price=st.decimals( + "1", "10000", places=3, allow_nan=False, allow_infinity=False + ), + year=st.integers(2017, 2026), + unit=st.sampled_from(["USD/year", "USD/month", "USD/hour", "USD/stock"]), +) +def test_property_mock_money_roundtrip( + endowments, reference_price, native_price, year, unit +): + """Unit conversion is invertible for synthetic signed money in any supported year.""" + indices = {2025: reference_price} + if year != 2025: + indices[year] = native_price + basis = PriceBasis(indices) + period = "month" if unit == "USD/month" else "year" + field = money("mock_property_money", period=period, unit=unit) + contract = InputContract((field,), {"person": len(endowments)}) + # Explicit distinct months; this does not broadcast one annual total. + original = ( + { + month: [Fraction(value) + Fraction(month, 100) for value in endowments] + for month in range(1, 13) + } + if period == "month" + else endowments + ) + native = to_native_inputs( + {field.name: original}, contract=contract, basis=basis, target_year=year + ) + restored = cash_to_reference( + native.values[field.name], + basis=basis, + native_year=year, + unit=unit, + period=period, + entity_count=len(endowments), + ) + if period == "month": + assert dict(restored) == { + month: tuple(values) for month, values in original.items() + } + else: + assert restored == tuple(Fraction(value) for value in original) + assert native.units[field.name] == unit + assert native.target_year == year + + +@settings(max_examples=50, deadline=None, database=None, derandomize=True) +@given( + endowment=st.one_of( + st.integers(-1_000_000, 1_000_000), + st.decimals( + "-1000000", "1000000", places=4, allow_nan=False, allow_infinity=False + ), + ), + shock=st.decimals( + "-10000", "10000", places=4, allow_nan=False, allow_infinity=False + ), + reference_price=st.integers(1, 10000), + native_price=st.integers(1, 10000), + year=st.integers(2017, 2026), + age=st.integers(0, 110), + mock_weight=st.decimals( + "0", "1000", places=3, allow_nan=False, allow_infinity=False + ), + origination_year=st.integers(0, 2035), +) +def test_property_mock_shock_is_linear_and_facts_are_fixed( + endowment, + shock, + reference_price, + native_price, + year, + age, + mock_weight, + origination_year, +): + """A synthetic real shock changes money only, even with future contract dates.""" + indices = {2025: reference_price} + if year != 2025: + indices[year] = native_price + basis = PriceBasis(indices) + fields = ( + money(), + FieldSpec("age", "person", Kind.AGE, Disposition.KEEP, "age_years", "year"), + FieldSpec("person_id", "person", Kind.ID, Disposition.KEEP, "id", "eternity"), + FieldSpec( + "person_weight", "person", Kind.WEIGHT, Disposition.KEEP, "weight", "year" + ), + FieldSpec( + "first_home_mortgage_origination_year", + "person", + Kind.CALENDAR, + Disposition.KEEP, + "calendar_year", + "year", + ), + ) + contract = InputContract(fields, {"person": 1}) + original = { + "mock_earnings": [endowment], + "age": [age], + "person_id": [101], + "person_weight": [mock_weight], + "first_home_mortgage_origination_year": [origination_year], + } + shocked_input = { + **original, + "mock_earnings": [Fraction(endowment) + Fraction(shock)], + } + baseline = to_native_inputs( + original, contract=contract, basis=basis, target_year=year + ) + shocked = to_native_inputs( + shocked_input, contract=contract, basis=basis, target_year=year + ) + assert shocked.values["mock_earnings"][0] - baseline.values["mock_earnings"][ + 0 + ] == earnings_shock_to_native( + shock, + basis=basis, + target_year=year, + unit="USD/year", + ) + for name in ( + "age", + "person_id", + "person_weight", + "first_home_mortgage_origination_year", + ): + assert baseline.values[name] == shocked.values[name] == tuple(original[name]) + + +def test_fixed_age_and_birth_facts_require_reviewed_disposition(): + fields = ( + FieldSpec("age", "person", Kind.AGE, Disposition.KEEP, "age_years", "year"), + FieldSpec( + "birth_date", + "person", + Kind.CALENDAR, + Disposition.KEEP, + "calendar_date", + "year", + ), + ) + with pytest.raises(ContractError, match="birth"): + InputContract(fields, {"person": 1}) + + +@pytest.mark.parametrize("disposition", [Disposition.DROP, Disposition.KEEP]) +def test_age_led_birth_disposition_is_recorded_without_shifting_dates( + disposition, mock_basis +): + reason = "Fix synthetic age and exclude stored birth-cohort eligibility consumers" + fields = ( + FieldSpec("age", "person", Kind.AGE, Disposition.KEEP, "age_years", "year"), + FieldSpec( + "birth_date", + "person", + Kind.CALENDAR, + disposition, + "calendar_date", + "year", + calendar_scope="age_led_birth_facts", + calendar_reason=reason, + ), + FieldSpec( + "loan_origination_date", + "person", + Kind.CALENDAR, + Disposition.KEEP, + "calendar_date", + "year", + ), + ) + contract = InputContract( + fields, {"person": 1}, calendar_scopes=frozenset({"age_led_birth_facts"}) + ) + original = { + "age": [40.7], + "birth_date": ["1985-03-01"], + "loan_origination_date": ["2023-01-01"], + } + result = to_native_inputs( + original, contract=contract, basis=mock_basis, target_year=2017 + ) + assert result.values["age"] == (40.7,) + assert result.values["loan_origination_date"] == ("2023-01-01",) + assert result.calendar_dispositions == { + "birth_date": { + "disposition": disposition.value, + "scope": "age_led_birth_facts", + "reason": reason, + } + } + if disposition == Disposition.DROP: + assert result.dropped_fields == ("birth_date",) + assert "birth_date" not in result.values + else: + assert result.dropped_fields == () + assert result.values["birth_date"] == ("1985-03-01",) + assert original["birth_date"] == ["1985-03-01"] + with pytest.raises(TypeError): + result.calendar_dispositions["birth_date"]["scope"] = "unreviewed" + + +@pytest.mark.parametrize("disposition", [Disposition.DROP, Disposition.KEEP]) +def test_birth_disposition_requires_approved_scope(disposition): + fields = ( + FieldSpec("age", "person", Kind.AGE, Disposition.KEEP, "age_years", "year"), + FieldSpec( + "birth_year", + "person", + Kind.CALENDAR, + disposition, + "calendar_year", + "year", + calendar_scope="unapproved", + calendar_reason="Synthetic ages hold cohort-sensitive provisions outside scope", + ), + ) + with pytest.raises(ContractError, match="not approved"): + InputContract(fields, {"person": 1}) + + +@pytest.mark.parametrize( + "scope,reason", + [(None, None), ("age_led", None), ("", "reviewed"), ([], "reviewed")], +) +def test_birth_drop_requires_explicit_scope_and_reason(scope, reason): + with pytest.raises(ContractError): + FieldSpec( + "birth_date", + "person", + Kind.CALENDAR, + Disposition.DROP, + "calendar_date", + "year", + calendar_scope=scope, + calendar_reason=reason, + ) + + +def test_calendar_drop_is_limited_to_declared_age_derived_birth_facts(): + with pytest.raises(ContractError): + FieldSpec( + "loan_origination_date", + "person", + Kind.CALENDAR, + Disposition.DROP, + "calendar_date", + "year", + calendar_scope="age_led", + calendar_reason="This is a loan fact, not an age-derived birth fact", + ) + birth = FieldSpec( + "birth_year", + "person", + Kind.CALENDAR, + Disposition.DROP, + "calendar_year", + "year", + calendar_scope="age_led", + calendar_reason="Replace stored birth year with a declared synthetic age", + ) + with pytest.raises(ContractError, match="fixed age"): + InputContract((birth,), {"person": 1}, calendar_scopes={"age_led"}) + + +@pytest.mark.parametrize( + "kind,unit,name,text", + [ + (Kind.AGE, "age_years", "age", "40.7"), + (Kind.WEIGHT, "weight", "person_weight", "1.5"), + (Kind.DIMENSIONLESS, "fraction", "mock_fraction", "0.25"), + ], +) +def test_numeric_fact_strings_fail_without_coercion(kind, unit, name, text, mock_basis): + spec = FieldSpec(name, "person", kind, Disposition.KEEP, unit, "year") + with pytest.raises(ContractError, match="numeric values"): + to_native_inputs( + {name: [text]}, + contract=InputContract((spec,), {"person": 1}), + basis=mock_basis, + target_year=2017, + ) + + +@pytest.mark.parametrize( + "kind,unit,name", + [ + (Kind.AGE, "age_years", "age"), + (Kind.WEIGHT, "weight", "person_weight"), + (Kind.DIMENSIONLESS, "fraction", "mock_fraction"), + ], +) +def test_finite_numeric_facts_preserve_values_and_types(kind, unit, name, mock_basis): + values = [0, 40.7, Decimal("8.125"), Fraction(1, 3)] + spec = FieldSpec(name, "person", kind, Disposition.KEEP, unit, "year") + result = to_native_inputs( + {name: values}, + contract=InputContract((spec,), {"person": 4}), + basis=mock_basis, + target_year=2017, + ) + assert result.values[name] == tuple(values) + assert [type(v) for v in result.values[name]] == [type(v) for v in values] + + +@pytest.mark.parametrize( + "value", + [ + "1e999999999", + "1e-999999999", + Decimal("1e999999999"), + "1" * 1001, + "1" * 2049, + 1 << 4096, + ], +) +def test_oversized_representations_fail_before_fraction_allocation( + value, monkeypatch, mock_basis +): + import cliffs2017.native_currency as currency + + class NoAllocation(Fraction): + def __new__(cls, *args, **kwargs): + raise AssertionError( + "Fraction allocation preceded the representation guard" + ) + + monkeypatch.setattr(currency, "Fraction", NoAllocation) + with pytest.raises(ContractError): + earnings_shock_to_native( + value, basis=mock_basis, target_year=2017, unit="USD/year" + ) + + +@pytest.mark.parametrize("value", [Fraction(1 << 4096, 1), Fraction(1, 1 << 4096)]) +def test_existing_ratios_must_respect_representation_budget(value, mock_basis): + with pytest.raises(ContractError): + earnings_shock_to_native( + value, basis=mock_basis, target_year=2017, unit="USD/year" + ) + + +@pytest.mark.parametrize("unit", [[], {}, set()]) +def test_unhashable_shock_unit_raises_contract_error(unit, mock_basis): + with pytest.raises(ContractError): + earnings_shock_to_native(1, basis=mock_basis, target_year=2017, unit=unit) + + +@pytest.mark.parametrize("scopes", [None, "scope", [["nested"]], {"scope": []}]) +@pytest.mark.parametrize("attribute", ["background_scopes", "calendar_scopes"]) +def test_malformed_scope_collections_raise_contract_error(scopes, attribute): + with pytest.raises(ContractError): + InputContract((money(),), {"person": 1}, **{attribute: scopes}) + + +def test_fraction_category_and_count_months_preserve_explicit_facts(mock_basis): + fields = ( + FieldSpec( + "mock_fraction", + "person", + Kind.DIMENSIONLESS, + Disposition.KEEP, + "fraction", + "month", + ), + FieldSpec( + "mock_category", + "person", + Kind.DEMOGRAPHIC, + Disposition.KEEP, + "category", + "month", + ), + FieldSpec( + "mock_count", "person", Kind.STRUCTURE, Disposition.KEEP, "count", "month" + ), + ) + original = { + "mock_fraction": {m: [Fraction(m, 12)] for m in range(1, 13)}, + "mock_category": {m: [f"group{m}"] for m in range(1, 13)}, + "mock_count": {m: [m] for m in range(1, 13)}, + } + result = to_native_inputs( + original, + contract=InputContract(fields, {"person": 1}), + basis=mock_basis, + target_year=2017, + ) + for name, months in original.items(): + assert dict(result.values[name]) == {m: tuple(v) for m, v in months.items()} + + +@pytest.mark.parametrize( + "kind,unit,value", + [ + (Kind.DEMOGRAPHIC, "category", ""), + (Kind.DEMOGRAPHIC, "category", True), + (Kind.STRUCTURE, "count", -1), + (Kind.STRUCTURE, "count", 1.5), + (Kind.STRUCTURE, "count", True), + (Kind.DIMENSIONLESS, "fraction", None), + (Kind.DIMENSIONLESS, "fraction", float("nan")), + ], +) +def test_bad_category_count_and_fraction_facts_fail(kind, unit, value, mock_basis): + spec = FieldSpec("mock_fact", "person", kind, Disposition.KEEP, unit, "year") + with pytest.raises(ContractError): + to_native_inputs( + {spec.name: [value]}, + contract=InputContract((spec,), {"person": 1}), + basis=mock_basis, + target_year=2017, + ) + + +@pytest.mark.parametrize("count", [True, -1, "2", None]) +def test_inverse_rejects_invalid_entity_count(count, mock_basis): + with pytest.raises(ContractError, match="entity count"): + cash_to_reference( + [1, 2], + basis=mock_basis, + native_year=2017, + unit="USD/year", + period="year", + entity_count=count, + ) + + +def test_entity_counts_do_not_invent_unsupplied_fields(mock_basis): + contract = InputContract((), {"person": 2, "household": 1}) + result = to_native_inputs({}, contract=contract, basis=mock_basis, target_year=2017) + assert contract.entity_counts == {"person": 2, "household": 1} + assert result.values == result.units == result.calendar_dispositions == {} + assert result.dropped_fields == ()