diff --git a/core/engine/src/compiled/core/mod.rs b/core/engine/src/compiled/core/mod.rs new file mode 100644 index 00000000..85732daf --- /dev/null +++ b/core/engine/src/compiled/core/mod.rs @@ -0,0 +1 @@ +pub(crate) mod switch; diff --git a/core/engine/src/compiled/core/switch.rs b/core/engine/src/compiled/core/switch.rs new file mode 100644 index 00000000..0ca48400 --- /dev/null +++ b/core/engine/src/compiled/core/switch.rs @@ -0,0 +1,166 @@ +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::time::Duration; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Path { + Typed, + Lane, +} + +pub(crate) struct Cost { + calls: AtomicU32, + typed: AtomicU64, + lane: AtomicU64, +} + +pub(crate) struct Density; + +#[derive(Clone, Copy)] +pub(crate) enum Switch<'c> { + Always, + Measured(&'c Cost), +} + +impl Density { + pub(crate) fn sparse(local: usize, rows: usize) -> bool { + local * 4 < rows + } +} + +impl Switch<'_> { + pub(crate) fn path(self) -> (Path, bool) { + match self { + Switch::Always => (Path::Typed, false), + Switch::Measured(cost) => cost.path(), + } + } + + pub(crate) fn record(self, path: (Path, bool), elapsed: Duration, rows: usize) { + if let Switch::Measured(cost) = self { + cost.record(path, elapsed, rows); + } + } +} + +impl Cost { + const WARM: u32 = 2; + const PERIOD: u32 = 64; + + pub(crate) fn new() -> Self { + Self { + calls: AtomicU32::new(0), + typed: AtomicU64::new(u64::MAX), + lane: AtomicU64::new(u64::MAX), + } + } + + pub(crate) fn path(&self) -> (Path, bool) { + let call = self.calls.fetch_add(1, Ordering::Relaxed); + if call < Self::WARM { + return (Path::Typed, false); + } + if call < 2 * Self::WARM { + return (Path::Lane, false); + } + let (faster, slower) = match self.typed.load(Ordering::Relaxed) <= self.lane.load(Ordering::Relaxed) { + true => (Path::Typed, Path::Lane), + false => (Path::Lane, Path::Typed), + }; + match call % Self::PERIOD { + 0 => (slower, true), + 1 => (faster, true), + _ => (faster, false), + } + } + + pub(crate) fn record(&self, (path, fresh): (Path, bool), elapsed: Duration, rows: usize) { + let per = u64::try_from(elapsed.as_nanos().saturating_mul(1024) / rows.max(1) as u128).unwrap_or(u64::MAX - 1); + let cell = match path { + Path::Typed => &self.typed, + Path::Lane => &self.lane, + }; + match fresh { + true => cell.store(per, Ordering::Relaxed), + false => { + cell.fetch_min(per, Ordering::Relaxed); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::{Cost, Density, Path, Switch}; + use std::time::Duration; + + fn timed(cost: &Cost, typed: u64, lane: u64) -> Vec<(Path, bool)> { + (0..130) + .map(|_| { + let path = cost.path(); + let nanos = match path.0 { + Path::Typed => typed, + Path::Lane => lane, + }; + cost.record(path, Duration::from_nanos(nanos), 1024); + path + }) + .collect() + } + + #[test] + fn warm_calls_alternate_then_pick_the_faster_path() { + let cost = Cost::new(); + let calls = timed(&cost, 10, 20); + assert_eq!(&calls[..4], &[(Path::Typed, false), (Path::Typed, false), (Path::Lane, false), (Path::Lane, false)]); + assert!(calls[4..64].iter().all(|&call| call == (Path::Typed, false))); + assert_eq!(calls[64], (Path::Lane, true)); + assert_eq!(calls[65], (Path::Typed, true)); + assert!(calls[66..128].iter().all(|&call| call == (Path::Typed, false))); + assert_eq!(calls[128], (Path::Lane, true)); + assert_eq!(calls[129], (Path::Typed, true)); + } + + #[test] + fn lane_wins_when_it_is_faster() { + let cost = Cost::new(); + let calls = timed(&cost, 30, 20); + assert!(calls[4..64].iter().all(|&call| call == (Path::Lane, false))); + assert_eq!(calls[64], (Path::Typed, true)); + assert_eq!(calls[65], (Path::Lane, true)); + } + + #[test] + fn fresh_probe_replaces_the_minimum() { + let cost = Cost::new(); + for _ in 0..4 { + let path = cost.path(); + cost.record(path, Duration::from_nanos(10), 1024); + } + (4..64).for_each(|_| { + cost.path(); + }); + cost.record((Path::Typed, true), Duration::from_nanos(50), 1024); + assert_eq!(cost.path(), (Path::Typed, true)); + cost.record((Path::Typed, false), Duration::from_nanos(5), 1024); + assert_eq!(cost.path(), (Path::Typed, true)); + assert_eq!(cost.path(), (Path::Typed, false)); + } + + #[test] + fn always_switch_never_touches_the_cost() { + let cost = Cost::new(); + assert_eq!(Switch::Always.path(), (Path::Typed, false)); + Switch::Always.record((Path::Lane, true), Duration::from_nanos(1), 1); + assert_eq!(Switch::Measured(&cost).path(), (Path::Typed, false)); + } + + #[test] + fn density_matches_both_gates() { + for rows in 0..70 { + for local in 0..=rows { + let full = local == rows; + assert_eq!(Density::sparse(local, rows), !full && local * 4 < rows); + } + } + } +} diff --git a/core/engine/src/compiled/graph/plan/run/typed.rs b/core/engine/src/compiled/graph/plan/run/typed.rs index 8fc39f53..39c0bd78 100644 --- a/core/engine/src/compiled/graph/plan/run/typed.rs +++ b/core/engine/src/compiled/graph/plan/run/typed.rs @@ -1,6 +1,7 @@ use crate::compiled::graph::plan::view::{M, SlotId}; use crate::compiled::graph::table::{First, Table}; -use crate::compiled::graph::plan::typed::{Deferred, Grouping, Path, Piece, Target, TypedOp}; +use crate::compiled::core::switch::{Density, Path, Switch}; +use crate::compiled::graph::plan::typed::{Deferred, Grouping, Piece, Target, TypedOp}; use crate::compiled::graph::plan::{Op, SegPlan, TableOp}; use zen_expression::typed::{Batch, Data as Slotted, Slot}; use crate::compiled::shred::{Normalizer, Seen}; @@ -61,11 +62,12 @@ impl<'a> Run<'_, 'a> { pub(super) fn typed(&mut self, seg: &SegPlan, op: &TypedOp, units: &[Op], positions: Option<&Rc<[usize]>>) { let rows = self.store.rows; let local = positions.map_or(rows, |p| p.len()); - if local * 4 < rows { + if Density::sparse(local, rows) { self.laned(seg, units, positions); return; } - let path = op.cost.path(); + let switch = Switch::Measured(&op.cost); + let path = switch.path(); let start = Instant::now(); let typed = match path.0 { Path::Typed => self.lowered(seg, op, positions).map(|lowered| self.merged(seg, op, units, positions, lowered)).is_some(), @@ -74,7 +76,7 @@ impl<'a> Run<'_, 'a> { if !typed { self.laned(seg, units, positions); } - op.cost.record(path, start.elapsed(), local); + switch.record(path, start.elapsed(), local); } fn laned(&mut self, seg: &SegPlan, units: &[Op], positions: Option<&Rc<[usize]>>) { diff --git a/core/engine/src/compiled/graph/plan/typed.rs b/core/engine/src/compiled/graph/plan/typed.rs index b432457e..1de8abd1 100644 --- a/core/engine/src/compiled/graph/plan/typed.rs +++ b/core/engine/src/compiled/graph/plan/typed.rs @@ -1,12 +1,12 @@ use super::view::{Expr, Masks, M, Ref, Shape, SlotId}; use super::{Builder, LaneOp, Op, Program, SlotInfo, Source, TableMode, TableOp}; +use crate::compiled::core::switch::Cost; use crate::compiled::lowered::Exports; use crate::compiled::shred::Seen; use crate::compiled::graph::table::Table; use crate::compiled::graph::{Body, CompiledGraph, Kind}; -use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::atomic::AtomicU32; use std::sync::{Arc, RwLock}; -use std::time::Duration; use zen_expression::lane::{Binding as Site, Fusion}; use zen_expression::typed::{Class, Lowering, Program as Typed, Resolve, Resolved}; @@ -57,18 +57,6 @@ enum Attempt { Failed, } -#[derive(Clone, Copy, PartialEq, Eq)] -pub(crate) enum Path { - Typed, - Lane, -} - -pub(crate) struct Cost { - calls: AtomicU32, - typed: AtomicU64, - lane: AtomicU64, -} - struct Probe<'p> { masks: &'p Masks, slots: &'p [SlotInfo], @@ -126,52 +114,6 @@ impl Deferred { } } -impl Cost { - const WARM: u32 = 2; - const PERIOD: u32 = 64; - - fn new() -> Self { - Self { - calls: AtomicU32::new(0), - typed: AtomicU64::new(u64::MAX), - lane: AtomicU64::new(u64::MAX), - } - } - - pub fn path(&self) -> (Path, bool) { - let call = self.calls.fetch_add(1, Ordering::Relaxed); - if call < Self::WARM { - return (Path::Typed, false); - } - if call < 2 * Self::WARM { - return (Path::Lane, false); - } - let (faster, slower) = match self.typed.load(Ordering::Relaxed) <= self.lane.load(Ordering::Relaxed) { - true => (Path::Typed, Path::Lane), - false => (Path::Lane, Path::Typed), - }; - match call % Self::PERIOD { - 0 => (slower, true), - 1 => (faster, true), - _ => (faster, false), - } - } - - pub fn record(&self, (path, fresh): (Path, bool), elapsed: Duration, rows: usize) { - let per = u64::try_from(elapsed.as_nanos().saturating_mul(1024) / rows.max(1) as u128).unwrap_or(u64::MAX - 1); - let cell = match path { - Path::Typed => &self.typed, - Path::Lane => &self.lane, - }; - match fresh { - true => cell.store(per, Ordering::Relaxed), - false => { - cell.fetch_min(per, Ordering::Relaxed); - } - } - } -} - impl Resolve for Probe<'_> { fn path(&mut self, path: &str) -> Resolved { let Some((_, read)) = self.reads.iter().find(|(key, _)| key.as_ref() == path) else { diff --git a/core/engine/src/compiled/mod.rs b/core/engine/src/compiled/mod.rs index 401b5ac2..900a4449 100644 --- a/core/engine/src/compiled/mod.rs +++ b/core/engine/src/compiled/mod.rs @@ -1,3 +1,4 @@ +mod core; pub(crate) mod exact; mod graph; mod leaf; diff --git a/core/engine/src/compiled/policy/columnar/typed.rs b/core/engine/src/compiled/policy/columnar/typed.rs index 122b8de1..42093397 100644 --- a/core/engine/src/compiled/policy/columnar/typed.rs +++ b/core/engine/src/compiled/policy/columnar/typed.rs @@ -1,5 +1,6 @@ use super::fuse::{Fused, Fusions, Sink}; use super::{Bind, Member, Pass, Sheet}; +use crate::compiled::core::switch::{Density, Path, Switch}; use crate::compiled::lowered::Exports; use crate::compiled::shred::{Listing, Normalizer}; use crate::compiled::leaf::{Bits, Leaf}; @@ -211,7 +212,7 @@ impl<'s, 'a> Pass<'s, 'a> { pub(super) fn typed(&mut self, units: &[(usize, usize, usize)], entity: Option, rows: &[usize]) -> (usize, Vec) { let total = self.sheet.rows; let full = rows.len() == total; - if !full && rows.len() * 4 < total { + if Density::sparse(rows.len(), total) || Switch::Always.path().0 == Path::Lane { return (0, Vec::new()); } let plan = self.plan;