File size: 10,662 Bytes
18de23f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
//! 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(())
}