From 123294c334b789aabb047ce4925cacab2e03f8f8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 03:32:18 +0000 Subject: [PATCH 01/13] grass.script: Make worker processes work with any multiprocessing start method Stop forcing the fork start method for the RPC and message servers and the t.rast.mapcalc and t.rast.extract workers. Use the platform default (spawn on Windows and macOS, forkserver on Linux since Python 3.14) and pass the session environment to the worker explicitly, because a forkserver worker otherwise gets the environment from the time the fork server started. Run the server start-method test with every available start method instead of skipping it, drop the spawn xfail of the GridModule tests by using a picklable function, and test that workers see the current environment. Written with the help of an AI assistant; the logic was reviewed and tested with the spawn and forkserver start methods on Linux and with Python 3.13 and 3.15. --- python/grass/pygrass/messages/__init__.py | 17 +- .../modules/tests/grass_pygrass_grid_test.py | 209 ++++++++---------- python/grass/pygrass/rpc/__init__.py | 10 +- python/grass/pygrass/rpc/base.py | 9 +- python/grass/script/tests/utils_test.py | 39 +++- python/grass/script/utils.py | 35 +-- .../grass/temporal/c_libraries_interface.py | 10 +- python/grass/temporal/extract.py | 11 +- python/grass/temporal/mapcalc.py | 7 +- ...c_libraries_interface_start_method_test.py | 22 +- 10 files changed, 182 insertions(+), 187 deletions(-) diff --git a/python/grass/pygrass/messages/__init__.py b/python/grass/pygrass/messages/__init__.py index e064e99d7a0..3fadd8b66ac 100644 --- a/python/grass/pygrass/messages/__init__.py +++ b/python/grass/pygrass/messages/__init__.py @@ -14,12 +14,13 @@ from __future__ import annotations +import multiprocessing import sys from typing import TYPE_CHECKING, Literal, NoReturn import grass.lib.gis as libgis from grass.exceptions import FatalError -from grass.script.utils import _get_multiprocessing_context +from grass.script.utils import _environ_process if TYPE_CHECKING: from multiprocessing.connection import Connection @@ -180,10 +181,9 @@ class Messenger: def __init__(self, raise_on_error: bool = False) -> None: self.raise_on_error = raise_on_error - ctx = _get_multiprocessing_context() - self.client_conn, self.server_conn = ctx.Pipe() - self.lock = ctx.Lock() - self.server = ctx.Process( + self.client_conn, self.server_conn = multiprocessing.Pipe() + self.lock = multiprocessing.Lock() + self.server = _environ_process( target=message_server, args=(self.lock, self.server_conn) ) self.server.daemon = True @@ -191,10 +191,9 @@ def __init__(self, raise_on_error: bool = False) -> None: def start_server(self) -> None: """Start the messenger server and open the pipe""" - ctx = _get_multiprocessing_context() - self.client_conn, self.server_conn = ctx.Pipe() - self.lock = ctx.Lock() - self.server = ctx.Process( + self.client_conn, self.server_conn = multiprocessing.Pipe() + self.lock = multiprocessing.Lock() + self.server = _environ_process( target=message_server, args=(self.lock, self.server_conn) ) self.server.daemon = True diff --git a/python/grass/pygrass/modules/tests/grass_pygrass_grid_test.py b/python/grass/pygrass/modules/tests/grass_pygrass_grid_test.py index 5f49689688f..59788236e29 100644 --- a/python/grass/pygrass/modules/tests/grass_pygrass_grid_test.py +++ b/python/grass/pygrass/modules/tests/grass_pygrass_grid_test.py @@ -1,36 +1,46 @@ """Test main functions of PyGRASS GridModule""" import multiprocessing +import os import pytest import grass.script as gs from grass.pygrass.modules.grid import GridModule -xfail_mp_spawn = pytest.mark.xfail( - multiprocessing.get_start_method() == "spawn", - reason="Multiprocessing using 'spawn' start method requires pickable functions", - raises=AttributeError, - strict=True, -) - def max_processes(): """Get max useful number of parallel processes to run""" return min(multiprocessing.cpu_count(), 4) +def run_grid_module(environ, *args, run_kwargs, **kwargs): + """Create and run a GridModule + + This is a module-level function so that it can be pickled when the start + method is "spawn" or "forkserver". The environment is passed explicitly + because a forkserver process keeps the environment from when it was + started, so it does not see the session of the current test. + """ + os.environ.clear() + os.environ.update(environ) + GridModule(*args, **kwargs).run(**run_kwargs) + + # GridModule uses C libraries which can easily initialize only once # and thus can't easily change location/mapset, so we use a subprocess # to separate individual GridModule calls. -def run_in_subprocess(function): - """Run function in a separate process""" - process = multiprocessing.Process(target=function) +def run_in_subprocess(*args, run_kwargs=None, **kwargs): + """Run GridModule with the given arguments in a separate process""" + process = multiprocessing.Process( + target=run_grid_module, + args=(os.environ.copy(), *args), + kwargs={"run_kwargs": run_kwargs or {}, **kwargs}, + ) process.start() process.join() -@xfail_mp_spawn @pytest.mark.needs_solo_run @pytest.mark.parametrize("processes", list(range(1, max_processes() + 1)) + [None]) def test_processes(tmp_path, processes): @@ -43,20 +53,16 @@ def test_processes(tmp_path, processes): surface = "surface" gs.run_command("r.surf.fractal", output=surface) - def run_grid_module(): - grid = GridModule( - "r.slope.aspect", - width=10, - height=5, - overlap=2, - processes=processes, - elevation=surface, - slope="slope", - aspect="aspect", - ) - grid.run() - - run_in_subprocess(run_grid_module) + run_in_subprocess( + "r.slope.aspect", + width=10, + height=5, + overlap=2, + processes=processes, + elevation=surface, + slope="slope", + aspect="aspect", + ) info = gs.raster_info("slope") assert info["min"] > 0 @@ -65,7 +71,6 @@ def run_grid_module(): # @pytest.mark.parametrize("split", [False]) # True does not work. -@xfail_mp_spawn @pytest.mark.parametrize("width", [5, 10, 50]) # None does not work. @pytest.mark.parametrize("height", [5, 10, 50]) def test_tiling_schemes(tmp_path, width, height): @@ -78,26 +83,21 @@ def test_tiling_schemes(tmp_path, width, height): surface = "surface" gs.run_command("r.surf.fractal", output=surface) - def run_grid_module(): - grid = GridModule( - "r.slope.aspect", - width=width, - height=height, - overlap=2, - processes=max_processes(), - elevation=surface, - slope="slope", - aspect="aspect", - ) - grid.run() - - run_in_subprocess(run_grid_module) + run_in_subprocess( + "r.slope.aspect", + width=width, + height=height, + overlap=2, + processes=max_processes(), + elevation=surface, + slope="slope", + aspect="aspect", + ) info = gs.raster_info("slope") assert info["min"] > 0 -@xfail_mp_spawn @pytest.mark.parametrize("overlap", [0, 1, 2, 5]) def test_overlaps(tmp_path, overlap): """Check that overlap accepts different values""" @@ -108,26 +108,21 @@ def test_overlaps(tmp_path, overlap): surface = "surface" gs.run_command("r.surf.fractal", output=surface) - def run_grid_module(): - grid = GridModule( - "r.slope.aspect", - width=10, - height=5, - overlap=overlap, - processes=max_processes(), - elevation=surface, - slope="slope", - aspect="aspect", - ) - grid.run() - - run_in_subprocess(run_grid_module) + run_in_subprocess( + "r.slope.aspect", + width=10, + height=5, + overlap=overlap, + processes=max_processes(), + elevation=surface, + slope="slope", + aspect="aspect", + ) info = gs.raster_info("slope") assert info["min"] > 0 -@xfail_mp_spawn @pytest.mark.parametrize("clean", [True, False]) @pytest.mark.parametrize("surface", ["surface", "non_exist_surface"]) def test_cleans(tmp_path, clean, surface): @@ -140,21 +135,18 @@ def test_cleans(tmp_path, clean, surface): if surface == "surface": gs.run_command("r.surf.fractal", output=surface) - def run_grid_module(): - grid = GridModule( - "r.slope.aspect", - width=10, - height=5, - overlap=0, - processes=max_processes(), - elevation=surface, - slope="slope", - aspect="aspect", - mapset_prefix=mapset_prefix, - ) - grid.run(clean=clean) - - run_in_subprocess(run_grid_module) + run_in_subprocess( + "r.slope.aspect", + width=10, + height=5, + overlap=0, + processes=max_processes(), + elevation=surface, + slope="slope", + aspect="aspect", + mapset_prefix=mapset_prefix, + run_kwargs={"clean": clean}, + ) prefixed = 0 for item in project.iterdir(): @@ -169,7 +161,6 @@ def run_grid_module(): assert prefixed, "Not even one prefixed mapset" -@xfail_mp_spawn @pytest.mark.parametrize("patch_backend", [None, "r.patch", "RasterRow"]) def test_patching_backend(tmp_path, patch_backend): """Check patching backend works""" @@ -185,29 +176,24 @@ def test_patching_backend(tmp_path, patch_backend): "v.to.rast", input=points, output=reference, type="point", use="cat" ) - def run_grid_module(): - grid = GridModule( - "v.to.rast", - width=10, - height=5, - overlap=0, - patch_backend=patch_backend, - processes=max_processes(), - input=points, - output="output", - type="point", - use="cat", - ) - grid.run() - - run_in_subprocess(run_grid_module) + run_in_subprocess( + "v.to.rast", + width=10, + height=5, + overlap=0, + patch_backend=patch_backend, + processes=max_processes(), + input=points, + output="output", + type="point", + use="cat", + ) mean_ref = float(gs.parse_command("r.univar", map=reference, flags="g")["mean"]) mean = float(gs.parse_command("r.univar", map="output", flags="g")["mean"]) assert abs(mean - mean_ref) < 0.0001 -@xfail_mp_spawn @pytest.mark.parametrize( ("width", "height", "processes"), [ @@ -226,26 +212,21 @@ def test_tiling(tmp_path, width, height, processes): surface = "surface" gs.run_command("r.surf.fractal", output=surface) - def run_grid_module(): - grid = GridModule( - "r.slope.aspect", - width=width, - height=height, - overlap=2, - processes=processes, - elevation=surface, - slope="slope", - aspect="aspect", - ) - grid.run() - - run_in_subprocess(run_grid_module) + run_in_subprocess( + "r.slope.aspect", + width=width, + height=height, + overlap=2, + processes=processes, + elevation=surface, + slope="slope", + aspect="aspect", + ) info = gs.raster_info("slope") assert info["min"] > 0 -@xfail_mp_spawn @pytest.mark.needs_solo_run @pytest.mark.parametrize( ("processes", "backend"), @@ -265,18 +246,14 @@ def test_patching_error(tmp_path, processes, backend): gs.run_command("g.region", s=0, n=10, w=0, e=10, res=0.1) surface = "fractal" - def run_grid_module(): - grid = GridModule( - "r.surf.fractal", - overlap=0, - processes=processes, - output=surface, - patch_backend=backend, - debug=True, - ) - grid.run() - - run_in_subprocess(run_grid_module) + run_in_subprocess( + "r.surf.fractal", + overlap=0, + processes=processes, + output=surface, + patch_backend=backend, + debug=True, + ) info = gs.parse_command("r.univar", flags="g", map=surface) assert int(info["null_cells"]) == 0 diff --git a/python/grass/pygrass/rpc/__init__.py b/python/grass/pygrass/rpc/__init__.py index eb21376ba2b..97751e75427 100644 --- a/python/grass/pygrass/rpc/__init__.py +++ b/python/grass/pygrass/rpc/__init__.py @@ -8,6 +8,7 @@ :authors: Soeren Gebbert """ +import multiprocessing import sys from ctypes import CFUNCTYPE, c_void_p @@ -18,7 +19,7 @@ from grass.pygrass.raster import RasterRow, raster2numpy_img from grass.pygrass.vector import VectorTopo from grass.pygrass.vector.basic import Bbox -from grass.script.utils import _get_multiprocessing_context +from grass.script.utils import _environ_process from .base import RPCServerBase @@ -244,10 +245,9 @@ def __init__(self): def start_server(self): """This function must be re-implemented in the subclasses""" - ctx = _get_multiprocessing_context() - self.client_conn, self.server_conn = ctx.Pipe(True) - self.lock = ctx.Lock() - self.server = ctx.Process( + self.client_conn, self.server_conn = multiprocessing.Pipe(True) + self.lock = multiprocessing.Lock() + self.server = _environ_process( target=data_provider_server, args=(self.lock, self.server_conn) ) self.server.daemon = True diff --git a/python/grass/pygrass/rpc/base.py b/python/grass/pygrass/rpc/base.py index 09a2ace09e3..660bbfa90f0 100644 --- a/python/grass/pygrass/rpc/base.py +++ b/python/grass/pygrass/rpc/base.py @@ -17,7 +17,7 @@ from typing import TYPE_CHECKING, NoReturn from grass.exceptions import FatalError -from grass.script.utils import _get_multiprocessing_context +from grass.script.utils import _environ_process if TYPE_CHECKING: from multiprocessing.connection import Connection @@ -161,10 +161,9 @@ def start_server(self): """This function must be re-implemented in the subclasses""" logger.debug("Start the libgis server") - ctx = _get_multiprocessing_context() - self.client_conn, self.server_conn = ctx.Pipe(True) - self.lock = ctx.Lock() - self.server = ctx.Process( + self.client_conn, self.server_conn = multiprocessing.Pipe(True) + self.lock = multiprocessing.Lock() + self.server = _environ_process( target=dummy_server, args=(self.lock, self.server_conn) ) self.server.daemon = True diff --git a/python/grass/script/tests/utils_test.py b/python/grass/script/tests/utils_test.py index 63e715c444b..d6682f1b10a 100644 --- a/python/grass/script/tests/utils_test.py +++ b/python/grass/script/tests/utils_test.py @@ -1,7 +1,8 @@ """Test functions in grass.script.utils""" import multiprocessing -import sys +import os +from pathlib import Path import pytest @@ -113,13 +114,35 @@ def test_resolve_nprocs_from_gisenv(empty_session): assert gs.resolve_nprocs(None, env=env) == gs.resolve_nprocs(nprocs) -def test_get_multiprocessing_context(): - """Fork is used where available and safe, the platform default elsewhere.""" - ctx = gutils._get_multiprocessing_context() - if sys.platform != "darwin" and "fork" in multiprocessing.get_all_start_methods(): - assert ctx.get_start_method() == "fork" - else: - assert ctx.get_start_method() == multiprocessing.get_start_method() +def write_environ_value(path): + """Write a variable from the environment to a file (worker process target)""" + Path(path).write_text(os.environ["GRASS_TEST_ENVIRON_PROCESS"]) + + +@pytest.fixture(params=multiprocessing.get_all_start_methods()) +def start_method(request): + """Set each available multiprocessing start method as the default""" + original = multiprocessing.get_start_method(allow_none=True) + multiprocessing.set_start_method(request.param, force=True) + yield request.param + multiprocessing.set_start_method(original, force=True) + + +def test_environ_process_sees_current_environment(start_method, tmp_path, monkeypatch): + """Worker gets the current environment with any start method + + With forkserver, a worker would otherwise get the environment from the time + the fork server was started, so start it with a different value first. + """ + monkeypatch.setenv("GRASS_TEST_ENVIRON_PROCESS", "first") + for value in ("first", "second"): + monkeypatch.setenv("GRASS_TEST_ENVIRON_PROCESS", value) + path = tmp_path / value + process = gutils._environ_process(write_environ_value, (path,)) + process.start() + process.join() + assert process.exitcode == 0 + assert path.read_text() == value @pytest.mark.parametrize( diff --git a/python/grass/script/utils.py b/python/grass/script/utils.py index 7303fc81c5b..c47ce23bf9f 100644 --- a/python/grass/script/utils.py +++ b/python/grass/script/utils.py @@ -27,7 +27,6 @@ import uuid import random import string -import sys from pathlib import Path from typing import TYPE_CHECKING, AnyStr, TypeVar, cast, overload @@ -36,7 +35,6 @@ if TYPE_CHECKING: from _typeshed import FileDescriptorOrPath, StrOrBytesPath, StrPath from collections.abc import Callable - from multiprocessing.context import BaseContext # Type variables @@ -148,27 +146,32 @@ def resolve_nprocs(nprocs: int | str | None = None, env=None) -> int: return max(1, available + n) -def _get_multiprocessing_context() -> BaseContext: - """Return the multiprocessing context to use for GRASS worker processes. +def _run_with_environ(environ, target, args): + """Run target in a worker process after setting its environment""" + os.environ.clear() + os.environ.update(environ) + target(*args) - Python 3.14 changed the default multiprocessing start method from "fork" - to "forkserver" (on platforms where "fork" is available, except macOS). - GRASS worker processes rely on "fork" semantics: they inherit the - initialized C library state and the session environment from the parent. - Use "fork" wherever it is available, i.e. the default before 3.14, except - on macOS, which has defaulted to "spawn" since Python 3.8 and where - "fork" is unsafe. Everywhere else (Windows) keep the platform default. - This is a workaround until GRASS supports the "spawn" and "forkserver" - start methods. +def _environ_process(target, args=()): + """Create a worker process which runs with the environment of this process. + + Workers need the GRASS session environment (e.g., GISRC) of the parent. + With the "fork" and "spawn" start methods the worker gets it automatically, + but with "forkserver", the default on Linux since Python 3.14, it gets + the environment from the time the fork server was started. Passing the + environment explicitly makes the worker independent of the start method. + + The target and its arguments need to be picklable, which is required by + the "spawn" and "forkserver" start methods. """ # Imported here because grass.script is imported by every Python tool # and only a few callers need multiprocessing. import multiprocessing - if sys.platform != "darwin" and "fork" in multiprocessing.get_all_start_methods(): - return multiprocessing.get_context("fork") - return multiprocessing.get_context() + return multiprocessing.Process( + target=_run_with_environ, args=(os.environ.copy(), target, args) + ) def diff_files( diff --git a/python/grass/temporal/c_libraries_interface.py b/python/grass/temporal/c_libraries_interface.py index be9e1b2d400..524be598345 100644 --- a/python/grass/temporal/c_libraries_interface.py +++ b/python/grass/temporal/c_libraries_interface.py @@ -12,6 +12,7 @@ import logging import math +import multiprocessing import sys from ctypes import CFUNCTYPE, POINTER, byref, c_int, c_void_p, cast from datetime import datetime @@ -28,7 +29,7 @@ from grass.pygrass.rpc.base import RPCServerBase from grass.pygrass.utils import decode from grass.pygrass.vector import VectorTopo -from grass.script.utils import _get_multiprocessing_context, encode +from grass.script.utils import _environ_process, encode import grass.script as gs if TYPE_CHECKING: @@ -1466,10 +1467,9 @@ def __init__(self) -> None: RPCServerBase.__init__(self) def start_server(self) -> None: - ctx = _get_multiprocessing_context() - self.client_conn, self.server_conn = ctx.Pipe(True) - self.lock = ctx.Lock() - self.server = ctx.Process( + self.client_conn, self.server_conn = multiprocessing.Pipe(True) + self.lock = multiprocessing.Lock() + self.server = _environ_process( target=c_library_server, args=(self.lock, self.server_conn) ) self.server.daemon = True diff --git a/python/grass/temporal/extract.py b/python/grass/temporal/extract.py index dd882afb5c9..b4573bf12a1 100644 --- a/python/grass/temporal/extract.py +++ b/python/grass/temporal/extract.py @@ -13,7 +13,7 @@ import grass.script as gs from grass.exceptions import CalledModuleError -from grass.script.utils import _get_multiprocessing_context +from grass.script.utils import _environ_process from .abstract_map_dataset import AbstractMapDataset @@ -207,7 +207,6 @@ def extract_dataset( # Run the mapcalc expression if expression: - ctx = _get_multiprocessing_context() proc_count = 0 proc_list = [] @@ -263,15 +262,15 @@ def extract_dataset( # Add process to the process list if type == "raster": msgr.verbose(_('Applying r.mapcalc expression: "%s"') % expr) - proc_list.append(ctx.Process(target=run_mapcalc2d, args=(expr,))) + proc_list.append(_environ_process(target=run_mapcalc2d, args=(expr,))) elif type == "raster3d": msgr.verbose(_('Applying r3.mapcalc expression: "%s"') % expr) - proc_list.append(ctx.Process(target=run_mapcalc3d, args=(expr,))) + proc_list.append(_environ_process(target=run_mapcalc3d, args=(expr,))) elif type == "vector": msgr.verbose(_('Applying v.extract where statement: "%s"') % expression) if row["layer"]: proc_list.append( - ctx.Process( + _environ_process( target=run_vector_extraction, args=( row["name"] + "@" + row["mapset"], @@ -284,7 +283,7 @@ def extract_dataset( ) else: proc_list.append( - ctx.Process( + _environ_process( target=run_vector_extraction, args=( row["name"] + "@" + row["mapset"], diff --git a/python/grass/temporal/mapcalc.py b/python/grass/temporal/mapcalc.py index 9033e63f4e4..8eef34010c3 100644 --- a/python/grass/temporal/mapcalc.py +++ b/python/grass/temporal/mapcalc.py @@ -13,7 +13,7 @@ import grass.script as gs from grass.exceptions import CalledModuleError -from grass.script.utils import _get_multiprocessing_context +from grass.script.utils import _environ_process from .core import ( SQLDatabaseInterfaceConnection, @@ -234,7 +234,6 @@ def dataset_mapcalculator( num = len(map_matrix[0]) # Parallel processing - ctx = _get_multiprocessing_context() proc_list = [] proc_count = 0 @@ -310,9 +309,9 @@ def dataset_mapcalculator( # Start the parallel r.mapcalc computation if type == "raster": - proc_list.append(ctx.Process(target=_run_mapcalc2d, args=(expr,))) + proc_list.append(_environ_process(target=_run_mapcalc2d, args=(expr,))) else: - proc_list.append(ctx.Process(target=_run_mapcalc3d, args=(expr,))) + proc_list.append(_environ_process(target=_run_mapcalc3d, args=(expr,))) proc_list[proc_count].start() proc_count += 1 diff --git a/python/grass/temporal/tests/grass_temporal_c_libraries_interface_start_method_test.py b/python/grass/temporal/tests/grass_temporal_c_libraries_interface_start_method_test.py index c05c0b2a25a..9d235c6f76e 100644 --- a/python/grass/temporal/tests/grass_temporal_c_libraries_interface_start_method_test.py +++ b/python/grass/temporal/tests/grass_temporal_c_libraries_interface_start_method_test.py @@ -1,12 +1,11 @@ # Copyright (C) 2026 by the GRASS Development Team # SPDX-License-Identifier: GPL-2.0-or-later -"""Test that GRASS server processes start when the default start method is not fork. +"""Test that GRASS server processes start with every multiprocessing start method. -Python 3.14 made forkserver the default multiprocessing start method on Linux, -which broke the RPC servers in grass.pygrass and grass.temporal. The servers -now request a fork context explicitly. This test forces forkserver as the -default in a subprocess to reproduce the Python 3.14 situation on any version. +Python 3.14 made forkserver the default start method on Linux, while macOS and Windows use +spawn. This test sets each available start method as the default in a subprocess, +so that all of them are tested on any platform and Python version. """ import multiprocessing @@ -55,21 +54,18 @@ def main(): if __name__ == "__main__": - multiprocessing.set_start_method("forkserver") + multiprocessing.set_start_method(sys.argv[2]) main() """ -@pytest.mark.skipif( - sys.platform == "darwin" or "fork" not in multiprocessing.get_all_start_methods(), - reason="Fork is only requested where it is available and not macOS", -) -def test_servers_start_with_forkserver_default(tmp_path): - """Servers work and exit cleanly when forkserver is the default start method.""" +@pytest.mark.parametrize("start_method", multiprocessing.get_all_start_methods()) +def test_servers_start_with_start_method(tmp_path, start_method): + """Servers work and exit cleanly with the start method set as the default.""" script = tmp_path / "script.py" script.write_text(SCRIPT) result = subprocess.run( - [sys.executable, str(script), str(tmp_path / "project")], + [sys.executable, str(script), str(tmp_path / "project"), start_method], capture_output=True, text=True, check=False, From b1040400407d9afc3ec3e7ccbad2c6e29d72e73b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 03:45:54 +0000 Subject: [PATCH 02/13] grass.pygrass: Do not fix the default multiprocessing start method Create the worker processes, locks, pipes and queues from a context which uses the current default start method without setting it, so applications can still choose a start method after using grass.pygrass or grass.temporal. Also start the MultiModule processes with the session environment, which is needed with the forkserver start method after the session changed. Skip the fork start method on macOS in the start-method test. Written with the help of an AI assistant; tested with Python 3.13 and 3.15. --- python/grass/pygrass/messages/__init__.py | 13 +++++----- .../grass/pygrass/modules/interface/module.py | 17 ++++++++----- python/grass/pygrass/rpc/__init__.py | 8 +++---- python/grass/pygrass/rpc/base.py | 7 +++--- python/grass/script/tests/utils_test.py | 1 - python/grass/script/utils.py | 24 +++++++++++++++---- .../grass/temporal/c_libraries_interface.py | 8 +++---- ...c_libraries_interface_start_method_test.py | 16 +++++++++---- 8 files changed, 61 insertions(+), 33 deletions(-) diff --git a/python/grass/pygrass/messages/__init__.py b/python/grass/pygrass/messages/__init__.py index 3fadd8b66ac..830cfc2bd2e 100644 --- a/python/grass/pygrass/messages/__init__.py +++ b/python/grass/pygrass/messages/__init__.py @@ -14,13 +14,12 @@ from __future__ import annotations -import multiprocessing import sys from typing import TYPE_CHECKING, Literal, NoReturn import grass.lib.gis as libgis from grass.exceptions import FatalError -from grass.script.utils import _environ_process +from grass.script.utils import _environ_process, _get_multiprocessing_context if TYPE_CHECKING: from multiprocessing.connection import Connection @@ -181,8 +180,9 @@ class Messenger: def __init__(self, raise_on_error: bool = False) -> None: self.raise_on_error = raise_on_error - self.client_conn, self.server_conn = multiprocessing.Pipe() - self.lock = multiprocessing.Lock() + ctx = _get_multiprocessing_context() + self.client_conn, self.server_conn = ctx.Pipe() + self.lock = ctx.Lock() self.server = _environ_process( target=message_server, args=(self.lock, self.server_conn) ) @@ -191,8 +191,9 @@ def __init__(self, raise_on_error: bool = False) -> None: def start_server(self) -> None: """Start the messenger server and open the pipe""" - self.client_conn, self.server_conn = multiprocessing.Pipe() - self.lock = multiprocessing.Lock() + ctx = _get_multiprocessing_context() + self.client_conn, self.server_conn = ctx.Pipe() + self.lock = ctx.Lock() self.server = _environ_process( target=message_server, args=(self.lock, self.server_conn) ) diff --git a/python/grass/pygrass/modules/interface/module.py b/python/grass/pygrass/modules/interface/module.py index def9638217e..cc7b0d12551 100644 --- a/python/grass/pygrass/modules/interface/module.py +++ b/python/grass/pygrass/modules/interface/module.py @@ -1,10 +1,15 @@ -from multiprocessing import Process, Queue import time from xml.etree.ElementTree import fromstring from grass.exceptions import CalledModuleError, GrassError, ParameterError from grass.script.core import Popen, PIPE, use_temp_region, del_temp_region -from grass.script.utils import available_cpus, decode, resolve_nprocs +from grass.script.utils import ( + _environ_process, + _get_multiprocessing_context, + available_cpus, + decode, + resolve_nprocs, +) from .docstring import docstring_property from .parameter import Parameter from .flag import Flag @@ -1013,7 +1018,7 @@ def __init__(self, module_list, sync=True, set_temp_region=False): self.set_temp_region = set_temp_region self.finish_ = sync # We use the same variable name a Module self.p = None - self.q = Queue() + self.q = _get_multiprocessing_context().Queue() def __str__(self): """Return the command string that can be executed in a shell""" @@ -1047,11 +1052,11 @@ def run(self): module.run() return None if self.set_temp_region is True: - self.p = Process( - target=run_modules_in_temp_region, args=[self.module_list, self.q] + self.p = _environ_process( + run_modules_in_temp_region, (self.module_list, self.q) ) else: - self.p = Process(target=run_modules, args=[self.module_list, self.q]) + self.p = _environ_process(run_modules, (self.module_list, self.q)) self.p.start() return self.p diff --git a/python/grass/pygrass/rpc/__init__.py b/python/grass/pygrass/rpc/__init__.py index 97751e75427..7ff966d0e7f 100644 --- a/python/grass/pygrass/rpc/__init__.py +++ b/python/grass/pygrass/rpc/__init__.py @@ -8,7 +8,6 @@ :authors: Soeren Gebbert """ -import multiprocessing import sys from ctypes import CFUNCTYPE, c_void_p @@ -19,7 +18,7 @@ from grass.pygrass.raster import RasterRow, raster2numpy_img from grass.pygrass.vector import VectorTopo from grass.pygrass.vector.basic import Bbox -from grass.script.utils import _environ_process +from grass.script.utils import _environ_process, _get_multiprocessing_context from .base import RPCServerBase @@ -245,8 +244,9 @@ def __init__(self): def start_server(self): """This function must be re-implemented in the subclasses""" - self.client_conn, self.server_conn = multiprocessing.Pipe(True) - self.lock = multiprocessing.Lock() + ctx = _get_multiprocessing_context() + self.client_conn, self.server_conn = ctx.Pipe(True) + self.lock = ctx.Lock() self.server = _environ_process( target=data_provider_server, args=(self.lock, self.server_conn) ) diff --git a/python/grass/pygrass/rpc/base.py b/python/grass/pygrass/rpc/base.py index 660bbfa90f0..8017fb3c5c8 100644 --- a/python/grass/pygrass/rpc/base.py +++ b/python/grass/pygrass/rpc/base.py @@ -17,7 +17,7 @@ from typing import TYPE_CHECKING, NoReturn from grass.exceptions import FatalError -from grass.script.utils import _environ_process +from grass.script.utils import _environ_process, _get_multiprocessing_context if TYPE_CHECKING: from multiprocessing.connection import Connection @@ -161,8 +161,9 @@ def start_server(self): """This function must be re-implemented in the subclasses""" logger.debug("Start the libgis server") - self.client_conn, self.server_conn = multiprocessing.Pipe(True) - self.lock = multiprocessing.Lock() + ctx = _get_multiprocessing_context() + self.client_conn, self.server_conn = ctx.Pipe(True) + self.lock = ctx.Lock() self.server = _environ_process( target=dummy_server, args=(self.lock, self.server_conn) ) diff --git a/python/grass/script/tests/utils_test.py b/python/grass/script/tests/utils_test.py index d6682f1b10a..58be7a9694b 100644 --- a/python/grass/script/tests/utils_test.py +++ b/python/grass/script/tests/utils_test.py @@ -134,7 +134,6 @@ def test_environ_process_sees_current_environment(start_method, tmp_path, monkey With forkserver, a worker would otherwise get the environment from the time the fork server was started, so start it with a different value first. """ - monkeypatch.setenv("GRASS_TEST_ENVIRON_PROCESS", "first") for value in ("first", "second"): monkeypatch.setenv("GRASS_TEST_ENVIRON_PROCESS", value) path = tmp_path / value diff --git a/python/grass/script/utils.py b/python/grass/script/utils.py index c47ce23bf9f..028b8e0ff01 100644 --- a/python/grass/script/utils.py +++ b/python/grass/script/utils.py @@ -153,6 +153,24 @@ def _run_with_environ(environ, target, args): target(*args) +def _get_multiprocessing_context(): + """Return the multiprocessing context with the default start method. + + Unlike using the multiprocessing module directly (e.g., multiprocessing.Lock()), + this does not fix the default start method, so the application can still + set it later. + """ + # Imported here because grass.script is imported by every Python tool + # and only a few callers need multiprocessing. + import multiprocessing + + method = multiprocessing.get_start_method(allow_none=True) + # The first of the available methods is the platform default. + return multiprocessing.get_context( + method or multiprocessing.get_all_start_methods()[0] + ) + + def _environ_process(target, args=()): """Create a worker process which runs with the environment of this process. @@ -165,11 +183,7 @@ def _environ_process(target, args=()): The target and its arguments need to be picklable, which is required by the "spawn" and "forkserver" start methods. """ - # Imported here because grass.script is imported by every Python tool - # and only a few callers need multiprocessing. - import multiprocessing - - return multiprocessing.Process( + return _get_multiprocessing_context().Process( target=_run_with_environ, args=(os.environ.copy(), target, args) ) diff --git a/python/grass/temporal/c_libraries_interface.py b/python/grass/temporal/c_libraries_interface.py index 524be598345..950fb1dcd04 100644 --- a/python/grass/temporal/c_libraries_interface.py +++ b/python/grass/temporal/c_libraries_interface.py @@ -12,7 +12,6 @@ import logging import math -import multiprocessing import sys from ctypes import CFUNCTYPE, POINTER, byref, c_int, c_void_p, cast from datetime import datetime @@ -29,7 +28,7 @@ from grass.pygrass.rpc.base import RPCServerBase from grass.pygrass.utils import decode from grass.pygrass.vector import VectorTopo -from grass.script.utils import _environ_process, encode +from grass.script.utils import _environ_process, _get_multiprocessing_context, encode import grass.script as gs if TYPE_CHECKING: @@ -1467,8 +1466,9 @@ def __init__(self) -> None: RPCServerBase.__init__(self) def start_server(self) -> None: - self.client_conn, self.server_conn = multiprocessing.Pipe(True) - self.lock = multiprocessing.Lock() + ctx = _get_multiprocessing_context() + self.client_conn, self.server_conn = ctx.Pipe(True) + self.lock = ctx.Lock() self.server = _environ_process( target=c_library_server, args=(self.lock, self.server_conn) ) diff --git a/python/grass/temporal/tests/grass_temporal_c_libraries_interface_start_method_test.py b/python/grass/temporal/tests/grass_temporal_c_libraries_interface_start_method_test.py index 9d235c6f76e..159a133cffe 100644 --- a/python/grass/temporal/tests/grass_temporal_c_libraries_interface_start_method_test.py +++ b/python/grass/temporal/tests/grass_temporal_c_libraries_interface_start_method_test.py @@ -3,9 +3,9 @@ """Test that GRASS server processes start with every multiprocessing start method. -Python 3.14 made forkserver the default start method on Linux, while macOS and Windows use -spawn. This test sets each available start method as the default in a subprocess, -so that all of them are tested on any platform and Python version. +Python 3.14 made forkserver the default start method on Linux, while macOS and +Windows use spawn. This test sets each available start method as the default in +a subprocess, so that all of them are tested on any platform and Python version. """ import multiprocessing @@ -59,7 +59,15 @@ def main(): """ -@pytest.mark.parametrize("start_method", multiprocessing.get_all_start_methods()) +# Fork is unsafe on macOS, which is why spawn is the default there. +START_METHODS = [ + method + for method in multiprocessing.get_all_start_methods() + if not (method == "fork" and sys.platform == "darwin") +] + + +@pytest.mark.parametrize("start_method", START_METHODS) def test_servers_start_with_start_method(tmp_path, start_method): """Servers work and exit cleanly with the start method set as the default.""" script = tmp_path / "script.py" From ad49bf303d4389293291906901cec96119805212 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 14:05:50 +0000 Subject: [PATCH 03/13] grass.script: Add type annotations to the worker process helpers Annotate the helpers for starting worker processes and the tests changed with them. Declare the type of RPCServerBase.server. Count a missing exit code as zero in t.rast.mapcalc and t.rast.extract, because the exit code of a process is optional. Written with the help of an AI assistant; checked with mypy, ty, pyrefly and zuban, which report no new problems and fewer than before. --- .../modules/tests/grass_pygrass_grid_test.py | 24 +++++++++++++++---- python/grass/pygrass/rpc/base.py | 3 ++- python/grass/script/tests/utils_test.py | 14 ++++++++--- python/grass/script/utils.py | 18 ++++++++++---- python/grass/temporal/extract.py | 2 +- python/grass/temporal/mapcalc.py | 2 +- 6 files changed, 47 insertions(+), 16 deletions(-) diff --git a/python/grass/pygrass/modules/tests/grass_pygrass_grid_test.py b/python/grass/pygrass/modules/tests/grass_pygrass_grid_test.py index 59788236e29..7a24c2e3782 100644 --- a/python/grass/pygrass/modules/tests/grass_pygrass_grid_test.py +++ b/python/grass/pygrass/modules/tests/grass_pygrass_grid_test.py @@ -1,20 +1,32 @@ """Test main functions of PyGRASS GridModule""" +from __future__ import annotations + import multiprocessing import os +from typing import TYPE_CHECKING import pytest import grass.script as gs from grass.pygrass.modules.grid import GridModule +if TYPE_CHECKING: + from collections.abc import Mapping + -def max_processes(): +def max_processes() -> int: """Get max useful number of parallel processes to run""" return min(multiprocessing.cpu_count(), 4) -def run_grid_module(environ, *args, run_kwargs, **kwargs): +def run_grid_module( + environ: Mapping[str, str], + name: str, + *, + run_kwargs: dict[str, object], + **kwargs: object, +) -> None: """Create and run a GridModule This is a module-level function so that it can be pickled when the start @@ -24,17 +36,19 @@ def run_grid_module(environ, *args, run_kwargs, **kwargs): """ os.environ.clear() os.environ.update(environ) - GridModule(*args, **kwargs).run(**run_kwargs) + GridModule(name, **kwargs).run(**run_kwargs) # GridModule uses C libraries which can easily initialize only once # and thus can't easily change location/mapset, so we use a subprocess # to separate individual GridModule calls. -def run_in_subprocess(*args, run_kwargs=None, **kwargs): +def run_in_subprocess( + name: str, run_kwargs: dict[str, object] | None = None, **kwargs: object +) -> None: """Run GridModule with the given arguments in a separate process""" process = multiprocessing.Process( target=run_grid_module, - args=(os.environ.copy(), *args), + args=(os.environ.copy(), name), kwargs={"run_kwargs": run_kwargs or {}, **kwargs}, ) process.start() diff --git a/python/grass/pygrass/rpc/base.py b/python/grass/pygrass/rpc/base.py index 8017fb3c5c8..1ad5800629c 100644 --- a/python/grass/pygrass/rpc/base.py +++ b/python/grass/pygrass/rpc/base.py @@ -21,6 +21,7 @@ if TYPE_CHECKING: from multiprocessing.connection import Connection + from multiprocessing.process import BaseProcess from multiprocessing.synchronize import _LockLike @@ -105,7 +106,7 @@ def __init__(self) -> None: self.client_conn: Connection | None = None self.server_conn: Connection | None = None self.queue = None - self.server = None + self.server: BaseProcess | None = None self.checkThread: threading.Thread | None = None # Set to ask the current checker thread to return. self._checker_stop = threading.Event() diff --git a/python/grass/script/tests/utils_test.py b/python/grass/script/tests/utils_test.py index 58be7a9694b..bd051064b77 100644 --- a/python/grass/script/tests/utils_test.py +++ b/python/grass/script/tests/utils_test.py @@ -1,14 +1,20 @@ """Test functions in grass.script.utils""" +from __future__ import annotations + import multiprocessing import os from pathlib import Path +from typing import TYPE_CHECKING import pytest import grass.script as gs from grass.script import utils as gutils +if TYPE_CHECKING: + from collections.abc import Iterator + def test_named_separators(): """Check that named separators are recognized and correctly evaluated""" @@ -114,13 +120,13 @@ def test_resolve_nprocs_from_gisenv(empty_session): assert gs.resolve_nprocs(None, env=env) == gs.resolve_nprocs(nprocs) -def write_environ_value(path): +def write_environ_value(path: Path) -> None: """Write a variable from the environment to a file (worker process target)""" Path(path).write_text(os.environ["GRASS_TEST_ENVIRON_PROCESS"]) @pytest.fixture(params=multiprocessing.get_all_start_methods()) -def start_method(request): +def start_method(request: pytest.FixtureRequest) -> Iterator[str]: """Set each available multiprocessing start method as the default""" original = multiprocessing.get_start_method(allow_none=True) multiprocessing.set_start_method(request.param, force=True) @@ -128,7 +134,9 @@ def start_method(request): multiprocessing.set_start_method(original, force=True) -def test_environ_process_sees_current_environment(start_method, tmp_path, monkeypatch): +def test_environ_process_sees_current_environment( + start_method: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: """Worker gets the current environment with any start method With forkserver, a worker would otherwise get the environment from the time diff --git a/python/grass/script/utils.py b/python/grass/script/utils.py index 028b8e0ff01..ef5fbeaa0af 100644 --- a/python/grass/script/utils.py +++ b/python/grass/script/utils.py @@ -34,7 +34,9 @@ if TYPE_CHECKING: from _typeshed import FileDescriptorOrPath, StrOrBytesPath, StrPath - from collections.abc import Callable + from collections.abc import Callable, Iterable, Mapping + from multiprocessing.context import BaseContext + from multiprocessing.process import BaseProcess # Type variables @@ -146,14 +148,16 @@ def resolve_nprocs(nprocs: int | str | None = None, env=None) -> int: return max(1, available + n) -def _run_with_environ(environ, target, args): +def _run_with_environ( + environ: Mapping[str, str], target: Callable[..., object], args: Iterable[object] +) -> None: """Run target in a worker process after setting its environment""" os.environ.clear() os.environ.update(environ) target(*args) -def _get_multiprocessing_context(): +def _get_multiprocessing_context() -> BaseContext: """Return the multiprocessing context with the default start method. Unlike using the multiprocessing module directly (e.g., multiprocessing.Lock()), @@ -171,7 +175,9 @@ def _get_multiprocessing_context(): ) -def _environ_process(target, args=()): +def _environ_process( + target: Callable[..., object], args: Iterable[object] = () +) -> BaseProcess: """Create a worker process which runs with the environment of this process. Workers need the GRASS session environment (e.g., GISRC) of the parent. @@ -183,7 +189,9 @@ def _environ_process(target, args=()): The target and its arguments need to be picklable, which is required by the "spawn" and "forkserver" start methods. """ - return _get_multiprocessing_context().Process( + ctx = _get_multiprocessing_context() + # The type stubs miss Process in BaseContext, but all contexts have it. + return ctx.Process( # type: ignore[attr-defined] # ty: ignore[missing-attribute] target=_run_with_environ, args=(os.environ.copy(), target, args) ) diff --git a/python/grass/temporal/extract.py b/python/grass/temporal/extract.py index b4573bf12a1..dc1ae4fe46e 100644 --- a/python/grass/temporal/extract.py +++ b/python/grass/temporal/extract.py @@ -305,7 +305,7 @@ def extract_dataset( exitcodes = 0 for proc in proc_list: proc.join() - exitcodes += proc.exitcode + exitcodes += proc.exitcode or 0 if exitcodes != 0: dbif.close() msgr.fatal(_("Error in computation process")) diff --git a/python/grass/temporal/mapcalc.py b/python/grass/temporal/mapcalc.py index 8eef34010c3..d0717c557bc 100644 --- a/python/grass/temporal/mapcalc.py +++ b/python/grass/temporal/mapcalc.py @@ -321,7 +321,7 @@ def dataset_mapcalculator( exitcodes = 0 for proc in proc_list: proc.join() - exitcodes += proc.exitcode + exitcodes += proc.exitcode or 0 if exitcodes != 0: dbif.close() From 9875fa5712cbc6fbf473d1cf5557914e7e76fa59 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 15:33:18 +0000 Subject: [PATCH 04/13] grass.pygrass: Fix the MultiModule doctests for any start method Check the process returned by MultiModule.run() against BaseProcess, because the processes of a multiprocessing context are not instances of multiprocessing.Process. Check the exit code of the process in the GridModule tests, since failures of the module were not reported. Exclude fork on macOS from the start methods of the environment test. Written with the help of an AI assistant; tested with Python 3.13 and 3.15. --- python/grass/pygrass/modules/interface/module.py | 12 ++++++------ .../modules/tests/grass_pygrass_grid_test.py | 14 ++++++++++++-- python/grass/script/tests/utils_test.py | 10 +++++++++- 3 files changed, 27 insertions(+), 9 deletions(-) diff --git a/python/grass/pygrass/modules/interface/module.py b/python/grass/pygrass/modules/interface/module.py index cc7b0d12551..7272f9299ba 100644 --- a/python/grass/pygrass/modules/interface/module.py +++ b/python/grass/pygrass/modules/interface/module.py @@ -917,7 +917,7 @@ class MultiModule: >>> from grass.pygrass.modules import Module >>> from grass.pygrass.modules import MultiModule - >>> from multiprocessing import Process + >>> from multiprocessing.process import BaseProcess >>> import copy Synchronous module run @@ -955,7 +955,7 @@ class MultiModule: ... sync=False, ... ) >>> t = mm.run() - >>> isinstance(t, Process) + >>> isinstance(t, BaseProcess) True >>> m_list = mm.wait() >>> m_list[0].returncode @@ -981,7 +981,7 @@ class MultiModule: >>> str(mm) 'g.region format=plain -p ; g.region format=plain -p ; g.region format=plain -p ; g.region format=plain -p ; g.region format=plain -p' >>> t = mm.run() - >>> isinstance(t, Process) + >>> isinstance(t, BaseProcess) True >>> m_list = mm.wait() >>> m_list[0].returncode @@ -1043,7 +1043,7 @@ def run(self): be run one after the another. :return: None in case of ``self.finish_`` is True, - otherwise a multiprocessing.Process object that invokes the modules + otherwise a multiprocessing process object that invokes the modules """ if self.finish_ is True: @@ -1077,7 +1077,7 @@ def wait(self): def run_modules_in_temp_region(module_list, q): """Run the modules in a temporary region environment - This function is the argument for multiprocessing.Process class + This function is the target of the multiprocessing process in the MultiModule asynchronous execution. :param module_list: The list of modules to run in serial @@ -1096,7 +1096,7 @@ def run_modules_in_temp_region(module_list, q): def run_modules(module_list, q): """Run the modules - This function is the argument for multiprocessing.Process class + This function is the target of the multiprocessing process in the MultiModule asynchronous execution. :param module_list: The list of modules to run in serial diff --git a/python/grass/pygrass/modules/tests/grass_pygrass_grid_test.py b/python/grass/pygrass/modules/tests/grass_pygrass_grid_test.py index 7a24c2e3782..b39ba8c55de 100644 --- a/python/grass/pygrass/modules/tests/grass_pygrass_grid_test.py +++ b/python/grass/pygrass/modules/tests/grass_pygrass_grid_test.py @@ -43,9 +43,16 @@ def run_grid_module( # and thus can't easily change location/mapset, so we use a subprocess # to separate individual GridModule calls. def run_in_subprocess( - name: str, run_kwargs: dict[str, object] | None = None, **kwargs: object + name: str, + run_kwargs: dict[str, object] | None = None, + *, + succeeds: bool = True, + **kwargs: object, ) -> None: - """Run GridModule with the given arguments in a separate process""" + """Run GridModule with the given arguments in a separate process + + The process is expected to succeed unless *succeeds* is false. + """ process = multiprocessing.Process( target=run_grid_module, args=(os.environ.copy(), name), @@ -53,6 +60,7 @@ def run_in_subprocess( ) process.start() process.join() + assert (process.exitcode == 0) == succeeds @pytest.mark.needs_solo_run @@ -160,6 +168,8 @@ def test_cleans(tmp_path, clean, surface): aspect="aspect", mapset_prefix=mapset_prefix, run_kwargs={"clean": clean}, + # A missing input map makes the module fail. + succeeds=surface == "surface", ) prefixed = 0 diff --git a/python/grass/script/tests/utils_test.py b/python/grass/script/tests/utils_test.py index bd051064b77..c2637882c52 100644 --- a/python/grass/script/tests/utils_test.py +++ b/python/grass/script/tests/utils_test.py @@ -4,6 +4,7 @@ import multiprocessing import os +import sys from pathlib import Path from typing import TYPE_CHECKING @@ -125,7 +126,14 @@ def write_environ_value(path: Path) -> None: Path(path).write_text(os.environ["GRASS_TEST_ENVIRON_PROCESS"]) -@pytest.fixture(params=multiprocessing.get_all_start_methods()) +# Fork is unsafe on macOS, which is why spawn is the default there. +@pytest.fixture( + params=[ + method + for method in multiprocessing.get_all_start_methods() + if not (method == "fork" and sys.platform == "darwin") + ] +) def start_method(request: pytest.FixtureRequest) -> Iterator[str]: """Set each available multiprocessing start method as the default""" original = multiprocessing.get_start_method(allow_none=True) From d0e9b3463cd0f7189063483f9c5354094a3c2f0f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 15:53:34 +0000 Subject: [PATCH 05/13] grass.script: Document the main guard and use one multiprocessing context Scripts which use grass.temporal or the grass.pygrass servers need to run their code under a main guard with the spawn and forkserver start methods, which is now also needed on Linux with Python 3.14 and later. Describe it in the temporal framework documentation and add the guard to its examples. Let _environ_process() take the context, so that the process, the locks, the pipes and the queues use the same one even when the application changes the start method in between. Written with the help of an AI assistant; tested with Python 3.11, 3.13 and 3.15. --- python/grass/docs/src/temporal_framework.rst | 210 ++++++++++-------- python/grass/pygrass/messages/__init__.py | 4 +- .../grass/pygrass/modules/interface/module.py | 7 +- python/grass/pygrass/rpc/__init__.py | 2 +- python/grass/pygrass/rpc/base.py | 2 +- python/grass/script/tests/utils_test.py | 32 ++- python/grass/script/utils.py | 11 +- .../grass/temporal/c_libraries_interface.py | 2 +- 8 files changed, 163 insertions(+), 107 deletions(-) diff --git a/python/grass/docs/src/temporal_framework.rst b/python/grass/docs/src/temporal_framework.rst index 95bbe080f0f..277c191d130 100644 --- a/python/grass/docs/src/temporal_framework.rst +++ b/python/grass/docs/src/temporal_framework.rst @@ -262,6 +262,18 @@ Here the full list of all temporal modules: Examples -------- +Scripts using the temporal framework or the *pygrass* servers +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The temporal framework starts server processes (see ``tgis.init()``). They are +started with the default start method of the Python *multiprocessing* module: +*spawn* on Windows and macOS and, since Python 3.14, *forkserver* on Linux. +These methods import the main script again in the server process, so the code +which uses the temporal framework (or *pygrass* tools such as ``Messenger`` +and ``DataProvider``) needs to be in a function called under +``if __name__ == "__main__":``, as in the examples below. Without it, a script +fails with an error such as ``Connection reset by peer``. + Howto start example ^^^^^^^^^^^^^^^^^^^ @@ -275,48 +287,54 @@ to access its registered maps. import grass.temporal as tgis import grass.script as gs - # Make sure the temporal database exists - # and set the temporal GIS environment - tgis.init() - # We create the temporal database interface for fast processing - dbif = tgis.SQLDatabaseInterfaceConnection() - dbif.connect() + def main(): + # Make sure the temporal database exists + # and set the temporal GIS environment + tgis.init() - # The id of a space time raster dataset is build from its name and its mapset - id = "test@PERMANENT" + # We create the temporal database interface for fast processing + dbif = tgis.SQLDatabaseInterfaceConnection() + dbif.connect() - # We create a space time raster dataset object - strds = tgis.SpaceTimeRasterDataset(id) + # The id of a space time raster dataset is build from its name and its mapset + id = "test@PERMANENT" - # Check if the space time raster dataset is in the temporal database - if strds.is_in_db(dbif=dbif) is False: - dbif.close() - gs.fatal(_("Space time %s dataset <%s> not found") % ( - strds.get_new_map_instance(None).get_type(), id)) + # We create a space time raster dataset object + strds = tgis.SpaceTimeRasterDataset(id) - # Fill the object with the content from the temporal database - strds.select(dbif=dbif) + # Check if the space time raster dataset is in the temporal database + if strds.is_in_db(dbif=dbif) is False: + dbif.close() + gs.fatal(_("Space time %s dataset <%s> not found") % ( + strds.get_new_map_instance(None).get_type(), id)) - # Print information about the space time raster dataset to stdout - strds.print_info() + # Fill the object with the content from the temporal database + strds.select(dbif=dbif) - # Get all maps that are registered in the strds and print - # information about the maps to stdout - maps = strds.get_registered_maps_as_objects(dbif=dbif) + # Print information about the space time raster dataset to stdout + strds.print_info() - # We iterate over the temporal sorted map list - for map in maps: - # We fill the map object with the content - # from the temporal database. We use the existing - # database connection, otherwise a new connection - # will be established for each map object - # which slows the processing down - map.select(dbif=dbif) - map.print_info() + # Get all maps that are registered in the strds and print + # information about the maps to stdout + maps = strds.get_registered_maps_as_objects(dbif=dbif) - # Close the database connection - dbif.close() + # We iterate over the temporal sorted map list + for map in maps: + # We fill the map object with the content + # from the temporal database. We use the existing + # database connection, otherwise a new connection + # will be established for each map object + # which slows the processing down + map.select(dbif=dbif) + map.print_info() + + # Close the database connection + dbif.close() + + + if __name__ == "__main__": + main() Creation of a space time dataset @@ -332,52 +350,58 @@ for different space time datasets (raster, 3D raster and vector): import grass.temporal as tgis import grass.script as gs - # The id of the new space time dataset - id="test@PERMANENT" - # The title of the new space time dataset - title="This is a test dataset" - # The description of the space time dataset - description="The description" - # The type of the space time dataset (strds, str3ds or stvds) - type="strds" - # The temporal type of the space time dataset (absolute or relative) - temporal_type="absolute" - - # Make sure the temporal database exists - # and set the temporal GIS environment - tgis.init() - - # We use the dataset factory to create an new space time dataset instance of a specific type - stds = tgis.dataset_factory(type, id) - - # We need a dtabase connection to insert the content of the space time dataset - dbif = tgis.SQLDatabaseInterfaceConnection() - dbif.connect() - - # First we check if the dataset is already in the database - if stds.is_in_db(dbif=dbif) and overwrite is False: - dbif.close() - gs.fatal(_("Space time %s dataset <%s> is already in the database. " - "Use the overwrite flag.") % - (stds.get_new_map_instance(None).get_type(), name)) - - # We delete the exiting dataset and create a new one in case we are allowed to overwrite it - if stds.is_in_db(dbif=dbif) and overwrite is True: - gs.warning(_("Overwrite space time %s dataset <%s> " - "and unregister all maps.") % - (stds.get_new_map_instance(None).get_type(), name)) - stds.delete(dbif=dbif) - stds = stds.get_new_instance(id) - # We set the initial values. This function also created the command history. - stds.set_initial_values(temporal_type=temporaltype, semantic_type="mean", - title=title, description=description) + def main(): + # The id of the new space time dataset + id="test@PERMANENT" + # The title of the new space time dataset + title="This is a test dataset" + # The description of the space time dataset + description="The description" + # The type of the space time dataset (strds, str3ds or stvds) + type="strds" + # The temporal type of the space time dataset (absolute or relative) + temporal_type="absolute" + + # Make sure the temporal database exists + # and set the temporal GIS environment + tgis.init() + + # We use the dataset factory to create an new space time dataset instance of a specific type + stds = tgis.dataset_factory(type, id) + + # We need a dtabase connection to insert the content of the space time dataset + dbif = tgis.SQLDatabaseInterfaceConnection() + dbif.connect() + + # First we check if the dataset is already in the database + if stds.is_in_db(dbif=dbif) and overwrite is False: + dbif.close() + gs.fatal(_("Space time %s dataset <%s> is already in the database. " + "Use the overwrite flag.") % + (stds.get_new_map_instance(None).get_type(), name)) + + # We delete the exiting dataset and create a new one in case we are allowed to overwrite it + if stds.is_in_db(dbif=dbif) and overwrite is True: + gs.warning(_("Overwrite space time %s dataset <%s> " + "and unregister all maps.") % + (stds.get_new_map_instance(None).get_type(), name)) + stds.delete(dbif=dbif) + stds = stds.get_new_instance(id) + + # We set the initial values. This function also created the command history. + stds.set_initial_values(temporal_type=temporaltype, semantic_type="mean", + title=title, description=description) + + # Now we can insert the new space time dataset in the database + stds.insert(dbif=dbif) + + # Close the database connection + dbif.close() - # Now we can insert the new space time dataset in the database - stds.insert(dbif=dbif) - # Close the database connection - dbif.close() + if __name__ == "__main__": + main() Temporal shifting @@ -388,27 +412,33 @@ Temporal shifting import grass.script as gs import grass.temporal as tgis - id="test@PERMANENT" - type="strds" - # Make sure the temporal database exists - tgis.init() + def main(): + id="test@PERMANENT" + type="strds" - dbif = tgis.SQLDatabaseInterfaceConnection() - dbif.connect() + # Make sure the temporal database exists + tgis.init() - stds = tgis.dataset_factory(type, id) + dbif = tgis.SQLDatabaseInterfaceConnection() + dbif.connect() - if stds.is_in_db(dbif) is False: - dbif.close() - gs.fatal(_("Space time dataset <%s> not found in temporal database") % (id)) + stds = tgis.dataset_factory(type, id) + + if stds.is_in_db(dbif) is False: + dbif.close() + gs.fatal(_("Space time dataset <%s> not found in temporal database") % (id)) - stds.select(dbif=dbif) + stds.select(dbif=dbif) + + stds.snap(dbif=dbif) + + stds.update_command_string(dbif=dbif) + dbif.close() - stds.snap(dbif=dbif) - stds.update_command_string(dbif=dbif) - dbif.close() + if __name__ == "__main__": + main() References diff --git a/python/grass/pygrass/messages/__init__.py b/python/grass/pygrass/messages/__init__.py index 830cfc2bd2e..a0e2c9d30f7 100644 --- a/python/grass/pygrass/messages/__init__.py +++ b/python/grass/pygrass/messages/__init__.py @@ -184,7 +184,7 @@ def __init__(self, raise_on_error: bool = False) -> None: self.client_conn, self.server_conn = ctx.Pipe() self.lock = ctx.Lock() self.server = _environ_process( - target=message_server, args=(self.lock, self.server_conn) + target=message_server, args=(self.lock, self.server_conn), ctx=ctx ) self.server.daemon = True self.server.start() @@ -195,7 +195,7 @@ def start_server(self) -> None: self.client_conn, self.server_conn = ctx.Pipe() self.lock = ctx.Lock() self.server = _environ_process( - target=message_server, args=(self.lock, self.server_conn) + target=message_server, args=(self.lock, self.server_conn), ctx=ctx ) self.server.daemon = True self.server.start() diff --git a/python/grass/pygrass/modules/interface/module.py b/python/grass/pygrass/modules/interface/module.py index 7272f9299ba..269ff72da24 100644 --- a/python/grass/pygrass/modules/interface/module.py +++ b/python/grass/pygrass/modules/interface/module.py @@ -1018,7 +1018,8 @@ def __init__(self, module_list, sync=True, set_temp_region=False): self.set_temp_region = set_temp_region self.finish_ = sync # We use the same variable name a Module self.p = None - self.q = _get_multiprocessing_context().Queue() + self.ctx = _get_multiprocessing_context() + self.q = self.ctx.Queue() def __str__(self): """Return the command string that can be executed in a shell""" @@ -1053,10 +1054,10 @@ def run(self): return None if self.set_temp_region is True: self.p = _environ_process( - run_modules_in_temp_region, (self.module_list, self.q) + run_modules_in_temp_region, (self.module_list, self.q), self.ctx ) else: - self.p = _environ_process(run_modules, (self.module_list, self.q)) + self.p = _environ_process(run_modules, (self.module_list, self.q), self.ctx) self.p.start() return self.p diff --git a/python/grass/pygrass/rpc/__init__.py b/python/grass/pygrass/rpc/__init__.py index 7ff966d0e7f..acfb271bc71 100644 --- a/python/grass/pygrass/rpc/__init__.py +++ b/python/grass/pygrass/rpc/__init__.py @@ -248,7 +248,7 @@ def start_server(self): self.client_conn, self.server_conn = ctx.Pipe(True) self.lock = ctx.Lock() self.server = _environ_process( - target=data_provider_server, args=(self.lock, self.server_conn) + target=data_provider_server, args=(self.lock, self.server_conn), ctx=ctx ) self.server.daemon = True self.server.start() diff --git a/python/grass/pygrass/rpc/base.py b/python/grass/pygrass/rpc/base.py index 1ad5800629c..6dddebe7c2a 100644 --- a/python/grass/pygrass/rpc/base.py +++ b/python/grass/pygrass/rpc/base.py @@ -166,7 +166,7 @@ def start_server(self): self.client_conn, self.server_conn = ctx.Pipe(True) self.lock = ctx.Lock() self.server = _environ_process( - target=dummy_server, args=(self.lock, self.server_conn) + target=dummy_server, args=(self.lock, self.server_conn), ctx=ctx ) self.server.daemon = True self.server.start() diff --git a/python/grass/script/tests/utils_test.py b/python/grass/script/tests/utils_test.py index c2637882c52..7b5d232882d 100644 --- a/python/grass/script/tests/utils_test.py +++ b/python/grass/script/tests/utils_test.py @@ -127,13 +127,14 @@ def write_environ_value(path: Path) -> None: # Fork is unsafe on macOS, which is why spawn is the default there. -@pytest.fixture( - params=[ - method - for method in multiprocessing.get_all_start_methods() - if not (method == "fork" and sys.platform == "darwin") - ] -) +START_METHODS = [ + method + for method in multiprocessing.get_all_start_methods() + if not (method == "fork" and sys.platform == "darwin") +] + + +@pytest.fixture(params=START_METHODS) def start_method(request: pytest.FixtureRequest) -> Iterator[str]: """Set each available multiprocessing start method as the default""" original = multiprocessing.get_start_method(allow_none=True) @@ -160,6 +161,23 @@ def test_environ_process_sees_current_environment( assert path.read_text() == value +@pytest.mark.parametrize("method", START_METHODS) +def test_environ_process_uses_given_context( + method: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Worker is started with the given context, not the default one""" + monkeypatch.setenv("GRASS_TEST_ENVIRON_PROCESS", "value") + ctx = multiprocessing.get_context(method) + path = tmp_path / "result" + process = gutils._environ_process(write_environ_value, (path,), ctx) + # The type stubs miss Process in BaseContext. + assert isinstance(process, ctx.Process) # type: ignore[attr-defined] # ty: ignore[missing-attribute] + process.start() + process.join() + assert process.exitcode == 0 + assert path.read_text() == "value" + + @pytest.mark.parametrize( "name", ["and", "AND", "aNd", "or", "OR", "Or", "not", "NOT", "nOt"] ) diff --git a/python/grass/script/utils.py b/python/grass/script/utils.py index ef5fbeaa0af..aeac0b83232 100644 --- a/python/grass/script/utils.py +++ b/python/grass/script/utils.py @@ -176,7 +176,9 @@ def _get_multiprocessing_context() -> BaseContext: def _environ_process( - target: Callable[..., object], args: Iterable[object] = () + target: Callable[..., object], + args: Iterable[object] = (), + ctx: BaseContext | None = None, ) -> BaseProcess: """Create a worker process which runs with the environment of this process. @@ -188,8 +190,13 @@ def _environ_process( The target and its arguments need to be picklable, which is required by the "spawn" and "forkserver" start methods. + + Locks, pipes, and queues given to the process need to be created in the same + context, so pass it as *ctx*. The context from _get_multiprocessing_context() + is used by default. """ - ctx = _get_multiprocessing_context() + if ctx is None: + ctx = _get_multiprocessing_context() # The type stubs miss Process in BaseContext, but all contexts have it. return ctx.Process( # type: ignore[attr-defined] # ty: ignore[missing-attribute] target=_run_with_environ, args=(os.environ.copy(), target, args) diff --git a/python/grass/temporal/c_libraries_interface.py b/python/grass/temporal/c_libraries_interface.py index 950fb1dcd04..c17f44b4e27 100644 --- a/python/grass/temporal/c_libraries_interface.py +++ b/python/grass/temporal/c_libraries_interface.py @@ -1470,7 +1470,7 @@ def start_server(self) -> None: self.client_conn, self.server_conn = ctx.Pipe(True) self.lock = ctx.Lock() self.server = _environ_process( - target=c_library_server, args=(self.lock, self.server_conn) + target=c_library_server, args=(self.lock, self.server_conn), ctx=ctx ) self.server.daemon = True self.server.start() From 019c15c6ae9adb3e0d2ba3ec25f9d3e259124bac Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 16:21:52 +0000 Subject: [PATCH 06/13] grass.temporal: Correct what happens without the main guard in the docs Without the main guard, Messenger does not raise an error, its messages are just not printed, so the note did not cover all failures. Also call Messenger and DataProvider classes, not tools, which in GRASS are the r.*, v.*, etc. commands. Written with the help of an AI assistant; tested by running scripts without the main guard using tgis.init(), Messenger, and DataProvider with Python 3.15 on Linux and by building the page with Sphinx. --- python/grass/docs/src/temporal_framework.rst | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/python/grass/docs/src/temporal_framework.rst b/python/grass/docs/src/temporal_framework.rst index 277c191d130..27970622659 100644 --- a/python/grass/docs/src/temporal_framework.rst +++ b/python/grass/docs/src/temporal_framework.rst @@ -269,10 +269,11 @@ The temporal framework starts server processes (see ``tgis.init()``). They are started with the default start method of the Python *multiprocessing* module: *spawn* on Windows and macOS and, since Python 3.14, *forkserver* on Linux. These methods import the main script again in the server process, so the code -which uses the temporal framework (or *pygrass* tools such as ``Messenger`` +which uses the temporal framework (or *pygrass* classes such as ``Messenger`` and ``DataProvider``) needs to be in a function called under -``if __name__ == "__main__":``, as in the examples below. Without it, a script -fails with an error such as ``Connection reset by peer``. +``if __name__ == "__main__":``, as in the examples below. Without it, the +server processes fail, so a script fails with an error such as +``Connection reset by peer`` or its messages are not printed. Howto start example ^^^^^^^^^^^^^^^^^^^ From e4c1021ee5232e365bd81d863922b34dc60d19d3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 16:21:52 +0000 Subject: [PATCH 07/13] grass.temporal: Check that the message server prints in the start method test A message server which fails to start loses the messages without an error, so the test passed even if the messages were not printed. Written with the help of an AI assistant; tested with pytest on Python 3.11, 3.13, and 3.15 and checked that the test fails when no message is sent. --- .../grass_temporal_c_libraries_interface_start_method_test.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/python/grass/temporal/tests/grass_temporal_c_libraries_interface_start_method_test.py b/python/grass/temporal/tests/grass_temporal_c_libraries_interface_start_method_test.py index 159a133cffe..17fe3c68579 100644 --- a/python/grass/temporal/tests/grass_temporal_c_libraries_interface_start_method_test.py +++ b/python/grass/temporal/tests/grass_temporal_c_libraries_interface_start_method_test.py @@ -35,7 +35,7 @@ def main(): mapset = gs.gisenv()["MAPSET"] messenger = Messenger() - messenger.message("test") + messenger.message("Message from the server") messenger.stop() server = RPCServerBase() @@ -79,6 +79,7 @@ def test_servers_start_with_start_method(tmp_path, start_method): check=False, ) assert result.returncode == 0, result.stderr + assert "Message from the server" in result.stderr, result.stderr # A failing server check thread does not change the exit code. assert "Traceback" not in result.stderr, result.stderr assert "leaked semaphore" not in result.stderr, result.stderr From f658ed8fa49009e033d1d41f3a0bb40d69f58516 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 16:21:53 +0000 Subject: [PATCH 08/13] grass.script: Use the Path argument directly in the worker process test The argument is already a Path, so wrapping it again is not needed and Path is only used for type annotations. Written with the help of an AI assistant; tested with pytest on Python 3.11 and 3.15. --- python/grass/script/tests/utils_test.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/grass/script/tests/utils_test.py b/python/grass/script/tests/utils_test.py index 7b5d232882d..85aa314219e 100644 --- a/python/grass/script/tests/utils_test.py +++ b/python/grass/script/tests/utils_test.py @@ -5,7 +5,6 @@ import multiprocessing import os import sys -from pathlib import Path from typing import TYPE_CHECKING import pytest @@ -15,6 +14,7 @@ if TYPE_CHECKING: from collections.abc import Iterator + from pathlib import Path def test_named_separators(): @@ -123,7 +123,7 @@ def test_resolve_nprocs_from_gisenv(empty_session): def write_environ_value(path: Path) -> None: """Write a variable from the environment to a file (worker process target)""" - Path(path).write_text(os.environ["GRASS_TEST_ENVIRON_PROCESS"]) + path.write_text(os.environ["GRASS_TEST_ENVIRON_PROCESS"]) # Fork is unsafe on macOS, which is why spawn is the default there. From 94ad70cd715af46be875f25206b54f7691251425 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 19:03:40 +0000 Subject: [PATCH 09/13] grass.temporal: Treat any nonzero exit code of the parallel tools as a failure Summing the exit codes let a negative code (a tool killed by a signal) cancel out a positive one, so the failure went unnoticed. --- python/grass/temporal/extract.py | 10 ++++------ python/grass/temporal/mapcalc.py | 10 ++++------ 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/python/grass/temporal/extract.py b/python/grass/temporal/extract.py index 7e93665cd60..54af4495936 100644 --- a/python/grass/temporal/extract.py +++ b/python/grass/temporal/extract.py @@ -304,10 +304,8 @@ def extract_dataset( # Wait for the tools when the maximum number of them is running if proc_count == nprocs: proc_count = 0 - exitcodes = 0 - for proc in proc_list: - exitcodes += proc.wait() - if exitcodes != 0: + exitcodes = [proc.wait() for proc in proc_list] + if any(exitcodes): dbif.close() msgr.fatal(_("Error in computation process")) @@ -319,8 +317,8 @@ def extract_dataset( finally: # Wait for the last batch, which may be incomplete or follow skipped # rows, and for the started tools if an exception is raised - exitcodes = sum(proc.wait() for proc in proc_list) - if exitcodes != 0: + exitcodes = [proc.wait() for proc in proc_list] + if any(exitcodes): dbif.close() msgr.fatal(_("Error in computation process")) diff --git a/python/grass/temporal/mapcalc.py b/python/grass/temporal/mapcalc.py index 7326647e38e..f8cf49a514e 100644 --- a/python/grass/temporal/mapcalc.py +++ b/python/grass/temporal/mapcalc.py @@ -330,11 +330,9 @@ def dataset_mapcalculator( if proc_count != nprocs: continue proc_count = 0 - exitcodes = 0 - for proc in proc_list: - exitcodes += proc.wait() + exitcodes = [proc.wait() for proc in proc_list] - if exitcodes != 0: + if any(exitcodes): dbif.close() msgr.fatal(_("Error while mapcalc computation")) @@ -343,8 +341,8 @@ def dataset_mapcalculator( finally: # Wait for the last batch, which may be incomplete or follow skipped # samples, and for the started tools if an exception is raised - exitcodes = sum(proc.wait() for proc in proc_list) - if exitcodes != 0: + exitcodes = [proc.wait() for proc in proc_list] + if any(exitcodes): dbif.close() msgr.fatal(_("Error while mapcalc computation")) From 0716db43b285be5ebd40049331c46c2755053168 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 19:23:12 +0000 Subject: [PATCH 10/13] t.rast.mapcalc: Test that any nonzero exit code of the parallel tools is a failure --- .../tests/test_t_rast_mapcalc_exit_codes.py | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 temporal/t.rast.mapcalc/tests/test_t_rast_mapcalc_exit_codes.py diff --git a/temporal/t.rast.mapcalc/tests/test_t_rast_mapcalc_exit_codes.py b/temporal/t.rast.mapcalc/tests/test_t_rast_mapcalc_exit_codes.py new file mode 100644 index 00000000000..5ac44c3c98c --- /dev/null +++ b/temporal/t.rast.mapcalc/tests/test_t_rast_mapcalc_exit_codes.py @@ -0,0 +1,57 @@ +"""Test how t.rast.mapcalc evaluates the exit codes of the parallel tools. + +SPDX-FileCopyrightText: 2026 GRASS Development Team +SPDX-License-Identifier: GPL-2.0-or-later +""" + +import os + +import pytest + +import grass.script as gs +import grass.temporal as tgis + + +class FakeProcess: + """Process which has already finished with the given exit code.""" + + def __init__(self, exitcode): + self.exitcode = exitcode + + def wait(self): + return self.exitcode + + +@pytest.mark.parametrize( + "exitcodes", + [ + [1, 0, 0], + [0, 0, 1], + # Failures with a different sign must not cancel each other out. + [1, -1, 0], + [0, 0, -9], + ], +) +@pytest.mark.parametrize("nprocs", [2, 3]) +def test_failed_tool_is_reported(mapcalc_session, monkeypatch, exitcodes, nprocs): + """A nonzero exit code is a failure in a full and in the last, partial batch.""" + # tgis reads the session from os.environ. + for key, value in mapcalc_session.env.items(): + if os.environ.get(key) != value: + monkeypatch.setenv(key, value) + tgis.init() + codes = iter(exitcodes) + monkeypatch.setattr( + gs, "start_command", lambda *args, **kwargs: FakeProcess(next(codes)) + ) + # The temporal message interface exits on a fatal error. + with pytest.raises(SystemExit): + tgis.dataset_mapcalculator( + inputs="precip_abs1,precip_abs2", + output="precip_exit_codes", + type="raster", + expression="precip_abs1 + precip_abs2", + base="exit_codes", + method=["equal"], + nprocs=nprocs, + ) From 9639ef6b1b19b74a9fa07d30108c1e9b4264ce31 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 19:37:13 +0000 Subject: [PATCH 11/13] t.rast.extract: Test that any nonzero exit code of the parallel tools is a failure --- .../tests/test_t_rast_extract_pytest.py | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/temporal/t.rast.extract/tests/test_t_rast_extract_pytest.py b/temporal/t.rast.extract/tests/test_t_rast_extract_pytest.py index b8701937895..3d2d5afd348 100644 --- a/temporal/t.rast.extract/tests/test_t_rast_extract_pytest.py +++ b/temporal/t.rast.extract/tests/test_t_rast_extract_pytest.py @@ -19,6 +19,7 @@ import pytest import grass.script as gs +import grass.temporal as tgis from grass.tools import Tools @@ -196,3 +197,52 @@ def test_selection_and_expression_simple_name(session): assert strds_info[k] == v, ( f"Expected value for key '{k}' is {v}. Got: {strds_info[k]}" ) + + +class FakeProcess: + """Process which has already finished with the given exit code.""" + + def __init__(self, exitcode): + self.exitcode = exitcode + + def wait(self): + return self.exitcode + + +@pytest.mark.parametrize( + "exitcodes", + [ + [1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1], + # Failures with a different sign must not cancel each other out. + [1, -1, 0, 0, 0, 0], + [0, 0, 0, 0, 1, -1], + [0, 0, 0, 0, 0, -9], + ], +) +def test_failed_tool_is_reported(session, monkeypatch, exitcodes): + """A nonzero exit code is a failure in a full and in the last, partial batch. + + There are six maps and four processes, so the last batch has two maps. + """ + # tgis reads the session from os.environ. + for key, value in session.env.items(): + if os.environ.get(key) != value: + monkeypatch.setenv(key, value) + tgis.init() + codes = iter(exitcodes) + monkeypatch.setattr( + gs, "start_command", lambda *args, **kwargs: FakeProcess(next(codes)) + ) + # The temporal message interface exits on a fatal error. + with pytest.raises(SystemExit): + tgis.extract_dataset( + input="perc", + output="perc_exit_codes", + type="raster", + where="start_time > '2025-07-01'", + expression="perc@perc + 1", + base="perc_exit_codes", + time_suffix="num", + nprocs=4, + ) From cd33c98203fa5ea306a59746553b482214004889 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 19:38:24 +0000 Subject: [PATCH 12/13] temporal: Check the error message in the exit code tests The fake tools create no maps, so a later step fails too and the SystemExit alone does not show that the exit codes were handled. --- temporal/t.rast.extract/tests/test_t_rast_extract_pytest.py | 4 +++- .../t.rast.mapcalc/tests/test_t_rast_mapcalc_exit_codes.py | 6 +++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/temporal/t.rast.extract/tests/test_t_rast_extract_pytest.py b/temporal/t.rast.extract/tests/test_t_rast_extract_pytest.py index 3d2d5afd348..a82daf0a524 100644 --- a/temporal/t.rast.extract/tests/test_t_rast_extract_pytest.py +++ b/temporal/t.rast.extract/tests/test_t_rast_extract_pytest.py @@ -220,7 +220,7 @@ def wait(self): [0, 0, 0, 0, 0, -9], ], ) -def test_failed_tool_is_reported(session, monkeypatch, exitcodes): +def test_failed_tool_is_reported(session, monkeypatch, capfd, exitcodes): """A nonzero exit code is a failure in a full and in the last, partial batch. There are six maps and four processes, so the last batch has two maps. @@ -246,3 +246,5 @@ def test_failed_tool_is_reported(session, monkeypatch, exitcodes): time_suffix="num", nprocs=4, ) + # Later steps fail too, because the fake tools create no maps. + assert "Error in computation process" in capfd.readouterr().err diff --git a/temporal/t.rast.mapcalc/tests/test_t_rast_mapcalc_exit_codes.py b/temporal/t.rast.mapcalc/tests/test_t_rast_mapcalc_exit_codes.py index 5ac44c3c98c..7da1d9b35e4 100644 --- a/temporal/t.rast.mapcalc/tests/test_t_rast_mapcalc_exit_codes.py +++ b/temporal/t.rast.mapcalc/tests/test_t_rast_mapcalc_exit_codes.py @@ -33,7 +33,9 @@ def wait(self): ], ) @pytest.mark.parametrize("nprocs", [2, 3]) -def test_failed_tool_is_reported(mapcalc_session, monkeypatch, exitcodes, nprocs): +def test_failed_tool_is_reported( + mapcalc_session, monkeypatch, capfd, exitcodes, nprocs +): """A nonzero exit code is a failure in a full and in the last, partial batch.""" # tgis reads the session from os.environ. for key, value in mapcalc_session.env.items(): @@ -55,3 +57,5 @@ def test_failed_tool_is_reported(mapcalc_session, monkeypatch, exitcodes, nprocs method=["equal"], nprocs=nprocs, ) + # Later steps fail too, because the fake tools create no maps. + assert "Error while mapcalc computation" in capfd.readouterr().err From 17564385f35031f44d767148c7a671b7677abeb8 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 00:30:37 +0000 Subject: [PATCH 13/13] grass.script: Make test modules importable in spawn and forkserver workers With --import-mode=importlib, pytest imports test modules by their path relative to the root directory without adding the root to sys.path. The worker processes then could not import the test module to get the target function, unless the current directory happened to be the root and was on sys.path, as with the trailing colon in PYTHONPATH in CI. --- .../modules/tests/grass_pygrass_grid_test.py | 13 +++++++++++++ python/grass/script/tests/utils_test.py | 13 +++++++++++++ 2 files changed, 26 insertions(+) diff --git a/python/grass/pygrass/modules/tests/grass_pygrass_grid_test.py b/python/grass/pygrass/modules/tests/grass_pygrass_grid_test.py index b39ba8c55de..7e786dba47c 100644 --- a/python/grass/pygrass/modules/tests/grass_pygrass_grid_test.py +++ b/python/grass/pygrass/modules/tests/grass_pygrass_grid_test.py @@ -39,6 +39,19 @@ def run_grid_module( GridModule(name, **kwargs).run(**run_kwargs) +@pytest.fixture(autouse=True) +def importable_test_module( + monkeypatch: pytest.MonkeyPatch, pytestconfig: pytest.Config +) -> None: + """Make this module importable by name in spawn and forkserver workers + + With --import-mode=importlib, pytest imports this module by its path + relative to the root directory without adding the root to sys.path, + so a worker could not import it to get the target function. + """ + monkeypatch.syspath_prepend(str(pytestconfig.rootpath)) + + # GridModule uses C libraries which can easily initialize only once # and thus can't easily change location/mapset, so we use a subprocess # to separate individual GridModule calls. diff --git a/python/grass/script/tests/utils_test.py b/python/grass/script/tests/utils_test.py index 85aa314219e..c073bec4f14 100644 --- a/python/grass/script/tests/utils_test.py +++ b/python/grass/script/tests/utils_test.py @@ -126,6 +126,19 @@ def write_environ_value(path: Path) -> None: path.write_text(os.environ["GRASS_TEST_ENVIRON_PROCESS"]) +@pytest.fixture(autouse=True) +def importable_test_module( + monkeypatch: pytest.MonkeyPatch, pytestconfig: pytest.Config +) -> None: + """Make this module importable by name in spawn and forkserver workers + + With --import-mode=importlib, pytest imports this module by its path + relative to the root directory without adding the root to sys.path, + so a worker could not import it to get the target function. + """ + monkeypatch.syspath_prepend(str(pytestconfig.rootpath)) + + # Fork is unsafe on macOS, which is why spawn is the default there. START_METHODS = [ method