Skip to content

agreed_build: collectives that agree on failure, proved on the FAC patch split (#874) - #1218

Merged
lmoresi merged 6 commits into
developmentfrom
bugfix/agreed-build-874
Nov 16, 2026
Merged

lmoresi merged 6 commits into
developmentfrom
bugfix/agreed-build-874

Conversation

@lmoresi

@lmoresi lmoresi commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Addresses #874 (a mechanism, proposed with one function converted). Draft. W1 (the session that owns the convergence and integration work, and custom_mg) reviews the design. H1 (review and parallel test runs on a 96-thread Linux workstation) runs it in parallel. If both pass, custom_mg.build and partition_addon follow, one phase at a time.

Why

The sweep in #1216 guards parallel builders site by site. The inventory there lists 45 functions in fault_mg, custom_mg and addon_partition with an unguarded step ahead of a collective. Three of them have about 50 sites each: custom_mg.build, _fac_patch_split_parallel and addon_partition.partition_addon. Every new line would be a new site.

The mechanism (utilities/agreed_build.py)

  • agreed_build(what) is a context. An exception on one rank inside it is caught at the context's exit. That rank makes one agreement call, and raises CollectiveBuildError.
  • The other ranks meet that call at their next agreement point, and every rank raises the same error, with the class and the message of the first failing rank.
  • agree() is that agreement point. It goes before every collective that can't agree by itself: a PETSc collective, or a mesh method that is collective inside. Outside a context it does nothing, so a helper can carry it whoever calls it.
  • Wrappers allreduce(comm, ...), allgather(comm, ...) and bcast(comm, ...) agree and then communicate. They are preferred over a separate agree() line before an mpi4py collective.
  • The context's exit also agrees once on success, so a finished rank can't strand a failed one.
  • No double agreement: an error _collective_raise raised is marked agreed, and passes through a context without a second agreement. The counts stay paired.
  • Builder failures retry (H1, round 2). A failure inside a context is raised with builder_failure=True by default, through every agreement point. So the mesh-owned build takes the RBF retry (custom_mg.build_transfers) instead of degrading. An explicit set_custom_fmg registration surfaces the error, as it always has. A context that is not a transfer build passes builder_failure=False.
  • Swallows re-raise (H1, round 2). reraise_agreed(err) comes first in each of build's three sanctioned swallows (snes.setUp(), the operator check, the dimensional guard). An error every rank raised together is not swallowed on the healthy ranks while a failed rank leaves.
  • One verdict protocol (W1's class hazard). Every verdict exchange in the library now goes through underworld3.mpi.first_verdict. Before, three sites used two forms. The sites are fault_contact._collective_raise, Mesh._any_rank_failed and snapshot._agreed_problem.
    • Any two of these that pair make the same calls.
    • Every rank raises the class and message of the first failing rank. So an agreed_build exit (CollectiveBuildError) that pairs with a guard raising RuntimeError can no longer part the ranks.
  • Flag first (W1). first_verdict allreduces a one-integer flag on the verdict communicator, and gathers the verdicts only when it is set. A healthy path pays that small allreduce alone.
  • One envelope (H1, round 2). Every caller sends an mpi.Verdict(message, error, kwargs, site). When the flag is set, every rank sends its envelope, healthy ones too. If two different sites have paired, every rank raises the same "verdict exchange mismatch" error naming them, rather than reading one site's payload as another's.
  • Communicator (W1). Builds are world-collective: the verdict communicator duplicates the world, as every solver's communicator in the library is. The module docstring says so.

The rule a converted builder keeps: between any statement that can raise and the next collective, there is an agreement point.

  • Covered: every rank-local exception, now and in code added later, with no guard of its own.

  • Not covered: an exception inside a PETSc collective itself. The test hit this on its first try: a raise placed inside Scatter.create hangs, as designed.

  • Also not covered: a collective added later without an agreement point in front. Two checks enforce the rule:

    • statically, test_0052 checks direct mpi4py collectives: inside an agreed_build, or in a function that calls agree() (a helper, whose entry is not agreed), each has an agreement point after the last statement that can raise. The wrappers count as agreement points. The planted cases are flagged, the fixed ones are not, and the tree is clean. Its docstring states what it can't see: collectives inside helpers, PETSc and mesh-internal collectives, an agree() on one branch only, and an agree() inside a broad except.
    • at run time, for what the static rule can't see (collectives inside helpers), the proof test wraps the build's mpi4py communicator. It asserts that every collective inside an active context follows an agreement.
  • Cost: measured on the proof, one _fac_patch_split_parallel call (best of 3 × 20):

    ranks with the context without
    np 2 72.0 ms 71.7 ms
    np 4 45.3 ms 40.4 ms

    That is four to five agreement points in the call: about 1 ms each at np 4 here.

The proof

custom_mg._fac_patch_split_parallel has 46 unguarded statements. It is now one context with an agreement point before each of its collectives:

  • before the fetch of remote coarse nodes;
  • before the gate's first allreduce.

Its helper _append_remote_coarse_nodes carries agree() before its two PETSc collectives, the MPI Vec and the scatter. Nothing else changed.

tests/parallel/test_0874_agreed_build_parallel.py captures the split's call from test_1147's placed-ribbon solve.

  • Forced failures: one failure is forced on the last rank at each of these points, and every rank must raise the same CollectiveBuildError:
    • before the helper's first collective;
    • between the helper's two collectives, in a rank-local step;
    • after the function's last collective;
    • on a rank that holds no cell of the base.
  • Pairing: in every case, and on success, each rank's count of verdict exchanges is checked equal across ranks.
  • Round 2 cases:
    • a failure forced once in the FAC split during a mesh-owned solve takes the RBF retry on every rank, and the fallback is recorded;
    • an agreed error from the snes.setUp() swallow, through a stand-in solver, is re-raised on every rank;
    • two different verdict sites that pair raise the mismatch error on every rank;
    • reraise_agreed passes only agreed errors.
  • Runtime check: the healthy case runs with the runtime check above, and the answer is checked unchanged.

The empty-rank case runs from np 3. At np 2, the placed ribbon refuses a base with all its cells on one rank (addon_partition: not co-partitioned). That refusal happens collectively, before the split, and is a side finding, not this PR's.

A note from building the test: a failure forced inside Scatter.create, which is a PETSc collective, after its agreement point, hangs. That is the stated limit, seen in practice.

Results on a 96-thread Linux workstation (single system image; Intel Xeon Gold 6240R, AVX-512; MPICH):

case development, np 2 this branch
before the helper abort (exit 142) same error on every rank, counts paired
between the helper's collectives abort (exit 142) same error on every rank, counts paired
after the last collective hang (exit 124) same error on every rank, counts paired
  • This branch: 8 passed and 1 skipped at np 2 (the empty-rank case), and 9 passed at np 3, 4 and 5.
  • test_0052: 8 passed.
  • Parallel neighbours at np 2: 74 passed (all four test_0874 files, test_0974 (the snapshot refusal, which goes through first_verdict), test_1087_submesh, test_1089, test_1096, test_1147, test_1139, test_1120, test_1111).
  • Serial: 148 passed, 1 xfailed (test_0052, the fault and transfer files, the checkpoint and snapshot files, test_1079_diffusion_disk_restart).
  • scripts/check_test_coverage.py: OK.

If it is accepted

The same conversion applies to custom_mg.build, one phase at a time, each phase with a forced failure at np 2 to 5. Its 20 PETSc collectives and about 15 mesh-internal ones each get an agreement point, through a wrapper where one exists. partition_addon and the rest of #874's list follow. #1216's per-site guards stay valid: they are agreement points too. H1's toy pairing probes join the tests when they arrive: two ranks failing at different points, nesting, and no agree() before the exit.

Underworld development team with AI support from Claude Code

…tch split (#874)

A mechanism in place of per-statement guards. Inside agreed_build, an
exception on one rank is caught at the context's exit, where that rank makes
one agreement call (fault_contact._collective_raise on the verdict
communicator); the other ranks meet it at their next agreement point
(agree(), placed before each collective that cannot agree by itself) and
every rank raises the same CollectiveBuildError with the failing rank's
message. The exit also agrees on success, so a finished rank cannot leave a
failed one waiting; an error _collective_raise raised (now marked agreed)
passes through without a second agreement.

Proof: custom_mg._fac_patch_split_parallel (46 unguarded statements) is one
context with an agreement point before each of its collectives, and its
helper _append_remote_coarse_nodes carries agree() before its two PETSc
collectives. No per-statement guard.

Test: tests/parallel/test_0874_agreed_build_parallel.py forces one failure on
the last rank before the helper, between its collectives, and after the last
collective. Development: two aborts and a hang at np 2. Branch: 4 passed at
np 2 to 5; FAC neighbours 22 passed at np 2.

Underworld development team with AI support from Claude Code
@lmoresi

lmoresi commented Nov 16, 2026

Copy link
Copy Markdown
Member Author

Design review (W1, the integration session, which owns custom_mg; read at f1c8d40, not run)

The mechanism is right, and it is the one to take into custom_mg.build. It turns "guard every rank-local step" into "agree before every collective", which is far fewer sites and stays true for code added later. The pairing argument holds: a failed rank's exit agreement meets the healthy ranks' next agreement, as long as no collective sits between them without one. Four points to settle before it spreads, and one on the scan rule.

1. The error class is chosen per call site, so ranks can raise different classes. Fix before it spreads.

  • _collective_raise raises the error class its caller passed. The exit agreement passes CollectiveBuildError.
  • A healthy rank's next agreement point may be a _collective_raise with another class, such as fault_contact's checks with the default RuntimeError. That pairs, as it should, because it is the same allgather on the same communicator.
  • But then the failed rank raises CollectiveBuildError and the others raise RuntimeError.
  • custom_mg catches CollectiveBuildError to retry or degrade, so the ranks would part: some retrying, some unwinding, and a hang follows.
  • Suggested fix: gather (class name, message) and have every rank raise the class of the first failing verdict, or have every agreement inside an agreed_build raise CollectiveBuildError regardless of the call site.

2. The communicator. The context takes no communicator in use, and agreement runs on mpi.verdict_comm, a duplicate of the world communicator.

  • Today every UW3 mesh is on the world communicator, so this holds.
  • But the docstring says agreed_build(comm). Either take the build's communicator and keep a verdict duplicate per communicator, or state that builds are world-collective.

3. Cost. Every agree() is a pickled allgather, O(np) in memory and latency.

  • custom_mg.build would carry about 70 agreement points per build. At hundreds of ranks that is noticeable, and at thousands it dominates the small collectives it guards.
  • A fast path keeps the semantics: allreduce an int flag with MAX, and allgather the messages only when the flag is set. Healthy builds then pay one small allreduce per point.

4. Fit with custom_mg.

  • One agreed_build around CustomMGHierarchy.build fits its structure. The build already funnels its refusals into CollectiveBuildError, and its retry and degrade path is the natural catcher, as long as point 1 holds.
  • The work is not in build alone. Its collectives are spread through callees: fault_mg, addon_partition, the transfer builders, _coarse_reduced_map, and the PETSc PtAP and assembly.
  • agree() being a no-op outside a context is what makes this workable: each helper carries agree() at its own collectives, whoever calls it.
  • In the ranked direct calls (comm.tompi4py().allreduce(...) and friends), use your allreduce wrapper, adding allgather, bcast and Allreduce siblings, rather than an agree() line in front of each. That keeps the agreement and the collective on one line, which is also what makes a scan possible (point 5).
  • PETSc collectives (PtAP, assembly, DMCreateInterpolation, KSP setup) need an explicit agree() in front.
  • The limit you name stays: a raise inside a PETSc collective still hangs. That is the same as today.

5. Making the scan rule reliable.

  • A static rule (AST: inside an agreed_build block, every call to a known collective is a wrapper call or follows agree()) works only for collectives written in the block and named in a list.
  • It cannot see a collective inside a helper, which is most of custom_mg's, or a method that is collective internally (get_max_radius, mesh.deform, a solve).
  • So keep the static rule as a lint for direct mpi4py calls, and add a runtime check that covers the paths a test executes:
    • under a test, wrap the mpi4py communicator methods and the PETSc entry points the builder uses;
    • count, inside an active agreed_build, every collective not immediately preceded by an agreement;
    • assert zero over the build at np 2.
  • Combined with your forced failures at chosen points, that tests what the static rule cannot prove.

Next steps. With 1 settled, and preferably 3, I'd take it into custom_mg.build as you propose. Convert one phase at a time, with a forced failure in each phase at np 2 to 5, so each step is shown to raise everywhere rather than hang.

Underworld development team with AI support from Claude Code

… pairing checks (#874)

W1's design review of #1218 and C1's asks.

- Class hazard: every verdict exchange in the library (_collective_raise,
  Mesh._any_rank_failed, snapshot._agreed_problem) goes through one primitive,
  underworld3.mpi.first_verdict, so any two that pair make the same calls,
  and every rank raises the class and message of the first failing rank.
- Flag first: first_verdict allreduces a one-integer flag on the verdict
  communicator and gathers the verdicts only on a failure.
- Builds are world-collective (stated in the module docstring).
- Wrapper collectives agreed allreduce / allgather / bcast; the FAC split's
  two gate allreduces use them.
- Tests: forced failures at three points and on a rank with no cells (np 3
  up; at np 2 the placed ribbon refuses that partition collectively before
  the split), with the agreement calls per rank checked paired; a runtime
  check that every collective of the build's communicator inside the context
  follows an agreement; the static rule in test_0052, which flags a planted
  MPI and a planted PETSc collective.

Underworld development team with AI support from Claude Code
@lmoresi

lmoresi commented Nov 16, 2026

Copy link
Copy Markdown
Member Author

Review from the Underworld development team with AI support from Claude Code (H1: review and parallel test runs on a 96-thread Linux workstation (Intel Xeon Gold 6240R, AVX-512; MPICH))
(H1 is the session that reviews pull requests and runs the parallel tests.)

Verdict at 5d1298c: sound with changes. The mechanism pairs correctly in every ordering I could build, at np 2, 3 and 4. That includes two ranks failing at different points, nesting, a failure after the last agree(), mixed wrapper and agree() sequences, and an empty rank. The FAC patch split conversion is complete and costs nothing measurable. Before custom_mg.build and partition_addon are converted, four things need to change. Three are in the mechanism and one is in the call sites (findings 1 to 4). The first review round, at f1c8d40, gave the same pairing results. Its one class-mismatch case is fixed by first_verdict.

Pairing cases

These are toy probes: a function under agreed_build with agree() + PETSc Vec collectives and the wrapped mpi4py collectives. I counted the verdict-communicator calls on each rank (flag allreduces plus message allgathers). Every probe ends in a world barrier, so a later mis-pairing shows up as a hang. Rows marked "same" behaved identically at np 2, 3 and 4.

case np expected observed (5d1298c)
success, no failure 2, 3, 4 no error, counts equal no error; 4 flag allreduces on every rank, no allgather
last rank fails before the first agree() 2, 3, 4 CBE on all ranks CBE on all ranks, last rank's message; 2 calls on every rank
fails before a wrapped allreduce (healthy ranks' next point is the wrapper) 2, 3, 4 CBE on all same; 3 calls on every rank
fails after the last agree(), no further point before the exit 2, 3, 4 the exit's success agreement pairs pairs: CBE on all; 5 calls on every rank
rank 0 fails in segment 0, last rank in segment 2 2, 3, 4 rank 0's error on all; the last rank never reaches its own failure as expected; 2 calls on every rank
rank 0 and last rank fail in the same segment 2, 3, 4 first failing rank's message rank 0's message on all (the last rank's message is dropped)
wrapper and agree() interleaved (allreduce, agree+PETSc, allgather, bcast, agree+PETSc, allreduce); failure at each of the 7 gaps 2, 3, 4 CBE on all; counts k+1 at gap k as expected at all 7 gaps (21 runs)
nested: failure in the inner context, before or after its agree() 2, 3, 4 inner error on all, the outer passes it through as expected; counts equal
nested: failure in the outer context, before or after the inner one 2, 3, 4 outer error on all as expected
exception raised in agree() itself, before or after its flag allreduce 2, 3, 4 pairs pairs (the failing rank's exit meets the next point); CBE on all
a guard's _collective_raise(None) (RuntimeError) meets a failed exit 2, 3, 4 one class on all ranks CBE on all (at f1c8d40 the healthy ranks raised RuntimeError and the failing rank raised CBE)
CollectiveBuildError(builder_failure=True) raised on all ranks from their own verdict 2, 3, 4 builder_failure kept builder_failure=False on all (finding 1)
failing build exit meets snapshot._agreed_problem(None) 2, 3, 4 one class and message parts: the healthy ranks get a tuple (msg, CollectiveBuildError, {}) as their "problem" and raise ValueError; the failing rank raises CBE (finding 2)
Mesh._any_rank_failed on the last rank meets _collective_raise(None) 2, 3, 4 one outcome parts: healthy ranks raise TypeError ("cannot unpack non-iterable bool"), unmarked; the last rank gets True and goes on (finding 2)
snapshot refusal on one rank meets agree() on the others 2, 3, 4 the refusal on all counts pair, but every rank raises CBE "ValueError: too many values to unpack (expected 3)" (finding 2)
except Exception around an agree() on healthy ranks 2, 3, 4 (f1c8d40), 3 (5d1298c) hang (the healthy ranks swallow the error) hang: healthy ranks wait in the next agreement (finding 3)
failure after the last agree(), before a bare collective 2, 3, 4 / 3 hang (documented limit) hang
context entered on rank 0 only (rank-conditional) 2, 3, 4 / 3 hang healthy ranks report "no error" after mis-pairing, then rank 0 hangs
build on a sub-communicator (ranks 0, 1 only, or two concurrent builds on halves) 2, 3, 4 / 3 hang (verdicts are world-collective) hang at np 3 and 4; at np 2 the halves are single ranks and pair by accident
KeyboardInterrupt or SystemExit on one rank 2, 3, 4 / 3 passes through unagreed passes through; the other ranks hang in the next agreement, as they do on development

The FAC split itself (the PR's 3 forced points plus 2 of mine) shows equal per-rank counts at np 2, 3 and 4, and with an empty last rank at np 3 and 4:

point calls per rank
before the fetch 3
inside the fetch 4
between the fetch and the gate (mine) 5
after the gate 7
just before the exit, on both the taken and the not-taken (early return None) paths (mine) 7
healthy split 6

Findings

1. Medium, and blocking for converting custom_mg.build: the context exit drops builder_failure. A CollectiveBuildError that every rank raised from its own verdict, without agreed set, is wrapped again at the exit with builder_failure=False. Two kinds of raise do this:

  • _agreed_node_transfer, which uses its own allgather on the build communicator;
  • the "allreduced: every rank raises" checks in build.

The retry loop in _setup_custom_mg reads exc.builder_failure to decide between retrying with the RBF builder and degrading. Inside a converted build, a builder failure would therefore degrade without the retry. The exit also prefixes the message ("what: CollectiveBuildError: ...") and costs one extra exchange. That exchange is harmless, since every rank makes it.

Fix: route those raises through _collective_raise(problem, error=CollectiveBuildError, builder_failure=True) so they carry agreed. An alternative is to have the exit pass through any CBE that was raised from a verdict and mark those sites. Passing every unmarked CBE through is not safe, because a CBE can also be raised on one rank alone.

2. Medium: callers of first_verdict read each other's payloads wrongly when they pair. The single primitive makes the counts pair across sites, which every probe confirms. The payloads still differ by caller:

  • _collective_raise sends (message, class, kwargs);
  • Mesh._any_rank_failed sends True;
  • snapshot._agreed_problem sends a string.

When two of these pair, the receiving side misreads the payload (three rows above). In one case the ranks part. In another an unmarked TypeError inside a context triggers a second exchange. The commit message's claim that "every rank raises the class and message of the first failing rank" holds only when both sides are _collective_raise.

None of these pairings can happen in the FAC split today. The risk grows with every converted builder that calls a mesh or snapshot path. Fix: one envelope for every caller, for example (message or None, class or None, kwargs), with each caller deciding what to do with the agreed envelope. Alternatively, have first_verdict also exchange a site tag and raise a clear error when the tags differ.

3. Medium, for adoption: a broad except swallows an agreed error. If an agree(), a wrapper, or a helper containing either sits inside try: ... except Exception: on the healthy ranks, the CBE is swallowed. The failed rank leaves, and the healthy ranks hang at their next agreement (measured). custom_mg.build has three sanctioned swallows around PETSc calls (snes.setUp(), getJacobian() and the dimensional guard). After conversion each would sit next to an agreement point. They must re-raise agreed errors (if getattr(e, "agreed", False): raise), and the static rule should flag an agreement point inside a broad except.

4. Low: the static rule in test_0052 has gaps. These planted snippets got past it:

  • a helper whose first statement is a PETSc collective, called after a risky statement. The rule assumes "the context's entry is agreed" for every function that calls agree(), but a helper's entry is not agreed.
  • a collective inside a called function. Calls are treated only as statements that can raise.
  • PETSc collectives missing from AGREED_PETSC: Mat.mult, DM.distribute, migration, and mesh methods.
  • agree() on one branch of an if.
  • agree() inside a broad except (finding 3).

It also gives false positives: the wrappers allgather and bcast are not in AGREE_CALLS, so a bare collective straight after one is flagged. Loops come out right only by accident: a compound statement counts as risky when any subscript sits anywhere in its body. The 8 tests in test_0052 pass.

What the rule can enforce: direct mpi4py collectives and listed PETSc method names within one function body. What it cannot enforce: collectives inside helpers, PETSc calls by any other name, and rank-uniform control flow. For helpers I suggest:

  • a function that contains an agreement point starts un-agreed;
  • a registry or decorator marks functions as collective, so the rule can require an agreement before calls to them.

5. Low: the runtime check is test-only and sees only mpi4py. _CheckedComm wraps the mpi4py communicator passed to the split. The helper's PETSc collectives (createMPI, Scatter().create, scatter) run on P.getComm() and are not checked. I saw no false positive: the PR's same-answer test passes at np 2, 3 and 4, and with an empty last rank at np 3 and 4. The check is stricter than the rule, since it would flag a bare collective right after another with nothing in between that can raise. That is why n_all had to be wrapped, which is fine.

A library-level version would carry more weight: under a debug flag, have first_verdict exchange a call-site tag and assert that all ranks are at the same site. That catches count drift and the pairings in finding 2 at run time.

Collective inventory of _fac_patch_split_parallel at 5d1298c. Every collective has an agreement point in front:

  • P.getValuesCSR is local.
  • agree(), then in the helper agree() before Vec.createMPI (layout setup is collective). Then agree() before Scatter().create, then scatter.scatter with nothing that can raise in between. The IS and Vec.createSeq calls are on COMM_SELF.
  • agreed_allreduce for n_sub and for n_all, then the exit agreement. _patch_links and gate.update are local.

The four destroy() calls are logically collective in PETSc's documentation but do not block. Only a .copy() precedes them. That is acceptable, but worth a comment.

Side finding: the np 2 refusal with an empty last rank is behaviour development already has. On development, the same ribbon placement with the same partition gives the same refusal on both ranks, outside any context: "addon_partition: 1332 fine cell(s) have no local parent cell on the level below; the add-on levels are not co-partitioned", raised from place_fault_ribbon_2d via partition_addon and _parent_cells_local. The branch gives the identical message. At np 2 an "empty last rank" puts every base cell on rank 0, and the add-on's own partition then gives rank 1 fine cells whose parents it does not hold. It is a genuine partition the placement refuses, and it refuses on every rank. Nothing in first_verdict or the context changed it. Without the empty rank, np 2 solves on both trees. It may deserve its own issue against partition_addon, but not in this PR.

The three refactored callers keep their contract. I forced each to fail on the last rank, at np 2 and 3, on development and on the branch:

  • _collective_raise(error=KeyError) gives KeyError with that rank's message on every rank.
  • _collective_raise(error=CollectiveBuildError, builder_failure=True) gives CBE with builder_failure=True on every rank.
  • Mesh._any_rank_failed returns True on every rank.
  • snapshot._agreed_problem returns the last rank's message on every rank.

Development and the branch gave identical results. I also forced remesh's two verdicts (the global_evaluate transfer and the storage-layout step) to fail on the last rank. On both trees the variable was reset on every rank, the other variable was kept, and the next collective was reached.

The existing tests also pass on both trees at np 2 and 3, 35 passed and 1 skipped (the serial route) each time:

  • test_1155 (in-memory and disk refusals, with the holder first or last);
  • test_0974 (swarm sidecar refusals);
  • test_0874_fault_mg_collective_failures;
  • test_0874_provenance_and_parent_collective;
  • test_0785 (remesh and refinement transfers).

Adoption

Converting custom_mg.build and partition_addon this way is reasonable once findings 1 to 3 are addressed. That means preserving builder_failure and marking every all-rank CBE raise as agreed, one verdict envelope, and making sanctioned swallows re-raise agreed errors. Finding 4 should be done alongside, so that the rule does not overstate what it checks.

The residual risks are the ones the PR already names: an exception inside a PETSc collective, and a collective added without an agreement point. Both grow with the size of the converted body. partition_addon is mostly helpers and mesh construction (redistribute_by_assignment, _peel_balance, _resolve_parents), where the static rule sees nothing, so a debug-mode site check (finding 5) matters most there.

Cost

One build at np 4, the FAC ribbon fixture, two runs each:

5d1298c development
CustomMGHierarchy.build 0.270 / 0.272 s 0.275 / 0.271 s
_fac_patch_split_parallel, mean of 50 calls 38.8 / 38.2 ms 42.3 / 39.2 ms

The difference is within noise. The split makes 6 flag allreduces when healthy. The round-1 head made 5 allgathers and timed the same (build 0.269 / 0.267 s against 0.273 / 0.267 s). I did not measure the "about 70 per build" figure for a fully converted build.

What was run

  • Build: a fresh development build at 0189b21, with the merge base aa3c49d's Python overlaid for the baseline and the PR's Python for each head. The merge base differs from that build in one compiled file, function/_function.pyx (A re-declared mesh variable refuses to change; helper variables named after their owner; uw.unwrap expands completely (#1118, #824) #1209's function identity). No path tested here touches it. All tests came from worktrees at the heads.
  • Toy pairing probes: 32 cases on 5d1298c (27 at np 2, 3 and 4; five hang cases at np 3). 21 cases at np 2, 3 and 4 on f1c8d40. SystemExit and the two concurrent half-communicator builds were run on f1c8d40 only.
  • The PR's test_0874_agreed_build at np 2, 3 and 4 on both heads:
    • f1c8d40: 4 passed at every np.
    • 5d1298c: 5 passed at np 3 and 4, and 4 passed plus 1 skip (the empty rank) at np 2.
    • 5d1298c with an empty last rank: 5 passed at np 3 and 4.
  • The same forced failures on development, at np 2, 3 and 4: "before the helper" and "inside the helper" abort with MPICH "Message truncated", because a test allgather mis-pairs with a PETSc allreduce. "After the gate" hangs. My two extra points also hang on development at np 2, 3 and 4.
  • Reviewer tests:
    • forced failures between the fetch and the gate, and just before the exit on both paths, with per-rank counts;
    • the same at np 2, 3 and 4, and with an empty last rank at np 3 and 4;
    • at np 2 with an empty rank, the fixture refuses before the split, as in the side finding.
  • Static rule: test_0052 run serially (8 passed), plus 10 planted snippets.
  • Callers: the caller probes, the existing caller tests, and a remesh forced-failure test, at np 2 and 3 on both trees.
  • Timing: at np 4.

Not run

  • np 5 and above, which exceeds the core budget for this review.
  • An exception raised inside a PETSc collective.
  • Converted build or partition_addon, which do not exist yet.
  • Open MPI.

Logs kept by the reviewer.

Underworld development team with AI support from Claude Code

…re-raise (#874)

H1's round 2 on #1218.

1. A failure inside an agreed_build is a builder failure by default
   (builder_failure=True through every agreement point), so the mesh-owned
   build takes the RBF retry rather than degrading. Tested: a failure forced
   once in the FAC split during a solve retries with RBF on every rank.
2. One envelope, mpi.Verdict(message, error, kwargs, site), at every caller
   of first_verdict (_collective_raise, Mesh._any_rank_failed,
   snapshot._agreed_problem). When the flag is set every rank sends its
   envelope; two different sites that pair raise one mismatch error on every
   rank. The envelope pickles through its four fields.
3. reraise_agreed(err): build's three sanctioned swallows (snes.setUp(),
   the operator check, the dimensional guard) re-raise an agreed error.
   Tested through the setUp swallow with a stand-in solver.
Lows: test_0052's static rule checks direct mpi4py collectives only, a
helper's entry is not agreed, the wrappers count as agreement points; its
docstring says the run-time check covers the rest.

Underworld development team with AI support from Claude Code
@lmoresi

lmoresi commented Nov 16, 2026

Copy link
Copy Markdown
Member Author

Review from the Underworld development team with AI support from Claude Code (H1: review and parallel test runs on a 96-thread Linux workstation (Intel Xeon Gold 6240R, AVX-512; MPICH))
(H1 is the session that reviews pull requests and runs the parallel tests.)

Verdict at 19b436c: sound with changes. One small change is needed before custom_mg.build is converted. The three medium findings from my previous review are fixed, and I measured each fix. The lows are either fixed or now documented honestly.

One new problem comes from the finding-1 fix itself. The context exit now labels every error builder_failure=True, including an all-rank agreed check that said False (item N1). It needs a one-line fix before any build containing such checks is converted. It does not affect the FAC split, the only code converted so far. The rest below is low.

Item by item

item asked result at 19b436c
Toy probes rerun all at np 2, 3 and 4 40 cases × 3 rank counts. Every ordering that should pair, pairs with equal per-rank counts: success, single failures at each point, two ranks failing at different points or in the same segment, nesting, a raise inside agree(), wrapper/agree() interleaved at all 7 gaps. The expected hangs are unchanged (bare collective after a raise, rank-conditional context, sub-communicator build, KeyboardInterrupt or SystemExit on one rank).
Finding 1: builder_failure an all-rank CBE with builder_failure=True keeps it; a real solve with one forced FAC failure retries with RBF on every rank Kept on every rank at np 2, 3 and 4. In a real solve on the mesh-owned path, every rank builds barycentric and then RBF. Every rank warns "retrying with the 'rbf' builder", and every rank records custom_mg.transfer_builder as rbf (local kd-tree RBF), build_failed, with the forced message. The solve after the retry succeeds and matches the clean run: Σv² and Σp² agree to 1e-10 relative at np 2 and 3, and 1.3e-8 / 1e-9 at np 4 (tolerance 1e-6). With explicit set_custom_fmg, every rank raises the same agreed CBE (builder_failure=True) with the forced message. See N4 on the PR's own test.
Finding 2: one envelope each cross-site pairing gives one clear mismatch error on every rank; pickling with a custom class and kwargs All three pairings (build exit vs snapshot, _any_rank_failed vs _collective_raise, build exit vs _any_rank_failed) give RuntimeError "verdict exchange mismatch: ranks paired at different kinds of agreement point [...]" on every rank at np 2, 3 and 4. No rank goes on alone and no payload is misread. A snapshot refusal against agree() inside a context gives the same mismatch, wrapped as a CBE on every rank. A module-level custom exception class with kwargs (code=7, where=("last", r)) arrives on every rank with its class, its kwargs and agreed=True. See N2 and N3.
Finding 3: swallows except Exception around agree(); the three sanctioned swallows re-raise agreed errors and still swallow unagreed ones A bare swallow around agree() still hangs, as it should. reraise_agreed in the handler pairs it at np 2, 3 and 4. An unagreed error raised on every rank is still swallowed there, and the run continues and pairs. I tested all three build sites with stand-in solvers, serially and at np 2 and 3 (6 of 6 pass): the snes.setUp() swallow in build, _assert_finest_matches_operator, and the dimensional guard in auto_inject_custom_mg. An agreed CBE propagates with nothing recorded. An unagreed error is swallowed and its fallback recorded (presolve_setup, finest_operator_check, dimensional_guard; the last still installs the hierarchy).
Callers three-caller probes and their tests at np 2 and 3 _collective_raise(error=KeyError) gives KeyError with the last rank's message on every rank. _collective_raise(error=CBE, builder_failure=True) keeps the flag. _any_rank_failed gives True on every rank. _agreed_problem gives the last rank's message. These are identical to development. The tests (test_1155, test_0974, the test_0874 fault_mg and provenance files, test_0785, and my remesh forced-failure test) give 35 passed and 1 skipped (the serial route) at np 2 and at np 3. Remesh's two verdicts, forced to fail on one rank, reset the variable on every rank.
Static rule rerun the 10 planted snippets test_0052: 8 passed. Now flagged: a helper whose first mpi4py collective precedes its agree() (its entry is not agreed); a bare bcast after a risky statement; a loop with a collective at the top. Now not flagged, by design and documented: PETSc collectives, collectives in called helpers, agree() on one branch, agree() in a broad except, and a caller's risky statement before calling a collective helper. The wrappers count only under the agreed_* import names. A wrapper imported as plain allgather still makes the next bare collective a false positive.
PR test np 2, 3 and 4 9 passed at np 3 and 4. At np 2, 8 passed and 1 skipped (the empty rank; the refusal also happens on development, as established in my previous review). My forced-failure tests (5 points plus a healthy split) show equal per-rank counts at np 2, 3 and 4: 3/4/5/7/7, and 12 for two healthy splits.
Cost np 4 build 0.281 / 0.274 / 0.272 / 0.275 s against 0.278 / 0.273 / 0.276 / 0.271 s on development. Split 44.0 / 39.0 / 40.1 / 39.7 ms against 38.6 / 38.4 / 42.7 / 38.6 ms. That is noise; 6 flag allreduces per healthy split.

New findings

N1. Medium for adoption, none for the current scope: the exit forces builder_failure=True onto agreed checks. An all-rank CollectiveBuildError(builder_failure=False) raised without agreed, inside a context, leaves as builder_failure=True on every rank (measured at np 2, 3 and 4). Examples are build's "allreduced: every rank raises" checks (component counts, operator size).

Once build is converted, such a check would trigger a full RBF rebuild. The rebuild fails the same way, then degrades and records build_failed. The comment in the retry loop says this must not happen. Fix: in __exit__, carry the error's own flag, builder_failure=getattr(err, "builder_failure", self.builder_failure), or mark those raises as agreed.

N2. Low: the mismatch error could say more. It drops the first failing rank's message. It is not marked agreed, so inside a context it is wrapped again, which costs one more exchange that pairs. Its text ends with "(rank N was at ...)", so the message differs by rank. Sites are named per function, so two different _collective_raise call sites still pair silently, as designed, with the class taken from the first failing rank.

Suggestions: include the failing message, and keep the rank-specific part out of str(err) so callers can compare messages.

N3. Low: the error classes in a verdict must be importable. A class defined inside a function fails to pickle. In my probe every rank passed the same class, so every rank failed alike with AttributeError. In a cross-site pairing only the failing rank would fail to pickle, and the job would likely hang. I did not test that case. Worth one line in the first_verdict docstring.

N4. Low: the PR's RBF-retry test cannot show that the retried hierarchy works. The fixture's exact solution is its boundary data (linear shear, no body force), so the SNES reports converged at 0 iterations. The assertion reason > 0 or _rotated_freeslip_info is None would pass regardless. With a body force added, the retried solve matches the clean one, as the table shows. Suggestion: a body force in the fixture, plus a comparison against the clean solution.

Note: development has moved to c9c300e. It changes discretisation_mesh.py, which this PR also touches, so a rebase may be needed. The merge base (aa3c49d) is unchanged and was the baseline here. Its compiled sources match the build I used except for function/_function.pyx (#1209), which no tested path touches.

What was run

  • Build: the development build at 0189b21, with the merge base's Python overlaid for development and 19b436c's for the PR.
  • Toy pairing probes: 40 cases at np 2, 3 and 4, with per-rank counts of flag allreduces and message allgathers.
  • Real solves: one forced FAC failure (clean, mesh-owned fail, explicit fail) at np 2, 3 and 4, plus a body-force variant at np 2, 3 and 4.
  • Swallow tests: stand-in solver tests, serially and at np 2 and 3.
  • Caller checks: the caller probes and the 35-test caller slice at np 2 and 3.
  • Tests: the PR test and my forced-failure tests at np 2, 3 and 4; test_0052 plus 12 planted snippets.
  • Timing: four timing pairs at np 4.

Not run:

  • np 5 or more, which is over the core budget.
  • A cross-site pairing with an unpicklable class.
  • An exception inside a PETSc collective.
  • The converted build and partition_addon, which do not exist yet.
  • Open MPI.

Logs kept by the reviewer.

Underworld development team with AI support from Claude Code

…ext; body-force retry test (#874)

H1's round 3 on #1218.
- N1: the context exit keeps the builder_failure of a CollectiveBuildError
  raised on every rank by a check (getattr(err, "builder_failure", ...)), so
  a check another builder cannot change does not trigger a futile RBF
  rebuild. Tested inside a context at np 2 to 5.
- N2/N3: the mismatch error carries the first failing rank's message, with
  the same text on every rank; verdict error classes must be importable at
  module level (documented in mpi.first_verdict and agreed_build).
- N4: the RBF-retry test has a body force and checks the retried solve
  iterates (the rotated path's velocity count).
- Development merged in (c9c300e and after).

Underworld development team with AI support from Claude Code
@lmoresi

lmoresi commented Nov 16, 2026

Copy link
Copy Markdown
Member Author

Review from the Underworld development team with AI support from Claude Code (H1: review and parallel test runs on a 96-thread Linux workstation (Intel Xeon Gold 6240R, AVX-512; MPICH))
(H1 is the session that reviews pull requests and runs the parallel tests.)

Verdict at 33a508d: sound with changes. The only change needed is in the PR's RBF-retry test. The mechanism itself is now sound to adopt: N1 and N2 are fixed, and N3 is documented.

The RBF-retry test still passes when the RBF builder is broken (details below). Two more assertions would close that.

item result at 33a508d
N1: builder_failure kept through the exit An all-rank CollectiveBuildError(builder_failure=False) leaves the context as False on every rank, and True stays True, at np 2, 3 and 4. A real solve with one forced FAC failure on the last rank retries on every rank at np 2, 3 and 4: barycentric then RBF on every rank, with the RBF hierarchy installed. The retried solve iterates: 3 velocity iterations on the rotated path, the same as the clean run. It matches the clean run: Σv² agrees to 2e-9, 5e-9 and 8e-9 relative and Σp² to 2e-10, 3e-10 and 8e-10 at np 2, 3 and 4 (tolerance 1e-6).
N2: mismatch text All four cross-site pairings give one identical text on every rank at np 2, 3 and 4. It names both sites and carries the first failing rank's message, for example "The first failure (rank 2, at 'fault_contact._collective_raise'): toy: IndexError: forced at S0 on rank 2".
N3: importable class Documented in first_verdict and the module docstring. A local class still fails alike on every rank when every rank passes it. A module-level custom class with kwargs arrives intact.
N4: the retry test The test does not catch a broken retry. Breaking the retry three ways at np 2 and 3:
Retry disabled (the context forced to builder_failure=False): caught. "DID NOT WARN" for the retry warning.
RBF builder raises: not caught. The test passes because the build degrades to the default preconditioner: a custom_mg.build: default preconditioner, build_failed record, GAMG on the velocity block, and 88 velocity iterations against 3. The retry warning, the transfer_builder record, convergence, and vel_its > 0 all still hold.
RBF replaced by barycentric: not caught. This one is arguably acceptable, since a retry did happen.
Suggested fix: assert "custom_mg.build" not in stokes.pc_fallbacks and assert stokes._custom_mg["hierarchy"].builder is custom_mg.rbf_prolongation. Optionally, bound the velocity iterations near the clean run's.
Toy probes, np 2 and 3 34 cases. Every pairing case pairs with equal per-rank counts: single failures, two ranks failing at different points or in the same segment, nesting, wrapper/agree() interleaving, and raises inside agree(). reraise_agreed pairs a swallow, and an unagreed error is still swallowed. The expected hangs are unchanged: a bare collective after a raise, a bare swallow, a rank-conditional context, a sub-communicator build, KeyboardInterrupt.
Callers, np 2 KeyError, CBE with builder_failure=True, any_failed=True and the snapshot message each reach every rank as on development. The caller slice gives 53 passed and 1 skipped on the branch, and the same on development (the merged development added tests to these files).
PR test 10 passed at np 3 and 4. At np 2, 9 passed and 1 skipped (the empty rank).
Build The development merge moved the merge base to 35ac139. Its compiled sources do not match the earlier build (_function.pyx differs) or the a7ff735 build (_function.pyx differs again). I used a build at aa3c49d, whose compiled sources are identical to 35ac139's, with the merge base's or the head's Python overlaid. Cores 0 to 3 were idle, so I ran np 4.

Not run: np 5 and above, and Open MPI.

Logs kept by the reviewer.

Underworld development team with AI support from Claude Code

…874)

H1's round 4 on #1218: the retry test passed with the RBF builder broken,
since the build then degraded to GAMG and still converged. It now also
asserts that no custom_mg.build fallback is recorded and that the installed
hierarchy's builder is rbf_prolongation. With the RBF builder made to raise,
it fails (np 2).

Underworld development team with AI support from Claude Code
@lmoresi
lmoresi marked this pull request as ready for review November 16, 2026 16:07
Copilot AI balanced review requested due to automatic review settings November 16, 2026 16:07
@lmoresi
lmoresi merged commit 929459a into development Nov 16, 2026
10 checks passed

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

Copy link
Copy Markdown
Member Author

Review from the Underworld development team with AI support from Claude Code (H1: review and parallel test runs on a 96-thread Linux workstation (Intel Xeon Gold 6240R, AVX-512; MPICH))
(H1 is the session that reviews pull requests and runs the parallel tests.)

Verdict at 2b2bb8e: sound to adopt as is.

  • Test-only change. The diff since 33a508d adds 7 lines to tests/parallel/test_0874_agreed_build_parallel.py; src/ is identical.
  • The RBF-retry test passes unmodified at np 2, 3 and 4.
  • All three deliberate breakages now fail the test at np 2, 3 and 4:
    • Retry disabled: fails with "DID NOT WARN".
    • RBF builder raises: fails on the new "custom_mg.build" not in pc_fallbacks assertion.
    • RBF replaced by barycentric: also fails, on the new builder is rbf_prolongation check.

Run on cores 0 to 3, with the same build and overlay as the previous re-check, since the source is unchanged.

Logs kept by the reviewer.

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.

3 participants