From 8afea44e98b5cdc8e13e7274095f188e89a7a712 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:44:43 +0400 Subject: [PATCH 01/15] Add Frame._adopt, replace_tables and with_columns, and a shared-buffer write scan Frame._adopt stores the tables it is given without copying them when pandas copy-on-write is on, and deep-copies them when it is off (pandas 2.x defaults), with the constructor's full validation. replace_tables builds a frame from shallow copies of every table plus the replacements, and with_columns assigns columns on a shallow copy of one entity's table. The default constructor still deep-copies every table; its body moved into _assemble unchanged. Nothing calls the new methods yet. test_shared_buffer_writes.py reads the source of every workspace package and tools/ and refuses writes that copy-on-write does not protect: making an array writable, writes through .array, pandas' private buffer attributes, np.copyto, and out=, ufunc.at and NumPy's in-place functions into arrays the function did not create. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/frame/bundle.py | 196 ++- .../shared/test_frame_table_sharing.py | 543 +++++++ .../shared/test_shared_buffer_writes.py | 1381 +++++++++++++++++ 3 files changed, 2116 insertions(+), 4 deletions(-) create mode 100644 packages/microcosm-frame/tests/engine_free/shared/test_frame_table_sharing.py create mode 100644 packages/microcosm-frame/tests/engine_free/shared/test_shared_buffer_writes.py diff --git a/packages/microcosm-frame/src/microcosm/frame/bundle.py b/packages/microcosm-frame/src/microcosm/frame/bundle.py index e16c3a45a7..ad9fb20089 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -20,6 +20,11 @@ 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`). """ from collections.abc import Mapping @@ -107,6 +112,96 @@ 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. Raw writes into the shared memory (through ``Series.array``, + private pandas attributes, an array made writable, ``np.copyto`` or + ``out=``) are never protected; ``test_shared_buffer_writes.py`` + refuses them in the workspace's source. + + 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. + + Arguments and validation are the constructor's: every invariant is + checked and the same errors are raised. 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, ValueError: Exactly 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(), + ) + 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, + ) -> 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). + """ + self._schema = schema self._mass_log = tuple(mass_log) self._metadata = _freeze_metadata(metadata) @@ -115,9 +210,9 @@ def __init__( self._link_tables: dict[str, pd.DataFrame] = {} 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() @@ -357,7 +452,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( @@ -379,7 +476,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 @@ -803,6 +900,84 @@ 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. + + 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. Weights, strata, the mass log and metadata are + carried unchanged. When copy-on-write is off, every table is + deep-copied instead (see :meth:`_adopt`). + + Args: + **changed_tables: Replacement tables 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). + """ + + for name, table in changed_tables.items(): + if not isinstance(table, pd.DataFrame): + raise TypeError( + f"Table {name!r} must be a pandas DataFrame, got " + f"{type(table).__name__}." + ) + 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 3 + 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`. + + Args: + entity: An entity declared by the schema (not a link). + **columns: Column values keyed by column name. + + Returns: + A new validated frame. + + Raises: + ValueError: If ``entity`` is not declared by the schema, a value's + length does not match the table, or the new columns break a + constructor invariant (a name another table already carries, + a reserved ``{entity}_weight`` name, or broken linkage). + """ + + table = self.table(entity).copy(deep=not _pandas_copy_on_write()) + 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. @@ -1343,6 +1518,19 @@ def __repr__(self) -> str: return f"Frame({sizes}; weights[{weighted}]; strata={n_strata}{links})" +def _pandas_copy_on_write() -> bool: + """Whether pandas copy-on-write is on in this process, checked at each call. + + pandas 3 always has copy-on-write on and deprecates its option, so the + option is read only under pandas 2.x, where it is ``True`` only when + copy-on-write is enabled (it is ``False`` by default, or ``"warn"``). + """ + + if int(pd.__version__.split(".", 1)[0]) >= 3: + return True + return pd.get_option("mode.copy_on_write") is True + + @dataclass(frozen=True) class _FrozenMapping(Mapping[str, Any]): """Small pickle-safe immutable mapping used for frame metadata.""" 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 new file mode 100644 index 0000000000..016da4f262 --- /dev/null +++ b/packages/microcosm-frame/tests/engine_free/shared/test_frame_table_sharing.py @@ -0,0 +1,543 @@ +"""Frames that share unchanged tables: ``_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 +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`` +deep-copies instead. These tests replace the copy-on-write check to take that +path, because pandas 3 always has copy-on-write on. +""" + +from collections.abc import Callable +from typing import Any + +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 + +_SCHEMA = EntitySchema( + group_entities=("household", "firm"), + links=(LinkSpec(name="jobs", left_entity="person", right_entity="firm"),), +) + +_SOURCE_INCOME = [50_000.0, 0.0, 30_000.0, 20_000.0] +_SOURCE_RENT = [900.0, 1_200.0] + + +def _source_tables() -> dict[str, pd.DataFrame]: + """Four persons in two households and two firms, plus a jobs link table.""" + + 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(_SOURCE_INCOME), + } + ), + "household": pd.DataFrame( + { + "household_id": np.array([1, 2], dtype="int64"), + "rent": np.array(_SOURCE_RENT), + "state": ["CA", "NY"], + } + ), + "firm": pd.DataFrame( + { + "firm_id": np.array([10, 20], dtype="int64"), + "payroll": np.array([1.0e6, 2.0e6]), + } + ), + "jobs": pd.DataFrame( + { + "person_id": np.array([0, 2, 3], dtype="int64"), + "firm_id": np.array([10, 20, 20], dtype="int64"), + } + ), + } + + +def _source_weights() -> dict[str, Weights]: + return { + "household": Weights(values=np.array([100.0, 200.0]), kind=WeightKind.DESIGN) + } + + +def _source_strata() -> pd.Series: + return pd.Series(["cps", "cps", "puf", "puf"], index=pd.RangeIndex(4)) + + +@pytest.fixture +def source_frame() -> Frame: + """A frame with a link table, strata, metadata and one mass-log entry.""" + + frame = Frame( + _source_tables(), + _SCHEMA, + _source_weights(), + _source_strata(), + metadata={"stage": "source"}, + ) + return frame.with_weights( + "household", + Weights(values=np.array([150.0, 300.0]), kind=WeightKind.CALIBRATED), + mass=MassChange(factor=1.5, reason="test calibration"), + ) + + +@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 _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 + + +class TestDefaultConstructor: + def test_constructor_deep_copies_every_table(self) -> None: + tables = _source_tables() + frame = Frame(tables, _SCHEMA, _source_weights(), _source_strata()) + + for name, table in _tables_of(frame).items(): + assert table is not tables[name] + sharing = _numeric_columns_sharing_memory(_tables_of(frame), tables) + assert sharing, "the comparison found no numeric columns" + assert not any(sharing.values()), sharing + + +class TestAdopt: + def test_adopt_stores_the_given_tables_without_copying(self) -> None: + tables = _source_tables() + frame = Frame._adopt(tables, _SCHEMA, _source_weights(), _source_strata()) + + for name, table in _tables_of(frame).items(): + assert table is tables[name] + assert frame.links == ("jobs",) + + 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) + + for name, table in _tables_of(frame).items(): + assert table is not tables[name] + sharing = _numeric_columns_sharing_memory(_tables_of(frame), tables) + assert sharing, "the comparison found no numeric columns" + assert not any(sharing.values()), sharing + assert not np.shares_memory(frame.strata.to_numpy(), strata.to_numpy()) + + 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) + + 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( + _source_tables(), + _SCHEMA, + _source_weights(), + mass_log=source_frame.mass_log, + metadata={"stage": "adopted", "inputs": ["cps", "puf"]}, + ) + + assert frame.mass_log == source_frame.mass_log + assert dict(frame.metadata) == {"stage": "adopted", "inputs": ("cps", "puf")} + + +def _drop_table(name: str) -> Callable[[dict[str, Any]], None]: + def change(arguments: dict[str, Any]) -> None: + del arguments["tables"][name] + + return change + + +def _set_table(name: str, make: Callable[[pd.DataFrame], Any]) -> Callable: + def change(arguments: dict[str, Any]) -> None: + tables = arguments["tables"] + tables[name] = make(tables.get(name)) + + return change + + +def _set_cell(table: str, row: int, column: str, value: Any) -> Callable: + def change(arguments: dict[str, Any]) -> None: + arguments["tables"][table].loc[row, column] = value + + return change + + +def _set_argument(name: str, value: Any) -> Callable[[dict[str, Any]], None]: + def change(arguments: dict[str, Any]) -> None: + arguments[name] = value() if callable(value) else value + + return change + + +#: Each case breaks one constructor invariant; the ids name the invariant. +_INVALID_ARGUMENTS = { + "missing_entity_table": _drop_table("firm"), + "unknown_entity_table": _set_table( + "spaceship", lambda _table: pd.DataFrame({"spaceship_id": [1]}) + ), + "missing_person_id_column": _set_table( + "person", lambda table: table.drop(columns=["person_id"]) + ), + "duplicate_person_id": _set_cell("person", 1, "person_id", 0), + "missing_membership_column": _set_table( + "person", lambda table: table.drop(columns=["person_firm_id"]) + ), + "unsorted_group_ids": _set_table( + "household", lambda table: table.iloc[::-1].reset_index(drop=True) + ), + "orphaned_group_id": _set_table( + "firm", + lambda _table: pd.DataFrame( + {"firm_id": [10, 20, 30], "payroll": [1.0, 2.0, 3.0]} + ), + ), + "global_column_collision": _set_table( + "firm", lambda table: table.assign(rent=[1.0, 2.0]) + ), + "link_table_missing_id_column": _set_table( + "jobs", lambda table: table.drop(columns=["firm_id"]) + ), + "link_table_dangling_id": _set_cell("jobs", 0, "firm_id", 99), + "reserved_weight_column": _set_table( + "person", lambda table: table.assign(person_weight=1.0) + ), + "no_weights": _set_argument("weights", {}), + "weights_length_mismatch": _set_argument( + "weights", + { + "household": Weights( + values=np.array([1.0, 2.0, 3.0]), kind=WeightKind.DESIGN + ) + }, + ), + "weights_not_typed": _set_argument("weights", {"household": np.array([1.0, 2.0])}), + "weights_for_unknown_entity": _set_argument( + "weights", + { + **_source_weights(), + "galaxy": Weights(values=np.array([1.0]), kind=WeightKind.DESIGN), + }, + ), + "strata_misaligned": _set_argument( + "strata", lambda: pd.Series(["cps"] * 4, index=[5, 6, 7, 8]) + ), + "strata_not_a_series": _set_argument("strata", ["cps"] * 4), + "strata_missing_label": _set_argument( + "strata", lambda: pd.Series(["cps", None, "puf", "puf"]) + ), + "metadata_not_a_mapping": _set_argument("metadata", ["stage"]), + "metadata_unsupported_value": _set_argument("metadata", {"stage": object()}), +} + + +def _constructor_arguments(change: Callable[[dict[str, Any]], None]) -> dict: + arguments: dict[str, Any] = { + "tables": _source_tables(), + "schema": _SCHEMA, + "weights": _source_weights(), + "strata": _source_strata(), + "metadata": None, + } + change(arguments) + return arguments + + +@pytest.mark.parametrize("copy_on_write", [True, False], ids=["cow_on", "cow_off"]) +@pytest.mark.parametrize( + "change", list(_INVALID_ARGUMENTS.values()), ids=list(_INVALID_ARGUMENTS) +) +def test_adopt_raises_the_constructors_validation_errors( + monkeypatch: pytest.MonkeyPatch, change, copy_on_write: bool +) -> None: + monkeypatch.setattr(bundle_module, "_pandas_copy_on_write", lambda: copy_on_write) + 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)) + + assert str(adopt_error.value) == str(constructor_error.value) + + +class TestReplaceTables: + def test_unchanged_tables_share_memory_with_the_source(self, source_frame) -> None: + # A shallow copy with one column replaced keeps sharing the others. + household = source_frame.table("household").copy(deep=False) + household["rent"] = [1_000.0, 1_300.0] + replaced = source_frame.replace_tables(household=household) + + assert replaced.table("household")["rent"].tolist() == [1_000.0, 1_300.0] + assert source_frame.table("household")["rent"].tolist() == _SOURCE_RENT + sharing = _numeric_columns_sharing_memory( + _tables_of(replaced), _tables_of(source_frame) + ) + unchanged = { + key: shared for key, shared in sharing.items() if key[0] != "household" + } + assert unchanged and all(unchanged.values()), unchanged + assert not sharing[("household", "rent")] + assert sharing[("household", "household_id")] + + def test_every_table_is_a_distinct_object(self, source_frame) -> None: + household = source_frame.table("household").copy() + replaced = source_frame.replace_tables(household=household) + + source_tables = _tables_of(source_frame) + for name, table in _tables_of(replaced).items(): + assert table is not source_tables[name] + assert replaced.table("household") is not household + assert np.shares_memory( + replaced.table("household")["rent"].to_numpy(), + household["rent"].to_numpy(), + ) + + def test_weights_strata_mass_log_and_metadata_are_carried( + self, source_frame + ) -> None: + replaced = source_frame.replace_tables( + firm=source_frame.table("firm").assign(payroll=[5.0, 6.0]) + ) + + assert type(replaced) is Frame + assert replaced.weights_for("household") is source_frame.weights_for( + "household" + ) + assert replaced.strata.equals(source_frame.strata) + assert replaced.mass_log == source_frame.mass_log + assert len(replaced.mass_log) == 1 + assert replaced.metadata == source_frame.metadata + assert replaced.links == ("jobs",) + + def test_a_link_table_can_be_replaced(self, source_frame) -> None: + jobs = pd.DataFrame({"person_id": [1, 3], "firm_id": [10, 20]}) + replaced = source_frame.replace_tables(jobs=jobs) + + assert replaced.link("jobs")["person_id"].tolist() == [1, 3] + assert source_frame.link("jobs")["person_id"].tolist() == [0, 2, 3] + + def test_a_later_write_to_the_passed_table_does_not_reach_the_frame( + self, source_frame + ) -> None: + household = source_frame.table("household").copy() + replaced = source_frame.replace_tables(household=household) + + household.loc[0, "rent"] = -1.0 + + assert replaced.table("household")["rent"].tolist() == _SOURCE_RENT + + def test_replace_tables_deep_copies_when_copy_on_write_is_off( + self, source_frame, copy_on_write_off: None + ) -> None: + household = source_frame.table("household").copy() + replaced = source_frame.replace_tables(household=household) + + against_source = _numeric_columns_sharing_memory( + _tables_of(replaced), _tables_of(source_frame) + ) + against_passed = _numeric_columns_sharing_memory( + _tables_of(replaced), {"household": household} + ) + assert against_source and not any(against_source.values()), against_source + assert against_passed and not any(against_passed.values()), against_passed + + def test_the_result_is_fully_validated(self, source_frame) -> None: + reversed_households = ( + source_frame.table("household").iloc[::-1].reset_index(drop=True) + ) + with pytest.raises(ValueError, match="sorted ascending"): + source_frame.replace_tables(household=reversed_households) + with pytest.raises( + ValueError, match=r"Unknown entity table\(s\): \['spaceship'\]" + ): + source_frame.replace_tables(spaceship=pd.DataFrame({"spaceship_id": [1]})) + + def test_a_table_that_is_not_a_dataframe_is_refused(self, source_frame) -> None: + with pytest.raises(TypeError, match="'household'.*DataFrame.*dict"): + source_frame.replace_tables(household={"household_id": [1, 2]}) + + +class TestWithColumns: + def test_columns_are_replaced_and_added(self, source_frame) -> None: + income = np.array([1.0, 2.0, 3.0, 4.0]) + updated = source_frame.with_columns("person", income=income, bonus=np.zeros(4)) + + assert updated.person["income"].tolist() == [1.0, 2.0, 3.0, 4.0] + assert updated.person["bonus"].tolist() == [0.0] * 4 + assert source_frame.person["income"].tolist() == _SOURCE_INCOME + assert "bonus" not in source_frame.person.columns + assert not np.shares_memory(updated.person["income"].to_numpy(), income) + + def test_unchanged_columns_share_memory_with_the_source(self, source_frame) -> None: + updated = source_frame.with_columns("person", income=np.ones(4)) + + sharing = _numeric_columns_sharing_memory( + _tables_of(updated), _tables_of(source_frame) + ) + unchanged = { + key: shared + for key, shared in sharing.items() + if key != ("person", "income") + } + assert unchanged and all(unchanged.values()), unchanged + assert not sharing[("person", "income")] + assert updated.person is not source_frame.person + + def test_weights_strata_mass_log_and_metadata_are_carried( + self, source_frame + ) -> None: + updated = source_frame.with_columns("household", rent=[1.0, 2.0]) + + assert updated.weights_for("household") is source_frame.weights_for("household") + assert updated.strata.equals(source_frame.strata) + assert updated.mass_log == source_frame.mass_log + assert updated.metadata == source_frame.metadata + assert updated.links == ("jobs",) + + def test_a_column_may_be_named_entity(self, source_frame) -> None: + updated = source_frame.with_columns("person", entity=np.arange(4)) + + assert updated.person["entity"].tolist() == [0, 1, 2, 3] + + def test_an_unknown_entity_is_named(self, source_frame) -> None: + with pytest.raises(ValueError, match="Unknown entity 'spaceship'"): + source_frame.with_columns("spaceship", fuel=[1.0]) + with pytest.raises(ValueError, match="Unknown entity 'jobs'"): + source_frame.with_columns("jobs", hours=[1.0, 2.0, 3.0]) + + def test_the_result_is_fully_validated(self, source_frame) -> None: + with pytest.raises(ValueError, match="globally unique"): + source_frame.with_columns("firm", rent=[1.0, 2.0]) + with pytest.raises(ValueError, match="sorted ascending"): + source_frame.with_columns("household", household_id=[2, 1]) + with pytest.raises(ValueError, match="reserved weight-column"): + source_frame.with_columns("person", person_weight=np.ones(4)) + + def test_with_columns_deep_copies_when_copy_on_write_is_off( + self, source_frame, copy_on_write_off: None + ) -> None: + updated = source_frame.with_columns("person", bonus=np.zeros(4)) + + sharing = _numeric_columns_sharing_memory( + _tables_of(updated), _tables_of(source_frame) + ) + assert sharing and not any(sharing.values()), sharing + + +def _frames_built_from(source_frame: Frame) -> dict[str, Frame]: + return { + "with_columns": source_frame.with_columns("person", bonus=np.zeros(4)), + "replace_tables": source_frame.replace_tables( + firm=source_frame.table("firm").assign(payroll=[5.0, 6.0]) + ), + } + + +@pytest.mark.parametrize("method", ["with_columns", "replace_tables"]) +def test_a_pandas_write_to_the_new_frame_leaves_the_source_unchanged( + source_frame, method: str +) -> None: + derived = _frames_built_from(source_frame)[method] + assert np.shares_memory( + derived.person["income"].to_numpy(), source_frame.person["income"].to_numpy() + ) + + derived.person.loc[0, "income"] = -1.0 + derived.table("household").loc[1, "rent"] = -1.0 + derived.link("jobs").loc[0, "firm_id"] = 20 + + assert derived.person["income"].tolist()[0] == -1.0 + assert source_frame.person["income"].tolist() == _SOURCE_INCOME + assert source_frame.table("household")["rent"].tolist() == _SOURCE_RENT + assert source_frame.link("jobs")["firm_id"].tolist() == [10, 20, 20] + source_frame.revalidate() + + +@pytest.mark.parametrize("method", ["with_columns", "replace_tables"]) +def test_a_pandas_write_to_the_source_leaves_the_new_frame_unchanged( + source_frame, method: str +) -> None: + derived = _frames_built_from(source_frame)[method] + + source_frame.person.loc[0, "income"] = -1.0 + source_frame.table("household").loc[1, "rent"] = -1.0 + + assert derived.person["income"].tolist() == _SOURCE_INCOME + assert derived.table("household")["rent"].tolist() == _SOURCE_RENT + + +class TestCopyOnWriteCheck: + def test_pandas_3_has_copy_on_write_without_reading_the_option( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + def refuse_option_reads(name: str) -> object: + raise AssertionError(f"pandas 3 must not read option {name!r}") + + monkeypatch.setattr(bundle_module.pd, "__version__", "3.0.3") + monkeypatch.setattr(bundle_module.pd, "get_option", refuse_option_reads) + + assert bundle_module._pandas_copy_on_write() is True + + @pytest.mark.parametrize( + ("option_value", "expected"), + [(True, True), (False, False), ("warn", False)], + ids=["enabled", "disabled", "warn_mode"], + ) + def test_pandas_2_reads_the_copy_on_write_option( + self, monkeypatch: pytest.MonkeyPatch, option_value: object, expected: bool + ) -> None: + options = {"mode.copy_on_write": option_value} + monkeypatch.setattr(bundle_module.pd, "__version__", "2.3.3") + monkeypatch.setattr(bundle_module.pd, "get_option", options.__getitem__) + + assert bundle_module._pandas_copy_on_write() is expected 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 new file mode 100644 index 0000000000..31f99d0278 --- /dev/null +++ b/packages/microcosm-frame/tests/engine_free/shared/test_shared_buffer_writes.py @@ -0,0 +1,1381 @@ +"""No raw writes into memory that pandas copy-on-write does not protect. + +:meth:`Frame.replace_tables` and :meth:`Frame.with_columns` build frames that +share the memory of every unchanged column with their source frame +(:meth:`Frame._adopt`). pandas copy-on-write keeps a write made through pandas +(``.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 write below changes the other frame's +data without an error, so this test reads the scanned source with :mod:`ast` +and refuses it. Each rule's name is what a failure reports. + +``makes-array-writable`` + ``setflags(write=...)`` with anything but a false constant, or assigning + ``flags.writeable``, ``flags["W"]`` or ``flags["WRITEABLE"]``. The arrays + ``to_numpy()`` and ``.values`` return for NumPy-typed columns are + read-only views of the shared memory; this makes them writable. +``writes-through-series-array`` + A write into ``.array`` (of a Series or Index): item assignment, + ``__setitem__``, ``fill``, ``sort``, ``put`` and the other in-place + ndarray methods, ``out=``, or the in-place NumPy functions below. It + counts when the written expression reaches ``.array`` through indexing, + ``np.asarray`` and the other NumPy view functions, ``to_numpy()`` and + the other view methods, or a name the same function binds to such an + expression. ``ser.array`` is writable for float, integer and boolean + columns, and so are ``np.asarray(ser.array)`` and + ``ser.array.to_numpy()``. +``pandas-private-attribute`` + ``._ndarray`` or ``._mgr`` on anything, and ``._values``, ``._data``, + ``._mask`` or ``._codes`` on anything but ``self`` or ``cls``. These + reach pandas' internal arrays, which are always writable. +``numpy-copyto`` + Any use of ``numpy.copyto``. +``writes-into-existing-array`` + ``out=`` given to a NumPy function, ufunc or ndarray method (by keyword, + or by position for NumPy functions and ufuncs), the first argument of + ``numpy..at`` (which writes even into a read-only array), and the + first argument of ``numpy.put``, ``numpy.putmask``, ``numpy.place``, + ``numpy.fill_diagonal`` and ``numpy.random.shuffle``, unless the array + was created in the same function. Created means one of: the result of a + ufunc or of a NumPy function that always allocates + (``_ALLOCATING_NUMPY_FUNCTIONS``: ``np.zeros``, ``np.where``, + ``np.concatenate``, ...), when not given an output array; ``np.array`` + without ``copy=``; a deep ``.copy()``; arithmetic, a comparison, or a + list, set or dict display; a subscript of one of these; or a local name + whose every binding in the function, other than to ``None``, is one of + these. + +``setflags``, ``Series.array[i] = value``, ``._ndarray``, ``._mgr``, +``np.copyto`` and ``out=`` are the writes first identified as unprotected. +``ufunc.at``, the other in-place NumPy functions and methods, the other +writes through ``.array``, and the other private attributes were added after +checking that they write into shared memory too. + +Scope: every Python file under ``packages/*/src/`` (the source of every +workspace package, including microcosm-frame and the microcosm-build code that +builds US and UK frames) and under ``tools/`` (the release and build tools), +except files in ``node_modules`` or hidden directories. Tests and +``test_support/`` are not scanned. + +What source reading cannot see: the arrays ``to_numpy()`` and ``.values`` +return for nullable extension types (``Int64``, ``boolean``, ``Float64``) +are writable views of the shared memory, and a pandas object built with +``copy=False`` over another object's array writes into it when it is written +through pandas. Neither is refused here. + +A finding that cannot write into memory a pandas object shares goes in +``_REVIEWED_FINDINGS`` with the reason. +""" + +from __future__ import annotations + +import ast +import bisect +import functools +import inspect +import re +from collections import defaultdict +from collections.abc import Iterable, Iterator +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +import pytest + +from test_support.paths import paths_for + +_REPOSITORY = paths_for("microcosm-frame").repository + +#: Reviewed findings that cannot write into memory a pandas object shares, +#: keyed by (repository-relative path, enclosing function, rule, the +#: expression's source as a failure reports it), with the reason. The +#: function is ``Class.method`` or ``outer.inner``, or ```` for +#: module-level code. A changed expression needs a new review. +_REVIEWED_FINDINGS: dict[tuple[str, str, str, str], str] = { + ( + "packages/microcosm-build/src/microcosm/build/uk_runtime/frs_relationships.py", + "derive_frs_relationships", + "writes-into-existing-array", + "np.fill_diagonal(matrix, 0)", + ): ( + "np.fill_diagonal writes into matrix = grid[rows][:, columns]; indexing " + "with integer arrays returns a new array, and grid is to_numpy() of a " + "DataFrame this function computes from the raw FRS columns." + ), + ( + "tools/verify_uk_identity_stability.py", + "_pre_split_household_weights", + "writes-into-existing-array", + "np.add.at(weights, lineage.root_positions, weights[lineage.copy_positions])", + ): ( + "np.add.at writes into the array _pre_clone_household_weights returns, " + "which _pre_residential_household_weights creates with " + "np.asarray(...).copy() from the household weights." + ), +} + +_MAKES_ARRAY_WRITABLE = "makes-array-writable" +_WRITES_THROUGH_SERIES_ARRAY = "writes-through-series-array" +_PANDAS_PRIVATE_ATTRIBUTE = "pandas-private-attribute" +_NUMPY_COPYTO = "numpy-copyto" +_WRITES_INTO_EXISTING_ARRAY = "writes-into-existing-array" + +#: Private attributes refused on any object. +_ALWAYS_PRIVATE_ATTRIBUTES = frozenset({"_ndarray", "_mgr"}) +#: Private attributes refused unless read from ``self`` or ``cls``, because +#: workspace classes use the same names for their own state. +_FOREIGN_PRIVATE_ATTRIBUTES = frozenset({"_values", "_data", "_mask", "_codes"}) +_OWN_OBJECT_NAMES = frozenset({"self", "cls"}) + +#: NumPy functions whose result is always a new array (unless given ``out=``). +#: A ufunc's result is new too. +_ALLOCATING_NUMPY_FUNCTIONS = frozenset( + f"numpy.{name}" + for name in ( + "where", + "select", + "sort", + "argsort", + "unique", + "searchsorted", + "isin", + "bincount", + "diff", + "cumsum", + "cumprod", + "clip", + "take", + "flatnonzero", + "outer", + "dot", + "empty", + "zeros", + "ones", + "full", + "empty_like", + "zeros_like", + "ones_like", + "full_like", + "arange", + "linspace", + "eye", + "identity", + "copy", + "concatenate", + "stack", + "hstack", + "vstack", + "column_stack", + "tile", + "repeat", + ) +) + +#: Expressions whose value is always a new object: arithmetic, comparisons, +#: and list, set and dict displays and comprehensions. +_NEW_OBJECT_EXPRESSIONS = ( + ast.BinOp, + ast.UnaryOp, + ast.Compare, + ast.List, + ast.ListComp, + ast.Set, + ast.SetComp, + ast.Dict, + ast.DictComp, +) + +#: ndarray methods that take an ``out`` array. +_ARRAY_METHODS_WITH_OUT = frozenset( + { + "all", + "any", + "argmax", + "argmin", + "choose", + "clip", + "compress", + "cumprod", + "cumsum", + "dot", + "max", + "mean", + "min", + "prod", + "round", + "std", + "sum", + "take", + "trace", + "var", + } +) + +#: NumPy functions that write into their first argument. +_IN_PLACE_NUMPY_FUNCTIONS = frozenset( + { + "numpy.put", + "numpy.putmask", + "numpy.place", + "numpy.fill_diagonal", + "numpy.random.shuffle", + } +) + +#: ndarray methods that write into the array they are called on. +_IN_PLACE_ARRAY_METHODS = frozenset( + { + "__setitem__", + "fill", + "sort", + "put", + "partition", + "resize", + "itemset", + "setfield", + "byteswap", + } +) + +#: NumPy functions that can return a view of their first argument. +_VIEW_NUMPY_FUNCTIONS = frozenset( + f"numpy.{name}" + for name in ( + "asarray", + "asanyarray", + "ascontiguousarray", + "asfortranarray", + "ravel", + "reshape", + "squeeze", + "transpose", + "atleast_1d", + "atleast_2d", + "atleast_3d", + "frombuffer", + ) +) + +#: Methods and attributes that can return a view of the object they are read +#: from. +_VIEW_METHODS = frozenset( + {"to_numpy", "view", "reshape", "ravel", "squeeze", "transpose", "__array__"} +) +_VIEW_ATTRIBUTES = frozenset({"T", "real", "imag", "flat"}) + +_NESTED_SCOPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda) + + +@dataclass(frozen=True) +class Finding: + """One refused expression: where it is, which rule, and its source.""" + + path: str + line: int + function: str + rule: str + code: str + + @property + def key(self) -> tuple[str, str, str, str]: + return (self.path, self.function, self.rule, self.code) + + def describe(self) -> str: + return f"{self.path}:{self.line} in {self.function}: {self.rule}: {self.code}" + + +class _Scope: + """One function, class or module, and the names it binds. + + The bindings are collected on first use, because most scopes are never + asked. A name maps to the value of each assignment to it; ``None`` stands + for a binding whose value cannot be followed (a loop target, tuple + unpacking, an import, a ``with`` target, ...). + """ + + def __init__(self, qualified_name: str, node: ast.AST) -> None: + self.qualified_name = qualified_name + self._node = node + self._parameters: frozenset[str] = frozenset() + self._declared_elsewhere: set[str] = set() + self._bindings: defaultdict[str, list[ast.expr | None]] | None = None + + def child_name(self, name: str) -> str: + if self.qualified_name == "": + return name + return f"{self.qualified_name}.{name}" + + def bindings_of(self, name: str) -> list[ast.expr | None] | None: + """The values ``name`` is bound to here, or ``None`` when it is not local. + + A parameter, a name declared ``global`` or ``nonlocal``, and a name + this scope never binds are not local. + """ + + if self._bindings is None: + self._bindings = defaultdict(list) + self._collect_bindings() + if name in self._parameters or name in self._declared_elsewhere: + return None + return self._bindings.get(name) or None + + def _bind(self, target: ast.expr, value: ast.expr | None) -> None: + if isinstance(target, ast.Name): + self._bindings[target.id].append(value) + elif isinstance(target, ast.Starred): + self._bind(target.value, None) + elif isinstance(target, (ast.Tuple, ast.List)): + for element in target.elts: + self._bind(element, None) + + def _collect_bindings(self) -> None: + node = self._node + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)): + arguments = node.args + self._parameters = frozenset( + argument.arg + for argument in ( + *arguments.posonlyargs, + *arguments.args, + *arguments.kwonlyargs, + arguments.vararg, + arguments.kwarg, + ) + if argument is not None + ) + body = [node.body] if isinstance(node, ast.Lambda) else node.body + for child in _nodes_in_scope(body): + if isinstance(child, ast.Assign): + for target in child.targets: + self._bind(target, child.value) + elif isinstance(child, (ast.AnnAssign, ast.NamedExpr)): + if child.value is not None: + self._bind(child.target, child.value) + elif isinstance(child, (ast.For, ast.AsyncFor)): + self._bind(child.target, None) + elif isinstance(child, ast.withitem) and child.optional_vars is not None: + self._bind(child.optional_vars, None) + elif isinstance(child, ast.ExceptHandler) and child.name: + self._bindings[child.name].append(None) + elif isinstance(child, (ast.Import, ast.ImportFrom)): + for alias in child.names: + bound = alias.asname or alias.name.split(".", 1)[0] + self._bindings[bound].append(None) + elif isinstance(child, _NESTED_SCOPES) and not isinstance( + child, ast.Lambda + ): + self._bindings[child.name].append(None) + elif isinstance(child, (ast.Global, ast.Nonlocal)): + self._declared_elsewhere.update(child.names) + elif isinstance(child, (ast.MatchAs, ast.MatchStar)) and child.name: + self._bindings[child.name].append(None) + elif isinstance(child, ast.MatchMapping) and child.rest: + self._bindings[child.rest].append(None) + + +def _nodes_in_scope(roots: Iterable[ast.AST]) -> Iterator[ast.AST]: + """Yield the nodes of one scope, without entering nested scopes. + + A nested function, class or lambda is yielded (its name is bound here) + but not entered. Comprehensions are entered except for their loop + targets, which bind in the comprehension's own scope. + """ + + stack = list(reversed(list(roots))) + while stack: + node = stack.pop() + yield node + if isinstance(node, _NESTED_SCOPES): + continue + children = list(ast.iter_child_nodes(node)) + if isinstance(node, ast.comprehension): + children = [child for child in children if child is not node.target] + stack.extend(reversed(children)) + + +def _statements(tree: ast.Module) -> Iterator[ast.AST]: + """Yield every statement at any depth, without entering expressions.""" + + stack: list[ast.AST] = list(reversed(tree.body)) + while stack: + node = stack.pop() + yield node + for field_name in ("body", "orelse", "finalbody", "handlers", "cases"): + children = getattr(node, field_name, None) + if isinstance(children, list): + stack.extend(reversed(children)) + + +class _NumpyNames: + """The names one module binds to NumPy, to resolve ``np.add.at`` and the like.""" + + def __init__(self, tree: ast.Module) -> None: + self._aliases: dict[str, str] = {} + for node in _statements(tree): + if isinstance(node, ast.Import): + for alias in node.names: + if alias.name == "numpy" or alias.name.startswith("numpy."): + if alias.asname: + self._aliases[alias.asname] = alias.name + else: + self._aliases["numpy"] = "numpy" + elif ( + isinstance(node, ast.ImportFrom) + and node.level == 0 + and node.module is not None + and (node.module == "numpy" or node.module.startswith("numpy.")) + ): + for alias in node.names: + self._aliases[alias.asname or alias.name] = ( + f"{node.module}.{alias.name}" + ) + + @property + def bound_names(self) -> frozenset[str]: + return frozenset(self._aliases) + + def resolve(self, expression: ast.expr) -> str | None: + """The dotted NumPy name of ``expression`` (``numpy.add.at``), if any.""" + + attributes: list[str] = [] + while isinstance(expression, ast.Attribute): + attributes.append(expression.attr) + expression = expression.value + if not isinstance(expression, ast.Name): + return None + root = self._aliases.get(expression.id) + if root is None: + return None + return ".".join([root, *reversed(attributes)]) + + +#: Text found in every refused expression, except NumPy names and writes +#: through a name bound to ``.array``. +_TRIGGER_TEXT = ( + r"setflags|writeable|WRITEABLE|flags\s*\[|copyto" + r"|\.\s*_(?:ndarray|mgr|values|data|mask|codes)\b|\bout\s*=" +) +#: A module without any of this text cannot hold a finding and is not parsed. +_FILE_TRIGGERS = re.compile(_TRIGGER_TEXT + r"|numpy|\.\s*array\b") +_ARRAY_ATTRIBUTE = re.compile(r"\.\s*array\b") + + +class _TriggerLines: + """The lines of one module that hold text a refused expression contains. + + A statement whose lines hold none of it cannot hold a finding, so the + scan skips it. This needs line numbers counted as the parser counts + them, so a module with a lone carriage return gets no ``_TriggerLines``. + """ + + def __init__(self, source: str, numpy_names: Iterable[str]) -> None: + alternatives = [_TRIGGER_TEXT] + alternatives.extend(rf"\b{re.escape(name)}\b" for name in sorted(numpy_names)) + pattern = re.compile("|".join(alternatives)) + newlines = [match.start() for match in re.finditer("\n", source)] + self._lines = sorted( + { + bisect.bisect_left(newlines, match.start()) + 1 + for match in pattern.finditer(source) + } + ) + + def may_hold_finding(self, statement: ast.stmt) -> bool: + decorators = getattr(statement, "decorator_list", ()) + first = min([statement.lineno, *(item.lineno for item in decorators)]) + index = bisect.bisect_left(self._lines, first) + last = statement.end_lineno or statement.lineno + return index < len(self._lines) and self._lines[index] <= last + + +@functools.cache +def _numpy_object(dotted_name: str) -> object | None: + found: object = np + for part in dotted_name.split(".")[1:]: + found = getattr(found, part, None) + if found is None: + return None + return found + + +@functools.cache +def _positional_outputs(dotted_name: str) -> slice | None: + """Which positional arguments of a NumPy function or ufunc are outputs.""" + + function = _numpy_object(dotted_name) + if isinstance(function, np.ufunc): + return slice(function.nin, None) + if not callable(function): + return None + try: + parameters = list(inspect.signature(function).parameters.values()) + except (TypeError, ValueError): + return None + positional = ( + inspect.Parameter.POSITIONAL_ONLY, + inspect.Parameter.POSITIONAL_OR_KEYWORD, + ) + for index, parameter in enumerate(parameters): + if parameter.name == "out" and parameter.kind in positional: + return slice(index, index + 1) + return None + + +def _is_false_constant(expression: ast.expr) -> bool: + return isinstance(expression, ast.Constant) and not expression.value + + +def _keyword(call: ast.Call, name: str) -> ast.keyword | None: + return next((keyword for keyword in call.keywords if keyword.arg == name), None) + + +def _is_true_constant(expression: ast.expr) -> bool: + return isinstance(expression, ast.Constant) and expression.value is True + + +class _Scanner: + def __init__(self, source: str, path: str, tree: ast.Module) -> None: + self._source = source + self._path = path + self._tree = tree + self._numpy = _NumpyNames(tree) + # A write through a name bound to ``.array`` holds no trigger text of + # its own, so a module that reads ``.array`` is scanned in full. + lone_carriage_return = "\r" in source and "\r" in source.replace("\r\n", "") + self._trigger_lines = ( + None + if lone_carriage_return or _ARRAY_ATTRIBUTE.search(source) + else _TriggerLines(source, self._numpy.bound_names) + ) + self._scope = _Scope("", tree) + self._checks = { + ast.Call: self._check_call, + ast.Assign: self._check_assign, + ast.AnnAssign: self._check_annotated_assign, + ast.AugAssign: self._check_augmented_assign, + ast.Attribute: self._check_attribute, + ast.ImportFrom: self._check_import_from, + } + self.findings: list[Finding] = [] + + def scan(self) -> list[Finding]: + stack = [(node, self._scope) for node in reversed(self._tree.body)] + while stack: + node, scope = stack.pop() + if ( + self._trigger_lines is not None + and isinstance(node, ast.stmt) + and not self._trigger_lines.may_hold_finding(node) + ): + continue + self._scope = scope + check = self._checks.get(type(node)) + if check is not None: + check(node) + if isinstance(node, _NESTED_SCOPES): + name = "" if isinstance(node, ast.Lambda) else node.name + scope = _Scope(scope.child_name(name), node) + children = list(ast.iter_child_nodes(node)) + stack.extend((child, scope) for child in reversed(children)) + return self.findings + + # Reporting ----------------------------------------------------------- + + def _report(self, node: ast.AST, rule: str) -> None: + segment = ast.get_source_segment(self._source, node) or ast.unparse(node) + code = " ".join(segment.split()) + self.findings.append( + Finding( + path=self._path, + line=node.lineno, + function=self._scope.qualified_name, + rule=rule, + code=code if len(code) <= 120 else code[:117] + "...", + ) + ) + + # Following arrays ------------------------------------------------------ + + def _bindings(self, name: str) -> list[ast.expr | None] | None: + """The values ``name`` is bound to in the current scope, if it is local.""" + + return self._scope.bindings_of(name) + + def _allocates_new_array(self, call: ast.Call) -> bool: + if self._output_arguments(call): + return False + name = self._numpy.resolve(call.func) + if name in _ALLOCATING_NUMPY_FUNCTIONS: + return True + if name is not None and isinstance(_numpy_object(name), np.ufunc): + return True + if name == "numpy.array": + copy = _keyword(call, "copy") + return copy is None or _is_true_constant(copy.value) + if isinstance(call.func, ast.Attribute) and call.func.attr == "copy": + deep = _keyword(call, "deep") + if deep is not None and not _is_true_constant(deep.value): + return False + if not call.args: + return True + first = call.args[0] + return isinstance(first, ast.Constant) and ( + first.value is True or isinstance(first.value, str) + ) + return False + + def _is_new_local_array( + self, expression: ast.expr, following: frozenset[str] = frozenset() + ) -> bool: + if isinstance(expression, ast.Subscript): + return self._is_new_local_array(expression.value, following) + if isinstance(expression, ast.IfExp): + return self._is_new_local_array( + expression.body, following + ) and self._is_new_local_array(expression.orelse, following) + if isinstance(expression, ast.Call): + return self._allocates_new_array(expression) + if isinstance(expression, _NEW_OBJECT_EXPRESSIONS): + return True + if isinstance(expression, ast.Name) and expression.id in following: + # A binding that refers back to the name being followed (such as + # values = values[:n]) is new when the name's other bindings are. + return True + if isinstance(expression, ast.Name): + # A binding to None is a placeholder that holds no array. + values = [ + value + for value in self._bindings(expression.id) or [] + if not (isinstance(value, ast.Constant) and value.value is None) + ] + return bool(values) and all( + value is not None + and self._is_new_local_array(value, following | {expression.id}) + for value in values + ) + return False + + def _reaches_series_array( + self, expression: ast.expr, following: frozenset[str] = frozenset() + ) -> bool: + if isinstance(expression, ast.Attribute): + if expression.attr == "array": + return True + if expression.attr in _VIEW_ATTRIBUTES: + return self._reaches_series_array(expression.value, following) + return False + if isinstance(expression, ast.Subscript): + return self._reaches_series_array(expression.value, following) + if isinstance(expression, ast.IfExp): + return self._reaches_series_array( + expression.body, following + ) or self._reaches_series_array(expression.orelse, following) + if isinstance(expression, ast.Call): + name = self._numpy.resolve(expression.func) + copy = _keyword(expression, "copy") + makes_view = name in _VIEW_NUMPY_FUNCTIONS or ( + name == "numpy.array" + and copy is not None + and not _is_true_constant(copy.value) + ) + if makes_view: + return bool(expression.args) and self._reaches_series_array( + expression.args[0], following + ) + function = expression.func + if isinstance(function, ast.Attribute) and function.attr in _VIEW_METHODS: + if copy is not None and _is_true_constant(copy.value): + return False + return self._reaches_series_array(function.value, following) + return False + if isinstance(expression, ast.Name) and expression.id not in following: + values = self._bindings(expression.id) or [] + return any( + value is not None + and self._reaches_series_array(value, following | {expression.id}) + for value in values + ) + return False + + def _check_written_array(self, node: ast.AST, written: ast.expr) -> None: + """Report a write into ``written`` unless it is a new local array.""" + + if self._reaches_series_array(written): + self._report(node, _WRITES_THROUGH_SERIES_ARRAY) + elif not self._is_new_local_array(written): + self._report(node, _WRITES_INTO_EXISTING_ARRAY) + + # Rules ----------------------------------------------------------------- + + def _output_arguments(self, call: ast.Call) -> list[ast.expr]: + """The arrays a call writes into: ``out=``, positional outputs, ``ufunc.at``.""" + + written: list[ast.expr] = [] + name = self._numpy.resolve(call.func) + output = _keyword(call, "out") + # ``out=`` means an output array only to NumPy and to ndarray methods; + # workspace functions use it for output paths. + array_method = ( + isinstance(call.func, ast.Attribute) + and call.func.attr in _ARRAY_METHODS_WITH_OUT + ) + if output is not None and (name is not None or array_method): + if isinstance(output.value, (ast.Tuple, ast.List)): + written.extend(output.value.elts) + elif not _is_false_constant(output.value): + written.append(output.value) + if name is None or any(isinstance(arg, ast.Starred) for arg in call.args): + return written + if name in _IN_PLACE_NUMPY_FUNCTIONS: + return [*written, *call.args[:1]] + if name.endswith(".at") and isinstance(_numpy_object(name[:-3]), np.ufunc): + return [*written, *call.args[:1]] + outputs = _positional_outputs(name) + return written if outputs is None else [*written, *call.args[outputs]] + + def _check_call(self, node: ast.Call) -> None: + function = node.func + if isinstance(function, ast.Attribute): + if function.attr == "setflags": + write = _keyword(node, "write") + flag = write.value if write is not None else None + if flag is None and node.args: + flag = node.args[0] + if flag is not None and not _is_false_constant(flag): + self._report(node, _MAKES_ARRAY_WRITABLE) + elif function.attr in _IN_PLACE_ARRAY_METHODS: + if self._reaches_series_array(function.value): + self._report(node, _WRITES_THROUGH_SERIES_ARRAY) + for written in self._output_arguments(node): + self._check_written_array(node, written) + + def _check_assigned_target( + self, node: ast.AST, target: ast.expr, value: ast.expr | None + ) -> None: + if isinstance(target, (ast.Tuple, ast.List)): + for element in target.elts: + self._check_assigned_target(node, element, None) + elif isinstance(target, ast.Starred): + self._check_assigned_target(node, target.value, None) + elif isinstance(target, ast.Subscript): + flags = target.value + key = target.slice + if ( + isinstance(flags, ast.Attribute) + and flags.attr == "flags" + and isinstance(key, ast.Constant) + and key.value in ("W", "WRITEABLE") + ): + if value is None or not _is_false_constant(value): + self._report(node, _MAKES_ARRAY_WRITABLE) + elif self._reaches_series_array(target.value): + self._report(node, _WRITES_THROUGH_SERIES_ARRAY) + elif ( + isinstance(target, ast.Attribute) + and target.attr == "writeable" + and isinstance(target.value, ast.Attribute) + and target.value.attr == "flags" + ): + if value is None or not _is_false_constant(value): + self._report(node, _MAKES_ARRAY_WRITABLE) + + def _check_assign(self, node: ast.Assign) -> None: + for target in node.targets: + self._check_assigned_target(node, target, node.value) + + def _check_annotated_assign(self, node: ast.AnnAssign) -> None: + self._check_assigned_target(node, node.target, node.value) + + def _check_augmented_assign(self, node: ast.AugAssign) -> None: + self._check_assigned_target(node, node.target, None) + + def _check_attribute(self, node: ast.Attribute) -> None: + if node.attr in _ALWAYS_PRIVATE_ATTRIBUTES: + self._report(node, _PANDAS_PRIVATE_ATTRIBUTE) + elif node.attr in _FOREIGN_PRIVATE_ATTRIBUTES and not ( + isinstance(node.value, ast.Name) and node.value.id in _OWN_OBJECT_NAMES + ): + self._report(node, _PANDAS_PRIVATE_ATTRIBUTE) + elif node.attr == "copyto": + self._report(node, _NUMPY_COPYTO) + + def _check_import_from(self, node: ast.ImportFrom) -> None: + if node.module is not None and ( + node.module == "numpy" or node.module.startswith("numpy.") + ): + if any(alias.name == "copyto" for alias in node.names): + self._report(node, _NUMPY_COPYTO) + + +def scan_source(source: str, path: str) -> list[Finding]: + """Every refused expression in one module's source.""" + + if not _FILE_TRIGGERS.search(source): + return [] + tree = ast.parse(source, filename=path) + return _Scanner(source, path, tree).scan() + + +def scanned_files(repository: Path) -> list[Path]: + """The Python files the scan reads: ``packages/*/src/`` and ``tools/``.""" + + roots = [*sorted(repository.glob("packages/*/src")), repository / "tools"] + files: list[Path] = [] + for root in roots: + for path in sorted(root.rglob("*.py")): + parts = path.relative_to(root).parts[:-1] + if any(part == "node_modules" or part.startswith(".") for part in parts): + continue + files.append(path) + return files + + +@dataclass(frozen=True) +class _WorkspaceScan: + paths: frozenset[str] + findings: tuple[Finding, ...] + + +@pytest.fixture(scope="module") +def workspace_scan() -> _WorkspaceScan: + paths: set[str] = set() + findings: list[Finding] = [] + for path in scanned_files(_REPOSITORY): + relative = path.relative_to(_REPOSITORY).as_posix() + paths.add(relative) + findings.extend(scan_source(path.read_text(encoding="utf-8"), relative)) + return _WorkspaceScan(frozenset(paths), tuple(findings)) + + +def test_the_scanned_source_has_no_unprotected_buffer_writes( + workspace_scan: _WorkspaceScan, +) -> None: + unreviewed = [ + finding + for finding in workspace_scan.findings + if finding.key not in _REVIEWED_FINDINGS + ] + + assert not unreviewed, ( + "These expressions can write into memory that frames share under " + "pandas copy-on-write (see this module's docstring for each rule). " + "Write through pandas instead (.loc, column assignment), or copy the " + "array first (np.array(values, copy=True)). A finding that cannot " + "write into memory a pandas object shares goes in " + "_REVIEWED_FINDINGS with the reason.\n" + + "\n".join(finding.describe() for finding in unreviewed) + ) + + +def test_every_reviewed_finding_still_occurs(workspace_scan: _WorkspaceScan) -> None: + present = {finding.key for finding in workspace_scan.findings} + + assert not sorted(set(_REVIEWED_FINDINGS) - present) + + +def test_the_scan_covers_every_package_and_the_us_frame_building_code( + workspace_scan: _WorkspaceScan, +) -> None: + packages_with_source = { + directory.name + for directory in (_REPOSITORY / "packages").iterdir() + if (directory / "src").is_dir() + } + scanned_packages = { + path.split("/")[1] + for path in workspace_scan.paths + if path.startswith("packages/") + } + + assert scanned_packages == packages_with_source + assert { + "packages/microcosm-frame/src/microcosm/frame/bundle.py", + "packages/microcosm-build/src/microcosm/build/frame_checkpoint.py", + "packages/microcosm-build/src/microcosm/build/us_runtime/acs_transfer.py", + "packages/microcosm-build/src/microcosm/build/us_runtime/stacked_spine.py", + "tools/build_us_fiscal_refresh_release.py", + "tools/build_us_multispine_pool.py", + } <= workspace_scan.paths + + +def test_the_scan_skips_node_modules_and_hidden_directories(tmp_path: Path) -> None: + for relative in ( + "packages/microcosm-example/src/microcosm/example/module.py", + "packages/microcosm-example/tests/test_module.py", + "tools/tool.py", + "tools/route_a/helper.py", + "tools/orrery-contract/node_modules/node-gyp/gyp/pylib/gyp/input.py", + "tools/.cache/generated.py", + ): + (tmp_path / relative).parent.mkdir(parents=True, exist_ok=True) + (tmp_path / relative).write_text("", encoding="utf-8") + + scanned = [ + path.relative_to(tmp_path).as_posix() for path in scanned_files(tmp_path) + ] + + assert scanned == [ + "packages/microcosm-example/src/microcosm/example/module.py", + "tools/route_a/helper.py", + "tools/tool.py", + ] + + +_NUMPY = "import numpy as np\n" + +#: Snippets the scan must refuse, with the one rule each must report. +_REFUSED_SNIPPETS = { + "setflags_write_true": ( + "values = series.to_numpy()\nvalues.setflags(write=True)\nvalues[0] = 1.0\n", + _MAKES_ARRAY_WRITABLE, + ), + "setflags_positional": ("values.setflags(True)\n", _MAKES_ARRAY_WRITABLE), + "setflags_variable": ("values.setflags(write=flag)\n", _MAKES_ARRAY_WRITABLE), + "flags_writeable_attribute": ( + "values.flags.writeable = True\n", + _MAKES_ARRAY_WRITABLE, + ), + "flags_writeable_key": ( + 'values.flags["WRITEABLE"] = True\n', + _MAKES_ARRAY_WRITABLE, + ), + "flags_w_key": ('values.flags["W"] = 1\n', _MAKES_ARRAY_WRITABLE), + "series_array_item": ( + 'frame.person["income"].array[0] = 1.0\n', + _WRITES_THROUGH_SERIES_ARRAY, + ), + "series_array_slice_augmented": ( + "series.array[mask] += 1\n", + _WRITES_THROUGH_SERIES_ARRAY, + ), + "series_array_annotated": ( + "series.array[0]: float = 1.0\n", + _WRITES_THROUGH_SERIES_ARRAY, + ), + "series_array_unpacked": ( + "series.array[0], other = 1.0, 2.0\n", + _WRITES_THROUGH_SERIES_ARRAY, + ), + "series_array_setitem_call": ( + "series.array.__setitem__(0, 1.0)\n", + _WRITES_THROUGH_SERIES_ARRAY, + ), + "index_array_item": ("table.index.array[0] = 7\n", _WRITES_THROUGH_SERIES_ARRAY), + "series_array_through_asarray": ( + _NUMPY + + "def zero_first(series):\n" + + " values = np.asarray(series.array)\n" + + " values[0] = 0.0\n", + _WRITES_THROUGH_SERIES_ARRAY, + ), + "series_array_through_to_numpy": ( + "series.array.to_numpy()[0] = 1.0\n", + _WRITES_THROUGH_SERIES_ARRAY, + ), + "series_array_through_alias_chain": ( + "def zero_first(series):\n" + + " backing = series.array\n" + + " values = backing\n" + + " values[0] = 0.0\n", + _WRITES_THROUGH_SERIES_ARRAY, + ), + "series_array_fill": ( + _NUMPY + "np.asarray(series.array).fill(0)\n", + _WRITES_THROUGH_SERIES_ARRAY, + ), + "series_array_sort": ( + _NUMPY + "np.asarray(series.array).sort()\n", + _WRITES_THROUGH_SERIES_ARRAY, + ), + "series_array_reshaped_view": ( + "series.array.reshape(-1)[0] = 1.0\n", + _WRITES_THROUGH_SERIES_ARRAY, + ), + "series_array_as_out": ( + _NUMPY + "np.add(series.array, 1, out=series.array)\n", + _WRITES_THROUGH_SERIES_ARRAY, + ), + "series_array_in_place_function": ( + _NUMPY + "np.putmask(np.asarray(series.array), mask, 0)\n", + _WRITES_THROUGH_SERIES_ARRAY, + ), + "series_array_no_copy_array": ( + _NUMPY + "np.array(series.array, copy=False)[0] = 1\n", + _WRITES_THROUGH_SERIES_ARRAY, + ), + "ndarray_attribute": ( + "values = series.array._ndarray\n", + _PANDAS_PRIVATE_ATTRIBUTE, + ), + "manager_attribute": ("blocks = frame._mgr.blocks\n", _PANDAS_PRIVATE_ATTRIBUTE), + "manager_attribute_on_self": ( + "class Table:\n def blocks(self):\n return self._mgr.blocks\n", + _PANDAS_PRIVATE_ATTRIBUTE, + ), + "series_values_attribute": ( + "raw = series._values\n", + _PANDAS_PRIVATE_ATTRIBUTE, + ), + "masked_data": ("raw = series.array._data\n", _PANDAS_PRIVATE_ATTRIBUTE), + "masked_mask": ("series.array._mask[:] = False\n", _PANDAS_PRIVATE_ATTRIBUTE), + "categorical_codes": ( + "codes = series.cat.codes.array._codes\n", + _PANDAS_PRIVATE_ATTRIBUTE, + ), + "copyto": (_NUMPY + "np.copyto(target, source)\n", _NUMPY_COPYTO), + "copyto_through_numpy": ( + "import numpy\nnumpy.copyto(target, source)\n", + _NUMPY_COPYTO, + ), + "copyto_imported": ( + "from numpy import copyto\ncopyto(target, source)\n", + _NUMPY_COPYTO, + ), + "copyto_imported_as_alias": ( + "from numpy import copyto as overwrite\n", + _NUMPY_COPYTO, + ), + "copyto_passed_as_function": ( + "apply_each(np.copyto, pairs)\n", + _NUMPY_COPYTO, + ), + "out_parameter": ( + _NUMPY + "def add_one(values):\n np.add(values, 1, out=values)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_attribute": ( + _NUMPY + "np.multiply(scale, 2, out=self.buffer)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_to_numpy": ( + _NUMPY + "np.add(scale, 1, out=series.to_numpy())\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_method_call": ( + "def clip_in_place(values):\n values.clip(0, 1, out=values)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_rebound_to_existing": ( + _NUMPY + + "def add_one(series):\n" + + " buffer = np.zeros(3)\n" + + " buffer = series.to_numpy()\n" + + " np.add(buffer, 1, out=buffer)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_slice_of_existing": ( + _NUMPY + + "def add_one(series):\n" + + " buffer = series.to_numpy()\n" + + " buffer = buffer[1:]\n" + + " np.add(buffer, 1, out=buffer)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_slice_of_parameter": ( + _NUMPY + + "def add_one(values):\n" + + " values = values[1:]\n" + + " np.add(values, 1, out=values)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_tuple": ( + _NUMPY + "def split(left, right):\n np.divmod(7, 2, out=(left, right))\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_positional_ufunc": ( + _NUMPY + "def add_one(values):\n np.add(values, 1, values)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_positional_function": ( + _NUMPY + + "def running(values, totals):\n np.cumsum(values, 0, None, totals)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_from_imported_ufunc": ( + "from numpy import add\ndef add_one(values):\n add(values, 1, values)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "ufunc_at": ( + _NUMPY + "def count(values):\n np.add.at(values, [0], 1)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "ufunc_at_imported": ( + "from numpy import add\ndef count(values):\n add.at(values, [0], 1)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "ufunc_at_on_to_numpy": ( + _NUMPY + "np.maximum.at(series.to_numpy(), positions, values)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "numpy_put": ( + _NUMPY + "def set_first(values):\n np.put(values, [0], 1)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "numpy_fill_diagonal": ( + _NUMPY + "def clear(matrix):\n np.fill_diagonal(matrix, 0)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "numpy_random_shuffle": ( + _NUMPY + "def mix(values):\n np.random.shuffle(values)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_module_array_from_function": ( + _NUMPY + "buffer = np.zeros(3)\ndef add_one():\n np.add(1, 1, out=buffer)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_global_declared": ( + _NUMPY + + "def add_one():\n" + + " global buffer\n" + + " buffer = np.zeros(3)\n" + + " np.add(1, 1, out=buffer)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_loop_target": ( + _NUMPY + + "def add_one(arrays):\n" + + " for buffer in arrays:\n" + + " np.add(buffer, 1, out=buffer)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_comprehension_target": ( + _NUMPY + "def add_one(arrays):\n [np.add(a, 1, out=a) for a in arrays]\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_lambda_parameter": ( + _NUMPY + "add_one = lambda values: np.add(values, 1, out=values)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_shallow_copy": ( + _NUMPY + + "def add_one(table):\n" + + " shallow = table.copy(deep=False)\n" + + " np.add(1, 1, out=shallow)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_positional_shallow_copy": ( + _NUMPY + + "def add_one(table):\n" + + " shallow = table.copy(False)\n" + + " np.add(1, 1, out=shallow)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_array_without_copy": ( + _NUMPY + + "def add_one(values):\n" + + " view = np.array(values, copy=None)\n" + + " np.add(view, 1, out=view)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_concatenate_into_existing": ( + _NUMPY + + "def join(parts, existing):\n" + + " joined = np.concatenate(parts, out=existing)\n" + + " np.add(joined, 1, out=joined)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_one_branch_existing": ( + _NUMPY + + "def add_one(values, fresh):\n" + + " buffer = np.zeros(3) if fresh else values\n" + + " np.add(buffer, 1, out=buffer)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_with_target": ( + _NUMPY + + "def add_one(opener):\n" + + " with opener() as buffer:\n" + + " np.add(buffer, 1, out=buffer)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_array_method_on_parameter": ( + "def running(values):\n values.cumsum(out=values)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_either_operand": ( + _NUMPY + + "def add_one(given):\n" + + " buffer = given or np.zeros(3)\n" + + " np.add(buffer, 1, out=buffer)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_ufunc_result_with_output": ( + _NUMPY + + "def add_one(values, existing):\n" + + " total = np.add(values, 1, existing)\n" + + " np.add(total, 1, out=total)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), +} + + +@pytest.mark.parametrize( + ("source", "rule"), list(_REFUSED_SNIPPETS.values()), ids=list(_REFUSED_SNIPPETS) +) +def test_the_scanner_refuses_each_unprotected_write(source: str, rule: str) -> None: + findings = scan_source(source, "snippet.py") + + assert {finding.rule for finding in findings} == {rule}, findings + + +#: Snippets the scan must accept: reads, read-only flags, and writes into +#: arrays the same function created. +_ACCEPTED_SNIPPETS = { + "setflags_read_only": "values.setflags(write=False)\nvalues.setflags(write=0)\n", + "setflags_alignment_only": "values.setflags(align=True)\n", + "flags_read_only": ( + 'values.flags.writeable = False\nvalues.flags["WRITEABLE"] = False\n' + ), + "out_new_array_inline": ( + _NUMPY + + "share = np.divide(part, total, out=np.zeros_like(part), where=total > 0)\n" + ), + "out_new_array_slice": ( + _NUMPY + + "def running(weights):\n" + + " totals = np.empty(len(weights) + 1)\n" + + " totals[0] = 0.0\n" + + " np.cumsum(weights, out=totals[1:])\n" + ), + "out_deep_copy": ( + _NUMPY + + "def accumulate(first, later):\n" + + " total = first.copy()\n" + + " np.add(total, later, out=total)\n" + ), + "out_deep_copy_in_order": ( + _NUMPY + + "def accumulate(first, later):\n" + + " total = first.copy('C')\n" + + " np.add(total, later, out=total)\n" + ), + "out_same_array_as_input": ( + _NUMPY + + "def capped(count):\n" + + " draws = np.empty(count)\n" + + " np.minimum(draws, 1.0, out=draws)\n" + + " return draws\n" + ), + "out_chained_and_conditional_names": ( + _NUMPY + + "def add_one(values, wide):\n" + + " first = second = np.zeros(3)\n" + + " alias = second\n" + + " chosen = np.ones(3) if wide else alias\n" + + " chosen += 1\n" + + " np.add(values, 1, out=chosen)\n" + + " np.add(values, 1, out=first)\n" + ), + "out_array_with_copy": ( + _NUMPY + + "def add_one(values):\n" + + " owned = np.array(values)\n" + + " copied = np.array(values, copy=True)\n" + + " np.add(owned, 1, out=owned)\n" + + " np.add(copied, 1, out=copied)\n" + ), + "out_none": _NUMPY + "np.add(left, right, out=None)\n", + "ufunc_at_new_array": ( + _NUMPY + + "def count(positions, size):\n" + + " counts = np.zeros(size, dtype=np.int64)\n" + + " np.add.at(counts, positions, 1)\n" + ), + "in_place_function_new_array": ( + _NUMPY + + "def clear(size):\n" + + " matrix = np.ones((size, size))\n" + + " np.fill_diagonal(matrix, 0)\n" + ), + "ufunc_without_out": _NUMPY + "total = np.add(left, right)\n", + "array_function_not_attribute": ( + _NUMPY + + "import pandas as pd\n" + + "values = np.array(series)\n" + + "values[0] = 1\n" + + "codes = pd.array([1, 2])\n" + + "codes[0] = 3\n" + ), + "series_array_reads": ( + "for value in series.array:\n" + + " total += value\n" + + "index = pd.Index(series.array, name='id')\n" + + "first = series.array[0]\n" + ), + "series_array_deep_copy_written": ( + "values = series.array.to_numpy(copy=True)\nvalues[0] = 1\n" + ), + "own_private_state": ( + "class Catalog:\n" + + " def add(self, key, value):\n" + + " self._values[key] = value\n" + + " self._data.append(value)\n" + + " @classmethod\n" + + " def empty(cls):\n" + + " return cls._mask\n" + ), + "subscript_write_into_new_array": ( + _NUMPY + "def flags(size):\n marks = np.zeros(size)\n marks[0] = 1\n" + ), + "out_keyword_of_workspace_functions": ( + "launch(pool_manifest=manifest, out=args.out)\n" + + "report.write(rows, out=destination)\n" + ), + "none_placeholder_then_copy": ( + _NUMPY + + "def accumulate(slices):\n" + + " total: np.ndarray | None = None\n" + + " for current in slices:\n" + + " if total is None:\n" + + " total = current.copy()\n" + + " else:\n" + + " np.add(total, current, out=total)\n" + ), + "list_display_shuffled": ( + _NUMPY + + "def sizes(draws):\n" + + " values: list[float] = []\n" + + " values.extend(draws)\n" + + " values = values[:3]\n" + + " np.random.shuffle(values)\n" + ), + "where_ufunc_arithmetic_and_comparison_results": ( + _NUMPY + + "def totals(positions, values, mask, left, right):\n" + + " out = np.zeros(3)\n" + + " np.add.at(out, positions, values)\n" + + " out = np.where(mask, out, 0.0)\n" + + " np.multiply(out, 2, out=out)\n" + + " scaled = np.exp(values)\n" + + " np.multiply(scaled, 2, out=scaled)\n" + + " total = left + right\n" + + " np.add(total, 1, out=total)\n" + + " positive = left > 0\n" + + " np.logical_not(positive, out=positive)\n" + ), +} + + +@pytest.mark.parametrize( + "source", list(_ACCEPTED_SNIPPETS.values()), ids=list(_ACCEPTED_SNIPPETS) +) +def test_the_scanner_accepts_reads_and_writes_into_new_arrays(source: str) -> None: + assert scan_source(source, "snippet.py") == [] + + +def test_a_finding_names_its_file_line_and_function() -> None: + source = ( + _NUMPY + + "class Aggregator:\n" + + " def add(self, values):\n" + + " def inner(target):\n" + + " np.add(target, 1, out=target)\n" + + " inner(values)\n" + ) + + (finding,) = scan_source(source, "pkg/module.py") + + assert finding.describe() == ( + "pkg/module.py:5 in Aggregator.add.inner: writes-into-existing-array: " + "np.add(target, 1, out=target)" + ) From 34d287221ac65aa35b9b2fe559a3e10e78751f50 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:25:02 +0400 Subject: [PATCH 02/15] Fix review findings in Frame._adopt and the shared-buffer write scan Frame._adopt now raises TypeError for a table that is not a DataFrame. On pandas 2.x, the copy-on-write check also requires the block data manager, as pandas' own check does. The _adopt docstring lists the extension types whose to_numpy() and .values are writable shared views, and says the check is made when a frame is built. The frame tests use object-dtype strata, so the strata memory checks can fail, and turn copy-on-write on when they run under pandas 2.x. The scan now also refuses: - augmented assignment to a name bound to a writable view; - writes through .base and .asi8, astype(copy=False) and fillna(copy=False); - np.put_along_axis, np.nan_to_num(copy=False), .shuffle methods and Generator methods given out=; - NumPy functions reached through a local alias. It follows views through containers, unpacking, loop and with targets, `or` and NumPy view functions. It treats an item of a container or of a .copy() as not new, and treats comprehension targets and decorators in their own scopes. np.diff(x, 0) returns its input, so diff left the list of allocating functions. The per-statement text filter now also matches `flags` and dots split by a backslash continuation. Reviewed exemptions are keyed on a digest of the enclosing function's source, so any change to that function needs a new review. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/frame/bundle.py | 75 +- .../shared/test_frame_table_sharing.py | 71 +- .../shared/test_shared_buffer_writes.py | 1356 ++++++++++++----- 3 files changed, 1084 insertions(+), 418 deletions(-) diff --git a/packages/microcosm-frame/src/microcosm/frame/bundle.py b/packages/microcosm-frame/src/microcosm/frame/bundle.py index ad9fb20089..6f62aa0efe 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -27,6 +27,7 @@ and deep-copy when it is off (see :meth:`Frame._adopt`). """ +import warnings from collections.abc import Mapping from dataclasses import dataclass from typing import Any @@ -141,19 +142,29 @@ def _adopt( 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. Raw writes into the shared memory (through ``Series.array``, - private pandas attributes, an array made writable, ``np.copyto`` or - ``out=``) are never protected; ``test_shared_buffer_writes.py`` - refuses them in the workspace's source. + frame. + + Copy-on-write does not protect raw writes into the shared memory: + through ``Series.array``, private pandas attributes, an array made + writable, ``ufunc.at``, ``np.copyto`` or ``out=`` + (``test_shared_buffer_writes.py`` refuses these in the workspace's + source), and through the arrays that ``to_numpy()`` and ``.values`` + return for extension-typed columns, which are writable views: + ``Int64``, ``Float64``, ``boolean``, ``category`` and python-backed + strings. 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. + 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. Weights are stored as given - (their arrays are read-only), and the strata are shallow-copied when - copy-on-write is on. + checked and the same errors are raised, except that a table that is + not a DataFrame raises ``TypeError`` (the constructor fails on its + ``copy()`` call). 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. @@ -168,8 +179,9 @@ def _adopt( A new validated frame that owns ``tables``. Raises: - TypeError, ValueError: Exactly as the constructor would on the - same arguments. + 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) @@ -181,6 +193,7 @@ def _adopt( mass_log=mass_log, metadata=metadata, copy_data=not _pandas_copy_on_write(), + require_dataframes=True, ) return frame @@ -194,12 +207,15 @@ def _assemble( 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). + 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 @@ -208,6 +224,8 @@ def _assemble( 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() if copy_data else frame @@ -926,12 +944,7 @@ def replace_tables(self, /, **changed_tables: pd.DataFrame) -> "Frame": example, the weights or strata no longer align with them). """ - for name, table in changed_tables.items(): - if not isinstance(table, pd.DataFrame): - raise TypeError( - f"Table {name!r} must be a pandas DataFrame, got " - f"{type(table).__name__}." - ) + _require_dataframes(changed_tables) tables = { name: table.copy(deep=False) for name, table in {**self._tables, **self._link_tables}.items() @@ -1518,17 +1531,37 @@ 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 3 always has copy-on-write on and deprecates its option, so the - option is read only under pandas 2.x, where it is ``True`` only when - copy-on-write is enabled (it is ``False`` by default, or ``"warn"``). + pandas 3 always has copy-on-write on and deprecates its options, so they + are read only under pandas 2.x. There, as in pandas' own check, + copy-on-write is on only when ``mode.copy_on_write`` is ``True`` (it is + ``False`` by default, or ``"warn"``) and ``mode.data_manager`` is + ``"block"``. """ if int(pd.__version__.split(".", 1)[0]) >= 3: return True - return pd.get_option("mode.copy_on_write") is True + if pd.get_option("mode.copy_on_write") is not True: + return False + with warnings.catch_warnings(): + # pandas 2.x deprecates the data_manager option. + warnings.simplefilter("ignore", category=DeprecationWarning) + warnings.simplefilter("ignore", category=FutureWarning) + try: + return pd.get_option("mode.data_manager") == "block" + except pd.errors.OptionError: + return True @dataclass(frozen=True) 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 016da4f262..1fe07c6b3e 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 @@ -11,7 +11,7 @@ path, because pandas 3 always has copy-on-write on. """ -from collections.abc import Callable +from collections.abc import Callable, Iterator from typing import Any import numpy as np @@ -79,7 +79,9 @@ def _source_weights() -> dict[str, Weights]: def _source_strata() -> pd.Series: - return pd.Series(["cps", "cps", "puf", "puf"], index=pd.RangeIndex(4)) + # Object dtype, as the frame's default strata: ``to_numpy()`` then returns + # a view of the stored array, so memory sharing can be checked. + return pd.Series(["cps", "cps", "puf", "puf"], index=pd.RangeIndex(4), dtype=object) @pytest.fixture @@ -100,6 +102,17 @@ def source_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.""" @@ -149,11 +162,26 @@ def test_constructor_deep_copies_every_table(self) -> None: class TestAdopt: def test_adopt_stores_the_given_tables_without_copying(self) -> None: tables = _source_tables() - frame = Frame._adopt(tables, _SCHEMA, _source_weights(), _source_strata()) + strata = _source_strata() + frame = Frame._adopt(tables, _SCHEMA, _source_weights(), strata) for name, table in _tables_of(frame).items(): assert table is tables[name] assert frame.links == ("jobs",) + assert frame.strata is not strata + assert np.shares_memory(frame.strata.to_numpy(), strata.to_numpy()) + + @pytest.mark.parametrize("copy_on_write", [True, False], ids=["cow_on", "cow_off"]) + def test_adopt_refuses_a_table_that_is_not_a_dataframe( + self, monkeypatch: pytest.MonkeyPatch, copy_on_write: bool + ) -> None: + monkeypatch.setattr( + bundle_module, "_pandas_copy_on_write", lambda: copy_on_write + ) + 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()) def test_adopt_deep_copies_when_copy_on_write_is_off( self, copy_on_write_off: None @@ -529,15 +557,40 @@ def refuse_option_reads(name: str) -> object: assert bundle_module._pandas_copy_on_write() is True @pytest.mark.parametrize( - ("option_value", "expected"), - [(True, True), (False, False), ("warn", False)], - ids=["enabled", "disabled", "warn_mode"], + ("copy_on_write", "data_manager", "expected"), + [ + (True, "block", True), + (False, "block", False), + ("warn", "block", False), + (True, "array", False), + ], + ids=["enabled", "disabled", "warn_mode", "array_manager"], ) - def test_pandas_2_reads_the_copy_on_write_option( - self, monkeypatch: pytest.MonkeyPatch, option_value: object, expected: bool + def test_pandas_2_reads_the_copy_on_write_and_data_manager_options( + self, + monkeypatch: pytest.MonkeyPatch, + copy_on_write: object, + data_manager: str, + expected: bool, ) -> None: - options = {"mode.copy_on_write": option_value} + options = { + "mode.copy_on_write": copy_on_write, + "mode.data_manager": data_manager, + } monkeypatch.setattr(bundle_module.pd, "__version__", "2.3.3") monkeypatch.setattr(bundle_module.pd, "get_option", options.__getitem__) assert bundle_module._pandas_copy_on_write() is expected + + def test_pandas_2_without_a_data_manager_option_uses_copy_on_write( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + def read_option(name: str) -> object: + if name == "mode.copy_on_write": + return True + raise pd.errors.OptionError(f"No such keys(s): {name!r}") + + monkeypatch.setattr(bundle_module.pd, "__version__", "2.3.3") + monkeypatch.setattr(bundle_module.pd, "get_option", read_option) + + assert bundle_module._pandas_copy_on_write() is True 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 31f99d0278..176d8fe961 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 @@ -14,42 +14,51 @@ ``flags.writeable``, ``flags["W"]`` or ``flags["WRITEABLE"]``. The arrays ``to_numpy()`` and ``.values`` return for NumPy-typed columns are read-only views of the shared memory; this makes them writable. -``writes-through-series-array`` - A write into ``.array`` (of a Series or Index): item assignment, - ``__setitem__``, ``fill``, ``sort``, ``put`` and the other in-place - ndarray methods, ``out=``, or the in-place NumPy functions below. It - counts when the written expression reaches ``.array`` through indexing, - ``np.asarray`` and the other NumPy view functions, ``to_numpy()`` and - the other view methods, or a name the same function binds to such an - expression. ``ser.array`` is writable for float, integer and boolean - columns, and so are ``np.asarray(ser.array)`` and - ``ser.array.to_numpy()``. +``writes-through-writable-view`` + A write into a writable view of pandas' memory: ``.array`` (of a Series + or Index), ``.base`` (the writable array behind a read-only view) or + ``.asi8`` (datetime data). Writes are item assignment, augmented + assignment, ``__setitem__``, ``fill``, ``sort`` and the other in-place + ndarray methods, ``fillna(copy=False)``, ``out=``, ``shuffle`` and the + in-place NumPy functions below. It counts when the written expression + reaches the view through indexing, ``np.asarray``, ``np.flip`` and the + other NumPy view functions, ``to_numpy()``, ``astype(copy=False)`` and + the other view methods, a list, tuple, set or dict holding it, ``or`` + and conditional expressions, or a name the same function binds to any + of these (by assignment, unpacking, a ``for`` loop or a ``with`` + statement). Workspace classes' own ``self.array`` is exempt. ``pandas-private-attribute`` - ``._ndarray`` or ``._mgr`` on anything, and ``._values``, ``._data``, + ``._ndarray``, ``._mgr``, ``._get_column_array`` or + ``._iter_column_arrays`` on anything, and ``._values``, ``._data``, ``._mask`` or ``._codes`` on anything but ``self`` or ``cls``. These reach pandas' internal arrays, which are always writable. ``numpy-copyto`` Any use of ``numpy.copyto``. ``writes-into-existing-array`` - ``out=`` given to a NumPy function, ufunc or ndarray method (by keyword, - or by position for NumPy functions and ufuncs), the first argument of - ``numpy..at`` (which writes even into a read-only array), and the - first argument of ``numpy.put``, ``numpy.putmask``, ``numpy.place``, - ``numpy.fill_diagonal`` and ``numpy.random.shuffle``, unless the array - was created in the same function. Created means one of: the result of a - ufunc or of a NumPy function that always allocates + A write into an array the same function did not create: + ``out=`` given to a NumPy function, ufunc, ndarray method or NumPy random + ``Generator`` method (by keyword, or by position for NumPy functions and + ufuncs), the first argument of ``numpy..at`` (which writes even + into a read-only array), the first argument of ``numpy.put``, + ``numpy.putmask``, ``numpy.place``, ``numpy.put_along_axis``, + ``numpy.fill_diagonal``, ``numpy.random.shuffle``, any ``.shuffle`` + method and ``numpy.nan_to_num(copy=False)``. NumPy functions are also + followed through a local name bound to them (``plus = np.add``). + Created means one of: the result of a ufunc, a ``numpy.random`` function + or a NumPy function that always allocates (``_ALLOCATING_NUMPY_FUNCTIONS``: ``np.zeros``, ``np.where``, ``np.concatenate``, ...), when not given an output array; ``np.array`` - without ``copy=``; a deep ``.copy()``; arithmetic, a comparison, or a - list, set or dict display; a subscript of one of these; or a local name - whose every binding in the function, other than to ``None``, is one of - these. + without ``copy=``; ``to_numpy(copy=True)``; a subscript of one of these; + a ``.copy()``, arithmetic, a comparison, ``list(...)`` and the other + container builtins, or a list, set or dict display (a slice of these is + new, an item is not, because a shallow copy or a container shares its + items); or a local name whose every binding in the function, other than + to ``None``, is one of these. ``setflags``, ``Series.array[i] = value``, ``._ndarray``, ``._mgr``, ``np.copyto`` and ``out=`` are the writes first identified as unprotected. -``ufunc.at``, the other in-place NumPy functions and methods, the other -writes through ``.array``, and the other private attributes were added after -checking that they write into shared memory too. +The other rules, views, functions and methods were added after checking that +they write into shared memory too. Scope: every Python file under ``packages/*/src/`` (the source of every workspace package, including microcosm-frame and the microcosm-build code that @@ -57,11 +66,16 @@ except files in ``node_modules`` or hidden directories. Tests and ``test_support/`` are not scanned. -What source reading cannot see: the arrays ``to_numpy()`` and ``.values`` -return for nullable extension types (``Int64``, ``boolean``, ``Float64``) -are writable views of the shared memory, and a pandas object built with -``copy=False`` over another object's array writes into it when it is written -through pandas. Neither is refused here. +What source reading cannot see, so is not refused here: + +- the arrays ``to_numpy()`` and ``.values`` return for extension-typed + columns (``Int64``, ``Float64``, ``boolean``, ``category``, python-backed + strings) are writable views of the shared memory; +- a pandas object built with ``copy=False`` over another object's array + writes into it when it is written through pandas; +- names reached dynamically (``getattr(np, name)``, ``**{"out": array}``, + ``*arguments``), positional ``out`` given to ndarray methods, writes + through closures, and items of a container a function did not build. A finding that cannot write into memory a pandas object shares goes in ``_REVIEWED_FINDINGS`` with the reason. @@ -72,10 +86,11 @@ import ast import bisect import functools +import hashlib import inspect import re from collections import defaultdict -from collections.abc import Iterable, Iterator +from collections.abc import Iterable, Iterator, Mapping from dataclasses import dataclass from pathlib import Path @@ -88,15 +103,17 @@ #: Reviewed findings that cannot write into memory a pandas object shares, #: keyed by (repository-relative path, enclosing function, rule, the -#: expression's source as a failure reports it), with the reason. The -#: function is ``Class.method`` or ``outer.inner``, or ```` for -#: module-level code. A changed expression needs a new review. -_REVIEWED_FINDINGS: dict[tuple[str, str, str, str], str] = { +#: expression's source, a digest of the enclosing function's source) as a +#: failure prints it, with the reason. The function is ``Class.method`` or +#: ``outer.inner``, or ```` for module-level code. Any change to the +#: enclosing function changes the digest and needs a new review. +_REVIEWED_FINDINGS: dict[tuple[str, str, str, str, str], str] = { ( "packages/microcosm-build/src/microcosm/build/uk_runtime/frs_relationships.py", "derive_frs_relationships", "writes-into-existing-array", "np.fill_diagonal(matrix, 0)", + "f439ecc6ea13", ): ( "np.fill_diagonal writes into matrix = grid[rows][:, columns]; indexing " "with integer arrays returns a new array, and grid is to_numpy() of a " @@ -107,6 +124,7 @@ "_pre_split_household_weights", "writes-into-existing-array", "np.add.at(weights, lineage.root_positions, weights[lineage.copy_positions])", + "6cc4521d9bc0", ): ( "np.add.at writes into the array _pre_clone_household_weights returns, " "which _pre_residential_household_weights creates with " @@ -115,20 +133,25 @@ } _MAKES_ARRAY_WRITABLE = "makes-array-writable" -_WRITES_THROUGH_SERIES_ARRAY = "writes-through-series-array" +_WRITES_THROUGH_WRITABLE_VIEW = "writes-through-writable-view" _PANDAS_PRIVATE_ATTRIBUTE = "pandas-private-attribute" _NUMPY_COPYTO = "numpy-copyto" _WRITES_INTO_EXISTING_ARRAY = "writes-into-existing-array" #: Private attributes refused on any object. -_ALWAYS_PRIVATE_ATTRIBUTES = frozenset({"_ndarray", "_mgr"}) +_ALWAYS_PRIVATE_ATTRIBUTES = frozenset( + {"_ndarray", "_mgr", "_get_column_array", "_iter_column_arrays"} +) #: Private attributes refused unless read from ``self`` or ``cls``, because #: workspace classes use the same names for their own state. _FOREIGN_PRIVATE_ATTRIBUTES = frozenset({"_values", "_data", "_mask", "_codes"}) _OWN_OBJECT_NAMES = frozenset({"self", "cls"}) +#: Attributes that return a writable view of pandas' memory. +_WRITABLE_VIEW_ATTRIBUTES = frozenset({"array", "base", "asi8"}) + #: NumPy functions whose result is always a new array (unless given ``out=``). -#: A ufunc's result is new too. +#: A ufunc's result and a ``numpy.random`` function's result are new too. _ALLOCATING_NUMPY_FUNCTIONS = frozenset( f"numpy.{name}" for name in ( @@ -140,11 +163,12 @@ "searchsorted", "isin", "bincount", - "diff", "cumsum", "cumprod", "clip", "take", + "round", + "around", "flatnonzero", "outer", "dot", @@ -171,22 +195,29 @@ ) ) -#: Expressions whose value is always a new object: arithmetic, comparisons, -#: and list, set and dict displays and comprehensions. -_NEW_OBJECT_EXPRESSIONS = ( - ast.BinOp, - ast.UnaryOp, - ast.Compare, +#: Builtins whose result is a new container (whose items may be shared). +_CONTAINER_BUILTINS = frozenset( + {"list", "dict", "set", "frozenset", "tuple", "sorted", "bytearray"} +) + +#: Expressions whose value is a new array: arithmetic and comparisons. +_NEW_VALUE_EXPRESSIONS = (ast.BinOp, ast.UnaryOp, ast.Compare) +#: Displays and comprehensions: a new container whose items may be shared. +_CONTAINER_EXPRESSIONS = ( ast.List, ast.ListComp, + ast.Tuple, ast.Set, ast.SetComp, ast.Dict, ast.DictComp, + ast.GeneratorExp, ) +_COMPREHENSIONS = (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp) -#: ndarray methods that take an ``out`` array. -_ARRAY_METHODS_WITH_OUT = frozenset( +#: ndarray methods and NumPy random Generator methods that take an ``out`` +#: array. +_METHODS_WITH_OUT = frozenset( { "all", "any", @@ -208,6 +239,11 @@ "take", "trace", "var", + "random", + "standard_normal", + "standard_exponential", + "standard_gamma", + "permuted", } ) @@ -217,6 +253,7 @@ "numpy.put", "numpy.putmask", "numpy.place", + "numpy.put_along_axis", "numpy.fill_diagonal", "numpy.random.shuffle", } @@ -233,11 +270,10 @@ "resize", "itemset", "setfield", - "byteswap", } ) -#: NumPy functions that can return a view of their first argument. +#: NumPy functions that can return a view of an argument. _VIEW_NUMPY_FUNCTIONS = frozenset( f"numpy.{name}" for name in ( @@ -253,6 +289,17 @@ "atleast_2d", "atleast_3d", "frombuffer", + "flip", + "fliplr", + "flipud", + "rot90", + "moveaxis", + "swapaxes", + "rollaxis", + "expand_dims", + "real", + "imag", + "lib.stride_tricks.as_strided", ) ) @@ -265,6 +312,14 @@ _NESTED_SCOPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda) +#: How new the value of an expression is (higher is newer). +_NOT_NEW = 0 +#: A new object whose items may be shared: a container, or a ``.copy()`` +#: that may be a shallow copy of a container. +_NEW_OBJECT = 1 +#: A new array: every item and view of it is new memory. +_NEW_ARRAY = 2 + @dataclass(frozen=True) class Finding: @@ -275,61 +330,86 @@ class Finding: function: str rule: str code: str + function_digest: str @property - def key(self) -> tuple[str, str, str, str]: - return (self.path, self.function, self.rule, self.code) + def key(self) -> tuple[str, str, str, str, str]: + return (self.path, self.function, self.rule, self.code, self.function_digest) def describe(self) -> str: return f"{self.path}:{self.line} in {self.function}: {self.rule}: {self.code}" +# Bindings ------------------------------------------------------------------ + +#: One binding of a name: the value expression (``None`` when it cannot be +#: followed, as for an import), and whether the name is bound to exactly that +#: value (``False`` when it is bound to a part of it, as a loop target is +#: bound to an item of its iterable). +_Binding = tuple[ast.expr | None, bool] + + class _Scope: """One function, class or module, and the names it binds. The bindings are collected on first use, because most scopes are never - asked. A name maps to the value of each assignment to it; ``None`` stands - for a binding whose value cannot be followed (a loop target, tuple - unpacking, an import, a ``with`` target, ...). + asked. """ def __init__(self, qualified_name: str, node: ast.AST) -> None: self.qualified_name = qualified_name - self._node = node + self.node = node self._parameters: frozenset[str] = frozenset() self._declared_elsewhere: set[str] = set() - self._bindings: defaultdict[str, list[ast.expr | None]] | None = None + self._bindings: defaultdict[str, list[_Binding]] | None = None def child_name(self, name: str) -> str: if self.qualified_name == "": return name return f"{self.qualified_name}.{name}" - def bindings_of(self, name: str) -> list[ast.expr | None] | None: - """The values ``name`` is bound to here, or ``None`` when it is not local. + def bindings_of(self, name: str) -> list[_Binding] | None: + """The bindings of ``name`` here, or ``None`` when it is not local. A parameter, a name declared ``global`` or ``nonlocal``, and a name this scope never binds are not local. """ - if self._bindings is None: - self._bindings = defaultdict(list) - self._collect_bindings() + self._collect() if name in self._parameters or name in self._declared_elsewhere: return None return self._bindings.get(name) or None - def _bind(self, target: ast.expr, value: ast.expr | None) -> None: + def is_parameter(self, name: str) -> bool: + self._collect() + return name in self._parameters + + def _bind(self, target: ast.expr, value: ast.expr | None, exact: bool) -> None: if isinstance(target, ast.Name): - self._bindings[target.id].append(value) + self._bindings[target.id].append((value, exact)) elif isinstance(target, ast.Starred): - self._bind(target.value, None) + self._bind(target.value, value, False) elif isinstance(target, (ast.Tuple, ast.List)): - for element in target.elts: - self._bind(element, None) - - def _collect_bindings(self) -> None: - node = self._node + pairs = ( + exact + and isinstance(value, (ast.Tuple, ast.List)) + and len(value.elts) == len(target.elts) + and not any( + isinstance(element, ast.Starred) + for element in (*target.elts, *value.elts) + ) + ) + for index, element in enumerate(target.elts): + if pairs: + self._bind(element, value.elts[index], True) + else: + self._bind(element, value, False) + + def _collect(self) -> None: + if self._bindings is not None: + return + self._bindings = defaultdict(list) + node = self.node if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)): arguments = node.args self._parameters = frozenset( @@ -347,30 +427,55 @@ def _collect_bindings(self) -> None: for child in _nodes_in_scope(body): if isinstance(child, ast.Assign): for target in child.targets: - self._bind(target, child.value) + self._bind(target, child.value, True) elif isinstance(child, (ast.AnnAssign, ast.NamedExpr)): if child.value is not None: - self._bind(child.target, child.value) + self._bind(child.target, child.value, True) elif isinstance(child, (ast.For, ast.AsyncFor)): - self._bind(child.target, None) + self._bind(child.target, child.iter, False) elif isinstance(child, ast.withitem) and child.optional_vars is not None: - self._bind(child.optional_vars, None) + self._bind(child.optional_vars, child.context_expr, False) elif isinstance(child, ast.ExceptHandler) and child.name: - self._bindings[child.name].append(None) + self._bindings[child.name].append((None, False)) elif isinstance(child, (ast.Import, ast.ImportFrom)): for alias in child.names: bound = alias.asname or alias.name.split(".", 1)[0] - self._bindings[bound].append(None) + self._bindings[bound].append((None, False)) elif isinstance(child, _NESTED_SCOPES) and not isinstance( child, ast.Lambda ): - self._bindings[child.name].append(None) + self._bindings[child.name].append((None, False)) elif isinstance(child, (ast.Global, ast.Nonlocal)): self._declared_elsewhere.update(child.names) elif isinstance(child, (ast.MatchAs, ast.MatchStar)) and child.name: - self._bindings[child.name].append(None) + self._bindings[child.name].append((None, False)) elif isinstance(child, ast.MatchMapping) and child.rest: - self._bindings[child.rest].append(None) + self._bindings[child.rest].append((None, False)) + + +class _ComprehensionScope: + """A comprehension: its loop targets shadow the enclosing scope's names.""" + + def __init__(self, enclosing: _Scope | _ComprehensionScope, node: ast.AST): + self._enclosing = enclosing + self.qualified_name = enclosing.qualified_name + self.node = enclosing.node + self._targets: defaultdict[str, list[_Binding]] = defaultdict(list) + for generator in node.generators: + for name in ast.walk(generator.target): + if isinstance(name, ast.Name): + self._targets[name.id].append((generator.iter, False)) + + def child_name(self, name: str) -> str: + return self._enclosing.child_name(name) + + def bindings_of(self, name: str) -> list[_Binding] | None: + if name in self._targets: + return self._targets[name] + return self._enclosing.bindings_of(name) + + def is_parameter(self, name: str) -> bool: + return name in self._targets or self._enclosing.is_parameter(name) def _nodes_in_scope(roots: Iterable[ast.AST]) -> Iterator[ast.AST]: @@ -407,11 +512,17 @@ def _statements(tree: ast.Module) -> Iterator[ast.AST]: class _NumpyNames: - """The names one module binds to NumPy, to resolve ``np.add.at`` and the like.""" + """The names one module binds to NumPy, to resolve ``np.add.at`` and the like. + + ``derived_names`` are names some statement assigns a NumPy object to + (``plus = np.add``); the scanner follows them through the bindings of + the scope that uses them. + """ def __init__(self, tree: ast.Module) -> None: self._aliases: dict[str, str] = {} - for node in _statements(tree): + statements = list(_statements(tree)) + for node in statements: if isinstance(node, ast.Import): for alias in node.names: if alias.name == "numpy" or alias.name.startswith("numpy."): @@ -429,6 +540,21 @@ def __init__(self, tree: ast.Module) -> None: self._aliases[alias.asname or alias.name] = ( f"{node.module}.{alias.name}" ) + derived: set[str] = set() + for node in statements: + if isinstance(node, (ast.Assign, ast.AnnAssign)) and node.value is not None: + if self.resolve(node.value) is None: + continue + targets = ( + node.targets if isinstance(node, ast.Assign) else [node.target] + ) + for target in targets: + derived.update( + name.id + for name in ast.walk(target) + if isinstance(name, ast.Name) + ) + self.derived_names = frozenset(derived) @property def bound_names(self) -> frozenset[str]: @@ -449,15 +575,20 @@ def resolve(self, expression: ast.expr) -> str | None: return ".".join([root, *reversed(attributes)]) -#: Text found in every refused expression, except NumPy names and writes -#: through a name bound to ``.array``. +# Which statements can hold a finding --------------------------------------- + +#: A dot before an attribute, allowing spaces and backslash continuations. +_DOT = r"\.(?:\s|\\)*" +#: Text found in every refused expression, except NumPy names, names bound to +#: NumPy objects, and writes through a name bound to a writable view. _TRIGGER_TEXT = ( - r"setflags|writeable|WRITEABLE|flags\s*\[|copyto" - r"|\.\s*_(?:ndarray|mgr|values|data|mask|codes)\b|\bout\s*=" + r"setflags|writeable|WRITEABLE|\bflags\b|copyto|shuffle|\bout\s*=" + rf"|{_DOT}_(?:ndarray|mgr|values|data|mask|codes|get_column_array" + r"|iter_column_arrays)\b" ) +_WRITABLE_VIEW_TEXT = re.compile(rf"{_DOT}(?:array|base|asi8)\b") #: A module without any of this text cannot hold a finding and is not parsed. -_FILE_TRIGGERS = re.compile(_TRIGGER_TEXT + r"|numpy|\.\s*array\b") -_ARRAY_ATTRIBUTE = re.compile(r"\.\s*array\b") +_FILE_TRIGGERS = re.compile(rf"{_TRIGGER_TEXT}|numpy|{_WRITABLE_VIEW_TEXT.pattern}") class _TriggerLines: @@ -468,9 +599,9 @@ class _TriggerLines: them, so a module with a lone carriage return gets no ``_TriggerLines``. """ - def __init__(self, source: str, numpy_names: Iterable[str]) -> None: + def __init__(self, source: str, names: Iterable[str]) -> None: alternatives = [_TRIGGER_TEXT] - alternatives.extend(rf"\b{re.escape(name)}\b" for name in sorted(numpy_names)) + alternatives.extend(rf"\b{re.escape(name)}\b" for name in sorted(names)) pattern = re.compile("|".join(alternatives)) newlines = [match.start() for match in re.finditer("\n", source)] self._lines = sorted( @@ -488,6 +619,9 @@ def may_hold_finding(self, statement: ast.stmt) -> bool: return index < len(self._lines) and self._lines[index] <= last +# NumPy lookups ------------------------------------------------------------- + + @functools.cache def _numpy_object(dotted_name: str) -> object | None: found: object = np @@ -525,6 +659,10 @@ def _is_false_constant(expression: ast.expr) -> bool: return isinstance(expression, ast.Constant) and not expression.value +def _is_none(expression: ast.expr | None) -> bool: + return isinstance(expression, ast.Constant) and expression.value is None + + def _keyword(call: ast.Call, name: str) -> ast.keyword | None: return next((keyword for keyword in call.keywords if keyword.arg == name), None) @@ -533,21 +671,42 @@ def _is_true_constant(expression: ast.expr) -> bool: return isinstance(expression, ast.Constant) and expression.value is True +def _copy_is_off(call: ast.Call) -> bool: + """Whether a call passes ``copy=`` with anything but ``True``.""" + + copy = _keyword(call, "copy") + return copy is not None and not _is_true_constant(copy.value) + + +def _is_own_object(expression: ast.expr) -> bool: + return isinstance(expression, ast.Name) and expression.id in _OWN_OBJECT_NAMES + + +# The scanner --------------------------------------------------------------- + + class _Scanner: def __init__(self, source: str, path: str, tree: ast.Module) -> None: self._source = source self._path = path self._tree = tree self._numpy = _NumpyNames(tree) - # A write through a name bound to ``.array`` holds no trigger text of - # its own, so a module that reads ``.array`` is scanned in full. + # A write through a name bound to a writable view holds no trigger + # text of its own, so a module that reads one is scanned in full. lone_carriage_return = "\r" in source and "\r" in source.replace("\r\n", "") + # Without ``.array``, ``.base`` or ``.asi8`` text, nothing in the + # module can reach a writable view. + self._has_writable_views = bool(_WRITABLE_VIEW_TEXT.search(source)) self._trigger_lines = ( None - if lone_carriage_return or _ARRAY_ATTRIBUTE.search(source) - else _TriggerLines(source, self._numpy.bound_names) + if lone_carriage_return or self._has_writable_views + else _TriggerLines( + source, self._numpy.bound_names | self._numpy.derived_names + ) ) - self._scope = _Scope("", tree) + self._module_scope = _Scope("", tree) + self._scope: _Scope | _ComprehensionScope = self._module_scope + self._digests: dict[int, str] = {} self._checks = { ast.Call: self._check_call, ast.Assign: self._check_assign, @@ -559,7 +718,9 @@ def __init__(self, source: str, path: str, tree: ast.Module) -> None: self.findings: list[Finding] = [] def scan(self) -> list[Finding]: - stack = [(node, self._scope) for node in reversed(self._tree.body)] + stack: list[tuple[ast.AST, _Scope | _ComprehensionScope]] = [ + (node, self._module_scope) for node in reversed(self._tree.body) + ] while stack: node, scope = stack.pop() if ( @@ -572,15 +733,39 @@ def scan(self) -> list[Finding]: check = self._checks.get(type(node)) if check is not None: check(node) + children = list(ast.iter_child_nodes(node)) if isinstance(node, _NESTED_SCOPES): + # Decorators, defaults, annotations and base classes belong + # to the enclosing scope; only the body is inside. name = "" if isinstance(node, ast.Lambda) else node.name - scope = _Scope(scope.child_name(name), node) - children = list(ast.iter_child_nodes(node)) - stack.extend((child, scope) for child in reversed(children)) + inner = _Scope(scope.child_name(name), node) + body = [node.body] if isinstance(node, ast.Lambda) else node.body + inside = {id(statement) for statement in body} + stack.extend( + (child, inner if id(child) in inside else scope) + for child in reversed(children) + ) + elif isinstance(node, _COMPREHENSIONS): + inner = _ComprehensionScope(scope, node) + stack.extend((child, inner) for child in reversed(children)) + else: + stack.extend((child, scope) for child in reversed(children)) return self.findings # Reporting ----------------------------------------------------------- + def _function_digest(self) -> str: + node = self._scope.node + digest = self._digests.get(id(node)) + if digest is None: + if isinstance(node, ast.Module): + segment = self._source + else: + segment = ast.get_source_segment(self._source, node) or "" + digest = hashlib.sha256(segment.encode("utf-8")).hexdigest()[:12] + self._digests[id(node)] = digest + return digest + def _report(self, node: ast.AST, rule: str) -> None: segment = ast.get_source_segment(self._source, node) or ast.unparse(node) code = " ".join(segment.split()) @@ -591,118 +776,190 @@ def _report(self, node: ast.AST, rule: str) -> None: function=self._scope.qualified_name, rule=rule, code=code if len(code) <= 120 else code[:117] + "...", + function_digest=self._function_digest(), ) ) - # Following arrays ------------------------------------------------------ + # Following names ------------------------------------------------------- - def _bindings(self, name: str) -> list[ast.expr | None] | None: - """The values ``name`` is bound to in the current scope, if it is local.""" + def _bindings(self, name: str) -> list[_Binding] | None: + """The bindings of ``name`` in the current scope, if it is local.""" return self._scope.bindings_of(name) - def _allocates_new_array(self, call: ast.Call) -> bool: + def _resolve(self, expression: ast.expr) -> str | None: + """The dotted NumPy name of ``expression``, following ``plus = np.add``.""" + + name = self._numpy.resolve(expression) + if name is not None: + return name + attributes: list[str] = [] + root = expression + while isinstance(root, ast.Attribute): + attributes.append(root.attr) + root = root.value + if not isinstance(root, ast.Name) or root.id not in self._numpy.derived_names: + return None + bindings = self._bindings(root.id) + if bindings is None and not self._scope.is_parameter(root.id): + bindings = self._module_scope.bindings_of(root.id) + if not bindings or not all(exact for _value, exact in bindings): + return None + resolved = {self._numpy.resolve(value) for value, _exact in bindings if value} + if len(resolved) != 1 or None in resolved: + return None + return ".".join([resolved.pop(), *reversed(attributes)]) + + def _call_newness(self, call: ast.Call) -> int: if self._output_arguments(call): - return False - name = self._numpy.resolve(call.func) - if name in _ALLOCATING_NUMPY_FUNCTIONS: - return True - if name is not None and isinstance(_numpy_object(name), np.ufunc): - return True - if name == "numpy.array": + return _NOT_NEW + name = self._resolve(call.func) + if name is not None: + if name in _ALLOCATING_NUMPY_FUNCTIONS: + return _NEW_ARRAY + if isinstance(_numpy_object(name), np.ufunc): + return _NEW_ARRAY + if ( + name.startswith("numpy.random.") + and name not in _IN_PLACE_NUMPY_FUNCTIONS + ): + return _NEW_ARRAY + if name == "numpy.array": + return _NOT_NEW if _copy_is_off(call) else _NEW_ARRAY + return _NOT_NEW + function = call.func + if isinstance(function, ast.Name) and function.id in _CONTAINER_BUILTINS: + return _NEW_OBJECT + if not isinstance(function, ast.Attribute): + return _NOT_NEW + if function.attr == "to_numpy": copy = _keyword(call, "copy") - return copy is None or _is_true_constant(copy.value) - if isinstance(call.func, ast.Attribute) and call.func.attr == "copy": + return _NEW_ARRAY if copy and _is_true_constant(copy.value) else _NOT_NEW + if function.attr == "copy": deep = _keyword(call, "deep") if deep is not None and not _is_true_constant(deep.value): - return False + return _NOT_NEW if not call.args: - return True + return _NEW_OBJECT first = call.args[0] - return isinstance(first, ast.Constant) and ( + if isinstance(first, ast.Constant) and ( first.value is True or isinstance(first.value, str) - ) - return False + ): + return _NEW_OBJECT + return _NOT_NEW - def _is_new_local_array( - self, expression: ast.expr, following: frozenset[str] = frozenset() - ) -> bool: + def _newness( + self, expression: ast.expr, assumed: Mapping[str, int] | None = None + ) -> int: + """How new the value of ``expression`` is (``_NOT_NEW`` to ``_NEW_ARRAY``).""" + + assumed = assumed or {} if isinstance(expression, ast.Subscript): - return self._is_new_local_array(expression.value, following) + container = self._newness(expression.value, assumed) + if container == _NEW_ARRAY: + return _NEW_ARRAY + if container == _NEW_OBJECT and isinstance(expression.slice, ast.Slice): + return _NEW_OBJECT + return _NOT_NEW if isinstance(expression, ast.IfExp): - return self._is_new_local_array( - expression.body, following - ) and self._is_new_local_array(expression.orelse, following) - if isinstance(expression, ast.Call): - return self._allocates_new_array(expression) - if isinstance(expression, _NEW_OBJECT_EXPRESSIONS): - return True - if isinstance(expression, ast.Name) and expression.id in following: - # A binding that refers back to the name being followed (such as - # values = values[:n]) is new when the name's other bindings are. - return True - if isinstance(expression, ast.Name): - # A binding to None is a placeholder that holds no array. - values = [ - value - for value in self._bindings(expression.id) or [] - if not (isinstance(value, ast.Constant) and value.value is None) - ] - return bool(values) and all( - value is not None - and self._is_new_local_array(value, following | {expression.id}) - for value in values + return min( + self._newness(expression.body, assumed), + self._newness(expression.orelse, assumed), ) - return False - - def _reaches_series_array( + if isinstance(expression, ast.BoolOp): + return min(self._newness(value, assumed) for value in expression.values) + if isinstance(expression, ast.Call): + return self._call_newness(expression) + if isinstance(expression, _NEW_VALUE_EXPRESSIONS): + return _NEW_ARRAY + if isinstance(expression, _CONTAINER_EXPRESSIONS): + return _NEW_OBJECT + if not isinstance(expression, ast.Name): + return _NOT_NEW + name = expression.id + if name in assumed: + return assumed[name] + # A binding to None is a placeholder that holds no array. + bindings = [ + (value, exact) + for value, exact in self._bindings(name) or [] + if not (exact and _is_none(value)) + ] + if not bindings or any(value is None or not exact for value, exact in bindings): + return _NOT_NEW + # A binding may refer back to the name (values = values[:n]), so + # start from the newest level and lower it until it holds. + level = _NEW_ARRAY + while True: + inner = {**assumed, name: level} + result = min(self._newness(value, inner) for value, _exact in bindings) + if result >= level: + return level + level = result + + def _reaches_writable_view( self, expression: ast.expr, following: frozenset[str] = frozenset() ) -> bool: + """Whether ``expression`` can be, or hold, a writable view of pandas' memory.""" + + if not self._has_writable_views: + return False if isinstance(expression, ast.Attribute): - if expression.attr == "array": - return True + if expression.attr in _WRITABLE_VIEW_ATTRIBUTES: + return not _is_own_object(expression.value) if expression.attr in _VIEW_ATTRIBUTES: - return self._reaches_series_array(expression.value, following) + return self._reaches_writable_view(expression.value, following) return False - if isinstance(expression, ast.Subscript): - return self._reaches_series_array(expression.value, following) + if isinstance(expression, (ast.Subscript, ast.Starred)): + return self._reaches_writable_view(expression.value, following) if isinstance(expression, ast.IfExp): - return self._reaches_series_array( - expression.body, following - ) or self._reaches_series_array(expression.orelse, following) - if isinstance(expression, ast.Call): - name = self._numpy.resolve(expression.func) - copy = _keyword(expression, "copy") - makes_view = name in _VIEW_NUMPY_FUNCTIONS or ( - name == "numpy.array" - and copy is not None - and not _is_true_constant(copy.value) - ) - if makes_view: - return bool(expression.args) and self._reaches_series_array( - expression.args[0], following - ) - function = expression.func - if isinstance(function, ast.Attribute) and function.attr in _VIEW_METHODS: - if copy is not None and _is_true_constant(copy.value): - return False - return self._reaches_series_array(function.value, following) + parts: list[ast.expr] = [expression.body, expression.orelse] + elif isinstance(expression, ast.BoolOp): + parts = list(expression.values) + elif isinstance(expression, (ast.List, ast.Tuple, ast.Set)): + parts = list(expression.elts) + elif isinstance(expression, ast.Dict): + parts = list(expression.values) + elif isinstance(expression, (ast.ListComp, ast.SetComp, ast.GeneratorExp)): + parts = [expression.elt] + elif isinstance(expression, ast.DictComp): + parts = [expression.value] + elif isinstance(expression, ast.Call): + parts = self._view_call_sources(expression) + elif isinstance(expression, ast.Name) and expression.id not in following: + parts = [ + value for value, _exact in self._bindings(expression.id) or [] if value + ] + following = following | {expression.id} + else: return False - if isinstance(expression, ast.Name) and expression.id not in following: - values = self._bindings(expression.id) or [] - return any( - value is not None - and self._reaches_series_array(value, following | {expression.id}) - for value in values - ) - return False + return any(self._reaches_writable_view(part, following) for part in parts) + + def _view_call_sources(self, call: ast.Call) -> list[ast.expr]: + """The expressions a call's result can be a view of.""" + + name = self._resolve(call.func) + if name in _VIEW_NUMPY_FUNCTIONS or ( + name == "numpy.array" and _copy_is_off(call) + ): + return [*call.args, *(keyword.value for keyword in call.keywords)] + function = call.func + if isinstance(function, ast.Attribute): + if function.attr in _VIEW_METHODS: + copy = _keyword(call, "copy") + if copy is not None and _is_true_constant(copy.value): + return [] + return [function.value] + if function.attr == "astype" and _copy_is_off(call): + return [function.value] + return [] def _check_written_array(self, node: ast.AST, written: ast.expr) -> None: - """Report a write into ``written`` unless it is a new local array.""" + """Report a write into ``written`` unless it is new in this function.""" - if self._reaches_series_array(written): - self._report(node, _WRITES_THROUGH_SERIES_ARRAY) - elif not self._is_new_local_array(written): + if self._reaches_writable_view(written): + self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) + elif self._newness(written) == _NOT_NEW: self._report(node, _WRITES_INTO_EXISTING_ARRAY) # Rules ----------------------------------------------------------------- @@ -711,28 +968,47 @@ def _output_arguments(self, call: ast.Call) -> list[ast.expr]: """The arrays a call writes into: ``out=``, positional outputs, ``ufunc.at``.""" written: list[ast.expr] = [] - name = self._numpy.resolve(call.func) + name = self._resolve(call.func) + function = call.func + method = function.attr if isinstance(function, ast.Attribute) else None output = _keyword(call, "out") - # ``out=`` means an output array only to NumPy and to ndarray methods; - # workspace functions use it for output paths. - array_method = ( - isinstance(call.func, ast.Attribute) - and call.func.attr in _ARRAY_METHODS_WITH_OUT - ) - if output is not None and (name is not None or array_method): + # ``out=`` means an output array only to NumPy and to array and random + # Generator methods; workspace functions use it for output paths. + if output is not None and (name is not None or method in _METHODS_WITH_OUT): if isinstance(output.value, (ast.Tuple, ast.List)): - written.extend(output.value.elts) + written.extend( + element for element in output.value.elts if not _is_none(element) + ) elif not _is_false_constant(output.value): written.append(output.value) - if name is None or any(isinstance(arg, ast.Starred) for arg in call.args): + if any(isinstance(argument, ast.Starred) for argument in call.args): + return written + if name is None: + if method == "shuffle": + written.extend(call.args[:1]) return written if name in _IN_PLACE_NUMPY_FUNCTIONS: return [*written, *call.args[:1]] + if name == "numpy.nan_to_num" and _copy_is_off(call): + return [*written, *call.args[:1]] if name.endswith(".at") and isinstance(_numpy_object(name[:-3]), np.ufunc): return [*written, *call.args[:1]] outputs = _positional_outputs(name) return written if outputs is None else [*written, *call.args[outputs]] + def _writes_into_receiver(self, call: ast.Call, method: str) -> bool: + if method in _IN_PLACE_ARRAY_METHODS: + return True + if method == "fillna": + return _copy_is_off(call) + if method == "byteswap": + in_place = _keyword(call, "inplace") + flag = in_place.value if in_place is not None else None + if flag is None and call.args: + flag = call.args[0] + return flag is not None and not _is_false_constant(flag) + return False + def _check_call(self, node: ast.Call) -> None: function = node.func if isinstance(function, ast.Attribute): @@ -743,9 +1019,9 @@ def _check_call(self, node: ast.Call) -> None: flag = node.args[0] if flag is not None and not _is_false_constant(flag): self._report(node, _MAKES_ARRAY_WRITABLE) - elif function.attr in _IN_PLACE_ARRAY_METHODS: - if self._reaches_series_array(function.value): - self._report(node, _WRITES_THROUGH_SERIES_ARRAY) + elif self._writes_into_receiver(node, function.attr): + if self._reaches_writable_view(function.value): + self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) for written in self._output_arguments(node): self._check_written_array(node, written) @@ -768,8 +1044,8 @@ def _check_assigned_target( ): if value is None or not _is_false_constant(value): self._report(node, _MAKES_ARRAY_WRITABLE) - elif self._reaches_series_array(target.value): - self._report(node, _WRITES_THROUGH_SERIES_ARRAY) + elif self._reaches_writable_view(target.value): + self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) elif ( isinstance(target, ast.Attribute) and target.attr == "writeable" @@ -787,13 +1063,19 @@ def _check_annotated_assign(self, node: ast.AnnAssign) -> None: self._check_assigned_target(node, node.target, node.value) def _check_augmented_assign(self, node: ast.AugAssign) -> None: - self._check_assigned_target(node, node.target, None) + # ``values += 1`` writes into the array ``values`` names. + if isinstance(node.target, ast.Name) and self._reaches_writable_view( + node.target + ): + self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) + else: + self._check_assigned_target(node, node.target, None) def _check_attribute(self, node: ast.Attribute) -> None: if node.attr in _ALWAYS_PRIVATE_ATTRIBUTES: self._report(node, _PANDAS_PRIVATE_ATTRIBUTE) - elif node.attr in _FOREIGN_PRIVATE_ATTRIBUTES and not ( - isinstance(node.value, ast.Name) and node.value.id in _OWN_OBJECT_NAMES + elif node.attr in _FOREIGN_PRIVATE_ATTRIBUTES and not _is_own_object( + node.value ): self._report(node, _PANDAS_PRIVATE_ATTRIBUTE) elif node.attr == "copyto": @@ -843,7 +1125,9 @@ def workspace_scan() -> _WorkspaceScan: for path in scanned_files(_REPOSITORY): relative = path.relative_to(_REPOSITORY).as_posix() paths.add(relative) - findings.extend(scan_source(path.read_text(encoding="utf-8"), relative)) + # Read the bytes as they are, so line endings reach the parser. + source = path.read_bytes().decode("utf-8") + findings.extend(scan_source(source, relative)) return _WorkspaceScan(frozenset(paths), tuple(findings)) @@ -862,15 +1146,21 @@ def test_the_scanned_source_has_no_unprotected_buffer_writes( "Write through pandas instead (.loc, column assignment), or copy the " "array first (np.array(values, copy=True)). A finding that cannot " "write into memory a pandas object shares goes in " - "_REVIEWED_FINDINGS with the reason.\n" - + "\n".join(finding.describe() for finding in unreviewed) + "_REVIEWED_FINDINGS, under the key shown, with the reason.\n" + + "\n".join( + f"{finding.describe()}\n key: {finding.key!r}" for finding in unreviewed + ) ) def test_every_reviewed_finding_still_occurs(workspace_scan: _WorkspaceScan) -> None: present = {finding.key for finding in workspace_scan.findings} - assert not sorted(set(_REVIEWED_FINDINGS) - present) + assert not sorted(set(_REVIEWED_FINDINGS) - present), ( + "These reviewed findings no longer occur as reviewed. The expression " + "or its enclosing function changed, so review it again and update " + "its key, or remove the entry." + ) def test_the_scan_covers_every_package_and_the_us_frame_building_code( @@ -923,8 +1213,17 @@ def test_the_scan_skips_node_modules_and_hidden_directories(tmp_path: Path) -> N _NUMPY = "import numpy as np\n" + +def _in_function(*body_lines: str, parameters: str = "series") -> str: + """A module importing NumPy with one function holding ``body_lines``.""" + + body = "".join(f" {line}\n" for line in body_lines) + return f"{_NUMPY}def change({parameters}):\n{body}" + + #: Snippets the scan must refuse, with the one rule each must report. _REFUSED_SNIPPETS = { + # makes-array-writable "setflags_write_true": ( "values = series.to_numpy()\nvalues.setflags(write=True)\nvalues[0] = 1.0\n", _MAKES_ARRAY_WRITABLE, @@ -940,74 +1239,193 @@ def test_the_scan_skips_node_modules_and_hidden_directories(tmp_path: Path) -> N _MAKES_ARRAY_WRITABLE, ), "flags_w_key": ('values.flags["W"] = 1\n', _MAKES_ARRAY_WRITABLE), + "flags_key_parenthesized": ( + _in_function('(values.flags)["W"] = True', parameters="values"), + _MAKES_ARRAY_WRITABLE, + ), + # writes-through-writable-view "series_array_item": ( 'frame.person["income"].array[0] = 1.0\n', - _WRITES_THROUGH_SERIES_ARRAY, + _WRITES_THROUGH_WRITABLE_VIEW, ), "series_array_slice_augmented": ( "series.array[mask] += 1\n", - _WRITES_THROUGH_SERIES_ARRAY, + _WRITES_THROUGH_WRITABLE_VIEW, ), "series_array_annotated": ( "series.array[0]: float = 1.0\n", - _WRITES_THROUGH_SERIES_ARRAY, + _WRITES_THROUGH_WRITABLE_VIEW, ), "series_array_unpacked": ( "series.array[0], other = 1.0, 2.0\n", - _WRITES_THROUGH_SERIES_ARRAY, + _WRITES_THROUGH_WRITABLE_VIEW, ), "series_array_setitem_call": ( "series.array.__setitem__(0, 1.0)\n", - _WRITES_THROUGH_SERIES_ARRAY, + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "index_array_item": ( + "table.index.array[0] = 7\n", + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_backslash_continuation": ( + "series.\\\narray[0] = 1.0\n", + _WRITES_THROUGH_WRITABLE_VIEW, ), - "index_array_item": ("table.index.array[0] = 7\n", _WRITES_THROUGH_SERIES_ARRAY), "series_array_through_asarray": ( - _NUMPY - + "def zero_first(series):\n" - + " values = np.asarray(series.array)\n" - + " values[0] = 0.0\n", - _WRITES_THROUGH_SERIES_ARRAY, + _in_function("values = np.asarray(series.array)", "values[0] = 0.0"), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_asarray_keyword": ( + _NUMPY + "np.asarray(a=series.array)[0] = 1\n", + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_flip": ( + _NUMPY + "np.flip(np.asarray(series.array))[0] = 1\n", + _WRITES_THROUGH_WRITABLE_VIEW, ), "series_array_through_to_numpy": ( "series.array.to_numpy()[0] = 1.0\n", - _WRITES_THROUGH_SERIES_ARRAY, + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_astype_without_copy": ( + 'series.array.astype("float64", copy=False)[0] = 1.0\n', + _WRITES_THROUGH_WRITABLE_VIEW, ), "series_array_through_alias_chain": ( - "def zero_first(series):\n" - + " backing = series.array\n" - + " values = backing\n" - + " values[0] = 0.0\n", - _WRITES_THROUGH_SERIES_ARRAY, + _in_function("backing = series.array", "values = backing", "values[0] = 0.0"), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_conditional": ( + _in_function( + "values = series.array if flag else other", + "values[0] = 1", + parameters="series, other, flag", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_either_operand": ( + _in_function( + "values = override or series.array", + "values[0] = 1", + parameters="override, series", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_unpacking": ( + _in_function( + "left, right = first.array, second.array", + "left[0] = 1", + parameters="first, second", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_loop_target": ( + _in_function( + "for values in (frame[name].array for name in names):", + " values[0] = 1", + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_in_dict_comprehension": ( + _in_function( + "arrays = {name: frame[name].array for name in names}", + 'arrays["income"][0] = 1.0', + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_in_list_written_by_out": ( + _in_function( + "arrays = [np.asarray(series.array)]", + "np.add(arrays[0], 1, out=arrays[0])", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_augmented_name": ( + _in_function("values = np.asarray(series.array)", "values += 1"), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_to_numpy_augmented_name": ( + _in_function("values = series.array.to_numpy()", "values *= 2"), + _WRITES_THROUGH_WRITABLE_VIEW, ), "series_array_fill": ( _NUMPY + "np.asarray(series.array).fill(0)\n", - _WRITES_THROUGH_SERIES_ARRAY, + _WRITES_THROUGH_WRITABLE_VIEW, ), "series_array_sort": ( _NUMPY + "np.asarray(series.array).sort()\n", - _WRITES_THROUGH_SERIES_ARRAY, + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_put": ( + _NUMPY + "np.asarray(series.array).put([0], 1)\n", + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_partition": ( + _NUMPY + "np.asarray(series.array).partition(1)\n", + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_resize": ( + _NUMPY + "np.asarray(series.array).resize(3)\n", + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_itemset": ( + _NUMPY + "np.asarray(series.array).itemset(0, 1)\n", + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_setfield": ( + _NUMPY + "np.asarray(series.array).setfield(1, np.int64)\n", + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_byteswap_in_place": ( + _NUMPY + "np.asarray(series.array).byteswap(inplace=True)\n", + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_fillna_without_copy": ( + "series.array.fillna(0.0, copy=False)\n", + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_transposed_view": ( + "series.array.T[0] = 1\n", + _WRITES_THROUGH_WRITABLE_VIEW, ), "series_array_reshaped_view": ( "series.array.reshape(-1)[0] = 1.0\n", - _WRITES_THROUGH_SERIES_ARRAY, + _WRITES_THROUGH_WRITABLE_VIEW, ), "series_array_as_out": ( _NUMPY + "np.add(series.array, 1, out=series.array)\n", - _WRITES_THROUGH_SERIES_ARRAY, + _WRITES_THROUGH_WRITABLE_VIEW, ), "series_array_in_place_function": ( _NUMPY + "np.putmask(np.asarray(series.array), mask, 0)\n", - _WRITES_THROUGH_SERIES_ARRAY, + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_shuffled_by_generator": ( + _in_function("rng.shuffle(np.asarray(series.array))", parameters="rng, series"), + _WRITES_THROUGH_WRITABLE_VIEW, ), "series_array_no_copy_array": ( _NUMPY + "np.array(series.array, copy=False)[0] = 1\n", - _WRITES_THROUGH_SERIES_ARRAY, + _WRITES_THROUGH_WRITABLE_VIEW, ), + "read_only_view_base": ( + "series.to_numpy().base[0] = 1\n", + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "datetime_asi8": ("series.array.asi8[0] = 0\n", _WRITES_THROUGH_WRITABLE_VIEW), + "index_asi8": ("frame.index.asi8[0] = 0\n", _WRITES_THROUGH_WRITABLE_VIEW), + # pandas-private-attribute "ndarray_attribute": ( "values = series.array._ndarray\n", _PANDAS_PRIVATE_ATTRIBUTE, ), - "manager_attribute": ("blocks = frame._mgr.blocks\n", _PANDAS_PRIVATE_ATTRIBUTE), + "manager_attribute": ( + "blocks = frame._mgr.blocks\n", + _PANDAS_PRIVATE_ATTRIBUTE, + ), "manager_attribute_on_self": ( "class Table:\n def blocks(self):\n return self._mgr.blocks\n", _PANDAS_PRIVATE_ATTRIBUTE, @@ -1022,6 +1440,15 @@ def test_the_scan_skips_node_modules_and_hidden_directories(tmp_path: Path) -> N "codes = series.cat.codes.array._codes\n", _PANDAS_PRIVATE_ATTRIBUTE, ), + "column_array_method": ( + "column = frame._get_column_array(0)\n", + _PANDAS_PRIVATE_ATTRIBUTE, + ), + "column_arrays_iterator": ( + "for column in frame._iter_column_arrays():\n pass\n", + _PANDAS_PRIVATE_ATTRIBUTE, + ), + # numpy-copyto "copyto": (_NUMPY + "np.copyto(target, source)\n", _NUMPY_COPYTO), "copyto_through_numpy": ( "import numpy\nnumpy.copyto(target, source)\n", @@ -1039,8 +1466,9 @@ def test_the_scan_skips_node_modules_and_hidden_directories(tmp_path: Path) -> N "apply_each(np.copyto, pairs)\n", _NUMPY_COPYTO, ), + # writes-into-existing-array "out_parameter": ( - _NUMPY + "def add_one(values):\n np.add(values, 1, out=values)\n", + _in_function("np.add(values, 1, out=values)", parameters="values"), _WRITES_INTO_EXISTING_ARRAY, ), "out_attribute": ( @@ -1055,48 +1483,81 @@ def test_the_scan_skips_node_modules_and_hidden_directories(tmp_path: Path) -> N "def clip_in_place(values):\n values.clip(0, 1, out=values)\n", _WRITES_INTO_EXISTING_ARRAY, ), + "out_array_method_on_parameter": ( + "def running(values):\n values.cumsum(out=values)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_generator_method": ( + _in_function("rng.random(out=values)", parameters="rng, values"), + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_generator_permuted": ( + _in_function("rng.permuted(values, out=values)", parameters="rng, values"), + _WRITES_INTO_EXISTING_ARRAY, + ), "out_rebound_to_existing": ( - _NUMPY - + "def add_one(series):\n" - + " buffer = np.zeros(3)\n" - + " buffer = series.to_numpy()\n" - + " np.add(buffer, 1, out=buffer)\n", + _in_function( + "buffer = np.zeros(3)", + "buffer = series.to_numpy()", + "np.add(buffer, 1, out=buffer)", + ), _WRITES_INTO_EXISTING_ARRAY, ), "out_slice_of_existing": ( - _NUMPY - + "def add_one(series):\n" - + " buffer = series.to_numpy()\n" - + " buffer = buffer[1:]\n" - + " np.add(buffer, 1, out=buffer)\n", + _in_function( + "buffer = series.to_numpy()", + "buffer = buffer[1:]", + "np.add(buffer, 1, out=buffer)", + ), _WRITES_INTO_EXISTING_ARRAY, ), "out_slice_of_parameter": ( - _NUMPY - + "def add_one(values):\n" - + " values = values[1:]\n" - + " np.add(values, 1, out=values)\n", + _in_function( + "values = values[1:]", + "np.add(values, 1, out=values)", + parameters="values", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_item_of_new_list_rebound_to_itself": ( + _in_function( + "values = [series.to_numpy()]", + "values = values[0]", + "np.add(values, 1, out=values)", + ), _WRITES_INTO_EXISTING_ARRAY, ), "out_tuple": ( - _NUMPY + "def split(left, right):\n np.divmod(7, 2, out=(left, right))\n", + _in_function("np.divmod(7, 2, out=(left, right))", parameters="left, right"), _WRITES_INTO_EXISTING_ARRAY, ), "out_positional_ufunc": ( - _NUMPY + "def add_one(values):\n np.add(values, 1, values)\n", + _in_function("np.add(values, 1, values)", parameters="values"), _WRITES_INTO_EXISTING_ARRAY, ), "out_positional_function": ( - _NUMPY - + "def running(values, totals):\n np.cumsum(values, 0, None, totals)\n", + _in_function("np.cumsum(values, 0, None, totals)", parameters="values, totals"), _WRITES_INTO_EXISTING_ARRAY, ), "out_from_imported_ufunc": ( "from numpy import add\ndef add_one(values):\n add(values, 1, values)\n", _WRITES_INTO_EXISTING_ARRAY, ), + "out_through_local_function_alias": ( + _NUMPY + + "plus = np.add\n" + + "def add_one(values):\n" + + " plus(values, 1, values)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_keyword_through_function_alias": ( + _in_function( + "plus = np.add", "plus(values, 1, out=values)", parameters="values" + ), + _WRITES_INTO_EXISTING_ARRAY, + ), "ufunc_at": ( - _NUMPY + "def count(values):\n np.add.at(values, [0], 1)\n", + _in_function("np.add.at(values, [0], 1)", parameters="values"), _WRITES_INTO_EXISTING_ARRAY, ), "ufunc_at_imported": ( @@ -1107,16 +1568,47 @@ def test_the_scan_skips_node_modules_and_hidden_directories(tmp_path: Path) -> N _NUMPY + "np.maximum.at(series.to_numpy(), positions, values)\n", _WRITES_INTO_EXISTING_ARRAY, ), + "ufunc_at_on_item_of_new_list": ( + _in_function( + "columns = [frame[name].to_numpy() for name in names]", + "np.add.at(columns[0], [0], 1)", + parameters="frame, names", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_item_of_shallow_dict_copy": ( + _in_function( + "arrays = arrays_by_name.copy()", + 'np.multiply(arrays["x"], 2, out=arrays["x"])', + parameters="arrays_by_name", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), "numpy_put": ( - _NUMPY + "def set_first(values):\n np.put(values, [0], 1)\n", + _in_function("np.put(values, [0], 1)", parameters="values"), + _WRITES_INTO_EXISTING_ARRAY, + ), + "numpy_place": ( + _in_function("np.place(values, mask, 0)", parameters="values, mask"), + _WRITES_INTO_EXISTING_ARRAY, + ), + "numpy_put_along_axis": ( + _in_function( + "np.put_along_axis(values, positions, 0, axis=0)", + parameters="values, positions", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), + "numpy_nan_to_num_without_copy": ( + _in_function("np.nan_to_num(values, copy=False)", parameters="values"), _WRITES_INTO_EXISTING_ARRAY, ), "numpy_fill_diagonal": ( - _NUMPY + "def clear(matrix):\n np.fill_diagonal(matrix, 0)\n", + _in_function("np.fill_diagonal(matrix, 0)", parameters="matrix"), _WRITES_INTO_EXISTING_ARRAY, ), "numpy_random_shuffle": ( - _NUMPY + "def mix(values):\n np.random.shuffle(values)\n", + _in_function("np.random.shuffle(values)", parameters="values"), _WRITES_INTO_EXISTING_ARRAY, ), "out_module_array_from_function": ( @@ -1124,86 +1616,141 @@ def test_the_scan_skips_node_modules_and_hidden_directories(tmp_path: Path) -> N _WRITES_INTO_EXISTING_ARRAY, ), "out_global_declared": ( - _NUMPY - + "def add_one():\n" - + " global buffer\n" - + " buffer = np.zeros(3)\n" - + " np.add(1, 1, out=buffer)\n", + _in_function( + "global buffer", + "buffer = np.zeros(3)", + "np.add(1, 1, out=buffer)", + parameters="", + ), _WRITES_INTO_EXISTING_ARRAY, ), "out_loop_target": ( - _NUMPY - + "def add_one(arrays):\n" - + " for buffer in arrays:\n" - + " np.add(buffer, 1, out=buffer)\n", + _in_function( + "for buffer in arrays:", + " np.add(buffer, 1, out=buffer)", + parameters="arrays", + ), _WRITES_INTO_EXISTING_ARRAY, ), "out_comprehension_target": ( - _NUMPY + "def add_one(arrays):\n [np.add(a, 1, out=a) for a in arrays]\n", + _in_function("[np.add(a, 1, out=a) for a in arrays]", parameters="arrays"), + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_comprehension_target_shadowing_a_new_array": ( + _in_function( + "a = np.zeros(3)", + "return [np.add(a, 1, out=a) for a in arrays]", + parameters="arrays", + ), _WRITES_INTO_EXISTING_ARRAY, ), "out_lambda_parameter": ( _NUMPY + "add_one = lambda values: np.add(values, 1, out=values)\n", _WRITES_INTO_EXISTING_ARRAY, ), - "out_shallow_copy": ( + "out_in_a_decorator": ( _NUMPY - + "def add_one(table):\n" - + " shallow = table.copy(deep=False)\n" - + " np.add(1, 1, out=shallow)\n", + + "@register(np.add(1, 1, out=buffer))\n" + + "def change():\n" + + " return 1\n", _WRITES_INTO_EXISTING_ARRAY, ), - "out_positional_shallow_copy": ( + "out_in_a_decorator_over_a_function_binding_the_name": ( _NUMPY - + "def add_one(table):\n" - + " shallow = table.copy(False)\n" - + " np.add(1, 1, out=shallow)\n", + + "@register(np.add(1, 1, out=buffer))\n" + + "def change():\n" + + " buffer = np.zeros(3)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_shallow_copy": ( + _in_function( + "shallow = table.copy(deep=False)", + "np.add(1, 1, out=shallow)", + parameters="table", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_positional_shallow_copy": ( + _in_function( + "shallow = table.copy(False)", + "np.add(1, 1, out=shallow)", + parameters="table", + ), _WRITES_INTO_EXISTING_ARRAY, ), "out_array_without_copy": ( - _NUMPY - + "def add_one(values):\n" - + " view = np.array(values, copy=None)\n" - + " np.add(view, 1, out=view)\n", + _in_function( + "view = np.array(values, copy=None)", + "np.add(view, 1, out=view)", + parameters="values", + ), _WRITES_INTO_EXISTING_ARRAY, ), "out_concatenate_into_existing": ( - _NUMPY - + "def join(parts, existing):\n" - + " joined = np.concatenate(parts, out=existing)\n" - + " np.add(joined, 1, out=joined)\n", + _in_function( + "joined = np.concatenate(parts, out=existing)", + "np.add(joined, 1, out=joined)", + parameters="parts, existing", + ), _WRITES_INTO_EXISTING_ARRAY, ), "out_one_branch_existing": ( - _NUMPY - + "def add_one(values, fresh):\n" - + " buffer = np.zeros(3) if fresh else values\n" - + " np.add(buffer, 1, out=buffer)\n", + _in_function( + "buffer = np.zeros(3) if fresh else values", + "np.add(buffer, 1, out=buffer)", + parameters="values, fresh", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_either_operand": ( + _in_function( + "buffer = given or np.zeros(3)", + "np.add(buffer, 1, out=buffer)", + parameters="given", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_ufunc_result_with_output": ( + _in_function( + "total = np.add(values, 1, existing)", + "np.add(total, 1, out=total)", + parameters="values, existing", + ), _WRITES_INTO_EXISTING_ARRAY, ), "out_with_target": ( - _NUMPY - + "def add_one(opener):\n" - + " with opener() as buffer:\n" - + " np.add(buffer, 1, out=buffer)\n", + _in_function( + "with opener() as buffer:", + " np.add(buffer, 1, out=buffer)", + parameters="opener", + ), _WRITES_INTO_EXISTING_ARRAY, ), - "out_array_method_on_parameter": ( - "def running(values):\n values.cumsum(out=values)\n", + "out_except_target": ( + _in_function( + "try:", + " pass", + "except Exception as buffer:", + " np.add(1, 1, out=buffer)", + parameters="", + ), _WRITES_INTO_EXISTING_ARRAY, ), - "out_either_operand": ( - _NUMPY - + "def add_one(given):\n" - + " buffer = given or np.zeros(3)\n" - + " np.add(buffer, 1, out=buffer)\n", + "out_imported_name": ( + _in_function("import buffer", "np.add(1, 1, out=buffer)", parameters=""), _WRITES_INTO_EXISTING_ARRAY, ), - "out_ufunc_result_with_output": ( - _NUMPY - + "def add_one(values, existing):\n" - + " total = np.add(values, 1, existing)\n" - + " np.add(total, 1, out=total)\n", + "out_match_capture": ( + _in_function( + "match value:", + " case [buffer]:", + " np.add(1, 1, out=buffer)", + parameters="value", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_after_lone_carriage_returns": ( + "import numpy as np\rdef change(values):\r np.add(values, 1, out=values)\r", _WRITES_INTO_EXISTING_ARRAY, ), } @@ -1230,62 +1777,62 @@ def test_the_scanner_refuses_each_unprotected_write(source: str, rule: str) -> N _NUMPY + "share = np.divide(part, total, out=np.zeros_like(part), where=total > 0)\n" ), - "out_new_array_slice": ( - _NUMPY - + "def running(weights):\n" - + " totals = np.empty(len(weights) + 1)\n" - + " totals[0] = 0.0\n" - + " np.cumsum(weights, out=totals[1:])\n" - ), - "out_deep_copy": ( - _NUMPY - + "def accumulate(first, later):\n" - + " total = first.copy()\n" - + " np.add(total, later, out=total)\n" - ), - "out_deep_copy_in_order": ( - _NUMPY - + "def accumulate(first, later):\n" - + " total = first.copy('C')\n" - + " np.add(total, later, out=total)\n" - ), - "out_same_array_as_input": ( - _NUMPY - + "def capped(count):\n" - + " draws = np.empty(count)\n" - + " np.minimum(draws, 1.0, out=draws)\n" - + " return draws\n" - ), - "out_chained_and_conditional_names": ( - _NUMPY - + "def add_one(values, wide):\n" - + " first = second = np.zeros(3)\n" - + " alias = second\n" - + " chosen = np.ones(3) if wide else alias\n" - + " chosen += 1\n" - + " np.add(values, 1, out=chosen)\n" - + " np.add(values, 1, out=first)\n" - ), - "out_array_with_copy": ( - _NUMPY - + "def add_one(values):\n" - + " owned = np.array(values)\n" - + " copied = np.array(values, copy=True)\n" - + " np.add(owned, 1, out=owned)\n" - + " np.add(copied, 1, out=copied)\n" + "out_new_array_slice": _in_function( + "totals = np.empty(len(weights) + 1)", + "totals[0] = 0.0", + "np.cumsum(weights, out=totals[1:])", + parameters="weights", + ), + "out_new_array_row": _in_function( + "grid = np.zeros((2, 3))", "np.add(1, 1, out=grid[0])", parameters="" + ), + "out_deep_copy": _in_function( + "total = first.copy()", + "np.add(total, later, out=total)", + parameters="first, later", + ), + "out_deep_copy_in_order": _in_function( + "total = first.copy('C')", + "np.add(total, later, out=total)", + parameters="first, later", + ), + "out_copied_to_numpy": _in_function( + "values = series.to_numpy(dtype=float, copy=True)", + "np.add(values, 1, out=values)", + ), + "out_same_array_as_input": _in_function( + "draws = np.empty(count)", + "np.minimum(draws, 1.0, out=draws)", + "return draws", + parameters="count", + ), + "out_chained_and_conditional_names": _in_function( + "first = second = np.zeros(3)", + "alias = second", + "chosen = np.ones(3) if wide else alias", + "chosen += 1", + "np.add(values, 1, out=chosen)", + "np.add(values, 1, out=first)", + parameters="values, wide", + ), + "out_array_with_copy": _in_function( + "owned = np.array(values)", + "copied = np.array(values, copy=True)", + "np.add(owned, 1, out=owned)", + "np.add(copied, 1, out=copied)", + parameters="values", ), "out_none": _NUMPY + "np.add(left, right, out=None)\n", - "ufunc_at_new_array": ( - _NUMPY - + "def count(positions, size):\n" - + " counts = np.zeros(size, dtype=np.int64)\n" - + " np.add.at(counts, positions, 1)\n" - ), - "in_place_function_new_array": ( - _NUMPY - + "def clear(size):\n" - + " matrix = np.ones((size, size))\n" - + " np.fill_diagonal(matrix, 0)\n" + "out_none_pair": _NUMPY + "np.divmod(left, 2, out=(None, None))\n", + "ufunc_at_new_array": _in_function( + "counts = np.zeros(size, dtype=np.int64)", + "np.add.at(counts, positions, 1)", + parameters="positions, size", + ), + "in_place_function_new_array": _in_function( + "matrix = np.ones((size, size))", + "np.fill_diagonal(matrix, 0)", + parameters="size", ), "ufunc_without_out": _NUMPY + "total = np.add(left, right)\n", "array_function_not_attribute": ( @@ -1305,6 +1852,12 @@ def test_the_scanner_refuses_each_unprotected_write(source: str, rule: str) -> N "series_array_deep_copy_written": ( "values = series.array.to_numpy(copy=True)\nvalues[0] = 1\n" ), + "series_array_byteswap_copy": ( + _NUMPY + "swapped = np.asarray(series.array).byteswap()\n" + ), + "own_array_attribute": ( + "class Grid:\n def set(self, row, value):\n self.array[row] = value\n" + ), "own_private_state": ( "class Catalog:\n" + " def add(self, key, value):\n" @@ -1314,44 +1867,54 @@ def test_the_scanner_refuses_each_unprotected_write(source: str, rule: str) -> N + " def empty(cls):\n" + " return cls._mask\n" ), - "subscript_write_into_new_array": ( - _NUMPY + "def flags(size):\n marks = np.zeros(size)\n marks[0] = 1\n" + "subscript_write_into_new_array": _in_function( + "marks = np.zeros(size)", "marks[0] = 1", parameters="size" ), "out_keyword_of_workspace_functions": ( "launch(pool_manifest=manifest, out=args.out)\n" + "report.write(rows, out=destination)\n" ), - "none_placeholder_then_copy": ( - _NUMPY - + "def accumulate(slices):\n" - + " total: np.ndarray | None = None\n" - + " for current in slices:\n" - + " if total is None:\n" - + " total = current.copy()\n" - + " else:\n" - + " np.add(total, current, out=total)\n" - ), - "list_display_shuffled": ( - _NUMPY - + "def sizes(draws):\n" - + " values: list[float] = []\n" - + " values.extend(draws)\n" - + " values = values[:3]\n" - + " np.random.shuffle(values)\n" - ), - "where_ufunc_arithmetic_and_comparison_results": ( - _NUMPY - + "def totals(positions, values, mask, left, right):\n" - + " out = np.zeros(3)\n" - + " np.add.at(out, positions, values)\n" - + " out = np.where(mask, out, 0.0)\n" - + " np.multiply(out, 2, out=out)\n" - + " scaled = np.exp(values)\n" - + " np.multiply(scaled, 2, out=scaled)\n" - + " total = left + right\n" - + " np.add(total, 1, out=total)\n" - + " positive = left > 0\n" - + " np.logical_not(positive, out=positive)\n" + "none_placeholder_then_copy": _in_function( + "total: np.ndarray | None = None", + "for current in slices:", + " if total is None:", + " total = current.copy()", + " else:", + " np.add(total, current, out=total)", + parameters="slices", + ), + "list_display_shuffled": _in_function( + "values: list[float] = []", + "values.extend(draws)", + "values = values[:3]", + "np.random.shuffle(values)", + parameters="draws", + ), + "list_builtin_shuffled": _in_function( + "order = list(range(size))", "np.random.shuffle(order)", parameters="size" + ), + "random_and_rounded_results": _in_function( + "order = np.random.permutation(size)", + "np.add(order, 1, out=order)", + "rounded = np.round(values)", + "np.add(rounded, 1, out=rounded)", + parameters="size, values", + ), + "generator_method_into_new_array": _in_function( + "draws = np.empty(3)", "rng.random(out=draws)", parameters="rng" + ), + "where_ufunc_arithmetic_and_comparison_results": _in_function( + "out = np.zeros(3)", + "np.add.at(out, positions, values)", + "out = np.where(mask, out, 0.0)", + "np.multiply(out, 2, out=out)", + "scaled = np.exp(values)", + "np.multiply(scaled, 2, out=scaled)", + "total = left + right", + "np.add(total, 1, out=total)", + "positive = left > 0", + "np.logical_not(positive, out=positive)", + parameters="positions, values, mask, left, right", ), } @@ -1363,15 +1926,14 @@ def test_the_scanner_accepts_reads_and_writes_into_new_arrays(source: str) -> No assert scan_source(source, "snippet.py") == [] -def test_a_finding_names_its_file_line_and_function() -> None: - source = ( - _NUMPY - + "class Aggregator:\n" - + " def add(self, values):\n" +def test_a_finding_names_its_file_line_function_and_digest() -> None: + method = ( + " def add(self, values):\n" + " def inner(target):\n" + " np.add(target, 1, out=target)\n" + " inner(values)\n" ) + source = _NUMPY + "class Aggregator:\n" + method (finding,) = scan_source(source, "pkg/module.py") @@ -1379,3 +1941,21 @@ def test_a_finding_names_its_file_line_and_function() -> None: "pkg/module.py:5 in Aggregator.add.inner: writes-into-existing-array: " "np.add(target, 1, out=target)" ) + inner_source = "def inner(target):\n np.add(target, 1, out=target)" + assert ( + finding.function_digest + == hashlib.sha256(inner_source.encode("utf-8")).hexdigest()[:12] + ) + + +def test_a_changed_function_changes_the_finding_key() -> None: + original = _in_function("np.fill_diagonal(matrix, 0)", parameters="matrix") + changed = _in_function( + "matrix = matrix.T", "np.fill_diagonal(matrix, 0)", parameters="matrix" + ) + + (before,) = scan_source(original, "pkg/module.py") + (after,) = scan_source(changed, "pkg/module.py") + + assert before.code == after.code + assert before.key != after.key From 5992e56ff981450eb83e618f863e9227cf83a194 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:17:02 +0400 Subject: [PATCH 03/15] Fix the second round of review findings in Frame and the write scan Frame: _pandas_copy_on_write now asks pandas 2.x's own pandas._config.using_copy_on_write(), which emits no deprecation warnings, instead of changing process-wide warning filters around option reads. When that function is missing, as on pandas 3, a version of 3 or later counts as on (an undotted version string no longer raises), and any other version reads mode.copy_on_write. with_columns drops a deep copy that _adopt already made, and the constructor test now checks the strata copy. Scan: - Newness and views are computed as per-scope fixed points, stored on each scope, so long chains of names no longer take exponential time and tables are never reused across functions. - Views are tracked by container depth: an item of a container holding a view is a view, but writing a column into a frame that holds one is not a write into the view. - Views are followed through zip, enumerate, .items(), .values(), .get(), containers filled by append, extend or name[key] = ..., joined lists, np.split and the other functions returning views. - `+` and `*` give a new container whose items may be shared. - np.clip, np.tile and np.round can return a pandas object's memory, so they no longer count as allocating. - SciPy ufuncs count like NumPy's. - Random Generator draws, .flatten(), ufunc reductions, views of new arrays and to_numpy(dtype, True) count as new. - Exemption keys hold the full expression. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/frame/bundle.py | 39 +- .../shared/test_frame_table_sharing.py | 78 +- .../shared/test_shared_buffer_writes.py | 1069 ++++++++++++++--- 3 files changed, 934 insertions(+), 252 deletions(-) diff --git a/packages/microcosm-frame/src/microcosm/frame/bundle.py b/packages/microcosm-frame/src/microcosm/frame/bundle.py index 6f62aa0efe..e9dd10a6f7 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -27,7 +27,7 @@ and deep-copy when it is off (see :meth:`Frame._adopt`). """ -import warnings +import re from collections.abc import Mapping from dataclasses import dataclass from typing import Any @@ -161,8 +161,9 @@ def _adopt( 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`` (the constructor fails on its - ``copy()`` call). Weights are stored as given (their arrays are + not a DataFrame raises ``TypeError`` before any other check (the + constructor fails on such a table later, with an error that depends + on the object). Weights are stored as given (their arrays are read-only), and the strata are shallow-copied when copy-on-write is on. @@ -986,7 +987,7 @@ def with_columns(self, entity: str, /, **columns: Any) -> "Frame": a reserved ``{entity}_weight`` name, or broken linkage). """ - table = self.table(entity).copy(deep=not _pandas_copy_on_write()) + table = self.table(entity).copy(deep=False) for column_name, values in columns.items(): table[column_name] = values return self.replace_tables(**{entity: table}) @@ -1543,25 +1544,23 @@ def _require_dataframes(tables: Mapping[str, Any]) -> None: def _pandas_copy_on_write() -> bool: """Whether pandas copy-on-write is on in this process, checked at each call. - pandas 3 always has copy-on-write on and deprecates its options, so they - are read only under pandas 2.x. There, as in pandas' own check, - copy-on-write is on only when ``mode.copy_on_write`` is ``True`` (it is - ``False`` by default, or ``"warn"``) and ``mode.data_manager`` is - ``"block"``. + 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 it along with the switch, because copy-on-write is + always on. Without the function, a version from 3 on counts as on, and + any other version reads ``mode.copy_on_write``. """ - if int(pd.__version__.split(".", 1)[0]) >= 3: - return True - if pd.get_option("mode.copy_on_write") is not True: - return False - with warnings.catch_warnings(): - # pandas 2.x deprecates the data_manager option. - warnings.simplefilter("ignore", category=DeprecationWarning) - warnings.simplefilter("ignore", category=FutureWarning) - try: - return pd.get_option("mode.data_manager") == "block" - except pd.errors.OptionError: + 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) 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 1fe07c6b3e..e6b6c50123 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 @@ -11,6 +11,7 @@ path, because pandas 3 always has copy-on-write on. """ +import importlib from collections.abc import Callable, Iterator from typing import Any @@ -28,6 +29,8 @@ ) from microcosm.frame import bundle as bundle_module +pandas_config = importlib.import_module("pandas._config") + _SCHEMA = EntitySchema( group_entities=("household", "firm"), links=(LinkSpec(name="jobs", left_entity="person", right_entity="firm"),), @@ -148,15 +151,17 @@ def _numeric_columns_sharing_memory( class TestDefaultConstructor: - def test_constructor_deep_copies_every_table(self) -> None: + def test_constructor_deep_copies_every_table_and_the_strata(self) -> None: tables = _source_tables() - frame = Frame(tables, _SCHEMA, _source_weights(), _source_strata()) + strata = _source_strata() + frame = Frame(tables, _SCHEMA, _source_weights(), strata) for name, table in _tables_of(frame).items(): assert table is not tables[name] sharing = _numeric_columns_sharing_memory(_tables_of(frame), tables) assert sharing, "the comparison found no numeric columns" assert not any(sharing.values()), sharing + assert not np.shares_memory(frame.strata.to_numpy(), strata.to_numpy()) class TestAdopt: @@ -545,52 +550,59 @@ def test_a_pandas_write_to_the_source_leaves_the_new_frame_unchanged( class TestCopyOnWriteCheck: + """``_pandas_copy_on_write`` on each pandas it can run under. + + pandas 2.x provides ``pandas._config.using_copy_on_write``; pandas 3 + removed it. The tests add or remove that function and replace the + version and the option reader to stand for each case. + """ + + @staticmethod + def _refuse_option_reads(name: str) -> object: + raise AssertionError(f"the check must not read option {name!r}") + def test_pandas_3_has_copy_on_write_without_reading_the_option( self, monkeypatch: pytest.MonkeyPatch ) -> None: - def refuse_option_reads(name: str) -> object: - raise AssertionError(f"pandas 3 must not read option {name!r}") - + monkeypatch.delattr(pandas_config, "using_copy_on_write", raising=False) monkeypatch.setattr(bundle_module.pd, "__version__", "3.0.3") - monkeypatch.setattr(bundle_module.pd, "get_option", refuse_option_reads) + monkeypatch.setattr(bundle_module.pd, "get_option", self._refuse_option_reads) assert bundle_module._pandas_copy_on_write() is True + @pytest.mark.parametrize("in_force", [True, False], ids=["on", "off"]) + def test_pandas_2_uses_pandas_own_check( + self, monkeypatch: pytest.MonkeyPatch, in_force: bool + ) -> None: + monkeypatch.setattr( + pandas_config, "using_copy_on_write", lambda: in_force, raising=False + ) + monkeypatch.setattr(bundle_module.pd, "__version__", "2.3.3") + monkeypatch.setattr(bundle_module.pd, "get_option", self._refuse_option_reads) + + assert bundle_module._pandas_copy_on_write() is in_force + @pytest.mark.parametrize( - ("copy_on_write", "data_manager", "expected"), + ("version", "option_value", "expected"), [ - (True, "block", True), - (False, "block", False), - ("warn", "block", False), - (True, "array", False), + ("2.3.3", True, True), + ("2.3.3", False, False), + ("2.3.3", "warn", False), + ("0+unknown", True, True), + ("0+unknown", False, False), ], - ids=["enabled", "disabled", "warn_mode", "array_manager"], + ids=["enabled", "disabled", "warn_mode", "undotted_on", "undotted_off"], ) - def test_pandas_2_reads_the_copy_on_write_and_data_manager_options( + def test_without_pandas_own_check_an_older_version_reads_the_option( self, monkeypatch: pytest.MonkeyPatch, - copy_on_write: object, - data_manager: str, + version: str, + option_value: object, expected: bool, ) -> None: - options = { - "mode.copy_on_write": copy_on_write, - "mode.data_manager": data_manager, - } - monkeypatch.setattr(bundle_module.pd, "__version__", "2.3.3") + options = {"mode.copy_on_write": option_value} + monkeypatch.delattr(pandas_config, "using_copy_on_write", raising=False) + monkeypatch.setattr(bundle_module.pd, "__version__", version) monkeypatch.setattr(bundle_module.pd, "get_option", options.__getitem__) assert bundle_module._pandas_copy_on_write() is expected - - def test_pandas_2_without_a_data_manager_option_uses_copy_on_write( - self, monkeypatch: pytest.MonkeyPatch - ) -> None: - def read_option(name: str) -> object: - if name == "mode.copy_on_write": - return True - raise pd.errors.OptionError(f"No such keys(s): {name!r}") - - monkeypatch.setattr(bundle_module.pd, "__version__", "2.3.3") - monkeypatch.setattr(bundle_module.pd, "get_option", read_option) - - assert bundle_module._pandas_copy_on_write() is True 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 176d8fe961..b1939efaea 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 @@ -21,12 +21,17 @@ assignment, ``__setitem__``, ``fill``, ``sort`` and the other in-place ndarray methods, ``fillna(copy=False)``, ``out=``, ``shuffle`` and the in-place NumPy functions below. It counts when the written expression - reaches the view through indexing, ``np.asarray``, ``np.flip`` and the - other NumPy view functions, ``to_numpy()``, ``astype(copy=False)`` and - the other view methods, a list, tuple, set or dict holding it, ``or`` - and conditional expressions, or a name the same function binds to any - of these (by assignment, unpacking, a ``for`` loop or a ``with`` - statement). Workspace classes' own ``self.array`` is exempt. + reaches the view through indexing, the NumPy functions that can return + a view (``np.asarray``, ``np.flip``, ``np.split``, ... in + ``_VIEW_NUMPY_FUNCTIONS``), ``to_numpy()``, ``astype(copy=False)`` and + the other view methods, a list, tuple, set or dict display or + comprehension holding it (also concatenated with ``+``), ``zip``, + ``enumerate``, ``.items()``, ``.values()`` and ``.get()``, ``or`` and + conditional expressions, or a name the same function binds to any of + these (by assignment, unpacking, a ``for`` loop or a ``with`` + statement) or fills with one (``append``, ``extend``, ``update``, + ``name[key] = ...``, ``+=``). Workspace classes' own ``self.array`` is + exempt. ``pandas-private-attribute`` ``._ndarray``, ``._mgr``, ``._get_column_array`` or ``._iter_column_arrays`` on anything, and ``._values``, ``._data``, @@ -36,24 +41,27 @@ Any use of ``numpy.copyto``. ``writes-into-existing-array`` A write into an array the same function did not create: - ``out=`` given to a NumPy function, ufunc, ndarray method or NumPy random - ``Generator`` method (by keyword, or by position for NumPy functions and - ufuncs), the first argument of ``numpy..at`` (which writes even - into a read-only array), the first argument of ``numpy.put``, - ``numpy.putmask``, ``numpy.place``, ``numpy.put_along_axis``, - ``numpy.fill_diagonal``, ``numpy.random.shuffle``, any ``.shuffle`` - method and ``numpy.nan_to_num(copy=False)``. NumPy functions are also - followed through a local name bound to them (``plus = np.add``). - Created means one of: the result of a ufunc, a ``numpy.random`` function - or a NumPy function that always allocates + ``out=`` given to a NumPy or SciPy function or ufunc, an ndarray method + or a NumPy random ``Generator`` method (by keyword, or by position for + NumPy and SciPy functions and ufuncs), the first argument of + ``numpy..at`` (which writes even into a read-only array), the + first argument of ``numpy.put``, ``numpy.putmask``, ``numpy.place``, + ``numpy.put_along_axis``, ``numpy.fill_diagonal``, + ``numpy.random.shuffle``, any ``.shuffle`` method and + ``numpy.nan_to_num(copy=False)``. Library functions are also followed + through a local name bound to them (``plus = np.add``). + Created means one of: the result of a ufunc or ufunc reduction, a + ``numpy.random`` function, a random ``Generator`` draw (``rng.normal``, + ...), ``.flatten()``, or a NumPy function that always allocates (``_ALLOCATING_NUMPY_FUNCTIONS``: ``np.zeros``, ``np.where``, - ``np.concatenate``, ...), when not given an output array; ``np.array`` - without ``copy=``; ``to_numpy(copy=True)``; a subscript of one of these; - a ``.copy()``, arithmetic, a comparison, ``list(...)`` and the other - container builtins, or a list, set or dict display (a slice of these is - new, an item is not, because a shallow copy or a container shares its - items); or a local name whose every binding in the function, other than - to ``None``, is one of these. + ``np.concatenate``, ...), when not given an output array; + ``np.array`` without ``copy=``; ``to_numpy(copy=True)``; a view or + subscript of one of these; arithmetic or a comparison; a ``.copy()``, + ``list(...)`` and the other container builtins, ``+`` or ``*`` + (which also join lists), or a list, set or dict display (a slice of + these is new, an item is not, because a shallow copy or a container + shares its items); or a local name whose every binding in the + function, other than to ``None``, is one of these. ``setflags``, ``Series.array[i] = value``, ``._ndarray``, ``._mgr``, ``np.copyto`` and ``out=`` are the writes first identified as unprotected. @@ -66,16 +74,24 @@ except files in ``node_modules`` or hidden directories. Tests and ``test_support/`` are not scanned. -What source reading cannot see, so is not refused here: - -- the arrays ``to_numpy()`` and ``.values`` return for extension-typed - columns (``Int64``, ``Float64``, ``boolean``, ``category``, python-backed - strings) are writable views of the shared memory; -- a pandas object built with ``copy=False`` over another object's array - writes into it when it is written through pandas; -- names reached dynamically (``getattr(np, name)``, ``**{"out": array}``, - ``*arguments``), positional ``out`` given to ndarray methods, writes - through closures, and items of a container a function did not build. +What this scan does not refuse: + +- Writes it cannot see from the source: into the arrays ``to_numpy()`` and + ``.values`` return for extension-typed columns (``Int64``, ``Float64``, + ``boolean``, ``category``, python-backed strings), which are writable + views of the shared memory; through a pandas object built with + ``copy=False`` over another object's array; into ``np.asarray(index)``, + which is writable although the index is shared even between deep copies. +- Arrays reached in ways it does not follow: through other functions' + return values or arguments, closures, object arrays, names reached + dynamically (``getattr(np, name)``, ``**{"out": array}``, ``*arguments``), + positional ``out`` given to ndarray methods, items of a container the + function did not build, and array libraries other than NumPy and SciPy + (``torch.from_numpy`` of a read-only view returns a writable tensor). +- The analysis is not flow-sensitive: a name counts as created only if + every binding in its function does, so a parameter rebound to a new + array, and ``.astype()`` (which shares memory when it is a pandas + object's same-type conversion), count as not created. A finding that cannot write into memory a pandas object shares goes in ``_REVIEWED_FINDINGS`` with the reason. @@ -87,10 +103,11 @@ import bisect import functools import hashlib +import importlib import inspect import re from collections import defaultdict -from collections.abc import Iterable, Iterator, Mapping +from collections.abc import Callable, Iterable, Iterator from dataclasses import dataclass from pathlib import Path @@ -106,7 +123,8 @@ #: expression's source, a digest of the enclosing function's source) as a #: failure prints it, with the reason. The function is ``Class.method`` or #: ``outer.inner``, or ```` for module-level code. Any change to the -#: enclosing function changes the digest and needs a new review. +#: enclosing function changes the digest and needs a new review; a reason +#: that rests on other functions names them, and changing them needs one too. _REVIEWED_FINDINGS: dict[tuple[str, str, str, str, str], str] = { ( "packages/microcosm-build/src/microcosm/build/uk_runtime/frs_relationships.py", @@ -128,7 +146,8 @@ ): ( "np.add.at writes into the array _pre_clone_household_weights returns, " "which _pre_residential_household_weights creates with " - "np.asarray(...).copy() from the household weights." + "np.asarray(...).copy() from the household weights. Review again if " + "either of those functions changes." ), } @@ -150,8 +169,13 @@ #: Attributes that return a writable view of pandas' memory. _WRITABLE_VIEW_ATTRIBUTES = frozenset({"array", "base", "asi8"}) -#: NumPy functions whose result is always a new array (unless given ``out=``). -#: A ufunc's result and a ``numpy.random`` function's result are new too. +#: Libraries whose functions the scan resolves through imports. +_LIBRARIES = ("numpy", "scipy") + +#: NumPy functions whose result is always new memory, for ndarrays and for +#: pandas objects alike (unless given ``out=``). ``np.clip``, ``np.tile`` and +#: ``np.round`` are left out: given a pandas object, their result can share +#: its memory. _ALLOCATING_NUMPY_FUNCTIONS = frozenset( f"numpy.{name}" for name in ( @@ -165,10 +189,8 @@ "bincount", "cumsum", "cumprod", - "clip", "take", - "round", - "around", + "interp", "flatnonzero", "outer", "dot", @@ -190,18 +212,66 @@ "hstack", "vstack", "column_stack", - "tile", "repeat", ) ) +#: ufunc methods whose result is a new array (unless given ``out=``). +_ALLOCATING_UFUNC_METHODS = frozenset({"reduce", "accumulate", "reduceat", "outer"}) + +#: NumPy random Generator methods that draw a new array. +_RANDOM_DRAW_METHODS = frozenset( + { + "random", + "normal", + "uniform", + "integers", + "choice", + "permutation", + "standard_normal", + "standard_exponential", + "standard_gamma", + "exponential", + "gamma", + "beta", + "binomial", + "poisson", + "lognormal", + "multinomial", + "multivariate_normal", + "dirichlet", + "laplace", + "logistic", + "triangular", + "geometric", + } +) + #: Builtins whose result is a new container (whose items may be shared). _CONTAINER_BUILTINS = frozenset( {"list", "dict", "set", "frozenset", "tuple", "sorted", "bytearray"} ) +#: Builtins and methods whose result holds the items of their arguments or +#: receiver, for following views through iteration. +_SAME_ITEMS_BUILTINS = frozenset( + {"reversed", "iter", "list", "tuple", "sorted", "set", "frozenset"} +) +_TUPLE_YIELDING_BUILTINS = frozenset({"zip", "enumerate"}) +_SAME_ITEMS_METHODS = frozenset({"values", "popitem"}) +_TUPLE_YIELDING_METHODS = frozenset({"items"}) +#: Methods that return one item of the container they are called on. +_ITEM_TAKING_METHODS = frozenset({"get", "pop", "setdefault"}) +#: Methods that put one item, or the items of an iterable, into the +#: container they are called on. +_ITEM_ADDING_METHODS = frozenset( + {"append", "appendleft", "insert", "add", "setdefault"} +) +_ITEMS_ADDING_METHODS = frozenset({"extend", "update"}) -#: Expressions whose value is a new array: arithmetic and comparisons. -_NEW_VALUE_EXPRESSIONS = (ast.BinOp, ast.UnaryOp, ast.Compare) +#: Arithmetic and comparisons give a new array; ``+`` and ``*`` also join or +#: repeat lists, whose items are shared, so they give a new container. +_NEW_ARRAY_EXPRESSIONS = (ast.UnaryOp, ast.Compare) +_JOINING_OPERATORS = (ast.Add, ast.Mult) #: Displays and comprehensions: a new container whose items may be shared. _CONTAINER_EXPRESSIONS = ( ast.List, @@ -256,6 +326,7 @@ "numpy.put_along_axis", "numpy.fill_diagonal", "numpy.random.shuffle", + "numpy.random.mtrand.shuffle", } ) @@ -273,7 +344,8 @@ } ) -#: NumPy functions that can return a view of an argument. +#: NumPy functions that can return a view of an argument (or views, as +#: ``np.split`` does). _VIEW_NUMPY_FUNCTIONS = frozenset( f"numpy.{name}" for name in ( @@ -281,14 +353,19 @@ "asanyarray", "ascontiguousarray", "asfortranarray", + "asarray_chkfinite", + "require", "ravel", "reshape", "squeeze", "transpose", + "permute_dims", + "matrix_transpose", "atleast_1d", "atleast_2d", "atleast_3d", "frombuffer", + "from_dlpack", "flip", "fliplr", "flipud", @@ -299,16 +376,44 @@ "expand_dims", "real", "imag", + "trim_zeros", + "tile", + "clip", + "round", + "around", "lib.stride_tricks.as_strided", ) ) +#: NumPy functions that return a list or tuple of views of an argument. +_SPLITTING_NUMPY_FUNCTIONS = frozenset( + f"numpy.{name}" + for name in ( + "split", + "array_split", + "hsplit", + "vsplit", + "dsplit", + "unstack", + "broadcast_arrays", + ) +) + #: Methods and attributes that can return a view of the object they are read #: from. _VIEW_METHODS = frozenset( - {"to_numpy", "view", "reshape", "ravel", "squeeze", "transpose", "__array__"} + { + "to_numpy", + "view", + "reshape", + "ravel", + "squeeze", + "transpose", + "swapaxes", + "__array__", + } ) -_VIEW_ATTRIBUTES = frozenset({"T", "real", "imag", "flat"}) +_VIEW_ATTRIBUTES = frozenset({"T", "mT", "real", "imag", "flat"}) _NESTED_SCOPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda) @@ -320,6 +425,42 @@ #: A new array: every item and view of it is new memory. _NEW_ARRAY = 2 +#: How deep in containers a value holds a writable view of pandas' memory: +#: ``_IS_VIEW`` for a view itself, 1 for a container of views, 2 for a +#: container of those, and ``_NO_VIEW`` for none (or deeper than tracked). +_IS_VIEW = 0 +_NO_VIEW = 5 + + +def _item_of(depth: int) -> int: + """An item of a view (a row or slice) is a view; of a container, one level less.""" + + if depth >= _NO_VIEW: + return _NO_VIEW + return max(depth - 1, _IS_VIEW) + + +def _holder_of(depth: int) -> int: + """A container of a value holds its view one level deeper.""" + + return min(depth + 1, _NO_VIEW) + + +def _shifted(depth: int, shift: int) -> int: + """``depth`` after taking ``-shift`` items, or going ``shift`` containers deeper.""" + + for _step in range(-shift): + depth = _item_of(depth) + for _step in range(shift): + depth = _holder_of(depth) + return depth + + +def _view_of(depth: int) -> int: + """A NumPy view of a view is a view; of a container (a list) it is a copy.""" + + return _IS_VIEW if depth == _IS_VIEW else _NO_VIEW + @dataclass(frozen=True) class Finding: @@ -337,23 +478,25 @@ def key(self) -> tuple[str, str, str, str, str]: return (self.path, self.function, self.rule, self.code, self.function_digest) def describe(self) -> str: - return f"{self.path}:{self.line} in {self.function}: {self.rule}: {self.code}" + code = self.code if len(self.code) <= 120 else self.code[:117] + "..." + return f"{self.path}:{self.line} in {self.function}: {self.rule}: {code}" # Bindings ------------------------------------------------------------------ #: One binding of a name: the value expression (``None`` when it cannot be -#: followed, as for an import), and whether the name is bound to exactly that -#: value (``False`` when it is bound to a part of it, as a loop target is -#: bound to an item of its iterable). -_Binding = tuple[ast.expr | None, bool] +#: followed, as for an import), and how many items deep into that value the +#: name is bound: 0 for the value itself, 1 for a loop target (an item of +#: its iterable), 2 for a name unpacked from a loop target, and so on. +_Binding = tuple[ast.expr | None, int] class _Scope: """One function, class or module, and the names it binds. The bindings are collected on first use, because most scopes are never - asked. + asked. ``held_values`` are the expressions a name's container is filled + with (``name.append(value)``, ``name[key] = value``, ``name += value``). """ def __init__(self, qualified_name: str, node: ast.AST) -> None: @@ -362,12 +505,25 @@ def __init__(self, qualified_name: str, node: ast.AST) -> None: self._parameters: frozenset[str] = frozenset() self._declared_elsewhere: set[str] = set() self._bindings: defaultdict[str, list[_Binding]] | None = None + self._held: defaultdict[str, list[tuple[ast.expr, bool]]] = defaultdict(list) + # Filled by the scanner on first use, held here so that they live + # exactly as long as the scope. + self.newness_table: dict[str, int] | None = None + self.view_table: dict[str, int] | None = None def child_name(self, name: str) -> str: if self.qualified_name == "": return name return f"{self.qualified_name}.{name}" + def is_local(self, name: str) -> bool: + self._collect() + return ( + name not in self._parameters + and name not in self._declared_elsewhere + and bool(self._bindings.get(name)) + ) + def bindings_of(self, name: str) -> list[_Binding] | None: """The bindings of ``name`` here, or ``None`` when it is not local. @@ -375,23 +531,40 @@ def bindings_of(self, name: str) -> list[_Binding] | None: this scope never binds are not local. """ - self._collect() - if name in self._parameters or name in self._declared_elsewhere: - return None - return self._bindings.get(name) or None + return self._bindings[name] if self.is_local(name) else None def is_parameter(self, name: str) -> bool: self._collect() return name in self._parameters - def _bind(self, target: ast.expr, value: ast.expr | None, exact: bool) -> None: + def local_bindings(self) -> dict[str, list[_Binding]]: + self._collect() + return { + name: bindings + for name, bindings in self._bindings.items() + if self.is_local(name) + } + + def held_names(self) -> list[str]: + self._collect() + return list(self._held) + + def held_values(self, name: str) -> list[tuple[ast.expr, bool]]: + """What the container ``name`` is filled with, and whether each value + goes in as one item (``append``) rather than as its items (``extend``).""" + + self._collect() + return self._held.get(name, []) + + def _bind(self, target: ast.expr, value: ast.expr | None, items_taken: int) -> None: if isinstance(target, ast.Name): - self._bindings[target.id].append((value, exact)) + self._bindings[target.id].append((value, items_taken)) elif isinstance(target, ast.Starred): - self._bind(target.value, value, False) + # A starred target collects items into a list: the same depth. + self._bind(target.value, value, items_taken) elif isinstance(target, (ast.Tuple, ast.List)): pairs = ( - exact + items_taken == 0 and isinstance(value, (ast.Tuple, ast.List)) and len(value.elts) == len(target.elts) and not any( @@ -401,9 +574,15 @@ def _bind(self, target: ast.expr, value: ast.expr | None, exact: bool) -> None: ) for index, element in enumerate(target.elts): if pairs: - self._bind(element, value.elts[index], True) + self._bind(element, value.elts[index], 0) else: - self._bind(element, value, False) + self._bind(element, value, items_taken + 1) + elif ( + isinstance(target, ast.Subscript) + and isinstance(target.value, ast.Name) + and value is not None + ): + self._held[target.value.id].append((value, True)) def _collect(self) -> None: if self._bindings is not None: @@ -427,55 +606,81 @@ def _collect(self) -> None: for child in _nodes_in_scope(body): if isinstance(child, ast.Assign): for target in child.targets: - self._bind(target, child.value, True) + self._bind(target, child.value, 0) elif isinstance(child, (ast.AnnAssign, ast.NamedExpr)): if child.value is not None: - self._bind(child.target, child.value, True) + self._bind(child.target, child.value, 0) + elif isinstance(child, ast.AugAssign): + target = child.target + if isinstance(target, ast.Subscript): + target = target.value + if isinstance(target, ast.Name): + self._held[target.id].append((child.value, False)) elif isinstance(child, (ast.For, ast.AsyncFor)): - self._bind(child.target, child.iter, False) + self._bind(child.target, child.iter, 1) elif isinstance(child, ast.withitem) and child.optional_vars is not None: - self._bind(child.optional_vars, child.context_expr, False) + self._bind(child.optional_vars, child.context_expr, 1) elif isinstance(child, ast.ExceptHandler) and child.name: - self._bindings[child.name].append((None, False)) + self._bindings[child.name].append((None, 1)) elif isinstance(child, (ast.Import, ast.ImportFrom)): for alias in child.names: bound = alias.asname or alias.name.split(".", 1)[0] - self._bindings[bound].append((None, False)) + self._bindings[bound].append((None, 1)) elif isinstance(child, _NESTED_SCOPES) and not isinstance( child, ast.Lambda ): - self._bindings[child.name].append((None, False)) + self._bindings[child.name].append((None, 1)) elif isinstance(child, (ast.Global, ast.Nonlocal)): self._declared_elsewhere.update(child.names) elif isinstance(child, (ast.MatchAs, ast.MatchStar)) and child.name: - self._bindings[child.name].append((None, False)) + self._bindings[child.name].append((None, 1)) elif isinstance(child, ast.MatchMapping) and child.rest: - self._bindings[child.rest].append((None, False)) + self._bindings[child.rest].append((None, 1)) + elif ( + isinstance(child, ast.Call) + and isinstance(child.func, ast.Attribute) + and isinstance(child.func.value, ast.Name) + ): + method = child.func.attr + if method in _ITEM_ADDING_METHODS or method in _ITEMS_ADDING_METHODS: + one_item = method in _ITEM_ADDING_METHODS + self._held[child.func.value.id].extend( + (argument, one_item) + for argument in ( + *child.args, + *(keyword.value for keyword in child.keywords), + ) + ) class _ComprehensionScope: """A comprehension: its loop targets shadow the enclosing scope's names.""" def __init__(self, enclosing: _Scope | _ComprehensionScope, node: ast.AST): - self._enclosing = enclosing + self.enclosing = enclosing self.qualified_name = enclosing.qualified_name self.node = enclosing.node - self._targets: defaultdict[str, list[_Binding]] = defaultdict(list) + self._targets: defaultdict[str, list[ast.expr]] = defaultdict(list) for generator in node.generators: for name in ast.walk(generator.target): if isinstance(name, ast.Name): - self._targets[name.id].append((generator.iter, False)) + self._targets[name.id].append(generator.iter) def child_name(self, name: str) -> str: - return self._enclosing.child_name(name) + return self.enclosing.child_name(name) + + def target_iterables(self, name: str) -> list[ast.expr] | None: + """The iterables ``name`` takes items from, if it is a loop target here.""" + + return self._targets.get(name) def bindings_of(self, name: str) -> list[_Binding] | None: if name in self._targets: - return self._targets[name] - return self._enclosing.bindings_of(name) + return [(iterable, 1) for iterable in self._targets[name]] + return self.enclosing.bindings_of(name) def is_parameter(self, name: str) -> bool: - return name in self._targets or self._enclosing.is_parameter(name) + return name in self._targets or self.enclosing.is_parameter(name) def _nodes_in_scope(roots: Iterable[ast.AST]) -> Iterator[ast.AST]: @@ -511,10 +716,16 @@ def _statements(tree: ast.Module) -> Iterator[ast.AST]: stack.extend(reversed(children)) -class _NumpyNames: - """The names one module binds to NumPy, to resolve ``np.add.at`` and the like. +def _is_library_module(module: str) -> bool: + return any( + module == library or module.startswith(f"{library}.") for library in _LIBRARIES + ) + - ``derived_names`` are names some statement assigns a NumPy object to +class _LibraryNames: + """The names one module binds to NumPy and SciPy, to resolve ``np.add.at``. + + ``derived_names`` are names some statement assigns a library object to (``plus = np.add``); the scanner follows them through the bindings of the scope that uses them. """ @@ -525,16 +736,18 @@ def __init__(self, tree: ast.Module) -> None: for node in statements: if isinstance(node, ast.Import): for alias in node.names: - if alias.name == "numpy" or alias.name.startswith("numpy."): - if alias.asname: - self._aliases[alias.asname] = alias.name - else: - self._aliases["numpy"] = "numpy" + if not _is_library_module(alias.name): + continue + if alias.asname: + self._aliases[alias.asname] = alias.name + else: + root = alias.name.split(".", 1)[0] + self._aliases[root] = root elif ( isinstance(node, ast.ImportFrom) and node.level == 0 and node.module is not None - and (node.module == "numpy" or node.module.startswith("numpy.")) + and _is_library_module(node.module) ): for alias in node.names: self._aliases[alias.asname or alias.name] = ( @@ -561,7 +774,7 @@ def bound_names(self) -> frozenset[str]: return frozenset(self._aliases) def resolve(self, expression: ast.expr) -> str | None: - """The dotted NumPy name of ``expression`` (``numpy.add.at``), if any.""" + """The dotted library name of ``expression`` (``numpy.add.at``), if any.""" attributes: list[str] = [] while isinstance(expression, ast.Attribute): @@ -579,8 +792,8 @@ def resolve(self, expression: ast.expr) -> str | None: #: A dot before an attribute, allowing spaces and backslash continuations. _DOT = r"\.(?:\s|\\)*" -#: Text found in every refused expression, except NumPy names, names bound to -#: NumPy objects, and writes through a name bound to a writable view. +#: Text found in every refused expression, except library names, names bound +#: to library objects, and writes through a name bound to a writable view. _TRIGGER_TEXT = ( r"setflags|writeable|WRITEABLE|\bflags\b|copyto|shuffle|\bout\s*=" rf"|{_DOT}_(?:ndarray|mgr|values|data|mask|codes|get_column_array" @@ -588,7 +801,9 @@ def resolve(self, expression: ast.expr) -> str | None: ) _WRITABLE_VIEW_TEXT = re.compile(rf"{_DOT}(?:array|base|asi8)\b") #: A module without any of this text cannot hold a finding and is not parsed. -_FILE_TRIGGERS = re.compile(rf"{_TRIGGER_TEXT}|numpy|{_WRITABLE_VIEW_TEXT.pattern}") +_FILE_TRIGGERS = re.compile( + rf"{_TRIGGER_TEXT}|numpy|scipy|{_WRITABLE_VIEW_TEXT.pattern}" +) class _TriggerLines: @@ -619,24 +834,32 @@ def may_hold_finding(self, statement: ast.stmt) -> bool: return index < len(self._lines) and self._lines[index] <= last -# NumPy lookups ------------------------------------------------------------- +# Library lookups ----------------------------------------------------------- @functools.cache -def _numpy_object(dotted_name: str) -> object | None: - found: object = np - for part in dotted_name.split(".")[1:]: - found = getattr(found, part, None) - if found is None: - return None - return found +def _library_object(dotted_name: str) -> object | None: + """The NumPy or SciPy object a dotted name names, importing its module.""" + + parts = dotted_name.split(".") + for split in range(len(parts), 0, -1): + try: + found: object = importlib.import_module(".".join(parts[:split])) + except ImportError: + continue + for part in parts[split:]: + found = getattr(found, part, None) + if found is None: + return None + return found + return None @functools.cache def _positional_outputs(dotted_name: str) -> slice | None: - """Which positional arguments of a NumPy function or ufunc are outputs.""" + """Which positional arguments of a library function or ufunc are outputs.""" - function = _numpy_object(dotted_name) + function = _library_object(dotted_name) if isinstance(function, np.ufunc): return slice(function.nin, None) if not callable(function): @@ -655,6 +878,11 @@ def _positional_outputs(dotted_name: str) -> slice | None: return None +def _is_ufunc_method(dotted_name: str, methods: Iterable[str]) -> bool: + owner, _, method = dotted_name.rpartition(".") + return method in methods and isinstance(_library_object(owner), np.ufunc) + + def _is_false_constant(expression: ast.expr) -> bool: return isinstance(expression, ast.Constant) and not expression.value @@ -684,24 +912,27 @@ def _is_own_object(expression: ast.expr) -> bool: # The scanner --------------------------------------------------------------- +#: How a name is looked up while a scope's table is computed. +_NameLookup = Callable[[str], object] + class _Scanner: def __init__(self, source: str, path: str, tree: ast.Module) -> None: self._source = source self._path = path self._tree = tree - self._numpy = _NumpyNames(tree) - # A write through a name bound to a writable view holds no trigger - # text of its own, so a module that reads one is scanned in full. + self._libraries = _LibraryNames(tree) lone_carriage_return = "\r" in source and "\r" in source.replace("\r\n", "") # Without ``.array``, ``.base`` or ``.asi8`` text, nothing in the - # module can reach a writable view. + # module can reach a writable view. A write through a name bound to + # one holds no trigger text of its own, so a module with that text + # is scanned in full. self._has_writable_views = bool(_WRITABLE_VIEW_TEXT.search(source)) self._trigger_lines = ( None if lone_carriage_return or self._has_writable_views else _TriggerLines( - source, self._numpy.bound_names | self._numpy.derived_names + source, self._libraries.bound_names | self._libraries.derived_names ) ) self._module_scope = _Scope("", tree) @@ -768,14 +999,13 @@ def _function_digest(self) -> str: def _report(self, node: ast.AST, rule: str) -> None: segment = ast.get_source_segment(self._source, node) or ast.unparse(node) - code = " ".join(segment.split()) self.findings.append( Finding( path=self._path, line=node.lineno, function=self._scope.qualified_name, rule=rule, - code=code if len(code) <= 120 else code[:117] + "...", + code=" ".join(segment.split()), function_digest=self._function_digest(), ) ) @@ -787,10 +1017,16 @@ def _bindings(self, name: str) -> list[_Binding] | None: return self._scope.bindings_of(name) + def _owning_scope(self) -> _Scope: + scope = self._scope + while isinstance(scope, _ComprehensionScope): + scope = scope.enclosing + return scope + def _resolve(self, expression: ast.expr) -> str | None: - """The dotted NumPy name of ``expression``, following ``plus = np.add``.""" + """The dotted library name of ``expression``, following ``plus = np.add``.""" - name = self._numpy.resolve(expression) + name = self._libraries.resolve(expression) if name is not None: return name attributes: list[str] = [] @@ -798,26 +1034,92 @@ def _resolve(self, expression: ast.expr) -> str | None: while isinstance(root, ast.Attribute): attributes.append(root.attr) root = root.value - if not isinstance(root, ast.Name) or root.id not in self._numpy.derived_names: + if ( + not isinstance(root, ast.Name) + or root.id not in self._libraries.derived_names + ): return None bindings = self._bindings(root.id) if bindings is None and not self._scope.is_parameter(root.id): bindings = self._module_scope.bindings_of(root.id) - if not bindings or not all(exact for _value, exact in bindings): + if not bindings or any(items_taken for _value, items_taken in bindings): return None - resolved = {self._numpy.resolve(value) for value, _exact in bindings if value} + resolved = { + self._libraries.resolve(value) for value, _items in bindings if value + } if len(resolved) != 1 or None in resolved: return None return ".".join([resolved.pop(), *reversed(attributes)]) - def _call_newness(self, call: ast.Call) -> int: + # How new a value is ---------------------------------------------------- + + def _name_newness(self, name: str) -> int: + """How new ``name``'s value is where it is used, in the current scope.""" + + scope = self._scope + while isinstance(scope, _ComprehensionScope): + if scope.target_iterables(name) is not None: + return _NOT_NEW + scope = scope.enclosing + return self._newness_table(scope).get(name, _NOT_NEW) + + def _newness_table(self, scope: _Scope) -> dict[str, int]: + """How new each local name of ``scope`` is. + + Every name starts at the newest level and is lowered to the oldest + level any of its bindings gives, until nothing changes, so a name + bound to itself (``values = values[:n]``) is as new as its other + bindings make it. A binding to None is a placeholder that holds no + array. + """ + + if scope.newness_table is not None: + return scope.newness_table + saved_scope, self._scope = self._scope, scope + levels: dict[str, int] = {} + candidates: dict[str, list[ast.expr]] = {} + for name, bindings in scope.local_bindings().items(): + kept = [ + (value, items_taken) + for value, items_taken in bindings + if not (items_taken == 0 and _is_none(value)) + ] + if not kept or any(value is None or items for value, items in kept): + levels[name] = _NOT_NEW + else: + levels[name] = _NEW_ARRAY + candidates[name] = [value for value, _items in kept] + + def lookup(name: str) -> int: + return levels.get(name, _NOT_NEW) + + changed = True + try: + while changed: + changed = False + for name, values in candidates.items(): + if levels[name] == _NOT_NEW: + continue + level = min(self._newness(value, lookup) for value in values) + if level < levels[name]: + levels[name] = level + changed = True + finally: + self._scope = saved_scope + scope.newness_table = levels + return levels + + def _call_newness(self, call: ast.Call, lookup: _NameLookup | None) -> int: if self._output_arguments(call): return _NOT_NEW name = self._resolve(call.func) + function = call.func if name is not None: if name in _ALLOCATING_NUMPY_FUNCTIONS: return _NEW_ARRAY - if isinstance(_numpy_object(name), np.ufunc): + if isinstance(_library_object(name), np.ufunc): + return _NEW_ARRAY + if _is_ufunc_method(name, _ALLOCATING_UFUNC_METHODS): return _NEW_ARRAY if ( name.startswith("numpy.random.") @@ -826,16 +1128,32 @@ def _call_newness(self, call: ast.Call) -> int: return _NEW_ARRAY if name == "numpy.array": return _NOT_NEW if _copy_is_off(call) else _NEW_ARRAY + if name in _VIEW_NUMPY_FUNCTIONS and call.args: + # A view of a new array, or an array made from a new container. + source = self._newness(call.args[0], lookup) + return _NEW_ARRAY if source >= _NEW_OBJECT else _NOT_NEW return _NOT_NEW - function = call.func if isinstance(function, ast.Name) and function.id in _CONTAINER_BUILTINS: return _NEW_OBJECT if not isinstance(function, ast.Attribute): return _NOT_NEW - if function.attr == "to_numpy": + method = function.attr + if method == "to_numpy": copy = _keyword(call, "copy") - return _NEW_ARRAY if copy and _is_true_constant(copy.value) else _NOT_NEW - if function.attr == "copy": + copy_value = copy.value if copy is not None else None + if copy_value is None and len(call.args) >= 2: + copy_value = call.args[1] + return ( + _NEW_ARRAY + if copy_value is not None and _is_true_constant(copy_value) + else _NOT_NEW + ) + if method == "flatten" or method in _RANDOM_DRAW_METHODS: + return _NEW_ARRAY + if method in _VIEW_METHODS: + receiver = self._newness(function.value, lookup) + return _NEW_ARRAY if receiver == _NEW_ARRAY else _NOT_NEW + if method == "copy": deep = _keyword(call, "deep") if deep is not None and not _is_true_constant(deep.value): return _NOT_NEW @@ -848,14 +1166,11 @@ def _call_newness(self, call: ast.Call) -> int: return _NEW_OBJECT return _NOT_NEW - def _newness( - self, expression: ast.expr, assumed: Mapping[str, int] | None = None - ) -> int: + def _newness(self, expression: ast.expr, lookup: _NameLookup | None = None) -> int: """How new the value of ``expression`` is (``_NOT_NEW`` to ``_NEW_ARRAY``).""" - assumed = assumed or {} if isinstance(expression, ast.Subscript): - container = self._newness(expression.value, assumed) + container = self._newness(expression.value, lookup) if container == _NEW_ARRAY: return _NEW_ARRAY if container == _NEW_OBJECT and isinstance(expression.slice, ast.Slice): @@ -863,61 +1178,157 @@ def _newness( return _NOT_NEW if isinstance(expression, ast.IfExp): return min( - self._newness(expression.body, assumed), - self._newness(expression.orelse, assumed), + self._newness(expression.body, lookup), + self._newness(expression.orelse, lookup), ) if isinstance(expression, ast.BoolOp): - return min(self._newness(value, assumed) for value in expression.values) + return min(self._newness(value, lookup) for value in expression.values) if isinstance(expression, ast.Call): - return self._call_newness(expression) - if isinstance(expression, _NEW_VALUE_EXPRESSIONS): + return self._call_newness(expression, lookup) + if isinstance(expression, ast.BinOp): + if isinstance(expression.op, _JOINING_OPERATORS): + return _NEW_OBJECT + return _NEW_ARRAY + if isinstance(expression, _NEW_ARRAY_EXPRESSIONS): return _NEW_ARRAY if isinstance(expression, _CONTAINER_EXPRESSIONS): return _NEW_OBJECT - if not isinstance(expression, ast.Name): - return _NOT_NEW - name = expression.id - if name in assumed: - return assumed[name] - # A binding to None is a placeholder that holds no array. - bindings = [ - (value, exact) - for value, exact in self._bindings(name) or [] - if not (exact and _is_none(value)) - ] - if not bindings or any(value is None or not exact for value, exact in bindings): - return _NOT_NEW - # A binding may refer back to the name (values = values[:n]), so - # start from the newest level and lower it until it holds. - level = _NEW_ARRAY - while True: - inner = {**assumed, name: level} - result = min(self._newness(value, inner) for value, _exact in bindings) - if result >= level: - return level - level = result - - def _reaches_writable_view( - self, expression: ast.expr, following: frozenset[str] = frozenset() - ) -> bool: - """Whether ``expression`` can be, or hold, a writable view of pandas' memory.""" + if isinstance(expression, ast.Name): + if lookup is not None: + return lookup(expression.id) + return self._name_newness(expression.id) + return _NOT_NEW + + # Whether a value can be a writable view -------------------------------- + + def _name_view_depth(self, name: str) -> int: + """How deep in containers ``name`` holds a writable view, where it is used.""" + + scope = self._scope + while isinstance(scope, _ComprehensionScope): + iterables = scope.target_iterables(name) + if iterables is not None: + self._scope = scope.enclosing + try: + return min(_item_of(self._view_depth(item)) for item in iterables) + finally: + self._scope = scope + scope = scope.enclosing + return self._view_table(scope).get(name, _NO_VIEW) + + def _view_table(self, scope: _Scope) -> dict[str, int]: + """How deep in containers each name of ``scope`` holds a writable view. + + Starts every name at ``_NO_VIEW`` and lowers it to the smallest depth + any of its bindings or held values gives, until nothing changes. A + binding that takes items of its value (a loop target, unpacking) + takes one level per item; a container filled with a value holds it + one level deeper. + """ + + if scope.view_table is not None: + return scope.view_table + saved_scope, self._scope = self._scope, scope + sources: defaultdict[str, list[tuple[ast.expr, int]]] = defaultdict(list) + for name, bindings in scope.local_bindings().items(): + for value, items_taken in bindings: + if value is not None: + sources[name].append((value, -items_taken)) + # A container filled here may be a parameter, so held values count + # for any name. + for name in scope.held_names(): + for value, adds_level in scope.held_values(name): + sources[name].append((value, 1 if adds_level else 0)) + depths: dict[str, int] = dict.fromkeys(sources, _NO_VIEW) + + def lookup(name: str) -> int: + return depths.get(name, _NO_VIEW) + + changed = True + try: + while changed: + changed = False + for name, parts in sources.items(): + if depths[name] == _IS_VIEW: + continue + depth = min( + _shifted(self._view_depth(value, lookup), shift) + for value, shift in parts + ) + if depth < depths[name]: + depths[name] = depth + changed = True + finally: + self._scope = saved_scope + scope.view_table = depths + return depths + + def _is_container(self, expression: ast.expr) -> bool: + if isinstance(expression, _CONTAINER_EXPRESSIONS): + return True + if isinstance(expression, ast.Call) and isinstance(expression.func, ast.Name): + return expression.func.id in _CONTAINER_BUILTINS + if isinstance(expression, ast.Name): + bindings = self._bindings(expression.id) or [] + return bool(bindings) and all( + value is not None + and items_taken == 0 + and isinstance(value, _CONTAINER_EXPRESSIONS) + for value, items_taken in bindings + ) + return False + + def _reaches_writable_view(self, expression: ast.expr) -> bool: + """Whether ``expression`` can be a writable view of pandas' memory.""" + + return self._view_depth(expression) == _IS_VIEW + + def _view_depth( + self, expression: ast.expr, lookup: _NameLookup | None = None + ) -> int: + """How deep in containers ``expression`` holds a writable view. + + ``_IS_VIEW`` (0) for a view itself, 1 for a container of views, 2 + for a container of those, up to ``_NO_VIEW`` for none. + """ if not self._has_writable_views: - return False + return _NO_VIEW if isinstance(expression, ast.Attribute): if expression.attr in _WRITABLE_VIEW_ATTRIBUTES: - return not _is_own_object(expression.value) + return _NO_VIEW if _is_own_object(expression.value) else _IS_VIEW if expression.attr in _VIEW_ATTRIBUTES: - return self._reaches_writable_view(expression.value, following) - return False - if isinstance(expression, (ast.Subscript, ast.Starred)): - return self._reaches_writable_view(expression.value, following) + return _view_of(self._view_depth(expression.value, lookup)) + return _NO_VIEW + if isinstance(expression, ast.Subscript): + return _item_of(self._view_depth(expression.value, lookup)) + if isinstance(expression, ast.Starred): + return self._view_depth(expression.value, lookup) + if isinstance(expression, ast.Name): + if lookup is not None: + return lookup(expression.id) + return self._name_view_depth(expression.id) if isinstance(expression, ast.IfExp): - parts: list[ast.expr] = [expression.body, expression.orelse] - elif isinstance(expression, ast.BoolOp): - parts = list(expression.values) - elif isinstance(expression, (ast.List, ast.Tuple, ast.Set)): - parts = list(expression.elts) + return min( + self._view_depth(expression.body, lookup), + self._view_depth(expression.orelse, lookup), + ) + if isinstance(expression, ast.BoolOp): + return min(self._view_depth(value, lookup) for value in expression.values) + if isinstance(expression, ast.BinOp): + # ``[a.array] + rest`` joins lists; arithmetic gives new memory. + joins = isinstance(expression.op, _JOINING_OPERATORS) and ( + self._is_container(expression.left) + or self._is_container(expression.right) + ) + if not joins: + return _NO_VIEW + return min( + self._view_depth(expression.left, lookup), + self._view_depth(expression.right, lookup), + ) + if isinstance(expression, (ast.List, ast.Tuple, ast.Set)): + parts: list[ast.expr] = list(expression.elts) elif isinstance(expression, ast.Dict): parts = list(expression.values) elif isinstance(expression, (ast.ListComp, ast.SetComp, ast.GeneratorExp)): @@ -925,34 +1336,77 @@ def _reaches_writable_view( elif isinstance(expression, ast.DictComp): parts = [expression.value] elif isinstance(expression, ast.Call): - parts = self._view_call_sources(expression) - elif isinstance(expression, ast.Name) and expression.id not in following: - parts = [ - value for value, _exact in self._bindings(expression.id) or [] if value - ] - following = following | {expression.id} + return self._call_view_depth(expression, lookup) else: - return False - return any(self._reaches_writable_view(part, following) for part in parts) + return _NO_VIEW + return _holder_of( + min((self._view_depth(part, lookup) for part in parts), default=_NO_VIEW) + ) - def _view_call_sources(self, call: ast.Call) -> list[ast.expr]: - """The expressions a call's result can be a view of.""" + def _call_view_depth(self, call: ast.Call, lookup: _NameLookup | None) -> int: + arguments = [*call.args, *(keyword.value for keyword in call.keywords)] + + def nearest(expressions: Iterable[ast.expr]) -> int: + return min( + (self._view_depth(expression, lookup) for expression in expressions), + default=_NO_VIEW, + ) name = self._resolve(call.func) + if name in _SPLITTING_NUMPY_FUNCTIONS: + return _holder_of(_view_of(nearest(arguments))) if name in _VIEW_NUMPY_FUNCTIONS or ( - name == "numpy.array" and _copy_is_off(call) + name in ("numpy.array", "numpy.astype") and _copy_is_off(call) ): - return [*call.args, *(keyword.value for keyword in call.keywords)] + return _view_of(nearest(arguments)) function = call.func - if isinstance(function, ast.Attribute): - if function.attr in _VIEW_METHODS: - copy = _keyword(call, "copy") - if copy is not None and _is_true_constant(copy.value): - return [] - return [function.value] - if function.attr == "astype" and _copy_is_off(call): - return [function.value] - return [] + if isinstance(function, ast.Name): + if function.id == "next": + return _item_of(nearest(arguments)) + if function.id in _SAME_ITEMS_BUILTINS: + # A new container of the argument's items. + return _holder_of(_item_of(nearest(arguments))) + if function.id in _TUPLE_YIELDING_BUILTINS: + # A new container of tuples of the arguments' items. + return _holder_of(_holder_of(_item_of(nearest(arguments)))) + return _NO_VIEW + if not isinstance(function, ast.Attribute): + return _NO_VIEW + method = function.attr + receiver = function.value + if method in _VIEW_METHODS: + copy = _keyword(call, "copy") + if copy is not None and _is_true_constant(copy.value): + return _NO_VIEW + return _view_of(self._view_depth(receiver, lookup)) + if method == "astype" and _copy_is_off(call): + return _view_of(self._view_depth(receiver, lookup)) + if method == "copy": + # A copy of an array is new memory; of a container, it holds the + # same items. + depth = self._view_depth(receiver, lookup) + return _NO_VIEW if depth == _IS_VIEW else depth + if method in _ITEM_TAKING_METHODS: + return _item_of(self._view_depth(receiver, lookup)) + if method in _SAME_ITEMS_METHODS: + return _holder_of(_item_of(self._view_depth(receiver, lookup))) + if method in _TUPLE_YIELDING_METHODS: + return _holder_of(_holder_of(_item_of(self._view_depth(receiver, lookup)))) + return _NO_VIEW + + def _bound_to_a_view(self, name: str) -> bool: + """Whether some binding sets ``name`` to exactly a writable view.""" + + if isinstance(self._scope, _ComprehensionScope) and ( + self._scope.target_iterables(name) is not None + ): + return False + return any( + items_taken == 0 + and value is not None + and self._reaches_writable_view(value) + for value, items_taken in self._bindings(name) or [] + ) def _check_written_array(self, node: ast.AST, written: ast.expr) -> None: """Report a write into ``written`` unless it is new in this function.""" @@ -972,8 +1426,8 @@ def _output_arguments(self, call: ast.Call) -> list[ast.expr]: function = call.func method = function.attr if isinstance(function, ast.Attribute) else None output = _keyword(call, "out") - # ``out=`` means an output array only to NumPy and to array and random - # Generator methods; workspace functions use it for output paths. + # ``out=`` means an output array only to the libraries and to array + # and random Generator methods; workspace functions use it for paths. if output is not None and (name is not None or method in _METHODS_WITH_OUT): if isinstance(output.value, (ast.Tuple, ast.List)): written.extend( @@ -991,7 +1445,7 @@ def _output_arguments(self, call: ast.Call) -> list[ast.expr]: return [*written, *call.args[:1]] if name == "numpy.nan_to_num" and _copy_is_off(call): return [*written, *call.args[:1]] - if name.endswith(".at") and isinstance(_numpy_object(name[:-3]), np.ufunc): + if _is_ufunc_method(name, ("at",)): return [*written, *call.args[:1]] outputs = _positional_outputs(name) return written if outputs is None else [*written, *call.args[outputs]] @@ -1063,10 +1517,9 @@ def _check_annotated_assign(self, node: ast.AnnAssign) -> None: self._check_assigned_target(node, node.target, node.value) def _check_augmented_assign(self, node: ast.AugAssign) -> None: - # ``values += 1`` writes into the array ``values`` names. - if isinstance(node.target, ast.Name) and self._reaches_writable_view( - node.target - ): + # ``values += 1`` writes into the array ``values`` names; a name that + # only takes items of a view (a loop target) may hold scalars. + if isinstance(node.target, ast.Name) and self._bound_to_a_view(node.target.id): self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) else: self._check_assigned_target(node, node.target, None) @@ -1223,6 +1676,164 @@ def _in_function(*body_lines: str, parameters: str = "series") -> str: #: Snippets the scan must refuse, with the one rule each must report. _REFUSED_SNIPPETS = { + # Round-two cases: views reached through iteration and filled containers. + "series_array_through_zip": ( + _in_function( + "arrays = [frame[name].array for name in names]", + "for name, values in zip(names, arrays):", + " values[0] = 1", + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_enumerate": ( + _in_function( + "arrays = [frame[name].array for name in names]", + "for position, values in enumerate(arrays):", + " values[0] = position", + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_dict_items": ( + _in_function( + "arrays = {name: frame[name].array for name in names}", + "for name, values in arrays.items():", + " values[0] = 1", + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_dict_get": ( + _in_function( + "arrays = {name: frame[name].array for name in names}", + 'arrays.get("income")[0] = 1', + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_appended": ( + _in_function( + "arrays = []", + "for name in names:", + " arrays.append(frame[name].array)", + "arrays[0][0] = 1", + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_appended_to_a_parameter": ( + _in_function( + "arrays.append(series.array)", + "arrays[0][0] = 1", + parameters="series, arrays", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_stored_by_key": ( + _in_function( + "columns = {}", + "for name in names:", + " columns[name] = frame[name].array", + 'columns["income"][0] = 1', + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_added_with_augmented_assignment": ( + _in_function( + "arrays = []", + "arrays += [series.array]", + "arrays[0][0] = 1", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_in_joined_lists": ( + _in_function( + "pair = [first.array] + [second.array]", + "pair[0][0] = 1", + parameters="first, second", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_split": ( + _in_function( + "parts = np.split(np.asarray(series.array), 2)", "parts[0][0] = 1" + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_broadcast": ( + _in_function( + "left, right = np.broadcast_arrays(np.asarray(series.array), 0)", + "left[0] = 1", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_required": ( + _NUMPY + "np.require(series.array)[0] = 1\n", + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_swapped_axes_method": ( + _NUMPY + "np.asarray(series.array).swapaxes(0, 0)[0] = 1\n", + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_matrix_transpose_attribute": ( + _NUMPY + "np.atleast_2d(series.array).mT[0, 0] = 1\n", + _WRITES_THROUGH_WRITABLE_VIEW, + ), + # Round-two cases: arrays that are not new. + "ufunc_at_on_item_of_joined_new_list": ( + _in_function( + "columns = [frame[name].to_numpy() for name in names] + []", + "np.add.at(columns[0], [0], 1)", + parameters="frame, names", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), + "ufunc_at_on_clip_of_a_series": ( + _in_function( + 'np.add.at(np.clip(frame["f"], 0, None), positions, weights)', + parameters="frame, positions, weights", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), + "ufunc_at_on_tile_of_a_series": ( + _in_function("np.add.at(np.tile(series, 1), [0], 1)"), + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_round_of_a_parameter": ( + _in_function( + "rounded = np.round(values)", + "np.add(rounded, 1, out=rounded)", + parameters="values", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_scipy_ufunc_keyword": ( + "import scipy.special\n" + + "def change(values):\n" + + " scipy.special.expit(values, out=values)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_scipy_ufunc_positional": ( + "from scipy.special import expit\n" + + "def change(values):\n" + + " expit(values, values)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "series_array_in_a_shallow_dict_copy": ( + _in_function( + "arrays = {name: frame[name].array for name in names}", + "copied = arrays.copy()", + 'copied["income"][0] = 1', + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "numpy_random_mtrand_shuffle": ( + _in_function("np.random.mtrand.shuffle(values)", parameters="values"), + _WRITES_INTO_EXISTING_ARRAY, + ), # makes-array-writable "setflags_write_true": ( "values = series.to_numpy()\nvalues.setflags(write=True)\nvalues[0] = 1.0\n", @@ -1768,6 +2379,66 @@ def test_the_scanner_refuses_each_unprotected_write(source: str, rule: str) -> N #: Snippets the scan must accept: reads, read-only flags, and writes into #: arrays the same function created. _ACCEPTED_SNIPPETS = { + # Round-two cases. + "long_chain_of_views_of_a_new_array": _in_function( + "chain_0 = np.zeros(64)", + *( + f"chain_{index} = chain_{index - 1}[1:] if flag else chain_{index - 1}[:-1]" + for index in range(1, 40) + ), + "np.add(chain_39, 1, out=chain_39)", + parameters="flag", + ), + "generator_draws": _in_function( + "draws = rng.normal(size=size)", + "np.multiply(draws, 2, out=draws)", + "sample = np.random.default_rng(seed).random(size)", + "np.add(sample, 1, out=sample)", + parameters="rng, seed, size", + ), + "flattened_reshaped_and_listed_new_arrays": _in_function( + "flat = values.flatten()", + "np.add(flat, 1, out=flat)", + "grid = np.empty(6).reshape(2, 3)", + "np.add(grid, 1, out=grid)", + "listed = np.asarray([1.0, 2.0])", + "np.add(listed, 1, out=listed)", + parameters="values", + ), + "ufunc_reductions_and_interpolation": _in_function( + "peaks = np.maximum.accumulate(values)", + "np.add(peaks, 1, out=peaks)", + "curve = np.interp(points, xp, fp)", + "np.add(curve, 1, out=curve)", + parameters="values, points, xp, fp", + ), + "positional_copy_to_numpy": _in_function( + "values = series.to_numpy(float, True)", "np.add(values, 1, out=values)" + ), + "copy_of_a_view_written": _in_function( + "encoded = series.array.asi8.copy()", "encoded[0] = 0" + ), + "list_of_a_view_reassigned": _in_function( + "items = list(series.array)", "items[0] = 1" + ), + "frame_holding_a_view_written_by_column": _in_function( + "carried = table.copy()", + "carried['id'] = replacement.array", + "tables = {}", + "tables['person'] = carried", + "tables['person']['income'] = aligned.array", + parameters="table, replacement, aligned", + ), + "arithmetic_on_a_view_written": _in_function( + "doubled = np.asarray(series.array) * 2", "doubled[0] = 0" + ), + "scipy_ufunc_into_new_array": ( + "import numpy as np\n" + + "import scipy.special\n" + + "def change(values):\n" + + " result = np.empty(3)\n" + + " scipy.special.expit(values, out=result)\n" + ), "setflags_read_only": "values.setflags(write=False)\nvalues.setflags(write=0)\n", "setflags_alignment_only": "values.setflags(align=True)\n", "flags_read_only": ( @@ -1893,11 +2564,11 @@ def test_the_scanner_refuses_each_unprotected_write(source: str, rule: str) -> N "list_builtin_shuffled": _in_function( "order = list(range(size))", "np.random.shuffle(order)", parameters="size" ), - "random_and_rounded_results": _in_function( + "random_results": _in_function( "order = np.random.permutation(size)", "np.add(order, 1, out=order)", - "rounded = np.round(values)", - "np.add(rounded, 1, out=rounded)", + "chosen = np.random.choice(values, 3)", + "np.add(chosen, 1, out=chosen)", parameters="size, values", ), "generator_method_into_new_array": _in_function( From 11a9a9b4a86f690c8ea68b62264185d23c476a5a Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:41:43 +0400 Subject: [PATCH 04/15] Fix the third round of review findings in Frame and the write scan Frame: fix two docstring claims (the order of _adopt's checks, which weight columns with_columns refuses). Under pandas 2.x the copy-on-write-off tests now turn copy-on-write off for real, and the check is tested with a version string that does not start with a number. Scan: - An item of a view is now an element, which may be a scalar. Writes into views and elements are refused, but augmented assignment only into a view itself, so accumulating scalars taken from a view is accepted. - `+=` adds a value's items to a container, so a running total of view columns no longer counts as a view. - Comprehension elements see their own loop targets, and later generators see earlier ones. - for-targets over zip, enumerate and .items() are paired with their own sources. - Displays and dicts unpacked with * and ** pass on their items. - dict | joins containers; * on an array is arithmetic. - .get(key, default) includes its default. - Unpacking into subscripts counts items. - Views, subscripts and items of new arrays count as new. - np.take is treated as a possible view of a pandas object. - .base counts only on array expressions. - copy=True by keyword or position stops a view. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/frame/bundle.py | 9 +- .../shared/test_frame_table_sharing.py | 30 +- .../shared/test_shared_buffer_writes.py | 770 +++++++++++++----- 3 files changed, 597 insertions(+), 212 deletions(-) diff --git a/packages/microcosm-frame/src/microcosm/frame/bundle.py b/packages/microcosm-frame/src/microcosm/frame/bundle.py index e9dd10a6f7..56597ec207 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -161,9 +161,9 @@ def _adopt( 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 other check (the - constructor fails on such a table later, with an error that depends - on the object). Weights are stored as given (their arrays are + not a DataFrame raises ``TypeError`` before any table is stored or + checked (the constructor fails on such a table later, with an error + that depends on the object). Weights are stored as given (their arrays are read-only), and the strata are shallow-copied when copy-on-write is on. @@ -984,7 +984,8 @@ def with_columns(self, entity: str, /, **columns: Any) -> "Frame": ValueError: If ``entity`` is not declared by the schema, a value's length does not match the table, or the new columns break a constructor invariant (a name another table already carries, - a reserved ``{entity}_weight`` name, or broken linkage). + an ``{entity}_weight`` name on a table whose entity has no + typed weights, or broken linkage). """ table = self.table(entity).copy(deep=False) 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 e6b6c50123..ceb9f7aa4c 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 @@ -105,11 +105,14 @@ def source_frame() -> Frame: ) +_PANDAS_3 = int(pd.__version__.split(".", 1)[0]) >= 3 + + @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: + if _PANDAS_3: yield return with pd.option_context("mode.copy_on_write", True): @@ -117,10 +120,17 @@ 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.""" +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.""" - monkeypatch.setattr(bundle_module, "_pandas_copy_on_write", lambda: False) + if _PANDAS_3: + monkeypatch.setattr(bundle_module, "_pandas_copy_on_write", lambda: False) + yield + return + with pd.option_context("mode.copy_on_write", False): + assert not bundle_module._pandas_copy_on_write() + yield def _tables_of(frame: Frame) -> dict[str, pd.DataFrame]: @@ -590,8 +600,18 @@ def test_pandas_2_uses_pandas_own_check( ("2.3.3", "warn", False), ("0+unknown", True, True), ("0+unknown", False, False), + ("unknown", True, True), + ("", False, False), + ], + ids=[ + "enabled", + "disabled", + "warn_mode", + "undotted_on", + "undotted_off", + "no_leading_number", + "empty", ], - ids=["enabled", "disabled", "warn_mode", "undotted_on", "undotted_off"], ) def test_without_pandas_own_check_an_older_version_reads_the_option( self, 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 b1939efaea..3d04370f50 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 @@ -16,22 +16,28 @@ read-only views of the shared memory; this makes them writable. ``writes-through-writable-view`` A write into a writable view of pandas' memory: ``.array`` (of a Series - or Index), ``.base`` (the writable array behind a read-only view) or - ``.asi8`` (datetime data). Writes are item assignment, augmented + or Index), ``.asi8`` (datetime data), or ``.base`` read from an array + expression (a call such as ``to_numpy()``, or ``.values``), which is + the writable array behind a read-only view. Writes are item assignment, ``__setitem__``, ``fill``, ``sort`` and the other in-place ndarray methods, ``fillna(copy=False)``, ``out=``, ``shuffle`` and the - in-place NumPy functions below. It counts when the written expression - reaches the view through indexing, the NumPy functions that can return - a view (``np.asarray``, ``np.flip``, ``np.split``, ... in - ``_VIEW_NUMPY_FUNCTIONS``), ``to_numpy()``, ``astype(copy=False)`` and - the other view methods, a list, tuple, set or dict display or - comprehension holding it (also concatenated with ``+``), ``zip``, - ``enumerate``, ``.items()``, ``.values()`` and ``.get()``, ``or`` and + in-place NumPy functions below, into the view or into an item of it (a + row of a two-dimensional view is a view too), and ``+=`` and the other + augmented assignments into the view itself (an item of a + one-dimensional view is a scalar, which ``+=`` rebinds). It counts + when the written expression reaches the view through indexing, the + NumPy functions that can return a view (``np.asarray``, ``np.flip``, + ``np.split``, ... in ``_VIEW_NUMPY_FUNCTIONS``), ``to_numpy()``, + ``astype(copy=False)`` and the other view methods, a list, tuple, set + or dict display or comprehension holding it (also with ``*``/``**`` + unpacking, ``+`` or ``|``), ``zip``, ``enumerate``, ``.items()``, + ``.values()`` and ``.get()`` (with its default), ``or`` and conditional expressions, or a name the same function binds to any of - these (by assignment, unpacking, a ``for`` loop or a ``with`` - statement) or fills with one (``append``, ``extend``, ``update``, - ``name[key] = ...``, ``+=``). Workspace classes' own ``self.array`` is - exempt. + these (by assignment, unpacking, a ``for`` loop, which pairs ``zip``, + ``enumerate`` and ``.items()`` targets with their own sources, or a + ``with`` statement) or fills with one (``append``, ``extend``, + ``update``, ``name[key] = ...``, ``+=``). Workspace classes' own + ``self.array`` is exempt. ``pandas-private-attribute`` ``._ndarray``, ``._mgr``, ``._get_column_array`` or ``._iter_column_arrays`` on anything, and ``._values``, ``._data``, @@ -55,8 +61,8 @@ ...), ``.flatten()``, or a NumPy function that always allocates (``_ALLOCATING_NUMPY_FUNCTIONS``: ``np.zeros``, ``np.where``, ``np.concatenate``, ...), when not given an output array; - ``np.array`` without ``copy=``; ``to_numpy(copy=True)``; a view or - subscript of one of these; arithmetic or a comparison; a ``.copy()``, + ``np.array`` without ``copy=``; ``to_numpy(copy=True)``; a view, + subscript or item (a loop target, unpacking) of one of these; arithmetic or a comparison; a ``.copy()``, ``list(...)`` and the other container builtins, ``+`` or ``*`` (which also join lists), or a list, set or dict display (a slice of these is new, an item is not, because a shallow copy or a container @@ -167,15 +173,16 @@ _OWN_OBJECT_NAMES = frozenset({"self", "cls"}) #: Attributes that return a writable view of pandas' memory. -_WRITABLE_VIEW_ATTRIBUTES = frozenset({"array", "base", "asi8"}) +#: ``.base`` counts too, when read from an array expression. +_WRITABLE_VIEW_ATTRIBUTES = frozenset({"array", "asi8"}) #: Libraries whose functions the scan resolves through imports. _LIBRARIES = ("numpy", "scipy") -#: NumPy functions whose result is always new memory, for ndarrays and for -#: pandas objects alike (unless given ``out=``). ``np.clip``, ``np.tile`` and -#: ``np.round`` are left out: given a pandas object, their result can share -#: its memory. +#: NumPy functions whose result is new memory (unless given ``out=``), +#: checked for ndarrays and for integer, float and boolean Series. +#: ``np.clip``, ``np.tile``, ``np.round`` and ``np.take`` are treated as +#: views instead: given a pandas object, their result can share its memory. _ALLOCATING_NUMPY_FUNCTIONS = frozenset( f"numpy.{name}" for name in ( @@ -189,7 +196,6 @@ "bincount", "cumsum", "cumprod", - "take", "interp", "flatnonzero", "outer", @@ -271,7 +277,10 @@ #: Arithmetic and comparisons give a new array; ``+`` and ``*`` also join or #: repeat lists, whose items are shared, so they give a new container. _NEW_ARRAY_EXPRESSIONS = (ast.UnaryOp, ast.Compare) -_JOINING_OPERATORS = (ast.Add, ast.Mult) +_JOINING_OPERATORS = (ast.Add, ast.Mult, ast.BitOr) +#: Operators that join containers holding views (``*`` repeats a list, but +#: with an array it is arithmetic, so it is left out). +_VIEW_JOINING_OPERATORS = (ast.Add, ast.BitOr) #: Displays and comprehensions: a new container whose items may be shared. _CONTAINER_EXPRESSIONS = ( ast.List, @@ -378,6 +387,9 @@ "imag", "trim_zeros", "tile", + "take", + "real_if_close", + "asmatrix", "clip", "round", "around", @@ -425,41 +437,62 @@ #: A new array: every item and view of it is new memory. _NEW_ARRAY = 2 -#: How deep in containers a value holds a writable view of pandas' memory: -#: ``_IS_VIEW`` for a view itself, 1 for a container of views, 2 for a -#: container of those, and ``_NO_VIEW`` for none (or deeper than tracked). +#: Whether, and how deep in containers, a value holds a writable view of +#: pandas' memory. ``_IS_VIEW`` is a view. ``_ELEMENT`` is an item of a view: +#: a row (itself a view) of a two-dimensional view, but a scalar of a +#: one-dimensional one. Each container level adds 2, so 2 is a container of +#: views and 3 a container of elements. ``_NO_VIEW`` is none, or deeper than +#: tracked. _IS_VIEW = 0 -_NO_VIEW = 5 +_ELEMENT = 1 +_NO_VIEW = 11 -def _item_of(depth: int) -> int: - """An item of a view (a row or slice) is a view; of a container, one level less.""" +def _item_of(level: int) -> int: + """An item of a view is an element; an item of a container, one level less.""" - if depth >= _NO_VIEW: + if level >= _NO_VIEW: return _NO_VIEW - return max(depth - 1, _IS_VIEW) + if level <= _ELEMENT: + return _ELEMENT + return level - 2 + + +def _items_taken(level: int, count: int) -> int: + for _step in range(count): + level = _item_of(level) + return level + + +def _holder_of(level: int) -> int: + """A container holding a value holds its view one level deeper.""" + return _NO_VIEW if level >= _NO_VIEW else min(level + 2, _NO_VIEW) -def _holder_of(depth: int) -> int: - """A container of a value holds its view one level deeper.""" - return min(depth + 1, _NO_VIEW) +def _items_holder_of(level: int) -> int: + """A new container of a value's items (``list(value)``, ``extend``).""" + return _holder_of(_item_of(level)) -def _shifted(depth: int, shift: int) -> int: - """``depth`` after taking ``-shift`` items, or going ``shift`` containers deeper.""" - for _step in range(-shift): - depth = _item_of(depth) - for _step in range(shift): - depth = _holder_of(depth) - return depth +def _view_of(level: int) -> int: + """A NumPy view of a view or element stays one; of a container it is a copy.""" + return level if level <= _ELEMENT else _NO_VIEW -def _view_of(depth: int) -> int: - """A NumPy view of a view is a view; of a container (a list) it is a copy.""" - return _IS_VIEW if depth == _IS_VIEW else _NO_VIEW +def _bound_level(items_taken: int, level: int) -> int: + """The level of a name bound ``items_taken`` items deep into a value.""" + + return _items_taken(level, items_taken) + + +def _held_level(items_taken: int, one_item: bool, level: int) -> int: + """The level of a container filled with a value (see ``_HeldValue``).""" + + level = _items_taken(level, items_taken) + return _holder_of(level) if one_item else _items_holder_of(level) @dataclass(frozen=True) @@ -489,14 +522,98 @@ def describe(self) -> str: #: name is bound: 0 for the value itself, 1 for a loop target (an item of #: its iterable), 2 for a name unpacked from a loop target, and so on. _Binding = tuple[ast.expr | None, int] +#: What a container is filled with: the value, how many items deep into it, +#: and whether it goes in as one item (``append``, ``name[key] = value``) +#: rather than as its items (``extend``, ``update``, ``+=``). +_HeldValue = tuple[ast.expr, int, bool] + + +def _target_names( + target: ast.expr, value: ast.expr | None, items_taken: int +) -> Iterator[tuple[ast.expr, ast.expr | None, int]]: + """The names and subscripts an assignment target binds, with their values. + + Each is yielded with the value it takes items from and how many items + deep it is bound. + """ + + if isinstance(target, (ast.Name, ast.Subscript)): + yield target, value, items_taken + elif isinstance(target, ast.Starred): + # A starred target collects items into a new list: the same depth. + yield from _target_names(target.value, value, items_taken) + elif isinstance(target, (ast.Tuple, ast.List)): + pairs = ( + items_taken == 0 + and isinstance(value, (ast.Tuple, ast.List)) + and len(value.elts) == len(target.elts) + and not any( + isinstance(element, ast.Starred) + for element in (*target.elts, *value.elts) + ) + ) + for index, element in enumerate(target.elts): + if pairs: + yield from _target_names(element, value.elts[index], 0) + elif isinstance(element, ast.Starred): + yield from _target_names(element.value, value, items_taken) + else: + yield from _target_names(element, value, items_taken + 1) + + +def _loop_target_names( + target: ast.expr, iterable: ast.expr +) -> Iterator[tuple[ast.expr, ast.expr | None, int]]: + """What a ``for`` target binds, pairing each name with its own source. + + ``for a, b in zip(x, y)`` binds ``a`` to an item of ``x`` and ``b`` to + an item of ``y``; ``enumerate`` and ``.items()`` pair the second name + with the iterable's items. + """ + + if ( + isinstance(target, (ast.Tuple, ast.List)) + and not any(isinstance(element, ast.Starred) for element in target.elts) + and isinstance(iterable, ast.Call) + and not any(isinstance(argument, ast.Starred) for argument in iterable.args) + ): + function = iterable.func + elements = target.elts + arguments = iterable.args + if ( + isinstance(function, ast.Name) + and function.id == "zip" + and len(arguments) == len(elements) + ): + for element, argument in zip(elements, arguments, strict=True): + yield from _target_names(element, argument, 1) + return + if ( + isinstance(function, ast.Name) + and function.id == "enumerate" + and len(elements) == 2 + and arguments + ): + yield from _target_names(elements[0], None, 1) + yield from _target_names(elements[1], arguments[0], 1) + return + if ( + isinstance(function, ast.Attribute) + and function.attr == "items" + and len(elements) == 2 + ): + yield from _target_names(elements[0], None, 1) + yield from _target_names(elements[1], function.value, 1) + return + yield from _target_names(target, iterable, 1) class _Scope: """One function, class or module, and the names it binds. The bindings are collected on first use, because most scopes are never - asked. ``held_values`` are the expressions a name's container is filled - with (``name.append(value)``, ``name[key] = value``, ``name += value``). + asked. ``held_values`` are what a name's container is filled with + (``name.append(value)``, ``name[key] = value``, ``name += value``). """ def __init__(self, qualified_name: str, node: ast.AST) -> None: @@ -505,7 +622,7 @@ def __init__(self, qualified_name: str, node: ast.AST) -> None: self._parameters: frozenset[str] = frozenset() self._declared_elsewhere: set[str] = set() self._bindings: defaultdict[str, list[_Binding]] | None = None - self._held: defaultdict[str, list[tuple[ast.expr, bool]]] = defaultdict(list) + self._held: defaultdict[str, list[_HeldValue]] = defaultdict(list) # Filled by the scanner on first use, held here so that they live # exactly as long as the scope. self.newness_table: dict[str, int] | None = None @@ -549,40 +666,17 @@ def held_names(self) -> list[str]: self._collect() return list(self._held) - def held_values(self, name: str) -> list[tuple[ast.expr, bool]]: - """What the container ``name`` is filled with, and whether each value - goes in as one item (``append``) rather than as its items (``extend``).""" - + def held_values(self, name: str) -> list[_HeldValue]: self._collect() return self._held.get(name, []) - def _bind(self, target: ast.expr, value: ast.expr | None, items_taken: int) -> None: - if isinstance(target, ast.Name): - self._bindings[target.id].append((value, items_taken)) - elif isinstance(target, ast.Starred): - # A starred target collects items into a list: the same depth. - self._bind(target.value, value, items_taken) - elif isinstance(target, (ast.Tuple, ast.List)): - pairs = ( - items_taken == 0 - and isinstance(value, (ast.Tuple, ast.List)) - and len(value.elts) == len(target.elts) - and not any( - isinstance(element, ast.Starred) - for element in (*target.elts, *value.elts) - ) - ) - for index, element in enumerate(target.elts): - if pairs: - self._bind(element, value.elts[index], 0) - else: - self._bind(element, value, items_taken + 1) - elif ( - isinstance(target, ast.Subscript) - and isinstance(target.value, ast.Name) - and value is not None - ): - self._held[target.value.id].append((value, True)) + def _record(self, bound: Iterable[tuple[ast.expr, ast.expr | None, int]]) -> None: + for target, value, items_taken in bound: + if isinstance(target, ast.Name): + self._bindings[target.id].append((value, items_taken)) + elif isinstance(target.value, ast.Name) and value is not None: + # ``name[key] = value`` puts one item into ``name``. + self._held[target.value.id].append((value, items_taken, True)) def _collect(self) -> None: if self._bindings is not None: @@ -606,20 +700,19 @@ def _collect(self) -> None: for child in _nodes_in_scope(body): if isinstance(child, ast.Assign): for target in child.targets: - self._bind(target, child.value, 0) + self._record(_target_names(target, child.value, 0)) elif isinstance(child, (ast.AnnAssign, ast.NamedExpr)): if child.value is not None: - self._bind(child.target, child.value, 0) + self._record(_target_names(child.target, child.value, 0)) elif isinstance(child, ast.AugAssign): - target = child.target - if isinstance(target, ast.Subscript): - target = target.value - if isinstance(target, ast.Name): - self._held[target.id].append((child.value, False)) + # ``name += values`` adds the items of ``values`` to a list; + # ``name[key] += value`` changes an item and adds none. + if isinstance(child.target, ast.Name): + self._held[child.target.id].append((child.value, 0, False)) elif isinstance(child, (ast.For, ast.AsyncFor)): - self._bind(child.target, child.iter, 1) + self._record(_loop_target_names(child.target, child.iter)) elif isinstance(child, ast.withitem) and child.optional_vars is not None: - self._bind(child.optional_vars, child.context_expr, 1) + self._record(_target_names(child.optional_vars, child.context_expr, 1)) elif isinstance(child, ast.ExceptHandler) and child.name: self._bindings[child.name].append((None, 1)) elif isinstance(child, (ast.Import, ast.ImportFrom)): @@ -645,7 +738,7 @@ def _collect(self) -> None: if method in _ITEM_ADDING_METHODS or method in _ITEMS_ADDING_METHODS: one_item = method in _ITEM_ADDING_METHODS self._held[child.func.value.id].extend( - (argument, one_item) + (argument, 0, one_item) for argument in ( *child.args, *(keyword.value for keyword in child.keywords), @@ -654,29 +747,52 @@ def _collect(self) -> None: class _ComprehensionScope: - """A comprehension: its loop targets shadow the enclosing scope's names.""" + """A comprehension: its loop targets shadow the enclosing scope's names. + + ``upto`` limits it to its first generators, the ones whose targets a + later generator's iterable can see. + """ - def __init__(self, enclosing: _Scope | _ComprehensionScope, node: ast.AST): + def __init__( + self, + enclosing: _Scope | _ComprehensionScope, + node: ast.AST, + upto: int | None = None, + ) -> None: self.enclosing = enclosing self.qualified_name = enclosing.qualified_name self.node = enclosing.node - self._targets: defaultdict[str, list[ast.expr]] = defaultdict(list) - for generator in node.generators: - for name in ast.walk(generator.target): - if isinstance(name, ast.Name): - self._targets[name.id].append(generator.iter) + self._comprehension = node + self._targets: defaultdict[str, list[tuple[ast.expr | None, int, int]]] = ( + defaultdict(list) + ) + generators = node.generators if upto is None else node.generators[:upto] + for index, generator in enumerate(generators): + for target, value, items_taken in _loop_target_names( + generator.target, generator.iter + ): + if isinstance(target, ast.Name): + self._targets[target.id].append((value, items_taken, index)) + + def before(self, index: int) -> _ComprehensionScope: + """This comprehension as seen from its generator ``index``.""" + + return _ComprehensionScope(self.enclosing, self._comprehension, upto=index) def child_name(self, name: str) -> str: return self.enclosing.child_name(name) - def target_iterables(self, name: str) -> list[ast.expr] | None: - """The iterables ``name`` takes items from, if it is a loop target here.""" + def target_sources( + self, name: str + ) -> list[tuple[ast.expr | None, int, int]] | None: + """What ``name`` takes items from, if it is a loop target here: each + source with its item count and the index of its generator.""" return self._targets.get(name) def bindings_of(self, name: str) -> list[_Binding] | None: if name in self._targets: - return [(iterable, 1) for iterable in self._targets[name]] + return [(value, items) for value, items, _index in self._targets[name]] return self.enclosing.bindings_of(name) def is_parameter(self, name: str) -> bool: @@ -878,6 +994,15 @@ def _positional_outputs(dotted_name: str) -> slice | None: return None +def _items_newness(level: int, items_taken: int) -> int: + """How new a name bound ``items_taken`` items deep into a value is: an + item of a new array is new memory, an item of a container may not be.""" + + if items_taken == 0: + return level + return _NEW_ARRAY if level == _NEW_ARRAY else _NOT_NEW + + def _is_ufunc_method(dotted_name: str, methods: Iterable[str]) -> bool: owner, _, method = dotted_name.rpartition(".") return method in methods and isinstance(_library_object(owner), np.ufunc) @@ -1058,7 +1183,7 @@ def _name_newness(self, name: str) -> int: scope = self._scope while isinstance(scope, _ComprehensionScope): - if scope.target_iterables(name) is not None: + if scope.target_sources(name) is not None: return _NOT_NEW scope = scope.enclosing return self._newness_table(scope).get(name, _NOT_NEW) @@ -1077,18 +1202,18 @@ def _newness_table(self, scope: _Scope) -> dict[str, int]: return scope.newness_table saved_scope, self._scope = self._scope, scope levels: dict[str, int] = {} - candidates: dict[str, list[ast.expr]] = {} + candidates: dict[str, list[_Binding]] = {} for name, bindings in scope.local_bindings().items(): kept = [ (value, items_taken) for value, items_taken in bindings if not (items_taken == 0 and _is_none(value)) ] - if not kept or any(value is None or items for value, items in kept): + if not kept or any(value is None for value, _items in kept): levels[name] = _NOT_NEW else: levels[name] = _NEW_ARRAY - candidates[name] = [value for value, _items in kept] + candidates[name] = kept def lookup(name: str) -> int: return levels.get(name, _NOT_NEW) @@ -1100,7 +1225,10 @@ def lookup(name: str) -> int: for name, values in candidates.items(): if levels[name] == _NOT_NEW: continue - level = min(self._newness(value, lookup) for value in values) + level = min( + _items_newness(self._newness(value, lookup), items_taken) + for value, items_taken in values + ) if level < levels[name]: levels[name] = level changed = True @@ -1169,6 +1297,12 @@ def _call_newness(self, call: ast.Call, lookup: _NameLookup | None) -> int: def _newness(self, expression: ast.expr, lookup: _NameLookup | None = None) -> int: """How new the value of ``expression`` is (``_NOT_NEW`` to ``_NEW_ARRAY``).""" + if isinstance(expression, ast.Attribute): + # ``.T`` and the other view attributes of a new array are new. + if expression.attr in _VIEW_ATTRIBUTES: + source = self._newness(expression.value, lookup) + return _NEW_ARRAY if source == _NEW_ARRAY else _NOT_NEW + return _NOT_NEW if isinstance(expression, ast.Subscript): container = self._newness(expression.value, lookup) if container == _NEW_ARRAY: @@ -1201,25 +1335,33 @@ def _newness(self, expression: ast.expr, lookup: _NameLookup | None = None) -> i # Whether a value can be a writable view -------------------------------- - def _name_view_depth(self, name: str) -> int: - """How deep in containers ``name`` holds a writable view, where it is used.""" + def _name_view_level(self, name: str) -> int: + """Whether, and how deep, ``name`` holds a writable view where it is used.""" scope = self._scope while isinstance(scope, _ComprehensionScope): - iterables = scope.target_iterables(name) - if iterables is not None: - self._scope = scope.enclosing + sources = scope.target_sources(name) + if sources is not None: + saved_scope = self._scope + levels = [] try: - return min(_item_of(self._view_depth(item)) for item in iterables) + for value, items_taken, index in sources: + if value is None: + continue + self._scope = scope.before(index) + levels.append( + _items_taken(self._view_level(value), items_taken) + ) finally: - self._scope = scope + self._scope = saved_scope + return min(levels, default=_NO_VIEW) scope = scope.enclosing return self._view_table(scope).get(name, _NO_VIEW) def _view_table(self, scope: _Scope) -> dict[str, int]: - """How deep in containers each name of ``scope`` holds a writable view. + """Whether, and how deep, each name of ``scope`` holds a writable view. - Starts every name at ``_NO_VIEW`` and lowers it to the smallest depth + Starts every name at ``_NO_VIEW`` and lowers it to the closest level any of its bindings or held values gives, until nothing changes. A binding that takes items of its value (a loop target, unpacking) takes one level per item; a container filled with a value holds it @@ -1229,39 +1371,45 @@ def _view_table(self, scope: _Scope) -> dict[str, int]: if scope.view_table is not None: return scope.view_table saved_scope, self._scope = self._scope, scope - sources: defaultdict[str, list[tuple[ast.expr, int]]] = defaultdict(list) + sources: defaultdict[str, list[tuple[ast.expr, Callable[[int], int]]]] = ( + defaultdict(list) + ) for name, bindings in scope.local_bindings().items(): for value, items_taken in bindings: if value is not None: - sources[name].append((value, -items_taken)) + sources[name].append( + (value, functools.partial(_bound_level, items_taken)) + ) # A container filled here may be a parameter, so held values count # for any name. for name in scope.held_names(): - for value, adds_level in scope.held_values(name): - sources[name].append((value, 1 if adds_level else 0)) - depths: dict[str, int] = dict.fromkeys(sources, _NO_VIEW) + for value, items_taken, one_item in scope.held_values(name): + sources[name].append( + (value, functools.partial(_held_level, items_taken, one_item)) + ) + levels: dict[str, int] = dict.fromkeys(sources, _NO_VIEW) def lookup(name: str) -> int: - return depths.get(name, _NO_VIEW) + return levels.get(name, _NO_VIEW) changed = True try: while changed: changed = False for name, parts in sources.items(): - if depths[name] == _IS_VIEW: + if levels[name] == _IS_VIEW: continue - depth = min( - _shifted(self._view_depth(value, lookup), shift) - for value, shift in parts + level = min( + convert(self._view_level(value, lookup)) + for value, convert in parts ) - if depth < depths[name]: - depths[name] = depth + if level < levels[name]: + levels[name] = level changed = True finally: self._scope = saved_scope - scope.view_table = depths - return depths + scope.view_table = levels + return levels def _is_container(self, expression: ast.expr) -> bool: if isinstance(expression, _CONTAINER_EXPRESSIONS): @@ -1279,135 +1427,175 @@ def _is_container(self, expression: ast.expr) -> bool: return False def _reaches_writable_view(self, expression: ast.expr) -> bool: - """Whether ``expression`` can be a writable view of pandas' memory.""" + """Whether a write into ``expression`` can reach pandas' memory.""" - return self._view_depth(expression) == _IS_VIEW + return self._view_level(expression) <= _ELEMENT - def _view_depth( + def _view_level( self, expression: ast.expr, lookup: _NameLookup | None = None ) -> int: - """How deep in containers ``expression`` holds a writable view. - - ``_IS_VIEW`` (0) for a view itself, 1 for a container of views, 2 - for a container of those, up to ``_NO_VIEW`` for none. - """ + """Whether, and how deep in containers, ``expression`` holds a writable view.""" if not self._has_writable_views: return _NO_VIEW if isinstance(expression, ast.Attribute): if expression.attr in _WRITABLE_VIEW_ATTRIBUTES: return _NO_VIEW if _is_own_object(expression.value) else _IS_VIEW + if expression.attr == "base": + # ``.base`` of an array expression is the array behind a view; + # on other objects it is an ordinary attribute. + array_expression = isinstance(expression.value, ast.Call) or ( + isinstance(expression.value, ast.Attribute) + and expression.value.attr in ("values", "array") + ) + return _IS_VIEW if array_expression else _NO_VIEW if expression.attr in _VIEW_ATTRIBUTES: - return _view_of(self._view_depth(expression.value, lookup)) + return _view_of(self._view_level(expression.value, lookup)) return _NO_VIEW if isinstance(expression, ast.Subscript): - return _item_of(self._view_depth(expression.value, lookup)) + return _item_of(self._view_level(expression.value, lookup)) if isinstance(expression, ast.Starred): - return self._view_depth(expression.value, lookup) + return self._view_level(expression.value, lookup) if isinstance(expression, ast.Name): if lookup is not None: return lookup(expression.id) - return self._name_view_depth(expression.id) + return self._name_view_level(expression.id) if isinstance(expression, ast.IfExp): return min( - self._view_depth(expression.body, lookup), - self._view_depth(expression.orelse, lookup), + self._view_level(expression.body, lookup), + self._view_level(expression.orelse, lookup), ) if isinstance(expression, ast.BoolOp): - return min(self._view_depth(value, lookup) for value in expression.values) + return min(self._view_level(value, lookup) for value in expression.values) if isinstance(expression, ast.BinOp): - # ``[a.array] + rest`` joins lists; arithmetic gives new memory. - joins = isinstance(expression.op, _JOINING_OPERATORS) and ( - self._is_container(expression.left) - or self._is_container(expression.right) - ) - if not joins: - return _NO_VIEW - return min( - self._view_depth(expression.left, lookup), - self._view_depth(expression.right, lookup), - ) + return self._joined_view_level(expression, lookup) if isinstance(expression, (ast.List, ast.Tuple, ast.Set)): - parts: list[ast.expr] = list(expression.elts) - elif isinstance(expression, ast.Dict): - parts = list(expression.values) - elif isinstance(expression, (ast.ListComp, ast.SetComp, ast.GeneratorExp)): - parts = [expression.elt] - elif isinstance(expression, ast.DictComp): - parts = [expression.value] - elif isinstance(expression, ast.Call): - return self._call_view_depth(expression, lookup) - else: + # A starred element puts its items into the new container. + items = [ + _item_of(self._view_level(element.value, lookup)) + if isinstance(element, ast.Starred) + else self._view_level(element, lookup) + for element in expression.elts + ] + return _holder_of(min(items, default=_NO_VIEW)) + if isinstance(expression, ast.Dict): + # ``**mapping`` puts the mapping's values into the new dict. + items = [ + _item_of(self._view_level(value, lookup)) + if key is None + else self._view_level(value, lookup) + for key, value in zip(expression.keys, expression.values, strict=True) + ] + return _holder_of(min(items, default=_NO_VIEW)) + if isinstance(expression, _COMPREHENSIONS): + return self._comprehension_view_level(expression, lookup) + if isinstance(expression, ast.Call): + return self._call_view_level(expression, lookup) + return _NO_VIEW + + def _joined_view_level( + self, expression: ast.BinOp, lookup: _NameLookup | None + ) -> int: + """``[a.array] + rest`` and ``mapping | other`` join containers; + arithmetic, and any operator with an array operand, give new memory.""" + + if not isinstance(expression.op, _VIEW_JOINING_OPERATORS) or not ( + self._is_container(expression.left) or self._is_container(expression.right) + ): return _NO_VIEW - return _holder_of( - min((self._view_depth(part, lookup) for part in parts), default=_NO_VIEW) + level = min( + self._view_level(expression.left, lookup), + self._view_level(expression.right, lookup), ) + return _NO_VIEW if level <= _ELEMENT else level + + def _comprehension_view_level( + self, expression: ast.expr, lookup: _NameLookup | None + ) -> int: + """A comprehension holds what its element is, its loop targets taking + items of their iterables.""" - def _call_view_depth(self, call: ast.Call, lookup: _NameLookup | None) -> int: + targets: dict[str, int] = {} + + def inner(name: str) -> int: + if name in targets: + return targets[name] + if lookup is not None: + return lookup(name) + return self._name_view_level(name) + + for generator in expression.generators: + for target, value, items_taken in _loop_target_names( + generator.target, generator.iter + ): + if isinstance(target, ast.Name): + level = ( + _NO_VIEW + if value is None + else _items_taken(self._view_level(value, inner), items_taken) + ) + targets[target.id] = min(targets.get(target.id, _NO_VIEW), level) + element = ( + expression.value if isinstance(expression, ast.DictComp) else expression.elt + ) + return _holder_of(self._view_level(element, inner)) + + def _call_view_level(self, call: ast.Call, lookup: _NameLookup | None) -> int: arguments = [*call.args, *(keyword.value for keyword in call.keywords)] def nearest(expressions: Iterable[ast.expr]) -> int: return min( - (self._view_depth(expression, lookup) for expression in expressions), + (self._view_level(expression, lookup) for expression in expressions), default=_NO_VIEW, ) name = self._resolve(call.func) if name in _SPLITTING_NUMPY_FUNCTIONS: return _holder_of(_view_of(nearest(arguments))) - if name in _VIEW_NUMPY_FUNCTIONS or ( - name in ("numpy.array", "numpy.astype") and _copy_is_off(call) - ): + if name in _VIEW_NUMPY_FUNCTIONS: + copy = _keyword(call, "copy") + if copy is not None and _is_true_constant(copy.value): + return _NO_VIEW + return _view_of(nearest(arguments)) + if name in ("numpy.array", "numpy.astype") and _copy_is_off(call): return _view_of(nearest(arguments)) function = call.func if isinstance(function, ast.Name): if function.id == "next": return _item_of(nearest(arguments)) if function.id in _SAME_ITEMS_BUILTINS: - # A new container of the argument's items. - return _holder_of(_item_of(nearest(arguments))) + return _items_holder_of(nearest(arguments)) if function.id in _TUPLE_YIELDING_BUILTINS: - # A new container of tuples of the arguments' items. - return _holder_of(_holder_of(_item_of(nearest(arguments)))) + # A container of tuples of the arguments' items. + return _holder_of(_items_holder_of(nearest(arguments))) return _NO_VIEW if not isinstance(function, ast.Attribute): return _NO_VIEW method = function.attr - receiver = function.value + receiver = self._view_level(function.value, lookup) if method in _VIEW_METHODS: copy = _keyword(call, "copy") - if copy is not None and _is_true_constant(copy.value): + copy_value = copy.value if copy is not None else None + if copy_value is None and method == "to_numpy" and len(call.args) >= 2: + copy_value = call.args[1] + if copy_value is not None and _is_true_constant(copy_value): return _NO_VIEW - return _view_of(self._view_depth(receiver, lookup)) + return _view_of(receiver) if method == "astype" and _copy_is_off(call): - return _view_of(self._view_depth(receiver, lookup)) + return _view_of(receiver) if method == "copy": - # A copy of an array is new memory; of a container, it holds the - # same items. - depth = self._view_depth(receiver, lookup) - return _NO_VIEW if depth == _IS_VIEW else depth + # A copy of an array is new memory; a copy of a container holds + # the same items. + return _NO_VIEW if receiver <= _ELEMENT else receiver if method in _ITEM_TAKING_METHODS: - return _item_of(self._view_depth(receiver, lookup)) + # ``get(key, default)`` may also return its default. + return min(_item_of(receiver), nearest(call.args[1:])) if method in _SAME_ITEMS_METHODS: - return _holder_of(_item_of(self._view_depth(receiver, lookup))) + return _items_holder_of(receiver) if method in _TUPLE_YIELDING_METHODS: - return _holder_of(_holder_of(_item_of(self._view_depth(receiver, lookup)))) + return _holder_of(_items_holder_of(receiver)) return _NO_VIEW - def _bound_to_a_view(self, name: str) -> bool: - """Whether some binding sets ``name`` to exactly a writable view.""" - - if isinstance(self._scope, _ComprehensionScope) and ( - self._scope.target_iterables(name) is not None - ): - return False - return any( - items_taken == 0 - and value is not None - and self._reaches_writable_view(value) - for value, items_taken in self._bindings(name) or [] - ) - def _check_written_array(self, node: ast.AST, written: ast.expr) -> None: """Report a write into ``written`` unless it is new in this function.""" @@ -1517,12 +1705,18 @@ def _check_annotated_assign(self, node: ast.AnnAssign) -> None: self._check_assigned_target(node, node.target, node.value) def _check_augmented_assign(self, node: ast.AugAssign) -> None: - # ``values += 1`` writes into the array ``values`` names; a name that - # only takes items of a view (a loop target) may hold scalars. - if isinstance(node.target, ast.Name) and self._bound_to_a_view(node.target.id): - self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) - else: - self._check_assigned_target(node, node.target, None) + # ``values += 1`` writes into the array ``values`` names. An element + # of a view may be a scalar, which ``+=`` rebinds, so only a view + # itself counts; ``holder[key] += 1`` writes into a view the holder + # holds. + target = node.target + if isinstance(target, ast.Name): + if self._view_level(target) == _IS_VIEW: + self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) + elif isinstance(target, ast.Subscript): + container = self._view_level(target.value) + if container <= _ELEMENT or _item_of(container) == _IS_VIEW: + self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) def _check_attribute(self, node: ast.Attribute) -> None: if node.attr in _ALWAYS_PRIVATE_ATTRIBUTES: @@ -1676,6 +1870,122 @@ def _in_function(*body_lines: str, parameters: str = "series") -> str: #: Snippets the scan must refuse, with the one rule each must report. _REFUSED_SNIPPETS = { + # Round-three cases. + "series_array_through_a_dict_comprehension_of_loop_targets": ( + _in_function( + "arrays = [frame[name].array for name in names]", + "by_name = {name: values for name, values in zip(names, arrays)}", + 'by_name["income"][0] = 1', + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_an_identity_comprehension": ( + _in_function( + "arrays = [frame[name].array for name in names]", + "[values for values in arrays][0][0] = 1", + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_filled_in_a_nested_comprehension": ( + _in_function( + "groups = [[frame[name].array for name in names]]", + "[values.fill(0) for group in groups for values in group]", + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_next": ( + _in_function( + "arrays = [frame[name].array for name in names]", + "next(values for values in arrays)[0] = 1", + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_augmented_through_a_loop_target": ( + _in_function( + "arrays = [np.asarray(frame[name].array) for name in names]", + "for values in arrays:", + " values += 1", + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_augmented_through_an_item": ( + _in_function( + "arrays = [np.asarray(frame[name].array) for name in names]", + "arrays[0] += 1", + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_augmented_after_split": ( + _in_function( + "left, right = np.split(np.asarray(series.array), 2)", "left += 1" + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_starred_display": ( + _in_function( + "arrays = [frame[name].array for name in names]", + "[*arrays, other][0][0] = 1", + parameters="frame, names, other", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_dict_unpacking": ( + _in_function( + "by_name = {name: frame[name].array for name in names}", + '{**by_name}["income"][0] = 1', + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_dict_union": ( + _in_function( + "by_name = {name: frame[name].array for name in names}", + '(by_name | {})["income"][0] = 1', + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_get_default": ( + _in_function( + 'values = overrides.get("income", frame["income"].array)', + "values[0] = 1", + parameters="frame, overrides", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_unpacked_into_subscripts": ( + _in_function( + "columns = {}", + 'columns["a"], columns["b"] = np.split(np.asarray(series.array), 2)', + 'columns["a"][0] = 1', + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_real_if_close": ( + _NUMPY + "np.real_if_close(np.asarray(series.array))[0] = 1\n", + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "out_item_of_a_dict_union": ( + _in_function( + "merged = by_name | {}", + 'np.add(merged["x"], 1, out=merged["x"])', + parameters="by_name", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), + "ufunc_at_on_take_of_a_frame": ( + _in_function( + "np.add.at(np.take(frame, [0], axis=1), ([0], [0]), 100)", + parameters="frame", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), # Round-two cases: views reached through iteration and filled containers. "series_array_through_zip": ( _in_function( @@ -2379,6 +2689,60 @@ def test_the_scanner_refuses_each_unprotected_write(source: str, rule: str) -> N #: Snippets the scan must accept: reads, read-only flags, and writes into #: arrays the same function created. _ACCEPTED_SNIPPETS = { + # Round-three cases. + "accumulating_scalars_of_views_into_a_dict": ( + "from collections import defaultdict\n" + + _in_function( + "totals = defaultdict(float)", + 'for group, weight in zip(frame["group"].array, frame["weight"].array):', + " totals[group] += weight", + parameters="frame", + ) + ), + "running_total_of_view_columns": _in_function( + "total = np.zeros(size)", + "for column in columns:", + " total += frame[column].array", + "total[total < 0] = 0", + "np.maximum(total, 0, out=total)", + parameters="frame, columns, size", + ), + "zip_pairs_rows_of_a_parameter_with_a_view": _in_function( + 'for row, value in zip(matrix, frame["x"].array):', + " row[:] = value", + parameters="matrix, frame", + ), + "views_and_items_of_new_arrays": _in_function( + "grid = np.zeros((3, 3)).T", + "np.add(grid, 1, out=grid)", + "matrix = np.ones((3, 3))", + "np.fill_diagonal(matrix.T, 0)", + "for row in np.zeros((3, 3)):", + " np.add(row, 1, out=row)", + "first, second = np.zeros((2, 3))", + "np.add(first, 1, out=first)", + parameters="", + ), + "copies_given_by_keyword_and_position": _in_function( + "values = np.asarray(series.array, copy=True)", + "values[0] = 1", + "other = series.array.to_numpy(float, True)", + "other[0] = 1", + ), + "starred_rest_replaced": _in_function( + "arrays = [frame[name].array for name in names]", + "first, *rest = arrays", + "rest[0] = np.zeros(3)", + parameters="frame, names", + ), + "view_times_a_list": _in_function( + "weights = [1.0, 2.0]", + "scaled = series.array * weights", + "scaled[0] = 0", + ), + "ordinary_base_attribute": _in_function( + "columns = holder.base", 'columns["x"] = 1', parameters="holder" + ), # Round-two cases. "long_chain_of_views_of_a_new_array": _in_function( "chain_0 = np.zeros(64)", From 60174dd1dd90322e7e6cae7fe6092566d2619886 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:01:38 +0400 Subject: [PATCH 05/15] Fix the fourth round of review findings in Frame and the write scan Frame: the _adopt docstring now lists which extension arrays .values and to_numpy() share (category columns' to_numpy() is a copy; pyarrow columns share under pandas 2.x). replace_tables and with_columns point to it for the writes copy-on-write does not protect. The tests decide "pandas 3" by the missing pandas._config.using_copy_on_write, as bundle.py does. Scan: - zip pairing nests inside enumerate and reaches through list, sorted and the other item-keeping wrappers. - Comprehension loop targets over a new array, and np.split pieces of one, count as created; comprehension targets are cached. - `+=` on a name bound only to .array is accepted: an extension array builds a new array on `+=`. - Joins of any length are handled without recursion. - dict(...) is followed. - np.clip, np.round and np.take no longer count as views of an ndarray or extension array, and still do not count as created. - The docstring now says the scan follows only the forms it lists. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/frame/bundle.py | 27 +- .../shared/test_frame_table_sharing.py | 11 +- .../shared/test_shared_buffer_writes.py | 442 ++++++++++++++---- 3 files changed, 372 insertions(+), 108 deletions(-) diff --git a/packages/microcosm-frame/src/microcosm/frame/bundle.py b/packages/microcosm-frame/src/microcosm/frame/bundle.py index 56597ec207..2e6685ac75 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -148,10 +148,12 @@ def _adopt( through ``Series.array``, private pandas attributes, an array made writable, ``ufunc.at``, ``np.copyto`` or ``out=`` (``test_shared_buffer_writes.py`` refuses these in the workspace's - source), and through the arrays that ``to_numpy()`` and ``.values`` - return for extension-typed columns, which are writable views: - ``Int64``, ``Float64``, ``boolean``, ``category`` and python-backed - strings. + source), and through the extension arrays of extension-typed columns: + ``.values`` returns the shared array itself for ``Int64``, + ``Float64``, ``boolean``, ``category`` and python-backed string + columns (and, under pandas 2.x, for pyarrow-backed ones), and + ``to_numpy()`` a writable view of it for all of these but + ``category``. 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 @@ -927,7 +929,8 @@ def replace_tables(self, /, **changed_tables: pd.DataFrame) -> "Frame": 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. Weights, strata, the mass log and metadata are + 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 (see :meth:`_adopt`). @@ -968,10 +971,11 @@ def with_columns(self, entity: str, /, **columns: Any) -> "Frame": 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 3 + 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`. + shared with this frame as in :meth:`replace_tables`, with the same + limits. Args: entity: An entity declared by the schema (not a link). @@ -981,6 +985,8 @@ def with_columns(self, entity: str, /, **columns: Any) -> "Frame": A new validated frame. Raises: + TypeError: If pandas cannot assign a value as a column (a set, + for example). ValueError: If ``entity`` is not declared by the schema, a value's length does not match the table, or the new columns break a constructor invariant (a name another table already carries, @@ -1549,9 +1555,10 @@ def _pandas_copy_on_write() -> bool: ``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 it along with the switch, because copy-on-write is - always on. Without the function, a version from 3 on counts as on, and - any other version reads ``mode.copy_on_write``. + 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: 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 ceb9f7aa4c..10921577dd 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 @@ -7,8 +7,10 @@ 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`` -deep-copies instead. These tests replace the copy-on-write check to take that -path, because pandas 3 always has copy-on-write on. +deep-copies instead. To take that path, the ``copy_on_write_off`` fixture +turns copy-on-write off under pandas 2.x and, under pandas 3, where it is +always on, replaces the check ``_adopt`` makes. Every other test runs with +copy-on-write on. """ import importlib @@ -105,7 +107,8 @@ def source_frame() -> Frame: ) -_PANDAS_3 = int(pd.__version__.split(".", 1)[0]) >= 3 +#: pandas 3 removed the copy-on-write switch along with this function. +_PANDAS_3 = not hasattr(pandas_config, "using_copy_on_write") @pytest.fixture(autouse=True) @@ -613,7 +616,7 @@ def test_pandas_2_uses_pandas_own_check( "empty", ], ) - def test_without_pandas_own_check_an_older_version_reads_the_option( + def test_without_pandas_own_check_the_version_or_the_option_decides( self, monkeypatch: pytest.MonkeyPatch, version: str, 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 3d04370f50..c68e2cdfd4 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 @@ -5,9 +5,9 @@ (: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 write below changes the other frame's +with pandas 3.0.3 and NumPy 2.4.6, the writes below change the other frame's data without an error, so this test reads the scanned source with :mod:`ast` -and refuses it. Each rule's name is what a failure reports. +and refuses them. Each rule's name is what a failure reports. ``makes-array-writable`` ``setflags(write=...)`` with anything but a false constant, or assigning @@ -16,28 +16,41 @@ read-only views of the shared memory; this makes them writable. ``writes-through-writable-view`` A write into a writable view of pandas' memory: ``.array`` (of a Series - or Index), ``.asi8`` (datetime data), or ``.base`` read from an array - expression (a call such as ``to_numpy()``, or ``.values``), which is - the writable array behind a read-only view. Writes are item - assignment, ``__setitem__``, ``fill``, ``sort`` and the other in-place - ndarray methods, ``fillna(copy=False)``, ``out=``, ``shuffle`` and the - in-place NumPy functions below, into the view or into an item of it (a - row of a two-dimensional view is a view too), and ``+=`` and the other - augmented assignments into the view itself (an item of a - one-dimensional view is a scalar, which ``+=`` rebinds). It counts - when the written expression reaches the view through indexing, the - NumPy functions that can return a view (``np.asarray``, ``np.flip``, - ``np.split``, ... in ``_VIEW_NUMPY_FUNCTIONS``), ``to_numpy()``, - ``astype(copy=False)`` and the other view methods, a list, tuple, set - or dict display or comprehension holding it (also with ``*``/``**`` - unpacking, ``+`` or ``|``), ``zip``, ``enumerate``, ``.items()``, - ``.values()`` and ``.get()`` (with its default), ``or`` and - conditional expressions, or a name the same function binds to any of - these (by assignment, unpacking, a ``for`` loop, which pairs ``zip``, - ``enumerate`` and ``.items()`` targets with their own sources, or a - ``with`` statement) or fills with one (``append``, ``extend``, - ``update``, ``name[key] = ...``, ``+=``). Workspace classes' own - ``self.array`` is exempt. + or Index), ``.asi8`` (datetime data), or ``.base`` read from a call's + result (such as ``to_numpy()``) or from ``.values`` or ``.array``, which + is the writable array behind a read-only view. + + Writes are item assignment, ``__setitem__``, ``fill``, ``sort`` and the + other in-place ndarray methods, ``fillna(copy=False)``, ``out=``, + ``shuffle`` and the in-place NumPy functions below, into the view or + into an item of it (a row of a two-dimensional view is a view too). + ``+=`` and the other augmented assignments count only into a view + itself, because an item of a one-dimensional view is a scalar, which + ``+=`` rebinds; and not into a name bound only to ``.array``, an + extension array, for which ``+=`` builds a new array. + + The written expression reaches the view through: + + - indexing of any kind; + - the NumPy functions that can return a view (``np.asarray``, + ``np.flip``, ``np.split``, ... in ``_VIEW_NUMPY_FUNCTIONS`` and + ``_SPLITTING_NUMPY_FUNCTIONS``), ``to_numpy()``, + ``astype(copy=False)`` and the other view methods and attributes, + unless given ``copy=True``; + - a list, tuple, set or dict display or comprehension holding it (with + ``*``/``**`` unpacking), containers joined with ``+`` or ``|``, + ``list``, ``tuple``, ``sorted``, ``dict``, ``zip``, ``enumerate``, + ``next``, ``.items()``, ``.values()``, ``.copy()`` of a container, + and ``.get()``, ``.pop()`` and ``.setdefault()`` (with a default); + - ``or`` and conditional expressions; + - a name the same function binds to any of these, by assignment, + unpacking, a ``with`` statement, or a ``for`` loop or comprehension + (which pair ``zip``, ``enumerate`` and ``.items()`` targets with + their own sources, also when nested or wrapped in ``list`` or + ``sorted``), or fills with one (``append``, ``extend``, ``insert``, + ``add``, ``update``, ``setdefault``, ``name[key] = ...``, ``+=``). + + Workspace classes' own ``self.array`` is exempt. ``pandas-private-attribute`` ``._ndarray``, ``._mgr``, ``._get_column_array`` or ``._iter_column_arrays`` on anything, and ``._values``, ``._data``, @@ -46,28 +59,36 @@ ``numpy-copyto`` Any use of ``numpy.copyto``. ``writes-into-existing-array`` - A write into an array the same function did not create: - ``out=`` given to a NumPy or SciPy function or ufunc, an ndarray method - or a NumPy random ``Generator`` method (by keyword, or by position for - NumPy and SciPy functions and ufuncs), the first argument of - ``numpy..at`` (which writes even into a read-only array), the + A write into an array the same function did not create: ``out=`` + given to a NumPy or SciPy function or ufunc, an ndarray method or a + NumPy random ``Generator`` method (by keyword, or by position for NumPy + and SciPy functions and ufuncs), the first argument of + ``numpy..at`` (which writes even into a read-only array), and the first argument of ``numpy.put``, ``numpy.putmask``, ``numpy.place``, ``numpy.put_along_axis``, ``numpy.fill_diagonal``, ``numpy.random.shuffle``, any ``.shuffle`` method and ``numpy.nan_to_num(copy=False)``. Library functions are also followed through a local name bound to them (``plus = np.add``). - Created means one of: the result of a ufunc or ufunc reduction, a - ``numpy.random`` function, a random ``Generator`` draw (``rng.normal``, - ...), ``.flatten()``, or a NumPy function that always allocates - (``_ALLOCATING_NUMPY_FUNCTIONS``: ``np.zeros``, ``np.where``, - ``np.concatenate``, ...), when not given an output array; - ``np.array`` without ``copy=``; ``to_numpy(copy=True)``; a view, - subscript or item (a loop target, unpacking) of one of these; arithmetic or a comparison; a ``.copy()``, - ``list(...)`` and the other container builtins, ``+`` or ``*`` - (which also join lists), or a list, set or dict display (a slice of - these is new, an item is not, because a shallow copy or a container - shares its items); or a local name whose every binding in the - function, other than to ``None``, is one of these. + + Created means one of: + + - the result of a ufunc or ufunc reduction, a ``numpy.random`` + function, a random ``Generator`` draw (``rng.normal``, ...), + ``.flatten()``, or a NumPy function that always allocates + (``_ALLOCATING_NUMPY_FUNCTIONS``: ``np.zeros``, ``np.where``, + ``np.concatenate``, ...), when not given an output array; + - ``np.array`` without ``copy=``, or ``to_numpy(copy=True)``; + - a view, piece (``np.split``), subscript or item (a loop target, + also in a comprehension, or unpacking) of one of these. ``np.clip``, + ``np.round`` and ``np.take`` count only as views here: given a + pandas object they can return its memory; + - arithmetic or a comparison; + - a ``.copy()``, ``list(...)`` and the other container builtins, ``+``, + ``*`` or ``|`` (which also join containers), or a list, set or dict + display. A slice of these is new; an item is not, because a shallow + copy or a container shares its items; + - a local name whose every binding in the function, other than to + ``None``, is one of these. ``setflags``, ``Series.array[i] = value``, ``._ndarray``, ``._mgr``, ``np.copyto`` and ``out=`` are the writes first identified as unprotected. @@ -80,24 +101,35 @@ except files in ``node_modules`` or hidden directories. Tests and ``test_support/`` are not scanned. -What this scan does not refuse: - -- Writes it cannot see from the source: into the arrays ``to_numpy()`` and - ``.values`` return for extension-typed columns (``Int64``, ``Float64``, - ``boolean``, ``category``, python-backed strings), which are writable - views of the shared memory; through a pandas object built with - ``copy=False`` over another object's array; into ``np.asarray(index)``, - which is writable although the index is shared even between deep copies. -- Arrays reached in ways it does not follow: through other functions' - return values or arguments, closures, object arrays, names reached - dynamically (``getattr(np, name)``, ``**{"out": array}``, ``*arguments``), - positional ``out`` given to ndarray methods, items of a container the - function did not build, and array libraries other than NumPy and SciPy - (``torch.from_numpy`` of a read-only view returns a writable tensor). -- The analysis is not flow-sensitive: a name counts as created only if - every binding in its function does, so a parameter rebound to a new - array, and ``.astype()`` (which shares memory when it is a pandas - object's same-type conversion), count as not created. +The scan follows arrays only through the forms listed above. In particular, +it does not refuse: + +- Writes it cannot see from the source: + - into the extension arrays of extension-typed columns: ``.values`` + returns the shared array for ``Int64``, ``Float64``, ``boolean``, + ``category`` and python-backed string columns, and ``to_numpy()`` a + writable view of it for all of these but ``category``; + - through a pandas object built with ``copy=False`` over another object's + array; + - into ``np.asarray(index)``, which is writable although the index is + shared even between deep copies; + - ``+=`` on a datetime column's ``.array``, which writes in place. +- Arrays reached in other ways: + - through other functions' return values or arguments, closures and + object arrays; + - names reached dynamically (``getattr(np, name)``, ``**{"out": array}``, + ``*arguments``), and positional ``out`` given to ndarray methods; + - items of a container the function did not build; + - array libraries other than NumPy and SciPy (``torch.from_numpy`` of a + read-only view returns a writable tensor). +- Differences of order or kind within a function: + - Neither rule is flow-sensitive: a name counts as created only if every + binding in its function does, and as a view if any binding is one. So + a parameter rebound to a new array, and a name rebound from a view to a + new array, count as before. + - A boolean or integer array index gives a copy, but counts as indexing. + - ``.astype()`` counts as not created, because a pandas object's + same-type conversion shares its memory. A finding that cannot write into memory a pandas object shares goes in ``_REVIEWED_FINDINGS`` with the reason. @@ -263,6 +295,8 @@ {"reversed", "iter", "list", "tuple", "sorted", "set", "frozenset"} ) _TUPLE_YIELDING_BUILTINS = frozenset({"zip", "enumerate"}) +#: Builtins whose result has exactly the items of their one argument. +_ITEM_KEEPING_WRAPPERS = frozenset({"list", "tuple", "sorted", "reversed", "iter"}) _SAME_ITEMS_METHODS = frozenset({"values", "popitem"}) _TUPLE_YIELDING_METHODS = frozenset({"items"}) #: Methods that return one item of the container they are called on. @@ -387,16 +421,19 @@ "imag", "trim_zeros", "tile", - "take", "real_if_close", "asmatrix", - "clip", - "round", - "around", "lib.stride_tricks.as_strided", ) ) +#: NumPy functions that return new memory for an ndarray or an extension +#: array, but, given a Series or DataFrame, call its method, whose result can +#: share the object's memory: never counted as created. +_PANDAS_SHARING_NUMPY_FUNCTIONS = frozenset( + f"numpy.{name}" for name in ("clip", "round", "around", "take") +) + #: NumPy functions that return a list or tuple of views of an argument. _SPLITTING_NUMPY_FUNCTIONS = frozenset( f"numpy.{name}" @@ -568,9 +605,19 @@ def _loop_target_names( ``for a, b in zip(x, y)`` binds ``a`` to an item of ``x`` and ``b`` to an item of ``y``; ``enumerate`` and ``.items()`` pair the second name - with the iterable's items. + with the iterable's items. Pairs nest (``enumerate(zip(...))``), and + ``list``, ``sorted`` and the other wrappers that keep the items change + nothing. """ + while ( + isinstance(iterable, ast.Call) + and isinstance(iterable.func, ast.Name) + and iterable.func.id in _ITEM_KEEPING_WRAPPERS + and len(iterable.args) == 1 + and not isinstance(iterable.args[0], ast.Starred) + ): + iterable = iterable.args[0] if ( isinstance(target, (ast.Tuple, ast.List)) and not any(isinstance(element, ast.Starred) for element in target.elts) @@ -586,7 +633,7 @@ def _loop_target_names( and len(arguments) == len(elements) ): for element, argument in zip(elements, arguments, strict=True): - yield from _target_names(element, argument, 1) + yield from _loop_target_names(element, argument) return if ( isinstance(function, ast.Name) @@ -595,7 +642,7 @@ def _loop_target_names( and arguments ): yield from _target_names(elements[0], None, 1) - yield from _target_names(elements[1], arguments[0], 1) + yield from _loop_target_names(elements[1], arguments[0]) return if ( isinstance(function, ast.Attribute) @@ -603,7 +650,7 @@ def _loop_target_names( and len(elements) == 2 ): yield from _target_names(elements[0], None, 1) - yield from _target_names(elements[1], function.value, 1) + yield from _loop_target_names(elements[1], function.value) return yield from _target_names(target, iterable, 1) @@ -762,7 +809,8 @@ def __init__( self.enclosing = enclosing self.qualified_name = enclosing.qualified_name self.node = enclosing.node - self._comprehension = node + self.comprehension = node + self.upto = upto self._targets: defaultdict[str, list[tuple[ast.expr | None, int, int]]] = ( defaultdict(list) ) @@ -777,7 +825,7 @@ def __init__( def before(self, index: int) -> _ComprehensionScope: """This comprehension as seen from its generator ``index``.""" - return _ComprehensionScope(self.enclosing, self._comprehension, upto=index) + return _ComprehensionScope(self.enclosing, self.comprehension, upto=index) def child_name(self, name: str) -> str: return self.enclosing.child_name(name) @@ -1063,6 +1111,7 @@ def __init__(self, source: str, path: str, tree: ast.Module) -> None: self._module_scope = _Scope("", tree) self._scope: _Scope | _ComprehensionScope = self._module_scope self._digests: dict[int, str] = {} + self._target_levels: dict[tuple[bool, int, int | None, str], int] = {} self._checks = { ast.Call: self._check_call, ast.Assign: self._check_assign, @@ -1183,11 +1232,50 @@ def _name_newness(self, name: str) -> int: scope = self._scope while isinstance(scope, _ComprehensionScope): - if scope.target_sources(name) is not None: - return _NOT_NEW + sources = scope.target_sources(name) + if sources is not None: + return self._comprehension_target(scope, name, sources, newness=True) scope = scope.enclosing return self._newness_table(scope).get(name, _NOT_NEW) + def _comprehension_target( + self, + scope: _ComprehensionScope, + name: str, + sources: list[tuple[ast.expr | None, int, int]], + *, + newness: bool, + ) -> int: + """How new, or how close to a view, a comprehension's loop target is. + + Each source is measured as the comprehension sees it from that + target's generator. Results are cached: they depend only on the + comprehension and the tables of the scopes around it. + """ + + key = (newness, id(scope.comprehension), scope.upto, name) + cached = self._target_levels.get(key) + if cached is not None: + return cached + saved_scope = self._scope + levels: list[int] = [] + try: + for value, items_taken, index in sources: + if value is None: + if newness: + levels.append(_NOT_NEW) + continue + self._scope = scope.before(index) + if newness: + levels.append(_items_newness(self._newness(value), items_taken)) + else: + levels.append(_items_taken(self._view_level(value), items_taken)) + finally: + self._scope = saved_scope + result = min(levels, default=_NOT_NEW if newness else _NO_VIEW) + self._target_levels[key] = result + return result + def _newness_table(self, scope: _Scope) -> dict[str, int]: """How new each local name of ``scope`` is. @@ -1256,7 +1344,11 @@ def _call_newness(self, call: ast.Call, lookup: _NameLookup | None) -> int: return _NEW_ARRAY if name == "numpy.array": return _NOT_NEW if _copy_is_off(call) else _NEW_ARRAY - if name in _VIEW_NUMPY_FUNCTIONS and call.args: + if call.args and ( + name in _VIEW_NUMPY_FUNCTIONS + or name in _SPLITTING_NUMPY_FUNCTIONS + or name in _PANDAS_SHARING_NUMPY_FUNCTIONS + ): # A view of a new array, or an array made from a new container. source = self._newness(call.args[0], lookup) return _NEW_ARRAY if source >= _NEW_OBJECT else _NOT_NEW @@ -1342,19 +1434,7 @@ def _name_view_level(self, name: str) -> int: while isinstance(scope, _ComprehensionScope): sources = scope.target_sources(name) if sources is not None: - saved_scope = self._scope - levels = [] - try: - for value, items_taken, index in sources: - if value is None: - continue - self._scope = scope.before(index) - levels.append( - _items_taken(self._view_level(value), items_taken) - ) - finally: - self._scope = saved_scope - return min(levels, default=_NO_VIEW) + return self._comprehension_target(scope, name, sources, newness=False) scope = scope.enclosing return self._view_table(scope).get(name, _NO_VIEW) @@ -1412,6 +1492,14 @@ def lookup(name: str) -> int: return levels def _is_container(self, expression: ast.expr) -> bool: + # A chain of joins (``[a] + [b] + rest``) is a container if any of + # its operands is one. + while isinstance(expression, ast.BinOp) and isinstance( + expression.op, _VIEW_JOINING_OPERATORS + ): + if self._is_container(expression.right): + return True + expression = expression.left if isinstance(expression, _CONTAINER_EXPRESSIONS): return True if isinstance(expression, ast.Call) and isinstance(expression.func, ast.Name): @@ -1496,17 +1584,23 @@ def _view_level( def _joined_view_level( self, expression: ast.BinOp, lookup: _NameLookup | None ) -> int: - """``[a.array] + rest`` and ``mapping | other`` join containers; - arithmetic, and any operator with an array operand, give new memory.""" + """``[a.array] + [b.array] + rest`` and ``mapping | other`` join + containers; arithmetic, and any operator with an array operand, give + new memory.""" - if not isinstance(expression.op, _VIEW_JOINING_OPERATORS) or not ( - self._is_container(expression.left) or self._is_container(expression.right) + if not isinstance(expression.op, _VIEW_JOINING_OPERATORS): + return _NO_VIEW + operands: list[ast.expr] = [] + node: ast.expr = expression + while isinstance(node, ast.BinOp) and isinstance( + node.op, _VIEW_JOINING_OPERATORS ): + operands.append(node.right) + node = node.left + operands.append(node) + if not any(self._is_container(operand) for operand in operands): return _NO_VIEW - level = min( - self._view_level(expression.left, lookup), - self._view_level(expression.right, lookup), - ) + level = min(self._view_level(operand, lookup) for operand in operands) return _NO_VIEW if level <= _ELEMENT else level def _comprehension_view_level( @@ -1563,6 +1657,19 @@ def nearest(expressions: Iterable[ast.expr]) -> int: if isinstance(function, ast.Name): if function.id == "next": return _item_of(nearest(arguments)) + if function.id == "dict": + # ``dict(mapping)`` holds the mapping's values, ``dict(pairs)`` + # the pairs' second items, and ``dict(key=value)`` each value. + positional = nearest(call.args) + from_items = ( + _NO_VIEW + if positional <= _ELEMENT + else min(positional, _holder_of(_items_taken(positional, 2))) + ) + return min( + from_items, + _holder_of(nearest(keyword.value for keyword in call.keywords)), + ) if function.id in _SAME_ITEMS_BUILTINS: return _items_holder_of(nearest(arguments)) if function.id in _TUPLE_YIELDING_BUILTINS: @@ -1711,13 +1818,39 @@ def _check_augmented_assign(self, node: ast.AugAssign) -> None: # holds. target = node.target if isinstance(target, ast.Name): - if self._view_level(target) == _IS_VIEW: + if self._view_level( + target + ) == _IS_VIEW and not self._bound_only_to_extension_arrays(target.id): self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) elif isinstance(target, ast.Subscript): container = self._view_level(target.value) if container <= _ELEMENT or _item_of(container) == _IS_VIEW: self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) + def _bound_only_to_extension_arrays(self, name: str) -> bool: + """Whether every binding of ``name`` is ``x.array`` itself (or a slice). + + That is a pandas extension array, for which ``+=`` builds a new + array and rebinds the name instead of writing, except for datetime + data. + """ + + bindings = self._bindings(name) or [] + + def is_extension_array(value: ast.expr) -> bool: + while isinstance(value, ast.Subscript): + value = value.value + return ( + isinstance(value, ast.Attribute) + and value.attr == "array" + and not _is_own_object(value.value) + ) + + return bool(bindings) and all( + items_taken == 0 and value is not None and is_extension_array(value) + for value, items_taken in bindings + ) + def _check_attribute(self, node: ast.Attribute) -> None: if node.attr in _ALWAYS_PRIVATE_ATTRIBUTES: self._report(node, _PANDAS_PRIVATE_ATTRIBUTE) @@ -1870,6 +2003,80 @@ def _in_function(*body_lines: str, parameters: str = "series") -> str: #: Snippets the scan must refuse, with the one rule each must report. _REFUSED_SNIPPETS = { + # Round-four cases. + "series_array_through_dict_values": ( + _in_function( + "by_name = {name: frame[name].array for name in names}", + "for values in by_name.values():", + " values[0] = 1", + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_dict_item_pairs": ( + _in_function( + "by_name = {name: frame[name].array for name in names}", + "for pair in by_name.items():", + " pair[1][0] = 1", + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_comprehension_target_named_like_its_source": ( + _in_function( + "values = [frame[name].array for name in names]", + "[values.fill(0) for values in values]", + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_in_a_three_way_join": ( + _in_function( + "pair = [first.array] + [second.array] + extra", + "pair[0][0] = 1", + parameters="first, second, extra", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_in_a_long_join": ( + _in_function( + "parts = " + " + ".join(["[series.array]"] * 600), "parts[0][0] = 1" + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_dict_of_zip": ( + _in_function( + "arrays = [frame[name].array for name in names]", + "by_name = dict(zip(names, arrays))", + 'by_name["income"][0] = 1', + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_dict_keyword": ( + _in_function( + 'by_name = dict(income=frame["income"].array)', + 'by_name["income"][0] = 1', + parameters="frame", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_enumerate_of_zip": ( + _in_function( + "arrays = [frame[name].array for name in names]", + "for position, (name, values) in enumerate(zip(names, arrays)):", + " values[0] = position", + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "out_loop_target_over_a_list_of_existing_arrays": ( + _in_function( + "for buffer in [series.to_numpy()]:", + " np.add(buffer, 1, out=buffer)", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), # Round-three cases. "series_array_through_a_dict_comprehension_of_loop_targets": ( _in_function( @@ -2689,6 +2896,53 @@ def test_the_scanner_refuses_each_unprotected_write(source: str, rule: str) -> N #: Snippets the scan must accept: reads, read-only flags, and writes into #: arrays the same function created. _ACCEPTED_SNIPPETS = { + # Round-four cases. + "zip_rows_paired_inside_enumerate": _in_function( + 'for position, (row, value) in enumerate(zip(matrix, frame["x"].array)):', + " row[:] = value", + parameters="matrix, frame", + ), + "zip_rows_paired_inside_list": _in_function( + 'for row, value in list(zip(matrix, frame["x"].array)):', + " row[:] = value", + parameters="matrix, frame", + ), + "comprehension_target_over_a_new_array": _in_function( + "grid = np.zeros((3, 3))", + "[np.add(row, 1, out=row) for row in grid]", + parameters="", + ), + "pieces_of_a_new_array": _in_function( + "buffer = np.zeros(size)", + "for chunk in np.array_split(buffer, parts):", + " np.multiply(chunk, 2, out=chunk)", + parameters="size, parts", + ), + "extension_array_name_augmented": _in_function( + 'total = frame["a"].array', + 'total += frame["b"].array', + parameters="frame", + ), + "scalar_of_a_view_augmented": _in_function( + 'for value in frame["x"].array:', + " value -= 1", + parameters="frame", + ), + "clip_of_a_view_written": _in_function( + 'clipped = np.clip(frame["x"].array, 0, None)', + "clipped[clipped > 10] = 10", + parameters="frame", + ), + "deep_chain_of_comprehension_generators": _in_function( + "chain_0 = series.array", + "[" + + "chain_24.fill(0) " + + " ".join( + f"for chain_{index} in zip(chain_{index - 1}, chain_{index - 1})" + for index in range(1, 25) + ) + + "]", + ), # Round-three cases. "accumulating_scalars_of_views_into_a_dict": ( "from collections import defaultdict\n" From f30ac14b8718c10448bf204fb8f7afb6aebf3711 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:32:08 +0400 Subject: [PATCH 06/15] Fix the fifth round of review findings in Frame and the write scan Frame: the docstrings now say which extension-typed columns share memory through .values and to_numpy(), with examples rather than a list, and the test docstrings describe how the deep-copy path is reached. Scan: - Filling a NumPy array the function created by key copies, so it no longer counts as holding a view. - `*=` on items of a container built only from .array is accepted. - dict.update with a mapping, pairs or keywords is followed. - A positional False copy for nan_to_num and astype is refused. - .base counts only on .values or a library or array-method call. - Literals count as created; assignment expressions are followed. - Finding text no longer re-splits the source for each finding. - itemset (gone in NumPy 2) is dropped. - The four binding-kind self-tests now shadow a new array, so they fail if the binding is ignored. - Every fill method has a self-test. - The comprehension-cache test runs under a 30-second alarm. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/frame/bundle.py | 14 +- .../shared/test_frame_table_sharing.py | 16 +- .../shared/test_shared_buffer_writes.py | 360 ++++++++++++++---- 3 files changed, 301 insertions(+), 89 deletions(-) diff --git a/packages/microcosm-frame/src/microcosm/frame/bundle.py b/packages/microcosm-frame/src/microcosm/frame/bundle.py index 2e6685ac75..0525434c25 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -148,12 +148,14 @@ def _adopt( through ``Series.array``, private pandas attributes, an array made writable, ``ufunc.at``, ``np.copyto`` or ``out=`` (``test_shared_buffer_writes.py`` refuses these in the workspace's - source), and through the extension arrays of extension-typed columns: - ``.values`` returns the shared array itself for ``Int64``, - ``Float64``, ``boolean``, ``category`` and python-backed string - columns (and, under pandas 2.x, for pyarrow-backed ones), and - ``to_numpy()`` a writable view of it for all of these but - ``category``. + source), and through what ``.values`` and ``to_numpy()`` return for + extension-typed columns. ``.values`` returns the column's own + extension array, for example for the nullable integer, float and + boolean types, ``category`` and python-backed strings, and under + pandas 2.x for pyarrow-backed types. ``to_numpy()`` returns a + writable view of the column's data for, for example, the nullable + integer, float and boolean types and python-backed strings when the + column has no missing value, 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 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 10921577dd..cb04eddb95 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 @@ -7,10 +7,11 @@ 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`` -deep-copies instead. To take that path, the ``copy_on_write_off`` fixture -turns copy-on-write off under pandas 2.x and, under pandas 3, where it is -always on, replaces the check ``_adopt`` makes. Every other test runs with -copy-on-write on. +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 +the check themselves (the parametrized ``cow_off`` cases). Every other test +runs with copy-on-write on. """ import importlib @@ -107,7 +108,8 @@ def source_frame() -> Frame: ) -#: pandas 3 removed the copy-on-write switch along with this function. +#: pandas 3 removed this function; its copy-on-write option is deprecated +#: there and has no effect. _PANDAS_3 = not hasattr(pandas_config, "using_copy_on_write") @@ -566,8 +568,8 @@ class TestCopyOnWriteCheck: """``_pandas_copy_on_write`` on each pandas it can run under. pandas 2.x provides ``pandas._config.using_copy_on_write``; pandas 3 - removed it. The tests add or remove that function and replace the - version and the option reader to stand for each case. + removed it. The tests replace or remove that function, and replace the + version and the option reader, to stand for each case. """ @staticmethod 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 c68e2cdfd4..02a0d9fc4e 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 @@ -16,9 +16,10 @@ read-only views of the shared memory; this makes them writable. ``writes-through-writable-view`` A write into a writable view of pandas' memory: ``.array`` (of a Series - or Index), ``.asi8`` (datetime data), or ``.base`` read from a call's - result (such as ``to_numpy()``) or from ``.values`` or ``.array``, which - is the writable array behind a read-only view. + or Index), ``.asi8`` (datetime data), or ``.base`` read from + ``.values`` or from the result of a library function or an array method + (such as ``to_numpy()``), which is the writable array behind a + read-only view. Writes are item assignment, ``__setitem__``, ``fill``, ``sort`` and the other in-place ndarray methods, ``fillna(copy=False)``, ``out=``, @@ -26,8 +27,9 @@ into an item of it (a row of a two-dimensional view is a view too). ``+=`` and the other augmented assignments count only into a view itself, because an item of a one-dimensional view is a scalar, which - ``+=`` rebinds; and not into a name bound only to ``.array``, an - extension array, for which ``+=`` builds a new array. + ``+=`` rebinds; and not into a name, or an item of a container, bound + only to ``.array``, an extension array, for which ``+=`` builds a new + array. The written expression reaches the view through: @@ -42,20 +44,23 @@ ``list``, ``tuple``, ``sorted``, ``dict``, ``zip``, ``enumerate``, ``next``, ``.items()``, ``.values()``, ``.copy()`` of a container, and ``.get()``, ``.pop()`` and ``.setdefault()`` (with a default); - - ``or`` and conditional expressions; + - ``or``, conditional expressions and assignment expressions (``:=``); - a name the same function binds to any of these, by assignment, unpacking, a ``with`` statement, or a ``for`` loop or comprehension (which pair ``zip``, ``enumerate`` and ``.items()`` targets with their own sources, also when nested or wrapped in ``list`` or - ``sorted``), or fills with one (``append``, ``extend``, ``insert``, - ``add``, ``update``, ``setdefault``, ``name[key] = ...``, ``+=``). + ``sorted``), or fills with one: ``append``, ``extend``, ``insert``, + ``add``, ``setdefault``, ``update`` (with a mapping, pairs or + keywords), ``+=``, and ``name[key] = ...`` except into a NumPy array + the function created, because assigning into an array copies. Workspace classes' own ``self.array`` is exempt. ``pandas-private-attribute`` ``._ndarray``, ``._mgr``, ``._get_column_array`` or ``._iter_column_arrays`` on anything, and ``._values``, ``._data``, ``._mask`` or ``._codes`` on anything but ``self`` or ``cls``. These - reach pandas' internal arrays, which are always writable. + reach pandas' internal arrays, which are writable whenever the data + they hold is. ``numpy-copyto`` Any use of ``numpy.copyto``. ``writes-into-existing-array`` @@ -82,7 +87,7 @@ also in a comprehension, or unpacking) of one of these. ``np.clip``, ``np.round`` and ``np.take`` count only as views here: given a pandas object they can return its memory; - - arithmetic or a comparison; + - arithmetic, a comparison or a literal; - a ``.copy()``, ``list(...)`` and the other container builtins, ``+``, ``*`` or ``|`` (which also join containers), or a list, set or dict display. A slice of these is new; an item is not, because a shallow @@ -105,20 +110,26 @@ it does not refuse: - Writes it cannot see from the source: - - into the extension arrays of extension-typed columns: ``.values`` - returns the shared array for ``Int64``, ``Float64``, ``boolean``, - ``category`` and python-backed string columns, and ``to_numpy()`` a - writable view of it for all of these but ``category``; + - into what ``.values`` and ``to_numpy()`` return for extension-typed + columns: ``.values`` returns the column's own extension array (for + example for the nullable integer, float and boolean types, + ``category`` and python-backed strings, and under pandas 2.x for + pyarrow-backed types), and ``to_numpy()`` a writable view of the + column's data (for example for the nullable types and python-backed + strings without missing values, and sparse columns without gaps); - through a pandas object built with ``copy=False`` over another object's array; - into ``np.asarray(index)``, which is writable although the index is shared even between deep copies; - - ``+=`` on a datetime column's ``.array``, which writes in place. + - ``+=`` on a datetime, timedelta or period column's ``.array``, which + writes in place. - Arrays reached in other ways: - through other functions' return values or arguments, closures and object arrays; - names reached dynamically (``getattr(np, name)``, ``**{"out": array}``, - ``*arguments``), and positional ``out`` given to ndarray methods; + ``*arguments``), library functions bound by unpacking or through a + second alias, and positional ``out`` given to ndarray methods; + - containers filled inside a comprehension; - items of a container the function did not build; - array libraries other than NumPy and SciPy (``torch.from_numpy`` of a read-only view returns a writable tensor). @@ -128,6 +139,9 @@ a parameter rebound to a new array, and a name rebound from a view to a new array, count as before. - A boolean or integer array index gives a copy, but counts as indexing. + - ``name[key] = view`` into a parameter or other array the function did + not create counts as filling a container, though for an array it + copies. - ``.astype()`` counts as not created, because a pandas object's same-type conversion shares its memory. @@ -144,6 +158,7 @@ import importlib import inspect import re +import signal from collections import defaultdict from collections.abc import Callable, Iterable, Iterator from dataclasses import dataclass @@ -306,7 +321,6 @@ _ITEM_ADDING_METHODS = frozenset( {"append", "appendleft", "insert", "add", "setdefault"} ) -_ITEMS_ADDING_METHODS = frozenset({"extend", "update"}) #: Arithmetic and comparisons give a new array; ``+`` and ``*`` also join or #: repeat lists, whose items are shared, so they give a new container. @@ -382,7 +396,6 @@ "put", "partition", "resize", - "itemset", "setfield", } ) @@ -525,11 +538,18 @@ def _bound_level(items_taken: int, level: int) -> int: return _items_taken(level, items_taken) -def _held_level(items_taken: int, one_item: bool, level: int) -> int: +def _held_level(items_taken: int, kind: str, level: int) -> int: """The level of a container filled with a value (see ``_HeldValue``).""" level = _items_taken(level, items_taken) - return _holder_of(level) if one_item else _items_holder_of(level) + if kind in (_ONE_ITEM, _BY_KEY): + return _holder_of(level) + if kind == _ITEMS: + return _items_holder_of(level) + # A mapping's values, or the second items of pairs. + if level <= _ELEMENT: + return _NO_VIEW + return min(_items_holder_of(level), _holder_of(_items_taken(level, 2))) @dataclass(frozen=True) @@ -560,9 +580,17 @@ def describe(self) -> str: #: its iterable), 2 for a name unpacked from a loop target, and so on. _Binding = tuple[ast.expr | None, int] #: What a container is filled with: the value, how many items deep into it, -#: and whether it goes in as one item (``append``, ``name[key] = value``) -#: rather than as its items (``extend``, ``update``, ``+=``). -_HeldValue = tuple[ast.expr, int, bool] +#: and how it goes in (one of the kinds below). +_HeldValue = tuple[ast.expr, int, str] +#: ``append``, ``add``, ``insert``, ``setdefault`` and keyword ``update``. +_ONE_ITEM = "one item" +#: ``name[key] = value``; ignored for a NumPy array the function created, +#: because assigning into an array copies the values. +_BY_KEY = "by key" +#: ``extend`` and ``+=``: the value's items. +_ITEMS = "items" +#: Positional ``update``: a mapping's values or the second items of pairs. +_ENTRIES = "entries" def _target_names( @@ -723,7 +751,7 @@ def _record(self, bound: Iterable[tuple[ast.expr, ast.expr | None, int]]) -> Non self._bindings[target.id].append((value, items_taken)) elif isinstance(target.value, ast.Name) and value is not None: # ``name[key] = value`` puts one item into ``name``. - self._held[target.value.id].append((value, items_taken, True)) + self._held[target.value.id].append((value, items_taken, _BY_KEY)) def _collect(self) -> None: if self._bindings is not None: @@ -755,7 +783,7 @@ def _collect(self) -> None: # ``name += values`` adds the items of ``values`` to a list; # ``name[key] += value`` changes an item and adds none. if isinstance(child.target, ast.Name): - self._held[child.target.id].append((child.value, 0, False)) + self._held[child.target.id].append((child.value, 0, _ITEMS)) elif isinstance(child, (ast.For, ast.AsyncFor)): self._record(_loop_target_names(child.target, child.iter)) elif isinstance(child, ast.withitem) and child.optional_vars is not None: @@ -782,15 +810,17 @@ def _collect(self) -> None: and isinstance(child.func.value, ast.Name) ): method = child.func.attr - if method in _ITEM_ADDING_METHODS or method in _ITEMS_ADDING_METHODS: - one_item = method in _ITEM_ADDING_METHODS - self._held[child.func.value.id].extend( - (argument, 0, one_item) - for argument in ( - *child.args, - *(keyword.value for keyword in child.keywords), - ) + held = self._held[child.func.value.id] + keywords = [keyword.value for keyword in child.keywords] + if method in _ITEM_ADDING_METHODS: + held.extend( + (value, 0, _ONE_ITEM) for value in (*child.args, *keywords) ) + elif method == "extend": + held.extend((value, 0, _ITEMS) for value in child.args) + elif method == "update": + held.extend((value, 0, _ENTRIES) for value in child.args) + held.extend((value, 0, _ONE_ITEM) for value in keywords) class _ComprehensionScope: @@ -1072,11 +1102,32 @@ def _is_true_constant(expression: ast.expr) -> bool: return isinstance(expression, ast.Constant) and expression.value is True -def _copy_is_off(call: ast.Call) -> bool: - """Whether a call passes ``copy=`` with anything but ``True``.""" +def _copy_is_off(call: ast.Call, position: int | None = None) -> bool: + """Whether a call passes ``copy`` with anything but ``True``: by keyword, + or by ``position`` when the function takes it positionally.""" copy = _keyword(call, "copy") - return copy is not None and not _is_true_constant(copy.value) + value = copy.value if copy is not None else None + if ( + value is None + and position is not None + and len(call.args) > position + and not any(isinstance(argument, ast.Starred) for argument in call.args) + ): + value = call.args[position] + return value is not None and not _is_true_constant(value) + + +def _is_extension_array_expression(expression: ast.expr) -> bool: + """``x.array`` (or a slice of it): a pandas extension array.""" + + while isinstance(expression, ast.Subscript): + expression = expression.value + return ( + isinstance(expression, ast.Attribute) + and expression.attr == "array" + and not _is_own_object(expression.value) + ) def _is_own_object(expression: ast.expr) -> bool: @@ -1111,6 +1162,7 @@ def __init__(self, source: str, path: str, tree: ast.Module) -> None: self._module_scope = _Scope("", tree) self._scope: _Scope | _ComprehensionScope = self._module_scope self._digests: dict[int, str] = {} + self._source_lines: list[str] | None = None self._target_levels: dict[tuple[bool, int, int | None, str], int] = {} self._checks = { ast.Call: self._check_call, @@ -1159,6 +1211,23 @@ def scan(self) -> list[Finding]: # Reporting ----------------------------------------------------------- + def _segment(self, node: ast.AST) -> str: + """The source of ``node``, as ``ast.get_source_segment`` gives it, + from lines split once per module.""" + + if self._source_lines is None: + self._source_lines = re.findall(r"[^\r\n]*(?:\r\n|\r|\n|$)", self._source) + lines = self._source_lines + first, last = node.lineno - 1, node.end_lineno - 1 + start, end = node.col_offset, node.end_col_offset + if first == last: + return lines[first].encode()[start:end].decode() + return ( + lines[first].encode()[start:].decode() + + "".join(lines[first + 1 : last]) + + lines[last].encode()[:end].decode() + ) + def _function_digest(self) -> str: node = self._scope.node digest = self._digests.get(id(node)) @@ -1166,13 +1235,13 @@ def _function_digest(self) -> str: if isinstance(node, ast.Module): segment = self._source else: - segment = ast.get_source_segment(self._source, node) or "" + segment = self._segment(node) digest = hashlib.sha256(segment.encode("utf-8")).hexdigest()[:12] self._digests[id(node)] = digest return digest def _report(self, node: ast.AST, rule: str) -> None: - segment = ast.get_source_segment(self._source, node) or ast.unparse(node) + segment = self._segment(node) self.findings.append( Finding( path=self._path, @@ -1417,6 +1486,11 @@ def _newness(self, expression: ast.expr, lookup: _NameLookup | None = None) -> i return _NEW_ARRAY if isinstance(expression, _NEW_ARRAY_EXPRESSIONS): return _NEW_ARRAY + if isinstance(expression, ast.NamedExpr): + return self._newness(expression.value, lookup) + if isinstance(expression, ast.Constant): + # A literal (``total = 0.0``) holds no pandas memory. + return _NEW_ARRAY if isinstance(expression, _CONTAINER_EXPRESSIONS): return _NEW_OBJECT if isinstance(expression, ast.Name): @@ -1461,11 +1535,19 @@ def _view_table(self, scope: _Scope) -> dict[str, int]: (value, functools.partial(_bound_level, items_taken)) ) # A container filled here may be a parameter, so held values count - # for any name. + # for any name; but assigning into a NumPy array this function + # created copies the values. + new_arrays = { + name + for name, level in self._newness_table(scope).items() + if level == _NEW_ARRAY + } for name in scope.held_names(): - for value, items_taken, one_item in scope.held_values(name): + for value, items_taken, kind in scope.held_values(name): + if kind == _BY_KEY and name in new_arrays: + continue sources[name].append( - (value, functools.partial(_held_level, items_taken, one_item)) + (value, functools.partial(_held_level, items_taken, kind)) ) levels: dict[str, int] = dict.fromkeys(sources, _NO_VIEW) @@ -1491,6 +1573,19 @@ def lookup(name: str) -> int: scope.view_table = levels return levels + def _is_array_expression(self, expression: ast.expr) -> bool: + """``.values``, or a call of a library function or of an array method.""" + + if isinstance(expression, ast.Attribute): + return expression.attr == "values" + if not isinstance(expression, ast.Call): + return False + function = expression.func + return self._resolve(function) is not None or ( + isinstance(function, ast.Attribute) + and function.attr in (*_VIEW_METHODS, "astype") + ) + def _is_container(self, expression: ast.expr) -> bool: # A chain of joins (``[a] + [b] + rest``) is a container if any of # its operands is one. @@ -1532,16 +1627,18 @@ def _view_level( if expression.attr == "base": # ``.base`` of an array expression is the array behind a view; # on other objects it is an ordinary attribute. - array_expression = isinstance(expression.value, ast.Call) or ( - isinstance(expression.value, ast.Attribute) - and expression.value.attr in ("values", "array") + return ( + _IS_VIEW + if self._is_array_expression(expression.value) + else _NO_VIEW ) - return _IS_VIEW if array_expression else _NO_VIEW if expression.attr in _VIEW_ATTRIBUTES: return _view_of(self._view_level(expression.value, lookup)) return _NO_VIEW if isinstance(expression, ast.Subscript): return _item_of(self._view_level(expression.value, lookup)) + if isinstance(expression, ast.NamedExpr): + return self._view_level(expression.value, lookup) if isinstance(expression, ast.Starred): return self._view_level(expression.value, lookup) if isinstance(expression, ast.Name): @@ -1688,7 +1785,7 @@ def nearest(expressions: Iterable[ast.expr]) -> int: if copy_value is not None and _is_true_constant(copy_value): return _NO_VIEW return _view_of(receiver) - if method == "astype" and _copy_is_off(call): + if method == "astype" and _copy_is_off(call, position=1): return _view_of(receiver) if method == "copy": # A copy of an array is new memory; a copy of a container holds @@ -1738,7 +1835,7 @@ def _output_arguments(self, call: ast.Call) -> list[ast.expr]: return written if name in _IN_PLACE_NUMPY_FUNCTIONS: return [*written, *call.args[:1]] - if name == "numpy.nan_to_num" and _copy_is_off(call): + if name == "numpy.nan_to_num" and _copy_is_off(call, position=1): return [*written, *call.args[:1]] if _is_ufunc_method(name, ("at",)): return [*written, *call.args[:1]] @@ -1824,33 +1921,58 @@ def _check_augmented_assign(self, node: ast.AugAssign) -> None: self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) elif isinstance(target, ast.Subscript): container = self._view_level(target.value) - if container <= _ELEMENT or _item_of(container) == _IS_VIEW: + if container <= _ELEMENT or ( + _item_of(container) == _IS_VIEW + and not self._holds_only_extension_arrays(target.value) + ): self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) def _bound_only_to_extension_arrays(self, name: str) -> bool: """Whether every binding of ``name`` is ``x.array`` itself (or a slice). That is a pandas extension array, for which ``+=`` builds a new - array and rebinds the name instead of writing, except for datetime - data. + array and rebinds the name instead of writing, except for datetime, + timedelta and period data. """ bindings = self._bindings(name) or [] - - def is_extension_array(value: ast.expr) -> bool: - while isinstance(value, ast.Subscript): - value = value.value - return ( - isinstance(value, ast.Attribute) - and value.attr == "array" - and not _is_own_object(value.value) - ) - return bool(bindings) and all( - items_taken == 0 and value is not None and is_extension_array(value) + items_taken == 0 + and value is not None + and _is_extension_array_expression(value) for value, items_taken in bindings ) + def _holds_only_extension_arrays(self, container: ast.expr) -> bool: + """Whether every item a container is built or filled with is an + ``x.array`` itself, so that ``container[key] += 1`` rebinds the item.""" + + if not isinstance(container, ast.Name): + return False + items: list[ast.expr] = [] + for value, items_taken in self._bindings(container.id) or []: + if items_taken or value is None: + return False + if isinstance(value, (ast.List, ast.Tuple, ast.Set)): + items.extend(value.elts) + elif isinstance(value, ast.Dict): + if any(key is None for key in value.keys): + return False + items.extend(value.values) + elif isinstance(value, (ast.ListComp, ast.SetComp, ast.GeneratorExp)): + items.append(value.elt) + elif isinstance(value, ast.DictComp): + items.append(value.value) + else: + return False + for value, items_taken, kind in self._owning_scope().held_values(container.id): + if items_taken or kind not in (_ONE_ITEM, _BY_KEY): + return False + items.append(value) + return bool(items) and all( + _is_extension_array_expression(item) for item in items + ) + def _check_attribute(self, node: ast.Attribute) -> None: if node.attr in _ALWAYS_PRIVATE_ATTRIBUTES: self._report(node, _PANDAS_PRIVATE_ATTRIBUTE) @@ -2003,6 +2125,40 @@ def _in_function(*body_lines: str, parameters: str = "series") -> str: #: Snippets the scan must refuse, with the one rule each must report. _REFUSED_SNIPPETS = { + # Round-five cases. + **{ + f"series_array_filled_with_{method}": ( + _in_function( + "holder = []", + fill, + "holder[0][0] = 1", + parameters="frame, names, by_name", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ) + for method, fill in { + "append": 'holder.append(frame["income"].array)', + "extend": "holder.extend([frame[name].array for name in names])", + "insert": 'holder.insert(0, frame["income"].array)', + "add": 'holder.add(frame["income"].array)', + "setdefault": 'holder.setdefault(0, frame["income"].array)', + "update_from_pairs": "holder.update(zip(names, (frame[n].array for n in names)))", + "update_from_a_mapping": "holder.update({0: frame['income'].array})", + "update_with_keywords": 'holder.update(income=frame["income"].array)', + }.items() + }, + "series_array_through_a_walrus": ( + _NUMPY + "(values := np.asarray(series.array))[0] = 1\n", + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_astype_with_a_positional_false_copy": ( + 'series.array.astype("float64", False)[0] = 1\n', + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "numpy_nan_to_num_with_a_positional_false_copy": ( + _in_function("np.nan_to_num(values, False)", parameters="values"), + _WRITES_INTO_EXISTING_ARRAY, + ), # Round-four cases. "series_array_through_dict_values": ( _in_function( @@ -2499,10 +2655,6 @@ def _in_function(*body_lines: str, parameters: str = "series") -> str: _NUMPY + "np.asarray(series.array).resize(3)\n", _WRITES_THROUGH_WRITABLE_VIEW, ), - "series_array_itemset": ( - _NUMPY + "np.asarray(series.array).itemset(0, 1)\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), "series_array_setfield": ( _NUMPY + "np.asarray(series.array).setfield(1, np.int64)\n", _WRITES_THROUGH_WRITABLE_VIEW, @@ -2848,6 +3000,7 @@ def _in_function(*body_lines: str, parameters: str = "series") -> str: ), "out_with_target": ( _in_function( + "buffer = np.zeros(3)", "with opener() as buffer:", " np.add(buffer, 1, out=buffer)", parameters="opener", @@ -2856,6 +3009,7 @@ def _in_function(*body_lines: str, parameters: str = "series") -> str: ), "out_except_target": ( _in_function( + "buffer = np.zeros(3)", "try:", " pass", "except Exception as buffer:", @@ -2865,11 +3019,17 @@ def _in_function(*body_lines: str, parameters: str = "series") -> str: _WRITES_INTO_EXISTING_ARRAY, ), "out_imported_name": ( - _in_function("import buffer", "np.add(1, 1, out=buffer)", parameters=""), + _in_function( + "buffer = np.zeros(3)", + "import buffer", + "np.add(1, 1, out=buffer)", + parameters="", + ), _WRITES_INTO_EXISTING_ARRAY, ), "out_match_capture": ( _in_function( + "buffer = np.zeros(3)", "match value:", " case [buffer]:", " np.add(1, 1, out=buffer)", @@ -2896,6 +3056,37 @@ def test_the_scanner_refuses_each_unprotected_write(source: str, rule: str) -> N #: Snippets the scan must accept: reads, read-only flags, and writes into #: arrays the same function created. _ACCEPTED_SNIPPETS = { + # Round-five cases. + "new_array_filled_by_key_from_views": _in_function( + "matrix = np.empty((len(columns), size))", + "for row, column in enumerate(columns):", + " matrix[row] = frame[column].array", + " matrix[row] /= matrix[row].sum()", + " np.divide(matrix[row], 2, out=matrix[row])", + "buffer = np.empty(size)", + "buffer[:] = frame['x'].array", + "buffer[mask] += 1", + parameters="frame, columns, size, mask", + ), + "extension_arrays_in_a_dict_scaled": _in_function( + "columns = {name: frame[name].array for name in names}", + 'columns["income"] *= factor', + parameters="frame, names, factor", + ), + "base_of_an_ordinary_call": _in_function( + "label = graph.node(version).base", + 'label += "/x"', + "columns = holder.base", + 'columns["x"] = 1', + parameters="graph, version, holder", + ), + "running_total_from_a_constant": _in_function( + "total = 0.0", + "for column in columns:", + " total = total + frame[column].to_numpy()", + "np.divide(total, len(columns), out=total)", + parameters="frame, columns", + ), # Round-four cases. "zip_rows_paired_inside_enumerate": _in_function( 'for position, (row, value) in enumerate(zip(matrix, frame["x"].array)):', @@ -2933,16 +3124,6 @@ def test_the_scanner_refuses_each_unprotected_write(source: str, rule: str) -> N "clipped[clipped > 10] = 10", parameters="frame", ), - "deep_chain_of_comprehension_generators": _in_function( - "chain_0 = series.array", - "[" - + "chain_24.fill(0) " - + " ".join( - f"for chain_{index} in zip(chain_{index - 1}, chain_{index - 1})" - for index in range(1, 25) - ) - + "]", - ), # Round-three cases. "accumulating_scalars_of_views_into_a_dict": ( "from collections import defaultdict\n" @@ -3248,3 +3429,30 @@ def test_a_changed_function_changes_the_finding_key() -> None: assert before.code == after.code assert before.key != after.key + + +def test_a_deep_chain_of_comprehension_generators_is_scanned_quickly() -> None: + """Comprehension loop targets are cached. Without the cache every + generator doubles the work, so forty of them would take days; the alarm + turns that into a failure instead of a hang.""" + + if not hasattr(signal, "setitimer"): + pytest.skip("needs signal.setitimer") + generators = " ".join( + f"for chain_{index} in zip(chain_{index - 1}, chain_{index - 1})" + for index in range(1, 41) + ) + source = _in_function("chain_0 = series.array", f"[chain_40.fill(0) {generators}]") + + def stop(_signal_number: int, _frame: object) -> None: + raise TimeoutError("the scan did not finish within 30 seconds") + + previous = signal.signal(signal.SIGALRM, stop) + signal.setitimer(signal.ITIMER_REAL, 30) + try: + findings = scan_source(source, "snippet.py") + finally: + signal.setitimer(signal.ITIMER_REAL, 0) + signal.signal(signal.SIGALRM, previous) + + assert findings == [] From 5cc0f72c7458f7935e1badc1cc9f4b77ea1be99f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:58:50 +0400 Subject: [PATCH 07/15] Fix the sixth round of review findings in Frame and the write scan Frame: correct the docstrings on python-backed strings (their to_numpy() shares memory even with missing values) and on the invariants with_columns can break. Scan: - In-place methods count only on a view itself, so string methods such as label.partition on scalars taken from a view are accepted. - A slice of a view is a view, so `+=` on one is refused. - A call given a created output array returns a created array. - .copy() of an array expression is a new array. - NumPy calls such as np.append are no longer taken for container fills. - insert and setdefault put in only their value. - dict(**mapping) and update(**mapping) pass on the mapping's values. - A positional copy counts only as the constant False. - A module that fails to import no longer stops the scan. - The time-limited test now also covers the newness cache. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/frame/bundle.py | 10 +- .../shared/test_shared_buffer_writes.py | 210 ++++++++++++++---- 2 files changed, 175 insertions(+), 45 deletions(-) diff --git a/packages/microcosm-frame/src/microcosm/frame/bundle.py b/packages/microcosm-frame/src/microcosm/frame/bundle.py index 0525434c25..9fafbec17b 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -154,8 +154,8 @@ def _adopt( boolean types, ``category`` and python-backed strings, and under pandas 2.x for pyarrow-backed types. ``to_numpy()`` returns a writable view of the column's data for, for example, the nullable - integer, float and boolean types and python-backed strings when the - column has no missing value, and sparse columns without gaps. + 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 @@ -991,9 +991,9 @@ def with_columns(self, entity: str, /, **columns: Any) -> "Frame": for example). ValueError: If ``entity`` is not declared by the schema, a value's length does not match the table, or the new columns break a - constructor invariant (a name another table already carries, - an ``{entity}_weight`` name on a table whose entity has no - typed weights, or broken linkage). + 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) 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 02a0d9fc4e..b4b9cdfc9c 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 @@ -21,15 +21,14 @@ (such as ``to_numpy()``), which is the writable array behind a read-only view. - Writes are item assignment, ``__setitem__``, ``fill``, ``sort`` and the - other in-place ndarray methods, ``fillna(copy=False)``, ``out=``, - ``shuffle`` and the in-place NumPy functions below, into the view or - into an item of it (a row of a two-dimensional view is a view too). - ``+=`` and the other augmented assignments count only into a view - itself, because an item of a one-dimensional view is a scalar, which - ``+=`` rebinds; and not into a name, or an item of a container, bound - only to ``.array``, an extension array, for which ``+=`` builds a new - array. + Writes are item assignment, ``__setitem__``, ``out=``, ``shuffle`` and + the in-place NumPy functions below, into the view or into an item of it + (a row of a two-dimensional view is a view too). ``fill``, ``sort`` + and the other in-place ndarray methods, ``fillna(copy=False)``, ``+=`` + and the other augmented assignments count only on a view itself (a + slice of it is one), because an item of a one-dimensional view is a + scalar; and ``+=`` not on a name, or an item of a container, bound only + to ``.array``, an extension array, for which ``+=`` builds a new array. The written expression reaches the view through: @@ -82,7 +81,9 @@ ``.flatten()``, or a NumPy function that always allocates (``_ALLOCATING_NUMPY_FUNCTIONS``: ``np.zeros``, ``np.where``, ``np.concatenate``, ...), when not given an output array; - - ``np.array`` without ``copy=``, or ``to_numpy(copy=True)``; + - ``np.array`` without ``copy=``, ``to_numpy(copy=True)``, or a + ``.copy()`` of ``.values`` or of a library or array-method call; + - the output array of a call given one that is created; - a view, piece (``np.split``), subscript or item (a loop target, also in a comprehension, or unpacking) of one of these. ``np.clip``, ``np.round`` and ``np.take`` count only as views here: given a @@ -115,8 +116,8 @@ example for the nullable integer, float and boolean types, ``category`` and python-backed strings, and under pandas 2.x for pyarrow-backed types), and ``to_numpy()`` a writable view of the - column's data (for example for the nullable types and python-backed - strings without missing values, and sparse columns without gaps); + column's data (for example for the nullable types without missing + values, python-backed strings, and sparse columns without gaps); - through a pandas object built with ``copy=False`` over another object's array; - into ``np.asarray(index)``, which is writable although the index is @@ -128,8 +129,11 @@ object arrays; - names reached dynamically (``getattr(np, name)``, ``**{"out": array}``, ``*arguments``), library functions bound by unpacking or through a - second alias, and positional ``out`` given to ndarray methods; - - containers filled inside a comprehension; + second alias, and positional ``out`` given to any method; + - containers filled inside a comprehension, comprehension loop targets + captured with ``:=``, and subscripts or attributes used as ``for`` or + ``with`` targets; + - ``.base`` read through a name (``values = s.to_numpy(); values.base``); - items of a container the function did not build; - array libraries other than NumPy and SciPy (``torch.from_numpy`` of a read-only view returns a writable tensor). @@ -139,9 +143,10 @@ a parameter rebound to a new array, and a name rebound from a view to a new array, count as before. - A boolean or integer array index gives a copy, but counts as indexing. - - ``name[key] = view`` into a parameter or other array the function did - not create counts as filling a container, though for an array it - copies. + - ``name[key] = view`` into a parameter, a ``.copy()`` of one, or another + array the function did not create counts as filling a container, + though for an array it copies; and a list from ``np.split`` of a + created array counts as an array, so it is not followed as a container. - ``.astype()`` counts as not created, because a pandas object's same-type conversion shares its memory. @@ -442,7 +447,8 @@ #: NumPy functions that return new memory for an ndarray or an extension #: array, but, given a Series or DataFrame, call its method, whose result can -#: share the object's memory: never counted as created. +#: share the object's memory. They are not views of ndarrays or extension +#: arrays, and count as created only as views of a created array. _PANDAS_SHARING_NUMPY_FUNCTIONS = frozenset( f"numpy.{name}" for name in ("clip", "round", "around", "take") ) @@ -811,16 +817,21 @@ def _collect(self) -> None: ): method = child.func.attr held = self._held[child.func.value.id] - keywords = [keyword.value for keyword in child.keywords] + # ``insert(index, value)`` and ``setdefault(key, value)`` put + # in only their second argument. + values = ( + child.args[1:] if method in ("insert", "setdefault") else child.args + ) if method in _ITEM_ADDING_METHODS: - held.extend( - (value, 0, _ONE_ITEM) for value in (*child.args, *keywords) - ) + held.extend((value, 0, _ONE_ITEM) for value in values) elif method == "extend": - held.extend((value, 0, _ITEMS) for value in child.args) + held.extend((value, 0, _ITEMS) for value in values) elif method == "update": - held.extend((value, 0, _ENTRIES) for value in child.args) - held.extend((value, 0, _ONE_ITEM) for value in keywords) + held.extend((value, 0, _ENTRIES) for value in values) + for keyword in child.keywords: + # ``**mapping`` puts in the mapping's values. + kind = _ENTRIES if keyword.arg is None else _ONE_ITEM + held.append((keyword.value, 0, kind)) class _ComprehensionScope: @@ -1041,6 +1052,9 @@ def _library_object(dotted_name: str) -> object | None: found: object = importlib.import_module(".".join(parts[:split])) except ImportError: continue + except Exception: + # A module that fails to import names nothing the scan can use. + return None for part in parts[split:]: found = getattr(found, part, None) if found is None: @@ -1086,6 +1100,14 @@ def _is_ufunc_method(dotted_name: str, methods: Iterable[str]) -> bool: return method in methods and isinstance(_library_object(owner), np.ufunc) +def _is_slice(index: ast.expr) -> bool: + """Whether a subscript's index is a slice (``a[1:]``, ``a[:, 0:2]``).""" + + if isinstance(index, ast.Tuple): + return any(isinstance(part, ast.Slice) for part in index.elts) + return isinstance(index, ast.Slice) + + def _is_false_constant(expression: ast.expr) -> bool: return isinstance(expression, ast.Constant) and not expression.value @@ -1114,7 +1136,11 @@ def _copy_is_off(call: ast.Call, position: int | None = None) -> bool: and len(call.args) > position and not any(isinstance(argument, ast.Starred) for argument in call.args) ): - value = call.args[position] + positional = call.args[position] + # Other methods of the same name take other arguments there (an + # ndarray's ``astype(dtype, order)``), so only the constant False + # counts. + return isinstance(positional, ast.Constant) and positional.value is False return value is not None and not _is_true_constant(value) @@ -1395,8 +1421,11 @@ def lookup(name: str) -> int: return levels def _call_newness(self, call: ast.Call, lookup: _NameLookup | None) -> int: - if self._output_arguments(call): - return _NOT_NEW + outputs = self._output_arguments(call) + if outputs: + # The result is the output array (or None, for ``ufunc.at`` and + # the in-place functions): as new as the outputs are. + return min(self._newness(output, lookup) for output in outputs) name = self._resolve(call.func) function = call.func if name is not None: @@ -1446,13 +1475,17 @@ def _call_newness(self, call: ast.Call, lookup: _NameLookup | None) -> int: deep = _keyword(call, "deep") if deep is not None and not _is_true_constant(deep.value): return _NOT_NEW - if not call.args: - return _NEW_OBJECT - first = call.args[0] - if isinstance(first, ast.Constant) and ( - first.value is True or isinstance(first.value, str) + first = call.args[0] if call.args else None + if first is not None and not ( + isinstance(first, ast.Constant) + and (first.value is True or isinstance(first.value, str)) ): - return _NEW_OBJECT + return _NOT_NEW + # A copy of an array is a new array; of anything else (a dict, a + # list), possibly a shallow copy whose items are shared. + return ( + _NEW_ARRAY if self._is_array_expression(function.value) else _NEW_OBJECT + ) return _NOT_NEW def _newness(self, expression: ast.expr, lookup: _NameLookup | None = None) -> int: @@ -1542,7 +1575,11 @@ def _view_table(self, scope: _Scope) -> dict[str, int]: for name, level in self._newness_table(scope).items() if level == _NEW_ARRAY } + library_names = self._libraries.bound_names | self._libraries.derived_names for name in scope.held_names(): + if name in library_names: + # ``np.append(...)`` is a library call, not a container fill. + continue for value, items_taken, kind in scope.held_values(name): if kind == _BY_KEY and name in new_arrays: continue @@ -1636,7 +1673,10 @@ def _view_level( return _view_of(self._view_level(expression.value, lookup)) return _NO_VIEW if isinstance(expression, ast.Subscript): - return _item_of(self._view_level(expression.value, lookup)) + container = self._view_level(expression.value, lookup) + if _is_slice(expression.slice): + return container + return _item_of(container) if isinstance(expression, ast.NamedExpr): return self._view_level(expression.value, lookup) if isinstance(expression, ast.Starred): @@ -1763,9 +1803,16 @@ def nearest(expressions: Iterable[ast.expr]) -> int: if positional <= _ELEMENT else min(positional, _holder_of(_items_taken(positional, 2))) ) + named = nearest( + keyword.value for keyword in call.keywords if keyword.arg + ) + unpacked = nearest( + keyword.value for keyword in call.keywords if keyword.arg is None + ) return min( from_items, - _holder_of(nearest(keyword.value for keyword in call.keywords)), + _holder_of(named), + _NO_VIEW if unpacked <= _ELEMENT else unpacked, ) if function.id in _SAME_ITEMS_BUILTINS: return _items_holder_of(nearest(arguments)) @@ -1866,7 +1913,9 @@ def _check_call(self, node: ast.Call) -> None: if flag is not None and not _is_false_constant(flag): self._report(node, _MAKES_ARRAY_WRITABLE) elif self._writes_into_receiver(node, function.attr): - if self._reaches_writable_view(function.value): + # Only on a view itself: an item of a one-dimensional view is + # a scalar, and ``label.partition(" ")`` is a string method. + if self._view_level(function.value) == _IS_VIEW: self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) for written in self._output_arguments(node): self._check_written_array(node, written) @@ -2125,6 +2174,43 @@ def _in_function(*body_lines: str, parameters: str = "series") -> str: #: Snippets the scan must refuse, with the one rule each must report. _REFUSED_SNIPPETS = { + # Round-six cases. + "slice_of_a_view_augmented": ( + _in_function("head = np.asarray(series.array)[:3]", "head += 1"), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "loop_over_a_slice_of_views_augmented": ( + _in_function( + "arrays = [np.asarray(frame[name].array) for name in names]", + "for values in arrays[1:]:", + " values -= arrays[0]", + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "array_of_a_slice_of_a_view_augmented": ( + _in_function("values = np.asarray(series.array[1:])", "values += 1"), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_dict_of_an_unpacked_mapping": ( + _in_function( + "by_name = {name: frame[name].array for name in names}", + "copied = dict(**by_name)", + 'copied["income"][0] = 1', + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "series_array_through_update_with_an_unpacked_mapping": ( + _in_function( + "by_name = {name: frame[name].array for name in names}", + "holder = {}", + "holder.update(**by_name)", + 'holder["income"][0] = 1', + parameters="frame, names", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), # Round-five cases. **{ f"series_array_filled_with_{method}": ( @@ -3056,6 +3142,40 @@ def test_the_scanner_refuses_each_unprotected_write(source: str, rule: str) -> N #: Snippets the scan must accept: reads, read-only flags, and writes into #: arrays the same function created. _ACCEPTED_SNIPPETS = { + # Round-six cases. + "string_methods_on_labels_from_views": _in_function( + 'for code, label in zip(frame["c"].array, frame["l"].array):', + ' head, _, rest = label.partition(" ")', + parameters="frame", + ), + "output_array_of_a_call_reused": _in_function( + "share = np.divide(part, total, out=np.zeros_like(part), where=total > 0)", + "np.clip(share, 0, 1, out=share)", + parameters="part, total", + ), + "copy_of_an_array_filled_by_key": _in_function( + "matrix = np.asarray(template).copy()", + "for row, column in enumerate(columns):", + " matrix[row] = frame[column].array", + " matrix[row] /= matrix[row].sum()", + parameters="template, frame, columns", + ), + "numpy_append_is_not_a_fill": _in_function( + 'extended = np.append(frame["x"].array, 0.0)', + "grid = np.copy(base)", + "grid[mask] += 1", + parameters="frame, base, mask", + ), + "extension_arrays_set_by_default_scaled": _in_function( + "columns = {}", + 'columns.setdefault("a", frame["a"].array)', + 'columns["a"] *= 2', + parameters="frame", + ), + "astype_given_an_order_written": _in_function( + "converted = np.asarray(series.array).astype(np.float64, 'C')", + "converted[0] = 1", + ), # Round-five cases. "new_array_filled_by_key_from_views": _in_function( "matrix = np.empty((len(columns), size))", @@ -3432,9 +3552,9 @@ def test_a_changed_function_changes_the_finding_key() -> None: def test_a_deep_chain_of_comprehension_generators_is_scanned_quickly() -> None: - """Comprehension loop targets are cached. Without the cache every - generator doubles the work, so forty of them would take days; the alarm - turns that into a failure instead of a hang.""" + """Comprehension loop targets are cached, for both rules. Without the + cache every generator doubles the work, so forty of them would take + days; the alarm turns that into a failure instead of a hang.""" if not hasattr(signal, "setitimer"): pytest.skip("needs signal.setitimer") @@ -3443,6 +3563,15 @@ def test_a_deep_chain_of_comprehension_generators_is_scanned_quickly() -> None: for index in range(1, 41) ) source = _in_function("chain_0 = series.array", f"[chain_40.fill(0) {generators}]") + branches = " ".join( + f"for chain_{index} in (chain_{index - 1} if flag else chain_{index - 1})" + for index in range(1, 41) + ) + newness_source = _in_function( + "chain_0 = np.zeros((2, 2))", + f"[np.add(chain_40, 1, out=chain_40) {branches}]", + parameters="flag", + ) def stop(_signal_number: int, _frame: object) -> None: raise TimeoutError("the scan did not finish within 30 seconds") @@ -3451,6 +3580,7 @@ def stop(_signal_number: int, _frame: object) -> None: signal.setitimer(signal.ITIMER_REAL, 30) try: findings = scan_source(source, "snippet.py") + findings += scan_source(newness_source, "snippet.py") finally: signal.setitimer(signal.ITIMER_REAL, 0) signal.signal(signal.SIGALRM, previous) From 32111cba365bfa27ca2336de01638b3e047aa486 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:19:46 +0400 Subject: [PATCH 08/15] Fix the seventh round of review findings in Frame and the write scan Frame: the _adopt docstring frames its list of unprotected writes as examples and adds .base and .asi8; replace_tables says it can add a declared link table; with_columns says pandas raises TypeError or ValueError for values it cannot assign. Scan: - A container fill is skipped as a library call only when the name is bound to a library object where it is filled. Library alias names come only from names bound directly, so `x[mask] = np.nan` no longer hides later fills of `x`. - Multi-dimensional slices of new containers count as new. - __setitem__ writes like item assignment again. - .copy() of a split list is a list copy. - The extension-array `+=` exemption follows names and slices. - `arrays[1:] += more` only rebinds list items. - New self-tests cover insert and a module that fails to import. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/frame/bundle.py | 37 ++--- .../shared/test_shared_buffer_writes.py | 130 ++++++++++++++++-- 2 files changed, 137 insertions(+), 30 deletions(-) diff --git a/packages/microcosm-frame/src/microcosm/frame/bundle.py b/packages/microcosm-frame/src/microcosm/frame/bundle.py index 9fafbec17b..13a3da7af5 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -144,9 +144,10 @@ def _adopt( DataFrame objects afterwards: a write to the same object changes this frame. - Copy-on-write does not protect raw writes into the shared memory: - through ``Series.array``, private pandas attributes, an array made - writable, ``ufunc.at``, ``np.copyto`` or ``out=`` + 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 these in the workspace's source), and through what ``.values`` and ``to_numpy()`` return for extension-typed columns. ``.values`` returns the column's own @@ -166,8 +167,8 @@ def _adopt( 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 fails on such a table later, with an error - that depends on the object). Weights are stored as given (their arrays are + checked (the constructor stores whatever the table's ``copy()`` + returns and checks that). Weights are stored as given (their arrays are read-only), and the strata are shallow-copied when copy-on-write is on. @@ -924,7 +925,7 @@ def _mass_change_record( ) def replace_tables(self, /, **changed_tables: pd.DataFrame) -> "Frame": - """Return a new frame with some entity or link tables replaced. + """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 @@ -932,12 +933,13 @@ 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 metadata are - carried unchanged. When copy-on-write is off, every table is - deep-copied instead (see :meth:`_adopt`). + 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 keyed by entity or link name. + **changed_tables: Replacement tables, or declared link tables to + add, keyed by entity or link name. Returns: A new validated frame. @@ -987,13 +989,14 @@ def with_columns(self, entity: str, /, **columns: Any) -> "Frame": A new validated frame. Raises: - TypeError: If pandas cannot assign a value as a column (a set, - for example). - ValueError: If ``entity`` is not declared by the schema, a value's - length does not match the table, 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). + TypeError, ValueError: As pandas raises them when it cannot + assign a value as a column (for example a set, a value of the + wrong length, or a two-dimensional array). + 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) 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 b4b9cdfc9c..aa153dd270 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 @@ -968,9 +968,11 @@ def __init__(self, tree: ast.Module) -> None: ) for target in targets: derived.update( - name.id - for name in ast.walk(target) - if isinstance(name, ast.Name) + bound.id + for bound, _value, _items in _target_names( + target, node.value, 0 + ) + if isinstance(bound, ast.Name) ) self.derived_names = frozenset(derived) @@ -1042,6 +1044,10 @@ def may_hold_finding(self, statement: ast.stmt) -> bool: # Library lookups ----------------------------------------------------------- +def _import_module(name: str) -> object: + return importlib.import_module(name) + + @functools.cache def _library_object(dotted_name: str) -> object | None: """The NumPy or SciPy object a dotted name names, importing its module.""" @@ -1049,7 +1055,7 @@ def _library_object(dotted_name: str) -> object | None: parts = dotted_name.split(".") for split in range(len(parts), 0, -1): try: - found: object = importlib.import_module(".".join(parts[:split])) + found: object = _import_module(".".join(parts[:split])) except ImportError: continue except Exception: @@ -1501,7 +1507,7 @@ def _newness(self, expression: ast.expr, lookup: _NameLookup | None = None) -> i container = self._newness(expression.value, lookup) if container == _NEW_ARRAY: return _NEW_ARRAY - if container == _NEW_OBJECT and isinstance(expression.slice, ast.Slice): + if container == _NEW_OBJECT and _is_slice(expression.slice): return _NEW_OBJECT return _NOT_NEW if isinstance(expression, ast.IfExp): @@ -1575,9 +1581,8 @@ def _view_table(self, scope: _Scope) -> dict[str, int]: for name, level in self._newness_table(scope).items() if level == _NEW_ARRAY } - library_names = self._libraries.bound_names | self._libraries.derived_names for name in scope.held_names(): - if name in library_names: + if self._resolve(ast.Name(id=name, ctx=ast.Load())) is not None: # ``np.append(...)`` is a library call, not a container fill. continue for value, items_taken, kind in scope.held_values(name): @@ -1618,9 +1623,13 @@ def _is_array_expression(self, expression: ast.expr) -> bool: if not isinstance(expression, ast.Call): return False function = expression.func - return self._resolve(function) is not None or ( - isinstance(function, ast.Attribute) - and function.attr in (*_VIEW_METHODS, "astype") + name = self._resolve(function) + if name is not None: + # ``np.split`` and the like return lists. + return name not in _SPLITTING_NUMPY_FUNCTIONS + return isinstance(function, ast.Attribute) and function.attr in ( + *_VIEW_METHODS, + "astype", ) def _is_container(self, expression: ast.expr) -> bool: @@ -1912,6 +1921,10 @@ def _check_call(self, node: ast.Call) -> None: flag = node.args[0] if flag is not None and not _is_false_constant(flag): self._report(node, _MAKES_ARRAY_WRITABLE) + elif function.attr == "__setitem__": + # Like item assignment: into a view or an item of one. + if self._reaches_writable_view(function.value): + self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) elif self._writes_into_receiver(node, function.attr): # Only on a view itself: an item of a one-dimensional view is # a scalar, and ``label.partition(" ")`` is a string method. @@ -1969,9 +1982,11 @@ def _check_augmented_assign(self, node: ast.AugAssign) -> None: ) == _IS_VIEW and not self._bound_only_to_extension_arrays(target.id): self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) elif isinstance(target, ast.Subscript): + # Into a view through indexing, or into a view a holder holds + # (``arrays[0] += 1``; ``arrays[1:] += more`` only rebinds items). container = self._view_level(target.value) if container <= _ELEMENT or ( - _item_of(container) == _IS_VIEW + self._view_level(target) == _IS_VIEW and not self._holds_only_extension_arrays(target.value) ): self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) @@ -1984,11 +1999,24 @@ def _bound_only_to_extension_arrays(self, name: str) -> bool: timedelta and period data. """ - bindings = self._bindings(name) or [] + return self._names_extension_array(ast.Name(id=name, ctx=ast.Load()), set()) + + def _names_extension_array(self, expression: ast.expr, following: set[str]) -> bool: + """Whether ``expression`` is ``x.array``, a slice of it, or a local + name bound only to one of these.""" + + while isinstance(expression, ast.Subscript): + expression = expression.value + if _is_extension_array_expression(expression): + return True + if not isinstance(expression, ast.Name) or expression.id in following: + return False + following.add(expression.id) + bindings = self._bindings(expression.id) or [] return bool(bindings) and all( items_taken == 0 and value is not None - and _is_extension_array_expression(value) + and self._names_extension_array(value, following) for value, items_taken in bindings ) @@ -2174,6 +2202,34 @@ def _in_function(*body_lines: str, parameters: str = "series") -> str: #: Snippets the scan must refuse, with the one rule each must report. _REFUSED_SNIPPETS = { + # Round-seven cases. + "fills_beside_a_masked_assignment_elsewhere": ( + _NUMPY + + "def mask_incomplete(group_values, complete):\n" + + " group_values[~complete] = np.nan\n" + + "def scale(frame, names):\n" + + " group_values = []\n" + + " for name in names:\n" + + " group_values.append(np.asarray(frame[name].array))\n" + + " for values in group_values:\n" + + " values *= 2\n", + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "setitem_call_on_a_row_of_a_view": ( + _in_function( + "rows = np.atleast_2d(np.asarray(series.array))", + "rows[0].__setitem__(0, 1)", + ), + _WRITES_THROUGH_WRITABLE_VIEW, + ), + "out_item_of_a_copied_split": ( + _in_function( + "pieces = np.split(values, 2).copy()", + "np.add(pieces[0], 1, out=pieces[0])", + parameters="values", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), # Round-six cases. "slice_of_a_view_augmented": ( _in_function("head = np.asarray(series.array)[:3]", "head += 1"), @@ -3142,6 +3198,31 @@ def test_the_scanner_refuses_each_unprotected_write(source: str, rule: str) -> N #: Snippets the scan must accept: reads, read-only flags, and writes into #: arrays the same function created. _ACCEPTED_SNIPPETS = { + # Round-seven cases. + "column_slices_of_copied_and_computed_matrices": _in_function( + "result = matrix.copy()", + "np.clip(result[:, 0], 0, None, out=result[:, 0])", + "weighted = values * weights[:, None]", + "np.maximum(weighted[:, 0], 0, out=weighted[:, 0])", + parameters="matrix, values, weights", + ), + "slice_of_an_extension_array_through_a_name": _in_function( + 'values = frame["x"].array', + "tail = values[1:]", + "tail -= values[:-1]", + parameters="frame", + ), + "slice_of_a_list_of_views_extended": _in_function( + "arrays = [np.asarray(frame[name].array) for name in names]", + "arrays[1:] += [other]", + parameters="frame, names, other", + ), + "extension_arrays_inserted_scaled": _in_function( + "columns = []", + 'columns.insert(0, frame["a"].array)', + "columns[0] *= 2", + parameters="frame", + ), # Round-six cases. "string_methods_on_labels_from_views": _in_function( 'for code, label in zip(frame["c"].array, frame["l"].array):', @@ -3586,3 +3667,26 @@ def stop(_signal_number: int, _frame: object) -> None: signal.signal(signal.SIGALRM, previous) assert findings == [] + + +def test_a_module_that_fails_to_import_does_not_stop_the_scan( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def import_module(name: str) -> object: + if name.startswith("numpy.broken"): + raise RuntimeError("this module cannot be imported here") + return importlib.import_module(name) + + monkeypatch.setitem(globals(), "_import_module", import_module) + _library_object.cache_clear() + _positional_outputs.cache_clear() + try: + findings = scan_source( + _in_function("np.broken.helper(values, out=values)", parameters="values"), + "snippet.py", + ) + finally: + _library_object.cache_clear() + _positional_outputs.cache_clear() + + assert [finding.rule for finding in findings] == [_WRITES_INTO_EXISTING_ARRAY] From bb9f11592c13fd573cbb2e025b553aa8dcc03ebe Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:38:41 +0400 Subject: [PATCH 09/15] Replace the shared-buffer write analysis with a syntactic check Seven review rounds showed that following arrays through names, containers, comprehensions and loops has no natural end: each fix added new edge cases. The scan is now a check on how code is written. It looks at one expression at a time, and only for out= and ufunc.at follows a name to its own assignments in the same function. It refuses: - setflags(write=...) and flags.writeable / flags["W"] assignments; - item assignment into x.array, and x.array.__setitem__; - ._ndarray, ._mgr, and ._values, ._data, ._mask and ._codes on other objects; - np.copyto; - out= given by keyword to NumPy or an ndarray method, and ufunc.at's first argument, unless the array is created in the function. Its docstring lists what it does not see. Raw writes into extension-typed columns' .values and to_numpy() are among them, and need a run-time check. Frame: three docstring corrections (what the scan refuses, what the constructor does with a table without copy(), which errors with_columns raises). Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/frame/bundle.py | 12 +- .../shared/test_shared_buffer_writes.py | 3649 +++-------------- 2 files changed, 553 insertions(+), 3108 deletions(-) diff --git a/packages/microcosm-frame/src/microcosm/frame/bundle.py b/packages/microcosm-frame/src/microcosm/frame/bundle.py index 13a3da7af5..8c69121c2d 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -148,8 +148,8 @@ def _adopt( 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 these in the workspace's - source), and through what ``.values`` and ``to_numpy()`` return for + (``test_shared_buffer_writes.py`` refuses the direct forms of some of + these in the workspace's source), and through what ``.values`` and ``to_numpy()`` return for extension-typed columns. ``.values`` returns the column's own extension array, for example for the nullable integer, float and boolean types, ``category`` and python-backed strings, and under @@ -167,8 +167,8 @@ def _adopt( 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 stores whatever the table's ``copy()`` - returns and checks that). Weights are stored as given (their arrays are + 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. @@ -990,8 +990,8 @@ def with_columns(self, entity: str, /, **columns: Any) -> "Frame": Raises: TypeError, ValueError: As pandas raises them when it cannot - assign a value as a column (for example a set, a value of the - wrong length, or a two-dimensional array). + 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 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 aa153dd270..2b6461f17c 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,105 +1,62 @@ -"""No raw writes into memory that pandas copy-on-write does not protect. +"""A syntactic check for raw writes that pandas copy-on-write does not protect. :meth:`Frame.replace_tables` and :meth:`Frame.with_columns` build frames that share the memory of every unchanged column with their source frame (:meth:`Frame._adopt`). pandas copy-on-write keeps a write made through pandas (``.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, the writes below change the other frame's -data without an error, so this test reads the scanned source with :mod:`ast` -and refuses them. Each rule's name is what a failure reports. +with pandas 3.0.3 and NumPy 2.4.6, each form below writes into the shared +memory without an error, so this test reads the scanned source with +:mod:`ast` and refuses it. + +This is a check on how code is written, not an analysis of where arrays come +from. It looks at one expression at a time and, for the last rule only, +follows a name to its own assignments in the same function. Each rule's name +is what a failure reports. ``makes-array-writable`` - ``setflags(write=...)`` with anything but a false constant, or assigning - ``flags.writeable``, ``flags["W"]`` or ``flags["WRITEABLE"]``. The arrays - ``to_numpy()`` and ``.values`` return for NumPy-typed columns are - read-only views of the shared memory; this makes them writable. -``writes-through-writable-view`` - A write into a writable view of pandas' memory: ``.array`` (of a Series - or Index), ``.asi8`` (datetime data), or ``.base`` read from - ``.values`` or from the result of a library function or an array method - (such as ``to_numpy()``), which is the writable array behind a - read-only view. - - Writes are item assignment, ``__setitem__``, ``out=``, ``shuffle`` and - the in-place NumPy functions below, into the view or into an item of it - (a row of a two-dimensional view is a view too). ``fill``, ``sort`` - and the other in-place ndarray methods, ``fillna(copy=False)``, ``+=`` - and the other augmented assignments count only on a view itself (a - slice of it is one), because an item of a one-dimensional view is a - scalar; and ``+=`` not on a name, or an item of a container, bound only - to ``.array``, an extension array, for which ``+=`` builds a new array. - - The written expression reaches the view through: - - - indexing of any kind; - - the NumPy functions that can return a view (``np.asarray``, - ``np.flip``, ``np.split``, ... in ``_VIEW_NUMPY_FUNCTIONS`` and - ``_SPLITTING_NUMPY_FUNCTIONS``), ``to_numpy()``, - ``astype(copy=False)`` and the other view methods and attributes, - unless given ``copy=True``; - - a list, tuple, set or dict display or comprehension holding it (with - ``*``/``**`` unpacking), containers joined with ``+`` or ``|``, - ``list``, ``tuple``, ``sorted``, ``dict``, ``zip``, ``enumerate``, - ``next``, ``.items()``, ``.values()``, ``.copy()`` of a container, - and ``.get()``, ``.pop()`` and ``.setdefault()`` (with a default); - - ``or``, conditional expressions and assignment expressions (``:=``); - - a name the same function binds to any of these, by assignment, - unpacking, a ``with`` statement, or a ``for`` loop or comprehension - (which pair ``zip``, ``enumerate`` and ``.items()`` targets with - their own sources, also when nested or wrapped in ``list`` or - ``sorted``), or fills with one: ``append``, ``extend``, ``insert``, - ``add``, ``setdefault``, ``update`` (with a mapping, pairs or - keywords), ``+=``, and ``name[key] = ...`` except into a NumPy array - the function created, because assigning into an array copies. - - Workspace classes' own ``self.array`` is exempt. + ``x.setflags(write=...)`` with anything but a false constant (a + positional first argument counts too), and assigning anything but a + false constant to ``x.flags.writeable``, ``x.flags["W"]`` or + ``x.flags["WRITEABLE"]``. The arrays ``to_numpy()`` and ``.values`` + return for NumPy-typed columns are read-only views of the shared memory; + this makes them writable. +``writes-through-series-array`` + Item assignment, plain or augmented (``x.array[i] = v``, + ``x.array[mask] += v``), into ``x.array``, and ``x.array.__setitem__(...)``, + where ``x`` is not ``self`` or ``cls``. ``Series.array`` is the column's + own array. ``pandas-private-attribute`` - ``._ndarray``, ``._mgr``, ``._get_column_array`` or - ``._iter_column_arrays`` on anything, and ``._values``, ``._data``, - ``._mask`` or ``._codes`` on anything but ``self`` or ``cls``. These - reach pandas' internal arrays, which are writable whenever the data - they hold is. + Any use of ``._ndarray`` or ``._mgr``, and of ``._values``, ``._data``, + ``._mask`` or ``._codes`` on anything but ``self`` or ``cls`` (workspace + classes use those names for their own state). These reach pandas' + internal arrays. ``numpy-copyto`` - Any use of ``numpy.copyto``. + Any use of ``copyto`` as an attribute (``np.copyto``) or imported from + NumPy. ``writes-into-existing-array`` - A write into an array the same function did not create: ``out=`` - given to a NumPy or SciPy function or ufunc, an ndarray method or a - NumPy random ``Generator`` method (by keyword, or by position for NumPy - and SciPy functions and ufuncs), the first argument of - ``numpy..at`` (which writes even into a read-only array), and the - first argument of ``numpy.put``, ``numpy.putmask``, ``numpy.place``, - ``numpy.put_along_axis``, ``numpy.fill_diagonal``, - ``numpy.random.shuffle``, any ``.shuffle`` method and - ``numpy.nan_to_num(copy=False)``. Library functions are also followed - through a local name bound to them (``plus = np.add``). - - Created means one of: - - - the result of a ufunc or ufunc reduction, a ``numpy.random`` - function, a random ``Generator`` draw (``rng.normal``, ...), - ``.flatten()``, or a NumPy function that always allocates - (``_ALLOCATING_NUMPY_FUNCTIONS``: ``np.zeros``, ``np.where``, - ``np.concatenate``, ...), when not given an output array; - - ``np.array`` without ``copy=``, ``to_numpy(copy=True)``, or a - ``.copy()`` of ``.values`` or of a library or array-method call; - - the output array of a call given one that is created; - - a view, piece (``np.split``), subscript or item (a loop target, - also in a comprehension, or unpacking) of one of these. ``np.clip``, - ``np.round`` and ``np.take`` count only as views here: given a - pandas object they can return its memory; - - arithmetic, a comparison or a literal; - - a ``.copy()``, ``list(...)`` and the other container builtins, ``+``, - ``*`` or ``|`` (which also join containers), or a list, set or dict - display. A slice of these is new; an item is not, because a shallow - copy or a container shares its items; - - a local name whose every binding in the function, other than to - ``None``, is one of these. + ``out=`` given by keyword to a NumPy function or ufunc (named through + ``import numpy as np`` or ``from numpy import ...``) or to an ndarray + method that takes it (``_METHODS_WITH_OUT``), and the first argument of + ``np..at``, which writes even into a read-only array, unless that + array is created in the function. Created means: + + - a call of a NumPy function that allocates + (``_ALLOCATING_NUMPY_FUNCTIONS``: ``np.zeros``, ``np.empty_like``, + ``np.where``, ...), of a ufunc, or of ``np.array`` without ``copy=``, + not itself given ``out=``; + - ``.copy()`` with no arguments; + - a subscript of one of these; + - a local name, or a subscript of one, whose every assignment in the + function is one of these or ``None``, with at least one that is not + ``None``. A parameter, a name declared ``global`` or ``nonlocal``, and + a name bound any other way in the function (a loop, comprehension or + ``with`` target, unpacking, an import) are not created. ``setflags``, ``Series.array[i] = value``, ``._ndarray``, ``._mgr``, ``np.copyto`` and ``out=`` are the writes first identified as unprotected. -The other rules, views, functions and methods were added after checking that -they write into shared memory too. +``ufunc.at`` and the other private attributes were added after probes showed +that they write into shared memory too. Scope: every Python file under ``packages/*/src/`` (the source of every workspace package, including microcosm-frame and the microcosm-build code that @@ -107,48 +64,27 @@ except files in ``node_modules`` or hidden directories. Tests and ``test_support/`` are not scanned. -The scan follows arrays only through the forms listed above. In particular, -it does not refuse: - -- Writes it cannot see from the source: - - into what ``.values`` and ``to_numpy()`` return for extension-typed - columns: ``.values`` returns the column's own extension array (for - example for the nullable integer, float and boolean types, - ``category`` and python-backed strings, and under pandas 2.x for - pyarrow-backed types), and ``to_numpy()`` a writable view of the - column's data (for example for the nullable types without missing - values, python-backed strings, and sparse columns without gaps); - - through a pandas object built with ``copy=False`` over another object's - array; - - into ``np.asarray(index)``, which is writable although the index is - shared even between deep copies; - - ``+=`` on a datetime, timedelta or period column's ``.array``, which - writes in place. -- Arrays reached in other ways: - - through other functions' return values or arguments, closures and - object arrays; - - names reached dynamically (``getattr(np, name)``, ``**{"out": array}``, - ``*arguments``), library functions bound by unpacking or through a - second alias, and positional ``out`` given to any method; - - containers filled inside a comprehension, comprehension loop targets - captured with ``:=``, and subscripts or attributes used as ``for`` or - ``with`` targets; - - ``.base`` read through a name (``values = s.to_numpy(); values.base``); - - items of a container the function did not build; - - array libraries other than NumPy and SciPy (``torch.from_numpy`` of a - read-only view returns a writable tensor). -- Differences of order or kind within a function: - - Neither rule is flow-sensitive: a name counts as created only if every - binding in its function does, and as a view if any binding is one. So - a parameter rebound to a new array, and a name rebound from a view to a - new array, count as before. - - A boolean or integer array index gives a copy, but counts as indexing. - - ``name[key] = view`` into a parameter, a ``.copy()`` of one, or another - array the function did not create counts as filling a container, - though for an array it copies; and a list from ``np.split`` of a - created array counts as an array, so it is not followed as a container. - - ``.astype()`` counts as not created, because a pandas object's - same-type conversion shares its memory. +What this check does not see, so does not refuse: + +- arrays reached in any other way: through another name + (``values = x.array; values[0] = 1``), ``np.asarray(x.array)``, + ``x.array.to_numpy()``, ``.base`` or ``.asi8``, containers, closures, and + other functions' arguments and return values; +- positional ``out`` arguments, SciPy ufuncs, and the other functions and + methods that write in place (``np.put``, ``np.putmask``, + ``np.fill_diagonal``, ``np.random.shuffle``, ``arr.sort()``, ``arr.fill()``); +- what ``.values`` and ``to_numpy()`` return for extension-typed columns: + ``.values`` returns the column's own extension array (for example for the + nullable integer, float and boolean types, ``category`` and python-backed + strings), and ``to_numpy()`` a writable view of the column's data (for + example for the nullable types without missing values, python-backed + strings, and sparse columns without gaps); +- pandas objects built with ``copy=False`` over another object's array, and + ``np.asarray(index)``, which is writable although the index is shared even + between deep copies. + +Catching these needs a check at run time, such as hashing each shared column +when a frame is built and again before its outputs are written. A finding that cannot write into memory a pandas object shares goes in ``_REVIEWED_FINDINGS`` with the reason. @@ -158,14 +94,10 @@ import ast import bisect -import functools import hashlib -import importlib -import inspect import re -import signal from collections import defaultdict -from collections.abc import Callable, Iterable, Iterator +from collections.abc import Iterable, Iterator from dataclasses import dataclass from pathlib import Path @@ -184,17 +116,6 @@ #: enclosing function changes the digest and needs a new review; a reason #: that rests on other functions names them, and changing them needs one too. _REVIEWED_FINDINGS: dict[tuple[str, str, str, str, str], str] = { - ( - "packages/microcosm-build/src/microcosm/build/uk_runtime/frs_relationships.py", - "derive_frs_relationships", - "writes-into-existing-array", - "np.fill_diagonal(matrix, 0)", - "f439ecc6ea13", - ): ( - "np.fill_diagonal writes into matrix = grid[rows][:, columns]; indexing " - "with integer arrays returns a new array, and grid is to_numpy() of a " - "DataFrame this function computes from the raw FRS columns." - ), ( "tools/verify_uk_identity_stability.py", "_pre_split_household_weights", @@ -210,34 +131,23 @@ } _MAKES_ARRAY_WRITABLE = "makes-array-writable" -_WRITES_THROUGH_WRITABLE_VIEW = "writes-through-writable-view" +_WRITES_THROUGH_SERIES_ARRAY = "writes-through-series-array" _PANDAS_PRIVATE_ATTRIBUTE = "pandas-private-attribute" _NUMPY_COPYTO = "numpy-copyto" _WRITES_INTO_EXISTING_ARRAY = "writes-into-existing-array" #: Private attributes refused on any object. -_ALWAYS_PRIVATE_ATTRIBUTES = frozenset( - {"_ndarray", "_mgr", "_get_column_array", "_iter_column_arrays"} -) -#: Private attributes refused unless read from ``self`` or ``cls``, because -#: workspace classes use the same names for their own state. +_ALWAYS_PRIVATE_ATTRIBUTES = frozenset({"_ndarray", "_mgr"}) +#: Private attributes refused unless read from ``self`` or ``cls``. _FOREIGN_PRIVATE_ATTRIBUTES = frozenset({"_values", "_data", "_mask", "_codes"}) _OWN_OBJECT_NAMES = frozenset({"self", "cls"}) -#: Attributes that return a writable view of pandas' memory. -#: ``.base`` counts too, when read from an array expression. -_WRITABLE_VIEW_ATTRIBUTES = frozenset({"array", "asi8"}) - -#: Libraries whose functions the scan resolves through imports. -_LIBRARIES = ("numpy", "scipy") - #: NumPy functions whose result is new memory (unless given ``out=``), #: checked for ndarrays and for integer, float and boolean Series. -#: ``np.clip``, ``np.tile``, ``np.round`` and ``np.take`` are treated as -#: views instead: given a pandas object, their result can share its memory. +#: ``np.clip``, ``np.tile``, ``np.round`` and ``np.take`` are left out: +#: given a pandas object, their result can share its memory. _ALLOCATING_NUMPY_FUNCTIONS = frozenset( - f"numpy.{name}" - for name in ( + { "where", "select", "sort", @@ -271,84 +181,10 @@ "vstack", "column_stack", "repeat", - ) -) - -#: ufunc methods whose result is a new array (unless given ``out=``). -_ALLOCATING_UFUNC_METHODS = frozenset({"reduce", "accumulate", "reduceat", "outer"}) - -#: NumPy random Generator methods that draw a new array. -_RANDOM_DRAW_METHODS = frozenset( - { - "random", - "normal", - "uniform", - "integers", - "choice", - "permutation", - "standard_normal", - "standard_exponential", - "standard_gamma", - "exponential", - "gamma", - "beta", - "binomial", - "poisson", - "lognormal", - "multinomial", - "multivariate_normal", - "dirichlet", - "laplace", - "logistic", - "triangular", - "geometric", } ) -#: Builtins whose result is a new container (whose items may be shared). -_CONTAINER_BUILTINS = frozenset( - {"list", "dict", "set", "frozenset", "tuple", "sorted", "bytearray"} -) -#: Builtins and methods whose result holds the items of their arguments or -#: receiver, for following views through iteration. -_SAME_ITEMS_BUILTINS = frozenset( - {"reversed", "iter", "list", "tuple", "sorted", "set", "frozenset"} -) -_TUPLE_YIELDING_BUILTINS = frozenset({"zip", "enumerate"}) -#: Builtins whose result has exactly the items of their one argument. -_ITEM_KEEPING_WRAPPERS = frozenset({"list", "tuple", "sorted", "reversed", "iter"}) -_SAME_ITEMS_METHODS = frozenset({"values", "popitem"}) -_TUPLE_YIELDING_METHODS = frozenset({"items"}) -#: Methods that return one item of the container they are called on. -_ITEM_TAKING_METHODS = frozenset({"get", "pop", "setdefault"}) -#: Methods that put one item, or the items of an iterable, into the -#: container they are called on. -_ITEM_ADDING_METHODS = frozenset( - {"append", "appendleft", "insert", "add", "setdefault"} -) - -#: Arithmetic and comparisons give a new array; ``+`` and ``*`` also join or -#: repeat lists, whose items are shared, so they give a new container. -_NEW_ARRAY_EXPRESSIONS = (ast.UnaryOp, ast.Compare) -_JOINING_OPERATORS = (ast.Add, ast.Mult, ast.BitOr) -#: Operators that join containers holding views (``*`` repeats a list, but -#: with an array it is arithmetic, so it is left out). -_VIEW_JOINING_OPERATORS = (ast.Add, ast.BitOr) -#: Displays and comprehensions: a new container whose items may be shared. -_CONTAINER_EXPRESSIONS = ( - ast.List, - ast.ListComp, - ast.Tuple, - ast.Set, - ast.SetComp, - ast.Dict, - ast.DictComp, - ast.GeneratorExp, -) -_COMPREHENSIONS = (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp) - -#: ndarray methods and NumPy random Generator methods that take an ``out`` -#: array. +#: ndarray methods, and NumPy random Generator methods, that take ``out``. _METHODS_WITH_OUT = frozenset( { "all", @@ -379,184 +215,15 @@ } ) -#: NumPy functions that write into their first argument. -_IN_PLACE_NUMPY_FUNCTIONS = frozenset( - { - "numpy.put", - "numpy.putmask", - "numpy.place", - "numpy.put_along_axis", - "numpy.fill_diagonal", - "numpy.random.shuffle", - "numpy.random.mtrand.shuffle", - } -) - -#: ndarray methods that write into the array they are called on. -_IN_PLACE_ARRAY_METHODS = frozenset( - { - "__setitem__", - "fill", - "sort", - "put", - "partition", - "resize", - "setfield", - } -) - -#: NumPy functions that can return a view of an argument (or views, as -#: ``np.split`` does). -_VIEW_NUMPY_FUNCTIONS = frozenset( - f"numpy.{name}" - for name in ( - "asarray", - "asanyarray", - "ascontiguousarray", - "asfortranarray", - "asarray_chkfinite", - "require", - "ravel", - "reshape", - "squeeze", - "transpose", - "permute_dims", - "matrix_transpose", - "atleast_1d", - "atleast_2d", - "atleast_3d", - "frombuffer", - "from_dlpack", - "flip", - "fliplr", - "flipud", - "rot90", - "moveaxis", - "swapaxes", - "rollaxis", - "expand_dims", - "real", - "imag", - "trim_zeros", - "tile", - "real_if_close", - "asmatrix", - "lib.stride_tricks.as_strided", - ) -) - -#: NumPy functions that return new memory for an ndarray or an extension -#: array, but, given a Series or DataFrame, call its method, whose result can -#: share the object's memory. They are not views of ndarrays or extension -#: arrays, and count as created only as views of a created array. -_PANDAS_SHARING_NUMPY_FUNCTIONS = frozenset( - f"numpy.{name}" for name in ("clip", "round", "around", "take") -) - -#: NumPy functions that return a list or tuple of views of an argument. -_SPLITTING_NUMPY_FUNCTIONS = frozenset( - f"numpy.{name}" - for name in ( - "split", - "array_split", - "hsplit", - "vsplit", - "dsplit", - "unstack", - "broadcast_arrays", - ) -) - -#: Methods and attributes that can return a view of the object they are read -#: from. -_VIEW_METHODS = frozenset( - { - "to_numpy", - "view", - "reshape", - "ravel", - "squeeze", - "transpose", - "swapaxes", - "__array__", - } +#: Text every refused expression contains. A module without any of it is not +#: parsed, and a statement whose lines hold none of it is not visited. +_TRIGGER_TEXT = re.compile( + r"setflags|writeable|WRITEABLE|\bflags\b|copyto|\.\s*array\b|\bout\s*=" + r"|\.\s*at\s*\(|\.\s*_(?:ndarray|mgr|values|data|mask|codes)\b" ) -_VIEW_ATTRIBUTES = frozenset({"T", "mT", "real", "imag", "flat"}) _NESTED_SCOPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda) -#: How new the value of an expression is (higher is newer). -_NOT_NEW = 0 -#: A new object whose items may be shared: a container, or a ``.copy()`` -#: that may be a shallow copy of a container. -_NEW_OBJECT = 1 -#: A new array: every item and view of it is new memory. -_NEW_ARRAY = 2 - -#: Whether, and how deep in containers, a value holds a writable view of -#: pandas' memory. ``_IS_VIEW`` is a view. ``_ELEMENT`` is an item of a view: -#: a row (itself a view) of a two-dimensional view, but a scalar of a -#: one-dimensional one. Each container level adds 2, so 2 is a container of -#: views and 3 a container of elements. ``_NO_VIEW`` is none, or deeper than -#: tracked. -_IS_VIEW = 0 -_ELEMENT = 1 -_NO_VIEW = 11 - - -def _item_of(level: int) -> int: - """An item of a view is an element; an item of a container, one level less.""" - - if level >= _NO_VIEW: - return _NO_VIEW - if level <= _ELEMENT: - return _ELEMENT - return level - 2 - - -def _items_taken(level: int, count: int) -> int: - for _step in range(count): - level = _item_of(level) - return level - - -def _holder_of(level: int) -> int: - """A container holding a value holds its view one level deeper.""" - - return _NO_VIEW if level >= _NO_VIEW else min(level + 2, _NO_VIEW) - - -def _items_holder_of(level: int) -> int: - """A new container of a value's items (``list(value)``, ``extend``).""" - - return _holder_of(_item_of(level)) - - -def _view_of(level: int) -> int: - """A NumPy view of a view or element stays one; of a container it is a copy.""" - - return level if level <= _ELEMENT else _NO_VIEW - - -def _bound_level(items_taken: int, level: int) -> int: - """The level of a name bound ``items_taken`` items deep into a value.""" - - return _items_taken(level, items_taken) - - -def _held_level(items_taken: int, kind: str, level: int) -> int: - """The level of a container filled with a value (see ``_HeldValue``).""" - - level = _items_taken(level, items_taken) - if kind in (_ONE_ITEM, _BY_KEY): - return _holder_of(level) - if kind == _ITEMS: - return _items_holder_of(level) - # A mapping's values, or the second items of pairs. - if level <= _ELEMENT: - return _NO_VIEW - return min(_items_holder_of(level), _holder_of(_items_taken(level, 2))) - @dataclass(frozen=True) class Finding: @@ -578,410 +245,56 @@ def describe(self) -> str: return f"{self.path}:{self.line} in {self.function}: {self.rule}: {code}" -# Bindings ------------------------------------------------------------------ - -#: One binding of a name: the value expression (``None`` when it cannot be -#: followed, as for an import), and how many items deep into that value the -#: name is bound: 0 for the value itself, 1 for a loop target (an item of -#: its iterable), 2 for a name unpacked from a loop target, and so on. -_Binding = tuple[ast.expr | None, int] -#: What a container is filled with: the value, how many items deep into it, -#: and how it goes in (one of the kinds below). -_HeldValue = tuple[ast.expr, int, str] -#: ``append``, ``add``, ``insert``, ``setdefault`` and keyword ``update``. -_ONE_ITEM = "one item" -#: ``name[key] = value``; ignored for a NumPy array the function created, -#: because assigning into an array copies the values. -_BY_KEY = "by key" -#: ``extend`` and ``+=``: the value's items. -_ITEMS = "items" -#: Positional ``update``: a mapping's values or the second items of pairs. -_ENTRIES = "entries" - - -def _target_names( - target: ast.expr, value: ast.expr | None, items_taken: int -) -> Iterator[tuple[ast.expr, ast.expr | None, int]]: - """The names and subscripts an assignment target binds, with their values. - - Each is yielded with the value it takes items from and how many items - deep it is bound. - """ - - if isinstance(target, (ast.Name, ast.Subscript)): - yield target, value, items_taken - elif isinstance(target, ast.Starred): - # A starred target collects items into a new list: the same depth. - yield from _target_names(target.value, value, items_taken) - elif isinstance(target, (ast.Tuple, ast.List)): - pairs = ( - items_taken == 0 - and isinstance(value, (ast.Tuple, ast.List)) - and len(value.elts) == len(target.elts) - and not any( - isinstance(element, ast.Starred) - for element in (*target.elts, *value.elts) - ) - ) - for index, element in enumerate(target.elts): - if pairs: - yield from _target_names(element, value.elts[index], 0) - elif isinstance(element, ast.Starred): - yield from _target_names(element.value, value, items_taken) - else: - yield from _target_names(element, value, items_taken + 1) - - -def _loop_target_names( - target: ast.expr, iterable: ast.expr -) -> Iterator[tuple[ast.expr, ast.expr | None, int]]: - """What a ``for`` target binds, pairing each name with its own source. - - ``for a, b in zip(x, y)`` binds ``a`` to an item of ``x`` and ``b`` to - an item of ``y``; ``enumerate`` and ``.items()`` pair the second name - with the iterable's items. Pairs nest (``enumerate(zip(...))``), and - ``list``, ``sorted`` and the other wrappers that keep the items change - nothing. - """ - - while ( - isinstance(iterable, ast.Call) - and isinstance(iterable.func, ast.Name) - and iterable.func.id in _ITEM_KEEPING_WRAPPERS - and len(iterable.args) == 1 - and not isinstance(iterable.args[0], ast.Starred) - ): - iterable = iterable.args[0] - if ( - isinstance(target, (ast.Tuple, ast.List)) - and not any(isinstance(element, ast.Starred) for element in target.elts) - and isinstance(iterable, ast.Call) - and not any(isinstance(argument, ast.Starred) for argument in iterable.args) - ): - function = iterable.func - elements = target.elts - arguments = iterable.args - if ( - isinstance(function, ast.Name) - and function.id == "zip" - and len(arguments) == len(elements) - ): - for element, argument in zip(elements, arguments, strict=True): - yield from _loop_target_names(element, argument) - return - if ( - isinstance(function, ast.Name) - and function.id == "enumerate" - and len(elements) == 2 - and arguments - ): - yield from _target_names(elements[0], None, 1) - yield from _loop_target_names(elements[1], arguments[0]) - return - if ( - isinstance(function, ast.Attribute) - and function.attr == "items" - and len(elements) == 2 - ): - yield from _target_names(elements[0], None, 1) - yield from _loop_target_names(elements[1], function.value) - return - yield from _target_names(target, iterable, 1) - - -class _Scope: - """One function, class or module, and the names it binds. - - The bindings are collected on first use, because most scopes are never - asked. ``held_values`` are what a name's container is filled with - (``name.append(value)``, ``name[key] = value``, ``name += value``). - """ - - def __init__(self, qualified_name: str, node: ast.AST) -> None: - self.qualified_name = qualified_name - self.node = node - self._parameters: frozenset[str] = frozenset() - self._declared_elsewhere: set[str] = set() - self._bindings: defaultdict[str, list[_Binding]] | None = None - self._held: defaultdict[str, list[_HeldValue]] = defaultdict(list) - # Filled by the scanner on first use, held here so that they live - # exactly as long as the scope. - self.newness_table: dict[str, int] | None = None - self.view_table: dict[str, int] | None = None - - def child_name(self, name: str) -> str: - if self.qualified_name == "": - return name - return f"{self.qualified_name}.{name}" - - def is_local(self, name: str) -> bool: - self._collect() - return ( - name not in self._parameters - and name not in self._declared_elsewhere - and bool(self._bindings.get(name)) - ) - - def bindings_of(self, name: str) -> list[_Binding] | None: - """The bindings of ``name`` here, or ``None`` when it is not local. - - A parameter, a name declared ``global`` or ``nonlocal``, and a name - this scope never binds are not local. - """ - - return self._bindings[name] if self.is_local(name) else None - - def is_parameter(self, name: str) -> bool: - self._collect() - return name in self._parameters - - def local_bindings(self) -> dict[str, list[_Binding]]: - self._collect() - return { - name: bindings - for name, bindings in self._bindings.items() - if self.is_local(name) - } - - def held_names(self) -> list[str]: - self._collect() - return list(self._held) - - def held_values(self, name: str) -> list[_HeldValue]: - self._collect() - return self._held.get(name, []) - - def _record(self, bound: Iterable[tuple[ast.expr, ast.expr | None, int]]) -> None: - for target, value, items_taken in bound: - if isinstance(target, ast.Name): - self._bindings[target.id].append((value, items_taken)) - elif isinstance(target.value, ast.Name) and value is not None: - # ``name[key] = value`` puts one item into ``name``. - self._held[target.value.id].append((value, items_taken, _BY_KEY)) - - def _collect(self) -> None: - if self._bindings is not None: - return - self._bindings = defaultdict(list) - node = self.node - if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)): - arguments = node.args - self._parameters = frozenset( - argument.arg - for argument in ( - *arguments.posonlyargs, - *arguments.args, - *arguments.kwonlyargs, - arguments.vararg, - arguments.kwarg, - ) - if argument is not None - ) - body = [node.body] if isinstance(node, ast.Lambda) else node.body - for child in _nodes_in_scope(body): - if isinstance(child, ast.Assign): - for target in child.targets: - self._record(_target_names(target, child.value, 0)) - elif isinstance(child, (ast.AnnAssign, ast.NamedExpr)): - if child.value is not None: - self._record(_target_names(child.target, child.value, 0)) - elif isinstance(child, ast.AugAssign): - # ``name += values`` adds the items of ``values`` to a list; - # ``name[key] += value`` changes an item and adds none. - if isinstance(child.target, ast.Name): - self._held[child.target.id].append((child.value, 0, _ITEMS)) - elif isinstance(child, (ast.For, ast.AsyncFor)): - self._record(_loop_target_names(child.target, child.iter)) - elif isinstance(child, ast.withitem) and child.optional_vars is not None: - self._record(_target_names(child.optional_vars, child.context_expr, 1)) - elif isinstance(child, ast.ExceptHandler) and child.name: - self._bindings[child.name].append((None, 1)) - elif isinstance(child, (ast.Import, ast.ImportFrom)): - for alias in child.names: - bound = alias.asname or alias.name.split(".", 1)[0] - self._bindings[bound].append((None, 1)) - elif isinstance(child, _NESTED_SCOPES) and not isinstance( - child, ast.Lambda - ): - self._bindings[child.name].append((None, 1)) - elif isinstance(child, (ast.Global, ast.Nonlocal)): - self._declared_elsewhere.update(child.names) - elif isinstance(child, (ast.MatchAs, ast.MatchStar)) and child.name: - self._bindings[child.name].append((None, 1)) - elif isinstance(child, ast.MatchMapping) and child.rest: - self._bindings[child.rest].append((None, 1)) - elif ( - isinstance(child, ast.Call) - and isinstance(child.func, ast.Attribute) - and isinstance(child.func.value, ast.Name) - ): - method = child.func.attr - held = self._held[child.func.value.id] - # ``insert(index, value)`` and ``setdefault(key, value)`` put - # in only their second argument. - values = ( - child.args[1:] if method in ("insert", "setdefault") else child.args - ) - if method in _ITEM_ADDING_METHODS: - held.extend((value, 0, _ONE_ITEM) for value in values) - elif method == "extend": - held.extend((value, 0, _ITEMS) for value in values) - elif method == "update": - held.extend((value, 0, _ENTRIES) for value in values) - for keyword in child.keywords: - # ``**mapping`` puts in the mapping's values. - kind = _ENTRIES if keyword.arg is None else _ONE_ITEM - held.append((keyword.value, 0, kind)) - - -class _ComprehensionScope: - """A comprehension: its loop targets shadow the enclosing scope's names. - - ``upto`` limits it to its first generators, the ones whose targets a - later generator's iterable can see. - """ - - def __init__( - self, - enclosing: _Scope | _ComprehensionScope, - node: ast.AST, - upto: int | None = None, - ) -> None: - self.enclosing = enclosing - self.qualified_name = enclosing.qualified_name - self.node = enclosing.node - self.comprehension = node - self.upto = upto - self._targets: defaultdict[str, list[tuple[ast.expr | None, int, int]]] = ( - defaultdict(list) - ) - generators = node.generators if upto is None else node.generators[:upto] - for index, generator in enumerate(generators): - for target, value, items_taken in _loop_target_names( - generator.target, generator.iter - ): - if isinstance(target, ast.Name): - self._targets[target.id].append((value, items_taken, index)) - - def before(self, index: int) -> _ComprehensionScope: - """This comprehension as seen from its generator ``index``.""" - - return _ComprehensionScope(self.enclosing, self.comprehension, upto=index) - - def child_name(self, name: str) -> str: - return self.enclosing.child_name(name) - - def target_sources( - self, name: str - ) -> list[tuple[ast.expr | None, int, int]] | None: - """What ``name`` takes items from, if it is a loop target here: each - source with its item count and the index of its generator.""" - - return self._targets.get(name) - - def bindings_of(self, name: str) -> list[_Binding] | None: - if name in self._targets: - return [(value, items) for value, items, _index in self._targets[name]] - return self.enclosing.bindings_of(name) - - def is_parameter(self, name: str) -> bool: - return name in self._targets or self.enclosing.is_parameter(name) - +def _is_false_constant(expression: ast.expr) -> bool: + return isinstance(expression, ast.Constant) and not expression.value -def _nodes_in_scope(roots: Iterable[ast.AST]) -> Iterator[ast.AST]: - """Yield the nodes of one scope, without entering nested scopes. - A nested function, class or lambda is yielded (its name is bound here) - but not entered. Comprehensions are entered except for their loop - targets, which bind in the comprehension's own scope. - """ +def _is_none(expression: ast.expr | None) -> bool: + return isinstance(expression, ast.Constant) and expression.value is None - stack = list(reversed(list(roots))) - while stack: - node = stack.pop() - yield node - if isinstance(node, _NESTED_SCOPES): - continue - children = list(ast.iter_child_nodes(node)) - if isinstance(node, ast.comprehension): - children = [child for child in children if child is not node.target] - stack.extend(reversed(children)) +def _keyword(call: ast.Call, name: str) -> ast.keyword | None: + return next((keyword for keyword in call.keywords if keyword.arg == name), None) -def _statements(tree: ast.Module) -> Iterator[ast.AST]: - """Yield every statement at any depth, without entering expressions.""" - stack: list[ast.AST] = list(reversed(tree.body)) - while stack: - node = stack.pop() - yield node - for field_name in ("body", "orelse", "finalbody", "handlers", "cases"): - children = getattr(node, field_name, None) - if isinstance(children, list): - stack.extend(reversed(children)) +def _is_own_object(expression: ast.expr) -> bool: + return isinstance(expression, ast.Name) and expression.id in _OWN_OBJECT_NAMES -def _is_library_module(module: str) -> bool: - return any( - module == library or module.startswith(f"{library}.") for library in _LIBRARIES +def _is_series_array(expression: ast.expr) -> bool: + return ( + isinstance(expression, ast.Attribute) + and expression.attr == "array" + and not _is_own_object(expression.value) ) -class _LibraryNames: - """The names one module binds to NumPy and SciPy, to resolve ``np.add.at``. - - ``derived_names`` are names some statement assigns a library object to - (``plus = np.add``); the scanner follows them through the bindings of - the scope that uses them. - """ +class _NumpyNames: + """The names one module binds to NumPy (``np``, ``from numpy import add``).""" def __init__(self, tree: ast.Module) -> None: self._aliases: dict[str, str] = {} - statements = list(_statements(tree)) - for node in statements: + for node in ast.walk(tree): if isinstance(node, ast.Import): for alias in node.names: - if not _is_library_module(alias.name): - continue - if alias.asname: - self._aliases[alias.asname] = alias.name - else: - root = alias.name.split(".", 1)[0] - self._aliases[root] = root + if alias.name == "numpy" or alias.name.startswith("numpy."): + if alias.asname: + self._aliases[alias.asname] = alias.name + else: + self._aliases["numpy"] = "numpy" elif ( isinstance(node, ast.ImportFrom) and node.level == 0 and node.module is not None - and _is_library_module(node.module) + and (node.module == "numpy" or node.module.startswith("numpy.")) ): for alias in node.names: self._aliases[alias.asname or alias.name] = ( f"{node.module}.{alias.name}" ) - derived: set[str] = set() - for node in statements: - if isinstance(node, (ast.Assign, ast.AnnAssign)) and node.value is not None: - if self.resolve(node.value) is None: - continue - targets = ( - node.targets if isinstance(node, ast.Assign) else [node.target] - ) - for target in targets: - derived.update( - bound.id - for bound, _value, _items in _target_names( - target, node.value, 0 - ) - if isinstance(bound, ast.Name) - ) - self.derived_names = frozenset(derived) - - @property - def bound_names(self) -> frozenset[str]: - return frozenset(self._aliases) def resolve(self, expression: ast.expr) -> str | None: - """The dotted library name of ``expression`` (``numpy.add.at``), if any.""" + """The dotted NumPy name of ``expression`` (``numpy.add.at``), if any.""" attributes: list[str] = [] while isinstance(expression, ast.Attribute): @@ -995,923 +308,253 @@ def resolve(self, expression: ast.expr) -> str | None: return ".".join([root, *reversed(attributes)]) -# Which statements can hold a finding --------------------------------------- +def _numpy_object(dotted_name: str) -> object | None: + found: object = np + for part in dotted_name.split(".")[1:]: + found = getattr(found, part, None) + if found is None: + return None + return found -#: A dot before an attribute, allowing spaces and backslash continuations. -_DOT = r"\.(?:\s|\\)*" -#: Text found in every refused expression, except library names, names bound -#: to library objects, and writes through a name bound to a writable view. -_TRIGGER_TEXT = ( - r"setflags|writeable|WRITEABLE|\bflags\b|copyto|shuffle|\bout\s*=" - rf"|{_DOT}_(?:ndarray|mgr|values|data|mask|codes|get_column_array" - r"|iter_column_arrays)\b" -) -_WRITABLE_VIEW_TEXT = re.compile(rf"{_DOT}(?:array|base|asi8)\b") -#: A module without any of this text cannot hold a finding and is not parsed. -_FILE_TRIGGERS = re.compile( - rf"{_TRIGGER_TEXT}|numpy|scipy|{_WRITABLE_VIEW_TEXT.pattern}" -) + +def _nodes_in_scope(roots: Iterable[ast.AST]) -> Iterator[ast.AST]: + """The nodes of one function or module, without entering nested ones.""" + + stack = list(reversed(list(roots))) + while stack: + node = stack.pop() + yield node + if not isinstance(node, _NESTED_SCOPES): + stack.extend(reversed(list(ast.iter_child_nodes(node)))) -class _TriggerLines: - """The lines of one module that hold text a refused expression contains. +class _Scope: + """One function, class or module and its assignments, collected on first use. - A statement whose lines hold none of it cannot hold a finding, so the - scan skips it. This needs line numbers counted as the parser counts - them, so a module with a lone carriage return gets no ``_TriggerLines``. + ``assignments`` maps a name to the value of each plain assignment to it, + with ``None`` for a binding of any other kind. """ - def __init__(self, source: str, names: Iterable[str]) -> None: - alternatives = [_TRIGGER_TEXT] - alternatives.extend(rf"\b{re.escape(name)}\b" for name in sorted(names)) - pattern = re.compile("|".join(alternatives)) - newlines = [match.start() for match in re.finditer("\n", source)] - self._lines = sorted( - { - bisect.bisect_left(newlines, match.start()) + 1 - for match in pattern.finditer(source) - } - ) + def __init__(self, qualified_name: str, node: ast.AST) -> None: + self.qualified_name = qualified_name + self.node = node + self._assignments: defaultdict[str, list[ast.expr | None]] | None = None + self._not_local: set[str] = set() - def may_hold_finding(self, statement: ast.stmt) -> bool: - decorators = getattr(statement, "decorator_list", ()) - first = min([statement.lineno, *(item.lineno for item in decorators)]) - index = bisect.bisect_left(self._lines, first) - last = statement.end_lineno or statement.lineno - return index < len(self._lines) and self._lines[index] <= last + def assignments_of(self, name: str) -> list[ast.expr | None] | None: + """The assignments of a local ``name``, or ``None`` if it is not local.""" + if self._assignments is None: + self._collect() + if name in self._not_local: + return None + return self._assignments.get(name) or None -# Library lookups ----------------------------------------------------------- + def _collect(self) -> None: + assignments: defaultdict[str, list[ast.expr | None]] = defaultdict(list) + node = self.node + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)): + arguments = node.args + self._not_local.update( + argument.arg + for argument in ( + *arguments.posonlyargs, + *arguments.args, + *arguments.kwonlyargs, + arguments.vararg, + arguments.kwarg, + ) + if argument is not None + ) + body = [node.body] if isinstance(node, ast.Lambda) else node.body + def bind_other(target: ast.AST) -> None: + for name in ast.walk(target): + if isinstance(name, ast.Name): + assignments[name.id].append(None) -def _import_module(name: str) -> object: - return importlib.import_module(name) + for child in _nodes_in_scope(body): + if isinstance(child, (ast.Assign, ast.AnnAssign, ast.NamedExpr)): + if child.value is None: + continue + targets = ( + child.targets if isinstance(child, ast.Assign) else [child.target] + ) + for target in targets: + if isinstance(target, ast.Name): + assignments[target.id].append(child.value) + elif isinstance(target, (ast.Tuple, ast.List, ast.Starred)): + bind_other(target) + elif isinstance(child, (ast.For, ast.AsyncFor, ast.comprehension)): + bind_other(child.target) + elif isinstance(child, ast.withitem) and child.optional_vars is not None: + bind_other(child.optional_vars) + elif isinstance(child, ast.ExceptHandler) and child.name: + assignments[child.name].append(None) + elif isinstance(child, (ast.Import, ast.ImportFrom)): + for alias in child.names: + assignments[alias.asname or alias.name.split(".", 1)[0]].append( + None + ) + elif isinstance( + child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef) + ): + assignments[child.name].append(None) + elif isinstance(child, (ast.Global, ast.Nonlocal)): + self._not_local.update(child.names) + elif isinstance(child, (ast.MatchAs, ast.MatchStar)) and child.name: + assignments[child.name].append(None) + elif isinstance(child, ast.MatchMapping) and child.rest: + assignments[child.rest].append(None) + self._assignments = assignments -@functools.cache -def _library_object(dotted_name: str) -> object | None: - """The NumPy or SciPy object a dotted name names, importing its module.""" +def _trigger_lines(source: str) -> list[int] | None: + """The numbers of the lines holding trigger text, or ``None`` when lines + cannot be counted as the parser counts them (a lone carriage return).""" - parts = dotted_name.split(".") - for split in range(len(parts), 0, -1): - try: - found: object = _import_module(".".join(parts[:split])) - except ImportError: - continue - except Exception: - # A module that fails to import names nothing the scan can use. - return None - for part in parts[split:]: - found = getattr(found, part, None) - if found is None: - return None - return found - return None - - -@functools.cache -def _positional_outputs(dotted_name: str) -> slice | None: - """Which positional arguments of a library function or ufunc are outputs.""" - - function = _library_object(dotted_name) - if isinstance(function, np.ufunc): - return slice(function.nin, None) - if not callable(function): + if "\r" in source and "\r" in source.replace("\r\n", ""): return None - try: - parameters = list(inspect.signature(function).parameters.values()) - except (TypeError, ValueError): - return None - positional = ( - inspect.Parameter.POSITIONAL_ONLY, - inspect.Parameter.POSITIONAL_OR_KEYWORD, + newlines = [match.start() for match in re.finditer("\n", source)] + return sorted( + { + bisect.bisect_left(newlines, match.start()) + 1 + for match in _TRIGGER_TEXT.finditer(source) + } ) - for index, parameter in enumerate(parameters): - if parameter.name == "out" and parameter.kind in positional: - return slice(index, index + 1) - return None -def _items_newness(level: int, items_taken: int) -> int: - """How new a name bound ``items_taken`` items deep into a value is: an - item of a new array is new memory, an item of a container may not be.""" - - if items_taken == 0: - return level - return _NEW_ARRAY if level == _NEW_ARRAY else _NOT_NEW +class _Scanner(ast.NodeVisitor): + def __init__(self, source: str, path: str, tree: ast.Module) -> None: + self._source = source + self._path = path + self._numpy = _NumpyNames(tree) + self._scopes = [_Scope("", tree)] + self._trigger_lines = _trigger_lines(source) + self.findings: list[Finding] = [] + def visit(self, node: ast.AST) -> None: + # Every rule looks at text inside the statement it reports, so a + # statement without trigger text cannot hold a finding. + if self._trigger_lines is not None and isinstance(node, ast.stmt): + decorators = getattr(node, "decorator_list", ()) + first = min([node.lineno, *(item.lineno for item in decorators)]) + index = bisect.bisect_left(self._trigger_lines, first) + last = node.end_lineno or node.lineno + if index >= len(self._trigger_lines) or self._trigger_lines[index] > last: + return + super().visit(node) + + # Scopes and reporting ------------------------------------------------ + + def _visit_scope(self, node: ast.AST, name: str) -> None: + enclosing = self._scopes[-1].qualified_name + qualified = name if enclosing == "" else f"{enclosing}.{name}" + # Decorators, defaults and base classes belong to the enclosing scope. + body = [node.body] if isinstance(node, ast.Lambda) else node.body + inside = {id(statement) for statement in body} + for child in ast.iter_child_nodes(node): + if id(child) not in inside: + self.visit(child) + self._scopes.append(_Scope(qualified, node)) + for statement in body: + self.visit(statement) + self._scopes.pop() -def _is_ufunc_method(dotted_name: str, methods: Iterable[str]) -> bool: - owner, _, method = dotted_name.rpartition(".") - return method in methods and isinstance(_library_object(owner), np.ufunc) + def visit_FunctionDef(self, node: ast.FunctionDef) -> None: + self._visit_scope(node, node.name) + def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None: + self._visit_scope(node, node.name) -def _is_slice(index: ast.expr) -> bool: - """Whether a subscript's index is a slice (``a[1:]``, ``a[:, 0:2]``).""" + def visit_ClassDef(self, node: ast.ClassDef) -> None: + self._visit_scope(node, node.name) - if isinstance(index, ast.Tuple): - return any(isinstance(part, ast.Slice) for part in index.elts) - return isinstance(index, ast.Slice) + def visit_Lambda(self, node: ast.Lambda) -> None: + self._visit_scope(node, "") + def _report(self, node: ast.AST, rule: str) -> None: + scope = self._scopes[-1] + if isinstance(scope.node, ast.Module): + function_source = self._source + else: + function_source = ast.get_source_segment(self._source, scope.node) or "" + segment = ast.get_source_segment(self._source, node) or ast.unparse(node) + self.findings.append( + Finding( + path=self._path, + line=node.lineno, + function=scope.qualified_name, + rule=rule, + code=" ".join(segment.split()), + function_digest=hashlib.sha256( + function_source.encode("utf-8") + ).hexdigest()[:12], + ) + ) -def _is_false_constant(expression: ast.expr) -> bool: - return isinstance(expression, ast.Constant) and not expression.value + # Created arrays -------------------------------------------------------- + def _allocates(self, call: ast.Call) -> bool: + if _keyword(call, "out") is not None: + return False + function = call.func + if ( + isinstance(function, ast.Attribute) + and function.attr == "copy" + and not call.args + and not call.keywords + ): + return True + name = self._numpy.resolve(function) + if name is None: + return False + if name == "numpy.array": + return _keyword(call, "copy") is None + if name.removeprefix("numpy.") in _ALLOCATING_NUMPY_FUNCTIONS: + return True + return isinstance(_numpy_object(name), np.ufunc) -def _is_none(expression: ast.expr | None) -> bool: - return isinstance(expression, ast.Constant) and expression.value is None + def _is_created(self, expression: ast.expr) -> bool: + while isinstance(expression, ast.Subscript): + expression = expression.value + if isinstance(expression, ast.Call): + return self._allocates(expression) + if not isinstance(expression, ast.Name): + return False + assignments = self._scopes[-1].assignments_of(expression.id) + if assignments is None: + return False + values = [value for value in assignments if not _is_none(value)] + return bool(values) and all( + isinstance(value, ast.Call) and self._allocates(value) for value in values + ) + # Rules ----------------------------------------------------------------- -def _keyword(call: ast.Call, name: str) -> ast.keyword | None: - return next((keyword for keyword in call.keywords if keyword.arg == name), None) - - -def _is_true_constant(expression: ast.expr) -> bool: - return isinstance(expression, ast.Constant) and expression.value is True - - -def _copy_is_off(call: ast.Call, position: int | None = None) -> bool: - """Whether a call passes ``copy`` with anything but ``True``: by keyword, - or by ``position`` when the function takes it positionally.""" - - copy = _keyword(call, "copy") - value = copy.value if copy is not None else None - if ( - value is None - and position is not None - and len(call.args) > position - and not any(isinstance(argument, ast.Starred) for argument in call.args) - ): - positional = call.args[position] - # Other methods of the same name take other arguments there (an - # ndarray's ``astype(dtype, order)``), so only the constant False - # counts. - return isinstance(positional, ast.Constant) and positional.value is False - return value is not None and not _is_true_constant(value) - - -def _is_extension_array_expression(expression: ast.expr) -> bool: - """``x.array`` (or a slice of it): a pandas extension array.""" - - while isinstance(expression, ast.Subscript): - expression = expression.value - return ( - isinstance(expression, ast.Attribute) - and expression.attr == "array" - and not _is_own_object(expression.value) - ) - - -def _is_own_object(expression: ast.expr) -> bool: - return isinstance(expression, ast.Name) and expression.id in _OWN_OBJECT_NAMES - - -# The scanner --------------------------------------------------------------- - -#: How a name is looked up while a scope's table is computed. -_NameLookup = Callable[[str], object] - - -class _Scanner: - def __init__(self, source: str, path: str, tree: ast.Module) -> None: - self._source = source - self._path = path - self._tree = tree - self._libraries = _LibraryNames(tree) - lone_carriage_return = "\r" in source and "\r" in source.replace("\r\n", "") - # Without ``.array``, ``.base`` or ``.asi8`` text, nothing in the - # module can reach a writable view. A write through a name bound to - # one holds no trigger text of its own, so a module with that text - # is scanned in full. - self._has_writable_views = bool(_WRITABLE_VIEW_TEXT.search(source)) - self._trigger_lines = ( - None - if lone_carriage_return or self._has_writable_views - else _TriggerLines( - source, self._libraries.bound_names | self._libraries.derived_names - ) - ) - self._module_scope = _Scope("", tree) - self._scope: _Scope | _ComprehensionScope = self._module_scope - self._digests: dict[int, str] = {} - self._source_lines: list[str] | None = None - self._target_levels: dict[tuple[bool, int, int | None, str], int] = {} - self._checks = { - ast.Call: self._check_call, - ast.Assign: self._check_assign, - ast.AnnAssign: self._check_annotated_assign, - ast.AugAssign: self._check_augmented_assign, - ast.Attribute: self._check_attribute, - ast.ImportFrom: self._check_import_from, - } - self.findings: list[Finding] = [] - - def scan(self) -> list[Finding]: - stack: list[tuple[ast.AST, _Scope | _ComprehensionScope]] = [ - (node, self._module_scope) for node in reversed(self._tree.body) - ] - while stack: - node, scope = stack.pop() - if ( - self._trigger_lines is not None - and isinstance(node, ast.stmt) - and not self._trigger_lines.may_hold_finding(node) - ): - continue - self._scope = scope - check = self._checks.get(type(node)) - if check is not None: - check(node) - children = list(ast.iter_child_nodes(node)) - if isinstance(node, _NESTED_SCOPES): - # Decorators, defaults, annotations and base classes belong - # to the enclosing scope; only the body is inside. - name = "" if isinstance(node, ast.Lambda) else node.name - inner = _Scope(scope.child_name(name), node) - body = [node.body] if isinstance(node, ast.Lambda) else node.body - inside = {id(statement) for statement in body} - stack.extend( - (child, inner if id(child) in inside else scope) - for child in reversed(children) - ) - elif isinstance(node, _COMPREHENSIONS): - inner = _ComprehensionScope(scope, node) - stack.extend((child, inner) for child in reversed(children)) - else: - stack.extend((child, scope) for child in reversed(children)) - return self.findings - - # Reporting ----------------------------------------------------------- - - def _segment(self, node: ast.AST) -> str: - """The source of ``node``, as ``ast.get_source_segment`` gives it, - from lines split once per module.""" - - if self._source_lines is None: - self._source_lines = re.findall(r"[^\r\n]*(?:\r\n|\r|\n|$)", self._source) - lines = self._source_lines - first, last = node.lineno - 1, node.end_lineno - 1 - start, end = node.col_offset, node.end_col_offset - if first == last: - return lines[first].encode()[start:end].decode() - return ( - lines[first].encode()[start:].decode() - + "".join(lines[first + 1 : last]) - + lines[last].encode()[:end].decode() - ) - - def _function_digest(self) -> str: - node = self._scope.node - digest = self._digests.get(id(node)) - if digest is None: - if isinstance(node, ast.Module): - segment = self._source - else: - segment = self._segment(node) - digest = hashlib.sha256(segment.encode("utf-8")).hexdigest()[:12] - self._digests[id(node)] = digest - return digest - - def _report(self, node: ast.AST, rule: str) -> None: - segment = self._segment(node) - self.findings.append( - Finding( - path=self._path, - line=node.lineno, - function=self._scope.qualified_name, - rule=rule, - code=" ".join(segment.split()), - function_digest=self._function_digest(), - ) - ) - - # Following names ------------------------------------------------------- - - def _bindings(self, name: str) -> list[_Binding] | None: - """The bindings of ``name`` in the current scope, if it is local.""" - - return self._scope.bindings_of(name) - - def _owning_scope(self) -> _Scope: - scope = self._scope - while isinstance(scope, _ComprehensionScope): - scope = scope.enclosing - return scope - - def _resolve(self, expression: ast.expr) -> str | None: - """The dotted library name of ``expression``, following ``plus = np.add``.""" - - name = self._libraries.resolve(expression) - if name is not None: - return name - attributes: list[str] = [] - root = expression - while isinstance(root, ast.Attribute): - attributes.append(root.attr) - root = root.value - if ( - not isinstance(root, ast.Name) - or root.id not in self._libraries.derived_names - ): - return None - bindings = self._bindings(root.id) - if bindings is None and not self._scope.is_parameter(root.id): - bindings = self._module_scope.bindings_of(root.id) - if not bindings or any(items_taken for _value, items_taken in bindings): - return None - resolved = { - self._libraries.resolve(value) for value, _items in bindings if value - } - if len(resolved) != 1 or None in resolved: - return None - return ".".join([resolved.pop(), *reversed(attributes)]) - - # How new a value is ---------------------------------------------------- - - def _name_newness(self, name: str) -> int: - """How new ``name``'s value is where it is used, in the current scope.""" - - scope = self._scope - while isinstance(scope, _ComprehensionScope): - sources = scope.target_sources(name) - if sources is not None: - return self._comprehension_target(scope, name, sources, newness=True) - scope = scope.enclosing - return self._newness_table(scope).get(name, _NOT_NEW) - - def _comprehension_target( - self, - scope: _ComprehensionScope, - name: str, - sources: list[tuple[ast.expr | None, int, int]], - *, - newness: bool, - ) -> int: - """How new, or how close to a view, a comprehension's loop target is. - - Each source is measured as the comprehension sees it from that - target's generator. Results are cached: they depend only on the - comprehension and the tables of the scopes around it. - """ - - key = (newness, id(scope.comprehension), scope.upto, name) - cached = self._target_levels.get(key) - if cached is not None: - return cached - saved_scope = self._scope - levels: list[int] = [] - try: - for value, items_taken, index in sources: - if value is None: - if newness: - levels.append(_NOT_NEW) - continue - self._scope = scope.before(index) - if newness: - levels.append(_items_newness(self._newness(value), items_taken)) - else: - levels.append(_items_taken(self._view_level(value), items_taken)) - finally: - self._scope = saved_scope - result = min(levels, default=_NOT_NEW if newness else _NO_VIEW) - self._target_levels[key] = result - return result - - def _newness_table(self, scope: _Scope) -> dict[str, int]: - """How new each local name of ``scope`` is. - - Every name starts at the newest level and is lowered to the oldest - level any of its bindings gives, until nothing changes, so a name - bound to itself (``values = values[:n]``) is as new as its other - bindings make it. A binding to None is a placeholder that holds no - array. - """ - - if scope.newness_table is not None: - return scope.newness_table - saved_scope, self._scope = self._scope, scope - levels: dict[str, int] = {} - candidates: dict[str, list[_Binding]] = {} - for name, bindings in scope.local_bindings().items(): - kept = [ - (value, items_taken) - for value, items_taken in bindings - if not (items_taken == 0 and _is_none(value)) - ] - if not kept or any(value is None for value, _items in kept): - levels[name] = _NOT_NEW - else: - levels[name] = _NEW_ARRAY - candidates[name] = kept - - def lookup(name: str) -> int: - return levels.get(name, _NOT_NEW) - - changed = True - try: - while changed: - changed = False - for name, values in candidates.items(): - if levels[name] == _NOT_NEW: - continue - level = min( - _items_newness(self._newness(value, lookup), items_taken) - for value, items_taken in values - ) - if level < levels[name]: - levels[name] = level - changed = True - finally: - self._scope = saved_scope - scope.newness_table = levels - return levels - - def _call_newness(self, call: ast.Call, lookup: _NameLookup | None) -> int: - outputs = self._output_arguments(call) - if outputs: - # The result is the output array (or None, for ``ufunc.at`` and - # the in-place functions): as new as the outputs are. - return min(self._newness(output, lookup) for output in outputs) - name = self._resolve(call.func) - function = call.func - if name is not None: - if name in _ALLOCATING_NUMPY_FUNCTIONS: - return _NEW_ARRAY - if isinstance(_library_object(name), np.ufunc): - return _NEW_ARRAY - if _is_ufunc_method(name, _ALLOCATING_UFUNC_METHODS): - return _NEW_ARRAY - if ( - name.startswith("numpy.random.") - and name not in _IN_PLACE_NUMPY_FUNCTIONS - ): - return _NEW_ARRAY - if name == "numpy.array": - return _NOT_NEW if _copy_is_off(call) else _NEW_ARRAY - if call.args and ( - name in _VIEW_NUMPY_FUNCTIONS - or name in _SPLITTING_NUMPY_FUNCTIONS - or name in _PANDAS_SHARING_NUMPY_FUNCTIONS - ): - # A view of a new array, or an array made from a new container. - source = self._newness(call.args[0], lookup) - return _NEW_ARRAY if source >= _NEW_OBJECT else _NOT_NEW - return _NOT_NEW - if isinstance(function, ast.Name) and function.id in _CONTAINER_BUILTINS: - return _NEW_OBJECT - if not isinstance(function, ast.Attribute): - return _NOT_NEW - method = function.attr - if method == "to_numpy": - copy = _keyword(call, "copy") - copy_value = copy.value if copy is not None else None - if copy_value is None and len(call.args) >= 2: - copy_value = call.args[1] - return ( - _NEW_ARRAY - if copy_value is not None and _is_true_constant(copy_value) - else _NOT_NEW - ) - if method == "flatten" or method in _RANDOM_DRAW_METHODS: - return _NEW_ARRAY - if method in _VIEW_METHODS: - receiver = self._newness(function.value, lookup) - return _NEW_ARRAY if receiver == _NEW_ARRAY else _NOT_NEW - if method == "copy": - deep = _keyword(call, "deep") - if deep is not None and not _is_true_constant(deep.value): - return _NOT_NEW - first = call.args[0] if call.args else None - if first is not None and not ( - isinstance(first, ast.Constant) - and (first.value is True or isinstance(first.value, str)) - ): - return _NOT_NEW - # A copy of an array is a new array; of anything else (a dict, a - # list), possibly a shallow copy whose items are shared. - return ( - _NEW_ARRAY if self._is_array_expression(function.value) else _NEW_OBJECT - ) - return _NOT_NEW - - def _newness(self, expression: ast.expr, lookup: _NameLookup | None = None) -> int: - """How new the value of ``expression`` is (``_NOT_NEW`` to ``_NEW_ARRAY``).""" - - if isinstance(expression, ast.Attribute): - # ``.T`` and the other view attributes of a new array are new. - if expression.attr in _VIEW_ATTRIBUTES: - source = self._newness(expression.value, lookup) - return _NEW_ARRAY if source == _NEW_ARRAY else _NOT_NEW - return _NOT_NEW - if isinstance(expression, ast.Subscript): - container = self._newness(expression.value, lookup) - if container == _NEW_ARRAY: - return _NEW_ARRAY - if container == _NEW_OBJECT and _is_slice(expression.slice): - return _NEW_OBJECT - return _NOT_NEW - if isinstance(expression, ast.IfExp): - return min( - self._newness(expression.body, lookup), - self._newness(expression.orelse, lookup), - ) - if isinstance(expression, ast.BoolOp): - return min(self._newness(value, lookup) for value in expression.values) - if isinstance(expression, ast.Call): - return self._call_newness(expression, lookup) - if isinstance(expression, ast.BinOp): - if isinstance(expression.op, _JOINING_OPERATORS): - return _NEW_OBJECT - return _NEW_ARRAY - if isinstance(expression, _NEW_ARRAY_EXPRESSIONS): - return _NEW_ARRAY - if isinstance(expression, ast.NamedExpr): - return self._newness(expression.value, lookup) - if isinstance(expression, ast.Constant): - # A literal (``total = 0.0``) holds no pandas memory. - return _NEW_ARRAY - if isinstance(expression, _CONTAINER_EXPRESSIONS): - return _NEW_OBJECT - if isinstance(expression, ast.Name): - if lookup is not None: - return lookup(expression.id) - return self._name_newness(expression.id) - return _NOT_NEW - - # Whether a value can be a writable view -------------------------------- - - def _name_view_level(self, name: str) -> int: - """Whether, and how deep, ``name`` holds a writable view where it is used.""" - - scope = self._scope - while isinstance(scope, _ComprehensionScope): - sources = scope.target_sources(name) - if sources is not None: - return self._comprehension_target(scope, name, sources, newness=False) - scope = scope.enclosing - return self._view_table(scope).get(name, _NO_VIEW) - - def _view_table(self, scope: _Scope) -> dict[str, int]: - """Whether, and how deep, each name of ``scope`` holds a writable view. - - Starts every name at ``_NO_VIEW`` and lowers it to the closest level - any of its bindings or held values gives, until nothing changes. A - binding that takes items of its value (a loop target, unpacking) - takes one level per item; a container filled with a value holds it - one level deeper. - """ - - if scope.view_table is not None: - return scope.view_table - saved_scope, self._scope = self._scope, scope - sources: defaultdict[str, list[tuple[ast.expr, Callable[[int], int]]]] = ( - defaultdict(list) - ) - for name, bindings in scope.local_bindings().items(): - for value, items_taken in bindings: - if value is not None: - sources[name].append( - (value, functools.partial(_bound_level, items_taken)) - ) - # A container filled here may be a parameter, so held values count - # for any name; but assigning into a NumPy array this function - # created copies the values. - new_arrays = { - name - for name, level in self._newness_table(scope).items() - if level == _NEW_ARRAY - } - for name in scope.held_names(): - if self._resolve(ast.Name(id=name, ctx=ast.Load())) is not None: - # ``np.append(...)`` is a library call, not a container fill. - continue - for value, items_taken, kind in scope.held_values(name): - if kind == _BY_KEY and name in new_arrays: - continue - sources[name].append( - (value, functools.partial(_held_level, items_taken, kind)) - ) - levels: dict[str, int] = dict.fromkeys(sources, _NO_VIEW) - - def lookup(name: str) -> int: - return levels.get(name, _NO_VIEW) - - changed = True - try: - while changed: - changed = False - for name, parts in sources.items(): - if levels[name] == _IS_VIEW: - continue - level = min( - convert(self._view_level(value, lookup)) - for value, convert in parts - ) - if level < levels[name]: - levels[name] = level - changed = True - finally: - self._scope = saved_scope - scope.view_table = levels - return levels - - def _is_array_expression(self, expression: ast.expr) -> bool: - """``.values``, or a call of a library function or of an array method.""" - - if isinstance(expression, ast.Attribute): - return expression.attr == "values" - if not isinstance(expression, ast.Call): - return False - function = expression.func - name = self._resolve(function) - if name is not None: - # ``np.split`` and the like return lists. - return name not in _SPLITTING_NUMPY_FUNCTIONS - return isinstance(function, ast.Attribute) and function.attr in ( - *_VIEW_METHODS, - "astype", - ) - - def _is_container(self, expression: ast.expr) -> bool: - # A chain of joins (``[a] + [b] + rest``) is a container if any of - # its operands is one. - while isinstance(expression, ast.BinOp) and isinstance( - expression.op, _VIEW_JOINING_OPERATORS - ): - if self._is_container(expression.right): - return True - expression = expression.left - if isinstance(expression, _CONTAINER_EXPRESSIONS): - return True - if isinstance(expression, ast.Call) and isinstance(expression.func, ast.Name): - return expression.func.id in _CONTAINER_BUILTINS - if isinstance(expression, ast.Name): - bindings = self._bindings(expression.id) or [] - return bool(bindings) and all( - value is not None - and items_taken == 0 - and isinstance(value, _CONTAINER_EXPRESSIONS) - for value, items_taken in bindings - ) - return False - - def _reaches_writable_view(self, expression: ast.expr) -> bool: - """Whether a write into ``expression`` can reach pandas' memory.""" - - return self._view_level(expression) <= _ELEMENT - - def _view_level( - self, expression: ast.expr, lookup: _NameLookup | None = None - ) -> int: - """Whether, and how deep in containers, ``expression`` holds a writable view.""" - - if not self._has_writable_views: - return _NO_VIEW - if isinstance(expression, ast.Attribute): - if expression.attr in _WRITABLE_VIEW_ATTRIBUTES: - return _NO_VIEW if _is_own_object(expression.value) else _IS_VIEW - if expression.attr == "base": - # ``.base`` of an array expression is the array behind a view; - # on other objects it is an ordinary attribute. - return ( - _IS_VIEW - if self._is_array_expression(expression.value) - else _NO_VIEW - ) - if expression.attr in _VIEW_ATTRIBUTES: - return _view_of(self._view_level(expression.value, lookup)) - return _NO_VIEW - if isinstance(expression, ast.Subscript): - container = self._view_level(expression.value, lookup) - if _is_slice(expression.slice): - return container - return _item_of(container) - if isinstance(expression, ast.NamedExpr): - return self._view_level(expression.value, lookup) - if isinstance(expression, ast.Starred): - return self._view_level(expression.value, lookup) - if isinstance(expression, ast.Name): - if lookup is not None: - return lookup(expression.id) - return self._name_view_level(expression.id) - if isinstance(expression, ast.IfExp): - return min( - self._view_level(expression.body, lookup), - self._view_level(expression.orelse, lookup), - ) - if isinstance(expression, ast.BoolOp): - return min(self._view_level(value, lookup) for value in expression.values) - if isinstance(expression, ast.BinOp): - return self._joined_view_level(expression, lookup) - if isinstance(expression, (ast.List, ast.Tuple, ast.Set)): - # A starred element puts its items into the new container. - items = [ - _item_of(self._view_level(element.value, lookup)) - if isinstance(element, ast.Starred) - else self._view_level(element, lookup) - for element in expression.elts - ] - return _holder_of(min(items, default=_NO_VIEW)) - if isinstance(expression, ast.Dict): - # ``**mapping`` puts the mapping's values into the new dict. - items = [ - _item_of(self._view_level(value, lookup)) - if key is None - else self._view_level(value, lookup) - for key, value in zip(expression.keys, expression.values, strict=True) - ] - return _holder_of(min(items, default=_NO_VIEW)) - if isinstance(expression, _COMPREHENSIONS): - return self._comprehension_view_level(expression, lookup) - if isinstance(expression, ast.Call): - return self._call_view_level(expression, lookup) - return _NO_VIEW - - def _joined_view_level( - self, expression: ast.BinOp, lookup: _NameLookup | None - ) -> int: - """``[a.array] + [b.array] + rest`` and ``mapping | other`` join - containers; arithmetic, and any operator with an array operand, give - new memory.""" - - if not isinstance(expression.op, _VIEW_JOINING_OPERATORS): - return _NO_VIEW - operands: list[ast.expr] = [] - node: ast.expr = expression - while isinstance(node, ast.BinOp) and isinstance( - node.op, _VIEW_JOINING_OPERATORS - ): - operands.append(node.right) - node = node.left - operands.append(node) - if not any(self._is_container(operand) for operand in operands): - return _NO_VIEW - level = min(self._view_level(operand, lookup) for operand in operands) - return _NO_VIEW if level <= _ELEMENT else level - - def _comprehension_view_level( - self, expression: ast.expr, lookup: _NameLookup | None - ) -> int: - """A comprehension holds what its element is, its loop targets taking - items of their iterables.""" - - targets: dict[str, int] = {} - - def inner(name: str) -> int: - if name in targets: - return targets[name] - if lookup is not None: - return lookup(name) - return self._name_view_level(name) - - for generator in expression.generators: - for target, value, items_taken in _loop_target_names( - generator.target, generator.iter - ): - if isinstance(target, ast.Name): - level = ( - _NO_VIEW - if value is None - else _items_taken(self._view_level(value, inner), items_taken) - ) - targets[target.id] = min(targets.get(target.id, _NO_VIEW), level) - element = ( - expression.value if isinstance(expression, ast.DictComp) else expression.elt - ) - return _holder_of(self._view_level(element, inner)) - - def _call_view_level(self, call: ast.Call, lookup: _NameLookup | None) -> int: - arguments = [*call.args, *(keyword.value for keyword in call.keywords)] - - def nearest(expressions: Iterable[ast.expr]) -> int: - return min( - (self._view_level(expression, lookup) for expression in expressions), - default=_NO_VIEW, - ) - - name = self._resolve(call.func) - if name in _SPLITTING_NUMPY_FUNCTIONS: - return _holder_of(_view_of(nearest(arguments))) - if name in _VIEW_NUMPY_FUNCTIONS: - copy = _keyword(call, "copy") - if copy is not None and _is_true_constant(copy.value): - return _NO_VIEW - return _view_of(nearest(arguments)) - if name in ("numpy.array", "numpy.astype") and _copy_is_off(call): - return _view_of(nearest(arguments)) - function = call.func - if isinstance(function, ast.Name): - if function.id == "next": - return _item_of(nearest(arguments)) - if function.id == "dict": - # ``dict(mapping)`` holds the mapping's values, ``dict(pairs)`` - # the pairs' second items, and ``dict(key=value)`` each value. - positional = nearest(call.args) - from_items = ( - _NO_VIEW - if positional <= _ELEMENT - else min(positional, _holder_of(_items_taken(positional, 2))) - ) - named = nearest( - keyword.value for keyword in call.keywords if keyword.arg - ) - unpacked = nearest( - keyword.value for keyword in call.keywords if keyword.arg is None - ) - return min( - from_items, - _holder_of(named), - _NO_VIEW if unpacked <= _ELEMENT else unpacked, - ) - if function.id in _SAME_ITEMS_BUILTINS: - return _items_holder_of(nearest(arguments)) - if function.id in _TUPLE_YIELDING_BUILTINS: - # A container of tuples of the arguments' items. - return _holder_of(_items_holder_of(nearest(arguments))) - return _NO_VIEW - if not isinstance(function, ast.Attribute): - return _NO_VIEW - method = function.attr - receiver = self._view_level(function.value, lookup) - if method in _VIEW_METHODS: - copy = _keyword(call, "copy") - copy_value = copy.value if copy is not None else None - if copy_value is None and method == "to_numpy" and len(call.args) >= 2: - copy_value = call.args[1] - if copy_value is not None and _is_true_constant(copy_value): - return _NO_VIEW - return _view_of(receiver) - if method == "astype" and _copy_is_off(call, position=1): - return _view_of(receiver) - if method == "copy": - # A copy of an array is new memory; a copy of a container holds - # the same items. - return _NO_VIEW if receiver <= _ELEMENT else receiver - if method in _ITEM_TAKING_METHODS: - # ``get(key, default)`` may also return its default. - return min(_item_of(receiver), nearest(call.args[1:])) - if method in _SAME_ITEMS_METHODS: - return _items_holder_of(receiver) - if method in _TUPLE_YIELDING_METHODS: - return _holder_of(_items_holder_of(receiver)) - return _NO_VIEW - - def _check_written_array(self, node: ast.AST, written: ast.expr) -> None: - """Report a write into ``written`` unless it is new in this function.""" - - if self._reaches_writable_view(written): - self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) - elif self._newness(written) == _NOT_NEW: - self._report(node, _WRITES_INTO_EXISTING_ARRAY) - - # Rules ----------------------------------------------------------------- - - def _output_arguments(self, call: ast.Call) -> list[ast.expr]: - """The arrays a call writes into: ``out=``, positional outputs, ``ufunc.at``.""" + def _written_arrays(self, call: ast.Call) -> list[ast.expr]: + """``out=`` given to NumPy or an array method, and ``ufunc.at``'s array.""" written: list[ast.expr] = [] - name = self._resolve(call.func) + name = self._numpy.resolve(call.func) function = call.func - method = function.attr if isinstance(function, ast.Attribute) else None output = _keyword(call, "out") - # ``out=`` means an output array only to the libraries and to array - # and random Generator methods; workspace functions use it for paths. - if output is not None and (name is not None or method in _METHODS_WITH_OUT): + array_method = ( + isinstance(function, ast.Attribute) and function.attr in _METHODS_WITH_OUT + ) + if output is not None and (name is not None or array_method): if isinstance(output.value, (ast.Tuple, ast.List)): written.extend( element for element in output.value.elts if not _is_none(element) ) elif not _is_false_constant(output.value): written.append(output.value) - if any(isinstance(argument, ast.Starred) for argument in call.args): - return written - if name is None: - if method == "shuffle": - written.extend(call.args[:1]) - return written - if name in _IN_PLACE_NUMPY_FUNCTIONS: - return [*written, *call.args[:1]] - if name == "numpy.nan_to_num" and _copy_is_off(call, position=1): - return [*written, *call.args[:1]] - if _is_ufunc_method(name, ("at",)): - return [*written, *call.args[:1]] - outputs = _positional_outputs(name) - return written if outputs is None else [*written, *call.args[outputs]] - - def _writes_into_receiver(self, call: ast.Call, method: str) -> bool: - if method in _IN_PLACE_ARRAY_METHODS: - return True - if method == "fillna": - return _copy_is_off(call) - if method == "byteswap": - in_place = _keyword(call, "inplace") - flag = in_place.value if in_place is not None else None - if flag is None and call.args: - flag = call.args[0] - return flag is not None and not _is_false_constant(flag) - return False - - def _check_call(self, node: ast.Call) -> None: + if name is not None and name.endswith(".at") and call.args: + if isinstance(_numpy_object(name[: -len(".at")]), np.ufunc): + written.append(call.args[0]) + return written + + def visit_Call(self, node: ast.Call) -> None: function = node.func if isinstance(function, ast.Attribute): if function.attr == "setflags": @@ -1921,39 +564,33 @@ def _check_call(self, node: ast.Call) -> None: flag = node.args[0] if flag is not None and not _is_false_constant(flag): self._report(node, _MAKES_ARRAY_WRITABLE) - elif function.attr == "__setitem__": - # Like item assignment: into a view or an item of one. - if self._reaches_writable_view(function.value): - self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) - elif self._writes_into_receiver(node, function.attr): - # Only on a view itself: an item of a one-dimensional view is - # a scalar, and ``label.partition(" ")`` is a string method. - if self._view_level(function.value) == _IS_VIEW: - self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) - for written in self._output_arguments(node): - self._check_written_array(node, written) - - def _check_assigned_target( + elif function.attr == "__setitem__" and _is_series_array(function.value): + self._report(node, _WRITES_THROUGH_SERIES_ARRAY) + for written in self._written_arrays(node): + if not self._is_created(written): + self._report(node, _WRITES_INTO_EXISTING_ARRAY) + self.generic_visit(node) + + def _check_target( self, node: ast.AST, target: ast.expr, value: ast.expr | None ) -> None: if isinstance(target, (ast.Tuple, ast.List)): for element in target.elts: - self._check_assigned_target(node, element, None) + self._check_target(node, element, None) elif isinstance(target, ast.Starred): - self._check_assigned_target(node, target.value, None) + self._check_target(node, target.value, None) elif isinstance(target, ast.Subscript): - flags = target.value - key = target.slice + container = target.value if ( - isinstance(flags, ast.Attribute) - and flags.attr == "flags" - and isinstance(key, ast.Constant) - and key.value in ("W", "WRITEABLE") + isinstance(container, ast.Attribute) + and container.attr == "flags" + and isinstance(target.slice, ast.Constant) + and target.slice.value in ("W", "WRITEABLE") ): if value is None or not _is_false_constant(value): self._report(node, _MAKES_ARRAY_WRITABLE) - elif self._reaches_writable_view(target.value): - self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) + elif _is_series_array(container): + self._report(node, _WRITES_THROUGH_SERIES_ARRAY) elif ( isinstance(target, ast.Attribute) and target.attr == "writeable" @@ -1963,118 +600,46 @@ def _check_assigned_target( if value is None or not _is_false_constant(value): self._report(node, _MAKES_ARRAY_WRITABLE) - def _check_assign(self, node: ast.Assign) -> None: + def visit_Assign(self, node: ast.Assign) -> None: for target in node.targets: - self._check_assigned_target(node, target, node.value) - - def _check_annotated_assign(self, node: ast.AnnAssign) -> None: - self._check_assigned_target(node, node.target, node.value) - - def _check_augmented_assign(self, node: ast.AugAssign) -> None: - # ``values += 1`` writes into the array ``values`` names. An element - # of a view may be a scalar, which ``+=`` rebinds, so only a view - # itself counts; ``holder[key] += 1`` writes into a view the holder - # holds. - target = node.target - if isinstance(target, ast.Name): - if self._view_level( - target - ) == _IS_VIEW and not self._bound_only_to_extension_arrays(target.id): - self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) - elif isinstance(target, ast.Subscript): - # Into a view through indexing, or into a view a holder holds - # (``arrays[0] += 1``; ``arrays[1:] += more`` only rebinds items). - container = self._view_level(target.value) - if container <= _ELEMENT or ( - self._view_level(target) == _IS_VIEW - and not self._holds_only_extension_arrays(target.value) - ): - self._report(node, _WRITES_THROUGH_WRITABLE_VIEW) - - def _bound_only_to_extension_arrays(self, name: str) -> bool: - """Whether every binding of ``name`` is ``x.array`` itself (or a slice). - - That is a pandas extension array, for which ``+=`` builds a new - array and rebinds the name instead of writing, except for datetime, - timedelta and period data. - """ - - return self._names_extension_array(ast.Name(id=name, ctx=ast.Load()), set()) + self._check_target(node, target, node.value) + self.generic_visit(node) - def _names_extension_array(self, expression: ast.expr, following: set[str]) -> bool: - """Whether ``expression`` is ``x.array``, a slice of it, or a local - name bound only to one of these.""" + def visit_AnnAssign(self, node: ast.AnnAssign) -> None: + self._check_target(node, node.target, node.value) + self.generic_visit(node) - while isinstance(expression, ast.Subscript): - expression = expression.value - if _is_extension_array_expression(expression): - return True - if not isinstance(expression, ast.Name) or expression.id in following: - return False - following.add(expression.id) - bindings = self._bindings(expression.id) or [] - return bool(bindings) and all( - items_taken == 0 - and value is not None - and self._names_extension_array(value, following) - for value, items_taken in bindings - ) - - def _holds_only_extension_arrays(self, container: ast.expr) -> bool: - """Whether every item a container is built or filled with is an - ``x.array`` itself, so that ``container[key] += 1`` rebinds the item.""" - - if not isinstance(container, ast.Name): - return False - items: list[ast.expr] = [] - for value, items_taken in self._bindings(container.id) or []: - if items_taken or value is None: - return False - if isinstance(value, (ast.List, ast.Tuple, ast.Set)): - items.extend(value.elts) - elif isinstance(value, ast.Dict): - if any(key is None for key in value.keys): - return False - items.extend(value.values) - elif isinstance(value, (ast.ListComp, ast.SetComp, ast.GeneratorExp)): - items.append(value.elt) - elif isinstance(value, ast.DictComp): - items.append(value.value) - else: - return False - for value, items_taken, kind in self._owning_scope().held_values(container.id): - if items_taken or kind not in (_ONE_ITEM, _BY_KEY): - return False - items.append(value) - return bool(items) and all( - _is_extension_array_expression(item) for item in items - ) + def visit_AugAssign(self, node: ast.AugAssign) -> None: + self._check_target(node, node.target, None) + self.generic_visit(node) - def _check_attribute(self, node: ast.Attribute) -> None: - if node.attr in _ALWAYS_PRIVATE_ATTRIBUTES: - self._report(node, _PANDAS_PRIVATE_ATTRIBUTE) - elif node.attr in _FOREIGN_PRIVATE_ATTRIBUTES and not _is_own_object( - node.value + def visit_Attribute(self, node: ast.Attribute) -> None: + if node.attr in _ALWAYS_PRIVATE_ATTRIBUTES or ( + node.attr in _FOREIGN_PRIVATE_ATTRIBUTES and not _is_own_object(node.value) ): self._report(node, _PANDAS_PRIVATE_ATTRIBUTE) elif node.attr == "copyto": self._report(node, _NUMPY_COPYTO) + self.generic_visit(node) - def _check_import_from(self, node: ast.ImportFrom) -> None: + def visit_ImportFrom(self, node: ast.ImportFrom) -> None: if node.module is not None and ( node.module == "numpy" or node.module.startswith("numpy.") ): if any(alias.name == "copyto" for alias in node.names): self._report(node, _NUMPY_COPYTO) + self.generic_visit(node) def scan_source(source: str, path: str) -> list[Finding]: """Every refused expression in one module's source.""" - if not _FILE_TRIGGERS.search(source): + if not _TRIGGER_TEXT.search(source): return [] tree = ast.parse(source, filename=path) - return _Scanner(source, path, tree).scan() + scanner = _Scanner(source, path, tree) + scanner.visit(tree) + return scanner.findings def scanned_files(repository: Path) -> list[Path]: @@ -2104,9 +669,7 @@ def workspace_scan() -> _WorkspaceScan: for path in scanned_files(_REPOSITORY): relative = path.relative_to(_REPOSITORY).as_posix() paths.add(relative) - # Read the bytes as they are, so line endings reach the parser. - source = path.read_bytes().decode("utf-8") - findings.extend(scan_source(source, relative)) + findings.extend(scan_source(path.read_text(encoding="utf-8"), relative)) return _WorkspaceScan(frozenset(paths), tuple(findings)) @@ -2193,7 +756,7 @@ def test_the_scan_skips_node_modules_and_hidden_directories(tmp_path: Path) -> N _NUMPY = "import numpy as np\n" -def _in_function(*body_lines: str, parameters: str = "series") -> str: +def _in_function(*body_lines: str, parameters: str = "values") -> str: """A module importing NumPy with one function holding ``body_lines``.""" body = "".join(f" {line}\n" for line in body_lines) @@ -2202,867 +765,199 @@ def _in_function(*body_lines: str, parameters: str = "series") -> str: #: Snippets the scan must refuse, with the one rule each must report. _REFUSED_SNIPPETS = { - # Round-seven cases. - "fills_beside_a_masked_assignment_elsewhere": ( - _NUMPY - + "def mask_incomplete(group_values, complete):\n" - + " group_values[~complete] = np.nan\n" - + "def scale(frame, names):\n" - + " group_values = []\n" - + " for name in names:\n" - + " group_values.append(np.asarray(frame[name].array))\n" - + " for values in group_values:\n" - + " values *= 2\n", - _WRITES_THROUGH_WRITABLE_VIEW, + # makes-array-writable + "setflags_write_true": ( + "values.setflags(write=True)\nvalues[0] = 1.0\n", + _MAKES_ARRAY_WRITABLE, ), - "setitem_call_on_a_row_of_a_view": ( - _in_function( - "rows = np.atleast_2d(np.asarray(series.array))", - "rows[0].__setitem__(0, 1)", - ), - _WRITES_THROUGH_WRITABLE_VIEW, + "setflags_positional": ("values.setflags(True)\n", _MAKES_ARRAY_WRITABLE), + "setflags_variable": ("values.setflags(write=flag)\n", _MAKES_ARRAY_WRITABLE), + "flags_writeable_attribute": ( + "values.flags.writeable = True\n", + _MAKES_ARRAY_WRITABLE, ), - "out_item_of_a_copied_split": ( - _in_function( - "pieces = np.split(values, 2).copy()", - "np.add(pieces[0], 1, out=pieces[0])", - parameters="values", - ), - _WRITES_INTO_EXISTING_ARRAY, + "flags_writeable_key": ( + 'values.flags["WRITEABLE"] = True\n', + _MAKES_ARRAY_WRITABLE, ), - # Round-six cases. - "slice_of_a_view_augmented": ( - _in_function("head = np.asarray(series.array)[:3]", "head += 1"), - _WRITES_THROUGH_WRITABLE_VIEW, + "flags_w_key": ('values.flags["W"] = 1\n', _MAKES_ARRAY_WRITABLE), + # writes-through-series-array + "series_array_item": ( + 'frame.person["income"].array[0] = 1.0\n', + _WRITES_THROUGH_SERIES_ARRAY, ), - "loop_over_a_slice_of_views_augmented": ( - _in_function( - "arrays = [np.asarray(frame[name].array) for name in names]", - "for values in arrays[1:]:", - " values -= arrays[0]", - parameters="frame, names", - ), - _WRITES_THROUGH_WRITABLE_VIEW, + "series_array_augmented": ( + "series.array[mask] += 1\n", + _WRITES_THROUGH_SERIES_ARRAY, ), - "array_of_a_slice_of_a_view_augmented": ( - _in_function("values = np.asarray(series.array[1:])", "values += 1"), - _WRITES_THROUGH_WRITABLE_VIEW, + "series_array_annotated": ( + "series.array[0]: float = 1.0\n", + _WRITES_THROUGH_SERIES_ARRAY, ), - "series_array_through_dict_of_an_unpacked_mapping": ( - _in_function( - "by_name = {name: frame[name].array for name in names}", - "copied = dict(**by_name)", - 'copied["income"][0] = 1', - parameters="frame, names", - ), - _WRITES_THROUGH_WRITABLE_VIEW, + "series_array_unpacked": ( + "series.array[0], other = 1.0, 2.0\n", + _WRITES_THROUGH_SERIES_ARRAY, ), - "series_array_through_update_with_an_unpacked_mapping": ( - _in_function( - "by_name = {name: frame[name].array for name in names}", - "holder = {}", - "holder.update(**by_name)", - 'holder["income"][0] = 1', - parameters="frame, names", - ), - _WRITES_THROUGH_WRITABLE_VIEW, + "series_array_setitem_call": ( + "series.array.__setitem__(0, 1.0)\n", + _WRITES_THROUGH_SERIES_ARRAY, ), - # Round-five cases. - **{ - f"series_array_filled_with_{method}": ( - _in_function( - "holder = []", - fill, - "holder[0][0] = 1", - parameters="frame, names, by_name", - ), - _WRITES_THROUGH_WRITABLE_VIEW, - ) - for method, fill in { - "append": 'holder.append(frame["income"].array)', - "extend": "holder.extend([frame[name].array for name in names])", - "insert": 'holder.insert(0, frame["income"].array)', - "add": 'holder.add(frame["income"].array)', - "setdefault": 'holder.setdefault(0, frame["income"].array)', - "update_from_pairs": "holder.update(zip(names, (frame[n].array for n in names)))", - "update_from_a_mapping": "holder.update({0: frame['income'].array})", - "update_with_keywords": 'holder.update(income=frame["income"].array)', - }.items() - }, - "series_array_through_a_walrus": ( - _NUMPY + "(values := np.asarray(series.array))[0] = 1\n", - _WRITES_THROUGH_WRITABLE_VIEW, + "index_array_item": ("table.index.array[0] = 7\n", _WRITES_THROUGH_SERIES_ARRAY), + # pandas-private-attribute + "ndarray_attribute": ( + "values = series.array._ndarray\n", + _PANDAS_PRIVATE_ATTRIBUTE, ), - "series_array_astype_with_a_positional_false_copy": ( - 'series.array.astype("float64", False)[0] = 1\n', - _WRITES_THROUGH_WRITABLE_VIEW, + "manager_attribute": ("blocks = frame._mgr.blocks\n", _PANDAS_PRIVATE_ATTRIBUTE), + "manager_attribute_on_self": ( + "class Table:\n def blocks(self):\n return self._mgr.blocks\n", + _PANDAS_PRIVATE_ATTRIBUTE, ), - "numpy_nan_to_num_with_a_positional_false_copy": ( - _in_function("np.nan_to_num(values, False)", parameters="values"), - _WRITES_INTO_EXISTING_ARRAY, + "series_values_attribute": ("raw = series._values\n", _PANDAS_PRIVATE_ATTRIBUTE), + "masked_data": ("raw = series.array._data\n", _PANDAS_PRIVATE_ATTRIBUTE), + "masked_mask": ("series.array._mask[:] = False\n", _PANDAS_PRIVATE_ATTRIBUTE), + "categorical_codes": ( + "codes = series.cat.codes.array._codes\n", + _PANDAS_PRIVATE_ATTRIBUTE, ), - # Round-four cases. - "series_array_through_dict_values": ( - _in_function( - "by_name = {name: frame[name].array for name in names}", - "for values in by_name.values():", - " values[0] = 1", - parameters="frame, names", - ), - _WRITES_THROUGH_WRITABLE_VIEW, + # numpy-copyto + "copyto": (_NUMPY + "np.copyto(target, source)\n", _NUMPY_COPYTO), + "copyto_through_numpy": ( + "import numpy\nnumpy.copyto(target, source)\n", + _NUMPY_COPYTO, ), - "series_array_through_dict_item_pairs": ( - _in_function( - "by_name = {name: frame[name].array for name in names}", - "for pair in by_name.items():", - " pair[1][0] = 1", - parameters="frame, names", - ), - _WRITES_THROUGH_WRITABLE_VIEW, + "copyto_imported": ( + "from numpy import copyto\ncopyto(target, source)\n", + _NUMPY_COPYTO, ), - "series_array_comprehension_target_named_like_its_source": ( - _in_function( - "values = [frame[name].array for name in names]", - "[values.fill(0) for values in values]", - parameters="frame, names", - ), - _WRITES_THROUGH_WRITABLE_VIEW, + "copyto_imported_as_alias": ( + "from numpy import copyto as overwrite\n", + _NUMPY_COPYTO, ), - "series_array_in_a_three_way_join": ( - _in_function( - "pair = [first.array] + [second.array] + extra", - "pair[0][0] = 1", - parameters="first, second, extra", - ), - _WRITES_THROUGH_WRITABLE_VIEW, + "copyto_passed_as_function": ("apply_each(np.copyto, pairs)\n", _NUMPY_COPYTO), + # writes-into-existing-array + "out_parameter": ( + _in_function("np.add(values, 1, out=values)"), + _WRITES_INTO_EXISTING_ARRAY, ), - "series_array_in_a_long_join": ( - _in_function( - "parts = " + " + ".join(["[series.array]"] * 600), "parts[0][0] = 1" - ), - _WRITES_THROUGH_WRITABLE_VIEW, + "out_attribute": ( + _NUMPY + "np.multiply(scale, 2, out=self.buffer)\n", + _WRITES_INTO_EXISTING_ARRAY, ), - "series_array_through_dict_of_zip": ( - _in_function( - "arrays = [frame[name].array for name in names]", - "by_name = dict(zip(names, arrays))", - 'by_name["income"][0] = 1', - parameters="frame, names", - ), - _WRITES_THROUGH_WRITABLE_VIEW, + "out_to_numpy": ( + _NUMPY + "np.add(scale, 1, out=series.to_numpy())\n", + _WRITES_INTO_EXISTING_ARRAY, ), - "series_array_through_dict_keyword": ( - _in_function( - 'by_name = dict(income=frame["income"].array)', - 'by_name["income"][0] = 1', - parameters="frame", - ), - _WRITES_THROUGH_WRITABLE_VIEW, + "out_tuple": ( + _in_function("np.divmod(7, 2, out=(left, right))", parameters="left, right"), + _WRITES_INTO_EXISTING_ARRAY, ), - "series_array_through_enumerate_of_zip": ( - _in_function( - "arrays = [frame[name].array for name in names]", - "for position, (name, values) in enumerate(zip(names, arrays)):", - " values[0] = position", - parameters="frame, names", - ), - _WRITES_THROUGH_WRITABLE_VIEW, + "out_array_method": ( + _in_function("values.clip(0, 1, out=values)"), + _WRITES_INTO_EXISTING_ARRAY, ), - "out_loop_target_over_a_list_of_existing_arrays": ( - _in_function( - "for buffer in [series.to_numpy()]:", - " np.add(buffer, 1, out=buffer)", - ), + "out_generator_method": ( + _in_function("rng.random(out=values)", parameters="rng, values"), _WRITES_INTO_EXISTING_ARRAY, ), - # Round-three cases. - "series_array_through_a_dict_comprehension_of_loop_targets": ( - _in_function( - "arrays = [frame[name].array for name in names]", - "by_name = {name: values for name, values in zip(names, arrays)}", - 'by_name["income"][0] = 1', - parameters="frame, names", - ), - _WRITES_THROUGH_WRITABLE_VIEW, + "out_through_imported_ufunc": ( + "from numpy import add\ndef change(values):\n add(1, 1, out=values)\n", + _WRITES_INTO_EXISTING_ARRAY, ), - "series_array_through_an_identity_comprehension": ( + "out_name_bound_to_a_view": ( _in_function( - "arrays = [frame[name].array for name in names]", - "[values for values in arrays][0][0] = 1", - parameters="frame, names", + "buffer = series.to_numpy()", + "np.add(buffer, 1, out=buffer)", + parameters="series", ), - _WRITES_THROUGH_WRITABLE_VIEW, + _WRITES_INTO_EXISTING_ARRAY, ), - "series_array_filled_in_a_nested_comprehension": ( + "out_name_rebound_to_a_view": ( _in_function( - "groups = [[frame[name].array for name in names]]", - "[values.fill(0) for group in groups for values in group]", - parameters="frame, names", + "buffer = np.zeros(3)", + "buffer = series.to_numpy()", + "np.add(buffer, 1, out=buffer)", + parameters="series", ), - _WRITES_THROUGH_WRITABLE_VIEW, + _WRITES_INTO_EXISTING_ARRAY, ), - "series_array_through_next": ( + "out_name_bound_to_another_name": ( _in_function( - "arrays = [frame[name].array for name in names]", - "next(values for values in arrays)[0] = 1", - parameters="frame, names", + "buffer = np.zeros(3)", + "alias = buffer", + "np.add(alias, 1, out=alias)", + parameters="", ), - _WRITES_THROUGH_WRITABLE_VIEW, + _WRITES_INTO_EXISTING_ARRAY, ), - "series_array_augmented_through_a_loop_target": ( + "out_shallow_copy": ( _in_function( - "arrays = [np.asarray(frame[name].array) for name in names]", - "for values in arrays:", - " values += 1", - parameters="frame, names", + "shallow = table.copy(deep=False)", + "np.add(1, 1, out=shallow)", + parameters="table", ), - _WRITES_THROUGH_WRITABLE_VIEW, + _WRITES_INTO_EXISTING_ARRAY, ), - "series_array_augmented_through_an_item": ( + "out_array_without_copy": ( _in_function( - "arrays = [np.asarray(frame[name].array) for name in names]", - "arrays[0] += 1", - parameters="frame, names", + "view = np.array(values, copy=None)", + "np.add(view, 1, out=view)", ), - _WRITES_THROUGH_WRITABLE_VIEW, + _WRITES_INTO_EXISTING_ARRAY, ), - "series_array_augmented_after_split": ( + "out_allocation_given_an_output": ( _in_function( - "left, right = np.split(np.asarray(series.array), 2)", "left += 1" + "joined = np.concatenate(parts, out=values)", + "np.add(joined, 1, out=joined)", + parameters="parts, values", ), - _WRITES_THROUGH_WRITABLE_VIEW, + _WRITES_INTO_EXISTING_ARRAY, ), - "series_array_through_starred_display": ( - _in_function( - "arrays = [frame[name].array for name in names]", - "[*arrays, other][0][0] = 1", - parameters="frame, names, other", - ), - _WRITES_THROUGH_WRITABLE_VIEW, + "out_module_array_used_in_a_function": ( + _NUMPY + "buffer = np.zeros(3)\ndef change():\n np.add(1, 1, out=buffer)\n", + _WRITES_INTO_EXISTING_ARRAY, ), - "series_array_through_dict_unpacking": ( + "out_global_declared": ( _in_function( - "by_name = {name: frame[name].array for name in names}", - '{**by_name}["income"][0] = 1', - parameters="frame, names", + "global buffer", + "buffer = np.zeros(3)", + "np.add(1, 1, out=buffer)", + parameters="", ), - _WRITES_THROUGH_WRITABLE_VIEW, + _WRITES_INTO_EXISTING_ARRAY, ), - "series_array_through_dict_union": ( + "out_loop_target_shadowing_a_new_array": ( _in_function( - "by_name = {name: frame[name].array for name in names}", - '(by_name | {})["income"][0] = 1', - parameters="frame, names", + "buffer = np.zeros(3)", + "for buffer in arrays:", + " np.add(buffer, 1, out=buffer)", + parameters="arrays", ), - _WRITES_THROUGH_WRITABLE_VIEW, + _WRITES_INTO_EXISTING_ARRAY, ), - "series_array_through_get_default": ( + "out_comprehension_target_shadowing_a_new_array": ( _in_function( - 'values = overrides.get("income", frame["income"].array)', - "values[0] = 1", - parameters="frame, overrides", + "buffer = np.zeros(3)", + "return [np.add(buffer, 1, out=buffer) for buffer in arrays]", + parameters="arrays", ), - _WRITES_THROUGH_WRITABLE_VIEW, + _WRITES_INTO_EXISTING_ARRAY, ), - "series_array_unpacked_into_subscripts": ( + "out_with_target_shadowing_a_new_array": ( _in_function( - "columns = {}", - 'columns["a"], columns["b"] = np.split(np.asarray(series.array), 2)', - 'columns["a"][0] = 1', - ), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_through_real_if_close": ( - _NUMPY + "np.real_if_close(np.asarray(series.array))[0] = 1\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "out_item_of_a_dict_union": ( - _in_function( - "merged = by_name | {}", - 'np.add(merged["x"], 1, out=merged["x"])', - parameters="by_name", - ), - _WRITES_INTO_EXISTING_ARRAY, - ), - "ufunc_at_on_take_of_a_frame": ( - _in_function( - "np.add.at(np.take(frame, [0], axis=1), ([0], [0]), 100)", - parameters="frame", - ), - _WRITES_INTO_EXISTING_ARRAY, - ), - # Round-two cases: views reached through iteration and filled containers. - "series_array_through_zip": ( - _in_function( - "arrays = [frame[name].array for name in names]", - "for name, values in zip(names, arrays):", - " values[0] = 1", - parameters="frame, names", - ), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_through_enumerate": ( - _in_function( - "arrays = [frame[name].array for name in names]", - "for position, values in enumerate(arrays):", - " values[0] = position", - parameters="frame, names", - ), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_through_dict_items": ( - _in_function( - "arrays = {name: frame[name].array for name in names}", - "for name, values in arrays.items():", - " values[0] = 1", - parameters="frame, names", - ), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_through_dict_get": ( - _in_function( - "arrays = {name: frame[name].array for name in names}", - 'arrays.get("income")[0] = 1', - parameters="frame, names", - ), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_appended": ( - _in_function( - "arrays = []", - "for name in names:", - " arrays.append(frame[name].array)", - "arrays[0][0] = 1", - parameters="frame, names", - ), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_appended_to_a_parameter": ( - _in_function( - "arrays.append(series.array)", - "arrays[0][0] = 1", - parameters="series, arrays", - ), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_stored_by_key": ( - _in_function( - "columns = {}", - "for name in names:", - " columns[name] = frame[name].array", - 'columns["income"][0] = 1', - parameters="frame, names", - ), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_added_with_augmented_assignment": ( - _in_function( - "arrays = []", - "arrays += [series.array]", - "arrays[0][0] = 1", - ), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_in_joined_lists": ( - _in_function( - "pair = [first.array] + [second.array]", - "pair[0][0] = 1", - parameters="first, second", - ), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_split": ( - _in_function( - "parts = np.split(np.asarray(series.array), 2)", "parts[0][0] = 1" - ), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_broadcast": ( - _in_function( - "left, right = np.broadcast_arrays(np.asarray(series.array), 0)", - "left[0] = 1", - ), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_required": ( - _NUMPY + "np.require(series.array)[0] = 1\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_swapped_axes_method": ( - _NUMPY + "np.asarray(series.array).swapaxes(0, 0)[0] = 1\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_matrix_transpose_attribute": ( - _NUMPY + "np.atleast_2d(series.array).mT[0, 0] = 1\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - # Round-two cases: arrays that are not new. - "ufunc_at_on_item_of_joined_new_list": ( - _in_function( - "columns = [frame[name].to_numpy() for name in names] + []", - "np.add.at(columns[0], [0], 1)", - parameters="frame, names", - ), - _WRITES_INTO_EXISTING_ARRAY, - ), - "ufunc_at_on_clip_of_a_series": ( - _in_function( - 'np.add.at(np.clip(frame["f"], 0, None), positions, weights)', - parameters="frame, positions, weights", - ), - _WRITES_INTO_EXISTING_ARRAY, - ), - "ufunc_at_on_tile_of_a_series": ( - _in_function("np.add.at(np.tile(series, 1), [0], 1)"), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_round_of_a_parameter": ( - _in_function( - "rounded = np.round(values)", - "np.add(rounded, 1, out=rounded)", - parameters="values", - ), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_scipy_ufunc_keyword": ( - "import scipy.special\n" - + "def change(values):\n" - + " scipy.special.expit(values, out=values)\n", - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_scipy_ufunc_positional": ( - "from scipy.special import expit\n" - + "def change(values):\n" - + " expit(values, values)\n", - _WRITES_INTO_EXISTING_ARRAY, - ), - "series_array_in_a_shallow_dict_copy": ( - _in_function( - "arrays = {name: frame[name].array for name in names}", - "copied = arrays.copy()", - 'copied["income"][0] = 1', - parameters="frame, names", - ), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "numpy_random_mtrand_shuffle": ( - _in_function("np.random.mtrand.shuffle(values)", parameters="values"), - _WRITES_INTO_EXISTING_ARRAY, - ), - # makes-array-writable - "setflags_write_true": ( - "values = series.to_numpy()\nvalues.setflags(write=True)\nvalues[0] = 1.0\n", - _MAKES_ARRAY_WRITABLE, - ), - "setflags_positional": ("values.setflags(True)\n", _MAKES_ARRAY_WRITABLE), - "setflags_variable": ("values.setflags(write=flag)\n", _MAKES_ARRAY_WRITABLE), - "flags_writeable_attribute": ( - "values.flags.writeable = True\n", - _MAKES_ARRAY_WRITABLE, - ), - "flags_writeable_key": ( - 'values.flags["WRITEABLE"] = True\n', - _MAKES_ARRAY_WRITABLE, - ), - "flags_w_key": ('values.flags["W"] = 1\n', _MAKES_ARRAY_WRITABLE), - "flags_key_parenthesized": ( - _in_function('(values.flags)["W"] = True', parameters="values"), - _MAKES_ARRAY_WRITABLE, - ), - # writes-through-writable-view - "series_array_item": ( - 'frame.person["income"].array[0] = 1.0\n', - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_slice_augmented": ( - "series.array[mask] += 1\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_annotated": ( - "series.array[0]: float = 1.0\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_unpacked": ( - "series.array[0], other = 1.0, 2.0\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_setitem_call": ( - "series.array.__setitem__(0, 1.0)\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "index_array_item": ( - "table.index.array[0] = 7\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_backslash_continuation": ( - "series.\\\narray[0] = 1.0\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_through_asarray": ( - _in_function("values = np.asarray(series.array)", "values[0] = 0.0"), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_through_asarray_keyword": ( - _NUMPY + "np.asarray(a=series.array)[0] = 1\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_through_flip": ( - _NUMPY + "np.flip(np.asarray(series.array))[0] = 1\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_through_to_numpy": ( - "series.array.to_numpy()[0] = 1.0\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_through_astype_without_copy": ( - 'series.array.astype("float64", copy=False)[0] = 1.0\n', - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_through_alias_chain": ( - _in_function("backing = series.array", "values = backing", "values[0] = 0.0"), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_through_conditional": ( - _in_function( - "values = series.array if flag else other", - "values[0] = 1", - parameters="series, other, flag", - ), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_through_either_operand": ( - _in_function( - "values = override or series.array", - "values[0] = 1", - parameters="override, series", - ), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_through_unpacking": ( - _in_function( - "left, right = first.array, second.array", - "left[0] = 1", - parameters="first, second", - ), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_through_loop_target": ( - _in_function( - "for values in (frame[name].array for name in names):", - " values[0] = 1", - parameters="frame, names", - ), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_in_dict_comprehension": ( - _in_function( - "arrays = {name: frame[name].array for name in names}", - 'arrays["income"][0] = 1.0', - parameters="frame, names", - ), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_in_list_written_by_out": ( - _in_function( - "arrays = [np.asarray(series.array)]", - "np.add(arrays[0], 1, out=arrays[0])", - ), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_augmented_name": ( - _in_function("values = np.asarray(series.array)", "values += 1"), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_to_numpy_augmented_name": ( - _in_function("values = series.array.to_numpy()", "values *= 2"), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_fill": ( - _NUMPY + "np.asarray(series.array).fill(0)\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_sort": ( - _NUMPY + "np.asarray(series.array).sort()\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_put": ( - _NUMPY + "np.asarray(series.array).put([0], 1)\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_partition": ( - _NUMPY + "np.asarray(series.array).partition(1)\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_resize": ( - _NUMPY + "np.asarray(series.array).resize(3)\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_setfield": ( - _NUMPY + "np.asarray(series.array).setfield(1, np.int64)\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_byteswap_in_place": ( - _NUMPY + "np.asarray(series.array).byteswap(inplace=True)\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_fillna_without_copy": ( - "series.array.fillna(0.0, copy=False)\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_transposed_view": ( - "series.array.T[0] = 1\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_reshaped_view": ( - "series.array.reshape(-1)[0] = 1.0\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_as_out": ( - _NUMPY + "np.add(series.array, 1, out=series.array)\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_in_place_function": ( - _NUMPY + "np.putmask(np.asarray(series.array), mask, 0)\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_shuffled_by_generator": ( - _in_function("rng.shuffle(np.asarray(series.array))", parameters="rng, series"), - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "series_array_no_copy_array": ( - _NUMPY + "np.array(series.array, copy=False)[0] = 1\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "read_only_view_base": ( - "series.to_numpy().base[0] = 1\n", - _WRITES_THROUGH_WRITABLE_VIEW, - ), - "datetime_asi8": ("series.array.asi8[0] = 0\n", _WRITES_THROUGH_WRITABLE_VIEW), - "index_asi8": ("frame.index.asi8[0] = 0\n", _WRITES_THROUGH_WRITABLE_VIEW), - # pandas-private-attribute - "ndarray_attribute": ( - "values = series.array._ndarray\n", - _PANDAS_PRIVATE_ATTRIBUTE, - ), - "manager_attribute": ( - "blocks = frame._mgr.blocks\n", - _PANDAS_PRIVATE_ATTRIBUTE, - ), - "manager_attribute_on_self": ( - "class Table:\n def blocks(self):\n return self._mgr.blocks\n", - _PANDAS_PRIVATE_ATTRIBUTE, - ), - "series_values_attribute": ( - "raw = series._values\n", - _PANDAS_PRIVATE_ATTRIBUTE, - ), - "masked_data": ("raw = series.array._data\n", _PANDAS_PRIVATE_ATTRIBUTE), - "masked_mask": ("series.array._mask[:] = False\n", _PANDAS_PRIVATE_ATTRIBUTE), - "categorical_codes": ( - "codes = series.cat.codes.array._codes\n", - _PANDAS_PRIVATE_ATTRIBUTE, - ), - "column_array_method": ( - "column = frame._get_column_array(0)\n", - _PANDAS_PRIVATE_ATTRIBUTE, - ), - "column_arrays_iterator": ( - "for column in frame._iter_column_arrays():\n pass\n", - _PANDAS_PRIVATE_ATTRIBUTE, - ), - # numpy-copyto - "copyto": (_NUMPY + "np.copyto(target, source)\n", _NUMPY_COPYTO), - "copyto_through_numpy": ( - "import numpy\nnumpy.copyto(target, source)\n", - _NUMPY_COPYTO, - ), - "copyto_imported": ( - "from numpy import copyto\ncopyto(target, source)\n", - _NUMPY_COPYTO, - ), - "copyto_imported_as_alias": ( - "from numpy import copyto as overwrite\n", - _NUMPY_COPYTO, - ), - "copyto_passed_as_function": ( - "apply_each(np.copyto, pairs)\n", - _NUMPY_COPYTO, - ), - # writes-into-existing-array - "out_parameter": ( - _in_function("np.add(values, 1, out=values)", parameters="values"), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_attribute": ( - _NUMPY + "np.multiply(scale, 2, out=self.buffer)\n", - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_to_numpy": ( - _NUMPY + "np.add(scale, 1, out=series.to_numpy())\n", - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_method_call": ( - "def clip_in_place(values):\n values.clip(0, 1, out=values)\n", - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_array_method_on_parameter": ( - "def running(values):\n values.cumsum(out=values)\n", - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_generator_method": ( - _in_function("rng.random(out=values)", parameters="rng, values"), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_generator_permuted": ( - _in_function("rng.permuted(values, out=values)", parameters="rng, values"), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_rebound_to_existing": ( - _in_function( - "buffer = np.zeros(3)", - "buffer = series.to_numpy()", - "np.add(buffer, 1, out=buffer)", - ), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_slice_of_existing": ( - _in_function( - "buffer = series.to_numpy()", - "buffer = buffer[1:]", - "np.add(buffer, 1, out=buffer)", - ), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_slice_of_parameter": ( - _in_function( - "values = values[1:]", - "np.add(values, 1, out=values)", - parameters="values", - ), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_item_of_new_list_rebound_to_itself": ( - _in_function( - "values = [series.to_numpy()]", - "values = values[0]", - "np.add(values, 1, out=values)", - ), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_tuple": ( - _in_function("np.divmod(7, 2, out=(left, right))", parameters="left, right"), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_positional_ufunc": ( - _in_function("np.add(values, 1, values)", parameters="values"), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_positional_function": ( - _in_function("np.cumsum(values, 0, None, totals)", parameters="values, totals"), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_from_imported_ufunc": ( - "from numpy import add\ndef add_one(values):\n add(values, 1, values)\n", - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_through_local_function_alias": ( - _NUMPY - + "plus = np.add\n" - + "def add_one(values):\n" - + " plus(values, 1, values)\n", - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_keyword_through_function_alias": ( - _in_function( - "plus = np.add", "plus(values, 1, out=values)", parameters="values" - ), - _WRITES_INTO_EXISTING_ARRAY, - ), - "ufunc_at": ( - _in_function("np.add.at(values, [0], 1)", parameters="values"), - _WRITES_INTO_EXISTING_ARRAY, - ), - "ufunc_at_imported": ( - "from numpy import add\ndef count(values):\n add.at(values, [0], 1)\n", - _WRITES_INTO_EXISTING_ARRAY, - ), - "ufunc_at_on_to_numpy": ( - _NUMPY + "np.maximum.at(series.to_numpy(), positions, values)\n", - _WRITES_INTO_EXISTING_ARRAY, - ), - "ufunc_at_on_item_of_new_list": ( - _in_function( - "columns = [frame[name].to_numpy() for name in names]", - "np.add.at(columns[0], [0], 1)", - parameters="frame, names", - ), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_item_of_shallow_dict_copy": ( - _in_function( - "arrays = arrays_by_name.copy()", - 'np.multiply(arrays["x"], 2, out=arrays["x"])', - parameters="arrays_by_name", - ), - _WRITES_INTO_EXISTING_ARRAY, - ), - "numpy_put": ( - _in_function("np.put(values, [0], 1)", parameters="values"), - _WRITES_INTO_EXISTING_ARRAY, - ), - "numpy_place": ( - _in_function("np.place(values, mask, 0)", parameters="values, mask"), - _WRITES_INTO_EXISTING_ARRAY, - ), - "numpy_put_along_axis": ( - _in_function( - "np.put_along_axis(values, positions, 0, axis=0)", - parameters="values, positions", - ), - _WRITES_INTO_EXISTING_ARRAY, - ), - "numpy_nan_to_num_without_copy": ( - _in_function("np.nan_to_num(values, copy=False)", parameters="values"), - _WRITES_INTO_EXISTING_ARRAY, - ), - "numpy_fill_diagonal": ( - _in_function("np.fill_diagonal(matrix, 0)", parameters="matrix"), - _WRITES_INTO_EXISTING_ARRAY, - ), - "numpy_random_shuffle": ( - _in_function("np.random.shuffle(values)", parameters="values"), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_module_array_from_function": ( - _NUMPY + "buffer = np.zeros(3)\ndef add_one():\n np.add(1, 1, out=buffer)\n", - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_global_declared": ( - _in_function( - "global buffer", "buffer = np.zeros(3)", - "np.add(1, 1, out=buffer)", - parameters="", - ), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_loop_target": ( - _in_function( - "for buffer in arrays:", + "with opener() as buffer:", " np.add(buffer, 1, out=buffer)", - parameters="arrays", + parameters="opener", ), _WRITES_INTO_EXISTING_ARRAY, ), - "out_comprehension_target": ( - _in_function("[np.add(a, 1, out=a) for a in arrays]", parameters="arrays"), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_comprehension_target_shadowing_a_new_array": ( + "out_unpacked_shadowing_a_new_array": ( _in_function( - "a = np.zeros(3)", - "return [np.add(a, 1, out=a) for a in arrays]", - parameters="arrays", + "buffer = np.zeros(3)", + "buffer, other = pair", + "np.add(buffer, 1, out=buffer)", + parameters="pair", ), _WRITES_INTO_EXISTING_ARRAY, ), @@ -3070,13 +965,6 @@ def _in_function(*body_lines: str, parameters: str = "series") -> str: _NUMPY + "add_one = lambda values: np.add(values, 1, out=values)\n", _WRITES_INTO_EXISTING_ARRAY, ), - "out_in_a_decorator": ( - _NUMPY - + "@register(np.add(1, 1, out=buffer))\n" - + "def change():\n" - + " return 1\n", - _WRITES_INTO_EXISTING_ARRAY, - ), "out_in_a_decorator_over_a_function_binding_the_name": ( _NUMPY + "@register(np.add(1, 1, out=buffer))\n" @@ -3084,103 +972,27 @@ def _in_function(*body_lines: str, parameters: str = "series") -> str: + " buffer = np.zeros(3)\n", _WRITES_INTO_EXISTING_ARRAY, ), - "out_shallow_copy": ( - _in_function( - "shallow = table.copy(deep=False)", - "np.add(1, 1, out=shallow)", - parameters="table", - ), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_positional_shallow_copy": ( - _in_function( - "shallow = table.copy(False)", - "np.add(1, 1, out=shallow)", - parameters="table", - ), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_array_without_copy": ( - _in_function( - "view = np.array(values, copy=None)", - "np.add(view, 1, out=view)", - parameters="values", - ), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_concatenate_into_existing": ( - _in_function( - "joined = np.concatenate(parts, out=existing)", - "np.add(joined, 1, out=joined)", - parameters="parts, existing", - ), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_one_branch_existing": ( - _in_function( - "buffer = np.zeros(3) if fresh else values", - "np.add(buffer, 1, out=buffer)", - parameters="values, fresh", - ), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_either_operand": ( - _in_function( - "buffer = given or np.zeros(3)", - "np.add(buffer, 1, out=buffer)", - parameters="given", - ), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_ufunc_result_with_output": ( - _in_function( - "total = np.add(values, 1, existing)", - "np.add(total, 1, out=total)", - parameters="values, existing", - ), - _WRITES_INTO_EXISTING_ARRAY, - ), - "out_with_target": ( - _in_function( - "buffer = np.zeros(3)", - "with opener() as buffer:", - " np.add(buffer, 1, out=buffer)", - parameters="opener", - ), + "ufunc_at": ( + _in_function("np.add.at(values, [0], 1)"), _WRITES_INTO_EXISTING_ARRAY, ), - "out_except_target": ( - _in_function( - "buffer = np.zeros(3)", - "try:", - " pass", - "except Exception as buffer:", - " np.add(1, 1, out=buffer)", - parameters="", - ), + "ufunc_at_imported": ( + "from numpy import add\ndef count(values):\n add.at(values, [0], 1)\n", _WRITES_INTO_EXISTING_ARRAY, ), - "out_imported_name": ( - _in_function( - "buffer = np.zeros(3)", - "import buffer", - "np.add(1, 1, out=buffer)", - parameters="", - ), + "out_after_lone_carriage_returns": ( + "import numpy as np\rdef change(values):\r np.add(values, 1, out=values)\r", _WRITES_INTO_EXISTING_ARRAY, ), - "out_match_capture": ( - _in_function( - "buffer = np.zeros(3)", - "match value:", - " case [buffer]:", - " np.add(1, 1, out=buffer)", - parameters="value", - ), + "out_in_a_decorator_over_a_plain_function": ( + _NUMPY + + "@register(np.add(1, 1, out=buffer))\n" + + "def change():\n" + + " return 1\n", _WRITES_INTO_EXISTING_ARRAY, ), - "out_after_lone_carriage_returns": ( - "import numpy as np\rdef change(values):\r np.add(values, 1, out=values)\r", + "ufunc_at_on_to_numpy": ( + _NUMPY + "np.maximum.at(series.to_numpy(), positions, weights)\n", _WRITES_INTO_EXISTING_ARRAY, ), } @@ -3196,254 +1008,37 @@ def test_the_scanner_refuses_each_unprotected_write(source: str, rule: str) -> N #: Snippets the scan must accept: reads, read-only flags, and writes into -#: arrays the same function created. +#: arrays the function created. _ACCEPTED_SNIPPETS = { - # Round-seven cases. - "column_slices_of_copied_and_computed_matrices": _in_function( - "result = matrix.copy()", - "np.clip(result[:, 0], 0, None, out=result[:, 0])", - "weighted = values * weights[:, None]", - "np.maximum(weighted[:, 0], 0, out=weighted[:, 0])", - parameters="matrix, values, weights", - ), - "slice_of_an_extension_array_through_a_name": _in_function( - 'values = frame["x"].array', - "tail = values[1:]", - "tail -= values[:-1]", - parameters="frame", - ), - "slice_of_a_list_of_views_extended": _in_function( - "arrays = [np.asarray(frame[name].array) for name in names]", - "arrays[1:] += [other]", - parameters="frame, names, other", - ), - "extension_arrays_inserted_scaled": _in_function( - "columns = []", - 'columns.insert(0, frame["a"].array)', - "columns[0] *= 2", - parameters="frame", - ), - # Round-six cases. - "string_methods_on_labels_from_views": _in_function( - 'for code, label in zip(frame["c"].array, frame["l"].array):', - ' head, _, rest = label.partition(" ")', - parameters="frame", - ), - "output_array_of_a_call_reused": _in_function( - "share = np.divide(part, total, out=np.zeros_like(part), where=total > 0)", - "np.clip(share, 0, 1, out=share)", - parameters="part, total", - ), - "copy_of_an_array_filled_by_key": _in_function( - "matrix = np.asarray(template).copy()", - "for row, column in enumerate(columns):", - " matrix[row] = frame[column].array", - " matrix[row] /= matrix[row].sum()", - parameters="template, frame, columns", - ), - "numpy_append_is_not_a_fill": _in_function( - 'extended = np.append(frame["x"].array, 0.0)', - "grid = np.copy(base)", - "grid[mask] += 1", - parameters="frame, base, mask", - ), - "extension_arrays_set_by_default_scaled": _in_function( - "columns = {}", - 'columns.setdefault("a", frame["a"].array)', - 'columns["a"] *= 2', - parameters="frame", - ), - "astype_given_an_order_written": _in_function( - "converted = np.asarray(series.array).astype(np.float64, 'C')", - "converted[0] = 1", - ), - # Round-five cases. - "new_array_filled_by_key_from_views": _in_function( - "matrix = np.empty((len(columns), size))", - "for row, column in enumerate(columns):", - " matrix[row] = frame[column].array", - " matrix[row] /= matrix[row].sum()", - " np.divide(matrix[row], 2, out=matrix[row])", - "buffer = np.empty(size)", - "buffer[:] = frame['x'].array", - "buffer[mask] += 1", - parameters="frame, columns, size, mask", - ), - "extension_arrays_in_a_dict_scaled": _in_function( - "columns = {name: frame[name].array for name in names}", - 'columns["income"] *= factor', - parameters="frame, names, factor", - ), - "base_of_an_ordinary_call": _in_function( - "label = graph.node(version).base", - 'label += "/x"', - "columns = holder.base", - 'columns["x"] = 1', - parameters="graph, version, holder", - ), - "running_total_from_a_constant": _in_function( - "total = 0.0", - "for column in columns:", - " total = total + frame[column].to_numpy()", - "np.divide(total, len(columns), out=total)", - parameters="frame, columns", - ), - # Round-four cases. - "zip_rows_paired_inside_enumerate": _in_function( - 'for position, (row, value) in enumerate(zip(matrix, frame["x"].array)):', - " row[:] = value", - parameters="matrix, frame", - ), - "zip_rows_paired_inside_list": _in_function( - 'for row, value in list(zip(matrix, frame["x"].array)):', - " row[:] = value", - parameters="matrix, frame", - ), - "comprehension_target_over_a_new_array": _in_function( - "grid = np.zeros((3, 3))", - "[np.add(row, 1, out=row) for row in grid]", - parameters="", - ), - "pieces_of_a_new_array": _in_function( - "buffer = np.zeros(size)", - "for chunk in np.array_split(buffer, parts):", - " np.multiply(chunk, 2, out=chunk)", - parameters="size, parts", - ), - "extension_array_name_augmented": _in_function( - 'total = frame["a"].array', - 'total += frame["b"].array', - parameters="frame", - ), - "scalar_of_a_view_augmented": _in_function( - 'for value in frame["x"].array:', - " value -= 1", - parameters="frame", - ), - "clip_of_a_view_written": _in_function( - 'clipped = np.clip(frame["x"].array, 0, None)', - "clipped[clipped > 10] = 10", - parameters="frame", - ), - # Round-three cases. - "accumulating_scalars_of_views_into_a_dict": ( - "from collections import defaultdict\n" - + _in_function( - "totals = defaultdict(float)", - 'for group, weight in zip(frame["group"].array, frame["weight"].array):', - " totals[group] += weight", - parameters="frame", - ) - ), - "running_total_of_view_columns": _in_function( - "total = np.zeros(size)", - "for column in columns:", - " total += frame[column].array", - "total[total < 0] = 0", - "np.maximum(total, 0, out=total)", - parameters="frame, columns, size", - ), - "zip_pairs_rows_of_a_parameter_with_a_view": _in_function( - 'for row, value in zip(matrix, frame["x"].array):', - " row[:] = value", - parameters="matrix, frame", - ), - "views_and_items_of_new_arrays": _in_function( - "grid = np.zeros((3, 3)).T", - "np.add(grid, 1, out=grid)", - "matrix = np.ones((3, 3))", - "np.fill_diagonal(matrix.T, 0)", - "for row in np.zeros((3, 3)):", - " np.add(row, 1, out=row)", - "first, second = np.zeros((2, 3))", - "np.add(first, 1, out=first)", - parameters="", - ), - "copies_given_by_keyword_and_position": _in_function( - "values = np.asarray(series.array, copy=True)", - "values[0] = 1", - "other = series.array.to_numpy(float, True)", - "other[0] = 1", - ), - "starred_rest_replaced": _in_function( - "arrays = [frame[name].array for name in names]", - "first, *rest = arrays", - "rest[0] = np.zeros(3)", - parameters="frame, names", - ), - "view_times_a_list": _in_function( - "weights = [1.0, 2.0]", - "scaled = series.array * weights", - "scaled[0] = 0", - ), - "ordinary_base_attribute": _in_function( - "columns = holder.base", 'columns["x"] = 1', parameters="holder" - ), - # Round-two cases. - "long_chain_of_views_of_a_new_array": _in_function( - "chain_0 = np.zeros(64)", - *( - f"chain_{index} = chain_{index - 1}[1:] if flag else chain_{index - 1}[:-1]" - for index in range(1, 40) - ), - "np.add(chain_39, 1, out=chain_39)", - parameters="flag", - ), - "generator_draws": _in_function( - "draws = rng.normal(size=size)", - "np.multiply(draws, 2, out=draws)", - "sample = np.random.default_rng(seed).random(size)", - "np.add(sample, 1, out=sample)", - parameters="rng, seed, size", - ), - "flattened_reshaped_and_listed_new_arrays": _in_function( - "flat = values.flatten()", - "np.add(flat, 1, out=flat)", - "grid = np.empty(6).reshape(2, 3)", - "np.add(grid, 1, out=grid)", - "listed = np.asarray([1.0, 2.0])", - "np.add(listed, 1, out=listed)", - parameters="values", - ), - "ufunc_reductions_and_interpolation": _in_function( - "peaks = np.maximum.accumulate(values)", - "np.add(peaks, 1, out=peaks)", - "curve = np.interp(points, xp, fp)", - "np.add(curve, 1, out=curve)", - parameters="values, points, xp, fp", - ), - "positional_copy_to_numpy": _in_function( - "values = series.to_numpy(float, True)", "np.add(values, 1, out=values)" - ), - "copy_of_a_view_written": _in_function( - "encoded = series.array.asi8.copy()", "encoded[0] = 0" - ), - "list_of_a_view_reassigned": _in_function( - "items = list(series.array)", "items[0] = 1" - ), - "frame_holding_a_view_written_by_column": _in_function( - "carried = table.copy()", - "carried['id'] = replacement.array", - "tables = {}", - "tables['person'] = carried", - "tables['person']['income'] = aligned.array", - parameters="table, replacement, aligned", - ), - "arithmetic_on_a_view_written": _in_function( - "doubled = np.asarray(series.array) * 2", "doubled[0] = 0" - ), - "scipy_ufunc_into_new_array": ( - "import numpy as np\n" - + "import scipy.special\n" - + "def change(values):\n" - + " result = np.empty(3)\n" - + " scipy.special.expit(values, out=result)\n" - ), "setflags_read_only": "values.setflags(write=False)\nvalues.setflags(write=0)\n", "setflags_alignment_only": "values.setflags(align=True)\n", "flags_read_only": ( 'values.flags.writeable = False\nvalues.flags["WRITEABLE"] = False\n' ), + "series_array_reads": ( + "for value in series.array:\n" + + " total += value\n" + + "index = pd.Index(series.array, name='id')\n" + + "first = series.array[0]\n" + ), + "own_array_and_private_state": ( + "class Grid:\n" + + " def set(self, row, value):\n" + + " self.array[row] = value\n" + + " self._values[row] = value\n" + + " self._data.append(value)\n" + + " @classmethod\n" + + " def empty(cls):\n" + + " return cls._mask\n" + ), + "array_function_not_attribute": ( + _NUMPY + + "import pandas as pd\n" + + "values = np.array(series)\n" + + "values[0] = 1\n" + + "codes = pd.array([1, 2])\n" + + "codes[0] = 3\n" + ), "out_new_array_inline": ( _NUMPY + "share = np.divide(part, total, out=np.zeros_like(part), where=total > 0)\n" @@ -3454,98 +1049,25 @@ def test_the_scanner_refuses_each_unprotected_write(source: str, rule: str) -> N "np.cumsum(weights, out=totals[1:])", parameters="weights", ), - "out_new_array_row": _in_function( - "grid = np.zeros((2, 3))", "np.add(1, 1, out=grid[0])", parameters="" - ), - "out_deep_copy": _in_function( + "out_copy": _in_function( "total = first.copy()", "np.add(total, later, out=total)", parameters="first, later", ), - "out_deep_copy_in_order": _in_function( - "total = first.copy('C')", - "np.add(total, later, out=total)", - parameters="first, later", - ), - "out_copied_to_numpy": _in_function( - "values = series.to_numpy(dtype=float, copy=True)", - "np.add(values, 1, out=values)", - ), "out_same_array_as_input": _in_function( "draws = np.empty(count)", "np.minimum(draws, 1.0, out=draws)", "return draws", parameters="count", ), - "out_chained_and_conditional_names": _in_function( - "first = second = np.zeros(3)", - "alias = second", - "chosen = np.ones(3) if wide else alias", - "chosen += 1", - "np.add(values, 1, out=chosen)", - "np.add(values, 1, out=first)", - parameters="values, wide", - ), - "out_array_with_copy": _in_function( - "owned = np.array(values)", - "copied = np.array(values, copy=True)", - "np.add(owned, 1, out=owned)", - "np.add(copied, 1, out=copied)", - parameters="values", - ), - "out_none": _NUMPY + "np.add(left, right, out=None)\n", - "out_none_pair": _NUMPY + "np.divmod(left, 2, out=(None, None))\n", - "ufunc_at_new_array": _in_function( - "counts = np.zeros(size, dtype=np.int64)", - "np.add.at(counts, positions, 1)", - parameters="positions, size", - ), - "in_place_function_new_array": _in_function( - "matrix = np.ones((size, size))", - "np.fill_diagonal(matrix, 0)", - parameters="size", - ), - "ufunc_without_out": _NUMPY + "total = np.add(left, right)\n", - "array_function_not_attribute": ( - _NUMPY - + "import pandas as pd\n" - + "values = np.array(series)\n" - + "values[0] = 1\n" - + "codes = pd.array([1, 2])\n" - + "codes[0] = 3\n" - ), - "series_array_reads": ( - "for value in series.array:\n" - + " total += value\n" - + "index = pd.Index(series.array, name='id')\n" - + "first = series.array[0]\n" - ), - "series_array_deep_copy_written": ( - "values = series.array.to_numpy(copy=True)\nvalues[0] = 1\n" - ), - "series_array_byteswap_copy": ( - _NUMPY + "swapped = np.asarray(series.array).byteswap()\n" - ), - "own_array_attribute": ( - "class Grid:\n def set(self, row, value):\n self.array[row] = value\n" - ), - "own_private_state": ( - "class Catalog:\n" - + " def add(self, key, value):\n" - + " self._values[key] = value\n" - + " self._data.append(value)\n" - + " @classmethod\n" - + " def empty(cls):\n" - + " return cls._mask\n" - ), - "subscript_write_into_new_array": _in_function( - "marks = np.zeros(size)", "marks[0] = 1", parameters="size" - ), - "out_keyword_of_workspace_functions": ( - "launch(pool_manifest=manifest, out=args.out)\n" - + "report.write(rows, out=destination)\n" + "out_rebound_between_new_arrays": _in_function( + "out = np.zeros(3)", + "np.add.at(out, positions, weights)", + "out = np.where(mask, out, 0.0)", + "np.multiply(out, 2, out=out)", + parameters="positions, weights, mask", ), - "none_placeholder_then_copy": _in_function( + "out_none_placeholder_then_copy": _in_function( "total: np.ndarray | None = None", "for current in slices:", " if total is None:", @@ -3554,39 +1076,24 @@ def test_the_scanner_refuses_each_unprotected_write(source: str, rule: str) -> N " np.add(total, current, out=total)", parameters="slices", ), - "list_display_shuffled": _in_function( - "values: list[float] = []", - "values.extend(draws)", - "values = values[:3]", - "np.random.shuffle(values)", - parameters="draws", - ), - "list_builtin_shuffled": _in_function( - "order = list(range(size))", "np.random.shuffle(order)", parameters="size" - ), - "random_results": _in_function( - "order = np.random.permutation(size)", - "np.add(order, 1, out=order)", - "chosen = np.random.choice(values, 3)", - "np.add(chosen, 1, out=chosen)", - parameters="size, values", - ), - "generator_method_into_new_array": _in_function( - "draws = np.empty(3)", "rng.random(out=draws)", parameters="rng" - ), - "where_ufunc_arithmetic_and_comparison_results": _in_function( - "out = np.zeros(3)", - "np.add.at(out, positions, values)", - "out = np.where(mask, out, 0.0)", - "np.multiply(out, 2, out=out)", + "out_ufunc_and_array_results": _in_function( "scaled = np.exp(values)", "np.multiply(scaled, 2, out=scaled)", - "total = left + right", - "np.add(total, 1, out=total)", - "positive = left > 0", - "np.logical_not(positive, out=positive)", - parameters="positions, values, mask, left, right", + "owned = np.array(values)", + "np.add(owned, 1, out=owned)", + ), + "out_none": _NUMPY + "np.add(left, right, out=None)\n", + "out_none_pair": _NUMPY + "np.divmod(left, 2, out=(None, None))\n", + "out_keyword_of_workspace_functions": ( + "launch(pool_manifest=manifest, out=args.out)\n" + + "report.write(rows, out=destination)\n" + ), + "ufunc_at_new_array": _in_function( + "counts = np.zeros(size, dtype=np.int64)", + "np.add.at(counts, positions, 1)", + parameters="positions, size", ), + "ufunc_without_out": _NUMPY + "total = np.add(left, right)\n", } @@ -3620,73 +1127,11 @@ def test_a_finding_names_its_file_line_function_and_digest() -> None: def test_a_changed_function_changes_the_finding_key() -> None: - original = _in_function("np.fill_diagonal(matrix, 0)", parameters="matrix") - changed = _in_function( - "matrix = matrix.T", "np.fill_diagonal(matrix, 0)", parameters="matrix" - ) + original = _in_function("np.add.at(values, [0], 1)") + changed = _in_function("values = values.T", "np.add.at(values, [0], 1)") (before,) = scan_source(original, "pkg/module.py") (after,) = scan_source(changed, "pkg/module.py") assert before.code == after.code assert before.key != after.key - - -def test_a_deep_chain_of_comprehension_generators_is_scanned_quickly() -> None: - """Comprehension loop targets are cached, for both rules. Without the - cache every generator doubles the work, so forty of them would take - days; the alarm turns that into a failure instead of a hang.""" - - if not hasattr(signal, "setitimer"): - pytest.skip("needs signal.setitimer") - generators = " ".join( - f"for chain_{index} in zip(chain_{index - 1}, chain_{index - 1})" - for index in range(1, 41) - ) - source = _in_function("chain_0 = series.array", f"[chain_40.fill(0) {generators}]") - branches = " ".join( - f"for chain_{index} in (chain_{index - 1} if flag else chain_{index - 1})" - for index in range(1, 41) - ) - newness_source = _in_function( - "chain_0 = np.zeros((2, 2))", - f"[np.add(chain_40, 1, out=chain_40) {branches}]", - parameters="flag", - ) - - def stop(_signal_number: int, _frame: object) -> None: - raise TimeoutError("the scan did not finish within 30 seconds") - - previous = signal.signal(signal.SIGALRM, stop) - signal.setitimer(signal.ITIMER_REAL, 30) - try: - findings = scan_source(source, "snippet.py") - findings += scan_source(newness_source, "snippet.py") - finally: - signal.setitimer(signal.ITIMER_REAL, 0) - signal.signal(signal.SIGALRM, previous) - - assert findings == [] - - -def test_a_module_that_fails_to_import_does_not_stop_the_scan( - monkeypatch: pytest.MonkeyPatch, -) -> None: - def import_module(name: str) -> object: - if name.startswith("numpy.broken"): - raise RuntimeError("this module cannot be imported here") - return importlib.import_module(name) - - monkeypatch.setitem(globals(), "_import_module", import_module) - _library_object.cache_clear() - _positional_outputs.cache_clear() - try: - findings = scan_source( - _in_function("np.broken.helper(values, out=values)", parameters="values"), - "snippet.py", - ) - finally: - _library_object.cache_clear() - _positional_outputs.cache_clear() - - assert [finding.rule for finding in findings] == [_WRITES_INTO_EXISTING_ARRAY] From 810eac964b2ab0f5af5003d9bb9ffd97d13eaedb Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:55:35 +0400 Subject: [PATCH 10/15] Fix review findings in the syntactic write check - np.array(copy=True) and to_numpy(copy=True), the copies the failure message suggests, count as created, and so do arithmetic, comparisons and random Generator draws. - A .copy() counts as created only whole or sliced: an item of a dict or list copy is a shared item. - Annotations without a value are not writes. - Files are read as utf-8-sig, so a byte-order mark cannot stop the scan. - NumPy imports are found by walking statements only. - New self-tests cover a parameter rebound on one path, a lambda parameter, a name only ever None, nonlocal and import bindings. - A new test fails if a function the reviewed exemption's reason rests on changes. Frame: the _adopt docstring says which writes through .values reach the other frame, and names the folders the check scans. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/frame/bundle.py | 18 +- .../shared/test_shared_buffer_writes.py | 245 +++++++++++++++--- 2 files changed, 222 insertions(+), 41 deletions(-) diff --git a/packages/microcosm-frame/src/microcosm/frame/bundle.py b/packages/microcosm-frame/src/microcosm/frame/bundle.py index 8c69121c2d..e691826e7d 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -149,14 +149,16 @@ def _adopt( ``.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 the workspace's source), and through what ``.values`` and ``to_numpy()`` return for - extension-typed columns. ``.values`` returns the column's own - extension array, for example for the nullable integer, float and - boolean types, ``category`` and python-backed strings, and under - pandas 2.x for 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. + 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 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 2b6461f17c..f764da699e 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 @@ -41,18 +41,24 @@ ``np..at``, which writes even into a read-only array, unless that array is created in the function. Created means: - - a call of a NumPy function that allocates + - a call, not itself given ``out=``, of a NumPy function that allocates (``_ALLOCATING_NUMPY_FUNCTIONS``: ``np.zeros``, ``np.empty_like``, - ``np.where``, ...), of a ufunc, or of ``np.array`` without ``copy=``, - not itself given ``out=``; - - ``.copy()`` with no arguments; - - a subscript of one of these; + ``np.where``, ...), of a ufunc, of ``np.array`` without ``copy=`` or + with ``copy=True``, of ``.to_numpy(copy=True)``, or of a random + ``Generator`` draw (``_RANDOM_DRAW_METHODS``: ``rng.random(n)``, ...); + - arithmetic or a comparison (``a * b``, ``a > 0``); + - ``.copy()`` with no arguments, or a slice of it, but not an item of + it, because a copy of a dict or list shares its items; + - a subscript of the others; - a local name, or a subscript of one, whose every assignment in the function is one of these or ``None``, with at least one that is not ``None``. A parameter, a name declared ``global`` or ``nonlocal``, and a name bound any other way in the function (a loop, comprehension or ``with`` target, unpacking, an import) are not created. + ``.astype()`` does not count as created: a pandas object's conversion + to its own type shares its memory. + ``setflags``, ``Series.array[i] = value``, ``._ndarray``, ``._mgr``, ``np.copyto`` and ``out=`` are the writes first identified as unprotected. ``ufunc.at`` and the other private attributes were added after probes showed @@ -130,6 +136,20 @@ ), } +#: The functions a reviewed reason rests on, by repository-relative path and +#: name, with a digest of each one's source. A change to one needs the +#: reasons that name it reviewed again. +_REVIEWED_HELPERS: dict[tuple[str, str], str] = { + ( + "tools/verify_uk_identity_stability.py", + "_pre_clone_household_weights", + ): "5edc525581d7", + ( + "tools/verify_uk_identity_stability.py", + "_pre_residential_household_weights", + ): "e39cc12da417", +} + _MAKES_ARRAY_WRITABLE = "makes-array-writable" _WRITES_THROUGH_SERIES_ARRAY = "writes-through-series-array" _PANDAS_PRIVATE_ATTRIBUTE = "pandas-private-attribute" @@ -184,6 +204,22 @@ } ) +#: NumPy random Generator methods that draw a new array. +_RANDOM_DRAW_METHODS = frozenset( + { + "random", + "normal", + "uniform", + "integers", + "choice", + "permutation", + "standard_normal", + "exponential", + "poisson", + "binomial", + } +) + #: ndarray methods, and NumPy random Generator methods, that take ``out``. _METHODS_WITH_OUT = frozenset( { @@ -224,6 +260,10 @@ _NESTED_SCOPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda) +#: What ``_created_kind`` returns: a new array, or a ``.copy()``. +_NEW_ARRAY = "new array" +_COPY = "copy" + @dataclass(frozen=True) class Finding: @@ -257,6 +297,18 @@ def _keyword(call: ast.Call, name: str) -> ast.keyword | None: return next((keyword for keyword in call.keywords if keyword.arg == name), None) +def _is_true_constant(expression: ast.expr) -> bool: + return isinstance(expression, ast.Constant) and expression.value is True + + +def _is_slice(index: ast.expr) -> bool: + """Whether a subscript's index is a slice (``a[1:]``, ``a[:, 0:2]``).""" + + if isinstance(index, ast.Tuple): + return any(isinstance(part, ast.Slice) for part in index.elts) + return isinstance(index, ast.Slice) + + def _is_own_object(expression: ast.expr) -> bool: return isinstance(expression, ast.Name) and expression.id in _OWN_OBJECT_NAMES @@ -269,12 +321,25 @@ def _is_series_array(expression: ast.expr) -> bool: ) +def _statements(tree: ast.Module) -> Iterator[ast.AST]: + """Every statement at any depth, without entering expressions.""" + + stack: list[ast.AST] = list(reversed(tree.body)) + while stack: + node = stack.pop() + yield node + for field_name in ("body", "orelse", "finalbody", "handlers", "cases"): + children = getattr(node, field_name, None) + if isinstance(children, list): + stack.extend(reversed(children)) + + class _NumpyNames: """The names one module binds to NumPy (``np``, ``from numpy import add``).""" def __init__(self, tree: ast.Module) -> None: self._aliases: dict[str, str] = {} - for node in ast.walk(tree): + for node in _statements(tree): if isinstance(node, ast.Import): for alias in node.names: if alias.name == "numpy" or alias.name.startswith("numpy."): @@ -495,40 +560,52 @@ def _report(self, node: ast.AST, rule: str) -> None: # Created arrays -------------------------------------------------------- - def _allocates(self, call: ast.Call) -> bool: - if _keyword(call, "out") is not None: - return False - function = call.func - if ( - isinstance(function, ast.Attribute) - and function.attr == "copy" - and not call.args - and not call.keywords - ): - return True + def _created_kind(self, expression: ast.expr) -> str | None: + """``"array"`` for a new array, ``"copy"`` for a ``.copy()`` (which + may be a container's copy, sharing its items), or ``None``.""" + + if isinstance(expression, (ast.BinOp, ast.UnaryOp, ast.Compare)): + return _NEW_ARRAY + if not isinstance(expression, ast.Call) or _keyword(expression, "out"): + return None + function = expression.func + if isinstance(function, ast.Attribute): + if function.attr == "copy": + plain = not expression.args and not expression.keywords + return _COPY if plain else None + if function.attr == "to_numpy": + copy = _keyword(expression, "copy") + return _NEW_ARRAY if copy and _is_true_constant(copy.value) else None + if function.attr in _RANDOM_DRAW_METHODS: + return _NEW_ARRAY name = self._numpy.resolve(function) if name is None: - return False + return None if name == "numpy.array": - return _keyword(call, "copy") is None + copy = _keyword(expression, "copy") + return _NEW_ARRAY if copy is None or _is_true_constant(copy.value) else None if name.removeprefix("numpy.") in _ALLOCATING_NUMPY_FUNCTIONS: - return True - return isinstance(_numpy_object(name), np.ufunc) + return _NEW_ARRAY + return _NEW_ARRAY if isinstance(_numpy_object(name), np.ufunc) else None def _is_created(self, expression: ast.expr) -> bool: + items_taken = False while isinstance(expression, ast.Subscript): + items_taken = items_taken or not _is_slice(expression.slice) expression = expression.value - if isinstance(expression, ast.Call): - return self._allocates(expression) - if not isinstance(expression, ast.Name): - return False - assignments = self._scopes[-1].assignments_of(expression.id) - if assignments is None: + if isinstance(expression, ast.Name): + assignments = self._scopes[-1].assignments_of(expression.id) + if assignments is None: + return False + values = [value for value in assignments if not _is_none(value)] + if not values or any(value is None for value in values): + return False + kinds = [self._created_kind(value) for value in values] + else: + kinds = [self._created_kind(expression)] + if None in kinds: return False - values = [value for value in assignments if not _is_none(value)] - return bool(values) and all( - isinstance(value, ast.Call) and self._allocates(value) for value in values - ) + return not (items_taken and _COPY in kinds) # Rules ----------------------------------------------------------------- @@ -606,7 +683,9 @@ def visit_Assign(self, node: ast.Assign) -> None: self.generic_visit(node) def visit_AnnAssign(self, node: ast.AnnAssign) -> None: - self._check_target(node, node.target, node.value) + # An annotation without a value writes nothing. + if node.value is not None: + self._check_target(node, node.target, node.value) self.generic_visit(node) def visit_AugAssign(self, node: ast.AugAssign) -> None: @@ -669,7 +748,8 @@ def workspace_scan() -> _WorkspaceScan: for path in scanned_files(_REPOSITORY): relative = path.relative_to(_REPOSITORY).as_posix() paths.add(relative) - findings.extend(scan_source(path.read_text(encoding="utf-8"), relative)) + # utf-8-sig drops a byte-order mark, which ast.parse refuses. + findings.extend(scan_source(path.read_text(encoding="utf-8-sig"), relative)) return _WorkspaceScan(frozenset(paths), tuple(findings)) @@ -705,6 +785,28 @@ def test_every_reviewed_finding_still_occurs(workspace_scan: _WorkspaceScan) -> ) +def test_the_functions_reviewed_reasons_rest_on_are_unchanged() -> None: + changed: list[str] = [] + for (relative, name), digest in _REVIEWED_HELPERS.items(): + source = (_REPOSITORY / relative).read_text(encoding="utf-8-sig") + function = next( + node + for node in ast.walk(ast.parse(source)) + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + and node.name == name + ) + segment = ast.get_source_segment(source, function) or "" + current = hashlib.sha256(segment.encode("utf-8")).hexdigest()[:12] + if current != digest: + changed.append(f"{relative}:{name} now has digest {current!r}") + + assert not changed, ( + "A reviewed reason in _REVIEWED_FINDINGS rests on these functions, " + "which changed. Review the reasons that name them again, then update " + "_REVIEWED_HELPERS.\n" + "\n".join(changed) + ) + + def test_the_scan_covers_every_package_and_the_us_frame_building_code( workspace_scan: _WorkspaceScan, ) -> None: @@ -794,6 +896,61 @@ def _in_function(*body_lines: str, parameters: str = "values") -> str: "series.array[0]: float = 1.0\n", _WRITES_THROUGH_SERIES_ARRAY, ), + "out_parameter_rebound_on_one_path": ( + _in_function( + "if flag:", + " values = np.zeros(3)", + "np.add.at(values, [0], 1)", + parameters="values, flag", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_lambda_parameter_shadowing_a_module_array": ( + _NUMPY + + "values = np.zeros(3)\n" + + "add_one = lambda values: np.add(values, 1, out=values)\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_name_only_ever_none": ( + _in_function("buffer = None", "np.add(1, 1, out=buffer)", parameters=""), + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_nonlocal_name": ( + _NUMPY + + "def outer():\n" + + " buffer = np.zeros(3)\n" + + " def inner():\n" + + " nonlocal buffer\n" + + " buffer = np.zeros(3)\n" + + " np.add(1, 1, out=buffer)\n" + + " return inner\n", + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_imported_name_shadowing_a_new_array": ( + _in_function( + "buffer = np.zeros(3)", + "import buffer", + "np.add(1, 1, out=buffer)", + parameters="", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), + "ufunc_at_on_an_item_of_a_copied_dict": ( + _in_function( + "updated = columns.copy()", + 'np.add.at(updated["income"], [0], 100)', + parameters="columns", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_astype": ( + _in_function( + "converted = series.astype(float)", + "np.add(converted, 1, out=converted)", + parameters="series", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), "series_array_unpacked": ( "series.array[0], other = 1.0, 2.0\n", _WRITES_THROUGH_SERIES_ARRAY, @@ -1094,6 +1251,28 @@ def test_the_scanner_refuses_each_unprotected_write(source: str, rule: str) -> N parameters="positions, size", ), "ufunc_without_out": _NUMPY + "total = np.add(left, right)\n", + "out_copies_the_failure_message_suggests": _in_function( + "weights = np.array(frame.w, copy=True)", + "np.add.at(weights, positions, 1)", + "values = frame.x.to_numpy(copy=True)", + "np.add(values, 1, out=values)", + parameters="frame, positions", + ), + "out_arithmetic_and_draws": _in_function( + "product = left * right", + "np.add(product, 1, out=product)", + "positive = left > 0", + "np.logical_not(positive, out=positive)", + "draws = rng.random(size)", + "np.multiply(draws, 2, out=draws)", + parameters="left, right, rng, size", + ), + "out_slice_of_a_copy": _in_function( + "totals = first.copy()", + "np.cumsum(later, out=totals[1:])", + parameters="first, later", + ), + "annotation_without_a_value": ('series.array[0]: float\nvalues.flags["W"]: bool\n'), } From a21e20b4564dc098229943edac2a56c1b590cc4f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:07:11 +0400 Subject: [PATCH 11/15] Re-pin the calibrate and simulate graph parity cases Their implementation hashes include the source of microcosm/frame/bundle.py, which this branch changes. Re-pinned with tools/graph_parity_repin.py under Python 3.14 (the pinned arm64/darwin/py3.14 platform): only the implementation hash and node keys moved, and the pinned direct.csv bytes are unchanged. 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 da0abddedc..c5322d9bcd 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":"3df328c2d5f449de45a543be8b5f4caf0cf2ff417542b0dc1251c7e4bfd33e64","kernel":"calibrate.adam@1","node":"calibrate","node_key":"98df2301f04fc79ffe90a07306a51d4fa8ad0cda6777d480ae6c172adef20dfe","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"98df2301f04fc79ffe90a07306a51d4fa8ad0cda6777d480ae6c172adef20dfe"}},"seed":0} +{"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} 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 1a3cecc086..7d502aba55 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":"60664a4f28b84a693dd5f3b916ad04be6b9d160c090e549659a674b0c2d81e42","kernel":"simulate.rules@1","node":"simulate","node_key":"5968c72d2bb1f0c909946e3a75d6757ba3bd5d945c4dd95e2c9c680a993f3536","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"5968c72d2bb1f0c909946e3a75d6757ba3bd5d945c4dd95e2c9c680a993f3536"}},"seed":null} +{"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} From 6315f92ea2e4072b776bc93f510485c53ecefda6 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:09:50 +0400 Subject: [PATCH 12/15] Fix the second review of the syntactic write check - np.copy(x) counts as created; the .copy() method rule no longer hides it. - A name assigned a subscript of a created array (np.sort(x)[::-1]) counts as created. - +, * and | count like .copy(): whole or sliced they are new, but an item is not, since joining lists or dicts shares their items. - The reviewed-helper test finds functions by qualified name and refuses a name defined more than once. - A new test checks that every output in out=(a, b) is reported. Co-Authored-By: Claude Opus 5.5 --- .../shared/test_shared_buffer_writes.py | 95 ++++++++++++++++--- 1 file changed, 81 insertions(+), 14 deletions(-) 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 f764da699e..d3a6ec66cc 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 @@ -46,9 +46,10 @@ ``np.where``, ...), of a ufunc, of ``np.array`` without ``copy=`` or with ``copy=True``, of ``.to_numpy(copy=True)``, or of a random ``Generator`` draw (``_RANDOM_DRAW_METHODS``: ``rng.random(n)``, ...); - - arithmetic or a comparison (``a * b``, ``a > 0``); - - ``.copy()`` with no arguments, or a slice of it, but not an item of - it, because a copy of a dict or list shares its items; + - arithmetic or a comparison (``a - b``, ``a > 0``); + - ``.copy()`` with no arguments, or ``+``, ``*`` or ``|`` (which also + join lists and dicts), or a slice of these, but not an item of them, + because a copy or join of a dict or list shares its items; - a subscript of the others; - a local name, or a subscript of one, whose every assignment in the function is one of these or ``None``, with at least one that is not @@ -561,15 +562,30 @@ def _report(self, node: ast.AST, rule: str) -> None: # Created arrays -------------------------------------------------------- def _created_kind(self, expression: ast.expr) -> str | None: - """``"array"`` for a new array, ``"copy"`` for a ``.copy()`` (which - may be a container's copy, sharing its items), or ``None``.""" + """``_NEW_ARRAY`` for a new array; ``_COPY`` for a new object whose + items may be shared (a ``.copy()``, or ``+``, ``*`` or ``|``, which + also join containers); ``None`` for anything else.""" - if isinstance(expression, (ast.BinOp, ast.UnaryOp, ast.Compare)): + items_taken = False + while isinstance(expression, ast.Subscript): + items_taken = items_taken or not _is_slice(expression.slice) + expression = expression.value + kind = self._whole_created_kind(expression) + if kind == _COPY and items_taken: + return None + return kind + + def _whole_created_kind(self, expression: ast.expr) -> str | None: + if isinstance(expression, ast.BinOp): + joins = isinstance(expression.op, (ast.Add, ast.Mult, ast.BitOr)) + return _COPY if joins else _NEW_ARRAY + if isinstance(expression, (ast.UnaryOp, ast.Compare)): return _NEW_ARRAY if not isinstance(expression, ast.Call) or _keyword(expression, "out"): return None function = expression.func - if isinstance(function, ast.Attribute): + name = self._numpy.resolve(function) + if name is None and isinstance(function, ast.Attribute): if function.attr == "copy": plain = not expression.args and not expression.keywords return _COPY if plain else None @@ -578,7 +594,6 @@ def _created_kind(self, expression: ast.expr) -> str | None: return _NEW_ARRAY if copy and _is_true_constant(copy.value) else None if function.attr in _RANDOM_DRAW_METHODS: return _NEW_ARRAY - name = self._numpy.resolve(function) if name is None: return None if name == "numpy.array": @@ -785,16 +800,28 @@ def test_every_reviewed_finding_still_occurs(workspace_scan: _WorkspaceScan) -> ) +def _definition(tree: ast.Module, qualified_name: str) -> ast.AST: + """The one function or class whose qualified name (``Class.method``) is + ``qualified_name``.""" + + found: list[ast.AST] = [] + stack: list[tuple[str, ast.AST]] = [("", node) for node in tree.body] + while stack: + prefix, node = stack.pop() + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + name = f"{prefix}{node.name}" + if name == qualified_name: + found.append(node) + stack.extend((f"{name}.", child) for child in node.body) + assert len(found) == 1, f"{qualified_name} is defined {len(found)} times" + return found[0] + + def test_the_functions_reviewed_reasons_rest_on_are_unchanged() -> None: changed: list[str] = [] for (relative, name), digest in _REVIEWED_HELPERS.items(): source = (_REPOSITORY / relative).read_text(encoding="utf-8-sig") - function = next( - node - for node in ast.walk(ast.parse(source)) - if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) - and node.name == name - ) + function = _definition(ast.parse(source), name) segment = ast.get_source_segment(source, function) or "" current = hashlib.sha256(segment.encode("utf-8")).hexdigest()[:12] if current != digest: @@ -935,6 +962,22 @@ def _in_function(*body_lines: str, parameters: str = "values") -> str: ), _WRITES_INTO_EXISTING_ARRAY, ), + "ufunc_at_on_an_item_of_a_merged_dict": ( + _in_function( + 'merged = columns | {"w": weights}', + 'np.add.at(merged["income"], [0], 100)', + parameters="columns, weights", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), + "ufunc_at_on_an_item_of_joined_lists": ( + _in_function( + "joined = parts + extra", + "np.add.at(joined[0], [0], 1)", + parameters="parts, extra", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), "ufunc_at_on_an_item_of_a_copied_dict": ( _in_function( "updated = columns.copy()", @@ -1267,6 +1310,18 @@ def test_the_scanner_refuses_each_unprotected_write(source: str, rule: str) -> N "np.multiply(draws, 2, out=draws)", parameters="left, right, rng, size", ), + "out_numpy_copy": _in_function( + "buffer = np.copy(values)", + "np.add(buffer, 1, out=buffer)", + "np.add.at(np.copy(values), [0], 1)", + ), + "out_names_bound_to_subscripts_of_new_arrays": _in_function( + "ordered = np.sort(values)[::-1]", + "np.cumsum(ordered, out=ordered)", + "row = np.zeros((2, size))[0]", + "np.add(row, 1, out=row)", + parameters="values, size", + ), "out_slice_of_a_copy": _in_function( "totals = first.copy()", "np.cumsum(later, out=totals[1:])", @@ -1314,3 +1369,15 @@ def test_a_changed_function_changes_the_finding_key() -> None: assert before.code == after.code assert before.key != after.key + + +def test_every_output_in_an_out_tuple_is_checked() -> None: + both_existing = _in_function( + "np.divmod(7, 2, out=(left, right))", parameters="left, right" + ) + second_existing = _in_function( + "np.divmod(7, 2, out=(np.zeros(1), right))", parameters="right" + ) + + assert len(scan_source(both_existing, "snippet.py")) == 2 + assert len(scan_source(second_existing, "snippet.py")) == 1 From 8e4d8d667f2f242fd2c39d91ce204e93778471c6 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:29:47 +0400 Subject: [PATCH 13/15] Fix the third review of the syntactic write check - Unpacking into items of an array (`a[0], b = ...`) no longer counts as rebinding `a`; only the names a target binds are recorded. - `.copy()` of `.index` or `.columns` is not counted as a new array, because `Index.copy()` is shallow by default. - `choice` is no longer counted as a random draw that creates an array, because the standard library's `random.choice` returns an existing object. - New snippets cover non-constant values assigned to the writeable flag, multi-dimensional slices of a copy, and the cases above. Co-Authored-By: Claude Opus 5.5 --- .../shared/test_shared_buffer_writes.py | 61 +++++++++++++++++-- 1 file changed, 55 insertions(+), 6 deletions(-) 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 d3a6ec66cc..202798e6c6 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 @@ -47,7 +47,8 @@ with ``copy=True``, of ``.to_numpy(copy=True)``, or of a random ``Generator`` draw (``_RANDOM_DRAW_METHODS``: ``rng.random(n)``, ...); - arithmetic or a comparison (``a - b``, ``a > 0``); - - ``.copy()`` with no arguments, or ``+``, ``*`` or ``|`` (which also + - ``.copy()`` with no arguments (except of ``.index`` or ``.columns``: + ``Index.copy()`` is shallow), or ``+``, ``*`` or ``|`` (which also join lists and dicts), or a slice of these, but not an item of them, because a copy or join of a dict or list shares its items; - a subscript of the others; @@ -212,7 +213,6 @@ "normal", "uniform", "integers", - "choice", "permutation", "standard_normal", "exponential", @@ -435,9 +435,15 @@ def _collect(self) -> None: body = [node.body] if isinstance(node, ast.Lambda) else node.body def bind_other(target: ast.AST) -> None: - for name in ast.walk(target): - if isinstance(name, ast.Name): - assignments[name.id].append(None) + # Only names the target binds: ``a[0], b = ...`` binds ``b`` and + # writes an item of ``a``. + if isinstance(target, ast.Name): + assignments[target.id].append(None) + elif isinstance(target, ast.Starred): + bind_other(target.value) + elif isinstance(target, (ast.Tuple, ast.List)): + for element in target.elts: + bind_other(element) for child in _nodes_in_scope(body): if isinstance(child, (ast.Assign, ast.AnnAssign, ast.NamedExpr)): @@ -587,8 +593,12 @@ def _whole_created_kind(self, expression: ast.expr) -> str | None: name = self._numpy.resolve(function) if name is None and isinstance(function, ast.Attribute): if function.attr == "copy": + # ``Index.copy()`` is shallow by default. plain = not expression.args and not expression.keywords - return _COPY if plain else None + of_an_index = isinstance(function.value, ast.Attribute) and ( + function.value.attr in ("index", "columns") + ) + return _COPY if plain and not of_an_index else None if function.attr == "to_numpy": copy = _keyword(expression, "copy") return _NEW_ARRAY if copy and _is_true_constant(copy.value) else None @@ -910,6 +920,15 @@ def _in_function(*body_lines: str, parameters: str = "values") -> str: _MAKES_ARRAY_WRITABLE, ), "flags_w_key": ('values.flags["W"] = 1\n', _MAKES_ARRAY_WRITABLE), + "flags_writeable_from_a_name": ( + "values.flags.writeable = flag\n", + _MAKES_ARRAY_WRITABLE, + ), + "flags_w_key_from_a_name": ('values.flags["W"] = flag\n', _MAKES_ARRAY_WRITABLE), + "flags_writeable_from_an_expression": ( + "values.flags.writeable = not frozen\n", + _MAKES_ARRAY_WRITABLE, + ), # writes-through-series-array "series_array_item": ( 'frame.person["income"].array[0] = 1.0\n', @@ -978,6 +997,22 @@ def _in_function(*body_lines: str, parameters: str = "values") -> str: ), _WRITES_INTO_EXISTING_ARRAY, ), + "ufunc_at_on_an_index_copy": ( + _in_function( + "ids = table.index.copy()", + "np.add.at(ids, positions, 1)", + parameters="table, positions", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), + "out_standard_library_random_choice": ( + _in_function( + "chosen = random.choice(arrays)", + "np.add(chosen, 1, out=chosen)", + parameters="random, arrays", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), "ufunc_at_on_an_item_of_a_copied_dict": ( _in_function( "updated = columns.copy()", @@ -1322,6 +1357,20 @@ def test_the_scanner_refuses_each_unprotected_write(source: str, rule: str) -> N "np.add(row, 1, out=row)", parameters="values, size", ), + "out_items_of_a_new_array_assigned_by_unpacking": _in_function( + "bounds = np.empty(2)", + "bounds[0], bounds[1] = low, high", + "np.clip(bounds, 0, 1, out=bounds)", + "order = np.argsort(values)", + "order[0], order[-1] = order[-1], order[0]", + "np.add(order, 1, out=order)", + parameters="low, high, values", + ), + "out_multidimensional_slice_of_a_copy": _in_function( + "result = matrix.copy()", + "np.clip(result[:, 1:], 0, None, out=result[:, 1:])", + parameters="matrix", + ), "out_slice_of_a_copy": _in_function( "totals = first.copy()", "np.cumsum(later, out=totals[1:])", From a467f35b555c6097a49599e357e61cea439b2d58 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:37:04 +0400 Subject: [PATCH 14/15] Refuse copies of index slices in the syntactic write check A slice of an index shares the index's memory, and `Index.copy()` is shallow, so `table.index[1:].copy()` is not a new array. The check now strips subscripts before testing whether `.copy()` is called on `.index` or `.columns`. Co-Authored-By: Claude Opus 5.5 --- .../shared/test_shared_buffer_writes.py | 23 +++++++++++++++---- 1 file changed, 18 insertions(+), 5 deletions(-) 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 202798e6c6..e2841e6933 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 @@ -47,8 +47,9 @@ with ``copy=True``, of ``.to_numpy(copy=True)``, or of a random ``Generator`` draw (``_RANDOM_DRAW_METHODS``: ``rng.random(n)``, ...); - arithmetic or a comparison (``a - b``, ``a > 0``); - - ``.copy()`` with no arguments (except of ``.index`` or ``.columns``: - ``Index.copy()`` is shallow), or ``+``, ``*`` or ``|`` (which also + - ``.copy()`` with no arguments (except of ``.index`` or ``.columns``, or + a subscript of them: ``Index.copy()`` is shallow, and a slice of an + index shares its memory), or ``+``, ``*`` or ``|`` (which also join lists and dicts), or a slice of these, but not an item of them, because a copy or join of a dict or list shares its items; - a subscript of the others; @@ -593,10 +594,14 @@ def _whole_created_kind(self, expression: ast.expr) -> str | None: name = self._numpy.resolve(function) if name is None and isinstance(function, ast.Attribute): if function.attr == "copy": - # ``Index.copy()`` is shallow by default. + # ``Index.copy()`` is shallow by default, and a slice of an + # index shares the index's memory. plain = not expression.args and not expression.keywords - of_an_index = isinstance(function.value, ast.Attribute) and ( - function.value.attr in ("index", "columns") + copied = function.value + while isinstance(copied, ast.Subscript): + copied = copied.value + of_an_index = isinstance(copied, ast.Attribute) and ( + copied.attr in ("index", "columns") ) return _COPY if plain and not of_an_index else None if function.attr == "to_numpy": @@ -1005,6 +1010,14 @@ def _in_function(*body_lines: str, parameters: str = "values") -> str: ), _WRITES_INTO_EXISTING_ARRAY, ), + "ufunc_at_on_a_copy_of_an_index_slice": ( + _in_function( + "ids = table.index[1:].copy()", + "np.add.at(ids, positions, 1)", + parameters="table, positions", + ), + _WRITES_INTO_EXISTING_ARRAY, + ), "out_standard_library_random_choice": ( _in_function( "chosen = random.choice(arrays)", From 4ee5584e06c87982a3bff15c422e7078a9049e95 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:32:01 +0400 Subject: [PATCH 15/15] Add a changelog fragment and reflow the _adopt docstring Review fixes from juaristi22 on PR 1666: - Add changelog.d/frame-adopt-replace-tables.added.md for Frame.replace_tables, Frame.with_columns and the source check. - Reflow the _adopt docstring line that was 107 characters to the repository's 88-character limit. The text is unchanged. The docstring edit changes the bytes of microcosm/frame/bundle.py, which the calibrate and simulate graph parity cases hash, so both are re-pinned with tools/graph_parity_repin.py under Python 3.14 (arm64/darwin/py3.14, their only pinned platform). Only the implementation hash and node keys moved. Co-Authored-By: Claude Opus 5.5 --- changelog.d/frame-adopt-replace-tables.added.md | 1 + packages/microcosm-frame/src/microcosm/frame/bundle.py | 6 +++--- .../tests/fixtures/parity/kernels/calibrate/pins.json | 2 +- .../tests/fixtures/parity/kernels/simulate/pins.json | 2 +- 4 files changed, 6 insertions(+), 5 deletions(-) create mode 100644 changelog.d/frame-adopt-replace-tables.added.md diff --git a/changelog.d/frame-adopt-replace-tables.added.md b/changelog.d/frame-adopt-replace-tables.added.md new file mode 100644 index 0000000000..a4b43985a8 --- /dev/null +++ b/changelog.d/frame-adopt-replace-tables.added.md @@ -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. diff --git a/packages/microcosm-frame/src/microcosm/frame/bundle.py b/packages/microcosm-frame/src/microcosm/frame/bundle.py index e691826e7d..c71f9b84c6 100644 --- a/packages/microcosm-frame/src/microcosm/frame/bundle.py +++ b/packages/microcosm-frame/src/microcosm/frame/bundle.py @@ -170,9 +170,9 @@ def _adopt( 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. + 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. 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..87c8d0d888 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":"584886552a44ac4208fb878f54a195fa9a6962324175ce7ae0991cafd1816a69","kernel":"calibrate.adam@1","node":"calibrate","node_key":"6bff4ad9837e10c290ecfd9778a1cd59ec0826a7bdb3fe03cc194a37feac3618","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"6bff4ad9837e10c290ecfd9778a1cd59ec0826a7bdb3fe03cc194a37feac3618"}},"seed":0} 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..d30dfcc3e5 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":"90753d809d5e9953a6c6b8c2a282e8dc675143d92d587fb144aba70ecd46b6ad","kernel":"simulate.rules@1","node":"simulate","node_key":"56247d886b9b25341f4c40ac18b9d331da6e692f3940f68268fe1c2a553d43e0","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"56247d886b9b25341f4c40ac18b9d331da6e692f3940f68268fe1c2a553d43e0"}},"seed":null}