Skip to main content

adk_code/embedded_python/
convert.rs

1//! Marshalling between the framework's JSON values and Monty's [`MontyObject`].
2//!
3//! The executor seam speaks `serde_json::Value`: `ExecutionRequest.input` binds
4//! a JSON value into the script, host functions receive JSON arguments and
5//! return JSON results, and a finished script reports its final expression as
6//! JSON (`ExecutionResult.output`). Monty speaks [`MontyObject`]. These two
7//! functions bridge the gap.
8//!
9//! Both directions are **depth-capped**. A script can build arbitrarily deep
10//! nesting iteratively (`for _ in range(50_000): x = [x]`) with trivial memory
11//! and no `RecursionError`, and an unbounded recursive conversion of that
12//! value would overflow the host stack — aborting the whole process for an
13//! in-process executor. Beyond [`MAX_CONVERSION_DEPTH`], nesting degrades to
14//! the [`DEPTH_PLACEHOLDER`] string.
15
16use monty_types::{DictPairs, MontyObject};
17use serde_json::{Map, Number, Value};
18
19/// Maximum nesting depth converted in either direction. Deeper levels degrade
20/// to [`DEPTH_PLACEHOLDER`]. Tool I/O legitimately nested this deep does not
21/// exist in practice; serde_json's own parser defaults to a 128-level limit.
22const MAX_CONVERSION_DEPTH: usize = 64;
23
24/// Substituted for any value nested beyond [`MAX_CONVERSION_DEPTH`].
25const DEPTH_PLACEHOLDER: &str = "<truncated: nesting depth limit reached>";
26
27/// Convert a host JSON value into a Monty value, to be injected into a script
28/// (an `input` binding, a host function result, a resolved name, ...).
29///
30/// The mapping is the obvious one. A JSON integer that fits in `i64` becomes an
31/// `int`; anything larger (or fractional) becomes a `float`. Objects become
32/// `dict`s keyed by their string keys, preserving insertion order. Nesting
33/// beyond the conversion depth limit degrades to a placeholder string.
34///
35/// # Example
36///
37/// ```rust
38/// use adk_code::embedded_python::{json_to_monty, monty_types::MontyObject};
39/// use serde_json::json;
40///
41/// assert_eq!(json_to_monty(json!(42)), MontyObject::Int(42));
42/// ```
43pub fn json_to_monty(value: Value) -> MontyObject {
44    to_monty(value, MAX_CONVERSION_DEPTH)
45}
46
47fn to_monty(value: Value, budget: usize) -> MontyObject {
48    if budget == 0 {
49        return MontyObject::String(DEPTH_PLACEHOLDER.to_string());
50    }
51    match value {
52        Value::Null => MontyObject::None,
53        Value::Bool(b) => MontyObject::Bool(b),
54        Value::Number(n) => {
55            if let Some(i) = n.as_i64() {
56                MontyObject::Int(i)
57            } else {
58                match n.as_f64() {
59                    // u64 values above i64::MAX and all non-integral numbers
60                    // fall back to float — good enough for tool I/O, which is
61                    // rarely built around > 2^63 integers.
62                    Some(f) => MontyObject::Float(f),
63                    // Unreachable without serde_json's `arbitrary_precision`
64                    // feature; degrade to the decimal string rather than a
65                    // silently wrong number.
66                    None => MontyObject::String(n.to_string()),
67                }
68            }
69        }
70        Value::String(s) => MontyObject::String(s),
71        Value::Array(items) => {
72            MontyObject::List(items.into_iter().map(|v| to_monty(v, budget - 1)).collect())
73        }
74        Value::Object(map) => {
75            let pairs: Vec<(MontyObject, MontyObject)> = map
76                .into_iter()
77                .map(|(k, v)| (MontyObject::String(k), to_monty(v, budget - 1)))
78                .collect();
79            MontyObject::Dict(DictPairs::from(pairs))
80        }
81    }
82}
83
84/// Convert a Monty value produced by a script into host JSON.
85///
86/// This is the "natural" projection: JSON-native Python values map to their
87/// bare JSON form (`42`, `"hi"`, `[...]`, `{"a": 1}`). It is deliberately *not*
88/// `serde_json::to_value(obj)` — [`MontyObject`]'s derived `Serialize` is an
89/// externally tagged snapshot format (`{"Int": 42}`) meant for binary
90/// transport, not human-facing JSON. The rare non-JSON-native value (a
91/// `tuple`, `bytes`, a `date`, ...) degrades to its Python `repr` string.
92/// Nesting beyond the conversion depth limit degrades to a placeholder string.
93///
94/// # Example
95///
96/// ```rust
97/// use adk_code::embedded_python::{monty_to_json, monty_types::MontyObject};
98/// use serde_json::json;
99///
100/// let list = MontyObject::List(vec![MontyObject::Int(1), MontyObject::Bool(true)]);
101/// assert_eq!(monty_to_json(&list), json!([1, true]));
102/// ```
103pub fn monty_to_json(obj: &MontyObject) -> Value {
104    to_json(obj, MAX_CONVERSION_DEPTH)
105}
106
107fn to_json(obj: &MontyObject, budget: usize) -> Value {
108    if budget == 0 {
109        return Value::String(DEPTH_PLACEHOLDER.to_string());
110    }
111    match obj {
112        MontyObject::None => Value::Null,
113        MontyObject::Bool(b) => Value::Bool(*b),
114        MontyObject::Int(i) => Value::Number(Number::from(*i)),
115        // NaN/Infinity have no JSON form; degrade to null rather than fail.
116        MontyObject::Float(f) => Number::from_f64(*f).map_or(Value::Null, Value::Number),
117        MontyObject::String(s) => Value::String(s.clone()),
118        MontyObject::Path(p) => Value::String(p.clone()),
119        // Every Python sequence projects to a JSON array.
120        MontyObject::List(items)
121        | MontyObject::Tuple(items)
122        | MontyObject::Set(items)
123        | MontyObject::FrozenSet(items) => {
124            Value::Array(items.iter().map(|item| to_json(item, budget - 1)).collect())
125        }
126        MontyObject::Dict(pairs) => dict_to_json(pairs, budget),
127        // Everything else (bytes, datetimes, exceptions, file handles, ...) has
128        // no JSON-native shape, so it degrades to its Python `repr` — guarded,
129        // because `py_repr` recurses through containers (e.g. a NamedTuple's
130        // values) with no depth limit of its own.
131        other => Value::String(guarded_repr(other, budget)),
132    }
133}
134
135/// Project a Monty `dict` to a JSON object, stringifying any non-string key
136/// via its Python `repr` (JSON object keys must be strings; script
137/// argument/result dicts are string-keyed in practice). Distinct Python keys
138/// whose string forms collide (`1` and `"1"`) merge silently — the last one
139/// wins, matching `json.dumps` round-trip behavior.
140fn dict_to_json(pairs: &DictPairs, budget: usize) -> Value {
141    let mut map = Map::new();
142    for (key, value) in pairs {
143        map.insert(key_string(key, budget), to_json(value, budget - 1));
144    }
145    Value::Object(map)
146}
147
148/// Stringify a Monty value used in a string position (dict key, kwargs key):
149/// strings pass through, anything else degrades to its guarded `repr`.
150pub(crate) fn monty_key_string(key: &MontyObject) -> String {
151    key_string(key, MAX_CONVERSION_DEPTH)
152}
153
154fn key_string(key: &MontyObject, budget: usize) -> String {
155    match key {
156        MontyObject::String(s) => s.clone(),
157        other => guarded_repr(other, budget),
158    }
159}
160
161/// `py_repr`, guarded by a depth probe: `py_repr` itself recurses through
162/// containers (a script can key a dict with an iteratively built deep tuple),
163/// so it is only called on values shallower than the remaining budget.
164fn guarded_repr(obj: &MontyObject, budget: usize) -> String {
165    if exceeds_depth(obj, budget) { DEPTH_PLACEHOLDER.to_string() } else { obj.py_repr() }
166}
167
168/// Whether `obj` nests deeper than `budget` levels. The recursion is bounded
169/// by `budget` itself, so the probe cannot overflow.
170fn exceeds_depth(obj: &MontyObject, budget: usize) -> bool {
171    if budget == 0 {
172        return true;
173    }
174    match obj {
175        MontyObject::List(items)
176        | MontyObject::Tuple(items)
177        | MontyObject::Set(items)
178        | MontyObject::FrozenSet(items)
179        | MontyObject::NamedTuple { values: items, .. } => {
180            items.iter().any(|item| exceeds_depth(item, budget - 1))
181        }
182        MontyObject::Dict(pairs) => pairs
183            .into_iter()
184            .any(|(k, v)| exceeds_depth(k, budget - 1) || exceeds_depth(v, budget - 1)),
185        // Non-container variants (and any future ones py_repr renders flat).
186        _ => false,
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193    use serde_json::json;
194
195    #[test]
196    fn round_trips_json_native_values() {
197        let cases = [
198            json!(null),
199            json!(true),
200            json!(42),
201            json!(3.5),
202            json!("hello"),
203            json!([1, 2, 3]),
204            json!({"nested": {"n": 7}, "list": [1, "two"]}),
205        ];
206        for case in cases {
207            let monty = json_to_monty(case.clone());
208            assert_eq!(monty_to_json(&monty), case);
209        }
210    }
211
212    #[test]
213    fn large_u64_degrades_to_float() {
214        let big = json!(u64::MAX);
215        assert!(matches!(json_to_monty(big), MontyObject::Float(_)));
216    }
217
218    #[test]
219    fn non_json_native_value_degrades_to_repr() {
220        let tuple = MontyObject::Tuple(vec![MontyObject::Int(1), MontyObject::Int(2)]);
221        assert_eq!(monty_to_json(&tuple), json!([1, 2]));
222        let bytes = MontyObject::Bytes(vec![1, 2]);
223        assert!(monty_to_json(&bytes).is_string());
224    }
225
226    #[test]
227    fn nan_and_infinity_degrade_to_null() {
228        for f in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
229            assert_eq!(monty_to_json(&MontyObject::Float(f)), Value::Null);
230        }
231    }
232
233    #[test]
234    fn path_projects_to_string() {
235        let path = MontyObject::Path("/data/report.csv".to_string());
236        assert_eq!(monty_to_json(&path), json!("/data/report.csv"));
237    }
238
239    #[test]
240    fn colliding_dict_keys_last_one_wins() {
241        let pairs = DictPairs::from(vec![
242            (MontyObject::Int(1), MontyObject::String("int".to_string())),
243            (MontyObject::String("1".to_string()), MontyObject::String("str".to_string())),
244        ]);
245        assert_eq!(monty_to_json(&MontyObject::Dict(pairs)), json!({"1": "str"}));
246    }
247
248    #[test]
249    fn deep_monty_nesting_degrades_instead_of_overflowing() {
250        // Deep enough to prove the 64-level cap, shallow enough that the
251        // value's own recursive drop glue stays within the test stack.
252        let mut obj = MontyObject::Int(1);
253        for _ in 0..2_000 {
254            obj = MontyObject::List(vec![obj]);
255        }
256        let json = monty_to_json(&obj);
257        assert!(json.is_array());
258        assert!(json.to_string().contains(DEPTH_PLACEHOLDER));
259    }
260
261    #[test]
262    fn deep_json_nesting_degrades_instead_of_overflowing() {
263        // Built directly — `json!([value])` would re-serialize the whole tree
264        // on every iteration.
265        let mut value = json!(1);
266        for _ in 0..2_000 {
267            value = Value::Array(vec![value]);
268        }
269        let monty = json_to_monty(value);
270        assert!(matches!(monty, MontyObject::List(_)));
271    }
272
273    #[test]
274    fn deep_tuple_dict_key_degrades_instead_of_overflowing() {
275        let mut key = MontyObject::Tuple(vec![MontyObject::Int(1)]);
276        for _ in 0..2_000 {
277            key = MontyObject::Tuple(vec![key]);
278        }
279        let pairs = DictPairs::from(vec![(key, MontyObject::Int(1))]);
280        let json = monty_to_json(&MontyObject::Dict(pairs));
281        assert_eq!(json, json!({DEPTH_PLACEHOLDER: 1}));
282    }
283
284    #[test]
285    fn shallow_values_are_unaffected_by_the_depth_cap() {
286        let value = json!({"a": [{"b": [{"c": 1}]}]});
287        assert_eq!(monty_to_json(&json_to_monty(value.clone())), value);
288    }
289}