//! Strict user examples merged into a frozen training/calibration contract. //! //! Only training rows and their hard-example indices may grow. Calibration, //! incumbent selection evidence and the independent benchmark remain frozen. use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; use serde_json::Value; use thiserror::Error; use unicode_normalization::UnicodeNormalization; use crate::actions::{Action, ActionKind, parse_command}; use crate::catalog::{ActionCatalog, OpenAction, parse_open_command}; use crate::config::expected_labels; use crate::evaluation::EvaluationData; use crate::tokenizer::{TokenizerError, tokenize}; use crate::training::{TrainingError, rows_sha256, validate_training_data_bytes}; /// One authored instruction and its supervised closed-set label. #[derive(Debug, Deserialize, Serialize, PartialEq, Eq)] #[serde(deny_unknown_fields)] pub struct Example { /// Materialized English instruction, with any literal encoded as JSON quotes. pub instruction: String, /// One existing action label or the explicit `reject` label. pub label: String, /// Include this training row in hard-example sampling. #[serde(default)] pub hard: bool, } /// The sole accepted import and persisted user-example schema. #[derive(Debug, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct ExampleFile { /// Schema identity, currently one. pub format_version: u32, /// User-owned examples; calibration and evaluation cannot be imported here. pub examples: Vec, } impl Default for ExampleFile { fn default() -> Self { Self { format_version: 1, examples: Vec::new(), } } } /// A complete validated portable training file produced from immutable sources. pub struct MaterializedData { /// Serialized trainer input with original calibration/reference fields intact. pub bytes: Vec, /// Number of final training rows, including the shared corpus. pub training_rows: usize, /// Number of additional distinct training examples. pub added_examples: usize, } /// Dataset-boundary failures distinguish conflicts from withheld-data leakage. #[derive(Debug, Error)] pub enum DatasetError { /// The import schema or an example cannot describe a usable supervised row. #[error("invalid example data: {0}")] Invalid(&'static str), /// The label is outside the fixed output vocabulary. #[error("unknown example label: {0}")] Label(String), /// Two normalized instructions assert different labels. #[error("conflicting labels for normalized instruction: {0}")] Conflict(String), /// A new example overlaps calibration or the frozen benchmark. #[error("example overlaps held-out calibration or evaluation: {0}")] Leakage(String), /// A supported example has an invalid action or argument shape. #[error("supported example is not a valid single action: {0}")] Command(#[from] crate::actions::InputError), /// JSON fields, duplicate members or value types are malformed. #[error(transparent)] Json(#[from] serde_json::Error), /// The authoritative portable trainer contract failed validation. #[error(transparent)] Training(#[from] TrainingError), /// Token normalization could not be constructed. #[error(transparent)] Tokenizer(#[from] TokenizerError), } /// Normalize matching identity without changing the stored classifier sentence. pub(crate) fn clause_key(text: &str) -> Result { let folded: String = text.nfkc().flat_map(char::to_lowercase).collect(); Ok(tokenize(&folded)?.join(" ")) } /// Convert a real command to the exact classifier/bi-encoder clause under an optional `ActionCatalog`. pub(crate) fn training_phrase_with_catalog( example: &Example, catalog: Option<&ActionCatalog>, ) -> Result { if example.instruction.trim().is_empty() || example.instruction.contains('\0') || example.instruction.len() > 4096 { return Err(DatasetError::Invalid( "instruction must be nonempty, bounded and NUL-free", )); } let parsed = match catalog { Some(_) => parse_open_command(&example.instruction), None => parse_command(&example.instruction), }; if example.label == "reject" { let phrase = match parsed { Ok(clauses) if clauses.len() == 1 => { clauses .into_iter() .next() .ok_or(DatasetError::Invalid("missing rejection clause"))? .text } _ => clause_key(&example.instruction)?, }; if clause_key(&phrase)?.is_empty() { return Err(DatasetError::Invalid( "rejection example needs English words", )); } return Ok(phrase); } match catalog { Some(cat) => { let Some(spec) = cat.get(&example.label) else { return Err(DatasetError::Label(example.label.to_owned())); }; let mut clauses = parsed?; if clauses.len() != 1 { return Err(DatasetError::Invalid( "one example must label exactly one action", )); } let clause = clauses .pop() .ok_or(DatasetError::Invalid("missing action clause"))?; OpenAction::new(spec, clause.name)?; Ok(clause.text) } None => { if !expected_labels().contains(&example.label) { return Err(DatasetError::Label(example.label.to_owned())); } let mut clauses = parsed?; if clauses.len() != 1 { return Err(DatasetError::Invalid( "one example must label exactly one action", )); } let clause = clauses .pop() .ok_or(DatasetError::Invalid("missing action clause"))?; Action::new(ActionKind::from_label(&example.label)?, clause.name)?; Ok(clause.text) } } } /// Read a strict schema and reject unsupported versions before modifying files. pub fn parse_examples(bytes: &[u8]) -> Result { parse_examples_with_catalog(bytes, None) } /// Read a strict schema validated against an optional open `ActionCatalog`. pub fn parse_examples_with_catalog( bytes: &[u8], catalog: Option<&ActionCatalog>, ) -> Result { let file: ExampleFile = serde_json::from_slice(bytes)?; if file.format_version != 1 { return Err(DatasetError::Invalid("unsupported examples format_version")); } for example in &file.examples { training_phrase_with_catalog(example, catalog)?; } Ok(file) } /// Decode one exact portable row array after authoritative schema validation. fn rows(source: &Value, field: &str) -> Result, DatasetError> { let value = source .get(field) .ok_or(DatasetError::Invalid("missing corpus rows"))?; Ok(serde_json::from_value(value.to_owned())?) } /// Reserve normalized held-out phrases, including individual benchmark clauses. fn withheld(source: &Value, evaluation: &[u8]) -> Result, DatasetError> { let mut reserved = BTreeSet::new(); for (phrase, _) in rows(source, "calibration_rows")? { reserved.insert(clause_key(&phrase)?); } let data: EvaluationData = serde_json::from_slice(evaluation)?; if data.format_version != 1 || data.corpora.is_empty() { return Err(DatasetError::Invalid("invalid frozen benchmark")); } for corpus in data.corpora.values() { for case in &corpus.cases { reserved.insert(clause_key(&case.input)?); if let Ok(clauses) = parse_command(&case.input) { for clause in clauses { reserved.insert(clause_key(&clause.text)?); } } } } Ok(reserved) } /// Extract canonical frozen training labels and held-out benchmark keys. pub(crate) fn frozen_maps( training: &[u8], evaluation: &[u8], ) -> Result<(BTreeMap, BTreeSet), DatasetError> { validate_training_data_bytes(training)?; let source: Value = serde_json::from_slice(training)?; let reserved = withheld(&source, evaluation)?; let mut known = BTreeMap::new(); for (phrase, label) in rows(&source, "training_rows")? { known.insert(clause_key(&phrase)?, label); } Ok((known, reserved)) } /// Merge imports without duplicate weighting, rejecting conflicting supervision. pub fn merge_examples( training: &[u8], evaluation: &[u8], current: ExampleFile, incoming: ExampleFile, ) -> Result { merge_examples_with_catalog(training, evaluation, current, incoming, None) } /// Merge imports validated against an optional open `ActionCatalog`. pub fn merge_examples_with_catalog( training: &[u8], evaluation: &[u8], current: ExampleFile, incoming: ExampleFile, catalog: Option<&ActionCatalog>, ) -> Result { if current.format_version != 1 || incoming.format_version != 1 { return Err(DatasetError::Invalid("unsupported examples format_version")); } let (mut known, reserved) = frozen_maps(training, evaluation)?; let mut merged = ExampleFile::default(); for example in current.examples.into_iter().chain(incoming.examples) { let phrase = training_phrase_with_catalog(&example, catalog)?; let identity = clause_key(&phrase)?; if let Some(label) = known.get(&identity) { if label != &example.label { return Err(DatasetError::Conflict(phrase)); } if example.hard { for existing in &mut merged.examples { if clause_key(&training_phrase_with_catalog(existing, catalog)?)? == identity { existing.hard = true; } } } continue; } if reserved.contains(&identity) { return Err(DatasetError::Leakage(phrase)); } known.insert(identity, example.label.to_owned()); merged.examples.push(example); } Ok(merged) } /// Append only training supervision and retain every frozen calibration field. pub fn materialize( training: &[u8], evaluation: &[u8], examples: ExampleFile, ) -> Result { materialize_with_catalog(training, evaluation, examples, None) } /// Append training supervision validated against an optional open `ActionCatalog`. pub fn materialize_with_catalog( training: &[u8], evaluation: &[u8], examples: ExampleFile, catalog: Option<&ActionCatalog>, ) -> Result { let merged = merge_examples_with_catalog( training, evaluation, ExampleFile::default(), examples, catalog, )?; let mut source: Value = serde_json::from_slice(training)?; let mut training_rows = rows(&source, "training_rows")?; let added_examples = merged.examples.len(); let mut hard: Vec = serde_json::from_value( source .get("hard_training_indices") .ok_or(DatasetError::Invalid("missing hard-example indices"))? .to_owned(), )?; for example in merged.examples { if example.hard { hard.push(training_rows.len()); } training_rows.push(( training_phrase_with_catalog(&example, catalog)?, example.label, )); } let object = source .as_object_mut() .ok_or(DatasetError::Invalid("training must be an object"))?; object.insert( "training_sha256".into(), Value::String(rows_sha256(&training_rows)?), ); object.insert( "training_rows".into(), serde_json::to_value(&training_rows)?, ); object.insert("hard_training_indices".into(), serde_json::to_value(hard)?); let bytes = serde_json::to_vec_pretty(&source)?; if catalog.is_none() { validate_training_data_bytes(&bytes)?; } Ok(MaterializedData { bytes, training_rows: training_rows.len(), added_examples, }) }