#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostClass {
pub os_build: String,
pub os_product_version: String,
pub chip: String,
pub arch: String,
}
impl HostClass {
pub fn running() -> Self {
HostClass {
os_build: sysctl_string("kern.osversion"),
os_product_version: sysctl_string("kern.osproductversion"),
chip: sysctl_string("machdep.cpu.brand_string"),
arch: match std::env::consts::ARCH {
"aarch64" => "arm64".to_string(),
other => other.to_string(),
},
}
}
}
impl std::fmt::Display for HostClass {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"macOS {} (build {}), {}, {}",
self.os_product_version, self.os_build, self.chip, self.arch
)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RecordedHost {
pub class: HostClass,
pub source: Option<String>,
}
impl From<HostClass> for RecordedHost {
fn from(class: HostClass) -> Self {
RecordedHost {
class,
source: None,
}
}
}
impl std::fmt::Display for RecordedHost {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.class)?;
match &self.source {
Some(source) => write!(f, " — oracle: {source}"),
None => Ok(()),
}
}
}
impl RecordedHost {
pub fn all_from_golden(name: &str, v: &serde_json::Value) -> Result<Vec<Self>, String> {
let present = |key: &str| v.get(key).filter(|x| !x.is_null());
match (present("generationHosts"), present("generationHost")) {
(Some(_), Some(_)) => Err(format!(
"{name}: carries BOTH `generationHosts` and `generationHost`. A golden records where \
it was produced exactly once — keep the `generationHosts` set and drop the legacy \
single-host key, or the two can disagree with nothing to say which is true"
)),
(Some(set), None) => {
let entries = set.as_array().ok_or_else(|| {
format!(
"{name}: `generationHosts` is {set} — expected a non-empty array of objects with \
osBuild / osProductVersion / chip / arch string fields"
)
})?;
if entries.is_empty() {
return Err(format!(
"{name}: `generationHosts` is empty. A golden either records the host classes its \
payload was reproduced on, or omits the key entirely (legacy, unattributable) — \
an empty set claims a payload nothing reproduced"
));
}
entries
.iter()
.enumerate()
.map(|(i, entry)| Self::from_object(name, &format!("generationHosts[{i}]"), entry))
.collect()
}
(None, Some(one)) => Ok(vec![Self::from_object(name, "generationHost", one)?]),
(None, None) => Ok(Vec::new()),
}
}
fn from_object(name: &str, label: &str, v: &serde_json::Value) -> Result<Self, String> {
let host = match v {
serde_json::Value::Object(map) => map,
other => {
return Err(format!(
"{name}: `{label}` is {other} — expected an object with osBuild / osProductVersion / \
chip / arch string fields"
));
}
};
let field = |key: &str| -> Result<String, String> {
host
.get(key)
.and_then(serde_json::Value::as_str)
.map(str::to_string)
.filter(|s| !s.is_empty())
.ok_or_else(|| format!("{name}: `{label}.{key}` is missing, not a string, or empty"))
};
let source = match host.get("source") {
None | Some(serde_json::Value::Null) => None,
Some(serde_json::Value::String(s)) if !s.is_empty() => Some(s.clone()),
Some(other) => {
return Err(format!(
"{name}: `{label}.source` is {other} — expected a non-empty string naming the oracle \
that produced this payload on this host"
));
}
};
Ok(RecordedHost {
class: HostClass {
os_build: field("osBuild")?,
os_product_version: field("osProductVersion")?,
chip: field("chip")?,
arch: field("arch")?,
},
source,
})
}
}
fn sysctl_string(key: &str) -> String {
let output = std::process::Command::new("/usr/sbin/sysctl")
.args(["-n", key])
.output()
.unwrap_or_else(|e| panic!("host-class gate: cannot spawn /usr/sbin/sysctl for `{key}`: {e}"));
assert!(
output.status.success(),
"host-class gate: `/usr/sbin/sysctl -n {key}` exited {}",
output.status
);
let value = String::from_utf8_lossy(&output.stdout).trim().to_string();
assert!(
!value.is_empty(),
"host-class gate: `/usr/sbin/sysctl -n {key}` produced empty output"
);
value
}
#[derive(Debug, PartialEq, Eq)]
pub enum HostVerdict {
Match,
LegacyUnknown,
}
pub fn check_host_class(
fixture: &str,
recorded: &[RecordedHost],
running: &HostClass,
regen_script: &str,
) -> Result<HostVerdict, String> {
if recorded.is_empty() {
return Ok(HostVerdict::LegacyUnknown);
}
if recorded.iter().any(|host| &host.class == running) {
return Ok(HostVerdict::Match);
}
let listed = recorded
.iter()
.map(|host| format!("\n - {host}"))
.collect::<String>();
let count = recorded.len();
Err(format!(
"{fixture}: committed golden has NOT been verified on this host-class — this machine is a \
DIFFERENT host-class from every one the golden was reproduced on.\n \
golden hosts ({count} recorded):{listed}\n \
this host : {running}\n\
CoreML floating point is not contracted portable across macOS builds or chips —\n\
neither the `CpuOnly` kernels that ship with the OS nor the Neural Engine's fp16\n\
arithmetic — so the tight parity bound would misattribute host float drift to the\n\
port. This failure is NOT evidence of a port defect. To test the port on this\n\
machine, regenerate a same-host oracle and re-run:\n {regen_script}\n\
A regeneration whose payload matches the committed one ADDS this machine's class to the\n\
set above rather than replacing it, so a host that reproduces the goldens joins them.\n\
Do NOT widen the parity tolerances instead — the tight bounds are what catch real\n\
stitching/index-mapping regressions on a matching host."
))
}
pub fn legacy_failure_note(regen_script: &str) -> String {
format!(
"\nNOTE: this golden predates host-class provenance (no `generationHosts` field), so this\n\
failure is AMBIGUOUS between a port defect and host-CoreML float drift (neither the\n\
`CpuOnly` kernels nor the Neural Engine's fp16 arithmetic are contracted portable across\n\
macOS builds/chips). Regenerate a same-host oracle via {regen_script} to disambiguate —\n\
regeneration also stamps the host class it ran on. Do NOT widen the tolerance."
)
}