ghast-physics 0.5.4

Vanilla-exact, pure and deterministic player movement for the ghast Minecraft Java Edition client library (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3), verified bit for bit against the real game
Documentation
//! Large-fuzz replay: every `*.jsonl.gz` in `oracle/cache/1.8.9/fuzz/`, `oracle/cache/1.8.9/fuzz-edges/`, `oracle/cache/1.8.9/fuzz-void/`, `oracle/cache/1.8.9/fuzz-boats/`, `oracle/cache/1.8.9/fuzz-minecarts/`, `oracle/cache/1.8.9/fuzz-mounts/`, `oracle/cache/1.8.9/fuzz-mount-boards/`, `oracle/cache/1.8.9/fuzz-pistons/`,
//! `oracle/cache/1.16.5/fuzz{,-edges,-extras,-entities,-nether,-riptide,-elytra,-boats,-boat-seats,-minecarts,-mounts,-mount-boards,-pistons}/`, `oracle/cache/1.12.2/fuzz{,-edges,-extras,-entities,-elytra,-boats,-boat-seats,-minecarts,-pistons}/`, the 26.1, 26.2 and 26.3 directories (or the file / directory in `GHAST_FUZZ`) produced by
//! `oracle/run.sh fuzz`, compared bit for bit. The version is taken from the path. The files
//! run on at most `GHAST_FUZZ_THREADS` worker threads (default: the available parallelism).
//!
//! Not here: the 1.12.2 living-mount cache (`oracle/cache/1.12.2/fuzz-mounts/`) has its own
//! replay, `mounts_cache_1_12_2` in `tests/mounts_1_12_2.rs`; `GHAST_FUZZ` pointed at it panics
//! on its `vehicle spawn` events.
//!
//! Needs the git-ignored oracle cache, so it is behind the `oracle-cache` feature:
//!
//! ```sh
//! oracle/run.sh fuzz --seed 11 --count 2000 --ticks 100 --out "$PWD/oracle/cache/1.8.9/fuzz/s11.jsonl.gz"
//! cargo test --release -p ghast-physics --features oracle-cache --test fuzz_cache -- --nocapture
//! ```
#![cfg(feature = "oracle-cache")]
#![recursion_limit = "256"]

mod common;

use std::collections::BTreeMap;
use std::path::PathBuf;

#[cfg(feature = "v1_8")]
use common::replay_file;
use common::{Summary, repo_root};

fn inputs() -> Vec<PathBuf> {
    let specs = match std::env::var("GHAST_FUZZ") {
        Ok(s) => vec![PathBuf::from(s)],
        Err(_) => vec![
            repo_root().join("oracle/cache/1.8.9/fuzz"),
            repo_root().join("oracle/cache/1.8.9/fuzz-edges"),
            repo_root().join("oracle/cache/1.8.9/fuzz-extras"),
            repo_root().join("oracle/cache/1.8.9/fuzz-void"),
            repo_root().join("oracle/cache/1.8.9/fuzz-boats"),
            repo_root().join("oracle/cache/1.8.9/fuzz-minecarts"),
            repo_root().join("oracle/cache/1.8.9/fuzz-mounts"),
            repo_root().join("oracle/cache/1.8.9/fuzz-mount-boards"),
            repo_root().join("oracle/cache/1.8.9/fuzz-pistons"),
            repo_root().join("oracle/cache/1.16.5/fuzz"),
            repo_root().join("oracle/cache/1.16.5/fuzz-edges"),
            repo_root().join("oracle/cache/1.16.5/fuzz-extras"),
            repo_root().join("oracle/cache/1.16.5/fuzz-entities"),
            repo_root().join("oracle/cache/1.16.5/fuzz-nether"),
            repo_root().join("oracle/cache/1.16.5/fuzz-riptide"),
            repo_root().join("oracle/cache/1.16.5/fuzz-elytra"),
            repo_root().join("oracle/cache/1.16.5/fuzz-boats"),
            repo_root().join("oracle/cache/1.16.5/fuzz-boat-seats"),
            repo_root().join("oracle/cache/1.16.5/fuzz-minecarts"),
            repo_root().join("oracle/cache/1.16.5/fuzz-mounts"),
            repo_root().join("oracle/cache/1.16.5/fuzz-mount-boards"),
            repo_root().join("oracle/cache/1.16.5/fuzz-pistons"),
            repo_root().join("oracle/cache/1.12.2/fuzz"),
            repo_root().join("oracle/cache/1.12.2/fuzz-edges"),
            repo_root().join("oracle/cache/1.12.2/fuzz-extras"),
            repo_root().join("oracle/cache/1.12.2/fuzz-entities"),
            repo_root().join("oracle/cache/1.12.2/fuzz-elytra"),
            repo_root().join("oracle/cache/1.12.2/fuzz-boats"),
            repo_root().join("oracle/cache/1.12.2/fuzz-boat-seats"),
            repo_root().join("oracle/cache/1.12.2/fuzz-minecarts"),
            repo_root().join("oracle/cache/1.12.2/fuzz-pistons"),
            repo_root().join("oracle/cache/26.1/fuzz"),
            repo_root().join("oracle/cache/26.1/fuzz-edges"),
            repo_root().join("oracle/cache/26.1/fuzz-extras"),
            repo_root().join("oracle/cache/26.1/fuzz-teleports"),
            repo_root().join("oracle/cache/26.1/fuzz-elytra"),
            repo_root().join("oracle/cache/26.1/fuzz-riptide"),
            repo_root().join("oracle/cache/26.1/fuzz-entities"),
            repo_root().join("oracle/cache/26.1/fuzz-nether"),
            repo_root().join("oracle/cache/26.1/fuzz-border"),
            repo_root().join("oracle/cache/26.1/fuzz-boats"),
            repo_root().join("oracle/cache/26.1/fuzz-minecarts"),
            repo_root().join("oracle/cache/26.1/fuzz-mounts"),
            repo_root().join("oracle/cache/26.1/fuzz-mounts-ghast"),
            repo_root().join("oracle/cache/26.1/fuzz-mounts-nautilus"),
            repo_root().join("oracle/cache/26.1/fuzz-mounts-steer"),
            repo_root().join("oracle/cache/26.1/fuzz-mounts-camel"),
            repo_root().join("oracle/cache/26.1/fuzz-mounts-seat"),
            repo_root().join("oracle/cache/26.1/fuzz-boats-seat"),
            repo_root().join("oracle/cache/26.1/fuzz-pistons"),
            repo_root().join("oracle/cache/26.2/fuzz"),
            repo_root().join("oracle/cache/26.2/fuzz-edges"),
            repo_root().join("oracle/cache/26.2/fuzz-extras"),
            repo_root().join("oracle/cache/26.2/fuzz-restitution"),
            repo_root().join("oracle/cache/26.2/fuzz-teleports"),
            repo_root().join("oracle/cache/26.2/fuzz-elytra"),
            repo_root().join("oracle/cache/26.2/fuzz-riptide"),
            repo_root().join("oracle/cache/26.2/fuzz-entities"),
            repo_root().join("oracle/cache/26.2/fuzz-nether"),
            repo_root().join("oracle/cache/26.2/fuzz-border"),
            repo_root().join("oracle/cache/26.2/fuzz-boats"),
            repo_root().join("oracle/cache/26.2/fuzz-minecarts"),
            repo_root().join("oracle/cache/26.2/fuzz-mounts"),
            repo_root().join("oracle/cache/26.2/fuzz-mounts-ghast"),
            repo_root().join("oracle/cache/26.2/fuzz-mounts-nautilus"),
            repo_root().join("oracle/cache/26.2/fuzz-mounts-steer"),
            repo_root().join("oracle/cache/26.2/fuzz-mounts-camel"),
            repo_root().join("oracle/cache/26.2/fuzz-mounts-seat"),
            repo_root().join("oracle/cache/26.2/fuzz-boats-seat"),
            repo_root().join("oracle/cache/26.2/fuzz-pistons"),
            repo_root().join("oracle/cache/26.3/fuzz"),
            repo_root().join("oracle/cache/26.3/fuzz-edges"),
            repo_root().join("oracle/cache/26.3/fuzz-extras"),
            repo_root().join("oracle/cache/26.3/fuzz-restitution"),
            repo_root().join("oracle/cache/26.3/fuzz-teleports"),
            repo_root().join("oracle/cache/26.3/fuzz-elytra"),
            repo_root().join("oracle/cache/26.3/fuzz-riptide"),
            repo_root().join("oracle/cache/26.3/fuzz-entities"),
            repo_root().join("oracle/cache/26.3/fuzz-nether"),
            repo_root().join("oracle/cache/26.3/fuzz-border"),
            repo_root().join("oracle/cache/26.3/fuzz-boats"),
            repo_root().join("oracle/cache/26.3/fuzz-minecarts"),
            repo_root().join("oracle/cache/26.3/fuzz-mounts"),
            repo_root().join("oracle/cache/26.3/fuzz-mounts-ghast"),
            repo_root().join("oracle/cache/26.3/fuzz-mounts-nautilus"),
            repo_root().join("oracle/cache/26.3/fuzz-mounts-steer"),
            repo_root().join("oracle/cache/26.3/fuzz-mounts-camel"),
            repo_root().join("oracle/cache/26.3/fuzz-mounts-seat"),
            repo_root().join("oracle/cache/26.3/fuzz-boats-seat"),
            repo_root().join("oracle/cache/26.3/fuzz-pistons"),
        ],
    };
    let mut files = Vec::new();
    for spec in specs {
        if spec.is_file() {
            files.push(spec);
            continue;
        }
        let Ok(dir) = std::fs::read_dir(&spec) else {
            continue;
        };
        files.extend(
            dir.filter_map(|e| e.ok().map(|e| e.path()))
                .filter(|p| p.to_string_lossy().ends_with(".jsonl.gz")),
        );
    }
    files.sort();
    files
}

/// Patch releases checked against a row (`harness.label` in `oracle/versions/<mc>.properties`)
/// replay with that row's rules: `oracle/cache/1.16.4/...` is read as a 1.16.5 file.
fn row_path(path: &std::path::Path) -> String {
    const ROWS: &[(&str, &str)] = &[
        ("/1.16.2/", "/1.16.5/"),
        ("/1.16.3/", "/1.16.5/"),
        ("/1.16.4/", "/1.16.5/"),
        ("/1.12.1/", "/1.12.2/"),
    ];
    let mut name = path.to_string_lossy().into_owned();
    for (sub, row) in ROWS {
        name = name.replace(sub, row);
    }
    name
}

fn replay_any(path: &std::path::Path) -> Summary {
    let name = row_path(path);
    #[cfg(all(feature = "v26_1", feature = "v26_3"))]
    if name.contains("fuzz-pistons") && name.contains("26.3") {
        let p = common::pistons26::replay_file_26_3(path);
        eprintln!(
            "{}: {} cut at another entity, {} with a push",
            path.file_name().unwrap().to_string_lossy(),
            p.cut,
            p.pushed
        );
        return Summary {
            cases: p.cases,
            ticks: p.ticks,
            failures: p.failures,
        };
    }
    #[cfg(all(feature = "v26_1", feature = "v26_3"))]
    if name.contains("26.3") {
        return common::v261::replay_file_with::<ghast_physics::modern::V26_3>(path);
    }
    #[cfg(feature = "v26_1")]
    if name.contains("fuzz-pistons") && (name.contains("26.1") || name.contains("26.2")) {
        #[cfg(feature = "v26_2")]
        let p = if name.contains("26.2") {
            common::pistons26::replay_file_26_2(path)
        } else {
            common::pistons26::replay_file_26_1(path)
        };
        #[cfg(not(feature = "v26_2"))]
        let p = common::pistons26::replay_file_26_1(path);
        eprintln!(
            "{}: {} cut at another entity, {} with a push",
            path.file_name().unwrap().to_string_lossy(),
            p.cut,
            p.pushed
        );
        return Summary {
            cases: p.cases,
            ticks: p.ticks,
            failures: p.failures,
        };
    }
    #[cfg(all(feature = "v26_1", feature = "v26_2"))]
    if name.contains("26.2") {
        return common::v261::replay_file_with::<ghast_physics::modern::V26_2>(path);
    }
    #[cfg(feature = "v26_1")]
    if name.contains("26.1") {
        return common::v261::replay_file(path);
    }
    #[cfg(feature = "v1_16_5")]
    if name.contains("1.16.5") {
        return common::v116::replay_file(path);
    }
    #[cfg(feature = "v1_12")]
    if name.contains("1.12.2") {
        return common::v112::replay_file(path);
    }
    #[cfg(feature = "v1_8")]
    if !["26.1", "26.2", "26.3", "1.16.5", "1.12.2"]
        .iter()
        .any(|v| name.contains(v))
    {
        return replay_file(path);
    }
    panic!("{name}: its version feature is off")
}

/// Worker threads for the replay: `GHAST_FUZZ_THREADS` (at least 1), by default the available
/// parallelism, never more than there are files.
fn worker_count(files: usize) -> usize {
    let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
    let wanted = match std::env::var("GHAST_FUZZ_THREADS") {
        Ok(s) => s
            .trim()
            .parse::<usize>()
            .unwrap_or_else(|_| panic!("GHAST_FUZZ_THREADS={s:?} is not a number"))
            .max(1),
        Err(_) => cores,
    };
    wanted.min(files).max(1)
}

/// Replays every file on a bounded pool of workers that take the next file from a shared index
/// (each file is still streamed case by case); the results come back in the files' order.
fn replay_all(files: &[PathBuf]) -> Vec<(PathBuf, Summary)> {
    use std::sync::atomic::{AtomicUsize, Ordering};
    let next = AtomicUsize::new(0);
    let workers = worker_count(files.len());
    let mut done: Vec<(usize, Summary)> = std::thread::scope(|s| {
        let handles: Vec<_> = (0..workers)
            .map(|_| {
                s.spawn(|| {
                    let mut out = Vec::new();
                    loop {
                        let i = next.fetch_add(1, Ordering::Relaxed);
                        let Some(f) = files.get(i) else { break };
                        out.push((i, replay_any(f)));
                    }
                    out
                })
            })
            .collect();
        handles
            .into_iter()
            .flat_map(|h| h.join().unwrap())
            .collect()
    });
    done.sort_by_key(|(i, _)| *i);
    done.into_iter()
        .map(|(i, s)| (files[i].clone(), s))
        .collect()
}

#[test]
fn oracle_fuzz_cache() {
    let files = inputs();
    assert!(
        !files.is_empty(),
        "no fuzz files; run oracle/run.sh fuzz first"
    );
    let results = replay_all(&files);
    let (mut cases, mut ticks, mut failed) = (0, 0, 0);
    let mut by_field: BTreeMap<String, usize> = BTreeMap::new();
    for (path, s) in &results {
        eprintln!(
            "{}: {} cases, {} ticks matched, {} cases differ",
            path.file_name().unwrap().to_string_lossy(),
            s.cases,
            s.ticks,
            s.failures.len()
        );
        for f in s.failures.iter().take(5) {
            eprintln!("MISMATCH {f}");
        }
        for f in &s.failures {
            *by_field.entry(f.field.clone()).or_default() += 1;
        }
        cases += s.cases;
        ticks += s.ticks;
        failed += s.failures.len();
    }
    eprintln!("TOTAL: {cases} cases, {ticks} ticks matched, {failed} cases differ");
    for (field, n) in &by_field {
        eprintln!("  first differing field {field}: {n} cases");
    }
    assert_eq!(failed, 0, "{failed} fuzz cases differ from vanilla");
}