Skip to content

Terminate all processes on error in parallel_run_from_cli - #624

Merged
yguclu merged 4 commits into
develfrom
yguclu-abort-parallel-run
Oct 27, 2026
Merged

yguclu merged 4 commits into
develfrom
yguclu-abort-parallel-run

Conversation

@yguclu

@yguclu yguclu commented Oct 11, 2026 •

Copy link
Copy Markdown
Member

Terminate all MPI processes when one of them raises an uncaught exception in psydac.utilities.parallel_utils.parallel_run_from_cli (fixes #621).

Without this, the other processes hang as soon as they wait for a message from the failing one, and a job on a cluster keeps its allocation until it reaches the wall-time limit. The same mechanism as in the launcher python -m mpi4py is used: the exception is passed to mpi4py.run.set_abort_status and re-raised, hence its traceback is printed and the failing process is cleaned up, then MPI_Abort is called at exit. This works with any MPI launcher (e.g. mpirun, mpiexec, or srun in a batch job), and does not require running scripts with python -m mpi4py.

  • In parallel_run_from_cli, abort all processes at exit in case of an uncaught exception in main, and document this behavior in the docstring
  • Add section "Running examples in parallel" to the Examples page of the documentation (docs/source/examples.rst), which very strongly recommends running every parallel script through parallel_run_from_cli
  • New module psydac.utilities.tests.test_parallel_utils, which tests parallel_run_from_cli in serial with and without an exception in main (the call to MPI_Abort is mocked)

The abort was also checked manually with a script failing on one of 4 processes: with the fix, the job terminates with exit code 1 after printing the traceback; without it, the job hangs.

This PR does not address PETSc-specific problems: once PETSc has been initialized (e.g. by converting a PSYDAC object to PETSc), the other processes may still hang on some systems, possibly because PetscFinalize waits for them at exit before MPI_Abort is called (see #635).

@codacy-production

codacy-production Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 7 complexity · 0 duplication

Metric Results
Complexity 7
Duplication 0

View in Codacy

🟢 Coverage 100.00% diff coverage · +0.05% coverage variation

Metric Results
Coverage variation ✅ +0.05% coverage variation
Diff coverage ✅ 100.00% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (6866096) 52327 33593 64.20%
Head commit (3495abb) 104712 (+52385) 67280 (+33687) 64.25% (+0.05%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#624) 30 30 100.00%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@yguclu
yguclu requested a review from a team October 11, 2026 15:29
@yguclu
yguclu marked this pull request as ready for review October 11, 2026 15:29
@yguclu yguclu added the Next Release Must be in next release label Oct 11, 2026
@yguclu yguclu assigned yguclu and campospinto and unassigned yguclu Oct 15, 2026
@FrederikSchnack

Copy link
Copy Markdown
Contributor

I reviewed this PR with Claude and it came up with an issue: The job still hangs if PETSc is used. The following script should replicate it as is described in the doc strings. Is this a relevant problem?

"""
Demonstrate that the abort-at-exit of PR #624 hangs once PETSc is in use.

One process raises an exception in `main`, while the others wait in a
barrier. `parallel_run_from_cli` should then terminate all the processes.

    # Expected: traceback, then MPI_Abort and exit code 1
    timeout 60 mpirun -n 2 python demo_abort_petsc_hang.py; echo "exit=$?"

    # Same, after converting a vector to PETSc: the job hangs (exit=124)
    timeout 60 mpirun -n 2 python demo_abort_petsc_hang.py --petsc; echo "exit=$?"

The failing process cannot call MPI_Abort, because `PetscFinalize` (which
runs at interpreter exit, before mpi4py's abort handler) waits for the other
processes, which in turn wait for the failing one in the barrier.
"""


def parse_input_arguments():
    import argparse

    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description=__doc__.split('\n\n')[0],
    )
    parser.add_argument('--petsc', action='store_true',
                        help='Convert a PSYDAC vector to PETSc before failing')
    parser.add_argument('--fail-rank', type=int, default=1, dest='fail_rank',
                        help='MPI rank of the process which raises an exception')
    return parser.parse_args()


def main(*, petsc, fail_rank, mpi_comm):

    import numpy as np

    from psydac.ddm.cart    import DomainDecomposition
    from psydac.fem.splines import SplineSpace
    from psydac.fem.tensor  import TensorFemSpace

    # Distributed 2D spline space, as in a typical PSYDAC simulation
    ncells = [8, 8]
    ddm    = DomainDecomposition(ncells, [False, False], comm=mpi_comm)
    spaces = [SplineSpace(2, grid=np.linspace(0., 1., n + 1)) for n in ncells]
    V      = TensorFemSpace(ddm, *spaces)
    x      = V.coeff_space.zeros()

    # Convert to PETSc using PSYDAC's own interface (imports petsc4py)
    if petsc:
        x_petsc = x.topetsc()
        print(f'rank {mpi_comm.rank}: PETSc vector of size {x_petsc.getSize()}', flush=True)

    # One process fails, the others wait for it
    if mpi_comm.rank == fail_rank:
        raise RuntimeError(f'failure on rank {fail_rank}')

    mpi_comm.Barrier()

    return locals()


if __name__ == '__main__':

    from psydac.utilities.parallel_utils import parallel_run_from_cli

    namespace = parallel_run_from_cli(parse_input_arguments, main)

@yguclu

yguclu commented Oct 20, 2026 •

Copy link
Copy Markdown
Member Author

I reviewed this PR with Claude and it came up with an issue: The job still hangs if PETSc is used. The following script should replicate it as is described in the doc strings. Is this a relevant problem?

"""
Demonstrate that the abort-at-exit of PR #624 hangs once PETSc is in use.

One process raises an exception in `main`, while the others wait in a
barrier. `parallel_run_from_cli` should then terminate all the processes.

    # Expected: traceback, then MPI_Abort and exit code 1
    timeout 60 mpirun -n 2 python demo_abort_petsc_hang.py; echo "exit=$?"

    # Same, after converting a vector to PETSc: the job hangs (exit=124)
    timeout 60 mpirun -n 2 python demo_abort_petsc_hang.py --petsc; echo "exit=$?"

The failing process cannot call MPI_Abort, because `PetscFinalize` (which
runs at interpreter exit, before mpi4py's abort handler) waits for the other
processes, which in turn wait for the failing one in the barrier.
"""


def parse_input_arguments():
    import argparse

    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description=__doc__.split('\n\n')[0],
    )
    parser.add_argument('--petsc', action='store_true',
                        help='Convert a PSYDAC vector to PETSc before failing')
    parser.add_argument('--fail-rank', type=int, default=1, dest='fail_rank',
                        help='MPI rank of the process which raises an exception')
    return parser.parse_args()


def main(*, petsc, fail_rank, mpi_comm):

    import numpy as np

    from psydac.ddm.cart    import DomainDecomposition
    from psydac.fem.splines import SplineSpace
    from psydac.fem.tensor  import TensorFemSpace

    # Distributed 2D spline space, as in a typical PSYDAC simulation
    ncells = [8, 8]
    ddm    = DomainDecomposition(ncells, [False, False], comm=mpi_comm)
    spaces = [SplineSpace(2, grid=np.linspace(0., 1., n + 1)) for n in ncells]
    V      = TensorFemSpace(ddm, *spaces)
    x      = V.coeff_space.zeros()

    # Convert to PETSc using PSYDAC's own interface (imports petsc4py)
    if petsc:
        x_petsc = x.topetsc()
        print(f'rank {mpi_comm.rank}: PETSc vector of size {x_petsc.getSize()}', flush=True)

    # One process fails, the others wait for it
    if mpi_comm.rank == fail_rank:
        raise RuntimeError(f'failure on rank {fail_rank}')

    mpi_comm.Barrier()

    return locals()


if __name__ == '__main__':

    from psydac.utilities.parallel_utils import parallel_run_from_cli

    namespace = parallel_run_from_cli(parse_input_arguments, main)

Fair point!

Intentionally, we have kept the dependency on PETSc as optional and very loose. If a PSYDAC user (or developer) wants to use the PETSc solvers, they can convert our data structures to PETSc, solve the linear systems, and then convert back. I do not want to chase the developments in PETSc and petsc4py from our side, and that is why we always pin them to a specific version.

@e-moral-sanchez You are the one person who works regularly with PETSc. Do you have an opinion about this? Would you like a dedicated issue, maybe?

As for me, I do not see this new issue as relevant to the current PR

@e-moral-sanchez

e-moral-sanchez commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

I reviewed this PR with Claude and it came up with an issue: The job still hangs if PETSc is used. The following script should replicate it as is described in the doc strings. Is this a relevant problem?

"""
Demonstrate that the abort-at-exit of PR #624 hangs once PETSc is in use.

One process raises an exception in `main`, while the others wait in a
barrier. `parallel_run_from_cli` should then terminate all the processes.

    # Expected: traceback, then MPI_Abort and exit code 1
    timeout 60 mpirun -n 2 python demo_abort_petsc_hang.py; echo "exit=$?"

    # Same, after converting a vector to PETSc: the job hangs (exit=124)
    timeout 60 mpirun -n 2 python demo_abort_petsc_hang.py --petsc; echo "exit=$?"

The failing process cannot call MPI_Abort, because `PetscFinalize` (which
runs at interpreter exit, before mpi4py's abort handler) waits for the other
processes, which in turn wait for the failing one in the barrier.
"""


def parse_input_arguments():
    import argparse

    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description=__doc__.split('\n\n')[0],
    )
    parser.add_argument('--petsc', action='store_true',
                        help='Convert a PSYDAC vector to PETSc before failing')
    parser.add_argument('--fail-rank', type=int, default=1, dest='fail_rank',
                        help='MPI rank of the process which raises an exception')
    return parser.parse_args()


def main(*, petsc, fail_rank, mpi_comm):

    import numpy as np

    from psydac.ddm.cart    import DomainDecomposition
    from psydac.fem.splines import SplineSpace
    from psydac.fem.tensor  import TensorFemSpace

    # Distributed 2D spline space, as in a typical PSYDAC simulation
    ncells = [8, 8]
    ddm    = DomainDecomposition(ncells, [False, False], comm=mpi_comm)
    spaces = [SplineSpace(2, grid=np.linspace(0., 1., n + 1)) for n in ncells]
    V      = TensorFemSpace(ddm, *spaces)
    x      = V.coeff_space.zeros()

    # Convert to PETSc using PSYDAC's own interface (imports petsc4py)
    if petsc:
        x_petsc = x.topetsc()
        print(f'rank {mpi_comm.rank}: PETSc vector of size {x_petsc.getSize()}', flush=True)

    # One process fails, the others wait for it
    if mpi_comm.rank == fail_rank:
        raise RuntimeError(f'failure on rank {fail_rank}')

    mpi_comm.Barrier()

    return locals()


if __name__ == '__main__':

    from psydac.utilities.parallel_utils import parallel_run_from_cli

    namespace = parallel_run_from_cli(parse_input_arguments, main)

I just ran it and it behaves as expected: the job terminates with errorcode 1 when one of the processes fails. I am using petsc version 3.25.0 however (the installation suggests using 3.25.5). Could we add this as a unit test?

@yguclu

yguclu commented Oct 27, 2026

Copy link
Copy Markdown
Member Author

I just ran it and it behaves as expected: the job terminates with errorcode 1 when one of the processes fails. I am using petsc version 3.25.0 however (the installation suggests using 3.25.5). Could we add this as a unit test?

@e-moral-sanchez, what do you mean with "as expected"? @FrederikSchnack wrote that this does not work as expected, because all the MPI processes hang (excluding the one which raised the error). Maybe you guys are using different operating systems?

If you guys can figure out when this problem happens exactly (OS, Python version, PETSc version, etc..), we could create a new issue. The code provided by Frederik would then become the minimal reproducible example (MRE) in the issue description. Whether to make it a unit test will be a decision to be taken later, in a new PR.

Given that this PR was not meant to address any PETSc-specific problems, I would like to proceed with merging it ASAP. I will clarify this in the PR description

@e-moral-sanchez

Copy link
Copy Markdown
Contributor

I just ran it and it behaves as expected: the job terminates with errorcode 1 when one of the processes fails. I am using petsc version 3.25.0 however (the installation suggests using 3.25.5). Could we add this as a unit test?

@e-moral-sanchez, what do you mean with "as expected"? @FrederikSchnack wrote that this does not work as expected, because all the MPI processes hang (excluding the one which raised the error). Maybe you guys are using different operating systems?

If you guys can figure out when this problem happens exactly (OS, Python version, PETSc version, etc..), we could create a new issue. The code provided by Frederik would then become the minimal reproducible example (MRE) in the issue description. Whether to make it a unit test will be a decision to be taken later, in a new PR.

Given that this PR was not meant to address any PETSc-specific problems, I would like to proceed with merging it ASAP. I will clarify this in the PR description

I meant that the job terminates when one of the processes fails, as desired. In my case the the MPI processes do not hang. What version are you using @FrederikSchnack ?
To be sure, I would add the unit test to see if it happens with petsc version 3.25.5 and for which OS it happens. We can always delete the test afterwards if you think it is not necessary.

@FrederikSchnack

Copy link
Copy Markdown
Contributor

I just ran it and it behaves as expected: the job terminates with errorcode 1 when one of the processes fails. I am using petsc version 3.25.0 however (the installation suggests using 3.25.5). Could we add this as a unit test?

@e-moral-sanchez, what do you mean with "as expected"? @FrederikSchnack wrote that this does not work as expected, because all the MPI processes hang (excluding the one which raised the error). Maybe you guys are using different operating systems?
If you guys can figure out when this problem happens exactly (OS, Python version, PETSc version, etc..), we could create a new issue. The code provided by Frederik would then become the minimal reproducible example (MRE) in the issue description. Whether to make it a unit test will be a decision to be taken later, in a new PR.
Given that this PR was not meant to address any PETSc-specific problems, I would like to proceed with merging it ASAP. I will clarify this in the PR description

I meant that the job terminates when one of the processes fails, as desired. In my case the the MPI processes do not hang. What version are you using @FrederikSchnack ? To be sure, I would add the unit test to see if it happens with petsc version 3.25.5 and for which OS it happens. We can always delete the test afterwards if you think it is not necessary.

I use Arch Linux (kernel 7.2.11-arch1-1, x86_64), PETSc 3.25.0, petsc4py 3.25.0, Open MPI 5.0.11, mpi4py 4.1.2, Python 3.14.8.

If I run the script as
mpirun -n 2 python demo_abort_petsc_hang.py --petsc,

I get the following output:

Running function 'main' in parallel with 2 MPI processes, and arguments:
{'petsc': True,
 'fail_rank': 1,
 'mpi_comm': <mpi4py.MPI.Intracomm object at 0x7f0d1aa84720>}

rank 1: PETSc vector of size 100
rank 0: PETSc vector of size 100
Traceback (most recent call last):
  File "/home/schnack/PhD/pyccel/psydac_codex/psydac/demo_abort_petsc_hang.py", line 71, in <module>
    namespace = parallel_run_from_cli(parse_input_arguments, main)
  File "/home/schnack/PhD/pyccel/psydac_codex/psydac/psydac/utilities/parallel_utils.py", line 95, in parallel_run_from_cli
    namespace.update(main(**args_dict))
                     ~~~~^^^^^^^^^^^^^
  File "/home/schnack/PhD/pyccel/psydac_codex/psydac/demo_abort_petsc_hang.py", line 60, in main
    raise RuntimeError(f'failure on rank {fail_rank}')
RuntimeError: failure on rank 1

And the terminal hangs indefinitely.

But I agree, this is nothing major and can be moved to its own issue.

@e-moral-sanchez

Copy link
Copy Markdown
Contributor

I just ran it and it behaves as expected: the job terminates with errorcode 1 when one of the processes fails. I am using petsc version 3.25.0 however (the installation suggests using 3.25.5). Could we add this as a unit test?

@e-moral-sanchez, what do you mean with "as expected"? @FrederikSchnack wrote that this does not work as expected, because all the MPI processes hang (excluding the one which raised the error). Maybe you guys are using different operating systems?
If you guys can figure out when this problem happens exactly (OS, Python version, PETSc version, etc..), we could create a new issue. The code provided by Frederik would then become the minimal reproducible example (MRE) in the issue description. Whether to make it a unit test will be a decision to be taken later, in a new PR.
Given that this PR was not meant to address any PETSc-specific problems, I would like to proceed with merging it ASAP. I will clarify this in the PR description

I meant that the job terminates when one of the processes fails, as desired. In my case the the MPI processes do not hang. What version are you using @FrederikSchnack ? To be sure, I would add the unit test to see if it happens with petsc version 3.25.5 and for which OS it happens. We can always delete the test afterwards if you think it is not necessary.

I use Arch Linux (kernel 7.2.11-arch1-1, x86_64), PETSc 3.25.0, petsc4py 3.25.0, Open MPI 5.0.11, mpi4py 4.1.2, Python 3.14.8.

If I run the script as mpirun -n 2 python demo_abort_petsc_hang.py --petsc,

I get the following output:

Running function 'main' in parallel with 2 MPI processes, and arguments:
{'petsc': True,
 'fail_rank': 1,
 'mpi_comm': <mpi4py.MPI.Intracomm object at 0x7f0d1aa84720>}

rank 1: PETSc vector of size 100
rank 0: PETSc vector of size 100
Traceback (most recent call last):
  File "/home/schnack/PhD/pyccel/psydac_codex/psydac/demo_abort_petsc_hang.py", line 71, in <module>
    namespace = parallel_run_from_cli(parse_input_arguments, main)
  File "/home/schnack/PhD/pyccel/psydac_codex/psydac/psydac/utilities/parallel_utils.py", line 95, in parallel_run_from_cli
    namespace.update(main(**args_dict))
                     ~~~~^^^^^^^^^^^^^
  File "/home/schnack/PhD/pyccel/psydac_codex/psydac/demo_abort_petsc_hang.py", line 60, in main
    raise RuntimeError(f'failure on rank {fail_rank}')
RuntimeError: failure on rank 1

And the terminal hangs indefinitely.

But I agree, this is nothing major and can be moved to its own issue.

I also agree that this can be moved to its own issue and this PR can be merged.

@yguclu

yguclu commented Oct 27, 2026

Copy link
Copy Markdown
Member Author

@FrederikSchnack @e-moral-sanchez Thanks for your comments!

I have just drafted issue #635; please feel free to expand its description. I do not think we can add the proposed MRE as a unit test, because the parallel unit tests are not supposed to hang and I am not aware of a clean way to handle that with Pytest.

As for merging this PR, I need at least one reviewer's approval 😅

@e-moral-sanchez e-moral-sanchez left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I think it can be merged.

@yguclu
yguclu marked this pull request as draft October 27, 2026 16:02
@yguclu
yguclu marked this pull request as ready for review October 27, 2026 16:02
@yguclu
yguclu merged commit 4868f6c into devel Oct 27, 2026
10 checks passed
@yguclu
yguclu deleted the yguclu-abort-parallel-run branch October 27, 2026 17:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Next Release Must be in next release

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Terminate all processes when one of them fails in parallel_run_from_cli

4 participants