Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions changelog.d/frame-adopt-replace-tables.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +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.
243 changes: 239 additions & 4 deletions packages/microcosm-frame/src/microcosm/frame/bundle.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,14 @@
Frame operations return new frames. Entity-table access follows a read-only
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`).
"""

import re
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any
Expand Down Expand Up @@ -107,17 +113,132 @@ def __init__(
mass_log: tuple[MassChangeRecord, ...] = (),
metadata: Mapping[str, Any] | None = None,
) -> None:
self._assemble(
tables,
schema,
weights,
strata,
mass_log=mass_log,
metadata=metadata,
copy_data=True,
)

@classmethod
def _adopt(
cls,
tables: Mapping[str, pd.DataFrame],
schema: EntitySchema,
weights: Mapping[str, Weights],
strata: pd.Series | None = None,
*,
mass_log: tuple[MassChangeRecord, ...] = (),
metadata: Mapping[str, Any] | None = None,
) -> "Frame":
"""Build a frame that takes ownership of ``tables`` instead of copying them.

When pandas copy-on-write is on, the frame stores the given DataFrame
objects themselves, so its columns share memory with any other
DataFrame that shares theirs. Copy-on-write then keeps a write made
through pandas to one of those DataFrames from reaching the others.
The caller hands the tables over and must not write to these
DataFrame objects afterwards: a write to the same object changes this
frame.

Copy-on-write does not protect raw writes into the shared memory, for
example through ``Series.array``, the ``.base`` of a read-only view,
``.asi8``, private pandas attributes, an array made writable,
``ufunc.at``, ``np.copyto`` or ``out=``
(``test_shared_buffer_writes.py`` refuses the direct forms of some of
these in ``packages/*/src/`` and ``tools/``), and through what
``.values`` and ``to_numpy()`` return for extension-typed columns.
``.values`` returns the column's own extension array, and a write
into it reaches every frame sharing the column, for example for the
nullable integer, float and boolean types, ``category`` and
python-backed strings, and under pandas 2.x pyarrow-backed types.
``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.

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
are deep-copied exactly as the constructor copies them. The check is
made when the frame is built: a frame built while copy-on-write was on
relies on it staying on.

Arguments and validation are the constructor's: every invariant is
checked and the same errors are raised, except that a table that is
not a DataFrame raises ``TypeError`` before any table is stored or
checked (the constructor calls each table's ``copy()`` and checks
what it returns, so it fails on a table without one). Weights are
stored as given (their arrays are read-only), and the strata are
shallow-copied when copy-on-write is on.

Args:
tables: Entity and link tables, as for the constructor.
schema: The entity structure.
weights: Typed weight vectors keyed by entity name.
strata: Per-person provenance labels, or ``None`` for
:data:`DEFAULT_STRATUM`.
mass_log: Declared mass changes, as for the constructor.
metadata: Stage receipts, as for the constructor.

Returns:
A new validated frame that owns ``tables``.

Raises:
TypeError: If a table is not a :class:`pandas.DataFrame`, or as
the constructor would.
ValueError: As the constructor would on the same arguments.
"""

frame = cls.__new__(cls)
frame._assemble(
tables,
schema,
weights,
strata,
mass_log=mass_log,
metadata=metadata,
copy_data=not _pandas_copy_on_write(),
require_dataframes=True,
)
return frame

def _assemble(
self,
tables: Mapping[str, pd.DataFrame],
schema: EntitySchema,
weights: Mapping[str, Weights],
strata: pd.Series | None,
*,
mass_log: tuple[MassChangeRecord, ...],
metadata: Mapping[str, Any] | None,
copy_data: bool,
require_dataframes: bool = False,
) -> None:
"""Store a frame's parts and check every constructor invariant.

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
``require_dataframes``, a table that is not a DataFrame raises
``TypeError`` (:meth:`_adopt`).
"""

self._schema = schema
self._mass_log = tuple(mass_log)
self._metadata = _freeze_metadata(metadata)
declared_links = {link.name for link in schema.links}
self._tables: dict[str, pd.DataFrame] = {}
self._link_tables: dict[str, pd.DataFrame] = {}
if require_dataframes:
_require_dataframes(tables)
for name, frame in tables.items():
target = self._link_tables if name in declared_links else self._tables
target[name] = frame.copy()
target[name] = frame.copy() if copy_data else frame
self._weights = dict(weights)
self._strata = self._validated_strata(strata)
self._strata = self._validated_strata(strata, deep=copy_data)
self._validate_tables()
self._validate_linkage()
self._validate_links()
Expand Down Expand Up @@ -357,7 +478,9 @@ def _validate_reserved_weight_columns(self) -> None:
"column; drop this column before constructing the frame."
)

def _validated_strata(self, strata: pd.Series | None) -> pd.Series:
def _validated_strata(
self, strata: pd.Series | None, *, deep: bool = True
) -> pd.Series:
person = self._tables.get(self._schema.person_entity)
if person is None:
raise ValueError(
Expand All @@ -379,7 +502,7 @@ def _validated_strata(self, strata: pd.Series | None) -> pd.Series:
)
if strata.isna().any():
raise ValueError("strata contains missing labels.")
out = strata.copy()
out = strata.copy(deep=deep)
out.name = "stratum"
return out

Expand Down Expand Up @@ -803,6 +926,86 @@ def _mass_change_record(
reason=change.reason,
)

def replace_tables(self, /, **changed_tables: pd.DataFrame) -> "Frame":
"""Return a new frame with some entity or link tables replaced or added.

The new frame holds a shallow copy of each replacement and of every
other table, so when pandas copy-on-write is on it shares their memory
with the replacements and with this frame, and a write made through
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
metadata are carried unchanged. When copy-on-write is off, every
table is deep-copied instead.

Args:
**changed_tables: Replacement tables, or declared link tables to
add, keyed by entity or link name.

Returns:
A new validated frame.

Raises:
TypeError: If a replacement is not a :class:`pandas.DataFrame`, or
as construction would.
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).
"""

_require_dataframes(changed_tables)
tables = {
name: table.copy(deep=False)
for name, table in {**self._tables, **self._link_tables}.items()
}
tables.update(
{name: table.copy(deep=False) for name, table in changed_tables.items()}
)
return Frame._adopt(
tables,
self._schema,
self._weights,
self._strata,
mass_log=self._mass_log,
metadata=self._metadata,
)

def with_columns(self, entity: str, /, **columns: Any) -> "Frame":
"""Return a new frame with columns set on one entity's table.

Each value is assigned with ``table[name] = values``, so a new name
adds a column and an existing name replaces one, under pandas'
assignment rules: a :class:`pandas.Series` aligns on the table's
index, and an array or list must have one value per row. pandas
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.

Args:
entity: An entity declared by the schema (not a link).
**columns: Column values keyed by column name.

Returns:
A new validated frame.

Raises:
TypeError, ValueError: As pandas raises them when it cannot
assign a value as a column (for example a set, or a value of
the wrong length), or as construction would.
ValueError: If ``entity`` is not declared by the schema, or the
new columns break a constructor invariant (for example a
name another table already carries, a reserved
``{entity}_weight`` name, a duplicated or missing id, or
broken linkage).
"""

table = self.table(entity).copy(deep=False)
for column_name, values in columns.items():
table[column_name] = values
return self.replace_tables(**{entity: table})

def broadcast(self, column: str, to: str = "person") -> pd.Series:
"""Map a group-table column onto persons via membership.

Expand Down Expand Up @@ -1343,6 +1546,38 @@ def __repr__(self) -> str:
return f"Frame({sizes}; weights[{weighted}]; strata={n_strata}{links})"


def _require_dataframes(tables: Mapping[str, Any]) -> None:
for name, table in tables.items():
if not isinstance(table, pd.DataFrame):
raise TypeError(
f"Table {name!r} must be a pandas DataFrame, got "
f"{type(table).__name__}."
)


def _pandas_copy_on_write() -> bool:
"""Whether pandas copy-on-write is on in this process, checked at each call.

pandas 2.x answers this itself with ``pandas._config.using_copy_on_write()``:
``mode.copy_on_write`` must be ``True`` (it is ``False`` by default, or
``"warn"``) and the data manager the default block manager. Reading
that function emits none of the deprecation warnings the options do.
pandas 3 removed that function: copy-on-write is always on there, and
its option is deprecated and ignored. Without the function, a version
from 3 on counts as on, and any other version reads
``mode.copy_on_write``.
"""

try:
from pandas._config import using_copy_on_write
except ImportError:
major_version = re.match(r"\d+", pd.__version__)
if major_version is not None and int(major_version.group()) >= 3:
return True
return pd.get_option("mode.copy_on_write") is True
return bool(using_copy_on_write())


@dataclass(frozen=True)
class _FrozenMapping(Mapping[str, Any]):
"""Small pickle-safe immutable mapping used for frame metadata."""
Expand Down
Loading
Loading