use crate::projection::ai_learning::provenance::Provenance;
use crate::projection::ai_learning::split::{TRAIN, VALIDATION};
use crate::projection::ai_learning::AiLearningContext;
use crate::projection::ids::element_id;
use std::collections::BTreeSet;
pub const ZENML_FAMILY: &str = "zenml";
pub const ZENML_TARGET_VERSION: &str = "0.68";
pub const ZENML_PIP_SPEC: &str = "zenml>=0.68,<0.69";
pub const LLM_DATASET_SUBDIR: &str = "llm_dataset";
pub const SOURCE_FAMILY: &str = "authorization_qa";
pub const METRIC_NAME: &str = "decision_agreement";
#[derive(Debug, Clone)]
pub struct DatasetRef {
pub root: String,
pub train: String,
pub dev: String,
pub family: String,
}
#[derive(Debug, Clone)]
pub struct StepSpec {
pub name: String,
pub inputs: Vec<String>,
pub artifact_id: String,
}
#[derive(Debug, Clone)]
pub struct LearningPipelineIR {
pub model_ref: String,
pub model_hash: String,
pub created_at: String,
pub generator_version: String,
pub pipeline_id: String,
pub pipeline_name: String,
pub model_name: String,
pub model_version: String,
pub decision_labels: Vec<String>,
pub policy_lines: Vec<String>,
pub metric_name: String,
pub promotion_threshold: f64,
pub dataset: DatasetRef,
pub steps: Vec<StepSpec>,
pub provenance: Provenance,
}
impl LearningPipelineIR {
pub fn build(ctx: &AiLearningContext) -> Result<Self, String> {
ctx.require_authority("zenml")?;
let cfg = &ctx.recipe.projections.zenml;
let has_decisive = ctx
.authority_cases
.iter()
.any(|c| cfg.include_unknown || c.label != "unknown");
if !has_decisive {
return Err(
"zenml projection requires at least one decisive authority case (allow/deny/\
escalate); the provided authority environment produced only 'unknown' tuples"
.to_string(),
);
}
let operations: BTreeSet<&str> = ctx
.authority_cases
.iter()
.map(|c| c.operation.as_str())
.collect();
if operations.is_empty() {
return Err(
"zenml projection requires at least one authority policy action; the provided \
authority environment declares none"
.to_string(),
);
}
let decision_labels: Vec<String> = ["allow", "deny", "escalate", "reject", "unknown"]
.iter()
.filter(|l| cfg.include_unknown || **l != "unknown")
.map(|l| l.to_string())
.collect();
let policy_lines = ctx
.policy_info
.values()
.map(|p| {
let scope = [
p.actor_role.as_deref().map(|r| format!("role={r}")),
p.action.as_deref().map(|a| format!("action={a}")),
p.resource_type.as_deref().map(|r| format!("resource={r}")),
]
.into_iter()
.flatten()
.collect::<Vec<_>>()
.join(", ");
let desc = p.description.as_deref().unwrap_or("");
format!(
"{} [{}] (priority {}) applies to {{ {} }}{}",
p.policy_id,
p.modality,
p.priority,
scope,
if desc.is_empty() {
String::new()
} else {
format!(": {desc}")
}
)
})
.collect();
let pipeline_name = cfg.pipeline_name.clone();
let pipeline_id = element_id(ZENML_FAMILY, &["pipeline", &pipeline_name]);
let hash_digits = ctx
.model_hash
.rsplit(':')
.next()
.unwrap_or(ctx.model_hash.as_str());
let model_version = format!("v-{hash_digits}");
let step = |name: &str, inputs: &[&str]| StepSpec {
name: name.to_string(),
inputs: inputs.iter().map(|s| s.to_string()).collect(),
artifact_id: element_id(ZENML_FAMILY, &["artifact", &pipeline_name, name]),
};
let steps = vec![
step("load_dataset", &[]),
step("train_model", &["load_dataset"]),
step("evaluate_model", &["load_dataset", "train_model"]),
step("register_model", &["train_model", "evaluate_model"]),
];
let dataset = DatasetRef {
root: "../ai_learning".to_string(),
train: format!("{LLM_DATASET_SUBDIR}/{TRAIN}.jsonl"),
dev: format!("{LLM_DATASET_SUBDIR}/{VALIDATION}.jsonl"),
family: SOURCE_FAMILY.to_string(),
};
let provenance = ctx.provenance(
ctx.policy_info.keys().cloned().collect(),
"authority_resolver",
"unreviewed",
);
Ok(Self {
model_ref: ctx.model_ref.clone(),
model_hash: ctx.model_hash.clone(),
created_at: ctx.created_at.clone(),
generator_version: crate::projection::ai_learning::GENERATOR_VERSION.to_string(),
pipeline_id,
pipeline_name,
model_name: cfg.model_name.clone(),
model_version,
decision_labels,
policy_lines,
metric_name: METRIC_NAME.to_string(),
promotion_threshold: cfg.promotion_threshold,
dataset,
steps,
provenance,
})
}
pub fn dag_edges(&self) -> Vec<(String, String)> {
let mut edges: BTreeSet<(String, String)> = BTreeSet::new();
for step in &self.steps {
for input in &step.inputs {
edges.insert((input.clone(), step.name.clone()));
}
}
edges.into_iter().collect()
}
}