diff --git a/changelog.d/frame-adopt-replace-tables.added.md b/changelog.d/frame-adopt-replace-tables.added.md index a4b43985a8..03f1e68dff 100644 --- a/changelog.d/frame-adopt-replace-tables.added.md +++ b/changelog.d/frame-adopt-replace-tables.added.md @@ -1 +1 @@ -Add `Frame.replace_tables(**tables)` and `Frame.with_columns(entity, **columns)`, which build a new frame that shares the memory of unchanged tables and columns with the source frame when pandas copy-on-write is on, instead of deep-copying every table; with copy-on-write off they deep-copy. Both go through the new private `Frame._adopt`, which runs the constructor's full validation. The default `Frame` constructor still deep-copies, and no build code calls the new methods yet, so outputs are unchanged. A new test reads the Python source under `packages/*/src/` and `tools/` and fails on raw writes into array memory that copy-on-write does not protect: `setflags(write=True)`, item assignment through `Series.array`, pandas private attributes such as `._mgr` and `._ndarray`, `np.copyto`, and `out=` or `ufunc.at` into an array the code did not create. Graph nodes whose kernels hash `bundle.py`, including the `calibrate` and `simulate` parity pins, get new cache keys. +Add `Frame.replace_tables(**tables)` and `Frame.with_columns(entity, **columns)`, which build a new frame that shares the memory of unchanged tables and columns with the source frame when pandas copy-on-write is on, instead of deep-copying every table; with copy-on-write off they deep-copy. Both go through the new `Frame.adopt`, which runs the constructor's full validation. The default `Frame` constructor still deep-copies, and no build code calls the new methods yet, so outputs are unchanged. A new test reads the Python source under `packages/*/src/` and `tools/` and fails on raw writes into array memory that copy-on-write does not protect: `setflags(write=True)`, item assignment through `Series.array`, pandas private attributes such as `._mgr` and `._ndarray`, `np.copyto`, and `out=` or `ufunc.at` into an array the code did not create. Graph nodes whose kernels hash `bundle.py`, including the `calibrate` and `simulate` parity pins, get new cache keys. diff --git a/changelog.d/frame-operations-share-columns.changed.md b/changelog.d/frame-operations-share-columns.changed.md new file mode 100644 index 0000000000..18f7f0171a --- /dev/null +++ b/changelog.d/frame-operations-share-columns.changed.md @@ -0,0 +1 @@ +`Frame.with_weights`, `Frame.place`, `Frame.select` and `load_frame_checkpoint` no longer deep-copy every table. Under pandas copy-on-write, frames from the three `Frame` operations share the memory of unchanged columns with their source, and the loader keeps the columns it decoded without a second copy. `calibrate` gains `return_frame=False`, which runs the same weight checks and returns the weights and diagnostics with `frame=None`. `Frame.adopt(tables, schema, weights, ...)` is now public, so other packages can build a frame that takes ownership of tables it decoded or built, as `load_frame_checkpoint` does: it validates like the constructor and, under copy-on-write, stores the given DataFrames without copying them. The caller must not write to those DataFrames afterwards, and `adopt` records no columns for `Frame.check_shared_columns`. diff --git a/changelog.d/frame-shared-column-check.added.md b/changelog.d/frame-shared-column-check.added.md new file mode 100644 index 0000000000..faa13479ce --- /dev/null +++ b/changelog.d/frame-shared-column-check.added.md @@ -0,0 +1 @@ +Every build now checks columns that frames share. Frame operations record a SHA-256 digest of each column when they start sharing it. The `Frame` constructor, `engine_tables`, and checkpoint and output writers compare the digests first, and raise `SharedColumnChangedError` naming each table and column whose shared memory was changed in place. `Frame.replace_tables` and `Frame.with_columns` also compare each recorded column they drop or replace before building the new frame, so a changed column cannot leave unreported while a column derived from it carries the change on. diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index 2245f28aab..fe4f4a87e9 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": "530bdaf982c7ad2440db7b4b02f8de5843dac083c6e36c28385ce5d8bbb23e35", - "protocol_sha256": "f5cc748f1b9fbeaea54c18d9e2c1e6e74f2679c9cbf6cf7a09e7b548d2788d66" + "map_sha256": "1dda5e09b93e4acd51844bfbd62555adfc91d309e0f7647d64b959e0820d1d1e", + "protocol_sha256": "90d566bb670521cc79f42cba8afe14fe79330ac2c990858dbe8f7debe1466fa5" }, "failures": [], "observed": { - "map_sha256": "530bdaf982c7ad2440db7b4b02f8de5843dac083c6e36c28385ce5d8bbb23e35", - "protocol_sha256": "f5cc748f1b9fbeaea54c18d9e2c1e6e74f2679c9cbf6cf7a09e7b548d2788d66" + "map_sha256": "1dda5e09b93e4acd51844bfbd62555adfc91d309e0f7647d64b959e0820d1d1e", + "protocol_sha256": "90d566bb670521cc79f42cba8afe14fe79330ac2c990858dbe8f7debe1466fa5" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "f5cc748f1b9fbeaea54c18d9e2c1e6e74f2679c9cbf6cf7a09e7b548d2788d66", + "implementation_sha256": "90d566bb670521cc79f42cba8afe14fe79330ac2c990858dbe8f7debe1466fa5", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "f5cc748f1b9fbeaea54c18d9e2c1e6e74f2679c9cbf6cf7a09e7b548d2788d66", + "implementation_sha256": "90d566bb670521cc79f42cba8afe14fe79330ac2c990858dbe8f7debe1466fa5", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "067676ed540f9a6d7981ce5df546e81384cf0409446b04b4cbc637db5a43ea22" + "spec_sha256": "2e3093b6acc4926e80e96b080c3bfe2727baa22127ebfb9faf8a1ef05eda0f50" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "067676ed540f9a6d7981ce5df546e81384cf0409446b04b4cbc637db5a43ea22" + "spec_sha256": "2e3093b6acc4926e80e96b080c3bfe2727baa22127ebfb9faf8a1ef05eda0f50" }, "status": "pass" } diff --git a/docs/us-local-annual-projection.md b/docs/us-local-annual-projection.md index 385d71aae7..822eb1f6e2 100644 --- a/docs/us-local-annual-projection.md +++ b/docs/us-local-annual-projection.md @@ -233,7 +233,8 @@ tables: On top of those sit the slim aging frame, a fraction of S, and about 2 GB of cell counts and engine objects. That comes to roughly 5.3 × S + 2 GB, or 55 to 80 GB. Run it alone on the 128 GiB host. The calibration result's frame -copy is released before the export. The write and the loader check each hold +shares the calibrated frame's tables instead of copying them, and the result is +released before the export. The write and the loader check each hold about 2.5 × S. **Wall time.** Roughly 30 to 60 minutes for two years on an otherwise idle diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index 3736f31b7f..92645b1559 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -522,10 +522,13 @@ reform and does not replace this sweep. (method, batch size, batch count, each stage's baseline keys and periods), and `reform_coverage_smoke.json` records what the smoke scored under `post_export_scoring`. Poverty rows stay record-only. Before the export write -the build frees the target frame and the calibration result's target tables: -`Frame.with_weights` copies every table, target columns included. Dense and -L0 results drop those frames; exact-k substitutes the clean export frame for -its receipt's later household-count check. The fixture sweep does not measure +the build frees the target frame and the calibration result's target tables. +A result frame that `Frame.with_weights` builds from the target frame (the +dense result, an L0 selection) shares every table's memory with it, target +columns included, so the tables are freed only once both the target frame and +those result frames are dropped. Dense and L0 results drop those frames; exact-k +substitutes the clean export frame for its receipt's later household-count +check. The fixture sweep does not measure memory or wall time of the batched stages at full size. ## Probing an export on a household subsample diff --git a/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py b/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py index ac26729c6c..44c2f42c29 100644 --- a/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py +++ b/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py @@ -94,10 +94,16 @@ def write_frame_checkpoint( *, metadata: Mapping[str, object] | None = None, ) -> Path: - """Atomically write a deterministic checkpoint, one column at a time.""" + """Atomically write a deterministic checkpoint, one column at a time. + + Raises: + SharedColumnChangedError: If a raw write changed a column the frame + shares. Nothing is written. + """ if not isinstance(frame, Frame): raise TypeError(f"frame must be a Frame, got {type(frame).__name__}.") + frame.check_shared_columns() external_metadata = _normalize_external_metadata(metadata) checkpoint_metadata = _checkpoint_metadata(frame, external_metadata) @@ -175,9 +181,17 @@ def load_frame_checkpoint( ) -> LoadedFrameCheckpoint: """Load a checkpoint and reconstruct its schema, data, and audit metadata. + The frame takes the decoded tables without copying them when pandas + copy-on-write is on (:meth:`~microcosm.frame.Frame.adopt`), so each + loaded table keeps one internal block per column; values, dtypes and the + bytes a rewrite produces are unchanged. A pandas fixed-format HDF write, + which stores one dataset per internal block, can therefore group a loaded + table's columns into different datasets than a write of the same table + built in memory; the values read back by column name are the same. + ``frame_metadata`` lets a caller restore separately bound :class:`~microcosm.frame.Frame` metadata during the loader's one Frame - construction. This avoids a second full-table copy for large checkpoints. + construction. This avoids building a second frame for large checkpoints. The caller remains responsible for validating that metadata against its own artifact identity or embedded external metadata. """ @@ -299,7 +313,10 @@ def load_frame_checkpoint( ) mass_log = _mass_log_from_metadata(stored_metadata, input_path) try: - frame = Frame( + # The decoded tables have no other owner, so the frame takes them + # without copying (under pandas copy-on-write): reading a checkpoint + # holds one copy of its data, not the decoded columns plus a copy. + frame = Frame.adopt( tables, schema, weights, 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 22450991ab..008d68bf4e 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 @@ -409,8 +409,10 @@ # acs_transfer's attested bytes change; no draw, RNG rule or QRF target does. # The QRF draw's default thread count, joblib.cpu_count() in place of # os.cpu_count() in microcosm.fit.qrf, moves both again; no draw changes. - "seed_map": "530bdaf982c7ad2440db7b4b02f8de5843dac083c6e36c28385ce5d8bbb23e35", - "seed_protocol": "f5cc748f1b9fbeaea54c18d9e2c1e6e74f2679c9cbf6cf7a09e7b548d2788d66", + # calibrate's return_frame option in solve moves both again; the default + # is unchanged, and no draw changes. + "seed_map": "1dda5e09b93e4acd51844bfbd62555adfc91d309e0f7647d64b959e0820d1d1e", + "seed_protocol": "90d566bb670521cc79f42cba8afe14fe79330ac2c990858dbe8f7debe1466fa5", "source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6", "take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35", "tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0", diff --git a/packages/microcosm-build/src/microcosm/build/transport/population_kernels.py b/packages/microcosm-build/src/microcosm/build/transport/population_kernels.py index 00f8257322..b0c2d4370f 100644 --- a/packages/microcosm-build/src/microcosm/build/transport/population_kernels.py +++ b/packages/microcosm-build/src/microcosm/build/transport/population_kernels.py @@ -37,6 +37,7 @@ import microcosm.frame.materialize as materialize_module import microcosm.frame.scaling as scaling_module import microcosm.frame.schema as schema_module +import microcosm.frame.shared_columns as shared_columns_module import microcosm.frame.transport as transport_module import microcosm.frame.unit_construction as units_module import microcosm.frame.weights as weights_module @@ -167,6 +168,7 @@ def implementation_hash(self) -> str: scaling_module, bundle_module, schema_module, + shared_columns_module, weights_module, *target_kernels._COMPILE_MODULES, dependencies=self.capabilities.dependencies, diff --git a/packages/microcosm-build/src/microcosm/build/transport/target_kernels.py b/packages/microcosm-build/src/microcosm/build/transport/target_kernels.py index cdea94844e..940f99fbb8 100644 --- a/packages/microcosm-build/src/microcosm/build/transport/target_kernels.py +++ b/packages/microcosm-build/src/microcosm/build/transport/target_kernels.py @@ -62,6 +62,7 @@ import microcosm.calibrate.target as target_module import microcosm.frame.bundle as frame_bundle_module import microcosm.frame.schema as frame_schema_module +import microcosm.frame.shared_columns as frame_shared_columns_module import microcosm.frame.unit_construction as units_module import microcosm.frame.weights as frame_weights_module from microcosm.build.calibration_columns import prepare_calibration_columns @@ -572,6 +573,7 @@ def _optional_float(value: float) -> float | None: target_module, frame_bundle_module, frame_schema_module, + frame_shared_columns_module, frame_weights_module, ) diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/national_frame.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/national_frame.py index 0a2e440a96..031b0d6fb5 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/national_frame.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/national_frame.py @@ -1120,11 +1120,13 @@ def uk_release_export_frame(frame: Frame) -> Frame: of the share keys' components at the frame's weights (:func:`uk_household_totals`); the dataset-year division sums them again at the weights the file stores (``weight_year.uk_dataset_year_frame``). A - frame that already left passes unchanged. + frame that already left passes unchanged. The tables are copied below, so + shared columns are checked first. """ from .geography_ladder import export_area_code_columns + frame.check_shared_columns() tables: dict[str, pd.DataFrame] = {} changed = False for entity in ("person", "benunit", "household"): diff --git a/packages/microcosm-build/src/microcosm/build/us_annual_static_aging.py b/packages/microcosm-build/src/microcosm/build/us_annual_static_aging.py index 8574156ec0..9275ddccf2 100644 --- a/packages/microcosm-build/src/microcosm/build/us_annual_static_aging.py +++ b/packages/microcosm-build/src/microcosm/build/us_annual_static_aging.py @@ -68,11 +68,13 @@ most five full copies of the entity tables at once, inside :func:`microcosm.frame.adapters.policyengine_us.multi_year_dataset` (the frame, its export copy, the base-year dataset, the year's tables and the year's -dataset); the calibration result's frame copy is released before that call. -The local line holds the same five plus the slim aging frame and its -calibration copy (only ids, memberships, the age-sex cells and the factored -columns), then the frame, the year's frame and one entity table during the -write, and the frame plus the native reload during the loader check. +dataset). The calibration result's frame shares the calibrated frame's tables +rather than copying them, and the result is released before that call. The +local line holds the same five plus the slim aging frame (only ids, +memberships, the age-sex cells and the factored columns), whose calibration +result shares its tables, then the frame, the year's frame and one entity +table during the write, and the frame plus the native reload during the +loader check. """ from __future__ import annotations @@ -1175,8 +1177,10 @@ def build_annual_static_aging( ), "fraction_within_10pct": float(projection.fraction_within_10pct), } - # The calibration result holds a full copy of the frame it - # calibrated; release it before the export copies are made. + # The calibration result's frame shares the calibrated frame's + # tables (Frame.with_weights does not copy them); release the + # result, and its constraint matrix, before the export copies + # are made. del projection, result if local: refuse_protected_factors(factors, what=f"the {year} factors") diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_ssi_medicaid_take_up.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_ssi_medicaid_take_up.py index e0799b5956..e129bd97e3 100755 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_ssi_medicaid_take_up.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_ssi_medicaid_take_up.py @@ -853,9 +853,10 @@ def with_acs_local_ssi_medicaid_take_up( medicaid_eligibility=medicaid_eligibility, ) - # Engine pre-pass over the ACS households only. ``select`` copied every - # table, so the view is this stage's own: its missing take-up cells read - # True, as the engine default would, and neither variable reads its flag. + # Engine pre-pass over the ACS households only. ``select`` gives the view + # its own DataFrame objects, so columns assigned here stay on it: its + # missing take-up cells read True, as the engine default would, and + # neither variable reads its flag. view = frame.select(acs) view_person = view.table("person") if not np.array_equal(view_person["person_id"].to_numpy(), person_ids): diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/h5_io.py b/packages/microcosm-build/src/microcosm/build/us_runtime/h5_io.py index 29c6b9a6f0..4bb698ad9c 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/h5_io.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/h5_io.py @@ -3081,11 +3081,14 @@ def write_nullable_us_h5( verified every nonempty entity table, household weights, period metadata, fixed-format storage, caller-declared root attributes, and the ``artifact_kind``. A failed write or verification leaves any existing - destination bytes untouched. + destination bytes untouched. A raw write into a column the frame shares + raises ``SharedColumnChangedError`` before anything is written; string + columns are converted below, so the check must come first. """ if not isinstance(frame, Frame): raise TypeError(f"frame must be a Frame, got {type(frame).__name__}.") + frame.check_shared_columns() if not isinstance(artifact_kind, str) or not artifact_kind.strip(): raise ValueError("artifact_kind must be a non-empty string.") if publication_run_id is not None and ( diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/spm_independence_role.py b/packages/microcosm-build/src/microcosm/build/us_runtime/spm_independence_role.py index c7441e3726..6390ebe393 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/spm_independence_role.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/spm_independence_role.py @@ -397,6 +397,8 @@ def with_us_spm_independence_role( if frame.schema != US_SCHEMA: raise ValueError("US SPM independence role requires the US schema.") + # The stage below works on deep copies, which could not show a raw write. + frame.check_shared_columns() person = frame.table("person") existing_role = ( person[NATIVE_SPM_ROLE] if NATIVE_SPM_ROLE in person.columns else None diff --git a/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint.py b/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint.py index 7c79ba3f81..99c5ab17e5 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint.py @@ -1,9 +1,11 @@ from __future__ import annotations +import hashlib import json import os import stat import time +from collections.abc import Iterator from pathlib import Path import numpy as np @@ -19,10 +21,13 @@ EntitySchema, Frame, LinkSpec, + MassChange, MassChangeRecord, + SharedColumnChangedError, WeightKind, Weights, ) +from microcosm.frame import shared_columns as shared_columns_module def _checkpoint_frame() -> Frame: @@ -741,3 +746,391 @@ def test_legacy_string_specs_restore_python_storage() -> None: path=Path("legacy.h5"), label="person.label", ) + + +@pytest.fixture +def copy_on_write_on() -> Iterator[None]: + """Turn copy-on-write on under pandas 2.x; pandas 3 always has it on.""" + + if int(pd.__version__.split(".", 1)[0]) >= 3: + yield + return + with pd.option_context("mode.copy_on_write", True): + yield + + +def test_loader_keeps_the_decoded_columns_without_copying( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, copy_on_write_on: None +) -> None: + """The loaded frame holds the columns the loader decoded, not a copy. + + The loader builds its one frame through ``Frame.adopt``, so reading a + checkpoint holds one copy of the data instead of the decoded columns plus + the constructor's copy of them. + """ + path = tmp_path / "frame.h5" + write_frame_checkpoint(path, _checkpoint_frame()) + decoded: dict[str, pd.Series] = {} + read_series = frame_checkpoint_module._read_series + + def recording_read_series(group, spec, input_path, *, label): + series = read_series(group, spec, input_path, label=label) + decoded[label] = series + return series + + monkeypatch.setattr(frame_checkpoint_module, "_read_series", recording_read_series) + + loaded = load_frame_checkpoint(path).frame + + compared = [] + for name, table in frame_checkpoint_module._frame_tables(loaded): + for column in table.select_dtypes("number").columns: + assert np.shares_memory( + table[column].to_numpy(), decoded[f"{name}.{column}"].to_numpy() + ), f"{name}.{column}" + compared.append(f"{name}.{column}") + assert {"person.float_measure", "household.household_income"} <= set(compared) + + +def _named_axes_frame() -> Frame: + """The checkpoint fixture with named column axes on two of its tables.""" + + frame = _checkpoint_frame() + tables = dict(frame_checkpoint_module._frame_tables(frame)) + for name in ("person", "household"): + tables[name] = tables[name].copy() + tables[name].columns.name = f"{name}_fields" + return Frame( + tables, + frame.schema, + {entity: frame.weights_for(entity) for entity in frame.weighted_entities}, + frame.strata, + mass_log=frame.mass_log, + metadata=frame.metadata, + ) + + +#: Source frames for the checkpoint comparisons below. +_SOURCE_FRAMES = { + "fixture": _checkpoint_frame, + "named column axes": _named_axes_frame, +} + + +def _without_links(frame: Frame) -> Frame: + """The frame with its link tables dropped, which ``Frame.select`` requires.""" + + return Frame( + {entity: frame.table(entity) for entity in frame.entities}, + EntitySchema( + person_entity=frame.schema.person_entity, + group_entities=frame.schema.group_entities, + ), + {entity: frame.weights_for(entity) for entity in frame.weighted_entities}, + frame.strata, + mass_log=frame.mass_log, + metadata=frame.metadata, + ) + + +def _doubled_household_weights(frame: Frame) -> Frame: + current = frame.weights_for("household") + return frame.with_weights( + "household", + Weights(current.values * 2.0, WeightKind.CALIBRATED), + mass=MassChange(factor=2.0, reason="test calibration"), + ) + + +#: Operations that build their result through ``Frame.adopt``. +_ADOPTING_OPERATIONS = { + "with_weights": _doubled_household_weights, + "place person to household": lambda frame: frame.place( + "small_integer", "household", how="sum" + ), + "place household to person": lambda frame: frame.place( + "household_income", "person", how="broadcast" + ), + "place a string to firm": lambda frame: frame.place( + "string_label", "firm", how="first" + ), + "select every person": lambda frame: _without_links(frame).select( + np.ones(frame.n("person"), dtype=bool) + ), + "select two persons": lambda frame: _without_links(frame).select( + np.asarray([True, False, True]) + ), + "no operation": lambda frame: frame, +} + + +def _derived_frame( + directory: Path, source_frame: str, source: str, operation: str +) -> Frame: + """Run ``operation`` on a source frame, built directly or loaded from disk.""" + + frame = _SOURCE_FRAMES[source_frame]() + if source == "loaded": + write_frame_checkpoint(directory / "source.h5", frame) + frame = load_frame_checkpoint(directory / "source.h5").frame + return _ADOPTING_OPERATIONS[operation](frame) + + +def _checkpoint_content_sha256(path: Path) -> str: + """SHA-256 of every dataset in a checkpoint: its name, dtype, shape and bytes. + + The metadata JSON is one of the datasets. Hashing what the datasets hold, + rather than the file, keeps the digest independent of the HDF5 build, + whose file layout differs between platforms. + """ + + h5py = pytest.importorskip("h5py") + digest = hashlib.sha256() + with h5py.File(path, mode="r") as h5: + dataset_names: list[str] = [] + h5.visititems( + lambda name, item: ( + dataset_names.append(name) if isinstance(item, h5py.Dataset) else None + ) + ) + for name in sorted(dataset_names): + values = np.asarray(h5[name]) + digest.update(f"{name}\0{values.dtype.str}\0{values.shape!r}\0".encode()) + digest.update(values.tobytes()) + return digest.hexdigest() + + +#: Checkpoint content digests of each operation's result, recorded with the +#: copying implementation at commit 8afea44e9, before ``with_weights``, +#: ``place``, ``select`` and the loader moved to ``Frame.adopt``. +_COPYING_IMPLEMENTATION_CONTENT_SHA256: dict[tuple[str, str, str], str] = { + ( + "fixture", + "constructed", + "with_weights", + ): "a3f0e69dd495e6f9e45caa4d13851a9356c7810df828fbe2bdba38a94272db72", + ( + "fixture", + "constructed", + "place person to household", + ): "9f5e81635306d47e73ae0fb4b593edcf1f47b6b40c865197e641a9b1adfb89c5", + ( + "fixture", + "constructed", + "place household to person", + ): "92eafb157899735517c357a02459528b5f8b9d08a5f6c070a79d4cb043bd314b", + ( + "fixture", + "constructed", + "place a string to firm", + ): "a7314048203f36611c2ff9011150b5bda8476407b618949756f681df5c82cb7b", + ( + "fixture", + "constructed", + "select every person", + ): "05ef02724683caa4e5815702b3a2d291573c8e39fba9022e4b3360da4054d0e8", + ( + "fixture", + "constructed", + "select two persons", + ): "4a4dc266b99efa4075a3bbf45163040e21445a62da8d0c2eee7a4fd06abc0672", + ( + "fixture", + "constructed", + "no operation", + ): "ad3d5745332e9725b941f2db6e1eb60e5d93dfdd5204fefe3497e7c702b5e543", + ( + "fixture", + "loaded", + "with_weights", + ): "a3f0e69dd495e6f9e45caa4d13851a9356c7810df828fbe2bdba38a94272db72", + ( + "fixture", + "loaded", + "place person to household", + ): "9f5e81635306d47e73ae0fb4b593edcf1f47b6b40c865197e641a9b1adfb89c5", + ( + "fixture", + "loaded", + "place household to person", + ): "92eafb157899735517c357a02459528b5f8b9d08a5f6c070a79d4cb043bd314b", + ( + "fixture", + "loaded", + "place a string to firm", + ): "a7314048203f36611c2ff9011150b5bda8476407b618949756f681df5c82cb7b", + ( + "fixture", + "loaded", + "select every person", + ): "05ef02724683caa4e5815702b3a2d291573c8e39fba9022e4b3360da4054d0e8", + ( + "fixture", + "loaded", + "select two persons", + ): "4a4dc266b99efa4075a3bbf45163040e21445a62da8d0c2eee7a4fd06abc0672", + ( + "fixture", + "loaded", + "no operation", + ): "ad3d5745332e9725b941f2db6e1eb60e5d93dfdd5204fefe3497e7c702b5e543", + ( + "named column axes", + "constructed", + "with_weights", + ): "f29f6e2ff48a87b5ea477b673c1d9947b1a58cb235dbee2eb83aaf72f15e37f9", + ( + "named column axes", + "constructed", + "place person to household", + ): "dc49c663387ebf528fd5586eab0067981d972bc02f8ab7e2f15615c25481ed27", + ( + "named column axes", + "constructed", + "place household to person", + ): "e6d89ab3373d5057399ef4983bad424bbab31399bd25b95c1743951474c3a83e", + ( + "named column axes", + "constructed", + "place a string to firm", + ): "995b70f552de6b61271ef88b6ea6f2ed3912e01c9e585ce9c11fa18e7e0358b6", + ( + "named column axes", + "constructed", + "select every person", + ): "8cb1bcfff2e6c27fb8067c5a9bc3745704aab1f5e67073093d2ca581e108c4b9", + ( + "named column axes", + "constructed", + "select two persons", + ): "d7e010959ae5b3f231bd64ace603b4b529bbe66fda946da0750df0b2f5ea8c30", + ( + "named column axes", + "constructed", + "no operation", + ): "56c83a3998b88b9a950bf1da9ffb506a79f6d6666669de04e8ee76fd4b3ba53c", + ( + "named column axes", + "loaded", + "with_weights", + ): "f29f6e2ff48a87b5ea477b673c1d9947b1a58cb235dbee2eb83aaf72f15e37f9", + ( + "named column axes", + "loaded", + "place person to household", + ): "dc49c663387ebf528fd5586eab0067981d972bc02f8ab7e2f15615c25481ed27", + ( + "named column axes", + "loaded", + "place household to person", + ): "e6d89ab3373d5057399ef4983bad424bbab31399bd25b95c1743951474c3a83e", + ( + "named column axes", + "loaded", + "place a string to firm", + ): "995b70f552de6b61271ef88b6ea6f2ed3912e01c9e585ce9c11fa18e7e0358b6", + ( + "named column axes", + "loaded", + "select every person", + ): "8cb1bcfff2e6c27fb8067c5a9bc3745704aab1f5e67073093d2ca581e108c4b9", + ( + "named column axes", + "loaded", + "select two persons", + ): "d7e010959ae5b3f231bd64ace603b4b529bbe66fda946da0750df0b2f5ea8c30", + ( + "named column axes", + "loaded", + "no operation", + ): "56c83a3998b88b9a950bf1da9ffb506a79f6d6666669de04e8ee76fd4b3ba53c", +} + + +_COMPARISON_CASES = [ + (source_frame, source, operation) + for source_frame in _SOURCE_FRAMES + for source in ("constructed", "loaded") + for operation in _ADOPTING_OPERATIONS +] + + +@pytest.mark.parametrize(("source_frame", "source", "operation"), _COMPARISON_CASES) +def test_adopted_frames_write_the_checkpoint_content_of_the_copying_code( + tmp_path: Path, source_frame: str, source: str, operation: str +) -> None: + """Each operation's result writes what the copying implementation wrote.""" + + derived = _derived_frame(tmp_path, source_frame, source, operation) + write_frame_checkpoint(tmp_path / "derived.h5", derived) + + assert ( + _checkpoint_content_sha256(tmp_path / "derived.h5") + == _COPYING_IMPLEMENTATION_CONTENT_SHA256[(source_frame, source, operation)] + ) + + +@pytest.mark.parametrize(("source_frame", "source", "operation"), _COMPARISON_CASES) +def test_adopted_frames_write_the_bytes_of_copied_frames( + tmp_path: Path, source_frame: str, source: str, operation: str +) -> None: + """A shared table layout writes the same file as a copied one. + + The reference rebuilds the derived frame through the copying constructor, + which merges each table's internal blocks. Both files are written in this + process, so the comparison does not depend on HDF5 library bytes that + differ between platforms. + """ + + derived = _derived_frame(tmp_path, source_frame, source, operation) + copied = Frame( + dict(frame_checkpoint_module._frame_tables(derived)), + derived.schema, + {entity: derived.weights_for(entity) for entity in derived.weighted_entities}, + derived.strata, + mass_log=derived.mass_log, + metadata=derived.metadata, + ) + + write_frame_checkpoint(tmp_path / "derived.h5", derived) + write_frame_checkpoint(tmp_path / "copied.h5", copied) + + assert (tmp_path / "derived.h5").read_bytes() == ( + tmp_path / "copied.h5" + ).read_bytes() + + +def test_writer_refuses_a_frame_whose_shared_column_changed(tmp_path: Path) -> None: + source = _checkpoint_frame() + shared = source.replace_tables() + np.add.at(source.table("person")["float_measure"].to_numpy(), [0], 1.0) + + with pytest.raises(SharedColumnChangedError) as raised: + write_frame_checkpoint(tmp_path / "frame.h5", shared) + + assert raised.value.changed_columns == (("person", "float_measure"),) + assert list(tmp_path.iterdir()) == [] + + +def test_loading_hashes_nothing_until_a_loaded_column_is_shared( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + path = tmp_path / "frame.h5" + write_frame_checkpoint(path, _checkpoint_frame()) + hashed_lengths: list[int] = [] + original_digest = shared_columns_module._buffer_digest + + def counting_digest(stored: shared_columns_module._StoredArray) -> bytes: + hashed_lengths.append(len(stored.values)) + return original_digest(stored) + + monkeypatch.setattr(shared_columns_module, "_buffer_digest", counting_digest) + + loaded = load_frame_checkpoint(path).frame + assert hashed_lengths == [] + + shared = loaded.replace_tables() + assert hashed_lengths != [] + np.add.at(loaded.table("person")["float_measure"].to_numpy(), [0], 1.0) + with pytest.raises(SharedColumnChangedError): + shared.check_shared_columns() 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 4fa27d3bad..96ff29382e 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 @@ -37,8 +37,9 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # again (acs_transfer's attested bytes; no draw changes). # 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. assert first.spec_sha256 == ( - "ee6f6bf511f47f24eaebc9fca6c227a7a9d2630c89a43db017ecd423d4ac9803" + "6ba1402eced96554e5d31781bf5a24b77d8b5421324d2da374b3806913a5d9bd" ) second_root = _rich_minimal(tmp_path / "xy", note="second", store="local:b") diff --git a/packages/microcosm-build/tests/engine_free/shared/test_transport_compile_modules.py b/packages/microcosm-build/tests/engine_free/shared/test_transport_compile_modules.py index 2aa1ba903a..ec565f01f7 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_transport_compile_modules.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_transport_compile_modules.py @@ -445,6 +445,27 @@ QUANTILE_MAP_1, QUANTILE_MAP_2, ), + # microcosm#1683: the frame bundle imports the shared-column check. + # takeup.compare, takeup.gap, targets.problem and transport.create + # hash it beside the bundle, as they hash the bundle's schema and + # weights, so target_kernels and population_kernels import it. These + # groups hash those modules or reach the bundle only through the + # compile list's exclusion, and leave the frame modules unhashed, as + # for schema above. + "microcosm.build.transport.population_kernels -> microcosm.frame.shared_columns": ( + QUANTILE_MAP_1, + QUANTILE_MAP_2, + ), + "microcosm.build.transport.target_kernels -> microcosm.frame.shared_columns": ( + COMPILE, + QUANTILE_MAP_1, + QUANTILE_MAP_2, + ), + "microcosm.frame.bundle -> microcosm.frame.shared_columns": ( + COMPILE, + QUANTILE_MAP_1, + QUANTILE_MAP_2, + ), "microcosm.build.transport.population_kernels -> microcosm.frame.unit_construction": ( QUANTILE_MAP_1, QUANTILE_MAP_2, 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 3e96f22df9..5e3c79341a 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 @@ -177,6 +177,9 @@ "microcosm.data.source_enrichment", "microcosm.data.stored_inputs", "microcosm.data.us_critical_targets", + # microcosm#1683: microcosm.frame.bundle imports the shared-column + # check, so a binding that reaches the frame bundle reaches it. + "microcosm.frame.shared_columns", ] ) BATTERY = "toy.gates.terminal" diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_graph_terminal.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_graph_terminal.py index 54da8fc6d1..f1cc12f2c0 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_graph_terminal.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_graph_terminal.py @@ -198,9 +198,15 @@ def test_export_roundtrip_preserves_dtype_weights_lineage_period_and_gate(tmp_pa def test_export_refuses_population_changed_after_descriptor(tmp_path): frame = _frame() descriptor = describe_uk_export(frame, bindings={}, solve_year=2025) - frame.table("person").loc[0, "income"] = 99.0 + # Build the changed population as a new frame. Frame tables are + # read-only: describe_uk_export shared the person columns with a frame it + # has since freed, so a .loc write here would change that recorded memory + # in place and be refused by the shared-column check instead. + income = frame.table("person")["income"].copy() + income.loc[0] = 99.0 + changed = frame.with_columns("person", income=income) with pytest.raises(ValueError, match="descriptor"): - materialize_uk_export(frame, descriptor, tmp_path / "changed.h5") + materialize_uk_export(changed, descriptor, tmp_path / "changed.h5") def test_export_readback_reports_changed_stored_values(tmp_path): diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_identifiers.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_identifiers.py index 952e8ee718..fe5f1fc725 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_identifiers.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_identifiers.py @@ -35,7 +35,7 @@ write_uk_national_frame, ) from microcosm.build.uk_runtime.weight_year import uk_dataset_year_frame -from microcosm.frame import WeightKind +from microcosm.frame import SharedColumnChangedError, WeightKind from test_support.microcosm_build.uk_graph_terminal import _frame as _ladder_frame # Two copies of a three-household survey, numbered the way the clone stages @@ -304,3 +304,16 @@ def test_the_local_readback_refuses_out_of_range_and_repeated_identifiers( report = validate_uk_export(path, descriptor) assert report["passed"] is False assert "Written 'person_id' repeats a value." in report["failures"] + + +def test_the_release_frame_refuses_a_changed_shared_column() -> None: + """The release boundary copies its tables, which would hide the change.""" + + built = _frame() + shared = built.replace_tables() + np.add.at(built.table("person")["person_id"].to_numpy(), [0], 1) + + with pytest.raises(SharedColumnChangedError) as raised: + uk_release_export_frame(shared) + + assert raised.value.changed_columns == (("person", "person_id"),) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_target_compile_modules.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_target_compile_modules.py index faa142ec88..f58e4c8e4d 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_target_compile_modules.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_target_compile_modules.py @@ -631,6 +631,15 @@ def test_national_target_kernels_hash_the_fact_decoder(monkeypatch): FULL_PROBLEM, NATIONAL, ), + # microcosm#1683: the frame bundle imports the shared-column check, + # which compares column digests before a write and raises + # SharedColumnChangedError on a mismatch. It changes no column, so no + # target value comes from it. + "microcosm.frame.bundle -> microcosm.frame.shared_columns": ( + FULL_TARGETS, + FULL_PROBLEM, + NATIONAL, + ), "microcosm.build.gates -> microcosm.frame.weights": ( FULL_TARGETS, FULL_PROBLEM, diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_sparse_cd.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_sparse_cd.py index 29e0549485..a299e07f0a 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_sparse_cd.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_sparse_cd.py @@ -24,7 +24,7 @@ from microcosm.calibrate import TargetSpec from microcosm.calibrate.matrix import build_constraint_matrix from microcosm.calibrate.target import TargetSet -from microcosm.frame import US_SCHEMA, Frame +from microcosm.frame import US_SCHEMA, Frame, SharedColumnChangedError from test_support.paths import paths_for _TEST_PATHS = paths_for("microcosm-build") @@ -1305,3 +1305,17 @@ def interrupted(*_args, **_kwargs): assert sorted(path.name for path in checkpoint.iterdir()) == sorted( ["weights_latest.npz", module.ACS_SSI_MEDICAID_TAKE_UP_FILENAME] ) + + +def test_struct_extraction_refuses_a_frame_whose_shared_column_changed() -> None: + """The extracted tables are copies, so a later check could not see the change.""" + + module = _load_tool_module() + source = _load_fixtures()._nested_frame() + shared = source.replace_tables() + np.add.at(source.table("household")["household_id"].to_numpy(), [0], 1) + + with pytest.raises(SharedColumnChangedError) as raised: + module.extract_struct_tables(shared) + + assert raised.value.changed_columns == (("household", "household_id"),) 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 1323134a5f..b4abeccba9 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 @@ -33,7 +33,13 @@ calibrate, ) from microcosm.data.stored_inputs import register_sha256 -from microcosm.frame import EntitySchema, Frame, WeightKind, Weights +from microcosm.frame import ( + EntitySchema, + Frame, + SharedColumnChangedError, + WeightKind, + Weights, +) from test_support.microcosm_diagnostics.json_schema import ( load_strict_json, published_json_schema_errors, @@ -20434,6 +20440,27 @@ def went_on(*args, **kwargs): assert not output.exists() +def test__given_changed_shared_column__then_target_frame_checkpoint_is_refused( + tmp_path, + small_frame, +) -> None: + builder = _load_builder_module() + shared = small_frame.replace_tables() + np.add.at(small_frame.table("person")["income"].to_numpy(), [0], 1.0) + + with pytest.raises(SharedColumnChangedError) as raised: + builder._write_target_frame_checkpoint( + tmp_path / "target_frame_checkpoint.h5", + frame=shared, + identity={}, + compilation={}, + build_commit="fixture-commit", + ) + + assert raised.value.changed_columns == (("person", "income"),) + assert list(tmp_path.iterdir()) == [] + + # --------------------------------------------------------------------------- # Build, then certify (microcosm#1585 item 11, PR 4a): the build ends with its # record; certification runs from it. diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_h5_io.py b/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_h5_io.py index 45c80b44ae..c073054133 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_h5_io.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_h5_io.py @@ -54,7 +54,13 @@ support_clone_index_column, support_source_id_column, ) -from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights +from microcosm.frame import ( + US_SCHEMA, + Frame, + SharedColumnChangedError, + WeightKind, + Weights, +) from test_support.paths import paths_for _TEST_PATHS = paths_for("microcosm-build") @@ -3705,3 +3711,24 @@ def test_legacy_stacked_manifest_refuses_h5_location_rule_attrs( with pytest.raises(ValueError, match="legacy-rule manifest"): load_simulation_ready_us_multispine_pool(manifest_path) + + +def test_nullable_h5_writer_refuses_a_frame_whose_shared_column_changed( + tmp_path: Path, +) -> None: + # The writer converts object strings to new arrays before writing them, so + # only a check of the frame itself can see this column. + source = _pool_frame_with_object_strings_on_every_entity() + shared = source.replace_tables() + np.asarray(source.table("person")["PERIDNUM"].array)[0] = "changed" + + with pytest.raises(SharedColumnChangedError) as raised: + write_nullable_us_h5( + shared, + tmp_path / "pool.h5", + period=2024, + artifact_kind=LEGACY_NULLABLE_STAGING_ARTIFACT_KIND, + ) + + assert raised.value.changed_columns == (("person", "PERIDNUM"),) + assert list(tmp_path.iterdir()) == [] diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py index deeeb97a7f..92b22a81cf 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py @@ -1,6 +1,9 @@ """Tests split from packages/microcosm-build/tests/test_us_post_export_scoring.py.""" # ruff: noqa: F403, F405 +import weakref +from collections.abc import Iterator + from test_support.microcosm_build.us_post_export_scoring import * @@ -1191,12 +1194,41 @@ def test_main_frees_the_target_frame_before_the_export(builder) -> None: assert reads and max(reads) < deleted_at -def test_calibration_result_holds_no_reference_to_the_target_frame() -> None: - """The premise of ``del target_frame``: ``calibrate`` keeps no reference - to its input frame, and ``result.frame`` shares no memory with it.""" +@pytest.fixture +def copy_on_write_on() -> Iterator[None]: + """Turn copy-on-write on under pandas 2.x; pandas 3 always has it on.""" + + if int(pd.__version__.split(".", 1)[0]) >= 3: + yield + return + with pd.option_context("mode.copy_on_write", True): + yield + + +def test_calibration_leaves_its_input_frame_unchanged_and_unreferenced( + copy_on_write_on: None, +) -> None: + """The premise of ``del target_frame``. + + ``calibrate`` keeps no reference to its input frame and leaves it + unchanged. Under pandas copy-on-write, ``result.frame`` shares the input's + column memory (``Frame.with_weights`` builds it without copying), so the + target tables are freed only once both ``target_frame`` and the result's + frame are gone: ``del target_frame`` removes one reference and + ``_without_calibrated_frames`` the other. A result built with + ``return_frame=False`` holds no frame, so it keeps nothing of the input's + tables alive. + """ frame, targets = _small_calibration_problem() + tables_before = { + entity: frame.table(entity).copy(deep=True) for entity in frame.entities + } + weights_before = frame.weights_for("household").values.copy() + strata_before = frame.strata.copy(deep=True) + result = calibrate(frame, targets, epochs=3, mass="conserve", seed=0) gc.collect() + # Nothing the calibration returned (or cached) refers to the input frame. referrers = [ type(referrer).__name__ @@ -1205,12 +1237,45 @@ def test_calibration_result_holds_no_reference_to_the_target_frame() -> None: ] assert referrers == [] assert result.frame is not frame - for entity in ("person", "household"): - for column in frame.table(entity).columns: - assert not np.shares_memory( + for entity, table_before in tables_before.items(): + pd.testing.assert_frame_equal( + frame.table(entity), table_before, check_exact=True + ) + assert result.frame.table(entity) is not frame.table(entity) + for column in table_before.columns: + assert np.shares_memory( frame.table(entity)[column].to_numpy(), result.frame.table(entity)[column].to_numpy(), - ) + ), (entity, column) + assert frame.weights_for("household").kind is WeightKind.DESIGN + np.testing.assert_array_equal(frame.weights_for("household").values, weights_before) + pd.testing.assert_series_equal(frame.strata, strata_before, check_exact=True) + assert frame.mass_log == () + + # A pandas write into the calibrated frame's tables never reaches the input. + result.frame.table("household").loc[0, "x"] = -1.0 + pd.testing.assert_frame_equal( + frame.table("household"), tables_before["household"], check_exact=True + ) + + frameless = calibrate( + frame, targets, epochs=3, mass="conserve", seed=0, return_frame=False + ) + assert frameless.frame is None + np.testing.assert_array_equal(frameless.weights, result.weights) + # Follow the input's income column to the array that owns its memory. + income_values = frame.table("person")["income"].to_numpy() + while isinstance(income_values.base, np.ndarray): + income_values = income_values.base + input_income_memory = weakref.ref(income_values) + del income_values, frame + gc.collect() + # The calibrated frame alone keeps the input's column memory alive... + assert input_income_memory() is not None + del result + gc.collect() + # ...and a result built with return_frame=False keeps none of it. + assert input_income_memory() is None def test_calibration_results_drop_their_frames_and_keep_everything_else( diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_spm_independence_role.py b/packages/microcosm-build/tests/engine_free/us/test_us_spm_independence_role.py index 62dcd3350e..8f179bfb79 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_spm_independence_role.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_spm_independence_role.py @@ -1,6 +1,7 @@ """Tests split from packages/microcosm-build/tests/test_us_spm_independence_role.py.""" # ruff: noqa: F403, F405 +from microcosm.frame import SharedColumnChangedError from test_support.microcosm_build.us_spm_independence_role import * @@ -537,3 +538,22 @@ def test_seeded_agreement_with_the_raw_rule_and_the_derivation( assert provenance["adult_child_person_count_mismatch_units"] == 0 teens = person["age"].between(15, 17).to_numpy() assert provenance["independent_minor_persons"] == int((role & teens).sum()) + + +def test_the_stage_refuses_a_frame_whose_shared_column_changed(population) -> None: + """The stage works on deep copies, which could not show the change.""" + + _source, path, pin, frame = population + shared = frame.replace_tables() + np.add.at(frame.table("person")["age"].to_numpy(), [0], 1) + + with pytest.raises(SharedColumnChangedError) as raised: + with_us_spm_independence_role( + shared, + seed=0, + time_period=2024, + asec_spm_role_source_paths={_INCOME_YEAR: path}, + source_pins={_INCOME_YEAR: pin}, + ) + + assert raised.value.changed_columns == (("person", "age"),) 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 18e17744ae..6c8a88b05e 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 @@ -369,7 +369,8 @@ def capture_equality(expected: object, actual: object) -> None: # moves it again (acs_transfer's attested bytes; no draw changes). # The QRF draw's default thread count, joblib.cpu_count() in # microcosm.fit.qrf, moves it again. - "spec_sha256": "067676ed540f9a6d7981ce5df546e81384cf0409446b04b4cbc637db5a43ea22", + # calibrate's return_frame option in solve moves it again. + "spec_sha256": "2e3093b6acc4926e80e96b080c3bfe2727baa22127ebfb9faf8a1ef05eda0f50", }, } diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py b/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py index e55a42a470..483d2f920a 100644 --- a/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py @@ -288,9 +288,15 @@ class CalibrationResult: Attributes: frame: A new :class:`~microcosm.frame.Frame` whose ``weight_entity`` - weights are :class:`~microcosm.frame.WeightKind.CALIBRATED`. + weights are :class:`~microcosm.frame.WeightKind.CALIBRATED`, or + ``None`` when :func:`calibrate` ran with ``return_frame=False`` + (or a caller dropped the frame with :func:`dataclasses.replace`). + Under pandas copy-on-write it shares the input frame's column + memory (:meth:`~microcosm.frame.Frame.with_weights` does not copy + tables). weight_entity: The entity whose weights were calibrated. - weights: The calibrated weight values (also on :attr:`frame`). + weights: The calibrated weight values (also on :attr:`frame`, when + the result carries one). initial_weights: The input weight values. These remain the frame's original weights even when the optimizer is initialized from ``warm_start_weights``. @@ -332,10 +338,11 @@ class CalibrationResult: learned gate state. The result is a frozen record; the calibrated frame is the primary product - and every operator downstream consumes :attr:`frame`. + and every operator downstream consumes :attr:`frame`, except a caller that + asked for weights and diagnostics only (``return_frame=False``). """ - frame: Frame + frame: Frame | None weight_entity: str weights: np.ndarray initial_weights: np.ndarray @@ -461,8 +468,8 @@ class L0RefitResult: selected_mask: np.ndarray @property - def frame(self) -> Frame: - """The post-L0-refit sparse frame.""" + def frame(self) -> Frame | None: + """The post-L0-refit sparse frame (``None`` if the refit carries none).""" return self.refit.frame @property @@ -2447,6 +2454,7 @@ def calibrate( warm_start_weights: np.ndarray | None = None, progress_callback: Callable[[dict[str, object]], None] | None = None, retain_best_objective: bool = False, + return_frame: bool = True, ) -> CalibrationResult: """Calibrate ``weight_entity``'s weights to ``targets`` over ``frame``. @@ -2617,12 +2625,25 @@ def calibrate( ``options["iterate_selection"] == "best_feasible_objective"``. Without an L2 penalty the solve already keeps its best target-loss epoch, and the flag changes nothing. + return_frame: ``True`` (default) returns the calibrated frame as + :attr:`CalibrationResult.frame`. ``False`` returns ``frame=None`` + for a caller that needs only the weights and diagnostics, so the + result keeps nothing of the input's tables alive. Every other + field is the same, and the calibrated weights pass the same + weight checks :meth:`~microcosm.frame.Frame.with_weights` makes + (forward kind transition, the mass policy), so a vector that + breaks them is refused either way. Building the frame also + re-checks the input frame's table invariants; without a frame + they are not re-checked (they already held when the input frame + was built, unless a caller changed its tables in place since). Returns: - A :class:`CalibrationResult` with the calibrated frame, per-target - diagnostics, loss trajectory, and any skipped targets. + A :class:`CalibrationResult` with the calibrated frame (``None`` when + ``return_frame=False``), per-target diagnostics, loss trajectory, and + any skipped targets. Raises: + TypeError: If ``return_frame`` is not a bool. ValueError: If ``method`` is unknown, ``mass`` is not ``"free"`` or ``"conserve"``, ``epochs`` is not positive, ``max_weight_ratio`` is given and is not ``> 0``, or ``target_records`` is given and is not @@ -2652,6 +2673,10 @@ def calibrate( "and deprecated alias 'apg' -> 'adam'." ) _check_mass(mass) + if not isinstance(return_frame, bool): + raise TypeError( + f"return_frame must be a bool, got {type(return_frame).__name__}." + ) if mass_reason is not None: if mass != FREE_MASS: raise ValueError( @@ -2946,6 +2971,7 @@ def calibrate( mass, targets, mass_reason=mass_reason, + return_frame=return_frame, ) diagnostics = _build_diagnostics(problem, frame, w0, final_weights) @@ -3260,7 +3286,8 @@ def _apply_weights( targets: TargetSet, *, mass_reason: str | None = None, -) -> Frame: + return_frame: bool = True, +) -> Frame | None: """Place the calibrated weights on the frame with the right mass policy. ``mass="conserve"`` uses the kernel's ``CONSERVE_MASS`` (the total is held @@ -3269,21 +3296,26 @@ def _apply_weights( moved on purpose to fit the targets, and the change is recorded on the frame's mass log with the caller's ``mass_reason`` when supplied, else a generic reason naming the calibration. + + With ``return_frame=False`` no frame is built: the weights go through the + same weight checks ``Frame.with_weights`` makes + (``Frame._checked_weight_change``), and ``None`` is returned. """ if mass == CONSERVE_MASS: from microcosm.frame import CONSERVE_MASS as FRAME_CONSERVE - return frame.with_weights(weight_entity, calibrated, mass=FRAME_CONSERVE) - factor = calibrated.total / initial.total if initial.total != 0 else None - reason = mass_reason or ( - f"calibrated {weight_entity!r} weights to {len(targets)} target(s) " - "(capped weighted-MAPE loss); total mass free to move" - ) - return frame.with_weights( - weight_entity, - calibrated, - mass=MassChange(factor=factor, reason=reason), - ) + policy: str | MassChange = FRAME_CONSERVE + else: + factor = calibrated.total / initial.total if initial.total != 0 else None + reason = mass_reason or ( + f"calibrated {weight_entity!r} weights to {len(targets)} target(s) " + "(capped weighted-MAPE loss); total mass free to move" + ) + policy = MassChange(factor=factor, reason=reason) + if not return_frame: + frame._checked_weight_change(weight_entity, calibrated, mass=policy) + return None + return frame.with_weights(weight_entity, calibrated, mass=policy) def _phase_callback( @@ -3465,6 +3497,14 @@ def refit_l0_selection( selected_mask = selection.weights > ( _PRUNE_REL_ATOL * float(np.mean(selection.initial_weights)) ) + if selection.frame is None: + raise ValueError( + "refit_l0_selection selects the survivors from the selection's " + "calibrated frame, and this selection carries none (it was " + "calibrated with return_frame=False). Calibrate the selection " + "with return_frame=True, or pass support and k for an exact-k " + "refit, which selects from the original frame." + ) subset_source = selection.frame selected_inclusion_probabilities = None else: diff --git a/packages/microcosm-calibrate/tests/engine_free/shared/test_solve.py b/packages/microcosm-calibrate/tests/engine_free/shared/test_solve.py index 7b52e4ccd8..e3ef2c7ba8 100644 --- a/packages/microcosm-calibrate/tests/engine_free/shared/test_solve.py +++ b/packages/microcosm-calibrate/tests/engine_free/shared/test_solve.py @@ -9,6 +9,7 @@ from __future__ import annotations +import dataclasses import hashlib import importlib.util import inspect @@ -2356,3 +2357,113 @@ def test_best_iterate_preserves_pre_change_excluded_paths(case_id: str) -> None: assert np.all( (result.gate_open_probabilities > 0) & (result.gate_open_probabilities < 1) ) + + +def _assert_results_equal_except_frame( + frameless: CalibrationResult, framed: CalibrationResult +) -> None: + """Every field but ``frame`` holds the same values in both results.""" + + for field in dataclasses.fields(CalibrationResult): + if field.name == "frame": + continue + actual = getattr(frameless, field.name) + expected = getattr(framed, field.name) + if isinstance(expected, np.ndarray): + np.testing.assert_array_equal(actual, expected, err_msg=field.name) + elif field.name == "problem": + assert actual.names == expected.names + assert actual.targets == expected.targets + assert actual.weight_entity == expected.weight_entity + np.testing.assert_array_equal(actual.target_vector, expected.target_vector) + np.testing.assert_array_equal( + actual.initial_weights.values, expected.initial_weights.values + ) + assert (actual.matrix != expected.matrix).nnz == 0 + else: + assert actual == expected, field.name + + +@pytest.mark.parametrize("mass", ["conserve", "free"]) +def test_calibrate_without_a_frame_returns_the_same_result_otherwise( + feasible_frame, mass: str +) -> None: + """``return_frame=False`` changes only that the result carries no frame.""" + frame, truths = feasible_frame(n=60) + targets = TargetSet( + ( + _population_target(truths["population"], 1.0), + _income_target(truths["income"], 1.1), + ) + ) + + framed = calibrate(frame, targets, epochs=25, seed=0, mass=mass) + frameless = calibrate( + frame, targets, epochs=25, seed=0, mass=mass, return_frame=False + ) + + assert framed.frame is not None + assert frameless.frame is None + _assert_results_equal_except_frame(frameless, framed) + + +@pytest.mark.parametrize("return_frame", [True, False]) +def test_calibrate_checks_the_weights_whether_or_not_it_returns_a_frame( + feasible_frame, monkeypatch, return_frame: bool +) -> None: + """``return_frame=False`` keeps the checks ``Frame.with_weights`` makes. + + A solver that broke mass conservation is refused with the same error + whether or not the calibrated frame is built. + """ + frame, truths = feasible_frame(n=40) + targets = TargetSet((_income_target(truths["income"], 1.1),)) + + def unconserving_optimize(*arguments, **options): + initial_weights = arguments[5] + return initial_weights * 1.5, np.zeros(options["epochs"]), None + + monkeypatch.setattr(solve_module, "_optimize", unconserving_optimize) + + with pytest.raises(ValueError, match="violates mass conservation"): + calibrate( + frame, + targets, + epochs=3, + seed=0, + mass="conserve", + return_frame=return_frame, + ) + + +def test_calibrate_refuses_a_return_frame_that_is_not_a_bool(feasible_frame) -> None: + frame, truths = feasible_frame(n=20) + targets = TargetSet((_income_target(truths["income"], 1.0),)) + + with pytest.raises(TypeError, match="return_frame must be a bool"): + calibrate(frame, targets, epochs=2, return_frame="False") + + +def test_refit_l0_selection_refuses_a_selection_without_a_frame( + feasible_frame, +) -> None: + """The thresholded refit selects survivors from the selection's frame.""" + frame, truths = feasible_frame(n=60) + targets = TargetSet( + ( + _population_target(truths["population"], 1.0), + _income_target(truths["income"], 1.0), + ) + ) + selection = calibrate( + frame, + targets, + epochs=20, + seed=0, + target_records=20, + mass="conserve", + return_frame=False, + ) + + with pytest.raises(ValueError, match="calibrated with return_frame=False"): + refit_l0_selection(frame, targets, selection, epochs=5, mass="conserve") diff --git a/packages/microcosm-frame/src/microcosm/frame/__init__.py b/packages/microcosm-frame/src/microcosm/frame/__init__.py index 7dd0e6ad79..2dc3a1b5c7 100644 --- a/packages/microcosm-frame/src/microcosm/frame/__init__.py +++ b/packages/microcosm-frame/src/microcosm/frame/__init__.py @@ -27,6 +27,10 @@ from microcosm.frame.rules import ExportContract, RulesEngine from microcosm.frame.scaling import ScaleFactor, SignedScale, apply_scale from microcosm.frame.schema import EntitySchema, LinkSpec, VariableMetadata +from microcosm.frame.shared_columns import ( + SharedColumnChangedError, + check_shared_columns, +) from microcosm.frame.units import ( MICROUNIT_REQUIRED_COLUMNS, TAX_UNIT_FILING_STATUS_COLUMN, @@ -60,6 +64,7 @@ "PyTablesBooleanMaterialization", "RulesEngine", "ScaleFactor", + "SharedColumnChangedError", "SignedScale", "VariableMetadata", "WeightKind", @@ -67,6 +72,7 @@ "assert_kind_transition", "apply_scale", "assign_us_unit_structure", + "check_shared_columns", "engine_tables", "gini", "groupby_wsum", diff --git a/packages/microcosm-frame/src/microcosm/frame/bundle.py b/packages/microcosm-frame/src/microcosm/frame/bundle.py index c71f9b84c6..0a726bac5e 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -21,13 +21,19 @@ caller convention; integrity-critical receipts belong in the frame's private, immutable metadata rather than in mutable table columns. -The constructor deep-copies every table it is given. :meth:`Frame.replace_tables` -and :meth:`Frame.with_columns` instead build a frame that shares the memory of -every unchanged column with its source frame when pandas copy-on-write is on, -and deep-copy when it is off (see :meth:`Frame._adopt`). +The constructor deep-copies every table it is given. :meth:`Frame.replace_tables`, +:meth:`Frame.with_columns`, :meth:`Frame.with_weights`, :meth:`Frame.place` and +:meth:`Frame.select` instead build a frame that shares the memory of every +unchanged column with its source frame when pandas copy-on-write is on, and +deep-copy when it is off (see :meth:`Frame.adopt`). Those operations record a +digest of each column of this frame they start sharing, and +:meth:`Frame.check_shared_columns` compares the digests, which finds a raw write +into memory the checked frame still holds (see +:mod:`microcosm.frame.shared_columns`). """ import re +import warnings from collections.abc import Mapping from dataclasses import dataclass from typing import Any @@ -36,6 +42,11 @@ import pandas as pd from microcosm.frame.schema import EntitySchema +from microcosm.frame.shared_columns import ( + check_columns_leaving, + check_shared_columns, + record_shared_columns, +) from microcosm.frame.weights import ( MassChange, MassChangeRecord, @@ -113,6 +124,8 @@ def __init__( mass_log: tuple[MassChangeRecord, ...] = (), metadata: Mapping[str, Any] | None = None, ) -> None: + # The deep copies made below could not show an earlier raw write. + check_shared_columns(tables, strata=strata) self._assemble( tables, schema, @@ -124,7 +137,7 @@ def __init__( ) @classmethod - def _adopt( + def adopt( cls, tables: Mapping[str, pd.DataFrame], schema: EntitySchema, @@ -158,7 +171,12 @@ def _adopt( ``to_numpy()`` returns a writable view of the column's data for, for example, the nullable integer, float and boolean types when the column has no missing value, python-backed strings, and sparse - columns without gaps. + columns without gaps. :meth:`check_shared_columns` finds such a write + afterwards, for columns a frame operation recorded when it started + sharing them. ``adopt`` records no columns itself: the frame + operations record the columns they share before calling it, so a raw + write into tables that a caller shares with another frame and passes + straight to ``adopt`` is not found. When copy-on-write is off (the pandas 2.x default), a shallow copy shares data even for ordinary pandas writes, so the tables and strata @@ -221,9 +239,9 @@ def _assemble( With ``copy_data``, each table and the strata are deep-copied (the constructor); without it, the tables are stored as given and the - strata shallow-copied (:meth:`_adopt` under copy-on-write). With + strata shallow-copied (:meth:`adopt` under copy-on-write). With ``require_dataframes``, a table that is not a DataFrame raises - ``TypeError`` (:meth:`_adopt`). + ``TypeError`` (:meth:`adopt`). """ self._schema = schema @@ -246,6 +264,22 @@ def _assemble( self._validate_weights() self._validate_reserved_weight_columns() + def check_shared_columns(self) -> None: + """Refuse this frame if a raw write changed a column it shares. + + Every table, link table and the strata are compared with the digests + recorded when frame operations started sharing their columns. Writers + of checkpoints and outputs call this first. Columns that were never + shared have no digest and cost nothing here. + + Raises: + SharedColumnChangedError: Naming each changed table and column. + """ + check_shared_columns( + {**self._tables, **self._link_tables}, + strata=self._strata, + ) + def revalidate(self) -> None: """Re-run every constructor invariant against the current state. @@ -841,7 +875,11 @@ def with_weights( :class:`~microcosm.frame.weights.MassChange`. Required. Returns: - A new validated bundle. + A new validated bundle. Its tables are built through + :meth:`adopt`, so under pandas copy-on-write they share every + column's memory with this bundle; each bundle holds its own + DataFrame objects, so a write made through pandas to either + never reaches the other. Raises: TypeError: If ``weights`` is not a :class:`Weights`, or ``mass`` is @@ -852,6 +890,47 @@ def with_weights( :class:`MassChange` whose declared ``factor`` does not match the realized ratio. """ + record = self._checked_weight_change(entity, weights, mass=mass) + new_weights = dict(self._weights) + new_weights[entity] = weights + new_mass_log = self._mass_log if record is None else (*self._mass_log, record) + return Frame.adopt( + self._shallow_table_copies(), + self._schema, + new_weights, + self._strata, + mass_log=new_mass_log, + metadata=self._metadata, + ) + + def _checked_weight_change( + self, + entity: str, + weights: Weights, + *, + mass: "str | MassChange", + ) -> MassChangeRecord | None: + """Check a replacement of ``entity``'s weights without building a frame. + + Runs every check :meth:`with_weights` makes on the new weights before + it builds the new frame, with the same errors: the entity name, the + argument types, the kind transition, and the mass policy. A caller + that needs only the checked weights, such as + ``calibrate(return_frame=False)``, calls this instead of building a + frame it would discard. The constructor's checks, which + :meth:`with_weights` runs when it builds the frame, are not run: that + the weight vector's length matches the entity table, and every table + invariant this frame passed when it was built (those fail only if a + caller changed a table in place since; see :meth:`revalidate`). + + Returns: + The :class:`~microcosm.frame.weights.MassChangeRecord` a + :class:`MassChange` policy appends to the mass log, or ``None`` + under :data:`CONSERVE_MASS`. + + Raises: + TypeError, ValueError: As :meth:`with_weights` raises them. + """ self.table(entity) # validates the entity name if not isinstance(weights, Weights): raise TypeError( @@ -884,18 +963,20 @@ def with_weights( ) from None else: record = self._mass_change_record(entity, existing, weights, mass) + return record - new_weights = dict(self._weights) - new_weights[entity] = weights - new_mass_log = self._mass_log if record is None else (*self._mass_log, record) - return Frame( - {**self._tables, **self._link_tables}, - self._schema, - new_weights, - self._strata, - mass_log=new_mass_log, - metadata=self._metadata, - ) + def _shallow_table_copies(self) -> dict[str, pd.DataFrame]: + """A shallow copy of every entity and link table, keyed by name. + + Each copy is a new DataFrame object over the same data. A frame built + from them through :meth:`adopt` therefore shares this frame's column + memory under copy-on-write but never its DataFrame objects, so a + write made through pandas to either frame cannot reach the other. + The columns are recorded for :meth:`check_shared_columns`. + """ + tables = {**self._tables, **self._link_tables} + _record_columns_being_shared(tables, strata=self._strata) + return {name: table.copy(deep=False) for name, table in tables.items()} @staticmethod def _mass_change_record( @@ -935,7 +1016,11 @@ def replace_tables(self, /, **changed_tables: pd.DataFrame) -> "Frame": pandas to either side never reaches the other. Each frame still holds its own DataFrame objects, so the caller may go on writing to the DataFrames it passed. Raw writes into the shared memory are not - protected (see :meth:`_adopt`). Weights, strata, the mass log and + protected (see :meth:`adopt`). A replacement's columns are recorded + for :meth:`check_shared_columns` only once a later operation shares + them. Each recorded column of a replaced table that the replacement + drops or replaces is compared first, because the new frame no longer + holds it for a later check to see. Weights, strata, the mass log and metadata are carried unchanged. When copy-on-write is off, every table is deep-copied instead. @@ -952,17 +1037,17 @@ def replace_tables(self, /, **changed_tables: pd.DataFrame) -> "Frame": ValueError: If a name is neither a declared entity nor a declared link, or the new tables break any constructor invariant (for example, the weights or strata no longer align with them). + SharedColumnChangedError: If a raw write changed a shared column + that the replacements drop or replace. """ _require_dataframes(changed_tables) - tables = { - name: table.copy(deep=False) - for name, table in {**self._tables, **self._link_tables}.items() - } + check_columns_leaving({**self._tables, **self._link_tables}, changed_tables) + tables = self._shallow_table_copies() tables.update( {name: table.copy(deep=False) for name, table in changed_tables.items()} ) - return Frame._adopt( + return Frame.adopt( tables, self._schema, self._weights, @@ -981,7 +1066,7 @@ def with_columns(self, entity: str, /, **columns: Any) -> "Frame": copies a NumPy array on assignment, so the frame does not alias the caller's array. The table's other columns and every other table are shared with this frame as in :meth:`replace_tables`, with the same - limits. + limits, and a recorded column it replaces is compared first. Args: entity: An entity declared by the schema (not a link). @@ -999,6 +1084,8 @@ def with_columns(self, entity: str, /, **columns: Any) -> "Frame": name another table already carries, a reserved ``{entity}_weight`` name, a duplicated or missing id, or broken linkage). + SharedColumnChangedError: If a raw write changed a shared column + that ``columns`` replaces. """ table = self.table(entity).copy(deep=False) @@ -1096,7 +1183,10 @@ def place( exactly one member per group. Returns: - A new validated bundle with the column on ``entity``. + A new validated bundle with the column on ``entity``, built + through :meth:`adopt`: under pandas copy-on-write it shares the + memory of every column it does not move with this bundle, in + DataFrame objects of its own. Raises: ValueError: On unknown column/entity, structural columns, a @@ -1141,13 +1231,18 @@ def place( else: placed = self._aggregate_group_to_group(column, owner, entity, values, how) - tables = {name: table for name, table in self._tables.items()} - tables.update(self._link_tables) - destination = tables[entity].copy() - destination[column] = placed - tables[entity] = destination - tables[owner] = tables[owner].drop(columns=[column]) - return Frame( + tables = self._shallow_table_copies() + destination = tables[entity] + with warnings.catch_warnings(): + # The shallow copy keeps the source table's internal blocks, and + # a table loaded from a checkpoint holds one block per column, so + # inserting into a wide table would warn that it is fragmented. + # Merging the blocks would copy the whole table; the inserted + # values and dtype are the same either way. + warnings.simplefilter("ignore", pd.errors.PerformanceWarning) + destination[column] = placed + tables[owner] = self._tables[owner].drop(columns=[column]) + return Frame.adopt( tables, self._schema, dict(self._weights), @@ -1410,7 +1505,8 @@ def select(self, person_mask: np.ndarray | pd.Series) -> "Frame": Returns: A new validated bundle containing the masked persons, the group rows they reference, the matching weight slices, and the matching - strata. + strata, built through :meth:`adopt`: under pandas copy-on-write + the selected tables are not copied a second time. Raises: NotImplementedError: If the frame carries link tables (links are @@ -1446,6 +1542,11 @@ def select(self, person_mask: np.ndarray | pd.Series) -> "Frame": ) person_entity = self._schema.person_entity + every_person_kept = bool(mask.all()) + # A table keeps sharing its source's memory only when every row stays. + tables_kept_whole: dict[str, pd.DataFrame] = {} + if every_person_kept: + tables_kept_whole[person_entity] = person tables: dict[str, pd.DataFrame] = {person_entity: person.loc[mask]} weights: dict[str, Weights] = {} if person_entity in self._weights: @@ -1460,6 +1561,8 @@ def select(self, person_mask: np.ndarray | pd.Series) -> "Frame": referenced = np.unique(membership) table = self._tables[group] keep = table[self._schema.id_column(group)].isin(referenced).to_numpy() + if keep.all(): + tables_kept_whole[group] = table tables[group] = table.loc[keep].reset_index(drop=True) if group in self._weights: existing = self._weights[group] @@ -1467,7 +1570,14 @@ def select(self, person_mask: np.ndarray | pd.Series) -> "Frame": existing.values[keep], kind=existing.kind ) strata = self._strata.loc[mask] - return Frame( + _record_columns_being_shared( + tables_kept_whole, + strata=self._strata if every_person_kept else None, + ) + # Row selection makes new DataFrame objects, so the result can own + # them; under copy-on-write, a table that kept every row still shares + # the source's memory. + return Frame.adopt( tables, self._schema, weights, @@ -1555,6 +1665,14 @@ def _require_dataframes(tables: Mapping[str, Any]) -> None: ) +def _record_columns_being_shared( + tables: Mapping[str, pd.DataFrame], *, strata: pd.Series | None = None +) -> None: + """Record columns a new frame will share; nothing is shared without copy-on-write.""" + if _pandas_copy_on_write(): + record_shared_columns(tables, strata=strata) + + def _pandas_copy_on_write() -> bool: """Whether pandas copy-on-write is on in this process, checked at each call. diff --git a/packages/microcosm-frame/src/microcosm/frame/materialize.py b/packages/microcosm-frame/src/microcosm/frame/materialize.py index be49c5ebe7..9d361e22b8 100644 --- a/packages/microcosm-frame/src/microcosm/frame/materialize.py +++ b/packages/microcosm-frame/src/microcosm/frame/materialize.py @@ -26,6 +26,7 @@ import pandas as pd from microcosm.frame.bundle import Frame +from microcosm.frame.shared_columns import check_shared_columns __all__ = [ "PyTablesBooleanMaterialization", @@ -156,8 +157,14 @@ def put_frame_table( preferred_format: str, data_columns: bool | list[str] | None = None, ) -> PyTablesBooleanMaterialization: - """Write one Frame table through the shared nullable-boolean boundary.""" + """Write one Frame table through the shared nullable-boolean boundary. + Raises: + SharedColumnChangedError: If a raw write changed a column of ``table`` + that frames share. Nothing is written for this table. + """ + + check_shared_columns({key: table}) materialized = materialize_nullable_booleans_for_pytables(table) hdf_format = materialized.hdf_format(preferred_format) options: dict[str, object] = {} @@ -282,8 +289,13 @@ def engine_tables( Entity name -> copied table, in :attr:`Frame.entities` order, with each selected entity's ``{entity}_weight`` column overwritten from its typed weights. + + Raises: + SharedColumnChangedError: If a raw write changed a column the frame + shares. The copies made here could not show it later. """ + frame.check_shared_columns() tables = {name: frame.table(name).copy() for name in frame.entities} selected = ( frame.weighted_entities diff --git a/packages/microcosm-frame/src/microcosm/frame/shared_columns.py b/packages/microcosm-frame/src/microcosm/frame/shared_columns.py new file mode 100644 index 0000000000..481dc12dee --- /dev/null +++ b/packages/microcosm-frame/src/microcosm/frame/shared_columns.py @@ -0,0 +1,333 @@ +"""Find in-place changes to column memory that frames share. + +Under pandas copy-on-write, frame operations such as +:meth:`~microcosm.frame.bundle.Frame.with_weights` share the memory of unchanged +columns. A write made through pandas stays on one frame, but a raw write into +the memory, for example through ``np.add.at`` or the array behind a nullable +column, changes every frame sharing it. This module detects that afterwards. It +does not prevent the write or identify the code that made it. + +**Recording.** When an operation starts sharing a frame's columns, +:func:`record_shared_columns` stores a SHA-256 digest of each array +:func:`_column_buffers` lists for the column. A digest belongs to the array's +memory, not to a frame, so a column is hashed once however many frames go on to +share it. Columns that are never shared are never hashed. Digests live only in +this process and are dropped when the array that owns the memory is freed. + +**Comparing.** :func:`check_shared_columns` hashes each recorded array again and +raises :class:`SharedColumnChangedError` naming every column that differs. The +:class:`~microcosm.frame.bundle.Frame` constructor, ``engine_tables`` and the +writers of checkpoints and outputs call it before copying or writing. A column +that leaves a frame would take the evidence of a raw write with it, while a +column derived from it carries the changed values on, so +:func:`check_columns_leaving` compares each recorded column that +``replace_tables`` or ``with_columns`` drops or replaces before the new frame +is built. + +A column is compared only while it is still stored in the memory that was +recorded. Replacing, adding or dropping a column through pandas moves it to +other memory, and so does a pandas write while the memory is still shared, so +none of these trip the check. Once no other table refers to the memory, an +in-place pandas write such as ``.loc``, ``fillna(inplace=True)`` or ``update`` +changes the recorded memory and is reported, because frame tables are documented +as read-only. + +Not covered: + +- pyarrow-backed columns, whose buffers are immutable, and any other extension + type :func:`_column_buffers` does not list; +- a copy taken after the change, for example ``table.copy()`` or a ``select`` + that drops rows, which carries the changed values into new memory; +- a recorded column that leaves every checked frame other than through + ``replace_tables`` or ``with_columns``, for example when a new ``Frame`` is + built from tables without it, or when values derived from it are written + without a frame. +""" + +from __future__ import annotations + +import hashlib +import weakref +from collections.abc import Iterable, Iterator, Mapping +from functools import partial +from typing import NamedTuple + +import numpy as np +import pandas as pd + +_NULLABLE_ARRAY_TYPES = ( + pd.arrays.BooleanArray, + pd.arrays.FloatingArray, + pd.arrays.IntegerArray, +) +_DATETIME_LIKE_ARRAY_TYPES = ( + pd.arrays.DatetimeArray, + pd.arrays.PeriodArray, + pd.arrays.TimedeltaArray, +) + +_BufferKey = tuple[int, int, int, str, int] + + +class SharedColumnChangedError(RuntimeError): + """Memory that frames shared was changed in place. + + Attributes: + changed_columns: ``(table, column)`` pairs, in table and column order. + """ + + def __init__(self, changed_columns: Iterable[tuple[str, str]]) -> None: + self.changed_columns = tuple(changed_columns) + super().__init__(self.changed_columns) + + def __str__(self) -> str: + columns = ", ".join( + f"column {column!r} of table {table!r}" + for table, column in self.changed_columns + ) + return ( + "Refusing to continue: column memory was changed in place after " + f"frames began sharing it, in {columns}. The usual cause is a raw " + "write that bypassed pandas, which changes every frame still " + "holding that memory. An in-place pandas write made after the " + "other tables sharing the memory were freed is reported too." + ) + + +class _StoredArray(NamedTuple): + """One array holding part of a column. + + ``hidden_positions`` marks positions whose stored values mean nothing, + because a nullable column's mask says they are missing. pandas itself + overwrites them, for example in ``cumsum``, so they are left out of the + digest. + """ + + values: np.ndarray + hidden_positions: np.ndarray | None = None + + +class _OwnerRecord: + """The digests of the arrays stored in one owning array's memory.""" + + __slots__ = ("digests", "reference") + + def __init__(self, reference: weakref.ref) -> None: + self.reference = reference + self.digests: dict[_BufferKey, bytes] = {} + + +#: Records by ``id`` of the owning array. Each entry's weak reference removes it +#: when the owner is freed, so a later array at the same address or with the +#: same ``id`` is never compared with it. +_owner_records: dict[int, _OwnerRecord] = {} + + +def _forget_owner(owner_id: int, _reference: weakref.ref) -> None: + _owner_records.pop(owner_id, None) + + +def _tracked_owner_count() -> int: + """How many owning arrays currently have recorded digests.""" + + return len(_owner_records) + + +def _column_buffers(column: pd.Series | pd.Index) -> tuple[_StoredArray, ...]: + """The arrays holding a column's data, without copying them. + + Returns an empty tuple for storage this module does not track. + """ + + if isinstance(column.dtype, np.dtype): + return (_StoredArray(column.to_numpy()),) + values = column.array + if isinstance(values, _NULLABLE_ARRAY_TYPES): + # pandas has no public way to reach these arrays when the column has + # missing values: to_numpy() then returns a converted copy. They are + # only read here. + mask = values._mask + return (_StoredArray(values._data, mask), _StoredArray(mask)) + if isinstance(values, pd.Categorical): + return (_StoredArray(values.codes), *_column_buffers(values.categories)) + if isinstance(values, pd.arrays.StringArray): + return (_StoredArray(values.to_numpy()),) + if isinstance(values, _DATETIME_LIKE_ARRAY_TYPES): + return (_StoredArray(values.asi8),) + if isinstance(values, pd.arrays.SparseArray): + sparse_index = values.sp_index + positions = ( + (sparse_index.blocs, sparse_index.blengths) + if values.kind == "block" + else (sparse_index.indices,) + ) + return (_StoredArray(values.sp_values), *map(_StoredArray, positions)) + return () + + +def _owner_of(array: np.ndarray) -> np.ndarray: + """The array at the root of ``array``'s chain of views.""" + + owner = array + while isinstance(owner.base, np.ndarray): + owner = owner.base + return owner + + +def _array_address(array: np.ndarray) -> int: + return array.__array_interface__["data"][0] + + +def _buffer_key(stored: _StoredArray) -> _BufferKey: + values = stored.values + hidden_positions = stored.hidden_positions + return ( + _array_address(values), + values.shape[0], + values.strides[0], + values.dtype.str, + 0 if hidden_positions is None else _array_address(hidden_positions), + ) + + +def _buffer_digest(stored: _StoredArray) -> bytes: + """Digest the meaningful contents of one stored array. + + An object array stores references, so its digest covers which object each + position refers to. That needs no hashable values, so columns of lists work, + and replacing an element with another object changes it. + """ + + values = stored.values + hidden_positions = stored.hidden_positions + if hidden_positions is not None and hidden_positions.any(): + values = values.copy() + values[hidden_positions] = 0 + if values.dtype.hasobject: + contents = np.fromiter(map(id, values), dtype=np.uintp, count=len(values)) + elif values.flags.c_contiguous: + contents = values + else: + contents = values.copy(order="C") + return hashlib.sha256(contents.view(np.uint8)).digest() + + +def _named_columns( + tables: Mapping[str, pd.DataFrame], strata: pd.Series | None +) -> Iterator[tuple[str, str, pd.Series]]: + """Each column of the DataFrames given; anything else is left to its caller.""" + + for table_name, table in tables.items(): + if isinstance(table, pd.DataFrame): + for column_name, column in table.items(): + yield str(table_name), str(column_name), column + if isinstance(strata, pd.Series): + yield "strata", "strata", strata + + +def _record_buffer(stored: _StoredArray) -> None: + owner = _owner_of(stored.values) + owner_id = id(owner) + record = _owner_records.get(owner_id) + if record is None: + reference = weakref.ref(owner, partial(_forget_owner, owner_id)) + record = _owner_records.setdefault(owner_id, _OwnerRecord(reference)) + key = _buffer_key(stored) + if key not in record.digests: + record.digests[key] = _buffer_digest(stored) + + +def _buffer_changed(stored: _StoredArray) -> bool: + record = _owner_records.get(id(_owner_of(stored.values))) + if record is None: + return False + recorded_digest = record.digests.get(_buffer_key(stored)) + return recorded_digest is not None and recorded_digest != _buffer_digest(stored) + + +def record_shared_columns( + tables: Mapping[str, pd.DataFrame], *, strata: pd.Series | None = None +) -> None: + """Record digests of the columns of ``tables`` that are about to be shared. + + A column whose memory already has a digest keeps it, so a change made + before a later frame starts sharing the column is still found. + + Args: + tables: DataFrames by table name. + strata: Per-person stratum labels, if they are shared too. + """ + + for _table_name, _column_name, column in _named_columns(tables, strata): + for stored in _column_buffers(column): + _record_buffer(stored) + + +def check_shared_columns( + tables: Mapping[str, pd.DataFrame], *, strata: pd.Series | None = None +) -> None: + """Refuse tables whose recorded column memory has changed. + + Columns with no recorded digest are skipped, so this is safe to call on + any table. + + Args: + tables: DataFrames by table name, used to name changed columns. + strata: Per-person stratum labels, reported as table ``"strata"``. + + Raises: + SharedColumnChangedError: If any recorded column has changed. + """ + + if not _owner_records: + return + changed_columns = [ + (table_name, column_name) + for table_name, column_name, column in _named_columns(tables, strata) + if any(_buffer_changed(stored) for stored in _column_buffers(column)) + ] + if changed_columns: + raise SharedColumnChangedError(changed_columns) + + +def check_columns_leaving( + tables: Mapping[str, pd.DataFrame], replacements: Mapping[str, pd.DataFrame] +) -> None: + """Refuse recorded columns of ``tables`` that their replacements do not keep. + + A column leaves when its replacement table no longer stores every array the + column is stored in, because the column was dropped or replaced. Only + leaving columns are hashed: columns the replacement keeps stay in the new + frame, and later checks of that frame compare them. + + Args: + tables: The current DataFrames by table name. + replacements: Their replacements by the same names. A name with no + current table is skipped. + + Raises: + SharedColumnChangedError: If any leaving column has changed. + """ + + if not _owner_records: + return + changed_columns = [] + for table_name, replacement in replacements.items(): + table = tables.get(table_name) + if not isinstance(table, pd.DataFrame) or not isinstance( + replacement, pd.DataFrame + ): + continue + kept = { + _buffer_key(stored) + for _column_name, column in replacement.items() + for stored in _column_buffers(column) + } + for column_name, column in table.items(): + stored_arrays = _column_buffers(column) + if all(_buffer_key(stored) in kept for stored in stored_arrays): + continue + if any(_buffer_changed(stored) for stored in stored_arrays): + changed_columns.append((str(table_name), str(column_name))) + if changed_columns: + raise SharedColumnChangedError(changed_columns) diff --git a/packages/microcosm-frame/tests/engine_free/shared/test_frame_operation_sharing.py b/packages/microcosm-frame/tests/engine_free/shared/test_frame_operation_sharing.py new file mode 100644 index 0000000000..7fb4bba328 --- /dev/null +++ b/packages/microcosm-frame/tests/engine_free/shared/test_frame_operation_sharing.py @@ -0,0 +1,427 @@ +"""``with_weights``, ``place`` and ``select`` build their result through ``Frame.adopt``. + +These operations used to rebuild their result with the :class:`Frame` +constructor, which deep-copies every table. They now hand the result's tables +to ``Frame.adopt``. Under pandas copy-on-write the result therefore shares the +memory of every column it does not change with its source frame, and a write +made through pandas to either frame never reaches the other, because each +frame holds its own DataFrame objects. When copy-on-write is off (the pandas +2.x default), ``Frame.adopt`` deep-copies instead; these tests replace the +copy-on-write check to take that path, because pandas 3 always has it on. +""" + +import warnings +from collections.abc import Callable, Iterator + +import numpy as np +import pandas as pd +import pytest + +from microcosm.frame import ( + EntitySchema, + Frame, + LinkSpec, + MassChange, + WeightKind, + Weights, +) +from microcosm.frame import bundle as bundle_module + +_LINKED_SCHEMA = EntitySchema( + group_entities=("household", "firm"), + links=(LinkSpec(name="jobs", left_entity="person", right_entity="firm"),), +) +_UNLINKED_SCHEMA = EntitySchema(group_entities=("household", "firm")) + + +def _entity_tables() -> dict[str, pd.DataFrame]: + """Four persons in two households and two firms.""" + + return { + "person": pd.DataFrame( + { + "person_id": np.array([0, 1, 2, 3], dtype="int64"), + "person_household_id": np.array([1, 1, 2, 2], dtype="int64"), + "person_firm_id": np.array([10, 10, 20, 20], dtype="int64"), + "age": np.array([40, 8, 30, 28], dtype="int64"), + "income": np.array([50_000.0, 0.0, 30_000.0, 20_000.0]), + } + ), + "household": pd.DataFrame( + { + "household_id": np.array([1, 2], dtype="int64"), + "rent": np.array([900.0, 1_200.0]), + "rooms": np.array([3, 5], dtype="int64"), + "state": ["CA", "NY"], + } + ), + "firm": pd.DataFrame( + { + "firm_id": np.array([10, 20], dtype="int64"), + "payroll": np.array([1.0e6, 2.0e6]), + } + ), + } + + +def _jobs_table() -> pd.DataFrame: + return pd.DataFrame( + { + "person_id": np.array([0, 2, 3], dtype="int64"), + "firm_id": np.array([10, 20, 20], dtype="int64"), + "hours": np.array([40.0, 20.0, 35.0]), + } + ) + + +def _weights() -> dict[str, Weights]: + return { + "household": Weights(values=np.array([100.0, 200.0]), kind=WeightKind.DESIGN) + } + + +def _strata() -> pd.Series: + # Object dtype, so ``to_numpy()`` returns the stored array and a memory + # comparison of strata is meaningful. + return pd.Series(["cps", "cps", "puf", "puf"], index=pd.RangeIndex(4), dtype=object) + + +@pytest.fixture +def linked_frame() -> Frame: + """A frame with a link table, strata, metadata and one mass-log entry.""" + + frame = Frame( + {**_entity_tables(), "jobs": _jobs_table()}, + _LINKED_SCHEMA, + _weights(), + _strata(), + metadata={"stage": "source"}, + ) + return frame.with_weights( + "household", + Weights(values=np.array([150.0, 300.0]), kind=WeightKind.IMPORTANCE), + mass=MassChange(factor=1.5, reason="test resampling"), + ) + + +@pytest.fixture +def unlinked_frame() -> Frame: + """The same frame without its link table, which ``select`` refuses.""" + + return Frame( + _entity_tables(), + _UNLINKED_SCHEMA, + _weights(), + _strata(), + metadata={"stage": "source"}, + ) + + +@pytest.fixture(autouse=True) +def copy_on_write_on() -> Iterator[None]: + """Turn copy-on-write on under pandas 2.x; pandas 3 always has it on.""" + + if int(pd.__version__.split(".", 1)[0]) >= 3: + yield + return + with pd.option_context("mode.copy_on_write", True): + yield + + +@pytest.fixture +def copy_on_write_off(monkeypatch: pytest.MonkeyPatch) -> None: + """Make ``Frame.adopt`` see pandas copy-on-write as off.""" + + monkeypatch.setattr(bundle_module, "_pandas_copy_on_write", lambda: False) + + +def _reweighted(frame: Frame) -> Frame: + current = frame.weights_for("household") + return frame.with_weights( + "household", + Weights(values=current.values * 2.0, kind=WeightKind.CALIBRATED), + mass=MassChange(factor=2.0, reason="test calibration"), + ) + + +def _income_to_household(frame: Frame) -> Frame: + return frame.place("income", "household", how="sum") + + +def _rent_to_person(frame: Frame) -> Frame: + return frame.place("rent", "person", how="broadcast") + + +def _every_person(frame: Frame) -> Frame: + return frame.select(np.ones(frame.n("person"), dtype=bool)) + + +def _first_household(frame: Frame) -> Frame: + return frame.select(frame.person["person_household_id"].to_numpy() == 1) + + +#: Each operation, with the fixture whose frame it runs on. +_OPERATIONS: dict[str, tuple[str, Callable[[Frame], Frame]]] = { + "with_weights": ("linked_frame", _reweighted), + "place person to household": ("linked_frame", _income_to_household), + "place household to person": ("linked_frame", _rent_to_person), + "select every person": ("unlinked_frame", _every_person), + "select one household": ("unlinked_frame", _first_household), +} + + +def _source_and_result(request: pytest.FixtureRequest, name: str): + fixture, operation = _OPERATIONS[name] + source = request.getfixturevalue(fixture) + return source, operation(source) + + +def _tables_of(frame: Frame) -> dict[str, pd.DataFrame]: + """Every entity table and link table the frame stores, by name.""" + + tables = {entity: frame.table(entity) for entity in frame.entities} + tables.update({name: frame.link(name) for name in frame.links}) + return tables + + +def _numeric_columns_sharing_memory( + left: dict[str, pd.DataFrame], right: dict[str, pd.DataFrame] +) -> dict[tuple[str, str], bool]: + """For each numeric column both table sets carry, whether its data is shared.""" + + sharing: dict[tuple[str, str], bool] = {} + for table_name, left_table in left.items(): + right_table = right.get(table_name) + if right_table is None: + continue + for column in left_table.select_dtypes("number").columns: + if column not in right_table.columns: + continue + sharing[(table_name, column)] = np.shares_memory( + left_table[column].to_numpy(), right_table[column].to_numpy() + ) + return sharing + + +def _snapshot(frame: Frame) -> dict[str, object]: + """Deep copies of everything a write could change, for a later comparison.""" + + return { + "tables": { + name: table.copy(deep=True) for name, table in _tables_of(frame).items() + }, + "weights": { + entity: frame.weights_for(entity).values.copy() + for entity in frame.weighted_entities + }, + "strata": frame.strata.copy(deep=True), + } + + +def _assert_matches_snapshot(frame: Frame, snapshot: dict[str, object]) -> None: + tables = _tables_of(frame) + assert tables.keys() == snapshot["tables"].keys() + for name, expected in snapshot["tables"].items(): + pd.testing.assert_frame_equal(tables[name], expected, check_exact=True) + for entity, expected in snapshot["weights"].items(): + np.testing.assert_array_equal(frame.weights_for(entity).values, expected) + pd.testing.assert_series_equal(frame.strata, snapshot["strata"], check_exact=True) + frame.revalidate() + + +def _write_every_numeric_column(frame: Frame) -> None: + """Write through pandas into the first row of every numeric column.""" + + for table in _tables_of(frame).values(): + for column in table.select_dtypes("number").columns: + table.loc[table.index[0], column] = -7 + + +def test_with_weights_shares_every_column_with_the_source(linked_frame) -> None: + reweighted = _reweighted(linked_frame) + + sharing = _numeric_columns_sharing_memory( + _tables_of(reweighted), _tables_of(linked_frame) + ) + assert ("jobs", "hours") in sharing + assert all(sharing.values()), sharing + assert np.shares_memory( + reweighted.strata.to_numpy(), linked_frame.strata.to_numpy() + ) + + +@pytest.mark.parametrize( + ("operation", "owner", "destination"), + [ + (_income_to_household, "person", "household"), + (_rent_to_person, "household", "person"), + ], + ids=["person to household", "household to person"], +) +def test_place_shares_every_table_it_does_not_change( + linked_frame, operation, owner: str, destination: str +) -> None: + placed = operation(linked_frame) + + untouched = { + name: table + for name, table in _tables_of(placed).items() + if name not in (owner, destination) + } + assert set(untouched) == {"firm", "jobs"} + sharing = _numeric_columns_sharing_memory(untouched, _tables_of(linked_frame)) + assert sharing and all(sharing.values()), sharing + destination_sharing = _numeric_columns_sharing_memory( + {destination: placed.table(destination)}, + {destination: linked_frame.table(destination)}, + ) + assert destination_sharing and all(destination_sharing.values()), ( + destination_sharing + ) + # The table the column moves out of keeps sharing its other columns. + owner_sharing = _numeric_columns_sharing_memory( + {owner: placed.table(owner)}, {owner: linked_frame.table(owner)} + ) + assert owner_sharing and all(owner_sharing.values()), owner_sharing + + +def test_select_keeping_every_person_shares_every_column(unlinked_frame) -> None: + selected = _every_person(unlinked_frame) + + sharing = _numeric_columns_sharing_memory( + _tables_of(selected), _tables_of(unlinked_frame) + ) + assert sharing and all(sharing.values()), sharing + + +@pytest.mark.parametrize("operation", list(_OPERATIONS)) +def test_every_result_table_is_a_distinct_object(request, operation: str) -> None: + source, result = _source_and_result(request, operation) + + source_tables = _tables_of(source) + for name, table in _tables_of(result).items(): + assert table is not source_tables[name], name + + +@pytest.mark.parametrize("operation", list(_OPERATIONS)) +def test_results_carry_metadata_and_the_mass_log(request, operation: str) -> None: + source, result = _source_and_result(request, operation) + + assert result.metadata == source.metadata + if operation == "with_weights": + assert result.mass_log[:-1] == source.mass_log + assert len(result.mass_log) == len(source.mass_log) + 1 + else: + assert result.mass_log == source.mass_log + result.revalidate() + + +@pytest.mark.parametrize("operation", list(_OPERATIONS)) +def test_a_pandas_write_to_the_result_leaves_the_source_unchanged( + request, operation: str +) -> None: + source, result = _source_and_result(request, operation) + before = _snapshot(source) + + _write_every_numeric_column(result) + + _assert_matches_snapshot(source, before) + + +@pytest.mark.parametrize("operation", list(_OPERATIONS)) +def test_a_pandas_write_to_the_source_leaves_the_result_unchanged( + request, operation: str +) -> None: + source, result = _source_and_result(request, operation) + before = _snapshot(result) + + _write_every_numeric_column(source) + + _assert_matches_snapshot(result, before) + + +# Selecting a strict subset of persons copies their rows whatever ``Frame.adopt`` +# does, so only operations that can share memory are checked here. +@pytest.mark.parametrize( + "operation", [name for name in _OPERATIONS if name != "select one household"] +) +def test_operations_deep_copy_when_copy_on_write_is_off( + request, copy_on_write_off: None, operation: str +) -> None: + source, result = _source_and_result(request, operation) + + sharing = _numeric_columns_sharing_memory(_tables_of(result), _tables_of(source)) + assert sharing, "the comparison found no numeric columns" + assert not any(sharing.values()), sharing + assert not np.shares_memory(result.strata.to_numpy(), source.strata.to_numpy()) + + +def _fragmented_frame() -> Frame: + """A frame whose person and household tables hold one block per column. + + A table built from a mapping of Series with ``copy=False`` keeps every + column in its own internal block, as the checkpoint loader's tables do. + pandas emits ``PerformanceWarning`` when a column is inserted into a table + with more than 100 blocks. + """ + + tables = _entity_tables() + fragmented = {} + for name in ("person", "household"): + table = tables[name] + columns = {column: table[column] for column in table.columns} + for position in range(120): + columns[f"{name}_filler_{position}"] = pd.Series( + np.full(len(table), float(position)), index=table.index + ) + fragmented[name] = pd.DataFrame(columns, index=table.index, copy=False) + tables.update(fragmented) + return Frame.adopt(tables, _UNLINKED_SCHEMA, _weights(), _strata()) + + +@pytest.mark.parametrize( + "operation", + [_income_to_household, _rent_to_person], + ids=["person to household", "household to person"], +) +def test_place_into_a_fragmented_table_emits_no_performance_warning( + operation, +) -> None: + frame = _fragmented_frame() + + with warnings.catch_warnings(): + warnings.simplefilter("error", pd.errors.PerformanceWarning) + placed = operation(frame) + + placed.revalidate() + + +@pytest.mark.parametrize( + ("operation", "column", "destination"), + [ + (_income_to_household, "income", "household"), + (_rent_to_person, "rent", "person"), + ], + ids=["person to household", "household to person"], +) +def test_place_into_a_fragmented_table_keeps_columns_order_and_dtypes( + operation, column: str, destination: str +) -> None: + fragmented = _fragmented_frame() + consolidated = Frame( + _tables_of(fragmented), + fragmented.schema, + {"household": fragmented.weights_for("household")}, + fragmented.strata, + ) + + from_fragmented = operation(fragmented) + from_consolidated = operation(consolidated) + + for name in from_consolidated.entities: + pd.testing.assert_frame_equal( + from_fragmented.table(name), + from_consolidated.table(name), + check_exact=True, + ) + assert list(from_fragmented.table(destination).columns)[-1] == column diff --git a/packages/microcosm-frame/tests/engine_free/shared/test_frame_table_sharing.py b/packages/microcosm-frame/tests/engine_free/shared/test_frame_table_sharing.py index cb04eddb95..d4a69cba53 100644 --- a/packages/microcosm-frame/tests/engine_free/shared/test_frame_table_sharing.py +++ b/packages/microcosm-frame/tests/engine_free/shared/test_frame_table_sharing.py @@ -1,15 +1,15 @@ -"""Frames that share unchanged tables: ``_adopt``, ``replace_tables``, ``with_columns``. +"""Frames that share unchanged tables: ``Frame.adopt``, ``replace_tables``, ``with_columns``. The default :class:`Frame` constructor deep-copies every table it is given. -``Frame._adopt`` instead stores the tables it is given without copying them +``Frame.adopt`` instead stores the tables it is given without copying them when pandas copy-on-write is on, so a frame built by ``replace_tables`` or ``with_columns`` shares the memory of every unchanged column with its source frame. Copy-on-write keeps a write made through pandas on one frame from reaching the other. When copy-on-write is off (the pandas 2.x default), a -shallow copy shares data even for ordinary pandas writes, so ``_adopt`` +shallow copy shares data even for ordinary pandas writes, so ``Frame.adopt`` deep-copies instead. Tests take that path through the ``copy_on_write_off`` fixture, which turns copy-on-write off under pandas 2.x and, under pandas 3, -where it is always on, replaces the check ``_adopt`` makes, or by replacing +where it is always on, replaces the check ``Frame.adopt`` makes, or by replacing the check themselves (the parametrized ``cow_off`` cases). Every other test runs with copy-on-write on. """ @@ -127,7 +127,7 @@ def copy_on_write_on() -> Iterator[None]: @pytest.fixture def copy_on_write_off(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: """Turn copy-on-write off: under pandas 2.x through its option, and under - pandas 3, where it cannot be off, by replacing the check ``_adopt`` makes.""" + pandas 3, where it cannot be off, by replacing the check ``Frame.adopt`` makes.""" if _PANDAS_3: monkeypatch.setattr(bundle_module, "_pandas_copy_on_write", lambda: False) @@ -180,10 +180,14 @@ def test_constructor_deep_copies_every_table_and_the_strata(self) -> None: class TestAdopt: + def test_adopt_is_public_with_no_private_alias(self) -> None: + assert callable(Frame.adopt) + assert not hasattr(Frame, "_adopt") + def test_adopt_stores_the_given_tables_without_copying(self) -> None: tables = _source_tables() strata = _source_strata() - frame = Frame._adopt(tables, _SCHEMA, _source_weights(), strata) + frame = Frame.adopt(tables, _SCHEMA, _source_weights(), strata) for name, table in _tables_of(frame).items(): assert table is tables[name] @@ -201,14 +205,14 @@ def test_adopt_refuses_a_table_that_is_not_a_dataframe( tables: dict[str, Any] = {**_source_tables(), "jobs": None} with pytest.raises(TypeError, match="'jobs' must be a pandas DataFrame"): - Frame._adopt(tables, _SCHEMA, _source_weights()) + Frame.adopt(tables, _SCHEMA, _source_weights()) def test_adopt_deep_copies_when_copy_on_write_is_off( self, copy_on_write_off: None ) -> None: tables = _source_tables() strata = _source_strata() - frame = Frame._adopt(tables, _SCHEMA, _source_weights(), strata) + frame = Frame.adopt(tables, _SCHEMA, _source_weights(), strata) for name, table in _tables_of(frame).items(): assert table is not tables[name] @@ -221,14 +225,14 @@ def test_adopt_names_the_strata_without_renaming_the_callers_series( self, ) -> None: strata = _source_strata().rename("provenance") - frame = Frame._adopt(_source_tables(), _SCHEMA, _source_weights(), strata) + frame = Frame.adopt(_source_tables(), _SCHEMA, _source_weights(), strata) assert frame.strata.name == "stratum" assert strata.name == "provenance" assert frame.strata.tolist() == ["cps", "cps", "puf", "puf"] def test_adopt_carries_the_mass_log_and_metadata(self, source_frame) -> None: - frame = Frame._adopt( + frame = Frame.adopt( _source_tables(), _SCHEMA, _source_weights(), @@ -353,7 +357,7 @@ def test_adopt_raises_the_constructors_validation_errors( with pytest.raises((TypeError, ValueError)) as constructor_error: Frame(**_constructor_arguments(change)) with pytest.raises(type(constructor_error.value)) as adopt_error: - Frame._adopt(**_constructor_arguments(change)) + Frame.adopt(**_constructor_arguments(change)) assert str(adopt_error.value) == str(constructor_error.value) diff --git a/packages/microcosm-frame/tests/engine_free/shared/test_shared_buffer_writes.py b/packages/microcosm-frame/tests/engine_free/shared/test_shared_buffer_writes.py index e2841e6933..d3ad62d9ab 100644 --- a/packages/microcosm-frame/tests/engine_free/shared/test_shared_buffer_writes.py +++ b/packages/microcosm-frame/tests/engine_free/shared/test_shared_buffer_writes.py @@ -1,8 +1,9 @@ """A syntactic check for raw writes that pandas copy-on-write does not protect. -:meth:`Frame.replace_tables` and :meth:`Frame.with_columns` build frames that -share the memory of every unchanged column with their source frame -(:meth:`Frame._adopt`). pandas copy-on-write keeps a write made through pandas +:meth:`Frame.replace_tables`, :meth:`Frame.with_columns`, +:meth:`Frame.with_weights`, :meth:`Frame.place` and :meth:`Frame.select` build +frames that share the memory of unchanged columns with their source frame +(:meth:`Frame.adopt`). pandas copy-on-write keeps a write made through pandas (``.loc``, column assignment, in-place methods) on one frame from reaching the other, but it does not see a raw write into the shared memory. Checked with pandas 3.0.3 and NumPy 2.4.6, each form below writes into the shared @@ -137,6 +138,26 @@ "np.asarray(...).copy() from the household weights. Review again if " "either of those functions changes." ), + ( + "packages/microcosm-frame/src/microcosm/frame/shared_columns.py", + "_column_buffers", + "pandas-private-attribute", + "values._data", + "64ca7d79dc01", + ): ( + "Read only, so the shared-column check can hash a nullable column's " + "values. pandas has no public access to them when values are missing." + ), + ( + "packages/microcosm-frame/src/microcosm/frame/shared_columns.py", + "_column_buffers", + "pandas-private-attribute", + "values._mask", + "64ca7d79dc01", + ): ( + "Read only, so the shared-column check can hash a nullable column's " + "missing-value mask. pandas exposes only a copy of it." + ), } #: The functions a reviewed reason rests on, by repository-relative path and diff --git a/packages/microcosm-frame/tests/engine_free/shared/test_shared_column_check.py b/packages/microcosm-frame/tests/engine_free/shared/test_shared_column_check.py new file mode 100644 index 0000000000..587cd52c18 --- /dev/null +++ b/packages/microcosm-frame/tests/engine_free/shared/test_shared_column_check.py @@ -0,0 +1,725 @@ +"""The check that finds raw writes into column memory frames share. + +Frames built by ``with_weights``, ``place``, ``select``, ``replace_tables`` and +``with_columns`` share unchanged columns under pandas copy-on-write. Copy-on-write +keeps pandas writes apart, but a raw write into the shared memory changes every +frame holding it. These tests make those raw writes on purpose and check that +the comparison run before output is written names the changed column, and that +writes pandas keeps apart never trip it. +""" + +import gc +import warnings +from collections.abc import Callable, Iterator + +import numpy as np +import pandas as pd +import pytest + +from microcosm.frame import ( + EntitySchema, + Frame, + LinkSpec, + MassChange, + SharedColumnChangedError, + WeightKind, + Weights, + check_shared_columns, + engine_tables, + put_frame_table, +) +from microcosm.frame import bundle as bundle_module +from microcosm.frame import shared_columns as shared_columns_module + +_SCHEMA = EntitySchema(group_entities=("household",)) +_PERSON_COUNT = 4 + + +def _source_frame() -> Frame: + """Two households of two people, with one column of each stored form.""" + + person = pd.DataFrame( + { + "person_id": np.arange(_PERSON_COUNT, dtype="int64"), + "person_household_id": np.array([1, 1, 2, 2], dtype="int64"), + "income": np.array([50_000.0, 0.0, 30_000.0, 20_000.0]), + "age": np.array([40, 8, 30, 28], dtype="int64"), + "count_complete": pd.array([1, 2, 3, 4], dtype="Int64"), + "count_with_gap": pd.array([1, None, 3, 4], dtype="Int64"), + "amount_complete": pd.array([1.5, 2.5, 3.5, 4.5], dtype="Float64"), + "flag_complete": pd.array([True, False, True, False], dtype="boolean"), + "region": pd.Categorical(["north", "south", "north", "south"]), + "label_python": pd.array( + ["a", "b", "c", "d"], dtype=pd.StringDtype("python") + ), + "label_object": pd.Series(["a", "b", "c", "d"], dtype=object), + "tags": pd.Series([["a"], ["b"], ["c"], ["d"]], dtype=object), + "born": pd.date_range("2000-01-01", periods=_PERSON_COUNT), + "born_utc": pd.date_range("2000-01-01", periods=_PERSON_COUNT, tz="UTC"), + "born_month": pd.period_range("2000-01", periods=_PERSON_COUNT, freq="M"), + "rare_count": pd.arrays.SparseArray([0, 1, 0, 2]), + "size_band": pd.Categorical([10, 20, 10, 20]), + "rare_block": pd.arrays.SparseArray([0, 1, 1, 0], kind="block"), + } + ) + household = pd.DataFrame( + { + "household_id": np.array([1, 2], dtype="int64"), + "rent": np.array([900.0, 1_200.0]), + } + ) + return Frame( + {"person": person, "household": household}, + _SCHEMA, + {"household": Weights(np.array([100.0, 200.0]), WeightKind.DESIGN)}, + pd.Series(["cps", "cps", "puf", "puf"], dtype=object), + ) + + +def _reweighted(frame: Frame) -> Frame: + current = frame.weights_for("household") + return frame.with_weights( + "household", + Weights(current.values * 2.0, WeightKind.CALIBRATED), + mass=MassChange(factor=2.0, reason="test calibration"), + ) + + +def _with_rent_on_people(frame: Frame) -> Frame: + return frame.place("rent", "person", how="broadcast") + + +def _every_person(frame: Frame) -> Frame: + return frame.select(np.ones(frame.n("person"), dtype=bool)) + + +def _every_table_replaced_by_itself(frame: Frame) -> Frame: + return frame.replace_tables() + + +def _with_new_column(frame: Frame) -> Frame: + return frame.with_columns("person", new_measure=np.ones(frame.n("person"))) + + +_SHARING_OPERATIONS: dict[str, Callable[[Frame], Frame]] = { + "with_weights": _reweighted, + "place": _with_rent_on_people, + "select every person": _every_person, + "replace_tables": _every_table_replaced_by_itself, + "with_columns": _with_new_column, +} + + +@pytest.fixture(autouse=True) +def copy_on_write_on() -> Iterator[None]: + """Turn copy-on-write on under pandas 2.x; pandas 3 always has it on.""" + + if int(pd.__version__.split(".", 1)[0]) >= 3: + yield + return + with pd.option_context("mode.copy_on_write", True): + yield + + +def _write_through_to_numpy(column: pd.Series) -> None: + column.to_numpy()[1] = column.to_numpy()[0] + + +def _write_category_through_values(column: pd.Series) -> None: + column.values[1] = "north" + + +def _add_at_into_to_numpy(column: pd.Series) -> None: + np.add.at(column.to_numpy(), [1], 1.0) + + +def _write_through_asarray_of_array(column: pd.Series) -> None: + np.asarray(column.array)[1] = np.asarray(column.array)[0] + + +def _write_in_place_through_torch(column: pd.Series) -> None: + torch = pytest.importorskip("torch") + with warnings.catch_warnings(): + # torch warns that the array it wraps is read-only, which is the point. + warnings.simplefilter("ignore", UserWarning) + torch.from_numpy(column.to_numpy()).add_(1.0) + + +def _write_through_extension_array(column: pd.Series) -> None: + column.array[1] = 99 + + +def _write_string_through_to_numpy(column: pd.Series) -> None: + column.to_numpy()[1] = "changed" + + +def _replace_list_through_asarray(column: pd.Series) -> None: + np.asarray(column.array)[1] = ["changed"] + + +def _add_at_into_datetime_integers(column: pd.Series) -> None: + np.add.at(column.array.asi8, [1], 1) + + +def _add_at_into_sparse_values(column: pd.Series) -> None: + np.add.at(column.array.sp_values, [0], 1) + + +def _move_a_sparse_value(column: pd.Series) -> None: + column.array.sp_index.indices[0] = 0 + + +def _change_a_category(column: pd.Series) -> None: + np.asarray(column.array.categories.array)[0] = 999 + + +def _mark_a_value_missing(column: pd.Series) -> None: + column.array._mask[0] = True + + +def _hide_a_stored_false(column: pd.Series) -> None: + column.array._mask[1] = True + + +def _move_a_sparse_block(column: pd.Series) -> None: + column.array.sp_index.blocs[0] = 0 + + +def _shorten_a_sparse_block(column: pd.Series) -> None: + column.array.sp_index.blengths[0] = 1 + + +_RAW_WRITES: dict[str, tuple[str, Callable[[pd.Series], None]]] = { + "to_numpy on Int64": ("count_complete", _write_through_to_numpy), + "to_numpy on Float64": ("amount_complete", _write_through_to_numpy), + "to_numpy on boolean": ("flag_complete", _write_through_to_numpy), + "values on category": ("region", _write_category_through_values), + "add.at on float64": ("income", _add_at_into_to_numpy), + "asarray of array on float64": ("income", _write_through_asarray_of_array), + "torch in place on float64": ("income", _write_in_place_through_torch), + "array on Int64 with a gap": ("count_with_gap", _write_through_extension_array), + "to_numpy on python strings": ("label_python", _write_string_through_to_numpy), + "asarray of array on object": ("label_object", _write_through_asarray_of_array), + "asarray of array on lists": ("tags", _replace_list_through_asarray), + "add.at on time-zone dates": ("born_utc", _add_at_into_datetime_integers), + "add.at on periods": ("born_month", _add_at_into_datetime_integers), + "add.at on sparse values": ("rare_count", _add_at_into_sparse_values), + "sparse positions": ("rare_count", _move_a_sparse_value), + "category values": ("size_band", _change_a_category), + "mask of Int64": ("count_complete", _mark_a_value_missing), + "mask over a stored false": ("flag_complete", _hide_a_stored_false), + "sparse block positions": ("rare_block", _move_a_sparse_block), + "sparse block lengths": ("rare_block", _shorten_a_sparse_block), +} + + +@pytest.mark.parametrize("raw_write", sorted(_RAW_WRITES)) +def test_the_check_names_a_column_changed_by_a_raw_write(raw_write: str) -> None: + column_name, write = _RAW_WRITES[raw_write] + source = _source_frame() + result = _reweighted(source) + + write(source.table("person")[column_name]) + + for frame in (source, result): + with pytest.raises(SharedColumnChangedError) as raised: + frame.check_shared_columns() + assert raised.value.changed_columns == (("person", column_name),) + assert "person" in str(raised.value) + assert column_name in str(raised.value) + + +# A column that leaves a frame takes the evidence of a raw write with it: no +# later check of the new frame sees it (microcosm#1683 review). replace_tables, +# and with_columns through it, compare each recorded column the new frame drops +# or replaces before building it. + + +@pytest.mark.parametrize("raw_write", sorted(_RAW_WRITES)) +def test_dropping_a_changed_shared_column_is_refused(raw_write: str) -> None: + column_name, write = _RAW_WRITES[raw_write] + source = _source_frame() + result = _reweighted(source) + write(result.table("person")[column_name]) + + with pytest.raises(SharedColumnChangedError) as raised: + result.replace_tables(person=result.table("person").drop(columns=column_name)) + assert raised.value.changed_columns == (("person", column_name),) + + +def test_a_column_derived_from_a_changed_column_cannot_drop_it() -> None: + """The writer reads its changed column into a new one, then drops it.""" + + source = _source_frame() + result = _reweighted(source) + _add_at_into_to_numpy(result.table("person")["income"]) + person = result.table("person") + derived = person.assign(doubled=2 * person["income"]).drop(columns="income") + + with pytest.raises(SharedColumnChangedError) as raised: + result.replace_tables(person=derived) + assert raised.value.changed_columns == (("person", "income"),) + + +def test_a_frame_cannot_drop_a_column_another_frame_changed() -> None: + """The other frame's raw write changed this frame's column too.""" + + source = _source_frame() + result = _reweighted(source) + _add_at_into_to_numpy(result.table("person")["income"]) + person = source.table("person") + derived = person.assign(raised=person["income"] + 1.0).drop(columns="income") + + with pytest.raises(SharedColumnChangedError) as raised: + source.replace_tables(person=derived) + assert raised.value.changed_columns == (("person", "income"),) + + +def test_with_columns_cannot_replace_a_changed_shared_column() -> None: + source = _source_frame() + result = _reweighted(source) + _add_at_into_to_numpy(source.table("person")["income"]) + + with pytest.raises(SharedColumnChangedError) as raised: + result.with_columns("person", income=np.zeros(_PERSON_COUNT)) + assert raised.value.changed_columns == (("person", "income"),) + + +def test_dropping_or_replacing_an_unchanged_shared_column_passes() -> None: + source = _source_frame() + result = _reweighted(source) + + dropped = result.replace_tables( + person=result.table("person").drop(columns="income") + ) + replaced = result.with_columns("person", income=np.zeros(_PERSON_COUNT)) + + for frame in (dropped, replaced, result, source): + frame.check_shared_columns() + + +@pytest.mark.parametrize("operation", sorted(_SHARING_OPERATIONS)) +def test_every_sharing_operation_makes_its_columns_checked(operation: str) -> None: + source = _source_frame() + result = _SHARING_OPERATIONS[operation](source) + result.check_shared_columns() + + _add_at_into_to_numpy(source.table("person")["income"]) + + with pytest.raises(SharedColumnChangedError) as raised: + result.check_shared_columns() + assert raised.value.changed_columns == (("person", "income"),) + + +def test_pyarrow_strings_are_not_hashed() -> None: + """Their buffers are immutable, and hashing text is the slowest case.""" + + pytest.importorskip("pyarrow") + column = pd.Series(["a", "b"], dtype=pd.StringDtype("pyarrow")) + + assert shared_columns_module._column_buffers(column) == () + + +def test_a_group_table_kept_whole_by_a_partial_select_is_checked() -> None: + source = _source_frame() + # Dropping one of a household's two people keeps every household row. + result = source.select(np.array([True, False, True, True])) + + _add_at_into_to_numpy(source.table("household")["rent"]) + + with pytest.raises(SharedColumnChangedError) as raised: + result.check_shared_columns() + assert raised.value.changed_columns == (("household", "rent"),) + + +@pytest.mark.parametrize("operation", sorted(_SHARING_OPERATIONS)) +def test_a_raw_write_into_shared_strata_is_named(operation: str) -> None: + source = _source_frame() + result = _SHARING_OPERATIONS[operation](source) + + np.asarray(source.strata.array)[1] = "changed" + + with pytest.raises(SharedColumnChangedError) as raised: + result.check_shared_columns() + assert raised.value.changed_columns == (("strata", "strata"),) + + +def test_a_raw_write_into_a_shared_link_table_is_named() -> None: + schema = EntitySchema( + group_entities=("household",), + links=( + LinkSpec(name="visits", left_entity="person", right_entity="household"), + ), + ) + source_tables = { + entity: _source_frame().table(entity) for entity in ("person", "household") + } + visits = pd.DataFrame( + { + "person_id": np.array([0, 2], dtype="int64"), + "household_id": np.array([2, 1], dtype="int64"), + "hours": np.array([1.0, 2.0]), + } + ) + source = Frame( + {**source_tables, "visits": visits}, + schema, + {"household": Weights(np.array([100.0, 200.0]), WeightKind.DESIGN)}, + ) + result = _reweighted(source) + + _add_at_into_to_numpy(source.link("visits")["hours"]) + + with pytest.raises(SharedColumnChangedError) as raised: + result.check_shared_columns() + assert raised.value.changed_columns == (("visits", "hours"),) + + +def test_the_constructor_refuses_tables_with_a_changed_shared_column() -> None: + """It deep-copies, so the frame it built could not show the change.""" + + source = _source_frame() + result = _reweighted(source) + _add_at_into_to_numpy(source.table("person")["income"]) + + with pytest.raises(SharedColumnChangedError) as raised: + Frame( + {entity: result.table(entity) for entity in result.entities}, + result.schema, + {"household": result.weights_for("household")}, + ) + assert raised.value.changed_columns == (("person", "income"),) + + +def test_the_constructor_still_reports_a_table_that_is_not_a_dataframe() -> None: + source = _source_frame() + _reweighted(source) + + with pytest.raises(AttributeError, match="no attribute 'columns'"): + Frame( + { + "person": source.table("person")["person_id"], + "household": source.table("household"), + }, + source.schema, + {"household": source.weights_for("household")}, + ) + + +def test_the_constructor_still_reports_strata_that_are_not_a_series() -> None: + source = _source_frame() + _reweighted(source) + + with pytest.raises(TypeError, match="strata must be a pandas Series"): + Frame( + {entity: source.table(entity) for entity in source.entities}, + source.schema, + {"household": source.weights_for("household")}, + strata="not a series", + ) + + +def test_columns_sharing_values_under_different_masks_are_kept_apart() -> None: + values = np.array([1, 2, 3], dtype="int64") + table = pd.DataFrame( + { + "first_hidden": pd.arrays.IntegerArray( + values, np.array([True, False, False]), copy=False + ), + "last_hidden": pd.arrays.IntegerArray( + values, np.array([False, False, True]), copy=False + ), + }, + copy=False, + ) + + shared_columns_module.record_shared_columns({"person": table}) + + check_shared_columns({"person": table}) + + +def test_every_changed_column_is_named_at_once() -> None: + source = _source_frame() + result = _reweighted(source) + + _add_at_into_to_numpy(source.table("person")["income"]) + _add_at_into_to_numpy(source.table("household")["rent"]) + + with pytest.raises(SharedColumnChangedError) as raised: + result.check_shared_columns() + assert raised.value.changed_columns == ( + ("person", "income"), + ("household", "rent"), + ) + + +@pytest.mark.parametrize("operation", sorted(_SHARING_OPERATIONS)) +def test_unchanged_frames_pass_the_check(operation: str) -> None: + source = _source_frame() + result = _SHARING_OPERATIONS[operation](source) + + source.check_shared_columns() + result.check_shared_columns() + + +def _replace_whole_column(table: pd.DataFrame) -> None: + table["income"] = table["income"].to_numpy() + 1.0 + + +def _add_column(table: pd.DataFrame) -> None: + table["added"] = 1.0 + + +def _drop_column_in_place(table: pd.DataFrame) -> None: + table.drop(columns=["income"], inplace=True) + + +def _write_one_cell(table: pd.DataFrame) -> None: + table.loc[table.index[0], "income"] = -1.0 + + +def _replace_nullable_column(table: pd.DataFrame) -> None: + table["count_with_gap"] = pd.array([9, 9, None, 9], dtype="Int64") + + +def _replace_category_column(table: pd.DataFrame) -> None: + table["region"] = pd.Categorical(["south"] * _PERSON_COUNT) + + +_PANDAS_WRITES: dict[str, Callable[[pd.DataFrame], None]] = { + "replace a whole column": _replace_whole_column, + "add a column": _add_column, + "drop a column in place": _drop_column_in_place, + "write one cell": _write_one_cell, + "replace a nullable column": _replace_nullable_column, + "replace a category column": _replace_category_column, +} + + +@pytest.mark.parametrize("pandas_write", sorted(_PANDAS_WRITES)) +def test_writes_made_through_pandas_do_not_trip_the_check(pandas_write: str) -> None: + source = _source_frame() + result = _reweighted(source) + + _PANDAS_WRITES[pandas_write](result.table("person")) + + result.check_shared_columns() + source.check_shared_columns() + person = result.table("person").drop(columns=["income"], errors="ignore") + result.replace_tables(person=person).check_shared_columns() + + +def test_replacing_a_column_after_its_sharer_is_gone_passes_the_check() -> None: + source = _source_frame() + result = _reweighted(source) + del source + gc.collect() + + person = result.table("person") + person["income"] = person["income"].to_numpy() + 1.0 + person["income"] = person["income"].to_numpy() + 1.0 + + result.check_shared_columns() + + +@pytest.mark.parametrize( + ("column_name", "accumulation"), + [ + ("count_with_gap", "cumsum"), + ("count_with_gap", "cummax"), + ("count_with_gap", "cummin"), + ], +) +def test_pandas_overwriting_masked_values_does_not_trip_the_check( + column_name: str, accumulation: str +) -> None: + """pandas rewrites the stored values behind a missing entry here.""" + + source = _source_frame() + result = _reweighted(source) + + getattr(source.table("person")[column_name], accumulation)() + + result.check_shared_columns() + source.check_shared_columns() + + +def test_a_caller_may_keep_writing_to_a_table_it_passed_to_replace_tables() -> None: + source = _source_frame() + table = source.table("person").copy() + first = source.replace_tables(person=table) + del first + gc.collect() + + table.loc[table.index[0], "income"] = 99.0 + + source.replace_tables(person=table).check_shared_columns() + + +def test_an_in_place_pandas_write_after_sharing_ended_is_reported() -> None: + """With no other table on the memory, pandas writes into it directly.""" + + source = _source_frame() + result = _reweighted(source) + del source + gc.collect() + + person = result.table("person") + person.loc[person.index[0], "income"] = -1.0 + + with pytest.raises(SharedColumnChangedError) as raised: + result.check_shared_columns() + assert raised.value.changed_columns == (("person", "income"),) + assert "pandas write" in str(raised.value) + + +def test_freed_memory_is_forgotten() -> None: + gc.collect() + before = shared_columns_module._tracked_owner_count() + table = pd.DataFrame({"income": np.arange(1_000, dtype=float)}) + shared_columns_module.record_shared_columns({"person": table}) + assert shared_columns_module._tracked_owner_count() == before + 1 + + del table + gc.collect() + + assert shared_columns_module._tracked_owner_count() == before + + +def test_a_new_array_at_a_freed_address_is_not_compared() -> None: + """An array allocated where a freed one lived is different memory.""" + + size = 4_096 + table = pd.DataFrame({"income": np.zeros(size)}) + shared_columns_module.record_shared_columns({"person": table}) + address = table["income"].to_numpy().__array_interface__["data"][0] + del table + gc.collect() + + # The allocator usually hands the same block back; the test means nothing + # unless it did. + arrays = [np.ones(size) for _ in range(32)] + reused = [ + array for array in arrays if array.__array_interface__["data"][0] == address + ] + if not reused: + pytest.skip("the allocator did not reuse the freed address") + + check_shared_columns({"person": pd.DataFrame({"income": reused[0]}, copy=False)}) + + +def _counted_digests(monkeypatch: pytest.MonkeyPatch) -> list[int]: + """Record the length of every buffer the check hashes.""" + + hashed_lengths: list[int] = [] + original = shared_columns_module._buffer_digest + + def counting_digest(stored: shared_columns_module._StoredArray) -> bytes: + hashed_lengths.append(len(stored.values)) + return original(stored) + + monkeypatch.setattr(shared_columns_module, "_buffer_digest", counting_digest) + return hashed_lengths + + +def test_a_column_is_hashed_once_however_many_frames_share_it( + monkeypatch: pytest.MonkeyPatch, +) -> None: + source = _source_frame() + hashed_lengths = _counted_digests(monkeypatch) + + first = _reweighted(source) + hashed_for_first_frame = len(hashed_lengths) + assert hashed_for_first_frame > 0 + + second = _reweighted(first) + third = second.replace_tables() + + assert len(hashed_lengths) == hashed_for_first_frame + assert third.n("person") == _PERSON_COUNT + + +def test_replace_tables_hashes_only_the_columns_it_drops( + monkeypatch: pytest.MonkeyPatch, +) -> None: + source = _source_frame() + result = _reweighted(source) + hashed_lengths = _counted_digests(monkeypatch) + + result.replace_tables(person=result.table("person").drop(columns="income")) + + assert hashed_lengths == [_PERSON_COUNT] + + +def test_frames_that_share_nothing_are_not_hashed( + monkeypatch: pytest.MonkeyPatch, +) -> None: + hashed_lengths = _counted_digests(monkeypatch) + + source = _source_frame() + # A selection dropping a household copies every row it keeps. + selected = source.select(np.array([True, True, False, False])) + source.check_shared_columns() + selected.check_shared_columns() + + assert hashed_lengths == [] + + +def test_nothing_is_recorded_when_copy_on_write_is_off( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(bundle_module, "_pandas_copy_on_write", lambda: False) + hashed_lengths = _counted_digests(monkeypatch) + + result = _reweighted(_source_frame()) + result.check_shared_columns() + + assert hashed_lengths == [] + + +class _RecordingStore: + """Stands in for an HDF store and records what reaches it.""" + + def __init__(self) -> None: + self.written_keys: list[str] = [] + + def put(self, key: str, *_arguments: object, **_options: object) -> None: + self.written_keys.append(key) + + +def test_the_table_writer_refuses_a_changed_shared_column() -> None: + source = _source_frame() + result = _reweighted(source) + _add_at_into_to_numpy(source.table("person")["income"]) + store = _RecordingStore() + + with pytest.raises(SharedColumnChangedError) as raised: + put_frame_table( + store, "person", result.table("person"), preferred_format="fixed" + ) + + assert raised.value.changed_columns == (("person", "income"),) + assert store.written_keys == [] + + +def test_the_table_writer_accepts_unchanged_shared_columns() -> None: + source = _source_frame() + result = _reweighted(source) + store = _RecordingStore() + + put_frame_table( + store, "household", result.table("household"), preferred_format="fixed" + ) + + assert store.written_keys == ["household"] + + +def test_engine_tables_refuses_a_frame_with_a_changed_shared_column() -> None: + """``engine_tables`` deep-copies, so a later check could not see the change.""" + + source = _source_frame() + result = _reweighted(source) + _add_at_into_to_numpy(source.table("person")["income"]) + + with pytest.raises(SharedColumnChangedError): + engine_tables(result) diff --git a/packages/microcosm-graph/tests/fixtures/parity/kernels/calibrate/pins.json b/packages/microcosm-graph/tests/fixtures/parity/kernels/calibrate/pins.json index 87c8d0d888..da8d41937d 100644 --- a/packages/microcosm-graph/tests/fixtures/parity/kernels/calibrate/pins.json +++ b/packages/microcosm-graph/tests/fixtures/parity/kernels/calibrate/pins.json @@ -1 +1 @@ -{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","scipy":"1.17.1","torch":"2.12.0"},"implementation_hash":"584886552a44ac4208fb878f54a195fa9a6962324175ce7ae0991cafd1816a69","kernel":"calibrate.adam@1","node":"calibrate","node_key":"6bff4ad9837e10c290ecfd9778a1cd59ec0826a7bdb3fe03cc194a37feac3618","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"6bff4ad9837e10c290ecfd9778a1cd59ec0826a7bdb3fe03cc194a37feac3618"}},"seed":0} +{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","scipy":"1.17.1","torch":"2.12.0"},"implementation_hash":"e8ab1d370f02917ac073f7ac0e2413e259d66acf66adeab93d4bfa9057554673","kernel":"calibrate.adam@1","node":"calibrate","node_key":"18a16aefaba5c3fbbce77d193074a202ef1d58e0a3d90bd085bf8ae5853628b2","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"18a16aefaba5c3fbbce77d193074a202ef1d58e0a3d90bd085bf8ae5853628b2"}},"seed":0} diff --git a/packages/microcosm-graph/tests/fixtures/parity/kernels/simulate/pins.json b/packages/microcosm-graph/tests/fixtures/parity/kernels/simulate/pins.json index d30dfcc3e5..bb816bddcf 100644 --- a/packages/microcosm-graph/tests/fixtures/parity/kernels/simulate/pins.json +++ b/packages/microcosm-graph/tests/fixtures/parity/kernels/simulate/pins.json @@ -1 +1 @@ -{"dependencies":{},"implementation_hash":"90753d809d5e9953a6c6b8c2a282e8dc675143d92d587fb144aba70ecd46b6ad","kernel":"simulate.rules@1","node":"simulate","node_key":"56247d886b9b25341f4c40ac18b9d331da6e692f3940f68268fe1c2a553d43e0","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"56247d886b9b25341f4c40ac18b9d331da6e692f3940f68268fe1c2a553d43e0"}},"seed":null} +{"dependencies":{},"implementation_hash":"f39954666c78cd388868c14b1eebb8ad915212feac1bbe31381a88884d340f09","kernel":"simulate.rules@1","node":"simulate","node_key":"f648aad2be5ae8ba5003bdd9ea2629fc9337c2db2df361c50720ead91d32f61c","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"f648aad2be5ae8ba5003bdd9ea2629fc9337c2db2df361c50720ead91d32f61c"}},"seed":null} diff --git a/tools/_legacy/build_us_acs_multispine_base.py b/tools/_legacy/build_us_acs_multispine_base.py index 4299a2e65f..e5bf3cbb8b 100644 --- a/tools/_legacy/build_us_acs_multispine_base.py +++ b/tools/_legacy/build_us_acs_multispine_base.py @@ -2258,6 +2258,7 @@ def _write_dataset( back; the default writes none, so a legacy file is unchanged. """ + frame.check_shared_columns() output = Path(path) output.unlink(missing_ok=True) try: diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index a92d124e92..4037d9240e 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -1766,9 +1766,11 @@ def extract_struct_tables(frame, *, county_column="county_fips", county_run=Fals """Small structural/geography copies so the big frame can be freed early. ``county_run`` keeps what county reliability needs after a reload - (:func:`us_acs_local_county_surface.struct_columns`). + (:func:`us_acs_local_county_surface.struct_columns`). The lean checkpoint + is written from these copies, so shared columns are checked here. """ + frame.check_shared_columns() households = frame.table("household") struct_columns = [ column for column in LEAN_HOUSEHOLD_COLUMNS if column in households.columns diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index f672b84652..15cc13341f 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -3261,6 +3261,7 @@ def _write_target_frame_checkpoint( ) -> dict[str, object]: import h5py + frame.check_shared_columns() path.parent.mkdir(parents=True, exist_ok=True) tmp_path = path.with_name(f"{path.name}.tmp") if tmp_path.exists(): @@ -18122,9 +18123,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: "refit_initial_loss": _finite_or_none(result.initial_loss), "refit_final_loss": _finite_or_none(result.final_loss), } - # Frame.with_weights copies the target tables into each calibrated frame. - # Drop the input now and replace those result frames after building the - # clean export from base_frame and the calibrated weights below. + # A calibrated frame built from target_frame by Frame.with_weights (the + # dense result, an L0 selection) shares the target tables' memory with it, + # so the tables are freed only once both references are gone: drop the + # input now, and replace those result frames after building the clean + # export from base_frame and the calibrated weights below. del target_frame if telemetry is not None: telemetry.stage(