graphrt-core 0.3.0

Executor-agnostic graph runtime for agentic AI workflows: graph model, variable pool, scheduler, events, snapshots and built-in control nodes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
//! Selectors and the variable pool.
//!
//! A [`Selector`] addresses a value as `namespace.name[.path...]`, where the
//! namespace is a node id or one of the reserved namespaces ([`SYS`], [`ENV`],
//! [`CONVERSATION`]). The [`VariablePool`] stores one [`Variables`] map per
//! namespace (shared on clone), and the namespace table itself is shared too:
//! cloning a pool (for a node context, an iteration item or a loop round) is
//! O(1), and writes copy only the touched namespace (plus the table, when it is
//! shared). A node's outputs become its namespace without being copied.

use std::collections::HashMap;
use std::fmt;
use std::hash::{BuildHasher, BuildHasherDefault, Hasher};
use std::sync::{Arc, OnceLock};

use indexmap::IndexMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::value::{Value, ValueType};
use crate::variables::Variables;

/// System variables (`sys.query`, `sys.files`, `sys.run_id`, ...). Written by the host only.
pub const SYS: &str = "sys";
/// Environment variables / secrets. Supplied by the host, never persisted in snapshots.
pub const ENV: &str = "env";
/// Conversation-scoped variables. Persisted by the host between runs.
pub const CONVERSATION: &str = "conversation";

/// Address of a value: `[namespace, name, path...]`.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Selector {
    parts: Arc<[Arc<str>]>,
}

/// Error for malformed selectors.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("invalid selector `{0}`: needs at least a namespace and a name")]
pub struct InvalidSelector(pub String);

impl Selector {
    /// Build from parts. Requires at least two non-empty parts.
    pub fn new<I, S>(parts: I) -> Result<Self, InvalidSelector>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let parts: Vec<Arc<str>> = parts.into_iter().map(|p| Arc::from(p.as_ref())).collect();
        if parts.len() < 2 || parts.iter().any(|p| p.is_empty()) {
            return Err(InvalidSelector(parts.join(".")));
        }
        Ok(Self { parts: parts.into() })
    }

    /// Parse a dotted selector such as `llm.text` or `start.user.name`.
    pub fn parse(dotted: &str) -> Result<Self, InvalidSelector> {
        Self::new(dotted.split('.'))
    }

    /// Two-part selector `namespace.name`.
    pub fn of(namespace: &str, name: &str) -> Self {
        Self { parts: vec![Arc::from(namespace), Arc::from(name)].into() }
    }

    pub fn namespace(&self) -> &str {
        self.parts.first().map(AsRef::as_ref).unwrap_or_default()
    }

    pub fn name(&self) -> &str {
        self.parts.get(1).map(AsRef::as_ref).unwrap_or_default()
    }

    /// Path below the variable (`a.b.c` -> `[c]`).
    pub fn path(&self) -> &[Arc<str>] {
        self.parts.get(2..).unwrap_or_default()
    }

    pub fn parts(&self) -> &[Arc<str>] {
        &self.parts
    }

    /// The `namespace.name` prefix of this selector.
    pub fn root(&self) -> Selector {
        Selector::of(self.namespace(), self.name())
    }

    /// Append path parts.
    pub fn child(&self, part: &str) -> Selector {
        let mut parts: Vec<Arc<str>> = self.parts.to_vec();
        parts.push(Arc::from(part));
        Selector { parts: parts.into() }
    }
}

impl fmt::Display for Selector {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.parts.join("."))
    }
}

impl fmt::Debug for Selector {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Selector({self})")
    }
}

impl Serialize for Selector {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.parts.iter().map(AsRef::as_ref).collect::<Vec<&str>>().serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for Selector {
    /// Accepts `["node", "var"]` or `"node.var"`.
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Repr {
            List(Vec<String>),
            Dotted(String),
        }
        let sel = match Repr::deserialize(deserializer)? {
            Repr::List(parts) => Selector::new(parts),
            Repr::Dotted(s) => Selector::parse(&s),
        };
        sel.map_err(serde::de::Error::custom)
    }
}

type Namespace = Variables;
type ShardMap = HashMap<Arc<str>, Namespace, BuildHasherDefault<NamespaceHasher>>;

/// Hasher for namespace names in the shard maps.
///
/// Every node commit looks its namespace up, and SipHash (the std default) was
/// a visible share of the engine's per-node cost. Names are short ids from the
/// workflow document or the host, so a word-at-a-time multiplicative hash
/// (FxHash-style) suffices; it is keyed per process so collisions cannot be
/// precomputed.
#[derive(Clone, Copy)]
struct NamespaceHasher(u64);

/// Per-process key of [`NamespaceHasher`].
fn namespace_hash_seed() -> u64 {
    static SEED: OnceLock<u64> = OnceLock::new();
    *SEED.get_or_init(|| std::collections::hash_map::RandomState::new().build_hasher().finish())
}

impl Default for NamespaceHasher {
    fn default() -> Self {
        Self(namespace_hash_seed())
    }
}

impl NamespaceHasher {
    fn add(&mut self, word: u64) {
        self.0 = (self.0.rotate_left(5) ^ word).wrapping_mul(0x517c_c1b7_2722_0a95);
    }
}

impl Hasher for NamespaceHasher {
    fn finish(&self) -> u64 {
        // The multiply leaves the low bits (the table's bucket index) weakest.
        self.0.rotate_left(26)
    }

    fn write(&mut self, bytes: &[u8]) {
        let mut chunks = bytes.chunks_exact(8);
        for chunk in &mut chunks {
            let mut word = [0u8; 8];
            word.copy_from_slice(chunk);
            self.add(u64::from_le_bytes(word));
        }
        let rest = chunks.remainder();
        if !rest.is_empty() {
            let mut word = [0u8; 8];
            if let Some(head) = word.get_mut(..rest.len()) {
                head.copy_from_slice(rest);
            }
            self.add(u64::from_le_bytes(word));
        }
    }

    fn write_u8(&mut self, byte: u8) {
        self.add(u64::from(byte));
    }
}
/// `None` until a namespace hashing to the shard is written.
type Shard = Option<Arc<ShardMap>>;

/// Number of shards in the namespace table. Every node owns a namespace, so a
/// large graph has many; sharding keeps a copy-on-write update proportional to
/// one shard instead of the whole table while snapshots are shared with
/// running nodes.
const SHARDS: usize = 32;

/// Namespace table split into [`SHARDS`] independently shared maps. Cloning is
/// O(1); an update copies at most the shard array (`SHARDS` pointers) and one shard.
///
/// Shards and the shard array are allocated on first write: an empty table
/// costs no allocation, where eagerly creating every shard cost 33 per pool
/// and a pool is created for every execution frame.
#[derive(Clone, Default)]
struct Table {
    shards: Option<Arc<[Shard; SHARDS]>>,
    /// Initial capacity of a shard map when it is created.
    shard_capacity: usize,
}

/// Shard index of a namespace (FNV-1a: stable and fast for short ids).
fn shard_of(namespace: &str) -> usize {
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    for byte in namespace.bytes() {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(0x0100_0000_01b3);
    }
    // The remainder is below SHARDS, so the conversion cannot fail.
    usize::try_from(hash % SHARDS as u64).unwrap_or(0)
}

impl Table {
    fn shard(&self, namespace: &str) -> Option<&ShardMap> {
        self.shards.as_ref()?.get(shard_of(namespace))?.as_deref()
    }

    /// Mutable shard holding `namespace`, allocating or copying shared structure as needed.
    #[allow(clippy::indexing_slicing)] // shard_of() < SHARDS by construction
    fn shard_mut(&mut self, namespace: &str) -> &mut ShardMap {
        let capacity = self.shard_capacity;
        let shards = Arc::make_mut(self.shards.get_or_insert_with(Default::default));
        let shard = shards[shard_of(namespace)]
            .get_or_insert_with(|| Arc::new(HashMap::with_capacity_and_hasher(capacity, Default::default())));
        Arc::make_mut(shard)
    }

    fn get(&self, namespace: &str) -> Option<&Namespace> {
        self.shard(namespace)?.get(namespace)
    }

    fn entry(&mut self, namespace: &str) -> &mut Namespace {
        let shard = self.shard_mut(namespace);
        // Reuse the existing key (a reference-count bump) instead of allocating
        // a new `Arc<str>` on every write to a namespace that already exists.
        let key = shard.get_key_value(namespace).map_or_else(|| Arc::from(namespace), |(key, _)| Arc::clone(key));
        shard.entry(key).or_default()
    }

    /// Like [`Table::entry`], but a new namespace takes `namespace` as its key
    /// (a reference-count bump) instead of allocating a copy.
    fn entry_shared(&mut self, namespace: &Arc<str>) -> &mut Namespace {
        let shard = self.shard_mut(namespace);
        let key =
            shard.get_key_value(namespace.as_ref()).map_or_else(|| Arc::clone(namespace), |(key, _)| Arc::clone(key));
        shard.entry(key).or_default()
    }

    fn remove(&mut self, namespace: &str) {
        if self.get(namespace).is_some() {
            self.shard_mut(namespace).remove(namespace);
        }
    }

    fn iter(&self) -> impl Iterator<Item = (&Arc<str>, &Namespace)> {
        self.shards.iter().flat_map(|shards| shards.iter().flatten()).flat_map(|shard| shard.iter())
    }
}

/// Store a node's outputs in its namespace. An empty namespace (the usual
/// case: a node's first commit) takes the outputs map itself, a reference-count
/// bump; otherwise the outputs are merged in.
fn store_outputs(namespace: &mut Namespace, outputs: &Variables) {
    if namespace.is_empty() {
        namespace.clone_from(outputs);
        return;
    }
    namespace.reserve(outputs.len());
    for (name, value) in outputs.named_entries() {
        namespace.insert(name.clone(), value.clone());
    }
}

/// Variable storage for one execution frame.
#[derive(Clone, Default)]
pub struct VariablePool {
    namespaces: Table,
}

impl fmt::Debug for VariablePool {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut map = f.debug_map();
        for (ns, vars) in self.namespaces.iter() {
            map.entry(ns, vars);
        }
        map.finish()
    }
}

impl VariablePool {
    pub fn new() -> Self {
        Self::default()
    }

    /// An empty pool sized for about `namespaces` namespaces (the engine passes
    /// the graph's node count), so filling it does not keep regrowing its maps.
    pub(crate) fn with_namespace_capacity(namespaces: usize) -> Self {
        // Shards fill unevenly; a quarter of headroom avoids most regrowth.
        let shard_capacity = (namespaces + namespaces / 4) / SHARDS;
        Self { namespaces: Table { shards: None, shard_capacity } }
    }

    /// Resolve a selector, descending into nested values. Missing values return `None`.
    pub fn get(&self, selector: &Selector) -> Option<Value> {
        let root = self.namespaces.get(selector.namespace())?.get(selector.name())?;
        if selector.path().is_empty() { Some(root.clone()) } else { root.get_path(selector.path()) }
    }

    /// Resolve a selector, returning [`Value::Null`] when absent.
    pub fn get_or_null(&self, selector: &Selector) -> Value {
        self.get(selector).unwrap_or(Value::Null)
    }

    /// Set `namespace.name`. Any path in the selector is ignored; use [`VariablePool::set_path`]
    /// for nested writes.
    pub fn set(&mut self, selector: &Selector, value: Value) {
        self.insert(selector.namespace(), selector.name(), value);
    }

    /// Set a variable by namespace and name.
    pub fn insert(&mut self, namespace: &str, name: &str, value: Value) {
        self.namespaces.entry(namespace).insert_str(name, value);
    }

    /// Write into a nested path, creating intermediate objects as needed.
    /// Array elements are addressed by index; writing past the end of an array
    /// is an error (nothing is written).
    pub fn set_path(&mut self, selector: &Selector, value: Value) -> Result<(), PathError> {
        if selector.path().is_empty() {
            self.set(selector, value);
            return Ok(());
        }
        let current = self.get(&selector.root()).unwrap_or(Value::Null);
        let updated = write_path(current, selector.path(), value)
            .map_err(|index| PathError { selector: selector.to_string(), index })?;
        self.set(selector, updated);
        Ok(())
    }

    /// Remove one variable.
    pub fn remove(&mut self, selector: &Selector) -> Option<Value> {
        if !self.namespaces.get(selector.namespace())?.contains_key(selector.name()) {
            return None;
        }
        self.namespaces.entry(selector.namespace()).remove(selector.name())
    }

    /// Drop a whole namespace (e.g. a node's outputs before a loop round re-runs it).
    pub fn remove_namespace(&mut self, namespace: &str) {
        self.namespaces.remove(namespace);
    }

    /// Bulk-insert a node's outputs. Into an empty namespace this shares
    /// `outputs` instead of copying it.
    pub fn set_outputs(&mut self, namespace: &str, outputs: &Variables) {
        store_outputs(self.namespaces.entry(namespace), outputs);
    }

    /// [`VariablePool::set_outputs`] for a namespace the caller already holds as
    /// an `Arc<str>` (the engine's node ids), which avoids copying the name.
    pub(crate) fn set_outputs_shared(&mut self, namespace: &Arc<str>, outputs: &Variables) {
        store_outputs(self.namespaces.entry_shared(namespace), outputs);
    }

    /// All variables in a namespace.
    pub fn namespace(&self, namespace: &str) -> Option<&Variables> {
        self.namespaces.get(namespace)
    }

    pub fn contains(&self, selector: &Selector) -> bool {
        self.get(selector).is_some()
    }

    /// Iterate `(namespace, name, value)`.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &str, &Value)> {
        self.namespaces.iter().flat_map(|(ns, vars)| vars.iter().map(move |(k, v)| (ns.as_ref(), k, v)))
    }

    /// Serializable form for snapshots. The [`ENV`] namespace is excluded: the host
    /// must supply environment variables again on resume. Secrets in other
    /// namespaces are stored as `{"$secret": "redacted"}` markers and restored as
    /// redacted secrets (see [`Value::redacted_secret`]).
    pub fn to_snapshot(&self) -> PoolSnapshot {
        let mut out: IndexMap<String, IndexMap<String, Value>> = IndexMap::new();
        let mut entries: Vec<(&Arc<str>, &Namespace)> = self.namespaces.iter().collect();
        entries.sort_by(|a, b| a.0.cmp(b.0));
        for (ns, vars) in entries {
            if ns.as_ref() == ENV {
                continue;
            }
            out.insert(ns.to_string(), vars.iter().map(|(k, v)| (k.to_string(), v.to_snapshot_value())).collect());
        }
        PoolSnapshot(out)
    }

    /// Restore from a snapshot (env variables must be re-applied by the caller).
    pub fn from_snapshot(snapshot: PoolSnapshot) -> Self {
        let mut pool = Self::new();
        for (ns, vars) in snapshot.0 {
            let restored: Variables = vars.into_iter().map(|(k, v)| (k, v.from_snapshot_value())).collect();
            store_outputs(pool.namespaces.entry(&ns), &restored);
        }
        pool
    }

    /// Insert a typed declared variable, validating it against its declared type.
    pub fn insert_typed(
        &mut self,
        namespace: &str,
        name: &str,
        ty: ValueType,
        value: Value,
    ) -> Result<(), crate::value::TypeMismatch> {
        let v = ty.coerce(value)?;
        self.insert(namespace, name, v);
        Ok(())
    }
}

/// Persistable variable pool contents (`namespace -> name -> value`).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct PoolSnapshot(pub IndexMap<String, IndexMap<String, Value>>);

/// Error writing a nested path.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("cannot write `{selector}`: array index {index} is out of range")]
pub struct PathError {
    pub selector: String,
    pub index: usize,
}

/// Returns the out-of-range index on failure.
fn write_path(current: Value, path: &[Arc<str>], value: Value) -> Result<Value, usize> {
    let Some((head, rest)) = path.split_first() else {
        return Ok(value);
    };
    match current {
        Value::Array(items) if head.parse::<usize>().is_ok() => {
            let idx = head.parse::<usize>().unwrap_or(0);
            let mut items = Arc::unwrap_or_clone(items);
            let slot = items.get_mut(idx).ok_or(idx)?;
            let old = std::mem::take(slot);
            *slot = write_path(old, rest, value)?;
            Ok(Value::Array(Arc::new(items)))
        }
        other => {
            let mut map = match other {
                Value::Object(m) => Arc::unwrap_or_clone(m),
                _ => IndexMap::new(),
            };
            // Take the old value in place so the key keeps its position.
            let old = map.get_mut(head.as_ref()).map(std::mem::take).unwrap_or(Value::Null);
            map.insert(head.to_string(), write_path(old, rest, value)?);
            Ok(Value::Object(Arc::new(map)))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sel(s: &str) -> Selector {
        Selector::parse(s).unwrap_or_else(|_| Selector::of("bad", "bad"))
    }

    #[test]
    fn selector_parsing() {
        assert!(Selector::parse("a").is_err());
        assert!(Selector::parse("a..b").is_err());
        let s = sel("n.v.x.y");
        assert_eq!(s.namespace(), "n");
        assert_eq!(s.name(), "v");
        assert_eq!(s.path().len(), 2);
        let from_list: Result<Selector, _> = serde_json::from_str("[\"n\",\"v\"]");
        let from_str: Result<Selector, _> = serde_json::from_str("\"n.v\"");
        assert_eq!(from_list.ok(), from_str.ok());
    }

    #[test]
    fn namespace_hasher_separates_similar_ids() {
        let hash = |s: &str| BuildHasherDefault::<NamespaceHasher>::default().hash_one(s);
        assert_eq!(hash("node_12"), hash("node_12"));
        let ids: std::collections::HashSet<u64> = (0..10_000).map(|i| hash(&format!("n{i}"))).collect();
        assert_eq!(ids.len(), 10_000);
        // Ids differing only past the first 8-byte word, or by a trailing byte.
        assert_ne!(hash("longer_node_id_a"), hash("longer_node_id_b"));
        assert_ne!(hash("abcdefgh"), hash("abcdefgh\0"));
    }

    #[test]
    fn outputs_become_the_namespace_without_a_copy() {
        let outputs = Variables::from([("text", Value::from("hi"))]);
        let mut p = VariablePool::new();
        p.set_outputs("llm", &outputs);
        assert!(p.namespace("llm").is_some_and(|ns| ns.ptr_eq(&outputs)));
        // A namespace that already holds variables merges instead.
        p.insert("loop", "i", Value::Int(1));
        p.set_outputs("loop", &outputs);
        let merged = p.namespace("loop").map(|ns| ns.keys().collect::<Vec<_>>());
        assert_eq!(merged, Some(vec!["i", "text"]));
        assert_eq!(outputs.len(), 1, "the caller's map is not modified");
    }

    #[test]
    fn presized_pool_behaves_like_a_new_one() {
        let mut p = VariablePool::with_namespace_capacity(1_000);
        p.insert("n", "x", Value::Int(1));
        let mut q = p.clone();
        q.insert("n", "x", Value::Int(2));
        assert_eq!(p.get(&sel("n.x")), Some(Value::Int(1)));
        assert_eq!(q.get(&sel("n.x")), Some(Value::Int(2)));
        assert!(VariablePool::with_namespace_capacity(0).get(&sel("n.x")).is_none());
    }

    #[test]
    fn many_namespaces_stay_addressable() {
        let mut p = VariablePool::new();
        for i in 0..2_000 {
            p.insert(&format!("node{i}"), "v", Value::Int(i));
        }
        for i in 0..2_000 {
            assert_eq!(p.get(&sel(&format!("node{i}.v"))), Some(Value::Int(i)));
        }
    }

    #[test]
    fn clone_is_copy_on_write() {
        let mut a = VariablePool::new();
        a.insert("n", "x", Value::Int(1));
        let mut b = a.clone();
        b.insert("n", "x", Value::Int(2));
        assert_eq!(a.get(&sel("n.x")), Some(Value::Int(1)));
        assert_eq!(b.get(&sel("n.x")), Some(Value::Int(2)));
    }

    #[test]
    fn nested_get_and_set() {
        let mut p = VariablePool::new();
        p.set_path(&sel("n.obj.a.b"), Value::from("deep")).unwrap();
        p.insert("n", "list", Value::from_json(serde_json::json!([1, 2])));
        p.set_path(&sel("n.list.1"), Value::Int(9)).unwrap();
        assert_eq!(p.get(&sel("n.list")), Some(Value::from_json(serde_json::json!([1, 9]))));
        assert!(p.set_path(&sel("n.list.5"), Value::Int(9)).is_err());
        assert_eq!(p.get(&sel("n.obj.a.b")), Some(Value::from("deep")));
        assert_eq!(p.get(&sel("n.obj.missing")), None);
    }

    #[test]
    fn snapshot_excludes_env() {
        let mut p = VariablePool::new();
        p.insert(ENV, "KEY", Value::Secret(Arc::from("s3cret")));
        p.insert("n", "x", Value::Int(1));
        let snap = p.to_snapshot();
        let json = serde_json::to_string(&snap).unwrap_or_default();
        assert!(!json.contains("s3cret"));
        assert!(!json.contains("env"));
        let restored = VariablePool::from_snapshot(snap);
        assert_eq!(restored.get(&sel("n.x")), Some(Value::Int(1)));
    }
}