Skip to content

Fix MPI submesh injection across parent ownership boundaries - #858

Merged
lmoresi merged 3 commits into
underworldcode:developmentfrom
gthyagi:bugfix/submesh-parent-ownership
Nov 12, 2026
Merged

lmoresi merged 3 commits into
underworldcode:developmentfrom
gthyagi:bugfix/submesh-parent-ownership

Conversation

@gthyagi

@gthyagi gthyagi commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Submesh injection can lose shared-node values when a parent DOF owner retains no extracted-region cells. Local copies reach another rank's parent ghosts, then owner synchronization overwrites them with untouched values. In the annulus workflow this zeroed four inner-wall topography values before gravity assembly.

Reduce matched values and their multiplicities through the parent field DM before synchronizing owners. Averaging shared contributions preserves replace/add semantics and leaves unmatched parent values unchanged. Production transfer uses distributed PETSc vectors without gathering global coordinates.

The original CI failure exposed a second cause: if an extracted region initially occupies one MPI rank, the filtered DM reports isDistributed() == False. The Mesh constructor then redistributed the child, invalidating rank-local parent matches. Preserve the parent-derived partition when constructing region and surface submeshes; ordinary mesh distribution is unchanged. Surface extraction now checks for a globally empty face stratum, allowing legitimate empty ranks while still rejecting missing/empty surfaces. Independent child repartitioning remains outside coordinate-coincidence injection.

Validation of the updated branch on an isolated Mac PETSc 3.25.0 int32/Open MPI 5.0.10 build:

  • Deterministic single-rank-region P1/P2 replace/add cases first fail on the original PR with the same CI errors: replace 5.0, add 4.0. Default-partition controls pass.
  • Patched serial suite: 20 passed and one pre-existing expected failure in embedded 1D on-surface evaluation.
  • Two MPI ranks: 23 tests passed on each rank, covering injection, region extraction/restriction, starved-rank cell sizes, subsequent mesh construction and surface extraction.
  • Four MPI ranks: all 10 focused cases passed on each rank, including empty parent/child ranks, re-extraction, unchanged exterior values and collective rejection of a globally empty surface.
  • Style gate, test formatting, Python parsing, diff checks and CI test reachability pass. No new benchmark models were run; the shared Mac installation is unchanged. Fresh Linux/MPICH CI validation is pending.

Earlier Gadi validation applies to the unchanged owner-reduction implementation in feature commit 86cb3cf1, before the partition-preservation follow-up:

  • Fresh PETSc int32 build: 18 UW3 tests in serial and on each of 16 MPI ranks; 270 annulus components passed.
  • Actual h=1/32 annulus meshes with 1h/2h/3h buffers reproduce the old 2h failure; corrected serial/MPI16 transfers agree within 1.8e-15.
  • Six complete Stokes–topography–Poisson regressions restore every saved source value, preserve Stokes fields to roundoff and agree between serial/MPI potential coefficients within 1.01e-11. Audited evidence.

Underworld development team with AI support from Claude Code

Review follow-up (29 October 2026)

The shared-DOF injection now reduces per-component minima/maxima through the parent field's PETSc section SF and raises collectively on disagreement (rtol 1e-12, atol 1e-14) before touching the target. Sum/multiplicity injection and raw nondimensional values are retained. Extraction documents its collective contract and deliberately persistent empty parent labels.

A deliberately corrupted local-copy regression failed before the fix. The final regression uses a whole-domain extracted child to guarantee shared nodes at MPI2 and MPI3, checks both vector components and both transfer modes, and verifies unchanged targets on failure. An isolated native Mac rebuild passes the complete file: serial 10 passed/4 MPI-only skipped; MPI2 and MPI3 each pass all 14 tests on every rank. Source/target meshes are not repartitioned by this change.

Merge this PR before #856: its globally surviving-label collective requires the collective extraction guards supplied here.

Underworld development team with AI support from Claude Code

Reduce source values and multiplicities through the parent field DM before owner synchronisation. This preserves spatial injection without global coordinate gathering, including add mode and untouched exterior values. A parent owner may retain no extracted-region cells even when another rank has the corresponding source node.

Add independent P1/P2 vector replace/add regressions. Reproducer: annulus 2h buffers at h=1/32 on 16 ranks lose four inner-wall source values despite correct saved submesh topography. Static compilation and diff checks pass; matching versioned int32 installation, serial/MPI regression gates and affected scientific reruns remain pending on Gadi.
Avoid implicit child redistribution when a filtered region or surface occupies only one MPI rank. Preserve the parent-derived point/DOF mappings and retain the existing parent-owner reduction. Make surface emptiness validation collective so ranks outside a valid surface do not fail before PETSc extraction.

Add deterministic P1/P2 replace/add coverage with the region concentrated on one parent rank, plus empty-rank re-extraction/cell-size and surface-label tests. The four new transfer cases fail on the original PR with errors 5.0/4.0 before this change.

Validation on an isolated rebuilt Mac PETSc 3.25 int32/Open MPI runtime: 20 serial passed, one existing expected failure; 23 passed on each of two ranks; 10 passed on each of four ranks. Python parsing, Black test formatting, deprecated-pattern gate, CI test reachability and diff checks pass. Shared runtime and benchmark results unchanged. Next: verify the fresh Linux/MPICH CI run.

Underworld development team with AI support from Claude Code
@lmoresi

lmoresi commented Oct 28, 2026

Copy link
Copy Markdown
Member

Adversarial review

1. The average conceals rank disagreement.

injected = values.array.reshape(new_data.shape)[matched] / multiplicity[matched]

is correct only while every contributing rank holds the same submesh value for
a shared parent DOF. If two ranks disagree, the result equals neither, silently,
under both replace and add. The description states that equality as a
property of coordinate-coincidence injection rather than checking it, and
nothing downstream asks whether a shared DOF was consistent.

The guard is cheap: reduce min and max alongside the sum and raise when they
differ beyond a tolerance. That turns a silent blend — the hardest class of bug
to find later — into a diagnosable failure. This is the one finding we would
want addressed before merge.

2. extract_surface is now collective, and its failure mode changed. The
emptiness check was rank-local; it is now
uw.mpi.comm.allreduce(local_faces) == 0. Calling extract_surface on a
subset of ranks now hangs where it previously raised. The file already uses
uw.mpi.comm 19 times against dm.comm 6, so the choice of communicator
matches house practice — we are recording the change of failure mode, not
asking for a different comm. See also #856, which adds a collective to
_surviving_labels further down the same function and depends on this change
landing first.

3. self.dm.createLabel(label_name) mutates the parent. It is called
unconditionally on the parent DM from a child-extraction path, adding an empty
label on ranks that lacked it. Harmless for a name that is already a boundary,
but it is a side effect on the parent and the comment above it explains the
collective need rather than the mutation. One line would record that it is
intended and that the parent keeps the label afterwards.

Discharged on inspection. We expected the = 1.0 count assignment to
under-count when two submesh rows map to one parent row, but _build_dof_map
returns parent_rows = numpy.where(matched)[0], which is unique by
construction, so it cannot. sub_rows can repeat — two coincident parent DOFs
on a split-mesh parent matching one submesh DOF — and both then receive the same
value; that is existing behaviour, not something this PR changes.

We also traced add through the shared-DOF case: a ghost-only match reduces to
the owner through localToGlobal(ADD), divides by its own multiplicity, and
pack_raw_data_to_petsc(..., sync=True) lets the owner win, so there is no
double count. That is the bug the PR fixes and the arithmetic holds.

Reduce component minima and maxima in the parent field section SF before changing any target values. Preserve raw nondimensional transfer and document collective surface extraction and its persistent empty labels.

Underworld development team with AI support from Claude Code
@gthyagi

gthyagi commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @lmoresi. Addressed in f93cadbd.

Shared contributions now undergo per-component minimum/maximum reductions through the parent field's PETSc section SF. Disagreement beyond atol=1e-14, rtol=1e-12 raises collectively before changing the target; agreeing values retain the existing sum/multiplicity injection and add semantics.

The regression deliberately corrupts local shared copies, covers both vector components and both transfer modes, and checks that rejection leaves the target unchanged. The inconsistency reproducer failed before the fix. After rebuilding locally, the complete file passes: serial 10 passed/4 MPI-only skipped; MPI2 and MPI3 each pass all 14 tests on every rank.

I also documented collective surface extraction and the intentional persistence of empty parent labels. #858 must merge before #856.

@gthyagi
gthyagi marked this pull request as ready for review October 29, 2026 12:46
@gthyagi
gthyagi requested a review from lmoresi as a code owner October 29, 2026 12:46
@lmoresi

lmoresi commented Nov 6, 2026

Copy link
Copy Markdown
Member

Adversarial review of #858

Verdict: ready with listed changes. The production injection is correct under every attack we ran. The regression test does not exercise the defect the PR is named for, and the new code leaks memory on every call in parallel.

Reviewed head f93cadb. Its base 7222caf is 344 commits behind development eddab70. The textual merge is clean. The last CI run (2026-10-29) predates that base, so it says nothing about the merged state.

Findings

  1. High. The injection test cannot fail on the ownership bug. With the old prolongate body restored and _preserve_partition kept, all 8 test_submesh_injection_preserves_all_parent_copies params still pass at np 2 to 8; only the 4 rejection tests fail. Owned parent DOFs with a child copy only on another rank: 0 in both test partitions at np 2, 3, 4, 8. Development does fail the test at np 2 (replace 5.0, add 4.0, "matched 0 of 59"), but through redistribution, not ownership. Cause: test lines 39 and 41 split at y=0.5 with the region on the last rank. Splitting at y=0.85 with Outer on rank 0 gives 21 orphan DOFs; the old body then errs 5.15 (np 4), the modified test fails 4 injection params at 5.0 (np 2, 4), and the fix passes 14/14.
  2. High. Memory grows on every parallel prolongate: overlap (discretisation_mesh.py:2597) is never destroyed. Rank 0, np 2, 2-D P2 vector: 15.4 kB per call at 1,142 DOF; 1,098 kB per call at 93,858 DOF, on PR head and merged. About 11 GB per 10,000 injections at that size. Development: 0. With overlap.destroy() in the finally: 0. We did not trace what holds the reference.
  3. Medium. The average is not tested at CI's rank count. Removing the division by multiplicity passes 14/14 at np 2 and fails 4 at np 3, 4, 8. At np 2 the region sits on one rank here (cells [0, 42]). The whole-domain case has shared copies at np 2, but asserts only rejection; it needs an agreeing-values injection assert.
  4. Medium. A label absent from a rank crashes before createLabel can help (:2147, :2161). getLabel returns a null-handle object, not None, so the guard is dead and getValueIS SEGVs. Removing "Top" on rank 0 alone SEGVs at np 2. Before extraction, hasLabel is True on every rank, and deleting createLabel passes 14/14 at np 2, so the comment and the design note describe a state that cannot be reached. extract_surface("NoSuchLabel", label_value=5) SEGVs at np 1 on PR and development, while the docstring promises ValueError: pre-existing, but these lines are rewritten here. self.dm.hasLabel fixes both.
  5. Medium. The new "Collective" note holds only for root parents until Keep extracted boundary names consistent across MPI ranks #856 lands. child.extract_surface("Top") raises ValueError on ranks whose child enum lacks the name, with peers hanging (np 2, 4). add_dirichlet_bc(..., "Internal") on a child raises KeyError with peers hanging in solver setup; development does the same at np 4, so not a regression. With Keep extracted boundary names consistent across MPI ranks #856's _surviving_labels hunk on top, the enum agrees and nested injection errs 0 at np 4.
  6. Low. The rejection contract is unpinned: dropping the non-finite check, or loosening to rtol=atol=0.1, still passes 14/14.
  7. Low. submesh-solver-architecture.md:50 ends "share one usage pattern:", and the new paragraph sits between it and the pattern at line 67.
  8. Low. The test file has no mpi(min_size=2) mark (:15), unlike test_0770. Bare serial pytest gives 10 passed, 4 skipped. test.sh --p 2 does reach it.
  9. Low. MPI._typedict (:2598) is a private mpi4py name where MPI.DOUBLE is public. About 70 inline lines in prolongate would read better as a helper (Charter section 1).

Attacks that failed

  • Test file: 14/14 at np 2, 3, 4, 5, 8 on head and np 2, 4, 8 merged; np 1 gives 10 passed, 4 skipped.
  • Field and geometry matrix, err 0 at np 2, 3, 4, 8 in both partitions: scalar, vector, sym-tensor and tensor at P1 to P3; a P3 fourth field; a field added after first use; P2 to P1 and P1 to P2; surfaces Top, Internal and Left; nested extraction; restrict round trip; annulus; 3-D P2 region and surface.
  • The headline defect itself: 21 orphan DOFs, err 0 at np 2, 3, 4, 8 on head, against 5.15 for the old body. The fix works; only the test misses it.
  • Rejection, raising or accepting on all ranks together, np 2, 4: 1 vs 1+5e-13 and 1e20 vs 1e20(1+5e-13) accepted; 1 vs 1+5e-11 raises; NaN and inf raise; 1e-15 vs 3e-15 accepted, averaging to 2e-15.
  • Empty ranks on a child, np 4: evaluate err 8.9e-16; write_timestep, integral, a 252-particle swarm and cell_size complete; DG0 and DG1 err 0.
  • Error symmetry: extract_surface on a bad name or value raises ValueError on all ranks; extract_region(value=99999) raises PETSc error 62 on all ranks.
  • Mutants caught: local raise and local empty check (hang, stopped by the supervisor), min-only reduction, disagreement check removed, counts doubled, partition preservation removed.
  • Existing tests, merged: test_0770, 0773_mpi, 0775, 0779 pass at np 2, 4; serial 0771, 0772, 0773 give 15 passed. Cost: 17 to 18 ms per call against 7.2 ms at 93,858 DOF.

Issues

Merge conditions

  • Move the test partition to y=0.85 with the region on rank 0, and show it fails on the old body.
  • Destroy overlap, with a test or measurement of no growth.
  • Add an agreeing-values injection assert on a child with shared copies at np 2.
  • Replace the null-label path with hasLabel, and remove createLabel and its claim unless a reachable case is shown.
  • Rebase on development and rerun CI.
  • Merge Keep extracted boundary names consistent across MPI ranks #856 straight after, as the PR body says.

Not tested

Open MPI and np above 8; CI's own partition at np 2; periodic parents and meshes after adapt beyond direct _re_extract_from_parent; surface re-extraction; the annulus and Stokes-topography workflow in the PR body, including its np 16 Gadi evidence, which predates the partition-preservation commit; a true three-way merge with #856, which ran only as a hunk overlay.

Underworld development team with AI support from Claude Code

@lmoresi

lmoresi commented Nov 12, 2026

Copy link
Copy Markdown
Member

Finishing this PR (H5, at Louis's and C1's direction): a superseding PR from underworldcode/underworld3:bugfix/submesh-injection-858. @gthyagi, your three commits are kept as they are, merged, not squashed.

What changed, against H1's review of f93cadb (2026-11-06):

  • Rebase condition. Development f8c6014 is merged in. It merged cleanly.
  • Finding 1 (high), the test missed the ownership bug. The shell partition now puts the extracted region (Outer, y > 0.85) on rank 0 and the inner slab on the last rank, split at the interface. Parent DOFs owned by a rank with no child copy now exist, and the test asserts that they do. The old prolongate body fails 10 tests at np 2 and at np 3; it passed them before.
  • Finding 2 (high), memory growth. The section SF is released in a finally. At np 2 with 23.6k DOF rows on rank 0, growth was 1098 kB per call; it's now 0.0 kB. The reduction moved into a helper, _reduce_injection, using the public MPI.DOUBLE (finding 9).
  • Finding 3, the average untested at np 2. A new test injects agreeing shared copies on a whole-domain child. Removing the division by the multiplicity now fails at np 2.
  • Finding 4, labels. extract_surface asks hasLabel first. The null-handle path aborted PETSc, and extract_surface("NoSuchLabel", label_value=5) now raises ValueError, which is tested. createLabel on the parent, and the claim about it in the docstring and design note, are removed, since every rank already has the label.
  • Finding 6, the rejection contract. It's now pinned: 5e-13 is accepted, and 5e-11 and NaN raise (each leaves the target unchanged).
  • Finding 7. The design-note paragraph moved below the flavours table.
  • Finding 8. The MPI-only tests carry mpi(min_size=2).
  • Added, Mesh.prolongate from a submesh loses values at parent DOFs owned by a rank outside the region (fails at np 3) #1087. tests/test_0858_submesh_injection_odd_ranks.py runs the annulus injection at np 3 and np 5 from serial CI; CI's np 2 and np 4 miss the bug on that mesh. It starts from a field of sevens, so dropped old values show, and asserts orphan DOFs exist.

Mutants (overlays): the old body, no division, dropped old values, a loose tolerance and no finiteness check are each caught.

Results: the file passes 20/20 at np 2, 3 and 4. The submesh files pass serially (81) and at np 2, 3 and 4 (54–56 each). test_0770 now passes at np 3.

Finding 5 (enum agreement on nested children) is #856's. That follows next, the same way.

Underworld development team with AI support from Claude Code

lmoresi added a commit that referenced this pull request Nov 12, 2026
…-858

Fix MPI submesh injection across parent ownership boundaries (completes #858)
@lmoresi
lmoresi merged commit e515e78 into underworldcode:development Nov 12, 2026
2 checks passed
gthyagi pushed a commit to gthyagi/underworld3 that referenced this pull request Nov 13, 2026
…, hasLabel, tests pinned

H1's review of f93cadb (2026-11-06), with development merged.

- The injection test now puts the extracted region on rank 0 and its
  neighbour on the last rank, split at the interface (y = 0.85). Parent
  DOFs owned there by a rank with no child copy now exist, and the test
  asserts that they do; the old prolongate body fails it (10 tests at
  np 2 and 3), where before it passed.
- The section SF taken in prolongate is released: it grew memory by
  1098 kB per call at 23.6k DOF rows on rank 0 at np 2; now 0.
- The shared-value reduction is a helper, _reduce_injection, with the
  public MPI.DOUBLE.
- extract_surface asks hasLabel before reading a label (getLabel gives a
  null handle, and getValueIS on it aborted PETSc), and no longer adds
  empty labels to the parent: every rank already has the label.
- New tests: agreeing shared copies are injected (a missing division by
  the multiplicity now fails at np 2); the rejection tolerance on both
  sides and non-finite values; a missing label raises ValueError. The
  MPI-only tests carry mpi(min_size=2).
- tests/test_0858_submesh_injection_odd_ranks.py runs the annulus
  injection at np 3 and 5 from serial CI (underworldcode#1087), from a field of sevens
  so dropped old values show, and asserts orphan DOFs exist.
- The design note's paragraph moves below the flavours table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
gthyagi pushed a commit to gthyagi/underworld3 that referenced this pull request Nov 13, 2026
…evelopment f8c6014) into underworldcode#856

underworldcode#856 must land after underworldcode#858: its collective _surviving_labels needs underworldcode#858's
collective extraction guards. Merged, not rebased, to keep gthyagi's
commits and authorship.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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