Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
5461375
Build with_weights, place, select and the checkpoint loader through F…
anth-volk Nov 17, 2026
cbbeb2e
Address review: pin checkpoint content, tighten tests and docs
anth-volk Nov 17, 2026
414c27f
Check the place source table's sharing and correct result docs
anth-volk Nov 17, 2026
ca2d8fb
Guard sharing tests for pandas 2 and record the loaded-table layout
anth-volk Nov 17, 2026
1fe17cb
Check strata in the sharing tests and qualify select's no-copy claim
anth-volk Nov 17, 2026
0aac10f
Correct the annual static-aging memory account
anth-volk Nov 17, 2026
02cda02
Restore bundle.py's warnings import lost in the rebase, and re-pin
anth-volk Nov 17, 2026
cc5c7af
Re-pin the calibrate and simulate parity kernels
anth-volk Nov 17, 2026
526c986
Re-pin the US spec-engine digests for the solve.py change
anth-volk Nov 18, 2026
2177236
Add the changelog fragment and name the new sharing operations
anth-volk Nov 18, 2026
5f9a161
Check shared frame columns before every checkpoint and output write
anth-volk Nov 18, 2026
7a226f6
Close the shared-column check's review findings
anth-volk Nov 18, 2026
5a6e9b1
Check the UK release frame and cover the remaining storage forms
anth-volk Nov 18, 2026
c30b3c8
Re-pin the calibrate and simulate parity kernels for the column check
anth-volk Nov 19, 2026
6a19fe6
Test that sparse block lengths are checked
anth-volk Nov 19, 2026
c722e9e
Merge PR 1666's changelog fragment and docstring reflow, and re-pin
anth-volk Nov 19, 2026
00c3a99
Merge main and regenerate the US spec-engine digests
anth-volk Nov 19, 2026
faddba7
Merge main after #1666 merged
anth-volk Nov 19, 2026
c147c1b
List microcosm.frame.shared_columns among the modules the transport b…
anth-volk Nov 19, 2026
1ba3f23
Merge main after #1682 and regenerate the US spec-engine digests
anth-volk Nov 19, 2026
5fba262
Record the frame bundle's import of the shared-column check for the U…
anth-volk Nov 19, 2026
2649341
Change the UK export test's population through with_columns, not a .l…
anth-volk Nov 20, 2026
3b42af8
Expect the transport kernels to hash or record the shared-column chec…
anth-volk Nov 21, 2026
d9e786d
Hash the shared-column check beside the frame bundle in the transport…
anth-volk Nov 21, 2026
a217acb
Merge main after #1687
anth-volk Nov 24, 2026
62341fb
Merge main after #1667 and regenerate the US spec-engine digests
anth-volk Nov 24, 2026
070b919
Call Frame.adopt in the tests and expect no private _adopt (red)
anth-volk Nov 24, 2026
9027c2f
Make Frame.adopt public
anth-volk Nov 24, 2026
8d11614
Expect replace_tables to check the shared columns it drops or replace…
anth-volk Nov 24, 2026
5dbc01f
Check the shared columns replace_tables and with_columns drop or replace
anth-volk Nov 24, 2026
cc439d5
Merge main after #1684 and regenerate the US spec-engine digests
anth-volk Nov 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion changelog.d/frame-adopt-replace-tables.added.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions changelog.d/frame-operations-share-columns.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`Frame.with_weights`, `Frame.place`, `Frame.select` and `load_frame_checkpoint` no longer deep-copy every table. Under pandas copy-on-write, frames from the three `Frame` operations share the memory of unchanged columns with their source, and the loader keeps the columns it decoded without a second copy. `calibrate` gains `return_frame=False`, which runs the same weight checks and returns the weights and diagnostics with `frame=None`. `Frame.adopt(tables, schema, weights, ...)` is now public, so other packages can build a frame that takes ownership of tables it decoded or built, as `load_frame_checkpoint` does: it validates like the constructor and, under copy-on-write, stores the given DataFrames without copying them. The caller must not write to those DataFrames afterwards, and `adopt` records no columns for `Frame.check_shared_columns`.
1 change: 1 addition & 0 deletions changelog.d/frame-shared-column-check.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Every build now checks columns that frames share. Frame operations record a SHA-256 digest of each column when they start sharing it. The `Frame` constructor, `engine_tables`, and checkpoint and output writers compare the digests first, and raise `SharedColumnChangedError` naming each table and column whose shared memory was changed in place. `Frame.replace_tables` and `Frame.with_columns` also compare each recorded column they drop or replace before building the new frame, so a changed column cannot leave unreported while a column derived from it carries the change on.
16 changes: 8 additions & 8 deletions docs/evidence/spec-engine/us-f0-coverage.json
Original file line number Diff line number Diff line change
Expand Up @@ -1642,13 +1642,13 @@
"compiler_ir.node_slices"
],
"expected": {
"map_sha256": "530bdaf982c7ad2440db7b4b02f8de5843dac083c6e36c28385ce5d8bbb23e35",
"protocol_sha256": "f5cc748f1b9fbeaea54c18d9e2c1e6e74f2679c9cbf6cf7a09e7b548d2788d66"
"map_sha256": "1dda5e09b93e4acd51844bfbd62555adfc91d309e0f7647d64b959e0820d1d1e",
"protocol_sha256": "90d566bb670521cc79f42cba8afe14fe79330ac2c990858dbe8f7debe1466fa5"
},
"failures": [],
"observed": {
"map_sha256": "530bdaf982c7ad2440db7b4b02f8de5843dac083c6e36c28385ce5d8bbb23e35",
"protocol_sha256": "f5cc748f1b9fbeaea54c18d9e2c1e6e74f2679c9cbf6cf7a09e7b548d2788d66"
"map_sha256": "1dda5e09b93e4acd51844bfbd62555adfc91d309e0f7647d64b959e0820d1d1e",
"protocol_sha256": "90d566bb670521cc79f42cba8afe14fe79330ac2c990858dbe8f7debe1466fa5"
},
"status": "covered"
},
Expand All @@ -1663,7 +1663,7 @@
"compiler_ir.seed_stream_map"
],
"expected": {
"implementation_sha256": "f5cc748f1b9fbeaea54c18d9e2c1e6e74f2679c9cbf6cf7a09e7b548d2788d66",
"implementation_sha256": "90d566bb670521cc79f42cba8afe14fe79330ac2c990858dbe8f7debe1466fa5",
"protocol": "legacy-v1",
"streams": [
"build_model",
Expand All @@ -1684,7 +1684,7 @@
},
"failures": [],
"observed": {
"implementation_sha256": "f5cc748f1b9fbeaea54c18d9e2c1e6e74f2679c9cbf6cf7a09e7b548d2788d66",
"implementation_sha256": "90d566bb670521cc79f42cba8afe14fe79330ac2c990858dbe8f7debe1466fa5",
"protocol": "legacy-v1",
"streams": [
"build_model",
Expand Down Expand Up @@ -2585,7 +2585,7 @@
"country": "us",
"schema_id": "country_spec",
"schema_version": 1,
"spec_sha256": "067676ed540f9a6d7981ce5df546e81384cf0409446b04b4cbc637db5a43ea22"
"spec_sha256": "2e3093b6acc4926e80e96b080c3bfe2727baa22127ebfb9faf8a1ef05eda0f50"
}
},
"report_schema_version": 3,
Expand All @@ -2595,7 +2595,7 @@
"country": "us",
"schema_id": "country_spec",
"schema_version": 1,
"spec_sha256": "067676ed540f9a6d7981ce5df546e81384cf0409446b04b4cbc637db5a43ea22"
"spec_sha256": "2e3093b6acc4926e80e96b080c3bfe2727baa22127ebfb9faf8a1ef05eda0f50"
},
"status": "pass"
}
3 changes: 2 additions & 1 deletion docs/us-local-annual-projection.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 7 additions & 4 deletions docs/us-release-build-rule.md
Original file line number Diff line number Diff line change
Expand Up @@ -522,10 +522,13 @@ reform and does not replace this sweep.
(method, batch size, batch count, each stage's baseline keys and periods), and
`reform_coverage_smoke.json` records what the smoke scored under
`post_export_scoring`. Poverty rows stay record-only. Before the export write
the build frees the target frame and the calibration result's target tables:
`Frame.with_weights` copies every table, target columns included. Dense and
L0 results drop those frames; exact-k substitutes the clean export frame for
its receipt's later household-count check. The fixture sweep does not measure
the build frees the target frame and the calibration result's target tables.
A result frame that `Frame.with_weights` builds from the target frame (the
dense result, an L0 selection) shares every table's memory with it, target
columns included, so the tables are freed only once both the target frame and
those result frames are dropped. Dense and L0 results drop those frames; exact-k
substitutes the clean export frame for its receipt's later household-count
check. The fixture sweep does not measure
memory or wall time of the batched stages at full size.

## Probing an export on a household subsample
Expand Down
23 changes: 20 additions & 3 deletions packages/microcosm-build/src/microcosm/build/frame_checkpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -175,9 +181,17 @@ def load_frame_checkpoint(
) -> LoadedFrameCheckpoint:
"""Load a checkpoint and reconstruct its schema, data, and audit metadata.

The frame takes the decoded tables without copying them when pandas
copy-on-write is on (:meth:`~microcosm.frame.Frame.adopt`), so each
loaded table keeps one internal block per column; values, dtypes and the
bytes a rewrite produces are unchanged. A pandas fixed-format HDF write,
which stores one dataset per internal block, can therefore group a loaded
table's columns into different datasets than a write of the same table
built in memory; the values read back by column name are the same.

``frame_metadata`` lets a caller restore separately bound
:class:`~microcosm.frame.Frame` metadata during the loader's one Frame
construction. This avoids a second full-table copy for large checkpoints.
construction. This avoids building a second frame for large checkpoints.
The caller remains responsible for validating that metadata against its
own artifact identity or embedded external metadata.
"""
Expand Down Expand Up @@ -299,7 +313,10 @@ def load_frame_checkpoint(
)
mass_log = _mass_log_from_metadata(stored_metadata, input_path)
try:
frame = Frame(
# The decoded tables have no other owner, so the frame takes them
# without copying (under pandas copy-on-write): reading a checkpoint
# holds one copy of its data, not the decoded columns plus a copy.
frame = Frame.adopt(
tables,
schema,
weights,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -409,8 +409,10 @@
# acs_transfer's attested bytes change; no draw, RNG rule or QRF target does.
# The QRF draw's default thread count, joblib.cpu_count() in place of
# os.cpu_count() in microcosm.fit.qrf, moves both again; no draw changes.
"seed_map": "530bdaf982c7ad2440db7b4b02f8de5843dac083c6e36c28385ce5d8bbb23e35",
"seed_protocol": "f5cc748f1b9fbeaea54c18d9e2c1e6e74f2679c9cbf6cf7a09e7b548d2788d66",
# calibrate's return_frame option in solve moves both again; the default
# is unchanged, and no draw changes.
"seed_map": "1dda5e09b93e4acd51844bfbd62555adfc91d309e0f7647d64b959e0820d1d1e",
"seed_protocol": "90d566bb670521cc79f42cba8afe14fe79330ac2c990858dbe8f7debe1466fa5",
"source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6",
"take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35",
"tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import microcosm.frame.materialize as materialize_module
import microcosm.frame.scaling as scaling_module
import microcosm.frame.schema as schema_module
import microcosm.frame.shared_columns as shared_columns_module
import microcosm.frame.transport as transport_module
import microcosm.frame.unit_construction as units_module
import microcosm.frame.weights as weights_module
Expand Down Expand Up @@ -167,6 +168,7 @@ def implementation_hash(self) -> str:
scaling_module,
bundle_module,
schema_module,
shared_columns_module,
weights_module,
*target_kernels._COMPILE_MODULES,
dependencies=self.capabilities.dependencies,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1120,11 +1120,13 @@ def uk_release_export_frame(frame: Frame) -> Frame:
of the share keys' components at the frame's weights
(:func:`uk_household_totals`); the dataset-year division sums them again at
the weights the file stores (``weight_year.uk_dataset_year_frame``). A
frame that already left passes unchanged.
frame that already left passes unchanged. The tables are copied below, so
shared columns are checked first.
"""

from .geography_ladder import export_area_code_columns

frame.check_shared_columns()
tables: dict[str, pd.DataFrame] = {}
changed = False
for entity in ("person", "benunit", "household"):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading