// crates/ml/src/cuda_pipeline/target_q_p99_kernel.cu
//
// SP4 Layer A Task A5 — first end-to-end SP4 producer.
//
// Single-block kernel. Reads `denoise_target_q_buf [count]` (target-network
// Q-values flattened over `[B, num_actions]`), computes p99(|target_q|) via
// the header-only `sp4_histogram_p99<256>` device function, writes the
// step_observation to `producer_step_scratch_buf[scratch_idx]`. The host
// launcher (`GpuDqnTrainer::launch_sp4_target_q_p99`) follows up with the
// GPU `apply_pearls_ad_kernel` on the same stream which writes the new
// x_mean to ISV[TARGET_Q_BOUND_INDEX=131] + Wiener state back to
// `wiener_state_buf` (graph-capture-compatible 2026-05-01 GPU-Pearls
// refactor — no host sync between producer and applicator).

#include "sp4_histogram_p99.cuh"

extern "C" __global__ void target_q_p99_update(
    const float* __restrict__ buf,
    int          count,
    float*       __restrict__ scratch_buf,
    int          scratch_idx
) {
    if (blockIdx.x != 0) return;
    float p99 = sp4_histogram_p99<256>(buf, count);
    if (threadIdx.x == 0) {
        scratch_buf[scratch_idx] = p99;
        __threadfence_system();   // make host-mapped write visible
    }
}
