use polydat::dsl::compile::compile_polydat_with;
use polydat::{Engine, JitMode, Kernel, KernelError, Provenance};
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
fn outside() -> &'static Mutex<HashMap<String, f64>> {
static OUTSIDE: OnceLock<Mutex<HashMap<String, f64>>> = OnceLock::new();
OUTSIDE.get_or_init(|| Mutex::new(HashMap::new()))
}
fn set(key: &str, v: f64) {
outside()
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(key.to_string(), v);
}
#[polydat::polydat_node(
category = Context,
purity = Nondeterministic("reads state outside the graph; changes between cycles"),
)]
fn host_reading(which: Const<&str>) -> f64 {
outside()
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(which.0)
.copied()
.unwrap_or(0.0)
}
fn tiers() -> Vec<Engine> {
let mut all = vec![
Engine::Interpreter(JitMode::Auto),
Engine::Closures(Provenance::Auto),
Engine::Closures(Provenance::Raw),
];
if cfg!(feature = "jit") {
all.push(Engine::Native(Provenance::Auto));
all.push(Engine::Native(Provenance::Raw));
all.push(Engine::PureNative(Provenance::Auto));
all.push(Engine::PureNative(Provenance::Raw));
}
all
}
fn src(prefix: &str) -> String {
format!("a := host_reading(\"{prefix}.a\")\nb := host_reading(\"{prefix}.b\")\n")
}
fn read(k: &mut dyn Kernel, cycle: u64) -> Vec<polydat::ast::Value> {
k.set_inputs(&[cycle]);
["a", "b"].iter().map(|n| k.pull(n)).collect()
}
fn kernels(prefix: &str) -> Vec<(String, Box<dyn Kernel>)> {
kernels_of(&src(prefix))
}
fn kernels_of(source: &str) -> Vec<(String, Box<dyn Kernel>)> {
let mut out: Vec<(String, Box<dyn Kernel>)> = Vec::new();
for tier in tiers() {
match compile_polydat_with(source, tier) {
Ok(k) => out.push((format!("{tier}"), k)),
Err(KernelError::Refused { .. }) => {
eprintln!("{tier} refuses a host node of this shape");
}
Err(e) => panic!("{tier}: {e}"),
}
}
assert!(
out.len() >= 3,
"expected the interpreter and both closure modes at least, got {}",
out.len()
);
out
}
#[test]
fn a_host_node_agrees_on_every_engine() {
set("agree.a", 21.0);
set("agree.b", 42.0);
let mut ks = kernels("agree");
let want = read(ks[0].1.as_mut(), 1);
assert_eq!(
want,
vec![
polydat::ast::Value::F64(21.0),
polydat::ast::Value::F64(42.0)
],
"the interpreter itself is wrong; the rest of this test means nothing"
);
for (name, k) in ks.iter_mut() {
assert_eq!(read(k.as_mut(), 1), want, "{name}");
}
}
#[test]
fn a_host_node_stays_live_on_every_engine() {
set("live.a", 1.0);
set("live.b", 2.0);
let mut ks = kernels("live");
let first: Vec<_> = ks
.iter_mut()
.map(|(n, k)| (n.clone(), read(k.as_mut(), 1)))
.collect();
set("live.a", 7.0);
set("live.b", 9.0);
let second: Vec<_> = ks
.iter_mut()
.map(|(n, k)| (n.clone(), read(k.as_mut(), 2)))
.collect();
let before = &first[0].1;
let after = &second[0].1;
assert_ne!(
before, after,
"the interpreter did not see the change either; the test proves nothing"
);
for (name, v) in &first {
assert_eq!(v, before, "{name} disagreed before the change");
}
for (name, v) in &second {
assert_eq!(
v, after,
"{name} did not see the change — the step was folded or cached"
);
}
}
#[test]
fn read_granularity_is_the_engines_step() {
for (name, k) in kernels("midcycle").iter_mut() {
set("midcycle.a", 3.0);
set("midcycle.b", 3.0);
k.set_inputs(&[1]);
let a = k.pull("a");
set("midcycle.b", 9.0);
let b = k.pull("b");
assert_eq!(a, polydat::ast::Value::F64(3.0), "{name}: first read");
assert_eq!(
b,
polydat::ast::Value::F64(9.0),
"{name}: a second volatile read within one write is its own \
step's, read when its own output was pulled"
);
k.set_inputs(&[2]);
assert_eq!(
k.pull("b"),
polydat::ast::Value::F64(9.0),
"{name}: no engine may carry a volatile value across a write"
);
}
}
#[test]
fn connected_volatile_reads_are_one_unit_on_native_code() {
let source = "a := host_reading(\"joined.a\")\n\
b := host_reading(\"joined.b\") + a\n";
for (name, k) in kernels_of(source).iter_mut() {
set("joined.a", 3.0);
set("joined.b", 3.0);
k.set_inputs(&[1]);
let a = k.pull("a");
set("joined.b", 9.0);
let b = k.pull("b");
assert_eq!(a, polydat::ast::Value::F64(3.0), "{name}: first read");
let fused = name.starts_with("native") || name.starts_with("pure native");
let expected = if fused {
polydat::ast::Value::F64(6.0)
} else {
polydat::ast::Value::F64(12.0)
};
assert_eq!(
b, expected,
"{name}: connected volatile reads follow the engine's unit"
);
k.set_inputs(&[2]);
assert_eq!(
k.pull("b"),
polydat::ast::Value::F64(12.0),
"{name}: no engine may carry a volatile value across a write"
);
}
}