use std::collections::HashMap;
use std::sync::Arc;
use super::engines::{EngineCore, PolydatState, ProvScanState};
use super::{InputDef, WireSource};
use crate::ast::{PolydatNode, PortType, Value};
use crate::dsl::ast::{PolydatFile, Statement};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum EvalLifecycle {
CompileConst,
ScopeInit,
Dynamic,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ProvMask {
words: Vec<u64>,
}
impl ProvMask {
pub fn empty() -> Self {
Self { words: Vec::new() }
}
pub fn all_below(n: usize) -> Self {
let mut m = Self::empty();
for i in 0..n {
m.set(i);
}
m
}
pub fn clear(&mut self) {
self.words.fill(0);
}
pub fn set(&mut self, idx: usize) -> bool {
let word = idx / 64;
if word >= self.words.len() {
self.words.resize(word + 1, 0);
}
let bit = 1u64 << (idx % 64);
let newly = self.words[word] & bit == 0;
self.words[word] |= bit;
newly
}
pub fn contains(&self, idx: usize) -> bool {
self.words
.get(idx / 64)
.is_some_and(|w| w & (1u64 << (idx % 64)) != 0)
}
pub fn union_with(&mut self, other: &Self) -> bool {
if other.words.len() > self.words.len() {
self.words.resize(other.words.len(), 0);
}
let mut changed = false;
for (dst, src) in self.words.iter_mut().zip(other.words.iter()) {
let merged = *dst | *src;
changed |= merged != *dst;
*dst = merged;
}
changed
}
pub fn intersects(&self, other: &Self) -> bool {
self.words
.iter()
.zip(other.words.iter())
.any(|(a, b)| a & b != 0)
}
pub fn is_zero(&self) -> bool {
self.words.iter().all(|w| *w == 0)
}
pub fn iter_ones(&self) -> impl Iterator<Item = usize> + '_ {
self.words.iter().enumerate().flat_map(|(wi, w)| {
(0..64).filter_map(move |b| (w & (1u64 << b) != 0).then_some(wi * 64 + b))
})
}
}
pub(crate) struct NodeInventory {
pub input_provenance: Vec<ProvMask>,
pub nondet_nodes: Vec<usize>,
pub side_channel_nodes: Vec<bool>,
}
pub(crate) struct LifecycleClasses {
pub lifecycle: Vec<EvalLifecycle>,
pub nondeterministic: Vec<bool>,
}
#[derive(Debug, Default)]
pub struct CompileLedger {
programs: std::sync::atomic::AtomicU64,
cone_fallbacks: std::sync::Mutex<Vec<ConeFallback>>,
unresolved_names: std::sync::Mutex<Vec<UnresolvedNameWarning>>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UnresolvedNameWarning {
pub context: String,
pub statement: String,
pub line: usize,
pub col: usize,
pub reads: Vec<crate::iteration::comprehension::NameRead>,
}
impl std::fmt::Display for UnresolvedNameWarning {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"`{}` at line {}, col {}: {}",
self.statement,
self.line,
self.col,
crate::iteration::comprehension::ValidationWarning::UnresolvedNames {
reads: self.reads.clone()
}
)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ConeFallbackKind {
Codegen,
InputBound,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ConeFallback {
pub context: String,
pub members: Vec<String>,
pub outputs: Vec<String>,
pub boundary_inputs: usize,
pub kind: ConeFallbackKind,
pub reason: String,
}
impl CompileLedger {
pub fn new() -> Arc<Self> {
Arc::new(Self::default())
}
pub fn programs(&self) -> u64 {
self.programs.load(std::sync::atomic::Ordering::Relaxed)
}
pub(crate) fn record(&self) {
self.programs
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
pub fn cone_fallbacks(&self) -> Vec<ConeFallback> {
self.cone_fallbacks
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
#[cfg(feature = "jit")]
pub(crate) fn record_cone_fallback(&self, fallback: ConeFallback) {
self.cone_fallbacks
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(fallback);
}
pub fn unresolved_names(&self) -> Vec<UnresolvedNameWarning> {
self.unresolved_names
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
pub(crate) fn record_unresolved_names(&self, warning: UnresolvedNameWarning) {
let mut recorded = self
.unresolved_names
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if !recorded.contains(&warning) {
recorded.push(warning);
}
}
}
pub fn program_count(program: &PolydatProgram) -> usize {
1 + program
.traversals()
.iter()
.map(|t| program_count(&t.program))
.sum::<usize>()
}
pub(crate) fn dataset_sources_of(
nodes: &[Box<dyn PolydatNode>],
wiring: &[Vec<WireSource>],
input_defs: &[InputDef],
start: usize,
) -> DatasetSources {
fn constant(
i: usize,
nodes: &[Box<dyn PolydatNode>],
wiring: &[Vec<WireSource>],
memo: &mut [Option<Option<Vec<Value>>>],
) -> Option<Vec<Value>> {
if let Some(known) = &memo[i] {
return known.clone();
}
let node = &nodes[i];
let outputs = (|| {
if !matches!(node.purity(), crate::ast::Purity::Pure) {
return None;
}
let mut inputs = Vec::with_capacity(wiring[i].len());
for source in &wiring[i] {
match source {
WireSource::NodeOutput(j, port) => {
inputs.push(constant(*j, nodes, wiring, memo)?.get(*port)?.clone());
}
WireSource::Input(_) => return None,
}
}
let mut outputs = vec![Value::None; node.meta().outs.len()];
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
node.eval(&inputs, &mut outputs);
}))
.ok()?;
Some(outputs)
})();
memo[i] = Some(outputs.clone());
outputs
}
let is_dataset_port = |typ: PortType| matches!(typ, PortType::Forms | PortType::Fragment);
let mut sources = DatasetSources::default();
let mut memo: Vec<Option<Option<Vec<Value>>>> = vec![None; nodes.len()];
let mut seen_nodes = vec![false; nodes.len()];
let mut seen_inputs = vec![false; input_defs.len()];
let mut pending = vec![start];
while let Some(i) = pending.pop() {
if std::mem::replace(&mut seen_nodes[i], true) {
continue;
}
let node = &nodes[i];
if node
.meta()
.outs
.iter()
.any(|port| port.typ == PortType::Forms)
{
let forms: Vec<_> = constant(i, nodes, wiring, &mut memo)
.into_iter()
.flatten()
.filter_map(|value| match value {
Value::Dataset(forms) => Some(forms),
_ => None,
})
.collect();
if forms.is_empty() {
sources.computed.push(node.meta().name.clone());
} else {
for value in forms {
if !sources.constants.contains(&value) {
sources.constants.push(value);
}
}
continue;
}
}
for source in &wiring[i] {
match source {
WireSource::NodeOutput(j, _) => pending.push(*j),
WireSource::Input(j) => {
if !std::mem::replace(&mut seen_inputs[*j], true)
&& is_dataset_port(input_defs[*j].port_type)
{
sources.inputs.push(input_defs[*j].name.clone());
}
}
}
}
}
sources.inputs.sort();
sources.computed.sort();
sources
}
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct DatasetSources {
pub constants: Vec<crate::dataset_value::DatasetValue>,
pub inputs: Vec<String>,
pub computed: Vec<String>,
}
pub struct PolydatProgram {
pub(crate) nodes: Vec<Box<dyn PolydatNode>>,
pub(crate) wiring: Vec<Vec<WireSource>>,
input_defs: Vec<InputDef>,
source: Arc<String>,
context: Arc<String>,
coord_count: usize,
pub(crate) output_map: HashMap<String, (usize, usize)>,
output_list: Vec<(String, usize, usize)>,
pub(crate) input_provenance: Vec<ProvMask>,
input_dependents: Vec<Vec<usize>>,
nondet_nodes: Vec<usize>,
side_channel_nodes: Vec<bool>,
output_modifiers: HashMap<String, crate::dsl::ast::BindingModifier>,
inherited_outputs: std::collections::HashSet<String>,
cursor_schemas: Vec<crate::iteration::source::SourceSchema>,
const_inits: Vec<crate::kernel::ConstInit>,
cone_mode: crate::compile::cone::JitMode,
traversals: Vec<crate::dsl::traversal::Traversal>,
producers: Vec<crate::dsl::traversal::Producer>,
pub(crate) const_outputs: std::collections::HashSet<String>,
pub(crate) write_throughs: Vec<crate::kernel::KernelWriteThrough>,
pub(crate) ast: Option<Arc<PolydatFile>>,
ledger: Arc<CompileLedger>,
resources: crate::resource::ResourceScope,
graph_identity: Option<[u8; 32]>,
}
unsafe impl Send for PolydatProgram {}
unsafe impl Sync for PolydatProgram {}
impl std::fmt::Debug for PolydatProgram {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PolydatProgram")
.field("nodes", &self.nodes.len())
.field("inputs", &self.input_names())
.field("coord_count", &self.coord_count)
.finish()
}
}
impl PolydatProgram {
#[allow(clippy::too_many_arguments)]
pub(crate) fn with_inputs(
nodes: Vec<Box<dyn PolydatNode>>,
wiring: Vec<Vec<WireSource>>,
input_defs: Vec<InputDef>,
coord_count: usize,
output_map: HashMap<String, (usize, usize)>,
output_order: Vec<String>,
source: &str,
context: &str,
ledger: Arc<CompileLedger>,
) -> Self {
ledger.record();
let inventory = Self::compute_node_inventory(&nodes, &wiring);
let input_dependents =
Self::compute_dependents(&inventory.input_provenance, input_defs.len());
let output_list = Self::build_output_list(&output_order, &output_map);
Self {
nodes,
wiring,
input_defs,
coord_count,
output_map,
output_list,
input_provenance: inventory.input_provenance,
input_dependents,
nondet_nodes: inventory.nondet_nodes,
side_channel_nodes: inventory.side_channel_nodes,
source: Arc::new(source.to_string()),
context: Arc::new(context.to_string()),
output_modifiers: HashMap::new(),
inherited_outputs: std::collections::HashSet::new(),
cursor_schemas: Vec::new(),
const_inits: Vec::new(),
cone_mode: crate::compile::cone::JitMode::Off,
traversals: Vec::new(),
producers: Vec::new(),
const_outputs: std::collections::HashSet::new(),
write_throughs: Vec::new(),
ast: None,
ledger,
resources: crate::resource::ResourceScope::new(),
graph_identity: None,
}
}
pub(crate) fn mark_const_output(&mut self, name: &str) {
self.const_outputs.insert(name.to_string());
}
pub(crate) fn set_write_throughs(
&mut self,
write_throughs: Vec<crate::kernel::KernelWriteThrough>,
) {
self.write_throughs = write_throughs;
}
pub(crate) fn write_throughs(&self) -> &[crate::kernel::KernelWriteThrough] {
&self.write_throughs
}
pub(crate) fn set_ast(&mut self, ast: Arc<PolydatFile>) {
self.ast = Some(ast);
}
pub fn ast(&self) -> Option<&Arc<PolydatFile>> {
self.ast.as_ref()
}
pub fn ledger(&self) -> &Arc<CompileLedger> {
&self.ledger
}
pub fn resources(&self) -> &crate::resource::ResourceScope {
&self.resources
}
pub(crate) fn set_resources(&mut self, resources: crate::resource::ResourceScope) {
self.resources = resources;
}
pub fn binding_ast_for(&self, name: &str) -> Option<&Statement> {
let ast = self.ast.as_ref()?;
ast.statements.iter().find(|stmt| match stmt {
Statement::Binding(b) => b.targets.iter().any(|t| t == name),
_ => false,
})
}
pub fn local_inclusion_chain<'a>(
&'a self,
name: &str,
excluded: &std::collections::HashSet<String>,
) -> Vec<&'a Statement> {
let mut out: Vec<&'a Statement> = Vec::new();
let mut visited: std::collections::HashSet<String> = excluded.clone();
self.collect_chain_into(name, &mut out, &mut visited);
out
}
fn collect_chain_into<'a>(
&'a self,
name: &str,
out: &mut Vec<&'a Statement>,
visited: &mut std::collections::HashSet<String>,
) {
if !visited.insert(name.to_string()) {
return;
}
let modifier = self.output_modifier(name);
if modifier == crate::dsl::ast::BindingModifier::CONST
|| modifier == crate::dsl::ast::BindingModifier::SHARED
{
return;
}
let Some(stmt) = self.binding_ast_for(name) else {
return;
};
let Statement::Binding(binding) = stmt else {
return;
};
for target in &binding.targets {
visited.insert(target.clone());
}
let value = &binding.value;
let mut refs = std::collections::HashSet::new();
crate::dsl::validate::collect_references(value, &mut refs);
let mut refs_sorted: Vec<String> = refs.into_iter().collect();
refs_sorted.sort();
for r in refs_sorted {
self.collect_chain_into(&r, out, visited);
}
out.push(stmt);
}
pub fn input_kind(&self, idx: usize) -> Option<crate::kernel::InputKind> {
self.input_defs.get(idx).map(|d| d.kind)
}
pub fn output_map_lookup(&self, name: &str) -> Option<&(usize, usize)> {
self.output_map.get(name)
}
pub fn output_map_iter(&self) -> impl Iterator<Item = (&String, &(usize, usize))> {
self.output_map.iter()
}
pub(crate) fn set_output_modifier(
&mut self,
name: &str,
modifier: crate::dsl::ast::BindingModifier,
) {
if modifier != crate::dsl::ast::BindingModifier::NONE {
self.output_modifiers.insert(name.to_string(), modifier);
if modifier.is_volatile() {
self.refresh_never_current();
}
}
}
fn refresh_never_current(&mut self) {
let classes = Self::classify_lifecycle(
&self.nodes,
&self.wiring,
&self.input_defs,
&self.output_map,
&self.output_modifiers,
);
let mut marked = vec![false; self.nodes.len()];
for &i in &self.nondet_nodes {
marked[i] = true;
}
for (i, nd) in classes.nondeterministic.iter().enumerate() {
if *nd {
marked[i] = true;
}
}
self.nondet_nodes = marked
.iter()
.enumerate()
.filter_map(|(i, m)| m.then_some(i))
.collect();
}
pub fn output_modifier(&self, name: &str) -> crate::dsl::ast::BindingModifier {
self.output_modifiers
.get(name)
.copied()
.unwrap_or(crate::dsl::ast::BindingModifier::NONE)
}
pub fn shared_outputs(&self) -> Vec<&str> {
self.output_modifiers
.iter()
.filter(|(_, m)| **m == crate::dsl::ast::BindingModifier::SHARED)
.map(|(n, _)| n.as_str())
.collect()
}
pub fn mark_inherited(&mut self, name: &str) {
self.inherited_outputs.insert(name.to_string());
}
pub fn is_inherited(&self, name: &str) -> bool {
self.inherited_outputs.contains(name)
}
pub fn own_output_names(&self) -> Vec<&str> {
self.output_names()
.into_iter()
.filter(|name| !self.inherited_outputs.contains(*name))
.collect()
}
pub fn const_outputs(&self) -> Vec<&str> {
self.output_modifiers
.iter()
.filter(|(_, m)| **m == crate::dsl::ast::BindingModifier::CONST)
.map(|(n, _)| n.as_str())
.collect()
}
pub fn source(&self) -> &str {
&self.source
}
pub fn context(&self) -> &str {
&self.context
}
pub fn cursor_schemas(&self) -> &[crate::iteration::source::SourceSchema] {
&self.cursor_schemas
}
pub(crate) fn set_cursor_schemas(
&mut self,
schemas: Vec<crate::iteration::source::SourceSchema>,
) {
self.cursor_schemas = schemas;
}
pub fn const_inits(&self) -> &[crate::kernel::ConstInit] {
&self.const_inits
}
pub(crate) fn is_fixed_output(&self, name: &str) -> bool {
if self.const_outputs.contains(name) {
return true;
}
self.output_map.get(name).is_some_and(|(node, _)| {
self.wiring[*node].is_empty() && !self.nondet_nodes.contains(node)
})
}
pub(crate) fn set_const_inits(&mut self, inits: Vec<crate::kernel::ConstInit>) {
self.const_inits = inits;
}
pub fn cone_mode(&self) -> crate::compile::cone::JitMode {
self.cone_mode
}
pub(crate) fn set_cone_mode(&mut self, mode: crate::compile::cone::JitMode) {
self.cone_mode = mode;
}
pub fn traversals(&self) -> &[crate::dsl::traversal::Traversal] {
&self.traversals
}
pub fn producers(&self) -> &[crate::dsl::traversal::Producer] {
&self.producers
}
pub(crate) fn set_traversals(
&mut self,
traversals: Vec<crate::dsl::traversal::Traversal>,
producers: Vec<crate::dsl::traversal::Producer>,
) {
self.traversals = traversals;
self.producers = producers;
}
fn build_output_list(
output_order: &[String],
output_map: &HashMap<String, (usize, usize)>,
) -> Vec<(String, usize, usize)> {
let mut list: Vec<(String, usize, usize)> = output_order
.iter()
.filter_map(|name| output_map.get(name).map(|&(ni, pi)| (name.clone(), ni, pi)))
.collect();
let mut tail: Vec<(&String, &(usize, usize))> = output_map
.iter()
.filter(|(name, _)| !output_order.contains(*name))
.collect();
tail.sort_by(|a, b| a.0.cmp(b.0));
for (name, &(ni, pi)) in tail {
list.push((name.clone(), ni, pi));
}
list
}
pub(crate) fn compute_dependents(
provenance: &[ProvMask],
num_inputs: usize,
) -> Vec<Vec<usize>> {
let mut deps = vec![Vec::new(); num_inputs];
for (node_idx, prov) in provenance.iter().enumerate() {
for (input_idx, dep) in deps.iter_mut().enumerate() {
if prov.contains(input_idx) {
dep.push(node_idx);
}
}
}
deps
}
pub(crate) fn compute_provenance(
nodes: &[Box<dyn PolydatNode>],
wiring: &[Vec<WireSource>],
) -> Vec<ProvMask> {
Self::compute_node_inventory(nodes, wiring).input_provenance
}
pub(crate) fn classify_lifecycle(
nodes: &[Box<dyn PolydatNode>],
wiring: &[Vec<WireSource>],
input_defs: &[InputDef],
output_map: &HashMap<String, (usize, usize)>,
output_modifiers: &HashMap<String, crate::dsl::ast::BindingModifier>,
) -> LifecycleClasses {
use crate::kernel::InputKind;
let n = nodes.len();
let mut lifecycle: Vec<EvalLifecycle> = vec![EvalLifecycle::CompileConst; n];
let mut nondeterministic: Vec<bool> = vec![false; n];
for (i, wires) in wiring.iter().enumerate() {
for source in wires {
if let WireSource::Input(idx) = source {
let kind = input_defs
.get(*idx)
.map(|d| d.kind)
.unwrap_or(InputKind::Coordinate);
let lc = match kind {
InputKind::IterationExtern | InputKind::Const => EvalLifecycle::ScopeInit,
InputKind::Coordinate | InputKind::ExternalWrite => EvalLifecycle::Dynamic,
};
if lc > lifecycle[i] {
lifecycle[i] = lc;
}
}
}
let declared = matches!(
nodes[i].purity(),
crate::ast::Purity::Nondeterministic { .. }
);
let modifier = output_modifiers.iter().any(|(name, m)| {
m.is_volatile()
&& output_map
.get(name)
.map(|(ni, _)| *ni == i)
.unwrap_or(false)
});
if declared || modifier {
lifecycle[i] = EvalLifecycle::Dynamic;
nondeterministic[i] = true;
}
}
let mut changed = true;
while changed {
changed = false;
for i in 0..n {
for source in &wiring[i] {
if let WireSource::NodeOutput(upstream, _) = source {
if lifecycle[*upstream] > lifecycle[i] {
lifecycle[i] = lifecycle[*upstream];
changed = true;
}
if nondeterministic[*upstream] && !nondeterministic[i] {
nondeterministic[i] = true;
changed = true;
}
}
}
}
}
LifecycleClasses {
lifecycle,
nondeterministic,
}
}
pub(crate) fn compute_node_inventory(
nodes: &[Box<dyn PolydatNode>],
wiring: &[Vec<WireSource>],
) -> NodeInventory {
let n = nodes.len();
let mut prov: Vec<ProvMask> = (0..n).map(|_| ProvMask::empty()).collect();
let mut nondet: Vec<bool> = (0..n)
.map(|i| {
let nullary = wiring[i].is_empty() && nodes[i].meta().ins.is_empty();
let declared = matches!(
nodes[i].purity(),
crate::ast::Purity::Nondeterministic { .. }
);
nullary || declared
})
.collect();
let mut side: Vec<bool> = (0..n)
.map(|i| matches!(nodes[i].purity(), crate::ast::Purity::SideChannel { .. }))
.collect();
let mut changed = true;
while changed {
changed = false;
for i in 0..n {
for source in &wiring[i] {
match source {
WireSource::Input(idx) => {
changed |= prov[i].set(*idx);
}
WireSource::NodeOutput(up, _) => {
let up = *up;
if up == i {
continue; }
let (a, b) = if up < i {
let (l, r) = prov.split_at_mut(i);
(&l[up], &mut r[0])
} else {
let (l, r) = prov.split_at_mut(up);
(&r[0], &mut l[i])
};
changed |= b.union_with(a);
if nondet[up] && !nondet[i] {
nondet[i] = true;
changed = true;
}
if side[up] && !side[i] {
side[i] = true;
changed = true;
}
}
}
}
}
}
NodeInventory {
input_provenance: prov,
nondet_nodes: (0..n).filter(|&i| nondet[i]).collect(),
side_channel_nodes: side,
}
}
fn node_scratch(&self) -> Vec<Vec<crate::ast::ScratchBuf>> {
self.nodes
.iter()
.map(|n| {
n.scratch_layout()
.into_iter()
.map(crate::ast::ScratchBuf::new)
.collect()
})
.collect()
}
fn build_engine_core(&self) -> EngineCore {
let buffers: Vec<Vec<Value>> = self
.nodes
.iter()
.map(|n| vec![Value::None; n.meta().outs.len()])
.collect();
let node_count = self.nodes.len();
let inputs: Vec<Value> = self.input_defs.iter().map(|d| d.default.clone()).collect();
let input_defaults = inputs.clone();
let max_inputs = self.wiring.iter().map(|w| w.len()).max().unwrap_or(0);
let input_count = inputs.len();
EngineCore {
buffers,
node_clean: vec![false; node_count],
inputs,
input_defaults,
shared_cells: vec![None; input_count],
output_cells: Vec::new(),
broadcasting: std::sync::atomic::AtomicBool::new(false),
input_scratch: vec![Value::None; max_inputs],
node_scratch: self.node_scratch(),
scope_intent_words: Vec::new(),
next_cell_bit: 0,
last_seen: std::collections::HashMap::new(),
cell_cones: Vec::new(),
}
}
pub fn create_state(&self) -> PolydatState {
let buffers: Vec<Vec<Value>> = self
.nodes
.iter()
.map(|n| vec![Value::None; n.meta().outs.len()])
.collect();
let node_count = self.nodes.len();
let inputs: Vec<Value> = self.input_defs.iter().map(|d| d.default.clone()).collect();
let input_defaults = inputs.clone();
let max_inputs = self.wiring.iter().map(|w| w.len()).max().unwrap_or(0);
let nondeterministic_nodes: Vec<usize> = self.nondet_nodes.clone();
let input_count = inputs.len();
let core = EngineCore {
buffers,
node_clean: vec![false; node_count],
inputs,
input_defaults,
shared_cells: vec![None; input_count],
output_cells: Vec::new(),
broadcasting: std::sync::atomic::AtomicBool::new(false),
input_scratch: vec![Value::None; max_inputs],
node_scratch: self.node_scratch(),
scope_intent_words: Vec::new(),
next_cell_bit: 0,
last_seen: std::collections::HashMap::new(),
cell_cones: Vec::new(),
};
PolydatState::from_parts(core, self.input_dependents.clone(), nondeterministic_nodes)
}
pub fn create_provscan_state(&self) -> ProvScanState {
let core = self.build_engine_core();
let nondeterministic_nodes: Vec<usize> = self.nondet_nodes.clone();
ProvScanState::from_parts(core, self.input_provenance.clone(), nondeterministic_nodes)
}
pub fn input_names(&self) -> Vec<String> {
self.input_defs.iter().map(|d| d.name.clone()).collect()
}
pub fn coord_count(&self) -> usize {
self.coord_count
}
pub fn find_input(&self, name: &str) -> Option<usize> {
self.input_defs.iter().position(|d| d.name == name)
}
pub fn input_port_type(&self, name: &str) -> Option<crate::ast::PortType> {
self.input_defs
.iter()
.find(|d| d.name == name)
.map(|d| d.converts_to.unwrap_or(d.port_type))
}
pub fn input_type_origin(&self, name: &str) -> Option<crate::kernel::TypeOrigin> {
self.input_defs
.iter()
.find(|d| d.name == name)
.map(|d| d.type_origin)
}
pub fn input_port_type_by_idx(&self, idx: usize) -> Option<crate::ast::PortType> {
self.input_defs.get(idx).map(|d| d.port_type)
}
pub fn input_default_by_idx(&self, idx: usize) -> Option<&Value> {
self.input_defs.get(idx).map(|d| &d.default)
}
pub fn input_name_by_idx(&self, idx: usize) -> Option<&str> {
self.input_defs.get(idx).map(|d| d.name.as_str())
}
pub fn output_count(&self) -> usize {
self.output_list.len()
}
pub fn output_name(&self, idx: usize) -> &str {
&self.output_list[idx].0
}
pub fn output_names(&self) -> Vec<&str> {
self.output_list
.iter()
.map(|(n, _, _)| n.as_str())
.collect()
}
pub fn resolve_output(&self, name: &str) -> Option<(usize, usize)> {
if let Some(found) = self.output_map.get(name).copied() {
return Some(found);
}
if name.contains('.') {
return self.output_map.get(&name.replace('.', "__")).copied();
}
None
}
pub fn dataset_sources(&self, name: &str) -> Option<DatasetSources> {
let (start, _) = self.resolve_output(name)?;
Some(dataset_sources_of(
&self.nodes,
&self.wiring,
&self.input_defs,
start,
))
}
pub fn resolve_output_by_index(&self, idx: usize) -> (usize, usize) {
let (_, ni, pi) = &self.output_list[idx];
(*ni, *pi)
}
pub fn outputs_with_side_effects(&self) -> Vec<String> {
self.output_list
.iter()
.filter(|(_, node_idx, _)| self.cone_has_side_channel(*node_idx))
.map(|(name, _, _)| name.clone())
.collect()
}
fn cone_has_side_channel(&self, start: usize) -> bool {
self.side_channel_nodes.get(start).copied().unwrap_or(false)
}
pub(crate) fn output_list(&self) -> &[(String, usize, usize)] {
&self.output_list
}
pub fn output_index(&self, name: &str) -> Option<usize> {
self.output_list.iter().position(|(n, _, _)| n == name)
}
pub fn output_port_type(&self, name: &str) -> Option<crate::ast::PortType> {
let (node_idx, port_idx) = self.resolve_output(name)?;
let meta = self.node_meta(node_idx);
meta.outs.get(port_idx).map(|out| out.typ)
}
pub fn input_provenance_for(&self, node_idx: usize) -> Option<&ProvMask> {
self.input_provenance.get(node_idx)
}
pub fn is_equivalent_to(&self, other: &PolydatProgram) -> bool {
self.canonical_hash() == other.canonical_hash()
}
pub fn is_subset_of(&self, parent: &PolydatProgram) -> bool {
if self.is_equivalent_to(parent) {
return true;
}
let inputs: std::collections::HashSet<&str> =
self.input_defs.iter().map(|d| d.name.as_str()).collect();
if self
.output_list
.iter()
.any(|(name, _, _)| !inputs.contains(name.as_str()))
{
return false;
}
let parent_inputs: std::collections::HashSet<&str> =
parent.input_defs.iter().map(|d| d.name.as_str()).collect();
for d in &self.input_defs {
if !parent_inputs.contains(d.name.as_str()) {
return false;
}
}
true
}
pub fn instance_hash(&self, ancestors: &[&PolydatProgram]) -> [u8; 32] {
let chain: Vec<[u8; 32]> = ancestors.iter().map(|a| a.canonical_hash()).collect();
instance_hash_of(self.canonical_hash(), &chain)
}
pub fn extern_closure(&self, outputs: &[&str]) -> Vec<String> {
let mut mask = ProvMask::empty();
for (name, ni, _) in &self.output_list {
if outputs.contains(&name.as_str())
&& let Some(prov) = self.input_provenance.get(*ni)
{
mask.union_with(prov);
}
}
let names: std::collections::BTreeSet<String> = mask
.iter_ones()
.filter_map(|idx| self.input_defs.get(idx))
.filter(|def| def.kind != super::InputKind::Coordinate)
.map(|def| def.name.clone())
.collect();
names.into_iter().collect()
}
pub fn owned_extern_closure(&self) -> Vec<String> {
let owned: Vec<&str> = self
.output_names()
.into_iter()
.filter(|n| !self.is_inherited(n))
.collect();
self.extern_closure(&owned)
}
pub fn resolve_externs_through(
seed: impl IntoIterator<Item = String>,
ancestors: &[&PolydatProgram],
) -> Vec<String> {
let mut unresolved: std::collections::BTreeSet<String> = seed.into_iter().collect();
for prog in ancestors {
if unresolved.is_empty() {
break;
}
let outputs: std::collections::BTreeSet<&str> =
prog.output_names().into_iter().collect();
let produced: Vec<String> = unresolved
.iter()
.filter(|n| outputs.contains(n.as_str()))
.cloned()
.collect();
if produced.is_empty() {
continue;
}
let produced_refs: Vec<&str> = produced.iter().map(String::as_str).collect();
let closure = prog.extern_closure(&produced_refs);
for name in &produced {
unresolved.remove(name);
}
unresolved.extend(closure);
}
unresolved.into_iter().collect()
}
pub fn canonical_hash(&self) -> [u8; 32] {
let graph = self
.graph_identity
.unwrap_or_else(|| self.identity_graph().digest());
program_identity(
graph,
self.inherited_outputs.iter(),
&self.cursor_schemas,
&self.traversals,
)
}
fn identity_graph(&self) -> IdentityGraph<'_> {
IdentityGraph {
nodes: &self.nodes,
wiring: &self.wiring,
input_defs: &self.input_defs,
outputs: self
.output_list
.iter()
.map(|(n, ni, pi)| (n.as_str(), *ni, *pi))
.collect(),
output_modifiers: &self.output_modifiers,
const_outputs: &self.const_outputs,
}
}
pub(crate) fn set_graph_identity(&mut self, digest: [u8; 32]) {
self.graph_identity = Some(digest);
}
}
pub(crate) struct IdentityGraph<'a> {
pub(crate) nodes: &'a [Box<dyn PolydatNode>],
pub(crate) wiring: &'a [Vec<WireSource>],
pub(crate) input_defs: &'a [InputDef],
pub(crate) outputs: Vec<(&'a str, usize, usize)>,
pub(crate) output_modifiers: &'a HashMap<String, crate::dsl::ast::BindingModifier>,
pub(crate) const_outputs: &'a std::collections::HashSet<String>,
}
pub fn instance_hash_of(own: [u8; 32], ancestors: &[[u8; 32]]) -> [u8; 32] {
use sha2::{Digest, Sha256};
let mut h = Sha256::new();
h.update(b"PolydatProgram-instance-v1\n");
h.update(own);
for a in ancestors {
h.update(a);
}
h.finalize().into()
}
pub(crate) fn program_identity<'a>(
graph: [u8; 32],
inherited: impl Iterator<Item = &'a String>,
cursors: &[crate::iteration::source::SourceSchema],
traversals: &[crate::dsl::traversal::Traversal],
) -> [u8; 32] {
use sha2::{Digest, Sha256};
let mut h = Sha256::new();
h.update(b"PolydatProgram-v2\n");
h.update(graph);
let mut inherited: Vec<&String> = inherited.collect();
inherited.sort();
for name in inherited {
h.update(b"inh:");
h.update(name.as_bytes());
h.update(b"\n");
}
for schema in cursors {
h.update(b"cursor:");
h.update(schema.name.as_bytes());
h.update(b":");
h.update(format!("{:?}", schema.extent).as_bytes());
h.update(b"\n");
}
for t in traversals {
h.update(b"for:");
h.update((t.source_text.len() as u64).to_le_bytes().as_ref());
h.update(t.source_text.as_bytes());
h.update(b":");
h.update(t.program.canonical_hash());
h.update(b"\n");
}
h.finalize().into()
}
impl IdentityGraph<'_> {
pub(crate) fn digest(&self) -> [u8; 32] {
use sha2::{Digest, Sha256};
let mut h = Sha256::new();
h.update(b"PolydatGraph-v2\n");
let mut inputs: Vec<&InputDef> = self.input_defs.iter().collect();
inputs.sort_by(|a, b| a.name.cmp(&b.name));
for def in &inputs {
h.update(b"in:");
h.update(def.name.as_bytes());
h.update(b":");
h.update(format!("{:?}", def.port_type).as_bytes());
h.update(b":");
h.update(format!("{:?}", def.kind).as_bytes());
h.update(b":");
h.update(format!("{:?}", def.default).as_bytes());
h.update(b"\n");
}
let mut outputs = self.outputs.clone();
outputs.sort_by(|a, b| a.0.cmp(b.0));
let mut node_hashes: HashMap<usize, [u8; 32]> = HashMap::new();
for (name, ni, pi) in &outputs {
let (nh, pi_eff) = self.port_identity(*ni, *pi, &mut node_hashes);
h.update(b"out:");
h.update(name.as_bytes());
h.update(b":port:");
h.update(pi_eff.to_le_bytes().as_ref());
h.update(b":");
h.update(nh);
h.update(b"\n");
if let Some(m) = self.output_modifiers.get(*name) {
h.update(b" mod:");
h.update(if m.is_const() { b"F" } else { b"-" });
h.update(if m.is_shared() { b"S" } else { b"-" });
h.update(if m.is_volatile() { b"V" } else { b"-" });
h.update(b"\n");
}
}
let mut init_outs: Vec<&String> = self.const_outputs.iter().collect();
init_outs.sort();
for name in init_outs {
h.update(b"init:");
h.update(name.as_bytes());
h.update(b"\n");
}
h.finalize().into()
}
fn node_canonical_hash(&self, ni: usize, memo: &mut HashMap<usize, [u8; 32]>) -> [u8; 32] {
if let Some(h) = memo.get(&ni) {
return *h;
}
memo.insert(ni, [0u8; 32]);
use sha2::{Digest, Sha256};
let mut h = Sha256::new();
let meta = self.nodes[ni].meta();
h.update(b"node:");
h.update(meta.name.as_bytes());
h.update(b"\n");
for port in &meta.outs {
h.update(b" outp:");
h.update(port.name.as_bytes());
h.update(b":");
h.update(format!("{:?}", port.typ).as_bytes());
h.update(b"\n");
}
let wires = &self.wiring[ni];
let mut wire_idx = 0;
for slot in &meta.ins {
match slot {
crate::ast::Slot::Wire(port) => {
h.update(b" wirep:");
h.update(port.name.as_bytes());
h.update(b":");
h.update(format!("{:?}", port.typ).as_bytes());
h.update(b":");
if let Some(src) = wires.get(wire_idx) {
canonical_wire_source(src, self, memo, &mut h);
} else {
h.update(b"unwired");
}
h.update(b"\n");
wire_idx += 1;
}
crate::ast::Slot::Const { name, value } => {
h.update(b" const:");
h.update(name.as_bytes());
h.update(b":");
canonical_const_value(value, &mut h);
h.update(b"\n");
}
}
}
let result: [u8; 32] = h.finalize().into();
memo.insert(ni, result);
result
}
fn port_identity(
&self,
ni: usize,
pi: usize,
memo: &mut HashMap<usize, [u8; 32]>,
) -> ([u8; 32], usize) {
if let Some(sub) = self.nodes[ni].fusion_subgraph() {
let (m, p) = sub.out_ports[pi];
(self.fusion_member_hash(ni, &sub, m, memo), p)
} else {
(self.node_canonical_hash(ni, memo), pi)
}
}
fn fusion_member_hash(
&self,
fusion_ni: usize,
sub: &crate::ast::FusionSubgraph<'_>,
m: usize,
memo: &mut HashMap<usize, [u8; 32]>,
) -> [u8; 32] {
use sha2::{Digest, Sha256};
let mut h = Sha256::new();
let meta = sub.members[m].meta();
h.update(b"node:");
h.update(meta.name.as_bytes());
h.update(b"\n");
for port in &meta.outs {
h.update(b" outp:");
h.update(port.name.as_bytes());
h.update(b":");
h.update(format!("{:?}", port.typ).as_bytes());
h.update(b"\n");
}
let wires = &sub.wiring[m];
let mut wire_idx = 0;
for slot in &meta.ins {
match slot {
crate::ast::Slot::Wire(port) => {
h.update(b" wirep:");
h.update(port.name.as_bytes());
h.update(b":");
h.update(format!("{:?}", port.typ).as_bytes());
h.update(b":");
match wires.get(wire_idx) {
Some(super::WireSource::NodeOutput(j, p)) => {
h.update(b"node:");
let nh = self.fusion_member_hash(fusion_ni, sub, *j, memo);
h.update(nh);
h.update(b":port:");
h.update(p.to_le_bytes().as_ref());
}
Some(super::WireSource::Input(i)) => match self.wiring[fusion_ni].get(*i) {
Some(super::WireSource::NodeOutput(oj, op)) => {
h.update(b"node:");
let (nh, p_eff) = self.port_identity(*oj, *op, memo);
h.update(nh);
h.update(b":port:");
h.update(p_eff.to_le_bytes().as_ref());
}
Some(outer_input @ super::WireSource::Input(_)) => {
canonical_wire_source(outer_input, self, memo, &mut h);
}
None => h.update(b"unwired"),
},
None => h.update(b"unwired"),
}
h.update(b"\n");
wire_idx += 1;
}
crate::ast::Slot::Const { name, value } => {
h.update(b" const:");
h.update(name.as_bytes());
h.update(b":");
canonical_const_value(value, &mut h);
h.update(b"\n");
}
}
}
h.finalize().into()
}
}
impl PolydatProgram {
pub fn node_count(&self) -> usize {
self.nodes.len()
}
pub fn wire_count(&self) -> usize {
self.wiring.iter().map(|w| w.len()).sum()
}
pub fn avg_degree(&self) -> f64 {
let n = self.nodes.len();
if n == 0 {
return 0.0;
}
self.wire_count() as f64 / n as f64
}
pub fn node_ref(&self, idx: usize) -> &dyn crate::ast::PolydatNode {
self.nodes[idx].as_ref()
}
pub fn node_meta(&self, idx: usize) -> &crate::ast::NodeMeta {
self.nodes[idx].meta()
}
pub fn node_wiring(&self, idx: usize) -> &[super::WireSource] {
&self.wiring[idx]
}
pub fn node_wire_types(&self, idx: usize) -> Vec<crate::ast::PortType> {
self.wiring[idx]
.iter()
.map(|src| match src {
super::WireSource::Input(i) => self
.input_port_type_by_idx(*i)
.unwrap_or(crate::ast::PortType::U64),
super::WireSource::NodeOutput(j, p) => self.nodes[*j].meta().outs[*p].typ,
})
.collect()
}
pub fn node_compile_level(&self, idx: usize) -> crate::ast::CompileLevel {
crate::ast::compile_level_of(self.nodes[idx].as_ref(), &self.node_wire_types(idx))
}
pub fn engine_plan(&self) -> crate::EnginePlan {
let mut plan = crate::EnginePlan::default();
for i in 0..self.node_count() {
if self.node_ref(i).fusion_subgraph().is_some() {
plan.native_segments += 1;
} else {
plan.interpreted_nodes += 1;
}
}
plan
}
pub fn last_node_compile_level(&self) -> crate::ast::CompileLevel {
if self.nodes.is_empty() {
return crate::ast::CompileLevel::Phase1;
}
self.node_compile_level(self.nodes.len() - 1)
}
pub fn is_deterministic(&self) -> bool {
!self
.nodes
.iter()
.any(|n| matches!(n.purity(), crate::ast::Purity::Nondeterministic { .. }))
}
pub fn fold_init_constants(
&mut self,
) -> Result<usize, crate::compile::assembly::AssemblyError> {
self.fold_init_constants_impl(None, false)
}
pub fn fold_init_constants_with_log(
&mut self,
log: Option<&mut crate::dsl::events::CompileEventLog>,
) -> Result<usize, crate::compile::assembly::AssemblyError> {
self.fold_init_constants_impl(log, false)
}
pub(crate) fn config_wires_fed_by_cycle(
nodes: &[Box<dyn PolydatNode>],
wiring: &[Vec<WireSource>],
is_init: &[bool],
) -> Vec<(String, String)> {
let outer_is_cycle = |src: &WireSource| match src {
WireSource::Input(_) => true,
WireSource::NodeOutput(src_idx, _) => !is_init[*src_idx],
};
let mut found = Vec::new();
for (node, wires) in nodes.iter().zip(wiring.iter()) {
if let Some(sub) = node.fusion_subgraph() {
for (m, member) in sub.members.iter().enumerate() {
let ports = member.meta().wire_inputs();
for (k, src) in sub.wiring[m].iter().enumerate() {
let Some(port) = ports.get(k) else { break };
if port.wire_cost != crate::ast::WireCost::Config {
continue;
}
let cycle = match src {
WireSource::Input(bi) => wires.get(*bi).is_none_or(outer_is_cycle),
WireSource::NodeOutput(..) => true,
};
if cycle {
found.push((member.meta().name.clone(), port.name.clone()));
}
}
}
continue;
}
let wire_inputs = node.meta().wire_inputs();
for (port_idx, wire_source) in wires.iter().enumerate() {
let Some(port) = wire_inputs.get(port_idx) else {
break;
};
if port.wire_cost != crate::ast::WireCost::Config {
continue;
}
if outer_is_cycle(wire_source) {
found.push((node.meta().name.clone(), port.name.clone()));
}
}
}
found
}
pub(crate) fn strict_violation(
nodes: &[Box<dyn PolydatNode>],
wiring: &[Vec<WireSource>],
is_init: &[bool],
output_map: &HashMap<String, (usize, usize)>,
output_modifiers: &HashMap<String, crate::dsl::ast::BindingModifier>,
) -> Option<String> {
let n = nodes.len();
if let Some((node_name, port_name)) =
Self::config_wires_fed_by_cycle(nodes, wiring, is_init)
.into_iter()
.next()
{
return Some(format!(
"strict mode: config wire '{port_name}' on node '{node_name}' is connected \
to a cycle-time source."
));
}
let mut feeds_volatile = vec![false; n];
for (out_name, (node_idx, _)) in output_map.iter() {
if output_modifiers
.get(out_name)
.map(|m| m.is_volatile() || m.is_const())
.unwrap_or(false)
{
feeds_volatile[*node_idx] = true;
}
}
let mut changed = true;
while changed {
changed = false;
for i in 0..n {
if !feeds_volatile[i] {
continue;
}
for source in &wiring[i] {
if let WireSource::NodeOutput(upstream, _) = source
&& !feeds_volatile[*upstream]
{
feeds_volatile[*upstream] = true;
changed = true;
}
}
}
}
for (i, node) in nodes.iter().enumerate() {
let name = &node.meta().name;
if wiring[i].is_empty() && !is_init[i] && !name.starts_with("__") && !feeds_volatile[i]
{
return Some(format!(
"strict mode: non-deterministic node '{name}' used without explicit \
acknowledgment. Use a deterministic alternative."
));
}
}
let output_nodes: std::collections::HashSet<usize> =
output_map.values().map(|(idx, _)| *idx).collect();
for (i, node) in nodes.iter().enumerate() {
let name = &node.meta().name;
if name.starts_with("__") || output_nodes.contains(&i) {
continue;
}
let consumed = wiring.iter().any(|w| {
w.iter()
.any(|s| matches!(s, WireSource::NodeOutput(src, _) if *src == i))
});
if !consumed {
return Some(format!(
"strict mode: binding '{name}' is never referenced. Remove it or mark as \
output."
));
}
}
None
}
pub fn fold_init_constants_strict(
&mut self,
log: Option<&mut crate::dsl::events::CompileEventLog>,
strict: bool,
) -> Result<usize, crate::compile::assembly::AssemblyError> {
self.fold_init_constants_impl(log, strict)
}
#[allow(clippy::needless_range_loop)]
fn fold_init_constants_impl(
&mut self,
mut log: Option<&mut crate::dsl::events::CompileEventLog>,
strict: bool,
) -> Result<usize, crate::compile::assembly::AssemblyError> {
use crate::ast::Value;
use crate::library::fixed::ConstF64;
use crate::library::identity::{ConstExt, ConstHandle, ConstStr, ConstU64};
let n = self.nodes.len();
if n == 0 {
return Ok(0);
}
let lifecycle = Self::classify_lifecycle(
&self.nodes,
&self.wiring,
&self.input_defs,
&self.output_map,
&self.output_modifiers,
)
.lifecycle;
let mut is_init: Vec<bool> = lifecycle
.iter()
.map(|lc| *lc == EvalLifecycle::CompileConst)
.collect();
if strict
&& let Some(violation) = Self::strict_violation(
&self.nodes,
&self.wiring,
&is_init,
&self.output_map,
&self.output_modifiers,
)
{
return Err(crate::compile::assembly::AssemblyError::Other(violation));
}
for (node_name, port_name) in
Self::config_wires_fed_by_cycle(&self.nodes, &self.wiring, &is_init)
{
crate::library::support::audit::warn(&format!(
"config wire '{port_name}' on node '{node_name}' is connected to a \
cycle-time source."
));
if let Some(ref mut log) = log {
log.push(crate::dsl::events::CompileEvent::ConfigWireCycleWarning {
node: node_name,
port: port_name,
});
}
}
let mut feeds_volatile = vec![false; n];
for (out_name, node_idx, _port) in self.output_list.iter() {
if self
.output_modifiers
.get(out_name)
.map(|m| m.is_volatile() || m.is_const())
.unwrap_or(false)
{
feeds_volatile[*node_idx] = true;
}
}
let mut changed = true;
while changed {
changed = false;
for i in 0..n {
if !feeds_volatile[i] {
continue;
}
for source in &self.wiring[i] {
if let WireSource::NodeOutput(upstream, _) = source
&& !feeds_volatile[*upstream]
{
feeds_volatile[*upstream] = true;
changed = true;
}
}
}
}
for i in 0..n {
let name = &self.nodes[i].meta().name;
let is_nondeterministic =
self.wiring[i].is_empty() && !is_init[i] && !name.starts_with("__");
if !is_nondeterministic {
continue;
}
let consumed_by_volatile = feeds_volatile[i];
if consumed_by_volatile {
continue;
}
let msg =
format!("non-deterministic node '{name}' used without explicit acknowledgment");
crate::library::support::audit::warn(&msg);
if let Some(ref mut log) = log {
log.push(crate::dsl::events::CompileEvent::Warning { message: msg });
}
}
let output_node_indices: std::collections::HashSet<usize> =
self.output_map.values().map(|(idx, _)| *idx).collect();
for i in 0..n {
let name = &self.nodes[i].meta().name;
if name.starts_with("__") {
continue;
}
let is_output = output_node_indices.contains(&i);
let is_consumed = (0..n).any(|j| {
self.wiring[j]
.iter()
.any(|w| matches!(w, WireSource::NodeOutput(src, _) if *src == i))
});
if !is_output && !is_consumed {
let msg = format!("binding '{name}' is never referenced");
if !name.contains("__") {
crate::library::support::audit::warn(&msg);
if let Some(ref mut log) = log {
log.push(crate::dsl::events::CompileEvent::Warning { message: msg });
}
}
}
}
let init_count = is_init.iter().filter(|&&b| b).count();
if init_count == 0 {
return Ok(0);
}
let mut state = self.create_state();
let dummy_inputs = vec![0u64; self.coord_count];
state.seed_inputs(&dummy_inputs);
for i in 0..n {
if is_init[i] {
if self.nodes[i].meta().outs.len() != 1 {
is_init[i] = false;
continue;
}
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
state.eval_node_public(self, i);
}));
if let Err(payload) = result {
return Err(crate::compile::assembly::AssemblyError::ConstantFold(
crate::kernel::engines::without_panic_location(
crate::kernel::engines::panic_payload_text(payload.as_ref()),
),
));
}
}
}
let mut folded = 0;
for i in 0..n {
if !is_init[i] {
continue;
}
let value = state.core.buffers[i][0].clone();
if matches!(value, Value::None) {
continue;
}
let const_node: Box<dyn crate::ast::PolydatNode> = match &value {
Value::U64(v) => Box::new(ConstU64::new(*v)),
Value::F64(v) => Box::new(ConstF64::new(*v)),
Value::Bool(v) => Box::new(crate::library::fixed::ConstBool::new(*v)),
Value::Str(s) => Box::new(ConstStr::new(s.to_string())),
Value::Handle(arc) => {
let original_name = self.nodes[i].meta().name.clone();
crate::library::support::audit::debug(&format!(
"fold: replacing init node '{original_name}' with ConstHandle \
(Arc<dyn Any>) — eval will not re-fire post-fold"
));
Box::new(ConstHandle::new(arc.clone()))
}
Value::Ext(b) => {
let original_name = self.nodes[i].meta().name.clone();
crate::library::support::audit::debug(&format!(
"fold: replacing init node '{original_name}' with ConstExt \
({}) — eval will not re-fire post-fold",
b.type_name(),
));
Box::new(ConstExt::new(b.clone()))
}
#[cfg(feature = "vectordata")]
Value::Dataset(d) => {
Box::new(crate::library::identity::ConstDataset::new(d.clone()))
}
#[cfg(not(feature = "vectordata"))]
Value::Dataset(d) => match *d {},
_ => continue,
};
let node_name = self.nodes[i].meta().name.clone();
if let Some(ref mut log) = log {
log.push(crate::dsl::events::CompileEvent::ConstantFolded {
node: node_name,
value: value.to_display_string(),
});
}
self.nodes[i] = const_node;
self.wiring[i] = Vec::new();
folded += 1;
}
Ok(folded)
}
}
fn canonical_wire_source(
src: &super::WireSource,
program: &IdentityGraph<'_>,
memo: &mut HashMap<usize, [u8; 32]>,
h: &mut sha2::Sha256,
) {
use sha2::Digest;
match src {
super::WireSource::Input(idx) => {
h.update(b"input:");
if let Some(def) = program.input_defs.get(*idx) {
h.update(def.name.as_bytes());
} else {
h.update(b"<oob>");
}
}
super::WireSource::NodeOutput(ni, pi) => {
h.update(b"node:");
let (nh, pi_eff) = program.port_identity(*ni, *pi, memo);
h.update(nh);
h.update(b":port:");
h.update(pi_eff.to_le_bytes().as_ref());
}
}
}
fn canonical_const_value(v: &crate::ast::ConstValue, h: &mut sha2::Sha256) {
use crate::ast::ConstValue;
use sha2::Digest;
match v {
ConstValue::U64(x) => {
h.update(b"u64:");
h.update(x.to_le_bytes().as_ref());
}
ConstValue::F64(x) => {
h.update(b"f64:");
h.update(x.to_bits().to_le_bytes().as_ref());
}
ConstValue::Str(s) => {
h.update(b"str:");
h.update((s.len() as u64).to_le_bytes().as_ref());
h.update(s.as_bytes());
}
ConstValue::VecU64(xs) => {
h.update(b"vu64:");
h.update((xs.len() as u64).to_le_bytes().as_ref());
for x in xs {
h.update(x.to_le_bytes().as_ref());
}
}
ConstValue::VecF64(xs) => {
h.update(b"vf64:");
h.update((xs.len() as u64).to_le_bytes().as_ref());
for x in xs {
h.update(x.to_bits().to_le_bytes().as_ref());
}
}
}
}
#[cfg(test)]
mod canonical_hash_tests {
use crate::dsl::compile_polydat_interpreter;
#[test]
fn identical_source_produces_identical_hash() {
let src = "const dataset := \"sift1m\"\nconst count := 100\n";
let k1 = compile_polydat_interpreter(src).expect("compile1");
let k2 = compile_polydat_interpreter(src).expect("compile2");
assert_eq!(k1.program().canonical_hash(), k2.program().canonical_hash());
}
#[test]
fn different_const_value_changes_hash() {
let a = compile_polydat_interpreter("const x := 100\n").expect("compile a");
let b = compile_polydat_interpreter("const x := 101\n").expect("compile b");
assert_ne!(
a.program().canonical_hash(),
b.program().canonical_hash(),
"differing const value must change canonical hash"
);
}
#[test]
fn different_string_value_changes_hash() {
let a = compile_polydat_interpreter("const s := \"sift1m\"\n").expect("compile a");
let b = compile_polydat_interpreter("const s := \"sift10m\"\n").expect("compile b");
assert_ne!(
a.program().canonical_hash(),
b.program().canonical_hash(),
"differing string value must change canonical hash"
);
}
#[test]
fn renamed_output_changes_hash() {
let a = compile_polydat_interpreter("const foo := 42\n").expect("compile a");
let b = compile_polydat_interpreter("const bar := 42\n").expect("compile b");
assert_ne!(
a.program().canonical_hash(),
b.program().canonical_hash(),
"renamed output must change canonical hash"
);
}
#[test]
fn comment_only_change_does_not_change_hash() {
let a = compile_polydat_interpreter("const x := 42\n").expect("compile a");
let b = compile_polydat_interpreter(
"# explanatory comment\nconst x := 42\n# trailing comment\n",
)
.expect("compile b");
assert_eq!(
a.program().canonical_hash(),
b.program().canonical_hash(),
"comment-only edits should not affect canonical hash — \
the AST is what's hashed, not the source bytes"
);
}
#[test]
fn whitespace_change_does_not_change_hash() {
let a = compile_polydat_interpreter("const x := 42\n").expect("compile a");
let b = compile_polydat_interpreter("const x := 42\n\n\n").expect("compile b");
assert_eq!(
a.program().canonical_hash(),
b.program().canonical_hash(),
"whitespace-only edits should not affect canonical hash"
);
}
#[test]
fn additional_binding_changes_hash() {
let a = compile_polydat_interpreter("const x := 1\n").expect("compile a");
let b = compile_polydat_interpreter("const x := 1\nconst y := 2\n").expect("compile b");
assert_ne!(
a.program().canonical_hash(),
b.program().canonical_hash(),
"added output must change canonical hash"
);
}
#[test]
fn instance_hash_with_no_ancestors_differs_from_canonical_hash() {
let p = compile_polydat_interpreter("const x := 1\n").expect("compile");
let prog = p.program();
assert_ne!(prog.instance_hash(&[]), prog.canonical_hash());
}
#[test]
fn instance_hash_changes_when_an_ancestor_program_changes() {
let parent_a = compile_polydat_interpreter("const ds := \"v1\"\n").expect("a");
let parent_b = compile_polydat_interpreter("const ds := \"v2\"\n").expect("b");
let child = compile_polydat_interpreter("const y := 42\n").expect("child");
let cp = child.program();
let h_a = cp.instance_hash(&[parent_a.program().as_ref()]);
let h_b = cp.instance_hash(&[parent_b.program().as_ref()]);
assert_ne!(
h_a, h_b,
"ancestor const-slot edit must change instance_hash even \
when the child program is byte-identical"
);
}
#[test]
fn instance_hash_is_order_sensitive_in_the_chain() {
let g = compile_polydat_interpreter("const g := 1\n").expect("g");
let p = compile_polydat_interpreter("const p := 2\n").expect("p");
let c = compile_polydat_interpreter("const c := 3\n").expect("c");
let cp = c.program();
let chain1 = cp.instance_hash(&[p.program().as_ref(), g.program().as_ref()]);
let chain2 = cp.instance_hash(&[g.program().as_ref(), p.program().as_ref()]);
assert_ne!(chain1, chain2);
}
#[test]
fn instance_hash_is_deterministic_across_rebuilds() {
let parent_src = "const ds := \"sift1m\"\n";
let p1 = compile_polydat_interpreter(parent_src).expect("p1");
let p2 = compile_polydat_interpreter(parent_src).expect("p2");
let child = compile_polydat_interpreter("const y := 42\n").expect("child");
let cp = child.program();
let h1 = cp.instance_hash(&[p1.program().as_ref()]);
let h2 = cp.instance_hash(&[p2.program().as_ref()]);
assert_eq!(h1, h2);
}
#[test]
fn is_equivalent_to_identical_programs() {
let src = "const x := 100\n";
let a = compile_polydat_interpreter(src).expect("a");
let b = compile_polydat_interpreter(src).expect("b");
assert!(a.program().is_equivalent_to(b.program()));
assert!(b.program().is_equivalent_to(a.program())); }
#[test]
fn is_equivalent_to_differs_when_const_differs() {
let a = compile_polydat_interpreter("const x := 100\n").expect("a");
let b = compile_polydat_interpreter("const x := 101\n").expect("b");
assert!(!a.program().is_equivalent_to(b.program()));
}
#[test]
fn is_subset_of_self_is_true() {
let p = compile_polydat_interpreter("const x := 1\n").expect("p");
assert!(p.program().is_subset_of(p.program()));
}
#[test]
fn is_subset_of_distinct_definitions_is_false() {
let parent = compile_polydat_interpreter("const x := 1\n").expect("parent");
let inner = compile_polydat_interpreter("const y := 2\n").expect("inner");
assert!(!inner.program().is_subset_of(parent.program()));
}
}
#[cfg(test)]
mod ast_metadata_tests {
use crate::dsl::ast::Statement;
use crate::dsl::compile_polydat_interpreter;
#[test]
fn retained_ast_is_present_after_compile() {
let src = "const dataset := \"sift1m\"\ncount := 100\n";
let k = compile_polydat_interpreter(src).expect("compile");
assert!(
k.program().ast().is_some(),
"AST should be retained on program"
);
}
#[test]
fn binding_ast_for_finds_init_binding() {
let src = "const dataset := \"sift1m\"\nratio := 2.5\n";
let k = compile_polydat_interpreter(src).expect("compile");
let stmt = k
.program()
.binding_ast_for("dataset")
.expect("dataset binding should be retrievable");
match stmt {
Statement::Binding(b) => assert_eq!(b.targets[0], "dataset"),
other => panic!("expected InitBinding for 'dataset', got {other:?}"),
}
}
#[test]
fn binding_ast_for_finds_cycle_binding() {
let src = "count := 42\n";
let k = compile_polydat_interpreter(src).expect("compile");
let stmt = k
.program()
.binding_ast_for("count")
.expect("count binding should be retrievable");
match stmt {
Statement::Binding(b) => {
assert!(
b.targets.iter().any(|t| t == "count"),
"CycleBinding targets should include 'count'"
);
}
other => panic!("expected CycleBinding for 'count', got {other:?}"),
}
}
#[test]
fn binding_ast_for_unknown_name_returns_none() {
let k = compile_polydat_interpreter("const x := 1\n").expect("compile");
assert!(k.program().binding_ast_for("does_not_exist").is_none());
}
#[test]
fn local_inclusion_chain_unknown_name_is_empty() {
let k = compile_polydat_interpreter("const x := 1\n").expect("compile");
let chain = k
.program()
.local_inclusion_chain("missing", &std::collections::HashSet::new());
assert!(chain.is_empty());
}
}
#[cfg(test)]
mod r1v_contagion_tests {
use crate::ast::Value;
use crate::dsl::compile_polydat_interpreter;
#[test]
fn every_read_re_evaluates_a_volatile_node() {
let src = "input cycle: u64\n\
c := counter()\n";
let mut k = compile_polydat_interpreter(src).expect("compile");
k.set_inputs(&[0]);
let a = match k.pull_ref("c") {
Value::U64(v) => *v,
_ => panic!(),
};
let b = match k.pull_ref("c") {
Value::U64(v) => *v,
_ => panic!(),
};
let c = match k.pull_ref("c") {
Value::U64(v) => *v,
_ => panic!(),
};
assert_eq!(b, a + 1, "the second read re-evaluated the counter");
assert_eq!(c, b + 1, "the third read re-evaluated the counter");
}
}
#[cfg(test)]
mod provmask_tests {
use super::ProvMask;
#[test]
fn bits_above_63_are_exact() {
let mut a = ProvMask::empty();
assert!(a.set(2));
assert!(a.set(63));
assert!(a.set(64));
assert!(a.set(130));
assert!(!a.set(130), "re-set reports no change");
assert!(a.contains(2) && a.contains(63));
assert!(a.contains(64) && a.contains(130));
assert!(!a.contains(65) && !a.contains(129));
assert_eq!(a.iter_ones().collect::<Vec<_>>(), vec![2, 63, 64, 130]);
}
#[test]
fn union_and_intersect_across_word_boundaries() {
let mut a = ProvMask::empty();
a.set(1);
let mut b = ProvMask::empty();
b.set(100);
assert!(!a.intersects(&b));
assert!(a.union_with(&b), "union reports growth");
assert!(!a.union_with(&b), "idempotent union reports none");
assert!(a.contains(1) && a.contains(100));
assert!(a.intersects(&b));
assert!(ProvMask::empty().is_zero());
assert!(!a.is_zero());
}
}