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 is_token_separator(c: u8) -> bool {
matches!(
c,
b'[' | b']' | b'(' | b')' | b'{' | b'}' | b'=' | b',' | b';'
)
}
fn is_peelable_punct(c: char) -> bool {
matches!(
c,
':' | ',' | ';' | '.' | '(' | ')' | '[' | ']' | '{' | '}' | '\'' | '"' | '`'
)
}
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() || is_token_separator(bytes[i]) {
out.push(bytes[i] as char);
i += 1;
continue;
}
let start = i;
while i < bytes.len() && !bytes[i].is_ascii_whitespace() && !is_token_separator(bytes[i]) {
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 after_trailing = token.trim_end_matches(is_peelable_punct);
let suffix = &token[after_trailing.len()..];
let core = after_trailing.trim_start_matches(is_peelable_punct);
let prefix = &after_trailing[..after_trailing.len() - core.len()];
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'\\' || bytes[2] == b'/'))
|| (core.len() > 2 && bytes[0] == b'\\' && bytes[1] == b'\\')
|| (core.len() >= LONG_HEX_THRESHOLD && bytes.iter().all(|&b| is_hex_digit(b)));
if masked {
format!("{prefix}{MASK}{suffix}")
} else {
token.to_string()
}
}
const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
fn fnv1a(bytes: &[u8]) -> u64 {
let mut hash = FNV_OFFSET_BASIS;
for &b in bytes {
hash ^= u64::from(b);
hash = hash.wrapping_mul(FNV_PRIME);
}
hash
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ErrorId(u64);
impl ErrorId {
pub const fn as_u64(self) -> u64 {
self.0
}
}
impl std::fmt::Display for ErrorId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "err_{:016x}", self.0)
}
}
#[derive(Debug, Clone, Copy)]
pub struct DisplayWithId<'a>(&'a TensorWasmError);
impl std::fmt::Display for DisplayWithId<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} [{}]", self.0, self.0.error_id())
}
}
#[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 fn error_id(&self) -> ErrorId {
use std::fmt::Write as _;
let mut buf = String::new();
buf.push_str(self.kind());
buf.push('\u{1f}');
match self {
TensorWasmError::CudaError(s)
| TensorWasmError::WasmTrap(s)
| TensorWasmError::WasmCompile(s)
| TensorWasmError::Serialization(s) => buf.push_str(s),
TensorWasmError::MemoryExhausted { requested, limit } => {
let _ = write!(buf, "{requested}/{limit}");
}
TensorWasmError::GpuMemoryExhausted {
requested,
limit,
current,
} => {
let _ = write!(buf, "{requested}/{limit}/{current}");
}
TensorWasmError::KernelTimeout {
elapsed_ms,
deadline_ms,
} => {
let _ = write!(buf, "{elapsed_ms}/{deadline_ms}");
}
TensorWasmError::TenantIsolationViolation {
tenant_id,
resource,
} => {
let _ = write!(buf, "{}/{resource}", tenant_id.get());
}
TensorWasmError::Io(err) => {
buf.push_str(io_kind_name(err));
}
TensorWasmError::SnapshotTooOld {
created_unix_ms,
now_unix_ms,
max_age_ms,
} => {
let _ = write!(buf, "{created_unix_ms}/{now_unix_ms}/{max_age_ms}");
}
}
ErrorId(fnv1a(buf.as_bytes()))
}
pub fn display_with_id(&self) -> DisplayWithId<'_> {
DisplayWithId(self)
}
pub fn redacted_inner_with_id(&self) -> Option<(ErrorId, String)> {
self.redacted_inner().map(|r| (self.error_id(), r))
}
}
pub fn check_allocation(current: u64, requested: u64, cap: u64) -> Result<(), TensorWasmError> {
let fits = current
.checked_add(requested)
.is_some_and(|new_total| new_total <= cap);
if fits {
Ok(())
} else {
Err(TensorWasmError::GpuMemoryExhausted {
requested,
limit: cap,
current,
})
}
}
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 is_retryable_io_kind_pins_retryable_family() {
for kind in [
io::ErrorKind::WouldBlock,
io::ErrorKind::TimedOut,
io::ErrorKind::Interrupted,
io::ErrorKind::WriteZero,
io::ErrorKind::ConnectionReset,
io::ErrorKind::ConnectionAborted,
io::ErrorKind::BrokenPipe,
] {
assert!(
is_retryable_io_kind(kind),
"{kind:?} must be classified as retryable",
);
}
}
#[test]
fn is_retryable_io_kind_pins_hard_miss_kinds() {
for kind in [
io::ErrorKind::NotFound,
io::ErrorKind::PermissionDenied,
io::ErrorKind::AlreadyExists,
io::ErrorKind::InvalidInput,
io::ErrorKind::InvalidData,
io::ErrorKind::UnexpectedEof,
] {
assert!(
!is_retryable_io_kind(kind),
"{kind:?} must NOT 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());
}
#[test]
fn error_id_is_deterministic_and_content_sensitive() {
let a = TensorWasmError::CudaError("ctx lost".into());
let b = TensorWasmError::CudaError("ctx lost".into());
assert_eq!(a.error_id(), b.error_id());
let c = TensorWasmError::CudaError("ctx not current".into());
assert_ne!(a.error_id(), c.error_id());
}
#[test]
fn error_id_distinguishes_variants_with_identical_content() {
let cuda = TensorWasmError::CudaError("boom".into());
let trap = TensorWasmError::WasmTrap("boom".into());
assert_ne!(cuda.error_id(), trap.error_id());
}
#[test]
fn error_id_display_is_fixed_width_opaque_token() {
let e = TensorWasmError::WasmTrap("x".into());
let id = e.error_id().to_string();
assert!(id.starts_with("err_"), "expected err_ sigil, got: {id}");
assert_eq!(id.len(), "err_".len() + 16, "id must be fixed width: {id}");
assert!(
id["err_".len()..].bytes().all(|b| b.is_ascii_hexdigit()),
"id body must be hex: {id}",
);
}
#[test]
fn display_with_id_appends_id_without_leaking_inner() {
let e = TensorWasmError::CudaError("ctx not current at 0x7ffe0000".into());
let rendered = e.display_with_id().to_string();
assert!(
rendered.starts_with("cuda driver call failed"),
"must lead with the sanitised Display: {rendered}",
);
assert!(
rendered.contains(&e.error_id().to_string()),
"must embed the error id: {rendered}",
);
assert!(
!rendered.contains("0x7ffe0000"),
"must NOT leak the inner vendor string: {rendered}",
);
assert_eq!(format!("{e}"), "cuda driver call failed");
}
#[test]
fn redacted_inner_with_id_pairs_id_and_redaction() {
let e = TensorWasmError::WasmCompile("bad module at /dev/shm/tenant-7/mod.wasm".into());
let (id, redacted) = e
.redacted_inner_with_id()
.expect("vendor variant yields Some");
assert_eq!(id, e.error_id());
assert!(redacted.contains("<redacted>"), "expected mask: {redacted}");
assert!(
!redacted.contains("/dev/shm/tenant-7"),
"path must be masked: {redacted}",
);
let mem = TensorWasmError::MemoryExhausted {
requested: 1,
limit: 1,
};
assert!(mem.redacted_inner_with_id().is_none());
}
#[test]
fn check_allocation_admits_within_cap() {
assert!(check_allocation(100, 50, 200).is_ok());
assert!(check_allocation(150, 50, 200).is_ok());
assert!(check_allocation(200, 0, 200).is_ok());
}
#[test]
fn check_allocation_rejects_over_cap_with_fields() {
let err =
check_allocation(100, 150, 200).expect_err("100 + 150 = 250 > 200 must be rejected");
match err {
TensorWasmError::GpuMemoryExhausted {
requested,
limit,
current,
} => {
assert_eq!(requested, 150);
assert_eq!(limit, 200);
assert_eq!(current, 100);
}
other => panic!("expected GpuMemoryExhausted, got: {other:?}"),
}
}
#[test]
fn check_allocation_treats_overflow_as_over_cap() {
let err = check_allocation(u64::MAX, 1, u64::MAX);
assert!(
matches!(err, Err(TensorWasmError::GpuMemoryExhausted { .. })),
"arithmetic overflow must be treated as exceeding the cap",
);
}
#[test]
fn redact_masks_parenthesised_unix_path() {
let r = redact("opened (/dev/shm/tenant-7/mod.wasm) ok");
assert!(
!r.contains("/dev/shm/tenant-7"),
"parenthesised path must be masked: {r}",
);
assert!(r.contains("<redacted>"), "expected mask: {r}");
assert!(
r.contains('(') && r.contains(')'),
"parens must survive: {r}"
);
}
#[test]
fn redact_masks_equals_joined_pointer() {
let r = redact("addr=0x7ffe0000");
assert!(!r.contains("0x7ffe0000"), "pointer must be masked: {r}");
assert!(r.starts_with("addr="), "label must survive: {r}");
assert!(r.contains("<redacted>"), "expected mask: {r}");
}
#[test]
fn redact_masks_comma_joined_path() {
let r = redact("a,/dev/shm/secret/key");
assert!(!r.contains("/dev/shm/secret"), "path must be masked: {r}");
assert!(r.starts_with("a,"), "prefix must survive: {r}");
assert!(r.contains("<redacted>"), "expected mask: {r}");
}
#[test]
fn redact_masks_quote_wrapped_pointer() {
let r = redact("'0x7ffe0000'");
assert!(!r.contains("0x7ffe0000"), "pointer must be masked: {r}");
assert!(r.contains("<redacted>"), "expected mask: {r}");
assert_eq!(r.matches('\'').count(), 2, "both quotes must survive: {r}");
}
#[test]
fn redact_masks_forward_slash_windows_drive_path() {
let r = redact("read C:/Users/op/secret.json failed");
assert!(!r.contains("C:/Users"), "forward-slash drive path: {r}");
assert!(r.contains("<redacted>"), "expected mask: {r}");
}
#[test]
fn redact_masks_unc_path() {
let r = redact(r"copy from \\fileserver\share\secret.bin done");
assert!(!r.contains("fileserver"), "UNC server must be masked: {r}");
assert!(r.contains("<redacted>"), "expected mask: {r}");
}
#[test]
fn redact_does_not_panic_on_utf8_tokens() {
let input = "café 路径=0xdeadBEEF naïve ∑ 北京/上海";
let r = redact(input);
assert!(!r.contains("0xdeadBEEF"), "pointer must be masked: {r}");
assert!(r.contains("café") && r.contains("naïve"), "prose kept: {r}");
}
#[test]
fn redact_keeps_single_component_path_and_lone_slash() {
assert_eq!(redact("3 / 4"), "3 / 4");
assert_eq!(redact("/single"), "/single");
}
#[test]
fn display_snapshot_too_old_renders_all_fields() {
let e = TensorWasmError::SnapshotTooOld {
created_unix_ms: 1_000,
now_unix_ms: 9_999,
max_age_ms: 5_000,
};
let s = e.to_string();
assert!(s.contains("1000"), "created field missing: {s}");
assert!(s.contains("9999"), "now field missing: {s}");
assert!(s.contains("5000"), "max_age field missing: {s}");
}
#[test]
fn display_gpu_memory_exhausted_renders_all_fields() {
let e = TensorWasmError::GpuMemoryExhausted {
requested: 4096,
limit: 8192,
current: 6000,
};
let s = e.to_string();
assert!(s.contains("4096"), "requested field missing: {s}");
assert!(s.contains("8192"), "limit field missing: {s}");
assert!(s.contains("6000"), "current field missing: {s}");
}
#[test]
fn io_retryable_family_via_error_variant() {
for kind in [
io::ErrorKind::TimedOut,
io::ErrorKind::Interrupted,
io::ErrorKind::WriteZero,
io::ErrorKind::BrokenPipe,
io::ErrorKind::ConnectionReset,
io::ErrorKind::ConnectionAborted,
io::ErrorKind::WouldBlock,
] {
let e = TensorWasmError::Io(io::Error::from(kind));
assert!(e.is_retryable(), "Io({kind:?}) must be retryable");
}
}
#[test]
fn io_hard_miss_family_via_error_variant_not_retryable() {
for kind in [
io::ErrorKind::NotFound,
io::ErrorKind::PermissionDenied,
io::ErrorKind::AlreadyExists,
] {
let e = TensorWasmError::Io(io::Error::from(kind));
assert!(!e.is_retryable(), "Io({kind:?}) must NOT be retryable");
}
}
}