//! Project transitions preserve frozen evidence and never lose authored examples. use lispm_llm::dataset::{DatasetError, ExampleFile, materialize, parse_examples}; use lispm_llm::workflow::{self, ProjectInfo, RunInfo, RunOptions, RunStatus, WorkflowError}; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; use std::fs; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; /// Published portable inputs used as immutable integration-test sources. fn root() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) } /// Create one disposable project, retaining its temporary parent for cleanup. fn project() -> Result<(tempfile::TempDir, ProjectInfo), WorkflowError> { let directory = tempfile::tempdir()?; let repository = root(); let info = workflow::init_project( &directory.path().join("project"), &repository, &repository.join("data/training.json"), &repository.join("data/evaluation.json"), )?; Ok((directory, info)) } /// One unambiguous authored paraphrase outside the frozen training/evaluation sets. fn import(label: &str, hard: bool) -> Result, serde_json::Error> { serde_json::to_vec(&json!({"format_version":1,"examples":[{ "instruction":"persist this editing buffer onto its existing disk target promptly", "label":label,"hard":hard}]})) } /// Read one required fixture member without unchecked JSON indexing. fn required<'a>(value: &'a Value, pointer: &str) -> Result<&'a Value, WorkflowError> { value .pointer(pointer) .ok_or(WorkflowError::Invalid("fixture member missing")) } #[test] fn initialization_snapshots_sources_without_modifying_them() -> Result<(), WorkflowError> { let original = fs::read(root().join("data/training.json"))?; let (_directory, info) = project()?; assert!(info.project.is_absolute()); assert!(info.baseline_model.is_absolute()); assert_eq!(info.labels.len(), 49); assert_eq!(info.added_examples, 0); assert!(info.runs.is_empty()); assert_eq!( fs::read(info.project.join("frozen/training.json"))?, original ); assert_eq!(fs::read(root().join("data/training.json"))?, original); assert_eq!( fs::read(info.baseline_model.join("model.safetensors"))?, fs::read(root().join("model.safetensors"))? ); Ok(()) } #[test] fn imports_deduplicate_normalized_phrases_and_preserve_frozen_selection() -> Result<(), WorkflowError> { let (_directory, initial) = project()?; let updated = workflow::import_examples( &initial.project, &import("save-buffer", true)?, &initial.generation, )?; assert_eq!(updated.training_rows, initial.training_rows + 1); assert_eq!(updated.added_examples, 1); let duplicate = json!({"format_version":1,"examples":[{ "instruction":"PERSIST this editing buffer onto its existing disk target promptly!", "label":"save-buffer","hard":false}]}); let repeated = workflow::import_examples( &initial.project, &serde_json::to_vec(&duplicate)?, &updated.generation, )?; assert_eq!(repeated.added_examples, 1); let frozen = fs::read(initial.project.join("frozen/training.json"))?; let before: Value = serde_json::from_slice(&frozen)?; let after = materialize( &frozen, &fs::read(initial.evaluation_data)?, parse_examples(&fs::read(initial.project.join("examples.json"))?)?, )?; let after: Value = serde_json::from_slice(&after.bytes)?; for field in [ "calibration_rows", "calibration_commands", "calibration_sha256", "reference", "selection_reference_json", "selection_reference_sha256", ] { assert_eq!(before.get(field), after.get(field)); } assert_eq!( required(&after, "/hard_training_indices")? .as_array() .map(Vec::len), required(&before, "/hard_training_indices")? .as_array() .map(|items| items.len() + 1) ); Ok(()) } #[test] fn stale_generation_and_conflicting_labels_cannot_replace_examples() -> Result<(), WorkflowError> { let (_directory, initial) = project()?; let updated = workflow::import_examples( &initial.project, &import("save-buffer", false)?, &initial.generation, )?; let bytes = fs::read(initial.project.join("examples.json"))?; assert!(matches!( workflow::import_examples( &initial.project, &import("kill-line", false)?, &initial.generation ), Err(WorkflowError::GenerationChanged) )); assert!(matches!( workflow::import_examples( &initial.project, &import("kill-line", false)?, &updated.generation ), Err(WorkflowError::Dataset(DatasetError::Conflict(_))) )); assert_eq!(fs::read(initial.project.join("examples.json"))?, bytes); Ok(()) } #[test] fn replacing_authored_examples_corrects_labels_or_removes_rows_without_changing_frozen_data() -> Result<(), WorkflowError> { let (_directory, initial) = project()?; let frozen = fs::read(initial.project.join("frozen/training.json"))?; let added = workflow::import_examples( &initial.project, &import("save-buffer", false)?, &initial.generation, )?; assert!(matches!( workflow::replace_examples( &initial.project, &import("kill-line", true)?, &initial.generation ), Err(WorkflowError::GenerationChanged) )); let corrected = workflow::replace_examples( &initial.project, &import("kill-line", true)?, &added.generation, )?; assert_eq!(corrected.added_examples, 1); let examples = parse_examples(&fs::read(initial.project.join("examples.json"))?)?; assert_eq!( examples.examples.first().map(|item| item.label.as_str()), Some("kill-line") ); let cleared = workflow::replace_examples( &initial.project, &serde_json::to_vec(&ExampleFile::default())?, &corrected.generation, )?; assert_eq!(cleared.added_examples, 0); assert_eq!(cleared.training_rows, initial.training_rows); assert_eq!( fs::read(initial.project.join("frozen/training.json"))?, frozen ); Ok(()) } #[test] fn held_out_examples_and_unknown_import_fields_never_enter_training() -> Result<(), WorkflowError> { let (_directory, info) = project()?; let training: Value = serde_json::from_slice(&fs::read(info.project.join("frozen/training.json"))?)?; let calibration = json!({"format_version":1,"examples":[{"instruction":required(&training,"/calibration_rows/0/0")?, "label":required(&training,"/calibration_rows/0/1")?}]}); assert!(matches!( workflow::import_examples( &info.project, &serde_json::to_vec(&calibration)?, &info.generation ), Err(WorkflowError::Dataset(DatasetError::Leakage(_))) )); let evaluation: Value = serde_json::from_slice(&fs::read(&info.evaluation_data)?)?; let case = required(&evaluation, "/corpora/historical_emacs/cases/0")?; let benchmark = json!({"format_version":1,"examples":[{ "instruction":required(case,"/input")?,"label":required(case,"/action")?}]}); assert!(matches!( workflow::import_examples( &info.project, &serde_json::to_vec(&benchmark)?, &info.generation ), Err(WorkflowError::Dataset(DatasetError::Leakage(_))) )); for invalid in [ br#"{"format_version":1,"examples":[],"calibration_rows":[]}"#.as_slice(), br#"{"format_version":1,"format_version":1,"examples":[]}"#.as_slice(), br#"{"format_version":1,"examples":[{"instruction":"save","label":"eval"}]}"#.as_slice(), ] { assert!(workflow::import_examples(&info.project, invalid, &info.generation).is_err()); } assert_eq!(workflow::project_info(&info.project)?.added_examples, 0); Ok(()) } #[test] fn immutable_snapshot_changes_and_busy_writers_fail_explicitly() -> Result<(), WorkflowError> { let (_directory, info) = project()?; let lock = info.project.join(".workflow.lock"); fs::write(&lock, "test owner")?; assert!(matches!( workflow::import_examples( &info.project, &import("save-buffer", false)?, &info.generation ), Err(WorkflowError::Busy) )); fs::remove_file(lock)?; fs::write( info.project.join("frozen/evaluation.json"), "changed frozen benchmark", )?; assert!(matches!( workflow::project_info(&info.project), Err(WorkflowError::Changed(_)) )); Ok(()) } #[test] fn cancelled_training_and_invalid_run_names_have_no_candidate_side_effects() -> Result<(), WorkflowError> { let (_directory, info) = project()?; let cancelled = AtomicBool::new(true); let error = workflow::train_project( &info.project, &RunOptions::default(), &cancelled, &mut |_| {}, ) .err() .ok_or(WorkflowError::Invalid("cancellation was ignored"))?; assert!(error.is_cancelled()); assert!(workflow::project_info(&info.project)?.runs.is_empty()); assert!(workflow::finalize_run(&info.project, "../outside").is_err()); assert!(workflow::activate_run(&info.project, "../outside").is_err()); assert!(workflow::rollback(&info.project).is_err()); Ok(()) } #[test] fn direct_materialization_rejects_unsupported_example_versions() -> Result<(), WorkflowError> { let training = fs::read(root().join("data/training.json"))?; let evaluation = fs::read(root().join("data/evaluation.json"))?; assert!( materialize( &training, &evaluation, ExampleFile { format_version: 2, examples: vec![] } ) .is_err() ); Ok(()) } #[test] fn collecting_data_cannot_prevent_a_reserved_run_from_recording_completion() -> Result<(), WorkflowError> { let (_directory, info) = project()?; let cancelled = AtomicBool::new(false); let lock = info.project.join(".workflow.lock"); let mut write_error = None; let result = workflow::train_project( &info.project, &RunOptions::default(), &cancelled, &mut |event| { if event.get("phase").and_then(Value::as_str) == Some("run_reserved") { if let Err(error) = fs::write(&lock, "concurrent example collector") { write_error = Some(error); } cancelled.store(true, Ordering::Release); } }, ); if let Some(error) = write_error { return Err(error.into()); } let error = result .err() .ok_or(WorkflowError::Invalid("expected cancellation"))?; assert!(error.is_cancelled()); let after = workflow::project_info(&info.project)?; assert_eq!(after.runs.len(), 1); assert_eq!( after.runs.first().map(|run| &run.status), Some(&RunStatus::Cancelled) ); assert!(lock.is_file()); fs::remove_file(lock)?; Ok(()) } /// Install a byte-identical candidate to test evidence and lifecycle independently /// of optimizer quality; production creates this state only after training. fn identical_candidate(info: &ProjectInfo) -> Result { let id = "run-identical-fixture"; let directory = info.project.join("runs").join(id); fs::create_dir(&directory)?; let model = directory.join("model"); fs::create_dir(&model)?; for name in ["config.json", "model.safetensors"] { fs::copy(info.baseline_model.join(name), model.join(name))?; } let data = fs::read(info.project.join("frozen/training.json"))?; fs::write(directory.join("training.json"), &data)?; fs::copy( info.project.join("examples.json"), directory.join("examples.json"), )?; let run = RunInfo { id: id.into(), model, steps: 1, seed: 42, threads: 2, generation: info.generation.to_owned(), training_data_sha256: format!("{:x}", Sha256::digest(&data)), status: RunStatus::Trained, artifact: Some(info.baseline.clone()), benchmark_sha256: None, finalized_model: None, error: None, }; fs::write(directory.join("run.json"), serde_json::to_vec(&run)?)?; Ok(id.into()) } #[test] fn real_benchmark_binds_finalization_activation_and_baseline_rollback() -> Result<(), WorkflowError> { let (_directory, info) = project()?; let id = identical_candidate(&info)?; assert!(workflow::finalize_run(&info.project, &id).is_err()); let cancelled = AtomicBool::new(false); let benchmark = workflow::benchmark_run(&info.project, &id, &cancelled, &mut |_| {})?; assert!(benchmark.eligible); assert_eq!(benchmark.baseline, benchmark.candidate); let reopened = workflow::benchmark_report(&info.project, &id)?; assert_eq!(reopened.baseline, benchmark.baseline); assert!(reopened.eligible); let original = fs::read(&benchmark.path)?; fs::write(&benchmark.path, b"a copied unbound report")?; assert!(matches!( workflow::benchmark_report(&info.project, &id), Err(WorkflowError::Changed(_)) )); assert!(matches!( workflow::finalize_run(&info.project, &id), Err(WorkflowError::Changed(_)) )); fs::write(&benchmark.path, original)?; assert!(matches!( workflow::finalize_run_with_control(&info.project, &id, &AtomicBool::new(true)), Err(WorkflowError::Cancelled) )); assert!(!info.project.join("finalized").join(&id).exists()); let finalized = workflow::finalize_run(&info.project, &id)?; assert!(finalized.model.is_absolute()); assert!(workflow::benchmark_report(&info.project, &id)?.eligible); let active = workflow::activate_run(&info.project, &id)?; assert_eq!(active.active_model.as_ref(), Some(&finalized.model)); // Repeating activation must not overwrite the real predecessor with itself. workflow::activate_run(&info.project, &id)?; let restored = workflow::rollback(&info.project)?; assert_eq!(restored.active_model.as_ref(), Some(&info.baseline_model)); workflow::activate_run(&info.project, &id)?; fs::write( finalized.model.join("model.safetensors"), "mutated candidate", )?; assert!(matches!( workflow::project_info(&info.project), Err(WorkflowError::Changed(_)) )); Ok(()) } /// The real subprocess consumer requires an explicitly supplied local Emacs. #[test] #[ignore = "requires LISPM_TEST_EMACS and a real isolated batch Emacs runtime"] fn task_evidence_is_mandatory_for_task_enabled_project_finalization() -> Result<(), WorkflowError> { let executable = std::env::var_os("LISPM_TEST_EMACS").ok_or(WorkflowError::Invalid( "set LISPM_TEST_EMACS to an absolute executable", ))?; let directory = tempfile::tempdir()?; let repository = root(); let options = workflow::TaskSuiteOptions { data: repository.join("data/emacs-tasks.json"), runner: repository.join("emacs/lispm-llm-benchmark.el"), emacs: PathBuf::from(executable), timeout_seconds: 60, }; let info = workflow::init_project_with_tasks( &directory.path().join("project"), &repository, &repository.join("data/training.json"), &repository.join("data/benchmark.json"), Some(&options), )?; assert!(info.task_suite.is_some()); let frozen: Value = serde_json::from_slice(&fs::read(&info.evaluation_data)?)?; assert!( frozen .pointer("/corpora/emacs_state_instructions") .is_some() ); let id = identical_candidate(&info)?; let benchmark = workflow::benchmark_run(&info.project, &id, &AtomicBool::new(false), &mut |_| {})?; assert!(benchmark.eligible); assert!( benchmark .task_comparison .as_ref() .is_some_and(|tasks| tasks.eligible) ); let original_benchmark = fs::read(&benchmark.path)?; let run_path = info.project.join("runs").join(&id).join("run.json"); let original_run = fs::read(&run_path)?; let mut stripped: Value = serde_json::from_slice(&original_benchmark)?; stripped .as_object_mut() .ok_or(WorkflowError::Invalid("benchmark object missing"))? .remove("task_comparison"); let stripped = serde_json::to_vec(&stripped)?; fs::write(&benchmark.path, &stripped)?; let mut run: RunInfo = serde_json::from_slice(&original_run)?; run.benchmark_sha256 = Some(format!("{:x}", Sha256::digest(&stripped))); fs::write(&run_path, serde_json::to_vec(&run)?)?; assert!(matches!( workflow::finalize_run(&info.project, &id), Err(WorkflowError::Invalid(_)) )); fs::write(&benchmark.path, original_benchmark)?; fs::write(&run_path, original_run)?; workflow::finalize_run(&info.project, &id)?; fs::write( info.project.join("frozen/emacs-task-runner.el"), b"changed runner", )?; assert!(matches!( workflow::project_info(&info.project), Err(WorkflowError::Changed(_)) )); Ok(()) }