File size: 19,809 Bytes
fac4d07 18de23f 4a54697 fac4d07 18de23f fac4d07 18de23f fac4d07 18de23f fac4d07 18de23f fac4d07 18de23f fac4d07 18de23f fac4d07 18de23f fac4d07 18de23f fac4d07 18de23f fac4d07 18de23f fac4d07 18de23f fac4d07 4a54697 fac4d07 4a54697 fac4d07 4a54697 fac4d07 4a54697 fac4d07 4a54697 fac4d07 4a54697 fac4d07 18de23f fac4d07 18de23f fac4d07 18de23f fac4d07 | 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 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 | //! Frozen-corpus evaluation is separate from all calibration and training decisions.
use crate::{
actions::{Action, ActionKind, Program, parse_command},
engine::ModelEngine,
inference::InferenceError,
model::ModelError,
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{collections::BTreeMap, fs, path::Path};
use thiserror::Error;
/// One frozen command and its expected rendered program, if supported.
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct EvaluationCase {
/// Materialized instruction with quoted literals preserved as data.
pub input: String,
/// Expected Lisp; `None` means the instruction is outside the action set.
pub expected: Option<String>,
/// Supported or unsupported source partition.
pub split: String,
/// Intended single-action label; two-action cases use `actions` and leave this null.
pub action: Option<String>,
/// Ordered labels for a two-action program; legacy single-action rows omit this field.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub actions: Vec<String>,
/// Optional family of deliberately unsupported requests.
pub group: Option<String>,
/// Membership in the historical comparison's shared vocabulary novelty slice.
pub novel_to_both: bool,
}
/// Cases and the immutable source corpus identity.
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Corpus {
/// SHA-256 of the source corpus, or of compact serialized derived cases.
pub sha256: String,
/// Exact overlap-filtered commands in source order.
pub cases: Vec<EvaluationCase>,
}
/// Portable evaluation input; this file is never read by the trainer.
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct EvaluationData {
/// Schema version of this materialized dataset.
pub format_version: u32,
/// Description of corpus exposure and exclusion policy.
pub policy: String,
/// Independently named frozen corpora.
pub corpora: BTreeMap<String, Corpus>,
}
/// Accepted correctness and refusals are disjoint counts, including unsupported inputs.
#[derive(Debug, Default, Serialize)]
pub struct Counts {
/// Number of inputs observed.
pub total: usize,
/// Accepted predictions whose rendered form equals the supported expectation.
pub correct: usize,
/// Accepted wrong actions, including false acceptance of unsupported input.
pub wrong: usize,
/// Instructions explicitly refused by the command or model boundary.
pub rejected: usize,
}
impl Counts {
/// Accumulate one decision while preserving the partition of all observations.
fn observe(&mut self, actual: Option<&str>, expected: Option<&str>) {
self.total += 1;
match actual {
None => self.rejected += 1,
Some(value) if Some(value) == expected => self.correct += 1,
Some(_) => self.wrong += 1,
}
}
}
/// A wrong acceptance or supported refusal retained for manual inspection.
#[derive(Debug, Serialize)]
pub struct Failure {
/// Original instruction, copied into the durable report.
pub input: String,
/// Required form, or `None` for unsupported input.
pub expected: Option<String>,
/// Accepted form, or `None` for refusal.
pub actual: Option<String>,
/// Admission failure message, when the command was refused.
pub reason: Option<String>,
}
/// Detailed outcomes for one frozen corpus.
#[derive(Debug, Default, Serialize)]
pub struct CorpusResult {
/// Original benchmark file identity.
pub source_sha256: String,
/// Supported-command accuracy, mistakes and coverage.
pub supported: Counts,
/// Unsupported-command false acceptances and refusals.
pub unsupported: Counts,
/// Identical historical vocabulary novelty subset.
pub novel_to_both_supported: Counts,
/// Unsupported operation families, such as duplicated browser tabs.
pub unsupported_groups: BTreeMap<String, Counts>,
/// Whole-program outcomes for requests containing each intended action.
/// A two-action request contributes once to each action, so these totals overlap.
pub per_action: BTreeMap<String, Counts>,
/// Concrete mistakes and supported refusals; correct negative refusals are omitted.
pub failures: Vec<Failure>,
}
/// Artifact-bound evaluation report, never consumed for checkpoint selection.
#[derive(Debug, Serialize)]
pub struct EvaluationReport {
/// Actual SafeTensors bytes evaluated, independent of historical Python checkpoint IDs.
pub weights_sha256: String,
/// Exact configuration bytes binding vocabulary, labels, architecture and admission.
pub config_sha256: String,
/// SHA-256 of the complete materialized evaluation dataset.
pub evaluation_data_sha256: String,
/// Artifact admission settings used without threshold tuning.
pub thresholds: crate::config::Thresholds,
/// Corpus exposure and separation policy.
pub policy: String,
/// Outcomes for each named source corpus.
pub corpora: BTreeMap<String, CorpusResult>,
}
/// Evaluation input, I/O or model failures; these never inflate refusal metrics.
#[derive(Debug, Error)]
pub enum EvaluationError {
/// Dataset or artifact read failed.
#[error(transparent)]
Io(#[from] std::io::Error),
/// Dataset cannot be decoded.
#[error(transparent)]
Json(#[from] serde_json::Error),
/// Unsupported schema or contradictory source partition.
#[error("Invalid evaluation schema or partition.")]
InvalidData,
/// A configuration or weight file changed while loading or scoring the model.
#[error("Model artifacts changed during evaluation; no report was produced.")]
ArtifactChanged,
/// Artifact validation or model construction failed before scoring.
#[error(transparent)]
Model(#[from] ModelError),
/// A native inference failure interrupted evaluation.
#[error(transparent)]
Inference(#[from] InferenceError),
}
/// Identity of both files that jointly determine an artifact's predictions.
#[derive(Debug, PartialEq, Eq)]
struct ArtifactSnapshot {
/// Actual weight serialization, separate from historical checkpoint provenance.
weights_sha256: String,
/// Vocabulary, architecture, label order, thresholds and provenance metadata.
config_sha256: String,
}
impl ArtifactSnapshot {
/// Read a snapshot before loading instead of attributing later files to old predictions.
fn read(directory: &Path) -> Result<Self, EvaluationError> {
Ok(Self {
weights_sha256: format!(
"{:x}",
Sha256::digest(fs::read(directory.join("model.safetensors"))?)
),
config_sha256: format!(
"{:x}",
Sha256::digest(fs::read(directory.join("config.json"))?)
),
})
}
/// Reject changed serialized inputs before a report can be emitted.
fn verify_unchanged(&self, directory: &Path) -> Result<(), EvaluationError> {
if self != &Self::read(directory)? {
return Err(EvaluationError::ArtifactChanged);
}
Ok(())
}
}
/// Recognize source identities instead of accepting arbitrary text as hashes.
fn is_sha256(value: &str) -> bool {
value.len() == 64
&& value
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}
/// Reconstruct expected code only from ordered known labels and parsed literal arguments.
fn labeled_program(case: &EvaluationCase) -> Result<Program, EvaluationError> {
let labels: Vec<&str> = match (case.action.as_deref(), case.actions.as_slice()) {
(Some(label), []) => vec![label],
(None, [first, second]) => vec![first.as_str(), second.as_str()],
_ => return Err(EvaluationError::InvalidData),
};
let clauses = parse_command(&case.input).map_err(|_| EvaluationError::InvalidData)?;
if clauses.len() != labels.len() {
return Err(EvaluationError::InvalidData);
}
let actions = labels
.into_iter()
.zip(clauses)
.map(|(label, clause)| {
let kind = ActionKind::from_label(label).map_err(|_| EvaluationError::InvalidData)?;
Action::new(kind, clause.name).map_err(|_| EvaluationError::InvalidData)
})
.collect::<Result<Vec<_>, _>>()?;
Program::new(actions).map_err(|_| EvaluationError::InvalidData)
}
/// Validate one partition and require expected code to match its labels, order and literals.
fn validate_case(case: &EvaluationCase) -> Result<(), EvaluationError> {
if case.input.trim().is_empty() {
return Err(EvaluationError::InvalidData);
}
match (case.split.as_str(), case.expected.as_deref()) {
("supported", Some(expected)) if labeled_program(case)?.to_lisp() == expected => Ok(()),
("unsupported", None) if case.action.is_none() && case.actions.is_empty() => Ok(()),
_ => Err(EvaluationError::InvalidData),
}
}
/// Validate the complete dataset before scoring so malformed rows cannot yield a partial report.
fn validate_data(data: &EvaluationData) -> Result<(), EvaluationError> {
if data.format_version != 1 || data.policy.trim().is_empty() || data.corpora.is_empty() {
return Err(EvaluationError::InvalidData);
}
for (name, corpus) in &data.corpora {
if name.trim().is_empty() || !is_sha256(&corpus.sha256) || corpus.cases.is_empty() {
return Err(EvaluationError::InvalidData);
}
for case in &corpus.cases {
validate_case(case)?;
}
}
Ok(())
}
/// Decode and validate immutable benchmark bytes without loading a numerical model.
///
/// Single-action version-one datasets remain accepted. Two-action cases use
/// `action: null` with exactly two ordered, distinct labels in `actions`.
pub fn validate_data_bytes(bytes: &[u8]) -> Result<EvaluationData, EvaluationError> {
let data: EvaluationData = serde_json::from_slice(bytes)?;
validate_data(&data)?;
Ok(data)
}
/// Load and evaluate one unchanged artifact snapshot against an explicit frozen dataset.
pub fn evaluate(model_dir: &Path, data_path: &Path) -> Result<EvaluationReport, EvaluationError> {
let bytes = fs::read(data_path)?;
let data = validate_data_bytes(&bytes)?;
let snapshot = ArtifactSnapshot::read(model_dir)?;
let engine = ModelEngine::load(model_dir)?;
snapshot.verify_unchanged(model_dir)?;
let thresholds = engine.thresholds();
let mut results = BTreeMap::new();
for (name, corpus) in data.corpora {
let mut result = CorpusResult {
source_sha256: corpus.sha256,
..CorpusResult::default()
};
for case in corpus.cases {
evaluate_case(&engine, case, &mut result)?;
}
results.insert(name, result);
}
snapshot.verify_unchanged(model_dir)?;
Ok(EvaluationReport {
weights_sha256: snapshot.weights_sha256,
config_sha256: snapshot.config_sha256,
evaluation_data_sha256: format!("{:x}", Sha256::digest(bytes)),
thresholds,
policy: data.policy,
corpora: results,
})
}
/// Reduce one decision into overall, novelty, family and action summaries.
fn evaluate_case(
engine: &ModelEngine,
case: EvaluationCase,
result: &mut CorpusResult,
) -> Result<(), EvaluationError> {
let supported = match (case.split.as_str(), case.expected.is_some()) {
("supported", true) => true,
("unsupported", false) => false,
_ => return Err(EvaluationError::InvalidData),
};
let (actual, reason) = match engine.predict(&case.input, None, None) {
Ok(program) => (Some(program.to_lisp()), None),
Err(error) if error.is_refusal() => (None, Some(error.to_string())),
Err(error) => return Err(error.into()),
};
let observe = |counts: &mut Counts| counts.observe(actual.as_deref(), case.expected.as_deref());
if supported {
observe(&mut result.supported);
if case.novel_to_both {
observe(&mut result.novel_to_both_supported);
}
for label in case.action.iter().chain(case.actions.iter()) {
observe(result.per_action.entry(label.to_owned()).or_default());
}
} else {
observe(&mut result.unsupported);
if let Some(group) = &case.group {
observe(
result
.unsupported_groups
.entry(group.to_owned())
.or_default(),
);
}
}
if actual != case.expected {
result.failures.push(Failure {
input: case.input,
expected: case.expected,
actual,
reason,
});
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
/// Construct one schema-valid supported example without any model I/O.
fn dataset(action: Option<&str>, expected: Option<&str>, split: &str) -> EvaluationData {
let case = EvaluationCase {
input: "split right".into(),
expected: expected.map(str::to_owned),
split: split.into(),
action: action.map(str::to_owned),
actions: Vec::new(),
group: None,
novel_to_both: false,
};
EvaluationData {
format_version: 1,
policy: "frozen regression fixtures".into(),
corpora: [(
"regression".into(),
Corpus {
sha256: "a".repeat(64),
cases: vec![case],
},
)]
.into_iter()
.collect(),
}
}
#[test]
fn supported_cases_require_known_actions_and_consistent_partitions()
-> Result<(), EvaluationError> {
validate_data(&dataset(
Some("split-window-right"),
Some("(split-window-right)"),
"supported",
))?;
for data in [
dataset(None, Some("(split-window-right)"), "supported"),
dataset(
Some("arbitrary-eval"),
Some("(split-window-right)"),
"supported",
),
dataset(Some("split-window-right"), None, "supported"),
dataset(Some("split-window-right"), None, "unsupported"),
dataset(None, Some("(split-window-right)"), "unsupported"),
] {
assert!(matches!(
validate_data(&data),
Err(EvaluationError::InvalidData)
));
}
validate_data(&dataset(None, None, "unsupported"))?;
Ok(())
}
#[test]
fn composed_labels_must_match_order_literals_and_program_shape() -> Result<(), EvaluationError>
{
let base = serde_json::json!({
"input":"open file \"one.el\" then search forward for \"needle\"",
"expected":"(progn (find-file \"one.el\") (search-forward \"needle\"))",
"split":"supported", "action":null,
"actions":["find-file","search-forward"], "group":null, "novel_to_both":false
});
validate_case(&serde_json::from_value(base.to_owned())?)?;
for (field, value) in [
(
"actions",
serde_json::json!(["search-forward", "find-file"]),
),
("actions", serde_json::json!(["find-file", "find-file"])),
("actions", serde_json::json!(["find-file"])),
(
"actions",
serde_json::json!(["find-file", "arbitrary-eval"]),
),
("action", serde_json::json!("find-file")),
(
"expected",
serde_json::json!("(progn (find-file \"two.el\") (search-forward \"needle\"))"),
),
(
"expected",
serde_json::json!("(progn (search-forward \"needle\") (find-file \"one.el\"))"),
),
("input", serde_json::json!("open file \"one.el\"")),
(
"input",
serde_json::json!(
"open file \"one.el\" then search forward for \"needle\" then save"
),
),
] {
let mut invalid = base.to_owned();
invalid
.as_object_mut()
.ok_or(EvaluationError::InvalidData)?
.insert(field.to_owned(), value);
assert!(matches!(
validate_case(&serde_json::from_value(invalid)?),
Err(EvaluationError::InvalidData)
));
}
Ok(())
}
#[test]
fn original_single_action_schema_stays_compatible_and_extra_fields_fail()
-> Result<(), EvaluationError> {
let valid = r#"{"input":"save the current buffer","expected":"(save-buffer)","split":"supported","action":"save-buffer","group":null,"novel_to_both":false}"#;
let case: EvaluationCase = serde_json::from_str(valid)?;
assert!(case.actions.is_empty());
validate_case(&case)?;
let mut unknown: serde_json::Value = serde_json::from_str(valid)?;
unknown
.as_object_mut()
.ok_or(EvaluationError::InvalidData)?
.insert("extra".to_owned(), serde_json::json!(true));
assert!(serde_json::from_value::<EvaluationCase>(unknown).is_err());
Ok(())
}
#[test]
fn arbitrary_source_hashes_and_unknown_schema_fields_are_rejected()
-> Result<(), EvaluationError> {
let mut data = dataset(None, None, "unsupported");
let corpus = data
.corpora
.values_mut()
.next()
.ok_or(EvaluationError::InvalidData)?;
corpus.sha256 = "not-a-checkpoint-digest".into();
assert!(matches!(
validate_data(&data),
Err(EvaluationError::InvalidData)
));
assert!(
serde_json::from_str::<EvaluationData>(
r#"{"format_version":1,"policy":"frozen","corpora":{},"unknown":true}"#
)
.is_err()
);
Ok(())
}
#[test]
fn either_changed_model_file_invalidates_the_snapshot() -> Result<(), EvaluationError> {
let directory = tempfile::tempdir()?;
let weights = directory.path().join("model.safetensors");
let config = directory.path().join("config.json");
fs::write(&weights, b"original weights")?;
fs::write(&config, b"original config")?;
let snapshot = ArtifactSnapshot::read(directory.path())?;
snapshot.verify_unchanged(directory.path())?;
fs::write(&weights, b"changed weights")?;
assert!(matches!(
snapshot.verify_unchanged(directory.path()),
Err(EvaluationError::ArtifactChanged)
));
fs::write(&weights, b"original weights")?;
fs::write(&config, b"changed vocabulary or thresholds")?;
assert!(matches!(
snapshot.verify_unchanged(directory.path()),
Err(EvaluationError::ArtifactChanged)
));
Ok(())
}
#[test]
fn malformed_datasets_are_refused_before_loading_model_files() -> Result<(), EvaluationError> {
let directory = tempfile::tempdir()?;
let path = directory.path().join("evaluation.json");
fs::write(&path, br#"{"format_version":1,"policy":"frozen","corpora":{"bad":{"sha256":"bogus","cases":[]}}}"#)?;
let missing_model = directory.path().join("no-model-here");
assert!(matches!(
evaluate(&missing_model, &path),
Err(EvaluationError::InvalidData)
));
Ok(())
}
}
|