Skip to content

Commit 06cd0b9

Browse files
authored
Reuse the cel environment built from a Context across evaluations (#51)
## Why Every `evaluate()` and `Program.execute()` call rebuilt the cel-rust context from scratch: each variable re-boxed into a `Box<dyn Val>`, each registered Python function re-wrapped in a fresh closure. So the per-call cost scaled with the size of the Python `Context`, not the expression. The CLI, which registers all 47 extended-stdlib functions, paid ~7.5 µs of setup to evaluate `1 + 2`. ## What `Context` now builds its cel environment on first use and caches it (`Mutex<Option<Arc<cel::Context<'static>>>>`). `add_variable`, `add_function` and `update` drop the cache. `set_variable_resolver` does not need to: the resolver is bound per call in a child scope via cel-rust's `Context::new_inner_scope`, which keeps exactly the lookup order the resolver had on the root (resolver → registered variables → type identifiers), and leaves the root untouched and shareable. The evaluation borrows an `Arc` clone rather than the Python object, so a callback may mutate, or re-enter evaluation with, the `Context` it was registered on; the mutation applies from the next evaluation, which is also what happened before (the old code copied variables and functions out before executing). Dict contexts are still materialised per call, because a dict can change between calls without notice. Also in this PR, because the same code was being rewritten: the Python-function wrapper and the compile step are factored into helpers shared by `evaluate()`/`compile()`, and the panic message for an execution-time panic no longer calls itself a parser error. ## Numbers `min` of 3 × 50 000 iterations, release build, same machine. "Before" is `main`'s Rust (built from the #44 branch, which only touches Python). | `Program.execute()` against… | before | after | |---|---:|---:| | no context | 0.13 µs | 0.15 µs | | dict, 2 vars | 0.43 µs | 0.54 µs | | `Context`, 2 vars | 0.31 µs | 0.18 µs | | `Context`, 2 vars + 1 Python fn (called) | 0.70 µs | 0.37 µs | | `Context`, 2 vars + resolver | 0.43 µs | 0.24 µs | | `Context` with the 47 extended-stdlib functions | **7.48 µs** | **0.16 µs** | | `Context` with 200 vars | **31.85 µs** | **0.13 µs** | The no-context and dict rows are within run-to-run noise (an alternating A/B of 7 × 100 000 iterations gave 0.13–0.14 vs 0.13–0.14 and 0.45–0.48 vs 0.42–0.48). ## Tests New `tests/test_context_reuse.py` pins the contract: every mutator is visible on the next evaluation (including replacing a function and replacing the resolver); resolver precedence over registered variables is unchanged; a callback can mutate the context it runs under and can call `evaluate()`/`execute()` with that same context; one `Context` serves many programs; a `Context` shared across 8 threads returns correct results. 528 passed, 1 skipped, 5 xfailed. `cargo fmt --check`, `cargo clippy -D warnings`, `cargo test`, ruff and mypy clean. Note for merging: this and #44 both add to the CHANGELOG's Unreleased section, so whichever lands second will need a trivial conflict resolution there.
1 parent 2c71b41 commit 06cd0b9

5 files changed

Lines changed: 473 additions & 181 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1515
evaluation results use) and functions as the registered callables. Mutating the
1616
returned dict does not change the context.
1717

18+
### Performance
19+
20+
- **A `cel.Context` now builds its CEL-side environment once and reuses it.**
21+
Previously every `evaluate()` and `Program.execute()` call re-converted each
22+
variable and re-wrapped each registered Python function into a fresh cel-rust
23+
context, so the per-call cost grew with the size of the context: executing a
24+
pre-compiled `1 + 2` against a `Context` carrying the 47 extended-stdlib
25+
functions (what the `cel` CLI sets up) took about 9 µs, against about 0.2 µs
26+
with no context. The environment is now cached on the `Context` and shared by
27+
every evaluation until `add_variable`, `add_function` or `update` changes it,
28+
bringing that case down to about 0.2 µs as well. `set_variable_resolver` does
29+
not invalidate the cache: the resolver is bound per call in a child scope
30+
(cel-rust's `Context::new_inner_scope`), with the same lookup order as before
31+
(resolver, then registered variables). Dict contexts are still materialised on
32+
every call, since a dict can change between calls without notice; for hot
33+
loops, prefer a `Context`.
34+
- Behaviour that is unchanged and now pinned by tests: every mutator is visible on
35+
the next evaluation; a Python function may modify, or evaluate against, the
36+
`Context` it was registered on while an evaluation is in progress (the change
37+
applies from the next evaluation); and one `Context` can be shared between
38+
threads.
39+
40+
### Changed
41+
42+
- The `ValueError` raised when the interpreter panics during evaluation now reads
43+
"Internal evaluation error" rather than "Internal parser error"; parse failures
44+
were never what it reported.
45+
1846
### Fixed
1947

2048
- **`import cel` failed in a clean install.** `cel.cli` imported `Annotated` from

‎docs/reference/python-api.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,12 @@ The Context class provides more control over the evaluation environment than sim
207207
- Register custom Python functions
208208
- Manage complex evaluation scenarios
209209

210+
It is also the fast path for repeated evaluation. A `Context` converts its
211+
variables and wraps its functions for the CEL engine once, on first use, and
212+
reuses that work for every subsequent `evaluate()` or `Program.execute()` call
213+
until the context is modified. A dict passed as the context is converted afresh
214+
on every call, because it can change between calls without notice.
215+
210216
```python
211217
from cel import evaluate, Context
212218

‎src/context.rs‎

Lines changed: 64 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
use ::cel::objects::TryIntoValue;
2-
use ::cel::Value;
2+
use ::cel::{Context as CelContext, Value};
33
use pyo3::exceptions::PyValueError;
44
use pyo3::prelude::*;
55
use pyo3::types::PyDict;
66
use pyo3::IntoPyObjectExt;
77
use std::collections::HashMap;
8+
use std::sync::{Arc, Mutex, PoisonError};
89

910
#[pyo3::pyclass]
1011
/// Manages the evaluation environment for CEL expressions.
@@ -41,15 +42,69 @@ use std::collections::HashMap;
4142
/// for concurrent use or implement your own synchronization.
4243
///
4344
/// Performance Tips:
44-
/// - Reuse Context objects for multiple evaluations when possible
45+
/// - Reuse Context objects for multiple evaluations when possible: the
46+
/// CEL-side environment (converted variables and wrapped functions) is
47+
/// built on first use and reused until the context is modified
4548
/// - Pre-populate Context with all needed variables and functions
46-
/// - Avoid frequent add_variable/add_function calls in hot code paths
49+
/// - Avoid frequent add_variable/add_function calls in hot code paths, as
50+
/// each one discards the cached environment
4751
pub struct Context {
4852
pub variables: HashMap<String, Value>,
4953
pub functions: HashMap<String, Py<PyAny>>,
5054
/// Optional Python callable for lazy variable resolution. Invoked with a
5155
/// variable name; returns the value (or None to fall through to `variables`).
5256
pub resolver: Option<Py<PyAny>>,
57+
/// The cel environment built from `variables` and `functions`, created on
58+
/// first use and shared by every evaluation until a mutator clears it.
59+
///
60+
/// Building it boxes each variable and wraps each Python callable in a
61+
/// closure. That used to happen on every `evaluate()`/`execute()` call and
62+
/// dominated the cost of evaluating against a context with many functions
63+
/// (the CLI registers the whole extended stdlib). The resolver is
64+
/// deliberately not part of it: it is bound per call in a child scope, so
65+
/// setting one does not invalidate the cache.
66+
cel: Mutex<Option<Arc<CelContext<'static>>>>,
67+
}
68+
69+
impl Context {
70+
/// Materialises a fresh cel environment from the registered variables and
71+
/// functions. Used for the cache and, on every call, for dict contexts.
72+
pub(crate) fn build_cel_context(&self, py: Python<'_>) -> CelContext<'static> {
73+
let mut environment = crate::new_environment();
74+
for (name, value) in &self.variables {
75+
environment.add_variable_from_value(name.clone(), value.clone());
76+
}
77+
for (name, function) in &self.functions {
78+
crate::register_python_function(&mut environment, name, function.clone_ref(py));
79+
}
80+
environment
81+
}
82+
83+
/// Returns the cached cel environment, building it on first use.
84+
///
85+
/// The `Arc` lets a caller keep evaluating against a consistent snapshot
86+
/// even if a Python callback mutates this `Context` mid-evaluation; the
87+
/// mutation simply takes effect from the next evaluation.
88+
pub(crate) fn cel_context(&self, py: Python<'_>) -> Arc<CelContext<'static>> {
89+
let mut cached = self.cel.lock().unwrap_or_else(PoisonError::into_inner);
90+
if let Some(existing) = cached.as_ref() {
91+
return Arc::clone(existing);
92+
}
93+
let built = Arc::new(self.build_cel_context(py));
94+
*cached = Some(Arc::clone(&built));
95+
built
96+
}
97+
98+
/// Drops the cached environment so the next evaluation rebuilds it.
99+
///
100+
/// Every mutator calls this *before* touching `variables` or `functions`.
101+
/// A mutator can fail part-way (`update()` rejects a later key after
102+
/// inserting earlier ones), and invalidating up front means the cache can
103+
/// never describe state the maps no longer hold. Nothing can repopulate it
104+
/// while the mutator runs, because the mutator holds `&mut self`.
105+
fn invalidate(&mut self) {
106+
*self.cel.get_mut().unwrap_or_else(PoisonError::into_inner) = None;
107+
}
53108
}
54109

55110
#[pyo3::pymethods]
@@ -130,6 +185,7 @@ impl Context {
130185
variables: HashMap::new(),
131186
functions: HashMap::new(),
132187
resolver: None,
188+
cel: Mutex::new(None),
133189
};
134190

135191
if let Some(variables) = variables {
@@ -208,6 +264,7 @@ impl Context {
208264
/// >>> context.add_function("regex_match", re.match)
209265
/// >>> # Note: This would need proper error handling in practice
210266
fn add_function(&mut self, name: String, function: Py<PyAny>) {
267+
self.invalidate();
211268
self.functions.insert(name, function);
212269
}
213270

@@ -346,6 +403,7 @@ impl Context {
346403
/// >>> evaluate("counter", context)
347404
/// 2
348405
pub fn add_variable(&mut self, name: String, value: &Bound<'_, PyAny>) -> PyResult<()> {
406+
self.invalidate();
349407
let value = crate::RustyPyType(value).try_into_value().map_err(|e| {
350408
pyo3::exceptions::PyValueError::new_err(format!(
351409
"Failed to convert variable '{name}': {e}"
@@ -442,6 +500,9 @@ impl Context {
442500
/// >>> evaluate('join(["user", name, string(age)])', context)
443501
/// 'user-Bob-30'
444502
pub fn update(&mut self, variables: &Bound<'_, PyDict>) -> PyResult<()> {
503+
// Before the loop, not after: a bad key or value part-way through
504+
// returns early with the earlier entries already applied.
505+
self.invalidate();
445506
for (key, value) in variables {
446507
// Attempt to extract the key as a String
447508
let key = key

0 commit comments

Comments
 (0)