use rustsy_process::Graph;
use serde::{Deserialize, Serialize};
use std::{
collections::BTreeSet,
fs::File,
io::{self, BufReader},
path::Path,
};
#[derive(Deserialize)]
struct Sample {
contract: String,
execution: Execution,
}
#[derive(Deserialize)]
struct Execution {
tool_hash_ns: u64,
nodes: Vec<Node>,
}
#[derive(Deserialize)]
struct Node {
name: String,
status: String,
cache: String,
process_ns: u64,
hashing_ns: u64,
cache_lookup_restore_ns: u64,
}
#[derive(Serialize)]
pub(super) struct Decision {
pub(super) bypass: bool,
pub(super) rationale: &'static str,
direct_path_ns: Option<u64>,
observed_direct_work_ns: Option<u64>,
tool_hash_floor_ns: u64,
expected_key_and_lookup_path_ns: u64,
observed_hit_rate: f64,
samples: usize,
planning_ns: u128,
}
pub(super) fn choose(
paths: &[&Path],
contract: &str,
names: &[&str],
graph: &Graph,
) -> io::Result<Decision> {
let started = std::time::Instant::now();
let mut count = 0;
let mut hits = 0;
let mut probes = 0;
let mut direct = vec![0; names.len()];
let mut best_tools = None::<u64>;
let mut cache_path = 0;
let mut unique = BTreeSet::new();
for &path in paths {
if !unique.insert(path.canonicalize()?) {
continue;
}
let sample: Sample = serde_json::from_reader(BufReader::new(File::open(path)?))?;
let run = sample.execution;
if sample.contract != contract
|| !run
.nodes
.iter()
.map(|n| n.name.as_str())
.eq(names.iter().copied())
|| run
.nodes
.iter()
.any(|n| !matches!(n.status.as_str(), "cached" | "executed"))
{
continue;
}
count += 1;
if run.tool_hash_ns != 0 {
best_tools = Some(best_tools.map_or(run.tool_hash_ns, |n| n.min(run.tool_hash_ns)));
}
let mut costs = Vec::with_capacity(names.len());
for (id, node) in run.nodes.iter().enumerate() {
direct[id] = direct[id].max(node.process_ns);
hits += usize::from(node.cache == "hit");
probes += usize::from(node.cache != "off");
costs.push(if node.cache == "hit" {
node.hashing_ns.saturating_add(node.cache_lookup_restore_ns)
} else {
0
});
}
cache_path = cache_path.max(graph.cost_path(&costs).unwrap_or(0));
}
let direct_path = direct
.iter()
.all(|&n| n != 0)
.then(|| graph.cost_path(&direct).unwrap_or(0));
let direct_work = direct_path.map(|_| direct.iter().copied().fold(0u64, u64::saturating_add));
let tool_floor = best_tools.unwrap_or(0);
let bypass = count >= 2 && direct_work.is_some_and(|ns| tool_floor > ns.saturating_add(ns / 2));
Ok(Decision {
bypass,
rationale: if bypass {
"tool verification alone exceeds the observed sum of process work by the required margin"
} else {
"strict cache retained; insufficient evidence that direct execution is cheaper"
},
direct_path_ns: direct_path,
observed_direct_work_ns: direct_work,
tool_hash_floor_ns: tool_floor,
expected_key_and_lookup_path_ns: cache_path,
observed_hit_rate: (hits as f64 + 1.0) / (probes as f64 + 2.0),
samples: count,
planning_ns: started.elapsed().as_nanos(),
})
}