Skip to main content

oa/core/
validation.rs

1//! Debug validation layer for OA compute operations.
2//!
3//! Port provenance: `oa/core/validation.h`.
4//!
5//! # Build model
6//!
7//! | Build | Behaviour |
8//! |---|---|
9//! | `debug_assertions` on (dev) | [`oa_validate!`](macro@crate::oa_validate) always active; counters compiled in |
10//! | `debug_assertions` off (release) | [`oa_validate!`](macro@crate::oa_validate) compiled out — zero binary size |
11//! | release + `OA_ENABLE_VALIDATION` feature | [`oa_validate!`](macro@crate::oa_validate) compiled in, runtime-gated by `Validation::is_enabled()` |
12//!
13//! # Usage
14//!
15//! ```rust,ignore
16//! use oa::{oa_validate, ValidationSeverity};
17//!
18//! fn my_op(m: usize) -> oa::Result<()> {
19//!     oa_validate!(m > 0, ValidationSeverity::Error, "my_op: M must be > 0, got {m}");
20//!     Ok(())
21//! }
22//! ```
23
24#[cfg(debug_assertions)]
25use std::collections::HashMap;
26#[cfg(debug_assertions)]
27use std::sync::atomic::AtomicU64;
28use std::sync::{
29	Mutex, OnceLock,
30	atomic::{AtomicBool, Ordering},
31};
32
33// ─── ValidationSeverity ──────────────────────────────────────────────────────
34
35/// Severity levels for validation messages.
36///
37/// Port provenance: `oa::ValidationSeverity`.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
39#[repr(u8)]
40pub enum ValidationSeverity {
41	/// Internal state dumps; opt-in.
42	Verbose = 0,
43	/// Routing decisions, kernel selection, shape reports.
44	Info = 1,
45	/// Performance issues (naive fallback, misaligned tiles).
46	Warning = 2,
47	/// Contract violations producing wrong results.
48	Error = 3,
49	/// Invariant broken; cannot continue safely.
50	Fatal = 4,
51}
52
53impl ValidationSeverity {
54	/// Short uppercase name for log output.
55	pub fn as_str(self) -> &'static str {
56		match self {
57			Self::Verbose => "VERBOSE",
58			Self::Info => "INFO",
59			Self::Warning => "WARNING",
60			Self::Error => "ERROR",
61			Self::Fatal => "FATAL",
62		}
63	}
64}
65
66// ─── Validation ──────────────────────────────────────────────────────────────
67
68/// Optional custom callback type for validation messages.
69pub type ValidationCallback = fn(ValidationSeverity, &str, &str);
70
71struct ValidationState {
72	enabled: AtomicBool,
73	min_severity: Mutex<ValidationSeverity>,
74	callback: Mutex<Option<ValidationCallback>>,
75	#[cfg(debug_assertions)]
76	counters: Mutex<HashMap<String, AtomicU64>>,
77}
78
79static STATE: OnceLock<ValidationState> = OnceLock::new();
80
81fn state() -> &'static ValidationState {
82	STATE.get_or_init(|| ValidationState {
83		#[cfg(debug_assertions)]
84		enabled: AtomicBool::new(true),
85		#[cfg(not(debug_assertions))]
86		enabled: AtomicBool::new(false),
87		min_severity: Mutex::new(ValidationSeverity::Verbose),
88		callback: Mutex::new(None),
89		#[cfg(debug_assertions)]
90		counters: Mutex::new(HashMap::new()),
91	})
92}
93
94/// Global validation controller.
95///
96/// Port provenance: `oa::Validation`.
97pub struct Validation;
98
99impl Validation {
100	/// Enable or disable the validation layer globally.
101	pub fn enable(on: bool) {
102		state().enabled.store(on, Ordering::Release);
103	}
104
105	/// Return `true` when the validation layer is enabled.
106	pub fn is_enabled() -> bool {
107		state().enabled.load(Ordering::Acquire)
108	}
109
110	/// Read `OA_VK_VALIDATION` and `OA_VALIDATION_SEVERITY` from the process
111	/// environment and apply them. Call once at runtime init.
112	pub fn init_from_env() {
113		if std::env::var("OA_VK_VALIDATION")
114			.map(|v| !matches!(v.as_str(), "" | "0" | "false" | "no" | "off"))
115			.unwrap_or(false)
116		{
117			Self::enable(true);
118		}
119		if let Ok(sev) = std::env::var("OA_VALIDATION_SEVERITY") {
120			let parsed = match sev.to_ascii_uppercase().as_str() {
121				"VERBOSE" => Some(ValidationSeverity::Verbose),
122				"INFO" => Some(ValidationSeverity::Info),
123				"WARNING" | "WARN" => Some(ValidationSeverity::Warning),
124				"ERROR" => Some(ValidationSeverity::Error),
125				"FATAL" => Some(ValidationSeverity::Fatal),
126				_ => None,
127			};
128			if let Some(s) = parsed {
129				Self::set_min_severity(s);
130			}
131		}
132	}
133
134	/// Override the minimum severity for emitting messages. Default: `Verbose`
135	/// in debug, `Warning` in release.
136	pub fn set_min_severity(sev: ValidationSeverity) {
137		*state().min_severity.lock().unwrap() = sev;
138	}
139
140	/// Return the current minimum severity.
141	pub fn get_min_severity() -> ValidationSeverity {
142		*state().min_severity.lock().unwrap()
143	}
144
145	/// Set an optional custom callback; `None` restores the default stderr
146	/// writer.
147	pub fn set_callback(cb: Option<ValidationCallback>) {
148		*state().callback.lock().unwrap() = cb;
149	}
150
151	/// Emit a validation message. Returns `Err` on `Error` or `Fatal`
152	/// severity; `Ok` otherwise.
153	///
154	/// Called by [`oa_validate!`](macro@crate::oa_validate) when the condition fails.
155	pub fn report(sev: ValidationSeverity, component: &str, message: &str) -> crate::Result<()> {
156		let s = state();
157		if !s.enabled.load(Ordering::Acquire) {
158			return Ok(());
159		}
160		if sev < *s.min_severity.lock().unwrap() {
161			return Ok(());
162		}
163		let cb = *s.callback.lock().unwrap();
164		if let Some(f) = cb {
165			f(sev, component, message);
166		} else {
167			eprintln!("[OA {}] {}: {}", sev.as_str(), component, message);
168		}
169		if sev >= ValidationSeverity::Error {
170			return Err(crate::core::error::Error::invalid_argument(format!(
171				"validation error [{component}]: {message}"
172			)));
173		}
174		Ok(())
175	}
176
177	// ── Debug counters (compiled out in release) ──────────────────────────
178
179	/// Increment a named debug counter (no-op in release builds).
180	#[cfg(debug_assertions)]
181	pub fn incr_counter(name: &str) {
182		let s = state();
183		let mut map = s.counters.lock().unwrap();
184		map
185			.entry(name.to_owned())
186			.or_insert_with(|| AtomicU64::new(0))
187			.fetch_add(1, Ordering::Relaxed);
188	}
189
190	#[cfg(not(debug_assertions))]
191	pub fn incr_counter(_name: &str) {}
192
193	/// Return the current value of a named debug counter (0 in release builds).
194	#[cfg(debug_assertions)]
195	pub fn get_counter(name: &str) -> u64 {
196		state()
197			.counters
198			.lock()
199			.unwrap()
200			.get(name)
201			.map(|c| c.load(Ordering::Relaxed))
202			.unwrap_or(0)
203	}
204
205	#[cfg(not(debug_assertions))]
206	pub fn get_counter(_name: &str) -> u64 {
207		0
208	}
209
210	/// Reset all debug counters to zero (no-op in release builds).
211	#[cfg(debug_assertions)]
212	pub fn reset_counters() {
213		state().counters.lock().unwrap().clear();
214	}
215
216	#[cfg(not(debug_assertions))]
217	pub fn reset_counters() {}
218}
219
220// ─── oa_validate! macro ──────────────────────────────────────────────────────
221
222/// Validate a condition and report via the OA validation layer.
223///
224/// In debug builds the check is always active. In release builds the check
225/// compiles out unless the `oa-enable-validation` feature is set.
226///
227/// ```rust,ignore
228/// // In a function returning oa::Result<T>:
229/// oa_validate!(m > 0, oa::ValidationSeverity::Error, "Core", "M must be > 0, got {m}");
230/// ```
231///
232/// - `Error` / `Fatal` → logs and returns `Err(...)` from the enclosing function.
233/// - `Warning` / `Info` / `Verbose` → logs only; does not return.
234///
235/// Port provenance: `OA_VALIDATE` macro in `oa/core/validation.h`.
236#[macro_export]
237macro_rules! oa_validate {
238	($cond:expr, $sev:expr, $comp:expr, $($arg:tt)*) => {
239		#[cfg(any(debug_assertions, feature = "oa-enable-validation"))]
240		{
241			if $crate::Validation::is_enabled() && !($cond) {
242				let msg = format!($($arg)*);
243				$crate::Validation::report($sev, $comp, &msg)?;
244			}
245		}
246	};
247}
248
249/// Performance warning: logs at `Warning` severity when `cond` is true.
250/// Does **not** return an error. Compiled out in release without the feature.
251///
252/// Port provenance: `OA_WARN_PERF` in `oa/core/validation.h`.
253#[macro_export]
254macro_rules! oa_warn_perf {
255	($cond:expr, $($arg:tt)*) => {
256		#[cfg(any(debug_assertions, feature = "oa-enable-validation"))]
257		{
258			if $crate::Validation::is_enabled() && ($cond) {
259				let msg = format!($($arg)*);
260				let _ = $crate::Validation::report(
261					$crate::ValidationSeverity::Warning, "Core", &msg);
262			}
263		}
264	};
265}