Download src/composition.rs from ElderRyan/lispm-llm: direct link, hf CLI and curl.
- Browser
- Download file 12.6 kB
-
https://huggingface.co/ElderRyan/lispm-llm/resolve/main/src/composition.rs
- Command line
-
hf download hf://ElderRyan/lispm-llm/src/composition.rs
-
curl -L -o composition.rs https://huggingface.co/ElderRyan/lispm-llm/resolve/main/src/composition.rs
12.6 kB
| //! Deterministic two-action regression cohorts built from frozen single-action wording. | |
| //! | |
| //! The Cartesian product covers every ordered pair of distinct catalog actions. | |
| //! Reusing source wording measures composition, not independently authored language | |
| //! or successful execution in an editor. The original source cohorts are retained. | |
| use crate::actions::{Action, ActionKind, InputError, Program, parse_command}; | |
| use crate::evaluation::{Corpus, EvaluationCase, EvaluationError, validate_data_bytes}; | |
| use serde_json::Value; | |
| use sha2::{Digest, Sha256}; | |
| use std::collections::BTreeMap; | |
| use thiserror::Error; | |
| /// Stable names used by reports and the per-corpus nonregression gate. | |
| const CORPORA: [&str; 3] = [ | |
| "composition_emacs", | |
| "composition_lispm", | |
| "composition_cross_domain", | |
| ]; | |
| /// Failure to derive a complete, validated and reproducible composition benchmark. | |
| pub enum CompositionError { | |
| /// Source bytes or reconstructed expectations violate the evaluator contract. | |
| Evaluation( EvaluationError), | |
| /// A required historical corpus is absent. | |
| MissingCorpus(&'static str), | |
| /// Every catalog action needs at least one single-action source phrase. | |
| MissingAction(&'static str), | |
| /// An existing derived corpus must not be silently overwritten. | |
| AlreadyExpanded(&'static str), | |
| /// A source row is not a single operation from its owning domain. | |
| InvalidSource, | |
| /// Input language or typed argument construction failed. | |
| Input( InputError), | |
| /// Canonical JSON serialization failed. | |
| Json( serde_json::Error), | |
| } | |
| /// Literal roles are identity-free values, so copying preserves their meaning. | |
| enum Role { | |
| /// The literal belongs to the first operation. | |
| First, | |
| /// The literal belongs to the second operation. | |
| Second, | |
| } | |
| impl Role { | |
| /// Return a distinct readable marker for argument preservation checks. | |
| const fn marker(self) -> &'static str { | |
| match self { | |
| Self::First => "first", | |
| Self::Second => "second", | |
| } | |
| } | |
| } | |
| /// Borrow source rows grouped by the authoritative action labels. | |
| type Sources<'a> = BTreeMap<&'a str, Vec<&'a EvaluationCase>>; | |
| /// Classify an existing action's application domain without changing its meaning. | |
| fn is_lispm(kind: ActionKind) -> bool { | |
| kind.label().starts_with("lispm-") | |
| } | |
| /// Collect one source domain and reject falsely labeled composite source rows. | |
| fn collect_sources<'a>(corpus: &'a Corpus, lispm: bool) -> Result<Sources<'a>, CompositionError> { | |
| let mut sources = BTreeMap::<&str, Vec<&EvaluationCase>>::new(); | |
| for case in &corpus.cases { | |
| if case.split != "supported" { | |
| continue; | |
| } | |
| let label = case | |
| .action | |
| .as_deref() | |
| .ok_or(CompositionError::InvalidSource)?; | |
| let kind = ActionKind::from_label(label)?; | |
| if !case.actions.is_empty() || is_lispm(kind) != lispm { | |
| return Err(CompositionError::InvalidSource); | |
| } | |
| sources.entry(label).or_default().push(case); | |
| } | |
| Ok(sources) | |
| } | |
| /// Select a deterministic representative while keeping source row order significant. | |
| fn representative<'a>( | |
| sources: &Sources<'a>, | |
| kind: ActionKind, | |
| selection: usize, | |
| ) -> Result<&'a EvaluationCase, CompositionError> { | |
| let phrases = sources | |
| .get(kind.label()) | |
| .filter(|rows| !rows.is_empty()) | |
| .ok_or(CompositionError::MissingAction(kind.label()))?; | |
| phrases | |
| .get(selection % phrases.len()) | |
| .copied() | |
| .ok_or(CompositionError::MissingAction(kind.label())) | |
| } | |
| /// Produce distinct legal literal data, respecting the URL and basename domains. | |
| fn argument(kind: ActionKind, role: Role) -> Option<String> { | |
| kind.argument_name()?; | |
| let marker = role.marker(); | |
| Some(match kind { | |
| ActionKind::BrowserUrl => format!("https://example.org/{marker}-argument"), | |
| ActionKind::OpenFile => format!("{marker}-file.el"), | |
| ActionKind::FinderDirectory => format!("~/{marker}-directory"), | |
| ActionKind::FinderNewFolder => format!("{marker} folder"), | |
| _ => format!("{marker} argument"), | |
| }) | |
| } | |
| /// Materialize one original phrase with a role-specific quoted literal and typed action. | |
| fn materialize( | |
| case: &EvaluationCase, | |
| kind: ActionKind, | |
| role: Role, | |
| ) -> Result<(String, Action), CompositionError> { | |
| let clauses = parse_command(&case.input)?; | |
| let [clause] = clauses.as_slice() else { | |
| return Err(CompositionError::InvalidSource); | |
| }; | |
| let literal = argument(kind, role); | |
| let phrase = match &literal { | |
| Some(value) => clause.text.replace("NAME", &serde_json::to_string(value)?), | |
| None => clause.text.to_owned(), | |
| }; | |
| Ok((phrase, Action::new(kind, literal)?)) | |
| } | |
| /// Construct a complete expected program; no model prediction becomes a benchmark label. | |
| fn compose( | |
| first: (&EvaluationCase, ActionKind), | |
| second: (&EvaluationCase, ActionKind), | |
| ) -> Result<EvaluationCase, CompositionError> { | |
| let (first_phrase, first_action) = materialize(first.0, first.1, Role::First)?; | |
| let (second_phrase, second_action) = materialize(second.0, second.1, Role::Second)?; | |
| let expected = Program::new(vec![first_action, second_action])?.to_lisp(); | |
| Ok(EvaluationCase { | |
| input: format!("{first_phrase} then {second_phrase}"), | |
| expected: Some(expected), | |
| split: "supported".to_owned(), | |
| action: None, | |
| actions: vec![first.1.label().to_owned(), second.1.label().to_owned()], | |
| group: None, | |
| novel_to_both: first.0.novel_to_both || second.0.novel_to_both, | |
| }) | |
| } | |
| /// Select the regression cohort determined by both action domains. | |
| fn cohort_name(first: ActionKind, second: ActionKind) -> &'static str { | |
| match (is_lispm(first), is_lispm(second)) { | |
| (false, false) => "composition_emacs", | |
| (true, true) => "composition_lispm", | |
| _ => "composition_cross_domain", | |
| } | |
| } | |
| /// Hash deterministic serialized cases, binding expected labels, literals and source wording. | |
| fn derived_corpus(cases: Vec<EvaluationCase>) -> Result<Corpus, CompositionError> { | |
| let sha256 = format!("{:x}", Sha256::digest(serde_json::to_vec(&cases)?)); | |
| Ok(Corpus { sha256, cases }) | |
| } | |
| /// Append all 2,256 distinct ordered action pairs while preserving original cohort values. | |
| /// | |
| /// Requires `historical_emacs` and `historical_lispm`, together covering all 48 | |
| /// actions. The result is a new version-one evaluation document, not an edit to | |
| /// any existing project or frozen source. Repeated application is rejected. | |
| /// Derived cohort hashes identify their compact serialized case arrays. | |
| pub fn extend(bytes: &[u8]) -> Result<Vec<u8>, CompositionError> { | |
| let data = validate_data_bytes(bytes)?; | |
| for name in CORPORA { | |
| if data.corpora.contains_key(name) { | |
| return Err(CompositionError::AlreadyExpanded(name)); | |
| } | |
| } | |
| let emacs = data | |
| .corpora | |
| .get("historical_emacs") | |
| .ok_or(CompositionError::MissingCorpus("historical_emacs"))?; | |
| let lispm = data | |
| .corpora | |
| .get("historical_lispm") | |
| .ok_or(CompositionError::MissingCorpus("historical_lispm"))?; | |
| let mut sources = collect_sources(emacs, false)?; | |
| sources.extend(collect_sources(lispm, true)?); | |
| let mut derived = BTreeMap::<&str, Vec<EvaluationCase>>::new(); | |
| for (first_index, first) in ActionKind::ALL.into_iter().enumerate() { | |
| for (second_index, second) in ActionKind::ALL.into_iter().enumerate() { | |
| if first == second { | |
| continue; | |
| } | |
| // Both indices are below the fixed catalog size 48; these sums cannot overflow. | |
| let first_case = representative(&sources, first, first_index + second_index)?; | |
| let second_case = representative(&sources, second, first_index * 3 + second_index)?; | |
| derived | |
| .entry(cohort_name(first, second)) | |
| .or_default() | |
| .push(compose((first_case, first), (second_case, second))?); | |
| } | |
| } | |
| let mut output: Value = serde_json::from_slice(bytes)?; | |
| let corpora = output | |
| .get_mut("corpora") | |
| .and_then(Value::as_object_mut) | |
| .ok_or(CompositionError::InvalidSource)?; | |
| for (name, cases) in derived { | |
| corpora.insert( | |
| name.to_owned(), | |
| serde_json::to_value(derived_corpus(cases)?)?, | |
| ); | |
| } | |
| output | |
| .as_object_mut() | |
| .ok_or(CompositionError::InvalidSource)? | |
| .insert( | |
| "policy".to_owned(), | |
| Value::String(format!( | |
| "{} Added composition cohorts are deterministic two-action recombinations of historical wording, not independent language samples or execution tasks.", | |
| data.policy | |
| )), | |
| ); | |
| let encoded = serde_json::to_vec_pretty(&output)?; | |
| validate_data_bytes(&encoded)?; | |
| Ok(encoded) | |
| } | |
| mod tests { | |
| use super::*; | |
| use std::{collections::BTreeSet, fs, path::Path}; | |
| /// Read the immutable source benchmark used by the packaged native evaluator. | |
| fn original() -> Result<Vec<u8>, std::io::Error> { | |
| fs::read(Path::new(env!("CARGO_MANIFEST_DIR")).join("data/evaluation.json")) | |
| } | |
| fn complete_ordered_pairs_preserve_original_cohorts_and_distinct_literals() | |
| -> Result<(), CompositionError> { | |
| let bytes = original().map_err(EvaluationError::Io)?; | |
| let generated = extend(&bytes)?; | |
| assert_eq!(generated, extend(&bytes)?); | |
| let source: Value = serde_json::from_slice(&bytes)?; | |
| let output: Value = serde_json::from_slice(&generated)?; | |
| for name in ["historical_emacs", "historical_lispm", "fresh_robustness"] { | |
| assert_eq!( | |
| source.get("corpora").and_then(|c| c.get(name)), | |
| output.get("corpora").and_then(|c| c.get(name)) | |
| ); | |
| } | |
| let data = validate_data_bytes(&generated)?; | |
| let mut pairs = BTreeSet::new(); | |
| for (name, size) in [ | |
| ("composition_emacs", 552), | |
| ("composition_lispm", 552), | |
| ("composition_cross_domain", 1152), | |
| ] { | |
| let corpus = data | |
| .corpora | |
| .get(name) | |
| .ok_or(CompositionError::MissingCorpus(name))?; | |
| assert_eq!(corpus.cases.len(), size); | |
| assert_eq!( | |
| corpus.sha256, | |
| format!("{:x}", Sha256::digest(serde_json::to_vec(&corpus.cases)?)) | |
| ); | |
| for case in &corpus.cases { | |
| let [first, second] = case.actions.as_slice() else { | |
| return Err(CompositionError::InvalidSource); | |
| }; | |
| assert_ne!(first, second); | |
| assert!(pairs.insert((first.as_str(), second.as_str()))); | |
| let clauses = parse_command(&case.input)?; | |
| if let [first, second] = clauses.as_slice() | |
| && let (Some(first), Some(second)) = (&first.name, &second.name) | |
| { | |
| assert_ne!(first, second); | |
| assert!(first.contains("first")); | |
| assert!(second.contains("second")); | |
| } | |
| } | |
| } | |
| assert_eq!(pairs.len(), 2256); | |
| assert!(matches!( | |
| extend(&generated), | |
| Err(CompositionError::AlreadyExpanded(_)) | |
| )); | |
| Ok(()) | |
| } | |
| fn incomplete_source_catalog_is_an_error_instead_of_partial_coverage() | |
| -> Result<(), CompositionError> { | |
| let bytes = original().map_err(EvaluationError::Io)?; | |
| let mut data = validate_data_bytes(&bytes)?; | |
| let corpus = data | |
| .corpora | |
| .get_mut("historical_emacs") | |
| .ok_or(CompositionError::MissingCorpus("historical_emacs"))?; | |
| corpus | |
| .cases | |
| .retain(|case| case.action.as_deref() != Some("save-buffer")); | |
| assert!(matches!( | |
| extend(&serde_json::to_vec(&data)?), | |
| Err(CompositionError::MissingAction("save-buffer")) | |
| )); | |
| Ok(()) | |
| } | |
| } | |