File size: 7,183 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
//! Named filesystem and subprocess boundaries for isolated Emacs task execution.

use std::{
    env,
    fs::{self, File},
    io::{Read, Write},
    path::{Path, PathBuf},
    process::{Child, Command, Stdio},
    sync::atomic::{AtomicBool, Ordering},
    thread,
    time::{Duration, Instant},
};

use sha2::{Digest, Sha256};

use super::{RunnerOptions, TaskBenchmarkError};

/// Maximum child diagnostic bytes retained before terminating runaway output.
const MAX_DIAGNOSTIC_BYTES: u64 = 64 * 1024;
/// Maximum complete fixture or result bytes accepted by the adapter.
pub(super) const MAX_DOCUMENT_BYTES: u64 = 8 * 1024 * 1024;

/// Stop work at an explicit cooperative boundary.
pub(super) fn check_cancelled(cancelled: &AtomicBool) -> Result<(), TaskBenchmarkError> {
    if cancelled.load(Ordering::Acquire) {
        Err(TaskBenchmarkError::Cancelled)
    } else {
        Ok(())
    }
}

/// Hash one exact byte sequence using the publication manifest's digest format.
pub(super) fn digest(bytes: &[u8]) -> String {
    format!("{:x}", Sha256::digest(bytes))
}

/// Hash a file without allocating a second complete model or executable image.
pub(super) fn file_digest(path: &Path) -> Result<String, TaskBenchmarkError> {
    let mut source = File::open(path)?;
    let mut digest = Sha256::new();
    let mut buffer = [0_u8; 32 * 1024];
    loop {
        let read = source.read(&mut buffer)?;
        if read == 0 {
            break;
        }
        let bytes = buffer
            .get(..read)
            .ok_or(TaskBenchmarkError::Invalid("invalid file read length"))?;
        digest.update(bytes);
    }
    Ok(format!("{:x}", digest.finalize()))
}

/// Read a bounded document and reject a file growing past the byte limit.
pub(super) fn read_document(path: &Path) -> Result<Vec<u8>, TaskBenchmarkError> {
    let mut bytes = Vec::new();
    File::open(path)?
        .take(MAX_DOCUMENT_BYTES + 1)
        .read_to_end(&mut bytes)?;
    if u64::try_from(bytes.len()).map_err(|_| TaskBenchmarkError::OutputLimit)? > MAX_DOCUMENT_BYTES
    {
        return Err(TaskBenchmarkError::OutputLimit);
    }
    Ok(bytes)
}

/// Resolve one explicit executable without a shell or command-string interpretation.
pub(super) fn executable(path: &Path) -> Result<PathBuf, TaskBenchmarkError> {
    if path.is_absolute() || path.components().count() > 1 {
        return Ok(fs::canonicalize(path)?);
    }
    if let Some(paths) = env::var_os("PATH") {
        for directory in env::split_paths(&paths) {
            let candidate = directory.join(path);
            if candidate.is_file() {
                return Ok(fs::canonicalize(candidate)?);
            }
        }
    }
    Err(TaskBenchmarkError::EmacsNotFound(path.to_path_buf()))
}

/// Ensure every error and cancellation path terminates and reaps the child.
struct ChildGuard {
    /// Sole ownership of the subprocess handle.
    child: Child,
    /// A successful wait already reaped the child.
    finished: bool,
}

impl Drop for ChildGuard {
    fn drop(&mut self) {
        if !self.finished {
            let _ = self.child.kill();
            let _ = self.child.wait();
        }
    }
}

/// Reject a child that writes unbounded diagnostics or a result of excessive size.
fn bounded_outputs(diagnostic: &Path, output: &Path) -> Result<(), TaskBenchmarkError> {
    for (path, limit) in [
        (diagnostic, MAX_DIAGNOSTIC_BYTES),
        (output, MAX_DOCUMENT_BYTES),
    ] {
        match fs::metadata(path) {
            Ok(metadata) if metadata.len() > limit => {
                return Err(TaskBenchmarkError::OutputLimit);
            }
            Ok(_) => {}
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => return Err(error.into()),
        }
    }
    Ok(())
}

/// Wait in short cancellable intervals and return a bounded diagnostic on failure.
fn wait_for_runner(
    child: Child,
    options: &RunnerOptions,
    diagnostic: &Path,
    output: &Path,
    cancelled: &AtomicBool,
) -> Result<(), TaskBenchmarkError> {
    let mut child = ChildGuard {
        child,
        finished: false,
    };
    let started = Instant::now();
    loop {
        check_cancelled(cancelled)?;
        bounded_outputs(diagnostic, output)?;
        if let Some(status) = child.child.try_wait()? {
            child.finished = true;
            if status.success() {
                return Ok(());
            }
            let mut bytes = Vec::new();
            File::open(diagnostic)?
                .take(MAX_DIAGNOSTIC_BYTES)
                .read_to_end(&mut bytes)?;
            return Err(TaskBenchmarkError::RunnerFailed(format!(
                "{status}: {}",
                String::from_utf8_lossy(&bytes)
            )));
        }
        if started.elapsed() >= Duration::from_secs(options.timeout_seconds) {
            return Err(TaskBenchmarkError::Timeout(options.timeout_seconds));
        }
        thread::sleep(Duration::from_millis(20));
    }
}

/// Run reviewed source bytes in a clean batch process and private working directory.
///
/// This isolates fixture effects from the user's Emacs process. It is not an OS
/// sandbox: the reviewed Lisp runner must enforce its bounded action/path rules.
pub(super) fn run(
    executable: &Path,
    runner: &[u8],
    request: &[u8],
    options: &RunnerOptions,
    cancelled: &AtomicBool,
) -> Result<Vec<u8>, 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 scratch = tempfile::Builder::new().prefix("lispm-task-").tempdir()?;
    let source = scratch.path().join("runner.el");
    let input = scratch.path().join("request.json");
    let output = scratch.path().join("report.json");
    let diagnostic = scratch.path().join("stderr.log");
    fs::write(&source, runner)?;
    fs::write(&input, request)?;
    let errors = File::create(&diagnostic)?;
    let child = Command::new(executable)
        .args(["-Q", "--batch", "-l"])
        .arg(&source)
        .args(["-f", "lispm-llm-benchmark-batch"])
        .arg(&input)
        .arg(&output)
        .current_dir(scratch.path())
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::from(errors))
        .spawn()?;
    wait_for_runner(child, options, &diagnostic, &output, cancelled)?;
    check_cancelled(cancelled)?;
    read_document(&output)
}

/// Publish a report to a previously nonexistent path after complete serialization.
pub fn write_report(path: &Path, value: &impl serde::Serialize) -> Result<(), TaskBenchmarkError> {
    let bytes = serde_json::to_vec_pretty(value)?;
    let parent = path
        .parent()
        .filter(|path| !path.as_os_str().is_empty())
        .unwrap_or(Path::new("."));
    let mut temporary = tempfile::NamedTempFile::new_in(parent)?;
    temporary.write_all(&bytes)?;
    temporary.write_all(b"\n")?;
    temporary.as_file().sync_all()?;
    temporary
        .persist_noclobber(path)
        .map_err(|error| error.error)?;
    Ok(())
}