use std::io;
use thiserror::Error;
use crate::types::TenantId;
fn io_kind_name(err: &io::Error) -> &'static str {
match err.kind() {
io::ErrorKind::NotFound => "NotFound",
io::ErrorKind::PermissionDenied => "PermissionDenied",
io::ErrorKind::ConnectionRefused => "ConnectionRefused",
io::ErrorKind::ConnectionReset => "ConnectionReset",
io::ErrorKind::ConnectionAborted => "ConnectionAborted",
io::ErrorKind::NotConnected => "NotConnected",
io::ErrorKind::AddrInUse => "AddrInUse",
io::ErrorKind::AddrNotAvailable => "AddrNotAvailable",
io::ErrorKind::BrokenPipe => "BrokenPipe",
io::ErrorKind::AlreadyExists => "AlreadyExists",
io::ErrorKind::WouldBlock => "WouldBlock",
io::ErrorKind::InvalidInput => "InvalidInput",
io::ErrorKind::InvalidData => "InvalidData",
io::ErrorKind::TimedOut => "TimedOut",
io::ErrorKind::WriteZero => "WriteZero",
io::ErrorKind::Interrupted => "Interrupted",
io::ErrorKind::Unsupported => "Unsupported",
io::ErrorKind::UnexpectedEof => "UnexpectedEof",
io::ErrorKind::OutOfMemory => "OutOfMemory",
_ => "Other",
}
}
fn is_retryable_io_kind(kind: io::ErrorKind) -> bool {
matches!(
kind,
io::ErrorKind::WouldBlock
| io::ErrorKind::TimedOut
| io::ErrorKind::Interrupted
| io::ErrorKind::WriteZero
| io::ErrorKind::ConnectionReset
| io::ErrorKind::ConnectionAborted
| io::ErrorKind::BrokenPipe
)
}
const LONG_HEX_THRESHOLD: usize = 16;
fn is_hex_digit(b: u8) -> bool {
b.is_ascii_digit() || matches!(b, b'a'..=b'f' | b'A'..=b'F')
}
fn redact(s: &str) -> String {
let bytes = s.as_bytes();
let mut out = String::with_capacity(s.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i].is_ascii_whitespace() {
out.push(bytes[i] as char);
i += 1;
continue;
}
let start = i;
while i < bytes.len() && !bytes[i].is_ascii_whitespace() {
i += 1;
}
let token = &s[start..i];
out.push_str(&redact_token(token));
}
out
}
fn redact_token(token: &str) -> String {
const MASK: &str = "<redacted>";
let trimmed = token.trim_end_matches(|c: char| {
matches!(
c,
':' | ',' | ';' | '.' | ')' | ']' | '}' | '\'' | '"' | '`'
)
});
let suffix = &token[trimmed.len()..];
let core = trimmed;
if core.is_empty() {
return token.to_string();
}
let bytes = core.as_bytes();
let masked =
(core.len() > 2
&& bytes[0] == b'0'
&& (bytes[1] == b'x' || bytes[1] == b'X')
&& bytes[2..].iter().all(|&b| is_hex_digit(b)))
|| (bytes[0] == b'/' && core[1..].contains('/'))
|| (core.len() > 3
&& bytes[0].is_ascii_alphabetic()
&& bytes[1] == b':'
&& bytes[2] == b'\\')
|| (core.len() >= LONG_HEX_THRESHOLD && bytes.iter().all(|&b| is_hex_digit(b)));
if masked {
format!("{MASK}{suffix}")
} else {
token.to_string()
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum TensorWasmError {
#[error("cuda driver call failed")]
CudaError(Box<str>),
#[error("wasm trap")]
WasmTrap(Box<str>),
#[error("wasm compile failed")]
WasmCompile(Box<str>),
#[error("memory exhausted: requested {requested} bytes, limit {limit}")]
MemoryExhausted {
requested: u64,
limit: u64,
},
#[error("gpu memory exhausted: requested {requested} bytes, limit {limit}, current {current}")]
GpuMemoryExhausted {
requested: u64,
limit: u64,
current: u64,
},
#[error("kernel timeout after {elapsed_ms} ms (deadline {deadline_ms} ms)")]
KernelTimeout {
elapsed_ms: u64,
deadline_ms: u64,
},
#[error("tenant isolation violation")]
TenantIsolationViolation {
tenant_id: TenantId,
resource: Box<str>,
},
#[error("I/O error (kind: {})", io_kind_name(.0))]
Io(#[from] io::Error),
#[error("serialization error")]
Serialization(Box<str>),
#[error(
"snapshot too old: created {created_unix_ms} ms, now {now_unix_ms} ms, \
max age {max_age_ms} ms"
)]
SnapshotTooOld {
created_unix_ms: u64,
now_unix_ms: u64,
max_age_ms: u64,
},
}
impl TensorWasmError {
pub fn is_retryable(&self) -> bool {
match self {
TensorWasmError::KernelTimeout { .. } | TensorWasmError::MemoryExhausted { .. } => true,
TensorWasmError::Io(err) => is_retryable_io_kind(err.kind()),
_ => false,
}
}
pub fn inner(&self) -> Option<&str> {
match self {
TensorWasmError::CudaError(s)
| TensorWasmError::WasmTrap(s)
| TensorWasmError::WasmCompile(s)
| TensorWasmError::Serialization(s) => Some(s),
_ => None,
}
}
pub fn redacted_inner(&self) -> Option<String> {
self.inner().map(redact)
}
pub fn kind(&self) -> &'static str {
match self {
TensorWasmError::CudaError(_) => "cuda",
TensorWasmError::WasmTrap(_) => "wasm_trap",
TensorWasmError::WasmCompile(_) => "wasm_compile",
TensorWasmError::MemoryExhausted { .. } => "memory_exhausted",
TensorWasmError::GpuMemoryExhausted { .. } => "gpu_memory_exhausted",
TensorWasmError::KernelTimeout { .. } => "kernel_timeout",
TensorWasmError::TenantIsolationViolation { .. } => "tenant_isolation",
TensorWasmError::Io(_) => "io",
TensorWasmError::Serialization(_) => "serialization",
TensorWasmError::SnapshotTooOld { .. } => "snapshot_too_old",
}
}
}
pub type Result<T, E = TensorWasmError> = std::result::Result<T, E>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn display_cuda_is_opaque() {
let e = TensorWasmError::CudaError("ctx not current at 0x7ffe0000".into());
assert_eq!(format!("{e}"), "cuda driver call failed");
assert_eq!(e.inner(), Some("ctx not current at 0x7ffe0000"));
}
#[test]
fn display_memory_exhausted_fields() {
let e = TensorWasmError::MemoryExhausted {
requested: 1024,
limit: 512,
};
let s = e.to_string();
assert!(s.contains("1024"));
assert!(s.contains("512"));
}
#[test]
fn display_kernel_timeout_fields() {
let e = TensorWasmError::KernelTimeout {
elapsed_ms: 1500,
deadline_ms: 1000,
};
let s = e.to_string();
assert!(s.contains("1500"));
assert!(s.contains("1000"));
}
#[test]
fn display_isolation_violation_is_sanitised() {
let e = TensorWasmError::TenantIsolationViolation {
tenant_id: crate::types::TenantId(42),
resource: "/dev/shm/other-tenant".into(),
};
assert_eq!(e.to_string(), "tenant isolation violation");
}
#[test]
fn debug_isolation_violation_still_carries_fields() {
let e = TensorWasmError::TenantIsolationViolation {
tenant_id: crate::types::TenantId(42),
resource: "/dev/shm/other-tenant".into(),
};
let dbg = format!("{e:?}");
assert!(dbg.contains("42"), "Debug should expose tenant_id: {dbg}");
assert!(
dbg.contains("/dev/shm/other-tenant"),
"Debug should expose resource: {dbg}",
);
}
#[test]
fn display_wasm_trap_is_opaque() {
let e = TensorWasmError::WasmTrap("unreachable at ip 0x401234".into());
assert_eq!(format!("{e}"), "wasm trap");
assert_eq!(e.inner(), Some("unreachable at ip 0x401234"));
}
#[test]
fn display_wasm_compile_is_opaque() {
let e = TensorWasmError::WasmCompile("bad opcode 0xfe in /tmp/mod.wasm".into());
assert_eq!(format!("{e}"), "wasm compile failed");
assert_eq!(e.inner(), Some("bad opcode 0xfe in /tmp/mod.wasm"));
}
#[test]
fn display_io() {
let e = TensorWasmError::Io(io::Error::new(io::ErrorKind::NotFound, "missing"));
let s = format!("{e}");
assert!(s.contains("I/O error"));
assert!(s.contains("NotFound"));
assert!(
!s.contains("missing"),
"Display must not leak the inner OS string, got: {s}",
);
}
#[test]
fn display_serialization_is_opaque() {
let e = TensorWasmError::Serialization("bad json at byte 42: 'secret-tenant-key'".into());
assert_eq!(format!("{e}"), "serialization error");
assert_eq!(e.inner(), Some("bad json at byte 42: 'secret-tenant-key'"),);
}
#[test]
fn inner_returns_none_for_structured_variants() {
let mem = TensorWasmError::MemoryExhausted {
requested: 1,
limit: 1,
};
let kt = TensorWasmError::KernelTimeout {
elapsed_ms: 1,
deadline_ms: 1,
};
let iso = TensorWasmError::TenantIsolationViolation {
tenant_id: crate::types::TenantId(1),
resource: "x".into(),
};
let io = TensorWasmError::Io(io::Error::other("x"));
assert!(mem.inner().is_none());
assert!(kt.inner().is_none());
assert!(iso.inner().is_none());
assert!(io.inner().is_none());
}
#[test]
fn io_from_conversion() {
let io_err = io::Error::new(io::ErrorKind::PermissionDenied, "nope");
let e: TensorWasmError = io_err.into();
assert!(matches!(e, TensorWasmError::Io(_)));
assert_eq!(e.kind(), "io");
}
#[test]
fn kind_stable_names() {
assert_eq!(TensorWasmError::CudaError("x".into()).kind(), "cuda");
assert_eq!(TensorWasmError::WasmTrap("x".into()).kind(), "wasm_trap");
assert_eq!(
TensorWasmError::WasmCompile("x".into()).kind(),
"wasm_compile"
);
assert_eq!(
TensorWasmError::Serialization("x".into()).kind(),
"serialization"
);
}
#[test]
fn retryable_classification() {
assert!(TensorWasmError::KernelTimeout {
elapsed_ms: 1,
deadline_ms: 1
}
.is_retryable());
assert!(TensorWasmError::MemoryExhausted {
requested: 1,
limit: 1
}
.is_retryable());
assert!(!TensorWasmError::WasmTrap("x".into()).is_retryable());
assert!(!TensorWasmError::CudaError("x".into()).is_retryable());
}
#[test]
fn gpu_memory_exhausted_is_not_retryable() {
let gpu = TensorWasmError::GpuMemoryExhausted {
requested: 1024,
limit: 512,
current: 256,
};
assert!(
!gpu.is_retryable(),
"GpuMemoryExhausted must NOT be flagged as retryable",
);
assert!(TensorWasmError::MemoryExhausted {
requested: 1024,
limit: 512,
}
.is_retryable());
}
#[test]
fn io_kind_name_maps_common_kinds() {
assert_eq!(
io_kind_name(&io::Error::from(io::ErrorKind::NotFound)),
"NotFound"
);
assert_eq!(
io_kind_name(&io::Error::from(io::ErrorKind::PermissionDenied)),
"PermissionDenied"
);
assert_eq!(
io_kind_name(&io::Error::from(io::ErrorKind::WouldBlock)),
"WouldBlock"
);
assert_eq!(
io_kind_name(&io::Error::from(io::ErrorKind::TimedOut)),
"TimedOut"
);
assert_eq!(
io_kind_name(&io::Error::from(io::ErrorKind::AlreadyExists)),
"AlreadyExists"
);
assert_eq!(io_kind_name(&io::Error::other("x")), "Other");
}
#[test]
fn wasm_compile_is_not_retryable() {
let e = TensorWasmError::WasmCompile("invalid opcode 0xfe".into());
assert!(
!e.is_retryable(),
"WasmCompile must not be flagged as retryable",
);
}
#[test]
fn tenant_isolation_violation_is_not_retryable() {
let e = TensorWasmError::TenantIsolationViolation {
tenant_id: crate::types::TenantId(1),
resource: "/dev/shm/foreign".into(),
};
assert!(
!e.is_retryable(),
"TenantIsolationViolation must not be flagged as retryable",
);
}
#[test]
fn io_error_is_retryable_wouldblock_true() {
let e = TensorWasmError::Io(io::Error::from(io::ErrorKind::WouldBlock));
assert!(
e.is_retryable(),
"Io(WouldBlock) must be classified as retryable",
);
}
#[test]
fn io_error_is_retryable_notfound_false() {
let e = TensorWasmError::Io(io::Error::from(io::ErrorKind::NotFound));
assert!(
!e.is_retryable(),
"Io(NotFound) must NOT be classified as retryable",
);
}
#[test]
fn string_construction_via_into() {
let from_string: Box<str> = String::from("hello").into();
let from_str: Box<str> = "hello".into();
let from_box: Box<str> = Box::<str>::from("hello");
let e1 = TensorWasmError::CudaError(from_string);
let e2 = TensorWasmError::CudaError(from_str);
let e3 = TensorWasmError::CudaError(from_box);
assert_eq!(e1.inner(), Some("hello"));
assert_eq!(e2.inner(), Some("hello"));
assert_eq!(e3.inner(), Some("hello"));
}
#[test]
fn redacted_inner_masks_pointer() {
let e = TensorWasmError::CudaError("ctx not current at 0x7ffe0000".into());
let r = e.redacted_inner().expect("vendor variant yields Some");
assert!(
!r.contains("0x7ffe0000"),
"pointer must be masked, got: {r}",
);
assert!(r.contains("<redacted>"), "expected mask token, got: {r}");
assert!(r.contains("ctx not current at"), "prose must survive: {r}");
}
#[test]
fn redacted_inner_masks_unix_path() {
let e = TensorWasmError::WasmCompile("bad module at /dev/shm/tenant-7/mod.wasm".into());
let r = e.redacted_inner().expect("vendor variant yields Some");
assert!(
!r.contains("/dev/shm/tenant-7"),
"unix path must be masked, got: {r}",
);
assert!(r.contains("<redacted>"), "expected mask token, got: {r}");
assert!(r.contains("bad module at"), "prose must survive: {r}");
}
#[test]
fn redacted_inner_masks_windows_path() {
let e = TensorWasmError::Serialization("read failed: C:\\Users\\op\\secret.json".into());
let r = e.redacted_inner().expect("vendor variant yields Some");
assert!(
!r.contains("C:\\Users"),
"windows path must be masked, got: {r}",
);
assert!(r.contains("<redacted>"), "expected mask token, got: {r}");
}
#[test]
fn redacted_inner_masks_long_hex() {
let e = TensorWasmError::WasmTrap("trap at deadbeefcafebabe".into());
let r = e.redacted_inner().expect("vendor variant yields Some");
assert!(
!r.contains("deadbeefcafebabe"),
"long hex token must be masked, got: {r}",
);
assert!(r.contains("<redacted>"), "expected mask token, got: {r}");
}
#[test]
fn redacted_inner_preserves_ordinary_text() {
let e = TensorWasmError::WasmCompile("invalid opcode at index 3 / 4 byte 42".into());
let r = e.redacted_inner().expect("vendor variant yields Some");
assert_eq!(
r, "invalid opcode at index 3 / 4 byte 42",
"ordinary text must be preserved verbatim",
);
}
#[test]
fn redacted_inner_none_for_structured_variants() {
let mem = TensorWasmError::MemoryExhausted {
requested: 1,
limit: 1,
};
let io = TensorWasmError::Io(io::Error::other("/secret/path"));
assert!(mem.redacted_inner().is_none());
assert!(io.redacted_inner().is_none());
}
}