Skip to main content

graphrt_core/
pool.rs

1//! Selectors and the variable pool.
2//!
3//! A [`Selector`] addresses a value as `namespace.name[.path...]`, where the
4//! namespace is a node id or one of the reserved namespaces ([`SYS`], [`ENV`],
5//! [`CONVERSATION`]). The [`VariablePool`] stores one [`Variables`] map per
6//! namespace (shared on clone), and the namespace table itself is shared too:
7//! cloning a pool (for a node context, an iteration item or a loop round) is
8//! O(1), and writes copy only the touched namespace (plus the table, when it is
9//! shared). A node's outputs become its namespace without being copied.
10
11use std::collections::HashMap;
12use std::fmt;
13use std::hash::{BuildHasher, BuildHasherDefault, Hasher};
14use std::sync::{Arc, OnceLock};
15
16use indexmap::IndexMap;
17use serde::{Deserialize, Deserializer, Serialize, Serializer};
18
19use crate::value::{Value, ValueType};
20use crate::variables::Variables;
21
22/// System variables (`sys.query`, `sys.files`, `sys.run_id`, ...). Written by the host only.
23pub const SYS: &str = "sys";
24/// Environment variables / secrets. Supplied by the host, never persisted in snapshots.
25pub const ENV: &str = "env";
26/// Conversation-scoped variables. Persisted by the host between runs.
27pub const CONVERSATION: &str = "conversation";
28
29/// Address of a value: `[namespace, name, path...]`.
30#[derive(Clone, PartialEq, Eq, Hash)]
31pub struct Selector {
32    parts: Arc<[Arc<str>]>,
33}
34
35/// Error for malformed selectors.
36#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
37#[error("invalid selector `{0}`: needs at least a namespace and a name")]
38pub struct InvalidSelector(pub String);
39
40impl Selector {
41    /// Build from parts. Requires at least two non-empty parts.
42    pub fn new<I, S>(parts: I) -> Result<Self, InvalidSelector>
43    where
44        I: IntoIterator<Item = S>,
45        S: AsRef<str>,
46    {
47        let parts: Vec<Arc<str>> = parts.into_iter().map(|p| Arc::from(p.as_ref())).collect();
48        if parts.len() < 2 || parts.iter().any(|p| p.is_empty()) {
49            return Err(InvalidSelector(parts.join(".")));
50        }
51        Ok(Self { parts: parts.into() })
52    }
53
54    /// Parse a dotted selector such as `llm.text` or `start.user.name`.
55    pub fn parse(dotted: &str) -> Result<Self, InvalidSelector> {
56        Self::new(dotted.split('.'))
57    }
58
59    /// Two-part selector `namespace.name`.
60    pub fn of(namespace: &str, name: &str) -> Self {
61        Self { parts: vec![Arc::from(namespace), Arc::from(name)].into() }
62    }
63
64    pub fn namespace(&self) -> &str {
65        self.parts.first().map(AsRef::as_ref).unwrap_or_default()
66    }
67
68    pub fn name(&self) -> &str {
69        self.parts.get(1).map(AsRef::as_ref).unwrap_or_default()
70    }
71
72    /// Path below the variable (`a.b.c` -> `[c]`).
73    pub fn path(&self) -> &[Arc<str>] {
74        self.parts.get(2..).unwrap_or_default()
75    }
76
77    pub fn parts(&self) -> &[Arc<str>] {
78        &self.parts
79    }
80
81    /// The `namespace.name` prefix of this selector.
82    pub fn root(&self) -> Selector {
83        Selector::of(self.namespace(), self.name())
84    }
85
86    /// Append path parts.
87    pub fn child(&self, part: &str) -> Selector {
88        let mut parts: Vec<Arc<str>> = self.parts.to_vec();
89        parts.push(Arc::from(part));
90        Selector { parts: parts.into() }
91    }
92}
93
94impl fmt::Display for Selector {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        f.write_str(&self.parts.join("."))
97    }
98}
99
100impl fmt::Debug for Selector {
101    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102        write!(f, "Selector({self})")
103    }
104}
105
106impl Serialize for Selector {
107    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
108        self.parts.iter().map(AsRef::as_ref).collect::<Vec<&str>>().serialize(serializer)
109    }
110}
111
112impl<'de> Deserialize<'de> for Selector {
113    /// Accepts `["node", "var"]` or `"node.var"`.
114    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
115        #[derive(Deserialize)]
116        #[serde(untagged)]
117        enum Repr {
118            List(Vec<String>),
119            Dotted(String),
120        }
121        let sel = match Repr::deserialize(deserializer)? {
122            Repr::List(parts) => Selector::new(parts),
123            Repr::Dotted(s) => Selector::parse(&s),
124        };
125        sel.map_err(serde::de::Error::custom)
126    }
127}
128
129type Namespace = Variables;
130type ShardMap = HashMap<Arc<str>, Namespace, BuildHasherDefault<NamespaceHasher>>;
131
132/// Hasher for namespace names in the shard maps.
133///
134/// Every node commit looks its namespace up, and SipHash (the std default) was
135/// a visible share of the engine's per-node cost. Names are short ids from the
136/// workflow document or the host, so a word-at-a-time multiplicative hash
137/// (FxHash-style) suffices; it is keyed per process so collisions cannot be
138/// precomputed.
139#[derive(Clone, Copy)]
140struct NamespaceHasher(u64);
141
142/// Per-process key of [`NamespaceHasher`].
143fn namespace_hash_seed() -> u64 {
144    static SEED: OnceLock<u64> = OnceLock::new();
145    *SEED.get_or_init(|| std::collections::hash_map::RandomState::new().build_hasher().finish())
146}
147
148impl Default for NamespaceHasher {
149    fn default() -> Self {
150        Self(namespace_hash_seed())
151    }
152}
153
154impl NamespaceHasher {
155    fn add(&mut self, word: u64) {
156        self.0 = (self.0.rotate_left(5) ^ word).wrapping_mul(0x517c_c1b7_2722_0a95);
157    }
158}
159
160impl Hasher for NamespaceHasher {
161    fn finish(&self) -> u64 {
162        // The multiply leaves the low bits (the table's bucket index) weakest.
163        self.0.rotate_left(26)
164    }
165
166    fn write(&mut self, bytes: &[u8]) {
167        let (chunks, rest) = bytes.as_chunks::<8>();
168        for chunk in chunks {
169            self.add(u64::from_le_bytes(*chunk));
170        }
171        if !rest.is_empty() {
172            let mut word = [0u8; 8];
173            if let Some(head) = word.get_mut(..rest.len()) {
174                head.copy_from_slice(rest);
175            }
176            self.add(u64::from_le_bytes(word));
177        }
178    }
179
180    fn write_u8(&mut self, byte: u8) {
181        self.add(u64::from(byte));
182    }
183}
184/// `None` until a namespace hashing to the shard is written.
185type Shard = Option<Arc<ShardMap>>;
186
187/// Number of shards in the namespace table. Every node owns a namespace, so a
188/// large graph has many; sharding keeps a copy-on-write update proportional to
189/// one shard instead of the whole table while snapshots are shared with
190/// running nodes.
191const SHARDS: usize = 32;
192
193/// Namespace table split into [`SHARDS`] independently shared maps. Cloning is
194/// O(1); an update copies at most the shard array (`SHARDS` pointers) and one shard.
195///
196/// Shards and the shard array are allocated on first write: an empty table
197/// costs no allocation, where eagerly creating every shard cost 33 per pool
198/// and a pool is created for every execution frame.
199#[derive(Clone, Default)]
200struct Table {
201    shards: Option<Arc<[Shard; SHARDS]>>,
202    /// Initial capacity of a shard map when it is created.
203    shard_capacity: usize,
204}
205
206/// Shard index of a namespace (FNV-1a: stable and fast for short ids).
207fn shard_of(namespace: &str) -> usize {
208    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
209    for byte in namespace.bytes() {
210        hash ^= u64::from(byte);
211        hash = hash.wrapping_mul(0x0100_0000_01b3);
212    }
213    // The remainder is below SHARDS, so the conversion cannot fail.
214    usize::try_from(hash % SHARDS as u64).unwrap_or(0)
215}
216
217impl Table {
218    fn shard(&self, namespace: &str) -> Option<&ShardMap> {
219        self.shards.as_ref()?.get(shard_of(namespace))?.as_deref()
220    }
221
222    /// Mutable shard holding `namespace`, allocating or copying shared structure as needed.
223    #[allow(clippy::indexing_slicing)] // shard_of() < SHARDS by construction
224    fn shard_mut(&mut self, namespace: &str) -> &mut ShardMap {
225        let capacity = self.shard_capacity;
226        let shards = Arc::make_mut(self.shards.get_or_insert_with(Default::default));
227        let shard = shards[shard_of(namespace)]
228            .get_or_insert_with(|| Arc::new(HashMap::with_capacity_and_hasher(capacity, Default::default())));
229        Arc::make_mut(shard)
230    }
231
232    fn get(&self, namespace: &str) -> Option<&Namespace> {
233        self.shard(namespace)?.get(namespace)
234    }
235
236    fn entry(&mut self, namespace: &str) -> &mut Namespace {
237        let shard = self.shard_mut(namespace);
238        // Reuse the existing key (a reference-count bump) instead of allocating
239        // a new `Arc<str>` on every write to a namespace that already exists.
240        let key = shard.get_key_value(namespace).map_or_else(|| Arc::from(namespace), |(key, _)| Arc::clone(key));
241        shard.entry(key).or_default()
242    }
243
244    /// Like [`Table::entry`], but a new namespace takes `namespace` as its key
245    /// (a reference-count bump) instead of allocating a copy.
246    fn entry_shared(&mut self, namespace: &Arc<str>) -> &mut Namespace {
247        let shard = self.shard_mut(namespace);
248        let key =
249            shard.get_key_value(namespace.as_ref()).map_or_else(|| Arc::clone(namespace), |(key, _)| Arc::clone(key));
250        shard.entry(key).or_default()
251    }
252
253    fn remove(&mut self, namespace: &str) {
254        if self.get(namespace).is_some() {
255            self.shard_mut(namespace).remove(namespace);
256        }
257    }
258
259    fn iter(&self) -> impl Iterator<Item = (&Arc<str>, &Namespace)> {
260        self.shards.iter().flat_map(|shards| shards.iter().flatten()).flat_map(|shard| shard.iter())
261    }
262}
263
264/// Store a node's outputs in its namespace. An empty namespace (the usual
265/// case: a node's first commit) takes the outputs map itself, a reference-count
266/// bump; otherwise the outputs are merged in.
267fn store_outputs(namespace: &mut Namespace, outputs: &Variables) {
268    if namespace.is_empty() {
269        namespace.clone_from(outputs);
270        return;
271    }
272    namespace.reserve(outputs.len());
273    for (name, value) in outputs.named_entries() {
274        namespace.insert(name.clone(), value.clone());
275    }
276}
277
278/// Variable storage for one execution frame.
279#[derive(Clone, Default)]
280pub struct VariablePool {
281    namespaces: Table,
282}
283
284impl fmt::Debug for VariablePool {
285    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286        let mut map = f.debug_map();
287        for (ns, vars) in self.namespaces.iter() {
288            map.entry(ns, vars);
289        }
290        map.finish()
291    }
292}
293
294impl VariablePool {
295    pub fn new() -> Self {
296        Self::default()
297    }
298
299    /// An empty pool sized for about `namespaces` namespaces (the engine passes
300    /// the graph's node count), so filling it does not keep regrowing its maps.
301    pub(crate) fn with_namespace_capacity(namespaces: usize) -> Self {
302        // Shards fill unevenly; a quarter of headroom avoids most regrowth.
303        let shard_capacity = (namespaces + namespaces / 4) / SHARDS;
304        Self { namespaces: Table { shards: None, shard_capacity } }
305    }
306
307    /// Resolve a selector, descending into nested values. Missing values return `None`.
308    pub fn get(&self, selector: &Selector) -> Option<Value> {
309        let root = self.namespaces.get(selector.namespace())?.get(selector.name())?;
310        if selector.path().is_empty() { Some(root.clone()) } else { root.get_path(selector.path()) }
311    }
312
313    /// Resolve a selector, returning [`Value::Null`] when absent.
314    pub fn get_or_null(&self, selector: &Selector) -> Value {
315        self.get(selector).unwrap_or(Value::Null)
316    }
317
318    /// Set `namespace.name`. Any path in the selector is ignored; use [`VariablePool::set_path`]
319    /// for nested writes.
320    pub fn set(&mut self, selector: &Selector, value: Value) {
321        self.insert(selector.namespace(), selector.name(), value);
322    }
323
324    /// Set a variable by namespace and name.
325    pub fn insert(&mut self, namespace: &str, name: &str, value: Value) {
326        self.namespaces.entry(namespace).insert_str(name, value);
327    }
328
329    /// Write into a nested path, creating intermediate objects as needed.
330    /// Array elements are addressed by index; writing past the end of an array
331    /// is an error (nothing is written).
332    pub fn set_path(&mut self, selector: &Selector, value: Value) -> Result<(), PathError> {
333        if selector.path().is_empty() {
334            self.set(selector, value);
335            return Ok(());
336        }
337        let current = self.get(&selector.root()).unwrap_or(Value::Null);
338        let updated = write_path(current, selector.path(), value)
339            .map_err(|index| PathError { selector: selector.to_string(), index })?;
340        self.set(selector, updated);
341        Ok(())
342    }
343
344    /// Remove one variable.
345    pub fn remove(&mut self, selector: &Selector) -> Option<Value> {
346        if !self.namespaces.get(selector.namespace())?.contains_key(selector.name()) {
347            return None;
348        }
349        self.namespaces.entry(selector.namespace()).remove(selector.name())
350    }
351
352    /// Drop a whole namespace (e.g. a node's outputs before a loop round re-runs it).
353    pub fn remove_namespace(&mut self, namespace: &str) {
354        self.namespaces.remove(namespace);
355    }
356
357    /// Bulk-insert a node's outputs. Into an empty namespace this shares
358    /// `outputs` instead of copying it.
359    pub fn set_outputs(&mut self, namespace: &str, outputs: &Variables) {
360        store_outputs(self.namespaces.entry(namespace), outputs);
361    }
362
363    /// [`VariablePool::set_outputs`] for a namespace the caller already holds as
364    /// an `Arc<str>` (the engine's node ids), which avoids copying the name.
365    pub(crate) fn set_outputs_shared(&mut self, namespace: &Arc<str>, outputs: &Variables) {
366        store_outputs(self.namespaces.entry_shared(namespace), outputs);
367    }
368
369    /// All variables in a namespace.
370    pub fn namespace(&self, namespace: &str) -> Option<&Variables> {
371        self.namespaces.get(namespace)
372    }
373
374    pub fn contains(&self, selector: &Selector) -> bool {
375        self.get(selector).is_some()
376    }
377
378    /// Iterate `(namespace, name, value)`.
379    pub fn iter(&self) -> impl Iterator<Item = (&str, &str, &Value)> {
380        self.namespaces.iter().flat_map(|(ns, vars)| vars.iter().map(move |(k, v)| (ns.as_ref(), k, v)))
381    }
382
383    /// Serializable form for snapshots. The [`ENV`] namespace is excluded: the host
384    /// must supply environment variables again on resume. Secrets in other
385    /// namespaces are stored as `{"$secret": "redacted"}` markers and restored as
386    /// redacted secrets (see [`Value::redacted_secret`]).
387    pub fn to_snapshot(&self) -> PoolSnapshot {
388        let mut out: IndexMap<String, IndexMap<String, Value>> = IndexMap::new();
389        let mut entries: Vec<(&Arc<str>, &Namespace)> = self.namespaces.iter().collect();
390        entries.sort_unstable_by(|a, b| a.0.cmp(b.0));
391        for (ns, vars) in entries {
392            if ns.as_ref() == ENV {
393                continue;
394            }
395            out.insert(ns.to_string(), vars.iter().map(|(k, v)| (k.to_string(), v.to_snapshot_value())).collect());
396        }
397        PoolSnapshot(out)
398    }
399
400    /// Restore from a snapshot (env variables must be re-applied by the caller).
401    pub fn from_snapshot(snapshot: PoolSnapshot) -> Self {
402        let mut pool = Self::new();
403        for (ns, vars) in snapshot.0 {
404            let restored: Variables = vars.into_iter().map(|(k, v)| (k, v.from_snapshot_value())).collect();
405            store_outputs(pool.namespaces.entry(&ns), &restored);
406        }
407        pool
408    }
409
410    /// Insert a typed declared variable, validating it against its declared type.
411    pub fn insert_typed(
412        &mut self,
413        namespace: &str,
414        name: &str,
415        ty: ValueType,
416        value: Value,
417    ) -> Result<(), crate::value::TypeMismatch> {
418        let v = ty.coerce(value)?;
419        self.insert(namespace, name, v);
420        Ok(())
421    }
422}
423
424/// Persistable variable pool contents (`namespace -> name -> value`).
425#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
426#[serde(transparent)]
427pub struct PoolSnapshot(pub IndexMap<String, IndexMap<String, Value>>);
428
429/// Error writing a nested path.
430#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
431#[error("cannot write `{selector}`: array index {index} is out of range")]
432pub struct PathError {
433    pub selector: String,
434    pub index: usize,
435}
436
437/// Returns the out-of-range index on failure.
438fn write_path(current: Value, path: &[Arc<str>], value: Value) -> Result<Value, usize> {
439    let Some((head, rest)) = path.split_first() else {
440        return Ok(value);
441    };
442    match current {
443        Value::Array(items) if head.parse::<usize>().is_ok() => {
444            let idx = head.parse::<usize>().unwrap_or(0);
445            let mut items = Arc::unwrap_or_clone(items);
446            let slot = items.get_mut(idx).ok_or(idx)?;
447            let old = std::mem::take(slot);
448            *slot = write_path(old, rest, value)?;
449            Ok(Value::Array(Arc::new(items)))
450        }
451        other => {
452            let mut map = match other {
453                Value::Object(m) => Arc::unwrap_or_clone(m),
454                _ => IndexMap::new(),
455            };
456            // Take the old value in place so the key keeps its position.
457            let old = map.get_mut(head.as_ref()).map(std::mem::take).unwrap_or(Value::Null);
458            map.insert(head.to_string(), write_path(old, rest, value)?);
459            Ok(Value::Object(Arc::new(map)))
460        }
461    }
462}
463
464#[cfg(test)]
465mod tests {
466    use super::*;
467
468    fn sel(s: &str) -> Selector {
469        Selector::parse(s).unwrap_or_else(|_| Selector::of("bad", "bad"))
470    }
471
472    #[test]
473    fn selector_parsing() {
474        assert!(Selector::parse("a").is_err());
475        assert!(Selector::parse("a..b").is_err());
476        let s = sel("n.v.x.y");
477        assert_eq!(s.namespace(), "n");
478        assert_eq!(s.name(), "v");
479        assert_eq!(s.path().len(), 2);
480        let from_list: Result<Selector, _> = serde_json::from_str("[\"n\",\"v\"]");
481        let from_str: Result<Selector, _> = serde_json::from_str("\"n.v\"");
482        assert_eq!(from_list.ok(), from_str.ok());
483    }
484
485    #[test]
486    fn namespace_hasher_separates_similar_ids() {
487        let hash = |s: &str| BuildHasherDefault::<NamespaceHasher>::default().hash_one(s);
488        assert_eq!(hash("node_12"), hash("node_12"));
489        let ids: std::collections::HashSet<u64> = (0..10_000).map(|i| hash(&format!("n{i}"))).collect();
490        assert_eq!(ids.len(), 10_000);
491        // Ids differing only past the first 8-byte word, or by a trailing byte.
492        assert_ne!(hash("longer_node_id_a"), hash("longer_node_id_b"));
493        assert_ne!(hash("abcdefgh"), hash("abcdefgh\0"));
494    }
495
496    #[test]
497    fn outputs_become_the_namespace_without_a_copy() {
498        let outputs = Variables::from([("text", Value::from("hi"))]);
499        let mut p = VariablePool::new();
500        p.set_outputs("llm", &outputs);
501        assert!(p.namespace("llm").is_some_and(|ns| ns.ptr_eq(&outputs)));
502        // A namespace that already holds variables merges instead.
503        p.insert("loop", "i", Value::Int(1));
504        p.set_outputs("loop", &outputs);
505        let merged = p.namespace("loop").map(|ns| ns.keys().collect::<Vec<_>>());
506        assert_eq!(merged, Some(vec!["i", "text"]));
507        assert_eq!(outputs.len(), 1, "the caller's map is not modified");
508    }
509
510    #[test]
511    fn presized_pool_behaves_like_a_new_one() {
512        let mut p = VariablePool::with_namespace_capacity(1_000);
513        p.insert("n", "x", Value::Int(1));
514        let mut q = p.clone();
515        q.insert("n", "x", Value::Int(2));
516        assert_eq!(p.get(&sel("n.x")), Some(Value::Int(1)));
517        assert_eq!(q.get(&sel("n.x")), Some(Value::Int(2)));
518        assert!(VariablePool::with_namespace_capacity(0).get(&sel("n.x")).is_none());
519    }
520
521    #[test]
522    fn many_namespaces_stay_addressable() {
523        let mut p = VariablePool::new();
524        for i in 0..2_000 {
525            p.insert(&format!("node{i}"), "v", Value::Int(i));
526        }
527        for i in 0..2_000 {
528            assert_eq!(p.get(&sel(&format!("node{i}.v"))), Some(Value::Int(i)));
529        }
530    }
531
532    #[test]
533    fn clone_is_copy_on_write() {
534        let mut a = VariablePool::new();
535        a.insert("n", "x", Value::Int(1));
536        let mut b = a.clone();
537        b.insert("n", "x", Value::Int(2));
538        assert_eq!(a.get(&sel("n.x")), Some(Value::Int(1)));
539        assert_eq!(b.get(&sel("n.x")), Some(Value::Int(2)));
540    }
541
542    #[test]
543    fn nested_get_and_set() {
544        let mut p = VariablePool::new();
545        p.set_path(&sel("n.obj.a.b"), Value::from("deep")).unwrap();
546        p.insert("n", "list", Value::from_json(serde_json::json!([1, 2])));
547        p.set_path(&sel("n.list.1"), Value::Int(9)).unwrap();
548        assert_eq!(p.get(&sel("n.list")), Some(Value::from_json(serde_json::json!([1, 9]))));
549        assert!(p.set_path(&sel("n.list.5"), Value::Int(9)).is_err());
550        assert_eq!(p.get(&sel("n.obj.a.b")), Some(Value::from("deep")));
551        assert_eq!(p.get(&sel("n.obj.missing")), None);
552    }
553
554    #[test]
555    fn snapshot_excludes_env() {
556        let mut p = VariablePool::new();
557        p.insert(ENV, "KEY", Value::Secret(Arc::from("s3cret")));
558        p.insert("n", "x", Value::Int(1));
559        let snap = p.to_snapshot();
560        let json = serde_json::to_string(&snap).unwrap_or_default();
561        assert!(!json.contains("s3cret"));
562        assert!(!json.contains("env"));
563        let restored = VariablePool::from_snapshot(snap);
564        assert_eq!(restored.get(&sel("n.x")), Some(Value::Int(1)));
565    }
566}