Skip to content

A dropped faulted mesh is freed, in serial and in parallel - #882

Merged
lmoresi merged 17 commits into
developmentfrom
bugfix/faulted-rebuild-leak-dev
Oct 29, 2026
Merged

lmoresi merged 17 commits into
developmentfrom
bugfix/faulted-rebuild-leak-dev

Conversation

@lmoresi

@lmoresi lmoresi commented Oct 28, 2026

Copy link
Copy Markdown
Member

A driver that rebuilds a faulted mesh each time the fault moves kept every mesh it had built. On kaiju (the ZG95 annulus slab driver, np 16) memory grew by one full mesh per rebuild, 0.44 GB per rank, until an out-of-memory kill after 24 rebuilds. This branch frees a dropped mesh in serial and in parallel.

What held a dropped mesh

  1. The default model's registries held meshes, variables, solvers and the step transcript's part objects strongly. They are now weak indexes; ownership follows the objects (docs/developer/subsystems/model-orchestration.md, "Weak References and Ownership"):
    • a mesh owns its variables (mesh.vars), and the base variable holds the user-facing MeshVariable, so the variable the model indexes lives as long as its mesh;
    • a variable, a solver and a swarm each hold their mesh;
    • coordinate and variable symbols hold their mesh and variable weakly, so sympy's caches pin nothing;
    • the primary mesh is a weak reference.
  2. MeshVariable._init_params kept the constructor's mesh for the variable's life. It is dropped after __init__.
  3. In parallel, petsc4py defers the destroy of a collected PETSc object to a list that only PETSc.garbage_cleanup empties, and nothing called it (2217 live DMs after five rebuilds at np 2). Building a mesh now does, collectively on its DM's communicator.

A mesh and its variables form a reference cycle, freed by the cyclic collector at a different moment on each rank. Two rules follow and are applied here:

  • a traversal that makes a collective call per registered mesh (every snapshot reader and writer) takes its list from Model._live_meshes(), which collects first, once per entry point and on every rank;
  • nothing in a mesh's cycle destroys a parallel PETSc object from __del__ (MeshVariable.__del__ is gone); a temporary discarded at a collective point destroys its vectors there (the variable statistics).

Measured

Moving-fault box, k = 3, rebuild + three solves, every reference dropped:

resident growth per rebuild live after 20 rebuilds (Mesh / DM / Mat / KSP)
serial, before 53.7 MB 183 / 427 / 240 / 20
serial, after 0.1 MB 12 / 28 / 12 / 1
np 2, before 56.0 MB 189 / 439 / 240 / 20
np 2, after 0.1 MB 12 / 28 / 12 / 1

(hyperion, Linux.) On macOS the resident set does not fall when memory is freed: with the fix PETSc's object table is the same after 4 and 8 rebuilds at np 2 (284 DMs, 221 Mats, 298 Vecs on rank 0) while the resident set still rises 14-26 MB per rebuild, so test_0078 asserts on Linux only.

Tests

  • tests/test_0077_model_registry_does_not_pin.py (level 2, tier B): a dropped mesh with a variable and a solver, a dropped faulted rebuild with a solve, a solver that solved inside a step, the primary mesh, a variable that keeps its mesh, a snapshot after a dropped mesh, a swarm that keeps its mesh, a variable the caller did not keep, a proxy that does not keep its swarm variable. Each failed before its fix.
  • tests/parallel/test_0078_rebuild_memory_parallel.py: resident growth per rebuild under 10 MB at np 2 (39.6 MB before), Linux only.
  • tests/parallel/test_0079_snapshot_after_a_dropped_mesh_parallel.py: disk and in-memory snapshots after a dropped mesh that one rank has collected and the other has not. The disk case hung at np 2 before the fix (rank 0 past the mesh loop, rank 1 in a second write_checkpoint).
  • test_1058 orphans its variable the way the statistics helpers do (it relied on a model reset releasing variables).

Suites on this branch (laptop, macOS): tier A level 1 serial 1494 passed, 44 skipped, 1 xfailed, 0 failed (test_0077 is level 2 and ran separately: 9 passed); tests/parallel at np 2 164 passed, 12 skipped, 1 failed; at np 4 172 passed, 4 skipped, 1 failed. No hangs. The one parallel failure is test_1063_constrained_freeslip_parallel[ti] (#826), which fails identically without this branch.

Issues

No open issue tracked this leak. Left open, found in the review and present before this branch: #866 (a proxied swarm variable's remesh callback never runs), #867 (_update_mesh_for_swarm unregisters from the wrong mesh), #868 (on a fixed mesh in parallel, new variables leave the old DM and vectors on petsc4py's deferred list until the next mesh). Snapshot issues in the territory, untouched and still live: #252, #296, #773, #774.

The adversarial review (four rounds) is in the first comment.

Underworld development team with AI support from Claude Code

Twenty rebuilds of the moving-fault fixture with three solves each; resident
set and live Mesh / MeshVariable / PETSc object counts after every solve, to
tell growth per step from growth per rebuild.

Underworld development team with AI support from Claude Code

(cherry picked from commit 60426ed)
…links)

Two owners kept every faulted rebuild alive: the default model's _meshes,
_variables and _solvers (strong dicts; now WeakValueDictionary, as _swarms
already was), and the coordinate objects' strong link to their mesh, pinned
through sympy's function caches (UWCoordinate, CoordinateSystem and its
accessors now hold the mesh weakly). test_0077 failed on both counts before
and passes after; full validation and the memory probe still to run.

Underworld development team with AI support from Claude Code

(cherry picked from commit 8ce92ea)
…h dies

Weak variable registration changed what a variable's lifetime means (a mesh
holds its variables weakly, so a variable the caller did not keep vanished:
22 tier-A failures). The registry holds variables strongly again and a
finalizer on each mesh drops its variables when it is freed. MeshVariable
no longer keeps its constructor arguments (_init_params held the mesh
strongly). test_0077 passes; one remaining failure, test_0864, is being
checked against the base.

Underworld development team with AI support from Claude Code

(cherry picked from commit dd7545c)
petsc4py defers destroying collected objects in parallel until a collective
PETSc.garbage_cleanup; nothing called it, so every dropped mesh's DMs,
matrices and vectors lived on (52.7 MB per rebuild at np 2 with every Python
object freed; 2217 live DMs after five rebuilds against 98 in serial).
Mesh.__init__, collective over its DM's communicator, now collects and
cleans up on that communicator. tests/parallel/test_0078 (written first:
39.6 MB per rebuild against a 10 MB bound) passes.

Underworld development team with AI support from Claude Code

(cherry picked from commit 8a955f5)
Each faulted-mesh rebuild kept the whole previous mesh: 53.7 MB per rebuild
in serial and 56.0 MB at np 2 on the moving-fault fixture, ~7 GB per node per
rebuild in kaiju production (an OOM kill after 24 rebuilds). Four owners:

- the default model's _meshes and _solvers registries (now weak; _variables
  stays the variables' owner and drops a mesh's variables when it is freed);
- sympy's caches holding coordinate symbols that held their mesh
  (UWCoordinate, CoordinateSystem and its accessors now hold it weakly);
- MeshVariable._init_params, the constructor arguments kept with the mesh;
- in parallel, petsc4py's deferred destroy list, never emptied: Mesh.__init__
  now collects and runs PETSc.garbage_cleanup on its DM's communicator.

After: 0.1 MB per rebuild in serial and at np 2. tests/test_0077 and
tests/parallel/test_0078, both written first and failing, pass. Tier A
level 1: 1495 passed, 1 failed (test_0864, failing identically on the base);
np 2 custom-MG / rotated / fault-split: 19 passed, 4 skipped. Numbers and
method in scripts/sessions/rebuild_leak/README.md.

Underworld development team with AI support from Claude Code

(cherry picked from commit 547c2e5)
…exes

Review findings on the leak fix:
- Model._part_objects (the step transcript's part -> object map) was a strong
  dict keyed by instance: every solver that solved inside model.step was kept,
  with its mesh. Now weak.
- A variable no longer kept its mesh (a helper returning only a variable lost
  the mesh). A variable now holds its mesh; the mesh owns its variables
  (mesh._vars a plain dict, the cycle collected with the mesh); the model's
  _variables is a weak index, so the finalizer purge (and the stale stats()
  temporaries it missed) is gone. Variable symbols hold the variable weakly,
  so sympy's caches pin neither.
- _primary_mesh_id outlived its mesh and could be taken by a reused address,
  differently per rank: the primary mesh is now a weak reference, a freed
  primary is replaced by the next mesh, and set_primary_mesh always sets it.
- The .msh path's cleanup now uses the communicator the reader uses.
test_0077 gains three tests (a variable keeps its mesh; a solver that solved
in a step with transcripts on is freed; the primary mesh is released and
replaced), each failing on 547c2e5 and passing here.

Underworld development team with AI support from Claude Code

(cherry picked from commit 56df136)
A mesh now owns its variables, so a model reset no longer releases one and
the tests' orphan never appeared (3 tier-A failures, premise only). The
orphan is made the way the statistics helpers make it: the variable taken off
mesh.vars and collected, its DM field left behind. The assertions on packing
around the orphan are unchanged.

Underworld development team with AI support from Claude Code

(cherry picked from commit ff782c4)
Underworld development team with AI support from Claude Code

(cherry picked from commit 5b4e365)
Underworld development team with AI support from Claude Code

(cherry picked from commit fb9b1ba)
Underworld development team with AI support from Claude Code

(cherry picked from commit b8624a4)
Underworld development team with AI support from Claude Code
WIP, hyperion shutdown 2026-10-27

Underworld development team with AI support from Claude Code
WIP, hyperion shutdown 2026-10-27

Underworld development team with AI support from Claude Code
- A snapshot collects before it visits the registered meshes
  (Model._live_meshes). A dropped mesh with variables is a reference cycle
  and stays in the weak registry until the cyclic collector runs, at a
  different moment on each rank; write_snapshot's per-mesh collective
  checkpoint write then hung at np 2 (test_0079 hangs before, passes after;
  the in-memory snapshot raised "duplicate mesh name" in serial).
- A swarm holds its mesh. Found by id in the weak registry, a mesh nobody
  else held was freed under the swarm (swarm.mesh returned None).
- The base variable holds its user-facing wrapper, so the variable the model
  indexes lives as long as the mesh that owns the base. A dropped wrapper
  vanished from the registry, and units, scaling and the adjoint skipped it.
- MeshVariable no longer destroys its vectors in __del__: it is freed by the
  cyclic collector at per-rank times, where an explicit destroy of the
  parallel vector is a collective call by one rank. petsc4py defers it to
  the cleanup the next mesh construction runs.

The three serial tests in test_0077 fail before and pass after.

Underworld development team with AI support from Claude Code
It read /proc/self/statm and failed with FileNotFoundError on macOS. On
macOS the resident set does not track freed memory: with the fix, PETSc's
object table is unchanged between 4 and 8 rebuilds (284 DMs, 221 Mats, 298
Vecs on rank 0 at np 2) while the resident set rises 14-26 MB per rebuild,
so the bound is a Linux assertion.

Underworld development team with AI support from Claude Code
…ords out

The ownership rules review 3 added (the base variable holds its wrapper, a
swarm holds its mesh, collective traversals collect first, no parallel destroy
from __del__) go into docs/developer/subsystems/model-orchestration.md beside
the rest. The probes, run records and README under scripts/sessions/
rebuild_leak leave the repository (Louis, 2026-10-28: library and expertise
in underworld3, campaign drivers and run outputs outside it); they are kept
in ~/+Simulations/rebuild_leak, and the review record goes on the PR.

Underworld development team with AI support from Claude Code
… per snapshot

- A proxied swarm variable's remesh callback held the variable strongly; the
  proxy's mesh owns the proxy (through the base variable and its wrapper), so
  a swarm moved off a long-lived mesh left that mesh keeping the variable and
  the swarm's new mesh. The callback holds it weakly (test_0077, fails before).
- The variable statistics destroy their temporary's vectors where they discard
  it, a point every rank reaches; left to the collector they waited on
  petsc4py's deferred list until the next mesh, one vector per call.
- Each snapshot entry point collects once, on every rank, and passes the
  list down; _solvers_of and the metadata writer no longer collect again,
  which they did inside rank-0-only blocks.
- test_0077 is level 2 and tier B (two tests solve; all are new and proven);
  test_0079 uses the thread timeout and gains the in-memory snapshot case;
  the orchestration doc states the Swarm.__del__ exception; a stale comment
  in Swarm.__init__ and test_1058's docstring corrected.

Underworld development team with AI support from Claude Code
Copilot AI balanced review requested due to automatic review settings October 28, 2026 07:50
@lmoresi

lmoresi commented Oct 28, 2026

Copy link
Copy Markdown
Member Author

Adversarial review (four rounds)

Rounds 1-2 (2026-10-27, on the box-faults base, two read-only passes) and 3 (independent, on the development-based branch, 3524433) were run on hyperion; round 4 (2026-10-28, laptop) re-reviewed the round-3 fixes. Every finding below was fixed in this branch unless it names an issue.

Found and fixed

Round 1-2:

  • Model._part_objects (the step transcript's part map) was a strong dict: every solver that solved inside model.step was kept with its mesh. test_0077 ran with transcripts off and could not see it. Now weak; test_0077 gains a solve-in-a-step case with transcripts on.
  • The first fix made a variable stop keeping its mesh (a helper returning only a variable lost the mesh). Ownership is now: a variable holds its mesh, a mesh owns its variables, the model indexes all three weakly.
  • _primary_mesh_id outlived its mesh and could be taken by a reused address, differently per rank. The primary mesh is a weak reference; set_primary_mesh always sets it.
  • A .msh read with comm= would have cleaned up on COMM_WORLD; the cleanup uses the reader's communicator (latent: no caller passes comm=).
  • test_1058 made its orphan by resetting the model, which no longer releases a variable; it now orphans one as the statistics helpers do.

Round 3:

  • Parallel hang: a dropped mesh with variables is a reference cycle and stays in the weak registry until the cyclic collector runs, at different moments per rank; write_snapshot makes a collective write_checkpoint per registered mesh. tests/parallel/test_0079 hung at np 2 before the fix (rank 0 past the mesh loop, rank 1 in a second write_checkpoint); the serial snapshot raised "duplicate mesh name". Fix: Model._live_meshes() collects first.
  • Swarm.mesh resolved its mesh by id through the weak registry: a swarm on a mesh nobody else held lost it (swarm.mesh returned None). The swarm holds its mesh.
  • mesh.vars held the base variable while the model indexed the user-facing wrapper: a dropped wrapper vanished from the registry (get_variable None; units, scaling and adjoint lookups skipped it). The base holds its wrapper.
  • MeshVariable.__del__ destroyed _gvec explicitly, now from cyclic collection at per-rank times (a collective call by one rank). Removed; petsc4py defers it.
  • test_0078 read /proc/self/statm (FileNotFoundError on macOS). It uses uw.utilities.memprobe and asserts on Linux only: on macOS PETSc's object table is the same after 4 and 8 rebuilds (284 DMs, 221 Mats, 298 Vecs, rank 0, np 2) while the resident set rises 14-26 MB per rebuild.

Round 4:

  • A proxied swarm variable's remesh callback captured the variable strongly; with the mesh owning the proxy wrapper, a swarm moved off a long-lived mesh left that mesh keeping the variable and the swarm's new mesh. The callback holds it weakly (test_0077, fails before: {'moved_to': False, 'variable': False}).
  • With __del__ gone, stats() temporaries on a fixed mesh would wait on petsc4py's deferred list until the next mesh (one Vec per call in parallel). They are destroyed where discarded, a point every rank reaches.
  • _live_meshes() ran up to three times per snapshot call, twice inside rank-0-only blocks (_solvers_of, the metadata writer). Each entry point now collects once on every rank and passes the list down.
  • test_0077 was tier A and level 1; it is tier B (all its tests are new and proven) and level 2 (two solve). test_0079 uses the thread timeout (a rank blocked in MPI does not see the signal) and gains the in-memory snapshot case. The orchestration doc states the Swarm.__del__ exception; a stale comment in Swarm.__init__ and test_1058's docstring corrected.

Found, not fixed here (pre-existing)

Attacks that failed

  • No Mesh( is built by a subset of ranks or on a sub-communicator in src; PETSc.garbage_cleanup touches only the given communicator and destroys only what every rank queued.
  • The wrapper holds its base, a weak mesh reference and scalars; function symbols hold variables weakly; nothing deep-copies or pickles a variable, mesh or coordinate system. base._wrapper reaches no other mesh except through the proxy callback (fixed above).
  • Swarm._mesh makes no new cycle (meshes hold swarms in a WeakSet, swarm variables hold their swarm weakly); no reader of the removed _mesh_id remains in src, tests or docs.
  • With __del__ removed, a serial (COMM_SELF) vector is still destroyed eagerly by petsc4py; _setup_ds builds new vectors itself and relies on no prompt destroy.
  • restore and read_snapshot collect before changing anything; the per-swarm allreduce in write_snapshot follows the all-rank collection.
  • Each new test fails on its bug (round-3 and round-4 runs above); test_0077 matches tests/test_00[6-7]*py, tests/parallel is enumerated.

Issues in the territory

No open issue tracked this leak. Snapshot issues touched by the diff and still live: #252 (write_checkpoint routing), #296 (geometry vs topology version), #773, #774 (parameters and expression contents not captured). #826 (test_1063[ti]) fails identically with and without this branch.

Merge conditions

  • tier A level 1 serial, tests/parallel at np 2 and 4: results in the PR body.
  • CI green on this PR.

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.

@lmoresi
lmoresi merged commit 24923e5 into development Oct 29, 2026
2 checks passed
lmoresi pushed a commit that referenced this pull request Oct 29, 2026
…split-multigrid

One conflict, in scripts/test.sh: #863 turned each pytest line into a
`batch <shard> ...` call, and this branch added the test_108*/test_109* line
in the old form. Resolved to the batch form, with the new line on shard 3,
the lightest measured. check_test_coverage: all 376 files reachable.

Underworld development team with AI support from Claude Code
lmoresi added a commit that referenced this pull request Oct 29, 2026
Development now carries #863's sharded CI, and #882, #889 and #890 (this
branch's base). The one conflict was scripts/test.sh: test_1090's serial
entry now takes the batch form, on shard 4 beside test_1069. All 382 test
files are reachable (check_test_coverage).

Underworld development team with AI support from Claude Code
lmoresi added a commit that referenced this pull request Nov 5, 2026
…akref check, three levels (review)

Findings of the adversarial review of ff4b674, all fixed:
- The first reading of the resident set was taken with the last warm-up rebuild's
  objects still on petsc4py's deferred list, and the last reading after a mesh
  had emptied it, so up to one rebuild's footprint was hidden. A mesh is now
  built before both readings, here and in #882's test_0078, which had the same
  pattern.
- A Python-held pin, #948's kind, is deterministic. Weak references to every
  measured rebuild's mesh and solver must be dead once dropped; this runs on any
  platform. Serially, a hook-style pin keeps 6 of 6 alive, and none survive
  without it.
- The resident-set bound is 5 MB per rebuild, not 10. A pinned solver adds about
  60 MB per rebuild of this fixture in serial.
- The base has three levels (cellSize 0.1, refinement 2: 242 / 968 / 3872 cells),
  so the FAC gate runs on a middle level, at the same cost.
- The timeout is 600 s, and the docstring's claims are dated and narrowed.

Both checks are tier C until a pinned run at np 2 on Linux shows them failing.

Underworld development team with AI support from Claude Code
gthyagi pushed a commit to gthyagi/underworld3 that referenced this pull request Nov 13, 2026
… not grow memory (underworldcode#948)

underworldcode#882's rebuild test covers a plain Stokes solve and passes on development f631ce4,
where the zg95 fault runs grow about 190 MB per rank at every fault rebuild. This
is its fixture on the path those runs take. Each rebuild cuts a new fault into one
refined base and solves with rotated free slip on every wall, the fault's own
constraint, and the custom FMG with the FAC patch keyed on the fault's cells. The
bound is test_0078's: 10 MB of resident set per rebuild on the worst rank, Linux
only. The test is not yet shown to fail; it goes to kaiju at np 2 and 4 against
development.

In serial, PETSc's object table balances on this path, and on five others, at 2
and 4 rebuilds (wombat probe). A parallel leak lives where petsc4py defers
destruction, which only the resident set sees.

Underworld development team with AI support from Claude Code
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