From 546137586f98daca1ff58869288a17406855726e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:19:27 +0400 Subject: [PATCH 01/24] Build with_weights, place, select and the checkpoint loader through Frame._adopt with_weights, place and select now hand their result's tables to Frame._adopt instead of the copying constructor. Under pandas copy-on-write the result shares every unchanged column's memory with its source, in DataFrame objects of its own, so a pandas write to either frame never reaches the other; with copy-on-write off, _adopt still deep-copies. place keeps its column insert, on a shallow copy, and ignores pandas' fragmentation warning around it. The checkpoint loader takes its decoded tables without a copy, so reading a checkpoint holds one copy of the data instead of two. calibrate gains return_frame (default True). With return_frame=False the result carries frame=None, and the calibrated weights still pass the checks with_weights makes, now in Frame._checked_weight_change, which both paths call. The memory-sharing test in test_us_post_export_scoring.py now asserts that calibration leaves its input frame unchanged and unreferenced, and that the calibrated frame shares the input's column memory. The release tool's comment on del target_frame and the release build rule document describe why the tables are freed only once both references are gone. Co-Authored-By: Claude Opus 5.5 --- docs/us-release-build-rule.md | 10 +- .../src/microcosm/build/frame_checkpoint.py | 12 +- .../shared/test_frame_checkpoint.py | 119 ++++++ .../us/test_us_post_export_scoring.py | 56 ++- .../src/microcosm/calibrate/solve.py | 58 ++- .../tests/engine_free/shared/test_solve.py | 86 ++++ .../src/microcosm/frame/bundle.py | 107 +++-- .../shared/test_frame_operation_sharing.py | 401 ++++++++++++++++++ tools/build_us_fiscal_refresh_release.py | 8 +- 9 files changed, 799 insertions(+), 58 deletions(-) create mode 100644 packages/microcosm-frame/tests/engine_free/shared/test_frame_operation_sharing.py diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index 6ea4f3ed17..cde86a2bc7 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -358,10 +358,12 @@ 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. +`Frame.with_weights` shares every table's memory with its input, target +columns included, so the tables are freed only once both the target frame and +the 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..a12594c7a4 100644 --- a/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py +++ b/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py @@ -175,9 +175,14 @@ 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. + ``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 +304,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/tests/engine_free/shared/test_frame_checkpoint.py b/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint.py index 7c79ba3f81..365c676d78 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 @@ -19,6 +19,7 @@ EntitySchema, Frame, LinkSpec, + MassChange, MassChangeRecord, WeightKind, Weights, @@ -741,3 +742,121 @@ def test_legacy_string_specs_restore_python_storage() -> None: path=Path("legacy.h5"), label="person.label", ) + + +def test_loader_keeps_the_decoded_columns_without_copying( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> 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}") + # The decoded arrays are fresh and writable, as the constructor's + # copies were, so a pandas write into the loaded frame still works. + table.loc[table.index[0], column] = table[column].iloc[0] + assert {"person.float_measure", "household.household_income"} <= set(compared) + + +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, +} + + +@pytest.mark.parametrize("source", ["constructed", "loaded"]) +@pytest.mark.parametrize("operation", list(_ADOPTING_OPERATIONS)) +def test_adopted_frames_write_the_bytes_of_copied_frames( + tmp_path: Path, source: str, operation: str +) -> None: + """Sharing tables instead of copying them leaves checkpoint bytes unchanged. + + The reference rebuilds the same frame through the copying constructor, + which is how these operations built their result before they moved to + ``Frame._adopt``. Both checkpoints are written in this process, so the + comparison does not depend on HDF5 library bytes that differ between + platforms. + """ + frame = _checkpoint_frame() + if source == "loaded": + write_frame_checkpoint(tmp_path / "source.h5", frame) + frame = load_frame_checkpoint(tmp_path / "source.h5").frame + derived = _ADOPTING_OPERATIONS[operation](frame) + 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() 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 c45b8db3a4..ad857f1f5b 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,8 @@ """Tests split from packages/microcosm-build/tests/test_us_post_export_scoring.py.""" # ruff: noqa: F403, F405 +import weakref + from test_support.microcosm_build.us_post_export_scoring import * @@ -1173,12 +1175,28 @@ 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.""" +def test_calibration_leaves_its_input_frame_unchanged_and_unreferenced() -> 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__ @@ -1187,12 +1205,36 @@ 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) + input_household_table = weakref.ref(frame.table("household")) + del frame, result + gc.collect() + assert input_household_table() is None def test_calibration_results_drop_their_frames_and_keep_everything_else( diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py b/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py index e55a42a470..33b734901d 100644 --- a/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py @@ -288,7 +288,12 @@ 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`). initial_weights: The input weight values. These remain the frame's @@ -335,7 +340,7 @@ class CalibrationResult: and every operator downstream consumes :attr:`frame`. """ - frame: Frame + frame: Frame | None weight_entity: str weights: np.ndarray initial_weights: np.ndarray @@ -2447,6 +2452,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 +2623,22 @@ 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 + checks :meth:`~microcosm.frame.Frame.with_weights` makes (forward + kind transition, the mass policy), so a vector that breaks them + is refused either way. 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 +2668,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 +2966,7 @@ def calibrate( mass, targets, mass_reason=mass_reason, + return_frame=return_frame, ) diagnostics = _build_diagnostics(problem, frame, w0, final_weights) @@ -3260,7 +3281,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 +3291,25 @@ 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 checks ``Frame.with_weights`` makes, 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( 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..f4a6852245 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,88 @@ 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") diff --git a/packages/microcosm-frame/src/microcosm/frame/bundle.py b/packages/microcosm-frame/src/microcosm/frame/bundle.py index e691826e7d..f31b0b5577 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -21,10 +21,11 @@ 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`). """ import re @@ -841,7 +842,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 +857,43 @@ 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 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 length check is the + frame constructor's and runs only when a frame is built. + + 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 +926,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. + """ + return { + name: table.copy(deep=False) + for name, table in {**self._tables, **self._link_tables}.items() + } @staticmethod def _mass_change_record( @@ -1096,7 +1140,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 +1188,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 +1462,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` without a further copy of + the selected tables. Raises: NotImplementedError: If the frame carries link tables (links are @@ -1467,7 +1520,9 @@ def select(self, person_mask: np.ndarray | pd.Series) -> "Frame": existing.values[keep], kind=existing.kind ) strata = self._strata.loc[mask] - return Frame( + # Row selection makes new DataFrame objects, so the result can own + # them; with every person kept they still share the source's memory. + return Frame._adopt( tables, self._schema, weights, 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..9532e0ccf9 --- /dev/null +++ b/packages/microcosm-frame/tests/engine_free/shared/test_frame_operation_sharing.py @@ -0,0 +1,401 @@ +"""``with_weights``, ``place`` and ``select`` build their result through ``_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), ``_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 + +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: + return pd.Series(["cps", "cps", "puf", "puf"], index=pd.RangeIndex(4)) + + +@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 +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 + + +@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 + ) + + +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) + + +@pytest.mark.parametrize("operation", list(_OPERATIONS)) +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 + + +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/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 8e05283457..488d07fb95 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -15936,9 +15936,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. + # Each calibrated frame shares the target tables' memory with target_frame + # (Frame.with_weights does not copy them), 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( From cbbeb2e7db91ac9575a26556d904dac5122b2e16 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:11:36 +0400 Subject: [PATCH 02/24] Address review: pin checkpoint content, tighten tests and docs - Pin a SHA-256 of each checkpoint's dataset contents (names, dtypes, shapes, bytes) for every operation, recorded with the copying code at 8afea44e9, so a change to an operation's output, not just to the table layout, fails the test. Add a source frame with named column axes. - Drop the loader test's writability check, which could not fail. - Assert that each result holds its own strata object. - The post-export memory test now follows a column to the array that owns its memory: the calibrated frame keeps it alive, a result built with return_frame=False does not. - refit_l0_selection refuses a selection without a frame with a clear ValueError instead of an AttributeError; L0RefitResult.frame is typed Frame | None. - _checked_weight_change and calibrate's docstrings now say that the frame constructor's table checks are not re-run without a frame. Co-Authored-By: Claude Opus 5.5 --- .../shared/test_frame_checkpoint.py | 258 ++++++++++++++++-- .../us/test_us_post_export_scoring.py | 15 +- .../src/microcosm/calibrate/solve.py | 24 +- .../tests/engine_free/shared/test_solve.py | 25 ++ .../src/microcosm/frame/bundle.py | 16 +- .../shared/test_frame_operation_sharing.py | 1 + 6 files changed, 307 insertions(+), 32 deletions(-) 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 365c676d78..3b10a4ed42 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,5 +1,6 @@ from __future__ import annotations +import hashlib import json import os import stat @@ -774,12 +775,34 @@ def recording_read_series(group, spec, input_path, *, label): table[column].to_numpy(), decoded[f"{name}.{column}"].to_numpy() ), f"{name}.{column}" compared.append(f"{name}.{column}") - # The decoded arrays are fresh and writable, as the constructor's - # copies were, so a pandas write into the loaded frame still works. - table.loc[table.index[0], column] = table[column].iloc[0] 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.""" @@ -827,24 +850,225 @@ def _doubled_household_weights(frame: Frame) -> Frame: } -@pytest.mark.parametrize("source", ["constructed", "loaded"]) -@pytest.mark.parametrize("operation", list(_ADOPTING_OPERATIONS)) +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: str, operation: str + tmp_path: Path, source_frame: str, source: str, operation: str ) -> None: - """Sharing tables instead of copying them leaves checkpoint bytes unchanged. + """A shared table layout writes the same file as a copied one. - The reference rebuilds the same frame through the copying constructor, - which is how these operations built their result before they moved to - ``Frame._adopt``. Both checkpoints are written in this process, so the - comparison does not depend on HDF5 library bytes that differ between - platforms. + 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. """ - frame = _checkpoint_frame() - if source == "loaded": - write_frame_checkpoint(tmp_path / "source.h5", frame) - frame = load_frame_checkpoint(tmp_path / "source.h5").frame - derived = _ADOPTING_OPERATIONS[operation](frame) + + derived = _derived_frame(tmp_path, source_frame, source, operation) copied = Frame( dict(frame_checkpoint_module._frame_tables(derived)), derived.schema, 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 ad857f1f5b..9a39177cb2 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 @@ -1231,10 +1231,19 @@ def test_calibration_leaves_its_input_frame_unchanged_and_unreferenced() -> None ) assert frameless.frame is None np.testing.assert_array_equal(frameless.weights, result.weights) - input_household_table = weakref.ref(frame.table("household")) - del frame, result + # 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() - assert input_household_table() is None + # 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-calibrate/src/microcosm/calibrate/solve.py b/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py index 33b734901d..666f40162d 100644 --- a/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py @@ -466,8 +466,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 @@ -2628,9 +2628,12 @@ def calibrate( 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 - checks :meth:`~microcosm.frame.Frame.with_weights` makes (forward - kind transition, the mass policy), so a vector that breaks them - is refused either way. + 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 (``None`` when @@ -3293,7 +3296,8 @@ def _apply_weights( generic reason naming the calibration. With ``return_frame=False`` no frame is built: the weights go through the - same checks ``Frame.with_weights`` makes, and ``None`` is returned. + 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 @@ -3491,6 +3495,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 f4a6852245..e3ef2c7ba8 100644 --- a/packages/microcosm-calibrate/tests/engine_free/shared/test_solve.py +++ b/packages/microcosm-calibrate/tests/engine_free/shared/test_solve.py @@ -2442,3 +2442,28 @@ def test_calibrate_refuses_a_return_frame_that_is_not_a_bool(feasible_frame) -> 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/bundle.py b/packages/microcosm-frame/src/microcosm/frame/bundle.py index f31b0b5577..a2be825cc9 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -879,12 +879,16 @@ def _checked_weight_change( ) -> MassChangeRecord | None: """Check a replacement of ``entity``'s weights without building a frame. - Runs every check :meth:`with_weights` makes 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 length check is the - frame constructor's and runs only when a frame is built. + 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: the + weight vector's length, 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 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 index 9532e0ccf9..d8ef31d689 100644 --- 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 @@ -280,6 +280,7 @@ def test_every_result_table_is_a_distinct_object(request, operation: str) -> Non source_tables = _tables_of(source) for name, table in _tables_of(result).items(): assert table is not source_tables[name], name + assert result.strata is not source.strata @pytest.mark.parametrize("operation", list(_OPERATIONS)) From 414c27fd617e9f81c070de2cd92cfb5f6fbffea5 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:32:26 +0400 Subject: [PATCH 03/24] Check the place source table's sharing and correct result docs - test_place_shares_every_table_it_does_not_change also checks the table the column moves out of; drop a strata assertion that held whatever the operations did. - CalibrationResult docs and the release tool's comment on del target_frame describe which frames share the target tables and that a frameless result carries no frame. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/calibrate/solve.py | 6 ++++-- .../engine_free/shared/test_frame_operation_sharing.py | 6 +++++- tools/build_us_fiscal_refresh_release.py | 10 +++++----- 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py b/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py index 666f40162d..483d2f920a 100644 --- a/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py @@ -295,7 +295,8 @@ class CalibrationResult: 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``. @@ -337,7 +338,8 @@ 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 | None 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 index d8ef31d689..a63befe3e1 100644 --- 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 @@ -262,6 +262,11 @@ def test_place_shares_every_table_it_does_not_change( 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: @@ -280,7 +285,6 @@ def test_every_result_table_is_a_distinct_object(request, operation: str) -> Non source_tables = _tables_of(source) for name, table in _tables_of(result).items(): assert table is not source_tables[name], name - assert result.strata is not source.strata @pytest.mark.parametrize("operation", list(_OPERATIONS)) diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 488d07fb95..354912dc8c 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -15936,11 +15936,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), } - # Each calibrated frame shares the target tables' memory with target_frame - # (Frame.with_weights does not copy them), 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. + # 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( From ca2d8fb4f925828f49daa1e467ea04348539f958 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:00:21 +0400 Subject: [PATCH 04/24] Guard sharing tests for pandas 2 and record the loaded-table layout - The sharing tests turn copy-on-write on under pandas 2.x, as the _adopt tests do; packages still allow pandas >= 2.3. - load_frame_checkpoint's docstring says that a pandas fixed-format HDF write of a loaded table can group its columns into different datasets than a write of the same table built in memory, with the same values. - _checked_weight_change's docstring states the skipped length check correctly; the release build rule document names the frames that share the target tables. Co-Authored-By: Claude Opus 5.5 --- docs/us-release-build-rule.md | 5 +++-- .../src/microcosm/build/frame_checkpoint.py | 5 ++++- .../engine_free/shared/test_frame_checkpoint.py | 14 +++++++++++++- .../us/test_us_post_export_scoring.py | 16 +++++++++++++++- .../src/microcosm/frame/bundle.py | 8 ++++---- .../shared/test_frame_operation_sharing.py | 13 ++++++++++++- 6 files changed, 51 insertions(+), 10 deletions(-) diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index cde86a2bc7..473685a593 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -359,9 +359,10 @@ reform and does not replace this sweep. `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` shares every table's memory with its input, target +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 -the result frames are dropped. Dense and L0 results drop those frames; exact-k +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. diff --git a/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py b/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py index a12594c7a4..51f65d91c3 100644 --- a/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py +++ b/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py @@ -178,7 +178,10 @@ def load_frame_checkpoint( 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. + 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 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 3b10a4ed42..43671c47f4 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 @@ -5,6 +5,7 @@ import os import stat import time +from collections.abc import Iterator from pathlib import Path import numpy as np @@ -745,8 +746,19 @@ def test_legacy_string_specs_restore_python_storage() -> None: ) +@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 + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, copy_on_write_on: None ) -> None: """The loaded frame holds the columns the loader decoded, not a copy. 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 9a39177cb2..c556c332c1 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 @@ -2,6 +2,7 @@ # ruff: noqa: F403, F405 import weakref +from collections.abc import Iterator from test_support.microcosm_build.us_post_export_scoring import * @@ -1175,7 +1176,20 @@ def test_main_frees_the_target_frame_before_the_export(builder) -> None: assert reads and max(reads) < deleted_at -def test_calibration_leaves_its_input_frame_unchanged_and_unreferenced() -> None: +@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 diff --git a/packages/microcosm-frame/src/microcosm/frame/bundle.py b/packages/microcosm-frame/src/microcosm/frame/bundle.py index a2be825cc9..bebeaaeeb7 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -885,10 +885,10 @@ def _checked_weight_change( 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: the - weight vector's length, 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`). + :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 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 index a63befe3e1..69d08eb9b7 100644 --- 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 @@ -11,7 +11,7 @@ """ import warnings -from collections.abc import Callable +from collections.abc import Callable, Iterator import numpy as np import pandas as pd @@ -115,6 +115,17 @@ def unlinked_frame() -> Frame: ) +@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.""" From 1fe17cb21d66c3436d6bfa2e004e011a59579e14 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:21:53 +0400 Subject: [PATCH 05/24] Check strata in the sharing tests and qualify select's no-copy claim - The copy-on-write-off test drops the partial-selection case, which copies rows whatever _adopt does, and also checks the strata. The test frame's strata are object dtype so that memory comparisons of them are meaningful; with_weights' sharing test checks them too. - select's docstring and comment say the selected tables escape a second copy only under pandas copy-on-write. Co-Authored-By: Claude Opus 5.5 --- .../microcosm-frame/src/microcosm/frame/bundle.py | 7 ++++--- .../shared/test_frame_operation_sharing.py | 14 ++++++++++++-- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/packages/microcosm-frame/src/microcosm/frame/bundle.py b/packages/microcosm-frame/src/microcosm/frame/bundle.py index bebeaaeeb7..e9a715e895 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -1466,8 +1466,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, built through :meth:`_adopt` without a further copy of - the selected tables. + 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 @@ -1525,7 +1525,8 @@ def select(self, person_mask: np.ndarray | pd.Series) -> "Frame": ) strata = self._strata.loc[mask] # Row selection makes new DataFrame objects, so the result can own - # them; with every person kept they still share the source's memory. + # them; under copy-on-write, with every person kept, they still share + # the source's memory. return Frame._adopt( tables, self._schema, 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 index 69d08eb9b7..5c430e54ac 100644 --- 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 @@ -81,7 +81,9 @@ def _weights() -> dict[str, Weights]: def _strata() -> pd.Series: - return pd.Series(["cps", "cps", "puf", "puf"], index=pd.RangeIndex(4)) + # 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 @@ -243,6 +245,9 @@ def test_with_weights_shares_every_column_with_the_source(linked_frame) -> None: ) 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( @@ -335,7 +340,11 @@ def test_a_pandas_write_to_the_source_leaves_the_result_unchanged( _assert_matches_snapshot(result, before) -@pytest.mark.parametrize("operation", list(_OPERATIONS)) +# Selecting a strict subset of persons copies their rows whatever ``_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: @@ -344,6 +353,7 @@ def test_operations_deep_copy_when_copy_on_write_is_off( 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: From 0aac10fdfa14d75ee16f864997b82dca63180eaa Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:54:12 +0400 Subject: [PATCH 06/24] Correct the annual static-aging memory account calibrate's result frame now shares the calibrated frame's tables instead of copying them, so us_annual_static_aging's module docstring, its comment on releasing the calibration result, and docs/us-local-annual-projection.md no longer count a calibration copy. Co-Authored-By: Claude Opus 5.5 --- docs/us-local-annual-projection.md | 3 ++- .../microcosm/build/us_annual_static_aging.py | 18 +++++++++++------- 2 files changed, 13 insertions(+), 8 deletions(-) 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/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") From 02cda02edfb18b1657a93d98482b8344337c8d2b Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:03:49 +0400 Subject: [PATCH 07/24] Restore bundle.py's warnings import lost in the rebase, and re-pin Rebasing onto the Frame._adopt branch's latest commit, which rewrote the same import block, dropped `import warnings`, so Frame.place raised NameError. Restore it and re-record the calibrate and simulate parity pins, whose implementation hash covers bundle.py's source. Co-Authored-By: Claude Opus 5.5 --- packages/microcosm-frame/src/microcosm/frame/bundle.py | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/microcosm-frame/src/microcosm/frame/bundle.py b/packages/microcosm-frame/src/microcosm/frame/bundle.py index e9a715e895..c9ee52b9c3 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -29,6 +29,7 @@ """ import re +import warnings from collections.abc import Mapping from dataclasses import dataclass from typing import Any From cc5c7afabd19fb171c8de10ab9781c3ebc85babf Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:44:34 +0400 Subject: [PATCH 08/24] Re-pin the calibrate and simulate parity kernels The calibrate.adam@1 and simulate kernels hash the source of frame/bundle.py, and calibrate's also that of calibrate/solve.py, both of which this branch changes. Re-recorded on top of the Frame._adopt branch's pins with tools/graph_parity_repin.py on arm64/darwin/py3.14: only the implementation hash and node key move; the tool checks that each kernel's direct output bytes did not. Co-Authored-By: Claude Opus 5.5 --- .../tests/fixtures/parity/kernels/calibrate/pins.json | 2 +- .../tests/fixtures/parity/kernels/simulate/pins.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 c5322d9bcd..030db8486d 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":"fc60efef7fa130c91f9096d6e9c434f7a4d41c2e810117bc0c0d81099d5519a6","kernel":"calibrate.adam@1","node":"calibrate","node_key":"a630cc374e04d57e40a9b5accf38e613eca4432e6a1eaa2edd19e12010187744","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"a630cc374e04d57e40a9b5accf38e613eca4432e6a1eaa2edd19e12010187744"}},"seed":0} +{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","scipy":"1.17.1","torch":"2.12.0"},"implementation_hash":"eea4c43ca2ef64acc68012287d5e353f0a7d8d305939c4b484bcd0129c435697","kernel":"calibrate.adam@1","node":"calibrate","node_key":"99ccbc158a1b78ba6f5d7201a09a8f63407448fc22eb6e3f7f200feeb882345a","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"99ccbc158a1b78ba6f5d7201a09a8f63407448fc22eb6e3f7f200feeb882345a"}},"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 7d502aba55..6ced4ecdcd 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":"9e9c040b3ace173f7da06fbd1e7f887a70c54587f68da071660b0f0fa5c866e9","kernel":"simulate.rules@1","node":"simulate","node_key":"2d7c76fcb80924e1df716440e2bad67a907412d9f8cde5002878b2bd7d304ed9","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"2d7c76fcb80924e1df716440e2bad67a907412d9f8cde5002878b2bd7d304ed9"}},"seed":null} +{"dependencies":{},"implementation_hash":"910fadde4b27d7cb8925720dbbea15920b70a78a315e8d40b7cb020e51423b73","kernel":"simulate.rules@1","node":"simulate","node_key":"99188b86e5eaf8cc7ca59f91bd9d4373c2aec03e2a3a236b62dcf79cd06eee9a","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"99188b86e5eaf8cc7ca59f91bd9d4373c2aec03e2a3a236b62dcf79cd06eee9a"}},"seed":null} From 526c9864dc6316e3083fed8fa6980e03aed809b4 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:03:49 +0400 Subject: [PATCH 09/24] Re-pin the US spec-engine digests for the solve.py change calibrate's return_frame option changes solve.py, whose bytes the seed protocol hashes. Regenerated with tools/repin_us_spec_engine_contracts.py and tools/spec_engine_coverage.py in the locked US environment. The US bundle itself does not change. Co-Authored-By: Claude Opus 5.5 --- docs/evidence/spec-engine/us-f0-coverage.json | 16 ++++++++-------- .../build/spec_engine/inventory_coverage.py | 4 ++-- .../shared/test_spec_engine_loader.py | 2 +- .../us/test_us_multispine_pool_tool.py | 3 ++- 4 files changed, 13 insertions(+), 12 deletions(-) diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index 348354e26c..fd536dca16 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": "d756dc67535c04788e605bedb4cd6721cf715e5f5ce4be73d9b27420a61b3d50", - "protocol_sha256": "2c57cbfb9dd0f132f9b5751eb8bc303f4b7e37430cd5e0b155aac0b0b8eaa42e" + "map_sha256": "f84bca97184ea010e093f784d64bb26529668de53094a84a2bb23b86401fd26b", + "protocol_sha256": "69cd202c53ed179dcef3e80fdf3ccdd4f85caf35825887b24068ea1cfb99c917" }, "failures": [], "observed": { - "map_sha256": "d756dc67535c04788e605bedb4cd6721cf715e5f5ce4be73d9b27420a61b3d50", - "protocol_sha256": "2c57cbfb9dd0f132f9b5751eb8bc303f4b7e37430cd5e0b155aac0b0b8eaa42e" + "map_sha256": "f84bca97184ea010e093f784d64bb26529668de53094a84a2bb23b86401fd26b", + "protocol_sha256": "69cd202c53ed179dcef3e80fdf3ccdd4f85caf35825887b24068ea1cfb99c917" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "2c57cbfb9dd0f132f9b5751eb8bc303f4b7e37430cd5e0b155aac0b0b8eaa42e", + "implementation_sha256": "69cd202c53ed179dcef3e80fdf3ccdd4f85caf35825887b24068ea1cfb99c917", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "2c57cbfb9dd0f132f9b5751eb8bc303f4b7e37430cd5e0b155aac0b0b8eaa42e", + "implementation_sha256": "69cd202c53ed179dcef3e80fdf3ccdd4f85caf35825887b24068ea1cfb99c917", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "372858d059a129d7b3bcbd7ac2dbdc314742345bd35aaff8d53943e737c98f84" + "spec_sha256": "586a655e783d039c32325192094aafb01b68e38181db6c1afc8506c6400c3ffa" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "372858d059a129d7b3bcbd7ac2dbdc314742345bd35aaff8d53943e737c98f84" + "spec_sha256": "586a655e783d039c32325192094aafb01b68e38181db6c1afc8506c6400c3ffa" }, "status": "pass" } diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py index fff542b87b..6bf31694ca 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 @@ -402,8 +402,8 @@ # microcosm#1641 moves both again: it rewords docstrings and a comment in # solve and the delivery gate's docstring in ssi_take_up, which now names # the builder's arms by flag; no draw, RNG rule, QRF target or solve changes. - "seed_map": "d756dc67535c04788e605bedb4cd6721cf715e5f5ce4be73d9b27420a61b3d50", - "seed_protocol": "2c57cbfb9dd0f132f9b5751eb8bc303f4b7e37430cd5e0b155aac0b0b8eaa42e", + "seed_map": "f84bca97184ea010e093f784d64bb26529668de53094a84a2bb23b86401fd26b", + "seed_protocol": "69cd202c53ed179dcef3e80fdf3ccdd4f85caf35825887b24068ea1cfb99c917", "source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6", "take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35", "tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0", 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 56e430cbe6..bf9a6da33c 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 @@ -33,7 +33,7 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # microcosm#1641's docstring and comment wording in solve and ssi_take_up # moves it again. assert first.spec_sha256 == ( - "cb9742d5089eddb8783ee1cb890206b33a35efe5ff572656dbd58a1b95ea1e28" + "746bb14736f5f9a4ff6c3749a8ce5611f2651017784d3051503e7078f5eaabbd" ) second_root = _rich_minimal(tmp_path / "xy", note="second", store="local:b") 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 a22f1927d5..3eaae761e2 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 @@ -363,7 +363,8 @@ def capture_equality(expected: object, actual: object) -> None: # microcosm#1543's fit input checks in microcosm.fit.qrf move it again. # microcosm#1641 moves it again: docstring and comment wording in # solve and ssi_take_up, and the calibration contract's renamed modes. - "spec_sha256": "372858d059a129d7b3bcbd7ac2dbdc314742345bd35aaff8d53943e737c98f84", + # calibrate's return_frame option in solve moves it again. + "spec_sha256": "586a655e783d039c32325192094aafb01b68e38181db6c1afc8506c6400c3ffa", }, } From 217723611f39700960a30e92f016202cbf5876c9 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:03:49 +0400 Subject: [PATCH 10/24] Add the changelog fragment and name the new sharing operations Co-Authored-By: Claude Opus 5.5 --- changelog.d/frame-operations-share-columns.changed.md | 1 + .../tests/engine_free/shared/test_shared_buffer_writes.py | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) create mode 100644 changelog.d/frame-operations-share-columns.changed.md 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..3aea9cb678 --- /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`. 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..d64415bec7 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,7 +1,8 @@ """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.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 From 5f9a161adcfcf089c5b43cf29544fd2e63d25fe9 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:46:07 +0400 Subject: [PATCH 11/24] Check shared frame columns before every checkpoint and output write Frame operations now record a SHA-256 digest of each column when they start sharing it. The digest belongs to the array's memory, so a column is hashed once however many frames share it, and it is dropped when the memory is freed. Checkpoint and output writers compare the digests first and raise SharedColumnChangedError naming each changed table and column. A column replaced through pandas moves to new memory and is not compared. Co-Authored-By: Claude Opus 5.5 --- .../frame-shared-column-check.added.md | 1 + .../src/microcosm/build/frame_checkpoint.py | 8 +- .../acs_local_ssi_medicaid_take_up.py | 7 +- .../src/microcosm/build/us_runtime/h5_io.py | 5 +- .../shared/test_frame_checkpoint.py | 38 ++ .../us/test_us_acs_local_sparse_cd.py | 16 +- .../us/test_us_fiscal_refresh_builder.py | 29 +- .../us/test_us_multispine_pool_h5_io.py | 27 +- .../src/microcosm/frame/__init__.py | 6 + .../src/microcosm/frame/bundle.py | 61 ++- .../src/microcosm/frame/materialize.py | 14 +- .../src/microcosm/frame/shared_columns.py | 238 +++++++++ .../shared/test_shared_buffer_writes.py | 20 + .../shared/test_shared_column_check.py | 461 ++++++++++++++++++ tools/_legacy/build_us_acs_multispine_base.py | 1 + tools/build_us_acs_local_release.py | 4 +- tools/build_us_fiscal_refresh_release.py | 1 + 17 files changed, 916 insertions(+), 21 deletions(-) create mode 100644 changelog.d/frame-shared-column-check.added.md create mode 100644 packages/microcosm-frame/src/microcosm/frame/shared_columns.py create mode 100644 packages/microcosm-frame/tests/engine_free/shared/test_shared_column_check.py 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..758477d608 --- /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, and checkpoint and output writers compare the digests first. A raw write that changed shared memory raises `SharedColumnChangedError`, naming each changed table and column, before anything is written. diff --git a/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py b/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py index 51f65d91c3..5201dc2bc6 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) 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/tests/engine_free/shared/test_frame_checkpoint.py b/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint.py index 43671c47f4..9a0a0b5031 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 @@ -23,9 +23,11 @@ LinkSpec, MassChange, MassChangeRecord, + SharedColumnChangedError, WeightKind, Weights, ) +from microcosm.frame import shared_columns as shared_columns_module def _checkpoint_frame() -> Frame: @@ -1096,3 +1098,39 @@ def test_adopted_frames_write_the_bytes_of_copied_frames( 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(buffer: np.ndarray) -> bytes: + hashed_lengths.append(len(buffer)) + return original_digest(buffer) + + 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/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 29f437d2b5..0b519b3596 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 @@ -30,7 +30,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, @@ -19702,3 +19708,24 @@ def went_on(*args, **kwargs): assert raised.value.reason == "command_not_found" assert builder._ACTIVE_EMITTER is None 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()) == [] 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 ccfda92e6b..3c66cbf1f5 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") @@ -3660,3 +3666,22 @@ 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: + source = _pool_frame() + shared = source.replace_tables() + np.add.at(source.table("person")["person_id"].to_numpy(), [0], 1) + + 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", "person_id"),) + assert list(tmp_path.iterdir()) == [] 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 c9ee52b9c3..0047bf60b7 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -25,7 +25,10 @@ :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`). +deep-copy when it is off (see :meth:`Frame._adopt`). Those operations record a +digest of each column they start sharing, and :meth:`Frame.check_shared_columns` +compares the digests so that a raw write into shared memory is found before +the frame is written (see :mod:`microcosm.frame.shared_columns`). """ import re @@ -38,6 +41,7 @@ import pandas as pd from microcosm.frame.schema import EntitySchema +from microcosm.frame.shared_columns import check_shared_columns, record_shared_columns from microcosm.frame.weights import ( MassChange, MassChangeRecord, @@ -160,7 +164,9 @@ 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. 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 @@ -248,6 +254,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. @@ -940,11 +962,11 @@ def _shallow_table_copies(self) -> dict[str, pd.DataFrame]: 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`. """ - return { - name: table.copy(deep=False) - for name, table in {**self._tables, **self._link_tables}.items() - } + 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( @@ -1004,10 +1026,8 @@ def replace_tables(self, /, **changed_tables: pd.DataFrame) -> "Frame": """ _require_dataframes(changed_tables) - tables = { - name: table.copy(deep=False) - for name, table in {**self._tables, **self._link_tables}.items() - } + tables = self._shallow_table_copies() + _record_columns_being_shared(changed_tables) tables.update( {name: table.copy(deep=False) for name, table in changed_tables.items()} ) @@ -1504,6 +1524,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: @@ -1518,6 +1543,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] @@ -1525,8 +1552,12 @@ def select(self, person_mask: np.ndarray | pd.Series) -> "Frame": existing.values[keep], kind=existing.kind ) strata = self._strata.loc[mask] + _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, with every person kept, they still share + # them; under copy-on-write, a table that kept every row still shares # the source's memory. return Frame._adopt( tables, @@ -1616,6 +1647,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..628c5b9e70 --- /dev/null +++ b/packages/microcosm-frame/src/microcosm/frame/shared_columns.py @@ -0,0 +1,238 @@ +"""Find raw writes into 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 column, +:func:`record_shared_columns` stores a SHA-256 digest of each array holding the +column's data. 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 +writers of checkpoints and outputs call it before writing. + +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 the table +to other memory, and so does a pandas write while the memory is shared, so none +of these trip the check. A pandas write into a single cell of memory no other +table refers to any more happens in place and is reported, because it changes +the recorded memory of a frame whose 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. +""" + +from __future__ import annotations + +import hashlib +import weakref +from collections.abc import Iterable, Iterator, Mapping +from functools import partial + +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] + + +class SharedColumnChangedError(RuntimeError): + """A column's shared memory changed without going through pandas. + + 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: memory shared between frames changed after " + f"sharing began, in {columns}. Something wrote into that memory " + "directly instead of through pandas, so every frame sharing it now " + "holds the changed values." + ) + + +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) -> tuple[np.ndarray, ...]: + """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 (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. + return (values._data, values._mask) + if isinstance(values, pd.Categorical): + return (values.codes,) + if isinstance(values, pd.arrays.StringArray): + return (values.to_numpy(),) + if isinstance(values, _DATETIME_LIKE_ARRAY_TYPES): + return (values.asi8,) + if isinstance(values, pd.arrays.SparseArray): + return (values.sp_values,) + return () + + +def _owner_of(buffer: np.ndarray) -> np.ndarray: + """The array at the root of ``buffer``'s chain of views.""" + + owner = buffer + while isinstance(owner.base, np.ndarray): + owner = owner.base + return owner + + +def _buffer_key(buffer: np.ndarray) -> _BufferKey: + return ( + buffer.__array_interface__["data"][0], + buffer.shape[0], + buffer.strides[0], + buffer.dtype.str, + ) + + +def _buffer_digest(buffer: np.ndarray) -> bytes: + """Digest the bytes stored in ``buffer``. + + 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. + """ + + if buffer.dtype.hasobject: + contents = np.fromiter(map(id, buffer), dtype=np.uintp, count=len(buffer)) + elif buffer.flags.c_contiguous: + contents = buffer + else: + contents = buffer.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]]: + for table_name, table in tables.items(): + for column_name, column in table.items(): + yield str(table_name), str(column_name), column + if strata is not None: + yield "strata", "strata", strata + + +def _record_buffer(buffer: np.ndarray) -> None: + owner = _owner_of(buffer) + 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(buffer) + if key not in record.digests: + record.digests[key] = _buffer_digest(buffer) + + +def _buffer_changed(buffer: np.ndarray) -> bool: + record = _owner_records.get(id(_owner_of(buffer))) + if record is None: + return False + recorded_digest = record.digests.get(_buffer_key(buffer)) + return recorded_digest is not None and recorded_digest != _buffer_digest(buffer) + + +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 buffer in _column_buffers(column): + _record_buffer(buffer) + + +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(buffer) for buffer in _column_buffers(column)) + ] + if changed_columns: + raise SharedColumnChangedError(changed_columns) 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 d64415bec7..b1a550478d 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 @@ -138,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", + "cd4f137b0cd2", + ): ( + "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", + "cd4f137b0cd2", + ): ( + "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..e5a60f7ce3 --- /dev/null +++ b/packages/microcosm-frame/tests/engine_free/shared/test_shared_column_check.py @@ -0,0 +1,461 @@ +"""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, + 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]), + } + ) + 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) + + +_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), +} + + +@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) + + +@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"),) + + +def test_a_raw_write_into_shared_strata_is_named() -> None: + source = _source_frame() + result = _reweighted(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_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() + + +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() + + +def test_freed_memory_is_forgotten() -> None: + 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; try until it does, so + # the test exercises the reused address whenever the platform allows it. + arrays = [np.ones(size) for _ in range(32)] + reused = [ + array for array in arrays if array.__array_interface__["data"][0] == address + ] + replacement = reused[0] if reused else arrays[0] + + check_shared_columns({"person": pd.DataFrame({"income": replacement}, 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(buffer: np.ndarray) -> bytes: + hashed_lengths.append(len(buffer)) + return original(buffer) + + 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_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/tools/_legacy/build_us_acs_multispine_base.py b/tools/_legacy/build_us_acs_multispine_base.py index fd5e394855..259c619470 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 291713023c..7813d592df 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -1747,9 +1747,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 354912dc8c..8c4aa2ce76 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -3033,6 +3033,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(): From 7a226f6fd2d2b3acc03d671aaef82aa8fee86fc0 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:29:45 +0400 Subject: [PATCH 12/24] Close the shared-column check's review findings Compare recorded columns before the Frame constructor and the SPM stage make deep copies, so a changed column cannot pass through them unseen. Hash category values and sparse positions, and leave out values hidden by a nullable column's mask, which pandas itself overwrites. Stop recording tables passed to replace_tables, which callers may keep editing, and correct what the error and docs claim about in-place pandas writes. Co-Authored-By: Claude Opus 5.5 --- .../frame-shared-column-check.added.md | 2 +- .../build/us_runtime/spm_independence_role.py | 2 + .../shared/test_frame_checkpoint.py | 6 +- .../us/test_us_multispine_pool_h5_io.py | 8 +- .../us/test_us_spm_independence_role.py | 20 +++ .../src/microcosm/frame/bundle.py | 11 +- .../src/microcosm/frame/shared_columns.py | 156 +++++++++++------- .../shared/test_shared_buffer_writes.py | 4 +- .../shared/test_shared_column_check.py | 148 ++++++++++++++++- 9 files changed, 277 insertions(+), 80 deletions(-) diff --git a/changelog.d/frame-shared-column-check.added.md b/changelog.d/frame-shared-column-check.added.md index 758477d608..faee30cf0a 100644 --- a/changelog.d/frame-shared-column-check.added.md +++ b/changelog.d/frame-shared-column-check.added.md @@ -1 +1 @@ -Every build now checks columns that frames share. Frame operations record a SHA-256 digest of each column when they start sharing it, and checkpoint and output writers compare the digests first. A raw write that changed shared memory raises `SharedColumnChangedError`, naming each changed table and column, before anything is written. +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. 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 9a0a0b5031..84d0ec5616 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 @@ -1120,9 +1120,9 @@ def test_loading_hashes_nothing_until_a_loaded_column_is_shared( hashed_lengths: list[int] = [] original_digest = shared_columns_module._buffer_digest - def counting_digest(buffer: np.ndarray) -> bytes: - hashed_lengths.append(len(buffer)) - return original_digest(buffer) + 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) 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 3c66cbf1f5..a4843f5267 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 @@ -3671,9 +3671,11 @@ def test_legacy_stacked_manifest_refuses_h5_location_rule_attrs( def test_nullable_h5_writer_refuses_a_frame_whose_shared_column_changed( tmp_path: Path, ) -> None: - source = _pool_frame() + # 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.add.at(source.table("person")["person_id"].to_numpy(), [0], 1) + np.asarray(source.table("person")["PERIDNUM"].array)[0] = "changed" with pytest.raises(SharedColumnChangedError) as raised: write_nullable_us_h5( @@ -3683,5 +3685,5 @@ def test_nullable_h5_writer_refuses_a_frame_whose_shared_column_changed( artifact_kind=LEGACY_NULLABLE_STAGING_ARTIFACT_KIND, ) - assert raised.value.changed_columns == (("person", "person_id"),) + assert raised.value.changed_columns == (("person", "PERIDNUM"),) assert list(tmp_path.iterdir()) == [] 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-frame/src/microcosm/frame/bundle.py b/packages/microcosm-frame/src/microcosm/frame/bundle.py index 0047bf60b7..2d5b46ac55 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -26,9 +26,10 @@ :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 they start sharing, and :meth:`Frame.check_shared_columns` -compares the digests so that a raw write into shared memory is found before -the frame is written (see :mod:`microcosm.frame.shared_columns`). +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 @@ -119,6 +120,9 @@ 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. + if isinstance(tables, Mapping): + check_shared_columns(tables, strata=strata) self._assemble( tables, schema, @@ -1027,7 +1031,6 @@ def replace_tables(self, /, **changed_tables: pd.DataFrame) -> "Frame": _require_dataframes(changed_tables) tables = self._shallow_table_copies() - _record_columns_being_shared(changed_tables) tables.update( {name: table.copy(deep=False) for name, table in changed_tables.items()} ) diff --git a/packages/microcosm-frame/src/microcosm/frame/shared_columns.py b/packages/microcosm-frame/src/microcosm/frame/shared_columns.py index 628c5b9e70..e1872456ab 100644 --- a/packages/microcosm-frame/src/microcosm/frame/shared_columns.py +++ b/packages/microcosm-frame/src/microcosm/frame/shared_columns.py @@ -1,4 +1,4 @@ -"""Find raw writes into column memory that frames share. +"""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 @@ -7,26 +7,32 @@ 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 column, -:func:`record_shared_columns` stores a SHA-256 digest of each array holding the -column's data. 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. +**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 -writers of checkpoints and outputs call it before writing. +:class:`~microcosm.frame.bundle.Frame` constructor, ``engine_tables`` and the +writers of checkpoints and outputs call it before copying or writing. 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 the table -to other memory, and so does a pandas write while the memory is shared, so none -of these trip the check. A pandas write into a single cell of memory no other -table refers to any more happens in place and is reported, because it changes -the recorded memory of a frame whose 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. +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. """ from __future__ import annotations @@ -35,6 +41,7 @@ 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 @@ -50,11 +57,11 @@ pd.arrays.TimedeltaArray, ) -_BufferKey = tuple[int, int, int, str] +_BufferKey = tuple[int, int, int, str, int] class SharedColumnChangedError(RuntimeError): - """A column's shared memory changed without going through pandas. + """Memory that frames shared was changed in place. Attributes: changed_columns: ``(table, column)`` pairs, in table and column order. @@ -70,13 +77,27 @@ def __str__(self) -> str: for table, column in self.changed_columns ) return ( - "Refusing to continue: memory shared between frames changed after " - f"sharing began, in {columns}. Something wrote into that memory " - "directly instead of through pandas, so every frame sharing it now " - "holds the changed values." + "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.""" @@ -103,94 +124,113 @@ def _tracked_owner_count() -> int: return len(_owner_records) -def _column_buffers(column: pd.Series) -> tuple[np.ndarray, ...]: +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 (column.to_numpy(),) + 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. - return (values._data, values._mask) + mask = values._mask + return (_StoredArray(values._data, mask), _StoredArray(mask)) if isinstance(values, pd.Categorical): - return (values.codes,) + return (_StoredArray(values.codes), *_column_buffers(values.categories)) if isinstance(values, pd.arrays.StringArray): - return (values.to_numpy(),) + return (_StoredArray(values.to_numpy()),) if isinstance(values, _DATETIME_LIKE_ARRAY_TYPES): - return (values.asi8,) + return (_StoredArray(values.asi8),) if isinstance(values, pd.arrays.SparseArray): - return (values.sp_values,) + return ( + _StoredArray(values.sp_values), + _StoredArray(values.sp_index.to_int_index().indices), + ) return () -def _owner_of(buffer: np.ndarray) -> np.ndarray: - """The array at the root of ``buffer``'s chain of views.""" +def _owner_of(array: np.ndarray) -> np.ndarray: + """The array at the root of ``array``'s chain of views.""" - owner = buffer + owner = array while isinstance(owner.base, np.ndarray): owner = owner.base return owner -def _buffer_key(buffer: np.ndarray) -> _BufferKey: +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 ( - buffer.__array_interface__["data"][0], - buffer.shape[0], - buffer.strides[0], - buffer.dtype.str, + _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(buffer: np.ndarray) -> bytes: - """Digest the bytes stored in ``buffer``. +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. """ - if buffer.dtype.hasobject: - contents = np.fromiter(map(id, buffer), dtype=np.uintp, count=len(buffer)) - elif buffer.flags.c_contiguous: - contents = buffer + 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 = buffer.copy(order="C") + 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(): - for column_name, column in table.items(): - yield str(table_name), str(column_name), column - if strata is not None: + 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(buffer: np.ndarray) -> None: - owner = _owner_of(buffer) +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(buffer) + key = _buffer_key(stored) if key not in record.digests: - record.digests[key] = _buffer_digest(buffer) + record.digests[key] = _buffer_digest(stored) -def _buffer_changed(buffer: np.ndarray) -> bool: - record = _owner_records.get(id(_owner_of(buffer))) +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(buffer)) - return recorded_digest is not None and recorded_digest != _buffer_digest(buffer) + recorded_digest = record.digests.get(_buffer_key(stored)) + return recorded_digest is not None and recorded_digest != _buffer_digest(stored) def record_shared_columns( @@ -207,8 +247,8 @@ def record_shared_columns( """ for _table_name, _column_name, column in _named_columns(tables, strata): - for buffer in _column_buffers(column): - _record_buffer(buffer) + for stored in _column_buffers(column): + _record_buffer(stored) def check_shared_columns( @@ -232,7 +272,7 @@ def check_shared_columns( changed_columns = [ (table_name, column_name) for table_name, column_name, column in _named_columns(tables, strata) - if any(_buffer_changed(buffer) for buffer in _column_buffers(column)) + if any(_buffer_changed(stored) for stored in _column_buffers(column)) ] if changed_columns: raise SharedColumnChangedError(changed_columns) 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 b1a550478d..48a57e6795 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 @@ -143,7 +143,7 @@ "_column_buffers", "pandas-private-attribute", "values._data", - "cd4f137b0cd2", + "d2bfbc85dac5", ): ( "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." @@ -153,7 +153,7 @@ "_column_buffers", "pandas-private-attribute", "values._mask", - "cd4f137b0cd2", + "d2bfbc85dac5", ): ( "Read only, so the shared-column check can hash a nullable column's " "missing-value mask. pandas exposes only a copy of it." 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 index e5a60f7ce3..21d3feb332 100644 --- 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 @@ -19,6 +19,7 @@ from microcosm.frame import ( EntitySchema, Frame, + LinkSpec, MassChange, SharedColumnChangedError, WeightKind, @@ -57,6 +58,7 @@ def _source_frame() -> Frame: "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]), } ) household = pd.DataFrame( @@ -162,6 +164,18 @@ 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 + + _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), @@ -177,6 +191,9 @@ def _add_at_into_sparse_values(column: pd.Series) -> None: "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), } @@ -230,9 +247,10 @@ def test_a_group_table_kept_whole_by_a_partial_select_is_checked() -> None: assert raised.value.changed_columns == (("household", "rent"),) -def test_a_raw_write_into_shared_strata_is_named() -> None: +@pytest.mark.parametrize("operation", sorted(_SHARING_OPERATIONS)) +def test_a_raw_write_into_shared_strata_is_named(operation: str) -> None: source = _source_frame() - result = _reweighted(source) + result = _SHARING_OPERATIONS[operation](source) np.asarray(source.strata.array)[1] = "changed" @@ -241,6 +259,65 @@ def test_a_raw_write_into_shared_strata_is_named() -> None: 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): + Frame( + {"person": "not a table", "household": source.table("household")}, + source.schema, + {"household": source.weights_for("household")}, + ) + + def test_every_changed_column_is_named_at_once() -> None: source = _source_frame() result = _reweighted(source) @@ -323,7 +400,59 @@ def test_replacing_a_column_after_its_sharer_is_gone_passes_the_check() -> None: 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}) @@ -345,15 +474,16 @@ def test_a_new_array_at_a_freed_address_is_not_compared() -> None: del table gc.collect() - # The allocator usually hands the same block back; try until it does, so - # the test exercises the reused address whenever the platform allows it. + # 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 ] - replacement = reused[0] if reused else arrays[0] + if not reused: + pytest.skip("the allocator did not reuse the freed address") - check_shared_columns({"person": pd.DataFrame({"income": replacement}, copy=False)}) + check_shared_columns({"person": pd.DataFrame({"income": reused[0]}, copy=False)}) def _counted_digests(monkeypatch: pytest.MonkeyPatch) -> list[int]: @@ -362,9 +492,9 @@ def _counted_digests(monkeypatch: pytest.MonkeyPatch) -> list[int]: hashed_lengths: list[int] = [] original = shared_columns_module._buffer_digest - def counting_digest(buffer: np.ndarray) -> bytes: - hashed_lengths.append(len(buffer)) - return original(buffer) + 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 From 5a6e9b17f515a58d0fbac45e3cf974d09db82f47 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:39:24 +0400 Subject: [PATCH 13/24] Check the UK release frame and cover the remaining storage forms Compare shared columns at the start of uk_release_export_frame, whose copies would otherwise hide a change. Hash block-format sparse positions, and tighten the tests of nullable masks and of the constructor's error reporting. Co-Authored-By: Claude Opus 5.5 --- .../build/uk_runtime/national_frame.py | 3 +- .../uk/test_uk_release_identifiers.py | 15 +++++- .../src/microcosm/frame/bundle.py | 7 +-- .../src/microcosm/frame/shared_columns.py | 9 ++-- .../shared/test_shared_buffer_writes.py | 4 +- .../shared/test_shared_column_check.py | 50 ++++++++++++++++++- 6 files changed, 76 insertions(+), 12 deletions(-) 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 1c39b2fcbc..8669dc5d19 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 @@ -1031,11 +1031,12 @@ def uk_release_export_frame(frame: Frame) -> Frame: carries none. The identifiers leave inside the 32-bit range the engine stores, with the build identifiers beside them (microcosm#1194, :func:`uk_release_identifier_tables`). A frame that already left passes - unchanged. + 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/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-frame/src/microcosm/frame/bundle.py b/packages/microcosm-frame/src/microcosm/frame/bundle.py index 2d5b46ac55..6e0e1003e1 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -121,8 +121,7 @@ def __init__( metadata: Mapping[str, Any] | None = None, ) -> None: # The deep copies made below could not show an earlier raw write. - if isinstance(tables, Mapping): - check_shared_columns(tables, strata=strata) + check_shared_columns(tables, strata=strata) self._assemble( tables, schema, @@ -1010,7 +1009,9 @@ 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. Weights, strata, the mass log and metadata are carried unchanged. When copy-on-write is off, every table is deep-copied instead. diff --git a/packages/microcosm-frame/src/microcosm/frame/shared_columns.py b/packages/microcosm-frame/src/microcosm/frame/shared_columns.py index e1872456ab..461ee8aab1 100644 --- a/packages/microcosm-frame/src/microcosm/frame/shared_columns.py +++ b/packages/microcosm-frame/src/microcosm/frame/shared_columns.py @@ -146,10 +146,13 @@ def _column_buffers(column: pd.Series | pd.Index) -> tuple[_StoredArray, ...]: if isinstance(values, _DATETIME_LIKE_ARRAY_TYPES): return (_StoredArray(values.asi8),) if isinstance(values, pd.arrays.SparseArray): - return ( - _StoredArray(values.sp_values), - _StoredArray(values.sp_index.to_int_index().indices), + 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 () 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 48a57e6795..66465c0071 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 @@ -143,7 +143,7 @@ "_column_buffers", "pandas-private-attribute", "values._data", - "d2bfbc85dac5", + "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." @@ -153,7 +153,7 @@ "_column_buffers", "pandas-private-attribute", "values._mask", - "d2bfbc85dac5", + "64ca7d79dc01", ): ( "Read only, so the shared-column check can hash a nullable column's " "missing-value mask. pandas exposes only a copy of it." 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 index 21d3feb332..cfce2a5c44 100644 --- 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 @@ -59,6 +59,7 @@ def _source_frame() -> Frame: "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( @@ -176,6 +177,14 @@ 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 + + _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), @@ -194,6 +203,8 @@ def _mark_a_value_missing(column: pd.Series) -> None: "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), } @@ -310,14 +321,49 @@ def test_the_constructor_still_reports_a_table_that_is_not_a_dataframe() -> None source = _source_frame() _reweighted(source) - with pytest.raises(AttributeError): + 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( - {"person": "not a table", "household": source.table("household")}, + {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) From c30b3c876a0815713e7a0066b4f60f5ecc96b540 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:07:34 +0400 Subject: [PATCH 14/24] Re-pin the calibrate and simulate parity kernels for the column check Co-Authored-By: Claude Opus 5.5 --- .../tests/fixtures/parity/kernels/calibrate/pins.json | 2 +- .../tests/fixtures/parity/kernels/simulate/pins.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 030db8486d..e6f4f4c768 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":"eea4c43ca2ef64acc68012287d5e353f0a7d8d305939c4b484bcd0129c435697","kernel":"calibrate.adam@1","node":"calibrate","node_key":"99ccbc158a1b78ba6f5d7201a09a8f63407448fc22eb6e3f7f200feeb882345a","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"99ccbc158a1b78ba6f5d7201a09a8f63407448fc22eb6e3f7f200feeb882345a"}},"seed":0} +{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","scipy":"1.17.1","torch":"2.12.0"},"implementation_hash":"ce5f57ee28d96cc3f224f245b5d7ad8b34d71222db13780d5a5f59670dfc0e9e","kernel":"calibrate.adam@1","node":"calibrate","node_key":"8b16d040cc03f76d385442a791398bef5c1c2ebba3dd37a485928359251edd42","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"8b16d040cc03f76d385442a791398bef5c1c2ebba3dd37a485928359251edd42"}},"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 6ced4ecdcd..e9391cec48 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":"910fadde4b27d7cb8925720dbbea15920b70a78a315e8d40b7cb020e51423b73","kernel":"simulate.rules@1","node":"simulate","node_key":"99188b86e5eaf8cc7ca59f91bd9d4373c2aec03e2a3a236b62dcf79cd06eee9a","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"99188b86e5eaf8cc7ca59f91bd9d4373c2aec03e2a3a236b62dcf79cd06eee9a"}},"seed":null} +{"dependencies":{},"implementation_hash":"1334d48c4a9579c48651f44055f8051d985e5038af3e7a70eec89dff6d259664","kernel":"simulate.rules@1","node":"simulate","node_key":"52a4a1eb9c12917700e6443d392247092579c99600c4c1ab7f069b47a9e1e981","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"52a4a1eb9c12917700e6443d392247092579c99600c4c1ab7f069b47a9e1e981"}},"seed":null} From 6a19fe6d9d9dad48d47a0133c15df9a4c9c80e9b Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:24:09 +0400 Subject: [PATCH 15/24] Test that sparse block lengths are checked Co-Authored-By: Claude Opus 5.5 --- .../tests/engine_free/shared/test_shared_column_check.py | 5 +++++ 1 file changed, 5 insertions(+) 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 index cfce2a5c44..2f3e4c0b76 100644 --- 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 @@ -185,6 +185,10 @@ 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), @@ -205,6 +209,7 @@ def _move_a_sparse_block(column: pd.Series) -> None: "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), } From c147c1b3734b5b995b88c8ca7a27142853e45a8c Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:17:11 +0400 Subject: [PATCH 16/24] List microcosm.frame.shared_columns among the modules the transport bindings reach microcosm.frame.bundle imports the shared-column check, so the module count in test_the_batterys_binding_identity_adds_only_the_leaf_and_its_imports grows by one. engine-free (3.13) and (3.14) failed on this. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_transport_evidence_kernels.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py b/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py index 2a89ce08c5..9d5e8d350a 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" From 5fba262d3e8a5ce54c79e9ce0a0bd0afcebb5c4a Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:06:00 +0400 Subject: [PATCH 17/24] Record the frame bundle's import of the shared-column check for the UK target kernels microcosm.frame.bundle now imports microcosm.frame.shared_columns, so the walk from the UK target kernels' hashed modules meets that edge. engine-free (3.13) failed on test_every_import_a_target_kernel_reaches_is_hashed_or_recorded. The check changes no column, so no target value comes from it; the edge is recorded beside bundle's other imports, as #931 did for receipt_counts. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/uk/test_uk_target_compile_modules.py | 9 +++++++++ 1 file changed, 9 insertions(+) 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, From 26493412b9cbde8a50e94685c6f46b9fcc6b8e93 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:28:28 +0400 Subject: [PATCH 18/24] Change the UK export test's population through with_columns, not a .loc write describe_uk_export shares the person columns with the frame uk_dataset_year_frame returns (with_weights now shares unchanged columns). Once that frame is freed, the test's .loc write lands in the recorded memory and the shared-column check refuses it before the descriptor comparison runs, so test_export_refuses_population_changed_after_descriptor failed on engine-free (3.14) and fails locally on 3.13 and 3.14. Frame tables are read-only; the test now builds the changed population as a new frame and still expects the descriptor refusal. Co-Authored-By: Claude Opus 5.5 --- .../tests/engine_free/uk/test_uk_graph_terminal.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) 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): From 3b42af8565cfb6173b80eceb4dc5332a0b3f7b20 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:07:17 +0400 Subject: [PATCH 19/24] Expect the transport kernels to hash or record the shared-column check (red) microcosm.frame.bundle and microcosm.frame.materialize now import microcosm.frame.shared_columns, and engine-free (3.13) and (3.14) failed on test_every_import_a_compile_kernel_reaches_is_hashed_or_recorded. The record expects takeup.compare, takeup.gap and transport.create to hash the module beside the bundle, as they hash its schema and weights, and records the edges for targets.compile and transport.quantile_map@1 and @2, which leave the bundle's imports unhashed. Co-Authored-By: Claude Opus 5.5 --- .../shared/test_transport_compile_modules.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) 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, From d9e786d48926d2945ea3b3249a14981c797623eb Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:08:32 +0400 Subject: [PATCH 20/24] Hash the shared-column check beside the frame bundle in the transport kernels target_kernels._MATRIX_MODULES (targets.problem, takeup.compare, takeup.gap) and transport.create's hash list name microcosm.frame.bundle with its schema and weights. The bundle now calls the shared-column check when it builds and copies frames, so these lists hash microcosm.frame.shared_columns too. Their hashes already change in this PR because bundle.py changed. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/build/transport/population_kernels.py | 2 ++ .../src/microcosm/build/transport/target_kernels.py | 2 ++ 2 files changed, 4 insertions(+) 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 f8d24121fd..1f42f2435e 100644 --- a/packages/microcosm-build/src/microcosm/build/transport/population_kernels.py +++ b/packages/microcosm-build/src/microcosm/build/transport/population_kernels.py @@ -29,6 +29,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 @@ -157,6 +158,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, ) From 070b919e70d36c8c490ee65f059f3fa8eba90ef4 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:54:50 +0400 Subject: [PATCH 21/24] Call Frame.adopt in the tests and expect no private _adopt (red) The review of #1683 asked for Frame._adopt to be documented as private or made public, since load_frame_checkpoint in microcosm-build calls it. It becomes public as Frame.adopt. Co-Authored-By: Claude Opus 5.5 --- .../shared/test_frame_checkpoint.py | 6 ++--- .../shared/test_frame_operation_sharing.py | 12 ++++----- .../shared/test_frame_table_sharing.py | 26 +++++++++++-------- .../shared/test_shared_buffer_writes.py | 2 +- 4 files changed, 25 insertions(+), 21 deletions(-) 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 84d0ec5616..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 @@ -764,7 +764,7 @@ def test_loader_keeps_the_decoded_columns_without_copying( ) -> 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 + 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. """ @@ -842,7 +842,7 @@ def _doubled_household_weights(frame: Frame) -> Frame: ) -#: Operations that build their result through ``Frame._adopt``. +#: Operations that build their result through ``Frame.adopt``. _ADOPTING_OPERATIONS = { "with_weights": _doubled_household_weights, "place person to household": lambda frame: frame.place( @@ -902,7 +902,7 @@ def _checkpoint_content_sha256(path: Path) -> str: #: 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``. +#: ``place``, ``select`` and the loader moved to ``Frame.adopt``. _COPYING_IMPLEMENTATION_CONTENT_SHA256: dict[tuple[str, str, str], str] = { ( "fixture", 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 index 5c430e54ac..7fb4bba328 100644 --- 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 @@ -1,12 +1,12 @@ -"""``with_weights``, ``place`` and ``select`` build their result through ``_adopt``. +"""``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 +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), ``_adopt`` deep-copies instead; these tests replace the +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. """ @@ -130,7 +130,7 @@ def copy_on_write_on() -> Iterator[None]: @pytest.fixture def copy_on_write_off(monkeypatch: pytest.MonkeyPatch) -> None: - """Make ``Frame._adopt`` see pandas copy-on-write as off.""" + """Make ``Frame.adopt`` see pandas copy-on-write as off.""" monkeypatch.setattr(bundle_module, "_pandas_copy_on_write", lambda: False) @@ -340,7 +340,7 @@ def test_a_pandas_write_to_the_source_leaves_the_result_unchanged( _assert_matches_snapshot(result, before) -# Selecting a strict subset of persons copies their rows whatever ``_adopt`` +# 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"] @@ -376,7 +376,7 @@ def _fragmented_frame() -> Frame: ) fragmented[name] = pd.DataFrame(columns, index=table.index, copy=False) tables.update(fragmented) - return Frame._adopt(tables, _UNLINKED_SCHEMA, _weights(), _strata()) + return Frame.adopt(tables, _UNLINKED_SCHEMA, _weights(), _strata()) @pytest.mark.parametrize( 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 66465c0071..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 @@ -3,7 +3,7 @@ :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 +(: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 From 9027c2f99a7d0d08ce96f0f19cb55cbcd6122ccc Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:04:39 +0400 Subject: [PATCH 22/24] Make Frame.adopt public load_frame_checkpoint in microcosm-build builds its frame through it, so the method is public API rather than a private one called from another package. Its docstring now says that adopt records no columns for the shared-column check: the frame operations record the columns they share before calling it. Every reference, including both changelog fragments, moves to the new name. bundle.py's bytes change, so the calibrate and simulate parity kernels are re-pinned with tools/graph_parity_repin.py under Python 3.14. Co-Authored-By: Claude Opus 5.5 --- .../frame-adopt-replace-tables.added.md | 2 +- .../frame-operations-share-columns.changed.md | 2 +- .../src/microcosm/build/frame_checkpoint.py | 4 +-- .../src/microcosm/frame/bundle.py | 31 ++++++++++--------- .../parity/kernels/calibrate/pins.json | 2 +- .../parity/kernels/simulate/pins.json | 2 +- 6 files changed, 23 insertions(+), 20 deletions(-) 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 index 3aea9cb678..18f7f0171a 100644 --- a/changelog.d/frame-operations-share-columns.changed.md +++ b/changelog.d/frame-operations-share-columns.changed.md @@ -1 +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.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/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py b/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py index 5201dc2bc6..44c2f42c29 100644 --- a/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py +++ b/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py @@ -182,7 +182,7 @@ def load_frame_checkpoint( """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 + 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 @@ -316,7 +316,7 @@ def load_frame_checkpoint( # 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( + frame = Frame.adopt( tables, schema, weights, diff --git a/packages/microcosm-frame/src/microcosm/frame/bundle.py b/packages/microcosm-frame/src/microcosm/frame/bundle.py index fd502050c9..332dc2e194 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -25,7 +25,7 @@ :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 +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 @@ -133,7 +133,7 @@ def __init__( ) @classmethod - def _adopt( + def adopt( cls, tables: Mapping[str, pd.DataFrame], schema: EntitySchema, @@ -169,7 +169,10 @@ def _adopt( column has no missing value, python-backed strings, and sparse columns without gaps. :meth:`check_shared_columns` finds such a write afterwards, for columns a frame operation recorded when it started - sharing them. + 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 @@ -232,9 +235,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 @@ -869,7 +872,7 @@ def with_weights( Returns: A new validated bundle. Its tables are built through - :meth:`_adopt`, so under pandas copy-on-write they share every + :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. @@ -887,7 +890,7 @@ def with_weights( 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( + return Frame.adopt( self._shallow_table_copies(), self._schema, new_weights, @@ -962,7 +965,7 @@ 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 + 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`. @@ -1009,7 +1012,7 @@ 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`). A replacement's columns are recorded + protected (see :meth:`adopt`). A replacement's columns are recorded for :meth:`check_shared_columns` only once a later operation shares them. Weights, strata, the mass log and metadata are carried unchanged. When copy-on-write is off, every @@ -1035,7 +1038,7 @@ def replace_tables(self, /, **changed_tables: pd.DataFrame) -> "Frame": 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, @@ -1170,7 +1173,7 @@ def place( Returns: A new validated bundle with the column on ``entity``, built - through :meth:`_adopt`: under pandas copy-on-write it shares the + 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. @@ -1228,7 +1231,7 @@ def place( warnings.simplefilter("ignore", pd.errors.PerformanceWarning) destination[column] = placed tables[owner] = self._tables[owner].drop(columns=[column]) - return Frame._adopt( + return Frame.adopt( tables, self._schema, dict(self._weights), @@ -1491,7 +1494,7 @@ 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, built through :meth:`_adopt`: under pandas copy-on-write + strata, built through :meth:`adopt`: under pandas copy-on-write the selected tables are not copied a second time. Raises: @@ -1563,7 +1566,7 @@ def select(self, person_mask: np.ndarray | pd.Series) -> "Frame": # 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( + return Frame.adopt( tables, self._schema, weights, 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 9bf8c3f7ca..10d34a55a4 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":"72912ca06532579c61a9d6135ba8f59618b2d4672b23b5aa8c6c306d71002f97","kernel":"calibrate.adam@1","node":"calibrate","node_key":"206ccfc312d0501b5fea3e21905fa0b1105f79bd4330ce3bb90bb104e2c81956","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"206ccfc312d0501b5fea3e21905fa0b1105f79bd4330ce3bb90bb104e2c81956"}},"seed":0} +{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","scipy":"1.17.1","torch":"2.12.0"},"implementation_hash":"53d5af1faafce650b3d410b2673fda862477cada5094aeecd5e0e2c41f7a26a0","kernel":"calibrate.adam@1","node":"calibrate","node_key":"706a24b58cefd080b81a28b53d6bf697801b015e75b9fae36b5048f3c767410f","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"706a24b58cefd080b81a28b53d6bf697801b015e75b9fae36b5048f3c767410f"}},"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 4d8156b879..c4e6357a41 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":"fd6219b568a58f47ccd119d980ea382ee1bb0f072a581a951d3f4f1eeedc993c","kernel":"simulate.rules@1","node":"simulate","node_key":"412be190d16466a762bb37919b67f0b9a3ad9b8cfaafecc28a6bf1debcfa4d2a","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"412be190d16466a762bb37919b67f0b9a3ad9b8cfaafecc28a6bf1debcfa4d2a"}},"seed":null} +{"dependencies":{},"implementation_hash":"3b6f2e532a32ed8ddd2ec9c4242956c98ee11a8a41af022c78bae67986a9a683","kernel":"simulate.rules@1","node":"simulate","node_key":"95651cd7b0de526d7842334f7a159fd2572b9eb83445589fe1c2beb7a144f027","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"95651cd7b0de526d7842334f7a159fd2572b9eb83445589fe1c2beb7a144f027"}},"seed":null} From 8d116142809db154e881f308deb51441c358df0a Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:47:35 +0400 Subject: [PATCH 23/24] Expect replace_tables to check the shared columns it drops or replaces (red) The #1683 review found that a raw write into a shared column passes every later check once a step drops the column: a new column derived from it carries the changed value, and no checked frame still holds the evidence. These tests expect replace_tables, and with_columns through it, to compare each recorded column the new frame no longer holds before building it, for every raw write the check covers, and to hash only those columns. Co-Authored-By: Claude Opus 5.5 --- .../shared/test_shared_column_check.py | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) 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 index 2f3e4c0b76..587cd52c18 100644 --- 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 @@ -229,6 +229,75 @@ def test_the_check_names_a_column_changed_by_a_raw_write(raw_write: str) -> None 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() @@ -436,6 +505,8 @@ def test_writes_made_through_pandas_do_not_trip_the_check(pandas_write: str) -> 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: @@ -568,6 +639,18 @@ def test_a_column_is_hashed_once_however_many_frames_share_it( 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: From 5dbc01f953786d0836f03de98aff85fad1711a0e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:57:47 +0400 Subject: [PATCH 24/24] Check the shared columns replace_tables and with_columns drop or replace A raw write into a shared column passed every later check once a step dropped the column, while a column derived from it carried the changed value on (#1683 review). check_columns_leaving compares each recorded column of a replaced table whose arrays the replacement no longer stores, and replace_tables, which with_columns ends in, calls it before sharing anything. Only leaving columns are hashed. The shared_columns docstring now lists the remaining case: a column that leaves every checked frame outside these two operations. bundle.py changes, so the calibrate and simulate parity kernels are re-pinned under Python 3.14. Co-Authored-By: Claude Opus 5.5 --- .../frame-shared-column-check.added.md | 2 +- .../src/microcosm/frame/bundle.py | 17 +++++- .../src/microcosm/frame/shared_columns.py | 56 ++++++++++++++++++- .../parity/kernels/calibrate/pins.json | 2 +- .../parity/kernels/simulate/pins.json | 2 +- 5 files changed, 71 insertions(+), 8 deletions(-) diff --git a/changelog.d/frame-shared-column-check.added.md b/changelog.d/frame-shared-column-check.added.md index faee30cf0a..faa13479ce 100644 --- a/changelog.d/frame-shared-column-check.added.md +++ b/changelog.d/frame-shared-column-check.added.md @@ -1 +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. +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/packages/microcosm-frame/src/microcosm/frame/bundle.py b/packages/microcosm-frame/src/microcosm/frame/bundle.py index 332dc2e194..0a726bac5e 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -42,7 +42,11 @@ import pandas as pd from microcosm.frame.schema import EntitySchema -from microcosm.frame.shared_columns import check_shared_columns, record_shared_columns +from microcosm.frame.shared_columns import ( + check_columns_leaving, + check_shared_columns, + record_shared_columns, +) from microcosm.frame.weights import ( MassChange, MassChangeRecord, @@ -1014,7 +1018,9 @@ def replace_tables(self, /, **changed_tables: pd.DataFrame) -> "Frame": DataFrames it passed. Raw writes into the shared memory are not protected (see :meth:`adopt`). A replacement's columns are recorded for :meth:`check_shared_columns` only once a later operation shares - them. Weights, strata, the mass log and + 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. @@ -1031,9 +1037,12 @@ 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) + 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()} @@ -1057,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). @@ -1075,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) diff --git a/packages/microcosm-frame/src/microcosm/frame/shared_columns.py b/packages/microcosm-frame/src/microcosm/frame/shared_columns.py index 461ee8aab1..481dc12dee 100644 --- a/packages/microcosm-frame/src/microcosm/frame/shared_columns.py +++ b/packages/microcosm-frame/src/microcosm/frame/shared_columns.py @@ -17,7 +17,12 @@ **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. +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 @@ -32,7 +37,11 @@ - 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. + 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 @@ -279,3 +288,46 @@ def check_shared_columns( ] 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-graph/tests/fixtures/parity/kernels/calibrate/pins.json b/packages/microcosm-graph/tests/fixtures/parity/kernels/calibrate/pins.json index 10d34a55a4..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":"53d5af1faafce650b3d410b2673fda862477cada5094aeecd5e0e2c41f7a26a0","kernel":"calibrate.adam@1","node":"calibrate","node_key":"706a24b58cefd080b81a28b53d6bf697801b015e75b9fae36b5048f3c767410f","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"706a24b58cefd080b81a28b53d6bf697801b015e75b9fae36b5048f3c767410f"}},"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 c4e6357a41..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":"3b6f2e532a32ed8ddd2ec9c4242956c98ee11a8a41af022c78bae67986a9a683","kernel":"simulate.rules@1","node":"simulate","node_key":"95651cd7b0de526d7842334f7a159fd2572b9eb83445589fe1c2beb7a144f027","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"95651cd7b0de526d7842334f7a159fd2572b9eb83445589fe1c2beb7a144f027"}},"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}