weirflow 0.1.0

GPU-first dataflow analysis primitives for Vyre and Santh compiler pipelines.
Documentation
//! Source-level contracts for Weir's GPU byte ABI boundary.
//!
//! GPU dispatch inputs and outputs are untrusted byte buffers. The shared
//! `dispatch_decode` module is the single ABI choke point: it owns packing,
//! exact-length output decoding, output-count validation, bitset-tail checks,
//! and staging-buffer reuse. Production modules may build higher-level IFDS
//! adapters, but they must not grow new hand-rolled byte parsers.

use std::fs;
use std::path::{Path, PathBuf};

const RAW_U32_DECODE_TOKENS: &[&str] = &[
    "u32::from_le_bytes(",
    ".chunks_exact(4)",
    ".chunks_exact(std::mem::size_of::<u32>())",
];

const RAW_U32_PACK_TOKEN: &str = ".to_le_bytes()";

const CENTRAL_ABI_DIR: &str = "src/dispatch_decode/";
const FRONTIER_ADAPTER: &str = "src/ifds_frontier_decode.rs";
const IFDS_BYTE_ADAPTER: &str = "src/ifds_gpu_bytes.rs";

const NON_GPU_STABLE_ENDIAN_EXCEPTIONS: &[&str] = &[
    "src/fixed_point_execution_plan_cache.rs",
    "src/graph_layout.rs",
    "src/ifds_resident_direct_batch/sizing.rs",
    "src/ifds_resident_types/hash.rs",
];

#[test]
fn gpu_u32_byte_abi_has_one_choke_point() {
    let mut violations = Vec::new();
    for path in rust_sources(Path::new("src")) {
        let relative = normalize(&path);
        if is_test_source(&relative) || relative.ends_with("/cpu_oracle.rs") {
            continue;
        }

        let source = fs::read_to_string(&path).unwrap_or_else(|error| {
            panic!("failed to read {relative}: {error}");
        });
        let production_source = production_only(&source);

        if relative.starts_with(CENTRAL_ABI_DIR)
            || relative == FRONTIER_ADAPTER
            || relative == IFDS_BYTE_ADAPTER
            || NON_GPU_STABLE_ENDIAN_EXCEPTIONS.contains(&relative.as_str())
        {
            continue;
        }

        for token in RAW_U32_DECODE_TOKENS {
            if production_source.contains(token) {
                violations.push(format!("{relative} contains raw byte token `{token}`"));
            }
        }
    }

    assert!(
        violations.is_empty(),
        "GPU-facing u32 byte ABI must route through dispatch_decode or an explicitly reviewed adapter:\n{}",
        violations.join("\n")
    );
}

#[test]
fn ifds_byte_adapter_is_only_a_staging_wrapper() {
    let source = read(IFDS_BYTE_ADAPTER);

    for required in [
        "crate::dispatch_decode::try_write_zero_bytes",
        "crate::dispatch_decode::try_pack_u32_into",
        "crate::staging_reserve::ensure_vec_slots_at_least",
    ] {
        assert!(
            source.contains(required),
            "{IFDS_BYTE_ADAPTER} must delegate byte staging to {required}"
        );
    }

    for forbidden in RAW_U32_DECODE_TOKENS {
        assert!(
            !source.contains(forbidden),
            "{IFDS_BYTE_ADAPTER} must not hand-roll u32 ABI conversion with `{forbidden}`"
        );
    }
    assert!(
        !source.contains(RAW_U32_PACK_TOKEN),
        "{IFDS_BYTE_ADAPTER} must pack through dispatch_decode, not hand-roll {RAW_U32_PACK_TOKEN}"
    );
}

#[test]
fn frontier_decoder_exception_is_narrow_and_validated() {
    let source = read(FRONTIER_ADAPTER);

    for required in [
        "crate::dispatch_decode::bitset_word_capacity",
        "crate::dispatch_decode::u32_to_usize",
        "require_bitset_tail_clear_le_bytes",
        "dense_to_encoded",
    ] {
        assert!(
            source.contains(required),
            "{FRONTIER_ADAPTER} must keep frontier decoding coupled to shared validation and encoded-node mapping: missing {required}"
        );
    }

    for forbidden in [
        "VyreBackend",
        "DispatchConfig",
        "ProgramBuilder",
        "Vec<Vec<u8>>",
    ] {
        assert!(
            !source.contains(forbidden),
            "{FRONTIER_ADAPTER} is only a typed frontier decoder, not a dispatch implementation; found {forbidden}"
        );
    }
}

#[test]
fn non_gpu_little_endian_exceptions_are_stable_fingerprints_only() {
    for relative in NON_GPU_STABLE_ENDIAN_EXCEPTIONS {
        let source = read(relative);
        let production_source = production_only(&source);
        assert!(
            production_source.contains(".to_le_bytes()"),
            "{relative} is listed as a stable-endian exception but no longer uses little-endian byte mixing"
        );
        for forbidden in ["u32::from_le_bytes(", ".chunks_exact(4)", "Vec<Vec<u8>>"] {
            assert!(
                !production_source.contains(forbidden),
                "{relative} is allowed only for stable fingerprint mixing, not dispatch ABI parsing; found {forbidden}"
            );
        }
    }
}

#[test]
fn dispatch_decode_owns_adversarial_abi_tests() {
    let unpack = read("src/dispatch_decode/unpack.rs");
    let pack = read("src/dispatch_decode/pack.rs");

    for required in ["short", "trailing", "missing", "extra", "tail", "target"] {
        assert!(
            unpack.contains(required),
            "dispatch_decode unpack tests must cover adversarial ABI condition containing {required}"
        );
    }

    for required in ["reserve", "capacity", "zero", "resize"] {
        assert!(
            pack.contains(required),
            "dispatch_decode pack tests must cover staging allocation condition containing {required}"
        );
    }
}

fn read(relative: &str) -> String {
    fs::read_to_string(relative)
        .unwrap_or_else(|error| panic!("failed to read {relative}: {error}"))
}

fn rust_sources(root: &Path) -> Vec<PathBuf> {
    let mut out = Vec::new();
    collect_rust_sources(root, &mut out);
    out.sort();
    out
}

fn collect_rust_sources(dir: &Path, out: &mut Vec<PathBuf>) {
    for entry in fs::read_dir(dir).unwrap_or_else(|error| {
        panic!("failed to read directory {}: {error}", dir.display());
    }) {
        let entry = entry.unwrap_or_else(|error| panic!("failed to read directory entry: {error}"));
        let path = entry.path();
        if path.is_dir() {
            collect_rust_sources(&path, out);
        } else if path.extension().is_some_and(|extension| extension == "rs") {
            out.push(path);
        }
    }
}

fn normalize(path: &Path) -> String {
    path.components()
        .map(|component| component.as_os_str().to_string_lossy())
        .collect::<Vec<_>>()
        .join("/")
}

fn is_test_source(relative: &str) -> bool {
    relative.contains("/tests/")
        || relative.contains("_tests/")
        || relative.ends_with("/tests.rs")
        || relative.ends_with("_tests.rs")
}

fn production_only(source: &str) -> &str {
    source.split("#[cfg(test)]").next().unwrap_or(source)
}