Skip to main content

memra_engine/
pp.rs

1//! M2 pipeline-parallel N-stage runtime (generalizes the M1 2-stage seam).
2//!
3//! Door: `MEMRA_PP_STAGES=N` (default OFF — unset/0/1 = no behavior change anywhere).
4//! Stage map: N stages over the trunk layers with N-1 cuts. `MEMRA_PP_SPLITS=c1,..,cN-1`
5//! sets the cuts explicitly (strictly increasing, in (0, n_layers)); `MEMRA_PP_SPLIT=<i>`
6//! is the N=2 back-compat spelling; default = even split (cut s = s*n_layers/N).
7//! Placement: `MEMRA_PP_DEVICES=d0,..,dN-1` maps stage s to device ds (default: all on
8//! the primary engine's device).
9//!
10//! M1 history (increments 1-2, merged + hardened on the 8x box 2026-08-02): seam + gate
11//! single-device; then real transport — per-stage streams/events, device placement,
12//! peer-copy boundary (M0: cudaMemcpyPeerAsync beats NCCL 2.8x at PP activation sizes),
13//! per-context PDL module caches, default-mempool peer grants. All five r3 gates PASS
14//! bit-identical (receipts ~/receipts/m1-pp2/ on <bench-instance>).
15//!
16//! M2 increment 1 (this file): N-STAGE GENERALIZATION — `Pp2Rt` becomes `PpNRt`:
17//!   - `stages`: Vec of per-stage execution homes (device, context, stream, remote Engine);
18//!   - `boundaries`: N-1 boundary runtimes, each with TWO persistent double-buffered slots
19//!     (ev_tx/ev_rx per slot) and its own overlap step counter; transport is selected PER
20//!     BOUNDARY (dtod same-device / cudaMemcpyPeerAsync cross-device by default; opt-in
21//!     `MEMRA_PP_HOST_BOUNCE=1` uses pinned D2H + H2D instead);
22//!   - the default peer transport grants peer + default-mempool access between EVERY distinct
23//!     pair of devices in use. Host bounce skips serving-time grants; its boot diagnostics
24//!     transiently enable peer + pool access, then revoke the pool grants and disable peer access
25//!     before proceeding. Sharded weights plus stage-local auxiliary buffers ensure that no peer
26//!     read can bypass the bounced boundary.
27//!
28//! M2 increment 2 (weight sharding): the loader uploads each stage's layer range THROUGH
29//! that stage's engine (`layer_engine`), so weights land on the device that runs them —
30//! the bring-up peer-read placement dies. `output_norm` + lm head load through the LAST
31//! stage's engine; the embed table stays host-side with stage 0. Split-plane/f16 decode
32//! mirrors are built per layer through the owning stage's engine too (the rp4 mirrors ARE
33//! the decode weights on the q8 path — leaving them on dev0 would fake the kill).
34//! Rollback seam: `MEMRA_PP_SHARD=0` = M1 bring-up placement (all weights on primary,
35//! remote stages peer-read).
36//!
37//! M2 increment 3 (deferred readback — the pipelining seed): `PendingLogits` — the eager
38//! decode arm can END a step without the logits D2H (`decode_step_h_ppn_deferred`): the
39//! logits stay device-resident with a completion event; `wait()` drains them through a
40//! DEDICATED readback stream (waits the event, copies, syncs) so tokens t+1.. keep
41//! enqueuing on the stage streams while token t drains. Per-token math is fully
42//! event-ordered (same slots, same ev_tx/ev_rx chain) — scheduling changes, math does
43//! not; the pipelined replay arm of `ppn-gate` proves bit-identity per step.
44//!
45//! Ownership across a boundary (unchanged from M1):
46//!   - hidden state [n_embd] f32 is the ONLY tensor that crosses;
47//!   - KV/linear-attn cache entries are per-layer: stage s exclusively owns cache state
48//!     for its layer range (and, under MEMRA_PP_DEVICES, allocates it on its device);
49//!   - position/rope state is the scalar `cache.pos` snapshot taken once per step; every stage
50//!     uploads its own position buffer on its own stream (no cross-device position pointer);
51//!   - the embed table lives with stage 0, output_norm + lm head with the last stage.
52//!
53//! THE MULTI-STREAM LAW (why this is safe with cudarc event tracking disabled): all
54//! cross-stage bytes flow through the persistent boundary slots, ordered by ev_tx/ev_rx;
55//! per-stage scratch is allocated AND freed on that stage's stream (stream-ordered); the
56//! async mem pool runs with opportunistic reuse OFF + internal dependencies ON
57//! (memra-runtime), so a block freed on stream A and reused on stream B carries a
58//! driver-inserted dependency. Weights are load-time state no stage stream can precede,
59//! and the step's terminal logits readback (sync D2H, or PendingLogits' event-ordered
60//! readback stream) drains the last stage, whose TX-wait chain transitively drains all.
61//!
62//! Scope: plain eager decode only (generic arm N-stage; gemma4 arm 2-stage). NOT wired:
63//! batch/dc/graph/spec loops and the gemma4-E4B eager arm.
64//!
65//! CORRECTION (pp2-hardening 2026-08-06): this header used to add "(`warn_unwired_once`
66//! fires)" to that list, which was wrong. `warn_unwired_once` has exactly two call sites
67//! and BOTH are gemma4-specific (decode.rs, hybrid_forward.rs) — the batch/dc/graph/spec
68//! loops never warned. Worse, the batched loop did not merely run unsplit: it walked the
69//! whole trunk on the primary stream and, under a sharded cross-device placement,
70//! peer-read every remote stage's weights each step — 28x slower at B=1 with all three
71//! `decode-batch-gate` gates PASSING (peer reads are byte-exact, so only perf broke).
72//! `decode_step_batch` now FAILS CLOSED in that regime via `pp_sharded_cross_device()`
73//! (`MEMRA_PP_ALLOW_UNSPLIT_BATCH=1` = measurement override). "Unwired" for dc/graph/spec
74//! still means "runs unsplit, silently" — audit each before trusting it on a pair.
75
76use std::cell::RefCell;
77use std::marker::PhantomData;
78use std::rc::Rc;
79use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
80use std::sync::{Arc, Mutex, OnceLock, Weak};
81
82use cudarc::driver::{CudaContext, CudaEvent, CudaSlice, CudaStream};
83
84use crate::Engine;
85
86/// Restores the caller's primary CUDA context on every return path, including panic unwind. The
87/// explicit `restore` call preserves the bind error for normal Result propagation; Drop is the
88/// final safety net when a scoped host worker or head-stage callback panics.
89pub(crate) struct PrimaryContextRestore<'a> {
90    engine: &'a Engine,
91    restored: bool,
92}
93
94impl<'a> PrimaryContextRestore<'a> {
95    pub(crate) fn new(engine: &'a Engine) -> Self {
96        Self {
97            engine,
98            restored: false,
99        }
100    }
101
102    pub(crate) fn restore(mut self) -> Result<(), Box<dyn std::error::Error>> {
103        let result = self.engine.ctx().bind_to_thread();
104        self.restored = result.is_ok();
105        result?;
106        Ok(())
107    }
108}
109
110impl Drop for PrimaryContextRestore<'_> {
111    fn drop(&mut self) {
112        if !self.restored {
113            let _ = self.engine.ctx().bind_to_thread();
114        }
115    }
116}
117
118/// Returns the stage fence iff the ppN door is open: `MEMRA_PP_STAGES=N` (N >= 2) with a
119/// valid cut list. The fence has N+1 entries: `[0, c1, .., cN-1, n_layers]`; stage s runs
120/// layers `[fence[s], fence[s+1])`. Reads the environment on every call (gates toggle the
121/// door in-process); the cost is a few getenv per decode step, eager-loop noise.
122pub fn pp_cuts(n_layers: usize) -> Option<Vec<usize>> {
123    let n_st: usize = match std::env::var("MEMRA_PP_STAGES") {
124        Ok(v) if v.is_empty() || v == "0" || v == "1" => return None,
125        Ok(v) => match v.parse::<usize>() {
126            Ok(n) => n,
127            Err(_) => {
128                warn_bad_once(&format!("MEMRA_PP_STAGES={v} unparseable; door stays OFF"));
129                return None;
130            }
131        },
132        Err(_) => return None,
133    };
134    if n_st < 2 || n_st > n_layers {
135        warn_bad_once(&format!(
136            "MEMRA_PP_STAGES={n_st} outside [2, n_layers={n_layers}]; door stays OFF"
137        ));
138        return None;
139    }
140    let mut fence = Vec::with_capacity(n_st + 1);
141    fence.push(0usize);
142    if let Ok(s) = std::env::var("MEMRA_PP_SPLITS") {
143        let parts: Result<Vec<usize>, _> =
144            s.split(',').map(|p| p.trim().parse::<usize>()).collect();
145        match parts {
146            Ok(cuts) if cuts.len() == n_st - 1 => fence.extend(cuts),
147            _ => {
148                warn_bad_once(&format!(
149                    "MEMRA_PP_SPLITS={s} invalid (want {} comma-separated cuts); door stays OFF",
150                    n_st - 1
151                ));
152                return None;
153            }
154        }
155    } else if let Ok(v) = std::env::var("MEMRA_PP_SPLIT") {
156        // N=2 back-compat spelling. With N>2 a single split is ambiguous — fail the door
157        // loudly rather than guess (a silent even-split would fake a gate config).
158        if n_st != 2 {
159            warn_bad_once(&format!(
160                "MEMRA_PP_SPLIT={v} set with MEMRA_PP_STAGES={n_st}; use MEMRA_PP_SPLITS \
161                 for N>2 — door stays OFF"
162            ));
163            return None;
164        }
165        match v.parse::<usize>() {
166            Ok(c) => fence.push(c),
167            Err(_) => {
168                warn_bad_once(&format!("MEMRA_PP_SPLIT={v} unparseable; door stays OFF"));
169                return None;
170            }
171        }
172    } else {
173        for s in 1..n_st {
174            fence.push(s * n_layers / n_st);
175        }
176    }
177    fence.push(n_layers);
178    for w in fence.windows(2) {
179        if w[0] >= w[1] {
180            warn_bad_once(&format!(
181                "pp stage fence {fence:?} not strictly increasing over [0, {n_layers}]; \
182                 door stays OFF"
183            ));
184            return None;
185        }
186    }
187    Some(fence)
188}
189
190/// N=2 back-compat view of the door (the gemma4 arm and `pp2-gate` are 2-stage): `Some(cut)`
191/// iff the door is open with EXACTLY two stages.
192pub fn pp2_split(n_layers: usize) -> Option<usize> {
193    pp_cuts(n_layers).filter(|f| f.len() == 3).map(|f| f[1])
194}
195
196/// The stage that owns layer `il` under `fence` (see `pp_cuts`).
197pub fn stage_of(fence: &[usize], il: usize) -> usize {
198    debug_assert!(fence.len() >= 2);
199    match fence[1..fence.len() - 1].binary_search(&il) {
200        // fence[1..][k] == il means il is the FIRST layer of stage k+1
201        Ok(k) => k + 1,
202        Err(k) => k,
203    }
204}
205
206/// MEMRA_PP_STREAMS=0: rollback to the increment-1 same-stream seam (boundary = two plain
207/// dtod copies on the ambient compute stream, no per-stage streams/events/devices).
208pub fn pp2_streams_off() -> bool {
209    matches!(std::env::var("MEMRA_PP_STREAMS").as_deref(), Ok("0"))
210}
211
212/// True iff the ppN door would put TWO OR MORE stage streams on ONE device (devices
213/// unset = all stages on the primary; or an explicit placement with a repeated device).
214/// The deferred-readback (pipelined) arm is REFUSED in this regime: the 2026-08-02 x20
215/// soak record — singledev pipelined 13/20 PASS default, 7 failures each diverging at a
216/// different step (timing-race signature); MEMRA_PDL=0 went 20/20 on one soak but a
217/// second same-config soak on the auto-gated build failed 2/20 (n2) and battery-4 failed
218/// n4 — so PDL narrows the window without closing it, and the true root cause (same
219/// Engine kernels concurrent on two streams of one device) is NOT fixed by any flag yet.
220/// Cross-device pipelined (one stage stream per device) is 23/23 clean post-fix. Refuse
221/// loudly rather than return silently-wrong logits. Env-only read (callable pre-runtime).
222pub fn pp_multi_stream_same_device() -> bool {
223    let stages_open = std::env::var("MEMRA_PP_STAGES")
224        .map(|v| v.parse::<usize>().map(|n| n >= 2).unwrap_or(false))
225        .unwrap_or(false);
226    let devices = std::env::var("MEMRA_PP_DEVICES")
227        .ok()
228        .filter(|v| !v.is_empty());
229    if (!stages_open && devices.is_none()) || pp2_streams_off() {
230        return false;
231    }
232    match devices {
233        None => true, // door open, no placement: every stage stream lands on the primary
234        Some(s) => pp_devices_repeat(&s),
235    }
236}
237
238fn pp_devices_repeat(raw: &str) -> bool {
239    let Ok(mut devices) = raw
240        .split(',')
241        .map(|part| part.trim().parse::<usize>())
242        .collect::<Result<Vec<_>, _>>()
243    else {
244        // Runtime construction will return the precise parse error. Treat malformed input as
245        // unsafe here so a second environment interpretation can never admit a wavefront.
246        return true;
247    };
248    let count = devices.len();
249    devices.sort_unstable();
250    devices.dedup();
251    devices.len() < count
252}
253
254/// True iff the ppN door is open AND the placement spans 2+ DISTINCT devices AND the
255/// per-stage sharded loader is on — i.e. some layers' weights live on a device other than
256/// the primary. Any path that walks the WHOLE trunk on one stream in this regime reads
257/// those weights over PCIe every step. Env-only read (callable pre-runtime).
258///
259/// Measured cost of doing that (pp2-hardening 2026-08-06, 2x RTX PRO 6000, PCIe Gen5 x16
260/// P2P, decode-batch-bench q9, N=5 interleaved, `research/pp2-hardening-20260806`):
261/// **B=1 7.4 vs 208.9 tok/s (28x), B=4 29.8 vs 491.3 (16.5x), B=8 47.4 vs 657.0 (13.9x)**.
262/// The same sweep with `MEMRA_PP_SHARD=0` (weights all home) returns 178.5/491.1/656.6 —
263/// identical to the single-device door-open arm — so the entire cliff is the peer read,
264/// not the door and not the placement plumbing. Exactness is NOT the issue: peer reads
265/// return identical bytes and every `decode-batch-gate` gate PASSED on this config, which
266/// is precisely why it needs a refusal rather than a gate.
267pub fn pp_sharded_cross_device() -> bool {
268    let stages_open = std::env::var("MEMRA_PP_STAGES")
269        .map(|v| v.parse::<usize>().map(|n| n >= 2).unwrap_or(false))
270        .unwrap_or(false);
271    // MEMRA_PP_STREAMS=0 (2026-08-06, pp2-batch): the same-stream rollback seam ALSO turns
272    // the sharded loader off — `layer_engine` returns the primary engine whenever
273    // `pp2_streams_off()`, and `new_cache` skips `Cache::new_ppn` on the same condition. So
274    // in that regime every weight and every cache is home on the primary and an unsplit walk
275    // peer-reads NOTHING. Without this term the guard refused that config too: a spurious
276    // refusal of a placement that is sound and full-speed. Found wiring the batched pp arm.
277    if !stages_open || pp_shard_off() || pp2_streams_off() {
278        return false;
279    }
280    match pp2_devices_env() {
281        None => false, // no placement: every stage is the primary device, nothing remote
282        Some(s) => {
283            let mut v: Vec<&str> = s.split(',').map(|p| p.trim()).collect();
284            v.sort_unstable();
285            v.dedup();
286            v.len() >= 2
287        }
288    }
289}
290
291/// The shared fail-closed guard for EVERY decode path that has no pp stage split.
292/// Returns `Err` iff `pp_sharded_cross_device()` — i.e. the caller would walk the whole
293/// trunk on one stream while some layers' weights live on another device, peer-reading
294/// them every step. `path` names the refusing function so the operator knows which loop
295/// they hit; `alt` names the working alternative for that loop.
296///
297/// One helper rather than four copies because the audit found FOUR paths with the same
298/// hole (`decode_step_batch`, `decode_step_dc`, the graph capture that wraps dc, and
299/// `decode_step_t*` verify), and a per-path copy is how one gets missed on the next
300/// addition. Override: `MEMRA_PP_ALLOW_UNSPLIT_BATCH=1` (one door for all of them —
301/// they are the same measurement question).
302pub fn refuse_unsplit_if_remote(path: &str, alt: &str) -> Result<(), Box<dyn std::error::Error>> {
303    if pp_host_bounce_active() {
304        return Err(format!(
305            "{path}: refused with MEMRA_PP_HOST_BOUNCE=1 on sharded cross-device PP — \
306             this unsplit path peer-reads remote weights, while host bounce covers only \
307             explicit stage-boundary transfers. Use {alt}; the \
308             MEMRA_PP_ALLOW_UNSPLIT_BATCH override is unavailable on a broken-peer host."
309        )
310        .into());
311    }
312    if pp_sharded_cross_device()
313        && std::env::var("MEMRA_PP_ALLOW_UNSPLIT_BATCH").as_deref() != Ok("1")
314    {
315        return Err(format!(
316            "{path}: refused with the ppN door open across 2+ devices — this path has no pp \
317             stage split, so it would walk ALL layers on one stream and peer-read every \
318             remote stage's weights each step (measured 28x slower at B=1, 13.9x at B=8 on \
319             a PRO 6000 pair over PCIe Gen5 x16 P2P; research/pp2-hardening-20260806). \
320             Exactness is unaffected — peer reads return identical bytes and the exactness \
321             gates PASS on this config — which is exactly why it must refuse instead of \
322             being caught by a gate. Fixes, in order: {alt}; or MEMRA_PP_SHARD=0 (all \
323             weights home on the primary — full speed, forfeits the capacity PP-2 exists \
324             for); or close the pp door. MEMRA_PP_ALLOW_UNSPLIT_BATCH=1 overrides for \
325             measurement."
326        )
327        .into());
328    }
329    Ok(())
330}
331
332/// MEMRA_BATCH_PP=0: rollback/A-B seam for the BATCHED stage split (pp2-batch 2026-08-06).
333/// Default ON — with the ppN door open the batched decode step takes its own stage split
334/// (`decode_step_batch_ppn`) exactly as the eager step does. Setting 0 sends the batched
335/// path back through the unsplit body, which under a sharded cross-device placement is
336/// then caught by `refuse_unsplit_if_remote` (the 28x peer-read regime) rather than run
337/// silently. Exists so the bit-identity gate can A/B split vs unsplit IN ONE PROCESS
338/// against the same loaded weights — read per step, never memoized, for that reason.
339pub fn batch_pp_on() -> bool {
340    std::env::var("MEMRA_BATCH_PP").as_deref() != Ok("0")
341}
342
343/// Largest PP wavefront admitted by the RTX PRO 6000 product shape. The underlying placement
344/// runtime remains N-stage, but the serving wave scheduler is deliberately bounded to the 2--4
345/// card surface that has a concrete qualification plan.
346pub const PP_WAVE_MAX_STAGES: usize = 4;
347
348/// Strict opt-in for the PP3/PP4 request wavefront. PP2 keeps its independently qualified
349/// `MEMRA_DUAL_PP` default; a new stage count never inherits that default without its own target
350/// receipts.
351pub fn pp_wave_on_value(value: Option<&str>) -> Result<bool, &'static str> {
352    match value {
353        None | Some("0") => Ok(false),
354        Some("1") => Ok(true),
355        Some(_) => Err("MEMRA_PP_WAVE must be 0 or 1"),
356    }
357}
358
359pub fn pp_wave_on() -> Result<bool, &'static str> {
360    match std::env::var_os("MEMRA_PP_WAVE") {
361        None => pp_wave_on_value(None),
362        Some(value) => value
363            .to_str()
364            .ok_or("MEMRA_PP_WAVE must be valid UTF-8 and exactly 0 or 1")
365            .and_then(|value| pp_wave_on_value(Some(value))),
366    }
367}
368
369/// Split one scheduler tick into at most one wave per stage. Earlier waves carry the remainder so
370/// priority order is preserved, every row appears exactly once, and the largest wave is
371/// `ceil(batch / min(batch, stages))`.
372pub fn pp_wave_ranges(batch: usize, stages: usize) -> Vec<(usize, usize)> {
373    if batch == 0 || stages == 0 {
374        return Vec::new();
375    }
376    let waves = batch.min(stages);
377    let base = batch / waves;
378    let extra = batch % waves;
379    let mut out = Vec::with_capacity(waves);
380    let mut start = 0usize;
381    for wave in 0..waves {
382        let len = base + usize::from(wave < extra);
383        out.push((start, start + len));
384        start += len;
385    }
386    debug_assert_eq!(start, batch);
387    out
388}
389
390/// Cells on one pipeline anti-diagonal, returned as `(wave, stage)`. Cells in a diagonal never
391/// share a wave (request/cache state) or a stage (Engine scratch/stream), so they may be driven by
392/// scoped host threads without reintroducing the shared-Engine race that quarantined the old
393/// deferred PP walker.
394pub fn pp_wave_diagonal(stages: usize, waves: usize, diagonal: usize) -> Vec<(usize, usize)> {
395    if stages == 0 || waves == 0 || diagonal >= stages + waves - 1 {
396        return Vec::new();
397    }
398    let first_stage = diagonal.saturating_sub(waves - 1);
399    let last_stage = diagonal.min(stages - 1);
400    (first_stage..=last_stage)
401        .map(|stage| (diagonal - stage, stage))
402        .collect()
403}
404
405/// Fail-closed topology gate for the unqualified PP3/PP4 wavefront. Native peer transport and one
406/// physical device per stage are required for the first implementation; host bounce and repeated
407/// devices retain the serial PP-N walker.
408pub fn pp_wave_eligibility(
409    stages: usize,
410    double_slot: bool,
411    host_bounce: bool,
412    repeated_device: bool,
413) -> Result<(), &'static str> {
414    if !(3..=PP_WAVE_MAX_STAGES).contains(&stages) {
415        return Err("PP wavefront requires 3 or 4 stages; PP2 is owned by MEMRA_DUAL_PP");
416    }
417    if !double_slot {
418        return Err("PP wavefront requires MEMRA_PP_OVERLAP=1 double-buffered boundaries");
419    }
420    if host_bounce {
421        return Err(
422            "PP wavefront is unqualified with MEMRA_PP_HOST_BOUNCE=1; use native peer transport",
423        );
424    }
425    if repeated_device {
426        return Err("PP wavefront requires one distinct CUDA device per stage");
427    }
428    Ok(())
429}
430
431/// The PP3/PP4 scheduler decomposes one serving batch into narrower stage waves. A preserved-BF16
432/// W4A16 artifact therefore needs the row-wise BF16 matvec program: the default f32-expanded
433/// cuBLAS path is batch-width dependent, and HY3 B=4/B=8 changed every logit row when wave cells
434/// narrowed to B=1/B=2. `MEMRA_BF16_MMV=1` keeps the same checkpoint BF16 values and runs one
435/// deterministic per-row reduction program at every width.
436pub const PP_WAVE_W4A16_BF16_REFUSAL: &str = "PP wavefront for a W4A16 artifact with preserved BF16 non-expert weights requires \
437     MEMRA_BF16_MMV=1; without the row-wise BF16 program, wave batch-width decomposition changes \
438     logits. Keep MEMRA_PP_WAVE=0 or enable and qualify MEMRA_BF16_MMV=1";
439
440pub fn pp_wave_numeric_eligibility(
441    weight_only_nvfp4: bool,
442    bf16_mmv: bool,
443) -> Result<(), &'static str> {
444    if weight_only_nvfp4 && !bf16_mmv {
445        return Err(PP_WAVE_W4A16_BF16_REFUSAL);
446    }
447    Ok(())
448}
449
450/// One routing predicate shared by decode and prime: requesting the wave door without the
451/// double-slot policy is the documented serial rollback, not a late per-request refusal.
452pub fn pp_wave_route_enabled(
453    requested: bool,
454    overlap: bool,
455    stages: usize,
456    work_items: usize,
457) -> bool {
458    requested && overlap && (3..=PP_WAVE_MAX_STAGES).contains(&stages) && work_items >= 2
459}
460
461static PP_WAVE_ACTIVE_CELLS: AtomicUsize = AtomicUsize::new(0);
462static PP_WAVE_OVERLAPS: AtomicUsize = AtomicUsize::new(0);
463static PP_WAVE_TICKS: AtomicUsize = AtomicUsize::new(0);
464static PP_WAVE_CELLS: AtomicUsize = AtomicUsize::new(0);
465
466pub(crate) struct PpWaveCellGuard;
467
468/// Mark one host-driven PP3/PP4 cell active. An overlap increment is proof that two distinct
469/// stage walkers were simultaneously inside their model range; enqueue order alone is not proof
470/// for MoE paths whose router readback synchronizes the host.
471pub(crate) fn enter_pp_wave_cell() -> PpWaveCellGuard {
472    let active = PP_WAVE_ACTIVE_CELLS.fetch_add(1, Ordering::AcqRel);
473    if active > 0 {
474        PP_WAVE_OVERLAPS.fetch_add(1, Ordering::Relaxed);
475    }
476    PP_WAVE_CELLS.fetch_add(1, Ordering::Relaxed);
477    PpWaveCellGuard
478}
479
480impl Drop for PpWaveCellGuard {
481    fn drop(&mut self) {
482        let active = PP_WAVE_ACTIVE_CELLS.fetch_sub(1, Ordering::AcqRel);
483        debug_assert!(active > 0, "PP wave active-cell counter underflow");
484    }
485}
486
487pub(crate) fn record_pp_wave_tick() {
488    PP_WAVE_TICKS.fetch_add(1, Ordering::Relaxed);
489}
490
491/// `(completed ticks, entered cells, observed concurrent-cell overlaps)`.
492pub fn pp_wave_snapshot() -> (usize, usize, usize) {
493    (
494        PP_WAVE_TICKS.load(Ordering::Relaxed),
495        PP_WAVE_CELLS.load(Ordering::Relaxed),
496        PP_WAVE_OVERLAPS.load(Ordering::Relaxed),
497    )
498}
499
500/// MEMRA_DUAL_PP three-state mode for the dual-active PP-2 batched decode path.
501/// Default ON (owner flip 2026-08-11) after the box1 PRO-pair re-gate: correctness
502/// bit-identity B=1..5, servestress no-thrash, 10-boot soak 929/929 golden matches with
503/// 0 slot collisions across 9123 pairs (research/dualpp2-20260811/RESULTS-regate.md), plus
504/// the dualpp1 c>=8 interleaved perf floor (+20.753% minimum,
505/// research/dualpp1-20260811/RESULTS.md).
506///
507/// The three states carry different failure semantics on purpose:
508/// - `Off` (`MEMRA_DUAL_PP=0`): the serial rollback seam. Overlap also follows OFF unless
509///   `MEMRA_PP_OVERLAP` is set explicitly, so one flag restores the exact pre-flip naked path.
510/// - `Forced` (`MEMRA_DUAL_PP=1`): the pre-flip explicit request. A placement that cannot
511///   run dual (single-slot boundary, host bounce, non-PP-2 fence) REFUSES with the binding
512///   quoted reason before any token or cache advance — the gate negative cells pin this.
513/// - `Auto` (unset): the flipped default. Dual runs where the re-gate validated it
514///   (PP-2 fence, double-slot, peer transport, B>=2) and silently degrades to the serial
515///   PP-N walker everywhere else — naked PP-3 serving and the MEMRA_PP_HOST_BOUNCE=1
516///   broken-peer escape hatch must keep decoding, not refuse.
517#[derive(Clone, Copy, PartialEq, Eq, Debug)]
518pub enum DualPpMode {
519    Off,
520    Forced,
521    Auto,
522}
523
524/// Pure resolution for MEMRA_DUAL_PP, split from the env read so the flip regression tests
525/// cannot race parallel test threads on process env.
526pub fn dual_pp_mode_resolve(v: Option<&str>) -> DualPpMode {
527    match v {
528        Some("0") => DualPpMode::Off,
529        Some("1") => DualPpMode::Forced,
530        _ => DualPpMode::Auto,
531    }
532}
533
534pub fn dual_pp_mode() -> DualPpMode {
535    dual_pp_mode_resolve(std::env::var("MEMRA_DUAL_PP").ok().as_deref())
536}
537
538/// True when the dual-active door is open (Forced or Auto). Read per step so the
539/// model-level gate can replay serial and waved arms against one loaded checkpoint.
540pub fn dual_pp_on() -> bool {
541    dual_pp_mode() != DualPpMode::Off
542}
543
544/// Engine-entry routing for the dual-active path, kept pure for the flip regression
545/// tests. `Forced` routes every B>=2 PP-2 call into `decode_step_batch_dual` even when
546/// the placement cannot run it, so the binding refusals stay reachable and loud.
547/// `Auto` routes only the exact re-gated regime and leaves everything else on the serial
548/// PP-N walker. `dual_pp_eligibility` remains behind this as defense in depth.
549pub fn dual_pp_route(
550    mode: DualPpMode,
551    batch: usize,
552    stages: usize,
553    double_slot: bool,
554    host_bounce: bool,
555) -> bool {
556    if batch < 2 {
557        return false;
558    }
559    match mode {
560        DualPpMode::Off => false,
561        DualPpMode::Forced => true,
562        DualPpMode::Auto => stages == 2 && double_slot && !host_bounce,
563    }
564}
565
566/// Binding-amendment refusal text. The negative gate quotes this exact line and requires the
567/// decode call to return before producing a token or advancing a cache.
568pub const DUAL_PP_SINGLE_SLOT_REFUSAL: &str = "decode_step_batch_dual: refused: PP boundary is single-slot; set MEMRA_PP_OVERLAP=1 so both alternating boundary slots are prepared before dual-active decode";
569pub const DUAL_PP_HOST_BOUNCE_REFUSAL: &str = "decode_step_batch_dual: refused: MEMRA_PP_HOST_BOUNCE=1 is unvalidated for dual-active decode; disable MEMRA_DUAL_PP or use peer transport";
570
571/// Pure schedule policy shared by the runtime and kernel-check manifest cells. A single row
572/// has no second wave and must stay on the serial PP-N walker.
573#[allow(clippy::manual_div_ceil)] // allow: explicit (n + k - 1) / k is the load-bearing sizing form, kept textually identical to the kernel-side math
574pub fn dual_pp_wave_mid(batch: usize) -> Option<usize> {
575    (batch >= 2).then_some((batch + 1) / 2)
576}
577
578/// Fail-closed eligibility check kept pure so the negative manifest cell cannot accidentally
579/// initialize CUDA state. Slot preparation itself remains `PpNRt::prepare_overlap_slots`.
580pub fn dual_pp_eligibility(
581    stages: usize,
582    double_slot: bool,
583    host_bounce: bool,
584) -> Result<(), &'static str> {
585    if stages != 2 {
586        return Err(
587            "decode_step_batch_dual: refused: dual-active decode requires exactly two PP stages",
588        );
589    }
590    if !double_slot {
591        return Err(DUAL_PP_SINGLE_SLOT_REFUSAL);
592    }
593    if host_bounce {
594        return Err(DUAL_PP_HOST_BOUNCE_REFUSAL);
595    }
596    Ok(())
597}
598
599/// Liveness is counted only while the two host-driven decode layer walkers are both active.
600/// Enqueue order is not proof for Step: its router readback synchronizes the issuing thread.
601static DUAL_PP_OVERLAPS: AtomicUsize = AtomicUsize::new(0);
602static DUAL_PP_ACTIVE_STAGES: AtomicUsize = AtomicUsize::new(0);
603static DUAL_PP_STAGE_NS: [AtomicU64; 4] = [
604    AtomicU64::new(0),
605    AtomicU64::new(0),
606    AtomicU64::new(0),
607    AtomicU64::new(0),
608];
609static DUAL_PP_STAGE_SAMPLES: [AtomicUsize; 4] = [
610    AtomicUsize::new(0),
611    AtomicUsize::new(0),
612    AtomicUsize::new(0),
613    AtomicUsize::new(0),
614];
615static DUAL_PP_TIMING_DROPPED: AtomicUsize = AtomicUsize::new(0);
616static DUAL_PP_SLOT_PAIRS: AtomicUsize = AtomicUsize::new(0);
617static DUAL_PP_SLOT_USES: [AtomicUsize; 2] = [AtomicUsize::new(0), AtomicUsize::new(0)];
618static DUAL_PP_SLOT_COLLISIONS: AtomicUsize = AtomicUsize::new(0);
619
620pub const DUAL_PP_STAGE_NAMES: [&str; 4] = [
621    "wave_a_stage0",
622    "wave_a_stage1",
623    "wave_b_stage0",
624    "wave_b_stage1",
625];
626
627pub fn dual_pp_overlaps() -> usize {
628    DUAL_PP_OVERLAPS.load(Ordering::Relaxed)
629}
630
631/// Record the two boundary slots selected for one dual-active wave pair. A same-slot pair is
632/// rejected by the caller before wave B can consume a residual; the collision counter makes that
633/// fail-closed path observable to the detached soak instead of relying only on log scanning.
634pub(crate) fn record_dual_pp_slot_pair(slot_a: usize, slot_b: usize) -> bool {
635    debug_assert!(slot_a < DUAL_PP_SLOT_USES.len());
636    debug_assert!(slot_b < DUAL_PP_SLOT_USES.len());
637    if slot_a == slot_b {
638        DUAL_PP_SLOT_COLLISIONS.fetch_add(1, Ordering::Relaxed);
639        return false;
640    }
641    DUAL_PP_SLOT_USES[slot_a].fetch_add(1, Ordering::Relaxed);
642    DUAL_PP_SLOT_USES[slot_b].fetch_add(1, Ordering::Relaxed);
643    DUAL_PP_SLOT_PAIRS.fetch_add(1, Ordering::Relaxed);
644    true
645}
646
647/// `(completed wave pairs, [slot 0 uses, slot 1 uses], rejected same-slot pairs)`.
648pub fn dual_pp_slot_snapshot() -> (usize, [usize; 2], usize) {
649    (
650        DUAL_PP_SLOT_PAIRS.load(Ordering::Relaxed),
651        std::array::from_fn(|i| DUAL_PP_SLOT_USES[i].load(Ordering::Relaxed)),
652        DUAL_PP_SLOT_COLLISIONS.load(Ordering::Relaxed),
653    )
654}
655
656/// CUDA-event timing is a diagnostic-only process door. The scored N=5 block runs without
657/// it; the companion box1 diagnostic process enables it and exports cumulative per-wave
658/// stage spans through `/metrics`.
659pub fn dual_pp_timing_on() -> bool {
660    static ON: OnceLock<bool> = OnceLock::new();
661    *ON.get_or_init(|| std::env::var("MEMRA_DUAL_PP_TIMING").as_deref() == Ok("1"))
662}
663
664pub(crate) fn record_dual_pp_stage_ms(stage: usize, ms: f32) {
665    assert!(
666        stage < DUAL_PP_STAGE_NS.len(),
667        "dual PP timing stage out of range"
668    );
669    let ns = (f64::from(ms) * 1_000_000.0).round() as u64;
670    DUAL_PP_STAGE_NS[stage].fetch_add(ns, Ordering::Relaxed);
671    DUAL_PP_STAGE_SAMPLES[stage].fetch_add(1, Ordering::Relaxed);
672}
673
674/// Timing is diagnostic only: a CUDA event that is not ready (or otherwise fails) must not
675/// change decode control flow. Count and warn once, then leave the scored-path result intact.
676pub(crate) fn record_dual_pp_timing_drop(context: &str, err: &dyn std::fmt::Display) {
677    let previous = DUAL_PP_TIMING_DROPPED.fetch_add(1, Ordering::Relaxed);
678    if previous == 0 {
679        eprintln!(
680            "[dual-pp] WARN: skipped diagnostic timing sample at {context}: {err}; decode continues"
681        );
682    }
683}
684
685pub(crate) fn record_dual_pp_stage_result<E: std::fmt::Display>(
686    stage: usize,
687    elapsed: Result<f32, E>,
688) {
689    match elapsed {
690        Ok(ms) => record_dual_pp_stage_ms(stage, ms),
691        Err(err) => record_dual_pp_timing_drop(DUAL_PP_STAGE_NAMES[stage], &err),
692    }
693}
694
695pub fn dual_pp_timing_dropped() -> usize {
696    DUAL_PP_TIMING_DROPPED.load(Ordering::Relaxed)
697}
698
699/// `(total_nanoseconds, samples)` for wave-A stage0/stage1 then wave-B stage0/stage1.
700pub fn dual_pp_timing_snapshot() -> ([u64; 4], [usize; 4]) {
701    (
702        std::array::from_fn(|i| DUAL_PP_STAGE_NS[i].load(Ordering::Relaxed)),
703        std::array::from_fn(|i| DUAL_PP_STAGE_SAMPLES[i].load(Ordering::Relaxed)),
704    )
705}
706
707pub(crate) struct DualPpStageGuard;
708
709pub(crate) fn enter_dual_pp_stage() -> DualPpStageGuard {
710    let active = DUAL_PP_ACTIVE_STAGES.fetch_add(1, Ordering::AcqRel);
711    if active > 0 {
712        DUAL_PP_OVERLAPS.fetch_add(1, Ordering::Relaxed);
713    }
714    DualPpStageGuard
715}
716
717impl Drop for DualPpStageGuard {
718    fn drop(&mut self) {
719        let active = DUAL_PP_ACTIVE_STAGES.fetch_sub(1, Ordering::AcqRel);
720        debug_assert!(active > 0, "dual PP active-stage counter underflow");
721    }
722}
723
724/// MEMRA_PRIME_PP=0: rollback/A-B seam for the PRIME (chunked prefill) stage split
725/// (lane/pp-leverb 2026-08-08). Default ON — with the ppN door open the chunked prime takes
726/// its own per-stage range walk exactly as the eager/batched/verify steps do. Setting 0 sends
727/// prime back through the unsplit whole-trunk walk. NOTE: unlike batch/dc/graph/spec, prime
728/// keeps NO `refuse_unsplit_if_remote` — its unsplit walk over a sharded placement is the
729/// measured 22% amortized peer-read tax (research/pp-prefill-20260807 anatomy: m=4096
730/// amortizes the weight reads), not the decode 28x cliff, and the unsplit walk IS the
731/// split-vs-unsplit gate's reference arm (`prime-split-gate`), so it must stay callable.
732/// Read per call, never memoized (the gate A/Bs both arms in one process).
733pub fn prime_pp_on() -> bool {
734    std::env::var("MEMRA_PRIME_PP").as_deref() != Ok("0")
735}
736
737/// MEMRA_PRIME_PIPE=0: rollback/A-B seam for the PP-2 PRIME CHUNK PIPELINE
738/// (lane/cx-pipeline-prime 2026-08-08). Default ON when the prime stage split is live;
739/// setting 0 keeps the serial per-chunk stage walk. Read per prime call so the exactness
740/// gate can replay both schedules against one loaded model.
741pub fn prime_pipe_on() -> bool {
742    std::env::var("MEMRA_PRIME_PIPE").as_deref() != Ok("0")
743}
744
745/// SPLIT-LIVENESS COUNTER for the prime stage split: bumped ONCE per prime chunk that
746/// actually executed the per-stage walk. The `prime-split-gate` requires this to ADVANCE
747/// during its split arm — bit-identity of two identical UNSPLIT walks is vacuous, so a gate
748/// that only compared bits would go green while the walker doesn't exist. With the counter,
749/// the gate is RED until the walker lands (the tickinv35 pattern: the gate exists and fails
750/// before the mechanism does). Relaxed ordering: single-threaded host issue, count-only.
751pub static PRIME_SPLIT_CHUNKS: AtomicUsize = AtomicUsize::new(0);
752
753/// Read the split-liveness counter (gate-side).
754pub fn prime_split_chunks() -> usize {
755    PRIME_SPLIT_CHUNKS.load(Ordering::Relaxed)
756}
757
758/// PIPELINE-LIVENESS COUNTER: bumped only when a second PP-2 prime stage enters its layer
759/// walker while the other stage's walker is still active. Step's per-layer router readback
760/// synchronizes the host, so enqueue order alone is not liveness: a single host thread can
761/// call stage 0(N+1) before the stage-1 epilogue and still serialize all trunk computation.
762pub static PRIME_PIPE_OVERLAPS: AtomicUsize = AtomicUsize::new(0);
763
764/// Read the prime-pipeline overlap counter (gate-side).
765pub fn prime_pipe_overlaps() -> usize {
766    PRIME_PIPE_OVERLAPS.load(Ordering::Relaxed)
767}
768
769static PRIME_PIPE_ACTIVE_STAGES: AtomicUsize = AtomicUsize::new(0);
770
771pub(crate) struct PrimePipeStageGuard;
772
773/// Mark one host-driven stage walker active. With PP-2, a transition 1 -> 2 proves the
774/// two device walkers overlap in wall time; exactly one transition is counted per pair.
775pub(crate) fn enter_prime_pipe_stage() -> PrimePipeStageGuard {
776    let active = PRIME_PIPE_ACTIVE_STAGES.fetch_add(1, Ordering::AcqRel);
777    if active > 0 {
778        PRIME_PIPE_OVERLAPS.fetch_add(1, Ordering::Relaxed);
779    }
780    PrimePipeStageGuard
781}
782
783impl Drop for PrimePipeStageGuard {
784    fn drop(&mut self) {
785        let active = PRIME_PIPE_ACTIVE_STAGES.fetch_sub(1, Ordering::AcqRel);
786        debug_assert!(active > 0, "prime pipeline active-stage counter underflow");
787    }
788}
789
790/// Step35 cross-request prime liveness counters (lane/cx-prime-batch, 2026-08-08).
791/// The exactness gate requires BOTH to advance: a successful step35 batch alone is not
792/// sufficient under PP-N if it walked the whole sharded trunk on one stream.
793pub static STEP35_PRIME_BATCHES: AtomicUsize = AtomicUsize::new(0);
794pub static STEP35_PRIME_BATCH_SPLITS: AtomicUsize = AtomicUsize::new(0);
795
796pub fn step35_prime_batches() -> usize {
797    STEP35_PRIME_BATCHES.load(Ordering::Relaxed)
798}
799
800pub fn step35_prime_batch_splits() -> usize {
801    STEP35_PRIME_BATCH_SPLITS.load(Ordering::Relaxed)
802}
803
804/// MEMRA_SPEC_PP=0: rollback/A-B seam for the SPEC VERIFY stage split (pp2-spec 2026-08-06).
805/// Default ON — with the ppN door open the verify forward (`decode_step_t_core_ppn`) takes its
806/// own stage split exactly as the eager and batched steps do. Setting 0 sends verify back through
807/// the unsplit trunk walk, which under a sharded cross-device placement is then caught by
808/// `refuse_unsplit_if_remote` (the 28x peer-read regime) rather than running silently. Exists so
809/// the bit-identity gate can A/B split vs unsplit IN ONE PROCESS against the same loaded weights
810/// — read per verify call, never memoized, for that reason.
811pub fn spec_pp_on() -> bool {
812    std::env::var("MEMRA_SPEC_PP").as_deref() != Ok("0")
813}
814
815/// MEMRA_PP_OVERLAP: alternate the double-buffered boundary slots per step (the
816/// pipelining seed). Scheduling structure only, never math. Read per step so gates can
817/// A/B in-process.
818///
819/// Unset follows the dual-PP mode (owner flip 2026-08-11): `Auto` resolves ON — the naked
820/// serve path is the box1 re-gate's dual arm (MEMRA_DUAL_PP=1 MEMRA_PP_OVERLAP=1,
821/// 929/929 golden, 0/9123 slot collisions). `Off` resolves OFF so MEMRA_DUAL_PP=0 alone
822/// restores the exact pre-flip serial naked path. `Forced` resolves OFF so the binding
823/// single-slot refusal of the explicit pre-flip request stays reachable — the
824/// decode-batch-gate negative cell pins and asserts precisely that combination.
825pub fn pp2_overlap() -> bool {
826    pp2_overlap_resolve(
827        std::env::var("MEMRA_PP_OVERLAP").ok().as_deref(),
828        dual_pp_mode(),
829    )
830}
831
832/// Pure resolution for MEMRA_PP_OVERLAP, split from the env read for the flip
833/// regression tests.
834pub fn pp2_overlap_resolve(v: Option<&str>, mode: DualPpMode) -> bool {
835    match v {
836        Some("1") => true,
837        Some(_) => false,
838        None => mode == DualPpMode::Auto,
839    }
840}
841
842/// Broken-peer escape hatch: stage-boundary activations travel through page-locked host
843/// memory instead of `cudaMemcpyPeerAsync`. Default OFF; captured when `PpNRt` is built.
844pub fn pp_host_bounce_on() -> bool {
845    matches!(std::env::var("MEMRA_PP_HOST_BOUNCE").as_deref(), Ok("1"))
846}
847
848/// True when host bounce is the live transport for a sharded cross-device placement.
849/// Callers use this to close paths that still peer-read non-boundary state.
850pub fn pp_host_bounce_active() -> bool {
851    (pp_host_bounce_on() || PEER_RUNTIME_HOST_BOUNCE.load(Ordering::Acquire))
852        && pp_sharded_cross_device()
853}
854
855/// M2 increment 2 rollback seam: MEMRA_PP_SHARD=0 = the M1 bring-up placement (all
856/// weights upload through the primary engine; remote stages peer-read). Default ON —
857/// under MEMRA_PP_DEVICES each stage's layer range uploads through its own engine.
858pub fn pp_shard_off() -> bool {
859    matches!(std::env::var("MEMRA_PP_SHARD").as_deref(), Ok("0"))
860}
861
862/// Raw `MEMRA_PP_DEVICES` (parsed/validated at PpNRt build — a bad string must fail the
863/// decode step loudly, never silently fall back to same-device and fake a gate PASS).
864fn pp2_devices_env() -> Option<String> {
865    std::env::var("MEMRA_PP_DEVICES")
866        .ok()
867        .filter(|v| !v.is_empty())
868}
869
870static WARNED_BAD: AtomicBool = AtomicBool::new(false);
871fn warn_bad_once(msg: &str) {
872    if !WARNED_BAD.swap(true, Ordering::Relaxed) {
873        eprintln!("[pp] {msg}");
874    }
875}
876
877static WARNED_UNWIRED: AtomicBool = AtomicBool::new(false);
878/// One-time notice when the door is set but the executing path has no pp arm
879/// (M2 wires the generic eager decode at any N and the gemma4 eager arm at N=2).
880pub fn warn_unwired_once(path: &str) {
881    let open = std::env::var("MEMRA_PP_STAGES")
882        .map(|v| !v.is_empty() && v != "0" && v != "1")
883        .unwrap_or(false);
884    if open && !WARNED_UNWIRED.swap(true, Ordering::Relaxed) {
885        eprintln!("[pp] MEMRA_PP_STAGES set but `{path}` has no pp arm at this N; running unsplit");
886    }
887}
888
889// ======================================================================================
890//  PpNRt: the M2 transport runtime (per-stage streams, per-boundary events + slots)
891// ======================================================================================
892
893/// One pipeline stage's execution home: device, context, launch stream, and (for a stage
894/// remote to the primary engine's device) a dedicated Engine in that device's primary
895/// context (CUmodules are per-context).
896pub struct StageRt {
897    pub dev: usize,
898    pub ctx: Arc<CudaContext>,
899    pub stream: Arc<CudaStream>,
900    pub blas: Arc<cudarc::cublaslt::CudaBlasLT>,
901    /// `Some` only when `dev` differs from the primary engine's device.
902    engine: Option<Engine>,
903}
904
905/// One boundary slot: a persistent RX-side buffer + its TX/RX completion events.
906/// PERSISTENT because the buffer is written by the TX stage's stream and read by the RX
907/// stage's: a per-step alloc/free would enqueue the free on ONE stream while the other
908/// might still be reading (the cross-stream free hazard) — a never-freed slot cannot race.
909struct BoundarySlot {
910    buf: Mutex<Option<CudaSlice<f32>>>,
911    /// Recorded on the TX stage's stream after the TX copy; RX waits on it. Created in
912    /// the TX stage's context (cuEventRecord requires event ctx == stream ctx).
913    ev_tx: CudaEvent,
914    /// Recorded on the RX stage's stream after the RX copy; the NEXT TX into this slot
915    /// waits on it (write-after-read guard). Created in the RX stage's context. Waiting
916    /// on a never-recorded event is a defined no-op, so step 0 needs no special case.
917    ev_rx: CudaEvent,
918}
919
920/// Boundary b sits between stage b (TX) and stage b+1 (RX). Two slots, alternating per
921/// step under MEMRA_PP_OVERLAP=1 (each boundary counts its own steps — a decode step
922/// crosses every boundary exactly once, so the counters stay in lockstep).
923struct BoundaryRt {
924    slots: [BoundarySlot; 2],
925    step: AtomicUsize,
926    /// true iff stage b and stage b+1 live on different devices (peer transport).
927    cross: bool,
928}
929
930#[derive(Clone, Copy, Debug, PartialEq, Eq)]
931enum BoundaryTransport {
932    Local,
933    Peer,
934    HostBounce,
935}
936
937#[derive(Clone, Copy)]
938struct BoundaryPath {
939    boundary: usize,
940    src_stage: usize,
941    dst_stage: usize,
942    transport: BoundaryTransport,
943}
944
945fn boundary_transport(cross: bool, host_bounce: bool) -> BoundaryTransport {
946    match (cross, host_bounce) {
947        (false, _) => BoundaryTransport::Local,
948        (true, false) => BoundaryTransport::Peer,
949        (true, true) => BoundaryTransport::HostBounce,
950    }
951}
952
953const PEER_PROBE_FIXED_BYTES: usize = 16 * 1024;
954const PEER_PROBE_TOKEN_WIDTHS: [usize; 4] = [1, 8, 16, crate::cache::PRIME_CHUNK_MAX_TOKENS];
955
956/// Native cross-device boundary copies between low-frequency runtime integrity probes.
957/// Fixed rather than operator-tunable: this is a safety gate, not a performance experiment.
958pub const PEER_RUNTIME_PROBE_INTERVAL_COPIES: u64 = 8 * 1024;
959/// One complete runtime width rotation. The maximum-chunk rung runs once per cycle.
960pub const PEER_RUNTIME_PROBE_CYCLE_COPIES: u64 =
961    PEER_RUNTIME_PROBE_INTERVAL_COPIES * PEER_PROBE_TOKEN_WIDTHS.len() as u64;
962/// Consecutive runnable probe intervals that may be blocked by live speculative UVA state before
963/// integrity coverage becomes explicitly degraded. Four intervals are one full width rotation.
964pub const PEER_RUNTIME_PROBE_DEFERRAL_BOUND_INTERVALS: u64 = PEER_PROBE_TOKEN_WIDTHS.len() as u64;
965/// Maximum measured owner-thread wall cost that may remain on an interactive scheduler boundary.
966const PEER_RUNTIME_PROBE_BUDGET_NS: u64 = 5_000_000;
967
968pub const PEER_PROBE_REQUIRED_REFUSAL: &str = "PP bring-up refused: MEMRA_PEER_PROBE=0 cannot authorize native peer transport for a \
969     sharded cross-device placement while MEMRA_PP_HOST_BOUNCE!=1; leave MEMRA_PEER_PROBE \
970     enabled or set MEMRA_PP_HOST_BOUNCE=1";
971
972#[derive(Clone, Copy, Debug, PartialEq, Eq)]
973pub enum PeerProbeStartupPolicy {
974    Allowed,
975    BypassedWithHostBounce,
976}
977
978/// Pure startup policy so unit tests and kernel-check pin the entire refusal matrix without
979/// mutating process-global environment variables.
980pub fn peer_probe_startup_policy(
981    probe_on: bool,
982    sharded_cross_device: bool,
983    host_bounce: bool,
984) -> Result<PeerProbeStartupPolicy, &'static str> {
985    match (probe_on, sharded_cross_device, host_bounce) {
986        (false, true, false) => Err(PEER_PROBE_REQUIRED_REFUSAL),
987        (false, true, true) => Ok(PeerProbeStartupPolicy::BypassedWithHostBounce),
988        _ => Ok(PeerProbeStartupPolicy::Allowed),
989    }
990}
991
992static PEER_PROBE_BYPASSED: AtomicU64 = AtomicU64::new(0);
993static PEER_BOUNDARY_COPIES: AtomicU64 = AtomicU64::new(0);
994static PEER_RUNTIME_PROBES: AtomicU64 = AtomicU64::new(0);
995static PEER_RUNTIME_PROBE_FAILURES: AtomicU64 = AtomicU64::new(0);
996static PEER_RUNTIME_PROBE_DEFERRED: AtomicU64 = AtomicU64::new(0);
997static PEER_RUNTIME_PROBE_INTEGRITY_DEGRADED: AtomicBool = AtomicBool::new(false);
998static PEER_RUNTIME_PROBE_FAILED: AtomicBool = AtomicBool::new(false);
999static PEER_RUNTIME_HOST_BOUNCE: AtomicBool = AtomicBool::new(false);
1000static PEER_RUNTIME_NEXT_PROBE_COPY: [AtomicU64; PEER_PROBE_TOKEN_WIDTHS.len()] = [
1001    AtomicU64::new(PEER_RUNTIME_PROBE_INTERVAL_COPIES),
1002    AtomicU64::new(2 * PEER_RUNTIME_PROBE_INTERVAL_COPIES),
1003    AtomicU64::new(3 * PEER_RUNTIME_PROBE_INTERVAL_COPIES),
1004    AtomicU64::new(4 * PEER_RUNTIME_PROBE_INTERVAL_COPIES),
1005];
1006static PEER_RUNTIME_PROBE_MAX_COST_NS: [AtomicU64; PEER_PROBE_TOKEN_WIDTHS.len()] = [
1007    AtomicU64::new(0),
1008    AtomicU64::new(0),
1009    AtomicU64::new(0),
1010    AtomicU64::new(0),
1011];
1012
1013#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1014pub struct PeerProbeMetrics {
1015    pub bypassed: u64,
1016    pub boundary_copies: u64,
1017    pub runtime_probes: u64,
1018    pub runtime_failures: u64,
1019    pub deferred_total: u64,
1020    pub integrity_degraded: bool,
1021    pub degraded_to_host_bounce: bool,
1022}
1023
1024pub fn peer_probe_metrics() -> PeerProbeMetrics {
1025    PeerProbeMetrics {
1026        bypassed: PEER_PROBE_BYPASSED.load(Ordering::Relaxed),
1027        boundary_copies: PEER_BOUNDARY_COPIES.load(Ordering::Relaxed),
1028        runtime_probes: PEER_RUNTIME_PROBES.load(Ordering::Relaxed),
1029        runtime_failures: PEER_RUNTIME_PROBE_FAILURES.load(Ordering::Relaxed),
1030        deferred_total: PEER_RUNTIME_PROBE_DEFERRED.load(Ordering::Relaxed),
1031        integrity_degraded: PEER_RUNTIME_PROBE_INTEGRITY_DEGRADED.load(Ordering::Acquire),
1032        degraded_to_host_bounce: PEER_RUNTIME_HOST_BOUNCE.load(Ordering::Acquire),
1033    }
1034}
1035
1036#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1037pub enum RuntimePeerProbeStatus {
1038    NotRun,
1039    Deferred,
1040    Passed,
1041    DegradedToHostBounce,
1042}
1043
1044impl RuntimePeerProbeStatus {
1045    pub fn ran(self) -> bool {
1046        matches!(self, Self::Passed | Self::DegradedToHostBounce)
1047    }
1048}
1049
1050fn publish_runtime_peer_probe_deferral(
1051    deferred_total: &AtomicU64,
1052    integrity_degraded: &AtomicBool,
1053    intervals: u64,
1054    bound_reached: bool,
1055) {
1056    deferred_total.fetch_add(intervals, Ordering::Relaxed);
1057    if bound_reached {
1058        integrity_degraded.store(true, Ordering::Release);
1059    }
1060}
1061
1062/// Publish newly observed copy-count intervals where a runnable peer probe was blocked by live
1063/// speculative UVA state. The worker coalesces scheduler polls before calling this function.
1064pub fn record_runtime_peer_probe_deferral(intervals: u64, bound_reached: bool) {
1065    publish_runtime_peer_probe_deferral(
1066        &PEER_RUNTIME_PROBE_DEFERRED,
1067        &PEER_RUNTIME_PROBE_INTEGRITY_DEGRADED,
1068        intervals,
1069        bound_reached,
1070    );
1071}
1072
1073/// A completed native probe or validated transport failover restores an explicit integrity state.
1074pub fn clear_runtime_peer_probe_integrity_degraded() {
1075    PEER_RUNTIME_PROBE_INTEGRITY_DEGRADED.store(false, Ordering::Release);
1076}
1077
1078fn runtime_peer_probe_idle_only(width_index: usize, measured_cost_ns: u64) -> bool {
1079    width_index + 1 == PEER_PROBE_TOKEN_WIDTHS.len()
1080        || measured_cost_ns > PEER_RUNTIME_PROBE_BUDGET_NS
1081}
1082
1083/// Pick the oldest runnable per-width deadline. Idle-only overdue work is skipped rather than
1084/// blocking later cheap deadlines, so the small integrity ladder keeps its copy-count cadence.
1085fn runtime_peer_probe_candidate(
1086    copies: u64,
1087    next_probe_copy: [u64; PEER_PROBE_TOKEN_WIDTHS.len()],
1088    measured_cost_ns: [u64; PEER_PROBE_TOKEN_WIDTHS.len()],
1089    scheduler_idle: bool,
1090) -> Option<(usize, usize)> {
1091    let mut selected: Option<(usize, u64)> = None;
1092    for width_index in 0..PEER_PROBE_TOKEN_WIDTHS.len() {
1093        let due = next_probe_copy[width_index];
1094        if copies < due
1095            || (!scheduler_idle
1096                && runtime_peer_probe_idle_only(width_index, measured_cost_ns[width_index]))
1097        {
1098            continue;
1099        }
1100        if selected.is_none_or(|(_, selected_due)| due < selected_due) {
1101            selected = Some((width_index, due));
1102        }
1103    }
1104    selected.map(|(width_index, _)| (width_index, PEER_PROBE_TOKEN_WIDTHS[width_index]))
1105}
1106
1107/// Advance a late per-width deadline to the first future cycle. Missed idle opportunities
1108/// collapse into one probe instead of producing an owner-thread catch-up burst.
1109fn runtime_peer_probe_next_copy(due: u64, copies: u64) -> u64 {
1110    let cycles = copies.saturating_sub(due) / PEER_RUNTIME_PROBE_CYCLE_COPIES + 1;
1111    due.saturating_add(PEER_RUNTIME_PROBE_CYCLE_COPIES.saturating_mul(cycles))
1112}
1113
1114/// Fail closed before arming the fallback, then publish host bounce only after its staging check
1115/// succeeds. The two atomics are parameters so unit tests never mutate process-global state.
1116fn latch_runtime_host_bounce<E>(
1117    native_failed: &AtomicBool,
1118    degraded_to_host_bounce: &AtomicBool,
1119    arm_and_validate: impl FnOnce() -> Result<(), E>,
1120) -> Result<(), E> {
1121    native_failed.store(true, Ordering::Release);
1122    arm_and_validate()?;
1123    degraded_to_host_bounce.store(true, Ordering::Release);
1124    Ok(())
1125}
1126
1127fn peer_probe_on() -> bool {
1128    std::env::var("MEMRA_PEER_PROBE").as_deref() != Ok("0")
1129}
1130
1131#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1132enum PeerProbeDecision {
1133    Clean,
1134    ProceedWithHostBounce { mismatches: usize },
1135}
1136
1137fn peer_probe_mismatch_count(expected: &[u8], readback: &[u8]) -> usize {
1138    expected
1139        .iter()
1140        .zip(readback)
1141        .filter(|(a, b)| a != b)
1142        .count()
1143        + expected.len().abs_diff(readback.len())
1144}
1145
1146fn peer_probe_decision(
1147    expected: &[u8],
1148    readback: &[u8],
1149    host_bounce: bool,
1150) -> Result<PeerProbeDecision, String> {
1151    let mismatches = peer_probe_mismatch_count(expected, readback);
1152    if mismatches == 0 {
1153        Ok(PeerProbeDecision::Clean)
1154    } else if host_bounce {
1155        Ok(PeerProbeDecision::ProceedWithHostBounce { mismatches })
1156    } else {
1157        Err(format!("{mismatches} mismatched byte(s)"))
1158    }
1159}
1160
1161fn peer_probe_pattern(bytes: usize, boundary: usize, src_dev: usize, dst_dev: usize) -> Vec<u8> {
1162    let mut state = 0xD1B5_4A32_D192_ED03u64
1163        ^ (bytes as u64).rotate_left(7)
1164        ^ (boundary as u64).rotate_left(19)
1165        ^ (src_dev as u64).rotate_left(31)
1166        ^ (dst_dev as u64).rotate_left(43);
1167    (0..bytes)
1168        .map(|_| {
1169            state ^= state << 13;
1170            state ^= state >> 7;
1171            state ^= state << 17;
1172            state as u8
1173        })
1174        .collect()
1175}
1176
1177fn peer_probe_bytes_to_f32(bytes: &[u8]) -> Vec<f32> {
1178    assert_eq!(bytes.len() % std::mem::size_of::<f32>(), 0);
1179    bytes
1180        .chunks_exact(std::mem::size_of::<f32>())
1181        .map(|chunk| f32::from_bits(u32::from_ne_bytes(chunk.try_into().unwrap())))
1182        .collect()
1183}
1184
1185fn peer_probe_f32_to_bytes(values: &[f32]) -> Vec<u8> {
1186    values
1187        .iter()
1188        .flat_map(|value| value.to_bits().to_ne_bytes())
1189        .collect()
1190}
1191
1192/// A legacy `cuMemAlloc` buffer used only by the boot probe. Unlike memra's normal
1193/// stream-ordered allocations, it becomes peer-visible through `cuCtxEnablePeerAccess`
1194/// without requiring the default-pool grants that deliberately happen after the probe.
1195struct PeerProbeBuffer {
1196    ctx: Arc<CudaContext>,
1197    ptr: cudarc::driver::sys::CUdeviceptr,
1198}
1199
1200impl PeerProbeBuffer {
1201    fn new(ctx: &Arc<CudaContext>, bytes: usize) -> Result<Self, Box<dyn std::error::Error>> {
1202        ctx.bind_to_thread()?;
1203        let ptr = unsafe { cudarc::driver::result::malloc_sync(bytes)? };
1204        Ok(Self {
1205            ctx: ctx.clone(),
1206            ptr,
1207        })
1208    }
1209}
1210
1211impl Drop for PeerProbeBuffer {
1212    fn drop(&mut self) {
1213        if self.ctx.bind_to_thread().is_ok() {
1214            let _ = unsafe { cudarc::driver::result::free_sync(self.ptr) };
1215        }
1216    }
1217}
1218
1219fn peer_probe_copy(
1220    src: &StageRt,
1221    dst: &StageRt,
1222    expected: &[u8],
1223) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
1224    let bytes = expected.len();
1225    let src_buf = PeerProbeBuffer::new(&src.ctx, bytes)?;
1226    unsafe {
1227        cudarc::driver::result::memcpy_htod_sync(src_buf.ptr, expected)?;
1228    }
1229
1230    let dst_buf = PeerProbeBuffer::new(&dst.ctx, bytes)?;
1231    let poison: Vec<u8> = expected.iter().map(|b| !b).collect();
1232    unsafe {
1233        cudarc::driver::result::memcpy_htod_sync(dst_buf.ptr, &poison)?;
1234    }
1235
1236    src.ctx.bind_to_thread()?;
1237    unsafe {
1238        cudarc::driver::result::memcpy_peer_async(
1239            dst.ctx.cu_ctx(),
1240            dst_buf.ptr,
1241            src.ctx.cu_ctx(),
1242            src_buf.ptr,
1243            bytes,
1244            src.stream.cu_stream(),
1245        )?;
1246    }
1247
1248    // Publish the peer write to the receiving context exactly like the live BoundarySlot
1249    // transport does. A host-side synchronize of only the TX stream is not the production
1250    // cross-context visibility contract; the RX stream waits on a TX event before touching the
1251    // destination allocation. Keeping the integrity probe on that same ordering path avoids
1252    // diagnosing an intentionally unordered destination-context read as fabric corruption.
1253    let published = src.ctx.new_event(None)?;
1254    published.record(&src.stream)?;
1255
1256    dst.ctx.bind_to_thread()?;
1257    dst.stream.wait(&published)?;
1258    dst.stream.synchronize()?;
1259    let mut readback = vec![0u8; bytes];
1260    unsafe {
1261        cudarc::driver::result::memcpy_dtoh_sync(&mut readback, dst_buf.ptr)?;
1262    }
1263    Ok(readback)
1264}
1265
1266fn run_peer_probe_pass(
1267    stages: &[StageRt],
1268    peer_capable: &[(usize, usize)],
1269    host_bounce: bool,
1270    label: &str,
1271    bytes: usize,
1272) -> Result<(), Box<dyn std::error::Error>> {
1273    if bytes == 0 {
1274        return Err(format!("PP peer byte-integrity probe {label} size is zero").into());
1275    }
1276    let started = std::time::Instant::now();
1277    let mut copies = 0usize;
1278    let mut skipped = 0usize;
1279    let mut total_mismatches = 0usize;
1280
1281    for boundary in 0..stages.len() - 1 {
1282        if stages[boundary].dev == stages[boundary + 1].dev {
1283            continue;
1284        }
1285        for (src_idx, dst_idx) in [(boundary, boundary + 1), (boundary + 1, boundary)] {
1286            let src = &stages[src_idx];
1287            let dst = &stages[dst_idx];
1288            if !peer_capable.contains(&(src.dev, dst.dev)) {
1289                if host_bounce {
1290                    skipped += 1;
1291                    eprintln!(
1292                        "[pp] peer byte-integrity probe SKIP: boundary={boundary} \
1293                         dev{}->dev{} label={label} bytes={bytes} (peer capability unavailable; \
1294                         MEMRA_PP_HOST_BOUNCE=1 remains fail-safe)",
1295                        src.dev, dst.dev,
1296                    );
1297                    continue;
1298                }
1299                return Err(format!(
1300                    "PP peer byte-integrity probe cannot run boundary={boundary} \
1301                     dev{}->dev{}: peer access was not enabled",
1302                    src.dev, dst.dev,
1303                )
1304                .into());
1305            }
1306
1307            let expected = peer_probe_pattern(bytes, boundary, src.dev, dst.dev);
1308            let readback = match peer_probe_copy(src, dst, &expected) {
1309                Ok(readback) => readback,
1310                Err(err) if host_bounce => {
1311                    skipped += 1;
1312                    eprintln!(
1313                        "[pp] peer byte-integrity probe ERROR: boundary={boundary} \
1314                         dev{}->dev{} label={label} bytes={bytes}: {err}; \
1315                         MEMRA_PP_HOST_BOUNCE=1, proceeding on the host-staged path",
1316                        src.dev, dst.dev,
1317                    );
1318                    continue;
1319                }
1320                Err(err) => {
1321                    return Err(format!(
1322                        "PP peer byte-integrity probe FAILED: boundary={boundary} \
1323                         dev{}->dev{} label={label} bytes={bytes}: {err}; refusing native P2P \
1324                         (set MEMRA_PP_HOST_BOUNCE=1 to use the host-staged path; \
1325                         MEMRA_PEER_PROBE=0 cannot authorize sharded native peer transport)",
1326                        src.dev, dst.dev,
1327                    )
1328                    .into());
1329                }
1330            };
1331            copies += 1;
1332            match peer_probe_decision(&expected, &readback, host_bounce) {
1333                Ok(PeerProbeDecision::Clean) => {}
1334                Ok(PeerProbeDecision::ProceedWithHostBounce { mismatches }) => {
1335                    total_mismatches += mismatches;
1336                    eprintln!(
1337                        "[pp] peer byte-integrity probe CORRUPTION: boundary={boundary} \
1338                         dev{}->dev{} label={label} bytes={bytes} mismatches={mismatches}; \
1339                         MEMRA_PP_HOST_BOUNCE=1, proceeding on the host-staged path",
1340                        src.dev, dst.dev,
1341                    );
1342                }
1343                Err(mismatch) => {
1344                    return Err(format!(
1345                        "PP peer byte-integrity probe FAILED: boundary={boundary} \
1346                         dev{}->dev{} label={label} bytes={bytes}: {mismatch}; refusing native \
1347                         P2P (set MEMRA_PP_HOST_BOUNCE=1 to use the host-staged path; \
1348                         MEMRA_PEER_PROBE=0 cannot authorize sharded native peer transport)",
1349                        src.dev, dst.dev,
1350                    )
1351                    .into());
1352                }
1353            }
1354        }
1355    }
1356
1357    let status = if total_mismatches > 0 {
1358        "BOUNCE"
1359    } else if skipped > 0 && copies > 0 {
1360        "PARTIAL"
1361    } else if skipped > 0 {
1362        "SKIP"
1363    } else {
1364        "PASS"
1365    };
1366    eprintln!(
1367        "[pp] peer byte-integrity probe {}: label={label} bytes={bytes} copies={copies} \
1368         skipped={skipped} mismatches={total_mismatches} elapsed_ms={:.3}",
1369        status,
1370        started.elapsed().as_secs_f64() * 1e3,
1371    );
1372    Ok(())
1373}
1374
1375fn host_bounce_capacity(n_embd: usize) -> Result<(usize, usize), String> {
1376    if n_embd == 0 {
1377        return Err("MEMRA_PP_HOST_BOUNCE needs non-zero model n_embd".into());
1378    }
1379    let elems = n_embd
1380        .checked_mul(crate::cache::PRIME_CHUNK_MAX_TOKENS)
1381        .ok_or_else(|| format!("host-bounce element count overflows for n_embd={n_embd}"))?;
1382    let bytes = elems
1383        .checked_mul(std::mem::size_of::<f32>())
1384        .ok_or_else(|| format!("host-bounce byte count overflows for n_embd={n_embd}"))?;
1385    Ok((elems, bytes))
1386}
1387
1388fn boundary_slot_growth_elements(current: [usize; 2], required: usize) -> usize {
1389    current.into_iter().fold(0usize, |total, len| {
1390        total.saturating_add(required.saturating_sub(len))
1391    })
1392}
1393
1394/// One bidirectional-DMA staging allocation. `CU_MEMHOSTALLOC_PORTABLE` matters here: the
1395/// D2H producer and H2D consumer are in distinct CUDA primary contexts. Cacheable memory is
1396/// intentional (rather than cudarc's write-combined pinned slice) because this allocation is
1397/// the destination of D2H as well as the source of H2D.
1398struct PinnedHostBounce {
1399    ptr: *mut f32,
1400    len: usize,
1401}
1402
1403unsafe impl Send for PinnedHostBounce {}
1404unsafe impl Sync for PinnedHostBounce {}
1405
1406impl PinnedHostBounce {
1407    fn new(len: usize) -> Result<Self, Box<dyn std::error::Error>> {
1408        let bytes = len
1409            .checked_mul(std::mem::size_of::<f32>())
1410            .ok_or("host-bounce pinned allocation size overflow")?;
1411        let ptr = unsafe {
1412            cudarc::driver::result::malloc_host(
1413                bytes,
1414                cudarc::driver::sys::CU_MEMHOSTALLOC_PORTABLE,
1415            )?
1416        } as *mut f32;
1417        if ptr.is_null() {
1418            return Err("cuMemHostAlloc returned a null host-bounce pointer".into());
1419        }
1420        Ok(Self { ptr, len })
1421    }
1422
1423    fn prefix(&self, n: usize) -> &[f32] {
1424        assert!(
1425            n <= self.len,
1426            "host-bounce source {n} > capacity {}",
1427            self.len
1428        );
1429        unsafe { std::slice::from_raw_parts(self.ptr, n) }
1430    }
1431
1432    fn prefix_mut(&mut self, n: usize) -> &mut [f32] {
1433        assert!(
1434            n <= self.len,
1435            "host-bounce destination {n} > capacity {}",
1436            self.len
1437        );
1438        unsafe { std::slice::from_raw_parts_mut(self.ptr, n) }
1439    }
1440}
1441
1442impl Drop for PinnedHostBounce {
1443    fn drop(&mut self) {
1444        let _ = unsafe { cudarc::driver::result::free_host(self.ptr.cast()) };
1445    }
1446}
1447
1448struct HostBounceRt {
1449    n_embd: usize,
1450    capacity: usize,
1451    slots: Vec<Option<[Mutex<PinnedHostBounce>; 2]>>,
1452}
1453
1454impl HostBounceRt {
1455    fn new(n_embd: usize, boundaries: &[BoundaryRt]) -> Result<Self, Box<dyn std::error::Error>> {
1456        let (capacity, _) = host_bounce_capacity(n_embd)?;
1457        let mut slots = Vec::with_capacity(boundaries.len());
1458        for boundary in boundaries {
1459            slots.push(if boundary.cross {
1460                Some([
1461                    Mutex::new(PinnedHostBounce::new(capacity)?),
1462                    Mutex::new(PinnedHostBounce::new(capacity)?),
1463                ])
1464            } else {
1465                None
1466            });
1467        }
1468        Ok(Self {
1469            n_embd,
1470            capacity,
1471            slots,
1472        })
1473    }
1474
1475    fn slot(
1476        &self,
1477        boundary: usize,
1478        slot: usize,
1479    ) -> Result<&Mutex<PinnedHostBounce>, Box<dyn std::error::Error>> {
1480        self.slots
1481            .get(boundary)
1482            .and_then(Option::as_ref)
1483            .and_then(|slots| slots.get(slot))
1484            .ok_or_else(|| format!("host-bounce slot {boundary}:{slot} is not initialized").into())
1485    }
1486}
1487
1488pub struct PpNRt {
1489    stages: Vec<StageRt>,
1490    boundaries: Vec<BoundaryRt>,
1491    /// Whole-walk ownership for the shared boundary slot/event sequence. Boundary-local atomics
1492    /// choose alternating slots but cannot distinguish two interleaved callers; one generation
1493    /// lease therefore spans entry fencing through final publication/result collection.
1494    walk_active: Arc<AtomicU64>,
1495    walk_next: AtomicU64,
1496    /// A deferred decode window intentionally owns several in-flight logits tickets. The weak
1497    /// reference lets consecutive enqueue calls on the same CUDA-owner thread join that window;
1498    /// the active generation is released only after the final `PendingLogits` is drained/dropped.
1499    deferred_walk: Mutex<Weak<PpWalkState>>,
1500    /// true iff ANY boundary crosses devices.
1501    cross_any: bool,
1502    /// Startup selection captured at runtime construction. A runtime probe failure may promote
1503    /// the process-wide one-way host-bounce latch without mutating this value.
1504    host_bounce: bool,
1505    /// Boot-time peer validation is default-on; `MEMRA_PEER_PROBE=0` is diagnostics-only.
1506    peer_probe: bool,
1507    /// Directed device pairs for which `cuDeviceCanAccessPeer` succeeded.
1508    peer_capable: Vec<(usize, usize)>,
1509    /// Sticky one-time model-width probe result. The value is the one-row geometry byte count.
1510    peer_probe_geometry: OnceLock<Result<usize, String>>,
1511    /// Lazily allocated after the authoritative model width is known at cache creation.
1512    bounce: OnceLock<Result<HostBounceRt, String>>,
1513    /// Dedicated readback stream in the LAST stage's context (deferred logits D2H —
1514    /// waiting there instead of on the compute stream keeps later tokens enqueuable).
1515    readback: Arc<CudaStream>,
1516}
1517
1518#[derive(Debug)]
1519struct PpWalkState {
1520    active: Arc<AtomicU64>,
1521    generation: u64,
1522    runtime_id: usize,
1523    deferred_owner: Option<std::thread::ThreadId>,
1524}
1525
1526impl PpWalkState {
1527    fn is_active(&self) -> bool {
1528        self.active.load(Ordering::Acquire) == self.generation
1529    }
1530}
1531
1532impl Drop for PpWalkState {
1533    fn drop(&mut self) {
1534        let _ =
1535            self.active
1536                .compare_exchange(self.generation, 0, Ordering::AcqRel, Ordering::Acquire);
1537    }
1538}
1539
1540/// Opaque lifetime token for one complete PP boundary walk. Clones are allowed only through an
1541/// explicit coordinator permit or the same-thread deferred enqueue window; the active generation
1542/// clears when the final clone is dropped.
1543#[derive(Debug)]
1544pub struct PpWalkLease {
1545    state: Arc<PpWalkState>,
1546}
1547
1548/// Explicit authority for a coordinator whose two host lanes intentionally share one PP walk.
1549#[derive(Clone, Debug)]
1550pub(crate) struct PpWalkPermit {
1551    state: Arc<PpWalkState>,
1552}
1553
1554thread_local! {
1555    static PP_WALK_BORROWS: RefCell<Vec<Arc<PpWalkState>>> = const { RefCell::new(Vec::new()) };
1556}
1557
1558/// Thread-local borrowed authority. It is deliberately !Send so a caller must install the permit
1559/// independently in each scoped coordinator lane.
1560pub(crate) struct PpWalkBorrowGuard {
1561    prior_len: usize,
1562    _not_send: PhantomData<Rc<()>>,
1563}
1564
1565impl Drop for PpWalkBorrowGuard {
1566    fn drop(&mut self) {
1567        PP_WALK_BORROWS.with(|borrows| borrows.borrow_mut().truncate(self.prior_len));
1568    }
1569}
1570
1571fn next_pp_walk_generation(next: &AtomicU64) -> u64 {
1572    loop {
1573        let generation = next.fetch_add(1, Ordering::Relaxed);
1574        if generation != 0 {
1575            return generation;
1576        }
1577    }
1578}
1579
1580fn acquire_pp_walk(
1581    active: &Arc<AtomicU64>,
1582    next: &AtomicU64,
1583    runtime_id: usize,
1584    deferred_owner: Option<std::thread::ThreadId>,
1585    path: &str,
1586) -> Result<PpWalkLease, String> {
1587    let generation = next_pp_walk_generation(next);
1588    active
1589        .compare_exchange(0, generation, Ordering::AcqRel, Ordering::Acquire)
1590        .map_err(|_| {
1591            format!(
1592                "{path}: refused concurrent PP walk; shared boundary slots already have an owner"
1593            )
1594        })?;
1595    Ok(PpWalkLease {
1596        state: Arc::new(PpWalkState {
1597            active: active.clone(),
1598            generation,
1599            runtime_id,
1600            deferred_owner,
1601        }),
1602    })
1603}
1604
1605fn borrowed_pp_walk(runtime_id: usize) -> Option<PpWalkLease> {
1606    PP_WALK_BORROWS.with(|borrows| {
1607        borrows
1608            .borrow()
1609            .iter()
1610            .rev()
1611            .find(|state| state.runtime_id == runtime_id && state.is_active())
1612            .cloned()
1613            .map(|state| PpWalkLease { state })
1614    })
1615}
1616
1617fn lock_deferred_walk<'a>(
1618    deferred: &'a Mutex<Weak<PpWalkState>>,
1619    path: &str,
1620) -> Result<std::sync::MutexGuard<'a, Weak<PpWalkState>>, String> {
1621    deferred
1622        .lock()
1623        .map_err(|_| format!("{path}: deferred PP walk owner lock is poisoned"))
1624}
1625
1626fn validate_walk_state(state: &PpWalkState, runtime_id: usize, path: &str) -> Result<(), String> {
1627    if state.runtime_id != runtime_id {
1628        return Err(format!(
1629            "{path}: PP walk permit belongs to a different runtime"
1630        ));
1631    }
1632    if !state.is_active() {
1633        return Err(format!(
1634            "{path}: PP walk permit generation is no longer active"
1635        ));
1636    }
1637    Ok(())
1638}
1639
1640/// M1 name kept alive for external callers (`pp-transport-smoke`, receipts, docs).
1641pub type Pp2Rt = PpNRt;
1642
1643static RTN: OnceLock<Result<PpNRt, String>> = OnceLock::new();
1644
1645impl PpNRt {
1646    /// The process-wide transport runtime, built on first use against the primary engine.
1647    /// The stage count + device map freeze at first build (one config per process — gates
1648    /// run one placement per invocation). Build errors are sticky and loud.
1649    pub fn get(e: &Engine) -> Result<&'static PpNRt, Box<dyn std::error::Error>> {
1650        RTN.get_or_init(|| Self::build(e).map_err(|err| err.to_string()))
1651            .as_ref()
1652            .map_err(|s| -> Box<dyn std::error::Error> { s.clone().into() })
1653    }
1654
1655    fn build(e: &Engine) -> Result<PpNRt, Box<dyn std::error::Error>> {
1656        // Validate the experimental PP3/PP4 door at runtime construction so an invalid value is a
1657        // boot refusal, never a silently-disabled serving policy discovered on the first request.
1658        pp_wave_on().map_err(|reason| -> Box<dyn std::error::Error> { reason.into() })?;
1659        let primary_dev = e.ctx().ordinal();
1660        // Stage count: MEMRA_PP_DEVICES length wins when set (it IS the placement);
1661        // else MEMRA_PP_STAGES; else 2 (the M1 default — pp-transport-smoke runs doorless).
1662        let devices: Vec<usize> =
1663            match pp2_devices_env() {
1664                Some(s) => {
1665                    let parts: Result<Vec<usize>, _> =
1666                        s.split(',').map(|p| p.trim().parse::<usize>()).collect();
1667                    match parts {
1668                        Ok(v) if v.len() >= 2 => v,
1669                        _ => return Err(format!(
1670                            "MEMRA_PP_DEVICES={s} unparseable (want <d0>,..,<dN-1> e.g. 0,1,2,3)"
1671                        )
1672                        .into()),
1673                    }
1674                }
1675                None => {
1676                    let n_st = std::env::var("MEMRA_PP_STAGES")
1677                        .ok()
1678                        .and_then(|v| v.parse::<usize>().ok())
1679                        .filter(|&n| n >= 2)
1680                        .unwrap_or(2);
1681                    vec![primary_dev; n_st]
1682                }
1683            };
1684        if let Ok(v) = std::env::var("MEMRA_PP_STAGES")
1685            && let Ok(n) = v.parse::<usize>()
1686            && n >= 2
1687            && n != devices.len()
1688        {
1689            return Err(format!(
1690                "MEMRA_PP_DEVICES lists {} devices but MEMRA_PP_STAGES={n} — \
1691                         refusing an ambiguous placement",
1692                devices.len()
1693            )
1694            .into());
1695        }
1696        let n_st = devices.len();
1697        let cross_any = devices.iter().any(|&d| d != devices[0]);
1698        let host_bounce = pp_host_bounce_on();
1699        let peer_probe = peer_probe_on();
1700        let sharded_cross_device = cross_any && !pp_shard_off();
1701        if host_bounce && cross_any {
1702            if pp_shard_off() {
1703                return Err(
1704                    "MEMRA_PP_HOST_BOUNCE=1 refuses MEMRA_PP_SHARD=0: the boundary can bounce, \
1705                     but remote stages would still peer-read primary-device weights"
1706                        .into(),
1707                );
1708            }
1709            if devices.last().copied() != Some(primary_dev) {
1710                return Err(format!(
1711                    "MEMRA_PP_HOST_BOUNCE=1 requires the primary engine on the last/head stage \
1712                     (primary dev{primary_dev}, placement {devices:?}); otherwise returned \
1713                     logits/hidden state remain peer reads"
1714                )
1715                .into());
1716            }
1717        }
1718        let peer_probe_policy =
1719            peer_probe_startup_policy(peer_probe, sharded_cross_device, host_bounce)?;
1720        if peer_probe_policy == PeerProbeStartupPolicy::BypassedWithHostBounce {
1721            PEER_PROBE_BYPASSED.fetch_add(1, Ordering::Relaxed);
1722            eprintln!(
1723                "[pp] SECURITY RED: peer_probe_bypassed: MEMRA_PEER_PROBE=0 on a sharded \
1724                 cross-device placement; MEMRA_PP_HOST_BOUNCE=1 is the only enabled transport"
1725            );
1726        }
1727
1728        // Validate every placement ordinal in both transports. Native peer transport requires
1729        // access both ways. Host bounce remains usable without it, but records any capable pairs
1730        // so the byte probe can still diagnose a lying peer path before selecting the fallback.
1731        let mut used: Vec<usize> = devices.clone();
1732        used.push(primary_dev);
1733        used.sort_unstable();
1734        used.dedup();
1735        let mut peer_capable = Vec::new();
1736        if used.len() > 1 {
1737            let n = cudarc::driver::result::device::get_count()? as usize;
1738            for &d in &used {
1739                if d >= n {
1740                    return Err(format!(
1741                        "MEMRA_PP_DEVICES={devices:?} but only {n} CUDA device(s) present"
1742                    )
1743                    .into());
1744                }
1745            }
1746            if !host_bounce || peer_probe {
1747                for &a in &used {
1748                    for &b in &used {
1749                        if a == b {
1750                            continue;
1751                        }
1752                        let da = cudarc::driver::result::device::get(a as i32)?;
1753                        let db = cudarc::driver::result::device::get(b as i32)?;
1754                        let mut can: i32 = 0;
1755                        let capability = unsafe {
1756                            cudarc::driver::sys::cuDeviceCanAccessPeer(&mut can, da, db).result()
1757                        };
1758                        if let Err(err) = capability {
1759                            if host_bounce {
1760                                eprintln!(
1761                                    "[pp] peer byte-integrity probe capability query failed for \
1762                                     dev{a}->dev{b}: {err}; MEMRA_PP_HOST_BOUNCE=1 remains active"
1763                                );
1764                                continue;
1765                            }
1766                            return Err(err.into());
1767                        }
1768                        if can == 0 {
1769                            if !host_bounce {
1770                                return Err(format!(
1771                                    "device {a} cannot peer-access device {b} \
1772                                     (cuDeviceCanAccessPeer=0); ppN cross-device needs P2P — \
1773                                     refusing a silently-staged path"
1774                                )
1775                                .into());
1776                            }
1777                        } else {
1778                            peer_capable.push((a, b));
1779                        }
1780                    }
1781                }
1782            }
1783        }
1784
1785        // PER-STAGE ENGINE ISOLATION (2026-08-02 singledev pipelined find): Engine owns
1786        // lazily-grown SHARED scratch pools (fa_part_pool, fa_vf16_scratch, argmax
1787        // partials, ...) that are stable-pointer by design — safe on one stream, a data
1788        // race the moment two stage streams run concurrently through the SAME Engine
1789        // (deferred readback, >=2 tokens in flight: token t+1's stage-0 fa memsets the
1790        // partials while token t's stage-s fa still reads them — the nondeterministic
1791        // all-logits divergence; cross-device arms were immune because remote stages
1792        // already got their own Engine). Every stage s>0 gets its OWN Engine even on the
1793        // primary device: same CUcontext (primary retain), so the per-context CUmodule
1794        // cache makes it cheap; scratch pools are per-Engine, so stages never share.
1795        // Stage 0 keeps the primary engine (single-threaded host issue: the only
1796        // concurrent user of `e` during a pp walk is stage 0 itself).
1797        let mk_stage = |dev: usize, s: usize| -> Result<StageRt, Box<dyn std::error::Error>> {
1798            if dev == primary_dev && s == 0 {
1799                let ctx = e.ctx().clone();
1800                let stream = ctx.new_stream()?;
1801                let blas = Arc::new(cudarc::cublaslt::CudaBlasLT::new(stream.clone())?);
1802                Ok(StageRt {
1803                    dev,
1804                    ctx,
1805                    stream,
1806                    blas,
1807                    engine: None,
1808                })
1809            } else {
1810                let eng = Engine::new(dev)?;
1811                let ctx = eng.ctx().clone();
1812                let stream = ctx.new_stream()?;
1813                let blas = Arc::new(cudarc::cublaslt::CudaBlasLT::new(stream.clone())?);
1814                Ok(StageRt {
1815                    dev,
1816                    ctx,
1817                    stream,
1818                    blas,
1819                    engine: Some(eng),
1820                })
1821            }
1822        };
1823        let mut stages = Vec::with_capacity(n_st);
1824        for (s, &d) in devices.iter().enumerate() {
1825            stages.push(mk_stage(d, s)?);
1826        }
1827
1828        if cross_any
1829            && !peer_probe
1830            && peer_probe_policy != PeerProbeStartupPolicy::BypassedWithHostBounce
1831        {
1832            eprintln!(
1833                "[pp] WARNING: MEMRA_PEER_PROBE=0 skips the boot-time peer byte-integrity \
1834                 gate; diagnostics escape hatch active"
1835            );
1836        }
1837
1838        if used.len() > 1 {
1839            if !host_bounce {
1840                // A context per distinct device (first stage that lives there; the primary's
1841                // context for the primary device).
1842                let ctx_of = |d: usize| -> &Arc<CudaContext> {
1843                    if d == primary_dev {
1844                        e.ctx()
1845                    } else {
1846                        &stages.iter().find(|s| s.dev == d).unwrap().ctx
1847                    }
1848                };
1849                // Enable peer access BOTH ways for every distinct pair (idempotent;
1850                // ALREADY_ENABLED is success).
1851                for &a in &used {
1852                    for &b in &used {
1853                        if a == b {
1854                            continue;
1855                        }
1856                        ctx_of(a).bind_to_thread()?;
1857                        let rc = unsafe {
1858                            cudarc::driver::sys::cuCtxEnablePeerAccess(ctx_of(b).cu_ctx(), 0)
1859                        };
1860                        use cudarc::driver::sys::cudaError_enum as E;
1861                        if rc != E::CUDA_SUCCESS && rc != E::CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED
1862                        {
1863                            return Err(format!(
1864                                "cuCtxEnablePeerAccess(dev{a} -> dev{b}) failed: {rc:?}"
1865                            )
1866                            .into());
1867                        }
1868                    }
1869                }
1870                // The fixed-size byte gate runs immediately after peer enable and before pool
1871                // grants. Legacy allocations make it exercise the exact `cuMemcpyPeerAsync` API
1872                // without depending on the pool setup that follows.
1873                if peer_probe && cross_any {
1874                    let probe = run_peer_probe_pass(
1875                        &stages,
1876                        &peer_capable,
1877                        host_bounce,
1878                        "fixed-16KiB",
1879                        PEER_PROBE_FIXED_BYTES,
1880                    );
1881                    e.ctx().bind_to_thread()?;
1882                    probe?;
1883                }
1884                // MEM-POOL access grant (8x box 2026-08-02, M1 cross-device fix #2):
1885                // cuCtxEnablePeerAccess does NOT map STREAM-ORDERED POOL allocations, and every
1886                // engine buffer/weight goes through the device default pool (cuMemAllocAsync via
1887                // cudarc; memra-runtime configures that pool). A stage kernel dereferencing
1888                // another device's weights — or a boundary peer TX writing the RX slot — needs
1889                // cuMemPoolSetAccess on the OWNING device's default pool for the ACCESSING
1890                // device; without it the first remote dereference is CUDA_ERROR_ILLEGAL_ADDRESS
1891                // (reported at the next API call in the poisoned context). Grant all pairs.
1892                for &owner in &used {
1893                    for &accessor in &used {
1894                        if owner == accessor {
1895                            continue;
1896                        }
1897                        let dev = cudarc::driver::result::device::get(owner as i32)?;
1898                        let mut pool: cudarc::driver::sys::CUmemoryPool = std::ptr::null_mut();
1899                        unsafe {
1900                            cudarc::driver::sys::cuDeviceGetDefaultMemPool(&mut pool, dev)
1901                                .result()?;
1902                        }
1903                        let desc = cudarc::driver::sys::CUmemAccessDesc {
1904                        location: cudarc::driver::sys::CUmemLocation {
1905                            type_: cudarc::driver::sys::CUmemLocationType::CU_MEM_LOCATION_TYPE_DEVICE,
1906                            id: accessor as i32,
1907                        },
1908                        flags: cudarc::driver::sys::CUmemAccess_flags::CU_MEM_ACCESS_FLAGS_PROT_READWRITE,
1909                    };
1910                        let rc = unsafe { cudarc::driver::sys::cuMemPoolSetAccess(pool, &desc, 1) };
1911                        if rc != cudarc::driver::sys::cudaError_enum::CUDA_SUCCESS {
1912                            return Err(format!(
1913                            "cuMemPoolSetAccess(dev{owner} pool -> dev{accessor}) failed: {rc:?}"
1914                        )
1915                        .into());
1916                        }
1917                    }
1918                }
1919                // MEM-POOL access grant (8x box 2026-08-02, cross-device fix #2):
1920                // cuCtxEnablePeerAccess does NOT map STREAM-ORDERED POOL allocations, and every
1921                // engine buffer/weight goes through the device default pool (cuMemAllocAsync via
1922                // cudarc; memra-runtime configures that pool). A stage-1 kernel dereferencing
1923                // dev0 weights — or the stage-0 peer TX writing dev1's RX slot — needs
1924                // cuMemPoolSetAccess on the OWNING device's default pool for the ACCESSING
1925                // device; without it the first remote dereference is CUDA_ERROR_ILLEGAL_ADDRESS
1926                // (reported at the next API call in the poisoned context). Grant both ways.
1927                for (owner, accessor) in [
1928                    (stages[0].dev, stages[1].dev),
1929                    (stages[1].dev, stages[0].dev),
1930                ] {
1931                    let dev = cudarc::driver::result::device::get(owner as i32)?;
1932                    let mut pool: cudarc::driver::sys::CUmemoryPool = std::ptr::null_mut();
1933                    unsafe {
1934                        cudarc::driver::sys::cuDeviceGetDefaultMemPool(&mut pool, dev).result()?;
1935                    }
1936                    let desc = cudarc::driver::sys::CUmemAccessDesc {
1937                    location: cudarc::driver::sys::CUmemLocation {
1938                        type_: cudarc::driver::sys::CUmemLocationType::CU_MEM_LOCATION_TYPE_DEVICE,
1939                        id: accessor as i32,
1940                    },
1941                    flags: cudarc::driver::sys::CUmemAccess_flags::CU_MEM_ACCESS_FLAGS_PROT_READWRITE,
1942                };
1943                    let rc = unsafe { cudarc::driver::sys::cuMemPoolSetAccess(pool, &desc, 1) };
1944                    if rc != cudarc::driver::sys::cudaError_enum::CUDA_SUCCESS {
1945                        return Err(format!(
1946                            "cuMemPoolSetAccess(dev{owner} pool -> dev{accessor}) failed: {rc:?}"
1947                        )
1948                        .into());
1949                    }
1950                }
1951                // restore the primary context for the caller's subsequent work
1952                e.ctx().bind_to_thread()?;
1953                eprintln!(
1954                    "[pp] cross-device transport: {} (cudaMemcpyPeerAsync per cross boundary; \
1955                 peer + default-pool access granted all pairs over {used:?}; weight home: {})",
1956                    devices
1957                        .iter()
1958                        .enumerate()
1959                        .map(|(s, d)| format!("stage{s}=dev{d}"))
1960                        .collect::<Vec<_>>()
1961                        .join(" "),
1962                    if pp_shard_off() {
1963                        format!("dev{primary_dev} (MEMRA_PP_SHARD=0 bring-up placement)")
1964                    } else {
1965                        "per-stage (sharded loader)".to_string()
1966                    }
1967                );
1968            } else {
1969                e.ctx().bind_to_thread()?;
1970                eprintln!(
1971                    "[pp] cross-device transport: {} (HOST-STAGED pinned D2H -> H2D per cross \
1972                     boundary; MEMRA_PP_HOST_BOUNCE=1; peer-pool grants bypassed; \
1973                     diagnostic peer access is removed before host-staged serving; \
1974                     weight home: per-stage (sharded loader))",
1975                    devices
1976                        .iter()
1977                        .enumerate()
1978                        .map(|(s, d)| format!("stage{s}=dev{d}"))
1979                        .collect::<Vec<_>>()
1980                        .join(" "),
1981                );
1982            }
1983        }
1984
1985        let mk_slot =
1986            |tx: &StageRt, rx: &StageRt| -> Result<BoundarySlot, Box<dyn std::error::Error>> {
1987                Ok(BoundarySlot {
1988                    buf: Mutex::new(None),
1989                    ev_tx: tx.ctx.new_event(None)?,
1990                    ev_rx: rx.ctx.new_event(None)?,
1991                })
1992            };
1993        let mut boundaries = Vec::with_capacity(n_st - 1);
1994        for b in 0..n_st - 1 {
1995            let (tx, rx) = (&stages[b], &stages[b + 1]);
1996            boundaries.push(BoundaryRt {
1997                slots: [mk_slot(tx, rx)?, mk_slot(tx, rx)?],
1998                step: AtomicUsize::new(0),
1999                cross: tx.dev != rx.dev,
2000            });
2001        }
2002        let readback = stages[n_st - 1].ctx.new_stream()?;
2003        let rt = PpNRt {
2004            stages,
2005            boundaries,
2006            walk_active: Arc::new(AtomicU64::new(0)),
2007            walk_next: AtomicU64::new(1),
2008            deferred_walk: Mutex::new(Weak::new()),
2009            cross_any,
2010            host_bounce,
2011            peer_probe,
2012            peer_capable,
2013            peer_probe_geometry: OnceLock::new(),
2014            bounce: OnceLock::new(),
2015            readback,
2016        };
2017        if rt.peer_probe && rt.cross_any && rt.host_bounce {
2018            rt.run_host_bounce_legacy_probe(e)?;
2019        }
2020        Ok(rt)
2021    }
2022
2023    pub fn n_stages(&self) -> usize {
2024        self.stages.len()
2025    }
2026
2027    /// Acquire exclusive ownership of the PP boundary/event sequence for one complete model walk.
2028    /// Fail fast rather than blocking. A nested call can join only when its thread has an explicit
2029    /// coordinator borrow installed; merely running on the original thread is not authority.
2030    pub fn acquire_walk(
2031        &'static self,
2032        path: &str,
2033    ) -> Result<PpWalkLease, Box<dyn std::error::Error>> {
2034        let runtime_id = self as *const Self as usize;
2035        if let Some(lease) = borrowed_pp_walk(runtime_id) {
2036            return Ok(lease);
2037        }
2038        acquire_pp_walk(&self.walk_active, &self.walk_next, runtime_id, None, path)
2039            .map_err(|error| -> Box<dyn std::error::Error> { error.into() })
2040    }
2041
2042    /// Join the one intentional multi-enqueue deferred window. Only the thread that opened the
2043    /// window may add work; unrelated callers still fail fast while any pending result exists.
2044    pub(crate) fn acquire_deferred_walk(
2045        &'static self,
2046        path: &str,
2047    ) -> Result<PpWalkLease, Box<dyn std::error::Error>> {
2048        let runtime_id = self as *const Self as usize;
2049        let current_thread = std::thread::current().id();
2050        let mut weak = lock_deferred_walk(&self.deferred_walk, path)
2051            .map_err(|error| -> Box<dyn std::error::Error> { error.into() })?;
2052        if let Some(state) = weak.upgrade() {
2053            validate_walk_state(&state, runtime_id, path)
2054                .map_err(|error| -> Box<dyn std::error::Error> { error.into() })?;
2055            if state.deferred_owner.as_ref() != Some(&current_thread) {
2056                return Err(format!(
2057                    "{path}: refused cross-thread join of the active deferred PP window"
2058                )
2059                .into());
2060            }
2061            return Ok(PpWalkLease { state });
2062        }
2063        let lease = acquire_pp_walk(
2064            &self.walk_active,
2065            &self.walk_next,
2066            runtime_id,
2067            Some(current_thread),
2068            path,
2069        )
2070        .map_err(|error| -> Box<dyn std::error::Error> { error.into() })?;
2071        *weak = Arc::downgrade(&lease.state);
2072        Ok(lease)
2073    }
2074
2075    /// Mint coordinator authority from an active owner lease. Passing this object is the only way
2076    /// another host thread can make nested PP calls within that same generation.
2077    pub(crate) fn walk_permit(
2078        &'static self,
2079        lease: &PpWalkLease,
2080        path: &str,
2081    ) -> Result<PpWalkPermit, Box<dyn std::error::Error>> {
2082        let runtime_id = self as *const Self as usize;
2083        validate_walk_state(&lease.state, runtime_id, path)
2084            .map_err(|error| -> Box<dyn std::error::Error> { error.into() })?;
2085        if lease.state.deferred_owner.is_some() {
2086            return Err(
2087                format!("{path}: deferred PP windows cannot mint coordinator permits").into(),
2088            );
2089        }
2090        Ok(PpWalkPermit {
2091            state: lease.state.clone(),
2092        })
2093    }
2094
2095    /// Install a coordinator permit on the current host thread for the lifetime of the guard.
2096    pub(crate) fn borrow_walk(
2097        &'static self,
2098        permit: &PpWalkPermit,
2099        path: &str,
2100    ) -> Result<PpWalkBorrowGuard, Box<dyn std::error::Error>> {
2101        let runtime_id = self as *const Self as usize;
2102        validate_walk_state(&permit.state, runtime_id, path)
2103            .map_err(|error| -> Box<dyn std::error::Error> { error.into() })?;
2104        let prior_len = PP_WALK_BORROWS.with(|borrows| {
2105            let mut borrows = borrows.borrow_mut();
2106            let prior_len = borrows.len();
2107            borrows.push(permit.state.clone());
2108            prior_len
2109        });
2110        Ok(PpWalkBorrowGuard {
2111            prior_len,
2112            _not_send: PhantomData,
2113        })
2114    }
2115
2116    /// True iff any boundary crosses devices.
2117    pub fn cross_device(&self) -> bool {
2118        self.cross_any
2119    }
2120
2121    pub fn host_bounce_active(&self) -> bool {
2122        self.host_bounce || PEER_RUNTIME_HOST_BOUNCE.load(Ordering::Acquire)
2123    }
2124
2125    /// Actual stage placement frozen when this runtime was built. Environment strings may be
2126    /// mutated by in-process gates later and are not authoritative for scheduler safety.
2127    pub fn repeated_stage_device(&self) -> bool {
2128        let mut devices: Vec<_> = self.stages.iter().map(|stage| stage.dev).collect();
2129        devices.sort_unstable();
2130        devices.dedup();
2131        devices.len() != self.stages.len()
2132    }
2133
2134    fn context_for_dev<'a>(
2135        &'a self,
2136        e: &'a Engine,
2137        dev: usize,
2138    ) -> Result<&'a Arc<CudaContext>, Box<dyn std::error::Error>> {
2139        if dev == e.ctx().ordinal() {
2140            return Ok(e.ctx());
2141        }
2142        self.stages
2143            .iter()
2144            .find(|stage| stage.dev == dev)
2145            .map(|stage| &stage.ctx)
2146            .ok_or_else(|| format!("PP peer probe has no CUDA context for dev{dev}").into())
2147    }
2148
2149    fn enable_probe_peer_access(
2150        &self,
2151        e: &Engine,
2152        pairs: &[(usize, usize)],
2153    ) -> Result<Vec<(usize, usize)>, Box<dyn std::error::Error>> {
2154        let mut enabled = Vec::new();
2155        for &(src_dev, dst_dev) in pairs {
2156            let enable = (|| -> Result<(), Box<dyn std::error::Error>> {
2157                let src_ctx = self.context_for_dev(e, src_dev)?;
2158                let dst_ctx = self.context_for_dev(e, dst_dev)?;
2159                src_ctx.bind_to_thread()?;
2160                let rc = unsafe { cudarc::driver::sys::cuCtxEnablePeerAccess(dst_ctx.cu_ctx(), 0) };
2161                use cudarc::driver::sys::cudaError_enum as E;
2162                if rc == E::CUDA_SUCCESS || rc == E::CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED {
2163                    Ok(())
2164                } else {
2165                    Err(format!("{rc:?}").into())
2166                }
2167            })();
2168            if let Err(err) = enable {
2169                eprintln!(
2170                    "[pp] peer byte-integrity probe could not enable \
2171                     dev{src_dev}->dev{dst_dev}: {err}; MEMRA_PP_HOST_BOUNCE=1 remains active"
2172                );
2173            } else {
2174                enabled.push((src_dev, dst_dev));
2175            }
2176        }
2177        Ok(enabled)
2178    }
2179
2180    fn disable_probe_peer_access(
2181        &self,
2182        e: &Engine,
2183        pairs: &[(usize, usize)],
2184    ) -> Result<(), Box<dyn std::error::Error>> {
2185        let mut failures = Vec::new();
2186        for &(src_dev, dst_dev) in pairs {
2187            let disable = (|| -> Result<(), Box<dyn std::error::Error>> {
2188                let src_ctx = self.context_for_dev(e, src_dev)?;
2189                let dst_ctx = self.context_for_dev(e, dst_dev)?;
2190                src_ctx.bind_to_thread()?;
2191                let rc = unsafe { cudarc::driver::sys::cuCtxDisablePeerAccess(dst_ctx.cu_ctx()) };
2192                use cudarc::driver::sys::cudaError_enum as E;
2193                if rc == E::CUDA_SUCCESS || rc == E::CUDA_ERROR_PEER_ACCESS_NOT_ENABLED {
2194                    Ok(())
2195                } else {
2196                    Err(format!("{rc:?}").into())
2197                }
2198            })();
2199            if let Err(err) = disable {
2200                failures.push(format!("dev{src_dev}->dev{dst_dev}: {err}"));
2201            }
2202        }
2203        e.ctx().bind_to_thread()?;
2204        if failures.is_empty() {
2205            eprintln!(
2206                "[pp] peer byte-integrity probe teardown: disabled {} diagnostic pair(s); \
2207                 host-bounce serving has no probe-enabled peer access",
2208                pairs.len(),
2209            );
2210            Ok(())
2211        } else {
2212            Err(format!(
2213                "PP peer probe could not disable diagnostic peer access ({}); \
2214                 refusing host-bounce serving",
2215                failures.join(", "),
2216            )
2217            .into())
2218        }
2219    }
2220
2221    fn grant_probe_pool_access(
2222        &self,
2223        e: &Engine,
2224        pairs: &[(usize, usize)],
2225    ) -> Result<Vec<(usize, usize)>, Box<dyn std::error::Error>> {
2226        let mut granted = Vec::new();
2227        for &(src_dev, dst_dev) in pairs {
2228            let grant = (|| -> Result<(), Box<dyn std::error::Error>> {
2229                self.context_for_dev(e, dst_dev)?.bind_to_thread()?;
2230                let dev = cudarc::driver::result::device::get(dst_dev as i32)?;
2231                let mut pool: cudarc::driver::sys::CUmemoryPool = std::ptr::null_mut();
2232                unsafe {
2233                    cudarc::driver::sys::cuDeviceGetDefaultMemPool(&mut pool, dev).result()?;
2234                }
2235                let desc = cudarc::driver::sys::CUmemAccessDesc {
2236                    location: cudarc::driver::sys::CUmemLocation {
2237                        type_: cudarc::driver::sys::CUmemLocationType::CU_MEM_LOCATION_TYPE_DEVICE,
2238                        id: src_dev as i32,
2239                    },
2240                    flags:
2241                        cudarc::driver::sys::CUmemAccess_flags::CU_MEM_ACCESS_FLAGS_PROT_READWRITE,
2242                };
2243                let rc = unsafe { cudarc::driver::sys::cuMemPoolSetAccess(pool, &desc, 1) };
2244                if rc == cudarc::driver::sys::cudaError_enum::CUDA_SUCCESS {
2245                    Ok(())
2246                } else {
2247                    Err(format!("{rc:?}").into())
2248                }
2249            })();
2250            if let Err(err) = grant {
2251                eprintln!(
2252                    "[pp] production-slot probe could not grant dev{src_dev} access to \
2253                     dev{dst_dev}'s default pool: {err}; MEMRA_PP_HOST_BOUNCE=1 remains active"
2254                );
2255            } else {
2256                granted.push((src_dev, dst_dev));
2257            }
2258        }
2259        Ok(granted)
2260    }
2261
2262    fn revoke_probe_pool_access(
2263        &self,
2264        e: &Engine,
2265        pairs: &[(usize, usize)],
2266    ) -> Result<(), Box<dyn std::error::Error>> {
2267        let mut failures = Vec::new();
2268        for &(src_dev, dst_dev) in pairs {
2269            let revoke = (|| -> Result<(), Box<dyn std::error::Error>> {
2270                self.context_for_dev(e, dst_dev)?.bind_to_thread()?;
2271                let dev = cudarc::driver::result::device::get(dst_dev as i32)?;
2272                let mut pool: cudarc::driver::sys::CUmemoryPool = std::ptr::null_mut();
2273                unsafe {
2274                    cudarc::driver::sys::cuDeviceGetDefaultMemPool(&mut pool, dev).result()?;
2275                }
2276                let desc = cudarc::driver::sys::CUmemAccessDesc {
2277                    location: cudarc::driver::sys::CUmemLocation {
2278                        type_: cudarc::driver::sys::CUmemLocationType::CU_MEM_LOCATION_TYPE_DEVICE,
2279                        id: src_dev as i32,
2280                    },
2281                    flags: cudarc::driver::sys::CUmemAccess_flags::CU_MEM_ACCESS_FLAGS_PROT_NONE,
2282                };
2283                let rc = unsafe { cudarc::driver::sys::cuMemPoolSetAccess(pool, &desc, 1) };
2284                if rc == cudarc::driver::sys::cudaError_enum::CUDA_SUCCESS {
2285                    Ok(())
2286                } else {
2287                    Err(format!("{rc:?}").into())
2288                }
2289            })();
2290            if let Err(err) = revoke {
2291                failures.push(format!("dev{src_dev}->dev{dst_dev}: {err}"));
2292            }
2293        }
2294        e.ctx().bind_to_thread()?;
2295        if failures.is_empty() {
2296            Ok(())
2297        } else {
2298            Err(format!(
2299                "PP peer probe could not revoke diagnostic pool access ({}); \
2300                 refusing host-bounce serving",
2301                failures.join(", "),
2302            )
2303            .into())
2304        }
2305    }
2306
2307    fn run_host_bounce_legacy_probe(&self, e: &Engine) -> Result<(), Box<dyn std::error::Error>> {
2308        let enabled = self.enable_probe_peer_access(e, &self.peer_capable)?;
2309        let probe = run_peer_probe_pass(
2310            &self.stages,
2311            &enabled,
2312            true,
2313            "fixed-16KiB-legacy-preflight",
2314            PEER_PROBE_FIXED_BYTES,
2315        );
2316        let disable = self.disable_probe_peer_access(e, &enabled);
2317        disable?;
2318        probe
2319    }
2320
2321    fn new_peer_probe_boundary(
2322        &self,
2323        src_stage: usize,
2324        dst_stage: usize,
2325    ) -> Result<BoundaryRt, Box<dyn std::error::Error>> {
2326        let tx = &self.stages[src_stage];
2327        let rx = &self.stages[dst_stage];
2328        let mk_slot = || -> Result<BoundarySlot, Box<dyn std::error::Error>> {
2329            Ok(BoundarySlot {
2330                buf: Mutex::new(None),
2331                ev_tx: tx.ctx.new_event(None)?,
2332                ev_rx: rx.ctx.new_event(None)?,
2333            })
2334        };
2335        Ok(BoundaryRt {
2336            slots: [mk_slot()?, mk_slot()?],
2337            step: AtomicUsize::new(0),
2338            cross: tx.dev != rx.dev,
2339        })
2340    }
2341
2342    fn production_probe_readback(
2343        &self,
2344        path: BoundaryPath,
2345        boundary: &BoundaryRt,
2346        expected: &[u8],
2347        n: usize,
2348        slot_idx: usize,
2349    ) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
2350        debug_assert_eq!(expected.len(), n * std::mem::size_of::<f32>());
2351        let host = peer_probe_bytes_to_f32(expected);
2352        let poison_bytes: Vec<u8> = expected.iter().map(|byte| !byte).collect();
2353        let poison = peer_probe_bytes_to_f32(&poison_bytes);
2354        let src = &self.stages[path.src_stage];
2355        let dst = &self.stages[path.dst_stage];
2356
2357        // Pre-poison the exact stream-ordered BoundarySlot allocation so a missing or partial
2358        // peer write cannot accidentally agree where the deterministic source contains zeroes.
2359        dst.ctx.bind_to_thread()?;
2360        let poison_buf = dst.stream.clone_htod(&poison)?;
2361        dst.stream.synchronize()?;
2362        let replaced = boundary.slots[slot_idx]
2363            .buf
2364            .lock()
2365            .unwrap()
2366            .replace(poison_buf);
2367        drop(replaced);
2368        dst.stream.synchronize()?;
2369
2370        src.ctx.bind_to_thread()?;
2371        let x = src.stream.clone_htod(&host)?;
2372        self.tx_slot_path(path, boundary, &x, n, slot_idx)?;
2373
2374        dst.ctx.bind_to_thread()?;
2375        let work = self.rx_slot_path(path, boundary, slot_idx, n)?;
2376        let back = dst.stream.clone_dtoh(&work)?;
2377        dst.stream.synchronize()?;
2378        Ok(peer_probe_f32_to_bytes(&back))
2379    }
2380
2381    fn clear_peer_probe_boundary(
2382        &self,
2383        boundary: &BoundaryRt,
2384        src_stage: usize,
2385        dst_stage: usize,
2386    ) -> Result<(), Box<dyn std::error::Error>> {
2387        self.stages[dst_stage].ctx.bind_to_thread()?;
2388        for slot in &boundary.slots {
2389            let buffer = slot.buf.lock().unwrap().take();
2390            drop(buffer);
2391        }
2392        self.stages[src_stage].stream.synchronize()?;
2393        self.stages[dst_stage].stream.synchronize()?;
2394        Ok(())
2395    }
2396
2397    fn run_production_peer_probe_widths(
2398        &self,
2399        enabled_pairs: &[(usize, usize)],
2400        host_bounce: bool,
2401        n_embd: usize,
2402        widths: &[usize],
2403    ) -> Result<(), Box<dyn std::error::Error>> {
2404        let started = std::time::Instant::now();
2405        let mut copies = 0usize;
2406        let mut skipped = 0usize;
2407        let mut total_mismatches = 0usize;
2408        let mut largest_clean_payload = 0usize;
2409
2410        for boundary_idx in 0..self.stages.len() - 1 {
2411            if self.stages[boundary_idx].dev == self.stages[boundary_idx + 1].dev {
2412                continue;
2413            }
2414            for (src_stage, dst_stage) in [
2415                (boundary_idx, boundary_idx + 1),
2416                (boundary_idx + 1, boundary_idx),
2417            ] {
2418                let src_dev = self.stages[src_stage].dev;
2419                let dst_dev = self.stages[dst_stage].dev;
2420                if !enabled_pairs.contains(&(src_dev, dst_dev)) {
2421                    if host_bounce {
2422                        skipped += widths.len();
2423                        eprintln!(
2424                            "[pp] production-slot peer probe SKIP: boundary={boundary_idx} \
2425                             dev{src_dev}->dev{dst_dev} widths_tokens={:?} \
2426                             (peer or pool access unavailable; MEMRA_PP_HOST_BOUNCE=1 remains \
2427                             fail-safe)",
2428                            widths,
2429                        );
2430                        continue;
2431                    }
2432                    return Err(format!(
2433                        "PP production-slot peer probe cannot run boundary={boundary_idx} \
2434                         dev{src_dev}->dev{dst_dev}: peer/pool access is not enabled"
2435                    )
2436                    .into());
2437                }
2438
2439                let probe_boundary = self.new_peer_probe_boundary(src_stage, dst_stage)?;
2440                let path = BoundaryPath {
2441                    boundary: boundary_idx,
2442                    src_stage,
2443                    dst_stage,
2444                    transport: BoundaryTransport::Peer,
2445                };
2446                let mut direction_copies = 0usize;
2447                let mut direction_skipped = 0usize;
2448                let mut direction_mismatches = 0usize;
2449                let mut direction_largest_clean = 0usize;
2450                let mut failure = None;
2451
2452                for (width_idx, tokens) in widths.iter().copied().enumerate() {
2453                    let n = n_embd.checked_mul(tokens).ok_or_else(|| {
2454                        format!(
2455                            "PP production-slot probe element count overflows for \
2456                             n_embd={n_embd} tokens={tokens}"
2457                        )
2458                    })?;
2459                    let bytes = n.checked_mul(std::mem::size_of::<f32>()).ok_or_else(|| {
2460                        format!(
2461                            "PP production-slot probe byte count overflows for \
2462                             n_embd={n_embd} tokens={tokens}"
2463                        )
2464                    })?;
2465                    let expected = peer_probe_pattern(bytes, boundary_idx, src_dev, dst_dev);
2466                    let readback = match self.production_probe_readback(
2467                        path,
2468                        &probe_boundary,
2469                        &expected,
2470                        n,
2471                        width_idx % 2,
2472                    ) {
2473                        Ok(readback) => readback,
2474                        Err(err) if host_bounce => {
2475                            skipped += 1;
2476                            direction_skipped += 1;
2477                            eprintln!(
2478                                "[pp] production-slot peer probe ERROR: \
2479                                 boundary={boundary_idx} dev{src_dev}->dev{dst_dev} \
2480                                 tokens={tokens} bytes={bytes}: {err}; \
2481                                 MEMRA_PP_HOST_BOUNCE=1, proceeding on the host-staged path"
2482                            );
2483                            continue;
2484                        }
2485                        Err(err) => {
2486                            failure = Some(format!(
2487                                "PP production-slot peer probe FAILED: \
2488                                 boundary={boundary_idx} dev{src_dev}->dev{dst_dev} \
2489                                 tokens={tokens} bytes={bytes}: {err}; refusing native P2P \
2490                                 (set MEMRA_PP_HOST_BOUNCE=1 to use the host-staged path; \
2491                                 MEMRA_PEER_PROBE=0 cannot authorize sharded native peer \
2492                                 transport)"
2493                            ));
2494                            break;
2495                        }
2496                    };
2497                    copies += 1;
2498                    direction_copies += 1;
2499                    let mismatches = peer_probe_mismatch_count(&expected, &readback);
2500                    if mismatches == 0 {
2501                        largest_clean_payload = largest_clean_payload.max(bytes);
2502                        direction_largest_clean = direction_largest_clean.max(bytes);
2503                    } else if host_bounce {
2504                        total_mismatches += mismatches;
2505                        direction_mismatches += mismatches;
2506                        eprintln!(
2507                            "[pp] production-slot peer probe CORRUPTION: \
2508                             boundary={boundary_idx} dev{src_dev}->dev{dst_dev} tokens={tokens} \
2509                             bytes={bytes} mismatches={mismatches}; MEMRA_PP_HOST_BOUNCE=1, \
2510                             proceeding on the host-staged path"
2511                        );
2512                    } else {
2513                        failure = Some(format!(
2514                            "PP production-slot peer probe FAILED: boundary={boundary_idx} \
2515                             dev{src_dev}->dev{dst_dev} tokens={tokens} bytes={bytes}: \
2516                             {mismatches} mismatched byte(s); refusing native P2P \
2517                             (set MEMRA_PP_HOST_BOUNCE=1 to use the host-staged path; \
2518                             MEMRA_PEER_PROBE=0 cannot authorize sharded native peer transport)"
2519                        ));
2520                        break;
2521                    }
2522                }
2523
2524                self.clear_peer_probe_boundary(&probe_boundary, src_stage, dst_stage)?;
2525                if let Some(err) = failure {
2526                    return Err(err.into());
2527                }
2528                eprintln!(
2529                    "[pp] production-slot peer probe direction: boundary={boundary_idx} \
2530                     dev{src_dev}->dev{dst_dev} copies={direction_copies} \
2531                     skipped={direction_skipped} mismatches={direction_mismatches} \
2532                     largest_clean_payload_bytes={direction_largest_clean}"
2533                );
2534            }
2535        }
2536
2537        let status = if total_mismatches > 0 {
2538            "BOUNCE"
2539        } else if skipped > 0 && copies > 0 {
2540            "PARTIAL"
2541        } else if skipped > 0 {
2542            "SKIP"
2543        } else {
2544            "PASS"
2545        };
2546        eprintln!(
2547            "[pp] production-slot peer probe {status}: widths_tokens={:?} copies={copies} \
2548             skipped={skipped} mismatches={total_mismatches} \
2549             largest_clean_payload_bytes={largest_clean_payload} elapsed_ms={:.3}",
2550            widths,
2551            started.elapsed().as_secs_f64() * 1e3,
2552        );
2553        Ok(())
2554    }
2555
2556    fn run_production_peer_probe(
2557        &self,
2558        enabled_pairs: &[(usize, usize)],
2559        host_bounce: bool,
2560        n_embd: usize,
2561    ) -> Result<(), Box<dyn std::error::Error>> {
2562        self.run_production_peer_probe_widths(
2563            enabled_pairs,
2564            host_bounce,
2565            n_embd,
2566            &PEER_PROBE_TOKEN_WIDTHS,
2567        )
2568    }
2569
2570    fn run_host_bounce_production_probe(
2571        &self,
2572        e: &Engine,
2573        n_embd: usize,
2574    ) -> Result<(), Box<dyn std::error::Error>> {
2575        let enabled = self.enable_probe_peer_access(e, &self.peer_capable)?;
2576        let granted = self.grant_probe_pool_access(e, &enabled)?;
2577        let probe = self.run_production_peer_probe(&granted, true, n_embd);
2578        // Teardown always runs, but the probe verdict wins: a CORRUPTION verdict (probe is
2579        // Err) must never be masked by a teardown failure. `revoke?; disable?; probe`
2580        // short-circuited teardown errors BEFORE probe was inspected, discarding the byte-
2581        // integrity signal on any teardown hiccup (hermes 9d6ae8d3). Surface teardown errors
2582        // only when the probe itself succeeded.
2583        let revoke = self.revoke_probe_pool_access(e, &granted);
2584        let disable = self.disable_probe_peer_access(e, &enabled);
2585        probe?;
2586        revoke?;
2587        disable?;
2588        Ok(())
2589    }
2590
2591    fn init_peer_probe_geometry(
2592        &self,
2593        e: &Engine,
2594        n_embd: usize,
2595    ) -> Result<(), Box<dyn std::error::Error>> {
2596        if !self.peer_probe || !self.cross_any {
2597            return Ok(());
2598        }
2599        let bytes = n_embd
2600            .checked_mul(std::mem::size_of::<f32>())
2601            .ok_or_else(|| format!("PP boundary-slot byte count overflows for n_embd={n_embd}"))?;
2602        let result = self.peer_probe_geometry.get_or_init(|| {
2603            let probe = if self.host_bounce_active() {
2604                self.run_host_bounce_production_probe(e, n_embd)
2605            } else {
2606                self.run_production_peer_probe(&self.peer_capable, false, n_embd)
2607            };
2608            let restore = e.ctx().bind_to_thread();
2609            match (probe, restore) {
2610                (Ok(()), Ok(())) => Ok(bytes),
2611                (Err(err), _) => Err(err.to_string()),
2612                (_, Err(err)) => Err(err.to_string()),
2613            }
2614        });
2615        let probed = result
2616            .as_ref()
2617            .map_err(|err| -> Box<dyn std::error::Error> { err.clone().into() })?;
2618        if *probed != bytes {
2619            return Err(format!(
2620                "peer probe initialized for boundary-slot bytes={probed} but model requests \
2621                 bytes={bytes}; one PP runtime supports one model geometry per process"
2622            )
2623            .into());
2624        }
2625        Ok(())
2626    }
2627
2628    fn init_host_bounce_staging(
2629        &self,
2630        e: &Engine,
2631        n_embd: usize,
2632    ) -> Result<(), Box<dyn std::error::Error>> {
2633        if !self.cross_any {
2634            return Ok(());
2635        }
2636        e.ctx().bind_to_thread()?;
2637        let result = self.bounce.get_or_init(|| {
2638            HostBounceRt::new(n_embd, &self.boundaries)
2639                .inspect(|rt| {
2640                    let bytes = rt.capacity * std::mem::size_of::<f32>();
2641                    eprintln!(
2642                        "[pp] host-bounce staging ready: n_embd={n_embd} max_tokens={} \
2643                         slot_bytes={bytes} slots_per_cross_boundary=2",
2644                        crate::cache::PRIME_CHUNK_MAX_TOKENS,
2645                    );
2646                })
2647                .map_err(|err| err.to_string())
2648        });
2649        let bounce = result
2650            .as_ref()
2651            .map_err(|err| -> Box<dyn std::error::Error> { err.clone().into() })?;
2652        if bounce.n_embd != n_embd {
2653            return Err(format!(
2654                "host-bounce runtime initialized for n_embd={} but model requests n_embd={n_embd}; \
2655                 one PP runtime supports one model geometry per process",
2656                bounce.n_embd,
2657            )
2658            .into());
2659        }
2660        Ok(())
2661    }
2662
2663    /// Exercise the newly armed staging through the real D2H/event/H2D boundary path before the
2664    /// live transport latch can observe it. One row per cross boundary is enough to validate the
2665    /// pinned capacity, event ordering, contexts, and byte continuity without touching peer DMA.
2666    fn validate_host_bounce_staging(
2667        &self,
2668        e: &Engine,
2669        n_embd: usize,
2670    ) -> Result<(), Box<dyn std::error::Error>> {
2671        let bytes = n_embd
2672            .checked_mul(std::mem::size_of::<f32>())
2673            .ok_or_else(|| {
2674                format!("host-bounce validation byte count overflows for n_embd={n_embd}")
2675            })?;
2676        for boundary_idx in 0..self.stages.len() - 1 {
2677            if !self.boundaries[boundary_idx].cross {
2678                continue;
2679            }
2680            let src_stage = boundary_idx;
2681            let dst_stage = boundary_idx + 1;
2682            let probe_boundary = self.new_peer_probe_boundary(src_stage, dst_stage)?;
2683            let path = BoundaryPath {
2684                boundary: boundary_idx,
2685                src_stage,
2686                dst_stage,
2687                transport: BoundaryTransport::HostBounce,
2688            };
2689            let expected = peer_probe_pattern(
2690                bytes,
2691                boundary_idx,
2692                self.stages[src_stage].dev,
2693                self.stages[dst_stage].dev,
2694            );
2695            let readback =
2696                self.production_probe_readback(path, &probe_boundary, &expected, n_embd, 0);
2697            let clear = self.clear_peer_probe_boundary(&probe_boundary, src_stage, dst_stage);
2698            let readback = readback?;
2699            clear?;
2700            let mismatches = peer_probe_mismatch_count(&expected, &readback);
2701            if mismatches > 0 {
2702                return Err(format!(
2703                    "runtime host-bounce staging validation FAILED: boundary={boundary_idx} \
2704                     bytes={bytes} mismatches={mismatches}"
2705                )
2706                .into());
2707            }
2708        }
2709        e.ctx().bind_to_thread()?;
2710        eprintln!(
2711            "[pp] runtime host-bounce staging validation PASS: row_bytes={bytes} \
2712             cross_boundaries={}",
2713            self.boundaries
2714                .iter()
2715                .filter(|boundary| boundary.cross)
2716                .count(),
2717        );
2718        Ok(())
2719    }
2720
2721    fn arm_runtime_host_bounce(
2722        &self,
2723        e: &Engine,
2724        row_bytes: usize,
2725    ) -> Result<(), Box<dyn std::error::Error>> {
2726        if row_bytes == 0 || !row_bytes.is_multiple_of(std::mem::size_of::<f32>()) {
2727            return Err(format!(
2728                "runtime host-bounce cannot recover n_embd from row_bytes={row_bytes}"
2729            )
2730            .into());
2731        }
2732        let n_embd = row_bytes / std::mem::size_of::<f32>();
2733        self.init_host_bounce_staging(e, n_embd)?;
2734        self.validate_host_bounce_staging(e, n_embd)
2735    }
2736
2737    /// Finish boot-time transport setup from the authoritative model width. This runs the
2738    /// production `BoundarySlot` ladder at 1/8/16/`PRIME_CHUNK_MAX_TOKENS` `[n_embd] f32` rows
2739    /// once, then allocates host-bounce slots when selected. The loader calls it before uploading
2740    /// the first model weight; `new_cache` repeats the call as an idempotent guard before the first
2741    /// forward.
2742    pub fn init_boundary_transport(
2743        &self,
2744        e: &Engine,
2745        n_embd: usize,
2746    ) -> Result<(), Box<dyn std::error::Error>> {
2747        if PEER_RUNTIME_PROBE_FAILED.load(Ordering::Acquire)
2748            && !PEER_RUNTIME_HOST_BOUNCE.load(Ordering::Acquire)
2749        {
2750            return Err(
2751                "PP runtime peer byte-integrity probe previously failed; refusing native P2P \
2752                 reuse because runtime host-bounce staging could not be armed"
2753                    .into(),
2754            );
2755        }
2756        self.init_peer_probe_geometry(e, n_embd)?;
2757        if !self.host_bounce_active() || !self.cross_any {
2758            return Ok(());
2759        }
2760        self.init_host_bounce_staging(e, n_embd)
2761    }
2762
2763    /// Run one due peer re-probe at a scheduler boundary on the CUDA owner thread. Each width has
2764    /// an independent copy-count deadline: an idle-only rung can remain pending while later cheap
2765    /// rungs keep running. The probe synchronizes the stage streams it exercises; no background
2766    /// thread touches CUDA.
2767    fn service_runtime_peer_probe(
2768        &self,
2769        e: &Engine,
2770        scheduler_idle: bool,
2771        probe_allowed: bool,
2772    ) -> Result<RuntimePeerProbeStatus, Box<dyn std::error::Error>> {
2773        if !self.peer_probe || !self.cross_any || self.host_bounce_active() {
2774            return Ok(RuntimePeerProbeStatus::NotRun);
2775        }
2776        if PEER_RUNTIME_PROBE_FAILED.load(Ordering::Acquire) {
2777            return Err(
2778                "PP runtime peer byte-integrity probe previously failed; native P2P is latched off"
2779                    .into(),
2780            );
2781        }
2782        let row_bytes = match self.peer_probe_geometry.get() {
2783            Some(Ok(bytes)) => *bytes,
2784            _ => return Ok(RuntimePeerProbeStatus::NotRun),
2785        };
2786
2787        let copies = PEER_BOUNDARY_COPIES.load(Ordering::Relaxed);
2788        let (width_index, tokens) = loop {
2789            let next_probe_copy = std::array::from_fn(|width_index| {
2790                PEER_RUNTIME_NEXT_PROBE_COPY[width_index].load(Ordering::Relaxed)
2791            });
2792            let measured_cost_ns = std::array::from_fn(|width_index| {
2793                PEER_RUNTIME_PROBE_MAX_COST_NS[width_index].load(Ordering::Relaxed)
2794            });
2795            let Some(candidate) = runtime_peer_probe_candidate(
2796                copies,
2797                next_probe_copy,
2798                measured_cost_ns,
2799                scheduler_idle,
2800            ) else {
2801                return Ok(RuntimePeerProbeStatus::NotRun);
2802            };
2803            // A mismatch immediately revokes native peer access before validated host bounce is
2804            // published. Live speculative sessions still dereference token/position state through
2805            // UVA outside the bounced boundary, so the worker may defer a runnable cheap rung until
2806            // those sessions retire. Do not consume its deadline or completed-probe counter.
2807            if !probe_allowed {
2808                return Ok(RuntimePeerProbeStatus::Deferred);
2809            }
2810            let due = next_probe_copy[candidate.0];
2811            let next = runtime_peer_probe_next_copy(due, copies);
2812            if PEER_RUNTIME_NEXT_PROBE_COPY[candidate.0]
2813                .compare_exchange(due, next, Ordering::AcqRel, Ordering::Relaxed)
2814                .is_ok()
2815            {
2816                break candidate;
2817            }
2818        };
2819        let probe_index = PEER_RUNTIME_PROBES.fetch_add(1, Ordering::Relaxed);
2820        let probe_bytes = row_bytes.checked_mul(tokens);
2821        let started = std::time::Instant::now();
2822        let probe = match probe_bytes {
2823            Some(_) => self.run_production_peer_probe_widths(
2824                &self.peer_capable,
2825                false,
2826                row_bytes / std::mem::size_of::<f32>(),
2827                &[tokens],
2828            ),
2829            None => Err(format!(
2830                "PP runtime peer probe byte count overflows for row_bytes={row_bytes} \
2831                 tokens={tokens}"
2832            )
2833            .into()),
2834        };
2835        let restore = e.ctx().bind_to_thread();
2836        let elapsed_ns = started.elapsed().as_nanos().min(u64::MAX as u128) as u64;
2837        let previous_max =
2838            PEER_RUNTIME_PROBE_MAX_COST_NS[width_index].fetch_max(elapsed_ns, Ordering::Relaxed);
2839        let verdict = match (probe, restore) {
2840            (Ok(()), Ok(())) => Ok(()),
2841            (Err(err), _) => Err(err.to_string()),
2842            (_, Err(err)) => Err(err.to_string()),
2843        };
2844        if let Err(err) = verdict {
2845            PEER_RUNTIME_PROBE_FAILURES.fetch_add(1, Ordering::Relaxed);
2846            let arm = latch_runtime_host_bounce(
2847                &PEER_RUNTIME_PROBE_FAILED,
2848                &PEER_RUNTIME_HOST_BOUNCE,
2849                || {
2850                    self.arm_runtime_host_bounce(e, row_bytes)
2851                        .map_err(|arm_err| arm_err.to_string())
2852                },
2853            );
2854            if let Err(arm_err) = arm {
2855                let message = format!(
2856                    "PP runtime peer byte-integrity re-probe FAILED after \
2857                     boundary_copies={copies} rung={}/{} tokens={tokens}: {err}; native P2P is \
2858                     latched off and host-bounce staging could not be armed: {arm_err}",
2859                    width_index + 1,
2860                    PEER_PROBE_TOKEN_WIDTHS.len(),
2861                );
2862                eprintln!("[pp] SECURITY RED: {message}; worker must stop");
2863                return Err(message.into());
2864            }
2865            eprintln!(
2866                "[pp] SECURITY RED: PP runtime peer byte-integrity re-probe FAILED after \
2867                 boundary_copies={copies} rung={}/{} tokens={tokens}: {err}; native P2P is \
2868                 latched off and the live transport DEGRADED to validated host bounce for the \
2869                 remainder of this process",
2870                width_index + 1,
2871                PEER_PROBE_TOKEN_WIDTHS.len(),
2872            );
2873            return Ok(RuntimePeerProbeStatus::DegradedToHostBounce);
2874        }
2875        if width_index + 1 != PEER_PROBE_TOKEN_WIDTHS.len()
2876            && previous_max <= PEER_RUNTIME_PROBE_BUDGET_NS
2877            && elapsed_ns > PEER_RUNTIME_PROBE_BUDGET_NS
2878        {
2879            eprintln!(
2880                "[pp] runtime peer re-probe rung exceeded the {:.3}ms owner-thread budget: \
2881                 tokens={tokens} measured_ms={:.3}; future runs are idle-only",
2882                PEER_RUNTIME_PROBE_BUDGET_NS as f64 / 1e6,
2883                elapsed_ns as f64 / 1e6,
2884            );
2885        }
2886        eprintln!(
2887            "[pp] runtime peer byte-integrity re-probe PASS: \
2888             boundary_copies={copies} interval_copies={PEER_RUNTIME_PROBE_INTERVAL_COPIES} \
2889             rung={}/{} tokens={tokens} bytes={} probe_index={probe_index} elapsed_ms={:.3} \
2890             scheduler_idle={scheduler_idle}",
2891            width_index + 1,
2892            PEER_PROBE_TOKEN_WIDTHS.len(),
2893            probe_bytes.unwrap(),
2894            elapsed_ns as f64 / 1e6,
2895        );
2896        Ok(RuntimePeerProbeStatus::Passed)
2897    }
2898
2899    fn bounce_rt(&self) -> Result<&HostBounceRt, Box<dyn std::error::Error>> {
2900        self.bounce
2901            .get()
2902            .ok_or_else(|| -> Box<dyn std::error::Error> {
2903                "MEMRA_PP_HOST_BOUNCE=1 staging was not initialized from model geometry".into()
2904            })?
2905            .as_ref()
2906            .map_err(|err| -> Box<dyn std::error::Error> { err.clone().into() })
2907    }
2908
2909    /// The engine a stage's subgraph must run through: the primary engine when the stage
2910    /// lives on the primary device, else the stage's own (remote-context) engine.
2911    pub fn engine<'a>(&'a self, s: usize, primary: &'a Engine) -> &'a Engine {
2912        self.stages[s].engine.as_ref().unwrap_or(primary)
2913    }
2914
2915    /// Bind this OS thread to stage `s`'s CUDA context before issuing work there.
2916    pub fn bind_stage(&self, s: usize) -> Result<(), Box<dyn std::error::Error>> {
2917        self.stages[s].ctx.bind_to_thread()?;
2918        Ok(())
2919    }
2920
2921    /// Enter stage `s`: until the guard drops, every engine op on this thread launches on
2922    /// the stage's stream (memra_runtime ambient-stream override).
2923    pub fn enter(&self, s: usize) -> memra_runtime::StreamOverride {
2924        memra_runtime::push_stream_override(
2925            self.stages[s].stream.clone(),
2926            self.stages[s].blas.clone(),
2927        )
2928    }
2929
2930    /// Allocate/grow BOTH slots for a boundary before pipelined issue starts. `tx()` can
2931    /// grow a slot lazily, but first-use ordering requires synchronizing the RX stream
2932    /// after that allocation. If slot 1 first grows after stage 1 of chunk N has already
2933    /// been queued, that sync drains chunk N and erases the only overlap in a two-chunk
2934    /// prime. Prewarming both slots pays the same one-time sync before either stage starts.
2935    pub fn prepare_overlap_slots(
2936        &self,
2937        b: usize,
2938        n: usize,
2939    ) -> Result<(), Box<dyn std::error::Error>> {
2940        let bd = &self.boundaries[b];
2941        let s_rx = &self.stages[b + 1].stream;
2942        let mut grew = false;
2943        for sl in &bd.slots {
2944            let mut guard = sl.buf.lock().unwrap();
2945            if guard.as_ref().map(|bf| bf.len() < n).unwrap_or(true) {
2946                *guard = Some(s_rx.alloc_zeros::<f32>(n)?);
2947                grew = true;
2948            }
2949        }
2950        if grew {
2951            s_rx.synchronize()?;
2952        }
2953        Ok(())
2954    }
2955
2956    /// Project only the additional device bytes needed to grow this process-global boundary to
2957    /// `n` elements per slot. Admission must not charge the full persistent high-water to every
2958    /// session after it already exists.
2959    pub fn boundary_slot_growth_bytes(
2960        &self,
2961        b: usize,
2962        n: usize,
2963    ) -> Result<usize, Box<dyn std::error::Error>> {
2964        let boundary = self
2965            .boundaries
2966            .get(b)
2967            .ok_or_else(|| format!("PP boundary {b} is outside the runtime"))?;
2968        let mut current = [0usize; 2];
2969        for (index, slot) in boundary.slots.iter().enumerate() {
2970            let guard = slot
2971                .buf
2972                .lock()
2973                .map_err(|_| format!("PP boundary {b} slot lock is poisoned"))?;
2974            current[index] = guard.as_ref().map_or(0, CudaSlice::len);
2975        }
2976        let elements = boundary_slot_growth_elements(current, n);
2977        Ok(elements.saturating_mul(std::mem::size_of::<f32>()))
2978    }
2979
2980    /// Boundary TX at boundary `b` (call within the stage-`b` scope; `x` = the
2981    /// materialized [n] residual): wait for the slot's previous RX (write-after-read
2982    /// guard), copy `x` into the slot's persistent buffer via the boundary's transport on
2983    /// stage-b's stream (the owning-stream/publication law), record ev_tx. Returns the
2984    /// slot index for the paired rx().
2985    ///
2986    /// `n` is the PAYLOAD ELEMENT COUNT, not a fixed model constant: the eager arm passes
2987    /// `n_embd` (one row), the batched arm passes `b_n * n_embd` (B stacked rows, the
2988    /// [B, n_embd] boundary). The slot buffer is GROW-ONLY and the transport moves exactly
2989    /// the first `n` elements — batched serving changes B every tick (chunk fill), and a
2990    /// realloc-on-every-size-change would host-sync the RX stream per width change (see the
2991    /// SLOT FIRST-USE ORDERING note below for why each allocation needs that sync). Growing
2992    /// to the high-water mark makes the syncs O(distinct widths) instead of O(width changes).
2993    pub fn tx(
2994        &self,
2995        b: usize,
2996        x: &CudaSlice<f32>,
2997        n: usize,
2998    ) -> Result<usize, Box<dyn std::error::Error>> {
2999        assert_eq!(x.len(), n, "pp tx: residual length mismatch");
3000        let bd = &self.boundaries[b];
3001        let slot_idx = if pp2_overlap() {
3002            bd.step.fetch_add(1, Ordering::Relaxed) % 2
3003        } else {
3004            0
3005        };
3006        self.tx_slot(b, x, n, slot_idx)
3007    }
3008
3009    /// Pipelined boundary TX: always alternate the shared double-buffer slots, independent
3010    /// of the decode-side `MEMRA_PP_OVERLAP` experiment flag. The boundary-local atomic
3011    /// keeps concurrent callers on one slot sequence rather than each restarting at A.
3012    pub fn tx_pipelined(
3013        &self,
3014        b: usize,
3015        x: &CudaSlice<f32>,
3016        n: usize,
3017    ) -> Result<usize, Box<dyn std::error::Error>> {
3018        assert_eq!(x.len(), n, "pp tx: residual length mismatch");
3019        let slot_idx = self.boundaries[b].step.fetch_add(1, Ordering::Relaxed) % 2;
3020        self.tx_slot(b, x, n, slot_idx)
3021    }
3022
3023    fn tx_slot(
3024        &self,
3025        b: usize,
3026        x: &CudaSlice<f32>,
3027        n: usize,
3028        slot_idx: usize,
3029    ) -> Result<usize, Box<dyn std::error::Error>> {
3030        let bd = &self.boundaries[b];
3031        let path = BoundaryPath {
3032            boundary: b,
3033            src_stage: b,
3034            dst_stage: b + 1,
3035            transport: boundary_transport(bd.cross, self.host_bounce_active()),
3036        };
3037        let copied_slot = self.tx_slot_path(path, bd, x, n, slot_idx)?;
3038        if path.transport == BoundaryTransport::Peer {
3039            PEER_BOUNDARY_COPIES.fetch_add(1, Ordering::Relaxed);
3040        }
3041        Ok(copied_slot)
3042    }
3043
3044    fn tx_slot_path(
3045        &self,
3046        path: BoundaryPath,
3047        bd: &BoundaryRt,
3048        x: &CudaSlice<f32>,
3049        n: usize,
3050        slot_idx: usize,
3051    ) -> Result<usize, Box<dyn std::error::Error>> {
3052        debug_assert!(slot_idx < 2);
3053        let sl = &bd.slots[slot_idx];
3054        let s_tx = &self.stages[path.src_stage].stream;
3055        s_tx.wait(&sl.ev_rx)?;
3056        let mut guard = sl.buf.lock().unwrap();
3057        if guard.as_ref().map(|bf| bf.len() < n).unwrap_or(true) {
3058            // allocated on the RX stage's stream: the buffer lives on the RX device.
3059            let s_rx = &self.stages[path.dst_stage].stream;
3060            *guard = Some(s_rx.alloc_zeros::<f32>(n)?);
3061            // SLOT FIRST-USE ORDERING (2026-08-02 pipelined-gate find): the lazy alloc's
3062            // pool-alloc + memset enqueue on the RX stream; the TX copy below issues on
3063            // the TX stream, and on a slot's FIRST use ev_rx has never been recorded —
3064            // nothing orders them. With >=2 tokens in flight the RX stream is still busy
3065            // with the previous token, the memset lands AFTER the TX copy, and the
3066            // boundary residual is zeroed (window=1 passed, window>=2 failed at the
3067            // slot-1 first-use step; -overlap arms passed because the synchronous serial
3068            // arm pre-warmed both slots). Host-sync the RX stream once per slot
3069            // allocation — at most 2*(N-1) one-time syncs per process, all during prime.
3070            s_rx.synchronize()?;
3071        }
3072        let buf = guard.as_mut().unwrap();
3073        match path.transport {
3074            BoundaryTransport::Local => s_tx.memcpy_dtod(x, buf)?,
3075            BoundaryTransport::HostBounce => {
3076                debug_assert_eq!(path.src_stage, path.boundary);
3077                debug_assert_eq!(path.dst_stage, path.boundary + 1);
3078                let bounce = self.bounce_rt()?;
3079                if n > bounce.capacity {
3080                    return Err(format!(
3081                        "pp host-bounce payload {n} exceeds geometry-sized capacity {} \
3082                         (n_embd={}, max prime tokens={})",
3083                        bounce.capacity,
3084                        bounce.n_embd,
3085                        crate::cache::PRIME_CHUNK_MAX_TOKENS,
3086                    )
3087                    .into());
3088                }
3089                let mut host = bounce.slot(path.boundary, slot_idx)?.lock().unwrap();
3090                // D2H is issued on the producing stage's stream. ev_tx below publishes the
3091                // completed host bytes to the receiving stream; the exact prefix avoids moving
3092                // a full 64 MiB slot for a one-row decode, and no peer pointer is formed here.
3093                s_tx.memcpy_dtoh(x, host.prefix_mut(n))?;
3094            }
3095            BoundaryTransport::Peer => {
3096                // cudaMemcpyPeerAsync (M0: 2.8x NCCL at PP activation sizes), issued on the
3097                // publishing TX stream with explicit src/dst contexts.
3098                use cudarc::driver::{DevicePtr, DevicePtrMut};
3099                let (sp, _g0) = x.device_ptr(s_tx);
3100                let (dp, _g1) = buf.device_ptr_mut(s_tx);
3101                self.stages[path.src_stage].ctx.bind_to_thread()?;
3102                unsafe {
3103                    cudarc::driver::result::memcpy_peer_async(
3104                        self.stages[path.dst_stage].ctx.cu_ctx(),
3105                        dp,
3106                        self.stages[path.src_stage].ctx.cu_ctx(),
3107                        sp,
3108                        n * std::mem::size_of::<f32>(),
3109                        s_tx.cu_stream(),
3110                    )?;
3111                }
3112            }
3113        }
3114        sl.ev_tx.record(s_tx)?;
3115        Ok(slot_idx)
3116    }
3117
3118    /// Boundary RX at boundary `b` (call within the stage-`b+1` scope): wait on the slot's
3119    /// ev_tx, copy the boundary buffer into a fresh working buffer (dtod on the RX stream —
3120    /// local on the RX device in both transports), record ev_rx. The returned buffer is
3121    /// RX-stage-owned: allocated, consumed, and eventually freed on that stage's stream.
3122    pub fn rx(
3123        &self,
3124        b: usize,
3125        slot_idx: usize,
3126        n: usize,
3127    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3128        let bd = &self.boundaries[b];
3129        let path = BoundaryPath {
3130            boundary: b,
3131            src_stage: b,
3132            dst_stage: b + 1,
3133            transport: boundary_transport(bd.cross, self.host_bounce_active()),
3134        };
3135        self.rx_slot_path(path, bd, slot_idx, n)
3136    }
3137
3138    fn rx_slot_path(
3139        &self,
3140        path: BoundaryPath,
3141        bd: &BoundaryRt,
3142        slot_idx: usize,
3143        n: usize,
3144    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3145        let sl = &bd.slots[slot_idx];
3146        let s_rx = &self.stages[path.dst_stage].stream;
3147        s_rx.wait(&sl.ev_tx)?;
3148        let mut guard = sl.buf.lock().unwrap();
3149        let buf = guard.as_mut().expect("pp rx before tx");
3150        assert!(
3151            buf.len() >= n,
3152            "pp rx: slot holds {} < requested {n}",
3153            buf.len()
3154        );
3155        if path.transport == BoundaryTransport::HostBounce {
3156            debug_assert_eq!(path.src_stage, path.boundary);
3157            debug_assert_eq!(path.dst_stage, path.boundary + 1);
3158            let bounce = self.bounce_rt()?;
3159            let host = bounce.slot(path.boundary, slot_idx)?.lock().unwrap();
3160            let mut dst = buf.slice_mut(0..n);
3161            // The destination stream already waits ev_tx, so this H2D cannot observe the
3162            // staging slot before the source stream's D2H completes.
3163            s_rx.memcpy_htod(host.prefix(n), &mut dst)?;
3164        }
3165        // uninit working buffer (fully overwritten by the copy), allocated explicitly on
3166        // the stage stream so rx() is correct even outside an enter() scope.
3167        let mut work = unsafe { s_rx.alloc::<f32>(n)? };
3168        // Slice the slot to the payload: the buffer is grow-only (see tx), so at a narrower
3169        // width it is LONGER than `work` and cudarc's memcpy_dtod (dst.len() >= src.len())
3170        // would assert. The paired tx wrote exactly these first n elements.
3171        s_rx.memcpy_dtod(&buf.slice(0..n), &mut work)?;
3172        sl.ev_rx.record(s_rx)?;
3173        Ok(work)
3174    }
3175
3176    /// PUBLISH a DEVICE-RESIDENT result off the last stage to the caller's stream
3177    /// (lane/pp2-spec 2026-08-06).
3178    ///
3179    /// Every ppN body before this one returned HOST values — `decode_step_h_ppn` and
3180    /// `decode_step_batch_ppn` both `dtoh` inside the last-stage scope, and a dtoh on the
3181    /// producing stream is self-ordering. The verify trunk is the FIRST ppN body whose
3182    /// contract is device-resident output (`decode_step_t_h_emb_dev` exists precisely so the
3183    /// accept walk argmaxes on-device instead of moving T x n_vocab f32 per round), and
3184    /// device slices carry no stream affinity: the caller resumes on the PRIMARY stream and
3185    /// dereferences buffers whose producing kernels are still queued on the last stage's
3186    /// stream. Nothing orders them.
3187    ///
3188    /// Why this only ever failed on ONE device: with stages on separate devices the caller's
3189    /// first touch is a cross-device copy that the driver orders against the source context,
3190    /// and the readback path syncs. Two streams on the SAME device genuinely overlap, so the
3191    /// primary stream reads a buffer whose matmul has not run — nondeterministic garbage
3192    /// (measured: NaN, 3155.677, and 2.87e-5 where the reference had -2.0048926), and it
3193    /// poisons the NEXT arm in the same process because the corrupted KV persists. This is
3194    /// the same class as the SLOT FIRST-USE ORDERING find above, one level up: there the
3195    /// unordered pair was alloc-memset vs TX copy, here it is stage-N compute vs the
3196    /// caller's consumer.
3197    ///
3198    /// Fix = the boundary law applied to the exit: record an event on the producing stage
3199    /// stream, make the caller's stream wait on it. Event-wait, not a device sync, so the
3200    /// stage streams keep running for the deferred-readback arm. Call INSIDE the last-stage
3201    /// scope, after the last enqueue, with the caller's (pre-`enter`) stream.
3202    pub fn publish_to(
3203        &self,
3204        s: usize,
3205        dst: &Arc<CudaStream>,
3206    ) -> Result<(), Box<dyn std::error::Error>> {
3207        let st = &self.stages[s];
3208        // Same stream (STREAMS=0 rollback, or a caller already on the stage stream): the
3209        // stream orders itself; recording+waiting would be a no-op with a stray event.
3210        if Arc::ptr_eq(&st.stream, dst) {
3211            return Ok(());
3212        }
3213        let ev = st.ctx.new_event(None)?;
3214        ev.record(&st.stream)?;
3215        dst.wait(&ev)?;
3216        Ok(())
3217    }
3218
3219    /// REVERSE PUBLICATION (#87 root cause, lane/pp2spec-crash 2026-08-07): order every
3220    /// STAGE stream behind the CALLER's stream — the mirror of `publish_to`.
3221    ///
3222    /// `publish_to` orders caller READS behind stage COMPUTE. Nothing ordered the other
3223    /// direction: buffers ALLOCATED on a stage stream (the verify's returned logits/hidden,
3224    /// the VerifyCkpt stashes) are CONSUMED by kernels the caller enqueues on the PRIMARY
3225    /// stream, and when they drop, cudarc enqueues `free_async` on the ALLOCATING (stage)
3226    /// stream. With event tracking elided (the decode-path default) the drop carries no
3227    /// read-guard, so the pool can hand the block to the NEXT stage-stream allocation and
3228    /// its writes overwrite memory the queued primary-stream consumer has not read yet.
3229    /// Measured (research/pp2spec-crash-20260807): the spec round-seed read 13/4096 NaN =
3230    /// the uninitialized-bits signature (P(NaN|random u32) ~ 1/256), clean by host re-read
3231    /// time — a read-before-write race, fatal via the argmax-sentinel -> embed_gather MMU
3232    /// fault, and gated on c>=2 because a backed-up primary stream widens the window.
3233    ///
3234    /// Fix law: before a ppN body enqueues NEW stage-stream work (allocations that may
3235    /// reuse freed blocks), every stage stream waits the caller's stream at its current
3236    /// point. All primary consumers of the previous round's stage-allocated buffers are
3237    /// enqueued by then (single host thread), so reuse-writes land strictly after them.
3238    /// Call at ppN-body ENTRY with the pre-`enter` caller stream. Door-shut configs never
3239    /// build a PpNRt, so single-card behavior is untouched.
3240    pub fn fence_stages_behind(
3241        &self,
3242        src: &Arc<CudaStream>,
3243    ) -> Result<(), Box<dyn std::error::Error>> {
3244        let ev = src.context().new_event(None)?;
3245        ev.record(src)?;
3246        for st in &self.stages {
3247            if Arc::ptr_eq(&st.stream, src) {
3248                continue;
3249            }
3250            st.stream.wait(&ev)?;
3251        }
3252        Ok(())
3253    }
3254
3255    /// Deferred readback: record a fresh completion event on the LAST stage's stream
3256    /// (call after the step's logits matmul has been enqueued there).
3257    pub fn record_done(&self) -> Result<CudaEvent, Box<dyn std::error::Error>> {
3258        let last = &self.stages[self.stages.len() - 1];
3259        let ev = last.ctx.new_event(None)?;
3260        ev.record(&last.stream)?;
3261        Ok(ev)
3262    }
3263
3264    /// The dedicated readback stream (last stage's context).
3265    pub fn readback_stream(&self) -> &Arc<CudaStream> {
3266        &self.readback
3267    }
3268}
3269
3270/// Service a due runtime peer probe without constructing a PP runtime on door-shut placements.
3271/// Must be called by the CUDA owner thread at a scheduling boundary.
3272pub fn service_runtime_peer_probe(
3273    e: &Engine,
3274    scheduler_idle: bool,
3275    probe_allowed: bool,
3276) -> Result<RuntimePeerProbeStatus, Box<dyn std::error::Error>> {
3277    let Some(rt) = RTN.get() else {
3278        return Ok(RuntimePeerProbeStatus::NotRun);
3279    };
3280    let rt = rt
3281        .as_ref()
3282        .map_err(|err| -> Box<dyn std::error::Error> { err.clone().into() })?;
3283    rt.service_runtime_peer_probe(e, scheduler_idle, probe_allowed)
3284}
3285
3286/// M2 increment 3: a step's logits, still device-resident on the LAST stage. `wait()`
3287/// orders the readback stream behind the step's completion event, copies, and syncs —
3288/// tokens enqueued after this step keep running on the stage streams while the caller
3289/// drains token t. Dropping without waiting is safe (buffers free stream-ordered).
3290pub struct PendingLogits {
3291    logits: CudaSlice<f32>,
3292    ev: CudaEvent,
3293    rb: Arc<CudaStream>,
3294    _walk: PpWalkLease,
3295}
3296
3297impl PendingLogits {
3298    pub(crate) fn new(
3299        logits: CudaSlice<f32>,
3300        ev: CudaEvent,
3301        rb: Arc<CudaStream>,
3302        walk: PpWalkLease,
3303    ) -> Self {
3304        PendingLogits {
3305            logits,
3306            ev,
3307            rb,
3308            _walk: walk,
3309        }
3310    }
3311
3312    /// Blocks until this step's logits are computed, returns them host-side. Only this
3313    /// step's work is waited on (event-ordered) — NOT later tokens already enqueued on
3314    /// the stage streams.
3315    pub fn wait(self) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
3316        self.rb.wait(&self.ev)?;
3317        let host = self.rb.clone_dtoh(&self.logits)?;
3318        self.rb.synchronize()?;
3319        // logits drop AFTER the sync: the D2H has fully completed, so the stream-ordered
3320        // free on the compute stream cannot race the copy.
3321        Ok(host)
3322    }
3323}
3324
3325/// Bring up the PP transport while model geometry is known but before model weights upload.
3326/// Door-shut and placement-free loads remain untouched.
3327pub fn init_model_transport(
3328    e: &Engine,
3329    cfg: &memra_gguf::config::ModelConfig,
3330    n_trunk: usize,
3331) -> Result<(), Box<dyn std::error::Error>> {
3332    if pp2_streams_off() || pp2_devices_env().is_none() || pp_cuts(n_trunk).is_none() {
3333        return Ok(());
3334    }
3335    PpNRt::get(e)?.init_boundary_transport(e, cfg.n_embd as usize)
3336}
3337
3338/// Stage-owned cache allocation door: when the ppN door is open AND `MEMRA_PP_DEVICES`
3339/// is set (placement plumbing), each layer's cache is allocated by its OWNING stage's
3340/// engine — on one device this is byte-for-byte today's allocation (gated); cross-device
3341/// it puts each stage's KV on that stage's HBM. Door shut or devices unset: plain
3342/// `Cache::new` (zero behavior change). Trailing MTP/NextN layers (beyond the trunk)
3343/// map to the LAST stage.
3344pub fn new_cache(
3345    e: &Engine,
3346    cfg: &memra_gguf::config::ModelConfig,
3347    max_ctx: usize,
3348) -> Result<crate::cache::Cache, Box<dyn std::error::Error>> {
3349    new_cache_inner(e, cfg, None, max_ctx)
3350}
3351
3352pub fn new_cache_planned(
3353    e: &Engine,
3354    cfg: &memra_gguf::config::ModelConfig,
3355    plan: &memra_gguf::model_plan::ModelPlan,
3356    max_ctx: usize,
3357) -> Result<crate::cache::Cache, Box<dyn std::error::Error>> {
3358    new_cache_inner(e, cfg, Some(plan), max_ctx)
3359}
3360
3361fn new_cache_inner(
3362    e: &Engine,
3363    cfg: &memra_gguf::config::ModelConfig,
3364    plan: Option<&memra_gguf::model_plan::ModelPlan>,
3365    max_ctx: usize,
3366) -> Result<crate::cache::Cache, Box<dyn std::error::Error>> {
3367    let n_trunk = (cfg.n_layer - cfg.nextn_predict_layers) as usize;
3368    if let Some(fence) = pp_cuts(n_trunk) {
3369        if pp2_devices_env().is_some() && !pp2_streams_off() {
3370            let rt = PpNRt::get(e)?;
3371            rt.init_boundary_transport(e, cfg.n_embd as usize)?;
3372            let n_st = fence.len() - 1;
3373            assert_eq!(
3374                rt.n_stages(),
3375                n_st,
3376                "PpNRt stage count {} != fence stages {n_st}",
3377                rt.n_stages()
3378            );
3379            // #87 REVERSE PUBLICATION at ADMISSION (lane/pp2spec-crash): this is the one
3380            // stage-stream allocation site OUTSIDE the ppN step bodies — a NEW session's
3381            // KV alloc_zeros enqueue on the STAGE streams, and their pool blocks can be
3382            // reuse of buffers freed from ANOTHER session's in-flight verify whose
3383            // primary-stream reads are still queued (the c=2 residual: exactly one trap
3384            // per admission collision, round 0, after the step-body fences landed).
3385            // Order the stage streams behind the caller before the memsets can clobber.
3386            // Anatomy: `PpNRt::fence_stages_behind`.
3387            rt.fence_stages_behind(&e.stream())?;
3388            let devs: Vec<&dyn memra_kv::KvDev> = (0..n_st)
3389                .map(|s| rt.engine(s, e) as &dyn memra_kv::KvDev)
3390                .collect();
3391            let cache = match plan {
3392                Some(plan) => {
3393                    crate::cache::Cache::new_ppn_planned(&devs, &fence, cfg, plan, max_ctx)?
3394                }
3395                None => crate::cache::Cache::new_ppn(&devs, &fence, cfg, max_ctx)?,
3396            };
3397            sync_stages_after_load(e, n_trunk)?;
3398            return Ok(cache);
3399        }
3400        if !pp2_streams_off() {
3401            // CACHE BIRTH BARRIER (2026-08-02 pipelined-arm residual race): with the door
3402            // open but no device placement, Cache::new's alloc_zeros memsets enqueue on
3403            // the PRIMARY worker stream while the first KV appends / recurrent-state
3404            // reads run on the per-stage streams — no event orders them, and under
3405            // deferred readback the stage streams are hot immediately (a memset tail
3406            // can zero an already-appended KV row; intermittent, ~1-in-3 gate FAIL).
3407            // One context-sync per cache creation kills the class.
3408            let cache = match plan {
3409                Some(plan) => crate::cache::Cache::new_planned(e, cfg, plan, max_ctx)?,
3410                None => crate::cache::Cache::new(e, cfg, max_ctx)?,
3411            };
3412            sync_stages_after_load(e, n_trunk)?;
3413            return Ok(cache);
3414        }
3415    }
3416    match plan {
3417        Some(plan) => crate::cache::Cache::new_planned(e, cfg, plan, max_ctx),
3418        None => crate::cache::Cache::new(e, cfg, max_ctx),
3419    }
3420}
3421
3422/// M2 increment 2 LOAD BARRIER: weight uploads and decode-mirror builds enqueue on the
3423/// loading engines' WORKER streams; the first consumer launches on a DIFFERENT stream
3424/// with no load->decode event — the door-off reference walk on the primary worker
3425/// stream (sharded load: remote builds still in flight), or a fresh per-stage stream.
3426/// The 2026-08-02 gate finds (n2-dev01 step-0 168k-logit graze; split5 ref=0.0 head —
3427/// a half-built rp4 mirror — poisoning step-0 KV and every later step): one
3428/// context-wide synchronize per stage at load end kills the class. No-op when the door
3429/// is shut at load (single-stream load+decode is ordered by the stream itself).
3430pub fn sync_stages_after_load(
3431    e: &Engine,
3432    n_trunk: usize,
3433) -> Result<(), Box<dyn std::error::Error>> {
3434    if pp2_streams_off() || pp_cuts(n_trunk).is_none() {
3435        return Ok(());
3436    }
3437    let rt = PpNRt::get(e)?;
3438    for s in 0..rt.n_stages() {
3439        rt.stages[s].ctx.bind_to_thread()?;
3440        unsafe {
3441            cudarc::driver::sys::cuCtxSynchronize().result()?;
3442        }
3443    }
3444    e.ctx().bind_to_thread()?;
3445    unsafe {
3446        cudarc::driver::sys::cuCtxSynchronize().result()?;
3447    }
3448    Ok(())
3449}
3450
3451/// M2 increment 2 (weight sharding): the engine that should UPLOAD layer `il`'s weights
3452/// (and build its decode mirrors) — the owning stage's engine when the door is open with
3453/// device placement and sharding not rolled back; else the primary. `il >= n_trunk`
3454/// (MTP/NextN blocks) maps to the last stage. The head (output_norm + lm head) belongs
3455/// to the last trunk layer's stage — call with `il = n_trunk - 1`.
3456pub fn layer_engine(
3457    e: &Engine,
3458    n_trunk: usize,
3459    il: usize,
3460) -> Result<&Engine, Box<dyn std::error::Error>> {
3461    if pp_shard_off() || pp2_devices_env().is_none() || pp2_streams_off() {
3462        return Ok(e);
3463    }
3464    let Some(fence) = pp_cuts(n_trunk) else {
3465        return Ok(e);
3466    };
3467    let rt = PpNRt::get(e)?;
3468    let s = stage_of(&fence, il.min(n_trunk - 1));
3469    Ok(rt.engine(s, e))
3470}
3471
3472/// Why a checkpoint restore refused a layer's distributed (TP) KV mirror.
3473#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3474pub(crate) enum TpRestoreRefusal {
3475    /// Snapshot recorded a distributed length but the in-place target has no mirror to rewind.
3476    TargetAbsent,
3477    /// Grow path: the snapshot recorded a distributed length the parked source cannot supply.
3478    SourceAbsent,
3479    /// Grow path: the freshly allocated target already holds a mirror it should not have.
3480    GrowTargetNotFresh,
3481    /// The whole-token TP CUDA graph door is open. That graph is MODEL-level state which bakes
3482    /// the rank-cache pointers, so freeing a mirror under it strands the captured parent.
3483    TokenGraphDoorOpen,
3484}
3485
3486/// What a checkpoint restore must do with one layer's distributed (TP) KV mirror.
3487#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3488pub(crate) enum TpRestore {
3489    /// Neither side holds a mirror: nothing to do.
3490    Nothing,
3491    /// In-place rewind of the target's existing mirror to the recorded committed length.
3492    Rewind(usize),
3493    /// Grow path: build the target's mirror from the parked source's, truncated to `len`.
3494    Grow(usize),
3495    /// The snapshot PREDATES this layer's lazily-created mirror. Clear it: the mirror is derived
3496    /// state, and `ensure_step_tp_kv_cache` rebuilds it from the authoritative local plane on the
3497    /// next TP use, at whatever length that plane then holds.
3498    DropMirror,
3499    Refuse(TpRestoreRefusal),
3500}
3501
3502/// Resolve the distributed-KV arm of a checkpoint restore for ONE layer.
3503///
3504/// MECHANISM (lane/step37, 2026-08-28). `tp_kv[il]` is created LAZILY on a layer's first TP use
3505/// (`hybrid_forward.rs::ensure_step_tp_kv_cache`, reached only from the two TP DECODE paths and
3506/// the TP-PREFILL path). When rank-local TP prefill is not engaged, a cold prime never touches
3507/// it, so the session-affinity checkpoint captured mid-prime at the stable boundary records
3508/// `tp_kv_len[il] = None` for EVERY layer. The first decode step then materializes the mirror.
3509/// At reuse time the recorded `None` met a live `Some(..)` and the whole checkpoint was refused
3510/// at layer 0, so affinity reuse was 100% dead on step37 and every turn paid a full re-prime.
3511///
3512/// WHY DROPPING IS EXACT, NOT LENIENT. The mirror is not an independent plane: it is created by
3513/// hydrating from the local plane, and every TP decode gathers its rank shards back and appends
3514/// them into the local plane in the same step (`append_kv_quantized` into `local.k/v`, then
3515/// `local.len = base_len + 1`), which is why every TP entry point asserts
3516/// `distributed.committed_len() == local.len`. The local plane is therefore authoritative and
3517/// complete. Clearing the mirror reproduces the checkpoint-time state LITERALLY (the snapshot
3518/// says this layer had no mirror), and the rebuild reads the same bytes the checkpoint saw.
3519///
3520/// WHY THE `MEMRA_NO_LOCAL_SHADOW=1` DOOR DOES NOT BREAK THIS. That door skips the local-plane
3521/// gathers and appends in the eager v2 TP decode: lengths still advance, contents go STALE
3522/// (tp.rs::no_local_shadow_on). It is ON in the step37 serving env, so "the local plane is
3523/// authoritative" is NOT true of rows written by a TP decode under that door. The drop is
3524/// nonetheless safe, and self-guarding: `DropMirror` fires ONLY when the snapshot recorded NO
3525/// mirror for the layer, and a snapshot with no mirror is proof that no TP decode had yet run in
3526/// that cache's life (the mirror is created by the first TP use). Since the restore truncates the
3527/// local plane to exactly that snapshot length, every surviving row predates the first TP decode
3528/// and was therefore written by a PRIME, which always writes the local plane in full. The
3529/// rehydration cannot read a shadow-skipped row. Rows above the boundary are discarded and
3530/// re-primed by the suffix. The door also never rebases the local ring during decode (it does not
3531/// call `prepare_kv_append`), so the physical layout below the boundary is exactly as the prime
3532/// left it.
3533///
3534/// WHY NOT "MATERIALIZE BEFORE SNAPSHOT". The checkpoint is captured MID-PRIME. Nothing in the
3535/// non-TP-prefill prime path maintains a mirror, so a mirror created at capture time would be
3536/// stranded at the boundary length while the rest of the prime appends to the local plane only,
3537/// and the first decode would hard-error on `cache lengths diverged before decode`. Eager
3538/// materialization converts a re-prime into an outage.
3539///
3540/// Every genuinely inconsistent arm still refuses.
3541/// `source_has_tp`: `None` = in-place rewind; `Some(has_tp)` = restore into a freshly grown cache.
3542pub(crate) fn tp_restore_plan(
3543    snap_len: Option<usize>,
3544    source_has_tp: Option<bool>,
3545    target_has_tp: bool,
3546    token_graph_door: bool,
3547) -> TpRestore {
3548    match (source_has_tp, snap_len) {
3549        (None, Some(len)) => {
3550            if target_has_tp {
3551                TpRestore::Rewind(len)
3552            } else {
3553                TpRestore::Refuse(TpRestoreRefusal::TargetAbsent)
3554            }
3555        }
3556        (None, None) => {
3557            if !target_has_tp {
3558                TpRestore::Nothing
3559            } else if token_graph_door {
3560                TpRestore::Refuse(TpRestoreRefusal::TokenGraphDoorOpen)
3561            } else {
3562                TpRestore::DropMirror
3563            }
3564        }
3565        (Some(source_has_tp), Some(len)) => {
3566            if !source_has_tp {
3567                TpRestore::Refuse(TpRestoreRefusal::SourceAbsent)
3568            } else if target_has_tp {
3569                TpRestore::Refuse(TpRestoreRefusal::GrowTargetNotFresh)
3570            } else {
3571                TpRestore::Grow(len)
3572            }
3573        }
3574        (Some(_), None) => {
3575            if target_has_tp {
3576                // A freshly allocated cache must not already carry a mirror.
3577                TpRestore::Refuse(TpRestoreRefusal::GrowTargetNotFresh)
3578            } else {
3579                // The snapshot predates the source's mirror (or the source never had one). Leave
3580                // the grown target without one: the next TP use hydrates it from the local rows
3581                // this restore just copied in. Before the step37 fix a source that HELD a mirror
3582                // here was a hard refusal, which killed every grow-path affinity reuse too.
3583                TpRestore::Nothing
3584            }
3585        }
3586    }
3587}
3588
3589/// Restore a cache checkpoint through each layer's owning engine.
3590///
3591/// `source = None` is an in-place rewind: the target already owns the append-only KV bytes and
3592/// only its lengths plus recurrent state move back to the snapshot. `Some(source)` restores into
3593/// a freshly allocated larger cache: checkpoint-valid KV rows are copied from the parked cache,
3594/// rank-local TP sidecars are rebuilt through their model-owned runtimes, and recurrent state
3595/// always comes from the checkpoint's owned device copies.
3596///
3597/// This cannot use `Cache::rollback(e, ...)` under cross-device PP: a single primary engine is
3598/// not the owner of every stage's cache buffers. The rare rewind/grow boundary synchronizes open
3599/// PP contexts before publishing the restored cache to the next request.
3600pub fn restore_cache_checkpoint(
3601    e: &Engine,
3602    model: &crate::hybrid::HybridModel,
3603    source: Option<&crate::cache::Cache>,
3604    target: &mut crate::cache::Cache,
3605    snap: &crate::cache::CacheSnapshot,
3606) -> Result<(), Box<dyn std::error::Error>> {
3607    target.ensure_usable("restore_cache_checkpoint target")?;
3608    if let Some(source) = source {
3609        source.ensure_usable("restore_cache_checkpoint source")?;
3610    }
3611    let cfg = &model.cfg;
3612    let n = target.kv.len();
3613    if target.recur.len() != n
3614        || target.tp_kv.len() != n
3615        || snap.kv_len.len() != n
3616        || snap.tp_kv_len.len() != n
3617        || snap.conv.len() != n
3618        || snap.ssm.len() != n
3619        || source.is_some_and(|s| s.kv.len() != n || s.recur.len() != n || s.tp_kv.len() != n)
3620    {
3621        return Err("checkpoint cache layer-count mismatch".into());
3622    }
3623    if snap.pos > target.max_ctx {
3624        return Err(format!(
3625            "checkpoint pos {} exceeds target capacity {}",
3626            snap.pos, target.max_ctx,
3627        )
3628        .into());
3629    }
3630
3631    let n_trunk = (cfg.n_layer - cfg.nextn_predict_layers) as usize;
3632    // Read the door ONCE: the refusal it drives must be uniform across layers within a restore.
3633    let token_graph_door = crate::tp::step_tp_graph_enabled().unwrap_or(false);
3634    let mut dropped_mirrors = 0usize;
3635    for il in 0..n {
3636        let owner = layer_engine(e, n_trunk, il)?;
3637        let src_kv = source.map(|s| &s.kv[il]);
3638        match (src_kv, target.kv[il].as_mut(), snap.kv_len[il]) {
3639            (Some(Some(src)), Some(dst), Some(len)) => {
3640                if len > src.len || len > target.max_ctx {
3641                    return Err(format!(
3642                        "checkpoint layer {il} len {len} exceeds source {} or target {}",
3643                        src.len, target.max_ctx,
3644                    )
3645                    .into());
3646                }
3647                if src.kv_dim_k != dst.kv_dim_k
3648                    || src.kv_dim_v != dst.kv_dim_v
3649                    || src.k_tok_bytes != dst.k_tok_bytes
3650                    || src.v_tok_bytes != dst.v_tok_bytes
3651                {
3652                    return Err(format!("checkpoint KV layout mismatch at layer {il}").into());
3653                }
3654                match (&src.ring, dst.ring.as_ref()) {
3655                    (Some(sring), Some(dring)) => {
3656                        // SWA ring: `len` is ABSOLUTE and can exceed the physical row count once
3657                        // the ring has lapped (the 2026-08-29 warm-turn-at-40k panic: a flat
3658                        // `len`-row copy sliced past the window-sized buffer). Copy only the
3659                        // aligned live window and rebase the fresh target to its start — the
3660                        // same geometry `ResidentTpKvCache::prepare_grow` already uses.
3661                        if dring.base() != 0 {
3662                            return Err(format!(
3663                                "checkpoint SWA restore at layer {il} requires a fresh target \
3664                                 ring (base {}, expected 0)",
3665                                dring.base(),
3666                            )
3667                            .into());
3668                        }
3669                        let (new_base, phys) = sring.restore_plan(len).map_err(|e| {
3670                            format!("checkpoint SWA restore refused at layer {il}: {e}")
3671                        })?;
3672                        let rows = phys.len();
3673                        let kb = rows * src.k_tok_bytes;
3674                        let vb = rows * src.v_tok_bytes;
3675                        if kb > 0 {
3676                            owner.copy_u8_range_into(
3677                                &mut dst.k,
3678                                0,
3679                                &src.k,
3680                                phys.start * src.k_tok_bytes,
3681                                kb,
3682                            )?;
3683                        }
3684                        if vb > 0 {
3685                            owner.copy_u8_range_into(
3686                                &mut dst.v,
3687                                0,
3688                                &src.v,
3689                                phys.start * src.v_tok_bytes,
3690                                vb,
3691                            )?;
3692                        }
3693                        dst.ring
3694                            .as_mut()
3695                            .expect("ring presence checked above")
3696                            .apply_rebase(new_base);
3697                        if let Some(base_d) = dst.base_d.as_mut() {
3698                            owner.set_i32_one(base_d, new_base as i32)?;
3699                        }
3700                    }
3701                    (None, None) => {
3702                        let kb = len * src.k_tok_bytes;
3703                        let vb = len * src.v_tok_bytes;
3704                        if kb > 0 {
3705                            owner.copy_u8_into(&mut dst.k, 0, &src.k, kb)?;
3706                        }
3707                        if vb > 0 {
3708                            owner.copy_u8_into(&mut dst.v, 0, &src.v, vb)?;
3709                        }
3710                    }
3711                    _ => {
3712                        return Err(
3713                            format!("checkpoint ring/flat KV mismatch at layer {il}").into()
3714                        );
3715                    }
3716                }
3717                dst.len = len;
3718                owner.set_i32_one(&mut dst.len_d, len as i32)?;
3719            }
3720            (None, Some(dst), Some(len)) => {
3721                if len > dst.len || len > target.max_ctx {
3722                    return Err(format!(
3723                        "checkpoint layer {il} len {len} exceeds live {} or target {}",
3724                        dst.len, target.max_ctx,
3725                    )
3726                    .into());
3727                }
3728                if let Some(ring) = &dst.ring
3729                    && !ring.can_rewind_to(len)
3730                {
3731                    return Err(format!(
3732                        "checkpoint SWA rewind at layer {il} has been lapped \
3733                             (len {len}, ring base {}); full re-prime required",
3734                        ring.base(),
3735                    )
3736                    .into());
3737                }
3738                dst.len = len;
3739                owner.set_i32_one(&mut dst.len_d, len as i32)?;
3740            }
3741            (Some(None), None, None) | (None, None, None) => {}
3742            _ => return Err(format!("checkpoint KV kind mismatch at layer {il}").into()),
3743        }
3744
3745        match tp_restore_plan(
3746            snap.tp_kv_len[il],
3747            source.map(|s| s.tp_kv[il].is_some()),
3748            target.tp_kv[il].is_some(),
3749            token_graph_door,
3750        ) {
3751            TpRestore::Nothing => {}
3752            TpRestore::Rewind(len) => target.tp_kv[il]
3753                .as_mut()
3754                .expect("tp_restore_plan::Rewind implies a present target mirror")
3755                .rewind_to(len)?,
3756            TpRestore::Grow(len) => {
3757                let src = source
3758                    .and_then(|s| s.tp_kv[il].as_ref())
3759                    .expect("tp_restore_plan::Grow implies a present source mirror");
3760                let runtime = model.step_tp_runtime_for_layer(il).ok_or_else(|| {
3761                    format!("checkpoint TP KV layer {il} has no distributed runtime")
3762                })?;
3763                let grown = runtime.grow_tp_kv_cache(src, target.max_ctx, len)?;
3764                target.tp_kv[il] = Some(grown);
3765            }
3766            TpRestore::DropMirror => {
3767                // The snapshot predates this layer's lazily-created distributed mirror. Clear it
3768                // and let `ensure_step_tp_kv_cache` rebuild it from the authoritative local
3769                // plane on the next TP use. See `tp_restore_plan` for why this is exact.
3770                if target.tp_kv[il].take().is_some() {
3771                    dropped_mirrors += 1;
3772                }
3773            }
3774            TpRestore::Refuse(reason) => {
3775                return Err(format!(
3776                    "checkpoint TP KV restore refused at layer {il}: {} \
3777                     (snap.tp_kv_len={:?}, snap.kv_len={:?}, snap.pos={}, \
3778                     source_has_tp={:?}, target_has_tp={}, target_committed={})",
3779                    match reason {
3780                        TpRestoreRefusal::TargetAbsent =>
3781                            "the snapshot recorded a distributed length but the target holds no \
3782                             distributed cache to rewind",
3783                        TpRestoreRefusal::SourceAbsent =>
3784                            "the snapshot recorded a distributed length the parked source cannot \
3785                             supply",
3786                        TpRestoreRefusal::GrowTargetNotFresh =>
3787                            "the freshly allocated grow target already holds a distributed cache",
3788                        TpRestoreRefusal::TokenGraphDoorOpen =>
3789                            "MEMRA_STEP_TP_GRAPH is open, and its model-level whole-token graph \
3790                             bakes the rank-cache pointers, so the stale mirror cannot be freed",
3791                    },
3792                    snap.tp_kv_len[il],
3793                    snap.kv_len[il],
3794                    snap.pos,
3795                    source.map(|s| s.tp_kv[il].is_some()),
3796                    target.tp_kv[il].is_some(),
3797                    target.tp_kv[il]
3798                        .as_ref()
3799                        .map(|c| c.committed_len())
3800                        .unwrap_or(0),
3801                )
3802                .into());
3803            }
3804        }
3805
3806        match (target.recur[il].as_mut(), &snap.conv[il], &snap.ssm[il]) {
3807            (Some(dst), Some(conv), Some(ssm)) => {
3808                if conv.len() != dst.conv_state.len() || ssm.len() != dst.ssm_state.len() {
3809                    return Err(
3810                        format!("checkpoint recurrent layout mismatch at layer {il}").into(),
3811                    );
3812                }
3813                owner.copy_into(&mut dst.conv_state, 0, conv, conv.len())?;
3814                owner.copy_into(&mut dst.ssm_state, 0, ssm, ssm.len())?;
3815            }
3816            (None, None, None) => {}
3817            _ => {
3818                return Err(format!("checkpoint recurrent kind mismatch at layer {il}").into());
3819            }
3820        }
3821    }
3822    target.pos = snap.pos;
3823    if dropped_mirrors > 0 {
3824        // ENGAGEMENT RECEIPT. Before this fix the same condition returned "checkpoint TP KV kind
3825        // mismatch at layer 0" and the caller dropped the session for a full re-prime. This line
3826        // proves the restore took the rebuild path instead.
3827        eprintln!(
3828            "[pp] checkpoint restore: cleared {dropped_mirrors} stale distributed KV mirror(s) \
3829             at pos {} (snapshot predates lazy TP hydration); the next TP use rehydrates them \
3830             from the local plane",
3831            snap.pos,
3832        );
3833    }
3834
3835    // Open PP uses per-stage streams/contexts; publish every restored plane before the caller
3836    // starts the next prime. Door-shut single-stream restores remain naturally ordered.
3837    sync_stages_after_load(e, n_trunk)?;
3838    if source.is_some() {
3839        // A grown cache replaces and drops the source immediately after this returns. Bound the
3840        // D2D copies first so an async-pool free cannot recycle a source plane prematurely.
3841        e.stream().synchronize()?;
3842    }
3843    Ok(())
3844}
3845
3846#[cfg(test)]
3847mod host_bounce_tests {
3848    use super::{
3849        BoundaryTransport, DUAL_PP_HOST_BOUNCE_REFUSAL, DUAL_PP_SINGLE_SLOT_REFUSAL,
3850        PEER_PROBE_FIXED_BYTES, PEER_PROBE_REQUIRED_REFUSAL, PEER_PROBE_TOKEN_WIDTHS,
3851        PEER_RUNTIME_PROBE_BUDGET_NS, PEER_RUNTIME_PROBE_CYCLE_COPIES,
3852        PEER_RUNTIME_PROBE_DEFERRAL_BOUND_INTERVALS, PEER_RUNTIME_PROBE_INTERVAL_COPIES,
3853        PP_WAVE_MAX_STAGES, PeerProbeDecision, PeerProbeStartupPolicy, acquire_pp_walk,
3854        boundary_slot_growth_elements, boundary_transport, dual_pp_eligibility,
3855        dual_pp_timing_dropped, dual_pp_timing_snapshot, dual_pp_wave_mid, enter_pp_wave_cell,
3856        host_bounce_capacity, latch_runtime_host_bounce, peer_probe_bytes_to_f32,
3857        peer_probe_decision, peer_probe_f32_to_bytes, peer_probe_mismatch_count,
3858        peer_probe_pattern, peer_probe_startup_policy, pp_devices_repeat, pp_wave_diagonal,
3859        pp_wave_eligibility, pp_wave_numeric_eligibility, pp_wave_on_value, pp_wave_ranges,
3860        pp_wave_route_enabled, pp_wave_snapshot, publish_runtime_peer_probe_deferral,
3861        record_dual_pp_stage_result, record_pp_wave_tick, runtime_peer_probe_candidate,
3862        runtime_peer_probe_next_copy,
3863    };
3864
3865    // ---- lane/step37 session-affinity TP-mirror regression (2026-08-28) -------------------
3866    //
3867    // BEFORE this fix `restore_cache_checkpoint` refused with "checkpoint TP KV kind mismatch at
3868    // layer 0" whenever a checkpoint captured mid-prime (tp_kv not yet lazily created) met a
3869    // target whose first decode had since materialized the mirror. That is EVERY step37
3870    // session-affinity reuse, so reuse was 100% dead and every turn paid a full re-prime.
3871    // The `mismatch_*` cases below assert the new outcome; each of them was a hard refusal
3872    // before. The `refuses_*` cases pin the arms that must STILL fail closed.
3873
3874    use super::{TpRestore, TpRestoreRefusal, tp_restore_plan};
3875
3876    #[test]
3877    fn mismatch_snapshot_predating_lazy_tp_drops_the_mirror_instead_of_refusing() {
3878        // in-place rewind, snapshot has no distributed length, target materialized one.
3879        assert_eq!(
3880            tp_restore_plan(None, None, true, false),
3881            TpRestore::DropMirror
3882        );
3883    }
3884
3885    #[test]
3886    fn mismatch_on_the_grow_path_leaves_the_fresh_target_without_a_mirror() {
3887        // Grow path, snapshot predates the source's mirror, fresh target has none. Build none and
3888        // let the next TP use hydrate from the copied local rows. This arm REFUSED before the fix.
3889        assert_eq!(
3890            tp_restore_plan(None, Some(true), false, false),
3891            TpRestore::Nothing
3892        );
3893    }
3894
3895    #[test]
3896    fn drop_is_refused_while_the_token_graph_door_bakes_rank_pointers() {
3897        assert_eq!(
3898            tp_restore_plan(None, None, true, true),
3899            TpRestore::Refuse(TpRestoreRefusal::TokenGraphDoorOpen)
3900        );
3901    }
3902
3903    #[test]
3904    fn healthy_arms_are_untouched() {
3905        assert_eq!(
3906            tp_restore_plan(None, None, false, false),
3907            TpRestore::Nothing
3908        );
3909        assert_eq!(tp_restore_plan(None, None, false, true), TpRestore::Nothing);
3910        assert_eq!(
3911            tp_restore_plan(Some(15222), None, true, false),
3912            TpRestore::Rewind(15222)
3913        );
3914        assert_eq!(
3915            tp_restore_plan(Some(15222), Some(true), false, false),
3916            TpRestore::Grow(15222)
3917        );
3918        assert_eq!(
3919            tp_restore_plan(None, Some(false), false, false),
3920            TpRestore::Nothing
3921        );
3922    }
3923
3924    #[test]
3925    fn refuses_a_recorded_distributed_length_with_no_target_mirror() {
3926        assert_eq!(
3927            tp_restore_plan(Some(15222), None, false, false),
3928            TpRestore::Refuse(TpRestoreRefusal::TargetAbsent)
3929        );
3930    }
3931
3932    #[test]
3933    fn refuses_a_recorded_distributed_length_the_source_cannot_supply() {
3934        assert_eq!(
3935            tp_restore_plan(Some(15222), Some(false), false, false),
3936            TpRestore::Refuse(TpRestoreRefusal::SourceAbsent)
3937        );
3938    }
3939
3940    #[test]
3941    fn refuses_a_grow_target_that_is_not_fresh() {
3942        assert_eq!(
3943            tp_restore_plan(Some(15222), Some(true), true, false),
3944            TpRestore::Refuse(TpRestoreRefusal::GrowTargetNotFresh)
3945        );
3946        assert_eq!(
3947            tp_restore_plan(None, Some(true), true, false),
3948            TpRestore::Refuse(TpRestoreRefusal::GrowTargetNotFresh)
3949        );
3950    }
3951
3952    // ---- 2026-08-11 default-flip safety regression (owner-ordered) ----------------------
3953    // All pure-resolution tests: no env mutation (parallel test threads share process env).
3954
3955    #[test]
3956    fn flip_default_is_dual_auto_with_explicit_off_and_forced_seams() {
3957        use super::{DualPpMode, dual_pp_mode_resolve};
3958        assert_eq!(dual_pp_mode_resolve(None), DualPpMode::Auto);
3959        assert_eq!(dual_pp_mode_resolve(Some("0")), DualPpMode::Off);
3960        assert_eq!(dual_pp_mode_resolve(Some("1")), DualPpMode::Forced);
3961        // Any other value is not a silent third state: treat as the default.
3962        assert_eq!(dual_pp_mode_resolve(Some("2")), DualPpMode::Auto);
3963        assert_eq!(dual_pp_mode_resolve(Some("")), DualPpMode::Auto);
3964    }
3965
3966    #[test]
3967    fn flip_overlap_follows_mode_and_one_flag_restores_preflip_serial() {
3968        use super::{DualPpMode, pp2_overlap_resolve};
3969        // Naked default = the re-gated dual arm: overlap ON.
3970        assert!(pp2_overlap_resolve(None, DualPpMode::Auto));
3971        // MEMRA_DUAL_PP=0 ALONE restores the exact pre-flip naked path (single-slot serial).
3972        assert!(!pp2_overlap_resolve(None, DualPpMode::Off));
3973        // The explicit pre-flip request keeps its binding single-slot refusal reachable.
3974        assert!(!pp2_overlap_resolve(None, DualPpMode::Forced));
3975        // Explicit values always win over the mode.
3976        for mode in [DualPpMode::Off, DualPpMode::Forced, DualPpMode::Auto] {
3977            assert!(pp2_overlap_resolve(Some("1"), mode));
3978            assert!(!pp2_overlap_resolve(Some("0"), mode));
3979        }
3980    }
3981
3982    #[test]
3983    fn flip_auto_routes_only_the_regated_regime_and_degrades_serially_elsewhere() {
3984        use super::{DualPpMode, dual_pp_route};
3985        // The exact box1 re-gate regime: PP-2, double-slot, peer transport, B>=2.
3986        assert!(dual_pp_route(DualPpMode::Auto, 2, 2, true, false));
3987        assert!(dual_pp_route(DualPpMode::Auto, 17, 2, true, false));
3988        // Outside it, Auto must DEGRADE (serial PP-N walker), never refuse:
3989        assert!(!dual_pp_route(DualPpMode::Auto, 1, 2, true, false)); // no second wave
3990        assert!(!dual_pp_route(DualPpMode::Auto, 2, 3, true, false)); // naked PP-3 keeps serving
3991        assert!(!dual_pp_route(DualPpMode::Auto, 2, 2, false, false)); // single-slot boundary
3992        assert!(!dual_pp_route(DualPpMode::Auto, 2, 2, true, true)); // host-bounce escape hatch
3993        // Forced routes every B>=2 call into the dual body so the binding refusals fire loud.
3994        assert!(dual_pp_route(DualPpMode::Forced, 2, 3, false, true));
3995        assert!(!dual_pp_route(DualPpMode::Forced, 1, 2, true, false));
3996        // Off is the rollback seam: never dual.
3997        assert!(!dual_pp_route(DualPpMode::Off, 8, 2, true, false));
3998    }
3999
4000    #[test]
4001    fn pp_wave_flag_is_strict_and_does_not_inherit_the_pp2_default() {
4002        assert_eq!(pp_wave_on_value(None), Ok(false));
4003        assert!(pp_wave_on_value(Some("")).is_err());
4004        assert_eq!(pp_wave_on_value(Some("0")), Ok(false));
4005        assert_eq!(pp_wave_on_value(Some("1")), Ok(true));
4006        assert!(pp_wave_on_value(Some("auto")).is_err());
4007        assert!(pp_wave_on_value(Some("2")).is_err());
4008    }
4009
4010    #[test]
4011    fn pp_wave_route_treats_overlap_off_and_single_work_item_as_serial_rollback() {
4012        assert!(pp_wave_route_enabled(true, true, 3, 2));
4013        assert!(pp_wave_route_enabled(true, true, 4, 8));
4014        assert!(!pp_wave_route_enabled(true, false, 3, 8));
4015        assert!(!pp_wave_route_enabled(false, true, 3, 8));
4016        assert!(!pp_wave_route_enabled(true, true, 2, 8));
4017        assert!(!pp_wave_route_enabled(true, true, 4, 1));
4018    }
4019
4020    #[test]
4021    fn pp_wave_ranges_are_balanced_contiguous_and_priority_preserving() {
4022        assert!(pp_wave_ranges(0, 4).is_empty());
4023        assert!(pp_wave_ranges(8, 0).is_empty());
4024        assert_eq!(pp_wave_ranges(1, 4), vec![(0, 1)]);
4025        assert_eq!(pp_wave_ranges(2, 4), vec![(0, 1), (1, 2)]);
4026        assert_eq!(pp_wave_ranges(8, 4), vec![(0, 2), (2, 4), (4, 6), (6, 8)]);
4027        assert_eq!(
4028            pp_wave_ranges(17, 4),
4029            vec![(0, 5), (5, 9), (9, 13), (13, 17)]
4030        );
4031        for batch in 1..=64 {
4032            for stages in 2..=PP_WAVE_MAX_STAGES {
4033                let ranges = pp_wave_ranges(batch, stages);
4034                assert_eq!(ranges.len(), batch.min(stages));
4035                assert_eq!(ranges.first().copied().unwrap().0, 0);
4036                assert_eq!(ranges.last().copied().unwrap().1, batch);
4037                assert!(ranges.iter().all(|(lo, hi)| lo < hi));
4038                assert!(ranges.windows(2).all(|pair| pair[0].1 == pair[1].0));
4039                let widths: Vec<_> = ranges.iter().map(|(lo, hi)| hi - lo).collect();
4040                assert!(widths.windows(2).all(|pair| pair[0] >= pair[1]));
4041                assert!(widths.first().unwrap() - widths.last().unwrap() <= 1);
4042            }
4043        }
4044    }
4045
4046    #[test]
4047    fn pp_wave_diagonals_cover_the_grid_without_stage_or_wave_aliasing() {
4048        for stages in 3..=PP_WAVE_MAX_STAGES {
4049            for waves in 1..=stages {
4050                let mut seen = vec![vec![false; stages]; waves];
4051                for diagonal in 0..stages + waves - 1 {
4052                    let cells = pp_wave_diagonal(stages, waves, diagonal);
4053                    let mut stage_seen = vec![false; stages];
4054                    let mut wave_seen = vec![false; waves];
4055                    for (wave, stage) in cells {
4056                        assert_eq!(wave + stage, diagonal);
4057                        assert!(!stage_seen[stage]);
4058                        assert!(!wave_seen[wave]);
4059                        assert!(!seen[wave][stage]);
4060                        stage_seen[stage] = true;
4061                        wave_seen[wave] = true;
4062                        seen[wave][stage] = true;
4063                    }
4064                }
4065                assert!(seen.into_iter().flatten().all(|cell| cell));
4066            }
4067        }
4068        assert!(pp_wave_diagonal(4, 4, 7).is_empty());
4069    }
4070
4071    #[test]
4072    fn pp_wavefront_refuses_every_unqualified_transport_shape() {
4073        assert!(pp_wave_eligibility(3, true, false, false).is_ok());
4074        assert!(pp_wave_eligibility(4, true, false, false).is_ok());
4075        assert!(pp_wave_eligibility(2, true, false, false).is_err());
4076        assert!(pp_wave_eligibility(5, true, false, false).is_err());
4077        assert!(pp_wave_eligibility(3, false, false, false).is_err());
4078        assert!(pp_wave_eligibility(3, true, true, false).is_err());
4079        assert!(pp_wave_eligibility(3, true, false, true).is_err());
4080    }
4081
4082    #[test]
4083    fn pp_wavefront_requires_width_invariant_bf16_for_w4a16() {
4084        assert!(pp_wave_numeric_eligibility(false, false).is_ok());
4085        assert!(pp_wave_numeric_eligibility(false, true).is_ok());
4086        assert!(pp_wave_numeric_eligibility(true, true).is_ok());
4087        assert!(pp_wave_numeric_eligibility(true, false).is_err());
4088    }
4089
4090    #[test]
4091    fn pp_device_aliases_cannot_bypass_the_distinct_stage_gate() {
4092        assert!(!pp_devices_repeat("0,1,2,3"));
4093        assert!(pp_devices_repeat("0,00,1"));
4094        assert!(pp_devices_repeat("2,1,2"));
4095        assert!(pp_devices_repeat("0,nope,1"));
4096    }
4097
4098    #[test]
4099    fn pp_walk_owner_refuses_reentry_and_releases_at_scope_end() {
4100        let active = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));
4101        let next = std::sync::atomic::AtomicU64::new(1);
4102        let first = acquire_pp_walk(&active, &next, 7, None, "first").unwrap();
4103        let held_clone = super::PpWalkLease {
4104            state: first.state.clone(),
4105        };
4106        let error = acquire_pp_walk(&active, &next, 7, None, "second").unwrap_err();
4107        assert!(error.contains("refused concurrent PP walk"));
4108        drop(first);
4109        assert!(acquire_pp_walk(&active, &next, 7, None, "third").is_err());
4110        drop(held_clone);
4111        assert!(acquire_pp_walk(&active, &next, 7, None, "fourth").is_ok());
4112    }
4113
4114    #[test]
4115    fn pp_walk_coordinator_borrow_is_explicit_and_thread_local() {
4116        let active = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));
4117        let next = std::sync::atomic::AtomicU64::new(1);
4118        let lease = acquire_pp_walk(&active, &next, 11, None, "owner").unwrap();
4119        let state = lease.state.clone();
4120        super::PP_WALK_BORROWS.with(|borrows| borrows.borrow_mut().push(state.clone()));
4121        assert!(super::borrowed_pp_walk(11).is_some());
4122        std::thread::spawn(move || {
4123            assert!(super::borrowed_pp_walk(11).is_none());
4124            drop(state);
4125        })
4126        .join()
4127        .unwrap();
4128        super::PP_WALK_BORROWS.with(|borrows| borrows.borrow_mut().clear());
4129        drop(lease);
4130        assert_eq!(active.load(std::sync::atomic::Ordering::Acquire), 0);
4131    }
4132
4133    #[test]
4134    fn boundary_growth_charges_first_allocation_and_only_missing_high_water_afterward() {
4135        assert_eq!(boundary_slot_growth_elements([0, 0], 4096), 8192);
4136        assert_eq!(boundary_slot_growth_elements([4096, 4096], 4096), 0);
4137        assert_eq!(boundary_slot_growth_elements([4096, 2048], 4096), 2048);
4138        assert_eq!(boundary_slot_growth_elements([8192, 8192], 4096), 0);
4139    }
4140
4141    #[test]
4142    fn pp_wave_liveness_snapshot_counts_ticks_cells_and_real_overlap() {
4143        let before = pp_wave_snapshot();
4144        let first = enter_pp_wave_cell();
4145        let second = enter_pp_wave_cell();
4146        drop(second);
4147        drop(first);
4148        record_pp_wave_tick();
4149        let after = pp_wave_snapshot();
4150        assert!(after.0 > before.0);
4151        assert!(after.1 >= before.1 + 2);
4152        assert!(after.2 > before.2);
4153    }
4154
4155    #[test]
4156    fn dual_pp_split_is_honest_at_one_and_ceil_first_afterward() {
4157        assert_eq!(dual_pp_wave_mid(1), None);
4158        assert_eq!(dual_pp_wave_mid(2), Some(1));
4159        assert_eq!(dual_pp_wave_mid(3), Some(2));
4160        assert_eq!(dual_pp_wave_mid(8), Some(4));
4161        assert_eq!(dual_pp_wave_mid(16), Some(8));
4162        assert_eq!(dual_pp_wave_mid(31), Some(16));
4163        assert_eq!(dual_pp_wave_mid(32), Some(16));
4164    }
4165
4166    #[test]
4167    fn dual_pp_refuses_single_slot_and_non_pp2_shapes() {
4168        assert_eq!(
4169            dual_pp_eligibility(2, false, false),
4170            Err(DUAL_PP_SINGLE_SLOT_REFUSAL)
4171        );
4172        assert!(dual_pp_eligibility(2, true, false).is_ok());
4173        assert!(dual_pp_eligibility(3, true, false).is_err());
4174    }
4175
4176    #[test]
4177    fn dual_pp_refuses_unvalidated_host_bounce_transport() {
4178        assert_eq!(
4179            dual_pp_eligibility(2, true, true),
4180            Err(DUAL_PP_HOST_BOUNCE_REFUSAL),
4181        );
4182    }
4183
4184    #[test]
4185    #[allow(clippy::int_plus_one)] // allow: the +1 form states the at-least-one-more-drop bound
4186    fn dual_pp_timing_error_is_counted_without_recording_a_sample() {
4187        let dropped_before = dual_pp_timing_dropped();
4188        let (_, samples_before) = dual_pp_timing_snapshot();
4189        record_dual_pp_stage_result(0, Err::<f32, _>("CUDA_ERROR_NOT_READY"));
4190        let (_, samples_after) = dual_pp_timing_snapshot();
4191        assert_eq!(samples_after[0], samples_before[0]);
4192        assert!(dual_pp_timing_dropped() >= dropped_before + 1);
4193    }
4194
4195    #[test]
4196    fn corrupted_peer_readback_fails_closed_unless_host_bounce_is_selected() {
4197        assert_eq!(
4198            PEER_PROBE_TOKEN_WIDTHS,
4199            [1, 8, 16, crate::cache::PRIME_CHUNK_MAX_TOKENS],
4200        );
4201        let largest_payload_bytes = PEER_PROBE_TOKEN_WIDTHS[3] * 4096 * std::mem::size_of::<f32>();
4202        assert_eq!(largest_payload_bytes, 64 * 1024 * 1024);
4203        assert!(largest_payload_bytes >= 1024 * 1024);
4204        let expected = peer_probe_pattern(PEER_PROBE_FIXED_BYTES, 2, 0, 1);
4205        assert_eq!(
4206            peer_probe_f32_to_bytes(&peer_probe_bytes_to_f32(&expected)),
4207            expected,
4208        );
4209        let mut corrupted = expected.clone();
4210        for offset in [0, 8_191, PEER_PROBE_FIXED_BYTES - 1] {
4211            corrupted[offset] ^= 0x5a;
4212        }
4213
4214        assert_eq!(peer_probe_mismatch_count(&expected, &corrupted), 3);
4215        assert_eq!(
4216            peer_probe_decision(&expected, &corrupted, false),
4217            Err("3 mismatched byte(s)".to_string()),
4218        );
4219        assert_eq!(
4220            peer_probe_decision(&expected, &corrupted, true),
4221            Ok(PeerProbeDecision::ProceedWithHostBounce { mismatches: 3 }),
4222        );
4223    }
4224
4225    #[test]
4226    fn probe_off_refusal_matrix_is_fail_closed_only_for_sharded_native_peer() {
4227        for probe_on in [false, true] {
4228            for sharded in [false, true] {
4229                for host_bounce in [false, true] {
4230                    let got = peer_probe_startup_policy(probe_on, sharded, host_bounce);
4231                    let expected = match (probe_on, sharded, host_bounce) {
4232                        (false, true, false) => Err(PEER_PROBE_REQUIRED_REFUSAL),
4233                        (false, true, true) => Ok(PeerProbeStartupPolicy::BypassedWithHostBounce),
4234                        _ => Ok(PeerProbeStartupPolicy::Allowed),
4235                    };
4236                    assert_eq!(
4237                        got, expected,
4238                        "probe_on={probe_on} sharded={sharded} host_bounce={host_bounce}",
4239                    );
4240                }
4241            }
4242        }
4243        assert!(PEER_PROBE_REQUIRED_REFUSAL.contains("MEMRA_PEER_PROBE=0"));
4244        assert!(PEER_PROBE_REQUIRED_REFUSAL.contains("MEMRA_PP_HOST_BOUNCE!=1"));
4245    }
4246
4247    #[test]
4248    fn runtime_reprobe_keeps_cheap_deadlines_live_while_expensive_work_waits_for_idle() {
4249        let every = PEER_RUNTIME_PROBE_INTERVAL_COPIES;
4250        assert_eq!(PEER_RUNTIME_PROBE_CYCLE_COPIES, 4 * every);
4251        let mut next = [every, 2 * every, 3 * every, 4 * every];
4252        let measured_ns = [1_000_000, 2_000_000, 3_000_000, 0];
4253
4254        assert_eq!(
4255            runtime_peer_probe_candidate(every - 1, next, measured_ns, false),
4256            None,
4257        );
4258        assert_eq!(
4259            runtime_peer_probe_candidate(every, next, measured_ns, false),
4260            Some((0, 1)),
4261        );
4262
4263        // Pretend the three cheap deadlines completed. The maximum rung is due but must not run
4264        // on the interactive boundary.
4265        next[..3].copy_from_slice(&[5 * every, 6 * every, 7 * every]);
4266        assert_eq!(
4267            runtime_peer_probe_candidate(4 * every, next, measured_ns, false),
4268            None,
4269        );
4270        // Once the next cheap deadline arrives, it remains runnable even though the older max
4271        // deadline is still pending.
4272        assert_eq!(
4273            runtime_peer_probe_candidate(5 * every, next, measured_ns, false),
4274            Some((0, 1)),
4275        );
4276        // An idle boundary drains the oldest pending rung first.
4277        assert_eq!(
4278            runtime_peer_probe_candidate(5 * every, next, measured_ns, true),
4279            Some((3, crate::cache::PRIME_CHUNK_MAX_TOKENS)),
4280        );
4281    }
4282
4283    #[test]
4284    fn runtime_reprobe_moves_any_measured_over_budget_rung_to_idle_only() {
4285        let every = PEER_RUNTIME_PROBE_INTERVAL_COPIES;
4286        let next = [u64::MAX, every, u64::MAX, u64::MAX];
4287        let mut measured_ns = [0; PEER_PROBE_TOKEN_WIDTHS.len()];
4288        measured_ns[1] = PEER_RUNTIME_PROBE_BUDGET_NS + 1;
4289        assert_eq!(
4290            runtime_peer_probe_candidate(every, next, measured_ns, false),
4291            None
4292        );
4293        assert_eq!(
4294            runtime_peer_probe_candidate(every, next, measured_ns, true),
4295            Some((1, 8)),
4296        );
4297    }
4298
4299    #[test]
4300    fn late_runtime_reprobe_advances_once_instead_of_bursting_catchup() {
4301        let every = PEER_RUNTIME_PROBE_INTERVAL_COPIES;
4302        let due = every;
4303        assert_eq!(runtime_peer_probe_next_copy(due, due), due + 4 * every);
4304        assert_eq!(runtime_peer_probe_next_copy(due, 20 * every), 21 * every);
4305    }
4306
4307    #[test]
4308    fn runtime_reprobe_deferral_metric_counts_intervals_and_publishes_bound_state() {
4309        use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4310
4311        assert_eq!(
4312            PEER_RUNTIME_PROBE_DEFERRAL_BOUND_INTERVALS * PEER_RUNTIME_PROBE_INTERVAL_COPIES,
4313            PEER_RUNTIME_PROBE_CYCLE_COPIES,
4314        );
4315        let deferred = AtomicU64::new(0);
4316        let degraded = AtomicBool::new(false);
4317        publish_runtime_peer_probe_deferral(&deferred, &degraded, 1, false);
4318        assert_eq!(deferred.load(Ordering::Relaxed), 1);
4319        assert!(!degraded.load(Ordering::Acquire));
4320
4321        publish_runtime_peer_probe_deferral(
4322            &deferred,
4323            &degraded,
4324            PEER_RUNTIME_PROBE_DEFERRAL_BOUND_INTERVALS - 1,
4325            true,
4326        );
4327        assert_eq!(
4328            deferred.load(Ordering::Relaxed),
4329            PEER_RUNTIME_PROBE_DEFERRAL_BOUND_INTERVALS,
4330        );
4331        assert!(degraded.load(Ordering::Acquire));
4332    }
4333
4334    #[test]
4335    fn runtime_probe_failure_latches_native_before_publishing_validated_bounce() {
4336        use std::sync::atomic::{AtomicBool, Ordering};
4337
4338        let failed = AtomicBool::new(false);
4339        let degraded = AtomicBool::new(false);
4340        let armed = latch_runtime_host_bounce(&failed, &degraded, || Ok::<_, String>(()));
4341        assert!(armed.is_ok());
4342        assert!(failed.load(Ordering::Acquire));
4343        assert!(degraded.load(Ordering::Acquire));
4344
4345        let failed = AtomicBool::new(false);
4346        let degraded = AtomicBool::new(false);
4347        let refused = latch_runtime_host_bounce(&failed, &degraded, || {
4348            Err::<(), _>("injected staging mismatch".to_string())
4349        });
4350        assert_eq!(refused, Err("injected staging mismatch".to_string()));
4351        assert!(failed.load(Ordering::Acquire));
4352        assert!(!degraded.load(Ordering::Acquire));
4353    }
4354
4355    #[test]
4356    fn transport_selection_keeps_peer_default_and_bounces_only_cross_device() {
4357        assert_eq!(boundary_transport(false, false), BoundaryTransport::Local);
4358        assert_eq!(boundary_transport(false, true), BoundaryTransport::Local);
4359        assert_eq!(boundary_transport(true, false), BoundaryTransport::Peer);
4360        assert_eq!(
4361            boundary_transport(true, true),
4362            BoundaryTransport::HostBounce
4363        );
4364    }
4365
4366    #[test]
4367    fn step37_geometry_sizes_each_slot_from_the_prime_cap() {
4368        let (elems, bytes) = host_bounce_capacity(4096).expect("valid Step-3.7 geometry");
4369        assert_eq!(elems, 4096 * crate::cache::PRIME_CHUNK_MAX_TOKENS);
4370        assert_eq!(bytes, 64 * 1024 * 1024);
4371    }
4372
4373    #[test]
4374    fn host_bounce_capacity_rejects_invalid_or_overflowing_geometry() {
4375        assert!(host_bounce_capacity(0).is_err());
4376        assert!(host_bounce_capacity(usize::MAX).is_err());
4377    }
4378}