diff --git a/python/grass/docs/src/temporal_framework.rst b/python/grass/docs/src/temporal_framework.rst index 95bbe080f0f..27970622659 100644 --- a/python/grass/docs/src/temporal_framework.rst +++ b/python/grass/docs/src/temporal_framework.rst @@ -262,6 +262,19 @@ 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* classes such as ``Messenger`` +and ``DataProvider``) needs to be in a function called under +``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 ^^^^^^^^^^^^^^^^^^^ @@ -275,48 +288,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 +351,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 +413,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 e064e99d7a0..a0e2c9d30f7 100644 --- a/python/grass/pygrass/messages/__init__.py +++ b/python/grass/pygrass/messages/__init__.py @@ -19,7 +19,7 @@ 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, _get_multiprocessing_context if TYPE_CHECKING: from multiprocessing.connection import Connection @@ -183,8 +183,8 @@ def __init__(self, raise_on_error: bool = False) -> None: ctx = _get_multiprocessing_context() self.client_conn, self.server_conn = ctx.Pipe() self.lock = ctx.Lock() - self.server = ctx.Process( - target=message_server, args=(self.lock, self.server_conn) + self.server = _environ_process( + target=message_server, args=(self.lock, self.server_conn), ctx=ctx ) self.server.daemon = True self.server.start() @@ -194,8 +194,8 @@ def start_server(self) -> None: ctx = _get_multiprocessing_context() self.client_conn, self.server_conn = ctx.Pipe() self.lock = ctx.Lock() - self.server = ctx.Process( - target=message_server, args=(self.lock, self.server_conn) + self.server = _environ_process( + 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 814fb199e0e..ba4b0465790 100644 --- a/python/grass/pygrass/modules/interface/module.py +++ b/python/grass/pygrass/modules/interface/module.py @@ -1,10 +1,14 @@ -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 decode, resolve_nprocs +from grass.script.utils import ( + _environ_process, + _get_multiprocessing_context, + decode, + resolve_nprocs, +) from .docstring import docstring_property from .parameter import Parameter from .flag import Flag @@ -914,7 +918,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 @@ -952,7 +956,7 @@ class MultiModule: ... sync=False, ... ) >>> t = mm.run() - >>> isinstance(t, Process) + >>> isinstance(t, BaseProcess) True >>> m_list = mm.wait() >>> m_list[0].returncode @@ -978,7 +982,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 @@ -1015,7 +1019,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 = 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""" @@ -1040,7 +1045,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: @@ -1049,11 +1054,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), self.ctx ) 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.ctx) self.p.start() return self.p @@ -1074,7 +1079,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 @@ -1093,7 +1098,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 423ba8cb52a..97013d71ab1 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,81 @@ """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 -xfail_mp_spawn = pytest.mark.xfail( - multiprocessing.get_start_method() == "spawn", - reason="Multiprocessing using 'spawn' start method requires pickable functions", - raises=AttributeError, - strict=True, -) +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: 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 + 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(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. -def run_in_subprocess(function): - """Run function in a separate process""" - process = multiprocessing.Process(target=function) +def run_in_subprocess( + 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 + + The process is expected to succeed unless *succeeds* is false. + """ + process = multiprocessing.Process( + target=run_grid_module, + args=(os.environ.copy(), name), + kwargs={"run_kwargs": run_kwargs or {}, **kwargs}, + ) process.start() process.join() + assert (process.exitcode == 0) == succeeds -@xfail_mp_spawn @pytest.mark.needs_solo_run @pytest.mark.parametrize("processes", [*range(1, max_processes() + 1), None, 0, -1]) def test_processes(tmp_path, processes): @@ -43,20 +88,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 +106,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 +118,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 +143,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 +170,20 @@ 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}, + # A missing input map makes the module fail. + succeeds=surface == "surface", + ) prefixed = 0 for item in project.iterdir(): @@ -169,7 +198,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 +213,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 +249,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 +283,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..acfb271bc71 100644 --- a/python/grass/pygrass/rpc/__init__.py +++ b/python/grass/pygrass/rpc/__init__.py @@ -18,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 _get_multiprocessing_context +from grass.script.utils import _environ_process, _get_multiprocessing_context from .base import RPCServerBase @@ -247,8 +247,8 @@ def start_server(self): ctx = _get_multiprocessing_context() self.client_conn, self.server_conn = ctx.Pipe(True) self.lock = ctx.Lock() - self.server = ctx.Process( - target=data_provider_server, args=(self.lock, self.server_conn) + self.server = _environ_process( + 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 09a2ace09e3..6dddebe7c2a 100644 --- a/python/grass/pygrass/rpc/base.py +++ b/python/grass/pygrass/rpc/base.py @@ -17,10 +17,11 @@ 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, _get_multiprocessing_context 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() @@ -164,8 +165,8 @@ def start_server(self): ctx = _get_multiprocessing_context() self.client_conn, self.server_conn = ctx.Pipe(True) self.lock = ctx.Lock() - self.server = ctx.Process( - target=dummy_server, args=(self.lock, self.server_conn) + self.server = _environ_process( + 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 292dd6004d5..84afbdee9b5 100644 --- a/python/grass/script/tests/utils_test.py +++ b/python/grass/script/tests/utils_test.py @@ -1,13 +1,21 @@ """Test functions in grass.script.utils""" +from __future__ import annotations + import multiprocessing +import os import sys +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 + from pathlib import Path + def test_named_separators(): """Check that named separators are recognized and correctly evaluated""" @@ -117,13 +125,74 @@ 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: Path) -> None: + """Write a variable from the environment to a file (worker process target)""" + 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 + 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) + 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: 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 + the fork server was started, so start it with a different value 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("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( diff --git a/python/grass/script/utils.py b/python/grass/script/utils.py index e721dfc276d..3234f8ab48c 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 @@ -35,8 +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 @@ -159,27 +159,59 @@ def resolve_nprocs(nprocs: int | str | None = None, env=None) -> int: return max(1, available + n) +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() -> BaseContext: - """Return the multiprocessing context to use for GRASS worker processes. - - 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. + """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 - if sys.platform != "darwin" and "fork" in multiprocessing.get_all_start_methods(): - return multiprocessing.get_context("fork") - return multiprocessing.get_context() + 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: Callable[..., object], + args: Iterable[object] = (), + ctx: BaseContext | None = None, +) -> 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. + 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. + + 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. + """ + 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) + ) def diff_files( diff --git a/python/grass/temporal/c_libraries_interface.py b/python/grass/temporal/c_libraries_interface.py index be9e1b2d400..c17f44b4e27 100644 --- a/python/grass/temporal/c_libraries_interface.py +++ b/python/grass/temporal/c_libraries_interface.py @@ -28,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 _get_multiprocessing_context, encode +from grass.script.utils import _environ_process, _get_multiprocessing_context, encode import grass.script as gs if TYPE_CHECKING: @@ -1469,8 +1469,8 @@ 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( - target=c_library_server, args=(self.lock, self.server_conn) + self.server = _environ_process( + target=c_library_server, args=(self.lock, self.server_conn), ctx=ctx ) self.server.daemon = True self.server.start() 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")) 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..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 @@ -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 @@ -36,7 +35,7 @@ def main(): mapset = gs.gisenv()["MAPSET"] messenger = Messenger() - messenger.message("test") + messenger.message("Message from the server") messenger.stop() server = RPCServerBase() @@ -55,26 +54,32 @@ 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.""" +# 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" 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, ) 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 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..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 @@ -19,6 +19,7 @@ import pytest import grass.script as gs +import grass.temporal as tgis from grass.tools import Tools @@ -196,3 +197,54 @@ 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, 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. + """ + # 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, + ) + # 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 new file mode 100644 index 00000000000..7da1d9b35e4 --- /dev/null +++ b/temporal/t.rast.mapcalc/tests/test_t_rast_mapcalc_exit_codes.py @@ -0,0 +1,61 @@ +"""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, 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(): + 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, + ) + # Later steps fail too, because the fake tools create no maps. + assert "Error while mapcalc computation" in capfd.readouterr().err