Skip to main content

dataflow_rs/engine/
executor.rs

1//! # Evaluation Primitives
2//!
3//! Free functions and types that support JSONLogic evaluation in the engine.
4//! Built-in function execution lives on each config type (`MapConfig::execute`,
5//! `ValidationConfig::execute`, …) — this module just provides the shared
6//! evaluation machinery they all build on.
7//!
8//! The bump arena is held in a thread-local cell on each Tokio worker. Per
9//! call, the arena is rewound via `Bump::reset` (constant-time, retains chunks)
10//! before the eval. Chunks accumulate to fit the workload's high-water mark
11//! and persist across calls — no per-task malloc/free churn. Profiling
12//! showed per-task `Bump::with_capacity` malloc was the dominant cost when
13//! arena sizing was tuned for realistic workloads; thread-local reuse
14//! amortizes that to zero in steady state.
15//!
16//! `ArenaContext` (below) extends this further for **mutating** tasks (map):
17//! the message context is `to_arena`'d once per task call into a depth‑2
18//! cache, and subsequent writes only re‑arena the dirtied subtree — typically
19//! `data.MT103` while the heavy `data.input` stays cached.
20
21use crate::engine::error::Result;
22use crate::engine::utils::{remove_nested_value_parts, strip_hash_prefix};
23use bumpalo::Bump;
24use datalogic_rs::{Engine, Logic};
25use datavalue::{DataValue, OwnedDataValue};
26use log::error;
27use std::cell::RefCell;
28use std::sync::Arc;
29
30/// Initial bump arena capacity per worker thread. Sized to cover a realistic
31/// ISO-20022-shaped payload's `to_arena` deep-clone in one shot, so the first
32/// few calls on each thread don't trigger `Bump::new_chunk`. After that the
33/// chunks persist across calls and the capacity is irrelevant.
34const ARENA_INITIAL_CAPACITY: usize = 128 * 1024;
35
36thread_local! {
37    /// Per-worker-thread bump arena. `Engine` and `Arc<Logic>` are `Send + Sync`
38    /// and shared across threads; `Bump` is `!Send` so it lives here for
39    /// zero-contention scratch space. Chunks accumulate over the thread's
40    /// lifetime and `reset()` rewinds the pointer without freeing chunks back
41    /// to the OS — steady-state allocator pressure is zero.
42    static EVAL_ARENA: RefCell<Bump> = RefCell::new(Bump::with_capacity(ARENA_INITIAL_CAPACITY));
43}
44
45/// Evaluate `compiled` against `context` using the worker thread's bump
46/// arena, returning the result as an owned `OwnedDataValue`. The arena is
47/// rewound before the call so peak memory is bounded by the single largest
48/// evaluation; chunks persist across calls so steady-state allocation is zero.
49///
50/// Use this for one-shot evals where the context isn't reused across
51/// multiple JSONLogic calls (e.g. a single condition check). For batches of
52/// read-only evals against the same context (validation, log) use
53/// [`with_arena`] and convert the context once via
54/// [`datavalue::OwnedDataValue::to_arena`].
55#[inline]
56pub(crate) fn eval_to_owned(
57    engine: &Engine,
58    compiled: &Logic,
59    context: &OwnedDataValue,
60) -> std::result::Result<OwnedDataValue, datalogic_rs::Error> {
61    with_eval_arena(|arena| {
62        let r = engine.evaluate(compiled, context, arena)?;
63        Ok(r.to_owned())
64    })
65}
66
67/// As [`eval_to_owned`] but projects the arena result directly to
68/// `serde_json::Value` — one walk out, with no `OwnedDataValue` intermediate
69/// and no `serde_json::from_value` rebuild.
70#[inline]
71pub(crate) fn eval_to_json(
72    engine: &Engine,
73    compiled: &Logic,
74    context: &OwnedDataValue,
75) -> std::result::Result<serde_json::Value, datalogic_rs::Error> {
76    with_eval_arena(|arena| Ok(engine.evaluate(compiled, context, arena)?.to_serde_value()))
77}
78
79/// As [`eval_to_owned`] but coerced to a *plain* string: a `DataValue::String`
80/// yields its contents, everything else its compact JSON form (`Display` on
81/// `DataValue` is compact JSON).
82///
83/// This deliberately disagrees with datalogic-rs's `String: FromDataValue` — and
84/// therefore with `Session::eval_str` — which keeps the JSON quoting, so a string
85/// result there comes back as `"\"abc\""`. The divergence is pinned by a test.
86#[inline]
87pub(crate) fn eval_to_plain_string(
88    engine: &Engine,
89    compiled: &Logic,
90    context: &OwnedDataValue,
91) -> std::result::Result<String, datalogic_rs::Error> {
92    with_eval_arena(|arena| {
93        Ok(match engine.evaluate(compiled, context, arena)? {
94            DataValue::String(s) => s.to_string(),
95            other => other.to_string(),
96        })
97    })
98}
99
100/// Run `f` against the worker thread's rewound arena, falling back to a fresh
101/// `Bump` if the thread-local is already borrowed.
102///
103/// The fallback exists for re-entrancy. The engine's own paths never nest:
104/// `next_async_boundary` keeps every non-sync-builtin task out of the
105/// `run_sync_stretch` arena block, and the only in-crate `TaskContext::new` call
106/// site sits at an `.await` outside every `with_arena` scope. But
107/// `TaskContext::new` is `pub` precisely so tests and benches can drive a handler
108/// directly, and one of those *can* be written inside a `with_arena` closure.
109/// Paying one allocation there is better than panicking out of
110/// `process_message`.
111///
112/// Note [`with_arena`] deliberately does **not** do this: a nested batch scope
113/// would be an engine bug, and the panic is the right signal for it.
114#[inline]
115fn with_eval_arena<R>(f: impl FnOnce(&Bump) -> R) -> R {
116    EVAL_ARENA.with(|cell| match cell.try_borrow_mut() {
117        Ok(mut arena) => {
118            arena.reset();
119            f(&arena)
120        }
121        Err(_) => {
122            let arena = Bump::new();
123            f(&arena)
124        }
125    })
126}
127
128/// Run `f` with the worker thread's bump arena rewound. The closure receives
129/// the `Bump` and can amortize work across multiple `engine.evaluate` calls
130/// by converting the input context to `DataValue` once and reusing it. Use
131/// this for batches of read-only evals against the same context (validation,
132/// log) — it skips the per-eval `to_arena` deep-clone that dominates
133/// realistic profile.
134#[inline]
135pub(crate) fn with_arena<R>(f: impl FnOnce(&Bump) -> R) -> R {
136    EVAL_ARENA.with(|cell| {
137        let mut arena = cell.borrow_mut();
138        arena.reset();
139        f(&arena)
140    })
141}
142
143/// Depth‑2 arena cache for a `Message.context` (always an
144/// `OwnedDataValue::Object`).
145///
146/// Built once at the top of a mutating task call, then mutated in place as
147/// the task writes back into `message.context`. Writes at path `a.b.X`
148/// invalidate only the `(a, b)` arena slot — `data.input` stays cached
149/// across the entire map task even while `data.MT103.*` is being written.
150///
151/// **Lifetime model.** All arena allocations come out of the borrowed `Bump`.
152/// `top_keys` / `top_values` / `depth2` are owned `Vec`s so we can mutate
153/// them freely; the `DataValue<'a>` slice handed to `engine.evaluate` is a
154/// fresh `arena.alloc_slice_copy` per call, so it stays valid for that eval
155/// regardless of subsequent mutations.
156pub(crate) struct ArenaContext<'a> {
157    arena: &'a Bump,
158    /// Top-level slot keys, arena-allocated `&'a str`.
159    top_keys: Vec<&'a str>,
160    /// Top-level slot values. When a slot's owned value is an `Object`, the
161    /// corresponding `top_values[i]` is `DataValue::Object(&'a [...])` whose
162    /// slice was minted from `depth2[i]` via `alloc_slice_copy`. When not an
163    /// Object, `depth2[i] = None` and `top_values[i]` is the full arena form.
164    top_values: Vec<DataValue<'a>>,
165    /// Depth‑2 cache, parallel to `top_keys`. `None` for non‑Object top slots.
166    depth2: Vec<Option<Depth2Cache<'a>>>,
167}
168
169struct Depth2Cache<'a> {
170    keys: Vec<&'a str>,
171    values: Vec<DataValue<'a>>,
172}
173
174impl<'a> ArenaContext<'a> {
175    /// Build from an `OwnedDataValue` context (which should be the canonical
176    /// `Object { data, metadata, temp_data }` shape). Deep-walks the owned
177    /// tree exactly once; subsequent reads / mutations are O(touched slot).
178    pub fn from_owned(ctx: &OwnedDataValue, arena: &'a Bump) -> Self {
179        let mut top_keys: Vec<&'a str> = Vec::with_capacity(4);
180        let mut top_values: Vec<DataValue<'a>> = Vec::with_capacity(4);
181        let mut depth2: Vec<Option<Depth2Cache<'a>>> = Vec::with_capacity(4);
182
183        if let OwnedDataValue::Object(pairs) = ctx {
184            for (k, v) in pairs {
185                top_keys.push(arena.alloc_str(k));
186                match v {
187                    OwnedDataValue::Object(children) => {
188                        let mut d2_keys: Vec<&'a str> = Vec::with_capacity(children.len());
189                        let mut d2_values: Vec<DataValue<'a>> = Vec::with_capacity(children.len());
190                        for (ck, cv) in children {
191                            d2_keys.push(arena.alloc_str(ck));
192                            d2_values.push(cv.to_arena(arena));
193                        }
194                        let slice = build_object_slice(arena, &d2_keys, &d2_values);
195                        top_values.push(DataValue::Object(slice));
196                        depth2.push(Some(Depth2Cache {
197                            keys: d2_keys,
198                            values: d2_values,
199                        }));
200                    }
201                    _ => {
202                        top_values.push(v.to_arena(arena));
203                        depth2.push(None);
204                    }
205                }
206            }
207        }
208
209        Self {
210            arena,
211            top_keys,
212            top_values,
213            depth2,
214        }
215    }
216
217    /// Build an arena `DataValue::Object` for the current state. The returned
218    /// slice is freshly allocated in the arena and stays valid for the caller
219    /// to pass into `engine.evaluate`; later mutations on `self` allocate a
220    /// new slice on the next call.
221    pub fn as_data_value(&self) -> DataValue<'a> {
222        let slice = build_object_slice(self.arena, &self.top_keys, &self.top_values);
223        DataValue::Object(slice)
224    }
225
226    /// Borrow the underlying arena — needed by callers that want to allocate
227    /// or evaluate into the same `Bump` (e.g. `engine.evaluate(...)`).
228    #[inline]
229    pub fn arena(&self) -> &'a Bump {
230        self.arena
231    }
232
233    /// Apply an owned write at `path` (pre-split into `parts`) to *both* the
234    /// underlying `OwnedDataValue` context (via the supplied closure that
235    /// performs the in-place mutation) and the arena cache, using the
236    /// already-arena-resident eval result `value_av` for the cache side.
237    ///
238    /// The cache update splices `value_av` into the depth-2 slot directly
239    /// (rebuilding only the spine of the written path — shallow pair copies,
240    /// no string data copied, no descent into unchanged siblings). The old
241    /// per-write behaviour — `to_arena` of the *entire* owned depth-2
242    /// subtree — made k mappings into the same subtree O(k²); it remains as
243    /// [`Self::refresh_after_write_parts`], the correctness backstop for any
244    /// shape the splice doesn't cover (array segments, missing depth-2 slot,
245    /// non-object hops, root writes).
246    ///
247    /// The owned-context write stays the source of truth; `value_av` must be
248    /// the arena form of the value the closure writes at `parts`.
249    pub fn apply_mutation_parts_write_through(
250        &mut self,
251        owned_ctx: &mut OwnedDataValue,
252        parts: &[Arc<str>],
253        value_av: DataValue<'a>,
254        apply: impl FnOnce(&mut OwnedDataValue),
255    ) {
256        apply(owned_ctx);
257        if !self.try_splice_write_parts(parts, value_av) {
258            self.refresh_after_write_parts(owned_ctx, parts);
259        }
260        // Differential check (unit-test builds only): after every write-through
261        // the cache must equal a from-scratch rebuild of the owned context.
262        // This gives every unit test that drives a map task free differential
263        // coverage of the splice against the owned source of truth.
264        #[cfg(test)]
265        self.assert_matches_owned(owned_ctx);
266    }
267
268    /// Removal counterpart of [`Self::apply_mutation_parts_write_through`]:
269    /// take the key at `parts` out of the owned context and bring the cache
270    /// along. Returns what was removed; `None` means nothing was there, and
271    /// neither side changed.
272    ///
273    /// No splice — a removal has no arena value to hand over, and the narrow
274    /// refresh already drops a vanished top slot or depth-2 child and
275    /// re-arenas the one depth-2 subtree a deeper removal dirtied.
276    pub fn apply_removal_parts(
277        &mut self,
278        owned_ctx: &mut OwnedDataValue,
279        parts: &[Arc<str>],
280    ) -> Option<OwnedDataValue> {
281        let removed = remove_nested_value_parts(owned_ctx, parts);
282        if removed.is_some() {
283            self.refresh_after_write_parts(owned_ctx, parts);
284        }
285        // Same differential guard as the write path.
286        #[cfg(test)]
287        self.assert_matches_owned(owned_ctx);
288        removed
289    }
290
291    /// Attempt the plain-case arena splice for a write of `value_av` at
292    /// `parts`. Covered shape: `parts[0]` resolves to a cached top slot with
293    /// a depth-2 cache; for writes deeper than depth 2, `parts[1]` names an
294    /// *existing* depth-2 child and every deeper segment is a plain
295    /// (non-numeric) object key. Returns `false` when the shape needs the
296    /// owned-rebuild fallback instead.
297    fn try_splice_write_parts(&mut self, parts: &[Arc<str>], value_av: DataValue<'a>) -> bool {
298        if parts.len() < 2 {
299            return false;
300        }
301        // A raw segment that parses as usize takes array-index semantics in
302        // `set_nested_value_parts` — fall back rather than mirror that here.
303        // (`#`-escaped keys never parse: `#20` is the object key "20".)
304        if parts[2..].iter().any(|p| p.parse::<usize>().is_ok()) {
305            return false;
306        }
307
308        let top = strip_hash_prefix(&parts[0]);
309        let Some(top_idx) = self.top_keys.iter().position(|k| *k == top) else {
310            // Write created a brand-new top slot — rare; let the fallback
311            // build it from owned.
312            return false;
313        };
314        let arena = self.arena;
315        let Some(d2) = self.depth2[top_idx].as_mut() else {
316            // Top slot isn't an Object (or has no depth-2 cache) — the owned
317            // write may have no-op'd or reshaped it; fall back.
318            return false;
319        };
320
321        let d2_key = strip_hash_prefix(&parts[1]);
322        let d2_pos = d2.keys.iter().position(|k| *k == d2_key);
323
324        if parts.len() == 2 {
325            // Whole depth-2 slot replace/insert: the eval result IS the new
326            // child value — no owned round-trip needed.
327            match d2_pos {
328                Some(pos) => d2.values[pos] = value_av,
329                None => {
330                    d2.keys.push(arena.alloc_str(d2_key));
331                    d2.values.push(value_av);
332                }
333            }
334        } else {
335            let Some(pos) = d2_pos else {
336                // First write into a not-yet-cached depth-2 subtree (e.g. the
337                // first mapping into `data.MT103`) — the owned write creates
338                // it; let the fallback arena the fresh subtree once.
339                return false;
340            };
341            let Some(new_subtree) =
342                splice_object_write(arena, d2.values[pos], &parts[2..], value_av)
343            else {
344                // Non-object hop (scalar/array mid-path) — the owned write
345                // no-ops or takes semantics the splice doesn't mirror.
346                return false;
347            };
348            d2.values[pos] = new_subtree;
349        }
350
351        let slice = build_object_slice(arena, &d2.keys, &d2.values);
352        self.top_values[top_idx] = DataValue::Object(slice);
353        true
354    }
355
356    /// Test-only differential check: the live cache must be value- and
357    /// order-identical to a fresh depth-2 rebuild of `owned_ctx`.
358    #[cfg(test)]
359    fn assert_matches_owned(&self, owned_ctx: &OwnedDataValue) {
360        let rebuilt = ArenaContext::from_owned(owned_ctx, self.arena);
361        assert_eq!(
362            self.as_data_value().to_owned(),
363            rebuilt.as_data_value().to_owned(),
364            "arena cache diverged from owned context"
365        );
366    }
367
368    /// Refresh the arena slot(s) for `path` from the current `owned_ctx`,
369    /// without applying any new write. Used when a sync task mutated
370    /// `message.context` directly (e.g. `parse_json` going through legacy
371    /// helpers) and we need the arena to catch up.
372    pub fn refresh_for_path(&mut self, owned_ctx: &OwnedDataValue, path: &str) {
373        self.refresh_after_write(owned_ctx, path);
374    }
375
376    /// Pre-split variant of [`Self::refresh_for_path`] — callers holding
377    /// compiler-populated path parts (parse/publish target paths) skip the
378    /// per-call `str::split`.
379    pub fn refresh_for_path_parts(&mut self, owned_ctx: &OwnedDataValue, parts: &[Arc<str>]) {
380        self.refresh_after_write_parts(owned_ctx, parts);
381    }
382
383    /// Pre-split variant of `refresh_after_write` — same algorithm, no
384    /// per-call `str::split` walk. `parts` retains the original `#` prefix;
385    /// the hash strip is applied here at lookup so the cache key matches
386    /// what `set_nested_value_parts` actually wrote.
387    fn refresh_after_write_parts(&mut self, owned_ctx: &OwnedDataValue, parts: &[Arc<str>]) {
388        let top_raw: &str = match parts.first() {
389            Some(p) if !p.is_empty() => p,
390            _ => {
391                self.rebuild_all_from(owned_ctx);
392                return;
393            }
394        };
395        let top = strip_hash_prefix(top_raw);
396        let depth2_key: Option<&str> = parts.get(1).map(|p| strip_hash_prefix(p));
397        let depth3_key: Option<&str> = parts.get(2).map(|p| strip_hash_prefix(p));
398        self.refresh_after_write_inner(owned_ctx, top, depth2_key, depth3_key);
399    }
400
401    /// Refresh the arena cache after `owned_ctx` was mutated at `path`.
402    fn refresh_after_write(&mut self, owned_ctx: &OwnedDataValue, path: &str) {
403        let mut parts = path.split('.');
404        let top_raw = match parts.next() {
405            Some(p) if !p.is_empty() => p,
406            _ => {
407                self.rebuild_all_from(owned_ctx);
408                return;
409            }
410        };
411        let top = strip_hash_prefix(top_raw);
412        let depth2_key = parts.next().map(strip_hash_prefix);
413        let depth3_key = parts.next().map(strip_hash_prefix);
414        self.refresh_after_write_inner(owned_ctx, top, depth2_key, depth3_key);
415    }
416
417    /// Shared body: walk the cache for `top` and optional `depth2_key`,
418    /// rebuilding only the dirtied slot. `depth3_key` is ignored (the
419    /// depth-3 sub-cache was tried but regressed on the realistic workload —
420    /// per-write d3 cache thrashing exceeded the savings).
421    fn refresh_after_write_inner(
422        &mut self,
423        owned_ctx: &OwnedDataValue,
424        top: &str,
425        depth2_key: Option<&str>,
426        _depth3_key: Option<&str>,
427    ) {
428        let OwnedDataValue::Object(owned_pairs) = owned_ctx else {
429            self.rebuild_all_from(owned_ctx);
430            return;
431        };
432
433        let owned_top_val = owned_pairs.iter().find(|(k, _)| k == top).map(|(_, v)| v);
434
435        let top_idx = self.top_keys.iter().position(|k| *k == top);
436
437        match (owned_top_val, top_idx) {
438            (None, Some(idx)) => {
439                // Top slot was removed from owned ctx — remove from cache.
440                self.top_keys.remove(idx);
441                self.top_values.remove(idx);
442                self.depth2.remove(idx);
443            }
444            (Some(new_val), idx_opt) => {
445                let idx = match idx_opt {
446                    Some(i) => i,
447                    None => {
448                        self.top_keys.push(self.arena.alloc_str(top));
449                        self.top_values.push(DataValue::Null);
450                        self.depth2.push(None);
451                        self.top_keys.len() - 1
452                    }
453                };
454
455                match (new_val, depth2_key, &mut self.depth2[idx]) {
456                    // Depth-2 write into an existing Object top slot that already
457                    // has a depth-2 cache → refresh only the child.
458                    (OwnedDataValue::Object(new_children), Some(child_key), Some(d2)) => {
459                        if let Some(new_child) = new_children
460                            .iter()
461                            .find(|(k, _)| k == child_key)
462                            .map(|(_, v)| v)
463                        {
464                            // Replace or insert the single child slot.
465                            let child_arena = new_child.to_arena(self.arena);
466                            if let Some(pos) = d2.keys.iter().position(|k| *k == child_key) {
467                                d2.values[pos] = child_arena;
468                            } else {
469                                d2.keys.push(self.arena.alloc_str(child_key));
470                                d2.values.push(child_arena);
471                            }
472                            // Also reflect deletions of *other* depth-2 keys
473                            // (rare but possible if the write replaced the
474                            // whole top object). Cheap O(n) scan.
475                            if d2.keys.len() != new_children.len() {
476                                // Owned children diverged from our cache —
477                                // rebuild the depth-2 cache from owned.
478                                self.rebuild_top_slot(new_val, idx);
479                                return;
480                            }
481                        } else {
482                            // child_key not found in new owned object — child
483                            // was removed. Drop from cache.
484                            if let Some(pos) = d2.keys.iter().position(|k| *k == child_key) {
485                                d2.keys.remove(pos);
486                                d2.values.remove(pos);
487                            }
488                        }
489                        let slice = build_object_slice(self.arena, &d2.keys, &d2.values);
490                        self.top_values[idx] = DataValue::Object(slice);
491                    }
492                    // Top-level (depth-1) write or shape change → rebuild
493                    // the whole top slot (cheap relative to a full ctx walk).
494                    _ => {
495                        self.rebuild_top_slot(new_val, idx);
496                    }
497                }
498            }
499            (None, None) => { /* no-op */ }
500        }
501    }
502
503    fn rebuild_top_slot(&mut self, owned: &OwnedDataValue, idx: usize) {
504        match owned {
505            OwnedDataValue::Object(children) => {
506                let mut d2_keys: Vec<&'a str> = Vec::with_capacity(children.len());
507                let mut d2_values: Vec<DataValue<'a>> = Vec::with_capacity(children.len());
508                for (ck, cv) in children {
509                    d2_keys.push(self.arena.alloc_str(ck));
510                    d2_values.push(cv.to_arena(self.arena));
511                }
512                let slice = build_object_slice(self.arena, &d2_keys, &d2_values);
513                self.top_values[idx] = DataValue::Object(slice);
514                self.depth2[idx] = Some(Depth2Cache {
515                    keys: d2_keys,
516                    values: d2_values,
517                });
518            }
519            _ => {
520                self.top_values[idx] = owned.to_arena(self.arena);
521                self.depth2[idx] = None;
522            }
523        }
524    }
525
526    /// Last-resort: ditch all cached state and rebuild from scratch. Should be
527    /// rare on normal flows — only triggered if the context shape changes in
528    /// a way the depth-2 cache can't track.
529    fn rebuild_all_from(&mut self, ctx: &OwnedDataValue) {
530        let rebuilt = ArenaContext::from_owned(ctx, self.arena);
531        self.top_keys = rebuilt.top_keys;
532        self.top_values = rebuilt.top_values;
533        self.depth2 = rebuilt.depth2;
534    }
535}
536
537/// Allocate a fresh `(key, value)` slice in the arena. Each
538/// `engine.evaluate` call gets its own slice; subsequent mutations to the
539/// underlying Vecs are independent.
540fn build_object_slice<'a>(
541    arena: &'a Bump,
542    keys: &[&'a str],
543    values: &[DataValue<'a>],
544) -> &'a [(&'a str, DataValue<'a>)] {
545    debug_assert_eq!(keys.len(), values.len());
546    arena.alloc_slice_fill_iter(keys.iter().zip(values.iter()).map(|(k, v)| (*k, *v)))
547}
548
549/// Rebuild only the spine of `current` for a write of `value` at `parts`
550/// (all plain object keys — the caller has excluded numeric segments).
551/// Each level allocates a fresh `(key, value)` slice with the one descended
552/// child replaced: shallow pair copies, no string data copied, no descent
553/// into unchanged siblings. A missing key builds the remaining chain as
554/// nested single-pair Objects, mirroring `set_nested_value_parts`' create
555/// semantics for non-numeric segments. Returns `None` when `current` is not
556/// an Object — those shapes (array hop, scalar overwrite mid-path) take the
557/// owned-rebuild fallback, which mirrors whatever the owned write did.
558fn splice_object_write<'a>(
559    arena: &'a Bump,
560    current: DataValue<'a>,
561    parts: &[Arc<str>],
562    value: DataValue<'a>,
563) -> Option<DataValue<'a>> {
564    let DataValue::Object(pairs) = current else {
565        return None;
566    };
567    let key = strip_hash_prefix(&parts[0]);
568    let pos = pairs.iter().position(|(k, _)| *k == key);
569
570    let new_slice = if parts.len() == 1 {
571        // Terminal level: replace the slot, or append a new pair.
572        match pos {
573            Some(p) => alloc_pairs_with_replaced(arena, pairs, p, value),
574            None => alloc_pairs_with_appended(arena, pairs, arena.alloc_str(key), value),
575        }
576    } else {
577        match pos {
578            Some(p) => {
579                let child = splice_object_write(arena, pairs[p].1, &parts[1..], value)?;
580                alloc_pairs_with_replaced(arena, pairs, p, child)
581            }
582            None => {
583                let chain = build_object_chain(arena, &parts[1..], value);
584                alloc_pairs_with_appended(arena, pairs, arena.alloc_str(key), chain)
585            }
586        }
587    };
588    Some(DataValue::Object(new_slice))
589}
590
591/// Wrap `value` in nested single-pair Objects, innermost-last: for parts
592/// `[a, b]` produces `{a: {b: value}}`. Mirrors the container-creation path
593/// of `set_nested_value_parts` when every segment is a non-numeric key.
594fn build_object_chain<'a>(
595    arena: &'a Bump,
596    parts: &[Arc<str>],
597    value: DataValue<'a>,
598) -> DataValue<'a> {
599    let mut acc = value;
600    for part in parts.iter().rev() {
601        let key: &'a str = arena.alloc_str(strip_hash_prefix(part));
602        let slice = arena.alloc_slice_fill_iter(std::iter::once((key, acc)));
603        acc = DataValue::Object(slice);
604    }
605    acc
606}
607
608/// Fresh slice with `pairs[replace_idx]`'s value swapped for `new_value`.
609fn alloc_pairs_with_replaced<'a>(
610    arena: &'a Bump,
611    pairs: &'a [(&'a str, DataValue<'a>)],
612    replace_idx: usize,
613    new_value: DataValue<'a>,
614) -> &'a [(&'a str, DataValue<'a>)] {
615    arena.alloc_slice_fill_with(pairs.len(), |i| {
616        if i == replace_idx {
617            (pairs[i].0, new_value)
618        } else {
619            pairs[i]
620        }
621    })
622}
623
624/// Fresh slice of `pairs` plus one appended `(key, value)` pair.
625fn alloc_pairs_with_appended<'a>(
626    arena: &'a Bump,
627    pairs: &'a [(&'a str, DataValue<'a>)],
628    key: &'a str,
629    value: DataValue<'a>,
630) -> &'a [(&'a str, DataValue<'a>)] {
631    arena.alloc_slice_fill_with(pairs.len() + 1, |i| {
632        if i < pairs.len() {
633            pairs[i]
634        } else {
635            (key, value)
636        }
637    })
638}
639
640/// Evaluate a workflow or task condition using a cached compiled logic
641/// expression. Returns `true` when `condition_index` is `None` (no condition
642/// is treated as "always run"). Evaluation errors are logged and downgraded
643/// to `false` — a condition that fails to evaluate skips its task/workflow
644/// rather than aborting the whole message.
645pub fn evaluate_condition(
646    engine: &Engine,
647    compiled_condition: Option<&Arc<Logic>>,
648    context: &OwnedDataValue,
649) -> Result<bool> {
650    match compiled_condition {
651        Some(compiled) => match eval_to_owned(engine, compiled, context) {
652            Ok(value) => Ok(matches!(value, OwnedDataValue::Bool(true))),
653            Err(e) => {
654                error!("Failed to evaluate condition: {:?}", e);
655                Ok(false)
656            }
657        },
658        None => Ok(true),
659    }
660}
661
662/// Same as `evaluate_condition` but evaluates against an arena-resident
663/// `DataValue` and an existing `Bump`. Used inside a `with_arena` block
664/// (the workflow sync-stretch path) to avoid re-entering the thread-local
665/// arena `RefCell::borrow_mut`.
666pub fn evaluate_condition_in_arena(
667    engine: &Engine,
668    compiled_condition: Option<&Arc<Logic>>,
669    ctx: DataValue<'_>,
670    arena: &Bump,
671) -> Result<bool> {
672    match compiled_condition {
673        Some(compiled) => match engine.evaluate(compiled, ctx, arena) {
674            Ok(value) => Ok(matches!(value, DataValue::Bool(true))),
675            Err(e) => {
676                error!("Failed to evaluate condition: {:?}", e);
677                Ok(false)
678            }
679        },
680        None => Ok(true),
681    }
682}
683
684#[cfg(test)]
685mod tests {
686    use super::*;
687    use crate::engine::utils::{set_nested_value, set_nested_value_parts};
688    use serde_json::json;
689
690    fn dv(v: serde_json::Value) -> OwnedDataValue {
691        OwnedDataValue::from(&v)
692    }
693
694    fn parts_of(path: &str) -> Vec<Arc<str>> {
695        path.split('.').map(Arc::from).collect()
696    }
697
698    /// Drive a corpus of writes through the write-through path. Every call
699    /// re-validates the cache against a from-scratch rebuild via the
700    /// `#[cfg(test)]` assertion inside `apply_mutation_parts_write_through`,
701    /// so this test fails on any splice/fallback divergence — splice hits
702    /// (deep object paths, `#`-escaped keys, chain creation, depth-2
703    /// replace/insert) and fallback shapes (array segments, scalar mid-path
704    /// no-ops, new top slots) alike.
705    #[test]
706    fn write_through_differential_corpus() {
707        let mut owned = dv(json!({
708            "data": {
709                "input": {"big": {"nested": [1, 2, 3]}, "flag": true},
710                "MT103": {"20": "REF", "72": "existing"},
711                "items": [{"x": 1}, {"x": 2}],
712                "scalar": "leaf"
713            },
714            "metadata": {"processed_at": "t0"},
715            "temp_data": {}
716        }));
717
718        with_arena(|arena| {
719            let mut ctx = ArenaContext::from_owned(&owned, arena);
720
721            let corpus: &[(&str, serde_json::Value)] = &[
722                // Depth-3 replace of an existing key inside a cached subtree.
723                ("data.MT103.20", json!("NEWREF")),
724                // Depth-3 append of a new key.
725                ("data.MT103.23B", json!("CRED")),
726                // Depth-4 with a missing intermediate — chain creation.
727                ("data.MT103.32A.amount", json!(1500.25)),
728                // Depth-4 into the now-existing intermediate.
729                ("data.MT103.32A.currency", json!("USD")),
730                // Deeper chain creation (three missing levels).
731                ("data.MT103.a.b.c", json!({"deep": [1, {"k": "v"}]})),
732                // Overwrite an entire existing sub-object.
733                ("data.MT103.32A", json!({"replaced": true})),
734                // Depth-2 whole-slot replace with an object.
735                ("data.MT103", json!({"fresh": {"start": 1}})),
736                // Depth-2 whole-slot replace with a scalar (drops d2 cache on
737                // next rebuild; subsequent write through it must no-op).
738                ("data.scalar2", json!("plain")),
739                // New depth-2 key inserted into an existing top slot.
740                ("data.MT202", json!({"20": "REF2"})),
741                // Write into a not-yet-cached depth-2 subtree (fallback).
742                ("data.MT205.20", json!("REF5")),
743                // `#`-escaped keys: object keys "20" and "#".
744                ("data.MT103.#20", json!("HASH20")),
745                ("data.MT103.##", json!("HASHKEY")),
746                // Array index segments — fallback shapes.
747                ("data.items.0.x", json!(10)),
748                ("data.items.3", json!({"x": 4})),
749                // Scalar mid-path — owned write no-ops; cache must stay in sync.
750                ("data.scalar.sub.key", json!("ignored")),
751                // Metadata / temp_data writes.
752                ("metadata.progress.workflow_id", json!("wf1")),
753                ("temp_data.uetr", json!("uuid-here")),
754                // Brand-new top-level slot (fallback creates it).
755                ("other_top.x.y", json!(42)),
756            ];
757
758            for (path, val) in corpus {
759                let parts = parts_of(path);
760                let owned_val = dv(val.clone());
761                let value_av = owned_val.to_arena(arena);
762                ctx.apply_mutation_parts_write_through(&mut owned, &parts, value_av, |c| {
763                    set_nested_value_parts(c, &parts, owned_val.clone());
764                });
765            }
766
767            // Spot-check a few end states against the owned source of truth.
768            assert_eq!(owned["data"]["MT103"]["20"], dv(json!("HASH20")));
769            assert_eq!(owned["data"]["MT103"]["fresh"]["start"], dv(json!(1)));
770            assert_eq!(owned["data"]["items"][3]["x"], dv(json!(4)));
771            assert_eq!(owned["data"]["scalar"], dv(json!("leaf")));
772            assert_eq!(
773                owned["metadata"]["progress"]["workflow_id"],
774                dv(json!("wf1"))
775            );
776        });
777    }
778
779    /// Interleave reads (as_data_value) with write-throughs to make sure a
780    /// previously handed-out slice never aliases a mutated spine.
781    #[test]
782    fn write_through_reads_see_latest_state() {
783        let mut owned = dv(json!({
784            "data": {"doc": {"a": 1}},
785            "metadata": {},
786            "temp_data": {}
787        }));
788
789        with_arena(|arena| {
790            let mut ctx = ArenaContext::from_owned(&owned, arena);
791
792            for i in 0..10u64 {
793                let key = format!("data.doc.f{i}");
794                let parts = parts_of(&key);
795                let owned_val = OwnedDataValue::from(i);
796                let value_av = owned_val.to_arena(arena);
797                ctx.apply_mutation_parts_write_through(&mut owned, &parts, value_av, |c| {
798                    set_nested_value_parts(c, &parts, owned_val.clone());
799                });
800                // A fresh projection after every write must equal owned.
801                assert_eq!(ctx.as_data_value().to_owned(), owned);
802            }
803        });
804    }
805
806    /// The refresh-only path (used by parse_json and the per-task progress
807    /// refresh) must remain consistent when mixed with write-throughs.
808    #[test]
809    fn refresh_and_write_through_interleave() {
810        let mut owned = dv(json!({
811            "data": {},
812            "metadata": {},
813            "temp_data": {}
814        }));
815
816        with_arena(|arena| {
817            let mut ctx = ArenaContext::from_owned(&owned, arena);
818
819            // Simulate parse_json: direct owned write + refresh_for_path.
820            set_nested_value(&mut owned, "data.input", dv(json!({"payload": {"v": 7}})));
821            ctx.refresh_for_path(&owned, "data.input");
822            assert_eq!(ctx.as_data_value().to_owned(), owned);
823
824            // Then map write-throughs landing next to it.
825            let parts = parts_of("data.out.v");
826            let owned_val = dv(json!(7));
827            let value_av = owned_val.to_arena(arena);
828            ctx.apply_mutation_parts_write_through(&mut owned, &parts, value_av, |c| {
829                set_nested_value_parts(c, &parts, owned_val.clone());
830            });
831
832            // Simulate the progress write + narrow refresh.
833            set_nested_value(
834                &mut owned,
835                "metadata.progress",
836                dv(json!({"task_id": "t1"})),
837            );
838            ctx.refresh_for_path(&owned, "metadata.progress");
839            assert_eq!(ctx.as_data_value().to_owned(), owned);
840        });
841    }
842}