//! Command line for arvin, a thin shell over the arvin
//! library.
//!
//! Every command names the state file first. The clock the
//! command line uses is the wall clock in UTC, and no flag
//! overrides it, so the evaluation a caller sees is the
//! evaluation the machine clock gives. Errors the switch raises
//! are printed as one line on stderr with the exit code the
//! error carries, and no traceback is ever printed for them.
//!
//! The argument parsing mirrors the Python argparse surface of
//! Round 1, its usage texts and parser error messages and exit
//! codes, its acceptance of unambiguous long option prefixes,
//! its collection of unrecognized arguments at the top level,
//! and its integer conversion with the Unicode digit and
//! whitespace families of the Python int grammar, probed against
//! the Python runtime before the port was written.
use std::io::Write;
use std::path::PathBuf;
use std::process::ExitCode;
use std::time::Duration;
use arvin::{
consultation_from_reply_body, py_float_repr, py_repr_str, timeout_printable,
validate_judge_form, validate_model_id, Error, FixtureTransport, Instant, ModelTransport,
Record, SubprocessTransport, Switch, Value, DEFAULT_JUDGE_TIMEOUT_SECONDS,
DEFAULT_MISSED_PROOF_LIMIT, DEFAULT_PROOF_INTERVAL_SECONDS, MODEL_NAME,
};
const MAIN_USAGE: &str =
"usage: arvin [-h] [-V] --state STATE {register,prove,spend,pull,stage,log,runs} ...";
const MAIN_HELP: &str = "\
usage: arvin [-h] [-V] --state STATE {register,prove,spend,pull,stage,log,runs} ...
Watch agent runs and walk them down a staged cutoff as the evidence of a
runaway grows.
positional arguments:
{register,prove,spend,pull,stage,log,runs}
register open a run record
prove record a progress proof for a run
spend record a spend report for a run
pull pull the switch and kill the run
stage evaluate a run and report its stage
log show the recorded decision log of a run
runs list the standing summary of every run
options:
-h, --help show this help message and exit
-V, --version show program's version number and exit
--state STATE the state file holding the runs, created by the first
mutation";
const COMMANDS: [&str; 7] = ["register", "prove", "spend", "pull", "stage", "log", "runs"];
fn sub_usage(command: &str) -> &'static str {
match command {
"register" => {
"usage: arvin register [-h] [--proof-interval PROOF_INTERVAL]\n [--missed-limit MISSED_LIMIT]\n [--soft-ceiling SOFT_CEILING]\n [--hard-ceiling HARD_CEILING]\n run"
}
"prove" => "usage: arvin prove [-h] [--note NOTE] run",
"spend" => "usage: arvin spend [-h] --amount AMOUNT run",
"pull" => "usage: arvin pull [-h] run",
"stage" => {
"usage: arvin stage [-h] [--judge JUDGE]\n [--judge-arg JUDGE_ARG]\n [--judge-timeout JUDGE_TIMEOUT]\n [--judge-fixture JUDGE_FIXTURE]\n [--judge-model JUDGE_MODEL]\n [--host-context HOST_CONTEXT]\n run"
}
"runs" => "usage: arvin runs [-h]",
_ => "usage: arvin log [-h] run",
}
}
fn sub_help(command: &str) -> String {
let body = match command {
"register" => {
"positional arguments:\n run\n\noptions:\n -h, --help show this help message and exit\n --proof-interval PROOF_INTERVAL\n the proof interval in seconds, default 60\n --missed-limit MISSED_LIMIT\n the missed proof limit that warrants kill, default 5\n --soft-ceiling SOFT_CEILING\n the spend at or above which cut budget is warranted\n --hard-ceiling HARD_CEILING\n the spend at or above which kill is warranted"
}
"prove" => {
"positional arguments:\n run\n\noptions:\n -h, --help show this help message and exit\n --note NOTE a short progress note, never judged"
}
"spend" => {
"positional arguments:\n run\n\noptions:\n -h, --help show this help message and exit\n --amount AMOUNT the spend to add, in host units"
}
"pull" => {
"positional arguments:\n run\n\noptions:\n -h, --help show this help message and exit"
}
"stage" => {
"positional arguments:\n run\n\noptions:\n -h, --help show this help message and exit\n --judge JUDGE the helper program that judges the picture\n --judge-arg JUDGE_ARG\n one argument handed to the helper before the payload flag, repeatable\n --judge-timeout JUDGE_TIMEOUT\n the seconds the helper may take before the call fails, default 10\n --judge-fixture JUDGE_FIXTURE\n a file holding one recorded reply body, judged instead of calling a helper\n --judge-model JUDGE_MODEL\n the decision model identifier pinned for the consultation, default jev-1.14.0\n --host-context HOST_CONTEXT\n host supplied context rendered into the picture"
}
"runs" => "options:\n -h, --help show this help message and exit",
_ => {
"positional arguments:\n run\n\noptions:\n -h, --help show this help message and exit"
}
};
format!("{}\n\n{}", sub_usage(command), body)
}
fn value_options(command: &str) -> &'static [&'static str] {
match command {
"register" => &[
"--proof-interval",
"--missed-limit",
"--soft-ceiling",
"--hard-ceiling",
],
"prove" => &["--note"],
"spend" => &["--amount"],
"stage" => &[
"--judge",
"--judge-arg",
"--judge-timeout",
"--judge-fixture",
"--judge-model",
"--host-context",
],
_ => &[],
}
}
fn is_int_option(command: &str, option: &str) -> bool {
match command {
"register" => matches!(
option,
"--proof-interval" | "--missed-limit" | "--soft-ceiling" | "--hard-ceiling"
),
"spend" => option == "--amount",
"stage" => option == "--judge-timeout",
_ => false,
}
}
fn required_options(command: &str) -> &'static [&'static str] {
match command {
"spend" => &["--amount"],
_ => &[],
}
}
struct ParserError {
usage: &'static str,
prog: String,
message: String,
}
fn parser_error(usage: &'static str, prog: &str, message: String) -> ParserError {
ParserError {
usage,
prog: prog.to_string(),
message,
}
}
/// Write one line to stderr, fallibly (DM-A24). The result
/// is ignored on purpose: the reporters of failure must not
/// themselves panic when stderr also fails, and the exit
/// code carries the failure either way.
fn eprint_line(text: &str) {
let stderr = std::io::stderr();
let mut lock = stderr.lock();
let _ = writeln!(lock, "{text}");
}
/// Write one line of command output to stdout, checked
/// (DM-A24). A failed write, a broken pipe or a full device,
/// answers the output error line on stderr and exits 1,
/// where the panicking print macros answered with a panic
/// report at exit 101, against this module's doctrine that
/// no traceback is ever printed. Where the command was a
/// mutation, the mutation has already published when its
/// print fails; the failure stands in the reporting, and
/// the message names the output, not the command.
fn print_line(text: &str) {
let stdout = std::io::stdout();
let mut lock = stdout.lock();
if writeln!(lock, "{text}").is_err() || lock.flush().is_err() {
eprint_line("error: the command's output could not be written");
std::process::exit(1);
}
}
fn parser_fail(usage: &str, prog: &str, message: &str) -> ExitCode {
eprint_line(usage);
eprint_line(&format!("{prog}: error: {message}"));
ExitCode::from(2)
}
fn is_option_like(token: &str) -> bool {
if token.len() < 2 || !token.starts_with('-') || token == "-" {
return false;
}
// A token in the shape of a negative number is positional,
// as argparse's negative number matcher holds when no
// option looks like a negative number. The digits of that
// shape are the decimal digits of the Python grammar, the
// same set the integer conversion below accepts.
let body = &token[1..];
let digits: String = body.chars().filter(|c| *c != '.').collect();
if !digits.is_empty() && digits.chars().all(|c| py_digit_value(c).is_some()) {
return false;
}
true
}
/// Resolve a long option token against the candidates of one
/// parser, the argparse way: an exact match wins, an
/// unambiguous prefix matches, an ambiguous prefix is an
/// error, and no match means the token is an extra.
fn resolve_long<'a>(name: &'a str, candidates: &[&'a str]) -> Result<Option<&'a str>, String> {
if candidates.contains(&name) {
return Ok(Some(name));
}
let matches: Vec<&str> = candidates
.iter()
.filter(|candidate| candidate.starts_with(name))
.copied()
.collect();
match matches.len() {
0 => Ok(None),
1 => Ok(Some(matches[0])),
_ => Err(format!(
"ambiguous option: {name} could match {}",
matches.join(", ")
)),
}
}
enum SubValue {
Text(String),
Int(Value),
}
struct SubArgs {
positionals: Vec<String>,
options: Vec<(String, SubValue)>,
extras: Vec<String>,
}
/// The decimal digit ranges of the Unicode character set,
/// each ten codepoints wide with the digit value standing at
/// the offset inside its range, as probed against the Python
/// runtime the conversion mirrors, Python 3.12.3 carrying
/// Unicode 15.0.0. The Python int conversion accepts a digit
/// from any of these families and no other numeric character.
const DECIMAL_DIGIT_RANGES: [(u32, u32); 68] = [
(0x0030, 0x0039),
(0x0660, 0x0669),
(0x06f0, 0x06f9),
(0x07c0, 0x07c9),
(0x0966, 0x096f),
(0x09e6, 0x09ef),
(0x0a66, 0x0a6f),
(0x0ae6, 0x0aef),
(0x0b66, 0x0b6f),
(0x0be6, 0x0bef),
(0x0c66, 0x0c6f),
(0x0ce6, 0x0cef),
(0x0d66, 0x0d6f),
(0x0de6, 0x0def),
(0x0e50, 0x0e59),
(0x0ed0, 0x0ed9),
(0x0f20, 0x0f29),
(0x1040, 0x1049),
(0x1090, 0x1099),
(0x17e0, 0x17e9),
(0x1810, 0x1819),
(0x1946, 0x194f),
(0x19d0, 0x19d9),
(0x1a80, 0x1a89),
(0x1a90, 0x1a99),
(0x1b50, 0x1b59),
(0x1bb0, 0x1bb9),
(0x1c40, 0x1c49),
(0x1c50, 0x1c59),
(0xa620, 0xa629),
(0xa8d0, 0xa8d9),
(0xa900, 0xa909),
(0xa9d0, 0xa9d9),
(0xa9f0, 0xa9f9),
(0xaa50, 0xaa59),
(0xabf0, 0xabf9),
(0xff10, 0xff19),
(0x104a0, 0x104a9),
(0x10d30, 0x10d39),
(0x11066, 0x1106f),
(0x110f0, 0x110f9),
(0x11136, 0x1113f),
(0x111d0, 0x111d9),
(0x112f0, 0x112f9),
(0x11450, 0x11459),
(0x114d0, 0x114d9),
(0x11650, 0x11659),
(0x116c0, 0x116c9),
(0x11730, 0x11739),
(0x118e0, 0x118e9),
(0x11950, 0x11959),
(0x11c50, 0x11c59),
(0x11d50, 0x11d59),
(0x11da0, 0x11da9),
(0x11f50, 0x11f59),
(0x16a60, 0x16a69),
(0x16ac0, 0x16ac9),
(0x16b50, 0x16b59),
(0x1d7ce, 0x1d7d7),
(0x1d7d8, 0x1d7e1),
(0x1d7e2, 0x1d7eb),
(0x1d7ec, 0x1d7f5),
(0x1d7f6, 0x1d7ff),
(0x1e140, 0x1e149),
(0x1e2f0, 0x1e2f9),
(0x1e4f0, 0x1e4f9),
(0x1e950, 0x1e959),
(0x1fbf0, 0x1fbf9),
];
/// The value of one character under the Python int conversion,
/// a decimal digit in any family of the table above, or None
/// for any other character.
fn py_digit_value(c: char) -> Option<u32> {
let n = c as u32;
DECIMAL_DIGIT_RANGES
.iter()
.find(|&&(low, high)| n >= low && n <= high)
.map(|&(low, _)| n - low)
}
/// The whitespace the Python int conversion strips, the
/// Py_UNICODE_ISSPACE set, which is wider than the Rust
/// whitespace property by the information separators.
fn is_python_space(c: char) -> bool {
matches!(c,
'\u{0009}'..='\u{000d}'
| '\u{001c}'..='\u{001f}'
| ' '
| '\u{0085}'
| '\u{00a0}'
| '\u{1680}'
| '\u{2000}'..='\u{200a}'
| '\u{2028}'
| '\u{2029}'
| '\u{202f}'
| '\u{205f}'
| '\u{3000}')
}
/// Python's int conversion for the numeric arguments: optional
/// surrounding whitespace from the Python whitespace set, an
/// optional sign, decimal digits from any family of the table
/// above with single underscores between them. The conversion
/// refuses a digit count past 4300 digit characters, the limit
/// the Python runtime applies, where a wider conversion would
/// stand as a parser failure where Python converted the value.
/// The value is kept whole, at 128 bit width when it fits and
/// as its canonical digit text when it does not, so a later
/// validation prints the number the caller typed.
fn python_int(text: &str) -> Option<Value> {
let trimmed = text.trim_matches(is_python_space);
let (negative, body) = if let Some(rest) = trimmed.strip_prefix('-') {
(true, rest)
} else if let Some(rest) = trimmed.strip_prefix('+') {
(false, rest)
} else {
(false, trimmed)
};
if body.is_empty() {
return None;
}
let mut digits = String::new();
let mut digit_count = 0usize;
let mut previous_digit = false;
let mut previous_underscore = false;
let mut seen_digit = false;
for ch in body.chars() {
if ch == '_' {
if !previous_digit || previous_underscore {
return None;
}
previous_underscore = true;
previous_digit = false;
} else if let Some(value) = py_digit_value(ch) {
digits.push(char::from_digit(value, 10).unwrap());
digit_count += 1;
previous_digit = true;
previous_underscore = false;
seen_digit = true;
} else {
return None;
}
}
if previous_underscore || !seen_digit {
return None;
}
if digit_count > 4300 {
return None;
}
let canonical_digits = {
let stripped = digits.trim_start_matches('0');
if stripped.is_empty() {
"0".to_string()
} else {
stripped.to_string()
}
};
let signed = if negative && canonical_digits != "0" {
format!("-{canonical_digits}")
} else {
canonical_digits.clone()
};
match signed.parse::<i128>() {
Ok(number) => Some(Value::Int(number)),
Err(_) => Some(Value::BigInt(signed)),
}
}
/// Parse one subcommand's arguments. Option values are drawn
/// from the following token unless it is option like, numeric
/// options are converted as they are consumed, and tokens the
/// subcommand does not consume are collected as extras for the
/// top level parser to report. A double dash stops option
/// handling and is itself consumed, as the Python parser
/// consumed it below the subcommand.
fn parse_sub(command: &str, tokens: &[String]) -> Result<SubArgs, ParserError> {
let mut candidates: Vec<&str> = vec!["--help"];
candidates.extend_from_slice(value_options(command));
let mut result = SubArgs {
positionals: Vec::new(),
options: Vec::new(),
extras: Vec::new(),
};
let mut index = 0;
let mut after_separator = false;
while index < tokens.len() {
let token = &tokens[index];
if !after_separator && token == "--" {
after_separator = true;
if command == "runs" {
result.extras.push(token.clone());
}
index += 1;
continue;
}
if !after_separator
&& (token == "-h"
|| token == "--help"
|| (token.starts_with("-h") && !token.starts_with("--")))
{
print_line(&sub_help(command));
std::process::exit(0);
}
if !after_separator && token.starts_with("--") && token.len() > 2 {
let (name, inline_value) = match token.find('=') {
Some(pos) => (&token[..pos], Some(token[pos + 1..].to_string())),
None => (&token[..], None),
};
match resolve_long(name, &candidates) {
Ok(Some("--help")) => {
if let Some(value) = inline_value {
return Err(parser_error(
sub_usage(command),
&format!("arvin {command}"),
format!(
"argument -h/--help: ignored explicit argument {}",
py_repr_str(&value)
),
));
}
print_line(&sub_help(command));
std::process::exit(0);
}
Ok(Some(option)) => {
let raw = if let Some(value) = inline_value {
index += 1;
value
} else if index + 1 < tokens.len() && !is_option_like(&tokens[index + 1]) {
let value = tokens[index + 1].clone();
index += 2;
value
} else {
return Err(parser_error(
sub_usage(command),
&format!("arvin {command}"),
format!("argument {option}: expected one argument"),
));
};
if is_int_option(command, option) {
match python_int(&raw) {
Some(value) => {
result
.options
.push((option.to_string(), SubValue::Int(value)));
}
None => {
return Err(parser_error(
sub_usage(command),
&format!("arvin {command}"),
format!(
"argument {option}: invalid int value: {}",
py_repr_str(&raw)
),
));
}
}
} else {
result
.options
.push((option.to_string(), SubValue::Text(raw)));
}
continue;
}
Ok(None) => {
result.extras.push(token.clone());
index += 1;
continue;
}
Err(message) => {
return Err(parser_error(
sub_usage(command),
&format!("arvin {command}"),
message,
));
}
}
}
if !after_separator && is_option_like(token) {
result.extras.push(token.clone());
index += 1;
continue;
}
if command != "runs" && result.positionals.is_empty() {
result.positionals.push(token.clone());
} else {
result.extras.push(token.clone());
}
index += 1;
}
Ok(result)
}
/// The values recorded under one option name, in the order
/// the caller named them. The option readers state their
/// direction and their projection over this one scan, so the
/// name matching stands in one place.
fn option_values<'a>(args: &'a SubArgs, name: &str) -> Vec<&'a SubValue> {
args.options
.iter()
.filter(|(seen, _)| seen == name)
.map(|(_, value)| value)
.collect()
}
fn option_text<'a>(args: &'a SubArgs, name: &str) -> Option<&'a str> {
option_values(args, name)
.into_iter()
.rev()
.find_map(|value| match value {
SubValue::Text(text) => Some(text.as_str()),
SubValue::Int(_) => None,
})
}
/// Every value of a repeatable option, in the order the
/// caller named them.
fn option_list<'a>(args: &'a SubArgs, name: &str) -> Vec<&'a str> {
option_values(args, name)
.into_iter()
.filter_map(|value| match value {
SubValue::Text(text) => Some(text.as_str()),
SubValue::Int(_) => None,
})
.collect()
}
fn option_int<'a>(args: &'a SubArgs, name: &str) -> Option<&'a Value> {
option_values(args, name)
.into_iter()
.rev()
.find_map(|value| match value {
SubValue::Int(value) => Some(value),
SubValue::Text(_) => None,
})
}
fn require(command: &str, args: &SubArgs) -> Result<(), ParserError> {
let mut missing: Vec<String> = Vec::new();
if command != "runs" && args.positionals.is_empty() {
missing.push("run".to_string());
}
for name in required_options(command) {
if option_int(args, name).is_none() {
missing.push(name.to_string());
}
}
if missing.is_empty() {
Ok(())
} else {
Err(parser_error(
sub_usage(command),
&format!("arvin {command}"),
format!(
"the following arguments are required: {}",
missing.join(", ")
),
))
}
}
fn report_error(error: &Error) -> ExitCode {
eprint_line(&format!("error: {}", error.message()));
ExitCode::from(error.exit_code())
}
fn run() -> ExitCode {
let os_argv: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
let argv: Vec<String> = os_argv
.iter()
.map(|arg| arg.to_string_lossy().into_owned())
.collect();
match dispatch(&argv, &os_argv) {
Ok(code) => code,
Err(error) => report_error(&error),
}
}
/// The state path is the one argument carried as raw bytes,
/// because it names a file, as the state option's seat in
/// dispatch records. Every other argument is read as text,
/// and an argument that is not valid UTF-8 text is refused
/// rather than rewritten with replacement characters on its
/// way into a run id, a proof note, a host context, or a
/// judge path, the lossy carriage DM-A13 recorded. The scan
/// walks the raw arguments as dispatch's own state scan
/// consumes them and exempts exactly the state value, in its
/// inline form after the first equals sign and in its
/// following token form. The refusal names the argument by
/// its position, the only name an undecodable argument has.
fn first_undecodable_argument(os_argv: &[std::ffi::OsString]) -> Option<usize> {
let mut exempt: Vec<bool> = vec![false; os_argv.len()];
let mut index = 0;
while index < os_argv.len() {
let token = os_argv[index].to_string_lossy();
if token == "--" {
break;
}
if token == "-h"
|| token == "--help"
|| (token.starts_with("-h") && !token.starts_with("--"))
|| token == "-V"
|| token == "--version"
{
break;
}
if token.starts_with("--") && token.len() > 2 {
let (name, inline_value) = match token.find('=') {
Some(pos) => (&token[..pos], true),
None => (&token[..], false),
};
match resolve_long(name, &["--help", "--version", "--state"]) {
Ok(Some("--state")) => {
if inline_value {
exempt[index] = true;
index += 1;
} else if index + 1 < os_argv.len()
&& !is_option_like(&os_argv[index + 1].to_string_lossy())
{
exempt[index] = true;
exempt[index + 1] = true;
index += 2;
} else {
index += 1;
}
}
Ok(Some(_)) => break,
Ok(None) => index += 1,
Err(_) => break,
}
continue;
}
if is_option_like(&token) {
index += 1;
continue;
}
break;
}
(0..os_argv.len()).find(|&i| !exempt[i] && os_argv[i].to_str().is_none())
}
/// The current instant in UTC. The command line is the one
/// clock reader in the repo (CONTRACT DM-6): it reads SystemTime
/// here and passes the instant in, and the library reads no
/// wall clock.
fn now_utc() -> Result<Instant, Error> {
instant_from_read(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH))
}
/// The instant a clock read names. A read that fails stands
/// before the epoch, and no command may run on an instant the
/// clock never gave (perfection finding DM-P8): the read
/// answers a failure naming the case, at the failure exit,
/// instead of the epoch the standing form fabricated.
fn instant_from_read(read: Result<Duration, std::time::SystemTimeError>) -> Result<Instant, Error> {
read.map(|elapsed| Instant::from_epoch_micros(elapsed.as_micros() as i128, Some(0)))
.map_err(|_| Error::Failure("the system clock stands before the epoch".to_string()))
}
fn inline_os_after_equals(arg: &std::ffi::OsStr) -> std::ffi::OsString {
#[cfg(unix)]
{
use std::os::unix::ffi::{OsStrExt, OsStringExt};
let raw = arg.as_bytes();
let at = raw.iter().position(|byte| *byte == b'=').unwrap();
std::ffi::OsString::from_vec(raw[at + 1..].to_vec())
}
#[cfg(windows)]
{
use std::os::windows::ffi::{OsStrExt, OsStringExt};
let wide: Vec<u16> = arg.encode_wide().collect();
let at = wide
.iter()
.position(|unit| *unit == u16::from(b'='))
.unwrap();
std::ffi::OsString::from_wide(&wide[at + 1..])
}
#[cfg(not(any(unix, windows)))]
{
let text = arg.to_string_lossy();
let (_, rest) = text.split_once('=').unwrap();
std::ffi::OsString::from(rest)
}
}
fn dispatch(argv: &[String], os_argv: &[std::ffi::OsString]) -> Result<ExitCode, Error> {
if let Some(index) = first_undecodable_argument(os_argv) {
return Ok(parser_fail(
MAIN_USAGE,
"arvin",
&format!("argument {} is not valid UTF-8 text", index + 1),
));
}
// Parse the top level: the state option and the subcommand
// word, with the remaining tokens handed to the subcommand.
// A double dash standing where the subcommand word is
// expected is taken as the subcommand word itself, and a
// double dash with nothing after it is taken as nothing,
// both as the Python parser took them.
let mut state_path: Option<PathBuf> = None;
let mut index = 0;
let mut command: Option<String> = None;
let mut rest: Vec<String> = Vec::new();
let mut extras: Vec<String> = Vec::new();
while index < argv.len() {
let token = &argv[index];
if token == "--" {
if index + 1 < argv.len() {
command = Some(token.clone());
rest = argv[index + 1..].to_vec();
}
break;
}
if token == "-h"
|| token == "--help"
|| (token.starts_with("-h") && !token.starts_with("--"))
{
print_line(MAIN_HELP);
return Ok(ExitCode::from(0));
}
if token == "-V" {
print_line(&format!("arvin {}", env!("CARGO_PKG_VERSION")));
return Ok(ExitCode::from(0));
}
if token.starts_with("--") && token.len() > 2 {
let (name, inline_value) = match token.find('=') {
Some(pos) => (&token[..pos], Some(token[pos + 1..].to_string())),
None => (&token[..], None),
};
match resolve_long(name, &["--help", "--version", "--state"]) {
Ok(Some("--help")) => {
if let Some(value) = inline_value {
return Ok(parser_fail(
MAIN_USAGE,
"arvin",
&format!(
"argument -h/--help: ignored explicit argument {}",
py_repr_str(&value)
),
));
}
print_line(MAIN_HELP);
return Ok(ExitCode::from(0));
}
Ok(Some("--version")) => {
if let Some(value) = inline_value {
return Ok(parser_fail(
MAIN_USAGE,
"arvin",
&format!(
"argument -V/--version: ignored explicit argument {}",
py_repr_str(&value)
),
));
}
print_line(&format!("arvin {}", env!("CARGO_PKG_VERSION")));
return Ok(ExitCode::from(0));
}
Ok(Some("--state")) => {
if inline_value.is_some() {
// The state value is carried as the raw
// argument bytes, so a state path that is
// not valid UTF-8 names the file the caller
// named, as the Python surface names it.
state_path = Some(PathBuf::from(inline_os_after_equals(&os_argv[index])));
index += 1;
} else if index + 1 < argv.len() && !is_option_like(&argv[index + 1]) {
state_path = Some(PathBuf::from(os_argv[index + 1].clone()));
index += 2;
} else {
return Ok(parser_fail(
MAIN_USAGE,
"arvin",
"argument --state: expected one argument",
));
}
continue;
}
Ok(Some(_)) => unreachable!(),
Ok(None) => {
extras.push(token.clone());
index += 1;
continue;
}
Err(message) => {
return Ok(parser_fail(MAIN_USAGE, "arvin", &message));
}
}
}
if is_option_like(token) {
extras.push(token.clone());
index += 1;
continue;
}
command = Some(token.clone());
rest = argv[index + 1..].to_vec();
break;
}
let Some(command) = command else {
let mut missing = Vec::new();
if state_path.is_none() {
missing.push("--state");
}
missing.push("command");
return Ok(parser_fail(
MAIN_USAGE,
"arvin",
&format!(
"the following arguments are required: {}",
missing.join(", ")
),
));
};
if !COMMANDS.contains(&command.as_str()) {
return Ok(parser_fail(
MAIN_USAGE,
"arvin",
&format!(
"argument command: invalid choice: {} (choose from 'register', 'prove', 'spend', 'pull', 'stage', 'log', 'runs')",
py_repr_str(&command)
),
));
}
let args = match parse_sub(&command, &rest) {
Ok(args) => args,
Err(failure) => {
return Ok(parser_fail(failure.usage, &failure.prog, &failure.message));
}
};
if let Err(failure) = require(&command, &args) {
return Ok(parser_fail(failure.usage, &failure.prog, &failure.message));
}
if state_path.is_none() {
return Ok(parser_fail(
MAIN_USAGE,
"arvin",
"the following arguments are required: --state",
));
}
extras.extend(args.extras.iter().cloned());
if !extras.is_empty() {
return Ok(parser_fail(
MAIN_USAGE,
"arvin",
&format!("unrecognized arguments: {}", extras.join(" ")),
));
}
let switch = Switch::new(state_path.unwrap());
let run = args.positionals.first().cloned().unwrap_or_default();
let run_value = Value::Str(run.clone());
match command.as_str() {
"register" => {
let now = now_utc()?;
let proof_interval = option_int(&args, "--proof-interval")
.cloned()
.unwrap_or(Value::Int(DEFAULT_PROOF_INTERVAL_SECONDS as i128));
let missed_limit = option_int(&args, "--missed-limit")
.cloned()
.unwrap_or(Value::Int(DEFAULT_MISSED_PROOF_LIMIT as i128));
let soft_ceiling = option_int(&args, "--soft-ceiling")
.cloned()
.unwrap_or(Value::Null);
let hard_ceiling = option_int(&args, "--hard-ceiling")
.cloned()
.unwrap_or(Value::Null);
switch.register(
&run_value,
&now,
&proof_interval,
&missed_limit,
&soft_ceiling,
&hard_ceiling,
)?;
print_line(&format!("registered {run}"));
}
"prove" => {
let now = now_utc()?;
let note = option_text(&args, "--note").unwrap_or("").to_string();
switch.prove(&run_value, &Value::Str(note), &now)?;
print_line(&format!("proved {run}"));
}
"spend" => {
let now = now_utc()?;
let amount = option_int(&args, "--amount").unwrap().clone();
let total = switch.spend(&run_value, &amount, &now)?;
print_line(&format!("spend_total {total}"));
}
"pull" => {
let now = now_utc()?;
let stage = switch.pull(&run_value, &now)?;
print_line(&format!("stage {stage}"));
}
"stage" => {
let now = now_utc()?;
stage_command(&switch, &run_value, &now, &args)?;
}
"runs" => {
for summary in switch.runs()? {
let interval_text = match &summary.proof_interval_seconds {
Value::Int(number) => number.to_string(),
Value::BigInt(text) => text.clone(),
_ => unreachable!(),
};
let soft_text = summary
.soft_ceiling
.map_or_else(|| "none".to_string(), |value| value.to_string());
let hard_text = summary
.hard_ceiling
.map_or_else(|| "none".to_string(), |value| value.to_string());
let last_proof_text = summary.last_proof_at.as_deref().unwrap_or("none");
print_line(&format!(
"{} stage={} killed={} spend_total={} soft_ceiling={} hard_ceiling={} proof_interval_seconds={} missed_proof_limit={} registered_at={} last_proof_at={}",
summary.id,
summary.stage,
summary.killed,
summary.spend_total,
soft_text,
hard_text,
interval_text,
summary.missed_proof_limit,
summary.registered_at,
last_proof_text,
));
}
}
_ => {
for record in switch.log(&run_value)? {
let mut line = format!(
"{} {} at={} stage={}",
record.seq, record.kind, record.at, record.stage
);
for reason in &record.reasons {
line.push_str(&format!(" reason={reason}"));
}
print_line(&line);
}
}
}
Ok(ExitCode::from(0))
}
/// The stage command, in its deterministic form and its model
/// form over the one model entry point of DM-20. The command
/// builds at most one transport from its judge options and
/// calls stage_with_model in every case, so the deterministic
/// behaviour is the library no transport case of that call and
/// no second evaluation path stands in the binary. The surface
/// refuses its own malformed shapes before any state changes,
/// in the invalid request class the library refusals of the
/// same conditions take.
fn stage_command(
switch: &Switch,
run_value: &Value,
now: &Instant,
args: &SubArgs,
) -> Result<(), Error> {
let judge = option_text(args, "--judge");
let fixture_file = option_text(args, "--judge-fixture");
let judge_args = option_list(args, "--judge-arg");
let judge_timeout = option_int(args, "--judge-timeout");
let judge_model = option_text(args, "--judge-model");
let host_context = option_text(args, "--host-context");
validate_judge_form(
judge.is_some(),
fixture_file.is_some(),
!judge_args.is_empty(),
judge_timeout.is_some(),
)?;
if judge_model.is_some() && judge.is_none() && fixture_file.is_none() {
return Err(Error::InvalidRequest(
"a judge model stands named with no judge form to carry it".to_string(),
));
}
if let Some(model_name) = judge_model {
validate_model_id(model_name)?;
}
let pinned_model = judge_model.unwrap_or(MODEL_NAME);
let timeout = match judge_timeout {
Some(value) => Some(judge_timeout_duration(value)?),
None => None,
};
let subprocess_transport;
let fixture_transport;
let transport: Option<&dyn ModelTransport> = if let Some(program) = judge {
subprocess_transport = SubprocessTransport::with_model(
PathBuf::from(program),
judge_args.iter().map(|arg| arg.to_string()).collect(),
timeout.unwrap_or(Duration::from_secs(DEFAULT_JUDGE_TIMEOUT_SECONDS)),
pinned_model,
)?;
Some(&subprocess_transport)
} else if let Some(path) = fixture_file {
let body = read_judge_fixture(path)?;
fixture_transport = FixtureTransport::new(
pinned_model,
vec![consultation_from_reply_body(&body, pinned_model)],
);
Some(&fixture_transport)
} else {
None
};
let report = switch.stage_with_model(run_value, now, transport, host_context)?;
print_line(&format!("stage {}", report.stage));
for reason in &report.reasons {
print_line(&format!("reason {reason}"));
}
if let Some(lines) = report.appended.as_ref().and_then(consultation_lines) {
for line in lines {
print_line(&line);
}
}
Ok(())
}
/// The deadline a judge timeout value names, refused as an
/// invalid request where the value does not stand as a
/// positive number of seconds the transport duration can
/// hold, with the message naming the value and the condition.
/// A value standing at or past the surfaces' whole ceiling
/// refuses without being held, because no surface reads a
/// number it cannot hold to name the value it refuses.
fn judge_timeout_duration(value: &Value) -> Result<Duration, Error> {
let seconds = match value {
Value::Int(number) if *number >= 1 && *number <= u64::MAX as i128 => Some(*number as u64),
_ => None,
};
match seconds {
Some(seconds) => Ok(Duration::from_secs(seconds)),
None => Err(Error::InvalidRequest(format!(
"judge timeout {} does not stand as a positive number of seconds the \
transport can hold",
timeout_printable(value)
))),
}
}
/// Read the reply body a judge fixture file holds. The file
/// is an input the command must open before any evaluation can
/// stand, so a file that cannot be read is a failure of the
/// command at exit 1 with a message naming the file, and no
/// state changes and no record stands appended. Bytes that
/// stand as no text parse under the reply grammar as no
/// document, in the malformed reply class the grammar states
/// for them.
fn read_judge_fixture(path: &str) -> Result<String, Error> {
match std::fs::read(path) {
Ok(bytes) => Ok(String::from_utf8(bytes).unwrap_or_default()),
Err(err) => Err(Error::Failure(format!(
"the judge fixture file {} cannot be read, {err}",
py_repr_str(path)
))),
}
}
/// The consultation lines the stage command prints after its
/// stage and reason lines, read from the record the
/// evaluation handed back in its report, or nothing where
/// that record carries no consultation. Only a consultation
/// record carries a model name, so the model fields of the
/// record are the whole identification, read off the record
/// the evaluation itself appended inside its lock, and no
/// second reading of the state and no reconstruction after
/// the fact stands between the evaluation and its lines.
/// The confidence and the score render by the library float
/// rendering the document writer uses, so the printed
/// numbers and the stored fields cannot disagree.
fn consultation_lines(record: &Record) -> Option<Vec<String>> {
let model = record.model_name.as_ref()?;
if let Some(class) = &record.fallback_taken {
Some(vec![format!("model {model}"), format!("fallback {class}")])
} else if let Some(verdict) = &record.model_verdict {
let confidence = record.model_confidence?;
let score = record.model_score?;
Some(vec![
format!("model {model}"),
format!("verdict {verdict}"),
format!("confidence {}", py_float_repr(confidence)),
format!("score {}", py_float_repr(score)),
])
} else {
None
}
}
fn main() -> ExitCode {
run()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_clock_standing_before_the_epoch_answers_the_failure() {
let read =
(std::time::UNIX_EPOCH - Duration::from_secs(1)).duration_since(std::time::UNIX_EPOCH);
assert!(read.is_err());
let error = instant_from_read(read).unwrap_err();
assert!(matches!(error, Error::Failure(_)));
assert_eq!(error.message(), "the system clock stands before the epoch");
assert_eq!(error.exit_code(), 1);
}
#[test]
fn a_clock_at_or_after_the_epoch_builds_its_instant() {
let at_epoch = instant_from_read(Ok(Duration::ZERO)).expect("the epoch read builds");
assert_eq!(at_epoch.epoch_micros(), 0);
let after =
instant_from_read(Ok(Duration::from_micros(90_000_000))).expect("a later read builds");
assert_eq!(after.epoch_micros(), 90_000_000);
}
}