clm-kernel 0.0.24

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
// @generated by tools/types/sync_runtime_contract.py from types/lattice/runtime_contract.json
// DO NOT EDIT MANUALLY — run `python3 tools/types/sync_runtime_contract.py --write`
// Normative Invariant: INV-596 (contract parameters reach kernel code through one ParameterContext)
//! Contract parameters as one immutable Layer 0 value record, with a pure boundary parser.

use std::collections::BTreeMap;

/// Exit code of a boundary violation.
pub const PRECONDITION_OR_BOUNDARY_VIOLATION: i32 = 5;
/// Handle prefix of the parameter VCards.
pub const VCARD_PARAMETER_PREFIX: &str = "urn:vcard:contract:param:";
/// BLAKE3 digest of the contract NetMCard (INV-597); Layer 1 recomputes it and compares.
pub const CONTRACT_NET_DIGEST: &str = "b9a3f6b5ffd122e9a2dca16b7b8d106ba0494fcf2c38ad2f8253eec5274c4f9c";
/// Contract key and refinement base type, in contract order.
pub const PARAMETER_TYPES: [(&str, &str); 14] = [
    ("sqlite.busy_timeout_ms", "u32"),
    ("sqlite.compaction_busy_timeout_ms", "u32"),
    ("sqlite.lock_retry_max", "u32"),
    ("sqlite.lock_retry_backoff_ms", "u32"),
    ("codec.b64_chunk_bytes", "usize"),
    ("text.encoding", "string"),
    ("network.gateway_timeout_ms", "u32"),
    ("term.reduction_fuel", "u32"),
    ("runtime.adapter_timeout_s", "u32"),
    ("petri.binding_timeout_s", "u32"),
    ("petri.binding_attempts", "u32"),
    ("cel.test_suite_timeout_s", "u32"),
    ("petri.function_pool_db", "string"),
    ("membrane.continuation_park_ttl_ms", "u32"),
];

/// Contract-owned parameters, resolved once at a process entry and passed inward.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParameterContext {
    /// Wait duration for a SQLite write lock on an ordinary connection.
    pub sqlite_busy_timeout_ms: u32,
    /// Wait duration for a SQLite write lock during compaction.
    pub sqlite_compaction_busy_timeout_ms: u32,
    /// Maximum additional SQLite lock attempts after the initial attempt.
    pub sqlite_lock_retry_max: u32,
    /// Base interval for bounded linear SQLite lock retry backoff.
    pub sqlite_lock_retry_backoff_ms: u32,
    /// Byte chunk size for streaming base64 framing without internal padding.
    pub codec_b64_chunk_bytes: usize,
    /// Canonical text encoding for transport and persisted textual content.
    pub text_encoding: String,
    /// Request deadline for retrieving content through the handle gateway.
    pub network_gateway_timeout_ms: u32,
    /// Reduction steps the layer 0 term core may take before it returns OutOfFuel.
    pub term_reduction_fuel: u32,
    /// Subprocess execution deadline for polyglot runtime adapters.
    pub runtime_adapter_timeout_s: u32,
    /// Subprocess execution deadline for Petri net transition bindings.
    pub petri_binding_timeout_s: u32,
    /// Maximum attempts for executing a Petri net transition binding including content-missing recovery.
    pub petri_binding_attempts: u32,
    /// Subprocess execution deadline for CEL run_test_suite operations.
    pub cel_test_suite_timeout_s: u32,
    /// Workspace-relative SQLite path for the Layer 0 function memory MCard pool.
    pub petri_function_pool_db: String,
    /// Default continuation park time-to-live offset added to the membrane clock when expiresAt is omitted.
    pub membrane_continuation_park_ttl_ms: u32,
}

impl Default for ParameterContext {
    fn default() -> Self {
        Self {
            sqlite_busy_timeout_ms: 5000,
            sqlite_compaction_busy_timeout_ms: 30000,
            sqlite_lock_retry_max: 5,
            sqlite_lock_retry_backoff_ms: 50,
            codec_b64_chunk_bytes: 12288,
            text_encoding: "utf-8".to_string(),
            network_gateway_timeout_ms: 10000,
            term_reduction_fuel: 1000,
            runtime_adapter_timeout_s: 10,
            petri_binding_timeout_s: 60,
            petri_binding_attempts: 2,
            cel_test_suite_timeout_s: 300,
            petri_function_pool_db: "db/layer0_function_memory.mcard.db".to_string(),
            membrane_continuation_park_ttl_ms: 300000,
        }
    }
}

/// A boundary value met its contract refinement at bottom (MISU meet); the process halts.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParameterBoundaryError {
    /// Contract key of the offending parameter.
    pub key: String,
    /// The boundary string that failed to narrow.
    pub raw: String,
    /// Why the value narrowed to bottom.
    pub reason: String,
    /// Boundary layer the value came from: `cli`, `env`, or `card`.
    pub source: &'static str,
}

impl ParameterBoundaryError {
    /// Process exit code for every boundary violation.
    pub const EXIT_CODE: i32 = PRECONDITION_OR_BOUNDARY_VIOLATION;

    fn new(key: &str, raw: &str, reason: String, source: &'static str) -> Self {
        Self { key: key.to_string(), raw: raw.to_string(), reason, source }
    }

    /// Handle of the VCard whose refinement the value failed.
    pub fn vcard(&self) -> String {
        format!("{VCARD_PARAMETER_PREFIX}{}", self.key)
    }
}

impl std::fmt::Display for ParameterBoundaryError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}={:?} from {}: {} ({})", self.key, self.raw, self.source, self.reason, self.vcard())
    }
}

impl std::error::Error for ParameterBoundaryError {}

/// A resolved parameter value, keyed by contract key in `ParameterContext::as_mapping`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ParameterValue {
    /// An unsigned integer parameter.
    Int(u64),
    /// A string parameter.
    Text(String),
    /// A boolean parameter.
    Bool(bool),
}

struct Spec {
    key: &'static str,
    env: &'static str,
    low: u64,
    high: u64,
    multiple_of: u64,
    allowed: Option<&'static [&'static str]>,
}

/// Boundary layers, highest precedence first after CLI: environment, then verified card overrides.
struct Layers<'a> {
    env: &'a BTreeMap<String, String>,
    cli: &'a BTreeMap<String, String>,
    card: &'a BTreeMap<String, String>,
}

impl<'a> Layers<'a> {
    fn raw(&self, spec: &Spec) -> Option<(&'a str, &'static str)> {
        if let Some(raw) = self.cli.get(spec.key) {
            return Some((raw.as_str(), "cli"));
        }
        if let Some(raw) = self.env.get(spec.env) {
            return Some((raw.as_str(), "env"));
        }
        self.card.get(spec.key).map(|raw| (raw.as_str(), "card"))
    }
}

fn narrow_int(spec: &Spec, raw: &str, source: &'static str) -> Result<u64, ParameterBoundaryError> {
    let bottom = |reason: String| ParameterBoundaryError::new(spec.key, raw, reason, source);
    if raw.is_empty() || !raw.bytes().all(|byte| byte.is_ascii_digit()) {
        return Err(bottom("not an unsigned decimal integer".to_string()));
    }
    let value: u64 = raw.parse().map_err(|_| bottom(format!("outside [{}, {}]", spec.low, spec.high)))?;
    if value < spec.low || value > spec.high {
        return Err(bottom(format!("outside [{}, {}]", spec.low, spec.high)));
    }
    if !value.is_multiple_of(spec.multiple_of) {
        return Err(bottom(format!("not a multiple of {}", spec.multiple_of)));
    }
    Ok(value)
}

fn narrow_text(spec: &Spec, raw: &str, source: &'static str) -> Result<String, ParameterBoundaryError> {
    if raw.is_empty() || spec.allowed.is_some_and(|allowed| !allowed.contains(&raw)) {
        return Err(ParameterBoundaryError::new(spec.key, raw, "outside allowed_values".to_string(), source));
    }
    Ok(raw.to_string())
}

#[allow(dead_code)]
fn narrow_bool(spec: &Spec, raw: &str, source: &'static str) -> Result<bool, ParameterBoundaryError> {
    match raw {
        "true" => Ok(true),
        "false" => Ok(false),
        _ => Err(ParameterBoundaryError::new(spec.key, raw, "not a boolean".to_string(), source)),
    }
}

fn reject_unknown(layer: &BTreeMap<String, String>, source: &'static str) -> Result<(), ParameterBoundaryError> {
    match layer.iter().find(|(key, _)| !SPECS.iter().any(|spec| spec.key == key.as_str())) {
        Some((key, raw)) => Err(ParameterBoundaryError::new(key, raw, "unknown parameter".to_string(), source)),
        None => Ok(()),
    }
}

const SPECS: [Spec; 14] = [
    Spec { key: "sqlite.busy_timeout_ms", env: "CLM_SQLITE_BUSY_TIMEOUT_MS", low: 100, high: 120000, multiple_of: 1, allowed: None },
    Spec { key: "sqlite.compaction_busy_timeout_ms", env: "CLM_SQLITE_COMPACTION_BUSY_TIMEOUT_MS", low: 1000, high: 600000, multiple_of: 1, allowed: None },
    Spec { key: "sqlite.lock_retry_max", env: "CLM_SQLITE_LOCK_RETRY_MAX", low: 0, high: 100, multiple_of: 1, allowed: None },
    Spec { key: "sqlite.lock_retry_backoff_ms", env: "CLM_SQLITE_LOCK_RETRY_BACKOFF_MS", low: 1, high: 1000, multiple_of: 1, allowed: None },
    Spec { key: "codec.b64_chunk_bytes", env: "CLM_CODEC_B64_CHUNK_BYTES", low: 3, high: 1048576, multiple_of: 3, allowed: None },
    Spec { key: "text.encoding", env: "CLM_TEXT_ENCODING", low: 0, high: 0, multiple_of: 1, allowed: Some(&["utf-8"]) },
    Spec { key: "network.gateway_timeout_ms", env: "CLM_NETWORK_GATEWAY_TIMEOUT_MS", low: 100, high: 120000, multiple_of: 1, allowed: None },
    Spec { key: "term.reduction_fuel", env: "CLM_TERM_REDUCTION_FUEL", low: 1, high: 1000000, multiple_of: 1, allowed: None },
    Spec { key: "runtime.adapter_timeout_s", env: "CLM_RUNTIME_ADAPTER_TIMEOUT_S", low: 1, high: 600, multiple_of: 1, allowed: None },
    Spec { key: "petri.binding_timeout_s", env: "CLM_PETRI_BINDING_TIMEOUT_S", low: 1, high: 600, multiple_of: 1, allowed: None },
    Spec { key: "petri.binding_attempts", env: "CLM_PETRI_BINDING_ATTEMPTS", low: 1, high: 20, multiple_of: 1, allowed: None },
    Spec { key: "cel.test_suite_timeout_s", env: "CLM_CEL_TEST_SUITE_TIMEOUT_S", low: 1, high: 3600, multiple_of: 1, allowed: None },
    Spec { key: "petri.function_pool_db", env: "CLM_PETRI_FUNCTION_POOL_DB", low: 0, high: 0, multiple_of: 1, allowed: None },
    Spec { key: "membrane.continuation_park_ttl_ms", env: "CLM_MEMBRANE_CONTINUATION_PARK_TTL_MS", low: 1000, high: 86400000, multiple_of: 1, allowed: None },
];

impl ParameterContext {
    /// Resolve CLI over environment over contract default; any bottom is a `ParameterBoundaryError`.
    pub fn from_mapping(env: &BTreeMap<String, String>, cli: &BTreeMap<String, String>) -> Result<Self, ParameterBoundaryError> {
        Self::from_layers(env, cli, &BTreeMap::new())
    }

    /// Resolve CLI over environment over verified card override (contract keys) over contract default.
    pub fn from_layers(env: &BTreeMap<String, String>, cli: &BTreeMap<String, String>, card: &BTreeMap<String, String>) -> Result<Self, ParameterBoundaryError> {
        Self::default().with_layers(&Layers { env, cli, card })
    }

    /// A copy with `cli` (contract keys to boundary strings) applied and narrowed.
    pub fn with_overrides(&self, cli: &BTreeMap<String, String>) -> Result<Self, ParameterBoundaryError> {
        let empty = BTreeMap::new();
        self.with_layers(&Layers { env: &empty, cli, card: &empty })
    }

    fn with_layers(&self, layers: &Layers<'_>) -> Result<Self, ParameterBoundaryError> {
        reject_unknown(layers.cli, "cli")?;
        reject_unknown(layers.card, "card")?;
        let mut context = self.clone();
        if let Some((raw, source)) = layers.raw(&SPECS[0]) { context.sqlite_busy_timeout_ms = u32::try_from(narrow_int(&SPECS[0], raw, source)?).expect("range fits the field"); }
        if let Some((raw, source)) = layers.raw(&SPECS[1]) { context.sqlite_compaction_busy_timeout_ms = u32::try_from(narrow_int(&SPECS[1], raw, source)?).expect("range fits the field"); }
        if let Some((raw, source)) = layers.raw(&SPECS[2]) { context.sqlite_lock_retry_max = u32::try_from(narrow_int(&SPECS[2], raw, source)?).expect("range fits the field"); }
        if let Some((raw, source)) = layers.raw(&SPECS[3]) { context.sqlite_lock_retry_backoff_ms = u32::try_from(narrow_int(&SPECS[3], raw, source)?).expect("range fits the field"); }
        if let Some((raw, source)) = layers.raw(&SPECS[4]) { context.codec_b64_chunk_bytes = usize::try_from(narrow_int(&SPECS[4], raw, source)?).expect("range fits the field"); }
        if let Some((raw, source)) = layers.raw(&SPECS[5]) { context.text_encoding = narrow_text(&SPECS[5], raw, source)?; }
        if let Some((raw, source)) = layers.raw(&SPECS[6]) { context.network_gateway_timeout_ms = u32::try_from(narrow_int(&SPECS[6], raw, source)?).expect("range fits the field"); }
        if let Some((raw, source)) = layers.raw(&SPECS[7]) { context.term_reduction_fuel = u32::try_from(narrow_int(&SPECS[7], raw, source)?).expect("range fits the field"); }
        if let Some((raw, source)) = layers.raw(&SPECS[8]) { context.runtime_adapter_timeout_s = u32::try_from(narrow_int(&SPECS[8], raw, source)?).expect("range fits the field"); }
        if let Some((raw, source)) = layers.raw(&SPECS[9]) { context.petri_binding_timeout_s = u32::try_from(narrow_int(&SPECS[9], raw, source)?).expect("range fits the field"); }
        if let Some((raw, source)) = layers.raw(&SPECS[10]) { context.petri_binding_attempts = u32::try_from(narrow_int(&SPECS[10], raw, source)?).expect("range fits the field"); }
        if let Some((raw, source)) = layers.raw(&SPECS[11]) { context.cel_test_suite_timeout_s = u32::try_from(narrow_int(&SPECS[11], raw, source)?).expect("range fits the field"); }
        if let Some((raw, source)) = layers.raw(&SPECS[12]) { context.petri_function_pool_db = narrow_text(&SPECS[12], raw, source)?; }
        if let Some((raw, source)) = layers.raw(&SPECS[13]) { context.membrane_continuation_park_ttl_ms = u32::try_from(narrow_int(&SPECS[13], raw, source)?).expect("range fits the field"); }
        Ok(context)
    }

    /// Contract key to resolved value.
    pub fn as_mapping(&self) -> BTreeMap<&'static str, ParameterValue> {
        let mut mapping = BTreeMap::new();
        mapping.insert("sqlite.busy_timeout_ms", ParameterValue::Int(u64::from(self.sqlite_busy_timeout_ms)));
        mapping.insert("sqlite.compaction_busy_timeout_ms", ParameterValue::Int(u64::from(self.sqlite_compaction_busy_timeout_ms)));
        mapping.insert("sqlite.lock_retry_max", ParameterValue::Int(u64::from(self.sqlite_lock_retry_max)));
        mapping.insert("sqlite.lock_retry_backoff_ms", ParameterValue::Int(u64::from(self.sqlite_lock_retry_backoff_ms)));
        mapping.insert("codec.b64_chunk_bytes", ParameterValue::Int(self.codec_b64_chunk_bytes as u64));
        mapping.insert("text.encoding", ParameterValue::Text(self.text_encoding.clone()));
        mapping.insert("network.gateway_timeout_ms", ParameterValue::Int(u64::from(self.network_gateway_timeout_ms)));
        mapping.insert("term.reduction_fuel", ParameterValue::Int(u64::from(self.term_reduction_fuel)));
        mapping.insert("runtime.adapter_timeout_s", ParameterValue::Int(u64::from(self.runtime_adapter_timeout_s)));
        mapping.insert("petri.binding_timeout_s", ParameterValue::Int(u64::from(self.petri_binding_timeout_s)));
        mapping.insert("petri.binding_attempts", ParameterValue::Int(u64::from(self.petri_binding_attempts)));
        mapping.insert("cel.test_suite_timeout_s", ParameterValue::Int(u64::from(self.cel_test_suite_timeout_s)));
        mapping.insert("petri.function_pool_db", ParameterValue::Text(self.petri_function_pool_db.clone()));
        mapping.insert("membrane.continuation_park_ttl_ms", ParameterValue::Int(u64::from(self.membrane_continuation_park_ttl_ms)));
        mapping
    }
}