use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use oxdock_fs::{GuardedPath, MockFs, PathResolver, WorkspaceFs};
use oxdock_parser::{ModuleFuncs, ModuleTable, STD_MODULE_NAME};
use super::args::check_host_return_value;
use super::base_name;
use super::io::ExecIo;
use super::native::{FuncParam, HostModule, HostRegistration, builtin_function_metas};
use super::state::ExecState;
use super::steps::StepCtx;
use super::typing::{TypeTag, Value};
use oxdock_process::{CommandStdin, ProcessManager};
const WATCHDOG_SECS: u64 = 60;
pub fn assert_module_returns_conformance<P: ProcessManager + Clone + Send + 'static>(
module_name: &str,
funcs: &[HostRegistration<P>],
exec_modules: Vec<HostModule<P>>,
process: P,
) {
let mut failures: Vec<String> = Vec::new();
for registration in funcs {
let (base, meta) = match registration {
HostRegistration::Pure { name, meta, .. } => (name.clone(), meta),
HostRegistration::Stateful { name, meta, .. } => (name.clone(), meta),
HostRegistration::Both { name, meta, .. } => (name.clone(), meta),
};
let qualified = format!("{module_name}::{base}");
if meta.returns.is_none() {
continue;
}
let vectors = sample_vectors(meta);
let mut ok = 0;
if meta.examples.is_empty() {
for args in vectors {
match invoke_sample(registration, args, process.clone()) {
SampleOutcome::Ok(value) => {
if let Err(err) = check_host_return_value(
&format!("{qualified} returns"),
&meta.returns,
&value,
) {
failures.push(format!("{qualified}: lying returns: {err:#}"));
} else {
ok += 1;
}
}
SampleOutcome::Err | SampleOutcome::TimedOut => {}
}
}
}
for example in meta.examples {
if !mentions(example.code, &base) {
failures.push(format!(
"{qualified} example '{}' never names `{base}`",
example.name
));
continue;
}
match run_example(module_name, funcs, &exec_modules, example, process.clone()) {
ExampleOutcome::Passed => ok += 1,
ExampleOutcome::ExpectedError => {}
ExampleOutcome::Failed(reason) => {
failures.push(format!("{qualified} example '{}': {reason}", example.name))
}
ExampleOutcome::TimedOut | ExampleOutcome::Skipped => {}
}
}
if ok == 0 {
failures.push(format!(
"{qualified}: no sampled call and no example reached Ok; add passing coverage or widen the sampler"
));
}
}
if !failures.is_empty() {
panic!(
"returns conformance failed ({}):\n- {}",
failures.len(),
failures.join("\n- ")
);
}
}
enum SampleOutcome {
Ok(Value),
Err,
TimedOut,
}
fn invoke_sample<P: ProcessManager + Send + 'static>(
registration: &HostRegistration<P>,
args: Vec<Value>,
process: P,
) -> SampleOutcome {
let (done_tx, done_rx) = std::sync::mpsc::channel();
match registration {
HostRegistration::Pure { func, .. } => {
let func = func.clone();
std::thread::spawn(move || {
let _ = done_tx.send(match func(args) {
Ok(value) => SampleOutcome::Ok(value),
Err(_) => SampleOutcome::Err,
});
});
}
HostRegistration::Both { template, .. } => {
let func = template.clone();
std::thread::spawn(move || {
let _ = done_tx.send(match func(args) {
Ok(value) => SampleOutcome::Ok(value),
Err(_) => SampleOutcome::Err,
});
});
}
HostRegistration::Stateful { func, .. } => {
let func = func.clone();
std::thread::spawn(move || {
let mut state: ExecState<P> = mock_state();
let mut process = process;
let mut cx = StepCtx {
state: &mut state,
process: &mut process,
stdin: CommandStdin::Null,
expose_stdin: false,
out: None,
err: None,
out_pipe: None,
stdin_pipe: None,
tty: None,
};
let _ = done_tx.send(match func(&mut cx, args) {
Ok(value) => SampleOutcome::Ok(value),
Err(_) => SampleOutcome::Err,
});
});
}
}
match done_rx.recv_timeout(std::time::Duration::from_secs(WATCHDOG_SECS)) {
Ok(outcome) => outcome,
Err(_) => SampleOutcome::TimedOut,
}
}
enum ExampleOutcome {
Passed,
ExpectedError,
Failed(String),
TimedOut,
Skipped,
}
fn run_example<P: ProcessManager + Clone + Send + 'static>(
module_name: &str,
funcs: &[HostRegistration<P>],
exec_modules: &[HostModule<P>],
example: &oxdock_parser::Example,
process: P,
) -> ExampleOutcome {
let mut table = ModuleTable {
modules: HashMap::from([(
STD_MODULE_NAME.to_string(),
Some(ModuleFuncs {
func_names: builtin_function_metas()
.iter()
.map(|meta| base_name(&meta.name).to_string())
.collect::<HashSet<_>>(),
}),
)]),
};
table.modules.insert(
module_name.to_string(),
Some(ModuleFuncs {
func_names: funcs
.iter()
.map(|registration| base_name(®istration.meta().name).to_string())
.collect::<HashSet<_>>(),
}),
);
let steps = match crate::parse_script_with_modules(example.code, table) {
Ok(steps) => steps,
Err(err) => return ExampleOutcome::Failed(format!("parse failed: {err:#}")),
};
let needle = match &example.fence_meta {
Some(info) => match oxdock_parser::expect_error_from_info(&format!("oxdock {info}")) {
Ok(needle) => needle,
Err(err) => return ExampleOutcome::Failed(format!("bad fence metadata: {err:#}")),
},
None => None,
};
if example.code.contains("INTERPRETER()") && example.code.contains("RUN [$exe") {
return ExampleOutcome::Skipped;
}
let (done_tx, done_rx) = std::sync::mpsc::channel();
let modules: Vec<HostModule<P>> = exec_modules.to_vec();
std::thread::spawn(move || {
let outcome = (|| {
let workspace_temp =
GuardedPath::tempdir().map_err(|err| format!("fs setup: {err:#}"))?;
let fs_root = workspace_temp.as_guarded_path().clone();
let mut resolver = PathResolver::new_guarded(fs_root.clone(), fs_root.clone())
.map_err(|err| format!("fs setup: {err:#}"))?;
resolver.set_workspace_root(fs_root.clone());
let fs: Box<dyn WorkspaceFs> = Box::new(resolver);
crate::run_steps_with_manager_with_modules(
fs,
&steps,
process,
ExecIo::new(),
modules,
Vec::new(),
)
.map(|_| ())
.map_err(|err| format!("{err:#}"))
})();
let _ = done_tx.send(outcome);
});
match done_rx.recv_timeout(std::time::Duration::from_secs(WATCHDOG_SECS)) {
Ok(Ok(())) => match needle {
Some(expected) => ExampleOutcome::Failed(format!(
"was expected to fail with '{expected}' but succeeded"
)),
None => ExampleOutcome::Passed,
},
Ok(Err(text)) => match needle {
Some(expected) if text.contains(&expected) => ExampleOutcome::ExpectedError,
Some(expected) => {
ExampleOutcome::Failed(format!("error did not contain '{expected}'; got: {text}"))
}
None => ExampleOutcome::Failed(format!("failed unexpectedly: {text}")),
},
Err(_) => ExampleOutcome::TimedOut,
}
}
fn mentions(haystack: &str, needle: &str) -> bool {
let bytes = haystack.as_bytes();
let mut start = 0;
while let Some(pos) = haystack[start..].find(needle) {
let abs = start + pos;
let end = abs + needle.len();
let boundary = |b: Option<u8>| {
b.map(|c| !(c.is_ascii_alphanumeric() || c == b'_'))
.unwrap_or(true)
};
let before = if abs == 0 { None } else { Some(bytes[abs - 1]) };
if boundary(before) && boundary(bytes.get(end).copied()) {
return true;
}
start = abs + 1;
}
false
}
fn mock_state<P: ProcessManager>() -> ExecState<P> {
let fs = MockFs::new();
let mut state = ExecState {
fs: Box::new(fs.clone()),
cargo_scratch: oxdock_fs::reserve_cargo_scratch().expect("cargo scratch"),
seed: Arc::new(HashMap::new()),
cwd: fs.root().clone(),
initial_root: fs.root().clone(),
envs: Arc::new(HashMap::new()),
bg_children: Vec::new(),
scope_stack: Vec::new(),
isolated_stack: Vec::new(),
io: ExecIo::new(),
assert_windows: Arc::new(std::sync::Mutex::new(HashMap::new())),
assert_windows_stderr: Arc::new(std::sync::Mutex::new(HashMap::new())),
exact_stdout: Arc::new(std::sync::Mutex::new(HashMap::new())),
var_scopes: Vec::new(),
cancel_token: Arc::new(std::sync::atomic::AtomicBool::new(false)),
cancel_hub: Arc::new(oxdock_process::CancelHub::new()),
active_process: Arc::new(std::sync::Mutex::new(None)),
named_tasks: Arc::new(std::sync::Mutex::new(HashMap::new())),
next_task_id: Arc::new(std::sync::atomic::AtomicU64::new(1)),
live_tasks: Arc::new(std::sync::atomic::AtomicU64::new(0)),
inside_async: false,
keeper_expiry: None,
cancellable: false,
reap_floor: None,
functions: super::native::FunctionRegistry::with_builtins(),
entry_file: None,
import_stack: Vec::new(),
import_alias_frame: None,
modules: HashMap::new(),
validated_modules: HashSet::new(),
module_stack: Vec::new(),
module_table: super::native::std_module_table(),
types: super::typing::startup_type_map(),
record_schemas: HashMap::new(),
module_states: HashMap::new(),
type_aliases: HashMap::new(),
call_depth: 0,
task_id: 0,
push_manifest: Vec::new(),
_marker: std::marker::PhantomData,
};
state.push_var_scope();
state
}
fn sample_vectors(meta: &super::native::FuncMeta) -> Vec<Vec<Value>> {
let params = meta.params.as_deref().unwrap_or(&[]);
let mut base: Vec<Value> = Vec::with_capacity(params.len());
let mut unions: Vec<(usize, Vec<Value>)> = Vec::new();
let mut options_at: Vec<usize> = Vec::new();
for (idx, param) in params.iter().enumerate() {
if param.options.is_some() {
options_at.push(idx);
base.push(Value::map(BTreeMap::new()));
continue;
}
let candidates = param_candidates(param);
if candidates.is_empty() {
return Vec::new();
}
base.push(candidates[0].clone());
if candidates.len() > 1 {
unions.push((idx, candidates));
}
}
let mut out = vec![base.clone()];
for (idx, candidates) in &unions {
for extra in candidates.iter().skip(1) {
let mut vector = base.clone();
vector[*idx] = extra.clone();
out.push(vector);
}
}
for idx in options_at {
let count = params[idx].options.unwrap_or(&[]).len();
let cases = option_cases(¶ms[idx]);
assert_eq!(
cases.len(),
1 + count,
"option sampling is empty-map plus one single-key map per key, never a cross-product"
);
for case in cases {
let mut vector = base.clone();
vector[idx] = case;
out.push(vector);
}
}
out
}
fn param_candidates(param: &FuncParam) -> Vec<Value> {
if let Some(values) = param.allowed.as_ref()
&& let Some(first) = values.first()
{
return vec![Value::string(first.to_string())];
}
let Some(tag) = param.param_type.as_ref() else {
return Vec::new();
};
match tag {
TypeTag::Union(_, members) => members.iter().filter_map(sample_tag).collect(),
_ => sample_tag(tag).into_iter().collect(),
}
}
fn option_cases(param: &FuncParam) -> Vec<Value> {
let keys = param.options.unwrap_or(&[]);
let mut cases = vec![Value::map(BTreeMap::new())];
for key in keys {
if let Some(value) = sample_tag(&key.value) {
cases.push(Value::map(BTreeMap::from([(key.name.to_string(), value)])));
}
}
cases
}
fn sample_tag(tag: &TypeTag) -> Option<Value> {
match tag {
TypeTag::String => Some(Value::string("x".to_string())),
TypeTag::Int => Some(Value::int(1)),
TypeTag::Float => Some(Value::float(1.5)),
TypeTag::Bool => Some(Value::bool(true)),
TypeTag::List => Some(Value::list(Vec::new())),
TypeTag::Map => Some(Value::map(BTreeMap::new())),
TypeTag::Path => {
#[allow(clippy::disallowed_types)]
let path = std::path::PathBuf::from("x");
Some(Value::path(path))
}
TypeTag::Duration => Some(Value::duration(std::time::Duration::from_secs(1))),
TypeTag::Pipe => Some(Value::pipe_fresh()),
TypeTag::Any => Some(Value::string("x".to_string())),
TypeTag::Union(_, members) => members.iter().find_map(sample_tag),
TypeTag::ListOf(inner) => Some(Value::list(vec![sample_tag(inner)?])),
TypeTag::MapOf(values) => Some(Value::map(BTreeMap::from([(
"k".to_string(),
sample_tag(values)?,
)]))),
TypeTag::Record(fields) => {
let mut entries = BTreeMap::new();
for field in fields.iter() {
entries.insert(field.name.clone(), sample_tag(&field.ty)?);
}
Some(Value::map(entries))
}
TypeTag::Handle
| TypeTag::HandleOf(_)
| TypeTag::Void
| TypeTag::Semaphore
| TypeTag::Permit
| TypeTag::Custom(_) => None,
}
}