Skip to main content

lemma/
limits.rs

1use crate::error::Error;
2use crate::parsing::source::Source;
3
4pub const MAX_SPEC_NAME_LENGTH: usize = 128;
5pub const MAX_DATA_NAME_LENGTH: usize = 256;
6pub const MAX_RULE_NAME_LENGTH: usize = 256;
7
8/// Maximum character length for a text value (data/runtime input).
9pub const MAX_TEXT_VALUE_LENGTH: usize = 1024;
10
11/// Validate that a name does not exceed the given character limit.
12/// `kind` is a human-readable noun like "spec", "data", "rule", or "type".
13pub fn check_max_length(
14    name: &str,
15    limit: usize,
16    kind: &str,
17    source: Option<Source>,
18) -> Result<(), Error> {
19    if name.len() > limit {
20        return Err(Error::resource_limit_exceeded(
21            format!("max_{kind}_name_length"),
22            format!("{limit} characters"),
23            format!("{} characters", name.len()),
24            format!("Shorten the {kind} name to at most {limit} characters"),
25            source,
26            None,
27            None,
28        ));
29    }
30    Ok(())
31}
32
33/// Limits to prevent abuse and enable predictable resource usage
34///
35/// These limits protect against malicious inputs while being generous enough
36/// for all legitimate use cases.
37#[derive(Debug, Clone, serde::Serialize)]
38pub struct ResourceLimits {
39    /// Maximum size of one loaded source text in bytes.
40    /// Real usage: ~5KB, Limit: 5MB (1000x)
41    pub max_source_size_bytes: usize,
42
43    /// Maximum expression nesting depth
44    /// Real usage: ~3 levels, Limit: 7. Deeper logic via rule composition.
45    pub max_expression_depth: usize,
46
47    /// Maximum expression nodes per source (parser-level)
48    /// Quick-reject for pathological single sources.
49    pub max_expression_count: usize,
50
51    /// Maximum size of a single data value in bytes
52    /// Real usage: ~100 bytes, Limit: 1KB (10x)
53    /// Enables server pre-allocation for zero-allocation evaluation
54    pub max_data_value_bytes: usize,
55
56    /// Maximum total bytes to load in one batch (and/or in-memory size of loaded specs)
57    pub max_loaded_bytes: usize,
58
59    /// Maximum number of sources in one load batch (e.g. after expanding paths on disk)
60    pub max_sources: usize,
61
62    /// Maximum unique normal-form cells reachable from one rule root in the
63    /// shared graph after normalize. Bounds planning work and shipped table size.
64    /// Default: 30,000.
65    pub max_normalized_expression_nodes: usize,
66
67    /// Maximum depth of the spec dependency chain (`uses` imports) from the
68    /// root spec. Bounds recursion in dependency discovery and graph building.
69    /// Real usage: ~3 levels, Limit: 32 (10x).
70    pub max_spec_dependency_depth: usize,
71
72    /// Maximum number of specs in one dependency DAG (the root spec plus all
73    /// transitive dependencies). Bounds per-plan memory and planning work.
74    pub max_dag_specs: usize,
75
76    /// Maximum nesting depth of a rule's normalized NormalForm DAG (leaves =
77    /// depth 1). The evaluator walks recursively, so planning must guarantee
78    /// no rule root can overflow the stack at run time. Lemma's runtime does
79    /// not return errors — this limit is the guarantee.
80    pub max_normal_form_depth: usize,
81}
82
83impl Default for ResourceLimits {
84    fn default() -> Self {
85        Self {
86            max_source_size_bytes: 5 * 1024 * 1024, // 5 MB
87            max_expression_depth: 7,
88            max_expression_count: 65_536,
89            max_data_value_bytes: 1024,         // 1 KB
90            max_loaded_bytes: 50 * 1024 * 1024, // 50 MB
91            max_sources: 4096,
92            max_normalized_expression_nodes: 30_000,
93            max_spec_dependency_depth: 32,
94            max_dag_specs: 4096,
95            // Bounds recursive eval stack depth on the shared NormalForm DAG.
96            max_normal_form_depth: 4096,
97        }
98    }
99}
100
101impl ResourceLimits {
102    /// Apply one named limit override. Unknown keys return `Err`.
103    pub fn apply(&mut self, key: &str, value: usize) -> Result<(), String> {
104        match key {
105            "max_source_size_bytes" => self.max_source_size_bytes = value,
106            "max_expression_depth" => self.max_expression_depth = value,
107            "max_expression_count" => self.max_expression_count = value,
108            "max_data_value_bytes" => self.max_data_value_bytes = value,
109            "max_loaded_bytes" => self.max_loaded_bytes = value,
110            "max_sources" => self.max_sources = value,
111            "max_normalized_expression_nodes" => self.max_normalized_expression_nodes = value,
112            "max_spec_dependency_depth" => self.max_spec_dependency_depth = value,
113            "max_dag_specs" => self.max_dag_specs = value,
114            "max_normal_form_depth" => self.max_normal_form_depth = value,
115            other => return Err(format!("unknown limits key: '{other}'")),
116        }
117        Ok(())
118    }
119}
120
121/// Convert a JS/JSON number to a [`usize`] limit. Rejects non-integers, negatives,
122/// values outside the f64 safe-integer range, and values that do not fit in `usize`
123/// (e.g. large safe integers on wasm32).
124#[cfg(any(test, target_arch = "wasm32"))]
125pub(crate) fn usize_limit_from_f64(key: &str, value: f64) -> Result<usize, String> {
126    if !value.is_finite() || value < 0.0 || value.fract() != 0.0 {
127        return Err(format!(
128            "limits value for '{key}' must be a non-negative integer"
129        ));
130    }
131    let as_u64 = value as u64;
132    if value >= 2f64.powi(53) || as_u64 as f64 != value {
133        return Err(format!(
134            "limits value for '{key}' must be a non-negative integer within f64 safe range"
135        ));
136    }
137    if as_u64 > usize::MAX as u64 {
138        return Err(format!(
139            "limits value for '{key}' exceeds platform usize maximum ({})",
140            usize::MAX
141        ));
142    }
143    Ok(as_u64 as usize)
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    #[test]
151    fn apply_sets_known_key() {
152        let mut limits = ResourceLimits::default();
153        limits.apply("max_sources", 7).expect("known key");
154        assert_eq!(limits.max_sources, 7);
155    }
156
157    #[test]
158    fn apply_sets_max_normal_form_depth() {
159        let mut limits = ResourceLimits::default();
160        limits
161            .apply("max_normal_form_depth", 99)
162            .expect("known key");
163        assert_eq!(limits.max_normal_form_depth, 99);
164    }
165
166    #[test]
167    fn apply_rejects_unknown_key() {
168        let mut limits = ResourceLimits::default();
169        let err = limits.apply("not_a_limit", 1).expect_err("unknown");
170        assert!(err.contains("unknown limits key"));
171    }
172
173    #[test]
174    fn usize_limit_from_f64_accepts_integer() {
175        assert_eq!(usize_limit_from_f64("max_sources", 7.0).unwrap(), 7);
176    }
177
178    #[test]
179    fn usize_limit_from_f64_rejects_fraction() {
180        let err = usize_limit_from_f64("max_sources", 1.5).expect_err("fraction");
181        assert!(err.contains("non-negative integer"));
182    }
183
184    #[test]
185    fn usize_limit_from_f64_rejects_above_safe_integer() {
186        let err = usize_limit_from_f64("max_sources", 2f64.powi(53)).expect_err("unsafe");
187        assert!(err.contains("f64 safe range"));
188    }
189
190    #[test]
191    fn usize_limit_from_f64_rejects_above_usize_max() {
192        // On 64-bit hosts usize::MAX is outside f64 safe integers, so the safe-range
193        // check fires first. On 32-bit, a safe integer above u32::MAX must error here.
194        if (usize::MAX as u64) < (1u64 << 53) {
195            let too_big = (usize::MAX as u64).saturating_add(1) as f64;
196            let err = usize_limit_from_f64("max_loaded_bytes", too_big).expect_err("overflow");
197            assert!(err.contains("exceeds platform usize maximum"), "got: {err}");
198        }
199    }
200}