diff --git a/changelog.d/us-sipp-person-file-read-once.changed.md b/changelog.d/us-sipp-person-file-read-once.changed.md new file mode 100644 index 0000000000..02039120e5 --- /dev/null +++ b/changelog.d/us-sipp-person-file-read-once.changed.md @@ -0,0 +1 @@ +The US fiscal-refresh release tool now parses the full SIPP 2023 person file once, checking its digest in that one read, and builds the financial-asset, SSI disability, Head Start, vehicle and voluntary-filing donor tables from that one read, instead of hashing and parsing the 3.73 GB file once per donor. The read tokenizes the file with `low_memory=True`, keeping only the columns the donors use, and then infers their types over each whole chunk, so it no longer holds the field positions of the file's thousands of unused columns for 100,000 rows at a time. The donor tables are unchanged; the vehicle and voluntary-filing donors refuse a column whose values their former `low_memory=True` parse could have converted differently. `read_sipp_december_person_rows` and one `build_sipp_2023_*_donor` function per donor replace the per-donor loaders that took a file path; `load_sipp_2023_ssi_disability_donor` remains for the ACS local-area build. diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index fe4f4a87e9..e8344d4b9b 100644 --- a/docs/evidence/spec-engine/us-f0-coverage.json +++ b/docs/evidence/spec-engine/us-f0-coverage.json @@ -1642,13 +1642,13 @@ "compiler_ir.node_slices" ], "expected": { - "map_sha256": "1dda5e09b93e4acd51844bfbd62555adfc91d309e0f7647d64b959e0820d1d1e", - "protocol_sha256": "90d566bb670521cc79f42cba8afe14fe79330ac2c990858dbe8f7debe1466fa5" + "map_sha256": "74aa4ed49e24b76e6126d440180a71553c767f0cc60156ddd183033fd8972505", + "protocol_sha256": "24bb621745b2b753c1f89843c90f29949c0ad764df4cdcd315afdbf9aa7f6403" }, "failures": [], "observed": { - "map_sha256": "1dda5e09b93e4acd51844bfbd62555adfc91d309e0f7647d64b959e0820d1d1e", - "protocol_sha256": "90d566bb670521cc79f42cba8afe14fe79330ac2c990858dbe8f7debe1466fa5" + "map_sha256": "74aa4ed49e24b76e6126d440180a71553c767f0cc60156ddd183033fd8972505", + "protocol_sha256": "24bb621745b2b753c1f89843c90f29949c0ad764df4cdcd315afdbf9aa7f6403" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "90d566bb670521cc79f42cba8afe14fe79330ac2c990858dbe8f7debe1466fa5", + "implementation_sha256": "24bb621745b2b753c1f89843c90f29949c0ad764df4cdcd315afdbf9aa7f6403", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "90d566bb670521cc79f42cba8afe14fe79330ac2c990858dbe8f7debe1466fa5", + "implementation_sha256": "24bb621745b2b753c1f89843c90f29949c0ad764df4cdcd315afdbf9aa7f6403", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "2e3093b6acc4926e80e96b080c3bfe2727baa22127ebfb9faf8a1ef05eda0f50" + "spec_sha256": "499389d4b1f0c967c54a6f2fa81b8a07a7e59c045bf2a8fe6bb909f08561d049" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "2e3093b6acc4926e80e96b080c3bfe2727baa22127ebfb9faf8a1ef05eda0f50" + "spec_sha256": "499389d4b1f0c967c54a6f2fa81b8a07a7e59c045bf2a8fe6bb909f08561d049" }, "status": "pass" } diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py index 008d68bf4e..52bdfc8b8e 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py @@ -411,8 +411,10 @@ # os.cpu_count() in microcosm.fit.qrf, moves both again; no draw changes. # calibrate's return_frame option in solve moves both again; the default # is unchanged, and no draw changes. - "seed_map": "1dda5e09b93e4acd51844bfbd62555adfc91d309e0f7647d64b959e0820d1d1e", - "seed_protocol": "90d566bb670521cc79f42cba8afe14fe79330ac2c990858dbe8f7debe1466fa5", + # microcosm#1686's shared SIPP person-file read moves both again: the five + # SIPP donor tables are byte-identical, and no draw changes. + "seed_map": "74aa4ed49e24b76e6126d440180a71553c767f0cc60156ddd183033fd8972505", + "seed_protocol": "24bb621745b2b753c1f89843c90f29949c0ad764df4cdcd315afdbf9aa7f6403", "source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6", "take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35", "tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0", diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/__init__.py b/packages/microcosm-build/src/microcosm/build/us_runtime/__init__.py index e0c5613bc3..214b659873 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/__init__.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/__init__.py @@ -831,6 +831,10 @@ us_scf_wealth_summary, with_us_scf_wealth_inputs, ) +from microcosm.build.us_runtime.sipp_december_person_rows import ( + SippDecemberPersonRows, + read_sipp_december_person_rows, +) from microcosm.build.us_runtime.sipp_financial_assets import ( SIPP_2023_FINANCIAL_ASSET_DONOR_REPOSITORY_ID_PARTS, SIPP_2023_FINANCIAL_ASSET_DONOR_REPOSITORY_TYPE, @@ -843,9 +847,9 @@ SIPP_FINANCIAL_ASSET_SOURCE_COLUMNS, SIPP_FINANCIAL_ASSET_TARGET_ALLOCATION_COLUMNS, SIPP_FINANCIAL_ASSET_TARGET_SOURCE_COLUMNS, + build_sipp_2023_financial_asset_donor, fetch_sipp_2023_financial_asset_donor, impute_us_sipp_financial_assets, - load_sipp_2023_financial_asset_donor, ) from microcosm.build.us_runtime.sipp_head_start import ( HEAD_START_SIPP_DICTIONARY_URL, @@ -861,9 +865,9 @@ US_SIPP_HEAD_START_OUTPUT_COLUMNS, US_SIPP_HEAD_START_REQUIRED_SOURCE_COLUMNS, US_SIPP_HEAD_START_STAGE_NAME, + build_sipp_2023_head_start_donor, fetch_sipp_2023_head_start_donor, impute_us_sipp_head_start, - load_sipp_2023_head_start_donor, us_sipp_head_start_signal_gate, us_sipp_head_start_stage_spec, us_sipp_head_start_summary, @@ -894,10 +898,11 @@ SIPP_2023_VEHICLE_DONOR_SHA256, SIPP_2023_VEHICLE_DONOR_SIZE_BYTES, SIPP_2023_VEHICLE_DONOR_URL, + SIPP_VEHICLE_SOURCE_COLUMNS, US_SIPP_VEHICLE_NONCONSTANT_HOUSEHOLD_COLUMNS, US_SIPP_VEHICLE_OUTPUT_COLUMNS, + build_sipp_2023_vehicle_donor, fetch_sipp_2023_vehicle_donor, - load_sipp_2023_vehicle_donor, us_sipp_vehicles_signal_gate, us_sipp_vehicles_stage_spec, us_sipp_vehicles_summary, @@ -992,6 +997,7 @@ US_SSI_DISABILITY_CRITERIA_NONCONSTANT_PERSON_COLUMNS, US_SSI_DISABILITY_CRITERIA_OUTPUT_COLUMNS, US_SSI_DISABILITY_CRITERIA_STAGE_NAME, + build_sipp_2023_ssi_disability_donor, fetch_sipp_2023_ssi_disability_donor, impute_us_ssi_disability_criteria, load_sipp_2023_ssi_disability_donor, @@ -1071,9 +1077,9 @@ VOLUNTARY_FILING_ARCHIVED_DERIVATION_URL, VOLUNTARY_FILING_ARCHIVED_PARAMETERS_URL, VOLUNTARY_FILING_SIPP_DICTIONARY_URL, + build_sipp_2023_voluntary_filing_donor, fetch_sipp_2023_voluntary_filing_donor, impute_us_voluntary_filing, - load_sipp_2023_voluntary_filing_donor, us_voluntary_filing_signal_gate, us_voluntary_filing_stage_spec, us_voluntary_filing_summary, @@ -1684,9 +1690,11 @@ "SIPP_FINANCIAL_ASSET_SOURCE_COLUMNS", "SIPP_FINANCIAL_ASSET_TARGET_ALLOCATION_COLUMNS", "SIPP_FINANCIAL_ASSET_TARGET_SOURCE_COLUMNS", + "SippDecemberPersonRows", + "read_sipp_december_person_rows", + "build_sipp_2023_financial_asset_donor", "fetch_sipp_2023_financial_asset_donor", "impute_us_sipp_financial_assets", - "load_sipp_2023_financial_asset_donor", "HEAD_START_SIPP_DICTIONARY_URL", "SIPP_2023_HEAD_START_DONOR_REVISION", "SIPP_2023_HEAD_START_DONOR_SHA256", @@ -1700,9 +1708,9 @@ "US_SIPP_HEAD_START_OUTPUT_COLUMNS", "US_SIPP_HEAD_START_REQUIRED_SOURCE_COLUMNS", "US_SIPP_HEAD_START_STAGE_NAME", + "build_sipp_2023_head_start_donor", "fetch_sipp_2023_head_start_donor", "impute_us_sipp_head_start", - "load_sipp_2023_head_start_donor", "us_sipp_head_start_signal_gate", "us_sipp_head_start_stage_spec", "us_sipp_head_start_summary", @@ -1724,6 +1732,7 @@ "US_SSI_DISABILITY_CRITERIA_NONCONSTANT_PERSON_COLUMNS", "US_SSI_DISABILITY_CRITERIA_OUTPUT_COLUMNS", "US_SSI_DISABILITY_CRITERIA_STAGE_NAME", + "build_sipp_2023_ssi_disability_donor", "fetch_sipp_2023_ssi_disability_donor", "impute_us_ssi_disability_criteria", "load_sipp_2023_ssi_disability_donor", @@ -1783,8 +1792,9 @@ "SIPP_2023_VEHICLE_DONOR_URL", "US_SIPP_VEHICLE_NONCONSTANT_HOUSEHOLD_COLUMNS", "US_SIPP_VEHICLE_OUTPUT_COLUMNS", + "SIPP_VEHICLE_SOURCE_COLUMNS", + "build_sipp_2023_vehicle_donor", "fetch_sipp_2023_vehicle_donor", - "load_sipp_2023_vehicle_donor", "us_sipp_vehicles_signal_gate", "us_sipp_vehicles_stage_spec", "us_sipp_vehicles_summary", @@ -1801,9 +1811,9 @@ "VOLUNTARY_FILING_ARCHIVED_DERIVATION_URL", "VOLUNTARY_FILING_ARCHIVED_PARAMETERS_URL", "VOLUNTARY_FILING_SIPP_DICTIONARY_URL", + "build_sipp_2023_voluntary_filing_donor", "fetch_sipp_2023_voluntary_filing_donor", "impute_us_voluntary_filing", - "load_sipp_2023_voluntary_filing_donor", "us_voluntary_filing_signal_gate", "us_voluntary_filing_stage_spec", "us_voluntary_filing_summary", diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/sipp_december_person_rows.py b/packages/microcosm-build/src/microcosm/build/us_runtime/sipp_december_person_rows.py new file mode 100644 index 0000000000..b80fc8f397 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/sipp_december_person_rows.py @@ -0,0 +1,286 @@ +"""Read the December rows of the full SIPP 2023 person-month file once. + +The financial-asset, SSI-disability, Head Start, vehicle and voluntary-filing +donor tables all start from the same 3.73 GB file of about 5,000 columns. A +``low_memory=False`` parse of that file holds the position of every field of a +100,000-row chunk, including the columns no donor reads. This read avoids that +cost and still gives each donor the table its own parse gave. For each chunk: + +1. The file is tokenized with ``low_memory=True``, keeping only the requested + columns, as unconverted text. +2. That text, now only the requested columns wide, is parsed with + ``low_memory=False``, so pandas infers each column's type from the whole chunk + with the same parser and the same tokens as a direct parse of the file. + +A file with a carriage return outside a ``\\r\\n`` pair is refused: pandas splits +such a file into different rows depending on how it is read. + +The donors' own parses differed in three ways, which the result keeps apart: + +* The financial-asset donor read ``SSUID`` as text, so ``"0123"`` and ``"123"`` + stay separate households. ``ssuid_text`` holds that form. +* The Head Start donor kept chunks without December rows when concatenating, so + their column types count towards the result's types. +* The vehicle and voluntary-filing donors parsed with ``low_memory=True``, which + converts a few hundred rows at a time and combines the results. For a column + inferred as ``int64`` or ``bool`` over the whole chunk, the blocks agree with + it. For a ``float64`` column they agree when every integer cell has at most + fifteen digits and none is a negative zero. Any other column is recorded, and + :meth:`SippDecemberPersonRows.source_table` refuses it to these two donors, + including cases where the blocks would in fact have agreed. +""" + +from __future__ import annotations + +import hashlib +import io +import re +from collections.abc import Iterable +from dataclasses import dataclass +from pathlib import Path + +import pandas as pd + +__all__ = [ + "SIPP_PERSON_FILE_CHUNK_ROWS", + "SippDecemberPersonRows", + "read_sipp_december_person_rows", +] + +# Rows per chunk. Column types are inferred per chunk, and the old per-donor +# loaders all read 100,000-row chunks, so the donor tables equal theirs only at +# this size. Changing it, for example to lower memory, can change inferred types. +SIPP_PERSON_FILE_CHUNK_ROWS = 100_000 + +_DELIMITER = "|" +_IDENTIFIER_COLUMN = "SSUID" +_MONTH_COLUMN = "MONTHCODE" +_DECEMBER = 12 +_SCAN_BLOCK_BYTES = 8 * 1024 * 1024 +_INTEGER_TOKEN = re.compile(r"\s*([+-]?)([0-9]+)\s*") +# Integers written with up to fifteen digits, leading zeros included, are exact +# in float64 by either conversion route. +_MAX_EXACT_INTEGER_DIGITS = 15 + + +@dataclass(frozen=True, eq=False) +class SippDecemberPersonRows: + """December person rows of one SIPP file, ready for the donor builders. + + ``rows`` holds the requested columns in file order, with types inferred per + chunk. ``ssuid_text`` holds the same rows' identifiers as written in the + file. ``december_parts_by_chunk`` is empty when every chunk had a December + row; otherwise it holds each chunk's December rows in file order, zero-row + tables included. Builders take their columns from :meth:`source_table`; + pandas' copy-on-write keeps their changes out of this object. + """ + + rows: pd.DataFrame + ssuid_text: pd.Series + december_parts_by_chunk: tuple[pd.DataFrame, ...] + columns_sensitive_to_parser_blocks: frozenset[str] + file_row_count: int + file_size_bytes: int + verified_sha256: str | None + verified_size_bytes: int | None + + def source_table( + self, + columns: Iterable[str], + *, + ssuid_as_text: bool = False, + read_in_parser_blocks: bool = False, + include_chunks_without_december_rows: bool = False, + ) -> pd.DataFrame: + """Return ``columns`` in file order, as one donor's own parse gave them. + + ``read_in_parser_blocks`` is for a donor that parsed with + ``low_memory=True``; it refuses a column whose values that parse could + have changed. ``include_chunks_without_december_rows`` lets those chunks' + column types count, as a donor that concatenated them did. + """ + + requested = set(columns) + missing = sorted(requested - set(self.rows.columns)) + if missing: + raise ValueError(f"SIPP December person rows lack column(s): {missing}.") + if read_in_parser_blocks: + sensitive = sorted(requested & self.columns_sensitive_to_parser_blocks) + if sensitive: + raise ValueError( + f"SIPP person file column(s) {sensitive} hold values that " + "low_memory parser blocks could convert differently, so this " + "read cannot reproduce them for this donor." + ) + table = self.rows.loc[ + :, [column for column in self.rows.columns if column in requested] + ] + if include_chunks_without_december_rows and self.december_parts_by_chunk: + table = pd.concat( + [part.loc[:, table.columns] for part in self.december_parts_by_chunk], + ignore_index=True, + ) + if ssuid_as_text: + table = table.assign(**{_IDENTIFIER_COLUMN: self.ssuid_text}) + return table + + +def _scan_file(path: Path) -> tuple[str, bool]: + """Return the file's SHA-256 and whether it has a bare carriage return.""" + + digest = hashlib.sha256() + has_bare_carriage_return = False + previous_block_ended_in_carriage_return = False + with path.open("rb") as stream: + while block := stream.read(_SCAN_BLOCK_BYTES): + digest.update(block) + ends_in_carriage_return = block.endswith(b"\r") + paired_carriage_returns = block.count(b"\r\n") + if ( + previous_block_ended_in_carriage_return and not block.startswith(b"\n") + ) or block.count(b"\r") != ( + paired_carriage_returns + ends_in_carriage_return + ): + has_bare_carriage_return = True + previous_block_ended_in_carriage_return = ends_in_carriage_return + return digest.hexdigest(), ( + has_bare_carriage_return or previous_block_ended_in_carriage_return + ) + + +def _converts_differently_in_parser_blocks(token: str) -> bool: + """Return whether an integer cell of a float column depends on its block. + + A block holding only integers is parsed as ``int64`` and then cast to + ``float64``, and an integer outside ``int64`` leaves its block unconverted; + the whole chunk goes straight through the float parser. + """ + + integer = _INTEGER_TOKEN.fullmatch(token) + if integer is None: + return False + sign, digits = integer.groups() + is_negative_zero = sign == "-" and not digits.strip("0") + return is_negative_zero or len(digits) > _MAX_EXACT_INTEGER_DIGITS + + +def _columns_sensitive_to_parser_blocks( + cell_text: pd.DataFrame, + parsed: pd.DataFrame, +) -> set[str]: + """Return columns a ``low_memory=True`` parse of this chunk could change.""" + + sensitive: set[str] = set() + for column in parsed.columns: + dtype = parsed[column].dtype + if dtype == "int64" or pd.api.types.is_bool_dtype(dtype): + continue + if dtype != "float64" or any( + _converts_differently_in_parser_blocks(token) + for token in cell_text[column].dropna().unique() + ): + sensitive.add(column) + return sensitive + + +def read_sipp_december_person_rows( + path: str | Path, + *, + columns: Iterable[str], + expected_sha256: str | None = None, + expected_size_bytes: int | None = None, + chunksize: int = SIPP_PERSON_FILE_CHUNK_ROWS, +) -> SippDecemberPersonRows: + """Verify the file, then read it once and keep its December rows.""" + + source_path = Path(path) + file_size_bytes = source_path.stat().st_size + if expected_size_bytes is not None and file_size_bytes != expected_size_bytes: + raise ValueError( + "SIPP person file failed byte-length verification: " + f"expected {expected_size_bytes}, got {file_size_bytes}." + ) + actual_sha256, has_bare_carriage_return = _scan_file(source_path) + if expected_sha256 is not None and actual_sha256 != expected_sha256: + raise ValueError( + "SIPP person file failed sha-256 verification: " + f"expected {expected_sha256}, got {actual_sha256}." + ) + if has_bare_carriage_return: + raise ValueError( + "SIPP person file has a carriage return outside a CRLF pair, so its " + "rows depend on how it is parsed." + ) + if chunksize < 1: + raise ValueError("chunksize must be a positive integer") + + requested_columns = tuple(columns) + first_row = pd.read_csv(source_path, delimiter=_DELIMITER, nrows=1) + missing = sorted(set(requested_columns) - set(first_row.columns)) + if missing: + raise ValueError(f"SIPP person file missing column(s): {missing}.") + # pandas turns a first field beyond the header into an index and shifts the + # columns, but only when some header column is left unread. + if not isinstance(first_row.index, pd.RangeIndex): + raise ValueError("SIPP person file's first row is longer than its header.") + + december_parts: list[pd.DataFrame] = [] + ssuid_text_parts: list[pd.Series] = [] + columns_sensitive_to_parser_blocks: set[str] = set() + file_row_count = 0 + with pd.read_csv( + source_path, + delimiter=_DELIMITER, + usecols=list(requested_columns), + chunksize=int(chunksize), + dtype=object, + na_filter=False, + low_memory=True, + ) as chunks: + for cell_text in chunks: + if cell_text.empty: + continue + file_row_count += len(cell_text) + # The index column keeps data cells off the start of each row, where + # the parser can drop whitespace that ends its read buffer. + requested_csv = cell_text.to_csv(sep=_DELIMITER).encode() + parsed = pd.read_csv( + io.BytesIO(requested_csv), + delimiter=_DELIMITER, + index_col=0, + low_memory=False, + ).reset_index(drop=True) + columns_sensitive_to_parser_blocks |= _columns_sensitive_to_parser_blocks( + cell_text, + parsed, + ) + month = pd.to_numeric(parsed[_MONTH_COLUMN], errors="coerce") + is_december = month.eq(_DECEMBER) + december_parts.append(parsed.loc[is_december]) + if not is_december.any(): + continue + ssuid_text = pd.read_csv( + io.BytesIO(requested_csv), + delimiter=_DELIMITER, + usecols=[_IDENTIFIER_COLUMN], + dtype={_IDENTIFIER_COLUMN: "string"}, + low_memory=False, + )[_IDENTIFIER_COLUMN] + ssuid_text_parts.append(ssuid_text[is_december]) + if not ssuid_text_parts: + raise ValueError("SIPP person file has no December rows.") + parts_with_rows = [part for part in december_parts if not part.empty] + return SippDecemberPersonRows( + rows=pd.concat(parts_with_rows, ignore_index=True), + ssuid_text=pd.concat(ssuid_text_parts, ignore_index=True), + december_parts_by_chunk=( + tuple(december_parts) if len(parts_with_rows) < len(december_parts) else () + ), + columns_sensitive_to_parser_blocks=frozenset( + columns_sensitive_to_parser_blocks + ), + file_row_count=file_row_count, + file_size_bytes=file_size_bytes, + verified_sha256=expected_sha256, + verified_size_bytes=expected_size_bytes, + ) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/sipp_financial_assets.py b/packages/microcosm-build/src/microcosm/build/us_runtime/sipp_financial_assets.py index fd3583f015..47cb2a401f 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/sipp_financial_assets.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/sipp_financial_assets.py @@ -37,6 +37,10 @@ import numpy as np import pandas as pd +from microcosm.build.us_runtime.sipp_december_person_rows import ( + SippDecemberPersonRows, +) + __all__ = [ "SIPP_2023_FINANCIAL_ASSET_DONOR_REVISION", "SIPP_2023_FINANCIAL_ASSET_DONOR_REPOSITORY_ID_PARTS", @@ -49,9 +53,9 @@ "SIPP_FINANCIAL_ASSET_SOURCE_COLUMNS", "SIPP_FINANCIAL_ASSET_TARGET_ALLOCATION_COLUMNS", "SIPP_FINANCIAL_ASSET_TARGET_SOURCE_COLUMNS", + "build_sipp_2023_financial_asset_donor", "fetch_sipp_2023_financial_asset_donor", "impute_us_sipp_financial_assets", - "load_sipp_2023_financial_asset_donor", ] SIPP_2023_FINANCIAL_ASSET_DONOR_REPOSITORY_ID_PARTS = ( @@ -384,56 +388,17 @@ def _target_balanced_cap( return donor.iloc[np.asarray(selected, dtype=int)].copy().reset_index(drop=True) -def load_sipp_2023_financial_asset_donor( - path: str | Path, +def build_sipp_2023_financial_asset_donor( + person_rows: SippDecemberPersonRows, *, - expected_sha256: str | None = None, - expected_size_bytes: int | None = None, - chunksize: int = 100_000, max_train_samples: int | None = _MAX_TRAIN_SAMPLES, ) -> pd.DataFrame: - """Load the exact December SIPP asset-QRF donor surface from ``pu2023``.""" + """Build the exact December SIPP asset-QRF donor surface from ``pu2023``.""" - source_path = Path(path) - if ( - expected_size_bytes is not None - and source_path.stat().st_size != expected_size_bytes - ): - raise ValueError( - "SIPP 2023 financial-asset donor failed byte-length verification: " - f"expected {expected_size_bytes}, got {source_path.stat().st_size}." - ) - if expected_sha256 is not None: - actual_sha256 = _sha256_file(source_path) - if actual_sha256 != expected_sha256: - raise ValueError( - "SIPP 2023 financial-asset donor failed sha-256 verification: " - f"expected {expected_sha256}, got {actual_sha256}." - ) - if chunksize < 1: - raise ValueError("chunksize must be a positive integer") - - header = pd.read_csv(source_path, delimiter="|", nrows=0) - missing = sorted(set(SIPP_FINANCIAL_ASSET_SOURCE_COLUMNS) - set(header.columns)) - if missing: - raise ValueError(f"SIPP financial-asset donor missing column(s): {missing}.") - - parts: list[pd.DataFrame] = [] - for chunk in pd.read_csv( - source_path, - delimiter="|", - usecols=list(SIPP_FINANCIAL_ASSET_SOURCE_COLUMNS), - chunksize=int(chunksize), - dtype={"SSUID": "string"}, - low_memory=False, - ): - month = pd.to_numeric(chunk["MONTHCODE"], errors="coerce") - december = chunk.loc[month.eq(12)].copy() - if not december.empty: - parts.append(december) - if not parts: - raise ValueError("SIPP financial-asset donor has no December rows.") - raw = pd.concat(parts, ignore_index=True) + raw = person_rows.source_table( + SIPP_FINANCIAL_ASSET_SOURCE_COLUMNS, + ssuid_as_text=True, + ) for column in SIPP_FINANCIAL_ASSET_SOURCE_COLUMNS: if column == "SSUID": diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/sipp_head_start.py b/packages/microcosm-build/src/microcosm/build/us_runtime/sipp_head_start.py index 0708b27ae2..e2c574c7d1 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/sipp_head_start.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/sipp_head_start.py @@ -27,13 +27,16 @@ from importlib.resources import files from pathlib import Path -from typing import Any, BinaryIO +from typing import Any import numpy as np import pandas as pd from microcosm.build.gates import GateResult from microcosm.build.source_manifest import SourceStageSpec, load_source_manifest +from microcosm.build.us_runtime.sipp_december_person_rows import ( + SippDecemberPersonRows, +) from microcosm.build.us_runtime.support_provenance import ( has_support_role_metadata, require_assembled_support_provenance, @@ -64,9 +67,9 @@ "US_SIPP_HEAD_START_OUTPUT_COLUMNS", "US_SIPP_HEAD_START_REQUIRED_SOURCE_COLUMNS", "US_SIPP_HEAD_START_STAGE_NAME", + "build_sipp_2023_head_start_donor", "fetch_sipp_2023_head_start_donor", "impute_us_sipp_head_start", - "load_sipp_2023_head_start_donor", "us_sipp_head_start_signal_gate", "us_sipp_head_start_stage_spec", "us_sipp_head_start_summary", @@ -224,20 +227,6 @@ def us_sipp_head_start_stage_spec() -> SourceStageSpec: return spec -def _sha256_stream(stream: BinaryIO, *, chunk_size: int = 8 * 1024 * 1024) -> str: - import hashlib - - digest = hashlib.sha256() - for chunk in iter(lambda: stream.read(chunk_size), b""): - digest.update(chunk) - return digest.hexdigest() - - -def _sha256_file(path: Path) -> str: - with path.open("rb") as stream: - return _sha256_stream(stream) - - def fetch_sipp_2023_head_start_donor( cache_dir: str | Path | None = None, *, @@ -308,54 +297,15 @@ def _assert_pinned_audit(audit: dict[str, int | float]) -> None: ) -def load_sipp_2023_head_start_donor( - path: str | Path, - *, - expected_sha256: str | None = SIPP_2023_HEAD_START_DONOR_SHA256, - expected_size_bytes: int | None = SIPP_2023_HEAD_START_DONOR_SIZE_BYTES, - chunksize: int = 100_000, +def build_sipp_2023_head_start_donor( + person_rows: SippDecemberPersonRows, ) -> pd.DataFrame: - """Load strict December age-3--5 labels from the pinned full SIPP file.""" - - source_path = Path(path).expanduser() - if not source_path.is_file(): - raise FileNotFoundError(source_path) - if chunksize < 1: - raise ValueError("chunksize must be positive") - if ( - expected_size_bytes is not None - and source_path.stat().st_size != expected_size_bytes - ): - raise ValueError( - "SIPP Head Start donor byte length does not match the pinned artifact." - ) - if expected_sha256 is not None: - digest = _sha256_file(source_path) - if digest != expected_sha256: - raise ValueError( - "SIPP Head Start donor SHA-256 does not match the pinned artifact." - ) + """Build strict December age-3--5 labels from the full SIPP file's rows.""" - header = pd.read_csv(source_path, sep="|", nrows=0) - missing = sorted(set(SIPP_HEAD_START_SOURCE_COLUMNS) - set(header.columns)) - if missing: - raise ValueError(f"SIPP Head Start donor missing source column(s): {missing}.") - - december_parts: list[pd.DataFrame] = [] - raw_rows = 0 - for chunk in pd.read_csv( - source_path, - sep="|", - usecols=list(SIPP_HEAD_START_SOURCE_COLUMNS), - chunksize=chunksize, - low_memory=False, - ): - raw_rows += len(chunk) - month = pd.to_numeric(chunk["MONTHCODE"], errors="coerce") - december_parts.append(chunk.loc[month.eq(12)].copy()) - december = pd.concat(december_parts, ignore_index=True) - if december.empty: - raise ValueError("SIPP Head Start donor contains no December rows.") + december = person_rows.source_table( + SIPP_HEAD_START_SOURCE_COLUMNS, + include_chunks_without_december_rows=True, + ) if december[["SSUID", "PNUM"]].isna().any(axis=None): raise ValueError("SIPP Head Start December identity contains missing values.") if december.duplicated(["SSUID", "PNUM"]).any(): @@ -447,7 +397,7 @@ def load_sipp_2023_head_start_donor( positive_weight = float(donor.loc[donor[_OUTPUT], _DONOR_WEIGHT_COLUMN].sum()) weight_sum = float(donor[_DONOR_WEIGHT_COLUMN].sum()) audit: dict[str, int | float] = { - "raw_rows": raw_rows, + "raw_rows": person_rows.file_row_count, "december_rows": len(december), "age_domain_rows": int(np.count_nonzero(in_age_domain)), "training_rows": len(donor), @@ -461,8 +411,8 @@ def load_sipp_2023_head_start_donor( "weighted_true_share": positive_weight / weight_sum, } pinned_transform = bool( - expected_sha256 == SIPP_2023_HEAD_START_DONOR_SHA256 - and expected_size_bytes == SIPP_2023_HEAD_START_DONOR_SIZE_BYTES + person_rows.verified_sha256 == SIPP_2023_HEAD_START_DONOR_SHA256 + and person_rows.verified_size_bytes == SIPP_2023_HEAD_START_DONOR_SIZE_BYTES ) if pinned_transform: _assert_pinned_audit(audit) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/sipp_vehicles.py b/packages/microcosm-build/src/microcosm/build/us_runtime/sipp_vehicles.py index 7a5fdd9aea..029e6bd58d 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/sipp_vehicles.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/sipp_vehicles.py @@ -35,6 +35,9 @@ from microcosm.build.gates import GateResult from microcosm.build.source_manifest import SourceStageSpec, load_source_manifest +from microcosm.build.us_runtime.sipp_december_person_rows import ( + SippDecemberPersonRows, +) from microcosm.frame import Frame from microcosm.frame.units import US_SCHEMA @@ -51,9 +54,9 @@ "SIPP_VEHICLE_SOURCE_COLUMNS", "US_SIPP_VEHICLE_NONCONSTANT_HOUSEHOLD_COLUMNS", "US_SIPP_VEHICLE_OUTPUT_COLUMNS", + "build_sipp_2023_vehicle_donor", "fetch_sipp_2023_vehicle_donor", "impute_us_sipp_vehicles", - "load_sipp_2023_vehicle_donor", "us_sipp_vehicles_signal_gate", "us_sipp_vehicles_stage_spec", "us_sipp_vehicles_summary", @@ -365,52 +368,15 @@ def _cap_vehicle_training_sample(donor: pd.DataFrame) -> pd.DataFrame: return donor.iloc[positions].copy().reset_index(drop=True) -def load_sipp_2023_vehicle_donor( - path: str | Path, - *, - expected_sha256: str | None = None, - expected_size_bytes: int | None = SIPP_2023_VEHICLE_DONOR_SIZE_BYTES, - chunksize: int = 100_000, +def build_sipp_2023_vehicle_donor( + person_rows: SippDecemberPersonRows, ) -> pd.DataFrame: - """Load and transform the pinned person-month file to household donors.""" - - path = Path(path) - if expected_size_bytes is not None and path.stat().st_size != expected_size_bytes: - raise ValueError( - "SIPP 2023 vehicle donor failed byte-length verification: " - f"expected {expected_size_bytes}, got {path.stat().st_size}." - ) - if expected_sha256 is not None: - actual_sha256 = _sha256_file(path) - if actual_sha256 != expected_sha256: - raise ValueError( - "SIPP 2023 vehicle donor failed sha-256 verification: " - f"expected {expected_sha256}, got {actual_sha256}." - ) - if chunksize < 1: - raise ValueError("chunksize must be a positive integer") + """Transform the person-month file's December rows to household donors.""" - header = pd.read_csv(path, delimiter="|", nrows=0) - missing = sorted(set(SIPP_VEHICLE_SOURCE_COLUMNS) - set(header.columns)) - if missing: - raise ValueError(f"SIPP 2023 vehicle donor missing column(s): {missing}.") - - december_parts: list[pd.DataFrame] = [] - reader = pd.read_csv( - path, - delimiter="|", - usecols=list(SIPP_VEHICLE_SOURCE_COLUMNS), - chunksize=int(chunksize), - low_memory=True, + person = person_rows.source_table( + SIPP_VEHICLE_SOURCE_COLUMNS, + read_in_parser_blocks=True, ) - for chunk in reader: - month = pd.to_numeric(chunk["MONTHCODE"], errors="coerce") - december = chunk.loc[month.eq(12)].copy() - if not december.empty: - december_parts.append(december) - if not december_parts: - raise ValueError("SIPP 2023 vehicle donor has no December person records.") - person = pd.concat(december_parts, ignore_index=True) for column in SIPP_VEHICLE_SOURCE_COLUMNS: if column != "SSUID": diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/ssi_disability_criteria.py b/packages/microcosm-build/src/microcosm/build/us_runtime/ssi_disability_criteria.py index 681b61c793..1a9027bdf4 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/ssi_disability_criteria.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/ssi_disability_criteria.py @@ -44,6 +44,11 @@ from microcosm.build.gates import GateResult from microcosm.build.source_manifest import SourceStageSpec, load_source_manifest +from microcosm.build.us_runtime.sipp_december_person_rows import ( + SIPP_PERSON_FILE_CHUNK_ROWS, + SippDecemberPersonRows, + read_sipp_december_person_rows, +) from microcosm.build.us_runtime.support_provenance import ( has_support_role_metadata, support_clone_index_column, @@ -77,6 +82,7 @@ "US_SSI_DISABILITY_CRITERIA_NONCONSTANT_PERSON_COLUMNS", "US_SSI_DISABILITY_CRITERIA_OUTPUT_COLUMNS", "US_SSI_DISABILITY_CRITERIA_STAGE_NAME", + "build_sipp_2023_ssi_disability_donor", "fetch_sipp_2023_ssi_disability_donor", "impute_us_ssi_disability_criteria", "load_sipp_2023_ssi_disability_donor", @@ -353,16 +359,6 @@ def us_ssi_disability_criteria_stage_spec() -> SourceStageSpec: return spec -def _sha256_file(path: Path) -> str: - import hashlib - - digest = hashlib.sha256() - with path.open("rb") as stream: - for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): - digest.update(chunk) - return digest.hexdigest() - - def fetch_sipp_2023_ssi_disability_donor( cache_dir: str | Path | None = None, *, @@ -524,48 +520,31 @@ def load_sipp_2023_ssi_disability_donor( *, expected_sha256: str | None = None, expected_size_bytes: int | None = SIPP_2023_SSI_DISABILITY_DONOR_SIZE_BYTES, - chunksize: int = 100_000, + chunksize: int = SIPP_PERSON_FILE_CHUNK_ROWS, time_period: int = 2024, ) -> pd.DataFrame: - """Build the exact observed/candidate SIPP SSI disability training frame.""" + """Read the SIPP file and build the SSI disability training frame from it.""" + + return build_sipp_2023_ssi_disability_donor( + read_sipp_december_person_rows( + path, + columns=SIPP_SSI_DISABILITY_SOURCE_COLUMNS, + expected_sha256=expected_sha256, + expected_size_bytes=expected_size_bytes, + chunksize=chunksize, + ), + time_period=time_period, + ) - source_path = Path(path) - actual_size = source_path.stat().st_size - if expected_size_bytes is not None and actual_size != expected_size_bytes: - raise ValueError( - "SIPP 2023 SSI disability donor failed byte-length verification: " - f"expected {expected_size_bytes}, got {actual_size}." - ) - if expected_sha256 is not None: - actual_sha256 = _sha256_file(source_path) - if actual_sha256 != expected_sha256: - raise ValueError( - "SIPP 2023 SSI disability donor failed sha-256 verification: " - f"expected {expected_sha256}, got {actual_sha256}." - ) - if chunksize < 1: - raise ValueError("chunksize must be a positive integer") - header = pd.read_csv(source_path, delimiter="|", nrows=0) - missing = sorted(set(SIPP_SSI_DISABILITY_SOURCE_COLUMNS) - set(header.columns)) - if missing: - raise ValueError(f"SIPP SSI disability donor missing column(s): {missing}.") +def build_sipp_2023_ssi_disability_donor( + person_rows: SippDecemberPersonRows, + *, + time_period: int = 2024, +) -> pd.DataFrame: + """Build the exact observed/candidate SIPP SSI disability training frame.""" - parts: list[pd.DataFrame] = [] - for chunk in pd.read_csv( - source_path, - delimiter="|", - usecols=list(SIPP_SSI_DISABILITY_SOURCE_COLUMNS), - chunksize=int(chunksize), - low_memory=False, - ): - month = _numeric(chunk["MONTHCODE"]) - december = chunk.loc[month.eq(12.0)].copy() - if not december.empty: - parts.append(december) - if not parts: - raise ValueError("SIPP SSI disability donor has no December rows.") - frame = pd.concat(parts, ignore_index=True) + frame = person_rows.source_table(SIPP_SSI_DISABILITY_SOURCE_COLUMNS) for column in SIPP_SSI_DISABILITY_SOURCE_COLUMNS: if column == "SSUID": @@ -685,7 +664,7 @@ def load_sipp_2023_ssi_disability_donor( "time_period": int(time_period), } pinned_transform = ( - actual_size == SIPP_2023_SSI_DISABILITY_DONOR_SIZE_BYTES + person_rows.file_size_bytes == SIPP_2023_SSI_DISABILITY_DONOR_SIZE_BYTES and int(time_period) == 2024 ) audit["pinned_transform"] = pinned_transform diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/voluntary_filing.py b/packages/microcosm-build/src/microcosm/build/us_runtime/voluntary_filing.py index e15ea5702d..8940d96ff7 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/voluntary_filing.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/voluntary_filing.py @@ -37,6 +37,9 @@ from microcosm.build.gates import GateResult from microcosm.build.source_manifest import SourceStageSpec, load_source_manifest +from microcosm.build.us_runtime.sipp_december_person_rows import ( + SippDecemberPersonRows, +) from microcosm.build.us_runtime.support_provenance import ( has_support_role_metadata, require_assembled_support_provenance, @@ -60,9 +63,9 @@ "VOLUNTARY_FILING_ARCHIVED_DERIVATION_URL", "VOLUNTARY_FILING_ARCHIVED_PARAMETERS_URL", "VOLUNTARY_FILING_SIPP_DICTIONARY_URL", + "build_sipp_2023_voluntary_filing_donor", "fetch_sipp_2023_voluntary_filing_donor", "impute_us_voluntary_filing", - "load_sipp_2023_voluntary_filing_donor", "us_voluntary_filing_signal_gate", "us_voluntary_filing_stage_spec", "us_voluntary_filing_summary", @@ -349,54 +352,15 @@ def _source_unit_keys(december: pd.DataFrame) -> pd.Series: return pd.Series(keys, index=december.index, dtype="string") -def load_sipp_2023_voluntary_filing_donor( - path: str | Path, - *, - expected_sha256: str | None = None, - expected_size_bytes: int | None = SIPP_2023_VOLUNTARY_FILING_DONOR_SIZE_BYTES, - chunksize: int = 100_000, +def build_sipp_2023_voluntary_filing_donor( + person_rows: SippDecemberPersonRows, ) -> pd.DataFrame: - """Transform the pinned SIPP person file to measured filing tax units.""" - - path = Path(path) - if expected_size_bytes is not None and path.stat().st_size != expected_size_bytes: - raise ValueError( - "SIPP 2023 voluntary-filing donor failed byte-length verification: " - f"expected {expected_size_bytes}, got {path.stat().st_size}." - ) - if expected_sha256 is not None: - actual_sha256 = _sha256_file(path) - if actual_sha256 != expected_sha256: - raise ValueError( - "SIPP 2023 voluntary-filing donor failed sha-256 verification: " - f"expected {expected_sha256}, got {actual_sha256}." - ) - if chunksize < 1: - raise ValueError("chunksize must be a positive integer") - - header = pd.read_csv(path, delimiter="|", nrows=0) - missing = sorted(set(SIPP_VOLUNTARY_FILING_SOURCE_COLUMNS) - set(header.columns)) - if missing: - raise ValueError( - f"SIPP 2023 voluntary-filing donor missing column(s): {missing}." - ) + """Transform the SIPP person file's December rows to filing tax units.""" - parts: list[pd.DataFrame] = [] - reader = pd.read_csv( - path, - delimiter="|", - usecols=list(SIPP_VOLUNTARY_FILING_SOURCE_COLUMNS), - chunksize=int(chunksize), - low_memory=True, + december = person_rows.source_table( + SIPP_VOLUNTARY_FILING_SOURCE_COLUMNS, + read_in_parser_blocks=True, ) - for chunk in reader: - month = _numeric(chunk["MONTHCODE"]) - december = chunk.loc[month.eq(12)].copy() - if not december.empty: - parts.append(december) - if not parts: - raise ValueError("SIPP 2023 voluntary-filing donor has no December rows.") - december = pd.concat(parts, ignore_index=True) numeric_columns = [ column for column in SIPP_VOLUNTARY_FILING_SOURCE_COLUMNS if column != "SSUID" diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py index 96ff29382e..403ae2d6a4 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py @@ -38,8 +38,9 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # The QRF draw's default thread count, joblib.cpu_count() in # microcosm.fit.qrf, moves the fit kernels' bytes again. # calibrate's return_frame option in solve moves it again. + # microcosm#1686's shared SIPP person-file read moves it again. assert first.spec_sha256 == ( - "6ba1402eced96554e5d31781bf5a24b77d8b5421324d2da374b3806913a5d9bd" + "c0431e2baa14c8fcc5fb3475f8cca5391d3c87c814f84f4256a7710b942b8c0b" ) second_root = _rich_minimal(tmp_path / "xy", note="second", store="local:b") diff --git a/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py b/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py index 7133755f4b..450512f6c5 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py @@ -158,6 +158,9 @@ # microcosm#1585 item 11: us_runtime.multispine_pool's shadow sites # import us_runtime.gate_shadow. "microcosm.build.us_runtime.gate_shadow", + # microcosm#1686: the five SIPP donor modules import the shared read + # of the SIPP person file. + "microcosm.build.us_runtime.sipp_december_person_rows", # microcosm#1405: the gate battery refuses a signing key the committed # registry does not let sign, so it imports # microcosm.data.gate_signing_keys, and with it the microcosm.data diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py index b021c82fc8..5611c05447 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py @@ -8,6 +8,7 @@ import shlex import subprocess import sys +import weakref from dataclasses import replace from datetime import UTC, datetime from pathlib import Path @@ -3287,6 +3288,22 @@ def test_frozen_support_selection_is_followed_by_weeks_unemployed_regate() -> No assert "Post-selection weeks-unemployed input signal failed" in source +def test_sipp_person_file_read_covers_every_donor_table_column() -> None: + builder = _load_builder_module() + + columns = builder._SIPP_2023_DONOR_SOURCE_COLUMNS + + assert len(columns) == len(set(columns)) + for donor_columns in ( + builder.SIPP_FINANCIAL_ASSET_SOURCE_COLUMNS, + builder.SIPP_SSI_DISABILITY_SOURCE_COLUMNS, + builder.SIPP_HEAD_START_SOURCE_COLUMNS, + builder.SIPP_VEHICLE_SOURCE_COLUMNS, + builder.SIPP_VOLUNTARY_FILING_SOURCE_COLUMNS, + ): + assert set(donor_columns) <= set(columns) + + def test_sipp_vehicle_donor_override_parses(monkeypatch) -> None: builder = _load_builder_module() monkeypatch.setattr( @@ -8990,16 +9007,40 @@ def fake_join_acs_release_predictors(frame, **kwargs): lambda path: pd.DataFrame(), ) - def fake_load_sipp_financial_asset_donor( + class FakeSippDecemberPersonRows: + pass + + def fake_read_sipp_december_person_rows( path, *, + columns, expected_sha256=None, expected_size_bytes=None, ): - captured["sipp_financial_asset_donor_path"] = path - captured["sipp_financial_asset_donor_sha256"] = expected_sha256 - captured["sipp_financial_asset_donor_size_bytes"] = expected_size_bytes - return pd.DataFrame() + captured.setdefault("sipp_person_file_reads", []).append( + { + "path": path, + "columns": tuple(columns), + "sha256": expected_sha256, + "size_bytes": expected_size_bytes, + } + ) + person_rows = FakeSippDecemberPersonRows() + captured["sipp_person_rows_reference"] = weakref.ref(person_rows) + return person_rows + + def fake_sipp_donor_builder(donor_name): + def build_donor(person_rows, **options): + captured.setdefault("sipp_donor_builds", []).append( + ( + donor_name, + person_rows is captured["sipp_person_rows_reference"](), + options, + ) + ) + return pd.DataFrame() + + return build_donor monkeypatch.setattr( builder, @@ -9008,9 +9049,21 @@ def fake_load_sipp_financial_asset_donor( ) monkeypatch.setattr( builder, - "load_sipp_2023_financial_asset_donor", - fake_load_sipp_financial_asset_donor, - ) + "read_sipp_december_person_rows", + fake_read_sipp_december_person_rows, + ) + for builder_name, donor_name in ( + ("build_sipp_2023_financial_asset_donor", "financial_assets"), + ("build_sipp_2023_ssi_disability_donor", "ssi_disability"), + ("build_sipp_2023_head_start_donor", "head_start"), + ("build_sipp_2023_vehicle_donor", "vehicles"), + ("build_sipp_2023_voluntary_filing_donor", "voluntary_filing"), + ): + monkeypatch.setattr( + builder, + builder_name, + fake_sipp_donor_builder(donor_name), + ) def fake_with_scf_wealth_inputs( frame, *, seed, time_period, scf_donor, sipp_donor=None @@ -9075,17 +9128,6 @@ def fake_with_scf_auto_loan_inputs( ), ) - def fake_load_sipp_vehicle_donor( - path, - *, - expected_sha256=None, - expected_size_bytes=None, - ): - captured["sipp_vehicle_donor_path"] = path - captured["sipp_vehicle_donor_sha256"] = expected_sha256 - captured["sipp_vehicle_donor_size_bytes"] = expected_size_bytes - return pd.DataFrame() - def fake_with_sipp_vehicle_inputs(frame, *, seed, time_period, sipp_donor): captured["sipp_vehicle_stage_called"] = True captured["sipp_vehicle_seed"] = seed @@ -9099,11 +9141,6 @@ def fake_sipp_vehicles_signal_gate(frame): details={"checked": True}, ) - monkeypatch.setattr( - builder, - "load_sipp_2023_vehicle_donor", - fake_load_sipp_vehicle_donor, - ) monkeypatch.setattr( builder, "with_us_sipp_vehicle_inputs", @@ -9115,19 +9152,6 @@ def fake_sipp_vehicles_signal_gate(frame): fake_sipp_vehicles_signal_gate, ) - def fake_load_ssi_disability_donor( - path, - *, - expected_sha256=None, - expected_size_bytes=None, - time_period=2024, - ): - captured["ssi_disability_donor_path"] = path - captured["ssi_disability_donor_sha256"] = expected_sha256 - captured["ssi_disability_donor_size_bytes"] = expected_size_bytes - captured["ssi_disability_donor_period"] = time_period - return pd.DataFrame() - def fake_with_ssi_disability_criteria(frame, *, seed, time_period, sipp_donor): captured["ssi_disability_stage_called"] = True captured["ssi_disability_seed"] = seed @@ -9141,11 +9165,6 @@ def fake_ssi_disability_signal_gate(frame): details={"checked": True}, ) - monkeypatch.setattr( - builder, - "load_sipp_2023_ssi_disability_donor", - fake_load_ssi_disability_donor, - ) monkeypatch.setattr( builder, "with_us_ssi_disability_criteria", @@ -9157,17 +9176,6 @@ def fake_ssi_disability_signal_gate(frame): fake_ssi_disability_signal_gate, ) - def fake_load_sipp_head_start_donor( - path, - *, - expected_sha256=None, - expected_size_bytes=None, - ): - captured["sipp_head_start_donor_path"] = path - captured["sipp_head_start_donor_sha256"] = expected_sha256 - captured["sipp_head_start_donor_size_bytes"] = expected_size_bytes - return pd.DataFrame() - def fake_with_sipp_head_start_input( frame, *, @@ -9189,11 +9197,6 @@ def fake_sipp_head_start_signal_gate(frame): details={"checked": True}, ) - monkeypatch.setattr( - builder, - "load_sipp_2023_head_start_donor", - fake_load_sipp_head_start_donor, - ) monkeypatch.setattr( builder, "with_us_sipp_head_start_input", @@ -9304,17 +9307,6 @@ def fake_ssi_take_up_gate(diagnostics, *, targets): lambda frame, *, assignment_priors, prior_basis: "ssi-digest-sentinel", ) - def fake_load_voluntary_filing_donor( - path, - *, - expected_sha256=None, - expected_size_bytes=None, - ): - captured["voluntary_filing_donor_path"] = path - captured["voluntary_filing_donor_sha256"] = expected_sha256 - captured["voluntary_filing_donor_size_bytes"] = expected_size_bytes - return pd.DataFrame() - def fake_with_voluntary_filing_input(frame, *, seed, time_period, sipp_donor): captured["voluntary_filing_stage_called"] = True captured["voluntary_filing_seed"] = seed @@ -9328,11 +9320,6 @@ def fake_voluntary_filing_signal_gate(frame): details={"checked": True}, ) - monkeypatch.setattr( - builder, - "load_sipp_2023_voluntary_filing_donor", - fake_load_voluntary_filing_donor, - ) monkeypatch.setattr( builder, "with_us_voluntary_filing_input", @@ -9356,6 +9343,9 @@ def fake_load_sipp_tip_donor(path, *, expected_sha256=None): def fake_with_sipp_tip_inputs(frame, *, seed, time_period, sipp_donor): captured["sipp_tip_stage_called"] = True + captured["sipp_person_rows_alive_at_tip_stage"] = ( + captured["sipp_person_rows_reference"]() is not None + ) return frame def fake_sipp_tips_signal_gate(frame): @@ -10385,50 +10375,30 @@ def fake_release_gate_failures(*args, **kwargs): assert captured["sipp_tip_donor_sha256"] == builder.SIPP_2023_TIP_DONOR_SHA256 assert captured["sipp_tip_stage_called"] is True assert captured["sipp_tip_gate_called"] is True - assert captured["sipp_financial_asset_donor_path"] == Path("pu2023.csv") - assert ( - captured["sipp_financial_asset_donor_sha256"] - == builder.SIPP_2023_FINANCIAL_ASSET_DONOR_SHA256 - ) - assert ( - captured["sipp_financial_asset_donor_size_bytes"] - == builder.SIPP_2023_FINANCIAL_ASSET_DONOR_SIZE_BYTES - ) + assert captured["sipp_person_file_reads"] == [ + { + "path": Path("pu2023.csv"), + "columns": builder._SIPP_2023_DONOR_SOURCE_COLUMNS, + "sha256": builder.SIPP_2023_FINANCIAL_ASSET_DONOR_SHA256, + "size_bytes": builder.SIPP_2023_FINANCIAL_ASSET_DONOR_SIZE_BYTES, + } + ] + assert captured["sipp_donor_builds"] == [ + ("financial_assets", True, {}), + ("ssi_disability", True, {"time_period": builder.PERIOD}), + ("head_start", True, {}), + ("vehicles", True, {}), + ("voluntary_filing", True, {}), + ] + assert captured["sipp_person_rows_alive_at_tip_stage"] is False assert captured["sipp_scf_wealth_blend_called"] is True assert captured["sipp_scf_wealth_blend_gate_required"] is True - assert captured["sipp_vehicle_donor_path"] == Path("pu2023.csv") - assert ( - captured["sipp_vehicle_donor_sha256"] == builder.SIPP_2023_VEHICLE_DONOR_SHA256 - ) - assert ( - captured["sipp_vehicle_donor_size_bytes"] - == builder.SIPP_2023_VEHICLE_DONOR_SIZE_BYTES - ) assert captured["sipp_vehicle_stage_called"] is True assert captured["sipp_vehicle_seed"] == 42 assert captured["sipp_vehicle_gate_called"] is True - assert captured["ssi_disability_donor_path"] == Path("pu2023.csv") - assert ( - captured["ssi_disability_donor_sha256"] - == builder.SIPP_2023_SSI_DISABILITY_DONOR_SHA256 - ) - assert ( - captured["ssi_disability_donor_size_bytes"] - == builder.SIPP_2023_SSI_DISABILITY_DONOR_SIZE_BYTES - ) - assert captured["ssi_disability_donor_period"] == builder.PERIOD assert captured["ssi_disability_stage_called"] is True assert captured["ssi_disability_seed"] == 42 assert captured["ssi_disability_gate_called"] is True - assert captured["sipp_head_start_donor_path"] == Path("pu2023.csv") - assert ( - captured["sipp_head_start_donor_sha256"] - == builder.SIPP_2023_HEAD_START_DONOR_SHA256 - ) - assert ( - captured["sipp_head_start_donor_size_bytes"] - == builder.SIPP_2023_HEAD_START_DONOR_SIZE_BYTES - ) assert captured["sipp_head_start_stage_called"] is True assert captured["sipp_head_start_seed"] == 0 assert captured["sipp_head_start_period"] == builder.PERIOD @@ -10555,15 +10525,6 @@ def fake_release_gate_failures(*args, **kwargs): assert "final_medicaid_diagnostics_called" not in captured else: assert captured["final_medicaid_diagnostics_called"] is True - assert captured["voluntary_filing_donor_path"] == Path("pu2023.csv") - assert ( - captured["voluntary_filing_donor_sha256"] - == builder.SIPP_2023_VOLUNTARY_FILING_DONOR_SHA256 - ) - assert ( - captured["voluntary_filing_donor_size_bytes"] - == builder.SIPP_2023_VOLUNTARY_FILING_DONOR_SIZE_BYTES - ) assert captured["voluntary_filing_stage_called"] is True assert captured["voluntary_filing_seed"] == 0 assert captured["voluntary_filing_gate_called"] is True diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py index 24f20fba67..ab47f72314 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py @@ -18,17 +18,19 @@ from test_support.microcosm_build.us_gate_shadow import arm_us_tool_gate_shadows from test_support.microcosm_build.us_post_export_scoring import * -#: The nine donor-table loaders ``_main`` calls, one per imputation stage. -_DONOR_LOADERS = ( +#: The calls that make ``_main``'s nine donor tables, one per imputation stage: +#: four read a file each, and five build a table from the shared SIPP December +#: rows, which ``_main`` deletes after the last of those stages. +_DONOR_TABLE_CALLS = ( + "build_sipp_2023_financial_asset_donor", + "build_sipp_2023_head_start_donor", + "build_sipp_2023_ssi_disability_donor", + "build_sipp_2023_vehicle_donor", + "build_sipp_2023_voluntary_filing_donor", "load_org_2024_donor", "load_scf_2022_auto_loan_donor", "load_scf_2022_financial_asset_donor", - "load_sipp_2023_financial_asset_donor", - "load_sipp_2023_head_start_donor", - "load_sipp_2023_ssi_disability_donor", "load_sipp_2023_tip_donor", - "load_sipp_2023_vehicle_donor", - "load_sipp_2023_voluntary_filing_donor", ) @@ -558,24 +560,28 @@ def test_main_passes_each_donor_table_straight_into_its_stage(builder) -> None: for parent in ast.walk(main) for child in ast.iter_child_nodes(parent) } - loader_calls = [ + donor_table_calls = [ node for node in ast.walk(main) if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) - and re.fullmatch(r"load_\w+_donor", node.func.id) + and re.fullmatch(r"(?:build|load)_\w+_donor", node.func.id) ] - assert sorted(call.func.id for call in loader_calls) == sorted(_DONOR_LOADERS) - for call in loader_calls: + assert sorted(call.func.id for call in donor_table_calls) == sorted( + _DONOR_TABLE_CALLS + ) + for call in donor_table_calls: keyword = parents[call] assert isinstance(keyword, ast.keyword), ast.unparse(call) stage = parents[keyword] assert isinstance(stage, ast.Call) assert isinstance(stage.func, ast.Name) assert stage.func.id.startswith("with_us_"), ast.unparse(stage.func) - # A cached loader would keep its table for the process, whatever _main does. - for loader in _DONOR_LOADERS: - assert not hasattr(getattr(builder, loader), "cache_info"), loader + # A cached call would keep its table for the process, whatever _main does. + for donor_table_call in _DONOR_TABLE_CALLS: + assert not hasattr(getattr(builder, donor_table_call), "cache_info"), ( + donor_table_call + ) def test_main_frees_base_frame_after_the_export_input_mass_check(builder) -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_sipp_december_person_rows.py b/packages/microcosm-build/tests/engine_free/us/test_us_sipp_december_person_rows.py new file mode 100644 index 0000000000..800c260891 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_sipp_december_person_rows.py @@ -0,0 +1,1075 @@ +"""One read of the SIPP person file must give each donor what its own read gave. + +``_separate_december_read`` keeps a copy of the per-donor reads the shared read +replaced: each donor read its own columns, and they differed in how ``SSUID`` +was parsed, in ``low_memory`` and in whether chunks without December rows were +kept. The comparison needs that copy; nothing else should use it. +""" + +from __future__ import annotations + +import inspect +from collections.abc import Callable +from dataclasses import dataclass, replace +from hashlib import sha256 +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest +from pandas.testing import assert_frame_equal + +from microcosm.build.us_runtime import sipp_december_person_rows as person_rows_module +from microcosm.build.us_runtime.sipp_december_person_rows import ( + SippDecemberPersonRows, + read_sipp_december_person_rows, +) +from microcosm.build.us_runtime.sipp_financial_assets import ( + SIPP_2023_FINANCIAL_ASSET_DONOR_SHA256, + SIPP_2023_FINANCIAL_ASSET_DONOR_SIZE_BYTES, + SIPP_FINANCIAL_ASSET_SOURCE_COLUMNS, + build_sipp_2023_financial_asset_donor, +) +from microcosm.build.us_runtime.sipp_head_start import ( + SIPP_2023_HEAD_START_DONOR_SHA256, + SIPP_2023_HEAD_START_DONOR_SIZE_BYTES, + SIPP_HEAD_START_SOURCE_COLUMNS, + build_sipp_2023_head_start_donor, +) +from microcosm.build.us_runtime.sipp_vehicles import ( + SIPP_2023_VEHICLE_DONOR_SHA256, + SIPP_2023_VEHICLE_DONOR_SIZE_BYTES, + SIPP_VEHICLE_SOURCE_COLUMNS, + build_sipp_2023_vehicle_donor, +) +from microcosm.build.us_runtime.ssi_disability_criteria import ( + SIPP_2023_SSI_DISABILITY_DONOR_SHA256, + SIPP_2023_SSI_DISABILITY_DONOR_SIZE_BYTES, + SIPP_SSI_DISABILITY_SOURCE_COLUMNS, + build_sipp_2023_ssi_disability_donor, + load_sipp_2023_ssi_disability_donor, +) +from microcosm.build.us_runtime.voluntary_filing import ( + SIPP_2023_VOLUNTARY_FILING_DONOR_SHA256, + SIPP_2023_VOLUNTARY_FILING_DONOR_SIZE_BYTES, + SIPP_VOLUNTARY_FILING_SOURCE_COLUMNS, + build_sipp_2023_voluntary_filing_donor, +) + +_CHUNK_ROWS = 7 +_HOUSEHOLD_COUNT = 24 +_UNREAD_COLUMN = "UNREAD_NOTE" +_ALL_DONOR_COLUMNS = tuple( + sorted( + { + *SIPP_FINANCIAL_ASSET_SOURCE_COLUMNS, + *SIPP_SSI_DISABILITY_SOURCE_COLUMNS, + *SIPP_HEAD_START_SOURCE_COLUMNS, + *SIPP_VEHICLE_SOURCE_COLUMNS, + *SIPP_VOLUNTARY_FILING_SOURCE_COLUMNS, + } + ) +) + + +@dataclass(frozen=True) +class _DonorRead: + """How one donor read the file before the reads were merged.""" + + columns: tuple[str, ...] + build_donor: Callable[[SippDecemberPersonRows], pd.DataFrame] + ssuid_as_text: bool = False + low_memory: bool = False + keeps_chunks_without_december_rows: bool = False + + +_DONOR_READS = { + "financial_assets": _DonorRead( + SIPP_FINANCIAL_ASSET_SOURCE_COLUMNS, + build_sipp_2023_financial_asset_donor, + ssuid_as_text=True, + ), + "ssi_disability": _DonorRead( + SIPP_SSI_DISABILITY_SOURCE_COLUMNS, + build_sipp_2023_ssi_disability_donor, + ), + "head_start": _DonorRead( + SIPP_HEAD_START_SOURCE_COLUMNS, + build_sipp_2023_head_start_donor, + keeps_chunks_without_december_rows=True, + ), + "vehicles": _DonorRead( + SIPP_VEHICLE_SOURCE_COLUMNS, + build_sipp_2023_vehicle_donor, + low_memory=True, + ), + "voluntary_filing": _DonorRead( + SIPP_VOLUNTARY_FILING_SOURCE_COLUMNS, + build_sipp_2023_voluntary_filing_donor, + low_memory=True, + ), +} +_SSUID_VARIANTS = ( + "digits_with_leading_zeros", + "blank_in_chunk_without_december_rows", + "blank_beside_december_rows", + "every_identifier_blank_in_one_chunk", + "text_identifiers", + "text_identifiers_with_blank", +) +# A donor that parsed in low_memory blocks refuses text identifiers, so the +# comparison with its own read covers numeric identifiers only. +_COMPARABLE_DONOR_CASES = tuple( + (donor_name, ssuid_variant) + for donor_name, donor_read in _DONOR_READS.items() + for ssuid_variant in _SSUID_VARIANTS + if not (donor_read.low_memory and ssuid_variant.startswith("text_identifiers")) +) + + +def _person_cells( + household_number: int, + person_number: int, + ssuid: str, +) -> dict[str, str]: + """Return one person's cells, valid for every donor's transform.""" + + has_spouse = household_number % 3 == 0 + is_first_person = person_number % 2 == 1 + if is_first_person or has_spouse: + age = 30 + household_number % 30 + (0 if is_first_person else 2) + elif household_number % 3 == 1: + age = 3 + (household_number // 3) % 3 + else: + age = 15 + is_adult = age >= 18 + monthly_earnings = 1_000 + 3 * household_number if is_adult else 0 + cells = dict.fromkeys(_ALL_DONOR_COLUMNS, "0") + cells.update( + { + "SSUID": ssuid, + "PNUM": str(person_number), + "WPFINWGT": f"{1_000 + household_number * 17.125 + person_number / 7:.6f}", + "TAGE": str(age), + "ESEX": "1" if is_first_person else "2", + "EMS": "1" if has_spouse and is_adult else "6", + "TPTOTINC": str(monthly_earnings), + "TJB1_MSUM": str(monthly_earnings), + "TJB2_MSUM": "", + "TVAL_BANK": "" + if household_number % 5 == 0 + else str(household_number * 10), + "TVAL_STMF": str(household_number), + "TVAL_BOND": str(household_number + 1), + "AJSSAVVAL": "2" if household_number % 4 == 0 else "0", + "RSSI_YRYN": "1" if household_number % 6 == 1 and is_adult else "2", + "ESSI_BRSN": "1", + "AEDHEADST": "1" if 3 <= age <= 5 else "0", + "EEDHEADST": "1" if household_number % 2 else "2", + "EPNSPOUSE": str(person_number + (1 if is_first_person else -1)) + if has_spouse + else "", + "AFILING": "1" if is_adult else "0", + "EFILING": "1" if household_number % 2 else "2", + "AWILLFILE": "1", + "EWILLFILE": "2", + "EDEPCLM": "2", + "TVEH_NUM": str(1 + household_number % 3), + "THVAL_VEH": str(5_000 * household_number), + "THVAL_HOME": str(100_000 * (household_number % 2)), + } + ) + return cells + + +def _household_identifiers(ssuid_variant: str) -> list[str]: + if ssuid_variant.startswith("text_identifiers"): + return [f"H{number:03d}" for number in range(_HOUSEHOLD_COUNT)] + identifiers = [f"{number + 7:012d}" for number in range(_HOUSEHOLD_COUNT)] + # Equal as numbers, different as text: only the financial-asset donor + # keeps these two households apart. + identifiers[-2:] = ["000000000123", "123"] + return identifiers + + +def _write_person_file(tmp_path: Path, ssuid_variant: str) -> Path: + identifiers = _household_identifiers(ssuid_variant) + rows: list[dict[str, str]] = [] + # Three chunks with no December row, one with a blank age. + for filler_position in range(3 * _CHUNK_ROWS): + cells = _person_cells(1, 101, identifiers[1]) + cells["MONTHCODE"] = "5" + cells["PNUM"] = str(500 + filler_position) + if filler_position == 3: + cells["TAGE"] = "" + if ssuid_variant == "blank_in_chunk_without_december_rows": + cells["SSUID"] = "" + if ( + ssuid_variant == "every_identifier_blank_in_one_chunk" + and filler_position < _CHUNK_ROWS + ): + cells["SSUID"] = "" + rows.append(cells) + for household_number, ssuid in enumerate(identifiers): + first_person = 101 + 2 * (ssuid == "123") + for person_number in (first_person, first_person + 1): + for month in ("11", "12"): + cells = _person_cells(household_number, person_number, ssuid) + cells["MONTHCODE"] = month + rows.append(cells) + if ssuid_variant in ("blank_beside_december_rows", "text_identifiers_with_blank"): + # This November row starts a chunk that also holds December rows. + rows[3 * _CHUNK_ROWS]["SSUID"] = "" + + # A file order unlike any donor's column list, with a column no donor reads. + header = [*sorted(_ALL_DONOR_COLUMNS, reverse=True), _UNREAD_COLUMN] + lines = ["|".join(header)] + lines.extend( + "|".join([*(row[column] for column in header[:-1]), "free text"]) + for row in rows + ) + path = tmp_path / "pu2023.csv" + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + return path + + +def _separate_december_read(path: Path, donor_read: _DonorRead) -> pd.DataFrame: + """Read December rows the way this donor's own read did.""" + + options: dict[str, object] = {} + if donor_read.ssuid_as_text: + options["dtype"] = {"SSUID": "string"} + parts: list[pd.DataFrame] = [] + for chunk in pd.read_csv( + path, + delimiter="|", + usecols=list(donor_read.columns), + chunksize=_CHUNK_ROWS, + low_memory=donor_read.low_memory, + **options, + ): + month = pd.to_numeric(chunk["MONTHCODE"], errors="coerce") + december = chunk.loc[month.eq(12)].copy() + if donor_read.keeps_chunks_without_december_rows or not december.empty: + parts.append(december) + return pd.concat(parts, ignore_index=True) + + +def _rows_from_separate_read(path: Path, donor_read: _DonorRead): + table = _separate_december_read(path, donor_read) + return SippDecemberPersonRows( + rows=table, + ssuid_text=table["SSUID"], + december_parts_by_chunk=(), + columns_sensitive_to_parser_blocks=frozenset(), + file_row_count=sum(1 for _ in path.open(encoding="utf-8")) - 1, + file_size_bytes=path.stat().st_size, + verified_sha256=None, + verified_size_bytes=None, + ) + + +def _assert_identical_tables(actual: pd.DataFrame, expected: pd.DataFrame) -> None: + """Compare exactly, separating 0.0 from -0.0 and object 1 from 1.0.""" + + assert_frame_equal(actual, expected, check_exact=True) + for column in expected.columns: + if pd.api.types.is_numeric_dtype(expected[column].dtype): + assert ( + actual[column].to_numpy().tobytes() + == expected[column].to_numpy().tobytes() + ), column + elif pd.api.types.is_object_dtype(expected[column].dtype): + assert list(map(repr, actual[column])) == list( + map(repr, expected[column]) + ), column + + +def _shared_read(path: Path) -> SippDecemberPersonRows: + return read_sipp_december_person_rows( + path, + columns=_ALL_DONOR_COLUMNS, + chunksize=_CHUNK_ROWS, + ) + + +@pytest.mark.parametrize(("donor_name", "ssuid_variant"), _COMPARABLE_DONOR_CASES) +def test_shared_read_gives_each_donor_the_table_of_its_own_read( + tmp_path: Path, + donor_name: str, + ssuid_variant: str, +) -> None: + donor_read = _DONOR_READS[donor_name] + path = _write_person_file(tmp_path, ssuid_variant) + table_without_empty_chunks = _separate_december_read( + path, + _DonorRead( + donor_read.columns, + donor_read.build_donor, + ssuid_as_text=donor_read.ssuid_as_text, + low_memory=donor_read.low_memory, + ), + ) + + shared_table = _shared_read(path).source_table( + donor_read.columns, + ssuid_as_text=donor_read.ssuid_as_text, + read_in_parser_blocks=donor_read.low_memory, + ) + + _assert_identical_tables(shared_table, table_without_empty_chunks) + + +@pytest.mark.parametrize("ssuid_variant", _SSUID_VARIANTS) +def test_head_start_table_counts_chunks_without_december_rows( + tmp_path: Path, + ssuid_variant: str, +) -> None: + donor_read = _DONOR_READS["head_start"] + path = _write_person_file(tmp_path, ssuid_variant) + + shared_table = _shared_read(path).source_table( + donor_read.columns, + include_chunks_without_december_rows=True, + ) + + _assert_identical_tables(shared_table, _separate_december_read(path, donor_read)) + + +@pytest.mark.parametrize("donor_name", ("vehicles", "voluntary_filing")) +def test_low_memory_donors_refuse_text_identifiers( + tmp_path: Path, + donor_name: str, +) -> None: + shared_rows = _shared_read(_write_person_file(tmp_path, "text_identifiers")) + + with pytest.raises(ValueError, match=r"SSUID.*parser blocks"): + _DONOR_READS[donor_name].build_donor(shared_rows) + + +@pytest.mark.parametrize(("donor_name", "ssuid_variant"), _COMPARABLE_DONOR_CASES) +def test_donor_built_from_shared_read_equals_donor_from_its_own_read( + tmp_path: Path, + donor_name: str, + ssuid_variant: str, +) -> None: + donor_read = _DONOR_READS[donor_name] + path = _write_person_file(tmp_path, ssuid_variant) + + shared_donor = donor_read.build_donor(_shared_read(path)) + separate_donor = donor_read.build_donor(_rows_from_separate_read(path, donor_read)) + + assert not separate_donor.empty + _assert_identical_tables(shared_donor, separate_donor) + assert shared_donor.attrs == separate_donor.attrs + + +def test_building_every_donor_leaves_the_shared_rows_unchanged(tmp_path: Path) -> None: + shared_rows = _shared_read( + _write_person_file(tmp_path, "digits_with_leading_zeros") + ) + rows_before = shared_rows.rows.copy(deep=True) + ssuid_text_before = shared_rows.ssuid_text.copy(deep=True) + + for donor_read in _DONOR_READS.values(): + donor_read.build_donor(shared_rows) + + assert_frame_equal(shared_rows.rows, rows_before, check_exact=True) + pd.testing.assert_series_equal(shared_rows.ssuid_text, ssuid_text_before) + + +def test_identifier_forms_keep_leading_zeros_only_as_text(tmp_path: Path) -> None: + shared_rows = _shared_read( + _write_person_file(tmp_path, "digits_with_leading_zeros") + ) + + as_text = shared_rows.source_table(("SSUID", "PNUM"), ssuid_as_text=True)["SSUID"] + as_number = shared_rows.source_table(("SSUID", "PNUM"))["SSUID"] + + assert as_text.iloc[0] == "000000000007" + assert as_number.iloc[0] == 7 + assert as_number.dtype == "int64" + assert as_text.nunique() == as_number.nunique() + 1 + + +def test_shared_read_counts_every_file_row_and_records_the_file(tmp_path: Path) -> None: + path = _write_person_file(tmp_path, "digits_with_leading_zeros") + digest = sha256(path.read_bytes()).hexdigest() + + shared_rows = read_sipp_december_person_rows( + path, + columns=_ALL_DONOR_COLUMNS, + expected_sha256=digest, + expected_size_bytes=path.stat().st_size, + chunksize=_CHUNK_ROWS, + ) + + assert shared_rows.file_row_count == 3 * _CHUNK_ROWS + 4 * _HOUSEHOLD_COUNT + assert len(shared_rows.rows) == 2 * _HOUSEHOLD_COUNT + assert shared_rows.file_size_bytes == path.stat().st_size + assert shared_rows.verified_sha256 == digest + assert shared_rows.verified_size_bytes == path.stat().st_size + + +def test_all_five_donors_pin_the_one_file_the_shared_read_verifies() -> None: + assert { + SIPP_2023_FINANCIAL_ASSET_DONOR_SHA256, + SIPP_2023_SSI_DISABILITY_DONOR_SHA256, + SIPP_2023_HEAD_START_DONOR_SHA256, + SIPP_2023_VEHICLE_DONOR_SHA256, + SIPP_2023_VOLUNTARY_FILING_DONOR_SHA256, + } == {SIPP_2023_FINANCIAL_ASSET_DONOR_SHA256} + assert { + SIPP_2023_FINANCIAL_ASSET_DONOR_SIZE_BYTES, + SIPP_2023_SSI_DISABILITY_DONOR_SIZE_BYTES, + SIPP_2023_HEAD_START_DONOR_SIZE_BYTES, + SIPP_2023_VEHICLE_DONOR_SIZE_BYTES, + SIPP_2023_VOLUNTARY_FILING_DONOR_SIZE_BYTES, + } == {SIPP_2023_FINANCIAL_ASSET_DONOR_SIZE_BYTES} + + +def test_ssi_path_loader_equals_the_donor_built_from_its_own_read( + tmp_path: Path, +) -> None: + path = _write_person_file(tmp_path, "digits_with_leading_zeros") + donor_read = _DONOR_READS["ssi_disability"] + + donor = load_sipp_2023_ssi_disability_donor( + path, + expected_size_bytes=None, + chunksize=_CHUNK_ROWS, + ) + + expected = donor_read.build_donor(_rows_from_separate_read(path, donor_read)) + _assert_identical_tables(donor, expected) + assert donor.attrs == expected.attrs + + +def test_ssi_path_loader_passes_its_pins_and_period_through(tmp_path: Path) -> None: + path = _write_person_file(tmp_path, "digits_with_leading_zeros") + + with pytest.raises(ValueError, match="sha-256 verification"): + load_sipp_2023_ssi_disability_donor( + path, + expected_sha256="0" * 64, + expected_size_bytes=None, + ) + with pytest.raises(ValueError, match="byte-length verification"): + load_sipp_2023_ssi_disability_donor(path, expected_size_bytes=1) + donor = load_sipp_2023_ssi_disability_donor( + path, + expected_size_bytes=None, + chunksize=_CHUNK_ROWS, + time_period=2023, + ) + assert donor.attrs["source_audit"]["time_period"] == 2023 + + +def test_head_start_audits_only_rows_verified_against_both_pins( + tmp_path: Path, +) -> None: + path = _write_person_file(tmp_path, "digits_with_leading_zeros") + person_rows = _shared_read(path) + + with pytest.raises(ValueError, match="Pinned SIPP Head Start audit drifted"): + build_sipp_2023_head_start_donor( + replace( + person_rows, + verified_sha256=SIPP_2023_HEAD_START_DONOR_SHA256, + verified_size_bytes=SIPP_2023_HEAD_START_DONOR_SIZE_BYTES, + ) + ) + donor = build_sipp_2023_head_start_donor( + replace(person_rows, verified_sha256=SIPP_2023_HEAD_START_DONOR_SHA256) + ) + assert donor.attrs["source_audit"]["pinned_transform"] is False + + +def test_ssi_donor_audits_a_file_of_the_pinned_size_for_2024(tmp_path: Path) -> None: + path = _write_person_file(tmp_path, "digits_with_leading_zeros") + pinned_size_rows = replace( + _shared_read(path), + file_size_bytes=SIPP_2023_SSI_DISABILITY_DONOR_SIZE_BYTES, + ) + + with pytest.raises(ValueError, match="Pinned SIPP SSI disability source audit"): + build_sipp_2023_ssi_disability_donor(pinned_size_rows) + donor = build_sipp_2023_ssi_disability_donor(pinned_size_rows, time_period=2023) + assert donor.attrs["source_audit"]["pinned_transform"] is False + + +def _write_table(path: Path, header: list[str], rows: list[list[str]]) -> Path: + lines = ["|".join(header), *("|".join(row) for row in rows)] + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + return path + + +def _write_wide_december_table( + path: Path, + weight_cells: list[str], + *, + month_cells: list[str] | None = None, +) -> Path: + """Write a table wide enough for ``low_memory`` to use 1,024-row blocks.""" + + unread_columns = [f"UNREAD_{position}" for position in range(1_000)] + months = month_cells or ["12"] * len(weight_cells) + return _write_table( + path, + ["SSUID", "MONTHCODE", "WPFINWGT", *unread_columns], + [ + [str(position + 1), month, weight, *[""] * len(unread_columns)] + for position, (month, weight) in enumerate( + zip(months, weight_cells, strict=True) + ) + ], + ) + + +_WIDE_TABLE_COLUMNS = ("SSUID", "MONTHCODE", "WPFINWGT") +_FIRST_BLOCK_ROWS = 1_100 +_CELLS_THAT_PARSER_BLOCKS_CHANGE = { + "seventeen_digit_integer": ["99302078781721519"] * _FIRST_BLOCK_ROWS + ["1.5"], + "negative_zero": ["-0"] * _FIRST_BLOCK_ROWS + ["0.5"], + "above_int64": ["1"] * _FIRST_BLOCK_ROWS + ["18446744073709551615"], + "text_after_numbers": ["3"] * _FIRST_BLOCK_ROWS + ["x"], + "integer_with_many_leading_zeros": ["0" * 20 + "12"] * _FIRST_BLOCK_ROWS + ["0.5"], +} + + +@pytest.mark.parametrize("case_name", _CELLS_THAT_PARSER_BLOCKS_CHANGE) +def test_whole_chunk_donors_get_a_direct_parse_of_awkward_cells( + tmp_path: Path, + case_name: str, +) -> None: + path = _write_wide_december_table( + tmp_path / "wide.csv", + _CELLS_THAT_PARSER_BLOCKS_CHANGE[case_name], + ) + + shared_table = read_sipp_december_person_rows( + path, + columns=_WIDE_TABLE_COLUMNS, + ).source_table(_WIDE_TABLE_COLUMNS) + + _assert_identical_tables( + shared_table, + pd.read_csv( + path, + delimiter="|", + usecols=list(_WIDE_TABLE_COLUMNS), + low_memory=False, + ), + ) + + +@pytest.mark.parametrize("case_name", _CELLS_THAT_PARSER_BLOCKS_CHANGE) +def test_low_memory_donors_refuse_cells_parser_blocks_change( + tmp_path: Path, + case_name: str, +) -> None: + path = _write_wide_december_table( + tmp_path / "wide.csv", + _CELLS_THAT_PARSER_BLOCKS_CHANGE[case_name], + ) + shared_rows = read_sipp_december_person_rows(path, columns=_WIDE_TABLE_COLUMNS) + + with pytest.raises(ValueError, match=r"WPFINWGT.*parser blocks"): + shared_rows.source_table(_WIDE_TABLE_COLUMNS, read_in_parser_blocks=True) + + +def test_low_memory_donors_refuse_an_out_of_range_integer_outside_december( + tmp_path: Path, +) -> None: + weights = ["1.5"] * _FIRST_BLOCK_ROWS + ["99999999999999999999999"] + path = _write_wide_december_table( + tmp_path / "wide.csv", + weights, + month_cells=["12"] * _FIRST_BLOCK_ROWS + ["11"], + ) + shared_rows = read_sipp_december_person_rows(path, columns=_WIDE_TABLE_COLUMNS) + + with pytest.raises(ValueError, match=r"WPFINWGT.*parser blocks"): + shared_rows.source_table(_WIDE_TABLE_COLUMNS, read_in_parser_blocks=True) + + +def test_low_memory_donors_refuse_a_month_only_parser_blocks_read_as_december( + tmp_path: Path, +) -> None: + columns = ("SSUID", "MONTHCODE", "WPFINWGT") + months = ["0" * 20 + "12"] * 3 + ["11.5"] + other_chunk = [["9", "12", "1"]] + path = _write_table( + tmp_path / "months.csv", + list(columns), + [ + *[[str(position + 1), month, "1"] for position, month in enumerate(months)], + *other_chunk, + ], + ) + shared_rows = read_sipp_december_person_rows(path, columns=columns, chunksize=4) + + with pytest.raises(ValueError, match=r"MONTHCODE.*parser blocks"): + shared_rows.source_table(columns, read_in_parser_blocks=True) + + +def test_low_memory_donors_get_their_own_parse_of_ordinary_numbers( + tmp_path: Path, +) -> None: + path = _write_wide_december_table( + tmp_path / "wide.csv", + ["123456789012345"] * _FIRST_BLOCK_ROWS + ["", "1.25"], + ) + + shared_table = read_sipp_december_person_rows( + path, + columns=_WIDE_TABLE_COLUMNS, + ).source_table(_WIDE_TABLE_COLUMNS, read_in_parser_blocks=True) + + _assert_identical_tables( + shared_table, + pd.read_csv( + path, + delimiter="|", + usecols=list(_WIDE_TABLE_COLUMNS), + low_memory=True, + ), + ) + assert shared_table["WPFINWGT"].dtype == np.float64 + + +@pytest.mark.parametrize( + "identifiers", + ( + ["True", "False"], + ["True", ""], + ["0012", "A13"], + ["12.5", "13"], + ["+7", "-7"], + ["12345678901234567890", "1"], + ), +) +def test_identifiers_are_parsed_as_a_direct_parse_would( + tmp_path: Path, + identifiers: list[str], +) -> None: + columns = ("SSUID", "MONTHCODE") + path = _write_table( + tmp_path / "identifiers.csv", + list(columns), + [[identifier, "12"] for identifier in identifiers], + ) + + shared_rows = read_sipp_december_person_rows(path, columns=columns) + + _assert_identical_tables( + shared_rows.source_table(columns), + pd.read_csv(path, delimiter="|", low_memory=False), + ) + _assert_identical_tables( + shared_rows.source_table(columns, ssuid_as_text=True), + pd.read_csv( + path, + delimiter="|", + dtype={"SSUID": "string"}, + low_memory=False, + ), + ) + + +def test_head_start_combines_every_chunk_in_one_concatenation(tmp_path: Path) -> None: + columns = ("SSUID", "MONTHCODE", "PNUM") + path = _write_table( + tmp_path / "large_identifiers.csv", + list(columns), + [ + ["9007199254740992", "12", "1"], + ["9007199254740993", "12", "1"], + ["1", "12", "1"], + ["", "11", "1"], + ["abc", "11", "1"], + ["abd", "11", "1"], + ], + ) + + shared_table = read_sipp_december_person_rows( + path, + columns=columns, + chunksize=2, + ).source_table(columns, include_chunks_without_december_rows=True) + + parts = [ + chunk.loc[chunk["MONTHCODE"].eq(12)] + for chunk in pd.read_csv( + path, + delimiter="|", + chunksize=2, + low_memory=False, + ) + ] + _assert_identical_tables(shared_table, pd.concat(parts, ignore_index=True)) + assert shared_table["SSUID"].iloc[:2].tolist() == [ + 9007199254740992, + 9007199254740993, + ] + + +@pytest.mark.parametrize( + "cell", + ( + '"a|b"', + '"line one\nline two"', + '"doubled "" quote"', + '"12"', + '"NA"', + " 12", + "12 ", + ), + ids=( + "quoted_delimiter", + "quoted_line_feed", + "doubled_quote", + "quoted_number", + "quoted_na", + "leading_space", + "trailing_space", + ), +) +def test_cell_text_survives_the_round_trip_through_the_narrow_table( + tmp_path: Path, + cell: str, +) -> None: + columns = ("SSUID", "MONTHCODE", "TAGE") + path = tmp_path / "quoted.csv" + path.write_text( + f"SSUID|MONTHCODE|UNREAD|TAGE\n1|12|x|{cell}\n2|12|y|40\n", + encoding="utf-8", + newline="", + ) + + shared_table = read_sipp_december_person_rows( + path, + columns=columns, + ).source_table(columns) + + _assert_identical_tables( + shared_table, + pd.read_csv(path, delimiter="|", usecols=list(columns), low_memory=False), + ) + + +@pytest.mark.parametrize( + "file_text", + ( + "SSUID|MONTHCODE\r1|12\r2|12\r", + "SSUID|MONTHCODE\r\n1|12\r2|12\r\n", + "SSUID|MONTHCODE\n1|12\n2|12\r", + 'SSUID|MONTHCODE\n"1\r2"|12\n', + ), + ids=("every_row", "one_row", "last_byte", "inside_quotes"), +) +@pytest.mark.parametrize("scan_block_bytes", (3, 1024)) +def test_read_refuses_a_bare_carriage_return( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + file_text: str, + scan_block_bytes: int, +) -> None: + monkeypatch.setattr(person_rows_module, "_SCAN_BLOCK_BYTES", scan_block_bytes) + path = tmp_path / "carriage_returns.csv" + path.write_bytes(file_text.encode("utf-8")) + + with pytest.raises(ValueError, match="carriage return"): + read_sipp_december_person_rows(path, columns=("SSUID", "MONTHCODE")) + + +@pytest.mark.parametrize("scan_block_bytes", (3, 16, 1024)) +def test_read_accepts_crlf_rows_across_scan_blocks( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + scan_block_bytes: int, +) -> None: + monkeypatch.setattr(person_rows_module, "_SCAN_BLOCK_BYTES", scan_block_bytes) + columns = ("SSUID", "MONTHCODE") + path = tmp_path / "crlf.csv" + path.write_bytes(b"SSUID|MONTHCODE\r\n0012|12\r\n13|12\r\n") + + shared_table = read_sipp_december_person_rows( + path, + columns=columns, + ).source_table(columns) + + _assert_identical_tables( + shared_table, + pd.read_csv(path, delimiter="|", low_memory=False), + ) + + +@pytest.mark.parametrize("header_has_unread_column", (False, True)) +def test_read_refuses_a_first_row_longer_than_the_header( + tmp_path: Path, + header_has_unread_column: bool, +) -> None: + columns = ["SSUID", "MONTHCODE"] + header = [*columns, "UNREAD"] if header_has_unread_column else columns + cells = ["1", "12", "x"] if header_has_unread_column else ["1", "12"] + path = _write_table(tmp_path / "long.csv", header, [[*cells, ""]]) + + with pytest.raises(ValueError, match="longer than its header"): + read_sipp_december_person_rows(path, columns=columns) + + +def test_leading_space_in_the_first_column_survives_the_parser_buffer_end( + tmp_path: Path, +) -> None: + # In a table of only these two columns, the cell with the leading space + # starts on the last character of pandas' 262,144-character read buffer. + last_buffer_offset = 262_143 + header = "SSUID|MONTHCODE\n" + row_characters = len("000000000001|12\n") + characters_before_cell = last_buffer_offset - len(header) + first_row_characters = characters_before_cell % row_characters or row_characters + ordinary_row_count = ( + characters_before_cell - first_row_characters + ) // row_characters + rows = [ + f"{'1' * (first_row_characters - len('|12' + chr(10)))}|12\n", + *(f"{number:012d}|12\n" for number in range(2, ordinary_row_count + 2)), + ] + assert len(header) + sum(map(len, rows)) == last_buffer_offset + narrow_lines = [*rows, " 000000000099|12\n", "000000000100|12\n"] + path = tmp_path / "boundary.csv" + path.write_text( + "SSUID|MONTHCODE|UNREAD\n" + + "".join(f"{line[:-1]}|x\n" for line in narrow_lines), + encoding="utf-8", + ) + columns = ("SSUID", "MONTHCODE") + + shared_rows = read_sipp_december_person_rows(path, columns=columns) + + direct_text = pd.read_csv( + path, + delimiter="|", + usecols=list(columns), + dtype={"SSUID": "string"}, + low_memory=False, + ) + assert " 000000000099" in set(direct_text["SSUID"]) + _assert_identical_tables( + shared_rows.source_table(columns, ssuid_as_text=True), + direct_text, + ) + + +def test_second_parse_infers_types_over_the_whole_chunk(tmp_path: Path) -> None: + # One hundred columns give 8,192-row blocks if the narrow table were parsed + # with low_memory=True, so the text cell would leave earlier blocks numeric. + columns = ["SSUID", "MONTHCODE", *(f"COLUMN_{n}" for n in range(98))] + rows = [["1", "12", *["3"] * 98] for _ in range(9_000)] + rows.append(["1", "12", "x", *["3"] * 97]) + path = _write_table(tmp_path / "text_late.csv", columns, rows) + + shared_table = read_sipp_december_person_rows( + path, + columns=columns, + ).source_table(columns) + + _assert_identical_tables( + shared_table, + pd.read_csv(path, delimiter="|", low_memory=False), + ) + + +def test_scan_finds_a_carriage_return_at_the_end_of_a_block( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + file_bytes = b"SSUID|MONTHCODE\n1\r2|12\n" + monkeypatch.setattr( + person_rows_module, + "_SCAN_BLOCK_BYTES", + file_bytes.index(b"\r") + 1, + ) + path = tmp_path / "block_end.csv" + path.write_bytes(file_bytes) + + with pytest.raises(ValueError, match="carriage return"): + read_sipp_december_person_rows(path, columns=("SSUID", "MONTHCODE")) + + +def test_low_memory_donors_accept_a_whole_chunk_boolean_column(tmp_path: Path) -> None: + columns = ("SSUID", "MONTHCODE", "FLAG") + path = _write_table( + tmp_path / "flags.csv", + list(columns), + [["1", "12", "True"], ["2", "12", "False"]], + ) + + table = read_sipp_december_person_rows(path, columns=columns).source_table( + columns, + read_in_parser_blocks=True, + ) + + assert table["FLAG"].tolist() == [True, False] + + +def test_text_identifiers_replace_numbers_when_empty_chunks_are_included( + tmp_path: Path, +) -> None: + columns = ("SSUID", "MONTHCODE") + path = _write_table( + tmp_path / "empty_chunk.csv", + list(columns), + [["1", "11"], ["2", "11"], ["0012", "12"], ["0013", "12"]], + ) + + table = read_sipp_december_person_rows( + path, + columns=columns, + chunksize=2, + ).source_table( + columns, + ssuid_as_text=True, + include_chunks_without_december_rows=True, + ) + + assert table["SSUID"].tolist() == ["0012", "0013"] + + +def test_head_start_builder_counts_chunks_without_december_rows( + tmp_path: Path, +) -> None: + # A blank identifier in a chunk with no December row makes SSUID float64, + # so these two identifiers become equal, as they did in the separate read. + identifiers = ["", "1", "9007199254740992", "9007199254740993"] + months = ["11", "11", "12", "12"] + columns = list(SIPP_HEAD_START_SOURCE_COLUMNS) + rows = [] + for identifier, month in zip(identifiers, months, strict=True): + cells = _person_cells(1, 101, identifier) + cells["MONTHCODE"] = month + rows.append([cells[column] for column in columns]) + path = _write_table(tmp_path / "head_start.csv", columns, rows) + + person_rows = read_sipp_december_person_rows( + path, + columns=columns, + chunksize=2, + ) + + with pytest.raises(ValueError, match="not person-unique"): + build_sipp_2023_head_start_donor(person_rows) + + +def test_read_keeps_non_ascii_digit_identifiers_as_text(tmp_path: Path) -> None: + path = _write_table( + tmp_path / "arabic_digits.csv", + ["SSUID", "MONTHCODE"], + [["\u0661\u0662", "12"], ["\u0663", "12"]], + ) + + shared_table = read_sipp_december_person_rows( + path, + columns=("SSUID", "MONTHCODE"), + ).source_table(("SSUID", "MONTHCODE")) + + assert_frame_equal( + shared_table, + pd.read_csv(path, delimiter="|", low_memory=False), + check_exact=True, + ) + + +def test_read_does_not_expand_a_home_directory_path( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("HOME", str(tmp_path)) + _write_table(tmp_path / "home.csv", ["SSUID", "MONTHCODE"], [["12", "12"]]) + + with pytest.raises(FileNotFoundError): + read_sipp_december_person_rows( + "~/home.csv", + columns=("SSUID", "MONTHCODE"), + ) + + +def test_read_reports_a_file_without_data_rows_as_having_no_december_rows( + tmp_path: Path, +) -> None: + path = _write_table(tmp_path / "header.csv", ["SSUID", "MONTHCODE"], []) + + with pytest.raises(ValueError, match="no December rows"): + read_sipp_december_person_rows(path, columns=("SSUID", "MONTHCODE")) + + +def test_read_refuses_a_file_that_fails_its_pins(tmp_path: Path) -> None: + path = _write_table( + tmp_path / "pinned.csv", + ["SSUID", "MONTHCODE"], + [["12", "12"]], + ) + + with pytest.raises(ValueError, match="byte-length verification"): + read_sipp_december_person_rows( + path, + columns=("SSUID", "MONTHCODE"), + expected_size_bytes=1, + ) + with pytest.raises(ValueError, match="sha-256 verification"): + read_sipp_december_person_rows( + path, + columns=("SSUID", "MONTHCODE"), + expected_sha256="0" * 64, + ) + + +def test_read_refuses_missing_columns_and_files_without_december_rows( + tmp_path: Path, +) -> None: + path = _write_table( + tmp_path / "november.csv", + ["SSUID", "MONTHCODE"], + [["12", "11"]], + ) + + with pytest.raises(ValueError, match=r"missing column\(s\): \['TAGE'\]"): + read_sipp_december_person_rows(path, columns=("SSUID", "MONTHCODE", "TAGE")) + with pytest.raises(ValueError, match="no December rows"): + read_sipp_december_person_rows(path, columns=("SSUID", "MONTHCODE")) + with pytest.raises(ValueError, match="chunksize"): + read_sipp_december_person_rows( + path, + columns=("SSUID", "MONTHCODE"), + chunksize=0, + ) + + +def test_source_table_refuses_a_column_the_read_did_not_keep(tmp_path: Path) -> None: + path = _write_table( + tmp_path / "december.csv", + ["SSUID", "MONTHCODE", "TAGE"], + [["12", "12", "40"]], + ) + shared_rows = read_sipp_december_person_rows(path, columns=("SSUID", "MONTHCODE")) + + with pytest.raises(ValueError, match="TAGE"): + shared_rows.source_table(("SSUID", "TAGE")) + + +def test_every_sipp_person_file_read_defaults_to_the_old_loaders_chunk_rows() -> None: + # The old per-donor loaders all read 100,000-row chunks, and the release + # tool and the ACS local-area build pass no chunk size. Column types are + # inferred per chunk, so the tests above show equal donor tables only when + # the chunk sizes match; a different default could change inferred types. + chunk_rows = person_rows_module.SIPP_PERSON_FILE_CHUNK_ROWS + assert chunk_rows == 100_000 + for read_function in ( + read_sipp_december_person_rows, + load_sipp_2023_ssi_disability_donor, + ): + default_chunk_rows = ( + inspect.signature(read_function).parameters["chunksize"].default + ) + assert default_chunk_rows == chunk_rows, read_function.__name__ diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_sipp_financial_assets.py b/packages/microcosm-build/tests/engine_free/us/test_us_sipp_financial_assets.py index 6aa5dd84c8..86fef3b56e 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_sipp_financial_assets.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_sipp_financial_assets.py @@ -5,6 +5,9 @@ import numpy as np import pandas as pd +from microcosm.build.us_runtime.sipp_december_person_rows import ( + read_sipp_december_person_rows, +) from microcosm.build.us_runtime.sipp_financial_assets import ( SIPP_2023_FINANCIAL_ASSET_DONOR_REPOSITORY_ID_PARTS, SIPP_2023_FINANCIAL_ASSET_DONOR_REPOSITORY_TYPE, @@ -18,9 +21,9 @@ SIPP_FINANCIAL_ASSET_TARGET_ALLOCATION_COLUMNS, SIPP_FINANCIAL_ASSET_TARGET_SOURCE_COLUMNS, _target_balanced_cap, + build_sipp_2023_financial_asset_donor, fetch_sipp_2023_financial_asset_donor, impute_us_sipp_financial_assets, - load_sipp_2023_financial_asset_donor, ) @@ -177,13 +180,16 @@ def test_pinned_sipp_source_and_final_archived_predictor_contract() -> None: } -def test_loader_filters_december_and_matches_archived_transforms(tmp_path) -> None: +def test_donor_keeps_december_rows_and_matches_archived_transforms(tmp_path) -> None: raw = _raw_sipp() path = tmp_path / "pu2023.csv" raw.to_csv(path, sep="|", index=False) - donor = load_sipp_2023_financial_asset_donor( - path, - chunksize=3, + donor = build_sipp_2023_financial_asset_donor( + read_sipp_december_person_rows( + path, + columns=SIPP_FINANCIAL_ASSET_SOURCE_COLUMNS, + chunksize=3, + ), max_train_samples=None, ) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_sipp_head_start.py b/packages/microcosm-build/tests/engine_free/us/test_us_sipp_head_start.py index ab26c8ef7d..4ef01faa95 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_sipp_head_start.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_sipp_head_start.py @@ -40,7 +40,7 @@ def test_source_coordinates_and_operation_contract_are_exact() -> None: assert "rate" not in " ".join(map(str, SIPP_HEAD_START_FIT_PARAMETERS.values())) -def test_loader_keeps_only_strict_reported_labels(tmp_path: Path) -> None: +def test_donor_keeps_only_strict_reported_labels(tmp_path: Path) -> None: rows = [ _source_row("yes", 1, head_start_answer=1), _source_row("no", 1, head_start_answer=2), @@ -86,10 +86,8 @@ def test_loader_keeps_only_strict_reported_labels(tmp_path: Path) -> None: _source_row("age_two", 1, age=2, head_start_answer=1), _source_row("month_eleven", 1, month=11, head_start_answer=1), ] - donor = load_sipp_2023_head_start_donor( + donor = _head_start_donor_from_file( _write_source(tmp_path, rows), - expected_sha256=None, - expected_size_bytes=None, chunksize=3, ) @@ -106,16 +104,14 @@ def test_loader_keeps_only_strict_reported_labels(tmp_path: Path) -> None: assert audit["pinned_transform"] is False -def test_loader_refuses_missing_upstream_status(tmp_path: Path) -> None: +def test_read_refuses_missing_upstream_status(tmp_path: Path) -> None: path = _write_source(tmp_path, [_source_row("one", 1)]) source = pd.read_csv(path, sep="|").drop(columns=["AED_SCRNR"]) source.to_csv(path, sep="|", index=False) with pytest.raises(ValueError, match="AED_SCRNR"): - load_sipp_2023_head_start_donor( + _head_start_donor_from_file( path, - expected_sha256=None, - expected_size_bytes=None, ) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_sipp_vehicles.py b/packages/microcosm-build/tests/engine_free/us/test_us_sipp_vehicles.py index 7c682c20e1..8c4cb71d97 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_sipp_vehicles.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_sipp_vehicles.py @@ -12,6 +12,9 @@ import pytest from sklearn.ensemble import RandomForestClassifier +from microcosm.build.us_runtime.sipp_december_person_rows import ( + read_sipp_december_person_rows, +) from microcosm.build.us_runtime.sipp_vehicles import ( _OWNED_OBSERVED_COLUMN, _VALUE_OBSERVED_COLUMN, @@ -30,9 +33,9 @@ _append_owned_dummies, _predictor_encoding, _recipient_household_predictor_table, + build_sipp_2023_vehicle_donor, fetch_sipp_2023_vehicle_donor, impute_us_sipp_vehicles, - load_sipp_2023_vehicle_donor, us_sipp_vehicles_signal_gate, us_sipp_vehicles_stage_spec, us_sipp_vehicles_summary, @@ -43,6 +46,16 @@ TIME_PERIOD = 2026 +def _vehicle_donor_from_file(path: Path, **read_options) -> pd.DataFrame: + return build_sipp_2023_vehicle_donor( + read_sipp_december_person_rows( + path, + columns=SIPP_VEHICLE_SOURCE_COLUMNS, + **read_options, + ) + ) + + def _source_row( household_id: int, person_number: int, @@ -353,9 +366,9 @@ def test_exact_source_columns_predictors_outputs_and_stage_spec() -> None: assert set(US_SIPP_VEHICLE_OUTPUT_COLUMNS) <= set(spec.outputs) -def test_loader_applies_exact_december_household_transform_and_masks(tmp_path) -> None: - donor = load_sipp_2023_vehicle_donor( - _write_sipp_source(tmp_path), expected_size_bytes=None, chunksize=2 +def test_donor_applies_exact_december_household_transform_and_masks(tmp_path) -> None: + donor = _vehicle_donor_from_file( + _write_sipp_source(tmp_path), chunksize=2 ).set_index("household_id") assert donor.index.tolist() == [10, 20, 30, 40] @@ -386,13 +399,12 @@ def test_loader_applies_exact_december_household_transform_and_masks(tmp_path) - assert donor.loc[10, "household_employment_income"] < 100_000 -def test_loader_rejects_missing_columns_and_bad_hash(tmp_path) -> None: +def test_read_rejects_missing_columns_and_bad_hash(tmp_path) -> None: path = _write_sipp_source(tmp_path) with pytest.raises(ValueError, match="sha-256 verification"): - load_sipp_2023_vehicle_donor( + _vehicle_donor_from_file( path, expected_sha256="0" * 64, - expected_size_bytes=None, ) missing_path = tmp_path / "missing.csv" @@ -400,7 +412,7 @@ def test_loader_rejects_missing_columns_and_bad_hash(tmp_path) -> None: missing_path, sep="|", index=False ) with pytest.raises(ValueError, match="missing column"): - load_sipp_2023_vehicle_donor(missing_path, expected_size_bytes=None) + _vehicle_donor_from_file(missing_path) def test_cached_full_donor_matches_pinned_household_support() -> None: @@ -415,7 +427,7 @@ def test_cached_full_donor_matches_pinned_household_support() -> None: if not snapshot.is_file(): pytest.skip("the 3.73 GB pinned SIPP donor is not mounted") - donor = load_sipp_2023_vehicle_donor( + donor = _vehicle_donor_from_file( snapshot, expected_sha256=SIPP_2023_VEHICLE_DONOR_SHA256, expected_size_bytes=SIPP_2023_VEHICLE_DONOR_SIZE_BYTES, 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 44664623b6..330060d03e 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 @@ -418,6 +418,9 @@ # stage shaped like scf_auto_loans. "scf_education_debt.py", "scf_wealth.py", + # Reads the December rows of the SIPP person file once for the five + # SIPP donor builders; reads no frame and treats no population. + "sipp_december_person_rows.py", "sipp_financial_assets.py", "sipp_tips.py", "sipp_vehicles.py", @@ -3871,8 +3874,10 @@ def test_pool_build_tool_import_graph_is_source_spine_blind() -> None: # --location-rule block_v1 household location reaches (#696). 86 adds # battery_bindings.py, gate_scopes.py and gate_shadow.py, the gate # battery the pool runs in shadow beside its gates (#1585 item 11). - assert len(runtime_graph) == 86, ( - f"{tool.name} must reach the pinned 86-module runtime graph; " + # 87 adds sipp_december_person_rows.py, the shared SIPP person-file + # read that sipp_financial_assets.py now builds its donor from. + assert len(runtime_graph) == 87, ( + f"{tool.name} must reach the pinned 87-module runtime graph; " f"reached {len(runtime_graph)}" ) assert not missing_modules, ( diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_voluntary_filing.py b/packages/microcosm-build/tests/engine_free/us/test_us_voluntary_filing.py index 9ad97dd1d7..01dfa44275 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_voluntary_filing.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_voluntary_filing.py @@ -68,14 +68,12 @@ def test_exact_source_columns_predictors_outputs_and_manifest_stage() -> None: ] -def test_loader_uses_reported_answers_drops_dependents_and_pairs_spouses( +def test_donor_uses_reported_answers_drops_dependents_and_pairs_spouses( tmp_path: Path, ) -> None: path = _write_source(tmp_path, _synthetic_source_rows()) - donor = load_sipp_2023_voluntary_filing_donor( - path, expected_size_bytes=None - ).set_index("source_tax_unit_key") + donor = _voluntary_filing_donor_from_file(path).set_index("source_tax_unit_key") assert len(donor) == 2 married_key = next(key for key in donor.index if str(key).startswith("1:")) @@ -94,7 +92,7 @@ def test_loader_uses_reported_answers_drops_dependents_and_pairs_spouses( assert donor["employment_income"].max() < 100_000.0 -def test_loader_rejects_reciprocal_spouse_target_disagreement(tmp_path: Path) -> None: +def test_donor_rejects_reciprocal_spouse_target_disagreement(tmp_path: Path) -> None: rows = [ _source_row(1, 101, spouse=102, filing=1), _source_row( @@ -108,10 +106,10 @@ def test_loader_rejects_reciprocal_spouse_target_disagreement(tmp_path: Path) -> ] path = _write_source(tmp_path, rows) with pytest.raises(ValueError, match="spouses disagree"): - load_sipp_2023_voluntary_filing_donor(path, expected_size_bytes=None) + _voluntary_filing_donor_from_file(path) -def test_loader_reference_is_minimum_pnum_before_response_filter( +def test_donor_reference_is_minimum_pnum_before_response_filter( tmp_path: Path, ) -> None: rows = [ @@ -144,9 +142,9 @@ def test_loader_reference_is_minimum_pnum_before_response_filter( will_file_status=1, ), ] - donor = load_sipp_2023_voluntary_filing_donor( - _write_source(tmp_path, rows), expected_size_bytes=None - ).set_index("source_tax_unit_key") + donor = _voluntary_filing_donor_from_file(_write_source(tmp_path, rows)).set_index( + "source_tax_unit_key" + ) married = donor.loc[next(key for key in donor.index if str(key).startswith("1:"))] assert married["reference_age"] == pytest.approx(63) @@ -155,15 +153,14 @@ def test_loader_reference_is_minimum_pnum_before_response_filter( assert married["employment_income"] == pytest.approx((100 + 200) * 12) -def test_loader_rejects_missing_columns_bad_hash_and_constant_target( +def test_read_and_donor_reject_missing_columns_bad_hash_and_constant_target( tmp_path: Path, ) -> None: path = _write_source(tmp_path, _synthetic_source_rows()) with pytest.raises(ValueError, match="sha-256 verification"): - load_sipp_2023_voluntary_filing_donor( + _voluntary_filing_donor_from_file( path, expected_sha256="0" * 64, - expected_size_bytes=None, ) missing = tmp_path / "missing.csv" @@ -171,7 +168,7 @@ def test_loader_rejects_missing_columns_bad_hash_and_constant_target( missing, sep="|", index=False ) with pytest.raises(ValueError, match="missing column"): - load_sipp_2023_voluntary_filing_donor(missing, expected_size_bytes=None) + _voluntary_filing_donor_from_file(missing) constant = tmp_path / "constant.csv" _write_source( @@ -179,7 +176,7 @@ def test_loader_rejects_missing_columns_bad_hash_and_constant_target( [_source_row(10, 101), _source_row(20, 101)], ).replace(constant) with pytest.raises(ValueError, match="target is constant"): - load_sipp_2023_voluntary_filing_donor(constant, expected_size_bytes=None) + _voluntary_filing_donor_from_file(constant) def test_cached_full_donor_matches_locked_response_and_weight_facts() -> None: @@ -196,7 +193,7 @@ def test_cached_full_donor_matches_locked_response_and_weight_facts() -> None: if not snapshot.is_file(): pytest.skip("the 3.73 GB pinned SIPP donor is not mounted") - donor = load_sipp_2023_voluntary_filing_donor( + donor = _voluntary_filing_donor_from_file( snapshot, expected_sha256=SIPP_2023_VOLUNTARY_FILING_DONOR_SHA256, expected_size_bytes=SIPP_2023_VOLUNTARY_FILING_DONOR_SIZE_BYTES, 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 6c8a88b05e..68f1f6a56a 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 @@ -370,7 +370,8 @@ def capture_equality(expected: object, actual: object) -> None: # The QRF draw's default thread count, joblib.cpu_count() in # microcosm.fit.qrf, moves it again. # calibrate's return_frame option in solve moves it again. - "spec_sha256": "2e3093b6acc4926e80e96b080c3bfe2727baa22127ebfb9faf8a1ef05eda0f50", + # microcosm#1686's shared SIPP person-file read moves it again. + "spec_sha256": "499389d4b1f0c967c54a6f2fa81b8a07a7e59c045bf2a8fe6bb909f08561d049", }, } diff --git a/test_support/microcosm_build/us_sipp_head_start.py b/test_support/microcosm_build/us_sipp_head_start.py index 51bfa9adaa..cdf16b5d2c 100644 --- a/test_support/microcosm_build/us_sipp_head_start.py +++ b/test_support/microcosm_build/us_sipp_head_start.py @@ -14,6 +14,9 @@ import microcosm.build.us_runtime.sipp_head_start as module from microcosm.build.us_runtime.puf_support import clone_us_frame_for_puf_support +from microcosm.build.us_runtime.sipp_december_person_rows import ( + read_sipp_december_person_rows, +) from microcosm.build.us_runtime.sipp_head_start import ( HEAD_START_SIPP_DICTIONARY_URL, SIPP_2023_HEAD_START_DONOR_REVISION, @@ -28,8 +31,8 @@ US_SIPP_HEAD_START_OUTPUT_COLUMNS, US_SIPP_HEAD_START_REQUIRED_SOURCE_COLUMNS, US_SIPP_HEAD_START_STAGE_NAME, + build_sipp_2023_head_start_donor, impute_us_sipp_head_start, - load_sipp_2023_head_start_donor, us_sipp_head_start_signal_gate, us_sipp_head_start_summary, with_us_sipp_head_start_input, @@ -51,6 +54,16 @@ def _load_tail_fixtures(): _TAIL = _load_tail_fixtures() +def _head_start_donor_from_file(path: Path, **read_options) -> pd.DataFrame: + return build_sipp_2023_head_start_donor( + read_sipp_december_person_rows( + path, + columns=SIPP_HEAD_START_SOURCE_COLUMNS, + **read_options, + ) + ) + + def _source_row( ssuid: str, pnum: int, diff --git a/test_support/microcosm_build/us_voluntary_filing.py b/test_support/microcosm_build/us_voluntary_filing.py index 0684f92d3b..8961388151 100644 --- a/test_support/microcosm_build/us_voluntary_filing.py +++ b/test_support/microcosm_build/us_voluntary_filing.py @@ -20,6 +20,9 @@ from microcosm.build.us_runtime.release_input_coverage import ( us_release_reform_coverage_probes, ) +from microcosm.build.us_runtime.sipp_december_person_rows import ( + read_sipp_december_person_rows, +) from microcosm.build.us_runtime.voluntary_filing import ( SIPP_2023_VOLUNTARY_FILING_DONOR_REVISION, SIPP_2023_VOLUNTARY_FILING_DONOR_SHA256, @@ -33,9 +36,9 @@ VOLUNTARY_FILING_ARCHIVED_DERIVATION_URL, VOLUNTARY_FILING_ARCHIVED_PARAMETERS_URL, VOLUNTARY_FILING_SIPP_DICTIONARY_URL, + build_sipp_2023_voluntary_filing_donor, fetch_sipp_2023_voluntary_filing_donor, impute_us_voluntary_filing, - load_sipp_2023_voluntary_filing_donor, us_voluntary_filing_signal_gate, us_voluntary_filing_stage_spec, us_voluntary_filing_summary, @@ -46,6 +49,16 @@ _OUTPUT = US_VOLUNTARY_FILING_OUTPUT_COLUMNS[0] +def _voluntary_filing_donor_from_file(path: Path, **read_options) -> pd.DataFrame: + return build_sipp_2023_voluntary_filing_donor( + read_sipp_december_person_rows( + path, + columns=SIPP_VOLUNTARY_FILING_SOURCE_COLUMNS, + **read_options, + ) + ) + + def _load_tail_fixtures(): path = Path(__file__).with_name("us_tail_clone_fixtures.py") spec = importlib.util.spec_from_file_location("us_tail_clone_fixtures", path) diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index e0d212a6e0..a39f775313 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -114,15 +114,12 @@ SCF_2025_SUMMARY_EXTRACT, SIPP_2023_FINANCIAL_ASSET_DONOR_SHA256, SIPP_2023_FINANCIAL_ASSET_DONOR_SIZE_BYTES, - SIPP_2023_HEAD_START_DONOR_SHA256, - SIPP_2023_HEAD_START_DONOR_SIZE_BYTES, - SIPP_2023_SSI_DISABILITY_DONOR_SHA256, - SIPP_2023_SSI_DISABILITY_DONOR_SIZE_BYTES, SIPP_2023_TIP_DONOR_SHA256, - SIPP_2023_VEHICLE_DONOR_SHA256, - SIPP_2023_VEHICLE_DONOR_SIZE_BYTES, - SIPP_2023_VOLUNTARY_FILING_DONOR_SHA256, - SIPP_2023_VOLUNTARY_FILING_DONOR_SIZE_BYTES, + SIPP_FINANCIAL_ASSET_SOURCE_COLUMNS, + SIPP_HEAD_START_SOURCE_COLUMNS, + SIPP_SSI_DISABILITY_SOURCE_COLUMNS, + SIPP_VEHICLE_SOURCE_COLUMNS, + SIPP_VOLUNTARY_FILING_SOURCE_COLUMNS, SOI_VARIABLE_MAP, US_FISCAL_TARGET_COVERAGE_REQUIREMENTS, US_FISCAL_TARGET_SUPPORT_EXCLUSIONS, @@ -136,6 +133,11 @@ assert_take_up_treatments_consistent, assert_target_parity_manifest_current, assert_validation_leaf_registry_current, + build_sipp_2023_financial_asset_donor, + build_sipp_2023_head_start_donor, + build_sipp_2023_ssi_disability_donor, + build_sipp_2023_vehicle_donor, + build_sipp_2023_voluntary_filing_donor, compile_us_fiscal_target_registry, default_congressional_district_vintage_crosswalk_path, fetch_asec_2023_weeks_unemployed_source, @@ -152,12 +154,8 @@ load_scf_2022_auto_loan_donor, load_scf_2022_financial_asset_donor, load_scf_2025_education_debt_donor, - load_sipp_2023_financial_asset_donor, - load_sipp_2023_head_start_donor, - load_sipp_2023_ssi_disability_donor, load_sipp_2023_tip_donor, - load_sipp_2023_vehicle_donor, - load_sipp_2023_voluntary_filing_donor, + read_sipp_december_person_rows, ssi_take_up_prior_basis_from_artifact, ssi_take_up_prior_basis_from_diagnostics, us_alimony_signal_gate, @@ -15429,6 +15427,20 @@ def _check_us_feed_carries_fsa_facts( return plan +# Every column the five donor tables built from the full SIPP 2023 file use. +_SIPP_2023_DONOR_SOURCE_COLUMNS = tuple( + sorted( + { + *SIPP_FINANCIAL_ASSET_SOURCE_COLUMNS, + *SIPP_SSI_DISABILITY_SOURCE_COLUMNS, + *SIPP_HEAD_START_SOURCE_COLUMNS, + *SIPP_VEHICLE_SOURCE_COLUMNS, + *SIPP_VOLUNTARY_FILING_SOURCE_COLUMNS, + } + ) +) + + def _main(argv: Sequence[str] | None = None) -> int | None: global _ACTIVE_EMITTER, _ACTIVE_PROGRESS _ACTIVE_EMITTER = None @@ -16993,25 +17005,29 @@ def _main(argv: Sequence[str] | None = None) -> int | None: else fetch_scf_2022_summary_extract() ) # The asset blend, SSI criterion, Head Start, vehicle, and filing families - # share one immutable full SIPP artifact. Resolve it once; the CLI option's - # historical name remains stable for existing release invocations. + # share one immutable full SIPP artifact. Resolve it once and parse it once; + # each stage builds its donor table from these December rows, which stay in + # memory until the last of the five stages. The CLI option's historical name + # remains stable for existing release invocations. sipp_full_donor_path = ( Path(args.sipp_vehicle_donor) if args.sipp_vehicle_donor is not None else fetch_sipp_2023_financial_asset_donor() ) - # Each donor table below is loaded in its stage's call, so no local keeps - # it once the stage returns. + # Each donor table below is loaded or built in its stage's call, so no + # local keeps it once the stage returns. + sipp_december_person_rows = read_sipp_december_person_rows( + sipp_full_donor_path, + columns=_SIPP_2023_DONOR_SOURCE_COLUMNS, + expected_sha256=SIPP_2023_FINANCIAL_ASSET_DONOR_SHA256, + expected_size_bytes=SIPP_2023_FINANCIAL_ASSET_DONOR_SIZE_BYTES, + ) base_frame = with_us_scf_wealth_inputs( base_frame, seed=args.seed, time_period=PERIOD, scf_donor=load_scf_2022_financial_asset_donor(scf_summary_extract_path), - sipp_donor=load_sipp_2023_financial_asset_donor( - sipp_full_donor_path, - expected_sha256=SIPP_2023_FINANCIAL_ASSET_DONOR_SHA256, - expected_size_bytes=SIPP_2023_FINANCIAL_ASSET_DONOR_SIZE_BYTES, - ), + sipp_donor=build_sipp_2023_financial_asset_donor(sipp_december_person_rows), ) scf_wealth_gate = shadow_gate( "us_national_scf_wealth", @@ -17042,7 +17058,6 @@ def _main(argv: Sequence[str] | None = None) -> int | None: scf_wealth_signal = _scf_wealth_gate_record( scf_wealth_gate, base_frame.table("household")["household_id"] ) - sipp_vehicle_donor_path = sipp_full_donor_path if telemetry is not None: telemetry.stage( "ssi_disability_criteria", @@ -17056,10 +17071,8 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # The retired weighted bootstrap and MicroImpute forest are fixed. seed=42, time_period=PERIOD, - sipp_donor=load_sipp_2023_ssi_disability_donor( - sipp_vehicle_donor_path, - expected_sha256=SIPP_2023_SSI_DISABILITY_DONOR_SHA256, - expected_size_bytes=SIPP_2023_SSI_DISABILITY_DONOR_SIZE_BYTES, + sipp_donor=build_sipp_2023_ssi_disability_donor( + sipp_december_person_rows, time_period=PERIOD, ), ) @@ -17097,11 +17110,7 @@ def _main(argv: Sequence[str] | None = None) -> int | None: base_frame, seed=args.seed, time_period=PERIOD, - sipp_donor=load_sipp_2023_head_start_donor( - sipp_vehicle_donor_path, - expected_sha256=SIPP_2023_HEAD_START_DONOR_SHA256, - expected_size_bytes=SIPP_2023_HEAD_START_DONOR_SIZE_BYTES, - ), + sipp_donor=build_sipp_2023_head_start_donor(sipp_december_person_rows), ) head_start_gate = _shadow_frame_gate( "us_national_sipp_head_start", @@ -17281,11 +17290,7 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # The retired MicroImpute model pins both forests to seed 42. seed=42, time_period=PERIOD, - sipp_donor=load_sipp_2023_vehicle_donor( - sipp_vehicle_donor_path, - expected_sha256=SIPP_2023_VEHICLE_DONOR_SHA256, - expected_size_bytes=SIPP_2023_VEHICLE_DONOR_SIZE_BYTES, - ), + sipp_donor=build_sipp_2023_vehicle_donor(sipp_december_person_rows), ) sipp_vehicles_gate = _shadow_frame_gate( "us_national_sipp_vehicles", @@ -17320,12 +17325,9 @@ def _main(argv: Sequence[str] | None = None) -> int | None: base_frame, seed=args.seed, time_period=PERIOD, - sipp_donor=load_sipp_2023_voluntary_filing_donor( - sipp_vehicle_donor_path, - expected_sha256=SIPP_2023_VOLUNTARY_FILING_DONOR_SHA256, - expected_size_bytes=SIPP_2023_VOLUNTARY_FILING_DONOR_SIZE_BYTES, - ), + sipp_donor=build_sipp_2023_voluntary_filing_donor(sipp_december_person_rows), ) + del sipp_december_person_rows voluntary_filing_gate = _shadow_frame_gate( "us_national_voluntary_filing", lambda: us_voluntary_filing_signal_gate(base_frame),