Skip to content

Dropped solvers and meshes leave nothing in PETSc's options database (#950) - #980

Merged
lmoresi merged 3 commits into
developmentfrom
bugfix/solver-options-cleanup-950
Nov 7, 2026
Merged

lmoresi merged 3 commits into
developmentfrom
bugfix/solver-options-cleanup-950

Conversation

@lmoresi

@lmoresi lmoresi commented Nov 6, 2026

Copy link
Copy Markdown
Member

Dropped solvers and meshes leave nothing behind in PETSc's global options database (#950).

The bug

Each solver writes its PETSc options under a prefix unique to it: Solver_N_, plus private_Solver_N_ copies for its sub-objects. Each mesh wrote three meshproj_N_ keys for its coordinate element. Nothing removed either. A loop that rebuilds a mesh and a solver therefore grew the database without bound: 17 keys a cycle for a Poisson solve on development eddab70, and about 41 a rebuild in the rotated-FMG rebuild fixture where #950 was found. That is kilobytes, not #948's megabytes, but it is unbounded, and every later options lookup searches a longer list.

The change

  • Solvers (cython/petsc_generic_snes_solvers.pyx, the base constructor and a module-level helper): a solver drops its options when it is collected, through weakref.finalize. The finalizer does not run at interpreter exit, when PETSc may already be finalised. The prefix is unique to the solver, so no live solver reads those keys. This is the only change in the solver file, and it changes no option that a live solver reads.
  • Meshes (discretisation_mesh.py): the three coordinate-element keys are dropped as soon as PETSc.FE().createDefault has read them, as the rotated route already does with its own keys.

A solver lives as long as its mesh, because the mesh holds it for its rebuild hook. A solver the user drops therefore keeps its options until its mesh is dropped too. That ownership is unchanged here.

Tests

tests/test_0079_options_database_does_not_grow.py (tier B):

  • Rebuilding a mesh and a Poisson solver three times leaves the database the same size. Development goes from 27 keys to 78.
  • A live solver keeps its options.

The broad serial set (test_00*, test_01*, test_100-102*) gives 1380 passed and 17 skipped.

Issues

Underworld development team with AI support from Claude Code

…abase

Each solver writes its PETSc options under its own prefix (Solver_N_, with
private_Solver_N_ copies for its sub-objects), and each mesh wrote three
meshproj_N_ keys for its coordinate element; nothing removed either, so a
loop that rebuilds a mesh and a solver grew the global database without
bound (17 keys a cycle for a Poisson solve on development).

- A solver drops its options when it is collected (weakref.finalize on the
  base class, not run at interpreter exit, when PETSc may be finalised). The
  prefix is unique to the solver, so no live solver reads them. A solver lives
  as long as its mesh, which holds it for its rebuild hook.
- The mesh drops its three coordinate-element keys right after
  PETSc.FE().createDefault has read them.

This touches petsc_generic_snes_solvers.pyx only in the base constructor
and a module-level helper; no option a live solver reads is changed.

test_0079 (tier B): rebuilding a mesh and a Poisson solver three times leaves
the database the same size (development: 27 -> 78), and a live solver keeps
its options. Broad serial set (test_00*, test_01*, test_100-102*): 1380
passed, 17 skipped.

Underworld development team with AI support from Claude Code
Copilot AI balanced review requested due to automatic review settings November 6, 2026 10:43

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@lmoresi

lmoresi commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

Adversarial review of #980

Verdict: ready with the changes below. Head 4031947, base eddab70, np 2 and 4 through the supervisor. Nothing hangs in parallel, and the key count is flat. One crash after PetscFinalize is real, though only if user code collects after finalise.

Findings

  1. Segfault if the finalizer runs after PetscFinalize. A probe with atexit calling PETSc._finalize(), then dropping the mesh and solver and running gc.collect(): rc=139 (SIGSEGV), where eddab70 exits rc=0. The try/except in _drop_solver_options cannot catch this, because getAll on a destroyed database is a C fault. atexit=False does not cover it, since the mesh and solver form a reference cycle, so the finalizer fires from whichever GC pass collects them. A normal script exit is clean (rc=0 in 3 of 3, including np 2 and gc.disable()). Fix: return early when PETSc.Sys.isFinalized() is true.
  2. A reused instance number lets a dead solver delete a live solver's options. After uw_object._reset(), a new solver with the same Solver_6_ loses its keys when the old one is collected: KeyError: '(prefix:Solver_6_, name:pc_type)' in _apply_preconditioner_options on rebuild. eddab70 keeps the keys. Not reachable from the public API: reset_default_model does not touch _obj_count, and nothing in src or tests calls _reset(). A latent trap for any future counter reset. Guard on the object rather than only the name, or document that _reset must not run with solvers alive.
  3. The live-solver test cannot catch over-deletion by another solver. A mutant whose finalizer matches every Solver_* and private_Solver_* key passes both tests in test_0079, because test_a_live_solver_keeps_its_options sets its key after the earlier solvers are collected. Keep solver A alive, build and collect solver B, then assert A's full option set is unchanged. The real code passes that check: 35 keys on a live Stokes solver are identical after 5 other Stokes solvers are built, solved and collected, and a re-solve after is_setup=False is bit-identical.
  4. Information, not a defect here: writing through a retained petsc_options view after its solver is collected writes into the global database again, and that key lingers. Reads return {}.

Attacks that failed

  • Rebuild loop key count, Poisson plus Stokes per cycle, np 1, 2, 4, with ranks calling gc.collect() on different cycles: 57 keys when a cycle is uncollected, 8 after, final count 8 on every rank. eddab70 grows 52 per cycle (60 to 320). No hang at np 2 or 4, since the finalizer is local.
  • The Memory grows ~190 MB per rank per fault rebuild on development f631ce42 (rotated free slip + custom FMG); 25d62812 did not leak, and #882's regression test does not cover this path #948 rotated FMG rebuild fixture, from origin/bugfix/rebuild-leak-948: flat at 8 per rebuild at np 2 and 4, 7 rebuilds, every rank. eddab70 at np 2 grows 44 per rebuild.
  • Collection during a solve: from inside a KSP monitor callback, a second solver on another mesh was built, solved and collected. The finalizer ran, and the outer solve completed with its 30 keys intact.
  • Prefix matching: Solver_1_ does not match Solver_11_, nor private_Solver_1_ match private_Solver_11_, by inspection; live keys survived the churn.
  • meshproj_N_ reuse: options are set before every createDefault, then deleted. After 3 nuke_coords_and_rebuild calls there are no keys left, and the solve is identical.
  • Rotated solve: its own rotfsN_ prefix is removed by itself; the rotated fixture ran at np 2 and 4.
  • Process teardown: a live solver exits cleanly at np 1 and 2, as a module global and with GC disabled. __init__ raising partway leaves nothing behind.
  • Tests fail for their reason on eddab70: test_rebuilding_a_mesh_and_solver_does_not_grow_the_options fails on the count; 2 passed here.
  • CI reach: test_0079 matches the test_00[6-7]* glob at tier B. It is serial, so the multi-rank evidence is these probes.

Issues

Merge conditions

  • Add the PETSc.Sys.isFinalized() guard.
  • Strengthen the live-solver test so it fails when another solver's collection deletes a live solver's keys.
  • For finding 2, guard against prefix reuse, or state in the _reset docstring that it must not run with live solvers.

Could not test

Checkpoint reload and refinement paths with meshproj; fieldsplit sub-prefix reads in isolation; GC firing inside SNESSetFromOptions itself, as opposed to a monitor callback; deliberately rank-asymmetric GC at np 8; pickle and deepcopy on eddab70 for comparison.

Underworld development team with AI support from Claude Code

…and never after PetscFinalize

From hyperion's review of #980:
- The mesh and its solvers form a reference cycle that the collector can
  reach after PetscFinalize; a finalizer touching the options database then
  ended the process (a segfault on Linux, rc 1 on macOS). It now returns once
  PETSc is finalised.
- After uw_object._reset() a new solver can take a dropped one's prefix, and
  the dropped one's finalizer deleted the new solver's options. Each prefix
  now records its owner by a token, and a finalizer acts only while its
  solver still owns the prefix.
- test_0079 keeps one solver alive while another is collected and checks
  every one of its options (a finalizer deleting every Solver_* key passed
  the old test), checks a reused prefix after uw_object._reset(), and runs
  the late finalizer in a child process (rc 1 before the guard, 0 after).
  Mutants deleting every solver's options, or ignoring ownership, fail it.

Underworld development team with AI support from Claude Code
@lmoresi

lmoresi commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

Response to hyperion's review, at 3a3b731:

  1. Finalizer after PetscFinalize. _drop_solver_options now returns early once PETSc.Sys.isFinalized(), before touching the options. Reproduced on macOS: a child process keeps the mesh-solver cycle alive, finalises PETSc, then collects. Without the guard it exits rc 1, silently; with it, rc 0. That child is now test_a_finalizer_after_petsc_is_finalised_does_nothing.
  2. Over-deletion. test_a_live_solver_keeps_its_options_when_another_is_dropped keeps one solver alive while another is collected, and compares every one of the live solver's keys and values. A mutant finalizer that deletes every Solver_* key fails it.
  3. Reused prefix after uw_object._reset(). Each prefix records its owner by a token, and a finalizer acts only while its own solver still owns the prefix. test_a_reused_prefix_keeps_the_new_solvers_options asserts the premise, the same prefix, and then that the new solver keeps its options. An ownership-blind mutant fails it.

test_0079: 4 passed serially. Thanks for the parallel runs, which are recorded above.

Underworld development team with AI support from Claude Code

…anup-950

Underworld development team with AI support from Claude Code
@lmoresi
lmoresi merged commit ec493da into development Nov 7, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants