use std::collections::BTreeMap;
#[derive(Debug, Clone)]
pub struct Geometry {
path: String,
map: BTreeMap<String, String>,
}
pub fn manifest_path(cache_dir: &str, family: &str) -> String {
format!("{cache_dir}/{family}-geometry.txt")
}
impl Geometry {
pub fn load(path: &str, regen_hint: &str) -> Result<Self, String> {
let text = std::fs::read_to_string(path).map_err(|e| {
format!(
"GEOMETRY MANIFEST MISSING: {path}: {e}\n \
This gate compares bytes against a reference dump. Without the manifest there \
is no way to assert the dump was produced under the same config as the \
checkpoint under test, and a reference regenerated under a different hidden \
size, tap set or block size is indistinguishable from a correct one \
(GATE-INTEGRITY-20260819 §5). Refusing rather than guessing.\n \
Regenerate the reference (and its manifest) with:\n {regen_hint}"
)
})?;
let mut map = BTreeMap::new();
for (i, raw) in text.lines().enumerate() {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let (k, v) = line
.split_once('=')
.ok_or_else(|| format!("{path}:{}: not a key=value line: {raw:?}", i + 1))?;
if map
.insert(k.trim().to_string(), v.trim().to_string())
.is_some()
{
return Err(format!("{path}:{}: duplicate key {:?}", i + 1, k.trim()));
}
}
if map.is_empty() {
return Err(format!(
"{path}: manifest is EMPTY — an empty manifest asserts nothing and must not \
read as agreement"
));
}
Ok(Self {
path: path.to_string(),
map,
})
}
pub fn get(&self, key: &str) -> Option<&str> {
self.map.get(key).map(String::as_str)
}
pub fn need_usize(&self, key: &str) -> Result<usize, String> {
let raw = self
.get(key)
.ok_or_else(|| format!("{}: missing required key {key}", self.path))?;
raw.parse::<usize>()
.map_err(|e| format!("{}: {key}={raw:?} is not a usize: {e}", self.path))
}
pub fn expect_usize(&self, key: &str, want: usize) -> Result<(), String> {
let got = self.need_usize(key)?;
if got == want {
return Ok(());
}
Err(format!(
"GEOMETRY MISMATCH {key}: reference dump was produced with {got}, the checkpoint \
under test has {want}.\n The bytes would still compare — a different {key} \
reinterprets the same buffer — which is why this is asserted BEFORE any value \
compare. Manifest: {}",
self.path
))
}
pub fn expect_str(&self, key: &str, want: &str) -> Result<(), String> {
let got = self
.get(key)
.ok_or_else(|| format!("{}: missing required key {key}", self.path))?;
if got == want {
return Ok(());
}
Err(format!(
"GEOMETRY MISMATCH {key}: reference dump was produced with {got:?}, the checkpoint \
under test has {want:?}. Manifest: {}",
self.path
))
}
pub fn expect_f64_near(&self, key: &str, want: f64, rel: f64) -> Result<(), String> {
let raw = self
.get(key)
.ok_or_else(|| format!("{}: missing required key {key}", self.path))?;
let got: f64 = raw
.parse()
.map_err(|e| format!("{}: {key}={raw:?} is not a number: {e}", self.path))?;
let denom = want.abs().max(f64::MIN_POSITIVE);
if ((got - want).abs() / denom) <= rel {
return Ok(());
}
Err(format!(
"GEOMETRY MISMATCH {key}: reference dump was produced with {got}, the checkpoint \
under test has {want} (rel tol {rel}). Manifest: {}",
self.path
))
}
pub fn expect_usize_if_present(&self, key: &str, want: usize) -> Result<bool, String> {
if self.get(key).is_none() {
return Ok(false);
}
self.expect_usize(key, want)?;
Ok(true)
}
pub fn expect_str_if_present(&self, key: &str, want: &str) -> Result<bool, String> {
if self.get(key).is_none() {
return Ok(false);
}
self.expect_str(key, want)?;
Ok(true)
}
}
pub fn expect_len(dump: &str, got: usize, want: usize, how: &str) -> Result<(), String> {
if got == want {
return Ok(());
}
Err(format!(
"GEOMETRY MISMATCH {dump}: {got} elements, config predicts {want} ({how}).\n \
The old form DERIVED a dimension from this length by integer division, so a dump of the \
wrong size became a comparison against a reinterpreted buffer instead of a failure."
))
}
#[allow(dead_code)]
pub fn exact_div(dump: &str, len: usize, per: usize, per_desc: &str) -> Result<usize, String> {
if per == 0 {
return Err(format!(
"{dump}: cannot divide by {per_desc}=0 — the config is degenerate, not the dump"
));
}
if len % per != 0 {
return Err(format!(
"GEOMETRY MISMATCH {dump}: {len} elements is not a multiple of {per_desc}={per} \
(remainder {}). The old form used integer division and silently truncated this.",
len % per
));
}
if len == 0 {
return Err(format!("{dump}: empty dump"));
}
Ok(len / per)
}
pub fn join_usize(v: &[usize]) -> String {
v.iter()
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(",")
}
pub fn join_bool(v: &[bool]) -> String {
v.iter()
.map(|b| if *b { "1" } else { "0" })
.collect::<Vec<_>>()
.join(",")
}
#[cfg(test)]
mod tests {
use super::*;
fn write(body: &str) -> String {
let p = std::env::temp_dir().join(format!(
"memra_parity_geometry_{}_{:?}.txt",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::write(&p, body).unwrap();
p.to_string_lossy().into_owned()
}
const GOOD: &str = "\
# produced by tools/dflash_oracle.py
producer=tools/dflash_oracle.py
dtype=f32
hidden=2560
n_layer=5
block_size=8
ctx=8
n_taps=5
target_layer_ids=13,26,39,52,61
head_dim=128
n_head=20
n_head_kv=4
rope_theta=1000000.0
sliding_window=2048
layer_sliding=1,1,1,1,0
";
#[test]
fn a_missing_manifest_is_a_refusal_that_names_the_remedy() {
let err = Geometry::load("/nonexistent/dflash-geometry.txt", "python tools/x.py A B")
.expect_err("a missing manifest must not load");
assert!(err.contains("GEOMETRY MANIFEST MISSING"), "{err}");
assert!(err.contains("python tools/x.py A B"), "{err}");
}
#[test]
fn an_empty_manifest_is_not_agreement() {
let p = write("\n# only comments\n\n");
let err = Geometry::load(&p, "regen").expect_err("empty manifest must not load");
assert!(err.contains("EMPTY"), "{err}");
std::fs::remove_file(p).ok();
}
#[test]
fn a_matching_manifest_passes_every_field() {
let p = write(GOOD);
let g = Geometry::load(&p, "regen").unwrap();
g.expect_str("dtype", "f32").unwrap();
g.expect_usize("hidden", 2560).unwrap();
g.expect_usize("block_size", 8).unwrap();
g.expect_usize("n_taps", 5).unwrap();
g.expect_str("target_layer_ids", &join_usize(&[13, 26, 39, 52, 61]))
.unwrap();
g.expect_str(
"layer_sliding",
&join_bool(&[true, true, true, true, false]),
)
.unwrap();
g.expect_f64_near("rope_theta", 1e6, 1e-9).unwrap();
assert!(g.expect_usize_if_present("sliding_window", 2048).unwrap());
assert_eq!(g.need_usize("ctx").unwrap(), 8);
std::fs::remove_file(p).ok();
}
#[test]
fn a_refactorised_geometry_with_the_same_product_is_caught() {
let p = write(
&GOOD
.replace("hidden=2560", "hidden=1280")
.replace("n_taps=5", "n_taps=10"),
);
let g = Geometry::load(&p, "regen").unwrap();
let err = g
.expect_usize("hidden", 2560)
.expect_err("must catch hidden");
assert!(err.contains("GEOMETRY MISMATCH hidden"), "{err}");
assert!(err.contains("2560") && err.contains("1280"), "{err}");
let old_total = 8 * 5 * 2560;
let new_total = 8 * 10 * 1280;
assert_eq!(old_total, new_total, "the fixture's premise");
std::fs::remove_file(p).ok();
}
#[test]
fn a_config_only_scalar_is_caught_even_though_no_byte_moves() {
let p = write(&GOOD.replace("rope_theta=1000000.0", "rope_theta=250000.0"));
let g = Geometry::load(&p, "regen").unwrap();
let err = g
.expect_f64_near("rope_theta", 1e6, 1e-6)
.expect_err("must catch rope_theta");
assert!(err.contains("GEOMETRY MISMATCH rope_theta"), "{err}");
let p2 = write(&GOOD.replace("head_dim=128", "head_dim=64"));
let g2 = Geometry::load(&p2, "regen").unwrap();
assert!(
g2.expect_usize("head_dim", 128)
.expect_err("must catch head_dim")
.contains("GEOMETRY MISMATCH head_dim")
);
std::fs::remove_file(p).ok();
std::fs::remove_file(p2).ok();
}
#[test]
fn a_tap_set_permutation_is_caught_though_the_count_agrees() {
let p = write(&GOOD.replace("13,26,39,52,61", "13,26,39,52,60"));
let g = Geometry::load(&p, "regen").unwrap();
g.expect_usize("n_taps", 5).expect("count still agrees");
let err = g
.expect_str("target_layer_ids", &join_usize(&[13, 26, 39, 52, 61]))
.expect_err("the tap SET must be asserted, not just its length");
assert!(err.contains("GEOMETRY MISMATCH target_layer_ids"), "{err}");
std::fs::remove_file(p).ok();
}
#[test]
fn a_dropped_optional_field_is_reported_not_silently_satisfied() {
let p = write(&GOOD.replace("sliding_window=2048\n", ""));
let g = Geometry::load(&p, "regen").unwrap();
assert!(
!g.expect_usize_if_present("sliding_window", 2048).unwrap(),
"absence must be reported as `false`, never as agreement"
);
std::fs::remove_file(p).ok();
}
#[test]
fn expect_len_replaces_the_derive_and_a_wrong_length_fails() {
expect_len(
"dflash-target_hidden.f32",
8 * 5 * 2560,
8 * 5 * 2560,
"ctx*n_taps*hidden",
)
.unwrap();
let err = expect_len(
"dflash-target_hidden.f32",
8 * 5 * 2560 + 2560,
8 * 5 * 2560,
"ctx*n_taps*hidden",
)
.expect_err("a longer dump must fail, not redefine ctx");
assert!(
err.contains("GEOMETRY MISMATCH dflash-target_hidden.f32"),
"{err}"
);
}
#[test]
fn exact_div_refuses_a_remainder_instead_of_truncating() {
assert_eq!(exact_div("d", 80, 10, "n_taps*hidden").unwrap(), 8);
let err = exact_div("d", 83, 10, "n_taps*hidden").expect_err("remainder must fail");
assert!(err.contains("remainder 3"), "{err}");
assert!(exact_div("d", 0, 10, "x").is_err(), "empty dump must fail");
assert!(exact_div("d", 80, 0, "x").is_err(), "div by zero must fail");
}
#[test]
fn a_malformed_or_duplicated_key_is_an_error_not_a_shrug() {
let p = write("hidden=2560\nnot a kv line\n");
assert!(Geometry::load(&p, "r").is_err());
std::fs::remove_file(p).ok();
let p = write("hidden=2560\nhidden=1280\n");
let err = Geometry::load(&p, "r").expect_err("duplicate key must fail");
assert!(err.contains("duplicate key"), "{err}");
std::fs::remove_file(p).ok();
}
#[test]
fn a_missing_required_key_names_itself() {
let p = write("hidden=2560\n");
let g = Geometry::load(&p, "r").unwrap();
assert!(
g.need_usize("ctx")
.unwrap_err()
.contains("missing required key ctx")
);
assert!(
g.expect_str("dtype", "f32")
.unwrap_err()
.contains("missing required key dtype")
);
std::fs::remove_file(p).ok();
}
}