//! Witnesses for task identity, metric partitioning and subprocess lifetime boundaries. use super::*; use std::{fs, sync::atomic::Ordering}; /// Create one reviewed single-step task without invoking Emacs or loading weights. fn suite() -> Value { json!({"format_version":1,"policy":"reviewed fixture regression","tasks":[{ "id":"begin","instruction":"go to buffer start","scenario":"buffer_start", "steps":1,"expected":{"actions":[{"action":"beginning-of-buffer"}]} }]}) } /// Build internally consistent report evidence for one controllable outcome. fn report(status: TaskStatus) -> TaskReport { let rejected = status == TaskStatus::Rejected; let completed = match status { TaskStatus::Success | TaskStatus::WrongState => 1, _ => 0, }; let results = vec![TaskResult { id: "begin".into(), scenario: "buffer_start".into(), steps: 1, status, completed_actions: completed, detail: None, state: Some(json!({"point":1})), }]; let (counts, by_steps, by_scenario) = summaries(&results); TaskReport { format_version: 1, weights_sha256: "a".repeat(64), config_sha256: "b".repeat(64), tasks_sha256: "c".repeat(64), runner_sha256: "d".repeat(64), emacs_executable_sha256: "e".repeat(64), emacs_version: "31.1".into(), policy: "reviewed fixture regression".into(), oracle_checked: 1, success_rate: counts.success_rate(), counts, by_steps, by_scenario, results, predictions: vec![TaskPrediction { id: "begin".into(), instruction: "go to buffer start".into(), program: (!rejected).then(|| json!({"actions":[{"action":"beginning-of-buffer"}]})), refusal: rejected.then(|| "uncertain".into()), }], } } /// Reference programs cannot smuggle new fields, unknown actions or inconsistent steps. #[test] fn strict_task_schema_and_typed_reference_programs_precede_model_loading() -> Result<(), TaskBenchmarkError> { validate_tasks_bytes(&serde_json::to_vec(&suite())?)?; for changed in [ json!({"format_version":1,"policy":"reviewed","tasks":[],"extra":true}), json!({"format_version":1,"policy":"reviewed","tasks":[{ "id":"bad","instruction":"go to buffer start","scenario":"buffer_start","steps":2, "expected":{"actions":[{"action":"beginning-of-buffer"}]}}]}), json!({"format_version":1,"policy":"reviewed","tasks":[{ "id":"bad","instruction":"go to buffer start","scenario":"buffer_start","steps":1, "expected":{"actions":[{"action":"eval","text":"anything"}]}}]}), json!({"format_version":1,"policy":"reviewed","tasks":[{ "id":"bad","instruction":"go to buffer start","scenario":"buffer_start","steps":1, "expected":{"actions":[{"action":"beginning-of-buffer","text":"anything"}]}}]}), ] { assert!(validate_tasks_bytes(&serde_json::to_vec(&changed)?).is_err()); } let directory = tempfile::tempdir()?; let tasks = directory.path().join("tasks.json"); fs::write(&tasks, b"{}")?; let options = RunnerOptions { emacs: "absent-emacs".into(), runner: "absent.el".into(), timeout_seconds: 1, }; assert!(matches!( evaluate( directory.path(), &tasks, &options, &AtomicBool::new(false), &mut |_| {} ), Err(TaskBenchmarkError::Json(_)) )); Ok(()) } /// Held-out task rows preserve both ordered action labels and literal parameters. #[test] fn task_rows_reserve_exact_single_and_two_step_programs() -> Result<(), TaskBenchmarkError> { let mut data = suite(); data.get_mut("tasks").and_then(Value::as_array_mut) .ok_or(TaskBenchmarkError::Invalid("test tasks missing"))?.push(json!({ "id":"open-search","instruction":"open file \"notes.el\" then search forward for \"TODO\"", "scenario":"open_search","steps":2,"expected":{"actions":[ {"action":"find-file","path":"notes.el"},{"action":"search-forward","text":"TODO"}]} })); let rows = evaluation_cases(&serde_json::to_vec(&data)?)?; let first = rows .first() .ok_or(TaskBenchmarkError::Invalid("test single missing"))?; let second = rows .get(1) .ok_or(TaskBenchmarkError::Invalid("test pair missing"))?; assert_eq!(first.action.as_deref(), Some("beginning-of-buffer")); assert!(first.actions.is_empty()); assert_eq!(second.actions, ["find-file", "search-forward"]); assert!(second.action.is_none()); assert_eq!( second.expected.as_deref(), Some("(progn (find-file \"notes.el\") (search-forward \"TODO\"))") ); Ok(()) } /// Supported refusals and every execution failure remain outside task successes. #[test] fn every_result_category_is_disjoint_and_aggregates_are_recomputed() -> Result<(), TaskBenchmarkError> { for status in [ TaskStatus::Success, TaskStatus::WrongState, TaskStatus::Rejected, TaskStatus::ExecutionError, TaskStatus::BlockedAction, ] { let report = report(status); validate_report(&report)?; assert_eq!(report.counts.total, 1); assert_eq!( report.counts.success, u32::from(status == TaskStatus::Success) ); } let mut forged = report(TaskStatus::Rejected); forged.counts.success = 1; forged.success_rate = 1.0; assert!(compare(report(TaskStatus::Success), forged).is_err()); Ok(()) } /// Reducing wrong states by refusing the supported task cannot qualify a candidate. #[test] fn more_supported_refusals_never_buy_task_eligibility() -> Result<(), TaskBenchmarkError> { assert!(!compare(report(TaskStatus::WrongState), report(TaskStatus::Rejected))?.eligible); assert!(!compare(report(TaskStatus::Success), report(TaskStatus::WrongState))?.eligible); assert!(compare(report(TaskStatus::Rejected), report(TaskStatus::Success))?.eligible); Ok(()) } /// Equal totals cannot hide changed environments, task identities or case order. #[test] fn comparisons_require_identical_fixtures_and_runtime_evidence() { let mut candidate = report(TaskStatus::Success); candidate.emacs_version = "other version".into(); assert!(compare(report(TaskStatus::Success), candidate).is_err()); let mut candidate = report(TaskStatus::Success); candidate.tasks_sha256 = "f".repeat(64); assert!(compare(report(TaskStatus::Success), candidate).is_err()); let mut candidate = report(TaskStatus::Success); candidate.oracle_checked = 0; assert!(compare(report(TaskStatus::Success), candidate).is_err()); } /// Equal aggregate accuracy cannot conceal a newly broken task scenario. #[test] fn per_scenario_regressions_fail_even_when_overall_counts_are_unchanged() -> Result<(), TaskBenchmarkError> { let paired = |first: TaskStatus, second: TaskStatus| { let mut evidence = report(first); let mut other = report(second); if let Some(result) = other.results.first_mut() { result.id = "other-case".into(); result.scenario = "other_scenario".into(); } if let Some(prediction) = other.predictions.first_mut() { prediction.id = "other-case".into(); } evidence.results.extend(other.results); evidence.predictions.extend(other.predictions); let (counts, by_steps, by_scenario) = summaries(&evidence.results); evidence.oracle_checked = counts.total; evidence.success_rate = counts.success_rate(); evidence.counts = counts; evidence.by_steps = by_steps; evidence.by_scenario = by_scenario; evidence }; let baseline = paired(TaskStatus::Success, TaskStatus::WrongState); let candidate = paired(TaskStatus::WrongState, TaskStatus::Success); assert_eq!(baseline.counts, candidate.counts); assert!(!compare(baseline, candidate)?.eligible); Ok(()) } /// Cancellation is observed before resolving executable paths or loading model weights. #[test] fn cancelled_task_benchmarks_have_no_process_or_model_side_effects() { let options = RunnerOptions { emacs: "missing".into(), runner: "missing".into(), timeout_seconds: 1, }; assert!(matches!( evaluate( Path::new("missing"), Path::new("missing"), &options, &AtomicBool::new(true), &mut |_| {} ), Err(TaskBenchmarkError::Cancelled) )); } /// A real child remains bounded by cancellation and timeout, and is reaped on either path. #[cfg(unix)] #[test] fn child_process_deadlines_and_cancellation_terminate_the_worker() -> Result<(), TaskBenchmarkError> { use std::{ os::unix::fs::PermissionsExt, sync::Arc, thread, time::{Duration, Instant}, }; let directory = tempfile::tempdir()?; let executable = directory.path().join("fake-emacs"); fs::write(&executable, b"#!/bin/sh\nexec sleep 30\n")?; fs::set_permissions(&executable, fs::Permissions::from_mode(0o700))?; let options = RunnerOptions { emacs: executable.to_path_buf(), runner: "unused".into(), timeout_seconds: 1, }; let started = Instant::now(); assert!(matches!( io::run(&executable, b"", b"{}", &options, &AtomicBool::new(false)), Err(TaskBenchmarkError::Timeout(1)) )); assert!(started.elapsed() < Duration::from_secs(5)); let cancelled = Arc::new(AtomicBool::new(false)); let signal = Arc::clone(&cancelled); let worker = thread::spawn(move || { thread::sleep(Duration::from_millis(80)); signal.store(true, Ordering::Release); }); assert!(matches!( io::run(&executable, b"", b"{}", &options, &cancelled), Err(TaskBenchmarkError::Cancelled) )); worker .join() .map_err(|_| TaskBenchmarkError::Invalid("test worker panicked"))?; Ok(()) } /// A completed report never overwrites previous benchmark evidence. #[test] fn report_publication_refuses_existing_destinations() -> Result<(), TaskBenchmarkError> { let directory = tempfile::tempdir()?; let output = directory.path().join("report.json"); write_report(&output, &json!({"result":"first"}))?; let previous = fs::read(&output)?; assert!(write_report(&output, &json!({"result":"second"})).is_err()); assert_eq!(fs::read(&output)?, previous); Ok(()) }