lispm-llm / src /task_benchmark.rs
Ryan.K
Publish open-vocabulary bi-encoder, continual learning, and technical paper
4a54697 unverified
Raw History Blame Contribute Delete
19.8 kB
//! Real Emacs task outcomes, separate from generated-program exact-match scores.
//!
//! Reviewed fixture programs must satisfy their state goals before model proposals
//! are scored. The adapter binds evidence to model, task, runner and runtime bytes;
//! native failures abort a report instead of becoming successful refusals.
mod io;
mod types;
pub use io::write_report;
pub use types::{
RunnerOptions, TaskBenchmarkError, TaskCase, TaskComparison, TaskCounts, TaskPrediction,
TaskReport, TaskResult, TaskStatus, TaskSuite,
};
use std::{
collections::{BTreeMap, BTreeSet},
path::{Path, PathBuf},
sync::atomic::AtomicBool,
};
use serde::Serialize;
use serde_json::{Value, json};
use crate::{
actions::{Action, ActionKind, Program, parse_command},
engine::ModelEngine,
evaluation::EvaluationCase,
};
use io::{check_cancelled, digest, executable, file_digest, read_document};
use types::RunnerReport;
/// Bound report size and arithmetic independently of user-provided task counts.
const MAX_TASKS: usize = 512;
/// Require a compact nonempty ASCII identity instead of arbitrary path syntax.
fn valid_identity(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 80
&& value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
}
/// Require actual digest-shaped evidence at report comparison boundaries.
fn valid_digest(value: &str) -> bool {
value.len() == 64
&& value
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}
/// Decode only the existing typed action JSON shape; executable source is never accepted.
fn expected_program(value: &Value) -> Result<Program, TaskBenchmarkError> {
let object = value
.as_object()
.ok_or(TaskBenchmarkError::Invalid("program must be an object"))?;
if object.len() != 1 {
return Err(TaskBenchmarkError::Invalid("program has unknown fields"));
}
let actions = object
.get("actions")
.and_then(Value::as_array)
.ok_or(TaskBenchmarkError::Invalid("program needs typed actions"))?;
if !matches!(actions.len(), 1 | 2) {
return Err(TaskBenchmarkError::Invalid(
"program needs one or two actions",
));
}
let parsed = actions
.iter()
.map(|value| {
let object = value
.as_object()
.ok_or(TaskBenchmarkError::Invalid("action must be an object"))?;
let label = object
.get("action")
.and_then(Value::as_str)
.ok_or(TaskBenchmarkError::Invalid("action label missing"))?;
let kind = ActionKind::from_label(label)?;
let argument = match kind.argument_name() {
Some(field) if object.len() == 2 => Some(
object
.get(field)
.and_then(Value::as_str)
.ok_or(TaskBenchmarkError::Invalid("typed string argument missing"))?
.to_owned(),
),
None if object.len() == 1 => None,
_ => {
return Err(TaskBenchmarkError::Invalid(
"action has incompatible fields",
));
}
};
Ok(Action::new(kind, argument)?)
})
.collect::<Result<Vec<_>, TaskBenchmarkError>>()?;
Ok(Program::new(parsed)?)
}
/// Strictly decode task descriptions without touching model weights or an Emacs process.
///
/// The standalone runner additionally validates registered scenario names and
/// proves each reference program reaches its specified fixture goal.
pub fn parse_tasks(bytes: &[u8]) -> Result<TaskSuite, TaskBenchmarkError> {
if u64::try_from(bytes.len()).map_err(|_| TaskBenchmarkError::OutputLimit)?
> io::MAX_DOCUMENT_BYTES
{
return Err(TaskBenchmarkError::OutputLimit);
}
let suite: TaskSuite = serde_json::from_slice(bytes)?;
if suite.format_version != 1
|| suite.policy.trim().is_empty()
|| suite.tasks.is_empty()
|| suite.tasks.len() > MAX_TASKS
{
return Err(TaskBenchmarkError::Invalid(
"invalid task suite version, policy or size",
));
}
let mut identities = BTreeSet::new();
for task in &suite.tasks {
if !valid_identity(&task.id)
|| !valid_identity(&task.scenario)
|| !identities.insert(&task.id)
|| !matches!(task.steps, 1 | 2)
|| task.instruction.len() > 4096
|| task.instruction.contains('\0')
{
return Err(TaskBenchmarkError::Invalid(
"invalid task identity, instruction or steps",
));
}
let program = expected_program(&task.expected)?;
if program.actions().len() != usize::from(task.steps)
|| parse_command(&task.instruction)?.len() != usize::from(task.steps)
|| program
.actions()
.iter()
.any(|action| action.kind().label().starts_with("lispm-"))
{
return Err(TaskBenchmarkError::Invalid(
"task reference must match supported core Emacs steps",
));
}
}
Ok(suite)
}
/// Validate the portable task schema before freezing it into a training project.
pub fn validate_tasks_bytes(bytes: &[u8]) -> Result<(), TaskBenchmarkError> {
parse_tasks(bytes).map(|_| ())
}
/// Materialize exact-match expectations so existing split checks reserve task clauses.
///
/// These rows supplement state-goal measurements; matching an expected program
/// remains a separate measure from achieving that goal when it executes.
pub fn evaluation_cases(bytes: &[u8]) -> Result<Vec<EvaluationCase>, TaskBenchmarkError> {
parse_tasks(bytes)?
.tasks
.into_iter()
.map(|task| {
let program = expected_program(&task.expected)?;
let labels: Vec<String> = program
.actions()
.iter()
.map(|action| action.kind().label().to_owned())
.collect();
let (action, actions) = if labels.len() == 1 {
(labels.first().cloned(), Vec::new())
} else {
(None, labels)
};
Ok(EvaluationCase {
input: task.instruction,
expected: Some(program.to_lisp()),
split: "supported".into(),
action,
actions,
group: None,
novel_to_both: false,
})
})
.collect()
}
/// One reviewed case plus the separately generated model proposal.
#[derive(Serialize)]
struct RunnerCase<'a> {
/// Reviewed fixture definition, including its independent reference program.
#[serde(flatten)]
task: &'a TaskCase,
/// Model-selected action data, never executable source.
prediction: &'a Option<Value>,
/// Explicit inference refusal, disjoint from a proposal.
refusal: &'a Option<String>,
}
/// Complete bounded request to the standalone batch runner.
#[derive(Serialize)]
struct RunnerRequest<'a> {
/// Version of the request contract.
format_version: u32,
/// Frozen task order with one inference outcome per task.
tasks: Vec<RunnerCase<'a>>,
}
/// A file path and its immutable content identity during one evaluation.
struct Source {
/// Original source to recheck before claiming a report is complete.
path: PathBuf,
/// Digest of the exact source bytes used by this run.
digest: String,
}
impl Source {
/// Capture a source identity without retaining a duplicate file image.
fn read(path: PathBuf) -> Result<Self, TaskBenchmarkError> {
Ok(Self {
digest: file_digest(&path)?,
path,
})
}
/// Refuse attribution if another process changed the source during evaluation.
fn verify(&self) -> Result<(), TaskBenchmarkError> {
if file_digest(&self.path)? != self.digest {
return Err(TaskBenchmarkError::Changed(self.path.to_path_buf()));
}
Ok(())
}
}
/// Score all task requests once with one loaded engine, preserving semantic refusals.
fn predictions(
engine: &ModelEngine,
suite: &TaskSuite,
cancelled: &AtomicBool,
progress: &mut dyn FnMut(Value),
) -> Result<Vec<TaskPrediction>, TaskBenchmarkError> {
suite
.tasks
.iter()
.enumerate()
.map(|(index, task)| {
check_cancelled(cancelled)?;
let (program, refusal) = match engine.predict(&task.instruction, None, None) {
Ok(program) => (Some(program.to_json()), None),
Err(error) if error.is_refusal() => (None, Some(error.to_string())),
Err(error) => return Err(error.into()),
};
progress(
json!({"phase":"task_inference", "completed":index + 1, "total":suite.tasks.len()}),
);
Ok(TaskPrediction {
id: task.id.to_owned(),
instruction: task.instruction.to_owned(),
program,
refusal,
})
})
.collect()
}
/// Derive all outcome cohorts from individual results instead of trusting summaries.
fn summaries(
results: &[TaskResult],
) -> (
TaskCounts,
BTreeMap<u8, TaskCounts>,
BTreeMap<String, TaskCounts>,
) {
let mut overall = TaskCounts::default();
let mut steps = BTreeMap::<u8, TaskCounts>::new();
let mut scenarios = BTreeMap::<String, TaskCounts>::new();
for result in results {
overall.observe(result.status);
steps
.entry(result.steps)
.or_default()
.observe(result.status);
scenarios
.entry(result.scenario.to_owned())
.or_default()
.observe(result.status);
}
(overall, steps, scenarios)
}
/// Reject mismatched or contradictory subprocess outcomes before constructing evidence.
fn validate_runner(
report: &RunnerReport,
suite: &TaskSuite,
predictions: &[TaskPrediction],
) -> Result<(), TaskBenchmarkError> {
let task_count =
u32::try_from(suite.tasks.len()).map_err(|_| TaskBenchmarkError::OutputLimit)?;
if report.format_version != 1
|| report.emacs_version.trim().is_empty()
|| report.emacs_version.len() > 200
|| report.oracle_checked != task_count
|| report.results.len() != suite.tasks.len()
|| predictions.len() != suite.tasks.len()
{
return Err(TaskBenchmarkError::Invalid(
"runner task/version/oracle identity mismatch",
));
}
for ((result, task), prediction) in report.results.iter().zip(&suite.tasks).zip(predictions) {
if result.id != task.id || result.scenario != task.scenario || result.steps != task.steps {
return Err(TaskBenchmarkError::Invalid(
"runner changed task order or identity",
));
}
validate_outcome(result, prediction)?;
}
if summaries(&report.results).0 != report.counts {
return Err(TaskBenchmarkError::Invalid(
"runner outcome counts disagree with cases",
));
}
Ok(())
}
/// Ensure a recorded task outcome agrees with its proposal or explicit refusal.
fn validate_outcome(
result: &TaskResult,
prediction: &TaskPrediction,
) -> Result<(), TaskBenchmarkError> {
let count = match (&prediction.program, &prediction.refusal) {
(Some(program), None) => expected_program(program)?.actions().len(),
(None, Some(reason)) if !reason.is_empty() => 0,
_ => {
return Err(TaskBenchmarkError::Invalid(
"proposal and refusal must be disjoint",
));
}
};
let complete = usize::from(result.completed_actions);
let consistent = match result.status {
TaskStatus::Rejected => count == 0 && complete == 0,
TaskStatus::BlockedAction => count > 0 && complete == 0,
TaskStatus::ExecutionError => count > 0 && complete < count,
TaskStatus::Success | TaskStatus::WrongState => count > 0 && complete == count,
};
if !consistent || result.id != prediction.id {
return Err(TaskBenchmarkError::Invalid(
"task outcome contradicts model proposal",
));
}
Ok(())
}
/// Evaluate one unchanged model in an isolated, bounded Emacs batch process.
///
/// The caller owns LibTorch runtime coordination and thread configuration, as
/// with `evaluation::evaluate`. No host Emacs APIs are called by this function.
pub fn evaluate(
model: &Path,
tasks: &Path,
options: &RunnerOptions,
cancelled: &AtomicBool,
progress: &mut dyn FnMut(Value),
) -> Result<TaskReport, TaskBenchmarkError> {
check_cancelled(cancelled)?;
if options.timeout_seconds == 0 || options.timeout_seconds > 3600 {
return Err(TaskBenchmarkError::Invalid(
"runner timeout must be 1..=3600 seconds",
));
}
let task_bytes = read_document(tasks)?;
let suite = parse_tasks(&task_bytes)?;
let runner_bytes = read_document(&options.runner)?;
let executable = executable(&options.emacs)?;
let weights = Source::read(model.join("model.safetensors"))?;
let config = Source::read(model.join("config.json"))?;
let task_source = Source {
path: tasks.to_path_buf(),
digest: digest(&task_bytes),
};
let runner_source = Source {
path: options.runner.to_path_buf(),
digest: digest(&runner_bytes),
};
let executable_source = Source::read(executable.to_path_buf())?;
let engine = ModelEngine::load(model)?;
weights.verify()?;
config.verify()?;
let predictions = predictions(&engine, &suite, cancelled, progress)?;
let request = RunnerRequest {
format_version: 1,
tasks: suite
.tasks
.iter()
.zip(&predictions)
.map(|(task, prediction)| RunnerCase {
task,
prediction: &prediction.program,
refusal: &prediction.refusal,
})
.collect(),
};
let request_bytes = serde_json::to_vec(&request)?;
if u64::try_from(request_bytes.len()).map_err(|_| TaskBenchmarkError::OutputLimit)?
> io::MAX_DOCUMENT_BYTES
{
return Err(TaskBenchmarkError::OutputLimit);
}
progress(json!({"phase":"task_execution", "tasks":suite.tasks.len()}));
let response = io::run(
&executable,
&runner_bytes,
&request_bytes,
options,
cancelled,
)?;
let execution: RunnerReport = serde_json::from_slice(&response)?;
validate_runner(&execution, &suite, &predictions)?;
for source in [
&weights,
&config,
&task_source,
&runner_source,
&executable_source,
] {
source.verify()?;
}
check_cancelled(cancelled)?;
let (counts, by_steps, by_scenario) = summaries(&execution.results);
let report = TaskReport {
format_version: 1,
weights_sha256: weights.digest,
config_sha256: config.digest,
tasks_sha256: task_source.digest,
runner_sha256: runner_source.digest,
emacs_executable_sha256: executable_source.digest,
emacs_version: execution.emacs_version,
policy: suite.policy,
oracle_checked: execution.oracle_checked,
success_rate: counts.success_rate(),
counts,
by_steps,
by_scenario,
results: execution.results,
predictions,
};
progress(
json!({"phase":"task_completed", "counts":report.counts, "success_rate":report.success_rate}),
);
Ok(report)
}
/// Validate persisted outcomes and recompute all aggregate metrics before comparison.
fn validate_report(report: &TaskReport) -> Result<(), TaskBenchmarkError> {
if report.format_version != 1
|| report.results.is_empty()
|| report.results.len() > MAX_TASKS
|| report.predictions.len() != report.results.len()
|| report.emacs_version.trim().is_empty()
|| report.policy.trim().is_empty()
|| ![
&report.weights_sha256,
&report.config_sha256,
&report.tasks_sha256,
&report.runner_sha256,
&report.emacs_executable_sha256,
]
.into_iter()
.all(|hash| valid_digest(hash))
{
return Err(TaskBenchmarkError::Invalid(
"incomplete task report identity",
));
}
let mut identities = BTreeSet::new();
for (result, prediction) in report.results.iter().zip(&report.predictions) {
if !valid_identity(&result.id)
|| !valid_identity(&result.scenario)
|| !identities.insert(&result.id)
|| !matches!(result.steps, 1 | 2)
{
return Err(TaskBenchmarkError::Invalid(
"invalid persisted task identity",
));
}
validate_outcome(result, prediction)?;
}
let (counts, steps, scenarios) = summaries(&report.results);
if counts != report.counts
|| steps != report.by_steps
|| scenarios != report.by_scenario
|| report.oracle_checked != counts.total
|| report.success_rate != counts.success_rate()
{
return Err(TaskBenchmarkError::Invalid(
"persisted task aggregates disagree with outcomes",
));
}
Ok(())
}
/// Compare independently executed models only when all task/runtime identities agree.
///
/// This recomputes eligibility from case outcomes, including per-step and per-fixture
/// cohorts. A lower error count bought by more supported refusals cannot qualify.
pub fn compare(
baseline: TaskReport,
candidate: TaskReport,
) -> Result<TaskComparison, TaskBenchmarkError> {
validate_report(&baseline)?;
validate_report(&candidate)?;
if baseline.tasks_sha256 != candidate.tasks_sha256
|| baseline.runner_sha256 != candidate.runner_sha256
|| baseline.emacs_executable_sha256 != candidate.emacs_executable_sha256
|| baseline.emacs_version != candidate.emacs_version
|| baseline.policy != candidate.policy
|| baseline.results.len() != candidate.results.len()
|| baseline
.results
.iter()
.zip(&candidate.results)
.any(|(left, right)| {
left.id != right.id || left.scenario != right.scenario || left.steps != right.steps
})
|| baseline
.predictions
.iter()
.zip(&candidate.predictions)
.any(|(left, right)| left.id != right.id || left.instruction != right.instruction)
{
return Err(TaskBenchmarkError::Invalid(
"task comparison requires identical tasks and runtime",
));
}
let steps_preserved = baseline.by_steps.iter().all(|(steps, scores)| {
candidate
.by_steps
.get(steps)
.is_some_and(|candidate| candidate.preserves(scores))
});
let scenarios_preserved = baseline.by_scenario.iter().all(|(scenario, scores)| {
candidate
.by_scenario
.get(scenario)
.is_some_and(|candidate| candidate.preserves(scores))
});
let eligible =
candidate.counts.preserves(&baseline.counts) && steps_preserved && scenarios_preserved;
Ok(TaskComparison {
baseline,
candidate,
eligible,
})
}
#[cfg(test)]
mod tests;