use crate::fkc::cost_expr::{CompiledCostExpr, CostEvalError, eval};
use crate::fkc::lower::{ResolvedFused, ResolvedPrimitive};
use crate::fused::CostEstimate;
use fuel_graph::registry::FusedOpParams;
use fuel_ir::{DType, Shape};
use std::sync::{Mutex, OnceLock};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CostClassKind {
Free,
JudgeMeasured,
DeclaredFormula,
VendorSpec,
}
pub fn classify_cost(
provenance: &str,
class: &str,
has_any_expr: bool,
has_cost_fn: bool,
) -> Option<CostClassKind> {
if class == "free" {
return Some(CostClassKind::Free);
}
match provenance {
"judge_measured" => Some(CostClassKind::JudgeMeasured),
"declared" if has_cost_fn => Some(CostClassKind::VendorSpec),
"declared" if has_any_expr => Some(CostClassKind::DeclaredFormula),
_ => None,
}
}
pub fn intern_cost_expr(expr: &CompiledCostExpr) -> Option<&'static CompiledCostExpr> {
if matches!(expr, CompiledCostExpr::Unknown) {
return None;
}
static POOL: OnceLock<Mutex<Vec<&'static CompiledCostExpr>>> = OnceLock::new();
let pool = POOL.get_or_init(|| Mutex::new(Vec::new()));
let mut g = pool.lock().expect("cost_expr interner poisoned");
if let Some(&e) = g.iter().find(|&&x| x == expr) {
return Some(e);
}
let leaked: &'static CompiledCostExpr = Box::leak(Box::new(expr.clone()));
g.push(leaked);
Some(leaked)
}
pub fn stamp_primitive_cost_expr(p: &ResolvedPrimitive) -> Option<&'static CompiledCostExpr> {
if p.cost_fn.is_some() {
return None;
}
intern_cost_expr(&p.cost)
}
pub fn stamp_fused_cost_expr(f: &ResolvedFused) -> Option<&'static CompiledCostExpr> {
intern_cost_expr(&f.cost)
}
pub fn fused_cost_estimate(
expr: &CompiledCostExpr,
input_shapes: &[Shape],
input_dtypes: &[DType],
_params: &FusedOpParams,
) -> Result<CostEstimate, CostEvalError> {
let mut b = std::collections::HashMap::new();
if let Some(s) = input_shapes.last() {
b.insert("n".to_string(), s.elem_count() as f64);
}
if let Some(d) = input_dtypes.last() {
b.insert("dtype_bytes".to_string(), d.size_in_bytes() as f64);
}
Ok(CostEstimate {
flops: eval(expr, &b)?.max(0.0) as u64,
..Default::default()
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fkc::cost_expr::compile_field;
#[test]
fn unknown_cost_expr_is_never_interned() {
assert!(
intern_cost_expr(&CompiledCostExpr::Unknown).is_none(),
"Unknown must map to None, never a leaked handle"
);
}
#[test]
fn equal_expressions_dedup_to_the_same_leaked_pointer() {
let a = compile_field(Some("n")).expect("parses");
let b = compile_field(Some("n")).expect("parses");
let pa = intern_cost_expr(&a).expect("interned");
let pb = intern_cost_expr(&b).expect("interned");
assert!(
std::ptr::eq(pa, pb),
"equal cost expressions must dedup to the same leaked pointer"
);
let c = compile_field(Some("2 * n")).expect("parses");
let pc = intern_cost_expr(&c).expect("interned");
assert!(
!std::ptr::eq(pa, pc),
"a distinct cost expression must not collide with an unrelated one"
);
}
}