From 7d3f9b113153a2538c20ebc94f8f58f910eab669 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 13 Nov 2026 11:59:27 -0500 Subject: [PATCH 1/6] Pin US county facts beside the main feed for the county rung (#922) The ACS-local county rung needs county-grain Chronicle facts: IRS SOI county TY2022, Census PEP county vintage 2024, and seven ACS 2020-2024 5-year county tables. Folding them into the main US feed would grow it about 6.5x for every fiscal compile while only county builds read them, so they get their own pin. - us/chronicle_county_facts.json and chronicle_county_facts_scope.json pin a bare v5 facts file at Chronicle main 3e9d3a069 (scope us_county_facts, 10 pairs). The main pin, its scope and the parity resources do not change; the two scopes share no pair. - chronicle_feed.py loads both pins through one validator; the main pin's messages are unchanged. - us_runtime/county_facts.py reads the file in one pass: digest and row count against the pin, refusal of any row on another contract, at another geography level or outside the scope, Puerto Rico dropped with a count, rows projected to the fields the rung reads. - The county rung takes --county-facts and --county-facts-sha256 (the pin's digest), requires --feed-sha256, loads the file once in prepare_run and never re-reads --feed for county facts. The run identity and refresh recipe record them; a no-county run's identity keeps its bytes. Co-Authored-By: Claude Opus 5.5 --- changelog.d/922-us-county-facts-pin.added.md | 1 + docs/us-acs-local-county-rung.md | 95 ++++---- docs/us-chronicle-feed-repin.md | 66 ++++++ .../build/us/chronicle_county_facts.json | 17 ++ .../us/chronicle_county_facts_scope.json | 105 +++++++++ .../build/us_runtime/chronicle_feed.py | 126 ++++++++--- .../build/us_runtime/county_facts.py | 187 ++++++++++++++++ .../us/test_us_acs_local_county_surface.py | 179 ++++++++++++++- .../us/test_us_chronicle_county_facts.py | 208 ++++++++++++++++++ .../engine_free/us/test_us_spine_blindness.py | 5 + tools/us_acs_local_county_surface.py | 100 ++++++++- 11 files changed, 990 insertions(+), 99 deletions(-) create mode 100644 changelog.d/922-us-county-facts-pin.added.md create mode 100644 packages/microcosm-build/src/microcosm/build/us/chronicle_county_facts.json create mode 100644 packages/microcosm-build/src/microcosm/build/us/chronicle_county_facts_scope.json create mode 100644 packages/microcosm-build/src/microcosm/build/us_runtime/county_facts.py create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_chronicle_county_facts.py diff --git a/changelog.d/922-us-county-facts-pin.added.md b/changelog.d/922-us-county-facts-pin.added.md new file mode 100644 index 0000000000..21a8bde4c7 --- /dev/null +++ b/changelog.d/922-us-county-facts-pin.added.md @@ -0,0 +1 @@ +Pin the US county facts (IRS SOI county, Census PEP county and seven ACS 5-year county tables) as their own Chronicle file beside the main US feed, and make the ACS-local county rung read them through `--county-facts` and `--county-facts-sha256` instead of `--feed`. diff --git a/docs/us-acs-local-county-rung.md b/docs/us-acs-local-county-rung.md index 8f2a84f6e3..451e52e254 100644 --- a/docs/us-acs-local-county-rung.md +++ b/docs/us-acs-local-county-rung.md @@ -127,60 +127,45 @@ two concepts are available. At fixed error, raising ESS cannot worsen a grade. These are report-only evidence grades; Kish ESS is not a county standard error or a guarantee of unbiased estimates. -## Audited feed and remaining input work - -The release's packaged pin is -`packages/microcosm-build/src/microcosm/build/us/chronicle_feed.json`, pointing -to Chronicle commit `51aa40fd28e2ca81937752515e773d123fecfb71`. The corresponding -local feed is -`/Users/maxghenis/PolicyEngine/_buildh-runtime/inputs/consumer_facts_us_51aa40f.jsonl`. -The audit streamed its actual bytes: 40,178 facts, 169,038,757 bytes, SHA256 -`965a29ac9458edb58a05184917ee4a19772fd3dc7b4588db6eb6da5803641aac`. -It contains **zero county facts**: 23,968 congressional-district, 12,251 state, -and 3,959 country facts. The historical release recipe uses a `--feed` -placeholder; that recipe does not prove county facts were exported. - -Both county source packages already exist at the pinned Chronicle commit. -They are omitted by the explicit `chronicle_feed_scope.json` selection. A -reviewed feed extension needs the following additional pairs: - -```json -[ - { - "record_set_id": "irs_soi.ty2022.county_totals", - "period_type": "tax_year", - "period_value": "2022", - "package_id": "soi-county-2022", - "package": "packages/irs_soi/county_2022", - "build_year": 2022 - }, - { - "record_set_id": "census_pep.vintage2024.county_population", - "period_type": "calendar_year", - "period_value": "2024", - "package_id": "census-pep-county-population-2024", - "package": "packages/census/pep_county_2024", - "build_year": 2024 - } -] -``` - -Add the packages to their build-year `runs` entries, update the scope pair -count, rebuild with `tools/build_us_chronicle_feed.py`, and review/update the -feed and scope hashes and fact-to-target parity/fencing evidence. The current -fiscal compiler excludes county SOI geography; this rung consumes the raw -county facts and splits existing state measures. Population defaults still -use the ladder. Future ACS county packages require an additional scoped feed -extension. This implementation performs **no feed or scope mutation** and -does not claim an available county feed hash. +## County facts input (microcosm#922) + +County facts do not come from `--feed`. They have their own pin, +`packages/microcosm-build/src/microcosm/build/us/chronicle_county_facts.json`, +with scope `chronicle_county_facts_scope.json` (scope name `us_county_facts`), +built at Chronicle commit `3e9d3a0694e8ca7e31ed5319c3ceb1bde92b12e0` on the +`chronicle.consumer_fact.v5` row contract. The file holds 180,326 rows +(922 MB, SHA256 +`67b0998aa2ee1aeed6637dab6a846f405246706508074b1c1b5bab7bd98c8bea`): IRS SOI +county TY2022, Census PEP county vintage 2024, and the ACS 2020-2024 5-year county tables B01003, B11001, B19001, +B19013, B19025, B19051 and B19061. The main feed, its scope and the target +parity resources are unchanged; [the re-pin notes](us-chronicle-feed-repin.md#the-county-facts-pin-microcosm922) +say why the county facts are a separate file. + +A `--soi-mode state_county` materialize must pass +`--county-facts --county-facts-sha256 ` +and `--feed-sha256` for the main feed. The parser refuses a county facts digest +other than the pin's, county facts without county geography or +`--soi-mode state_county`, and a county facts path that is the `--feed` file. +`prepare_run` reads the file once with +`microcosm.build.us_runtime.county_facts.load_us_county_facts`, which checks +the digest, the row count, the row contract, the county level and the scope of +every row, and drops the 78 Puerto Rico municipios (4,136 ACS rows) with a +count. Loading the pinned file took 42 s and 2.5 GB of memory on the build +machine; the rows stay in memory for the rest of the materialize stage. Every later +county step reads those rows; nothing re-reads `--feed` for county facts. The +run identity and `materialize_rss.json` record the county facts receipt under +`county_facts`, and the refresh recipe carries both flags. A run without county +facts records nothing new, so its run identity keeps its pre-county bytes. The inspected Chronicle publisher inputs have two concrete blockers: - **Kalawao:** the SOI CSV has 3,143 counties and omits `15005` Kalawao County; - the PEP CSV has all 3,144. A complete county SOI block currently fails with - that county named. A source correction or an explicitly reviewed county - treatment is needed before a full SOI run; this implementation introduces - no fallback and does not silently borrow Maui's facts. + the PEP and ACS tables carry all 3,144. The IRS 2022 county users guide + (`22incydocguide.docx`) says items with fewer than 20 returns for a county + were excluded, so Kalawao's SOI value is missing, not zero, and the IRS does + not fold it into Maui. Until the rung declares a reviewed treatment (a + combined SOI cell {15005, 15009}, planned on `lwi-county-rung-production`), + a complete county SOI block still fails with that county named. - **Connecticut:** both packages use the nine planning-region codes `09110` through `09190`. The household county column and ladder must use those same boundaries. Select `--county-column county_fips_2023` when the parallel @@ -199,7 +184,8 @@ for `co-est2024-alldata.csv`. ## Full-run requirements and command -A full run needs a reviewed county-inclusive Ledger feed and its actual SHA256, +A full run needs the pinned main feed and its SHA256, the pinned county facts +file and its SHA256, a staging H5 and summary with household support in every county, a matching county-boundary PUMA ladder, and resolution of the Kalawao SOI gap. The historical staging file was approximately 10.7 GB. The historical ladder was @@ -251,8 +237,10 @@ The **tax-target cost is unmeasured until the joint solve runs**; these are starting settings, not evidence that the production tradeoff is acceptable. ```bash -export COUNTY_FEED=/path/to/consumer_facts_county.jsonl -export COUNTY_FEED_SHA256='' +export COUNTY_FEED=/path/to/pinned/consumer_facts_us.jsonl +export COUNTY_FEED_SHA256='' +export COUNTY_FACTS=/path/to/consumer_facts_us_county_3e9d3a0.jsonl +export COUNTY_FACTS_SHA256='67b0998aa2ee1aeed6637dab6a846f405246706508074b1c1b5bab7bd98c8bea' export COUNTY_STAGING_H5=/path/to/acs_multispine_staging.h5 export COUNTY_STAGING_SUMMARY=/path/to/acs_multispine_staging.summary.json export COUNTY_LADDER=/path/to/matching_us_puma_ladder.npz @@ -264,6 +252,7 @@ uv run python tools/build_us_acs_local_release.py \ --staging-h5 "$COUNTY_STAGING_H5" \ --staging-summary "$COUNTY_STAGING_SUMMARY" \ --feed "$COUNTY_FEED" --feed-sha256 "$COUNTY_FEED_SHA256" \ + --county-facts "$COUNTY_FACTS" --county-facts-sha256 "$COUNTY_FACTS_SHA256" \ --ladder "$COUNTY_LADDER" \ --families snap,medicaid,soi --geographies state,cd,county \ --soi-mode state_county --county-column "$COUNTY_COLUMN" \ diff --git a/docs/us-chronicle-feed-repin.md b/docs/us-chronicle-feed-repin.md index f40483985f..d55816eab1 100644 --- a/docs/us-chronicle-feed-repin.md +++ b/docs/us-chronicle-feed-repin.md @@ -13,6 +13,72 @@ any other feed, and `test_us_chronicle_feed.py` fails if the parity resources, the generator and the pin disagree, or if the scope file changes without a new pin. +## The county facts pin (microcosm#922) + +The ACS-local county rung (`tools/us_acs_local_county_surface.py`) reads +county-grain facts: IRS SOI county returns and AGI for tax year 2022, Census +PEP county population vintage 2024, and the ACS 2020-2024 5-year county tables +B01003, B11001, B19001, B19013, B19025, B19051 and B19061. They have their own +pin, `us/chronicle_county_facts.json`, with scope +`us/chronicle_county_facts_scope.json` (scope name `us_county_facts`), beside +the main pin. No fiscal compile reads them, and the main feed, its scope and +the target-parity resources do not move when they do. + +They are separate because of size. The ACS county rows keep both estimate and +margin-of-error rows in one record set, about 4.9 KB per row, and the eight +record sets come to 170,896 rows and 886 MB. In the main feed they would have +grown it from 169 MB to about 1.1 GB (6.5x), raising every compile site's peak +from 2.8 GB to 6.7 GB and keeping about 3.2 GB more resident in every +fiscal-refresh run, while only county builds read them. A main-feed rebuild +with them also passed the build machine's 3.5 GB folder cap. The measurements +are in `~/reviews/lwi-county-build-2026-11-13/runs/feed-design-1113/` on the +build machine. + +- **Commit.** Chronicle main `3e9d3a0694e8ca7e31ed5319c3ceb1bde92b12e0` + (merged 2026-11-12), which carries every county package. It is on main, so + it needs no branch or tag; the next main re-pin starts at or after it. + The rows are on the `chronicle.consumer_fact.v5` contract + (schema digest `acd33a09…`); the main pin stays on v3. +- **Pairs.** 10, built at their own years (2022: `packages/irs_soi/county_2022`; + 2024: `packages/census/pep_county_2024` and the seven + `packages/census/acs5_b*_county_2024` packages). The scopes share no pair, + and `test_us_chronicle_county_facts.py` refuses a change that adds one to + both. +- **Build.** The same builder with the county scope: + + ```bash + uv run python tools/build_us_chronicle_feed.py --scope packages/microcosm-build/src/microcosm/build/us/chronicle_county_facts_scope.json --chronicle-root --out --skip-artifact + ``` + + The build at that commit wrote 180,326 rows (922 MB), SHA256 + `67b0998aa2ee1aeed6637dab6a846f405246706508074b1c1b5bab7bd98c8bea`. Its + output folder peaked at 2.89 GB under a disk-cap watcher that deleted each + finished package's intermediates. Nine of its ten record sets equal an + earlier build at Chronicle `c32c0b0` row for row (key, value, unit, measure + and geography); PEP county was not in that build. +- **Reading it.** `us_runtime/county_facts.load_us_county_facts` reads the file + in one pass: it hashes the bytes, refuses a row on another row contract, at + a geography level other than county or outside the scope's pairs, drops the + 78 Puerto Rico municipios (state 72) with a count, projects each kept row to + the fields the rung reads, and refuses the file unless its digest and row + count are the pin's. The file on disk keeps Chronicle's bytes. +- **Tool flags.** County runs pass `--county-facts + --county-facts-sha256 `, and `--feed-sha256` for the main feed. + The run identity records the main feed's digest (`feed_sha256`) and the + county facts receipt, which carries the county pin. +- **What it holds that the rung must handle.** SOI county 2022 has 3,143 + counties and no Kalawao (15005). ACS B19013 (median household income) has no + row for De Baca County (35011) and is a median, so it is a diagnostic, not a + linear target. B01003 carries margin-of-error rows for only some counties. + Connecticut appears as its nine planning regions (09110-09190) in every + package. Against the main pin's state SOI parents, the SOI county rows split + the other 49 states and DC exactly (6,278 county targets; share and target + sums exact), and Hawaii is refused, naming 15005, until the rung declares a + treatment for it. + +A later main re-pin can fold these pairs into the main scope only by retiring +the county pin in the same change. + ## A re-pin onto a newer row contract The US feed is on `chronicle.consumer_fact.v3`; Chronicle `main` writes diff --git a/packages/microcosm-build/src/microcosm/build/us/chronicle_county_facts.json b/packages/microcosm-build/src/microcosm/build/us/chronicle_county_facts.json new file mode 100644 index 0000000000..a788a93f5c --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us/chronicle_county_facts.json @@ -0,0 +1,17 @@ +{ + "version": 1, + "country": "us", + "scope": "us_county_facts", + "source_repo": "PolicyEngine/chronicle", + "source_commit": "3e9d3a0694e8ca7e31ed5319c3ceb1bde92b12e0", + "build": "tools/build_us_chronicle_feed.py --skip-artifact --scope packages/microcosm-build/src/microcosm/build/us/chronicle_county_facts_scope.json: one `chronicle build-bundle --year Y --source ` per build year in chronicle_county_facts_scope.json, rows kept for exactly the scope's (record set, period) pairs and sorted by aggregate_fact_key, at Chronicle main 3e9d3a069. County rows only (IRS SOI county TY2022, Census PEP county vintage 2024, seven ACS 2020-2024 5-year county tables), read only by the ACS-local county rung through --county-facts (microcosm#922); no fiscal compile reads them. Bare facts file; see docs/us-chronicle-feed-repin.md.", + "artifact_schema_version": null, + "consumer_fact_schema_versions": [ + "chronicle.consumer_fact.v5" + ], + "consumer_fact_schema_sha256": "acd33a091cd8d192be5d264e3e94c13e00afb6fd1972e57d4576ac55a54f6970", + "fact_row_count": 180326, + "facts_sha256": "67b0998aa2ee1aeed6637dab6a846f405246706508074b1c1b5bab7bd98c8bea", + "manifest_sha256": null, + "scope_sha256": "87b12e4f74702ccbf5fe96c128ff5df0ffd8214a78de8f1fcce2ab2ba37fe7f5" +} diff --git a/packages/microcosm-build/src/microcosm/build/us/chronicle_county_facts_scope.json b/packages/microcosm-build/src/microcosm/build/us/chronicle_county_facts_scope.json new file mode 100644 index 0000000000..dd9497d546 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us/chronicle_county_facts_scope.json @@ -0,0 +1,105 @@ +{ + "version": 1, + "country": "us", + "source_repo": "PolicyEngine/chronicle", + "source_commit": "3e9d3a0694e8ca7e31ed5319c3ceb1bde92b12e0", + "rule": "County facts for the ACS-local county rung only (microcosm#922, LWI County Files): IRS SOI county returns and AGI for tax year 2022, Census PEP county population vintage 2024, and the ACS 2020-2024 5-year county tables B01003, B11001, B19001, B19013, B19025, B19051 and B19061, each record set at its own period and built at that year. A separate pin from the main US feed: no fiscal compile reads it.", + "pair_count": 10, + "runs": { + "2022": [ + "packages/irs_soi/county_2022" + ], + "2024": [ + "packages/census/acs5_b01003_county_2024", + "packages/census/acs5_b11001_county_2024", + "packages/census/acs5_b19001_county_2024", + "packages/census/acs5_b19013_county_2024", + "packages/census/acs5_b19025_county_2024", + "packages/census/acs5_b19051_county_2024", + "packages/census/acs5_b19061_county_2024", + "packages/census/pep_county_2024" + ] + }, + "pairs": [ + { + "record_set_id": "irs_soi.ty2022.county_totals", + "period_type": "tax_year", + "period_value": "2022", + "package_id": "soi-county-2022", + "package": "packages/irs_soi/county_2022", + "build_year": 2022 + }, + { + "record_set_id": "census_pep.vintage2024.county_population", + "period_type": "calendar_year", + "period_value": "2024", + "package_id": "census-pep-county-population-2024", + "package": "packages/census/pep_county_2024", + "build_year": 2024 + }, + { + "record_set_id": "census_acs.acs5_2020_2024.b01003.county.group_0", + "period_type": "calendar_year", + "period_value": "2024", + "package_id": "census-acs5-b01003-county-2024", + "package": "packages/census/acs5_b01003_county_2024", + "build_year": 2024 + }, + { + "record_set_id": "census_acs.acs5_2020_2024.b01003.county.group_1", + "period_type": "calendar_year", + "period_value": "2024", + "package_id": "census-acs5-b01003-county-2024", + "package": "packages/census/acs5_b01003_county_2024", + "build_year": 2024 + }, + { + "record_set_id": "census_acs.acs5_2020_2024.b11001.county.group_0", + "period_type": "calendar_year", + "period_value": "2024", + "package_id": "census-acs5-b11001-county-2024", + "package": "packages/census/acs5_b11001_county_2024", + "build_year": 2024 + }, + { + "record_set_id": "census_acs.acs5_2020_2024.b19001.county.group_0", + "period_type": "calendar_year", + "period_value": "2024", + "package_id": "census-acs5-b19001-county-2024", + "package": "packages/census/acs5_b19001_county_2024", + "build_year": 2024 + }, + { + "record_set_id": "census_acs.acs5_2020_2024.b19013.county.group_1", + "period_type": "calendar_year", + "period_value": "2024", + "package_id": "census-acs5-b19013-county-2024", + "package": "packages/census/acs5_b19013_county_2024", + "build_year": 2024 + }, + { + "record_set_id": "census_acs.acs5_2020_2024.b19025.county.group_0", + "period_type": "calendar_year", + "period_value": "2024", + "package_id": "census-acs5-b19025-county-2024", + "package": "packages/census/acs5_b19025_county_2024", + "build_year": 2024 + }, + { + "record_set_id": "census_acs.acs5_2020_2024.b19051.county.group_0", + "period_type": "calendar_year", + "period_value": "2024", + "package_id": "census-acs5-b19051-county-2024", + "package": "packages/census/acs5_b19051_county_2024", + "build_year": 2024 + }, + { + "record_set_id": "census_acs.acs5_2020_2024.b19061.county.group_0", + "period_type": "calendar_year", + "period_value": "2024", + "package_id": "census-acs5-b19061-county-2024", + "package": "packages/census/acs5_b19061_county_2024", + "build_year": 2024 + } + ] +} diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/chronicle_feed.py b/packages/microcosm-build/src/microcosm/build/us_runtime/chronicle_feed.py index 9fdd69426f..044697d9ef 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/chronicle_feed.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/chronicle_feed.py @@ -13,6 +13,14 @@ ``artifact_schema_version`` null) when Chronicle's consumer-artifact validator refuses the feed at the pinned commit; the ``--base-h5`` release arm accepts a bare ``consumer_facts.jsonl``, the ``--exact-k`` arm needs the artifact. + +A second declaration, ``us/chronicle_county_facts.json`` with scope +``us/chronicle_county_facts_scope.json``, pins the county-grain facts that only +the ACS-local county rung reads (microcosm#922). It has the same fields and is +always a bare facts file; :func:`load_us_chronicle_county_facts_pin` loads it +and ``us_runtime.county_facts`` reads the file it names. The two scopes share +no (record set, period) pair, so the main feed, its scope and the parity +resources do not move when the county facts do. """ from __future__ import annotations @@ -31,16 +39,24 @@ from microcosm.build.ledger_artifact import validate_pinned_row_contracts __all__ = [ + "US_CHRONICLE_COUNTY_FACTS_RESOURCE", + "US_CHRONICLE_COUNTY_FACTS_SCOPE_RESOURCE", "US_CHRONICLE_FEED_RESOURCE", "US_CHRONICLE_FEED_SCOPE_RESOURCE", "USChronicleFeed", + "load_us_chronicle_county_facts_pin", "load_us_chronicle_feed", "require_us_chronicle_feed_row_contracts", + "us_chronicle_county_facts_scope_sha256", "us_chronicle_feed_scope_sha256", ] US_CHRONICLE_FEED_RESOURCE = "chronicle_feed.json" US_CHRONICLE_FEED_SCOPE_RESOURCE = "chronicle_feed_scope.json" +US_CHRONICLE_COUNTY_FACTS_RESOURCE = "chronicle_county_facts.json" +US_CHRONICLE_COUNTY_FACTS_SCOPE_RESOURCE = "chronicle_county_facts_scope.json" +_FEED_SUBJECT = "US Chronicle feed" +_COUNTY_FACTS_SUBJECT = "US Chronicle county facts" _HEX = "[0-9a-f]" @@ -116,57 +132,84 @@ def _scope_path(): return files("microcosm.build.us").joinpath(US_CHRONICLE_FEED_SCOPE_RESOURCE) +def _county_facts_path(): + return files("microcosm.build.us").joinpath(US_CHRONICLE_COUNTY_FACTS_RESOURCE) + + +def _county_facts_scope_path(): + return files("microcosm.build.us").joinpath( + US_CHRONICLE_COUNTY_FACTS_SCOPE_RESOURCE + ) + + def us_chronicle_feed_scope_sha256() -> str: """SHA-256 of the packaged scope file the pinned feed was built from.""" return hashlib.sha256(_scope_path().read_bytes()).hexdigest() -def _require_hex(raw: dict, field: str, length: int, *, nullable: bool = False) -> None: +def us_chronicle_county_facts_scope_sha256() -> str: + """SHA-256 of the packaged scope file the pinned county facts were built from.""" + + return hashlib.sha256(_county_facts_scope_path().read_bytes()).hexdigest() + + +def _require_hex( + raw: dict, + field: str, + length: int, + *, + nullable: bool = False, + subject: str = _FEED_SUBJECT, +) -> None: value = raw.get(field) if value is None and nullable: return if not isinstance(value, str) or not re.fullmatch(rf"{_HEX}{{{length}}}", value): raise ValueError( - f"US Chronicle feed {field} must be {length} lowercase hex chars" + f"{subject} {field} must be {length} lowercase hex chars" + (" or null." if nullable else ".") ) -def load_us_chronicle_feed() -> USChronicleFeed: - """Load the packaged US pin without importing Chronicle or an engine.""" - - content = _feed_path().read_bytes() +def _load_pin( + content: bytes, + *, + scope: str, + scope_resource: str, + scope_sha256: str, + subject: str, +) -> USChronicleFeed: raw = json.loads(content) if not isinstance(raw, dict): - raise ValueError("US Chronicle feed must contain a JSON object.") + raise ValueError(f"{subject} must contain a JSON object.") for field, expected in ( ("version", 1), ("country", "us"), - ("scope", "us_fiscal_targets"), + ("scope", scope), ("source_repo", "PolicyEngine/chronicle"), ): if type(raw.get(field)) is not type(expected) or raw[field] != expected: - raise ValueError(f"US Chronicle feed {field} must be {expected!r}.") - _require_hex(raw, "source_commit", 40) - _require_hex(raw, "facts_sha256", 64) - _require_hex(raw, "consumer_fact_schema_sha256", 64) - _require_hex(raw, "scope_sha256", 64) - _require_hex(raw, "manifest_sha256", 64, nullable=True) + raise ValueError(f"{subject} {field} must be {expected!r}.") + _require_hex(raw, "source_commit", 40, subject=subject) + _require_hex(raw, "facts_sha256", 64, subject=subject) + _require_hex(raw, "consumer_fact_schema_sha256", 64, subject=subject) + _require_hex(raw, "scope_sha256", 64, subject=subject) + _require_hex(raw, "manifest_sha256", 64, nullable=True, subject=subject) if type(raw.get("fact_row_count")) is not int or raw["fact_row_count"] <= 0: - raise ValueError("US Chronicle feed fact_row_count must be positive.") + raise ValueError(f"{subject} fact_row_count must be positive.") if not isinstance(raw.get("build"), str) or not raw["build"].strip(): - raise ValueError("US Chronicle feed build must be a nonempty string.") + raise ValueError(f"{subject} build must be a nonempty string.") artifact_schema_version = raw.get("artifact_schema_version") if (raw.get("manifest_sha256") is None) != (artifact_schema_version is None): raise ValueError( - "US Chronicle feed manifest_sha256 and artifact_schema_version must " + f"{subject} manifest_sha256 and artifact_schema_version must " "both be set (artifact feed) or both be null (bare feed)." ) if artifact_schema_version is not None and ( not is_accepted_consumer_artifact_schema_version(artifact_schema_version) ): - raise ValueError("US Chronicle feed artifact_schema_version is unsupported.") + raise ValueError(f"{subject} artifact_schema_version is unsupported.") versions = raw.get("consumer_fact_schema_versions") if ( not isinstance(versions, list) @@ -174,15 +217,12 @@ def load_us_chronicle_feed() -> USChronicleFeed: or any(not isinstance(v, str) or not v for v in versions) or len(set(versions)) != len(versions) ): - raise ValueError("US Chronicle feed consumer_fact_schema_versions is invalid.") - require_accepted_consumer_fact_schema_versions( - versions, subject="US Chronicle feed" - ) - expected_scope_sha256 = us_chronicle_feed_scope_sha256() - if raw["scope_sha256"] != expected_scope_sha256: + raise ValueError(f"{subject} consumer_fact_schema_versions is invalid.") + require_accepted_consumer_fact_schema_versions(versions, subject=subject) + if raw["scope_sha256"] != scope_sha256: raise ValueError( - "US Chronicle feed scope_sha256 does not match the packaged " - f"{US_CHRONICLE_FEED_SCOPE_RESOURCE} ({expected_scope_sha256}); a " + f"{subject} scope_sha256 does not match the packaged " + f"{scope_resource} ({scope_sha256}); a " "changed scope needs a rebuilt feed and a new pin." ) return USChronicleFeed( @@ -190,3 +230,37 @@ def load_us_chronicle_feed() -> USChronicleFeed: resource_sha256=hashlib.sha256(content).hexdigest(), resource_size_bytes=len(content), ) + + +def load_us_chronicle_feed() -> USChronicleFeed: + """Load the packaged US pin without importing Chronicle or an engine.""" + + return _load_pin( + _feed_path().read_bytes(), + scope="us_fiscal_targets", + scope_resource=US_CHRONICLE_FEED_SCOPE_RESOURCE, + scope_sha256=us_chronicle_feed_scope_sha256(), + subject=_FEED_SUBJECT, + ) + + +def load_us_chronicle_county_facts_pin() -> USChronicleFeed: + """Load the packaged county facts pin (microcosm#922). + + Same fields and checks as the main pin, with scope ``us_county_facts``; the + county facts are always a bare facts file, never a consumer artifact. + """ + + pin = _load_pin( + _county_facts_path().read_bytes(), + scope="us_county_facts", + scope_resource=US_CHRONICLE_COUNTY_FACTS_SCOPE_RESOURCE, + scope_sha256=us_chronicle_county_facts_scope_sha256(), + subject=_COUNTY_FACTS_SUBJECT, + ) + if not pin.is_bare_feed: + raise ValueError( + f"{_COUNTY_FACTS_SUBJECT} must pin a bare facts file " + "(manifest_sha256 and artifact_schema_version null)." + ) + return pin diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/county_facts.py b/packages/microcosm-build/src/microcosm/build/us_runtime/county_facts.py new file mode 100644 index 0000000000..1c0ef2f3a1 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/county_facts.py @@ -0,0 +1,187 @@ +"""Pinned county facts for the ACS-local county rung (microcosm#922). + +The county rung needs county-grain Chronicle facts: IRS SOI county returns and +AGI, Census PEP county population, and the ACS 5-year county tables. They live +in their own pinned file, ``us/chronicle_county_facts.json`` with scope +``us/chronicle_county_facts_scope.json``, beside the main US feed pin +(``us/chronicle_feed.json``), because carrying them in the main feed would grow +it 6.5x for every US build while only county builds read them. No fiscal +compile reads this file. + +:func:`load_us_county_facts` reads the file in one pass: it hashes the exact +bytes, parses every line, refuses a row on an unpinned row contract, at any +geography level but ``county`` or outside the scope's (record set, period) +pairs, drops Puerto Rico (state 72, outside the 3,144 county-equivalents the +County Files cover) with a count, and projects each kept row to the fields the +county rung reads. It refuses the file unless its digest and row count are the +pin's. The file on disk keeps Chronicle's own bytes; only the in-memory rows +are projected. +""" + +from __future__ import annotations + +import hashlib +import json +from collections import Counter +from collections.abc import Mapping +from dataclasses import dataclass, field +from importlib.resources import files +from pathlib import Path +from typing import Any + +from microcosm.build.us_runtime.chronicle_feed import ( + US_CHRONICLE_COUNTY_FACTS_SCOPE_RESOURCE, + USChronicleFeed, + load_us_chronicle_county_facts_pin, +) + +__all__ = [ + "COUNTY_FACT_FIELDS", + "DROPPED_STATE_FIPS", + "USCountyFacts", + "load_us_county_facts", + "us_county_facts_scope_pairs", +] + +#: Top-level row fields kept in memory. Everything else (source, lineage, +#: concept alignment, period coverage, labels) stays in the pinned bytes. +COUNTY_FACT_FIELDS = ( + "aggregate_fact_key", + "schema_version", + "geography", + "observed_measure", + "dimensions", + "dimension_value_labels", + "period", + "value", + "value_type", + "entity", + "aggregation", + "universe_constraints", + "layout", +) +#: Puerto Rico municipios: in the ACS county tables, outside the County Files. +DROPPED_STATE_FIPS = frozenset({"72"}) +_COUNTY_GEOID_PREFIX = "0500000US" + +Pair = tuple[str, str, str] + + +@dataclass(frozen=True) +class USCountyFacts: + """The kept, projected county rows and how they were read.""" + + rows: tuple[dict[str, Any], ...] + path: str + facts_sha256: str + row_count: int + dropped: Mapping[str, int] = field(default_factory=dict) + pin: USChronicleFeed | None = None + + def receipt(self) -> dict[str, object]: + return { + "path": self.path, + "facts_sha256": self.facts_sha256, + "row_count": self.row_count, + "kept_rows": len(self.rows), + "dropped": dict(self.dropped), + "pin": None if self.pin is None else self.pin.to_dict(), + } + + +def us_county_facts_scope_pairs() -> frozenset[Pair]: + """The (record set, period type, period value) pairs the county pin keeps.""" + + raw = json.loads( + files("microcosm.build.us") + .joinpath(US_CHRONICLE_COUNTY_FACTS_SCOPE_RESOURCE) + .read_bytes() + ) + return frozenset( + (entry["record_set_id"], entry["period_type"], str(entry["period_value"])) + for entry in raw["pairs"] + ) + + +def _county_state(row: Mapping[str, Any]) -> str: + geography = row.get("geography") + if not isinstance(geography, Mapping) or geography.get("level") != "county": + raise ValueError( + "US county facts must all be county rows; got geography " + f"{geography!r} in {row.get('aggregate_fact_key')!r}." + ) + geoid = str(geography.get("id", "")) + code = geoid[len(_COUNTY_GEOID_PREFIX) :] + if ( + not geoid.startswith(_COUNTY_GEOID_PREFIX) + or len(code) != 5 + or not code.isdigit() + ): + raise ValueError(f"US county facts: invalid county geography id {geoid!r}.") + return code[:2] + + +def _pair(row: Mapping[str, Any]) -> Pair: + period = row.get("period") or {} + layout = row.get("layout") or {} + return ( + str(layout.get("record_set_id", "")), + str(period.get("type", "")), + str(period.get("value", "")), + ) + + +def load_us_county_facts( + path: str | Path, *, pin: USChronicleFeed | None = None +) -> USCountyFacts: + """Read the pinned county facts file once and keep the projected rows.""" + + pin = pin or load_us_chronicle_county_facts_pin() + pairs = us_county_facts_scope_pairs() + contracts = set(pin.consumer_fact_schema_versions) + digest = hashlib.sha256() + rows: list[dict[str, Any]] = [] + dropped: Counter[str] = Counter() + count = 0 + with open(path, "rb") as stream: + for line in stream: + digest.update(line) + if not line.strip(): + continue + count += 1 + row = json.loads(line) + if row.get("schema_version") not in contracts: + raise ValueError( + "US county facts row carries an unpinned row contract " + f"{row.get('schema_version')!r}; the pin declares " + f"{sorted(contracts)}." + ) + pair = _pair(row) + if pair not in pairs: + raise ValueError( + f"US county facts row {row.get('aggregate_fact_key')!r} is " + f"outside the county scope: {pair}." + ) + if _county_state(row) in DROPPED_STATE_FIPS: + dropped[f"state_{_county_state(row)}"] += 1 + continue + rows.append({key: row[key] for key in COUNTY_FACT_FIELDS if key in row}) + facts_sha256 = digest.hexdigest() + if facts_sha256 != pin.facts_sha256: + raise ValueError( + f"US county facts {path} has sha256 {facts_sha256}; the county pin " + f"names {pin.facts_sha256}." + ) + if count != pin.fact_row_count: + raise ValueError( + f"US county facts {path} has {count} rows; the county pin names " + f"{pin.fact_row_count}." + ) + return USCountyFacts( + rows=tuple(rows), + path=str(path), + facts_sha256=facts_sha256, + row_count=count, + dropped=dict(sorted(dropped.items())), + pin=pin, + ) 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 5c6d250965..95021122a7 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 @@ -16,6 +16,9 @@ import pytest from scipy import sparse +from microcosm.build.us_runtime.chronicle_feed import ( + load_us_chronicle_county_facts_pin, +) from microcosm.calibrate import TargetSpec from test_support.paths import paths_for @@ -578,6 +581,7 @@ def test_county_hooks_materialize_a_fixture_and_preserve_configured_geography( ) -> None: """A three-household smoke exercises real sparse checkpoints, without an engine.""" from microcosm.build import ledger_artifact + from microcosm.build.us_runtime import county_facts as county_facts_module from microcosm.calibrate import TargetRegistry from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights @@ -609,12 +613,14 @@ def test_county_hooks_materialize_a_fixture_and_preserve_configured_geography( US_SCHEMA, {"household": Weights(np.asarray([10.0, 20.0, 30.0]), WeightKind.DESIGN)}, ) - staging, feed, ladder = ( - tmp_path / name for name in ("staging.h5", "feed.json", "ladder.npz") + staging, feed, ladder, county_facts_file = ( + tmp_path / name + for name in ("staging.h5", "feed.json", "ladder.npz", "county_facts.jsonl") ) - for path in (staging, feed, ladder): + for path in (staging, feed, ladder, county_facts_file): path.write_bytes(b"fixture") staging.with_suffix(".summary.json").write_text("{}") + county_pin = load_us_chronicle_county_facts_pin() args = module._parse_args( [ "--stage", @@ -623,6 +629,12 @@ def test_county_hooks_materialize_a_fixture_and_preserve_configured_geography( str(staging), "--feed", str(feed), + "--feed-sha256", + hashlib.sha256(b"fixture").hexdigest(), + "--county-facts", + str(county_facts_file), + "--county-facts-sha256", + county_pin.facts_sha256, "--ladder", str(ladder), "--checkpoint-dir", @@ -708,20 +720,37 @@ def fake_materialize(current, specs, **_kwargs): return materialized monkeypatch.setattr(module, "materialize_chunked", fake_materialize) - monkeypatch.setattr( - ledger_artifact, - "load_ledger_consumer_artifact", - lambda *_a: SimpleNamespace( - facts=[ + county_reads = [] + + def fake_county_facts(path, **_kwargs): + county_reads.append(path) + return SimpleNamespace( + rows=tuple( _fact(code, measure, value) for measure in ("return_count", "adjusted_gross_income") for code, value in (("01001", 1.0), ("01003", 3.0)) - ] - ), + ), + receipt=lambda: { + "path": str(path), + "facts_sha256": county_pin.facts_sha256, + "row_count": 4, + }, + ) + + def feed_is_not_county_facts(*_args, **_kwargs): + raise AssertionError("county facts must not be read from --feed") + + monkeypatch.setattr(county_facts_module, "load_us_county_facts", fake_county_facts) + monkeypatch.setattr( + ledger_artifact, "load_ledger_consumer_artifact", feed_is_not_county_facts ) module.do_materialize(args) assert seen == parents + # Read once, from the resolved --county-facts path, by prepare_run alone. + assert county_reads == [county_facts_file.resolve()] identity = json.loads((args.checkpoint_dir / "run_identity.json").read_text()) + assert identity["county_facts"]["facts_sha256"] == county_pin.facts_sha256 + assert identity["county_facts"]["path"] == str(county_facts_file.resolve()) loaded, design, registry, records, matrix = module.load_checkpoint_surface( args.checkpoint_dir, identity ) @@ -886,6 +915,10 @@ def test_county_refresh_recipe_round_trips_custom_geography_and_salt() -> None: "geographies": " state, county ", "county_column": "planning_region", "county_holdout": {"fraction": 0.0, "salt": "LWI's county | $(literal)"}, + "county_facts": { + "path": "/data/LWI county facts.jsonl", + "facts_sha256": load_us_chronicle_county_facts_pin().facts_sha256, + }, } recipe = _county().refresh_recipe( module.release_refresh_recipe("state_county"), metadata @@ -898,3 +931,129 @@ def test_county_refresh_recipe_round_trips_custom_geography_and_salt() -> None: assert parsed.county_column == "planning_region" assert parsed.county_holdout_fraction == 0.0 assert parsed.county_holdout_salt == metadata["county_holdout"]["salt"] + assert str(parsed.county_facts) == metadata["county_facts"]["path"] + assert parsed.county_facts_sha256 == metadata["county_facts"]["facts_sha256"] + + +# --- the county facts flags (microcosm#922) ---------------------------------- + + +def _county_argv(tmp_path, *extra, soi_mode="state_county", feed_sha=True): + for name in ("staging.h5", "feed.jsonl", "ladder.npz", "county.jsonl"): + (tmp_path / name).write_bytes(b"fixture") + argv = [ + "--stage", + "materialize", + "--staging-h5", + str(tmp_path / "staging.h5"), + "--feed", + str(tmp_path / "feed.jsonl"), + "--ladder", + str(tmp_path / "ladder.npz"), + "--checkpoint-dir", + str(tmp_path / "checkpoint"), + "--families", + "soi", + "--soi-mode", + soi_mode, + "--geographies", + "state,county", + ] + if feed_sha: + argv += ["--feed-sha256", hashlib.sha256(b"fixture").hexdigest()] + return argv + list(extra) + + +def _pinned_sha(): + return load_us_chronicle_county_facts_pin().facts_sha256 + + +@pytest.mark.parametrize( + ("extra", "options", "message"), + [ + ((), {}, "needs --county-facts and --county-facts-sha256"), + (("--county-facts", "{county}"), {}, "needs --county-facts-sha256"), + ( + ("--county-facts", "{county}", "--county-facts-sha256", "0" * 64), + {}, + "is not the county pin's facts_sha256", + ), + ( + ("--county-facts", "{county}", "--county-facts-sha256", "{pinned}"), + {"feed_sha": False}, + "needs --feed-sha256", + ), + ( + ("--county-facts", "{feed}", "--county-facts-sha256", "{pinned}"), + {}, + "must not be the --feed file", + ), + ( + ("--county-facts", "{county}", "--county-facts-sha256", "{pinned}"), + {"soi_mode": "state"}, + "needs --soi-mode state_county", + ), + ( + ("--county-facts-sha256", "{pinned}"), + {"soi_mode": "state"}, + "--county-facts-sha256 needs --county-facts", + ), + ], + ids=[ + "state-county-without-facts", + "facts-without-sha", + "sha-not-the-pin", + "no-feed-sha", + "facts-are-the-feed", + "facts-outside-state-county", + "sha-without-facts", + ], +) +def test_the_county_facts_flags_refuse_an_unpinned_or_ambiguous_run( + tmp_path, capsys, extra, options, message +) -> None: + fill = { + "county": str(tmp_path / "county.jsonl"), + "feed": str(tmp_path / "feed.jsonl"), + "pinned": _pinned_sha(), + } + argv = _county_argv(tmp_path, *(item.format(**fill) for item in extra), **options) + with pytest.raises(SystemExit): + _release()._parse_args(argv) + assert message in capsys.readouterr().err + + +def test_a_pinned_county_facts_run_parses(tmp_path) -> None: + args = _release()._parse_args( + _county_argv( + tmp_path, + "--county-facts", + str(tmp_path / "county.jsonl"), + "--county-facts-sha256", + _pinned_sha(), + ) + ) + assert args.county_facts == tmp_path / "county.jsonl" + assert args.county_facts_sha256 == _pinned_sha() + + +def test_a_county_facts_file_off_the_pin_is_refused_before_any_target( + tmp_path, +) -> None: + facts = tmp_path / "county.jsonl" + facts.write_bytes(b"{}\n") + args = SimpleNamespace( + soi_mode="state_county", + families="soi", + sample_fraction=0.01, + checkpoint_dir=tmp_path / "checkpoint", + county_facts=facts, + ) + surface = SimpleNamespace(registry=SimpleNamespace(specs=())) + with pytest.raises(SystemExit): + _county().prepare_run( + args, ["state", "county"], {"county": {1001: 10.0}}, surface=surface + ) + report = json.loads((args.checkpoint_dir / "county_surface.json").read_text()) + assert report["status"] == "refused" + assert not hasattr(surface, "county_surface") diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_chronicle_county_facts.py b/packages/microcosm-build/tests/engine_free/us/test_us_chronicle_county_facts.py new file mode 100644 index 0000000000..17580f2f47 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_chronicle_county_facts.py @@ -0,0 +1,208 @@ +"""The US county facts pin and its loader (microcosm#922). + +The county facts sit in their own pin beside the main US feed pin, so the main +feed, its scope and the parity resources do not move when county facts do. +""" + +from __future__ import annotations + +import dataclasses +import hashlib +import importlib.util +import json +from pathlib import Path + +import pytest +from hypothesis import given, settings +from hypothesis import strategies as st + +from microcosm.build.us_runtime.chronicle_feed import ( + US_CHRONICLE_COUNTY_FACTS_SCOPE_RESOURCE, + US_CHRONICLE_FEED_SCOPE_RESOURCE, + load_us_chronicle_county_facts_pin, + load_us_chronicle_feed, + us_chronicle_county_facts_scope_sha256, +) +from microcosm.build.us_runtime.county_facts import ( + COUNTY_FACT_FIELDS, + load_us_county_facts, + us_county_facts_scope_pairs, +) + +_REPOSITORY_ROOT = Path(__file__).resolve().parents[5] +_US_PACKAGE = _REPOSITORY_ROOT / "packages/microcosm-build/src/microcosm/build/us" + + +def _builder(): + path = _REPOSITORY_ROOT / "tools" / "build_us_chronicle_feed.py" + spec = importlib.util.spec_from_file_location("build_us_chronicle_feed", path) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module + + +# --- the packaged pin and scope --------------------------------------------- + + +def test_the_county_pin_loads_and_names_its_scope() -> None: + pin = load_us_chronicle_county_facts_pin() + assert pin.scope == "us_county_facts" + assert pin.scope_sha256 == us_chronicle_county_facts_scope_sha256() + assert pin.is_bare_feed + + +def test_the_county_pin_is_not_the_main_pin() -> None: + county = load_us_chronicle_county_facts_pin() + main = load_us_chronicle_feed() + assert county.facts_sha256 != main.facts_sha256 + assert county.scope_sha256 != main.scope_sha256 + + +def test_the_feed_builder_accepts_the_county_scope() -> None: + scope = _builder().load_scope( + _US_PACKAGE / US_CHRONICLE_COUNTY_FACTS_SCOPE_RESOURCE + ) + pin = load_us_chronicle_county_facts_pin() + assert scope["commit"] == pin.source_commit + assert len(scope["pairs"]) == scope["raw"]["pair_count"] + + +def test_county_and_main_scopes_share_no_pair() -> None: + builder = _builder() + county = builder.load_scope(_US_PACKAGE / US_CHRONICLE_COUNTY_FACTS_SCOPE_RESOURCE) + main = builder.load_scope(_US_PACKAGE / US_CHRONICLE_FEED_SCOPE_RESOURCE) + assert set(county["pairs"]).isdisjoint(main["pairs"]) + + +def test_the_loader_reads_the_county_scope_pairs() -> None: + builder = _builder() + county = builder.load_scope(_US_PACKAGE / US_CHRONICLE_COUNTY_FACTS_SCOPE_RESOURCE) + assert us_county_facts_scope_pairs() == frozenset(county["pairs"]) + + +# --- the loader -------------------------------------------------------------- + +_PAIRS = sorted(us_county_facts_scope_pairs()) + + +def _row(index: int, *, state: str = "01", pair=None, level="county", contract=None): + record_set_id, period_type, period_value = pair or _PAIRS[index % len(_PAIRS)] + return { + "aggregate_fact_key": f"key-{index:06d}", + "schema_version": contract or "chronicle.consumer_fact.v5", + "geography": { + "id": f"0500000US{state}{index % 1000:03d}", + "level": level, + "name": f"County {index}", + "vintage": "2024", + }, + "observed_measure": { + "source_name": "census_acs", + "source_measure_id": "X_001E", + "unit": "count", + }, + "dimensions": {"statistic": "estimate"}, + "period": {"type": period_type, "value": int(period_value)}, + "value": index, + "layout": {"record_set_id": record_set_id, "record_set_spec_id": "spec"}, + "lineage": {"heavy": "x" * 50}, + "source": {"heavy": "y" * 50}, + } + + +def _write(path: Path, rows, *, separators=(",", ":")) -> bytes: + payload = b"".join( + json.dumps(row, separators=separators, sort_keys=True).encode() + b"\n" + for row in rows + ) + path.write_bytes(payload) + return payload + + +def _pin_for(payload: bytes, rows: int): + pin = load_us_chronicle_county_facts_pin() + return dataclasses.replace( + pin, + facts_sha256=hashlib.sha256(payload).hexdigest(), + fact_row_count=rows, + consumer_fact_schema_versions=("chronicle.consumer_fact.v5",), + ) + + +_STATES = st.sampled_from(["01", "06", "09", "15", "48", "72"]) + + +@settings(max_examples=40, deadline=None) +@given( + states=st.lists(_STATES, min_size=1, max_size=30), + spaced=st.booleans(), +) +def test_the_loader_keeps_projected_mainland_rows_and_counts_puerto_rico( + tmp_path_factory, states, spaced +) -> None: + path = tmp_path_factory.mktemp("cf") / "facts.jsonl" + rows = [_row(i, state=s) for i, s in enumerate(states)] + payload = _write(path, rows, separators=(", ", ": ") if spaced else (",", ":")) + facts = load_us_county_facts(path, pin=_pin_for(payload, len(rows))) + expected = [r for r in rows if r["geography"]["id"][9:11] != "72"] + assert [r["aggregate_fact_key"] for r in facts.rows] == [ + r["aggregate_fact_key"] for r in expected + ] + assert all(set(r) == set(COUNTY_FACT_FIELDS) & set(rows[0]) for r in facts.rows) + assert all("lineage" not in r and "source" not in r for r in facts.rows) + assert facts.dropped == ( + {"state_72": len(rows) - len(expected)} if len(rows) != len(expected) else {} + ) + assert facts.facts_sha256 == hashlib.sha256(payload).hexdigest() + assert facts.row_count == len(rows) + + +@settings(max_examples=40, deadline=None) +@given( + count=st.integers(min_value=1, max_value=20), + data=st.data(), +) +def test_any_one_byte_change_is_refused(tmp_path_factory, count, data) -> None: + path = tmp_path_factory.mktemp("cf") / "facts.jsonl" + rows = [_row(i) for i in range(count)] + payload = _write(path, rows) + pin = _pin_for(payload, count) + position = data.draw(st.integers(min_value=0, max_value=len(payload) - 1)) + mutated = bytearray(payload) + # A digit for a digit keeps the line valid JSON, so the digest must refuse it. + mutated[position] = ord("7") if mutated[position] != ord("7") else ord("3") + path.write_bytes(bytes(mutated)) + with pytest.raises(ValueError): + load_us_county_facts(path, pin=pin) + + +@pytest.mark.parametrize( + ("bad", "match"), + [ + (lambda: _row(9, level="state"), "county rows"), + ( + lambda: _row(9, pair=("census_acs.not_in_scope", "calendar_year", "2024")), + "outside the county scope", + ), + ( + lambda: _row(9, contract="chronicle.consumer_fact.v3"), + "unpinned row contract", + ), + ], + ids=["non-county", "out-of-scope", "unpinned-contract"], +) +def test_a_bad_row_between_good_ones_is_refused(tmp_path, bad, match) -> None: + rows = [_row(0), bad(), _row(1)] + path = tmp_path / "facts.jsonl" + payload = _write(path, rows) + with pytest.raises(ValueError, match=match): + load_us_county_facts(path, pin=_pin_for(payload, len(rows))) + + +def test_a_row_count_other_than_the_pins_is_refused(tmp_path) -> None: + rows = [_row(0), _row(1)] + path = tmp_path / "facts.jsonl" + payload = _write(path, rows) + with pytest.raises(ValueError, match="rows; the county pin names 3"): + load_us_county_facts(path, pin=_pin_for(payload, 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 bb7b2c2190..adb3f593b0 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 @@ -312,6 +312,11 @@ "congressional_district_geography.py", "congressional_district_vintage.py", "congressional_district_vintage_crosswalk.py", + # Pinned county facts loader for the ACS-local county rung + # (microcosm#922): hashes, checks and projects Chronicle rows; assigns + # no households and applies no population treatment. Remains subject + # to the all-runtime source-identity scan. + "county_facts.py", # 2020 tract/county -> 2023 county-equivalent metadata and its gate; # writes calibration geography only, no population treatment. "county_vintage.py", diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index 5cfbae5a76..5f32931a6a 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -4,6 +4,11 @@ the stored state CSR row, including its return universe and engine values. Population, splitting, holdout and reliability helpers also accept future ACS county families. See docs/us-acs-local-county-rung.md for the input contract. + +County facts come from their own pinned file (``--county-facts``, pinned by +``us/chronicle_county_facts.json``, microcosm#922), never from ``--feed``: +:func:`prepare_run` loads it once and every county step reads +``surface.county_facts.rows``. """ from __future__ import annotations @@ -714,6 +719,69 @@ def add_arguments(parser): "--county-holdout-fraction", type=float, default=DEFAULT_COUNTY_HOLDOUT_FRACTION ) parser.add_argument("--county-holdout-salt", default=COUNTY_HOLDOUT_SALT) + parser.add_argument( + "--county-facts", + type=Path, + help=( + "The pinned US county facts file (us/chronicle_county_facts.json, " + "microcosm#922). Required by a --soi-mode state_county materialize." + ), + ) + parser.add_argument( + "--county-facts-sha256", + help="SHA-256 of --county-facts; must be the county pin's facts_sha256.", + ) + + +def _validate_county_facts(args, parser, geographies): + county_facts = getattr(args, "county_facts", None) + sha256 = getattr(args, "county_facts_sha256", None) + if county_facts is None: + if args.soi_mode == SOI_MODE and "materialize" in getattr( + args, "stages", ["materialize"] + ): + parser.error( + "--soi-mode state_county needs --county-facts and " + "--county-facts-sha256 (the pinned US county facts, microcosm#922)." + ) + if sha256 is not None: + parser.error("--county-facts-sha256 needs --county-facts.") + return + if args.soi_mode != SOI_MODE or "county" not in geographies: + parser.error( + "--county-facts needs --soi-mode state_county and county in --geographies." + ) + if sha256 is None: + parser.error("--county-facts needs --county-facts-sha256.") + from microcosm.build.us_runtime.chronicle_feed import ( + load_us_chronicle_county_facts_pin, + ) + + pinned = load_us_chronicle_county_facts_pin().facts_sha256 + if sha256 != pinned: + parser.error( + f"--county-facts-sha256 {sha256} is not the county pin's " + f"facts_sha256 {pinned}." + ) + if not getattr(args, "feed_sha256", None): + parser.error("--county-facts needs --feed-sha256 for the main feed.") + feed = getattr(args, "feed", None) + if feed is not None and (feed_path(feed).resolve() == Path(county_facts).resolve()): + parser.error("--county-facts must not be the --feed file.") + + +def _load_county_facts(args): + """Read the pinned county facts once and record their receipt on args.""" + + from microcosm.build.us_runtime.county_facts import load_us_county_facts + + if getattr(args, "county_facts", None) is None: + raise ValueError( + "--soi-mode state_county needs --county-facts (microcosm#922)." + ) + facts = load_us_county_facts(Path(args.county_facts).resolve()) + args.county_facts_receipt = facts.receipt() + return facts def validate_arguments(args, parser): @@ -732,6 +800,7 @@ def validate_arguments(args, parser): parser.error("--county-column must be a household column name.") if not args.county_holdout_salt: parser.error("--county-holdout-salt must be a non-empty string.") + _validate_county_facts(args, parser, geographies) def prepare_run(args, geographies, populations, *, surface=None): @@ -755,13 +824,13 @@ def prepare_run(args, geographies, populations, *, surface=None): }: raise SystemExit("--soi-mode state_county requires soi in --families.") if args.soi_mode == SOI_MODE and surface is not None: - from microcosm.build.ledger_artifact import load_ledger_consumer_artifact - - artifact = load_ledger_consumer_artifact(str(args.feed)) args.checkpoint_dir.mkdir(parents=True, exist_ok=True) try: + surface.county_facts = _load_county_facts(args) surface.county_surface = state_county_soi_surface( - surface.registry.specs, artifact.facts, populations["county"] + surface.registry.specs, + surface.county_facts.rows, + populations["county"], ) except ValueError as error: (args.checkpoint_dir / "county_surface.json").write_text( @@ -802,11 +871,9 @@ def attach_surface(surface, materialized, frame, populations, args): return materialized.compiled_specs, materialized.matrix county = getattr(surface, "county_surface", None) if county is None: - from microcosm.build.ledger_artifact import load_ledger_consumer_artifact - - artifact = load_ledger_consumer_artifact(str(args.feed)) + facts = getattr(surface, "county_facts", None) or _load_county_facts(args) county = state_county_soi_surface( - materialized.compiled_specs, artifact.facts, populations["county"] + materialized.compiled_specs, facts.rows, populations["county"] ) matrix = split_state_rows( materialized.compiled_specs, @@ -859,7 +926,7 @@ def assign_roles(roles, args): def run_metadata(args, county_holdout): - return { + metadata = { "geographies": ",".join( item.strip() for item in args.geographies.split(",") if item.strip() ), @@ -867,6 +934,12 @@ def run_metadata(args, county_holdout): "county_holdout": county_holdout, "county_targets_dropped": getattr(args, "county_targets_dropped", []), } + # Only a run that read county facts records them, so a no-county run + # identity keeps its pre-county bytes. + receipt = getattr(args, "county_facts_receipt", None) + if receipt is not None: + metadata["county_facts"] = receipt + return metadata def struct_columns(households, existing_columns, *, county_column=COUNTY_COLUMN): @@ -985,12 +1058,19 @@ def refresh_recipe(command, materialize_rss): }: return command holdout = materialize_rss["county_holdout"] - return ( + command = ( command + f" --geographies {shlex.quote(materialize_rss['geographies'])}" f" --county-column {shlex.quote(materialize_rss.get('county_column', COUNTY_COLUMN))}" f" --county-holdout-fraction {float(holdout['fraction'])!r}" f" --county-holdout-salt {shlex.quote(holdout['salt'])}" ) + facts = materialize_rss.get("county_facts") + if facts: + command += ( + f" --county-facts {shlex.quote(str(facts['path']))}" + f" --county-facts-sha256 {facts['facts_sha256']}" + ) + return command def _is_county(spec): From d2e2767f3843e58bf02f123d21d45a5423f4dff8 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 13 Nov 2026 20:29:25 -0500 Subject: [PATCH 2/6] Fix the county facts pin review findings (microcosm#922) Declare the county pin and its scope as legacy resources in tools/generate_us_bundle_from_constants.py and regenerate us/country_package.json, so load_country_spec('us') and the spec-engine load_bundle('us') load again (test_country_spec failed at 0a6f201b), and repin the US spec-engine contracts for the new manifest bytes. Loader: hash the file and check its digest and row count before parsing any row, so a wrong file is named as such; hash again while parsing and refuse a file that changed between the passes; refuse a row that is not a JSON object and a county code with non-ASCII digits; keep fewer fields per row (the pinned file's kept rows take about 0.9 GB instead of about 1.5 GB, loaded in about 5 s). County rung: record a county facts file that cannot be read in county_surface.json like any other refusal; the refresh recipe names a placeholder county facts file and the pinned digest, never the build machine's path; the error for missing SOI county rows names the county facts pin. Tests: lock the pin's literals; refuse a pin naming a consumer artifact and malformed pins; match the digest refusal; non-object rows, non-ASCII digits, the real receipt and a mid-read change; the projected rows give the same SOI surface as full rows; an off-pin county file and a missing one are refused before any target; a run without county geography is refused; a run without county facts adds no metadata key. Docs: correct the per-table county counts (B19013 has 3,143; B01003 reaches 3,144 across two record sets), the size figures (5.2 KB per ACS row, a 171.7 MB main feed, 6.4x), the feed build command (--chronicle-command), the c32c0b0 comparison key and its status, the raw SOI county sums against their state parents (AGI up to 5% short), what --feed-sha256 checks, and that county materialize runs are local; the agent guide no longer describes a county-inclusive main feed. Co-Authored-By: Claude Opus 5.5 --- changelog.d/922-us-county-facts-pin.added.md | 2 +- docs/agent-guide.md | 7 +- docs/evidence/spec-engine/us-f0-coverage.json | 20 +-- docs/us-acs-local-county-rung.md | 54 +++++--- docs/us-chronicle-feed-repin.md | 64 ++++++---- .../build/spec_engine/field_usage.py | 8 +- .../microcosm/build/us/country_package.json | 10 ++ .../build/us_runtime/county_facts.py | 80 +++++++----- .../us/test_spec_engine_coverage_tool.py | 10 +- .../shared/test_spec_engine_field_usage.py | 10 +- .../us/test_us_acs_local_county_surface.py | 104 +++++++++++++++- .../us/test_us_chronicle_county_facts.py | 117 +++++++++++++++++- .../us/test_us_multispine_pool_tool.py | 4 +- tools/generate_us_bundle_from_constants.py | 4 + tools/spec_engine_coverage.py | 2 +- tools/us_acs_local_county_surface.py | 13 +- 16 files changed, 397 insertions(+), 112 deletions(-) diff --git a/changelog.d/922-us-county-facts-pin.added.md b/changelog.d/922-us-county-facts-pin.added.md index 21a8bde4c7..61b40fd579 100644 --- a/changelog.d/922-us-county-facts-pin.added.md +++ b/changelog.d/922-us-county-facts-pin.added.md @@ -1 +1 @@ -Pin the US county facts (IRS SOI county, Census PEP county and seven ACS 5-year county tables) as their own Chronicle file beside the main US feed, and make the ACS-local county rung read them through `--county-facts` and `--county-facts-sha256` instead of `--feed`. +Pin the US county facts (IRS SOI county, Census PEP county and seven ACS 5-year county tables) as their own Chronicle file beside the main US feed, and make the ACS-local county rung read them through `--county-facts` and `--county-facts-sha256` instead of `--feed`. The US country package declares the two new pin files, which moves the US bundle's `spec_sha256`. diff --git a/docs/agent-guide.md b/docs/agent-guide.md index b9ba37ec42..2fb2ae7d21 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -575,8 +575,11 @@ The ACS local-area release can build its fresh staging H5 on Modal with `us-acs-multispine-staging`, then consume its verified H5 and summary through `us-acs-local-release`; see [the Modal stage runbook](us-modal-stage-runbook.md#acs-multispine-staging). Its optional [county calibration rung](us-acs-local-county-rung.md) uses -`--geographies state,cd,county --soi-mode state_county`, a county-inclusive -Ledger feed, and matching county boundaries. Full runs require all 3,144 +`--geographies state,cd,county --soi-mode state_county`, the separately +pinned county facts (`--county-facts` and `--county-facts-sha256`; +`us/chronicle_county_facts.json`, microcosm#922) beside the main feed, and +matching county boundaries. County materialize runs are local: the Modal stage +runner cannot pass `--county-facts`. Full runs require all 3,144 county-equivalents and write `county_reliability.json`; the base year is 2024. County solves use a run-level loss cap of 10 and a per-record weight cap of 5, configurable with `--county-target-loss-cap` and `--county-max-weight-ratio` diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index 41a33cb193..c2e175d0c7 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": 32609, + "authored_normative_field_count": 32615, "claim_count": 48, "claims": [ { @@ -16,8 +16,8 @@ "legacy_sinks": [], "mode": "front_end_validation", "pointer_class": "all", - "pointer_count": 104, - "pointer_sha256": "8a186065f5b8ffc59bc3f62fe927975e6f36bc1e913aa61761652c9a8aa67988", + "pointer_count": 110, + "pointer_sha256": "368fe74c5a1ac00cc51079ffc1e13add27471d6daeaf2bf362cb321be9535619", "rationale": null, "relative_sink_prefix": null, "source_prefix": "/authored/country_package.json", @@ -758,20 +758,20 @@ "verifier": "vintages" } ], - "configuration_field_count": 42394, - "consumed_field_count": 42394, + "configuration_field_count": 42400, + "consumed_field_count": 42400, "generation0_effect_counts": { "legacy_behavior": 38780, - "no_generation0_effect": 3614 + "no_generation0_effect": 3620 }, "mode_counts": { "compiler_semantic": 27673, - "front_end_validation": 349, + "front_end_validation": 355, "identity_only": 103, "legacy_behavior": 14269 }, "multiple_primary_use_field_count": 0, - "pointer_inventory_sha256": "f6832e8d2892af22e41afd0b0bea0cba354bbff8b84bebcc652e765a3ae7df92", + "pointer_inventory_sha256": "df98ac3762e95e3e20b83fb897b6947787f5939d9d5c631df9c1e06deb31ef56", "resolved_binding_field_count": 9785, "unused_field_count": 0 }, @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "98d583653d37fe58edcace1cf3e21a139b69ebe7d1c3dac6a58f08b2b5aab8cf" + "spec_sha256": "fdf6e8f4e81a5b24b43c2665413b4f5a04e38ab8e35e781b232939835df79ed4" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "98d583653d37fe58edcace1cf3e21a139b69ebe7d1c3dac6a58f08b2b5aab8cf" + "spec_sha256": "fdf6e8f4e81a5b24b43c2665413b4f5a04e38ab8e35e781b232939835df79ed4" }, "status": "pass" } diff --git a/docs/us-acs-local-county-rung.md b/docs/us-acs-local-county-rung.md index 451e52e254..aa787f3172 100644 --- a/docs/us-acs-local-county-rung.md +++ b/docs/us-acs-local-county-rung.md @@ -143,27 +143,40 @@ say why the county facts are a separate file. A `--soi-mode state_county` materialize must pass `--county-facts --county-facts-sha256 ` -and `--feed-sha256` for the main feed. The parser refuses a county facts digest +and `--feed-sha256`. `--feed-sha256` is the operator's digest of the `--feed` +file: materialize refuses a `--feed` file that does not match it, but nothing +binds it to the main pin, because local runs also use other feeds. The parser refuses a county facts digest other than the pin's, county facts without county geography or `--soi-mode state_county`, and a county facts path that is the `--feed` file. -`prepare_run` reads the file once with -`microcosm.build.us_runtime.county_facts.load_us_county_facts`, which checks -the digest, the row count, the row contract, the county level and the scope of -every row, and drops the 78 Puerto Rico municipios (4,136 ACS rows) with a -count. Loading the pinned file took 42 s and 2.5 GB of memory on the build -machine; the rows stay in memory for the rest of the materialize stage. Every later -county step reads those rows; nothing re-reads `--feed` for county facts. The +`prepare_run` loads the file with +`microcosm.build.us_runtime.county_facts.load_us_county_facts`. The loader +first hashes the file and refuses it unless its digest and row count are the +pin's. A second pass hashes it again and parses it. That pass refuses a row +that is not a JSON object, is on another row contract, is not a county row or +is outside the scope, and refuses a file whose bytes changed between the +passes. It drops the 78 Puerto Rico municipios (4,136 ACS rows) with a count +and keeps only the fields county targets read. A refusal, or a file that +cannot be read, is recorded in `county_surface.json` before any target is +built. On the build machine the loader reads the pinned file in about 5 s and +holds about 0.9 GB of rows, measured apart from importing the US runtime. The +rows stay on the surface for the rest of the materialize stage; today only the +SOI county split reads them, in `prepare_run`. Nothing re-reads `--feed` or the +county facts file. The run identity and `materialize_rss.json` record the county facts receipt under -`county_facts`, and the refresh recipe carries both flags. A run without county +`county_facts`. The refresh recipe carries both flags; like `--feed`, it +names a placeholder file (``) and the pinned digest, never +the build machine's path. A run without county facts records nothing new, so its run identity keeps its pre-county bytes. The inspected Chronicle publisher inputs have two concrete blockers: -- **Kalawao:** the SOI CSV has 3,143 counties and omits `15005` Kalawao County; - the PEP and ACS tables carry all 3,144. The IRS 2022 county users guide - (`22incydocguide.docx`) says items with fewer than 20 returns for a county - were excluded, so Kalawao's SOI value is missing, not zero, and the IRS does - not fold it into Maui. Until the rung declares a reviewed treatment (a +- **Kalawao:** the SOI CSV has 3,143 counties and omits `15005` Kalawao County. + PEP and five ACS tables carry all 3,144. B19013 has 3,143 (it has no De Baca + County, `35011`), and B01003 reaches 3,144 only across its two record sets. + The IRS 2022 county users guide (`22incydocguide.docx`) says items with fewer + than 20 returns for a county were excluded, so Kalawao's SOI value is + missing, not zero. The guide does not say whether Kalawao's returns are + counted in another county's row. Until the rung declares a reviewed treatment (a combined SOI cell {15005, 15009}, planned on `lwi-county-rung-production`), a complete county SOI block still fails with that county named. - **Connecticut:** both packages use the nine planning-region codes `09110` @@ -175,7 +188,7 @@ The inspected Chronicle publisher inputs have two concrete blockers: SOI facts carry `geography.level = "county"` and Census-style IDs such as `0500000US01001`; the row geography is authoritative even though the record set itself groups all counties. SOI geography metadata says vintage `2022`, -PEP says `2024`; actual county-code inventories must agree across feed, +PEP says `2024`; actual county-code inventories must agree across the county facts, ladder, and households. The audited raw publisher artifact hashes are `2c04ff235bcbacb990b316bf79c7c628089a9a4c1dd9593ac51f74a109b13343` for `22incyallnoagi.csv` and @@ -211,8 +224,12 @@ engine/frame dominate the total. Historical full materialization peaked at not a county-build benchmark. The implementation does not allocate a dense households-by-county-target matrix. -Once the input blockers are resolved, set these paths and the new reviewed -feed hash in the execution environment. This example uses the planning-region +County materialize runs are local. The Modal stage plan +(`tools/modal_us_stage_plan.py`) has no way to pass `--county-facts`, so its +preflight refuses a `state_county` materialize before any compute. + +Once the input blockers are resolved, set these paths and the two pinned +digests in the execution environment. This example uses the planning-region column; use `county_fips` only with a feed and ladder matching that column. The following is documentation only and has not been executed: @@ -296,7 +313,8 @@ installed, after the requested US setup completed: - Existing release, sparse district, district property, geography-label, and loss-weight suites: **125 passed, 2 skipped**, using `-n 2 --dist loadfile`. The skips are optional checks requiring an explicitly configured pinned - Chronicle feed; the actual feed inventory was audited separately above. + Chronicle feed. This record predates the county facts pin; the county + inventory is in the county facts section above. - `uv run ruff check .`: clean. - `uv run --no-sync python tools/ci_test_plan.py verify`: clean, 772 test files in registered directories. diff --git a/docs/us-chronicle-feed-repin.md b/docs/us-chronicle-feed-repin.md index d55816eab1..786d9efa73 100644 --- a/docs/us-chronicle-feed-repin.md +++ b/docs/us-chronicle-feed-repin.md @@ -25,14 +25,16 @@ the main pin. No fiscal compile reads them, and the main feed, its scope and the target-parity resources do not move when they do. They are separate because of size. The ACS county rows keep both estimate and -margin-of-error rows in one record set, about 4.9 KB per row, and the eight -record sets come to 170,896 rows and 886 MB. In the main feed they would have -grown it from 169 MB to about 1.1 GB (6.5x), raising every compile site's peak -from 2.8 GB to 6.7 GB and keeping about 3.2 GB more resident in every -fiscal-refresh run, while only county builds read them. A main-feed rebuild -with them also passed the build machine's 3.5 GB folder cap. The measurements -are in `~/reviews/lwi-county-build-2026-11-13/runs/feed-design-1113/` on the -build machine. +margin-of-error rows in one record set, about 5.2 KB per row, and the eight +ACS record sets come to 170,896 rows and 886 MB. The whole county file is +922 MB; the main feed at `41b2fb2` is 171.7 MB. Folding the county facts into +the main feed would grow it to about 1.09 GB (6.4x; 6.2x for the ACS rows +alone). Measured at the compile and parse sites, that would raise a compile's +peak memory from 2.8 GB to 6.7 GB and keep about 3.2 GB more resident in every +fiscal-refresh run, which holds the parsed feed for its whole length, while +only county builds read the rows. A main-feed rebuild with them also +passed the build machine's 3.5 GB folder cap. These were measured on the build +machine on 2026-11-13; the run notes are not in this repository. - **Commit.** Chronicle main `3e9d3a0694e8ca7e31ed5319c3ceb1bde92b12e0` (merged 2026-11-12), which carries every county package. It is on main, so @@ -47,23 +49,38 @@ build machine. - **Build.** The same builder with the county scope: ```bash - uv run python tools/build_us_chronicle_feed.py --scope packages/microcosm-build/src/microcosm/build/us/chronicle_county_facts_scope.json --chronicle-root --out --skip-artifact + uv run python tools/build_us_chronicle_feed.py --scope packages/microcosm-build/src/microcosm/build/us/chronicle_county_facts_scope.json --chronicle-root --chronicle-command "uv run --frozen --python 3.13 chronicle" --out --skip-artifact ``` + `--python 3.13` matters on a fresh checkout: without it, `uv` can pick a + newer Python for which Chronicle's locked wheels do not exist. A rebuild + that differs from the pin is refused by the pin's digest, not accepted. + The build at that commit wrote 180,326 rows (922 MB), SHA256 `67b0998aa2ee1aeed6637dab6a846f405246706508074b1c1b5bab7bd98c8bea`. Its output folder peaked at 2.89 GB under a disk-cap watcher that deleted each - finished package's intermediates. Nine of its ten record sets equal an - earlier build at Chronicle `c32c0b0` row for row (key, value, unit, measure - and geography); PEP county was not in that build. -- **Reading it.** `us_runtime/county_facts.load_us_county_facts` reads the file - in one pass: it hashes the bytes, refuses a row on another row contract, at - a geography level other than county or outside the scope's pairs, drops the - 78 Puerto Rico municipios (state 72) with a count, projects each kept row to - the fields the rung reads, and refuses the file unless its digest and row - count are the pin's. The file on disk keeps Chronicle's bytes. + finished package's intermediates. Nine of its ten record sets matched an + earlier build at Chronicle `c32c0b0` row for row, keying each row by record + set, period type, period value, source row and source column and comparing + value, unit, measure and geography; PEP county was not in that build. + `c32c0b0` is on no branch of the Chronicle remote and that build's output + has been deleted, so the comparison cannot be re-run. Rebuilding at + `3e9d3a0` with the command above and comparing the file's SHA256 with the + pin's can. +- **Reading it.** `us_runtime/county_facts.load_us_county_facts` first hashes + the file and refuses it unless its digest and row count are the pin's, so a + wrong file is named as such before any row is parsed. A second pass hashes + the bytes again while parsing; it refuses a row that is not a JSON object, + is on another row contract, is at a geography level other than county or is + outside the scope's pairs, and a file that changed between the passes. It + drops the 78 Puerto Rico municipios (state 72) with a count and projects + each kept row to the fields the rung reads. The file on disk keeps + Chronicle's bytes. - **Tool flags.** County runs pass `--county-facts - --county-facts-sha256 `, and `--feed-sha256` for the main feed. + --county-facts-sha256 `, and `--feed-sha256`. The county digest + must be the pin's. `--feed-sha256` is only the operator's digest of the + `--feed` file; the tool checks the file against it, not against the main + pin. The run identity records the main feed's digest (`feed_sha256`) and the county facts receipt, which carries the county pin. - **What it holds that the rung must handle.** SOI county 2022 has 3,143 @@ -72,9 +89,12 @@ build machine. linear target. B01003 carries margin-of-error rows for only some counties. Connecticut appears as its nine planning regions (09110-09190) in every package. Against the main pin's state SOI parents, the SOI county rows split - the other 49 states and DC exactly (6,278 county targets; share and target - sums exact), and Hawaii is refused, naming 15005, until the rung declares a - treatment for it. + the other 49 states and DC into 6,278 county targets whose shares sum to one + and whose targets sum to their state parents. The raw county sums are not + the parents: county AGI falls short of the state parent by up to 5% + (Montana), and returns differ by at most 0.05%. The rung uses the county + rows only as shares, so it rescales them to the parents. Hawaii is refused, + naming 15005, until the rung declares a treatment for it. A later main re-pin can fold these pairs into the main scope only by retiring the county pin in the same change. 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 e0be9d2e11..0b7d0356d5 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 = 32609 +EXPECTED_AUTHORED_FIELD_COUNT = 32615 EXPECTED_RESOLVED_BINDING_FIELD_COUNT = 9_785 -EXPECTED_CONFIGURATION_FIELD_COUNT = 42394 +EXPECTED_CONFIGURATION_FIELD_COUNT = 42400 class FieldUsageError(AssertionError): @@ -369,8 +369,8 @@ def _path_inventory(rows: Sequence[tuple[str, object]]) -> tuple[int, str]: "bdd9e79157590fade42d28cc2b5d5c8b58e13903af75375a0e3235c94d2a8339", ), "country_manifest": ( - 104, - "8a186065f5b8ffc59bc3f62fe927975e6f36bc1e913aa61761652c9a8aa67988", + 110, + "368fe74c5a1ac00cc51079ffc1e13add27471d6daeaf2bf362cb321be9535619", ), "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 5e14125c81..cffc573c90 100644 --- a/packages/microcosm-build/src/microcosm/build/us/country_package.json +++ b/packages/microcosm-build/src/microcosm/build/us/country_package.json @@ -62,6 +62,16 @@ "kind": "vintages", "schema_id": "vintages.schema.json" }, + { + "path": "chronicle_county_facts.json", + "kind": "legacy_json", + "schema_id": "legacy_json" + }, + { + "path": "chronicle_county_facts_scope.json", + "kind": "legacy_json", + "schema_id": "legacy_json" + }, { "path": "chronicle_feed.json", "kind": "legacy_json", diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/county_facts.py b/packages/microcosm-build/src/microcosm/build/us_runtime/county_facts.py index 1c0ef2f3a1..35cb8e0e9a 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/county_facts.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/county_facts.py @@ -8,14 +8,16 @@ it 6.5x for every US build while only county builds read them. No fiscal compile reads this file. -:func:`load_us_county_facts` reads the file in one pass: it hashes the exact -bytes, parses every line, refuses a row on an unpinned row contract, at any -geography level but ``county`` or outside the scope's (record set, period) -pairs, drops Puerto Rico (state 72, outside the 3,144 county-equivalents the -County Files cover) with a count, and projects each kept row to the fields the -county rung reads. It refuses the file unless its digest and row count are the -pin's. The file on disk keeps Chronicle's own bytes; only the in-memory rows -are projected. +:func:`load_us_county_facts` first hashes the exact bytes and refuses the +file unless its digest and row count are the pin's, so a wrong or damaged file +is named as such before any row is parsed. A second pass, which hashes the +bytes again and refuses a file that changed in between, parses every line, +refuses a row that is not a JSON object, is on an unpinned row contract, is at +any geography level but ``county`` or is outside the scope's (record set, +period) pairs, drops Puerto Rico (state 72, outside the 3,144 +county-equivalents the County Files cover) with a count, and projects each +kept row to the fields county targets read. The file on disk keeps Chronicle's +own bytes; only the in-memory rows are projected. """ from __future__ import annotations @@ -43,21 +45,20 @@ "us_county_facts_scope_pairs", ] -#: Top-level row fields kept in memory. Everything else (source, lineage, -#: concept alignment, period coverage, labels) stays in the pinned bytes. +#: Top-level row fields kept in memory: what a county target reads (the +#: geography, the measure, its dimensions, the period, the value and the +#: layout) plus the row's key and contract. Everything else (source, lineage, +#: labels, concept alignment, universe constraints, period coverage) stays in +#: the pinned bytes. COUNTY_FACT_FIELDS = ( "aggregate_fact_key", "schema_version", "geography", "observed_measure", "dimensions", - "dimension_value_labels", "period", "value", "value_type", - "entity", - "aggregation", - "universe_constraints", "layout", ) #: Puerto Rico municipios: in the ACS county tables, outside the County Files. @@ -115,7 +116,7 @@ def _county_state(row: Mapping[str, Any]) -> str: if ( not geoid.startswith(_COUNTY_GEOID_PREFIX) or len(code) != 5 - or not code.isdigit() + or not (code.isascii() and code.isdigit()) ): raise ValueError(f"US county facts: invalid county geography id {geoid!r}.") return code[:2] @@ -131,25 +132,50 @@ def _pair(row: Mapping[str, Any]) -> Pair: ) +def _digest(path: str | Path) -> tuple[str, int]: + digest = hashlib.sha256() + count = 0 + with open(path, "rb") as stream: + for line in stream: + digest.update(line) + if line.strip(): + count += 1 + return digest.hexdigest(), count + + def load_us_county_facts( path: str | Path, *, pin: USChronicleFeed | None = None ) -> USCountyFacts: - """Read the pinned county facts file once and keep the projected rows.""" + """Read the pinned county facts file and keep the projected rows.""" pin = pin or load_us_chronicle_county_facts_pin() + facts_sha256, count = _digest(path) + if facts_sha256 != pin.facts_sha256: + raise ValueError( + f"US county facts {path} has sha256 {facts_sha256}; the county pin " + f"names {pin.facts_sha256}." + ) + if count != pin.fact_row_count: + raise ValueError( + f"US county facts {path} has {count} rows; the county pin names " + f"{pin.fact_row_count}." + ) pairs = us_county_facts_scope_pairs() contracts = set(pin.consumer_fact_schema_versions) digest = hashlib.sha256() rows: list[dict[str, Any]] = [] dropped: Counter[str] = Counter() - count = 0 with open(path, "rb") as stream: for line in stream: digest.update(line) if not line.strip(): continue - count += 1 row = json.loads(line) + if not isinstance(row, dict): + raise ValueError( + "US county facts rows must be JSON objects; got " + f"{type(row).__name__}." + ) if row.get("schema_version") not in contracts: raise ValueError( "US county facts row carries an unpinned row contract " @@ -162,21 +188,13 @@ def load_us_county_facts( f"US county facts row {row.get('aggregate_fact_key')!r} is " f"outside the county scope: {pair}." ) - if _county_state(row) in DROPPED_STATE_FIPS: - dropped[f"state_{_county_state(row)}"] += 1 + state = _county_state(row) + if state in DROPPED_STATE_FIPS: + dropped[f"state_{state}"] += 1 continue rows.append({key: row[key] for key in COUNTY_FACT_FIELDS if key in row}) - facts_sha256 = digest.hexdigest() - if facts_sha256 != pin.facts_sha256: - raise ValueError( - f"US county facts {path} has sha256 {facts_sha256}; the county pin " - f"names {pin.facts_sha256}." - ) - if count != pin.fact_row_count: - raise ValueError( - f"US county facts {path} has {count} rows; the county pin names " - f"{pin.fact_row_count}." - ) + if digest.hexdigest() != facts_sha256: + raise ValueError(f"US county facts {path} changed while it was being read.") return USCountyFacts( rows=tuple(rows), path=str(path), 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 519651a171..f7139ece17 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"] == 42394 - assert fields["authored_normative_field_count"] == 32609 + assert fields["configuration_field_count"] == 42400 + assert fields["authored_normative_field_count"] == 32615 assert fields["resolved_binding_field_count"] == 9_785 - assert fields["consumed_field_count"] == 42394 + assert fields["consumed_field_count"] == 42400 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": 27673, - "front_end_validation": 349, + "front_end_validation": 355, "identity_only": 103, } assert fields["generation0_effect_counts"] == { "legacy_behavior": 38_780, - "no_generation0_effect": 3614, + "no_generation0_effect": 3620, } 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 63120bd15d..7b589120c8 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 == 42394 + assert len(field_ledger.fields) == EXPECTED_CONFIGURATION_FIELD_COUNT == 42400 assert field_ledger.source_counts == { - "authored": 32609, + "authored": 32615, "resolved_bindings": 9_785, } assert field_ledger.mode_counts == { "legacy_behavior": 14_269, "compiler_semantic": 27673, - "front_end_validation": 349, + "front_end_validation": 355, "identity_only": 103, } assert field_ledger.generation0_effect_counts == { "legacy_behavior": 38_780, - "no_generation0_effect": 3614, + "no_generation0_effect": 3620, } - assert len({field.pointer for field in field_ledger.fields}) == 42394 + assert len({field.pointer for field in field_ledger.fields}) == 42400 def test_eligibility_concepts_are_validation_not_generation0_behavior( 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 95021122a7..61c2a87ee9 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 @@ -746,7 +746,8 @@ def feed_is_not_county_facts(*_args, **_kwargs): ) module.do_materialize(args) assert seen == parents - # Read once, from the resolved --county-facts path, by prepare_run alone. + # Read exactly once, from the resolved --county-facts path; attach_surface + # reuses what prepare_run loaded. assert county_reads == [county_facts_file.resolve()] identity = json.loads((args.checkpoint_dir / "run_identity.json").read_text()) assert identity["county_facts"]["facts_sha256"] == county_pin.facts_sha256 @@ -931,10 +932,32 @@ def test_county_refresh_recipe_round_trips_custom_geography_and_salt() -> None: assert parsed.county_column == "planning_region" assert parsed.county_holdout_fraction == 0.0 assert parsed.county_holdout_salt == metadata["county_holdout"]["salt"] - assert str(parsed.county_facts) == metadata["county_facts"]["path"] + # Like --feed, the recipe names a placeholder file and the pinned digest, + # never the build machine's path. + assert metadata["county_facts"]["path"] not in recipe + assert str(parsed.county_facts) == "" assert parsed.county_facts_sha256 == metadata["county_facts"]["facts_sha256"] +def test_county_run_metadata_adds_only_the_county_facts_receipt() -> None: + """A run that read no county facts keeps its pre-county metadata keys.""" + + args = SimpleNamespace(geographies="state, cd", county_column="county_fips") + plain = _county().run_metadata(args, {"fraction": 0.1}) + assert set(plain) == { + "geographies", + "county_column", + "county_holdout", + "county_targets_dropped", + } + receipt = {"path": "/x", "facts_sha256": _pinned_sha(), "row_count": 1} + args.county_facts_receipt = receipt + assert _county().run_metadata(args, {"fraction": 0.1}) == { + **plain, + "county_facts": receipt, + } + + # --- the county facts flags (microcosm#922) ---------------------------------- @@ -998,6 +1021,18 @@ def _pinned_sha(): {"soi_mode": "state"}, "--county-facts-sha256 needs --county-facts", ), + ( + ( + "--county-facts", + "{county}", + "--county-facts-sha256", + "{pinned}", + "--geographies", + "state,cd", + ), + {}, + "county in --geographies", + ), ], ids=[ "state-county-without-facts", @@ -1007,6 +1042,7 @@ def _pinned_sha(): "facts-are-the-feed", "facts-outside-state-county", "sha-without-facts", + "facts-without-county-geography", ], ) def test_the_county_facts_flags_refuse_an_unpinned_or_ambiguous_run( @@ -1037,11 +1073,46 @@ def test_a_pinned_county_facts_run_parses(tmp_path) -> None: assert args.county_facts_sha256 == _pinned_sha() +def _v5_soi_row(county, measure, value): + """A county SOI row in the pinned v5 shape, with fields the loader drops.""" + + return { + **_fact(county, measure, value), + "aggregate_fact_key": f"key-{county}-{measure}", + "schema_version": "chronicle.consumer_fact.v5", + "dimension_value_labels": {"irs_soi.county": {county: f"County {county}"}}, + "universe_constraints": {"domain": "tax_returns", "constraints": []}, + "lineage": {"source_record_id": f"irs_soi.county.{county}"}, + "source": {"source_file": "22incyallnoagi.csv"}, + } + + +def _soi_rows(): + return [ + _v5_soi_row(code, measure, value) + for measure in ("return_count", "adjusted_gross_income") + for code, value in (("01001", 1.0), ("01003", 3.0)) + ] + + +def _pin_for(payload, rows): + return dataclasses.replace( + load_us_chronicle_county_facts_pin(), + facts_sha256=hashlib.sha256(payload).hexdigest(), + fact_row_count=rows, + ) + + +@pytest.mark.parametrize("case", ["off-pin digest", "missing file"]) def test_a_county_facts_file_off_the_pin_is_refused_before_any_target( - tmp_path, + tmp_path, case ) -> None: facts = tmp_path / "county.jsonl" - facts.write_bytes(b"{}\n") + if case == "off-pin digest": + # Well-formed pinned-contract rows, but not the pinned bytes. + facts.write_bytes( + b"".join(json.dumps(row).encode() + b"\n" for row in _soi_rows()) + ) args = SimpleNamespace( soi_mode="state_county", families="soi", @@ -1056,4 +1127,29 @@ def test_a_county_facts_file_off_the_pin_is_refused_before_any_target( ) report = json.loads((args.checkpoint_dir / "county_surface.json").read_text()) assert report["status"] == "refused" + expected = "the county pin names" if case == "off-pin digest" else "county.jsonl" + assert expected in report["error"] assert not hasattr(surface, "county_surface") + + +def test_projected_county_rows_give_the_same_soi_surface_as_full_rows( + tmp_path, +) -> None: + """The loader keeps every field the SOI county surface reads.""" + + from microcosm.build.us_runtime.county_facts import load_us_county_facts + + rows = _soi_rows() + path = tmp_path / "county.jsonl" + payload = b"".join(json.dumps(row).encode() + b"\n" for row in rows) + path.write_bytes(payload) + loaded = load_us_county_facts(path, pin=_pin_for(payload, len(rows))) + assert all("lineage" not in row for row in loaded.rows) + parents = [_state_spec(), _state_spec("adjusted_gross_income", 1000.0)] + populations = {1001: 80.0, 1003: 120.0} + full = _county().state_county_soi_surface(parents, rows, populations) + projected = _county().state_county_soi_surface(parents, loaded.rows, populations) + assert projected.receipt == full.receipt + assert [(s.name, s.value, s.metadata) for s in projected.specs] == [ + (s.name, s.value, s.metadata) for s in full.specs + ] diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_chronicle_county_facts.py b/packages/microcosm-build/tests/engine_free/us/test_us_chronicle_county_facts.py index 17580f2f47..df15339339 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_chronicle_county_facts.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_chronicle_county_facts.py @@ -16,6 +16,11 @@ from hypothesis import given, settings from hypothesis import strategies as st +from microcosm.build.chronicle_epoch import ( + ACCEPTED_CONSUMER_ARTIFACT_SCHEMA_VERSIONS, +) +from microcosm.build.us_runtime import chronicle_feed +from microcosm.build.us_runtime import county_facts as county_facts_module from microcosm.build.us_runtime.chronicle_feed import ( US_CHRONICLE_COUNTY_FACTS_SCOPE_RESOURCE, US_CHRONICLE_FEED_SCOPE_RESOURCE, @@ -52,6 +57,67 @@ def test_the_county_pin_loads_and_names_its_scope() -> None: assert pin.is_bare_feed +def test_the_county_pin_names_the_3e9d3a0_build() -> None: + """Moving the county pin is a deliberate repin, never a side effect.""" + + pin = load_us_chronicle_county_facts_pin() + assert pin.source_commit == "3e9d3a0694e8ca7e31ed5319c3ceb1bde92b12e0" + assert pin.facts_sha256 == ( + "67b0998aa2ee1aeed6637dab6a846f405246706508074b1c1b5bab7bd98c8bea" + ) + assert pin.fact_row_count == 180_326 + assert pin.scope_sha256 == ( + "87b12e4f74702ccbf5fe96c128ff5df0ffd8214a78de8f1fcce2ab2ba37fe7f5" + ) + assert pin.consumer_fact_schema_versions == ("chronicle.consumer_fact.v5",) + assert pin.consumer_fact_schema_sha256 == ( + "acd33a091cd8d192be5d264e3e94c13e00afb6fd1972e57d4576ac55a54f6970" + ) + assert pin.manifest_sha256 is None + assert pin.artifact_schema_version is None + + +def _write_pin(monkeypatch, tmp_path, **changes) -> None: + raw = json.loads( + (_US_PACKAGE / "chronicle_county_facts.json").read_text(encoding="utf-8") + ) + raw.update(changes) + path = tmp_path / "chronicle_county_facts.json" + path.write_text(json.dumps(raw), encoding="utf-8") + monkeypatch.setattr(chronicle_feed, "_county_facts_path", lambda: path) + + +def test_a_county_pin_naming_a_consumer_artifact_is_refused( + monkeypatch, tmp_path +) -> None: + _write_pin( + monkeypatch, + tmp_path, + manifest_sha256="a" * 64, + artifact_schema_version=sorted(ACCEPTED_CONSUMER_ARTIFACT_SCHEMA_VERSIONS)[0], + ) + with pytest.raises(ValueError, match="must pin a bare facts file"): + load_us_chronicle_county_facts_pin() + + +@pytest.mark.parametrize( + ("changes", "match"), + [ + ({"scope": "us_fiscal_targets"}, "scope must be 'us_county_facts'"), + ({"facts_sha256": "not-hex"}, "facts_sha256"), + ({"scope_sha256": "0" * 64}, "scope_sha256 does not match"), + ({"fact_row_count": 0}, "fact_row_count must be positive"), + ], + ids=["main-scope", "bad-digest", "other-scope-bytes", "no-rows"], +) +def test_a_malformed_county_pin_is_refused( + monkeypatch, tmp_path, changes, match +) -> None: + _write_pin(monkeypatch, tmp_path, **changes) + with pytest.raises(ValueError, match=match): + load_us_chronicle_county_facts_pin() + + def test_the_county_pin_is_not_the_main_pin() -> None: county = load_us_chronicle_county_facts_pin() main = load_us_chronicle_feed() @@ -170,10 +236,11 @@ def test_any_one_byte_change_is_refused(tmp_path_factory, count, data) -> None: pin = _pin_for(payload, count) position = data.draw(st.integers(min_value=0, max_value=len(payload) - 1)) mutated = bytearray(payload) - # A digit for a digit keeps the line valid JSON, so the digest must refuse it. + # Any changed byte moves the digest, which is checked before any row is + # parsed, so the refusal names the digest even when the line is still JSON. mutated[position] = ord("7") if mutated[position] != ord("7") else ord("3") path.write_bytes(bytes(mutated)) - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="has sha256 .*; the county pin names"): load_us_county_facts(path, pin=pin) @@ -189,8 +256,16 @@ def test_any_one_byte_change_is_refused(tmp_path_factory, count, data) -> None: lambda: _row(9, contract="chronicle.consumer_fact.v3"), "unpinned row contract", ), + (lambda: ["not", "a", "row"], "must be JSON objects"), + (lambda: _row(9, state="0\u0661"), "invalid county geography id"), + ], + ids=[ + "non-county", + "out-of-scope", + "unpinned-contract", + "not-an-object", + "non-ascii-digit", ], - ids=["non-county", "out-of-scope", "unpinned-contract"], ) def test_a_bad_row_between_good_ones_is_refused(tmp_path, bad, match) -> None: rows = [_row(0), bad(), _row(1)] @@ -206,3 +281,39 @@ def test_a_row_count_other_than_the_pins_is_refused(tmp_path) -> None: payload = _write(path, rows) with pytest.raises(ValueError, match="rows; the county pin names 3"): load_us_county_facts(path, pin=_pin_for(payload, 3)) + + +def test_the_receipt_names_the_file_its_counts_and_the_pin(tmp_path) -> None: + rows = [_row(0), _row(1, state="72"), _row(2)] + path = tmp_path / "facts.jsonl" + payload = _write(path, rows) + pin = _pin_for(payload, len(rows)) + receipt = load_us_county_facts(path, pin=pin).receipt() + assert receipt == { + "path": str(path), + "facts_sha256": hashlib.sha256(payload).hexdigest(), + "row_count": 3, + "kept_rows": 2, + "dropped": {"state_72": 1}, + "pin": pin.to_dict(), + } + json.dumps(receipt) + + +def test_a_file_that_changes_between_the_two_passes_is_refused( + monkeypatch, tmp_path +) -> None: + pinned = [_row(0), _row(1)] + path = tmp_path / "facts.jsonl" + payload = _write(path, pinned) + pin = _pin_for(payload, len(pinned)) + # The digest pass sees the pinned bytes; the file then changes before the + # parsing pass reads it. + monkeypatch.setattr( + county_facts_module, + "_digest", + lambda _path: (pin.facts_sha256, pin.fact_row_count), + ) + _write(path, [_row(0), _row(3)]) + with pytest.raises(ValueError, match="changed while it was being read"): + load_us_county_facts(path, pin=pin) 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 68df1f8a78..2f29e84127 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 @@ -355,7 +355,9 @@ def capture_equality(expected: object, actual: object) -> None: # through the bundle's source stages. # The hierarchy value ranks move it through medicaid_take_up's # attested bytes. - "spec_sha256": "98d583653d37fe58edcace1cf3e21a139b69ebe7d1c3dac6a58f08b2b5aab8cf", + # microcosm#922's county facts pin, two declared legacy resources, + # moves it. + "spec_sha256": "fdf6e8f4e81a5b24b43c2665413b4f5a04e38ab8e35e781b232939835df79ed4", }, } diff --git a/tools/generate_us_bundle_from_constants.py b/tools/generate_us_bundle_from_constants.py index c8b0dc9443..c1fb323f71 100644 --- a/tools/generate_us_bundle_from_constants.py +++ b/tools/generate_us_bundle_from_constants.py @@ -136,6 +136,10 @@ def _domain_builders() -> dict[str, Callable[[], object]]: # The three projections above are byte-frozen and equality-attested during the # F0 bridge; their existing direct consumers retire with the constants adapter. LEGACY_RESOURCE_PATHS = ( + # The county facts pin (microcosm#922): read only by the ACS-local county + # rung through --county-facts, never by a fiscal compile. + "chronicle_county_facts.json", + "chronicle_county_facts_scope.json", "chronicle_feed.json", "chronicle_feed_scope.json", "ecps_parity_known_gaps.json", diff --git a/tools/spec_engine_coverage.py b/tools/spec_engine_coverage.py index 8e6c05a0c8..f3147b210c 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 = ( - "f6832e8d2892af22e41afd0b0bea0cba354bbff8b84bebcc652e765a3ae7df92" + "df98ac3762e95e3e20b83fb897b6947787f5939d9d5c631df9c1e06deb31ef56" ) DEFAULT_REPORT_PATH = ( Path(__file__).resolve().parents[1] diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index 5f32931a6a..73dd2de0d4 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -7,8 +7,8 @@ County facts come from their own pinned file (``--county-facts``, pinned by ``us/chronicle_county_facts.json``, microcosm#922), never from ``--feed``: -:func:`prepare_run` loads it once and every county step reads -``surface.county_facts.rows``. +:func:`prepare_run` loads it once into ``surface.county_facts``; county steps +read ``surface.county_facts.rows`` and never reopen the file or ``--feed``. """ from __future__ import annotations @@ -279,7 +279,8 @@ def state_county_soi_surface(state_specs, facts, county_populations): blocks[key][code] = (value, fact) if not blocks: raise ValueError( - "Ledger feed has no county SOI facts; export soi-county-2022 and repin the feed." + "County facts carry no IRS SOI county rows; pass the pinned " + "--county-facts file (us/chronicle_county_facts.json, microcosm#922)." ) parents = {} for spec in state_specs: @@ -832,7 +833,7 @@ def prepare_run(args, geographies, populations, *, surface=None): surface.county_facts.rows, populations["county"], ) - except ValueError as error: + except (ValueError, OSError) as error: (args.checkpoint_dir / "county_surface.json").write_text( json.dumps({"status": "refused", "error": str(error)}) ) @@ -1064,10 +1065,12 @@ def refresh_recipe(command, materialize_rss): f" --county-holdout-fraction {float(holdout['fraction'])!r}" f" --county-holdout-salt {shlex.quote(holdout['salt'])}" ) + # Like --feed, the county facts file is a placeholder: the recipe names + # the pinned digest, never the build machine's path. facts = materialize_rss.get("county_facts") if facts: command += ( - f" --county-facts {shlex.quote(str(facts['path']))}" + " --county-facts " f" --county-facts-sha256 {facts['facts_sha256']}" ) return command From e09c18284c2fc4aa7f545554138fb66285183603 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 14 Nov 2026 09:21:26 -0500 Subject: [PATCH 3/6] Say where the county facts file lives and that the two pins move together (#922) The 922 MB county facts file is never committed; the repository holds only its pin (digest, size, row count, scope), and an operator builds or copies the file and passes it with --county-facts. A change that re-pins the main US feed at a Chronicle commit also rebuilds and re-pins the county facts at that commit, so a US build reads one Chronicle base. Co-Authored-By: Claude Opus 5.5 --- docs/us-chronicle-feed-repin.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/docs/us-chronicle-feed-repin.md b/docs/us-chronicle-feed-repin.md index 786d9efa73..a89627d9af 100644 --- a/docs/us-chronicle-feed-repin.md +++ b/docs/us-chronicle-feed-repin.md @@ -83,6 +83,11 @@ machine on 2026-11-13; the run notes are not in this repository. pin. The run identity records the main feed's digest (`feed_sha256`) and the county facts receipt, which carries the county pin. +- **Where the file lives.** Not in git. The repository holds only the pin: + the file's digest, size and row count and the scope. An operator builds the + file with the command above at the pinned commit, or copies a build + machine's copy, and passes its path with `--county-facts`; the loader's + digest check is what makes either acceptable. - **What it holds that the rung must handle.** SOI county 2022 has 3,143 counties and no Kalawao (15005). ACS B19013 (median household income) has no row for De Baca County (35011) and is a median, so it is a diagnostic, not a @@ -99,6 +104,12 @@ machine on 2026-11-13; the run notes are not in this repository. A later main re-pin can fold these pairs into the main scope only by retiring the county pin in the same change. +The two pins move together. The main feed is pinned at `41b2fb2` and the +county facts at `3e9d3a0`; the next main re-pin starts at or after +`3e9d3a0`. From then on, a change that re-pins the main feed at a Chronicle +commit also rebuilds the county facts at that commit and re-pins them, so a +US build reads one Chronicle base. + ## A re-pin onto a newer row contract The US feed is on `chronicle.consumer_fact.v3`; Chronicle `main` writes From ca3948494050fd3b27f554c91a77a492360dc516 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 15 Nov 2026 09:42:10 -0500 Subject: [PATCH 4/6] Fix the county facts pin's round-2 review findings (#922) - The loader's second pass now hashes the whole file before it refuses. A row it cannot accept stops parsing, not hashing, so a file swapped between the two passes is named as changed whatever its rows hold, and a malformed row in the pinned bytes is always a ValueError. Before, a swapped row with a text period or a list contract raised AttributeError or TypeError, which prepare_run did not record in county_surface.json. - Tests: county ids with the wrong prefix, four or six digits, or letters; a text period, a list layout, a list contract and a text geography; blank lines are hashed but not counted; every swapped file is named as changed; a property test that any pinned row value loads or raises ValueError; prepare_run records a run with no county facts and a swapped file; and no Modal plan input or option reaches --county-facts. - Docs: the pin holds the digest and row count, not the size; no county step reads --feed and nothing reopens the county facts file after prepare_run; refusals are recorded before the staging frame loads (the state admin targets come from --feed earlier); the Modal refusal comes from its check; the recipe's --feed-sha256 is a placeholder; 6.4x, not 6.5x; ten pairs from nine packages; "exceeded" the folder cap; stale feed wording; the changelog names --feed-sha256. Not changed: the unreachable county facts fallback in attach_surface (the production county rung rewrites that function) and dropping projected rows after the SOI split (the production rung reads them for the ACS families). Co-Authored-By: Claude Opus 5.5 --- changelog.d/922-us-county-facts-pin.added.md | 2 +- docs/us-acs-local-county-rung.md | 35 +++-- docs/us-chronicle-feed-repin.md | 11 +- .../build/us_runtime/county_facts.py | 91 ++++++++---- .../us/test_us_acs_local_county_surface.py | 56 +++++++- .../us/test_us_chronicle_county_facts.py | 132 ++++++++++++++++++ .../us/test_us_modal_stage_plan_tool.py | 27 ++++ 7 files changed, 302 insertions(+), 52 deletions(-) diff --git a/changelog.d/922-us-county-facts-pin.added.md b/changelog.d/922-us-county-facts-pin.added.md index 61b40fd579..a077f38f2a 100644 --- a/changelog.d/922-us-county-facts-pin.added.md +++ b/changelog.d/922-us-county-facts-pin.added.md @@ -1 +1 @@ -Pin the US county facts (IRS SOI county, Census PEP county and seven ACS 5-year county tables) as their own Chronicle file beside the main US feed, and make the ACS-local county rung read them through `--county-facts` and `--county-facts-sha256` instead of `--feed`. The US country package declares the two new pin files, which moves the US bundle's `spec_sha256`. +Pin the US county facts (IRS SOI county, Census PEP county and seven ACS 5-year county tables) as their own Chronicle file beside the main US feed, and make the ACS-local county rung read them through `--county-facts` and `--county-facts-sha256` instead of `--feed`; a county run also needs `--feed-sha256`, the operator's digest of the `--feed` file. The US country package declares the two new pin files, which moves the US bundle's `spec_sha256`. diff --git a/docs/us-acs-local-county-rung.md b/docs/us-acs-local-county-rung.md index aa787f3172..5f82a51767 100644 --- a/docs/us-acs-local-county-rung.md +++ b/docs/us-acs-local-county-rung.md @@ -66,8 +66,8 @@ every state, even when an entire concept or parent block is absent: | `return_count` | `irs_soi.individual_income_tax_returns` | count | | `adjusted_gross_income` | `us:statutes/26/62#adjusted_gross_income`, source concept `irs_soi.adjusted_gross_income` | USD | -The feed has already converted the AGI publisher values from thousands of USD -to USD; the county rung does not apply another scale factor. It refuses +Chronicle has already converted the AGI publisher values from thousands of USD +to USD in the county facts file; the county rung does not apply another scale factor. It refuses duplicate facts, negative or nonfinite shares, zero share denominators, incomplete county inventories, incompatible boundaries, and missing or ambiguous state parents. No unsupported concept receives a new engine measure. @@ -154,18 +154,21 @@ first hashes the file and refuses it unless its digest and row count are the pin's. A second pass hashes it again and parses it. That pass refuses a row that is not a JSON object, is on another row contract, is not a county row or is outside the scope, and refuses a file whose bytes changed between the -passes. It drops the 78 Puerto Rico municipios (4,136 ACS rows) with a count +passes; it reads to the end before refusing, so a file swapped between the +passes is named as changed whatever its rows hold. It drops the 78 Puerto Rico municipios (4,136 ACS rows) with a count and keeps only the fields county targets read. A refusal, or a file that -cannot be read, is recorded in `county_surface.json` before any target is -built. On the build machine the loader reads the pinned file in about 5 s and +cannot be read, is recorded in `county_surface.json` before the staging frame +is loaded or any target row is materialized (the state administrative targets +are compiled from `--feed` earlier). On the build machine the loader reads the pinned file in about 5 s and holds about 0.9 GB of rows, measured apart from importing the US runtime. The rows stay on the surface for the rest of the materialize stage; today only the -SOI county split reads them, in `prepare_run`. Nothing re-reads `--feed` or the -county facts file. The +SOI county split reads them, in `prepare_run`. No county step reads `--feed`, +and nothing reopens the county facts file after `prepare_run`. The run identity and `materialize_rss.json` record the county facts receipt under -`county_facts`. The refresh recipe carries both flags; like `--feed`, it -names a placeholder file (``) and the pinned digest, never -the build machine's path. A run without county +`county_facts`. The refresh recipe carries both flags. It names placeholder files +(``, like `--feed`'s) and never the build machine's path; +the county digest it carries is the pinned one, while `--feed-sha256` stays a +`` placeholder. A run without county facts records nothing new, so its run identity keeps its pre-county bytes. The inspected Chronicle publisher inputs have two concrete blockers: @@ -177,7 +180,7 @@ The inspected Chronicle publisher inputs have two concrete blockers: than 20 returns for a county were excluded, so Kalawao's SOI value is missing, not zero. The guide does not say whether Kalawao's returns are counted in another county's row. Until the rung declares a reviewed treatment (a - combined SOI cell {15005, 15009}, planned on `lwi-county-rung-production`), + combined SOI cell {15005, 15009}, planned in the production county rung's own change), a complete county SOI block still fails with that county named. - **Connecticut:** both packages use the nine planning-region codes `09110` through `09190`. The household county column and ladder must use those same @@ -210,7 +213,7 @@ At 3,144 counties and the current two SOI concepts, the county increment is `3,144 × (population + returns + AGI) = 9,432` rows. With the pinned 4,380 state administrative rows, 51 state population rows and 436 district population rows, this is approximately **14,299 rows** including holdouts. The exact -count depends on the reviewed feed and ladder; an incomplete SOI county block +count depends on the pinned county facts and the ladder; an incomplete SOI county block is refused rather than reducing that count silently. For the historical 1,588,854-household staging population, each household can @@ -226,11 +229,13 @@ households-by-county-target matrix. County materialize runs are local. The Modal stage plan (`tools/modal_us_stage_plan.py`) has no way to pass `--county-facts`, so its -preflight refuses a `state_county` materialize before any compute. +check (`check_stage`) refuses a `state_county` materialize before any compute. +A `--run` that skips that check stages its inputs first and is then refused by +the release tool's own argument check. Once the input blockers are resolved, set these paths and the two pinned digests in the execution environment. This example uses the planning-region -column; use `county_fips` only with a feed and ladder matching that column. +column; use `county_fips` only with a ladder matching that column. The following is documentation only and has not been executed: County rows activate a separate solver profile: `--county-target-loss-cap 10` @@ -300,7 +305,7 @@ tests with at most two workers, the related release/district tests, the test layout verifier, `uv run ruff check .`, and `uv run ruff format --check` on touched Python files; report actual results in the PR. No release build, full materialization, annual projection, publication, or -county-inclusive feed regeneration is part of this implementation's validation. +county facts rebuild is part of this implementation's validation. ## Validation record diff --git a/docs/us-chronicle-feed-repin.md b/docs/us-chronicle-feed-repin.md index a89627d9af..0f04cb794b 100644 --- a/docs/us-chronicle-feed-repin.md +++ b/docs/us-chronicle-feed-repin.md @@ -33,7 +33,7 @@ alone). Measured at the compile and parse sites, that would raise a compile's peak memory from 2.8 GB to 6.7 GB and keep about 3.2 GB more resident in every fiscal-refresh run, which holds the parsed feed for its whole length, while only county builds read the rows. A main-feed rebuild with them also -passed the build machine's 3.5 GB folder cap. These were measured on the build +exceeded the build machine's 3.5 GB folder cap. These were measured on the build machine on 2026-11-13; the run notes are not in this repository. - **Commit.** Chronicle main `3e9d3a0694e8ca7e31ed5319c3ceb1bde92b12e0` @@ -41,9 +41,10 @@ machine on 2026-11-13; the run notes are not in this repository. it needs no branch or tag; the next main re-pin starts at or after it. The rows are on the `chronicle.consumer_fact.v5` contract (schema digest `acd33a09…`); the main pin stays on v3. -- **Pairs.** 10, built at their own years (2022: `packages/irs_soi/county_2022`; - 2024: `packages/census/pep_county_2024` and the seven - `packages/census/acs5_b*_county_2024` packages). The scopes share no pair, +- **Pairs.** 10 (record set, period) pairs from nine packages, built at their + own years (2022: `packages/irs_soi/county_2022`; 2024: + `packages/census/pep_county_2024` and the seven + `packages/census/acs5_b*_county_2024` packages; B01003 has two record sets). The scopes share no pair, and `test_us_chronicle_county_facts.py` refuses a change that adds one to both. - **Build.** The same builder with the county scope: @@ -84,7 +85,7 @@ machine on 2026-11-13; the run notes are not in this repository. The run identity records the main feed's digest (`feed_sha256`) and the county facts receipt, which carries the county pin. - **Where the file lives.** Not in git. The repository holds only the pin: - the file's digest, size and row count and the scope. An operator builds the + the file's digest and row count (the file is 922,268,386 bytes) and the scope. An operator builds the file with the command above at the pinned commit, or copies a build machine's copy, and passes its path with `--county-facts`; the loader's digest check is what makes either acceptable. diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/county_facts.py b/packages/microcosm-build/src/microcosm/build/us_runtime/county_facts.py index 35cb8e0e9a..c1d96e2541 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/county_facts.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/county_facts.py @@ -5,7 +5,7 @@ in their own pinned file, ``us/chronicle_county_facts.json`` with scope ``us/chronicle_county_facts_scope.json``, beside the main US feed pin (``us/chronicle_feed.json``), because carrying them in the main feed would grow -it 6.5x for every US build while only county builds read them. No fiscal +it 6.4x for every US build while only county builds read them. No fiscal compile reads this file. :func:`load_us_county_facts` first hashes the exact bytes and refuses the @@ -16,8 +16,11 @@ any geography level but ``county`` or is outside the scope's (record set, period) pairs, drops Puerto Rico (state 72, outside the 3,144 county-equivalents the County Files cover) with a count, and projects each -kept row to the fields county targets read. The file on disk keeps Chronicle's -own bytes; only the in-memory rows are projected. +kept row to the fields county targets read. A row the second pass cannot +accept stops parsing but not hashing: the pass reads to the end, so a file +swapped between the passes is named as changed, whatever its rows hold, and a +malformed row in the pinned bytes is always a ``ValueError``. The file on disk +keeps Chronicle's own bytes; only the in-memory rows are projected. """ from __future__ import annotations @@ -125,6 +128,11 @@ def _county_state(row: Mapping[str, Any]) -> str: def _pair(row: Mapping[str, Any]) -> Pair: period = row.get("period") or {} layout = row.get("layout") or {} + if not isinstance(period, Mapping) or not isinstance(layout, Mapping): + raise ValueError( + f"US county facts row {row.get('aggregate_fact_key')!r} has a " + "period or layout that is not an object." + ) return ( str(layout.get("record_set_id", "")), str(period.get("type", "")), @@ -132,6 +140,37 @@ def _pair(row: Mapping[str, Any]) -> Pair: ) +def _checked_row( + line: bytes, pairs: frozenset[Pair], contracts: frozenset[str] +) -> tuple[str, dict[str, Any] | None]: + """Check one non-blank line; return its state and projected row. + + The projected row is ``None`` for a dropped state. + """ + + row = json.loads(line) + if not isinstance(row, dict): + raise ValueError( + f"US county facts rows must be JSON objects; got {type(row).__name__}." + ) + version = row.get("schema_version") + if not isinstance(version, str) or version not in contracts: + raise ValueError( + "US county facts row carries an unpinned row contract " + f"{version!r}; the pin declares {sorted(contracts)}." + ) + pair = _pair(row) + if pair not in pairs: + raise ValueError( + f"US county facts row {row.get('aggregate_fact_key')!r} is " + f"outside the county scope: {pair}." + ) + state = _county_state(row) + if state in DROPPED_STATE_FIPS: + return state, None + return state, {key: row[key] for key in COUNTY_FACT_FIELDS if key in row} + + def _digest(path: str | Path) -> tuple[str, int]: digest = hashlib.sha256() count = 0 @@ -161,40 +200,36 @@ def load_us_county_facts( f"{pin.fact_row_count}." ) pairs = us_county_facts_scope_pairs() - contracts = set(pin.consumer_fact_schema_versions) + contracts = frozenset(pin.consumer_fact_schema_versions) digest = hashlib.sha256() rows: list[dict[str, Any]] = [] dropped: Counter[str] = Counter() + failure: Exception | None = None with open(path, "rb") as stream: for line in stream: digest.update(line) - if not line.strip(): + if failure is not None or not line.strip(): continue - row = json.loads(line) - if not isinstance(row, dict): - raise ValueError( - "US county facts rows must be JSON objects; got " - f"{type(row).__name__}." - ) - if row.get("schema_version") not in contracts: - raise ValueError( - "US county facts row carries an unpinned row contract " - f"{row.get('schema_version')!r}; the pin declares " - f"{sorted(contracts)}." - ) - pair = _pair(row) - if pair not in pairs: - raise ValueError( - f"US county facts row {row.get('aggregate_fact_key')!r} is " - f"outside the county scope: {pair}." - ) - state = _county_state(row) - if state in DROPPED_STATE_FIPS: - dropped[f"state_{state}"] += 1 + try: + state, kept = _checked_row(line, pairs, contracts) + except Exception as error: # classified once the hash is complete + failure = error continue - rows.append({key: row[key] for key in COUNTY_FACT_FIELDS if key in row}) + if kept is None: + dropped[f"state_{state}"] += 1 + else: + rows.append(kept) if digest.hexdigest() != facts_sha256: - raise ValueError(f"US county facts {path} changed while it was being read.") + raise ValueError( + f"US county facts {path} changed while it was being read." + ) from failure + if isinstance(failure, ValueError): + raise failure + if failure is not None: + raise ValueError( + f"US county facts {path} holds a malformed row: " + f"{type(failure).__name__}: {failure}" + ) from failure return USCountyFacts( rows=tuple(rows), path=str(path), 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 61c2a87ee9..af6c9ae3e4 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 @@ -1103,7 +1103,7 @@ def _pin_for(payload, rows): ) -@pytest.mark.parametrize("case", ["off-pin digest", "missing file"]) +@pytest.mark.parametrize("case", ["off-pin digest", "missing file", "no county facts"]) def test_a_county_facts_file_off_the_pin_is_refused_before_any_target( tmp_path, case ) -> None: @@ -1118,7 +1118,7 @@ def test_a_county_facts_file_off_the_pin_is_refused_before_any_target( families="soi", sample_fraction=0.01, checkpoint_dir=tmp_path / "checkpoint", - county_facts=facts, + county_facts=None if case == "no county facts" else facts, ) surface = SimpleNamespace(registry=SimpleNamespace(specs=())) with pytest.raises(SystemExit): @@ -1127,11 +1127,61 @@ def test_a_county_facts_file_off_the_pin_is_refused_before_any_target( ) report = json.loads((args.checkpoint_dir / "county_surface.json").read_text()) assert report["status"] == "refused" - expected = "the county pin names" if case == "off-pin digest" else "county.jsonl" + expected = { + "off-pin digest": "the county pin names", + "missing file": "county.jsonl", + "no county facts": "needs --county-facts", + }[case] assert expected in report["error"] assert not hasattr(surface, "county_surface") +@pytest.mark.parametrize( + "swapped_row", + [ + {"period": "2022"}, + {"schema_version": ["chronicle.consumer_fact.v5"]}, + {"schema_version": "chronicle.consumer_fact.v6"}, + {"layout": None, "period": 7}, + ], + ids=["period-text", "contract-list", "contract-v6", "period-number"], +) +def test_a_county_facts_file_swapped_between_passes_is_recorded_as_changed( + monkeypatch, tmp_path, swapped_row +) -> None: + """microcosm#922 review P2-1: a file that changes after the digest pass is + recorded as changed, whatever its rows hold, never an unrecorded crash.""" + + from microcosm.build.us_runtime import county_facts as county_facts_module + + pin = load_us_chronicle_county_facts_pin() + # The digest pass sees the pinned bytes; the parsing pass reads this file. + monkeypatch.setattr( + county_facts_module, + "_digest", + lambda _path: (pin.facts_sha256, pin.fact_row_count), + ) + rows = _soi_rows() + rows[0] = {**rows[0], **swapped_row} + facts = tmp_path / "county.jsonl" + facts.write_bytes(b"".join(json.dumps(row).encode() + b"\n" for row in rows)) + args = SimpleNamespace( + soi_mode="state_county", + families="soi", + sample_fraction=0.01, + checkpoint_dir=tmp_path / "checkpoint", + county_facts=facts, + ) + surface = SimpleNamespace(registry=SimpleNamespace(specs=())) + with pytest.raises(SystemExit): + _county().prepare_run( + args, ["state", "county"], {"county": {1001: 10.0}}, surface=surface + ) + report = json.loads((args.checkpoint_dir / "county_surface.json").read_text()) + assert report["status"] == "refused" + assert "changed while it was being read" in report["error"] + + def test_projected_county_rows_give_the_same_soi_surface_as_full_rows( tmp_path, ) -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_chronicle_county_facts.py b/packages/microcosm-build/tests/engine_free/us/test_us_chronicle_county_facts.py index df15339339..320a6e7990 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_chronicle_county_facts.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_chronicle_county_facts.py @@ -177,6 +177,10 @@ def _row(index: int, *, state: str = "01", pair=None, level="county", contract=N } +def _with_geoid(row: dict, geoid: str) -> dict: + return {**row, "geography": {**row["geography"], "id": geoid}} + + def _write(path: Path, rows, *, separators=(",", ":")) -> bytes: payload = b"".join( json.dumps(row, separators=separators, sort_keys=True).encode() + b"\n" @@ -258,6 +262,20 @@ def test_any_one_byte_change_is_refused(tmp_path_factory, count, data) -> None: ), (lambda: ["not", "a", "row"], "must be JSON objects"), (lambda: _row(9, state="0\u0661"), "invalid county geography id"), + (lambda: _with_geoid(_row(9), "0400000US01001"), "invalid county geography id"), + (lambda: _with_geoid(_row(9), "0500000US0100"), "invalid county geography id"), + ( + lambda: _with_geoid(_row(9), "0500000US010010"), + "invalid county geography id", + ), + (lambda: _with_geoid(_row(9), "0500000US01ABC"), "invalid county geography id"), + (lambda: {**_row(9), "period": "2022"}, "period or layout that is not"), + (lambda: {**_row(9), "layout": ["x"]}, "period or layout that is not"), + ( + lambda: {**_row(9), "schema_version": ["chronicle.consumer_fact.v5"]}, + "unpinned row contract", + ), + (lambda: {**_row(9), "geography": "0500000US01001"}, "county rows"), ], ids=[ "non-county", @@ -265,6 +283,14 @@ def test_any_one_byte_change_is_refused(tmp_path_factory, count, data) -> None: "unpinned-contract", "not-an-object", "non-ascii-digit", + "not-a-county-geoid-prefix", + "four-digit-code", + "six-digit-code", + "non-digit-code", + "period-text", + "layout-list", + "contract-list", + "geography-text", ], ) def test_a_bad_row_between_good_ones_is_refused(tmp_path, bad, match) -> None: @@ -317,3 +343,109 @@ def test_a_file_that_changes_between_the_two_passes_is_refused( _write(path, [_row(0), _row(3)]) with pytest.raises(ValueError, match="changed while it was being read"): load_us_county_facts(path, pin=pin) + + +def test_blank_lines_are_hashed_but_not_counted_or_parsed(tmp_path) -> None: + rows = [_row(0), _row(1, state="72"), _row(2)] + lines = [json.dumps(row, sort_keys=True).encode() + b"\n" for row in rows] + payload = b"\n" + lines[0] + b" \n" + lines[1] + b"\t\n" + lines[2] + b"\n" + path = tmp_path / "facts.jsonl" + path.write_bytes(payload) + facts = load_us_county_facts(path, pin=_pin_for(payload, len(rows))) + assert facts.row_count == 3 + assert [row["aggregate_fact_key"] for row in facts.rows] == [ + "key-000000", + "key-000002", + ] + assert facts.dropped == {"state_72": 1} + assert facts.facts_sha256 == hashlib.sha256(payload).hexdigest() + # Counting blank lines would name four or more rows, not the pin's three. + with pytest.raises(ValueError, match="rows; the county pin names 4"): + load_us_county_facts(path, pin=_pin_for(payload, 4)) + + +_SWAPPED = [ + b'{"not": "json"\n', + b'["not", "a", "row"]\n', + json.dumps({**_row(5), "period": "2022"}).encode() + b"\n", + json.dumps({**_row(5), "schema_version": ["chronicle.consumer_fact.v5"]}).encode() + + b"\n", + json.dumps(_row(5, contract="chronicle.consumer_fact.v6")).encode() + b"\n", + json.dumps(_row(5, level="state")).encode() + b"\n", + json.dumps(_with_geoid(_row(5), "0500000US01ABC")).encode() + b"\n", + b"\xff\xfe\n", +] + + +@pytest.mark.parametrize("swapped", _SWAPPED, ids=range(len(_SWAPPED))) +@pytest.mark.parametrize("where", ["first", "last"]) +def test_a_file_swapped_between_the_passes_is_named_as_changed( + monkeypatch, tmp_path, swapped, where +) -> None: + """Review P2-1: whatever a swapped file holds, the refusal is the change, + a ValueError, and it is decided only after the whole file is hashed.""" + + pinned = [_row(0), _row(1), _row(2)] + path = tmp_path / "facts.jsonl" + payload = _write(path, pinned) + pin = _pin_for(payload, len(pinned)) + monkeypatch.setattr( + county_facts_module, + "_digest", + lambda _path: (pin.facts_sha256, pin.fact_row_count), + ) + good = [json.dumps(row, sort_keys=True).encode() + b"\n" for row in pinned] + lines = [swapped, *good[1:]] if where == "first" else [*good[:2], swapped] + path.write_bytes(b"".join(lines)) + with pytest.raises(ValueError, match="changed while it was being read"): + load_us_county_facts(path, pin=pin) + + +_JSON = st.recursive( + st.none() + | st.booleans() + | st.integers(min_value=-(2**40), max_value=2**40) + | st.floats(allow_nan=False, allow_infinity=False) + | st.text(max_size=12), + lambda children: ( + st.lists(children, max_size=3) + | st.dictionaries(st.text(max_size=8), children, max_size=3) + ), + max_leaves=8, +) +_FIELDS = st.sampled_from( + [ + ("schema_version",), + ("geography",), + ("geography", "id"), + ("geography", "level"), + ("period",), + ("period", "type"), + ("period", "value"), + ("layout",), + ("layout", "record_set_id"), + ] +) + + +@settings(max_examples=150, deadline=None) +@given(field=_FIELDS, value=_JSON, data=st.data()) +def test_any_pinned_row_value_loads_or_is_a_value_error( + tmp_path_factory, field, value, data +) -> None: + """For every pinned file, the loader returns rows or raises ValueError.""" + + rows = [_row(i) for i in range(3)] + index = data.draw(st.integers(min_value=0, max_value=2)) + target = rows[index] + if len(field) == 1: + target[field[0]] = value + else: + target[field[0]] = {**target[field[0]], field[1]: value} + path = tmp_path_factory.mktemp("cf") / "facts.jsonl" + payload = _write(path, rows) + try: + facts = load_us_county_facts(path, pin=_pin_for(payload, len(rows))) + except ValueError: + return + assert len(facts.rows) + sum(facts.dropped.values()) == len(rows) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_plan_tool.py b/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_plan_tool.py index e2704027ed..573a829e0a 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_plan_tool.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_plan_tool.py @@ -361,6 +361,33 @@ def test_no_option_maps_to_a_runner_owned_flag() -> None: ), (tool.name, key) +def test_a_release_plan_cannot_pass_the_county_facts() -> None: + """microcosm#922: county materialize runs are local. + + No staged input or plan option of the release tool reaches + ``--county-facts`` or ``--county-facts-sha256``, so a ``state_county`` + materialize plan builds an argv without them, which the tool's own argument + check (``county_surface._validate_county_facts``) refuses. + """ + + tool = plan_lib.US_ACS_LOCAL_RELEASE + assert not [name for name in tool.inputs if "county" in name] + assert not [ + option.flag + for option in tool.options.values() + if option.flag.startswith("--county-facts") + ] + data = _plan_data() + data["options"] = { + **data.get("options", {}), + "soi_mode": "state_county", + "geographies": "state,cd,county", + } + argv = plan_lib.planned_argv(plan_lib.parse_plan(data)) + assert argv[argv.index("--soi-mode") + 1] == "state_county" + assert not [item for item in argv if item.startswith("--county-facts")] + + def test_build_stage_argv_requires_every_staged_path() -> None: plan = plan_lib.parse_plan(_plan_data()) with pytest.raises(plan_lib.PlanError, match="no staged path"): From 8f71d34a77e7db2cc7555c080259b024d137b11c Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 15 Nov 2026 14:23:38 -0500 Subject: [PATCH 5/6] Test that the Modal check stage refuses a county plan through the tool's parser (#922) Round-3 review P2: test_a_release_plan_cannot_pass_the_county_facts checked only the planned argv, so it still passed with the release tool's parse_function registration removed. The check stage would then run the tool with --help and return 0, skipping the county argument check. The test now runs the check stage's own _parse_check on this checkout with the planned state_county argv and asserts return code 2 and the "--soi-mode state_county needs --county-facts and --county-facts-sha256" refusal. With parse_function set to None the new assertion fails (return code 0), so the registration is pinned. - test_us_modal_stage_plan_tool.py (-n 4): 284 passed - ruff check and format on the file, ci_test_plan.py verify, git diff --check: pass Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_modal_stage_plan_tool.py | 23 +++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_plan_tool.py b/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_plan_tool.py index 573a829e0a..da7f975e67 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_plan_tool.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_modal_stage_plan_tool.py @@ -361,13 +361,15 @@ def test_no_option_maps_to_a_runner_owned_flag() -> None: ), (tool.name, key) -def test_a_release_plan_cannot_pass_the_county_facts() -> None: +def test_a_release_plan_cannot_pass_the_county_facts(app, monkeypatch) -> None: """microcosm#922: county materialize runs are local. No staged input or plan option of the release tool reaches ``--county-facts`` or ``--county-facts-sha256``, so a ``state_county`` - materialize plan builds an argv without them, which the tool's own argument - check (``county_surface._validate_county_facts``) refuses. + materialize plan builds an argv without them. The check stage hands that + argv to the tool's registered parser, whose own argument check + (``county_surface._validate_county_facts``) refuses it; without the + registration the check would only run ``--help`` and pass. """ tool = plan_lib.US_ACS_LOCAL_RELEASE @@ -383,10 +385,23 @@ def test_a_release_plan_cannot_pass_the_county_facts() -> None: "soi_mode": "state_county", "geographies": "state,cd,county", } - argv = plan_lib.planned_argv(plan_lib.parse_plan(data)) + plan = plan_lib.parse_plan(data) + argv = plan_lib.planned_argv(plan) assert argv[argv.index("--soi-mode") + 1] == "state_county" assert not [item for item in argv if item.startswith("--county-facts")] + # Run the check stage's parse in this checkout instead of the image. + local_argv = [sys.executable, *argv[1:]] + monkeypatch.setattr(app.plan_lib, "IMAGE_REPO_ROOT", str(ROOT)) + parse = app._parse_check( + plan, local_argv, dict(os.environ, PYTHONDONTWRITEBYTECODE="1") + ) + assert parse["returncode"] == 2, parse + assert ( + "--soi-mode state_county needs --county-facts and --county-facts-sha256" + in parse["stderr_tail"] + ), parse + def test_build_stage_argv_requires_every_staged_path() -> None: plan = plan_lib.parse_plan(_plan_data()) From c840353549cff7b194499d5138119a060ff3c049 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 16 Nov 2026 12:19:22 -0500 Subject: [PATCH 6/6] Test that the county pin moves with the next main feed pin (#922) The main Chronicle feed may stay at 41b2fb2, the commit it had when the county facts were pinned on their own. A change that re-pins it anywhere else must re-pin the county facts to the same commit, as docs/us-chronicle-feed-repin.md says, so a US build reads one Chronicle base. Asked for by the feed's owner as a condition of landing. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_chronicle_county_facts.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_chronicle_county_facts.py b/packages/microcosm-build/tests/engine_free/us/test_us_chronicle_county_facts.py index 320a6e7990..715846ac2a 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_chronicle_county_facts.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_chronicle_county_facts.py @@ -125,6 +125,28 @@ def test_the_county_pin_is_not_the_main_pin() -> None: assert county.scope_sha256 != main.scope_sha256 +#: The main feed pin's Chronicle commit when the county facts were pinned on +#: their own, at 3e9d3a0 (docs/us-chronicle-feed-repin.md). +_MAIN_PIN_WHEN_THE_COUNTY_PIN_SPLIT = "41b2fb2b864a28c0eda03322b77a97ef147dfa3c" + + +def test_the_county_pin_moves_with_the_next_main_pin() -> None: + """The two pins move together. The main feed may stay at the commit it + had when the county facts were pinned separately; once a change re-pins it + anywhere else, the same change re-pins the county facts to that commit, so + a US build reads one Chronicle base.""" + + main = load_us_chronicle_feed() + county = load_us_chronicle_county_facts_pin() + assert main.source_commit in ( + _MAIN_PIN_WHEN_THE_COUNTY_PIN_SPLIT, + county.source_commit, + ), ( + f"The main Chronicle feed pin moved to {main.source_commit}; re-pin the " + "county facts to the same commit in the same change." + ) + + def test_the_feed_builder_accepts_the_county_scope() -> None: scope = _builder().load_scope( _US_PACKAGE / US_CHRONICLE_COUNTY_FACTS_SCOPE_RESOURCE