Skip to main content

clm_rust_core/layer0/
parameter_context.rs

1// @generated by tools/types/sync_runtime_contract.py from types/lattice/runtime_contract.json
2// DO NOT EDIT MANUALLY — run `python3 tools/types/sync_runtime_contract.py --write`
3// Normative Invariant: INV-596 (contract parameters reach kernel code through one ParameterContext)
4//! Contract parameters as one immutable Layer 0 value record, with a pure boundary parser.
5
6use std::collections::BTreeMap;
7
8/// Exit code of a boundary violation.
9pub const PRECONDITION_OR_BOUNDARY_VIOLATION: i32 = 5;
10/// Handle prefix of the parameter VCards.
11pub const VCARD_PARAMETER_PREFIX: &str = "urn:vcard:contract:param:";
12/// BLAKE3 digest of the contract NetMCard (INV-597); Layer 1 recomputes it and compares.
13pub const CONTRACT_NET_DIGEST: &str = "b9a3f6b5ffd122e9a2dca16b7b8d106ba0494fcf2c38ad2f8253eec5274c4f9c";
14/// Contract key and refinement base type, in contract order.
15pub const PARAMETER_TYPES: [(&str, &str); 14] = [
16    ("sqlite.busy_timeout_ms", "u32"),
17    ("sqlite.compaction_busy_timeout_ms", "u32"),
18    ("sqlite.lock_retry_max", "u32"),
19    ("sqlite.lock_retry_backoff_ms", "u32"),
20    ("codec.b64_chunk_bytes", "usize"),
21    ("text.encoding", "string"),
22    ("network.gateway_timeout_ms", "u32"),
23    ("term.reduction_fuel", "u32"),
24    ("runtime.adapter_timeout_s", "u32"),
25    ("petri.binding_timeout_s", "u32"),
26    ("petri.binding_attempts", "u32"),
27    ("cel.test_suite_timeout_s", "u32"),
28    ("petri.function_pool_db", "string"),
29    ("membrane.continuation_park_ttl_ms", "u32"),
30];
31
32/// Contract-owned parameters, resolved once at a process entry and passed inward.
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub struct ParameterContext {
35    /// Wait duration for a SQLite write lock on an ordinary connection.
36    pub sqlite_busy_timeout_ms: u32,
37    /// Wait duration for a SQLite write lock during compaction.
38    pub sqlite_compaction_busy_timeout_ms: u32,
39    /// Maximum additional SQLite lock attempts after the initial attempt.
40    pub sqlite_lock_retry_max: u32,
41    /// Base interval for bounded linear SQLite lock retry backoff.
42    pub sqlite_lock_retry_backoff_ms: u32,
43    /// Byte chunk size for streaming base64 framing without internal padding.
44    pub codec_b64_chunk_bytes: usize,
45    /// Canonical text encoding for transport and persisted textual content.
46    pub text_encoding: String,
47    /// Request deadline for retrieving content through the handle gateway.
48    pub network_gateway_timeout_ms: u32,
49    /// Reduction steps the layer 0 term core may take before it returns OutOfFuel.
50    pub term_reduction_fuel: u32,
51    /// Subprocess execution deadline for polyglot runtime adapters.
52    pub runtime_adapter_timeout_s: u32,
53    /// Subprocess execution deadline for Petri net transition bindings.
54    pub petri_binding_timeout_s: u32,
55    /// Maximum attempts for executing a Petri net transition binding including content-missing recovery.
56    pub petri_binding_attempts: u32,
57    /// Subprocess execution deadline for CEL run_test_suite operations.
58    pub cel_test_suite_timeout_s: u32,
59    /// Workspace-relative SQLite path for the Layer 0 function memory MCard pool.
60    pub petri_function_pool_db: String,
61    /// Default continuation park time-to-live offset added to the membrane clock when expiresAt is omitted.
62    pub membrane_continuation_park_ttl_ms: u32,
63}
64
65impl Default for ParameterContext {
66    fn default() -> Self {
67        Self {
68            sqlite_busy_timeout_ms: 5000,
69            sqlite_compaction_busy_timeout_ms: 30000,
70            sqlite_lock_retry_max: 5,
71            sqlite_lock_retry_backoff_ms: 50,
72            codec_b64_chunk_bytes: 12288,
73            text_encoding: "utf-8".to_string(),
74            network_gateway_timeout_ms: 10000,
75            term_reduction_fuel: 1000,
76            runtime_adapter_timeout_s: 10,
77            petri_binding_timeout_s: 60,
78            petri_binding_attempts: 2,
79            cel_test_suite_timeout_s: 300,
80            petri_function_pool_db: "db/layer0_function_memory.mcard.db".to_string(),
81            membrane_continuation_park_ttl_ms: 300000,
82        }
83    }
84}
85
86/// A boundary value met its contract refinement at bottom (MISU meet); the process halts.
87#[derive(Clone, Debug, PartialEq, Eq)]
88pub struct ParameterBoundaryError {
89    /// Contract key of the offending parameter.
90    pub key: String,
91    /// The boundary string that failed to narrow.
92    pub raw: String,
93    /// Why the value narrowed to bottom.
94    pub reason: String,
95    /// Boundary layer the value came from: `cli`, `env`, or `card`.
96    pub source: &'static str,
97}
98
99impl ParameterBoundaryError {
100    /// Process exit code for every boundary violation.
101    pub const EXIT_CODE: i32 = PRECONDITION_OR_BOUNDARY_VIOLATION;
102
103    fn new(key: &str, raw: &str, reason: String, source: &'static str) -> Self {
104        Self { key: key.to_string(), raw: raw.to_string(), reason, source }
105    }
106
107    /// Handle of the VCard whose refinement the value failed.
108    pub fn vcard(&self) -> String {
109        format!("{VCARD_PARAMETER_PREFIX}{}", self.key)
110    }
111}
112
113impl std::fmt::Display for ParameterBoundaryError {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        write!(f, "{}={:?} from {}: {} ({})", self.key, self.raw, self.source, self.reason, self.vcard())
116    }
117}
118
119impl std::error::Error for ParameterBoundaryError {}
120
121/// A resolved parameter value, keyed by contract key in `ParameterContext::as_mapping`.
122#[derive(Clone, Debug, PartialEq, Eq)]
123pub enum ParameterValue {
124    /// An unsigned integer parameter.
125    Int(u64),
126    /// A string parameter.
127    Text(String),
128    /// A boolean parameter.
129    Bool(bool),
130}
131
132struct Spec {
133    key: &'static str,
134    env: &'static str,
135    low: u64,
136    high: u64,
137    multiple_of: u64,
138    allowed: Option<&'static [&'static str]>,
139}
140
141/// Boundary layers, highest precedence first after CLI: environment, then verified card overrides.
142struct Layers<'a> {
143    env: &'a BTreeMap<String, String>,
144    cli: &'a BTreeMap<String, String>,
145    card: &'a BTreeMap<String, String>,
146}
147
148impl<'a> Layers<'a> {
149    fn raw(&self, spec: &Spec) -> Option<(&'a str, &'static str)> {
150        if let Some(raw) = self.cli.get(spec.key) {
151            return Some((raw.as_str(), "cli"));
152        }
153        if let Some(raw) = self.env.get(spec.env) {
154            return Some((raw.as_str(), "env"));
155        }
156        self.card.get(spec.key).map(|raw| (raw.as_str(), "card"))
157    }
158}
159
160fn narrow_int(spec: &Spec, raw: &str, source: &'static str) -> Result<u64, ParameterBoundaryError> {
161    let bottom = |reason: String| ParameterBoundaryError::new(spec.key, raw, reason, source);
162    if raw.is_empty() || !raw.bytes().all(|byte| byte.is_ascii_digit()) {
163        return Err(bottom("not an unsigned decimal integer".to_string()));
164    }
165    let value: u64 = raw.parse().map_err(|_| bottom(format!("outside [{}, {}]", spec.low, spec.high)))?;
166    if value < spec.low || value > spec.high {
167        return Err(bottom(format!("outside [{}, {}]", spec.low, spec.high)));
168    }
169    if !value.is_multiple_of(spec.multiple_of) {
170        return Err(bottom(format!("not a multiple of {}", spec.multiple_of)));
171    }
172    Ok(value)
173}
174
175fn narrow_text(spec: &Spec, raw: &str, source: &'static str) -> Result<String, ParameterBoundaryError> {
176    if raw.is_empty() || spec.allowed.is_some_and(|allowed| !allowed.contains(&raw)) {
177        return Err(ParameterBoundaryError::new(spec.key, raw, "outside allowed_values".to_string(), source));
178    }
179    Ok(raw.to_string())
180}
181
182#[allow(dead_code)]
183fn narrow_bool(spec: &Spec, raw: &str, source: &'static str) -> Result<bool, ParameterBoundaryError> {
184    match raw {
185        "true" => Ok(true),
186        "false" => Ok(false),
187        _ => Err(ParameterBoundaryError::new(spec.key, raw, "not a boolean".to_string(), source)),
188    }
189}
190
191fn reject_unknown(layer: &BTreeMap<String, String>, source: &'static str) -> Result<(), ParameterBoundaryError> {
192    match layer.iter().find(|(key, _)| !SPECS.iter().any(|spec| spec.key == key.as_str())) {
193        Some((key, raw)) => Err(ParameterBoundaryError::new(key, raw, "unknown parameter".to_string(), source)),
194        None => Ok(()),
195    }
196}
197
198const SPECS: [Spec; 14] = [
199    Spec { key: "sqlite.busy_timeout_ms", env: "CLM_SQLITE_BUSY_TIMEOUT_MS", low: 100, high: 120000, multiple_of: 1, allowed: None },
200    Spec { key: "sqlite.compaction_busy_timeout_ms", env: "CLM_SQLITE_COMPACTION_BUSY_TIMEOUT_MS", low: 1000, high: 600000, multiple_of: 1, allowed: None },
201    Spec { key: "sqlite.lock_retry_max", env: "CLM_SQLITE_LOCK_RETRY_MAX", low: 0, high: 100, multiple_of: 1, allowed: None },
202    Spec { key: "sqlite.lock_retry_backoff_ms", env: "CLM_SQLITE_LOCK_RETRY_BACKOFF_MS", low: 1, high: 1000, multiple_of: 1, allowed: None },
203    Spec { key: "codec.b64_chunk_bytes", env: "CLM_CODEC_B64_CHUNK_BYTES", low: 3, high: 1048576, multiple_of: 3, allowed: None },
204    Spec { key: "text.encoding", env: "CLM_TEXT_ENCODING", low: 0, high: 0, multiple_of: 1, allowed: Some(&["utf-8"]) },
205    Spec { key: "network.gateway_timeout_ms", env: "CLM_NETWORK_GATEWAY_TIMEOUT_MS", low: 100, high: 120000, multiple_of: 1, allowed: None },
206    Spec { key: "term.reduction_fuel", env: "CLM_TERM_REDUCTION_FUEL", low: 1, high: 1000000, multiple_of: 1, allowed: None },
207    Spec { key: "runtime.adapter_timeout_s", env: "CLM_RUNTIME_ADAPTER_TIMEOUT_S", low: 1, high: 600, multiple_of: 1, allowed: None },
208    Spec { key: "petri.binding_timeout_s", env: "CLM_PETRI_BINDING_TIMEOUT_S", low: 1, high: 600, multiple_of: 1, allowed: None },
209    Spec { key: "petri.binding_attempts", env: "CLM_PETRI_BINDING_ATTEMPTS", low: 1, high: 20, multiple_of: 1, allowed: None },
210    Spec { key: "cel.test_suite_timeout_s", env: "CLM_CEL_TEST_SUITE_TIMEOUT_S", low: 1, high: 3600, multiple_of: 1, allowed: None },
211    Spec { key: "petri.function_pool_db", env: "CLM_PETRI_FUNCTION_POOL_DB", low: 0, high: 0, multiple_of: 1, allowed: None },
212    Spec { key: "membrane.continuation_park_ttl_ms", env: "CLM_MEMBRANE_CONTINUATION_PARK_TTL_MS", low: 1000, high: 86400000, multiple_of: 1, allowed: None },
213];
214
215impl ParameterContext {
216    /// Resolve CLI over environment over contract default; any bottom is a `ParameterBoundaryError`.
217    pub fn from_mapping(env: &BTreeMap<String, String>, cli: &BTreeMap<String, String>) -> Result<Self, ParameterBoundaryError> {
218        Self::from_layers(env, cli, &BTreeMap::new())
219    }
220
221    /// Resolve CLI over environment over verified card override (contract keys) over contract default.
222    pub fn from_layers(env: &BTreeMap<String, String>, cli: &BTreeMap<String, String>, card: &BTreeMap<String, String>) -> Result<Self, ParameterBoundaryError> {
223        Self::default().with_layers(&Layers { env, cli, card })
224    }
225
226    /// A copy with `cli` (contract keys to boundary strings) applied and narrowed.
227    pub fn with_overrides(&self, cli: &BTreeMap<String, String>) -> Result<Self, ParameterBoundaryError> {
228        let empty = BTreeMap::new();
229        self.with_layers(&Layers { env: &empty, cli, card: &empty })
230    }
231
232    fn with_layers(&self, layers: &Layers<'_>) -> Result<Self, ParameterBoundaryError> {
233        reject_unknown(layers.cli, "cli")?;
234        reject_unknown(layers.card, "card")?;
235        let mut context = self.clone();
236        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"); }
237        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"); }
238        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"); }
239        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"); }
240        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"); }
241        if let Some((raw, source)) = layers.raw(&SPECS[5]) { context.text_encoding = narrow_text(&SPECS[5], raw, source)?; }
242        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"); }
243        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"); }
244        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"); }
245        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"); }
246        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"); }
247        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"); }
248        if let Some((raw, source)) = layers.raw(&SPECS[12]) { context.petri_function_pool_db = narrow_text(&SPECS[12], raw, source)?; }
249        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"); }
250        Ok(context)
251    }
252
253    /// Contract key to resolved value.
254    pub fn as_mapping(&self) -> BTreeMap<&'static str, ParameterValue> {
255        let mut mapping = BTreeMap::new();
256        mapping.insert("sqlite.busy_timeout_ms", ParameterValue::Int(u64::from(self.sqlite_busy_timeout_ms)));
257        mapping.insert("sqlite.compaction_busy_timeout_ms", ParameterValue::Int(u64::from(self.sqlite_compaction_busy_timeout_ms)));
258        mapping.insert("sqlite.lock_retry_max", ParameterValue::Int(u64::from(self.sqlite_lock_retry_max)));
259        mapping.insert("sqlite.lock_retry_backoff_ms", ParameterValue::Int(u64::from(self.sqlite_lock_retry_backoff_ms)));
260        mapping.insert("codec.b64_chunk_bytes", ParameterValue::Int(self.codec_b64_chunk_bytes as u64));
261        mapping.insert("text.encoding", ParameterValue::Text(self.text_encoding.clone()));
262        mapping.insert("network.gateway_timeout_ms", ParameterValue::Int(u64::from(self.network_gateway_timeout_ms)));
263        mapping.insert("term.reduction_fuel", ParameterValue::Int(u64::from(self.term_reduction_fuel)));
264        mapping.insert("runtime.adapter_timeout_s", ParameterValue::Int(u64::from(self.runtime_adapter_timeout_s)));
265        mapping.insert("petri.binding_timeout_s", ParameterValue::Int(u64::from(self.petri_binding_timeout_s)));
266        mapping.insert("petri.binding_attempts", ParameterValue::Int(u64::from(self.petri_binding_attempts)));
267        mapping.insert("cel.test_suite_timeout_s", ParameterValue::Int(u64::from(self.cel_test_suite_timeout_s)));
268        mapping.insert("petri.function_pool_db", ParameterValue::Text(self.petri_function_pool_db.clone()));
269        mapping.insert("membrane.continuation_park_ttl_ms", ParameterValue::Int(u64::from(self.membrane_continuation_park_ttl_ms)));
270        mapping
271    }
272}