# Issue 36: WCT 0.32.x patch release -- the run-by-run non-determinism fixes, built and validated for SBND DetSim

GitHub: https://github.com/HaiwangYu/wire-cell-toolkit-ai-helper/issues/36.

**Ask (Haiwang, 2026-10-02).** Patch release on `0.32.x` (the WCT that SBND
production runs, `wirecell v0_32_1`): cherry-pick `47d16673` (FFTW plan cache),
`36489a20` (`c_data_afterfilter` init), `68d3a99d` + `98846706` (stale
`contained_rois`); look for other randomness fixes; build in the SL7 container;
validate by running `standard_detsim_sbnd.fcl` several times on the Gen-2 g4
input and comparing the `recob::Wire` `dnnsp` / `gauss` / `wiener` waveforms,
which should be byte-identical. Local branch only, no push, Haiwang validates.

Context: #31 (production A/B, 88 events: gauss/wiener differ in 37-46 of 88,
dnnsp in 12-16), #34 (the stale-key fix), wcp-porting-validation
`sbnd/sbnd_xin/docs/127_sbnd-detsim-vplane-sp-nondeterminism.md` (Xin's
standalone reproduction and fix).

## 1. The branch

- Base: `origin/0.32.x` = tag `0.32.1` = `e0d639cf` (the branch has no commits
  past the tag).
- Local branch `0.32.x` is checked out in a **git worktree**,
  `/exp/sbnd/app/users/yuhw/wire-cell-toolkit-0.32.x`, so the master checkout in
  `wire-cell-toolkit/` is untouched (`setup-ap.sh` prepends that checkout's
  `cfg/` to `WIRECELL_PATH`; a branch switch there would change what every
  `lar` job runs).
- Cherry-picks (`git cherry-pick -x`), in order:

| on 0.32.x | upstream | what |
|---|---|---|
| `bc32dfe1` | `47d16673` | aux/FftwDFT: `FFTW_UNALIGNED` on all 7 plan creations, address-derived `aligned` bit dropped from the plan-cache key. Clean. |
| `f975806f` | `36489a20` | sigproc/OmnibusSigProc: `decon_2D_looseROI` fills every row of `c_data_afterfilter` (the FFT-padding rows were uninitialized). Clean. |
| `8fc30e70` | `68d3a99d` | sigproc: `r_erase_stale_contained` knob, `ROI_refinement::set_erase_stale_contained`, erase in both `CleanUpInductionROIs` branches, new doctest. **Conflicted** in `OmnibusSigProc.h`, `OmnibusSigProc.cxx`, `ROI_refinement.h`: the upstream hunks sit next to the per-plane knobs `r_th_factor_planes` / `r_pad_planes` / `r_break_roi_loop_planes` (`5d5d7a7d`, 2026-06-08) which 0.32.x does not have. Resolved by taking only the `erase_stale_contained` lines; the per-plane knobs were **not** brought in. |
| `70140ede` | `98846706` | sigproc: default flipped to `true`; OmnibusSigProc always passes the knob to ROI_refinement; doctest case for the default. Same conflict in `OmnibusSigProc.cxx`, same resolution. |

- `git diff 0.32.1` = 6 files, +185/-18: `aux/src/FftwDFT.cxx`,
  `sigproc/{inc/WireCellSigProc/OmnibusSigProc.h,src/OmnibusSigProc.cxx,src/ROI_refinement.cxx,src/ROI_refinement.h}`,
  `sigproc/test/doctest_roi_refinement_stale_keys.cxx` (new). No public header
  changes: `OmnibusSigProc.h` and `ROI_refinement.h` are private to the sigproc
  plugin (larwirecell does not include them), `FftwDFT.h` is unchanged.
- `wire-cell --version` of the build: `0.32.1-4-g70140ede`.

## 2. Other candidate determinism fixes in `0.32.1..master` (sim / NF / SP / DNN-ROI path)

Surveyed with `git log --grep` (determin|uninit|run-to-run|stale|random|UB|OOB|race)
restricted to `util aux gen sigproc iface pytorch root sio apps`, plus every
commit touching `FftwDFT.cxx`, `OmnibusSigProc.cxx`, `ROI_refinement.cxx`,
`ROI_formation.cxx`.

**Taken:** the four above. They are the only commits whose stated purpose is
run-to-run determinism of NF/SP output. Together they cover the three
hypotheses doc 127 ranked (H1 stale key, H2 padding rows, plus the FFTW plan
cache that #31 identified as the likely cause of the U-plane / dnnsp flips the
stale key cannot explain).

**Not taken, with reasons:**

| commit | what | why not |
|---|---|---|
| `dc613760` + `9b4ebd5f` (2026-05-06) | "fix iterator UB and use-after-free in BreakROIs", then its revert | `9b4ebd5f` shows the premise was inverted (no UB; the real cause was `36489a20`). Net effect on master is a harmless snapshot copy plus refreshed PDHD/PDVD test fixtures. Nothing to fix. |
| `501c5fe6` (2026-07-22, #491) | OOB `.block()` read in `decon_2D_*` when `unpad_data` already shrank the array | Only reachable with the ICARUS "twofaced" split induction planes (`nwires_separate_planes`); SBND has one face per plane, so `tm_r_data` still carries the FFT padding and the block is in bounds. Real fix, but a separate release decision (108-line diff, also hardens `restore_baseline`). |
| `c9a32e30` (2026-04-12) | "fix 17 bugs" in sigproc | Changes behaviour (`find_ROI_loose` merge loop `flag_repeat` 0->1, division guards, `r_th_precent`->`r_th_percent` key rename, `isWarped`->`isWrapped`). The uninitialized-pointer fix is in `PeakFinding` (uBooNE PMT filter, not used by SBND). Not a determinism patch. |
| `743958f8` | L1SPFilterPD doctests create their own FftwDFT | test-only, L1SP not used by SBND |
| `b3096622` | gen/util tests: `size_t` seed narrowing | test-only |
| `7822a440` | util: one shared log-file handle | logging only |
| `a91cb2d4` (gen) | irfft normalization fix in noise | behaviour change of the simulated noise, not determinism |

**Known, still unfixed on master (doc 127 sec 6):** the shared `gen::Random`
engine has no lock. Under *multi-threaded* TbbFlow two `AddNoise` /
`DepoTransform` nodes draw from one engine in timing-dependent order, which
changes the simulated ADC on **all** planes and dnnsp. It does not show in
the #31 production symptom (that would change every channel; it changes a
few), and `lar` runs art with one scheduler thread unless `-j N` is given, so
WCT's TbbFlow gets one worker. Fixing it (a mutex, or per-anode `Random`
instances in the cfg) changes the noise realization and is an SBND/owner
decision, so it is **not** in this patch. `gen/src/Random.cxx` on 0.32.x has no
mutex either.

Latent but benign (doc 127, #34): `SignalROI::ext_start_bin/ext_end_bin`
uninitialized (always set by `ExtendROIs` first); `BreakROI` `[205]` stack
arrays (`r_max_npeaks` default 200).

## 3. Build (SL7 container, sbndbuild03)

The production chain is `sbndcode v10_14_02_0x -> larwirecell v10_01_2x -> wirecell v0_32_1`
(e26:prof). To get **drop-in** libraries, 0.32.x is configured exactly like the
UPS recipe (`build-framework-wirecell-ssi-build/build_wirecell.sh`) against the
same products, which `setup sbndcode v10_14_02_03 -q e26:prof` brings in:
gcc v12_1_0, root v6_28_12, boost v1_82_0, spdlog v1_9_2 (bundled fmt -- fine
for 0.32.x; master's `Spdlog.h` rejects it, 0.32.x does not), jsoncpp v1_9_5a,
gojsonnet v0_18_0, tbb v2021_9_0, hdf5 v1_12_2a, libtorch v2_1_1b, eigen
v23_08_01, fftw v3_3_10.

    scripts/env-0.32.sh          # the environment (sourced inside SL7)
    scripts/build-wct-0.32.sh    # wcb configure/build/install, prefix /exp/sbnd/app/users/yuhw/opt-0.32.x
    SL7_SETUP=none in-gpvm-sl7.sh bash .../build-wct-0.32.sh all   # log: logs/build-wct-0.32.log

Result and gates (2026-10-02):

| gate | result |
|---|---|
| `WCB_RC=0` | yes; configure found hdf5 (pkg-config) and libtorch; submodules apps aux cfg clus gen hio iface img pgraph pytorch quickhull root sig sigproc sio tbb test util |
| libraries vs cvmfs `wirecell v0_32_1` | 15 `libWireCell*.so` + `libWCPQuickhull.so`; identical set except **no `libWireCellTriton.so`** (triton not set up; not used by SBND DetSim) |
| `NEEDED` of `libWireCellSigProc.so`, `libWireCellAux.so` vs cvmfs | identical |
| `nm -D -u ... __libc_single_threaded` | 0 (built inside SL7) |
| RPATH into `build/` (doc sec 1a) | 17 libs/bins + 8 `wcdoctest-*` stripped with patchelf to `opt-0.32.x/lib:<cvmfs deps>`; with `build/` hidden, `ldd` 0 not found, 0 WireCell deps outside `opt-0.32.x/lib` |
| `strings libWireCellSigProc.so \| grep -c r_erase_stale_contained` | 2 |
| `wire-cell --version` | `0.32.1-4-g70140ede` |

**larwirecell: not rebuilt, by measurement, not by assumption.** The diff
touches no header that larwirecell includes (sec 1), `libWireCellIface.so` /
`libWireCellUtil.so` symbols larwirecell links against are unchanged, and the
cvmfs `larwirecell v10_01_26_01` libraries load the patched WCT libraries
through `LD_LIBRARY_PATH` with every `libWireCell*` resolved from
`opt-0.32.x/lib` (`ldlibs.txt` in each run directory, from `LD_DEBUG=libs`).
If the release is cut as a UPS `wirecell v0_32_2`, larwirecell needs only a
table-file rebuild, not a code change.

**Unit tests** (`logs/doctest-sigproc-aux.log`): `wcdoctest-sigproc` 2/2 cases,
10/10 assertions (`ROI_refinement CleanUpInductionROIs contained_rois stale keys`,
`OmnibusSigProc r_erase_stale_contained defaults to true` -- on 0.32.x these are
the whole sigproc doctest suite); `wcdoctest-aux` (FftwDFT) 14/14 cases, 87856
assertions.

## 4. Validation: repeated `standard_detsim_sbnd.fcl`

- Input: `/exp/sbnd/data/users/yuhw/flare/twester/scratch/sbnd_gen2_full/g4/000000/000000/g4-gen-04cb-888a-ffaf-5808.root`
  (9 events, the largest of the 20 Gen-2 g4 files there; 20 files, 1-9 events each, 88 total = the #31 sample).
- Job: `lar -c standard_detsim_sbnd.fcl -s <g4> -n 9` under
  `sbndcode v10_14_02_03 -q e26:prof` (WCT engine `TbbFlow`, `roi=both`, DNN-ROI,
  default `lar` thread count), 6 repeats **concurrently** per arm on sbndbuild03,
  the two arms overlapping (load ~25-50 on 64 cores), i.e. a noisy heap/thread
  environment. Arms:
  - **control** `control-cvmfs-0.32.1`: the cvmfs `wirecell v0_32_1` libraries as production runs them;
  - **patched** `patched-0.32.x-70140ede`: `LD_LIBRARY_PATH=opt-0.32.x/lib:...`, everything else identical.
- Outputs: `/exp/sbnd/data/users/yuhw/wct-0.32.x-randomness/<arm>/rep<k>/{detsim.root,lar.log,ldlibs.txt,run.txt}`.
- Comparison: `scripts/compare_runs.py` (host, `wire-cell-python/venv` uproot;
  reuses #31's `wirebytes.py`): per event and product, SHA-256 of the
  decompressed `recob::Wires_simtpc2d_<p>_DetSim.obj` basket (one basket per
  event, asserted), runs grouped into distinct states; for differing states the
  baskets are decoded and the number of differing channels, channels whose ROI
  list changed, differing samples and max|d| are reported.

Scripts: `scripts/run-detsim.sh` (one job), `scripts/repeat-detsim.sh` (N concurrent).

### Results

Per-event detail: `logs/compare-<arm>.txt` (local). All 12 jobs `rc=0`;
34 min wall and 6.5 GB peak RSS per job under the shared load. `ldlibs.txt`
confirms the control loaded every `libWireCell*.so` from cvmfs
`wirecell/v0_32_1` and the patched arm from `opt-0.32.x/lib`, both with
`libWireCellLarsoft.so` from cvmfs `larwirecell v10_01_26_01`.

**Control (cvmfs 0.32.1), 6 runs x 9 events** -- the production symptom reproduces:

| product | events identical in all 6 runs | events with >1 state | states per differing event | differing channels (vs run 0) |
|---|---|---|---|---|
| dnnsp | 6/9 | **3/9** | 2, 2, 2 | 1-5 channels, all **TPC0 U** (614; 767 828 831; 147 882 905 906 914), ROI list changed, max\|d\| 0.8-2.6 |
| gauss | 3/9 | **6/9** | 2, 3, 5, 4, 4, 3 | 1-9 channels, all **V** (TPC0 and TPC1), ROI list changed in all but one, max\|d\| 0.02-15.6 |
| wiener | 3/9 | **6/9** | same events and channels as gauss | max\|d\| 0.2-20.3 |

- gauss and wiener always flip together and only on V, dnnsp flips only on U,
  never in the same event as gauss/wiener: exactly the #31 / doc 127 signature
  (stale `contained_rois` key for V; the FFTW plan-cache alignment bit for the
  rest).
- Event 4 (RSE 1/9/11) has 5 distinct gauss states in 6 runs; the "common"
  state is never guaranteed.

**Patched (0.32.x `70140ede`), 6 runs x 9 events** -- byte-identical:

| product | events identical in all 6 runs | events with >1 state |
|---|---|---|
| dnnsp | **9/9** | 0/9 |
| gauss | **9/9** | 0/9 |
| wiener | **9/9** | 0/9 |

Same 9 events, same node, same concurrent load as the control (the two arms
overlapped in time), 54 per-event SHA-256 comparisons per product, one state
each. `compare-patched-0.32.x-70140ede.txt`.

**Patched vs legacy output is NOT byte-identical, by design** (`47d16673`
changes the FFTW plans: `FFTW_UNALIGNED` selects a different codelet, so
every FFT result moves at the ULP level; doc 127's "fixed == legacy majority
state" was measured with the stale-key fix alone, on the same plans).
`compare-control-vs-patched.txt`, `diff-magnitude-control-vs-patched.txt`
(control run 0 vs patched run 0, 9 events):

| product | in-ROI samples | differing | of which \|d\| < 0.01 | 0.01 <= \|d\| < 0.1 | \|d\| >= 0.1 | channels with a changed ROI list (per event) |
|---|---|---|---|---|---|---|
| dnnsp | 2.62 M | 67.6 % | 66.7 % (float noise) | 0.18 % | **0.04 %** (1143 samples, max 20.6) | 558-1310 of 11276 |
| gauss | 2.97 M | 0.55 % | 0 (values are stored rounded) | 0.51 % | **0.04 %** (1231 samples, max 23.2) | 4-11 |
| wiener | 2.45 M | 0.80 % | 0 | 0.75 % | **0.05 %** (1184 samples, max 21) | 2-12 |

So the patch moves the output by what the legacy code already moved between
two of its own runs, spread over the whole frame instead of a few channels:
the legacy run-to-run flips (sec above) are 24-450 samples per differing
event with max\|d\| up to 20; legacy-vs-patched is ~130 samples >= 0.1 per
event per product with the same max\|d\|. No systematic shift: the per-event
FrameSaver charge sums (`q=` lines in `lar.log`, control run 0 vs patched run 0,
27 frames) agree to 1e-4 relative or better and the sample counts `n=` to
within 0.03 %, in both directions. Downstream validation (reco1/reco2 on the patched DetSim) is for SBND to
decide; the point of the patch is that a second run now gives the same
answer.

## 5. Status / next

- [x] local `0.32.x` branch with the four cherry-picks (worktree), conflicts resolved, not pushed
- [x] survey of other determinism fixes (sec 2)
- [x] SL7 build against the v0_32_1 product set, gates, doctests
- [x] control vs patched DetSim repeats: control 3/9 (dnnsp) and 6/9 (gauss, wiener) events non-deterministic; patched **9/9 byte-identical on all three** (sec 4)
- [x] Haiwang validated (2026-10-02). Released with master's `waft/release` script (`check` / `version` / `tarball`; the script is not on 0.32.x itself): `version.txt` commit `80ae82fc`, annotated tag `0.32.2` (tag object `2ceaaffe`), `0.32.x` pushed to `WireCell/wire-cell-toolkit`, GitHub release https://github.com/WireCell/wire-cell-toolkit/releases/tag/0.32.2 with `wire-cell-toolkit-0.32.2.tar.gz` (git archive; `wscript` falls back to `version.txt` where `git describe` is unavailable).
- [ ] UPS build `wirecell v0_32_2` (`build_wirecell.sh` with `pkgver=v0_32_2`), larwirecell table bump, sbndcode release -- SBND/SciSoft side
- [ ] optional, not done here: a multi-threaded art run (`lar -j N`) to see whether the shared `gen::Random` race (sec 2) is reachable in production; and SBND's downstream (reco1/reco2) check of the patched DetSim

Scripts: `scripts/{env-0.32.sh,build-wct-0.32.sh,run-detsim.sh,repeat-detsim.sh,compare_runs.py,diff_magnitude.py}`.
Results (tracked): `compare-control-cvmfs-0.32.1.txt`, `compare-patched-0.32.x-70140ede.txt`,
`compare-control-vs-patched.txt`, `diff-magnitude-control-vs-patched.txt`.

## log
- 2026-10-02: issue opened; worktree + cherry-picks; survey; build + gates + doctests; control and patched arms (6 x 9 events each) run and compared: legacy non-deterministic as in production, patched byte-identical. Haiwang validated.
- 2026-10-02 (evening): `0.32.x` pushed, tag `0.32.2`, GitHub release 0.32.2 with the source tarball.
