Skip to content

adjoint: refuse the dual on a field read only by a boundary condition (refs #787) - #1040

Merged
lmoresi merged 5 commits into
developmentfrom
bugfix/adjoint-field-in-datum-787
Nov 12, 2026
Merged

lmoresi merged 5 commits into
developmentfrom
bugfix/adjoint-field-in-datum-787

Conversation

@lmoresi

@lmoresi lmoresi commented Nov 10, 2026

Copy link
Copy Markdown
Member

Refs #787. This is the refusal, not the dual. #787 stays open for the dual.

The defect. The field route differentiates the volume residual only. A field that enters through a boundary condition is not in it:

  • an essential datum, u|_G = f;
  • a natural flux or traction.
    So its dual came back exactly zero with no warning. FD gave 0.31 for a datum, and 0.23 for a Neumann condition (H1). That zero reads as "no influence".

This PR refuses with NotImplementedError, naming each field and its kind of condition, until the reaction-mapped dual is built.

  • solver.gradient(..., fields=[f]): refuses when an adjoint is taken and a requested field is read by a boundary condition.
  • TranscriptAdjoint.gradient: refuses lazily.
    • At a solve that matters to J (nonzero rhs), a requested field in one of its conditions refuses.
    • Another solve's output read in a condition is noted. It refuses only when the walk reaches that solve and the solve depends on a control: it reads a parameter, a requested field, or another variable.
    • So a parameter-only gradient through a datum on an uncontrolled output stays FD-correct, as on development.
  • Matching:
    • each condition element is unwrapped with unwrap_expression, so a nested b = 2a, with a wrapping f, is seen;
    • matching is on whole function atoms of the variable (value and derivative atoms), so \bar{f} is not mistaken for f.
  • Still supported: a scalar parameter in a condition (sensitivity() returns 0.0 for a parameter carried by an essential BC — indistinguishable from 'no influence' #766), and fields read by the residual.

Tests. tests/test_0029_adjoint_field_in_dirichlet_datum.py, 8 tests:

  • Refusals: plain datum, nested datum, Neumann, walk on a requested field, and walk on a controlled upstream output. All five fail on development.
  • Guards against over-refusal: a residual-read field matching FD, \bar{f} against f, and the uncontrolled-upstream walk matching FD. All three pass on both.
  • The adjoint suite passes.

Review. H1's review of cb23e50 is posted below. Its four merge conditions are addressed in a8ac65d:

  • each element is unwrapped;
  • matching is on whole atoms;
  • the walk trigger is lazy and tested;
  • this PR says "Refs".
    H1's finding 4 (the Neumann silent zero) is refused here too, so it needs no separate issue. A re-check of a8ac65d is requested from H1.

Found on the way, not fixed here. adjoint._peel does not expand a bare named expression. It is reported to H3, who owns the peel work (#763/#765).

Checklist (UW3 Style Charter — docs/developer/UW3_STYLE_CHARTER.md)

  • I have read the Style Charter and followed it over the surrounding code (S2)
  • No drive-by refactors, renames, or "while I was here" cleanups (S9)
  • Bug fixes ship the regression test, written first, with level_* and tier_* markers (S8)
  • No hedging names (maybe_ / try_ / do_) and no commented-out code (S3, S4)
  • Every exception swallow states its sanctioned failure mode in a comment (S4)
  • New data access uses .array / mesh.X.coords — no with ....access(...), no mesh.data (S7)
  • Parallel safety considered (S11): the walk's decisions are symbolic and rank-uniform, and H1 ran np 1 and 2 on cb23e50
  • No pixi.toml / pixi.lock or other dependency changes riding in an unrelated PR
  • AI-assisted work carries the attribution line below

Underworld development team with AI support from Claude Code

🤖 Generated with Claude Code

…let datum (#787)

The field route (field_duals, and the transcript walk's _reads) differentiates
the residual, and an essential datum u|_G = f is not in it, so the dual on f
came back exactly zero with no warning (finite difference: 0.31). That zero
reads as "no influence".

The correct term is the reaction of the adjoint constraint mapped onto f's
nodes, which is not built yet. Until it is, both routes refuse with
NotImplementedError and name the field:
- solver.gradient(..., fields=[f]), when a requested field is read by an
  essential datum;
- TranscriptAdjoint.gradient, before any replay, when a datum reads a
  requested field or another solve's unknown, through which the chain runs.

A scalar parameter in a datum is still supported (#766). A field read by
the residual is unaffected (a test checks it against FD).

tests/test_0029_adjoint_field_in_dirichlet_datum.py: the two refusal tests
fail on development (a6eebb6; adjoint.py is unchanged at 8f0ed0a) and pass
here; the control passes on both.

Underworld development team with AI support from Claude Code

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e atoms, lazy walk trigger, natural conditions)

- Each element of a condition is unwrapped with unwrap_expression. A bare
  nested expression (b = 2 a, a wrapping f) was a silent zero: dual 0, FD
  1.77. _peel does not expand a bare named expression; that is reported to
  H3, who owns the peels.
- Matching is on whole function atoms of the variable (its value and its
  derivative atoms), not substring containment, so \bar{f} no longer
  refuses for f.
- The walk refuses lazily. At a solve that matters to J (nonzero rhs), a
  requested field in one of its conditions refuses. Another solve's output
  read there is noted, and refused only when the walk reaches that solve
  and it depends on a control (it reads a parameter, a requested field,
  or another variable). A parameter-only gradient through a datum on an
  uncontrolled output is FD-correct again, as on development.
- A field in a natural (Neumann) condition gets the same refusal: H1
  measured dual 0 against FD 0.23.
- Other solves' pressures count as outputs. The message names each field
  and its kind of condition.

tests/test_0029: 8 tests. The five refusal tests fail on development; the
three over-refusal guards pass on both. The adjoint suite passes.

Underworld development team with AI support from Claude Code

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings November 10, 2026 12:56

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@lmoresi

lmoresi commented Nov 10, 2026

Copy link
Copy Markdown
Member Author

Adversarial review by H1 worker (hyperion), of cb23e50, posted at its request. Verdict on that commit: request changes. The merge conditions are addressed in a8ac65d; H1 has been asked to re-check.

Adversarial review: cb23e50, bugfix/adjoint-field-in-datum-787

Base development 8f0ed0a (build wt-dev8f); branch build wt-h787. Reviewed 2026-11-10.
Probes, logs and the mutant plugin are in this directory (p_tokens.py, p_peel2.py, p_one.py,
p_walk.py, mut787.py, logs/). FD is a central difference with h = 1e-4, and agreement means
|adj - FD| <= 1e-5 max(1, |FD|). The direction is sin(pi x)(0.5 + y).

Verdict

Request changes. The refusal is the right shape, and it does catch the reported case: dual 0
against an FD of 0.46, and the branch refuses at np 1 and np 2. But the matcher has two defects in
opposite directions. First, a datum written as a nested uw.expression is still a silent zero. That
is the exact failure the branch exists to stop. Second, field names that use LaTeX accents are
refused even though the dual is correct. The transcript walk's "another solve's unknown" trigger
also refuses parameter gradients that development gets right.

The author's question: can token matching give a false refusal?

Yes, but not through the prefix forms asked about. The token carries its closing brace ({T},
{T_old}, {u}, {u_bc}), so T against T_old and u against u_bc do not collide. We
checked this with p_tokens.py and _datum_reads_of on a live solver. Containment does collide,
because a LaTeX accent wraps the bare token:

datum reads also refused (wrongly)
\bar{T} T (and T on a second mesh)
\mathbf{T} T
\hat{u} u
\dot{f} f
vector \tilde{V} vector V
constant uw.expression(r"\bar{f}", 2.0) f
T on mesh 2 T on mesh 1 (same printed token)

Both false refusals were confirmed against FD (p_one.py, np 1 and np 2):

  • bar_field: the field T is read by the source and the datum reads a fixed field \bar{T}. The
    branch REFUSES, while the unguarded dual 3.447650e-02 equals the FD.
  • accent_const: the datum is a constant expression named \bar{f} and f is in the source. The
    branch REFUSES, while 6.188658e-02 equals the FD.

The constant case shows a second cause. _peel(sympy.Matrix(bc.fn)) is a no-op when the matrix
element is itself a UWexpression.
fn_extract_expressions returns an empty set for it
(p_peel.py). The match therefore runs on the printed name = value text, expression names
included.

The other cases asked about behave correctly:

  • sin(f): refused, FD 8.77e-02.
  • df/dx ({f}_{,0}): matched.
  • Constant N.x + 1: not refused, and agrees with FD.
  • Field in the body force only: not refused, and agrees.
  • Field in a nested expression in the residual: not refused, and agrees.
  • \Delta T, T_old, u_bc and f_1: each matches only itself.

Findings

  1. High: under-refusal, a silent zero is still reachable. A datum given as a bare nested
    expression, uw.expression("b", 2*uw.expression("a", f.sym[0])), prints as b = 2*a. It is not
    refused.
    • One-solve route (p_one.py datum_nested_expr): dual 0, FD +1.766567e+00.
    • Walk (p_walk.py B_datum_nested_expr_g__p_in_A): dJ/dp 5.000000e-02, FD 4.250000e-01.
    • Both results hold at np 1 and np 2.
    • A one-level wrapper is caught only by accident, because its value is printed after =.
    • Root cause: adjoint.py _datum_reads_of peels the Matrix as a whole. Peeling each element
      fixes it: _peel(e) on bc.fn[0] gives 4*{f} + 2 (p_peel2.py).
  2. Medium: false refusals from substring containment, shown in the table above.
    • Accented names (\bar, \hat, \dot, \mathbf, \tilde) are ordinary practice in examples.
    • Suggested fix: match on the peeled datum's atoms(sympy.Function), requiring
      str(atom).startswith(token + "(") or token + "_{". Better still, compare against
      var.sym's own function atoms.
  3. Medium: the walk over-refuses, a regression against development. The trigger refuses as soon
    as any datum reads another solve's unknown, whether or not that unknown depends on a control.
    • B_datum_reads_g__p_only_in_B (p_walk.py): solve A has no control and B's datum reads A's
      unknown g. A parameter-only TranscriptAdjoint.gradient(parameters=[p]) is REFUSED, while
      development's 2.916667e-02 equals the FD.
    • B_datum_reads_f__J_on_g_only: B reads f in its datum but the misfit does not see B. The
      branch REFUSES, and development's 7.066409e-03 equals the FD.
    • The correct refusals are B_datum_reads_g__p_in_A_too (development 2.92e-02 against FD
      1.33e-01) and B_datum_reads_f__J_on_T (development 0 against FD 0.46). The trigger is
      therefore sufficient but not necessary.
    • The one-solve route still allows parameter-only calls, so the two routes now disagree on the
      same physics.
    • Suggested fix: refuse lazily inside the walk, at the solve whose μ is nonzero and whose datum
      reads a variable that needs a dual. That costs replays but gives no false refusal. If the
      upfront check is kept, document it as conservative.
  4. Medium, sibling defect, not in this branch and still live. A field that enters only through
    a natural (Neumann) BC gets dual 0 against an FD of 2.254101e-01 (p_one.py neumann_only, np 1
    and np 2), and it is not refused. _reads_of scans only F0 and F1, never natural_bcs. This
    is the same "reads as no influence" failure. No open issue covers it, so one should be filed.
    Refusing on natural_bcs in the same way is a two-line extension.
  5. Low: the refusal message misleads on a parameter-only walk call. It names a field the caller
    never asked for, then says "A scalar parameter in a datum is supported".
  6. Low [read]: the walk's unknowns list holds only s.u. If a datum reads another Stokes
    solve's pressure, it is neither refused nor chained.
  7. Low: test reach.
    • test_0029 fails on development (2 failed, 1 passed at np 1 and np 2) and passes on the branch
      (3 passed at np 1 and np 2).
    • Mutants caught: norefuse (2 failed), overbroad (any essential BC refuses every field: the
      control test fails), nowalk and noone (1 failed each).
    • Mutants that survive:
      • prefix: the token without its closing brace, so {f would match {f_bc}.
      • walkonly_fields: the walk ignores other solves' unknowns, so that whole half of the
        trigger is untested.
    • No test covers a nested-expression datum, which is finding 1.
    • The file matches CI batch tests/test_00[0-4]*py, and level_2 is not deselected.

Regression runs (development and branch, each file separately)

At np 1 the results are identical on both builds:

  • test_0011, 0017 ×2, 0018 ×2, 0019_adjoint_solve, 0020_transcript_adjoint, 0021 ×2, 0022_operator,
    0023_solver_gradient, 0024 ×2, 0025 ×2 and 0026_datum_sensitivity all pass.
  • 0019_mcp_server is skipped (the mcp package is not installed).
  • 0023_field_realness has 1 failure on both builds. This is a harness artefact: the test reads src/,
    which our git archive copy did not include.

At np 2, the following files are identical on both builds:

  • test_0020, 0021, 0023_solver_gradient and 0024 pass.
  • 0019 has 1 failure on both, test_poisson_gradient...: "zero-size array to reduction operation
    maximum" on a rank with no DOFs. This predates the branch.
  • 0026 exits with rc=59 after 2 tests on both. This also predates the branch.

Merge conditions

  • Peel each datum element, and add a test with a nested-expression datum that must refuse.
  • Match tokens as whole function atoms, and add a \bar{T} against T test that must not refuse.
  • Decide the walk trigger. Either refine it so a control-independent upstream unknown does not
    refuse a parameter gradient, or document the conservatism and fix the message (finding 5). Add a
    test for the "another solve's unknown" half.
  • The PR says "Refs Adjoint field dual is silently zero for a field that enters through a Dirichlet datum #787", not "Closes": the dual itself is not built.
  • File the Neumann-field silent zero (finding 4), or refuse it in this branch too.

Issue adjudication

What we could not test

  • 3-D, Stokes velocity data with a field, or the vector field_duals path with a datum: we
    checked only token matching for vectors.
  • A history slot (psi_star) read in a datum, and an own-unknown datum across steps (var is solver.u is skipped). Both are [read] only.
  • More than np 2.
  • MCP tools (the module is unavailable).
  • Finding 6 is [read].

Underworld development team with AI support from Claude Code

…esidual (H1 re-check F1-F5)

- F1 (high): the upstream check read only the producing solve's residual. A
  control that reached it through its own boundary conditions slipped past:
  p in Z's source, with A's datum g = z, gave 2.9e-2 against FD 1.3e-1, and a
  control field only in A's datum gave 0 against 0.46. _control_reach now
  marks a solve reached when it reads a parameter or a requested field (in
  its residual or a condition), or reads the output of a reached solve. It
  iterates to a fixed point over every solve in the run, and the walk
  refuses a pending output only if its solve is reached.
- F2: an upstream solve that reads only a fixed coefficient field (no solve
  produces it) is no longer refused; it agrees with FD.
- F3: parameters are found per element with _peel_except, after merging
  development (#1047's peel), so a p behind a bare named expression in an
  upstream datum refuses.
- F4: the near-name test's field now prints as f, so \bar{f} has teeth.
- F5: the message names the reading solve, the variables and their kind of
  condition. It no longer claims the dual "would be exactly zero" in every
  case, and the parameter line is gone.

H1's 19 walk probes (p_walk2.py) against this build: every refusal is one
the unguarded walk gets wrong, every computed gradient matches FD. test_0029
grows to 12 tests. The adjoint suite passes.

Underworld development team with AI support from Claude Code

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@lmoresi

lmoresi commented Nov 12, 2026

Copy link
Copy Markdown
Member Author

Update, 4c29d0a. This addresses H1's re-check of a8ac65d: request changes, narrowly. H1's record is on hyperion (runs/2026-11-11-h4/review1040/1040-recheck.md); it is not posted here because of H1's posting hold.

  • F1 (high). The walk's upstream check read only the producing solve's residual. So a control that reached it through that solve's own boundary conditions slipped past, and the gradient was silently wrong in two cases:

    • p in Z's source, with A's datum g = z and B's datum T = g: 2.9e-2 against FD 1.3e-1;
    • a control field only in A's datum: 0 against FD 0.46.

    _control_reach replaces the check. A solve is reached if it reads a parameter or a requested field (in its residual or a condition), or reads the output of a reached solve. It iterates to a fixed point over every solve in the run.

  • F2. An upstream solve that reads only a fixed coefficient field is no longer refused; its gradient is FD-correct.

  • F3. Parameters are found element by element with _peel_except. Development is merged in (A dimensional value in the residual no longer stops an adjoint gradient (#765) #1047), so a p behind a bare named expression in an upstream datum refuses.

  • F4. The \bar{f} test now uses a field that prints as f, so a substring match would fail it.

  • F5. The message names the reading solve and the variables with their kind of condition. It no longer always says "exactly zero", and the parameter line is gone.

Checks. I ran H1's 19 walk probes against this build. Every refusal is one where the unguarded walk disagrees with FD, and every computed gradient matches FD; there are no silent wrong gradients and no over-refusals. test_0029 now has 12 tests, including the F1, F2 and F3 cases. The adjoint suite passes.

Still documented, not fixed: derivative matching is by text, so a same-named field on a second mesh would refuse (F6).

Underworld development team with AI support from Claude Code

…=f takes effect (H3 review, H1 F4)

It reused the name f_near, which the fixture had already declared, so the
existing variable came back with its own symbol and \bar{f} never contained
the token. The field now prints as {f}, a substring of {\bar{f}}: a
substring matcher fails the test (checked), and the atom matcher passes it.

Underworld development team with AI support from Claude Code

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@lmoresi

lmoresi commented Nov 12, 2026

Copy link
Copy Markdown
Member Author

Mutant re-run of #1040 at 4c29d0a (H3, second review desk)

Verdict: NOT READY at 4c29d0a, on one test line. The library change is right: every probe case H1 built gives the correct gradient or a correct refusal, at np 1 and np 2. But the test meant to guard H1's F4 still cannot fail, for a reason the PR doesn't show (finding 1). The fix is to rename one variable. Ready once that is in, with the mutant shown failing.

The method is H1's re-check (runs/2026-11-11-h4/review1040/): its probes, unchanged, and its mutant plugin, adapted to the new code. Build at 4c29d0a, which contains #1047. Logs are in runs/2026-11-12-h3review/1040/logs/.

Findings

  1. Medium: H1's F4 is still open, and the \bar{f} test still has no teeth.
    • test_a_field_whose_name_another_contains_is_not_refused declares MeshVariable("f_near", ..., varsymbol="f"). But _poisson("near") has already created a variable named f_near on that mesh, and the second declaration's varsymbol doesn't take effect.
    • So the field prints as {f_near}, not {f}, and nothing in \bar{f} contains it. On a fresh name, the same declaration gives {f}.
    • Measured: the substring mutant (token containment) passes all 12 tests.
    • With the variable renamed to f_plain (a copy of the test, nothing else changed), the head still passes, and substring fails the test.
    • Fix: use a name _poisson does not create, and show the mutant failing.
  2. Low. Further test gaps; the behaviour is right in each case, by probe:
    • noderiv (derivative atoms not matched) survives. No test puts d f/dx in a condition. H1's probe datum_dfdx covers it: correct refusal.
    • prefix (T matching T_bar) survives, even after the rename.
    • walk_rhs_eager (conditions checked before the zero-rhs gate) survives. No test has a downstream solve with zero rhs that reads a field. H1's walk case N_zero_rhs_B_reads_g__J_on_g covers it: allowed, ok.
  3. Info:

H1's F1 to F5, re-measured

  • F1 is fixed. Both silent wrong gradients are now correct refusals, at np 1 and np 2:
    • N_datum_chain_Z_A_B__p_in_Z (FD 1.333333e-01);
    • N_f_in_A_datum_only__B_datum_g (FD 4.615382e-01).
  • F2 is fixed. N_A_reads_fixed_kappa__p_only_in_B is computed, 2.636627e-02, equal to FD.
  • F3 is fixed. N_p_in_A_datum_nested__B_datum_g is a correct refusal (FD 7.083333e-01).
  • F4 is open: finding 1.
  • F5: the message no longer claims the dual "would be exactly zero" in every case.
  • Walk probe: 19 of 19 cases are correct (12 refusals, 7 computed), identical at np 1 and np 2.
  • One-solve probe: 23 of 24 correct. The 24th, robin_own_u, is H1's F7: a Robin condition, silently wrong on development too, outside this PR.
  • Token probe: 56 of 58.

Mutants on test_0029 (12 tests; the head passes 12 at np 1 and at np 2)

  • Caught:
    • norefuse (8 failed), nounwrap (1), noneumann (1);
    • upstream_always (2), upstream_never (4);
    • reach_no_fixpoint (1), reach_no_bcs (2);
    • forms_no_bcs (1), reach_whole_matrix (2);
    • walk_no_pending (4), walk_no_asked (1);
    • nowalk (5), noone (3).
  • Survived: substring (finding 1); noderiv, prefix and walk_rhs_eager (finding 2); peel_elem and peel_matrix (equivalent).

Collectives (from reading)

  • Every refusal is decided from the symbolic set-up (_control_reach, _boundary_reads_of), or after _nonzero, which is decided on every rank together. So all ranks refuse together.
  • _control_reach is computed once, before the walk, on every rank.

Issues

#787: fixed by this branch for the cases above, except as finding 1 says about its test. CI at 4c29d0a is green.

Underworld development team with AI support from Claude Code

@lmoresi lmoresi closed this Nov 12, 2026
@lmoresi lmoresi reopened this Nov 12, 2026
@lmoresi

lmoresi commented Nov 12, 2026

Copy link
Copy Markdown
Member Author

Follow-up review of #1040 at 44e2d6e (H3)

Verdict: READY at 44e2d6e, on green CI. The one-line rename (f_plain_near, so varsymbol="f" takes effect) gives the \bar{f} test its teeth.

  • At the head (rebuilt), test_0029 passes 12/12.
  • The substring mutant (token containment) now fails it: 1 failed, 11 passed. At 4c29d0a it passed all 12.
  • So H1's F4 is closed.
  • Still surviving, Low and unchanged from our record at 4c29d0a: prefix, noderiv and walk_rhs_eager. H1's probes show the behaviour right in each case.

Underworld development team with AI support from Claude Code

@lmoresi

lmoresi commented Nov 12, 2026

Copy link
Copy Markdown
Member Author

Correction to my follow-up above: CI at 44e2d6e is not all green. Shard 3/6 (and the test job that aggregates the shards) fails on tests/parallel/test_1152_fac_zone_survives_a_mover_parallel.py::test_a_kept_zone_patch_matches_a_fresh_registration[zone]. That is the known pre-existing failure of #1096/#1101, also seen on development, in custom-MG code #1040 does not touch. The verdict stands: READY at 44e2d6e, with test_1152[zone] as the only CI failure.

Underworld development team with AI support from Claude Code

@lmoresi
lmoresi merged commit 8a388dd into development Nov 12, 2026
18 of 20 checks passed
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