Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ For upcoming releases, reviewed staged archives and the documented source fallba
work before publication. The quality CLI remains a separate
source-built work in progress.

The Grill is a Rust CLI for Linux. Build and check the workspace with:
The Grill is a Rust CLI for Linux and macOS (Apple Silicon). Build and check the workspace with:

```sh
cargo build --workspace --locked
Expand All @@ -27,11 +27,13 @@ cargo clippy -p grill-perf --locked --all-targets -- -D warnings
```

Native `/proc`/cgroup/NVML resource capture and external-program microbench
capture remain Linux-only, as do the quality CLI's evidence storage, run
ownership locks and interrupt latch; on macOS those paths fail closed and their
tests are compiled for Linux only. The full workspace check list above also
builds and passes on Apple Silicon macOS. Its media adapter fixture runs
`python3` from `PATH`, which must be Python 3.12 (the macOS system 3.9 lacks
capture remain Linux-only. The quality CLI's evidence storage, run ownership
locks and interrupt latch run on Linux and macOS: on Apple platforms the
evidence flushes come from std `sync_all`, which issues `F_FULLFSYNC`, and
the offline and runner test suites are compiled
for all UNIX targets. The full workspace check list above also builds and
passes on Apple Silicon macOS. Its media adapter fixture runs `python3` from
`PATH`, which must be Python 3.12 (the macOS system 3.9 lacks
`importlib.metadata.entry_points` selection). macOS changes must not weaken
those Linux contracts.

Expand Down
5 changes: 3 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ reqwest = { version = "0.13", default-features = false, features = ["rustls"] }
# Current-thread runtime, deadlines, Unix signal latch and select!.
tokio = { version = "1", default-features = false, features = ["rt", "net", "time", "signal", "macros"] }

[target.'cfg(target_os = "linux")'.dependencies]
# Architecture-correct O_NOFOLLOW/O_NONBLOCK constants for evidence opens.
[target.'cfg(unix)'.dependencies]
# Platform constants for evidence opens (O_NOFOLLOW/O_NONBLOCK) and flock
# ownership.
libc = { version = "0.2", default-features = false }
4 changes: 2 additions & 2 deletions docs/PROJECT.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ A successful new view directory contains fixed names `pack.json` (exact input by

`View = {version, claim, identities, cases}` where `claim` is `"submitted-artifacts-not-verified-execution"` and `cases` is an ordered CaseGrade array. `CaseGrade = {case_id, input, artifact, evidence, outcome}`: `input` is the per-case input digest; `artifact` is a digest or null; `evidence` and `outcome` have the values above. Receipt IDs are not trusted: comparison requalifies the pack, validates the submission, recomputes all identities, artifacts and outcomes, and requires exact typed equality. A missing/malformed required file, hash mismatch or forged grade fails verification. A fully rewritten internally consistent submission/view remains submitted evidence, not forgery-proof execution.

Storage currently supports Linux local filesystems with ordinary file and parent-directory sync. Inputs, required snapshot entries and the final view directory must be nonsymlink regular files/directories as appropriate. The parent of `--out` must already exist and must itself be a nonsymlink directory. Required file opens use libc's architecture-specific `O_NOFOLLOW | O_NONBLOCK` constants to reject final-component symlinks and avoid hanging on FIFO substitution; opened files are then checked for regular-file type. Ancestor traversal is not a sandbox against concurrent parent replacement or a hostile filesystem.
Storage currently supports Linux and macOS local filesystems. Every file and directory sync goes through std `sync_all`, which issues `F_FULLFSYNC` on Apple platforms — plain `fsync` there only reaches the buffer cache and does not force data to disk. Inputs, required snapshot entries and the final view directory must be nonsymlink regular files/directories as appropriate. The parent of `--out` must already exist and must itself be a nonsymlink directory. Required file opens use libc's architecture-specific `O_NOFOLLOW | O_NONBLOCK` constants to reject final-component symlinks and avoid hanging on FIFO substitution; opened files are then checked for regular-file type. Ancestor traversal is not a sandbox against concurrent parent replacement or a hostile filesystem.

Publication exclusively creates a fresh directory (0700), synchronizes its parent, exclusively creates and syncs snapshots (0600), then syncs their directory before creating and syncing `.view.json.pending`. A no-clobber hard link publishes `view.json`; the staging link is removed and the view directory and parent are synced. Existing destinations are always refused. Failures leave the owned partial directory for inspection and never recursively delete it or unrelated data; final-sync failure may leave a visible receipt despite a nonzero exit. Absent `view.json` means no authoritative grading view. Extra unreferenced files are never read or promoted. There is no overwrite/resume/repair or power-loss/hostile-race/cross-platform durability guarantee. Move/copy all three required files together for relocation.

Expand Down Expand Up @@ -316,7 +316,7 @@ Execution state is independent of attempt exhaustion. A final-attempt interrupti

`grill resume RUN` accepts no changed endpoint, model, pack, protocol, or credential-variable selector. It re-admits the saved pack and plan, verifies request/response/terminal/artifact lineage and every historical session snapshot, and requires a contiguous terminal prefix followed only by never-started cases. Completed, failed, and interrupted terminal attempts are consumed, never retried. Reserved-but-unsettled attempts, unfinished sessions, changed evidence, foreign attempt names, and unsupported lifecycle versions fail closed. An unfinished session is refused even if its last attempt appears settled: no operator-accounting or repair switch is provided for native evidence. Original v1 runs without lifecycle sidecars remain inspectable and regradeable, but are not implicitly adopted for continuation.

Linux `flock` ownership is held on the original run directory descriptor for the whole collector/resumer lifetime. Kernel lock release on process exit avoids PID-reuse ownership guesses and stale lock-file deletion. A separate permanent `lifecycle/admission.lock` serializes short admission/control operations; there is no daemon, polling loop, retry scheduler, or signal sent by `pause`. Advisory locking coordinates these collectors, not a hostile writer replacing directory ancestors or bypassing the protocol.
`flock` ownership (Linux and macOS) is held on the original run directory descriptor for the whole collector/resumer lifetime. Kernel lock release on process exit avoids PID-reuse ownership guesses and stale lock-file deletion. A separate permanent `lifecycle/admission.lock` serializes short admission/control operations; there is no daemon, polling loop, retry scheduler, or signal sent by `pause`. Advisory locking coordinates these collectors, not a hostile writer replacing directory ancestors or bypassing the protocol.

New runs add `lifecycle/NNNNNN/start.json`, optional `pause.request` (the session-start digest), `view.json`, and `end.json`. Session starts bind version 1, the original plan digest, previous session-end digest, first attempt, time, PID, binary version and compiled lockfile digest. End receipts bind the start digest, next attempt, state, and exact session-view digest. Each session view preserves the full fixed denominator and is independently checked against the corresponding immutable evidence prefix. Files are no-clobber publications with directory synchronization; credentials never enter these records. The fixed ceiling is 1025 sessions, including the first; the advisory byte bound includes all session metadata and view ceilings. No timing continuity or warmed-client equivalence is claimed across sessions.

Expand Down
2 changes: 1 addition & 1 deletion licenses/NOTICE-INPUTS.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"cargo_lock_sha256": "98e8e77d419daffad29e3fcbb7dd6f5b137d5daa02076451d9791db212976543",
"manifest_sha256": {
"Cargo.toml": "d42fce6074b77852935ba2d9b82ea4f419f619a27c0aa8a815fb7bcb50c55a5d",
"Cargo.toml": "4db39089363e587d1694caaf0ca9fe2450a46ab64cf32c84d7c9f08692d84e55",
"crates/grill-perf/Cargo.toml": "10efcb4bf626a6bef07acf0bdbd7e508105e15f958e28cd7a000b6b734d82e14",
"crates/grill-sse/Cargo.toml": "5f6d34630cd32f54aae216f1b5996886e4865343a3d1421e4053ba9c21ccabb1"
},
Expand Down
40 changes: 19 additions & 21 deletions src/lifecycle.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
//! Cooperative admission control and immutable continuation sessions (Linux local filesystems).
//! Cooperative admission control and immutable continuation sessions (Linux and macOS local filesystems).
use crate::contract::*;
use crate::store::{self, AttemptState, Loaded};
use crate::{identity, record};
use serde::{Deserialize, Serialize};
#[cfg(target_os = "linux")]
#[cfg(unix)]
use std::fs::{File, OpenOptions};
#[cfg(target_os = "linux")]
#[cfg(unix)]
use std::os::fd::AsRawFd;
#[cfg(target_os = "linux")]
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};

const SESSION_CAP: usize = CASE_CAP + 1;
const META_CAP: usize = 8192;

#[cfg(target_os = "linux")]
#[cfg(unix)]
pub(crate) struct Lock(File);
#[cfg(target_os = "linux")]
#[cfg(unix)]
impl Lock {
pub fn run(root: &Path) -> Result<Self> {
let file = OpenOptions::new()
Expand Down Expand Up @@ -55,7 +55,7 @@ impl Lock {
Ok(Self(file))
}
}
#[cfg(target_os = "linux")]
#[cfg(unix)]
impl Drop for Lock {
fn drop(&mut self) {
// SAFETY: the descriptor remains owned until after this call.
Expand All @@ -65,21 +65,21 @@ impl Drop for Lock {
}
}

/// Ownership and admission rely on Linux `flock` semantics; elsewhere every
/// Ownership and admission rely on BSD `flock` semantics; elsewhere every
/// lifecycle operation fails closed instead of running without a lock.
#[cfg(not(target_os = "linux"))]
#[cfg(not(unix))]
pub(crate) enum Lock {}
#[cfg(not(target_os = "linux"))]
#[cfg(not(unix))]
impl Lock {
pub fn run(root: &Path) -> Result<Self> {
let _ = root;
Err("run ownership locking is supported on Linux only".into())
Err("run ownership locking requires a UNIX platform".into())
}
fn gate(root: &Path) -> Result<Self> {
Self::run(root)
}
}
#[cfg(not(target_os = "linux"))]
#[cfg(not(unix))]
impl Drop for Lock {
fn drop(&mut self) {
match *self {}
Expand Down Expand Up @@ -535,17 +535,15 @@ mod tests {
assert_eq!(prefix(&attempts).unwrap(), 1);
}

#[cfg(not(target_os = "linux"))]
#[cfg(unix)]
#[test]
fn pause_fails_closed_without_linux_locking() {
fn run_ownership_lock_is_exclusive_while_held() {
let root = std::env::temp_dir().join(format!("grill-lock-{}", std::process::id()));
std::fs::create_dir_all(root.join("lifecycle")).unwrap();
std::fs::write(root.join("lifecycle/admission.lock"), b"").unwrap();
let result = pause(&root);
std::fs::create_dir_all(&root).unwrap();
let owner = Lock::run(&root).unwrap();
assert!(Lock::run(&root).is_err());
drop(owner);
assert!(Lock::run(&root).is_ok());
std::fs::remove_dir_all(&root).unwrap();
assert_eq!(
result.unwrap_err(),
"run ownership locking is supported on Linux only"
);
}
}
6 changes: 3 additions & 3 deletions src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ fn interrupted() -> bool {
INTERRUPTED.load(Ordering::SeqCst)
}

#[cfg(target_os = "linux")]
#[cfg(unix)]
fn latch_interrupt() -> Result<()> {
extern "C" fn on_interrupt(_: libc::c_int) {
INTERRUPTED.store(true, Ordering::SeqCst);
Expand All @@ -43,9 +43,9 @@ fn latch_interrupt() -> Result<()> {
Ok(())
}

#[cfg(not(target_os = "linux"))]
#[cfg(not(unix))]
fn latch_interrupt() -> Result<()> {
Err("the runner's interrupt latch is supported on Linux only".into())
Err("the runner's interrupt latch requires a UNIX platform".into())
}

#[derive(Clone, Copy, clap::ValueEnum)]
Expand Down
16 changes: 8 additions & 8 deletions src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ fn io_error(operation: &str, path: &Path, error: std::io::Error) -> String {
}

pub(crate) fn read(path: &Path, cap: usize) -> Result<Vec<u8>> {
#[cfg(not(target_os = "linux"))]
#[cfg(not(unix))]
{
let _ = (path, cap);
Err("evidence file handling is supported on Linux only".into())
Err("evidence file handling requires a UNIX platform".into())
}
#[cfg(target_os = "linux")]
#[cfg(unix)]
{
use std::io::Read;
use std::os::unix::fs::OpenOptionsExt;
Expand All @@ -27,7 +27,7 @@ pub(crate) fn read(path: &Path, cap: usize) -> Result<Vec<u8>> {
path.display()
));
}
// Linux O_NOFOLLOW | O_NONBLOCK: reject symlinks, do not hang if a FIFO
// POSIX O_NOFOLLOW | O_NONBLOCK: reject symlinks, do not hang if a FIFO
// is substituted between metadata and open. Parent races are not a sandbox.
let file = OpenOptions::new()
.read(true)
Expand Down Expand Up @@ -1273,7 +1273,7 @@ pub(crate) mod tests {
}
}

#[cfg(target_os = "linux")]
#[cfg(unix)]
fn tool_fixture(call: &str) -> (Pack, Vec<String>, Plan) {
let pack_bytes = serde_json::to_vec(&serde_json::json!({
"version":5, "label":"synthetic", "worlds":["w"], "groups":["g"],
Expand Down Expand Up @@ -1311,7 +1311,7 @@ pub(crate) mod tests {
provenance: Provenance {
grill: "fixture".into(),
lockfile: String::new(),
os: "linux".into(),
os: std::env::consts::OS.into(),
arch: "fixture".into(),
started_unix_ms: 0,
pid: 0,
Expand All @@ -1321,8 +1321,8 @@ pub(crate) mod tests {
(pack, inputs, plan)
}

// Replays evidence through store::read, which is Linux-only like tests/offline.rs.
#[cfg(target_os = "linux")]
// Replays evidence through store::read, which is UNIX-only like tests/offline.rs.
#[cfg(unix)]
#[test]
fn followup_rejects_call_artifact_without_raw_body_replay() {
let call =
Expand Down
14 changes: 13 additions & 1 deletion tests/offline.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#![cfg(target_os = "linux")]
#![cfg(unix)]
use serde::Deserialize;
use std::fs;
use std::path::{Path, PathBuf};
Expand Down Expand Up @@ -295,6 +295,18 @@ fn forged_or_missing_evidence_and_unsafe_inputs_are_rejected() {
.status
.success()
);
success(
&Command::new("mkfifo")
.arg(s.path("pack-fifo"))
.output()
.unwrap(),
);
assert!(
!grade(&s.path("pack-fifo"), &a, &s.path("fifo-view"))
.status
.success()
);
assert!(!s.path("fifo-view").exists());
}

#[test]
Expand Down
2 changes: 1 addition & 1 deletion tests/runner.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#![cfg(target_os = "linux")]
#![cfg(unix)]
// Regressions against an independent counted loopback HTTP fixture. Every
// scenario proves dispatch counts and persisted evidence through the real CLI;
// nothing here contacts a model service.
Expand Down
Loading