Skip to content

A dropped solver is freed with its KSP tree: weak solver registers, and the instrumentation cycle broken on collection (#1041) - #1050

Merged
lmoresi merged 6 commits into
developmentfrom
bugfix/weak-solver-register-1041
Nov 12, 2026
Merged

lmoresi merged 6 commits into
developmentfrom
bugfix/weak-solver-register-1041

Conversation

@lmoresi

@lmoresi lmoresi commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

A solver the user drops is now freed, with its SNES, its KSP tree and its PETSc options (#1041). Two references kept it alive, and a third, inside PETSc, kept its KSPs.

What held a dropped solver

  • The mesh's solver register. Each solver appends itself to mesh._equation_systems_register, so a mesh move or DM change can mark it for rebuild and a snapshot can capture its step state. It was a plain list, and nothing removed from it, so every solver built on a mesh lived as long as the mesh. It is now _SolverRegister, which holds solvers weakly in build order, as model._solvers, model._state_bearers and model._part_objects already did.
  • A material distribution. MaterialDistribution kept the solvers it pushes properties to in a strong list, so a distribution reused across solvers kept every one it had been given. It holds weak references now.
  • The solve instrumentation's KSP cycle. The instrumentation's monitor and post-solve callbacks on each KSP hold it, and it holds the KSP, a cycle through PETSc that Python's collector cannot see (the cycle of Stokes: reassigning bodyforce leaks about 23 MB per solve (28 MB per rank at np 2); Poisson and an updated uw.expression do not #1012). _reset broke it when the SNES was torn down; a solver that is simply dropped never runs _reset. The solver now breaks it when it is collected, through a weakref.finalize that calls the instrumentation's release().

With the register alone (this branch's first commit, 343f58b) the solver and its SNES were freed but its 3 KSPs per solve stayed, so the issue's reproduction still gave 3, 6, 9, 12 live KSPs. The first commit's message says the KSP tree is freed; that is true only from the second commit (b590073).

A contract this makes true: a snapshot does not keep its solvers alive

On development, a snapshot that captured a solver's history (its DuDt) could be restored after the solver was dropped, because the register kept the dropped solver and its history alive, and the restore wrote into them. The model's registries of history managers and transcript parts were already weak, with comments saying registration must not extend an object's lifetime, and TranscriptAdjoint already raises "the backward pass needs the solvers of the run in this process" when a solver is gone. Now that the register is weak too, a restore that names a collected history manager raises:

  • in memory, SnapshotInvalidatedError;
  • from disk, ValueError.

Both messages now say the object was collected, or the Model is not the originating one, and to keep the solver for as long as its snapshots are to be restored. A restore refused for a missing mesh, variable, swarm or history manager writes nothing: the in-memory restore looks up everything the snapshot names before it writes, and the disk restore looks up every mesh, variable and history manager the file names before it reads any. (The checks inside apply_snapshot_payload, a moved mesh or a changed layout, still run as each mesh is written, as on development.) Before, a refused restore had already rewound the fields. Before, they said only "restore requires the originating Model". The alternative, a snapshot holding strong references to what it captured, is a different design; Louis to confirm this one.

Parallel

The refusal is agreed across the ranks before anything is written, and raised on every rank. When a reference to the dropped solver survived on only some ranks, those ranks restored and the others raised, and the job hung in the next collective (review round 2, all six runs at np 2 and 4). tests/parallel/test_1155 holds the reference on one rank and checks that both restores are refused everywhere and the field is unchanged. The same holds for a mesh dropped on some ranks and kept on one: before the disk restore looked its meshes up first, that rank waited in the collective read while the others raised (review round 3).

A dropped solver is freed by the cyclic collector, whose timing can differ between ranks. The snapshot readers still agree, because each takes its meshes from Model._live_meshes(), which collects on every rank first. The first commit's message gave rank-0-only writes as the reason; that is not what makes it safe. The review forced disagreement four ways at np 2 and 4 (collection disabled on one rank, a rank-local strong reference on either rank), then moved the mesh, saved and loaded in memory and from disk, and ran PETSc garbage cleanup, with no hang.

Tests

tests/test_1154_a_deleted_solver_is_freed.py (level_1, tier_b), 5 tests, and tests/parallel/test_1155_snapshot_refusal_agrees_across_ranks_parallel.py (level_1, tier_b, np > 1):

  • three dropped Stokes solvers are collected, and their options leave the database;
  • the live KSP count is flat over three build, solve and drop cycles (development: 9 more);
  • the register keeps the live solvers in build order, and a move still marks them for rebuild;
  • a held material distribution does not keep a dropped solver;
  • the snapshot contract above, in memory and on disk, with the field unchanged by a refused restore (serial).

Mutants caught: a strong register, a strong materials list, the finalizer removed (9 KSPs left), and either error message reverted. The test fails on development. 161 snapshot, move, adapt, rebuild, materials, transcript, adjoint and instrumentation files plus test_1155 on wombat (serial, not level_3): 1683 passed, 0 failed.

Issue verdicts

Not changed

  • A solver that creates its own unknowns leaves them on the mesh when it is dropped (about 23 DMs and 12 Mats each): the mesh owns its variables by design (Mesh.__init__). Whether a solver's own unknowns should go with it is a design question, raised with the maintainers and not filed.

  • The register can no longer be indexed or pickled. Nothing in the library or the tests does either.

  • The solver counts in Model.describe and export_config can change once a dropped solver is collected (from reading; not tested).

Underworld development team with AI support from Claude Code

…eakly (#1041)

Each solver appends itself to mesh._equation_systems_register, so a mesh
move or DM change can mark it for rebuild and a snapshot can capture its
step state. The register was a plain list that nothing removed from, so
every solver built on a mesh lived as long as the mesh, with its SNES and
KSP tree and its PETSc options.

_SolverRegister keeps the list's append and iteration, holds the solvers
in a WeakValueDictionary keyed by build order, and iterates over a copy.
Its readers (_deform_mesh, _invalidate_caches_after_dm_change and the
snapshot capture, write and restore) only touch live solvers. The disk
snapshot writes solver states on rank 0 and reads them rank-locally, so a
solver collected at different times on different ranks raises no
collective mismatch.

test_1154 (level_1, tier_b): fails on development (all three dropped
Stokes solvers alive) and passes here. Snapshot, move, adapt and rebuild
tests (127 files, serial): 1258 passed, 0 failed.

Underworld development team with AI support from Claude Code
…vers weakly

- F1: a dropped solver's KSPs stayed. The solve instrumentation's
  callbacks on each KSP hold it, and it holds the KSP: a cycle through
  PETSc that the collector cannot see (#1012's). _reset broke it on a
  teardown; a solver that is only dropped now breaks it when collected
  (weakref.finalize on the solver, calling the instrumentation's release).
- F5: MaterialDistribution kept the solvers it pushes to in a strong
  list, so a distribution kept every dropped solver it had been given.
  It holds weak references now.
- F2: a snapshot holding a dropped solver's history no longer restores
  into the dead solver, which the register kept alive; the model's own
  registries of history managers and transcript parts were weak by
  design. The in-memory and disk errors now say the object was collected.
- F3: iteration no longer takes a copy (WeakValueDictionary guards
  removals made by the collector). Docstrings corrected: the snapshot
  readers agree across ranks because _live_meshes collects on every rank.

test_1154: 5 tests (KSP count flat over 3 build/solve/drop cycles; a
held distribution does not keep a dropped solver; the snapshot contract
in memory and on disk). Mutants caught: the finalizer removed (9 KSPs
left), a strong register, a strong materials list, either error message.
161 snapshot, move, adapt, rebuild, materials, transcript, adjoint and
instrumentation files (serial): 1683 passed, 0 failed.

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

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 10, 2026

Copy link
Copy Markdown
Member Author

Review record, round 1 of 2: 343f58b

This is the pre-PR round, on the branch's first commit. b590073 answers F1, F2 (as a decided contract), F3 and F5. Round 2 follows in a separate comment. Paths under runs/ are on hyperion.


Pre-PR adversarial review: bugfix/weak-solver-register-1041 at 343f58b

Base: development e7fdcb2. Builds: wt-1041 (branch) and wt-deve7f (base), not rebuilt; the installed
discretisation_mesh.py, snapshot.py and disk_snapshot.py match each worktree's source. Tests ran from
git archive copies in this directory. Probes and logs are in probes/ and logs/. Hyperion, 2026-11-11.

Verdict

Not ready as "Closes #1041". Ready as one half of the fix.

The weak register does what it says: a dropped solver's Python object and its SNES are freed, and no reader
hangs or mismatches when ranks disagree. But #1041's own reproduction is unchanged:

  • the KSP count still goes 3, 6, 9, 12;
  • RSS still grows by 3.5 to 4.2 MB per dropped solver, against 4.3 to 5.3 MB on base.

The KSP tree is held by a second cause. The solver instrumentation's KSP callbacks form a cycle through the
PETSc object (the #1012 mechanism), and only release() breaks it. A finalizer that calls release()
makes the count flat, but only together with this branch.

The branch also makes a new error reachable. If a solver with a history (a DDt) is rebuilt, load_state of
a snapshot taken before the rebuild now raises, in memory and on disk. On base the same call succeeds.

Answers

Q1. Parallel

No reader does a collective per solver, or on a count that can differ by rank. [run at np 2 and 4]

All four snapshot readers (capture, restore, disk write, disk read) take their meshes from
Model._live_meshes(), which calls gc.collect() on every rank first (model.py:576-587). So
_solvers_of sees an agreed register whenever the object graph is the same on every rank. This, not
"rank 0 writes, reads are rank-local", is what keeps the snapshot readers consistent. The commit message
should say so.

probes/par_asym.py builds a live solver A, then B (dropped), then a live solver C. It runs at np 2 and 4
in four modes:

mode how B is kept on some ranks only result
collect0 gc off; only rank 0 collects B the first snapshot's collection re-agrees the ranks; every step passes
disable1 gc off on rank 1 only B alive on rank 1 only ([F,T] at np 2, [F,T,F,F] at np 4); every step passes
pin0 a rank-local strong reference to B on rank 0, which survives the collection passes
pin1 the same reference, on rank 1 passes

The steps are mesh.deform while the ranks disagree, solves of A and C, in-memory save, solve, load,
disk save, solve, load, deform, solve, and garbage cleanup. Logs: logs/par*-1041-*.log.

  • Restore with B alive on one rank only. B's velocity block is gamg (PCs fieldsplit/gamg/gasm).
    So restore's _discard_preconditioner_setup runs setType("none"), setType("gamg") and
    setFromOptions on a parallel PC on one rank only. This completed at np 2 and 4. [run]

  • Disk file against read-back. Rank 0 wrote the solver groups of its own register:

    • pin0 wrote [Solver_18_, Solver_29_, Solver_7_], B included. The other ranks have no B, so they
      ignore B's group.
    • pin1 wrote [Solver_29_, Solver_7_]. Rank 1's B is not in the file, so it is reset to a
      never-solved state, on rank 1 only.

    Either way the result is rank-local, and the solver it touches is one nobody solves again. Consistent.
    [run]

  • _deform_mesh and _invalidate_caches_after_dm_change. They only set is_setup, a plain flag
    setter (petsc_generic_snes_solvers.pyx:1674). Register lengths [3,2] and [2,3,2,2] deformed fine. [run]

  • PETSc garbage. probes/par_garbage.py: three cycles in which only rank who (0 or 1) collects B,
    then PETSc.garbage_cleanup(comm) runs on all ranks, then a live solve, then all ranks collect and
    clean up again. No deadlock at np 2 or 4, and A converged every time (reason 2). Logs:
    logs/pgarb-*.log. [run]

  • Residual risk. [read; not run] A rank-local strong reference to a dropped solver (state that only
    rank 0 keeps, a traceback, an IPython Out[]) now makes registers differ even after the collection.
    None of today's readers is collective per solver, so this is harmless today. But F2's restore error
    becomes rank-dependent under such a reference: one rank raises and the others continue into
    collectives.

Q2. What relied on the register keeping a solver alive

  • Grep. _equation_systems_register has four appends (.pyx 6425, 7360, 8375, 9255) and three
    readers (discretisation_mesh.py 2572 and 4536, snapshot.py 222). Nothing indexes it. The appends
    register Stokes, AdvDiffusion and Vector_Projection once each. [run: probes/misc.py]

  • Helpers that build solvers. Every internal solver that is reused is held strongly by its owner:

    • DDt _psi_star_projection_solver, _commit_projection, _forcing_projection and _flux_projection;
    • the Stokes _tau_projector and _dual_projection_solver;
    • the mesh _eval_projector_* and _gradient_cache;
    • the yield-continuation _rate_strengthening_probe;
    • the free-surface projectors.

    Locals that are built and then dropped (the metric smoothing in meshing/smoothing/metrics.py:461,476,
    and a replaced _dual_projection_solver) were leaks on base and are freed now. Nothing reaches them
    later. [read]

  • Mesh variables made by a dropped solver. They stay in mesh._vars, a strong dict, so they do not
    become rank-asymmetric. [read] That is a separate residual.

  • Through the model, the snapshot or the transcript: this is F2.

    • model._part_objects, model._solvers and model._state_bearers are weak. On base they were full
      only because the register pinned every solver.

    • TranscriptAdjoint finds its solvers with model.part_object. After the caller drops them, base
      computes the gradient (-0.004824), and the branch raises SnapshotInvalidatedError for the dropped
      solver's EulerianSUPG state-bearer (probes/adj_dropped.py). [run]

    • The same happens with no adjoint involved: rebuild an AdvDiffusion solver, then load_state a
      snapshot taken before the rebuild (probes/rebuild_rewind.py, rebuild_rewind_disk.py). [run]

      base branch
      in memory ok SnapshotInvalidatedError
      disk ok ValueError
  • Suites. 90 files (snapshot, transcript, adjoint, DDt, projection, deform, adapt, restore, model and
    memory), -m "not level_3", 7 workers each:

    build passed failed failures
    branch 642 1 test_1079, a harness artefact
    base 640 3 test_1079 and both test_1154 tests

    test_1079 failed only because my archive had no scripts/. Rerun with it, it passes on both. Logs:
    logs/suite-*.log, logs/t1079-*.

  • Parallel suites (branch):

    • test_0079 and test_0020_snapshot_disk_swarm_values_parallel at np 2 and 4: 3 passed per rank;
    • ptest_0007 and ptest_0010 at np 2 and 4: PASS;
    • test_0078 and test_1144 (rebuild memory) at np 2: pass on branch and on base.

Q3. Memory

  • The issue's reproduction (probes/repro1041.py, serial, 4 solvers):

    build solvers alive SNES KSP register length
    base 1, 2, 3, 4 1, 2, 3, 4 3, 6, 9, 12 1, 2, 3, 4
    branch 0 0 3, 6, 9, 12 0

    On the branch the KSP count is not flat. The remaining referrer of each KSP is an _InstrumentedKSP.

  • H1's p12 delete, rerun (8 solvers, cellSize 0.125):

    build np live KSPs RSS per solver
    branch 1 +3 per solver +3.4 MB
    branch 2 +3 per solver +3.4 MB
    base 1 +3 per solver +4.4 MB
    base 2 +3 per solver +4.2 MB
  • p12 delete_release (explicit _instrumentation.release() before del) separates the two causes:

    build np live KSPs RSS per solver
    branch 1 0 +0.8 MB
    branch 2 0 +1.0 MB
    base 1 0 +4.5 MB
    base 2 0 +4.3 MB

    On base the solver is still pinned by the register. Both causes have to go.

  • A finalizer instead of an explicit call (probes/finalize_release.py, the branch plus
    weakref.finalize(solver, solver._instrumentation.release), 10 cycles): 0 KSP wrappers at np 1 and 2,
    and RSS +2.6 MB over 10 cycles at np 1 and +5.0 MB at np 2, about 0.3 to 0.5 MB per cycle.
    SolverInstrumentation holds no reference to the solver (solver_health.py:258), so the finalizer
    does not pin it. [run, as a monkeypatch]

  • PETSc object counts (probes/cycles_lv.py): PETSc.Log.view mid-run, after cleanup.
    (N=20 - N=10)/10 gives objects alive per dropped solver:

    object base, np 1 branch, np 1 base, np 2 branch, np 2
    SNES 1 0 1 0
    KSP 8 7 8 7
    PC 8 7 8 7
    Mat 38 36 60 54
    DM 54 50 54 50
    Vec 141 120 151 128
    Section 207 201 207 201

    The branch frees about 5 to 15% of a dropped solver's PETSc objects. RSS slope over the second half of
    the run: branch 3.5 to 4.2 MB per cycle, base 4.3 to 5.3 (logs/cyc*-*.log). The at-exit -log_view
    counts are identical on both builds, so the objects that are never freed are the same set.

Q4. Issue verdicts

issue verdict evidence
#1041 Still live (half fixed) The register's strong reference is gone. The issue's KSP count is unchanged, and RSS is about 3.5 MB per dropped solver instead of 4.5. Fixed only with F1.
#1012 (deletion residual) Still live The same residual: +3 Python KSP wrappers (7 PETSc KSPs) per deleted solver. Branch + release on collection is flat (0 KSPs, 0.3 to 1 MB per solver).
#966 Still live, not in territory The branch changes only which solvers _deform_mesh marks. _mesh_version and _move_version are untouched. [read]
#951 Not affected Its test is not on development. On this path the library no longer pins a solver through the register, so its weak-reference check now sees only pins outside the library (#948's kind). [read] test_0078 and test_1144 pass at np 2 on both builds.

Findings

F1 (High). The PR does not fix the issue it closes.

  • Dropped solvers' KSP trees stay alive through _InstrumentedKSP callbacks held in the PETSc context,
    at +3 Python KSP wrappers and 7 PETSc KSPs, 36 Mats and 50 DMs per solver.
  • Neither test_1154 nor any other test counts KSPs. Its docstring says the solver "is freed, with its SNES
    and KSP tree". The _SolverRegister docstring and the commit message carry the same claim.
  • Fix: release the instrumentation when the solver is collected (a weakref.finalize on the solver,
    through a holder, since _instrumentation is replaced at .pyx:3670). Or make the KSP callbacks hold
    their entry weakly.
  • Then test_1154 should assert the KSP count stays flat. That assertion fails on this branch today.

F2 (Medium-High). A rewind after rebuilding a solver now raises.

  • What happens: a dropped solver's DDt leaves model._state_bearers when it is collected. restore
    (snapshot.py:431-442) and read_snapshot (disk_snapshot.py:552-562) treat a captured bearer that
    is absent as a foreign model, and raise.

  • What this breaks: model.load_state, model.rewind and TranscriptAdjoint for any run that drops or
    rebuilds a solver with history.

  • Options:

    • skip bearers that are known to have been collected, for example by recording the keys of collected
      bearers through a weakref callback, while still raising for a key that was never registered;
    • or document and test the new contract.

    Either way, add a test.

  • Base "succeeded" by restoring the dead solver's history. The rebuilt solver's DDt kept its post-snapshot
    history, which is also wrong, so a decision is needed here, not a revert.

F3 (Low). The test does not pin the copy in __iter__.

  • Mutants (probes/mutants.py):

    mutant test_1154
    strong list fails 2 of 2
    WeakSet fails 1
    reversed order fails 1
    iteration without the copy passes
  • The copy is not load-bearing. WeakValueDictionary.values() already defers removals under its
    iteration guard. The copy does hold every live solver for the length of a loop, so a solver cannot be
    collected mid-walk: in the misc probe, the victim stayed alive until the walk ended.

  • Either drop the docstring's reason, or keep the copy as a guard against an append during iteration and
    say that.

F4 (Low). The register narrowed its interface.

  • It is no longer subscriptable, and it can no longer be pickled or deep-copied the way a list could.
    Nothing in src or tests indexes it. [run]
  • repr(mesh) is unchanged.
  • copy.deepcopy(mesh) and pickle.dumps(mesh) fail identically on both builds, from other members.
  • Appending the same solver twice yields it twice, as on base. The readers are idempotent.

F5 (Low, read). Solvers attached to materials are still pinned.

F6 (Info). Counts in the model description now depend on collection.

  • Model.describe facts (solvers) and export_config (solver_count) now drop solvers when they are
    collected. [read]
  • That is the intended meaning, but a transcript header written before and after a collection will
    differ.

Attacks that failed

  • The test can fail. test_1154 fails 2 of 2 on base (serial) and passes on the branch.
  • Build order. Order is preserved through drops (probes/misc.py: 6 solvers, 2 dropped). Base keeps
    the dead entries in order, so it fails that check.
  • Collectives per solver. None, at np 2 and 4, in all four disagreement modes, including
    restore-time gamg resets on one rank and PETSc.garbage_cleanup with mismatched deferred lists.
  • Solver names. They are unique per process (Solver_{instance_number}_), so last-wins on capture
    and first-wins on disk write do not depend on order.
  • CI reach. scripts/test.sh has batch 4 tests/test_1154*py.

Merge conditions

What we could not test

  • macOS, more than 4 ranks, and CI's environment on kaiju.
  • level_3 tests, and the full suite outside the 90-file selection.
  • F2 under a rank-local strong reference at np ≥ 2, the predicted hang where one rank raises. [read]
  • F5, a solver pinned through materials. [read]
  • A real fix for F1 in the build: shown only as a monkeypatch probe, since there were no rebuilds.
  • A rebuild-memory test on the rotated free-slip + custom-FMG + split-fault path (refs #948) #951's test, which is not on development.

Underworld development team with AI support from Claude Code

@lmoresi

lmoresi commented Nov 10, 2026

Copy link
Copy Markdown
Member Author

Review record, round 2 of 2: b590073

Paths under probes/ and logs/ are on hyperion, in runs/2026-11-11-1041/review2/.


Round 2: b590073

PR #1050, bugfix/weak-solver-register-1041 at b590073, against development e7fdcb2. Builds: wt-1041,
rebuilt for b590073 (the build has the finalizer: 1 weakref.finalize per instrumentation, checked), and
wt-deve7f. Tests ran from git archive copies in this directory. Probes and logs are in probes/ and
logs/. Hyperion, 2026-11-11. Round 1 is ../review/1041-review.md.

Verdict

The leak is fixed; one merge condition is left. The KSP tree is freed, and PETSc objects per dropped
solver are 0 when the solver is given its fields.

The remaining condition is a parallel hang in the F2 contract. When one rank still holds the dropped
solver, the restore error fires on the other ranks only, and the job hangs at the next collective (N1).

Round-1 findings: status

finding status numbers
F1 KSP tree kept by the instrumentation cycle Fixed See the tables below.
F2 rewind or adjoint after a solver rebuild raises Accepted as the contract; uniform only in serial and when no rank holds the solver All three round-1 probes still raise, now with the new text. See N1 and N2.
F3 copy in __iter__ not load-bearing Fixed The copy is dropped. Iteration is WeakValueDictionary.values(), whose guard defers removals. The suite and par_asym show no change.
F4 narrower register interface Unchanged, accepted Nothing indexes it.
F5 materials pinned solvers Fixed test_materials passes at np 1 and 2. The strong-materials mutant is caught.
F6 describe counts follow collection Unchanged, Info

F1 numbers. The issue's reproduction (6 solvers) gives 0 solvers, 0 SNES and 0 KSP alive after every
drop; on base they were 1..4, 1..4 and 3..12.

probe np live KSPs RSS
p12 delete, 8 solvers 1 0 375.6 → 377.5 MB, 0.24 per solver
p12 delete, 8 solvers 2 0 382.8 → 386.8 MB, 0.5 per solver
cycles_lv, Stokes builds its own fields 1 0 0.25 to 0.93 MB per cycle
cycles_lv, Stokes builds its own fields 2 0 1.1 MB per cycle
cycles_lv_fields, fields reused, 20 cycles 2 0 0.03 MB per cycle; base 2.85

PETSc objects alive per dropped solver, from PETSc.Log.view mid-run, (N=20 - N=10)/10:

objects per solver base branch, Stokes builds its own fields branch, fields reused (np 2)
KSP 8 0 0
PC 8 0 0
SNES 1 0 0
Mat 38 (np 1), 60 (np 2) 12 0
DM 54 23 0
Vec 141 to 151 12 0
Section 207 65 0
total 0 of every type; base 8 KSP, 29 DM, 48 Mat, 137 Vec

The objects that remain when Stokes builds its own fields belong to the velocity and pressure
MeshVariables it creates. They stay pinned in the mesh's strong _vars dict (N4).

Checks

1. Round-1 probes on b590073

  • par_asym, all four modes at np 2 and 4: 8 of 8 complete ("done ok"). The disk file is written from rank
    0's register: pin0 writes B, pin1 and disable1 do not.
  • par_garbage with who = 0 and 1, at np 2 and 4: 4 of 4 ok.
  • rebuild_rewind, rebuild_rewind_disk and adj_dropped (serial) raise SnapshotInvalidatedError,
    ValueError and SnapshotInvalidatedError, each with the new "collected" text.

2. Are the F2 errors rank-uniform?

They are not. probes/f2_rank.py: an AdvDiffusion solver with a swarm in the model. The probe saves a
snapshot, rebuilds the solver and calls load_state, with one rank holding a reference to the old solver.
Each rank writes its outcome to a file before any collective, then calls solve.

case outcome per rank job
nobody holds it, np 2, in memory both raise completes, exit 0
nobody holds it, np 2, disk both raise completes, exit 0
pin0, np 2, in memory rank 0 ok, rank 1 raises hang, killed by the supervisor (exit 124)
pin0, np 2, disk rank 0 ok, rank 1 raises hang (124)
pin1, np 2, in memory rank 1 ok, rank 0 raises hang (124)
pin1, np 2, disk rank 1 ok, rank 0 raises hang (124)
pin0, np 4, in memory rank 0 ok, ranks 1-3 raise hang (124)
pin1, np 4, disk rank 1 ok, ranks 0, 2, 3 raise hang (124)
pin0, np 2, in memory, error not caught rank 1 exits with the traceback hang, not an abort: rank 0 waits in solve (124)

The stacks put every live rank in the collective solve. The rank that held the solver also ran the
solver-state phase of the restore; the others raised before it.

3. The finalizer (probes/fin.py). Every run passed:

  • gc disabled, rank-local collection, np 2, who = 0 and 1. Dropped solvers alive per rank were [0, 3]
    and [3, 0]; KSP wrappers [3, 12] and [12, 3]. PETSc.garbage_cleanup on all ranks, then the live solve,
    then the same iterations as the reference. After every rank collects: [0, 0].
  • Interpreter exit, np 1 and 2.
    • With gc off, 3 dropped solvers were still alive; with gc on, 2.
    • Exit code 0, and no PETSc error, exception, leak warning or signal in the full output.
  • gc inside another solver's solve. A monitor on live A's velocity-block KSP ran gc.collect() on one
    rank (0, then 1) during the solve. That freed the dropped B on that rank only (2246 objects; B alive
    [F,T] and [T,F]).
    • A converged (reason 2) with the same iterations, and |ΔV| was 3.6e-14, the same as the unfired run.
    • The following collective cleanup and solve completed.
  • release() after PETSc is finalized. PETSc._finalize() by hand, then gc.collect() with 3
    collectable solvers, at np 1 and 2: exit 0 and no error.
    • detach() has no isFinalized() guard, unlike _drop_solver_options.
    • It survived here, but the guard is cheap (N5).

4. F5. A solver with materials, dropped while the distribution is held, is collected (test_materials
passes at np 1 and 2). The strong-materials mutant fails that test.

5. Tests

  • test_1154 at np 1: branch 5 of 5 pass; base 5 of 5 fail.

  • test_1154 at np 2 (mpirun -n 2 pytest --with-mpi):

    • branch: the 4 non-snapshot tests pass on both ranks; base fails them.
    • The snapshot test aborts the job at np 2 (N3): tmp_path differs per rank, so one rank's
      save_state(file=) hits FileNotFoundError on .bulk, and MPI aborts (Allreduce message truncated).
    • test_1154 runs only in the serial batch, so CI is unaffected.
  • Mutants (probes/mutants2.py), each against test_1154:

    mutant result
    strong register 5 of 5 fail
    strong materials test_materials fails
    finalizer removed test_..._no_ksp_behind fails
    in-memory message without "collected" the snapshot test fails
    disk message only, without "collected" the snapshot test fails
    unmutated 5 of 5 pass
  • The 90-file suite on the branch (not level_3, 5 workers): 645 passed, 0 failed, 6 skipped,
    1 xfailed. Round 1's test_1079 failure was my missing scripts/; it passes now.

New findings

N1 (Medium-High). The F2 errors are rank-dependent, and the job hangs.

  • restore (snapshot.py:431-445) and read_snapshot (disk_snapshot.py:552-566) decide "is this
    bearer here?" rank-locally. A reference to the dropped solver held on only some ranks makes those ranks
    succeed, and the others raise. The job then hangs at the next collective, even when the error is not
    caught.
  • Base never reaches this, because the register pins the solver on every rank.
  • Fix: agree on the missing keys before raising, with an allreduce of a "missing" flag or the key set, and
    raise on every rank. Test it at np 2 with a reference held on one rank.

N2 (Medium). A failed restore leaves the model half-restored.

  • Restore writes the meshes (and swarms) before it checks the state-bearers. probes/partial_restore.py,
    serial:
    • after the SnapshotInvalidatedError, T equals the snapshot's values (True);
    • T is not the field as it stood before the load (False).
  • This is pre-existing, but the new contract makes it the documented outcome of a common path. Either
    validate bearers first, so the load is all-or-nothing, or say in the error that the fields were already
    rewound.

N3 (Low). test_1154's snapshot test is not parallel-safe. It uses the per-rank tmp_path for a
collective disk write. It is serial-only in test.sh, so CI is unaffected. Mark it as serial, or broadcast
the path.

N4 (Low, separate issue). The mesh keeps MeshVariables that a solver created.

  • About 23 DMs and 12 Mats per dropped solver stay, in mesh._vars (strong), when Stokes builds its own
    fields.
  • With the fields reused the count is 0.
  • Not this PR's register. File it.

N5 (Low). SolverInstrumentation.release() and _KSPEntry.detach() have no PETSc.Sys.isFinalized()
guard.
The same holds for the finalizer that now calls them from gc. The hand-finalize probe was clean at
np 1 and 2, but _drop_solver_options guards for exactly this case. Add the guard.

Merge conditions

What we could not test

  • macOS, more than 4 ranks, CI's environment on kaiju.
  • level_3 tests.
  • The full suite outside the 90 files.
  • A real interpreter-exit race with PETSc finalize: only simulated, with PETSc._finalize() by hand.
  • N1 on base: unreachable there, since the register pins the solver.
  • Whether the user-facing message is clear enough. That is a judgement for the PR.

Underworld development team with AI support from Claude Code

… nothing

- N1: restore and read_snapshot decided rank-locally whether a history
  manager the snapshot names is still registered. With a reference to a
  dropped solver held on only some ranks, those ranks restored and the
  others raised, and the job hung in the next collective (hyperion, np 2
  and 4). The verdict is now agreed (_agreed_problem, on the verdict
  communicator) and raised on every rank.
- N2: a refused restore had already written the meshes and swarms. The
  in-memory restore now looks up everything the snapshot names before it
  writes anything (_restore_problem); the disk restore checks its
  state-bearers before it reads any variable. The errors say nothing
  was restored.
- N3: test_1154's snapshot test is serial (a per-rank tmp_path); the
  parallel contract is tests/parallel/test_1155, one rank holding a
  reference, both restores refused on every rank, the field unchanged.
- N5: SolverInstrumentation.release() touches no PETSc object once PETSc
  is finalised (it can run from the collection finaliser at exit).

test_1154: 5 passed; development's restore order fails its field check.
161 files plus test_1155 (serial): 1683 passed, 0 failed.

Underworld development team with AI support from Claude Code
@lmoresi

lmoresi commented Nov 10, 2026

Copy link
Copy Markdown
Member Author

Review record, round 3: cb2b2cc

Paths under probes/ and logs/ are on hyperion, in runs/2026-11-11-1041/review3/.


Round 3: cb2b2cc

PR #1050, bugfix/weak-solver-register-1041 at cb2b2cc, against development e7fdcb2.

  • Builds: wt-1041, rebuilt; the installed snapshot.py, disk_snapshot.py and solver_health.py
    match the source. wt-deve7f is the base.
  • Where things ran: tests from git archive copies in this directory. Swaps and mutants were patched
    in-process (probes/swap.py); nothing was written into a worktree.
  • Cores and record: at most 12 cores. Probes and logs are in probes/ and logs/. Hyperion,
    2026-11-11. Rounds 1 and 2: ../review/1041-review.md and ../review2/1041-review2.md.

Verdict

Ready to merge.

  • N1, N3 and N5 are fixed.
  • N2 is fixed for what this PR introduced. The two remaining partial-write and hang paths are on
    development too (F7 and F8), and are not regressions.
  • No regressions: the leak numbers are the same as round 2, test_1154 passes, and the 90-file suite passes.
  • The merge conditions are small text changes, plus filing F7 and F8.

Status of the round-2 findings

finding status evidence
N1 F2 error rank-dependent, job hangs Fixed Every f2_rank case raises on every rank and completes. test_1155 passes at np 2 and 4, and fails or hangs under development's checkpoint code or a rank-local check.
N2 refused restore half-restored Fixed for missing objects. Not for validation refusals inside the write loop (F7, on development too). partial_restore: field unchanged. Mutants that write before the check are caught at np 1 and np 2.
N3 test_1154 snapshot test not parallel-safe Fixed Skipped at np 2. The other 4 tests pass on both ranks, with exit 0.
N4 mesh pins solver-created MeshVariables Open, sent to C1 as a design question Unchanged. cycles_lv (Stokes makes its own fields) leaves 23 DMs, 12 Mats and 12 Vecs per cycle, 1.1 MB per cycle at np 2. With the fields reused: 0 objects, 0.03 MB per cycle.
N5 release() without an isFinalized() guard Fixed The guard is present (solver_health.py:305). The hand-finalize probe gives exit 0 with no error at np 1 and 2. The no-guard mutant is not caught by any test: the old code also survived this probe, so it is an equivalent mutant in practice.

Checks

1. f2_rank: every case is a rank-uniform raise, with no hang. Each rank writes its outcome to a file
before any collective, then calls solve.

np who holds the old solver in memory disk job
2 nobody, rank 0, rank 1 both raise SnapshotInvalidatedError both raise ValueError solve after on both, exit 0
4 nobody, rank 0, rank 3 all 4 raise all 4 raise solve after on all 4, exit 0
2, error not caught rank 0 or 1 both ranks traceback both ranks traceback exit 1, no hang
4, error not caught rank 1 (in memory), rank 3 (disk) all 4 traceback all 4 traceback exit 1, no hang

Round 2's equivalent cases hung with exit 124.

2. test_1155 (the new parallel test)

code np 2 np 4
as built 2 of 2 pass on every rank 2 of 2 pass on every rank
development's snapshot.py and disk_snapshot.py swapped in fail: the holding rank gets DID NOT RAISE, the others a "collected" regex mismatch fail, no hang
branch, _agreed_problem made rank-local (N1 revert) hang in apply_snapshot_payload, supervisor kill (exit 124) hang (exit 124)
branch, check moved after the writes (N2 revert), in memory or disk fail: the field-unchanged assertion
  • It guards N1. The rank-local revert hangs on both rank counts, and development's code fails the test.
  • pytest.mark.timeout(300) uses the default signal method. A rank blocked in MPI never sees the signal,
    so the hang lasted until the supervisor's silence kill. CI's supervisor (silence 300) still turns that
    red. test_0079 uses method="thread", which would make it a clean failure (F9).

3. N2

  • Missing objects. partial_restore: after the refusal, T is not the snapshot's value and equals what
    it was before the load. That is the in-memory case; the disk case shows the same in test_1154 and
    test_1155.
  • Remaining partial write, in memory (F7). probes/n2_more.py version2: two meshes, the second deformed
    after the snapshot. load_state raises "mesh ... _mesh_version moved", but mesh 1's field is
    already rewound
    : rewound True, unchanged False. Development gives the same result.
    • The version, coordinate-shape and variable checks live in Mesh.apply_snapshot_payload, inside the
      write loop. They are not in _restore_problem.
    • The new message's "Nothing was restored" is only claimed on the state-bearer refusal, so it is not
      wrong. The general claim in the comment ("a refused restore leaves the model as it was") holds only for
      missing objects.
  • Remaining hang, disk (F8). W1's statement that the disk path's mesh lookup is rank-symmetric holds
    only without rank-local references. probes/n2_more.py dropmesh at np 2: two meshes, with mesh 2
    dropped on every rank except rank 0, which keeps a reference.
    • read_snapshot: rank 1 raises "contains mesh ... not registered" in the read loop, and rank 0 waits in
      read_checkpoint. Supervisor kill, exit 124.
    • The same hang on development (exit 124, same stacks).
    • The in-memory path is not affected: _restore_problem checks meshes, and the verdict is agreed.
    • The fix has the same shape as N1: look up the file's meshes (and their variables) before the
      _agreed_problem call.
  • Is verdict_comm balanced? [read]
    • restore calls _agreed_problem exactly once, unconditionally, on success and on refusal.
    • read_snapshot calls it exactly once, unconditionally, inside the with h5py.File block.
    • _restore_problem returns a string and doesn't raise on its inputs.
    • _agreed_problem is a no-op at np 1.
    • Everything that can raise before the allgather is rank-symmetric on a shared filesystem: the rank-count
      check, the bulk-dir isdir, h5py.File open, _live_meshes.
    • On a node-local filesystem, a missing bulk dir on one node would leave the others waiting in
      verdict_comm.allgather. That is pre-existing in kind, and on its own communicator, as mpi.py:55-64
      intends.

4. N5. The guard is present. fin.py afterfin (PETSc._finalize() by hand, then a collection of 3
dropped solvers): exit 0 at np 1 and 2, no exception, error or signal.

5. Regressions

  • repro1041: 0 solvers, 0 SNES and 0 KSPs after each of 6 drops.

  • p12 delete: 0 KSPs at np 1 and 2, 376.0 → 377.9 MB (np 1) and 382.8 → 386.9 MB (np 2) over 8
    solvers.

  • cycles_lv* at np 2: the same as round 2. Fields reused: 0 PETSc objects and 0.03 MB per cycle.
    Fields created: 23 DMs and 1.1 MB per cycle (N4).

  • fin.py:

    • gc disabled with only rank 0 (or 1) collecting: alive [0, 3] (or [3, 0]), KSPs [3, 12] (or [12, 3]).
      The live solve matched the reference iterations.
    • Collection inside another solver's monitor on one rank: the live solve unchanged, |ΔV| 3.6e-14.
    • Exit with dropped solvers alive (gc on and gc off): exit 0, no error.
  • test_1154:

    • np 1: branch 5 of 5 pass; base 5 of 5 fail.
    • np 2: 4 pass on both ranks, the snapshot test skipped, exit 0.
  • The 90-file suite on the branch (not level_3, 8 workers): 645 passed, 0 failed, 6 skipped,
    1 xfailed.

  • Mutants:

    mutant caught by
    N1 rank-local check test_1155 hangs at np 2 and 4. test_1154 (serial) passes, as expected.
    N2 write-before-check, in memory test_1154 at np 1, and test_1155 at np 2
    N2 write-before-check, disk test_1154 at np 1, and test_1155 at np 2
    N5 guard removed nothing (equivalent in practice, see N5 above)

6. The solver_health.py and test.sh changes

  • SolverInstrumentation.release(). After PETSc.Sys.isFinalized() it sets each entry.ksp = None,
    clears the dict and resets _outer_handle, with no PETSc calls. Otherwise it is the old _detach_all().
    • PETSc is a module import (solver_health.py:59), so it is safe at gc time.
    • The _reset path is unchanged.
    • Correct. The docstring update ("can be at interpreter exit") is accurate.
  • scripts/test.sh.
    • It adds batch 3 tests/parallel/test_1155... to the serial phase, in the block of parallel-dir files
      that also run serially. test_1155 skips at np 1, so that line only records a skip.
    • The real coverage comes from the parallel phase's tests/parallel/test_*.py enumeration, at
      PARALLEL_RANKS, and at np 4 under --full-parallel.
    • Harmless, but the comment "So is a refused snapshot restore ..." implies a serial check that doesn't
      exist (F10).

New findings

F7 (Low, on development too). Validation refusals in the in-memory write loop still leave a partial
restore.

  • A moved _mesh_version, a coordinate-shape mismatch, or a missing or reshaped variable on a later mesh
    is refused inside apply_snapshot_payload, after earlier meshes were written.
  • Measured: with two meshes, the second deformed, mesh 1 is rewound and the load raises.
  • Fix: move these checks into _restore_problem. They are cheap and rank-symmetric, apart from the
    shape-mismatch check, which the agreement covers. Or file it.

F8 (Low-Medium, on development too). The disk read's mesh lookup is rank-local, so a rank-local mesh
reference hangs the job.

  • Measured at np 2 on branch and base: one rank raises "contains mesh ... not registered", the other
    waits in read_checkpoint, exit 124.
  • Fix: look up every mesh and variable the file names before _agreed_problem, which also makes the disk
    refusal write nothing. Or file it.

F9 (Info). test_1155's timeout(300) uses the signal method, which cannot interrupt a rank blocked in
MPI. Use method="thread", as test_0079 does.

F10 (Info). The serial batch 3 line for test_1155 only records a skip. Drop it, or reword its
comment.

Merge conditions

What we could not test

  • macOS, more than 4 ranks, kaiju/CI.
  • level_3 tests, and the full suite outside the 90 files.
  • A real exit-time race with PETSc finalize; it was simulated with PETSc._finalize() by hand.
  • A node-local filesystem for the pre-allgather raises. [read]

Underworld development team with AI support from Claude Code

… any read

- F8: read_snapshot looked up a mesh, and each of its variables, inside
  the read loop. With a mesh dropped on some ranks but still referenced
  on one, that rank waited in the collective read_checkpoint while the
  others raised "not registered" (hyperion, np 2). Every mesh, variable
  and history manager the file names is now looked up first, and the
  verdict agreed across the ranks before any read.
- F7: the in-memory restore's comment now says which refusals leave the
  model as it was (a missing mesh, swarm or history manager); the checks
  inside apply_snapshot_payload still run as each mesh is written, as on
  development.
- F9: test_1155's timeout uses the thread method.
- F10: test_1155 leaves the serial batch list, where it could only skip;
  the MPI phase's glob runs it.

43 snapshot and checkpoint files plus test_1154 (serial): 492 passed.

Underworld development team with AI support from Claude Code
@lmoresi

lmoresi commented Nov 10, 2026

Copy link
Copy Markdown
Member Author

Review record, round 4: 1dc10a3

Verdict: ready. F8 is fixed, and F7 and F9 are done as you described. F10 I took from your diff and didn't run separately. Rebuilt at 1dc10a3 on hyperion; tests ran from a git archive copy under mpi_supervisor.py --silence 300.

F8, the dropmesh case (review3/probes/n2_more.py dropmesh):

  • Setup: two meshes. Mesh 2 is dropped on every rank except rank 0, which keeps a reference, then a disk load runs.
  • I added a check that the surviving field T1 is unchanged after the refusal.
np cb2b2cc (round 3) / development 1dc10a3
2 rank 1 raises, rank 0 waits in read_checkpoint; hang, exit 124 both ranks raise the same ValueError; T1 unchanged on both; barrier after the load passes; exit 0
4 – all 4 raise the same ValueError; T1 unchanged on all 4; barrier passes; exit 0

So the disk refusal is now rank-uniform, and nothing is written.

Tests:

  • test_1155: 2 of 2 pass on every rank at np 2 and at np 4, in 7–9 s.
  • test_1155 now has timeout(300, method="thread") (F9).
  • test_1154 at np 1: 5 passed.

F7: only the comment is narrowed. Validation refusals inside apply_snapshot_payload can still leave an earlier mesh rewound; that also happens on development. Accepted as is.

Not rerun this round: the 90-file suite, and the round-3 mutants. Round 3's results stand for the code this commit doesn't touch.

Logs and the probe copy are on hyperion, in runs/2026-11-11-1041/review4/.

Underworld development team with AI support from Claude Code

One conflict, in the test list: both entries kept.

Underworld development team with AI support from Claude Code
Underworld development team with AI support from Claude Code

# Conflicts:
#	scripts/test.sh
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