use serde::{Deserialize, Serialize};
use crate::{
error::{Error, Result},
format::{Checksum, bincode_config, blake3_checksum},
};
pub const SCHEMA_VERSION: u16 = 1;
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct CreateContractV1 {
pub schema_version: u16,
pub text_enabled: bool,
pub max_dim: u32,
pub allowed_dtypes: u8,
pub auto_promote_non_f8: u64,
pub auto_promote_f8: u64,
pub reserved: [u8; 16],
}
impl Default for CreateContractV1 {
fn default() -> Self {
Self {
schema_version: SCHEMA_VERSION,
text_enabled: true,
max_dim: 4096,
allowed_dtypes: 0b0001_1111, auto_promote_non_f8: 200_000,
auto_promote_f8: 500_000,
reserved: [0u8; 16],
}
}
}
impl CreateContractV1 {
pub fn encode(&self) -> Result<Vec<u8>> {
bincode::serde::encode_to_vec(self, bincode_config())
.map_err(|err| Error::Serde(err.to_string()))
}
pub fn decode(bytes: &[u8]) -> Result<Self> {
let (contract, consumed) =
bincode::serde::decode_from_slice::<Self, _>(bytes, bincode_config())
.map_err(|err| Error::Serde(err.to_string()))?;
if consumed != bytes.len() {
return Err(Error::Format(
"CreateContractV1 has trailing bytes after decode".into(),
));
}
contract.validate_decoded()?;
Ok(contract)
}
pub fn digest(&self) -> Result<Checksum> {
Ok(blake3_checksum(&self.encode()?))
}
pub fn validate_options(&self) -> Result<()> {
if self.schema_version != SCHEMA_VERSION {
return Err(Error::Format(format!(
"CreateContractV1: unsupported schema_version {}",
self.schema_version
)));
}
if self.max_dim == 0 || self.max_dim > 65_535 {
return Err(Error::Format(format!(
"CreateContractV1: max_dim {} out of range (1..=65_535)",
self.max_dim
)));
}
if crate::format::dtype::DtypeSet::from_bits(self.allowed_dtypes).is_none() {
return Err(Error::Format(format!(
"CreateContractV1: allowed_dtypes 0x{:02X} contains unknown bits",
self.allowed_dtypes
)));
}
if self.allowed_dtypes == 0 {
return Err(Error::Format(
"CreateContractV1: allowed_dtypes is empty".into(),
));
}
if self.auto_promote_non_f8 < 1024 {
return Err(Error::Format(format!(
"CreateContractV1: auto_promote_non_f8 ({}) must be โฅ 1024",
self.auto_promote_non_f8
)));
}
if self.auto_promote_f8 < self.auto_promote_non_f8 {
return Err(Error::Format(format!(
"CreateContractV1: auto_promote_f8 ({}) must be โฅ auto_promote_non_f8 ({})",
self.auto_promote_f8, self.auto_promote_non_f8
)));
}
Ok(())
}
fn validate_decoded(&self) -> Result<()> {
if self.schema_version != SCHEMA_VERSION {
return Err(Error::Format(format!(
"CreateContractV1: unsupported schema_version {}",
self.schema_version
)));
}
if crate::format::dtype::DtypeSet::from_bits(self.allowed_dtypes).is_none() {
return Err(Error::Format(format!(
"CreateContractV1: allowed_dtypes 0x{:02X} contains unknown bits",
self.allowed_dtypes
)));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::format::dtype::DtypeSet;
#[test]
fn defaults_pass_validation() {
CreateContractV1::default()
.validate_options()
.expect("default contract validates");
}
#[test]
fn round_trip_through_bincode() {
let original = CreateContractV1 {
schema_version: SCHEMA_VERSION,
text_enabled: false,
max_dim: 1024,
allowed_dtypes: DtypeSet::F32.union(DtypeSet::F16).bits(),
auto_promote_non_f8: 50_000,
auto_promote_f8: 100_000,
reserved: [0u8; 16],
};
let bytes = original.encode().expect("encode");
let decoded = CreateContractV1::decode(&bytes).expect("decode");
assert_eq!(decoded, original);
}
#[test]
fn digest_is_stable_across_calls() {
let c = CreateContractV1::default();
assert_eq!(c.digest().unwrap(), c.digest().unwrap());
}
#[test]
fn digest_changes_when_contract_changes() {
let a = CreateContractV1::default();
let b = CreateContractV1 {
text_enabled: false,
..a.clone()
};
assert_ne!(a.digest().unwrap(), b.digest().unwrap());
}
#[test]
fn rejects_zero_max_dim() {
let c = CreateContractV1 {
max_dim: 0,
..Default::default()
};
c.validate_options().unwrap_err();
}
#[test]
fn rejects_oversized_max_dim() {
let c = CreateContractV1 {
max_dim: 1 << 17,
..Default::default()
};
c.validate_options().unwrap_err();
}
#[test]
fn rejects_empty_allowed_dtypes() {
let c = CreateContractV1 {
allowed_dtypes: 0,
..Default::default()
};
c.validate_options().unwrap_err();
}
#[test]
fn rejects_unknown_dtype_bits() {
let c = CreateContractV1 {
allowed_dtypes: 0b1110_0000,
..Default::default()
};
c.validate_options().unwrap_err();
}
#[test]
fn rejects_low_non_f8_threshold() {
let c = CreateContractV1 {
auto_promote_non_f8: 100,
..Default::default()
};
c.validate_options().unwrap_err();
}
#[test]
fn rejects_f8_threshold_below_non_f8() {
let c = CreateContractV1 {
auto_promote_non_f8: 200_000,
auto_promote_f8: 100_000,
..Default::default()
};
c.validate_options().unwrap_err();
}
#[test]
fn decode_rejects_unknown_dtype_bits() {
let c = CreateContractV1 {
allowed_dtypes: 0b1110_0000,
..Default::default()
};
let bytes = c.encode().expect("encode (no validate_options on encode)");
CreateContractV1::decode(&bytes).expect_err("decode validate rejects");
}
#[test]
fn decode_rejects_trailing_bytes() {
let c = CreateContractV1::default();
let mut bytes = c.encode().expect("encode");
bytes.push(0);
CreateContractV1::decode(&bytes).expect_err("trailing bytes rejected");
}
}