grippo 0.2.0

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/grok/shadow.rs
// Purpose:   Live lines checked and timed on both the steps and the regex
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Opt-in: a sampled line runs on the steps and on the regex. A disagreement
//! is counted, and when the steps take more than twice the regex's time the
//! parser runs the regex first, until they don't.

use std::num::NonZeroU32;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering::Relaxed};

use crate::parse::{Counter, Fields, Parsed};

/// The share of the way a running average moves to each new sample.
const WEIGHT: f32 = 1.0 / 16.0;
/// Samples before the averages decide anything.
const WARM: u32 = 16;

pub(super) struct Shadow {
    every: u32,
    seen: AtomicU32,
    samples: AtomicU32,
    /// Running averages in ns, as `f32` bits. A lost update between threads
    /// only delays a switch.
    steps_ns: AtomicU32,
    regex_ns: AtomicU32,
    regex_first: AtomicBool,
    disagree: Counter,
}

impl Shadow {
    pub(super) const fn new(every: NonZeroU32, disagree: Counter) -> Self {
        Self {
            every: every.get(),
            seen: AtomicU32::new(0),
            samples: AtomicU32::new(0),
            steps_ns: AtomicU32::new(0),
            regex_ns: AtomicU32::new(0),
            regex_first: AtomicBool::new(false),
            disagree,
        }
    }

    /// This line is one to sample.
    pub(super) fn sample(&self) -> bool {
        self.seen.fetch_add(1, Relaxed).is_multiple_of(self.every)
    }

    /// The regex has been more than twice as fast as the steps.
    pub(super) fn regex_first(&self) -> bool {
        self.regex_first.load(Relaxed)
    }

    /// One sampled line: both paths' times and whether they agreed.
    pub(super) fn record(&self, steps_ns: f32, regex_ns: f32, agreed: bool) {
        if !agreed {
            self.disagree.increment(1);
        }
        let n = self.samples.fetch_add(1, Relaxed).saturating_add(1);
        let average = |slot: &AtomicU32, x: f32| {
            let old = f32::from_bits(slot.load(Relaxed));
            let new = if n == 1 {
                x
            } else {
                (x - old).mul_add(WEIGHT, old)
            };
            slot.store(new.to_bits(), Relaxed);
            new
        };
        let steps = average(&self.steps_ns, steps_ns);
        let regex = average(&self.regex_ns, regex_ns);
        if n >= WARM {
            self.regex_first.store(switches(steps, regex), Relaxed);
        }
    }
}

/// Run the regex first while the steps take more than twice its time.
pub(super) fn switches(steps_ns: f32, regex_ns: f32) -> bool {
    steps_ns > 2.0 * regex_ns
}

/// The two paths gave the same answer and the same fields.
pub(super) fn agree(a: &Parsed, fa: &Fields<'_>, b: &Parsed, fb: &Fields<'_>) -> bool {
    let sorted = |f: &Fields<'_>| {
        let mut v: Vec<(String, Vec<u8>)> = f
            .as_slice()
            .iter()
            .map(|(n, v)| (n.clone(), v.bytes.to_vec()))
            .collect();
        v.sort_unstable();
        v
    };
    a == b && sorted(fa) == sorted(fb)
}

/// A timer, or none on a target with no clock, where the shadow only compares.
pub(super) struct Clock(
    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] std::time::Instant,
);

impl Clock {
    pub(super) fn now() -> Self {
        Self(
            #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
            std::time::Instant::now(),
        )
    }

    #[allow(
        clippy::cast_precision_loss,
        reason = "a parse takes far below 2^24 ns"
    )]
    pub(super) fn ns(&self) -> f32 {
        #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
        return self.0.elapsed().as_nanos() as f32;
        #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
        0.0
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parse::{FieldSink, FieldValue, Hint};

    fn shadow() -> Shadow {
        Shadow::new(NonZeroU32::MIN, crate::parse::counter("t", &[]))
    }

    #[test]
    fn the_regex_goes_first_only_past_twice_the_steps_time() {
        let s = shadow();
        for _ in 0..WARM - 1 {
            s.record(300.0, 100.0, true);
        }
        assert!(!s.regex_first(), "too few samples to decide");
        s.record(300.0, 100.0, true);
        assert!(s.regex_first());
        // The steps recover: the averages cross back below 2x.
        for _ in 0..64 {
            s.record(100.0, 100.0, true);
        }
        assert!(!s.regex_first());
        assert!(!switches(200.0, 100.0) && switches(201.0, 100.0));
    }

    #[test]
    fn agreement_is_the_same_answer_and_the_same_fields_in_any_order() {
        let (mut a, mut b) = (Fields::new(), Fields::new());
        a.field("x", FieldValue::borrowed(b"1", Hint::Text));
        a.field("y", FieldValue::borrowed(b"2", Hint::Text));
        b.field("y", FieldValue::borrowed(b"2", Hint::Int));
        b.field("x", FieldValue::borrowed(b"1", Hint::Text));
        assert!(agree(&Parsed::Done, &a, &Parsed::Done, &b));
        assert!(!agree(&Parsed::Done, &a, &Parsed::NoMatch, &b));
        b.field("z", FieldValue::borrowed(b"3", Hint::Text));
        assert!(!agree(&Parsed::Done, &a, &Parsed::Done, &b));
    }
}