Repository navigation
A dropped solver is freed with its KSP tree: weak solver registers, and the instrumentation cycle broken on collection (#1041) - #1050
Conversation
…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
Review record, round 1 of 2: 343f58bThis 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 Pre-PR adversarial review:
|
| 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(PCsfieldsplit/gamg/gasm).
So restore's_discard_preconditioner_setuprunssetType("none"),setType("gamg")and
setFromOptionson 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:
pin0wrote[Solver_18_, Solver_29_, Solver_7_], B included. The other ranks have no B, so they
ignore B's group.pin1wrote[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_meshand_invalidate_caches_after_dm_change. They only setis_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 rankwho(0 or 1) collects B,
thenPETSc.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 IPythonOut[]) 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_registerhas four appends (.pyx6425, 7360, 8375, 9255) and three
readers (discretisation_mesh.py2572 and 4536,snapshot.py222). 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_projectionand_flux_projection; - the Stokes
_tau_projectorand_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] - DDt
-
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._solversandmodel._state_bearersare weak. On base they were full
only because the register pinned every solver. -
TranscriptAdjointfinds its solvers withmodel.part_object. After the caller drops them, base
computes the gradient (-0.004824), and the branch raisesSnapshotInvalidatedErrorfor the dropped
solver'sEulerianSUPGstate-bearer (probes/adj_dropped.py). [run] -
The same happens with no adjoint involved: rebuild an AdvDiffusion solver, then
load_statea
snapshot taken before the rebuild (probes/rebuild_rewind.py,rebuild_rewind_disk.py). [run]base branch in memory ok SnapshotInvalidatedErrordisk 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()beforedel) 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.
SolverInstrumentationholds 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.viewmid-run, after cleanup.
(N=20 - N=10)/10gives 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
_InstrumentedKSPcallbacks 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_SolverRegisterdocstring and the commit message carry the same claim. - Fix: release the instrumentation when the solver is collected (a
weakref.finalizeon the solver,
through a holder, since_instrumentationis 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_bearerswhen it is collected.restore
(snapshot.py:431-442) andread_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.rewindandTranscriptAdjointfor 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.
- skip bearers that are known to have been collected, for example by recording the keys of collected
-
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)andpickle.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.
materials.py:480keeps_solversin a strong list. A dropped solver that was givenmaterialsstays
alive as long as itsMaterialRegistry. [read, not run]- The same residual as A deleted solver is never freed: Mesh._equation_systems_register holds every solver built on the mesh #1041, through another holder. Track it with A deleted solver is never freed: Mesh._equation_systems_register holds every solver built on the mesh #1041, or say why not.
F6 (Info). Counts in the model description now depend on collection.
Model.describefacts (solvers) andexport_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-timegamgresets on one rank andPETSc.garbage_cleanupwith 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.shhasbatch 4 tests/test_1154*py.
Merge conditions
- F1: release the instrumentation when the solver is collected. test_1154 asserts the KSP count is flat,
and it is shown to fail without the release, and without the weak register. - F2: decide the restore contract for the state-bearers of collected solvers, with a test, in memory and
on disk. Or file it, and leaveCloses #1041off until it is decided. - Docstrings and commit message: state what is freed, as measured, and name
_live_meshes'
collection as the reason the snapshot readers agree across ranks. - F3: keep the copy and give its real reason, or drop it.
- PR body: give the 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 and A deleted solver is never freed: Mesh._equation_systems_register holds every solver built on the mesh #1041 verdicts as above. F5 is filed or listed.
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
Review record, round 2 of 2: b590073Paths under Round 2: b590073PR #1050, VerdictThe leak is fixed; one merge condition is left. The KSP tree is freed, and PETSc objects per dropped The remaining condition is a parallel hang in the F2 contract. When one rank still holds the dropped Round-1 findings: status
F1 numbers. The issue's reproduction (6 solvers) gives 0 solvers, 0 SNES and 0 KSP alive after every
PETSc objects alive per dropped solver, from
The objects that remain when Stokes builds its own fields belong to the velocity and pressure Checks1. Round-1 probes on b590073
2. Are the F2 errors rank-uniform? They are not.
The stacks put every live rank in the collective 3. The finalizer (
4. F5. A solver with 5. Tests
New findingsN1 (Medium-High). The F2 errors are rank-dependent, and the job hangs.
N2 (Medium). A failed restore leaves the model half-restored.
N3 (Low). test_1154's snapshot test is not parallel-safe. It uses the per-rank N4 (Low, separate issue). The mesh keeps MeshVariables that a solver created.
N5 (Low). Merge conditions
What we could not test
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
Review record, round 3: cb2b2ccPaths under Round 3: cb2b2ccPR #1050,
VerdictReady to merge.
Status of the round-2 findings
Checks1.
Round 2's equivalent cases hung with exit 124. 2. test_1155 (the new parallel test)
3. N2
4. N5. The guard is present. 5. Regressions
6. The
New findingsF7 (Low, on development too). Validation refusals in the in-memory write loop still leave a partial
F8 (Low-Medium, on development too). The disk read's mesh lookup is rank-local, so a rank-local mesh
F9 (Info). test_1155's F10 (Info). The serial Merge conditions
What we could not test
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
Review record, round 4: 1dc10a3Verdict: 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 F8, the dropmesh case (
So the disk refusal is now rank-uniform, and nothing is written. Tests:
F7: only the comment is narrowed. Validation refusals inside 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 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
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
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, asmodel._solvers,model._state_bearersandmodel._part_objectsalready did.MaterialDistributionkept 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._resetbroke 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 aweakref.finalizethat calls the instrumentation'srelease().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, andTranscriptAdjointalready 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:SnapshotInvalidatedError;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_1155holds 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, andtests/parallel/test_1155_snapshot_refusal_agrees_across_ranks_parallel.py(level_1, tier_b, np > 1):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
_move_version) and A rebuild-memory test on the rotated free-slip + custom-FMG + split-fault path (refs #948) #951 (a rebuild-memory test): not affected.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.describeandexport_configcan change once a dropped solver is collected (from reading; not tested).Underworld development team with AI support from Claude Code