use std::cell::Cell;
use std::collections::BTreeMap;
use std::thread::LocalKey;
use relate_core::{Result, Value};
use web_time::Instant;
use crate::frontier_decline::FrontierDeclineReason;
use crate::overlay::ExecGraph;
use crate::redo::RedoOp;
use crate::row::Row;
#[derive(Clone, Copy)]
pub(crate) struct QueryCtx<'a> {
pub query_text: &'a str,
pub principal: Option<&'a str>,
pub batch_commit: Option<&'a dyn BatchCommit>,
}
#[derive(Clone, Copy)]
pub(crate) struct PlanMetricsSite<'a> {
pub(crate) sink: &'a dyn PlanMetricsSink,
pub(crate) stage: usize,
pub(crate) part: usize,
}
impl<'a> PlanMetricsSite<'a> {
pub(crate) fn at(sink: &'a dyn PlanMetricsSink, stage: usize, part: usize) -> Self {
PlanMetricsSite { sink, stage, part }
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct StoreReads {
pub hops: u64,
pub neighbor_walks: u64,
pub node_reads: u64,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PhaseTimes {
pub seek_ns: u128,
pub walk_ns: u128,
}
impl PhaseTimes {
pub fn since(self, earlier: PhaseTimes) -> PhaseTimes {
PhaseTimes {
seek_ns: self.seek_ns - earlier.seek_ns,
walk_ns: self.walk_ns - earlier.walk_ns,
}
}
}
thread_local! {
static PHASE_PROFILING: Cell<bool> = const { Cell::new(false) };
static SEEK_NS: Cell<u128> = const { Cell::new(0) };
static WALK_NS: Cell<u128> = const { Cell::new(0) };
}
pub(crate) fn arm_phase_profiling() {
PHASE_PROFILING.with(|c| c.set(true));
}
pub(crate) fn disarm_phase_profiling() {
PHASE_PROFILING.with(|c| c.set(false));
}
fn phase_span<T>(sum: &'static LocalKey<Cell<u128>>, run: impl FnOnce() -> Result<T>) -> Result<T> {
let stamp = PHASE_PROFILING.with(Cell::get).then(Instant::now);
let out = run()?;
if let Some(start) = stamp {
sum.with(|c| c.set(c.get() + start.elapsed().as_nanos()));
}
Ok(out)
}
pub(crate) fn phase_seek<T>(resolve: impl FnOnce() -> Result<T>) -> Result<T> {
phase_span(&SEEK_NS, resolve)
}
pub(crate) fn phase_walk<T>(walk: impl FnOnce() -> Result<T>) -> Result<T> {
phase_span(&WALK_NS, walk)
}
pub(crate) fn phase_times() -> PhaseTimes {
PhaseTimes {
seek_ns: SEEK_NS.with(Cell::get),
walk_ns: WALK_NS.with(Cell::get),
}
}
thread_local! {
static NODE_READS: Cell<u64> = const { Cell::new(0) };
}
pub(crate) fn count_node_reads(count: u64) {
NODE_READS.with(|c| c.set(c.get() + count));
}
pub(crate) fn node_reads() -> u64 {
NODE_READS.with(Cell::get)
}
#[cfg(test)]
pub(crate) fn take_node_reads() -> u64 {
NODE_READS.with(|c| c.replace(0))
}
pub const REARRIVAL_WORK_BUDGET: u64 = 1_000_000;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct FrontierCounters {
pub edge_visits: u64,
pub levels: u64,
pub endpoints: u64,
pub cells: u64,
pub rearrival_work: u64,
pub memo_hits: u64,
pub memo_misses: u64,
pub representative_proofs: u64,
pub search_proven: u64,
pub search_disproven: u64,
pub declined_exhausted: u64,
}
impl FrontierCounters {
pub fn since(self, earlier: FrontierCounters) -> FrontierCounters {
self - earlier
}
pub fn budget_fraction(&self) -> f64 {
self.rearrival_work as f64 / REARRIVAL_WORK_BUDGET as f64
}
}
impl std::ops::Sub for FrontierCounters {
type Output = FrontierCounters;
fn sub(self, earlier: FrontierCounters) -> FrontierCounters {
let FrontierCounters {
edge_visits,
levels,
endpoints,
cells,
rearrival_work,
memo_hits,
memo_misses,
representative_proofs,
search_proven,
search_disproven,
declined_exhausted,
} = earlier;
FrontierCounters {
edge_visits: self.edge_visits - edge_visits,
levels: self.levels - levels,
endpoints: self.endpoints - endpoints,
cells: self.cells - cells,
rearrival_work: self.rearrival_work - rearrival_work,
memo_hits: self.memo_hits - memo_hits,
memo_misses: self.memo_misses - memo_misses,
representative_proofs: self.representative_proofs - representative_proofs,
search_proven: self.search_proven - search_proven,
search_disproven: self.search_disproven - search_disproven,
declined_exhausted: self.declined_exhausted - declined_exhausted,
}
}
}
impl std::ops::AddAssign for FrontierCounters {
fn add_assign(&mut self, run: FrontierCounters) {
let FrontierCounters {
edge_visits,
levels,
endpoints,
cells,
rearrival_work,
memo_hits,
memo_misses,
representative_proofs,
search_proven,
search_disproven,
declined_exhausted,
} = run;
self.edge_visits += edge_visits;
self.levels += levels;
self.endpoints += endpoints;
self.cells += cells;
self.rearrival_work += rearrival_work;
self.memo_hits += memo_hits;
self.memo_misses += memo_misses;
self.representative_proofs += representative_proofs;
self.search_proven += search_proven;
self.search_disproven += search_disproven;
self.declined_exhausted += declined_exhausted;
}
}
impl StoreReads {
pub fn since(self, earlier: StoreReads) -> StoreReads {
StoreReads {
hops: self.hops - earlier.hops,
neighbor_walks: self.neighbor_walks - earlier.neighbor_walks,
node_reads: self.node_reads - earlier.node_reads,
}
}
pub fn total(self) -> u64 {
self.hops + self.neighbor_walks + self.node_reads
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct WalkStart {
pub element: usize,
pub backward: bool,
pub reason: StartReason,
}
impl WalkStart {
pub(crate) fn seed_side_forward() -> WalkStart {
WalkStart {
element: 0,
backward: false,
reason: StartReason::IndexZero,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StartReason {
BoundPivot,
Cheapest,
SeekAnchored,
IndexZero,
}
impl StartReason {
pub fn as_str(self) -> &'static str {
match self {
StartReason::BoundPivot => "bound-pivot",
StartReason::Cheapest => "cheapest",
StartReason::SeekAnchored => "seek-anchored",
StartReason::IndexZero => "index-0",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KernelRung {
Chain { hops: usize },
HubStar,
FrontierNfa,
Walker,
}
impl KernelRung {
pub fn as_str(self) -> &'static str {
match self {
KernelRung::Chain { .. } => relate_model::wire::KernelRungWire::CHAIN,
KernelRung::HubStar => relate_model::wire::KernelRungWire::HUB_STAR,
KernelRung::FrontierNfa => relate_model::wire::KernelRungWire::FRONTIER_NFA,
KernelRung::Walker => relate_model::wire::KernelRungWire::WALKER,
}
}
}
pub struct ClauseMetricsRecord {
pub stage: usize,
pub part: usize,
pub clause: usize,
pub rows: u64,
pub memory_bytes: u64,
pub expression_built_bytes: u64,
pub time_ns: u128,
pub reads: StoreReads,
pub phases: PhaseTimes,
pub start: Option<WalkStart>,
pub kernel: Option<KernelRung>,
pub batched: bool,
pub zone_skips: u64,
pub frontier: FrontierCounters,
pub frontier_decline: Option<FrontierDeclineReason>,
}
pub trait PlanMetricsSink {
fn record_clause(&self, record: ClauseMetricsRecord);
}
pub trait BatchCommit {
fn commit_batch(&self, ops: Vec<RedoOp>, snapshot_ts: u64) -> Result<u64>;
}
impl<'a> QueryCtx<'a> {
pub(crate) fn new(query_text: &'a str) -> Self {
Self {
query_text,
principal: None,
batch_commit: None,
}
}
pub(crate) fn with_principal(mut self, principal: Option<&'a str>) -> Self {
self.principal = principal;
self
}
pub(crate) fn with_batch_commit(mut self, sink: Option<&'a dyn BatchCommit>) -> Self {
self.batch_commit = sink;
self
}
}
#[derive(Clone, Copy)]
pub(crate) struct ExecCtx<'a> {
pub graph: &'a ExecGraph<'a>,
pub params: &'a BTreeMap<String, Value>,
pub principal: Option<&'a str>,
}
impl<'a> ExecCtx<'a> {
pub(crate) fn new(graph: &'a ExecGraph<'a>, params: &'a BTreeMap<String, Value>) -> Self {
Self {
graph,
params,
principal: None,
}
}
pub(crate) fn with_principal(mut self, principal: Option<&'a str>) -> Self {
self.principal = principal;
self
}
}
#[derive(Clone, Copy)]
pub(crate) struct EvalCtx<'a> {
pub graph: &'a ExecGraph<'a>,
pub row: &'a Row,
pub params: &'a BTreeMap<String, Value>,
}