Skip to content

Make a restore a clean line, and extrapolate velocities with the step ratio - #845

Merged
lmoresi merged 5 commits into
developmentfrom
bugfix/snapshot-restore-exact
Oct 12, 2026
Merged

lmoresi merged 5 commits into
developmentfrom
bugfix/snapshot-restore-exact

Conversation

@lmoresi

@lmoresi lmoresi commented Oct 12, 2026

Copy link
Copy Markdown
Member

A saved state is now a clean line to reconstruct a run from: restoring it and continuing gives the same fields to the last bit, whatever was solved between the save and the restore. The NS and semi-Lagrangian velocity extrapolations also now assume the timestep can vary.

Restore exactness.

  • Unmoved mesh: a restore moves the mesh only when its coordinates changed. It used to move it every time, which made every solver rebuild: 1.5e-5 in velocity on a viscoelastic channel.
  • Solver step state: captured and restored, in memory and on disk, as a SolverStepState dataclass (option-B adapters, per the state-as-dataclass contract). It holds the warm-start flag and, on the Eulerian Navier-Stokes and advection-diffusion solvers, the last step length, the rate estimate_dt reads and the extrapolation's previous step.
  • Characteristic trace: its step state (valid velocity levels, step lengths) travels with the DDt state and the swarm payload.
  • Preconditioners: a restore replaces each GAMG preconditioner, which keeps its hierarchy and eigenvalue estimates through PCReset, and drops the rotated free-slip workspace. Other preconditioners are left alone; a geometric multigrid holds transfers set in code.

Variable timesteps. Both formulas reduce to the old ones for equal steps:

  • Navier-Stokes advecting velocity: u^n + r(u^n - u^{n-1}), previously 2u^n - u^{n-1}.
  • Trace-back mid-time velocity: v^n + (r/2)(v^n - v^{n-1}), previously 3/2 v^n - 1/2 v^{n-1}. This covers the nodal, integration-point and forward SL histories, AdvDiffusion SLCN, and swarm advection with midtime_velocity.

Here r = dt_n / dt_{n-1}. Written for equal steps, both formulas dropped to first order on every step whose length changed.

What it gives:

  • No trace: a regretted step leaves none, bit for bit. This holds on AdvDiffusion SLCN, viscous and viscoelastic NS, custom-FMG Stokes and rotated free-slip Stokes, serial and 2 ranks.
  • Never-restored runs: the difference is the warm multigrid: 2.5e-8 relative on the AdvDiffusion test, 8.4e-7 before.
  • Order: swarm advection with alternating steps h, h/2 converges at rate 1.98-1.99, against 1.05-1.17 on development.
  • Constant steps: bit-identical to development for AdvDiffusion SLCN (order 2), NS (orders 1 and 2, with Picard) and VE Stokes (order 2).

Motivation: snap-back (retaking a failed Newton step as two half steps) on the VE cylinder campaign, which needs the start of a step to be a clean restore line.

Tests (each shown to fail on the defect it guards):

  • tests/test_0020_restore_continuation.py: unmoved mesh, solver step state, AdvDiffusion step state, code-set multigrid transfers, rotated free-slip workspace, disk round trip, and an end-to-end VE regretted step (level 3).
  • tests/test_1060_variable_timestep_extrapolation.py: the trace, NS, swarm.advection and the swarm trace restore.
  • tests/test_0008_snapshot_realsolver.py: the never-restored floor is now 1e-7 relative to the solution, so it rejects the old 8.4e-7.

Level 1: 2045 passed; level 2: 1122 passed (both run before the review fixes). Territory suites, 42 files: 412 passed on the branch, 406 on development; the difference is the new tests.

Adversarial review: one round, three reviewers, recorded in docs/reviews/2026-10/restore-exact-adversarial-review.md and posted below. It found a blocking regression: a restore reset geometric multigrid and dropped code-set transfers. Fixed.

Issues. None are fixed by this branch.

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). The dead SemiLagrangian._midtime_velocity_expr, whose signature this branch had extended, is removed.
  • 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 — np2/np4 checked where swarm/mesh/solver dispatch is touched (S11). Restore tests pass on 2 ranks; the mesh-move decision is collective on the mesh's communicator, checked with a deform on one rank only at np=2 and np=3.
  • 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

A restore brought back the fields and histories but not everything the next
solve reads, so a regretted step could steer the steps after it:

- The restore moved the mesh even when its coordinates had not changed. The
  move bumped the geometry version and every solver on the mesh rebuilt, so the
  next solve started from a different place (1.5e-5 in velocity on a small
  viscoelastic channel). A restore now moves the mesh only when it moved.
- Solvers carry state from one solve to the next: the warm-start flag (a
  diverged solve clears it and it decides how the next solve starts), and on the
  Eulerian Navier-Stokes and advection-diffusion solvers the last step length and
  the rate estimate_dt reads. These are captured as a SolverStepState dataclass
  (option-B adapters, per the state-as-dataclass contract) in the snapshot and
  put back on restore; a solver built after the capture returns to the state of
  one that never solved.
- A characteristic trace's count of valid velocity levels decides the mid-time
  velocity of the next trace-back; it now travels with the DDt state.
- Preconditioners keep history of their own. GAMG keeps its hierarchy and
  eigenvalue estimates even through PCReset, so restoring a solver's state
  discards its preconditioner setup (GAMG by replacing the instance, blocks of a
  field split recursively), and the solves after a restore are those of a run
  started from the restored fields.

A regretted step now leaves no trace bit for bit (serial and 2 ranks) in the
AdvDiffusion and viscoelastic Navier-Stokes tests. Against a never-restored run
the difference is the warm multigrid (~2e-8 on the AdvDiffusion test, down from
~7e-7).

Underworld development team with AI support from Claude Code
Two schemes extrapolate the velocity from the levels they hold, and both were
written for equal steps:

- the Eulerian Navier-Stokes advecting velocity, 2 u^n - u^{n-1}, is now
  u^n + r (u^n - u^{n-1});
- the semi-Lagrangian trace-back's mid-time velocity, 3/2 v^n - 1/2 v^{n-1}, is
  now v^n + (r/2)(v^n - v^{n-1}) (nodal, integration-point and forward
  histories, AdvDiffusion SLCN, swarm advection with midtime_velocity);

with r = dt_n / dt_{n-1}. Both are linear extrapolation in time, exact for a
velocity linear in time whatever the steps; written for r = 1 they dropped to
first order on every step whose length differs from the last (a step retaken in
halves, a step cut to an output time, an adaptive controller). The BDF
coefficients, the theta weights, the exponential coefficients and the older
trace segments already took the step lengths into account.

r = 1 reproduces the equal-step weights to the last bit (the trace's ratio is an
exact rational; the solver writes (1 + r) u^n - r u^{n-1}), so constant-step runs
are unchanged. The previous step length travels with the solver's and the
trace's step state, so a restore recovers it.

Underworld development team with AI support from Claude Code
From an independent review of the branch (three reviewers):

- A restore reset every preconditioner. PCReset on a geometric multigrid drops
  transfers set in code (set_custom_fmg, the adapt-on-top hierarchy), and the
  next setup tried to coarsen the DM itself and failed. Only GAMG, which keeps
  history through a reset, is replaced now; other preconditioners rebuild from
  the operator on their next setup and are left alone. Blocking; new test.
- The rotated free-slip solve keeps its own operator, preconditioner and a
  fast-path hint between solves; the state setter now discards that workspace.
- Asking a never-set-up field split for its blocks printed a PETSc error block
  on every restore; the probe now runs under the silent 'return' handler.
- A restore from a file ignored solver step state; disk snapshots now write and
  read it (a file without it restores solvers to their never-solved state).
- A swarm's own mid-time advection trace was not captured, so a regretted swarm
  step left its step length behind (5.6e-5 in position); it now travels with the
  swarm payload.
- The trace stores step lengths as plain non-dimensional floats (a float32 or
  sympy timestep made the disk record unreadable) and reads records tolerantly.
- The Navier-Stokes extrapolation uses the same _step_ratio as the trace.
- Stale equal-step formulas in the user guide, design note and docstrings; the
  dead SemiLagrangian._midtime_velocity_expr removed; the mesh's own
  communicator for the restore decision; comments and guides corrected.
- Tests: each new test shown to fail on the defect it guards; test_0008's
  floor is now relative (1e-7 of the solution) so it rejects the old 8.4e-7;
  levels per test (the end-to-end viscoelastic test is level 3, the rest use a
  viscous channel and run in seconds); the step ratio is tested through
  swarm.advection, not only the bare trace.

Underworld development team with AI support from Claude Code
Underworld development team with AI support from Claude Code
Underworld development team with AI support from Claude Code
Copilot AI balanced review requested due to automatic review settings October 12, 2026 07:03
@github-actions

Copy link
Copy Markdown

🔍 Architectural Review Checklist

Thank you for submitting an architectural review! Reviewers should validate:

Design & Architecture

  • Design rationale is clear and well-justified
  • Trade-offs are documented with alternatives considered
  • System architecture is comprehensible
  • Integration points are clearly identified

Implementation

  • Implementation matches documented design
  • Code quality meets project standards
  • Breaking changes are identified and justified
  • Backward compatibility is properly addressed

Testing & Validation

  • Testing strategy is adequate for the changes
  • Test coverage is sufficient
  • Edge cases are properly covered
  • Performance impact has been assessed

Documentation

  • Known limitations are clearly documented
  • Benefits are quantified with metrics
  • User-facing changes are documented
  • Migration guide provided (if needed)

Review Process: See CODE-REVIEW-PROCESS.md

Approval: This PR merge = Review formally approved

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 reached their quota limit.

@lmoresi

lmoresi commented Oct 12, 2026

Copy link
Copy Markdown
Member Author

Adversarial review (one round, three independent reviewers: restore semantics; step ratio; tests, style and contracts). Record: docs/reviews/2026-10/restore-exact-adversarial-review.md.

Findings and their state

  • Blocking — a restore crashed every solver on code-set multigrid transfers
    (set_custom_fmg, adapt-on-top): PCReset on a PCMG drops the transfers and the next
    setup calls DMCoarsen ("Grid adaptor mmg not registered"). Fixed: only GAMG is
    replaced. Test test_a_restore_keeps_multigrid_transfers_set_in_code (fails on 737b4e15).
  • Swarm-owned trace not captured: a regretted swarm step left its step length
    (5.6e-5 in position). Fixed; test_a_restore_brings_back_the_step_length_of_a_swarm_trace.
  • Rotated free-slip workspace survived a restore (~1e-15; its fast-path hint can steer
    a nonlinear run). Fixed; test_a_restore_discards_the_rotated_free_slip_workspace.
  • Disk restore ignored solver state (in-process load_state(path) kept the regretted
    step's last_timestep, previous_timestep). Fixed: written and read with the snapshot;
    test_a_disk_snapshot_carries_the_solver_step_state.
  • A float32 / sympy timestep made the trace record unreadable from disk (KeyError).
    Fixed: non-dimensional floats, tolerant read.
  • PETSc error block printed on every restore of a never-set-up field split. Fixed.
  • Tests: the end-to-end viscoelastic test guards only the solver step state and took
    213 s (now level 3, two steps; the rest moved to a viscous channel, seconds each);
    test_0008's 1e-5 floor passed the old 8.4e-7 (now 1e-7 relative); level-1 NS solve
    (now level 2); the step ratio was untested through any caller (now through
    swarm.advection).
  • Docs and dead code: five statements of the equal-step formula; the dead
    SemiLagrangian._midtime_velocity_expr; one comment and two guide passages. Fixed.
  • Not changed, with reason: the trace record nested in the DDt state stays a plain
    dict (the disk snapshot writes state field by field and cannot write a nested
    dataclass; commented); _DDtCoreState keeps schema 1 (the new field has a default and
    old files load — checked both ways); a Schur inner KSP is not reached by the
    preconditioner discard (UW never configures one); a capture taken before the first
    solve differs at round-off (1e-15) because objects built on first use cannot be un-built.

Attacks that failed

  • PC discard on standard paths: GAMG Stokes 40/8 iterations, refined native-mg Stokes 3
    iterations, Poisson GAMG 7 and FMG 3 — same counts as never-restored; refined mg Stokes
    bit-identical.
  • Mesh deformed on one rank only between save and load, np=2 and 3: every rank moves, no
    hang, coordinates exact.
  • Old disk snapshots read by the new code and new ones by the old code.
  • Step ratio through every caller (nodal, integration-point and forward SL histories,
    AdvDiffusion SLCN with the shared trace, swarm-owned trace): mid-time displacement error
    1e-15 after the first step; dimensional timesteps give the right ratio.
  • Second order with alternating steps h, h/2: swarm rates 1.98–1.99 (development
    1.05–1.17).
  • Constant steps: AdvDiffusion SLCN order 2, NS orders 1 and 2 (with Picard), VE Stokes
    order 2 bit-identical to development; advection="implicit" unaffected.
  • Territory suites (42 files, -n 8): 412 passed on the branch, 406 on development, the
    difference being the new tests. Level 1: 2045 passed; level 2: 1122 passed.

Issues adjudicated


Generated by Claude Code

@github-actions

Copy link
Copy Markdown

✅ Test Suite: success

@lmoresi
lmoresi merged commit 05d84a0 into development Oct 12, 2026
5 checks passed
lmoresi added a commit that referenced this pull request Oct 12, 2026
…sport guards

Development's #845 rewrote the extrapolated advecting velocity as
u^n + r(u^n - u^{n-1}) with r the ratio of this step to the last, and
changed the stored level from u_n to DuDt.psi_star[0]. This branch had
added two guards to the same lines, because it introduces the
semi-Lagrangian velocity transports where the extrapolation state does
not exist: _u_prev is allocated only when velocity_transport is
"eulerian".

Both are kept. Development's formula and stored level stand; this
branch's `and self._eulerian` and `if self._u_prev is not None` guards
stand with them. Taking development's side alone would have raised
AttributeError on every semi-Lagrangian step -- verified that _u_prev is
None for backward_nodes and forward_nodes, and a mesh variable only for
eulerian. _previous_timestep is recorded on every path, so the ratio is
right on the step after a transport switch.

test_1103 passes for all four transports including the [eulerian]
anchor: at constant dt _step_ratio nsimplifies to exactly 1, so the new
weights are the old 3/2 and 1/2 to the last bit.

Pre-existing failure, NOT from this merge:
test_1104_navier_stokes_supg_memory_stress::
test_the_developing_channel_keeps_its_recorded_flow fails on its
SIGMA_XY anchor, giving (-0.00331135, 0.00220583) against a recorded
(-0.00331132215, 0.00220579959) at atol 1e-9 -- about 3e-8, or 1e-5
relative. It fails with the IDENTICAL values at this branch's previous
head dcd363c, built and run before any of development's new work, so
neither #845 nor this merge moved it. The velocity anchor U_X passes.
Left as it is rather than re-recorded: the repository already skips
anchors recorded on a different platform because gmsh triangulates
differently, and a 1e-5 relative stress is consistent with that, so
re-recording to this machine could break CI instead of fixing it. CI
will say which it is.

Underworld development team with AI support from Claude Code

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E87Q7KrpapxeQiLD1RiNXv
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