use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use vyre_foundation::ir::Program;
use vyre_megakernel::{
Artifact, ArtifactValueId, FusionRecord, ResourceLifetime, TargetModuleBundle,
TargetModuleImage, TargetPayload, TargetPayloadFormat, TargetProfile,
};
use crate::{BackendError, DispatchConfig};
#[must_use]
pub fn invalid_module(reason: &str) -> BackendError {
BackendError::InvalidProgram {
fix: format!("Fix: {reason}. Recompile the target payload from the neutral artifact."),
}
}
#[must_use]
pub fn compile_error(backend: &str, error: impl std::fmt::Display) -> BackendError {
BackendError::KernelCompileFailed {
backend: backend.to_string(),
compiler_message: format!(
"{error}. Fix: rebuild the target payload from the neutral artifact."
),
}
}
#[derive(Clone, Copy, Debug)]
pub struct MaterializerTarget<'a> {
pub backend_id: &'a str,
pub format: &'a TargetPayloadFormat,
pub profile: &'a TargetProfile,
}
#[derive(Debug)]
pub struct AdmittedModule {
pub image: TargetModuleImage,
pub program: Arc<Program>,
pub config: DispatchConfig,
}
pub fn admit(
artifact: &Artifact,
payload: &TargetPayload,
target: MaterializerTarget<'_>,
) -> Result<Vec<AdmittedModule>, BackendError> {
if payload.neutral_artifact() != artifact.digest() {
return Err(invalid_module(
"target payload is not authenticated for the supplied neutral artifact",
));
}
if payload.format() != target.format {
return Err(BackendError::UnsupportedFeature {
name: format!("target payload format `{}`", payload.format().identity()),
backend: target.backend_id.to_string(),
});
}
if payload.profile() != target.profile {
return Err(invalid_module(
"target payload profile does not match the acquired materializer profile",
));
}
let bundle = TargetModuleBundle::from_bytes(payload.bytes())
.map_err(|error| compile_error(target.backend_id, error))?;
let selected = artifact.fusion();
if bundle.modules.len() != selected.len() {
return Err(invalid_module(
"target module count must equal the compiler-selected fusion-group count",
));
}
if payload.entries().len() != selected.len() {
return Err(invalid_module(
"target entry count must equal the compiler-selected fusion-group count",
));
}
let mut admitted = Vec::with_capacity(selected.len());
for ((image, record), entry) in bundle
.modules
.into_iter()
.zip(selected)
.zip(payload.entries())
{
admit_module_identity(&image, record)?;
if image.entry_point != "main" {
return Err(invalid_module("target module entry point must be `main`"));
}
if entry.name != image.entry_point {
return Err(invalid_module(
"target entry metadata must name the emitted target entry point",
));
}
let program = Arc::new(Program::from_wire(&image.program).map_err(|error| {
invalid_module(&format!("selected Program is malformed: {error}"))
})?);
let mut config = DispatchConfig::default();
config.grid_override = Some(entry.grid_size);
config.dispatch_grid = Some(entry.grid_size);
admitted.push(AdmittedModule {
image,
program,
config,
});
}
Ok(admitted)
}
fn admit_module_identity(
image: &TargetModuleImage,
record: &FusionRecord,
) -> Result<(), BackendError> {
if image.group != record.id || image.stage != record.stage || image.nodes != record.members {
return Err(invalid_module(
"target module group/stage/node identity must match the neutral selected plan",
));
}
Ok(())
}
pub struct ResourceProjection {
pub values: BTreeMap<String, ArtifactValueId>,
pub outputs: BTreeSet<ArtifactValueId>,
pub retained: BTreeSet<ArtifactValueId>,
}
#[must_use]
pub fn project_resources(artifact: &Artifact) -> ResourceProjection {
let mut projection = ResourceProjection {
values: BTreeMap::new(),
outputs: BTreeSet::new(),
retained: BTreeSet::new(),
};
for resource in artifact.resources() {
projection
.values
.insert(resource.name.clone(), resource.value);
match resource.lifetime {
ResourceLifetime::Output => {
projection.outputs.insert(resource.value);
}
ResourceLifetime::Retained => {
projection.retained.insert(resource.value);
}
_ => {}
}
}
projection
}