//! Validated Binary Loader & Thread-Local Cache for the Corpus-Trained LightGBM Ensemble (`trained_forest`). //! //! Binary format `AIDGB02\0` (`src/weights/gbdt_forest.bin`): //! - `[0..8]`: Magic `"AIDGB02\0"` //! - `[8..16]`: `base_margin: f64` (LE) //! - `[16..24]`: `platt_slope: f64` (LE) //! - `[24..32]`: `platt_intercept: f64` (LE) //! - `[32..36]`: `num_trees: u32` (LE) //! - `[36..40]`: `num_knots: u32` (LE) //! - Knots: `num_knots * 16` bytes of `(margin: f64, prob: f64)` (LE) //! - Trees: `num_trees` blocks of `num_nodes: u16` followed by `num_nodes * 30` bytes //! `(feature: i16, left: u16, right: u16, threshold: f64, leaf_value: f64, cover: f64)`. use std::cell::OnceCell; use crate::gbdt::{TrainedGbdtModel, TreeNode}; use crate::model::DetectError; /// Raw embedded LightGBM + Isotonic Calibration binary (`src/weights/gbdt_forest.bin`). pub static EMBEDDED_GBDT_BYTES: &[u8] = include_bytes!("weights/gbdt_forest.bin"); /// Decoded owned forest cached once per Wasm/native thread. pub struct DecodedForest { base_margin: f64, platt_tail: (f64, f64), knots: Vec<(f64, f64)>, trees: Vec>, } thread_local! { static CACHED_FOREST: OnceCell = const { OnceCell::new() }; } fn read_u16_le(buf: &[u8], off: &mut usize) -> Option { let s = buf.get(*off..*off + 2)?; *off += 2; Some(u16::from_le_bytes([*s.first()?, *s.get(1)?])) } fn read_i16_le(buf: &[u8], off: &mut usize) -> Option { let s = buf.get(*off..*off + 2)?; *off += 2; Some(i16::from_le_bytes([*s.first()?, *s.get(1)?])) } fn read_u32_le(buf: &[u8], off: &mut usize) -> Option { let s = buf.get(*off..*off + 4)?; *off += 4; Some(u32::from_le_bytes([ *s.first()?, *s.get(1)?, *s.get(2)?, *s.get(3)?, ])) } fn read_f64_le(buf: &[u8], off: &mut usize) -> Option { let s = buf.get(*off..*off + 8)?; *off += 8; Some(f64::from_le_bytes([ *s.first()?, *s.get(1)?, *s.get(2)?, *s.get(3)?, *s.get(4)?, *s.get(5)?, *s.get(6)?, *s.get(7)?, ])) } /// Parses and validates an `AIDGB02\0` binary forest buffer without panicking. pub fn decode_gbdt_bytes(raw: &[u8]) -> Result { if raw.get(0..8) != Some(b"AIDGB02\0".as_slice()) { return Err(DetectError::NullOrInvalidBuffer); } let mut off = 8usize; let base_margin = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; let platt_slope = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; let platt_intercept = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; let num_trees = usize::try_from(read_u32_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?) .unwrap_or(0); let num_knots = usize::try_from(read_u32_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?) .unwrap_or(0); if num_trees == 0 || num_trees > 1024 || num_knots > 512 { return Err(DetectError::NullOrInvalidBuffer); } let mut knots = Vec::with_capacity(num_knots); for _ in 0..num_knots { let kx = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; let ky = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; knots.push((kx, ky)); } let mut trees = Vec::with_capacity(num_trees); for _ in 0..num_trees { let n_nodes = usize::from(read_u16_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?); if n_nodes == 0 || n_nodes > 512 { return Err(DetectError::NullOrInvalidBuffer); } let mut nodes = Vec::with_capacity(n_nodes); for _ in 0..n_nodes { let feature = read_i16_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; let left = read_u16_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; let right = read_u16_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; let threshold = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; let leaf_value = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; let cover = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; nodes.push(TreeNode { feature, left, right, threshold, leaf_value, cover, }); } trees.push(nodes); } Ok(DecodedForest { base_margin, platt_tail: (platt_slope, platt_intercept), knots, trees, }) } /// Evaluates `f` with a zero-copy `TrainedGbdtModel` view backed by the thread-local decoded forest. pub fn with_trained_gbdt(f: F) -> Result where F: FnOnce(TrainedGbdtModel<'_>) -> R, { CACHED_FOREST.with(|cell| { if cell.get().is_none() { let decoded = decode_gbdt_bytes(EMBEDDED_GBDT_BYTES)?; let _ = cell.set(decoded); } let Some(forest) = cell.get() else { return Err(DetectError::NullOrInvalidBuffer); }; let tree_slices: Vec<&[TreeNode]> = forest.trees.iter().map(Vec::as_slice).collect(); let view = TrainedGbdtModel { base_margin: forest.base_margin, trees: &tree_slices, isotonic_knots: &forest.knots, platt_tail: forest.platt_tail, }; Ok(f(view)) }) }