diff --git a/src/underworld3/utilities/nd_array_callback.py b/src/underworld3/utilities/nd_array_callback.py index 6fc74f7f9..31997cb8a 100644 --- a/src/underworld3/utilities/nd_array_callback.py +++ b/src/underworld3/utilities/nd_array_callback.py @@ -706,6 +706,63 @@ 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=``). + """ + 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 + ) + 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 +787,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 +799,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 +811,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 +823,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 +835,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 +847,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 +859,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 +871,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 +883,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 +895,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 +907,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 +919,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..e77a2b503 --- /dev/null +++ b/tests/test_0061_ufunc_out_callback.py @@ -0,0 +1,125 @@ +"""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) + + +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)