← Explainer · Markdown · Source on GitHub

# Boundary-condition contracts and AMReX alignment

**Design and implementation plan, 2026-09-26.** Tasks: BC-01 and BC-02. Status and
owners live on the [work board](/docs/WORKBOARD). This plan changes no runtime
behavior and claims no new numerical qualification. The
[boundary guide](/docs/BOUNDARY_CONDITIONS_HALOS) describes current behavior;
[AMR-02](/docs/amrex-alignment/DATA_MODEL_ALIGNMENT) owns structural alignment and
[TRN-01](/docs/amrex-alignment/SINGLE_LEVEL_TRANSPORT) owns the conservative transport candidate.

## Outcome and scope

Give supported simulations consistent boundary meaning through the typed API and
scenario JSON, then qualify single-grid boundary transport before partitioning it.
Preserve the existing physical-face pressure construction, wall diffusion,
pressure gauges and GPU performance. Correcting input validation and changing
numerical boundary treatment are separate deliveries with separate evidence.

The source review found these gaps; it did not run a new CUDA reproduction:

| Current boundary | Required work |
| --- | --- |
| [ScenarioValidator](https://github.com/hankbeasley/polycfd/blob/452441867295de2160cb7631bd023662cc75fb50/src/PolyCfd.Core/Scenarios/ScenarioValidator.cs) checks joint velocity/pressure periodicity; [PatchBcSet.ValidateSupported](https://github.com/hankbeasley/polycfd/blob/452441867295de2160cb7631bd023662cc75fb50/src/PolyCfd.Core/BC/Patches/PatchBcSet.cs) checks their pairs separately | BC-01: consistent setup validation across simulation entry points |
| [Periodic velocity copies](https://github.com/hankbeasley/polycfd/blob/452441867295de2160cb7631bd023662cc75fb50/src/PolyCfd.Gpu/BC/Patches/PatchBoundaryKernels.cs) pair index lists by ordinal and stop at the shorter list | BC-01: validate or derive complete opposite-face coordinate correspondence; refuse unsupported partial periodic masks |
| [AdvectionGpu](https://github.com/hankbeasley/polycfd/blob/452441867295de2160cb7631bd023662cc75fb50/src/PolyCfd.Gpu/Advection/AdvectionGpu.cs) receives periodic flags and clamps other samples; standard [patches](https://github.com/hankbeasley/polycfd/blob/452441867295de2160cb7631bd023662cc75fb50/src/PolyCfd.Core/BC/Patches/PatchBuilder.cs) prescribe normal faces | BC-02: reproduce and qualify prescribed tangential inflow and wall/symmetry sampling; clamping is not a complete exterior-state contract |
| Outlet velocity application is a no-op for `ZeroGradient`; MacCormack samples intermediate scratch before the later stage BC application | BC-02: specify outlet reversal and intermediate-stage boundary semantics, with transport/projection evidence |
| Partial velocity masks select normal endpoint rows; pressure and tangential diffusion rules remain whole-face | Keep the current restriction explicit; spatially mixed BCs are a later numerical feature |

Existing pressure/diffusion tests remain evidence for their declared scope. They do
not establish nonperiodic advection accuracy, arbitrary backflow behavior or mixed
pressure support. See the boundary guide's source and test links.

## Design decisions

1. **Keep physical intent distinct from numerical treatment.** Walls, prescribed
   velocity, symmetry and pressure outlets remain understandable authoring choices.
   Resolve them into the supported per-component transport, diffusion and projection
   rules. AMReX's `BCRec` and `LinOpBCType` are correspondence models; use their names
   with C# spelling only where semantics match. Do not alias `ZeroGradient` to
   `FoExtrap` across all operators or add unused types to reproduce an API catalog.
2. **Make the value's meaning explicit.** Identify field/component, placement,
   physical value location, units and stage/time. A pressure boundary value is on
   the physical face; today's packed halo contains the reflected ghost sample.
   Preserve physical pressure, time-step increment and homogeneous Krylov/MG error
   conditions as distinct roles. Constant fixed physical pressure gives a zero
   prescribed increment in the current static scheme. Time-varying pressure and
   nonzero Neumann data require a separate derivation before being supported.
3. **Use one periodic topology.** BC-01 closes inconsistent setup paths now;
   AMR-02 subsequently puts authoritative periodicity in `DomainGeometry` and
   derives consumer descriptors from it. Same-level/periodic exchange and physical
   boundary treatment stay distinct; coarse/fine filling belongs to S3.
4. **Keep the existing efficient representations.** Six constant face descriptors,
   borrowed correction descriptors and inline velocity stencil rules remain useful.
   A per-component mathematical record is justified by actual consumers, not by a
   requirement to allocate boundary fields or velocity halos. Any new storage must
   have a measured stencil/lifetime need.
5. **Qualify numerical changes independently.** BC-02 may change supported transport
   boundary equations after reproduction and derivation; AMR-02 preserves existing
   numerical behavior. Existing accepted cases and scientific gates remain required.
   Do not silently change outlet behavior, defaults or reference results as a rename.

AMReX distinguishes physical, same-level and coarse/fine fills and provides component
boundary records. Its elliptic BC values represent physical-face data even when
stored in ghost slots. Hydro's documented reconstruction and outlet reversal rules
belong to its advection stages; directly clamping our final projected velocity could
violate discrete continuity. These are design references, not a claim of identical
algorithms. [AMReX boundary architecture](https://amrex-codes.github.io/amrex/docs_html/Basics.html#boundary-conditions),
[linear-solver boundaries](https://amrex-codes.github.io/amrex/docs_html/LinearSolvers.html#boundary-conditions),
[Hydro advection boundaries](https://amrex-fluids.github.io/amrex-hydro/docs_html/bcs.html#advective-bc-details).
Pin the reference source revision when implementing an AMReX-derived rule; the linked
development documentation is not a frozen algorithm specification.

## BC-01: shared setup validation

**Dependency:** current boundary contract; can be implemented before AMR-02. It does
not depend on BC-02, conservative transport or full GPU-01 migration.

**Context:** `rg -n "ValidateSupported|periodic|velocityMask" src/PolyCfd.Core/BC/Patches src/PolyCfd.Core/Scenarios/ScenarioValidator.cs src/PolyCfd.Gpu/Integration/SimulationSession.cs`

1. Inventory C# simulation, scenario and low-level operator entry points. Share
   mathematical consistency rules at the appropriate layer while preserving useful
   standalone pressure/diffusion test construction. A pressure-only solver must not
   acquire a dependency on scenario or velocity authoring rules.
2. Reject velocity/pressure periodic disagreement, nonreciprocal partners and wrong
   opposite faces before device allocation. Validate supported physical pairings and
   stationary-wall motion consistently in the high-level simulation paths.
3. Derive or validate periodic index correspondence using coordinates and component
   placement, including duplicated normal MAC endpoints. Equal counts alone are
   insufficient. Reject unsupported masks, missing samples and ambiguous pairings;
   either map correctly reordered lists or reject them explicitly.
4. Update maintained callers, fixtures, errors and current guides together. Preserve
   accepted input behavior and explain newly refused contradictory configurations.

**Acceptance:** focused tests exercise matching typed/JSON rejection and accepted
cases on all axes and opposite faces, invalid periodic lists and zero/tangential
wall velocity. A CUDA seam test verifies the accepted mapping. Configuration checks
finish at setup with no added per-step transfers, synchronization or allocation.
AMR-02 must reuse this contract rather than reintroduce independent topology flags.

## BC-02: single-grid boundary transport qualification

**Dependency:** an explicit supported configuration from BC-01. Derivation and small
reproductions can start earlier; production integration coordinates with AMR-02 and
TRN-01. S2 transport acceptance requires this evidence for each enabled method and
boundary scope; S3 inherits that qualified subset. Unrelated S2 layout work can proceed.

**Context:** `rg -n "BcFlags|ClampOrWrap|Advect|ApplyVelocityBcs|ZeroGradient" src/PolyCfd.Gpu/Advection src/PolyCfd.Gpu/Integration/TimeIntegratorGpu.cs src/PolyCfd.Gpu/BC/Patches/PatchBoundaryKernels.cs`

1. Reproduce the source-review cases on CUDA before choosing a correction. For
   example, prescribe an X-inlet with nonzero tangential velocity, initialize that
   component to zero and use zero viscosity: verify whether incoming characteristics
   supply the prescribed value. Specify a compatible outlet and other boundaries so
   the test measures inflow transport rather than a conflicting physical setup.
2. Derive the exterior sampling and boundary timing for both retained methods.
   Include RK2 departure sampling, MacCormack forward/reverse/correction stages and
   limiter bounds. For the conservative candidate, define reconstruction, predicted
   transport velocity, edge states, boundary fluxes and projection coupling under
   TRN-01. Each method needs its own consistent rules; final boundary enforcement
   alone does not qualify the values sampled during intermediate stages.
3. Choose an explicit outlet policy for the intended cases: document how exterior
   states are supplied during inflow, and whether an outlet forbids reversal or models
   a bidirectional opening. Establish consistency with pressure and global/regional
   mass balance. Do not change projected normal velocity afterward without deriving
   and testing the resulting continuity correction. Avoid adding a large menu of
   unqualified policies.
4. Implement the qualified rules with compact device descriptors and shared state.
   Reject unsupported method/BC/geometry combinations explicitly. Keep embedded-wall
   physics distinct from domain boundary sampling and qualify moving cases separately.

**Required evidence, with tolerances and references chosen before evaluating changes:**

| Case | What must be measured |
| --- | --- |
| Oblique inviscid inflow, both low and high faces and each axis | Normal and tangential prescribed data enter correctly; boundary-adjacent error under grid/time refinement |
| No-slip/moving wall and symmetry | Normal impermeability, appropriate tangential sampling and retained viscous profiles; distinguish inviscid sampling from viscous wall enforcement |
| Outlet with outward and locally reversed flow | Declared exterior-state policy, boundary momentum/energy exchange, mass balance and post-projection divergence; no claim of universal nonreflecting behavior |
| MacCormack forward/reverse/limiter stages | Valid boundary samples at the stage consumed, stable limiting and supported nonperiodic accuracy |
| Periodic seams and corners | Duplicated MAC endpoint consistency, correct interpolation across seams and unchanged periodic transport references |
| Current pressure/diffusion controls | Physical-face pressure profile, constant-pressure increment, component gauges, Couette/slip and masked-normal behavior remain valid |
| Conservative candidate on one grid | Boundary flux accounting under TRN-01; conservation and divergence are separate checks. Later single-grid/partitioned agreement belongs to S2 acceptance, not BC-02 completion |

**Acceptance:** required CUDA cases and scientific regressions pass for the declared
scope. Report boundary-local errors, whole-domain balances, stability, peak device
memory and measured cost; a converged pressure solve alone is insufficient. Keep any
remaining accuracy or moving-geometry limitations explicit. Existing methods preserve
their accepted capabilities; a new default requires its own evidence and decision.

## GPU and verification gates

Follow [GPU-01](/docs/plans/gpu-resident-processing). Host setup may validate authored metadata
and resolve immutable descriptors. Field-dependent sampling, direction decisions,
boundary fluxes and complete numerical reductions stay on the GPU. No bulk field or
reduction-partial downloads for CPU processing. Bounded control/status metadata must
have a measured payload, cadence and synchronization cost. No speculative full-face
arrays or general ghost service is required for constant conditions.

Use [staged verification](https://github.com/hankbeasley/polycfd/blob/452441867295de2160cb7631bd023662cc75fb50/test/README.md#staged-verification): focused tests while
implementing; `tools/verify static fast gpu` for runtime changes on the finished tree.
BC-02 numerical changes also need the appropriate
[verify-all selection](/docs/COMPLETE_VALIDATION#choose-coverage-for-the-change), with
full coverage before broad qualification. Measure performance on an idle machine
against the compatible reference; preserve limits and scientific baselines. CPU
backend not run (user directive). Documentation-only delivery requires static checks
and browser/link checks for the explainer; it does not complete BC-01 or BC-02.

## Deferred scope and open numerical choices

Spatially mixed pressure/velocity conditions, Robin and nonzero Neumann data,
time-varying boundary profiles and higher-order elliptic boundary closure are
separate extensions when a supported case requires them. Current velocity masks
are not mixed-BC fields. A future extension must use consistent spatial classification
through advection, diffusion, projection, connected pressure regions and multigrid
coarsening, with its own accuracy and memory evidence.
[AMReX-Hydro mixed BCs](https://amrex-fluids.github.io/amrex-hydro/docs_html/bcs.html#mixed-boundary-conditions)
are themselves documented as tested in restricted EB-separated configurations.
That feature is not a prerequisite for AMR-02 or initial S2/S3.

BC-02 must resolve the outlet reversal policy, exterior interpolation and boundary
stage times from the selected physical cases and method derivation. AMR-02 resolves
the compact descriptor spelling and ownership without changing those equations.