use crate::fkc::verify::VerificationLedger;
use crate::fkc::verify::seed_cpu_ledger::ITERS;
use crate::fused::PrecisionGuarantee;
pub(crate) fn evidence_clause() -> String {
format!(
"[evidence: bit_stable_on_same_hardware earned EMPIRICALLY per registered dtype \
— {ITERS} byte-identical repeat invocations of ONE probe, on the recording \
hardware and under the pinned toolchain ({}). Not a source-level determinism \
argument, and not evidence about other inputs, OTHER PARAMETER CONFIGURATIONS \
(one probe fixes one; branches such as causal/softcap/window go untaken), \
other machines, or other compilers.]",
pinned_toolchain()
)
}
fn pinned_toolchain() -> String {
let f = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../rust-toolchain.toml");
let text = std::fs::read_to_string(&f)
.unwrap_or_else(|e| panic!("the clause must name a pinned toolchain; read {f:?}: {e}"));
parse_pinned_channel(&text).unwrap_or_else(|| {
panic!("no `channel` in {f:?}; refusing to emit a clause that names no toolchain")
})
}
fn parse_pinned_channel(text: &str) -> Option<String> {
for line in text.lines() {
if let Some(rest) = line.split_once("channel")
&& let Some(v) = rest.1.split('"').nth(1)
{
return Some(format!("rust-toolchain.toml channel = {v}"));
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_toolchain_guard_refuses_a_file_with_no_channel() {
assert_eq!(
parse_pinned_channel(
"[toolchain]
channel = \"1.98.0\"
"
)
.as_deref(),
Some("rust-toolchain.toml channel = 1.98.0"),
"a real pin file must parse, or every emission breaks"
);
assert_eq!(
parse_pinned_channel(
"[toolchain]
components = [\"rustfmt\"]
"
),
None,
"a file with no channel must REFUSE — emitting a clause that names no toolchain is worse than emitting none, because a checkout without the pin resolves to the box default and the clause would be confidently wrong"
);
assert_eq!(
parse_pinned_channel(""),
None,
"an empty file must refuse too"
);
}
#[test]
#[ignore = "rewrites docs/kernel-contracts/cpu/*.fkc.md; run manually via `cargo test -p fuel-dispatch gap_228_flip -- --ignored --nocapture`"]
fn gap_228_flip_fully_backed_sections() {
let dir =
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../docs/kernel-contracts/cpu");
let ledger = VerificationLedger::embedded();
let unaudited_notes = PrecisionGuarantee::UNAUDITED.notes;
let clause = evidence_clause();
let mut flippable: Vec<(String, Vec<String>)> = Vec::new();
let mut files: Vec<(std::path::PathBuf, String)> = Vec::new();
for e in std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("read {dir:?}: {e}")) {
let path = e.expect("dir entry").path();
if path.extension().and_then(|x| x.to_str()) != Some("md") {
continue;
}
let Ok(text) = std::fs::read_to_string(&path) else {
continue;
};
let name = path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or_default()
.to_string();
files.push((path.clone(), text.clone()));
let Ok(provider) = crate::fkc::import_bundle_str(&text, &crate::fkc::CpuLinkRegistry)
else {
continue;
};
let mut table = crate::kernel::KernelBindingTable::new();
let mut fused = crate::fused::FusedKernelRegistry::new();
if provider.register_into(&mut table, &mut fused).is_err() {
continue;
}
let mut per_op: Vec<(String, (usize, usize))> = Vec::new();
for (op, dtypes, backend, entry) in table.iter_entries() {
if entry.precision.notes != unaudited_notes {
continue;
}
let backed = ledger.has_pass(
backend,
dtypes,
entry.kernel_revision_hash,
"bit_stable_on_same_hardware",
);
let k = format!("{op:?}");
match per_op.iter_mut().find(|(n, _)| *n == k) {
Some((_, (b, u))) => {
if backed {
*b += 1
} else {
*u += 1
}
}
None => per_op.push((k, if backed { (1, 0) } else { (0, 1) })),
}
}
let ops: Vec<String> = per_op
.into_iter()
.filter(|(_, (_, u))| *u == 0)
.map(|(k, _)| k)
.collect();
if !ops.is_empty() {
flippable.push((name, ops));
}
}
let mut flipped = 0usize;
for (path, text) in &files {
let name = path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or_default()
.to_string();
let empty_ops: Vec<String> = Vec::new();
let ops = match flippable.iter().find(|(n, _)| *n == name) {
Some((_, o)) => o,
None if text.contains("[evidence: bit_stable_on_same_hardware") => &empty_ops,
None => continue,
};
let lines: Vec<&str> = text.lines().collect();
let mut out: Vec<String> = Vec::with_capacity(lines.len());
let mut starts: Vec<usize> = Vec::new();
for (i, l) in lines.iter().enumerate() {
if l.starts_with("## ") {
starts.push(i);
}
}
let mut section_of = vec![usize::MAX; lines.len()];
for (si, &st) in starts.iter().enumerate() {
let en = starts.get(si + 1).copied().unwrap_or(lines.len());
for x in section_of.iter_mut().take(en).skip(st) {
*x = si;
}
}
let mut section_flip = vec![false; starts.len()];
for (i, l) in lines.iter().enumerate() {
let t = l.trim();
if let Some(rest) = t.strip_prefix("op_kind:") {
let op = rest.split('#').next().unwrap_or("").trim();
if ops.iter().any(|o| o == op) && section_of[i] != usize::MAX {
section_flip[section_of[i]] = true;
}
}
}
let mut has_clause = vec![false; starts.len().max(1)];
for (i, l) in lines.iter().enumerate() {
if l.contains("[evidence: bit_stable_on_same_hardware")
&& section_of[i] != usize::MAX
{
has_clause[section_of[i]] = true;
}
}
let mut flipped_sections = vec![false; starts.len().max(1)];
let mut changed = false;
for (i, l) in lines.iter().enumerate() {
let sec = section_of[i];
let in_flip = sec != usize::MAX && (section_flip[sec] || has_clause[sec]);
let t = l.trim_start();
if in_flip && t.starts_with("audited: false") {
let indent = &l[..l.len() - t.len()];
out.push(format!("{indent}audited: true"));
if sec != usize::MAX {
flipped_sections[sec] = true;
}
changed = true;
flipped += 1;
} else if in_flip
&& t.starts_with("notes:")
&& sec != usize::MAX
&& (flipped_sections[sec] || has_clause[sec])
{
let mut base = l.to_string();
if let Some(start) = base.find("[evidence: bit_stable_on_same_hardware")
&& let Some(rel_end) = base[start..].find(']')
{
let end = start + rel_end + 1;
let cut_from = if start > 0 && base.as_bytes()[start - 1] == b' ' {
start - 1
} else {
start
};
base.replace_range(cut_from..end, "");
}
if let Some(last) = base.rfind('"') {
base.insert_str(last, &format!(" {clause}"));
}
out.push(base);
} else {
out.push(l.to_string());
}
}
let refreshed = out.join(
"
",
) != lines.join(
"
",
);
if changed || refreshed {
let mut joined = out.join("\n");
if text.ends_with('\n') {
joined.push('\n');
}
std::fs::write(path, joined).unwrap_or_else(|e| panic!("write {path:?}: {e}"));
println!("[gap-228] rewrote {name}");
}
}
println!(
"[gap-228] flipped {flipped} `audited:` line(s) across {} file(s)",
files.len()
);
println!("[gap-228] clause in use: {}", evidence_clause());
println!("[gap-228] (0 flips is expected on a re-emission run)");
}
#[test]
fn every_unflipped_cpu_section_declares_no_ulp_bound() {
let dir =
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../docs/kernel-contracts/cpu");
let mut unflipped = 0usize;
let mut describe_only = 0usize;
let mut declares_a_bound: Vec<String> = Vec::new();
let mut bounded_elsewhere = 0usize;
let mut files = 0usize;
let entries =
std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("cannot read {dir:?}: {e}"));
for entry in entries {
let path = entry.expect("dir entry").path();
if path.extension().and_then(|e| e.to_str()) != Some("md") {
continue;
}
files += 1;
let src = std::fs::read_to_string(&path)
.unwrap_or_else(|e| panic!("cannot read {path:?}: {e}"));
let lines: Vec<&str> = src.lines().collect();
let starts: Vec<usize> = lines
.iter()
.enumerate()
.filter(|(_, l)| l.starts_with("## "))
.map(|(i, _)| i)
.collect();
for (si, &i) in starts.iter().enumerate() {
let end = starts.get(si + 1).copied().unwrap_or(lines.len());
let body = &lines[i..end];
let field = |key: &str| -> Option<String> {
body.iter().find_map(|l| {
let t = l.trim_start();
t.strip_prefix(key).map(|v| {
v.split('#').next().unwrap_or("").trim().to_string()
})
})
};
let audited = field("audited:");
let max_ulp = field("max_ulp:");
let name = lines[i][3..].split(" ").next().unwrap_or("?").trim();
if audited.as_deref() == Some("false") {
unflipped += 1;
if field("registrable:").as_deref() == Some("false") {
describe_only += 1;
}
match max_ulp.as_deref() {
Some("~") | None => {}
Some(v) => declares_a_bound.push(format!("{name}: max_ulp: {v}")),
}
} else if matches!(max_ulp.as_deref(), Some(v) if v != "~") {
bounded_elsewhere += 1;
}
}
}
assert!(
files >= 5 && unflipped > 0,
"read {files} contract files and found {unflipped} unflipped sections — the \
census is looking in the wrong place and would pass vacuously"
);
assert!(
bounded_elsewhere > 0,
"no CPU contract section anywhere declares a non-`~` max_ulp, so the \
assertion below is true of nothing and this census cannot discriminate"
);
println!(
"[gap-228] unflipped CPU sections: {unflipped} ({describe_only} describe-only, \
{} registrable); sections declaring a bound elsewhere: {bounded_elsewhere}",
unflipped - describe_only
);
assert!(
declares_a_bound.is_empty(),
"these unflipped sections DECLARE a ulp bound, so they need an exact \
reference and therefore a semantics ruling before they can be earned: \
{declares_a_bound:?}. Everything else in the residue needs only \
bit-stability and is reachable on the conv pattern with no ruling at all."
);
assert_eq!(
describe_only, 2,
"expected exactly 2 `registrable: false` describe-only sections among the \
unflipped ones (the elementwise-unary and inplace-unary-affine chassis \
umbrellas). They bind no OpKind and contribute ZERO entries, which is why \
42 sections correspond to 60 entries and not to 63."
);
}
#[test]
fn the_pins_this_harness_rests_on_are_still_present() {
const REQUIRED_PINS: &[(&str, &str, &str)] = &[
(
"seed_cpu_ledger.rs",
"nothing, 0,",
"the count of contract entries still declaring NO precision claim \
(GAP-226/228). Without it, a regression that un-earns entries reads \
as a pass.",
),
(
"seed_cpu_ledger.rs",
"expected all 623 contract-derived entries backed WITHOUT the fill",
"the count backed by contract + record rather than by \
`fill_unset_cpu_precision`. This is the number the whole program \
exists to move; unpinned, the fill could come back unnoticed.",
),
(
"seed_cpu_ledger.rs",
"expected 20 conv registrations to invoke",
"the conv registrations that must actually invoke (GAP-228(b)). \
Without it, a probe that stops building leaves the loop covering \
fewer ops and still reporting no constant output.",
),
(
"seed_cpu_ledger.rs",
"Under the old remainder",
"the assertion that every sweep outcome lands in a NAMED bucket. Its predecessor was `x + (L - x) == L`, which could not fail, while its catch-all was printed to the reader as an invoke error.",
),
(
"seed_cpu_ledger.rs",
"must not merge",
"the guard that a harness gap (no recipe written) and a verifier result (no reference available) never share a bucket again. They did, through a shared `starts_with` prefix.",
),
(
"seed_cpu_ledger.rs",
"is the IDENTITY",
"the guard that PagedAttn's block table is non-degenerate. An identity \
table is IN RANGE and silent, and a kernel ignoring block_table \
entirely would return byte-identical output under it.",
),
(
"seed_cpu_ledger.rs",
"the q-shaped and kv-shaped output classes are the SAME SIZE",
"the guard that the backward fixture separates the two output-shape \
classes. It is the axis the three backward OpKinds are collapsed onto \
ONE arm for, and the sweep passed 24/24 against a fixture where the \
two classes were the same size.",
),
(
"seed_cpu_ledger.rs",
"expected 8 FlashAttn registrations to invoke",
"the FlashAttn probes that must reach their kernel AND carry `k_len < sk` with a non-zero causal offset. Without it the family's records could silently become evidence about the static path only.",
),
(
"seed_cpu_ledger.rs",
"expected 20 registrations across the four small surfaces",
"the four small non-conv surfaces that must demonstrably reach their kernel (GAP-228(c)). Without it, a probe that stops building leaves the loop checking fewer ops and still reporting none inert.",
),
(
"seed_cpu_ledger.rs",
"families_tested, EXACT_REFERENCE_FAMILIES",
"the exact-reference families the attachment control actually \
poisoned. Without it, a family that stops passing is skipped with \
a println and the control silently covers less.",
),
];
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/fkc/verify");
let mut missing: Vec<String> = Vec::new();
let mut duplicated: Vec<String> = Vec::new();
let mut total_bytes = 0usize;
for (file, anchor, why) in REQUIRED_PINS {
let path = dir.join(file);
let src = std::fs::read_to_string(&path)
.unwrap_or_else(|e| panic!("cannot read {path:?}: {e}"));
total_bytes += src.len();
match src.matches(anchor).count() {
0 => missing.push(format!("{file}: `{anchor}` — {why}")),
1 => {}
n => duplicated.push(format!("{file}: `{anchor}` appears {n} times")),
}
}
assert!(
total_bytes > 10_000,
"read only {total_bytes} bytes across the pinned files — the scan is \
looking in the wrong place"
);
let probe = std::fs::read_to_string(dir.join("seed_cpu_ledger.rs")).expect("readable");
let absent = format!("nothing, {},", u32::MAX);
assert!(
!probe.contains(&absent),
"the absence predicate is broken: it finds `{absent}`, which is not in the file, so every pin below would report present no matter what"
);
assert!(
duplicated.is_empty(),
"these pins are ambiguous, so a deletion of one copy would go unnoticed: \
{duplicated:?}"
);
assert!(
missing.is_empty(),
"THESE PINS HAVE BEEN DELETED, AND THEIR GATES NOW PASS WITHOUT THEM:\n {}\n\
A wrong value is compared and fails; a deleted value is never compared \
at all. Restore the line, or remove its entry from REQUIRED_PINS in the \
same change and say why it is no longer load-bearing.",
missing.join("\n ")
);
}
#[test]
#[ignore = "planning measurement for GAP-228; run manually with --ignored --nocapture"]
fn gap_228_which_sections_are_wholesale_flippable() {
let dir =
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../docs/kernel-contracts/cpu");
let ledger = VerificationLedger::embedded();
let unaudited_notes = PrecisionGuarantee::UNAUDITED.notes;
let mut per_section: Vec<((String, String), (usize, usize))> = Vec::new();
for e in std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("read {dir:?}: {e}")) {
let path = e.expect("dir entry").path();
if path.extension().and_then(|x| x.to_str()) != Some("md") {
continue;
}
let name = path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or_default()
.to_string();
let Ok(text) = std::fs::read_to_string(&path) else {
continue;
};
let Ok(provider) = crate::fkc::import_bundle_str(&text, &crate::fkc::CpuLinkRegistry)
else {
continue;
};
let mut table = crate::kernel::KernelBindingTable::new();
let mut fused = crate::fused::FusedKernelRegistry::new();
if provider.register_into(&mut table, &mut fused).is_err() {
continue;
}
for (op, dtypes, backend, entry) in table.iter_entries() {
if entry.precision.notes != unaudited_notes {
continue;
}
let backed = ledger.has_pass(
backend,
dtypes,
entry.kernel_revision_hash,
"bit_stable_on_same_hardware",
);
let key = (name.clone(), format!("{op:?}"));
match per_section.iter_mut().find(|(k, _)| *k == key) {
Some((_, (b, u))) => {
if backed {
*b += 1
} else {
*u += 1
}
}
None => per_section.push((key, if backed { (1, 0) } else { (0, 1) })),
}
}
}
per_section.sort();
let (mut full, mut partial, mut none_) = (0usize, 0usize, 0usize);
let (mut full_e, mut partial_e, mut none_e) = (0usize, 0usize, 0usize);
println!("[gap-228] sections with UNAUDITED entries, by backing:");
for ((file, op), (b, u)) in &per_section {
let tag = if *u == 0 {
full += 1;
full_e += b;
"FULLY BACKED (flippable)"
} else if *b == 0 {
none_ += 1;
none_e += u;
"UNBACKED (leave)"
} else {
partial += 1;
partial_e += b + u;
"PARTLY BACKED (DO NOT flip wholesale)"
};
println!("[gap-228] {tag} {file} {op} backed={b} unbacked={u}");
}
println!("[gap-228] SECTIONS: {full} fully backed / {partial} partly / {none_} unbacked");
println!(
"[gap-228] ENTRIES : {full_e} in fully-backed sections / {partial_e} in partly / {none_e} in unbacked"
);
println!(
"[gap-228] PRE-DECLARED DELTA for the flip: UNAUDITED must drop by exactly {full_e}"
);
}
}