From c39a1275a7f94fbf01e8ba93aa986e0324f12d10 Mon Sep 17 00:00:00 2001 From: lmoresi Date: Wed, 22 Jul 2026 13:22:53 +1000 Subject: [PATCH 1/2] =?UTF-8?q?fix(data):=20intercept=20out=3D=20ufunc=20w?= =?UTF-8?q?rites=20=E2=80=94=20close=20the=20silent=20callback=20bypass=20?= =?UTF-8?q?(#379=20item=204a)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit np.add(x, 1, out=x) — and every in-place operator, which numpy routes through the same machinery — wrote straight into the buffer with no __setitem__ and no callback: values landed (the canonical array wraps the PETSc vec memory) but ghost synchronisation and the state increment silently did not happen, leaving stale ghosts and caches. NDArray_With_Callback now implements __array_ufunc__ using the standard override recipe: operands unwrap to base-class views for the compute (ndarray's default refuses mixed overriding operands), each requested out= comes back AS THE ORIGINAL OBJECT (so x += 1 keeps its subclass and callbacks), and each out= target that is one of ours is notified after the write. The notification composes with the canonical guard — an out= view resolves to the canonical array, an out= detached copy is skipped — and with synchronised_array_update (dirty-mark, one deferred flush). The 12 in-place operators drop their explicit triggers, which would now fire twice per operation. Remaining documented bypasses: np.copyto and ufunc.at (neither passes out=). Gates: units suite 240 passed; quick gate 419 passed; matplotlib quiver/masked-array smoke clean; ufunc dispatch overhead ~2-3 us per call (fixed cost, noise against any PETSc pack). Underworld development team with AI support from Claude Code --- .../utilities/nd_array_callback.py | 118 ++++++++++++------ tests/test_0061_ufunc_out_callback.py | 113 +++++++++++++++++ 2 files changed, 195 insertions(+), 36 deletions(-) create mode 100644 tests/test_0061_ufunc_out_callback.py diff --git a/src/underworld3/utilities/nd_array_callback.py b/src/underworld3/utilities/nd_array_callback.py index 6fc74f7f9..4aa14488e 100644 --- a/src/underworld3/utilities/nd_array_callback.py +++ b/src/underworld3/utilities/nd_array_callback.py @@ -706,6 +706,52 @@ def _trigger_callback( for callback in self._callbacks.copy(): # Copy in case callbacks modify the list callback(self, change_info) + def __array_ufunc__(self, ufunc, method, *inputs, out=None, **kwargs): + """Compute on plain-ndarray views, then notify ``out=`` targets. + + ``np.add(x, 1, out=x)`` (and every in-place operator, which numpy + routes through the same machinery) writes straight into the buffer + with no ``__setitem__`` — previously a silent bypass: values landed + but ghost sync and the state increment did not happen. + + The standard override recipe applies: operands are unwrapped to + base-class views (``ndarray.__array_ufunc__`` refuses mixed + overriding operands), and each requested ``out`` is returned AS THE + ORIGINAL OBJECT so ``x += 1`` keeps its subclass and callbacks. The + notification goes to each ``out=`` target rather than ``self``, + because numpy invokes this method on the first operand, which need + not be the array being written. Results without ``out`` come back + as plain ndarrays (matching the prior ``__array_wrap__`` policy of + not propagating callbacks to derived results). + + Remaining bypasses this cannot intercept: ``np.copyto`` and + ``ufunc.at`` (neither passes ``out=``). + """ + plain_inputs = tuple( + np.asarray(x) if isinstance(x, NDArray_With_Callback) else x for x in inputs + ) + if out is not None: + kwargs["out"] = tuple( + np.asarray(x) if isinstance(x, NDArray_With_Callback) else x for x in out + ) + + results = getattr(ufunc, method)(*plain_inputs, **kwargs) + + if out is not None: + for target in out: + if isinstance(target, NDArray_With_Callback): + target._trigger_callback("ufunc_out") + + if method == "at": + return None + if ufunc.nout == 1: + results = (results,) + wrapped = tuple( + out[i] if out is not None and i < len(out) and out[i] is not None else r + for i, r in enumerate(results) + ) + return wrapped[0] if len(wrapped) == 1 else wrapped + def __setitem__(self, key, value): """Override setitem to trigger callbacks on assignment.""" # Handle UnitAwareArray values by extracting magnitude @@ -730,9 +776,9 @@ def __iadd__(self, other): "Use explicit assignment instead: arr = arr + other" ) - result = super().__iadd__(other) - self._trigger_callback("iadd", new_value=other) - return result + # Callback fires via __array_ufunc__ (out= detection) — an + # explicit trigger here would notify twice per operation. + return super().__iadd__(other) def __isub__(self, other): """In-place subtraction with callback.""" @@ -742,9 +788,9 @@ def __isub__(self, other): "Use explicit assignment instead: arr = arr - other" ) - result = super().__isub__(other) - self._trigger_callback("isub", new_value=other) - return result + # Callback fires via __array_ufunc__ (out= detection) — an + # explicit trigger here would notify twice per operation. + return super().__isub__(other) def __imul__(self, other): """In-place multiplication with callback.""" @@ -754,9 +800,9 @@ def __imul__(self, other): "Use explicit assignment instead: arr = arr * other" ) - result = super().__imul__(other) - self._trigger_callback("imul", new_value=other) - return result + # Callback fires via __array_ufunc__ (out= detection) — an + # explicit trigger here would notify twice per operation. + return super().__imul__(other) def __itruediv__(self, other): """In-place true division with callback.""" @@ -766,9 +812,9 @@ def __itruediv__(self, other): "Use explicit assignment instead: arr = arr / other" ) - result = super().__itruediv__(other) - self._trigger_callback("itruediv", new_value=other) - return result + # Callback fires via __array_ufunc__ (out= detection) — an + # explicit trigger here would notify twice per operation. + return super().__itruediv__(other) def __ifloordiv__(self, other): """In-place floor division with callback.""" @@ -778,9 +824,9 @@ def __ifloordiv__(self, other): "Use explicit assignment instead: arr = arr // other" ) - result = super().__ifloordiv__(other) - self._trigger_callback("ifloordiv", new_value=other) - return result + # Callback fires via __array_ufunc__ (out= detection) — an + # explicit trigger here would notify twice per operation. + return super().__ifloordiv__(other) def __imod__(self, other): """In-place modulo with callback.""" @@ -790,9 +836,9 @@ def __imod__(self, other): "Use explicit assignment instead: arr = arr % other" ) - result = super().__imod__(other) - self._trigger_callback("imod", new_value=other) - return result + # Callback fires via __array_ufunc__ (out= detection) — an + # explicit trigger here would notify twice per operation. + return super().__imod__(other) def __ipow__(self, other): """In-place power with callback.""" @@ -802,9 +848,9 @@ def __ipow__(self, other): "Use explicit assignment instead: arr = arr ** other" ) - result = super().__ipow__(other) - self._trigger_callback("ipow", new_value=other) - return result + # Callback fires via __array_ufunc__ (out= detection) — an + # explicit trigger here would notify twice per operation. + return super().__ipow__(other) def __iand__(self, other): """In-place bitwise and with callback.""" @@ -814,9 +860,9 @@ def __iand__(self, other): "Use explicit assignment instead: arr = arr & other" ) - result = super().__iand__(other) - self._trigger_callback("iand", new_value=other) - return result + # Callback fires via __array_ufunc__ (out= detection) — an + # explicit trigger here would notify twice per operation. + return super().__iand__(other) def __ior__(self, other): """In-place bitwise or with callback.""" @@ -826,9 +872,9 @@ def __ior__(self, other): "Use explicit assignment instead: arr = arr | other" ) - result = super().__ior__(other) - self._trigger_callback("ior", new_value=other) - return result + # Callback fires via __array_ufunc__ (out= detection) — an + # explicit trigger here would notify twice per operation. + return super().__ior__(other) def __ixor__(self, other): """In-place bitwise xor with callback.""" @@ -838,9 +884,9 @@ def __ixor__(self, other): "Use explicit assignment instead: arr = arr ^ other" ) - result = super().__ixor__(other) - self._trigger_callback("ixor", new_value=other) - return result + # Callback fires via __array_ufunc__ (out= detection) — an + # explicit trigger here would notify twice per operation. + return super().__ixor__(other) def __ilshift__(self, other): """In-place left shift with callback.""" @@ -850,9 +896,9 @@ def __ilshift__(self, other): "Use explicit assignment instead: arr = arr << other" ) - result = super().__ilshift__(other) - self._trigger_callback("ilshift", new_value=other) - return result + # Callback fires via __array_ufunc__ (out= detection) — an + # explicit trigger here would notify twice per operation. + return super().__ilshift__(other) def __irshift__(self, other): """In-place right shift with callback.""" @@ -862,9 +908,9 @@ def __irshift__(self, other): "Use explicit assignment instead: arr = arr >> other" ) - result = super().__irshift__(other) - self._trigger_callback("irshift", new_value=other) - return result + # Callback fires via __array_ufunc__ (out= detection) — an + # explicit trigger here would notify twice per operation. + return super().__irshift__(other) def fill(self, value): """Fill array with scalar value, triggering callback.""" diff --git a/tests/test_0061_ufunc_out_callback.py b/tests/test_0061_ufunc_out_callback.py new file mode 100644 index 000000000..2ea72750d --- /dev/null +++ b/tests/test_0061_ufunc_out_callback.py @@ -0,0 +1,113 @@ +"""Regression tests for the ``out=`` ufunc callback bypass (#379 item 4a). + +``np.add(x, 1, out=x)`` writes straight into the buffer through numpy's +ufunc machinery — no ``__setitem__``, no in-place operator wrapper — so +before this fix no callback fired: values landed (the canonical array +wraps the PETSc vec memory) but ghost synchronisation and the state +increment silently did not happen. + +``__array_ufunc__`` now delegates to numpy unchanged and then notifies +each ``out=`` target that is an ``NDArray_With_Callback``. The canonical +guard composes: an ``out=`` view resolves to the canonical array, an +``out=`` detached copy is skipped, and inside +``uw.synchronised_array_update`` the write dirty-marks for the single +deferred flush. + +Known remaining bypasses (documented, not intercepted): ``np.copyto`` +and ``ufunc.at`` — neither routes through ``__array_ufunc__``'s ``out=``. +""" + +import numpy as np +import pytest + +import underworld3 as uw +from underworld3.utilities import NDArray_With_Callback + +pytestmark = [pytest.mark.level_1, pytest.mark.tier_a] + + +class _CallRecorder: + def __init__(self): + self.calls = [] + + def __call__(self, array, change_info): + self.calls.append(change_info["operation"]) + + +def _canonical(shape=(6, 2)): + arr = NDArray_With_Callback(np.zeros(shape)) + recorder = _CallRecorder() + arr.add_canonical_callback(recorder) + return arr, recorder + + +def test_ufunc_out_on_canonical_fires(): + arr, recorder = _canonical() + np.add(arr, 1.0, out=arr) + assert recorder.calls == ["ufunc_out"] + assert np.allclose(np.asarray(arr), 1.0) + + +def test_ufunc_out_on_view_resolves_to_canonical(): + arr, recorder = _canonical() + view = arr[1:4] + np.multiply(view, 0.0, out=view) + assert recorder.calls == ["ufunc_out"] + + +def test_ufunc_out_on_detached_copy_is_skipped(): + arr, recorder = _canonical() + detached = arr[np.array([0, 2])] # fancy index → independent copy + recorder.calls.clear() + np.add(detached, 5.0, out=detached) + assert recorder.calls == [] + assert np.allclose(np.asarray(arr), 0.0) + + +def test_plain_ufunc_without_out_stays_silent(): + arr, recorder = _canonical() + result = arr + 1.0 + assert recorder.calls == [] + assert not isinstance(result, NDArray_With_Callback) + assert np.allclose(result, 1.0) + + +def test_inplace_operator_fires_exactly_once(): + """+= routes through the ufunc machinery with out=self; the explicit + per-operator triggers are gone, so exactly ONE notification arrives.""" + arr, recorder = _canonical() + arr += 2.0 + assert recorder.calls == ["ufunc_out"] + assert np.allclose(np.asarray(arr), 2.0) + + +def test_masked_inplace_still_fires_exactly_once(): + """arr[mask] += 1: the temporary copy's ufunc_out is skipped (copy), + the parent write-back fires — net one canonical notification.""" + arr, recorder = _canonical() + mask = np.zeros(arr.shape[0], dtype=bool) + mask[1] = True + arr[mask] += 1.0 + assert recorder.calls == ["setitem"] + assert arr[1, 0] == 1.0 + + +def test_ufunc_out_defers_inside_synchronised_update(): + arr, recorder = _canonical() + with uw.synchronised_array_update("ufunc out"): + np.add(arr, 1.0, out=arr) + np.add(arr, 1.0, out=arr) + assert recorder.calls == [] + assert recorder.calls == ["deferred_flush"] + assert np.allclose(np.asarray(arr), 2.0) + + +def test_mesh_variable_ufunc_out_reaches_petsc(): + mesh = uw.meshing.StructuredQuadBox( + elementRes=(4, 4), minCoords=(0.0, 0.0), maxCoords=(1.0, 1.0) + ) + t = uw.discretisation.MeshVariable("t61", mesh, 1, vtype=uw.VarType.SCALAR, degree=1) + t.data[...] = 2.0 + np.multiply(t.data, 3.0, out=t.data) + assert np.allclose(np.asarray(t.data), 6.0) + assert np.allclose(t.vec.array, 6.0) From e09d89bc7487b9568b748168a63e67493fdb4d90 Mon Sep 17 00:00:00 2001 From: lmoresi Date: Wed, 22 Jul 2026 14:36:58 +1000 Subject: [PATCH 2/2] fix(data): out= ufunc writes honour disable_inplace_operators (#385 review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Round-1 review: np.add(x, 1, out=x) bypassed the guard that x += 1 enforces, re-arming the per-write hazard the flag exists to prevent (its only in-tree user was the legacy swarm.points wrapper, whose callback ran collective migrate() — removed by #382, but the flag's contract must hold regardless). The hook now raises the same RuntimeError for any out= target carrying the flag, before any computation. Regression test added. Underworld development team with AI support from Claude Code --- src/underworld3/utilities/nd_array_callback.py | 11 +++++++++++ tests/test_0061_ufunc_out_callback.py | 12 ++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/underworld3/utilities/nd_array_callback.py b/src/underworld3/utilities/nd_array_callback.py index 4aa14488e..31997cb8a 100644 --- a/src/underworld3/utilities/nd_array_callback.py +++ b/src/underworld3/utilities/nd_array_callback.py @@ -727,6 +727,17 @@ def __array_ufunc__(self, ufunc, method, *inputs, out=None, **kwargs): Remaining bypasses this cannot intercept: ``np.copyto`` and ``ufunc.at`` (neither passes ``out=``). """ + if out is not None: + for target in out: + if getattr(target, "_disable_inplace_operators", False): + # The out= spelling must honour the same contract as the + # in-place operators — bypassing it would re-arm the + # per-write hazard the flag exists to prevent. + raise RuntimeError( + "In-place ufunc output (out=) is disabled for parallel " + "safety on this array. Use explicit assignment instead." + ) + plain_inputs = tuple( np.asarray(x) if isinstance(x, NDArray_With_Callback) else x for x in inputs ) diff --git a/tests/test_0061_ufunc_out_callback.py b/tests/test_0061_ufunc_out_callback.py index 2ea72750d..e77a2b503 100644 --- a/tests/test_0061_ufunc_out_callback.py +++ b/tests/test_0061_ufunc_out_callback.py @@ -111,3 +111,15 @@ def test_mesh_variable_ufunc_out_reaches_petsc(): np.multiply(t.data, 3.0, out=t.data) assert np.allclose(np.asarray(t.data), 6.0) assert np.allclose(t.vec.array, 6.0) + + +def test_out_honours_disable_inplace_operators(): + """np.add(x, 1, out=x) must respect the same contract as x += 1 — + bypassing the flag re-armed the per-write hazard it exists to prevent + (#379 review round 1).""" + arr = NDArray_With_Callback(np.zeros(4), disable_inplace_operators=True) + with pytest.raises(RuntimeError, match="parallel safety"): + np.add(arr, 1.0, out=arr) + with pytest.raises(RuntimeError, match="parallel safety"): + arr += 1.0 + assert np.allclose(np.asarray(arr), 0.0)