Skip to content

Support pulse-height tallies in shared secondary mode - #4089

Open
GuySten wants to merge 10 commits into
openmc-dev:developfrom
GuySten:shared-pht
Open

GuySten wants to merge 10 commits into
openmc-dev:developfrom
GuySten:shared-pht

Conversation

@GuySten

@GuySten GuySten commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Support pulse-height tallies with the shared secondary bank

Removes the restriction that forced shared_secondary_bank off whenever a
pulse-height tally was present, and implements the deferred per-history scoring
described in the TODO that guard carried.

Problem

A pulse-height tally scores once per source history, in the bin containing the
total energy that history's entire particle tree deposited in a cell. In the
default transport modes the whole tree is carried by a single Particle, so
pht_storage_ already holds the per-history total when event_death() runs.

Under the shared secondary bank each generation is transported as a fresh set of
Particle objects, load balanced across MPI ranks between generations. Three
things broke:

  1. pht_storage_ is a per-Particle member reset in initialize_particle_track, so every descendant's deposition was dropped from its root's total.
  2. event_death() scored unconditionally, so each fragment of one physical pulse was scored as a separate pulse, shredding the spectrum toward low energy.
  3. The subtraction removing a secondary's energy from its parent was never implemented on this path. event_revive_from_secondary() skipped it on the grounds that create_secondary() had already done it; create_secondary() contained no pulse-height code. The compensating pre-add in sample_secondary_photons() still ran unconditionally.

Approach

Every particle carries a root index: the dense global index of its primary
in the source bank, in [0, n_particles). It has to survive bank sorting and
the MPI migration between generations, so it travels on SourceSite.

Each Particle still accumulates its own fragment as before. At death the
fragment is staged in a per-thread buffer keyed by root index rather than
scored. Once the generation loop drains, contributions are routed by
MPI_Alltoallv to the rank owning each root, summed, and scored once per
history.

Carrying the root without growing SourceSite

SourceSite is the element type of the fission bank and the source bank, both
sized by particles per batch, so an added field would be paid for in every run
including those that never touch the shared secondary bank. The existing
parent_id field is already free by the time the root is wanted: it and
progeny_id serve only to give a site its place in the collected bank, via
progeny_per_particle[parent_id] + progeny_id, and that key is consumed the
moment the site is placed.

The field is therefore renamed to ancestor_index and given two accessors over
the same storage:

  • parent_slot() — the immediate parent's slot in the current generation's work, valid from creation until collection places the site.
  • root_index() — the primary at the root of the history, valid afterwards.
    resolve_root_indices() performs the handover, once per generation, after
    collection and before the migration. A site's parent is a primary on the first
    pass, so its root comes from the phase-1 partition; on later passes the parent
    already carries its own resolved root, so the value propagates down the tree.
    Net effect on SourceSite is zero fields and zero bytes, and the MPI datatype
    is unchanged in size.

progeny_id stays: fission sites are appended concurrently, so their position
in the bank is nondeterministic and the ordinal is the only thing sort_bank()
has to work from. add_surf_source_to_bank() wrote a particle ID into one field
and a progeny count into the other, neither matching what those fields mean
anywhere else and neither read by anything, so both assignments are removed.

The phase-1 partition is computed, not stored

calculate_work() is a pure function of the primary count and the rank count —
a block partition with the remainder given to the first remainder ranks — so
the phase-1 partition can be recomputed wherever it is needed rather than
snapshotted before calculate_work() starts rewriting work_index for each
secondary generation. phase1_first_root() and phase1_owner_of_root() give
the range owned by a rank and the owner of a root in closed form. When
min_work is zero the boundary equals n_particles, so the branch that would
divide by zero is unreachable.

Reproducibility

Arrival order at a history's accumulator depends on which thread transported
each descendant and on which rank it landed, so summing fragments as they are
found would make a history's total vary in its last bits with the thread and
rank count. For most tallies that is invisible, but a pulse height is binned, so
an ulp can move a whole count across a bin edge. The regression test here is
exactly the exposed case: a delta_function(1e6) source with bin edges at
linspace(0, 1e6, 101), so every fully absorbed history lands on the top edge
and a one-ulp difference decides whether it is counted at all.

Contributions are therefore collected, not summed, and folded in track id order
at the end. A track id is the particle's global slot within its generation plus
the tracks completed in earlier generations, both global quantities, so the
order is the same for any thread or rank count, and it is unique within a batch
so the ordering needs no tie-break. This relies on the global ordering of the
secondary bank being independent of the rank count, which is the property
sort_bank() already exists to provide.

The cost is one sort per batch over the fragments that actually deposited,
which in a detector problem is a small fraction of tracks.

Changes

  • particle_data.h — SourceSite::parent_id renamed to ancestor_index, with parent_slot() and root_index() accessors; ParticleData::root_index_ and accessors
  • particle.cpp — propagate the root index; implement the parent-side subtraction in create_secondary(); route event_death() to staging in shared mode; drop the two dead bank-ordering writes in add_surf_source_to_bank()
  • tallies/pulse_height.{h,cpp} (new) — staging buffers, owner exchange, canonical fold order, deferred scoring
  • simulation.{h,cpp} — phase1_first_root(), phase1_owner_of_root(), resolve_root_indices(); hooks in both shared drivers
  • tally_scoring.cpp — score_pulse_height_tally() takes the energy vector as an argument instead of reading p.pht_storage()
  • initialize.cpp — remove check_pulse_height_compatibility(); mpi::source_site loses a field
  • lib/core.py — _SourceSite mirrors the renamed member

Testing

New tests in tests/unit_tests/test_pulse_height.py:

  • Count conservation (photon/neutron × shared/local). Fixed-source results are normalized per source particle, so the tally summed over all bins must be exactly 1.0. Per-track scoring pushes this above one; a dropped history pushes it below.
  • Mode comparison, over a thin photon, thin neutron and thick photon detector. Exact comparison is not possible, since compute_particle_id() and compute_transport_seed() both branch on the shared bank and the two modes therefore sample different random number streams. Mean deposited energy and per-bin shape are compared against combined standard errors. The thick case is the sensitive one: nothing escapes and each history spawns roughly 1.7 secondaries.
    Regression references for shared_photon and shared_neutron are regenerated;
    the local_* references are unchanged.

Notes for reviewers

  • SourceSite::parent_id is renamed. It is a public member of an installed header, so out-of-tree code touching it — most plausibly a compiled custom source — needs the new name. CollisionTrackSite::parent_id is a different struct and is untouched.
  • Two accessors over one field give no compile-time protection. Calling root_index() on an uncollected site compiles and returns the placement key. The window is about ten lines in each driver, between collection and resolve_root_indices(). If reviewers would rather have it enforced, storing the placement key negated makes the sign a free discriminant and lets each accessor assert; that is a small follow-up.
  • One allocation per secondary generation. The history-based driver used to recycle the read bank's buffer into the write bank before collection. The read bank is now needed until roots are resolved, so it is released afterwards instead.
  • Memory. Staging holds one record per track that actually deposited, not per track, plus one int64 track id each; in a typical detector problem most histories never reach a pulse-height cell. The per-rank totals array is 8 * n_owned_roots * n_pulse_height_cells bytes.

Checklist

  • I have performed a self-review of my own code
  • I have run clang-format (version 18) on any C++ source files (if applicable)
  • I have followed the style guidelines for Python source files (if applicable)
  • I have made corresponding changes to the documentation (if applicable)
  • I have added tests that prove my fix is effective or that my feature works (if applicable)

Summary by CodeRabbit

  • New Features
    • Pulse-height tallies now support shared-secondary-bank transport in both history-based and event-based modes.
    • Results are aggregated by source history, with a score recorded even when a history deposits no energy.
  • Bug Fixes
    • Improved pulse-height scoring for shared-secondary transport, including energy transferred to secondary photons.
  • Tests
    • Added comparisons between local and shared-secondary transport for photon and neutron cases, including thin and thick detector scenarios.

@GuySten
GuySten marked this pull request as ready for review August 31, 2026 18:02
@GuySten
GuySten requested a review from paulromano as a code owner August 31, 2026 18:02
@GuySten
GuySten marked this pull request as draft September 8, 2026 15:53
@GuySten
GuySten marked this pull request as ready for review September 8, 2026 17:54
@GuySten
GuySten requested a review from nelsonag as a code owner September 8, 2026 17:54
@GuySten
GuySten requested a review from jtramm September 8, 2026 17:55
claude added 2 commits October 3, 2026 21:28
Resolve the conflict in add_surf_source_to_bank: keep the comment
explaining why ancestor_index and progeny_id are left alone on surface
source sites, and drop the unused return value of thread_safe_append as
develop does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DwzNTbMvNjYHYYcvxN3bk7
Brings in the missing pathlib import in the weight window unit tests
(openmc-dev#4154).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DwzNTbMvNjYHYYcvxN3bk7
@coderabbitai

coderabbitai Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The change adds pulse-height tally support for shared-secondary-bank transport. It tracks each secondary’s root history, stages per-particle energy contributions, routes and combines them by history, then scores one result per owned history. Tests compare shared-bank and local transport spectra.

Changes: Shared-bank pulse-height scoring

Layer / File(s) Summary
Track root histories and placement keys
include/openmc/particle_data.h, include/openmc/simulation.h, src/simulation.cpp, src/bank.cpp, src/physics.cpp, src/physics_mg.cpp, src/initialize.cpp, openmc/lib/core.py, src/particle.cpp
Source sites use ancestor_index for parent placement and resolved root identity. Transport resolves roots for primary and descendant sites and propagates them through secondary generations.
Stage and score pulse-height contributions
include/openmc/tallies/pulse_height.h, include/openmc/tallies/tally_scoring.h, src/particle.cpp, src/tallies/pulse_height.cpp, src/tallies/tally_scoring.cpp, CMakeLists.txt
Shared-secondary transport stages pulse-height contributions by root and track ID. Finalization routes and combines contributions, then scores each locally owned history.
Wire transport lifecycle and tests
src/simulation.cpp, src/finalize.cpp, src/initialize.cpp, tests/unit_tests/test_pulse_height.py
Transport initializes and finalizes pulse-height buffers. The compatibility check that disabled shared-secondary banks for pulse-height tallies is removed. Tests compare local and shared-bank results.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant Particle
  participant stage_pulse_height
  participant pht_thread_buffers
  participant finalize_pulse_height_tallies
  participant MPI_ranks
  participant score_pulse_height_tally
  Particle->>stage_pulse_height: Pass root index, track ID, and cell energies
  stage_pulse_height->>pht_thread_buffers: Store contribution in thread buffer
  finalize_pulse_height_tallies->>pht_thread_buffers: Collect staged contributions
  finalize_pulse_height_tallies->>MPI_ranks: Exchange contributions when multiple ranks are active
  finalize_pulse_height_tallies->>score_pulse_height_tally: Score aggregated values for each owned history
Loading
Merge Risk: Minimal · up to 1d426

No concrete merge-blocking issue is established by the supplied evidence.

Security architecture risk: Low · up to bfab5

The inspected flow keeps history identity internally generated and preserves source-file and MPI field layouts. Remaining uncertainty concerns downstream compatibility and failure recovery for distributed aggregation; no introduced security attack path was demonstrated.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The demonstrated shared-state scope is participating ranks in the simulation communicator and their pulse-height result arrays. The available evidence does not establish cross-tenant, external-service or privileged-environment exposure.

Trust Boundaries and Controls

  • inferred — Normal root bounds follow from internally generated work indices, validated history-bank placement and descendant parent-slot validation. Final routing relies on this producer invariant rather than checking the upper root bound itself. No inspected path demonstrated that source-file ancestor metadata or ordinary source parameters can substitute an arbitrary root key.

Resilience and Maintainability Implications

  • observed — Detected invalid parent state invokes process termination and MPI abort, providing job-level containment rather than recovery. Aggregation clears staged buffers before exchange and directly updates tally results afterward; a transactional rollback or safe retry after interrupted aggregation was not established.

Hardening Proposals

  • proposed — Consider validating root ranges at aggregation entry and using checked arithmetic for MPI payload counts and displacements. These would strengthen failure containment for violated producer assumptions or oversized workloads; they are defense-in-depth proposals, not verified attack paths.
Pre-merge checks: Passed 5

Check name Status Explanation
Title check Passed The title "Support pulse-height tallies in shared secondary mode" matches the main change. The PR removes the restriction that disabled the shared secondary bank when pulse-height tallies were present…
Description check Passed The description follows the repository template. It includes a summary, a problem statement, an approach, a changes list, testing details, and reviewer notes, and it has the checklist. It has two gaps…
Docstring Coverage Passed Docstring coverage is inconclusive: files from earlier reviews still need to be rechecked within the check's analysis limits. Not blocking.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title "Support pulse-height tallies in shared secondary mode" matches the main change. The PR removes the restriction that disabled the shared secondary bank when pulse-height tallies were present. It also adds per-history scoring for that mode, as the description and objectives state. The title is concise and specific, so a teammate scanning history can identify the primary change.

Full details: Description check

Explanation

The description follows the repository template. It includes a summary, a problem statement, an approach, a changes list, testing details, and reviewer notes, and it has the checklist. It has two gaps. The "Fixes # (issue)" line is missing, and the "AI Assistance" section is absent, even though the template requires it when AI tools were used. The author also struck through the style-guideline and documentation checklist items without explaining why. These gaps are non-critical, so the description is mostly complete.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Tip

🎯 Customize your risk assessments

Guide how CodeRabbit assesses merge risk and security architecture risk. Highlight sensitive changes and explain your security boundaries using Merge Risk Instructions and Security Risk Instructions in your review settings. Security architecture risk assessments require the Advanced plan or above.

✅ Automatic approvals, with your rules

Let CodeRabbit approve pull requests once required threads are resolved, pre-merge checks pass, and your risk limits are met. Enable Automatic approvals in review settings, with overrides for teams or file paths.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 56b2bd56-471b-4984-b4d8-f3196059932e
Commits

Reviewing files that changed from the base of the PR and between bfab5df and 1d42661.

Files ignored due to path filters: 3

  • tests/regression_tests/pulse_height/shared_neutron/results_true.dat is excluded by !**/*.dat
  • tests/regression_tests/pulse_height/shared_photon/results_true.dat is excluded by !**/*.dat
  • tests/regression_tests/weightwindows_pulse_height/shared/results_true.dat is excluded by !**/*.dat
Files selected for processing: 1

  • include/openmc/particle_data.h

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

# Conflicts:
#	tests/regression_tests/pulse_height/shared_neutron/results_true.dat
#	tests/regression_tests/pulse_height/shared_photon/results_true.dat
#	tests/regression_tests/weightwindows_pulse_height/shared/results_true.dat

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants