← Explainer · Markdown · Source on GitHub
# Boundary-condition contracts and AMReX alignment **Design and implementation plan, 2026-09-26; the proposed periodic candidate stage table was filled the same day.** 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/b7f5b9ba6f52355d9b196b586e4a6c8719d8feea/src/PolyCfd.Core/Scenarios/ScenarioValidator.cs) checks joint velocity/pressure periodicity; [PatchBcSet.ValidateSupported](https://github.com/hankbeasley/polycfd/blob/b7f5b9ba6f52355d9b196b586e4a6c8719d8feea/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/b7f5b9ba6f52355d9b196b586e4a6c8719d8feea/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/b7f5b9ba6f52355d9b196b586e4a6c8719d8feea/src/PolyCfd.Gpu/Advection/AdvectionGpu.cs) receives periodic flags and clamps other samples; standard [patches](https://github.com/hankbeasley/polycfd/blob/b7f5b9ba6f52355d9b196b586e4a6c8719d8feea/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. ## Current static stage table **Source inventory, not new qualification.** The regular/static path in [TimeIntegratorGpu.Step](https://github.com/hankbeasley/polycfd/blob/b7f5b9ba6f52355d9b196b586e4a6c8719d8feea/src/PolyCfd.Gpu/Integration/TimeIntegratorGpu.cs) currently uses the stages below. U/V/W mean stored MAC velocity; F and B are advection scratch, not accepted physical time levels. Boundary values are constant descriptors; the presence of a `time` argument does not establish time-varying BCs. | Current operation | Fields and timing consumed | Current boundary treatment and limitation | | --- | --- | --- | | Advection preparation | Original U/V/W; physical pressure is not used | `ApplyVelocityBcs` sets selected normal values and copies periodic endpoints. Standard patches have no tangential boundary samples. No velocity halo is filled. | | RK2/forward interpolation | Original U/V/W carries each original component through the forward `dt` operation, producing F and optional stencil bounds | Each coordinate/index sample wraps or clamps. No explicit physical exterior state is supplied. Semi-Lagrangian copies F back without a separate final velocity BC application inside advection. | | MacCormack reverse interpolation | The same original carrying velocity transports F with `-dt`, producing B | F is consumed without a separate boundary refresh; `-dt` is the round-trip correction operation, not evidence of a time-dependent BC evaluation. | | MacCormack correction/limiter | Original component, F, B and forward stencil bounds produce the provisional U/V/W | All stored samples are corrected/limited; advection does not then reapply prescribed values. BC-02 must qualify the intermediate samples and result. | | Body-force sources | Provisional U/V/W; sources receive current `time` and `dt` | Sources modify borrowed fields and must not reapply BCs. The integrator does not refresh domain velocity conditions between this stage and the pressure predictor. | | Static pressure predictor | Stored physical pressure p and its refreshed physical halo act on provisional U/V/W | Pressure uses physical-face values (`pG=2*pB-pI` for fixed pressure). The velocity update has no following domain BC application here. | | Viscous solve, when `nu>0` | The predictor becomes the diffusion RHS; component stencils use constant BC descriptors | Inline tangential ghost folds and selected normal prescribed rows enforce diffusion BCs; solve exits reapply stored velocity BCs. At zero viscosity the integrator skips this stage. | | Immersed constraints and incremental projection | Static cut-face constraints, if present, precede divergence; p is saved and increment storage starts at zero | Projection applies velocity BCs before divergence and after correction. Constant physical fixed pressure becomes zero prescribed increment; homogeneous correction/error conditions remain distinct. Optional residual refinement is restricted and is not a new transport predictor. | | Pressure accumulation and final enforcement | Pressure increment is added to saved p; gauge and physical halo are restored | The static integrator reapplies velocity BCs at the end. Final enforcement does not establish that preceding transport samples were correct. | Implementation evidence: [advection](https://github.com/hankbeasley/polycfd/blob/b7f5b9ba6f52355d9b196b586e4a6c8719d8feea/src/PolyCfd.Gpu/Advection/AdvectionGpu.cs), [source contract](https://github.com/hankbeasley/polycfd/blob/b7f5b9ba6f52355d9b196b586e4a6c8719d8feea/src/PolyCfd.Gpu/SourceTerms/ISourceTermGpu.cs), [diffusion](/src/PolyCfd.Gpu/Diffusion/README) and [projection](https://github.com/hankbeasley/polycfd/blob/b7f5b9ba6f52355d9b196b586e4a6c8719d8feea/src/PolyCfd.Gpu/Projection/ProjectionGpu.cs). Moving geometry has a separate full-pressure/geometric-source path and wall timing; do not apply this static increment table to it. Its qualification remains separate. ## 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. Implement and test the selected conservative periodic stage contract below with TRN-01 before extending it to physical boundaries. Use the current source table to derive the retained methods' physical exterior sampling, including RK2 departures and MacCormack forward/reverse/correction and limiter inputs. Then derive the candidate's physical reconstruction, carrier and integrated-flux rules for each enabled BC. Final enforcement alone does not qualify earlier samples. 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 proposed stage tables **The periodic candidate below is selected design, not implemented or qualified runtime behavior.** Its equations and operator signs live in [the first regular-grid MAC candidate](/docs/amrex-alignment/ALGORITHMS#first-regular-grid-mac-candidate); TRN-01 owns its [scratch and lifetime budget](/docs/amrex-alignment/SINGLE_LEVEL_TRANSPORT#next-deliverable-one-complete-regular-grid-mac-timestep). Scope is one fixed, all-fluid periodic patch, constant density and constant nonnegative viscosity. The transported components approximate dual-volume means; one canonical endpoint owns each periodic sample. All exterior indexing wraps to that unique set; any stored duplicate is refreshed before a consumer can read it. | Proposed operation | Producer, consumer and stage meaning | Periodic rule and required assertion | | --- | --- | --- | | Accepted-state preparation and carrier construction | Borrow accepted projected `U^n/V^n/W^n` unchanged for every component and both transport stages; construct dual-face arithmetic-average carriers from those fields | Establish canonical periodic copies before carrier use; check the dual-divergence identity against the neighboring primal divergences. Evaluate the specified local CFL and its final reduction on-device before transport. An initialization projection, when needed, is a separate operation/cost. | | Stage 0 flux and `q1` | Reconstruct `q0` with minmod; for each direction compute one shared oriented upwind flux, then accumulate `q1 = q0 + dt*L(q0)` using the frozen carriers | Wrap the two-cell flux-divergence reach. Finish all directional contributions before any stage-1 reconstruction. Consume the `dt/2`-weighted stage transfer for budgets before reusing flux scratch; verify shared cancellation and constant preservation within the declared carrier-divergence tolerance. | | Stage 1 flux and `qadv` | Reconstruct completed `q1`; carriers remain the original accepted velocity, never `q1`. Accumulate `qadv = (q0+q1+dt*L(q1))/2` | Refresh any consumed duplicate of `q1`; keep `q1` fixed through every stage-1 flux. The other half-weighted transfer completes `I=dt*(F0+F1)/2`. Verify the actual weighted budget. Reuse the component scratch only after its update and diagnostics finish. | | Complete transport and prescribed source | Wait until all three `qadv` components exist before overwriting the borrowed original velocity. Add prescribed `dt*f^n`, zero by default | Use source dual means or explicitly recorded midpoint approximations at time `n`; preserve periodic source consistency and account for its component momentum increment. The artificial SSPRK2 stage is not a new prescribed-source time. | | Old-pressure predictor | Use stored physical `p^n` to subtract `dt*G p^n` from the advected/source result | Refresh the periodic physical pressure halo before its gradient is consumed. Verify the periodic gradient budget and retain physical pressure for later accumulation. | | Backward-Euler diffusion | Solve the existing periodic component Helmholtz systems when `nu>0`; at `nu=0`, use the predictor directly as `Ustar` | Use the same periodic component topology and current inline stencil contracts; establish fresh endpoint copies before dependent consumers. Verify viscous decay, periodic momentum balance and the explicit zero-viscosity path. | | One primary incremental projection | Start the increment at zero, form divergence from `Ustar`, solve with the matching `A=-DG`, then correct velocity | Use periodic increment and homogeneous solver-error conditions. Set `RefinePressureProjection=false` for this first scope; no intermediate carrier solve is required. Check compatibility, an independently computed true residual and final divergence using the specified signs and weights. | | Pressure accumulation and gauge | Add the increment to saved physical `p^n`, restore its gauge and fill the physical periodic pressure halo | Increment/error/physical roles remain distinct despite sharing periodic topology. Verify gauge changes leave pressure gradients unchanged; do not interpret residual success as continuity acceptance. | | Final copies and diagnostics | Restore final velocity endpoint copies and publish only the completed state | Count unique periodic samples in momentum/energy reductions. Measure final divergence after all final operations, stage budgets, field errors and actual resource/cost totals; copies must not introduce a seam defect. Finish reductions on-device. | The carrier is frozen across both flux evaluations; no velocity history is retained. The transport subproblem is second order in time for a prescribed steady carrier in its smooth regime. Evolving nonlinear momentum and the complete source/pressure/BE split are first order in time. Intermediate transported states need not be divergence free because they are not used as carriers. The final projection and its independent continuity checks remain required. The following extensions still need equations and filled stage tables before their runtime treatment changes: | Pending extension | Decision and evidence required | | --- | --- | | Retained semi-Lagrangian/MacCormack physical boundary sampling | Exact exterior values at each departure and stage, forward/reverse/limiter consistency, and whether a stage refresh is required; begin from the source inventory above | | Conservative physical inflow, wall/symmetry and outlet extension | Per-component reconstruction and exterior-state rules, physical stage times, explicit outlet reversal policy and integrated momentum/energy exchange | | Nonperiodic pressure/source/diffusion coupling | Preserve physical-face pressure, increment and homogeneous-error distinctions; derive the enabled physical BC chronology and final continuity relation, including any post-projection constraints | Final enforcement alone does not qualify preceding samples. Each physical extension must identify its exact producer/consumer, stencil, value location and on-device supply rule, including zero viscosity. Justify every additional solve from that method and include its cost. Follow the [pressure qualification contract](/docs/amrex-alignment/ALGORITHMS#pressure-solver-qualification); mixed pressure regions and moving geometry remain separately scoped. **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 | Resolve these claims into the [executable evidence records](/docs/amrex-alignment/SINGLE_LEVEL_TRANSPORT#executable-evidence-records): pinned configuration/method/stage, independent reference, frozen metrics/tolerances, an actual maintained command, effective run inputs, artifact/receipt and explicit verdict. Missing implementations or runs remain `notRun`. Freeze accuracy targets before candidate evaluation, then measure complete cost to meet the same targets; retain existing failed qualifications and do not select a favorable boundary metric after seeing the results. Stage-table completion alone is not numerical acceptance. **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/b7f5b9ba6f52355d9b196b586e4a6c8719d8feea/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. [The transport design checker](https://github.com/hankbeasley/polycfd/blob/b7f5b9ba6f52355d9b196b586e4a6c8719d8feea/tools/check_mac_transport_design.py) checks offline exact-arithmetic identities for the selected periodic formulas. It does not exercise boundary kernels or replace CUDA stage, convergence or performance evidence. ## 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.