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 map per namespace behind an
6//! `Arc`, and the namespace table itself is shared too: cloning a pool (for a
7//! node context, an iteration item or a loop round) is O(1), and writes copy
8//! only the touched namespace (plus the table, when it is shared).
9
10use std::collections::HashMap;
11use std::fmt;
12use std::sync::Arc;
13
14use indexmap::IndexMap;
15use serde::{Deserialize, Deserializer, Serialize, Serializer};
16
17use crate::value::{Value, ValueType};
18
19/// System variables (`sys.query`, `sys.files`, `sys.run_id`, ...). Written by the host only.
20pub const SYS: &str = "sys";
21/// Environment variables / secrets. Supplied by the host, never persisted in snapshots.
22pub const ENV: &str = "env";
23/// Conversation-scoped variables. Persisted by the host between runs.
24pub const CONVERSATION: &str = "conversation";
25
26/// Address of a value: `[namespace, name, path...]`.
27#[derive(Clone, PartialEq, Eq, Hash)]
28pub struct Selector {
29    parts: Arc<[Arc<str>]>,
30}
31
32/// Error for malformed selectors.
33#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
34#[error("invalid selector `{0}`: needs at least a namespace and a name")]
35pub struct InvalidSelector(pub String);
36
37impl Selector {
38    /// Build from parts. Requires at least two non-empty parts.
39    pub fn new<I, S>(parts: I) -> Result<Self, InvalidSelector>
40    where
41        I: IntoIterator<Item = S>,
42        S: AsRef<str>,
43    {
44        let parts: Vec<Arc<str>> = parts.into_iter().map(|p| Arc::from(p.as_ref())).collect();
45        if parts.len() < 2 || parts.iter().any(|p| p.is_empty()) {
46            return Err(InvalidSelector(parts.join(".")));
47        }
48        Ok(Self { parts: parts.into() })
49    }
50
51    /// Parse a dotted selector such as `llm.text` or `start.user.name`.
52    pub fn parse(dotted: &str) -> Result<Self, InvalidSelector> {
53        Self::new(dotted.split('.'))
54    }
55
56    /// Two-part selector `namespace.name`.
57    pub fn of(namespace: &str, name: &str) -> Self {
58        Self { parts: vec![Arc::from(namespace), Arc::from(name)].into() }
59    }
60
61    pub fn namespace(&self) -> &str {
62        self.parts.first().map(AsRef::as_ref).unwrap_or_default()
63    }
64
65    pub fn name(&self) -> &str {
66        self.parts.get(1).map(AsRef::as_ref).unwrap_or_default()
67    }
68
69    /// Path below the variable (`a.b.c` -> `[c]`).
70    pub fn path(&self) -> &[Arc<str>] {
71        self.parts.get(2..).unwrap_or_default()
72    }
73
74    pub fn parts(&self) -> &[Arc<str>] {
75        &self.parts
76    }
77
78    /// The `namespace.name` prefix of this selector.
79    pub fn root(&self) -> Selector {
80        Selector::of(self.namespace(), self.name())
81    }
82
83    /// Append path parts.
84    pub fn child(&self, part: &str) -> Selector {
85        let mut parts: Vec<Arc<str>> = self.parts.to_vec();
86        parts.push(Arc::from(part));
87        Selector { parts: parts.into() }
88    }
89}
90
91impl fmt::Display for Selector {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        f.write_str(&self.parts.join("."))
94    }
95}
96
97impl fmt::Debug for Selector {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        write!(f, "Selector({self})")
100    }
101}
102
103impl Serialize for Selector {
104    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
105        self.parts.iter().map(AsRef::as_ref).collect::<Vec<&str>>().serialize(serializer)
106    }
107}
108
109impl<'de> Deserialize<'de> for Selector {
110    /// Accepts `["node", "var"]` or `"node.var"`.
111    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
112        #[derive(Deserialize)]
113        #[serde(untagged)]
114        enum Repr {
115            List(Vec<String>),
116            Dotted(String),
117        }
118        let sel = match Repr::deserialize(deserializer)? {
119            Repr::List(parts) => Selector::new(parts),
120            Repr::Dotted(s) => Selector::parse(&s),
121        };
122        sel.map_err(serde::de::Error::custom)
123    }
124}
125
126type Namespace = Arc<IndexMap<Arc<str>, Value>>;
127type Shard = Arc<HashMap<Arc<str>, Namespace>>;
128
129/// Number of shards in the namespace table. Every node owns a namespace, so a
130/// large graph has many; sharding keeps a copy-on-write update proportional to
131/// one shard instead of the whole table while snapshots are shared with
132/// running nodes.
133const SHARDS: usize = 32;
134
135/// Namespace table split into [`SHARDS`] independently shared maps. Cloning is
136/// O(1); an update copies at most the shard array (`SHARDS` pointers) and one shard.
137#[derive(Clone, Default)]
138struct Table {
139    shards: Arc<[Shard; SHARDS]>,
140}
141
142/// Shard index of a namespace (FNV-1a: stable and fast for short ids).
143fn shard_of(namespace: &str) -> usize {
144    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
145    for byte in namespace.bytes() {
146        hash ^= u64::from(byte);
147        hash = hash.wrapping_mul(0x0100_0000_01b3);
148    }
149    // The remainder is below SHARDS, so the conversion cannot fail.
150    usize::try_from(hash % SHARDS as u64).unwrap_or(0)
151}
152
153impl Table {
154    #[allow(clippy::indexing_slicing)] // shard_of() < SHARDS by construction
155    fn shard(&self, namespace: &str) -> &HashMap<Arc<str>, Namespace> {
156        &self.shards[shard_of(namespace)]
157    }
158
159    /// Mutable shard holding `namespace`, copying shared structure as needed.
160    #[allow(clippy::indexing_slicing)] // shard_of() < SHARDS by construction
161    fn shard_mut(&mut self, namespace: &str) -> &mut HashMap<Arc<str>, Namespace> {
162        let shards = Arc::make_mut(&mut self.shards);
163        Arc::make_mut(&mut shards[shard_of(namespace)])
164    }
165
166    fn get(&self, namespace: &str) -> Option<&Namespace> {
167        self.shard(namespace).get(namespace)
168    }
169
170    fn entry(&mut self, namespace: &str) -> &mut Namespace {
171        self.shard_mut(namespace).entry(Arc::from(namespace)).or_default()
172    }
173
174    fn remove(&mut self, namespace: &str) {
175        if self.get(namespace).is_some() {
176            self.shard_mut(namespace).remove(namespace);
177        }
178    }
179
180    fn iter(&self) -> impl Iterator<Item = (&Arc<str>, &Namespace)> {
181        self.shards.iter().flat_map(|shard| shard.iter())
182    }
183}
184
185/// Variable storage for one execution frame.
186#[derive(Clone, Default)]
187pub struct VariablePool {
188    namespaces: Table,
189}
190
191impl fmt::Debug for VariablePool {
192    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193        let mut map = f.debug_map();
194        for (ns, vars) in self.namespaces.iter() {
195            map.entry(ns, vars);
196        }
197        map.finish()
198    }
199}
200
201impl VariablePool {
202    pub fn new() -> Self {
203        Self::default()
204    }
205
206    /// Resolve a selector, descending into nested values. Missing values return `None`.
207    pub fn get(&self, selector: &Selector) -> Option<Value> {
208        let root = self.namespaces.get(selector.namespace())?.get(selector.name())?;
209        if selector.path().is_empty() { Some(root.clone()) } else { root.get_path(selector.path()) }
210    }
211
212    /// Resolve a selector, returning [`Value::Null`] when absent.
213    pub fn get_or_null(&self, selector: &Selector) -> Value {
214        self.get(selector).unwrap_or(Value::Null)
215    }
216
217    /// Set `namespace.name`. Any path in the selector is ignored; use [`VariablePool::set_path`]
218    /// for nested writes.
219    pub fn set(&mut self, selector: &Selector, value: Value) {
220        self.insert(selector.namespace(), selector.name(), value);
221    }
222
223    /// Set a variable by namespace and name.
224    pub fn insert(&mut self, namespace: &str, name: &str, value: Value) {
225        Arc::make_mut(self.namespaces.entry(namespace)).insert(Arc::from(name), value);
226    }
227
228    /// Write into a nested path, creating intermediate objects as needed.
229    /// Array elements are addressed by index; writing past the end of an array
230    /// is an error (nothing is written).
231    pub fn set_path(&mut self, selector: &Selector, value: Value) -> Result<(), PathError> {
232        if selector.path().is_empty() {
233            self.set(selector, value);
234            return Ok(());
235        }
236        let current = self.get(&selector.root()).unwrap_or(Value::Null);
237        let updated = write_path(current, selector.path(), value)
238            .map_err(|index| PathError { selector: selector.to_string(), index })?;
239        self.set(selector, updated);
240        Ok(())
241    }
242
243    /// Remove one variable.
244    pub fn remove(&mut self, selector: &Selector) -> Option<Value> {
245        if !self.namespaces.get(selector.namespace())?.contains_key(selector.name()) {
246            return None;
247        }
248        Arc::make_mut(self.namespaces.entry(selector.namespace())).shift_remove(selector.name())
249    }
250
251    /// Drop a whole namespace (e.g. a node's outputs before a loop round re-runs it).
252    pub fn remove_namespace(&mut self, namespace: &str) {
253        self.namespaces.remove(namespace);
254    }
255
256    /// Bulk-insert a node's outputs.
257    pub fn set_outputs(&mut self, namespace: &str, outputs: &IndexMap<String, Value>) {
258        let ns = Arc::make_mut(self.namespaces.entry(namespace));
259        for (k, v) in outputs {
260            ns.insert(Arc::from(k.as_str()), v.clone());
261        }
262    }
263
264    /// All variables in a namespace.
265    pub fn namespace(&self, namespace: &str) -> Option<&IndexMap<Arc<str>, Value>> {
266        self.namespaces.get(namespace).map(AsRef::as_ref)
267    }
268
269    pub fn contains(&self, selector: &Selector) -> bool {
270        self.get(selector).is_some()
271    }
272
273    /// Iterate `(namespace, name, value)`.
274    pub fn iter(&self) -> impl Iterator<Item = (&str, &str, &Value)> {
275        self.namespaces.iter().flat_map(|(ns, vars)| vars.iter().map(move |(k, v)| (ns.as_ref(), k.as_ref(), v)))
276    }
277
278    /// Serializable form for snapshots. The [`ENV`] namespace is excluded: the host
279    /// must supply environment variables again on resume. Secrets in other
280    /// namespaces are stored as `{"$secret": "redacted"}` markers and restored as
281    /// redacted secrets (see [`Value::redacted_secret`]).
282    pub fn to_snapshot(&self) -> PoolSnapshot {
283        let mut out: IndexMap<String, IndexMap<String, Value>> = IndexMap::new();
284        let mut entries: Vec<(&Arc<str>, &Namespace)> = self.namespaces.iter().collect();
285        entries.sort_by(|a, b| a.0.cmp(b.0));
286        for (ns, vars) in entries {
287            if ns.as_ref() == ENV {
288                continue;
289            }
290            out.insert(ns.to_string(), vars.iter().map(|(k, v)| (k.to_string(), v.to_snapshot_value())).collect());
291        }
292        PoolSnapshot(out)
293    }
294
295    /// Restore from a snapshot (env variables must be re-applied by the caller).
296    pub fn from_snapshot(snapshot: PoolSnapshot) -> Self {
297        let mut pool = Self::new();
298        for (ns, vars) in snapshot.0 {
299            for (k, v) in vars {
300                pool.insert(&ns, &k, v.from_snapshot_value());
301            }
302        }
303        pool
304    }
305
306    /// Insert a typed declared variable, validating it against its declared type.
307    pub fn insert_typed(
308        &mut self,
309        namespace: &str,
310        name: &str,
311        ty: ValueType,
312        value: Value,
313    ) -> Result<(), crate::value::TypeMismatch> {
314        let v = ty.coerce(value)?;
315        self.insert(namespace, name, v);
316        Ok(())
317    }
318}
319
320/// Persistable variable pool contents (`namespace -> name -> value`).
321#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
322#[serde(transparent)]
323pub struct PoolSnapshot(pub IndexMap<String, IndexMap<String, Value>>);
324
325/// Error writing a nested path.
326#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
327#[error("cannot write `{selector}`: array index {index} is out of range")]
328pub struct PathError {
329    pub selector: String,
330    pub index: usize,
331}
332
333/// Returns the out-of-range index on failure.
334fn write_path(current: Value, path: &[Arc<str>], value: Value) -> Result<Value, usize> {
335    let Some((head, rest)) = path.split_first() else {
336        return Ok(value);
337    };
338    match current {
339        Value::Array(items) if head.parse::<usize>().is_ok() => {
340            let idx = head.parse::<usize>().unwrap_or(0);
341            let mut items = Arc::unwrap_or_clone(items);
342            let slot = items.get_mut(idx).ok_or(idx)?;
343            let old = std::mem::take(slot);
344            *slot = write_path(old, rest, value)?;
345            Ok(Value::Array(Arc::new(items)))
346        }
347        other => {
348            let mut map = match other {
349                Value::Object(m) => Arc::unwrap_or_clone(m),
350                _ => IndexMap::new(),
351            };
352            // Take the old value in place so the key keeps its position.
353            let old = map.get_mut(head.as_ref()).map(std::mem::take).unwrap_or(Value::Null);
354            map.insert(head.to_string(), write_path(old, rest, value)?);
355            Ok(Value::Object(Arc::new(map)))
356        }
357    }
358}
359
360#[cfg(test)]
361mod tests {
362    use super::*;
363
364    fn sel(s: &str) -> Selector {
365        Selector::parse(s).unwrap_or_else(|_| Selector::of("bad", "bad"))
366    }
367
368    #[test]
369    fn selector_parsing() {
370        assert!(Selector::parse("a").is_err());
371        assert!(Selector::parse("a..b").is_err());
372        let s = sel("n.v.x.y");
373        assert_eq!(s.namespace(), "n");
374        assert_eq!(s.name(), "v");
375        assert_eq!(s.path().len(), 2);
376        let from_list: Result<Selector, _> = serde_json::from_str("[\"n\",\"v\"]");
377        let from_str: Result<Selector, _> = serde_json::from_str("\"n.v\"");
378        assert_eq!(from_list.ok(), from_str.ok());
379    }
380
381    #[test]
382    fn clone_is_copy_on_write() {
383        let mut a = VariablePool::new();
384        a.insert("n", "x", Value::Int(1));
385        let mut b = a.clone();
386        b.insert("n", "x", Value::Int(2));
387        assert_eq!(a.get(&sel("n.x")), Some(Value::Int(1)));
388        assert_eq!(b.get(&sel("n.x")), Some(Value::Int(2)));
389    }
390
391    #[test]
392    fn nested_get_and_set() {
393        let mut p = VariablePool::new();
394        p.set_path(&sel("n.obj.a.b"), Value::from("deep")).unwrap();
395        p.insert("n", "list", Value::from_json(serde_json::json!([1, 2])));
396        p.set_path(&sel("n.list.1"), Value::Int(9)).unwrap();
397        assert_eq!(p.get(&sel("n.list")), Some(Value::from_json(serde_json::json!([1, 9]))));
398        assert!(p.set_path(&sel("n.list.5"), Value::Int(9)).is_err());
399        assert_eq!(p.get(&sel("n.obj.a.b")), Some(Value::from("deep")));
400        assert_eq!(p.get(&sel("n.obj.missing")), None);
401    }
402
403    #[test]
404    fn snapshot_excludes_env() {
405        let mut p = VariablePool::new();
406        p.insert(ENV, "KEY", Value::Secret(Arc::from("s3cret")));
407        p.insert("n", "x", Value::Int(1));
408        let snap = p.to_snapshot();
409        let json = serde_json::to_string(&snap).unwrap_or_default();
410        assert!(!json.contains("s3cret"));
411        assert!(!json.contains("env"));
412        let restored = VariablePool::from_snapshot(snap);
413        assert_eq!(restored.get(&sel("n.x")), Some(Value::Int(1)));
414    }
415}